mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-08-29 18:31:33 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
+3 |
a64c956c5b | ||
|
|
188380e8e7 | ||
|
|
9effddaba8 | ||
|
|
ad0e62434b | ||
|
|
d831b46cb3 | ||
|
|
4a7117b67f | ||
|
|
9ae48a8c6c | ||
|
|
e5b0db60c4 | ||
|
|
0327f9020c | ||
|
|
9f066d814a | ||
|
+2 |
1a26628a48 |
@@ -37,6 +37,14 @@ updates:
|
||||
major-updates:
|
||||
update-types:
|
||||
- "major"
|
||||
ignore:
|
||||
# typescript-eslint declares `typescript: >=4.8.4 <6.1.0`, and TypeScript 7
|
||||
# removed `ts.Extension`, which @typescript-eslint/typescript-estree reads
|
||||
# at import time. Bumping to 7 makes `eslint .` fail to load its own config,
|
||||
# so `npm run lint` cannot run at all. Drop this once typescript-eslint
|
||||
# supports TypeScript 7.
|
||||
- dependency-name: "typescript"
|
||||
update-types: ["version-update:semver-major"]
|
||||
|
||||
# Docker base images (docker/Dockerfile + docker-compose / compose-dev)
|
||||
- package-ecosystem: "docker"
|
||||
|
||||
@@ -121,7 +121,7 @@ jobs:
|
||||
CHANGES=$(git log --oneline --no-merges "${{ steps.prev.outputs.sha }}..${{ needs.prep.outputs.sha }}" -- . ':!package-lock.json' | sed 's/^/- /')
|
||||
fi
|
||||
if [ -z "$CHANGES" ]; then
|
||||
CHANGES="- No new commits since the last beta (or this is the first beta build)."
|
||||
CHANGES="- No new commits since the last beta."
|
||||
fi
|
||||
|
||||
cat > BETA_RELEASE_BODY.md << EOF
|
||||
@@ -157,7 +157,7 @@ jobs:
|
||||
|
||||
docker:
|
||||
needs: [prep, verify, create-release]
|
||||
if: ${{ always() && needs.prep.outputs.dev_branch != '' && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped') }}
|
||||
if: ${{ always() && needs.prep.outputs.dev_branch != '' && needs.verify.result == 'success' && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped') }}
|
||||
uses: ./.github/workflows/docker.yml
|
||||
with:
|
||||
version: ${{ needs.prep.outputs.beta_version }}
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
token: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ jobs:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
- name: Setup Docker Buildx
|
||||
uses: useblacksmith/setup-docker-builder@v1
|
||||
uses: useblacksmith/setup-docker-builder@v2
|
||||
|
||||
- name: Determine tags
|
||||
id: tags
|
||||
|
||||
@@ -559,7 +559,7 @@ jobs:
|
||||
CHECKSUM=$(shasum -a 256 "$DMG_PATH" | awk '{print $1}')
|
||||
|
||||
mkdir -p homebrew-generated
|
||||
cp packaging/Casks/termix.rb homebrew-generated/termix.rb
|
||||
cp Casks/termix.rb homebrew-generated/termix.rb
|
||||
|
||||
sed -i '' "s/VERSION_PLACEHOLDER/$VERSION/g" homebrew-generated/termix.rb
|
||||
sed -i '' "s/CHECKSUM_PLACEHOLDER/$CHECKSUM/g" homebrew-generated/termix.rb
|
||||
@@ -894,7 +894,7 @@ jobs:
|
||||
|
||||
mkdir -p homebrew-submission/Casks/t
|
||||
|
||||
cp packaging/Casks/termix.rb homebrew-submission/Casks/t/termix.rb
|
||||
cp Casks/termix.rb homebrew-submission/Casks/t/termix.rb
|
||||
|
||||
sed -i '' "s/VERSION_PLACEHOLDER/$VERSION/g" homebrew-submission/Casks/t/termix.rb
|
||||
sed -i '' "s/CHECKSUM_PLACEHOLDER/$CHECKSUM/g" homebrew-submission/Casks/t/termix.rb
|
||||
@@ -1075,13 +1075,21 @@ jobs:
|
||||
default_platform(:mac)
|
||||
|
||||
lane :fetch_build_number do
|
||||
number = app_store_build_number(
|
||||
live: false,
|
||||
live_number = app_store_build_number(
|
||||
live: true,
|
||||
platform: "osx",
|
||||
api_key_path: "/tmp/asc_keys/api_key.json",
|
||||
app_identifier: "com.karmaa.termix",
|
||||
version: "$APP_VERSION",
|
||||
initial_build_number: 0,
|
||||
)
|
||||
pending_number = app_store_build_number(
|
||||
live: false,
|
||||
platform: "osx",
|
||||
api_key_path: "/tmp/asc_keys/api_key.json",
|
||||
app_identifier: "com.karmaa.termix",
|
||||
initial_build_number: 0,
|
||||
)
|
||||
number = [live_number, pending_number].max
|
||||
File.write("$OUT_FILE", number.to_s)
|
||||
end
|
||||
EOF
|
||||
@@ -1129,6 +1137,8 @@ jobs:
|
||||
--skip_screenshots true \
|
||||
--submit_for_review true \
|
||||
--automatic_release true \
|
||||
--precheck_include_in_app_purchases false \
|
||||
--submission_information "{\"export_compliance_uses_encryption\": false}" \
|
||||
--force true
|
||||
|
||||
- name: Clean up keychains
|
||||
|
||||
@@ -24,8 +24,10 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run ESLint
|
||||
run: npx eslint .
|
||||
- name: Lint
|
||||
# npm run lint, not npx eslint — the script also checks that the
|
||||
# generated dialect schemas match schema.ts, which eslint cannot see.
|
||||
run: npm run lint
|
||||
|
||||
- name: Run Prettier check
|
||||
run: npx prettier --check .
|
||||
@@ -35,3 +37,76 @@ jobs:
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
database-dialects:
|
||||
name: Postgres and MySQL
|
||||
runs-on: blacksmith-2vcpu-ubuntu-2404
|
||||
|
||||
# The test suite only ever sees SQLite. Everything that differs per engine —
|
||||
# the RETURNING replacements, the read-then-write transactions, the
|
||||
# migrations themselves — is only covered here, against real servers.
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16
|
||||
env:
|
||||
POSTGRES_USER: termix
|
||||
POSTGRES_PASSWORD: termix
|
||||
POSTGRES_DB: termix_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
|
||||
mysql:
|
||||
image: mysql:8
|
||||
env:
|
||||
MYSQL_ROOT_PASSWORD: termix
|
||||
MYSQL_DATABASE: termix_test
|
||||
MYSQL_USER: termix
|
||||
MYSQL_PASSWORD: termix
|
||||
ports:
|
||||
- 3306:3306
|
||||
options: >-
|
||||
--health-cmd "mysqladmin ping -h 127.0.0.1 -ptermix"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
# Each run applies the migrations to an empty database first, so a
|
||||
# migration that does not apply cleanly fails the build.
|
||||
- name: Verify Postgres
|
||||
run: npm run verify:dialect -- postgres://termix:termix@127.0.0.1:5432/termix_test
|
||||
|
||||
- name: Verify MySQL
|
||||
run: npm run verify:dialect -- mysql://termix:termix@127.0.0.1:3306/termix_test
|
||||
|
||||
# The same repository suite the SQLite run executes, pointed at each
|
||||
# engine. This is where a dialect difference in a query shows up as a
|
||||
# failing assertion rather than as a bug report.
|
||||
- name: Repository tests on Postgres
|
||||
env:
|
||||
TEST_DIALECT: postgres
|
||||
TEST_DATABASE_URL: postgres://termix:termix@127.0.0.1:5432/termix_test
|
||||
run: npx vitest run src/backend/tests/database/repositories --no-file-parallelism
|
||||
|
||||
- name: Repository tests on MySQL
|
||||
env:
|
||||
TEST_DIALECT: mysql
|
||||
TEST_DATABASE_URL: mysql://termix:termix@127.0.0.1:3306/termix_test
|
||||
run: npx vitest run src/backend/tests/database/repositories --no-file-parallelism
|
||||
|
||||
@@ -395,10 +395,10 @@ jobs:
|
||||
git fetch origin main
|
||||
git checkout -B main origin/main
|
||||
|
||||
sed -i "s|version \".*\"|version \"$VERSION\"|g" packaging/Casks/termix.rb
|
||||
sed -i "s|sha256 \".*\"|sha256 \"$DMG_SHA256\"|g" packaging/Casks/termix.rb
|
||||
sed -i "s|version \".*\"|version \"$VERSION\"|g" Casks/termix.rb
|
||||
sed -i "s|sha256 \".*\"|sha256 \"$DMG_SHA256\"|g" Casks/termix.rb
|
||||
|
||||
git add packaging/Casks/termix.rb
|
||||
git add Casks/termix.rb
|
||||
if git diff --cached --quiet; then
|
||||
echo "Cask already up to date."
|
||||
exit 0
|
||||
|
||||
@@ -17,3 +17,6 @@ db
|
||||
*.min.js
|
||||
*.min.css
|
||||
openapi.json
|
||||
|
||||
# Generated by drizzle-kit; formatting is the tool's own
|
||||
drizzle/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
cask "termix" do
|
||||
version "2.5.1"
|
||||
sha256 "39f88b6fb6f8841496fe689968decbbc4f4baa92ab5a3a41a738123cf7daeb3f"
|
||||
version "2.6.0"
|
||||
sha256 "1ea70f6d909ac844cae40e834d54f12151b20f4bd0da15cd624b8cf9ecc2555a"
|
||||
|
||||
url "https://github.com/Termix-SSH/Termix/releases/download/release-#{version}-tag/termix_macos_universal_dmg.dmg"
|
||||
name "Termix"
|
||||
@@ -189,6 +189,20 @@ SSH sessions and tabs stay open across devices/refreshes if enabled in user prof
|
||||
**Languages:**
|
||||
Built-in support ~30 languages (managed by [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Session Sharing:**
|
||||
Share a live terminal, RDP, VNC, or Telnet session with others in real time. Share via a link (joined anonymously, no account needed) or with a specific Termix user, and choose read-only or read-write access. Shares can expire automatically or be revoked at any time, and session sharing can be toggled globally or per-host.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Desktop Standalone + 2-Way Sync:**
|
||||
The Electron desktop app runs fully standalone with its own local backend and database, no server required. Optionally connect it to a remote Termix server for automatic two-way sync of hosts, credentials, snippets, and more, and choose whether SSH connections are started locally or through the remote server.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -291,13 +305,19 @@ networks:
|
||||
driver: bridge
|
||||
```
|
||||
|
||||
### Cloud Hosting
|
||||
|
||||
You can also run the Termix server on a cloud VPS instead of inside your own network. If Termix runs on the network it manages, an outage takes Termix with it, and your hosts and saved sessions are stuck inside the system you are trying to fix. Hosting it externally keeps it reachable no matter what happens to your network, and gives you a static IP and access from anywhere without a VPN or port forward.
|
||||
|
||||
[GINERNET](https://docs.termix.site/install/ginernet) is a sponsor of Termix, and there is a full step by step guide for deploying to their VPS platform in the docs.
|
||||
|
||||
<br />
|
||||
|
||||
## Telemetry
|
||||
|
||||
Termix sends a small anonymous usage ping once every 24 hours to help understand how many instances are running and which features are actually used. This only includes a randomly generated instance ID, a count of users and hosts, the app version, and whether certain features (terminal, file manager, tunnels, docker, etc.) were used in the last 24 hours. It never includes usernames, hostnames, IP addresses, credentials, or any other identifying or connection data.
|
||||
|
||||
This is opt-out and enabled by default. You can disable it at any time in Admin Settings under **General**.
|
||||
This is opt-out and enabled by default. You can disable it at any time in Admin Settings under General, or set `ENABLE_TELEMETRY=false` to turn it off before you ever spin-up Termix.
|
||||
|
||||
<br />
|
||||
|
||||
@@ -333,10 +353,6 @@ Interested in a paid placement to support development? Email [mail@termix.site](
|
||||
<img src="https://sirv.sirv.com/website/screenshots/cloudflare/cloudflare-logo.png?w=300" height="40" alt="Cloudflare" />
|
||||
</a>
|
||||
|
||||
<a href="https://tailscale.com/">
|
||||
<img src="https://drive.google.com/uc?export=view&id=1lIxkJuX6M23bW-2FElhT0rQieTrzaVSL" height="40" alt="Tailscale" />
|
||||
</a>
|
||||
|
||||
<a href="https://akamai.com/">
|
||||
<img src="https://upload.wikimedia.org/wikipedia/commons/8/8b/Akamai_logo.svg" height="40" alt="Akamai" />
|
||||
</a>
|
||||
@@ -348,7 +364,10 @@ Interested in a paid placement to support development? Email [mail@termix.site](
|
||||
<a href="https://rackgenius.com/">
|
||||
<img src="https://rackgenius.com/rackgenius-logo.png" height="40" alt="Rack Genius" />
|
||||
</a>
|
||||
|
||||
|
||||
<a href="https://ginernet.com/">
|
||||
<img src="https://ginernet.com/img/logo-web.png" height="40" alt="Ginernet" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<br />
|
||||
|
||||
+53
-53
@@ -1,70 +1,70 @@
|
||||
<!-- SUMMARY -->
|
||||
|
||||
Revamped RBAC/sharing, session recording & replay, Vault auth for monitors, API key host enrollment, Proxmox guest auto sync, database refactor, plus 30+ bug fixes across terminal, file manager, RDP/VNC, and auth. DO NOT DOWNGRADE FROM THIS VERSION.
|
||||
Standalone-first Electron desktop app with optional remote sync, shared/multiplayer terminal and remote desktop sessions, improved SSH MFA support, custom key shortcuts, bug fixes across terminal, RDP/VNC, mobile, and auth.
|
||||
|
||||
<!-- /SUMMARY -->
|
||||
|
||||
<!-- YOUTUBE -->
|
||||
|
||||
https://youtu.be/c3UD4q2jW_8
|
||||
https://youtu.be/g0QjNdV3YYY
|
||||
|
||||
<!-- /YOUTUBE -->
|
||||
|
||||
<!-- UPDATE_LOG -->
|
||||
|
||||
- Revamped RBAC/sharing system (new UI, all auth types and host protocols now supported)
|
||||
- Complete admin control over user information (manage all users hosts, credentials, and snippets)
|
||||
- Support Vault auth for monitors
|
||||
- API key host enrollment endpoint
|
||||
- Allow pinned hosts with name sorting
|
||||
- Session recording and replay
|
||||
- Terminal font size shortcuts (ctrl + / -)
|
||||
- Open File Manager to tab right-click menu
|
||||
- Proxmox guest auto sync
|
||||
- Complete database refactor
|
||||
- 30-day donation reminder and new donation milestones that support research: (donate.termix.site)
|
||||
- Improve site performance with cache and poll pauses
|
||||
- Save quick connect sessions as hosts
|
||||
- Added support for multi disk usage in file manager/host metrics
|
||||
- Added better Ctrl + F terminal search
|
||||
- Added right click menu on app rail to pin sidebar faster
|
||||
- Support for overriding shared SSH credential
|
||||
- Added mapping for OIDC provider groups to RBAC roles
|
||||
- Added host export dialog for more customizable host exporting
|
||||
- Initial groundwork for supporting more database types (postgres and mysql)
|
||||
- Added audit log export (CSV/NDJSON) and optional live forwarding to a SIEM
|
||||
- Added configurable audit log retention by age and row count
|
||||
- Audit entries for file manager, RDP/VNC/Telnet, Docker and tunnel sessions
|
||||
- Encrypted SSO secrets instead of BASE64 encoding them
|
||||
- Added support for Tailscale SSH check mode with in-terminal browser authentication
|
||||
|
||||
<!-- /UPDATE_LOG -->
|
||||
|
||||
<!-- BUG_FIXES -->
|
||||
|
||||
- Syntax highlighting artifacts
|
||||
- Filter dashboard status hosts
|
||||
- Persist dashboard service link changes
|
||||
- Snippet text overflow
|
||||
- Persist remote desktop credential auth
|
||||
- Guard language switching failures
|
||||
- Resolve tunnel source credentials
|
||||
- Windows file delete command
|
||||
- Artifact release checkout ref
|
||||
- Command palette escape in fullscreen
|
||||
- Alerts and audit log normalization
|
||||
- macOS VNC protocol negotiation
|
||||
- Port knocking before SSH connect
|
||||
- Allow escape to close link confirmation
|
||||
- Prevent Electron modifier wheel zoom
|
||||
- Credential auth optional password
|
||||
- Retry transient terminal DNS lookups
|
||||
- OIDC redirect forwarded port handling
|
||||
- Preserve recent open tabs on startup
|
||||
- Terminal font selection
|
||||
- Poor font legibility in multiple places
|
||||
- File manager uploads failing
|
||||
- Tmux detection for non-POSTIX shells
|
||||
- OPKSSH js-yaml ESM import
|
||||
- Android Vietnamese IME input
|
||||
- Firefox RDP clipboard paste
|
||||
- Proxmox discovery over HTTPS
|
||||
- External editor actions in file preview
|
||||
- Firefox desktop OIDC callback
|
||||
- Status checks through jump hosts
|
||||
- Restore sudo password auto fill settings
|
||||
- Preserve file editor position on save
|
||||
- Sync cloud preference storage mode
|
||||
- Render RDP sessions at native pixel density
|
||||
- Restore database import in embedded desktop mode
|
||||
- Command autocomplete dropdown poor contrast
|
||||
- Allow clipboard paste in key recording field
|
||||
- Fix GitHub/google SSO "not defined" errors
|
||||
- Hardened nginx headers/asset caching
|
||||
- Deleting an account no longer deletes its audit entries and session recordings
|
||||
- Made logger display expanded error messages
|
||||
- Removed phantom port knocking
|
||||
- Fixed Proxmox guest discovery failures over jump host
|
||||
- Compare sync cursors independently of timestamp layout
|
||||
- Fixed sync deleting not reaching other side
|
||||
- Remote sync stalling after first pass and never propagating deletions
|
||||
- DB_FILE_ENCRYPTION variable loading DB file as empty
|
||||
- Removed unneeded field encryption boundaries
|
||||
- SSH login alerts being dropped silently
|
||||
- Honor lookupOptions.all in custom DNS lookup hook
|
||||
- Jump host SOCKS proxy settings being ignored
|
||||
- Jump host tunnels not reachable by guacd
|
||||
- Per-host RDP/VNC recording flags being ignored
|
||||
- RDP sessions not using the configured resolution
|
||||
- OIDC login failing with unverifiable ID tokens or JWKs without alg
|
||||
- Refuse to start with an empty database when data exists elsewhere
|
||||
- Database not persisting during container shutdown
|
||||
- Host command history setting not saving
|
||||
- Desktop preference sync and remote sync account identity
|
||||
- Desktop guacd calls not routed to the connected remote server
|
||||
- File manager navigation getting stuck after permission errors
|
||||
- Read-only shared hosts could be dragged into folders
|
||||
- Terminal highlighting breaking inside split control strings
|
||||
- Windows terminal Tab key and Android hardware keyboard keys
|
||||
- tmux monitor failing on Tailscale-authenticated hosts
|
||||
- Database export not staying same-origin on localhost
|
||||
- Snippet execution results not reported correctly
|
||||
- Shared hosts appearing twice
|
||||
- Wake-on-LAN broadcast address being dropped
|
||||
- Sharing an empty folder was rejected
|
||||
- Remote sync losing references between linked records
|
||||
- Desktop app failing to find its backend on some architectures
|
||||
- Centralized outbound address validation for homepage proxy requests
|
||||
- Default font size to medium instead of large
|
||||
- Tailscale hosts hanging on connect when the tailnet ACL requires a periodic check
|
||||
|
||||
<!-- /BUG_FIXES -->
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
"enabled": true,
|
||||
"clientKind": "git",
|
||||
"useIgnoreFile": true,
|
||||
"defaultBranch": "dev-2.5.0"
|
||||
"defaultBranch": "dev-2.6.1"
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
|
||||
@@ -76,6 +76,9 @@ COPY --chown=node:node --from=frontend-builder /app/dist /app/html
|
||||
COPY --chown=node:node --from=production-deps /app/node_modules /app/node_modules
|
||||
COPY --chown=node:node --from=backend-builder /app/dist/backend ./dist/backend
|
||||
COPY --chown=node:node package.json ./
|
||||
# Schema for Postgres and MySQL. Unused by the default SQLite deployment, which
|
||||
# builds its tables at startup instead.
|
||||
COPY --chown=node:node drizzle ./drizzle
|
||||
|
||||
VOLUME ["/app/data"]
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ services:
|
||||
PORT: "8080"
|
||||
NODE_ENV: development
|
||||
GUACD_HOST: "guacd-dev"
|
||||
GUACD_TUNNEL_HOST: "termix-dev"
|
||||
GUACD_RECORDING_PATH: "/termix-data/session_recordings/guacamole"
|
||||
depends_on:
|
||||
- guacd-dev
|
||||
|
||||
@@ -10,6 +10,7 @@ services:
|
||||
environment:
|
||||
PORT: "8080"
|
||||
GUACD_HOST: "guacd"
|
||||
GUACD_TUNNEL_HOST: "termix"
|
||||
GUACD_RECORDING_PATH: "/termix-data/session_recordings/guacamole"
|
||||
depends_on:
|
||||
- guacd
|
||||
|
||||
@@ -163,8 +163,4 @@ else
|
||||
echo "Warning: package.json not found"
|
||||
fi
|
||||
|
||||
node dist/backend/backend/starter.js
|
||||
|
||||
echo "All services started"
|
||||
|
||||
tail -f /dev/null
|
||||
exec node dist/backend/backend/starter.js
|
||||
|
||||
+55
-10
@@ -11,6 +11,8 @@ http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
server_tokens off;
|
||||
|
||||
access_log /tmp/nginx/access.log;
|
||||
|
||||
client_body_temp_path /tmp/nginx/client_body;
|
||||
@@ -69,7 +71,6 @@ http {
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /app/data/acme-webroot;
|
||||
@@ -80,6 +81,8 @@ http {
|
||||
location = /sw.js {
|
||||
root /app/html;
|
||||
expires off;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
@@ -87,31 +90,64 @@ http {
|
||||
location = /manifest.json {
|
||||
root /app/html;
|
||||
expires off;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||
location ^~ /assets/ {
|
||||
root /app/html;
|
||||
expires 1y;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ^~ /fonts/ {
|
||||
root /app/html;
|
||||
expires 1y;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ^~ /icons/ {
|
||||
root /app/html;
|
||||
expires 30d;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=2592000" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~* ^/[^/]+\.(js|css|png|jpe?g|gif|ico|svg|webp|woff2?|ttf|eot)$ {
|
||||
root /app/html;
|
||||
expires 30d;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=2592000" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~* \.map$ {
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
return 404;
|
||||
}
|
||||
|
||||
location / {
|
||||
root /app/html;
|
||||
index index.html index.htm;
|
||||
expires off;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~* \.map$ {
|
||||
return 404;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
|
||||
location ~ ^/users/sessions(/.*)?$ {
|
||||
proxy_pass http://127.0.0.1:30001;
|
||||
proxy_http_version 1.1;
|
||||
@@ -372,7 +408,9 @@ http {
|
||||
|
||||
proxy_cache_bypass 1;
|
||||
proxy_no_cache 1;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
}
|
||||
|
||||
location ~ ^/host/opkssh-callback(/.*)?$ {
|
||||
@@ -387,7 +425,9 @@ http {
|
||||
|
||||
proxy_cache_bypass 1;
|
||||
proxy_no_cache 1;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
}
|
||||
|
||||
location /host/ {
|
||||
@@ -549,6 +589,8 @@ http {
|
||||
client_max_body_size 5G;
|
||||
client_body_timeout 300s;
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate" always;
|
||||
|
||||
proxy_pass http://127.0.0.1:30004;
|
||||
@@ -570,6 +612,8 @@ http {
|
||||
client_max_body_size 5G;
|
||||
client_body_timeout 300s;
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate" always;
|
||||
|
||||
proxy_pass http://127.0.0.1:30004;
|
||||
@@ -771,6 +815,7 @@ http {
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root /app/html;
|
||||
internal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+44
-10
@@ -11,6 +11,8 @@ http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
server_tokens off;
|
||||
|
||||
access_log /tmp/nginx/access.log;
|
||||
|
||||
client_body_temp_path /tmp/nginx/client_body;
|
||||
@@ -58,7 +60,6 @@ http {
|
||||
absolute_redirect off;
|
||||
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /app/data/acme-webroot;
|
||||
@@ -69,6 +70,7 @@ http {
|
||||
location = /sw.js {
|
||||
root /app/html;
|
||||
expires off;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
@@ -76,31 +78,58 @@ http {
|
||||
location = /manifest.json {
|
||||
root /app/html;
|
||||
expires off;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||
location ^~ /assets/ {
|
||||
root /app/html;
|
||||
expires 1y;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ^~ /fonts/ {
|
||||
root /app/html;
|
||||
expires 1y;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ^~ /icons/ {
|
||||
root /app/html;
|
||||
expires 30d;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=2592000" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~* ^/[^/]+\.(js|css|png|jpe?g|gif|ico|svg|webp|woff2?|ttf|eot)$ {
|
||||
root /app/html;
|
||||
expires 30d;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "public, max-age=2592000" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~* \.map$ {
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
return 404;
|
||||
}
|
||||
|
||||
location / {
|
||||
root /app/html;
|
||||
index index.html index.htm;
|
||||
expires off;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~* \.map$ {
|
||||
return 404;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
|
||||
location ~ ^/users/sessions(/.*)?$ {
|
||||
proxy_pass http://127.0.0.1:30001;
|
||||
proxy_http_version 1.1;
|
||||
@@ -361,7 +390,8 @@ http {
|
||||
|
||||
proxy_cache_bypass 1;
|
||||
proxy_no_cache 1;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
}
|
||||
|
||||
location ~ ^/host/opkssh-callback(/.*)?$ {
|
||||
@@ -376,7 +406,8 @@ http {
|
||||
|
||||
proxy_cache_bypass 1;
|
||||
proxy_no_cache 1;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0" always;
|
||||
}
|
||||
|
||||
location /host/ {
|
||||
@@ -538,6 +569,7 @@ http {
|
||||
client_max_body_size 5G;
|
||||
client_body_timeout 300s;
|
||||
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate" always;
|
||||
|
||||
proxy_pass http://127.0.0.1:30004;
|
||||
@@ -559,6 +591,7 @@ http {
|
||||
client_max_body_size 5G;
|
||||
client_body_timeout 300s;
|
||||
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate" always;
|
||||
|
||||
proxy_pass http://127.0.0.1:30004;
|
||||
@@ -760,6 +793,7 @@ http {
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root /app/html;
|
||||
internal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
# Database backends
|
||||
|
||||
Termix runs on SQLite by default. Postgres and MySQL are supported for
|
||||
self-hosted deployments; this document records how the three differ, because the
|
||||
differences are not only about SQL.
|
||||
|
||||
## This is multi-backend, not a migration
|
||||
|
||||
SQLite is not going away. The desktop app embeds its own backend and cannot ship
|
||||
a database server, so it will always run on SQLite. Postgres and MySQL exist for
|
||||
self-hosted deployments that need more than one process to reach the data —
|
||||
multiple replicas, an external backup story, or an existing database estate.
|
||||
|
||||
Anything that assumes a single engine is wrong.
|
||||
|
||||
## Where the schema comes from
|
||||
|
||||
`src/backend/database/db/schema.ts` is the single source of truth, written
|
||||
against `drizzle-orm/sqlite-core`.
|
||||
|
||||
`schema.pg.ts` and `schema.mysql.ts` are **generated** from it:
|
||||
|
||||
```bash
|
||||
npm run schema:generate # rewrite the generated modules
|
||||
npm run schema:check # fail if they are out of date (runs as part of lint)
|
||||
```
|
||||
|
||||
Never edit the generated files. `npm run lint` fails if they drift from the
|
||||
source, so a schema change that forgets to regenerate cannot reach main.
|
||||
|
||||
The transforms are mechanical:
|
||||
|
||||
| sqlite | postgres | mysql |
|
||||
| ------------------------------------------------ | ----------------- | ----------------------- |
|
||||
| `integer(…, { mode: "boolean" })` | `boolean` | `boolean` |
|
||||
| `integer(…).primaryKey({ autoIncrement: true })` | `serial` | `int().autoincrement()` |
|
||||
| `integer` | `integer` | `int` |
|
||||
| `real` | `doublePrecision` | `double` |
|
||||
| `text` used as a key | `varchar(255)` | `varchar(255)` |
|
||||
|
||||
A column becomes `varchar` if it is a primary key, is unique, or sits on either
|
||||
end of a foreign key — MySQL cannot index an unbounded `TEXT`, and both sides of
|
||||
a foreign key must agree.
|
||||
|
||||
## Durability
|
||||
|
||||
On SQLite the database is loaded into memory and serialised back to an encrypted
|
||||
file, so every write needs an explicit flush. That is what the `onWrite` hook
|
||||
each repository receives is for.
|
||||
|
||||
On Postgres and MySQL a committed write is already durable. No hook is installed
|
||||
at all — see `needsExplicitPersist` in `db/dialect.ts`.
|
||||
|
||||
## Encryption: what changes, and what does not
|
||||
|
||||
This is the part most likely to be misread, so it is spelled out.
|
||||
|
||||
### Unchanged on every backend
|
||||
|
||||
**Field-level encryption still applies.** Credentials and other sensitive values
|
||||
are encrypted in the application before they reach the database, under a
|
||||
per-user data key:
|
||||
|
||||
- `ssh_data` — passwords, private keys, key passphrases, sudo/RDP/VNC/Telnet
|
||||
secrets
|
||||
- `ssh_credentials` — passwords, private and public keys
|
||||
- `users` — TOTP secret and backup codes
|
||||
- `vault_tokens`, `opkssh_tokens`, `termix_identity_ca` — certificates and keys
|
||||
- `shared_host_secrets` — re-encrypted per recipient
|
||||
|
||||
Installation-level secrets — the OIDC client secret and LDAP bind password —
|
||||
are encrypted under the system key, since they have no owning user and must be
|
||||
readable during login.
|
||||
|
||||
This is the protection that matters most, and it is identical on all three
|
||||
engines.
|
||||
|
||||
### Different on Postgres and MySQL
|
||||
|
||||
**Whole-file encryption does not exist.** On SQLite the database file itself is
|
||||
encrypted at rest. There is no equivalent for a client-server engine: the data
|
||||
lives in the server's storage, not in a file Termix owns.
|
||||
|
||||
Concretely, on Postgres/MySQL the following are readable by anyone with database
|
||||
access, where on SQLite they were covered by the file encryption:
|
||||
|
||||
- host names, addresses, ports and usernames
|
||||
- folder and snippet names, and **snippet contents**
|
||||
- audit log entries
|
||||
- session recording metadata and paths
|
||||
- user names, roles and API key hashes
|
||||
|
||||
None of these are credentials — those stay encrypted — but together they
|
||||
describe your estate.
|
||||
|
||||
**If you run Postgres or MySQL, encryption at rest is your responsibility**:
|
||||
transparent data encryption, an encrypted volume, or an encrypted filesystem.
|
||||
Termix does not provide it and cannot.
|
||||
|
||||
### Threat model, side by side
|
||||
|
||||
| | SQLite | Postgres / MySQL |
|
||||
| ----------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------ |
|
||||
| Stolen database file / volume | credentials encrypted, everything else encrypted | credentials encrypted, **rest depends on your storage encryption** |
|
||||
| Database access without app access | credentials unreadable | credentials unreadable |
|
||||
| Application compromise while a user is unlocked | that user's secrets readable | same |
|
||||
| Backups | inherit file encryption | **plain unless you encrypt them** |
|
||||
|
||||
The second row is the point of field-level encryption, and it holds everywhere.
|
||||
The first and last rows are where the backends genuinely differ.
|
||||
|
||||
## Running on Postgres or MySQL
|
||||
|
||||
Two variables. Unset, nothing changes and SQLite is used exactly as before.
|
||||
|
||||
```
|
||||
DATABASE_DIALECT=postgres
|
||||
DATABASE_URL=postgres://user:password@host:5432/termix
|
||||
```
|
||||
|
||||
```
|
||||
DATABASE_DIALECT=mysql
|
||||
DATABASE_URL=mysql://user:password@host:3306/termix
|
||||
```
|
||||
|
||||
`mariadb://` is accepted for MySQL. The scheme is checked against the dialect
|
||||
before a connection is attempted, so a mismatch fails with a readable message
|
||||
rather than a driver error deep in a stack.
|
||||
|
||||
Point it at an **empty** database. Migrations are applied at startup, from
|
||||
`drizzle/postgres` or `drizzle/mysql`, and drizzle records what it has applied —
|
||||
so several instances against one database are safe, and so is restarting.
|
||||
|
||||
There is no migration path from an existing SQLite database. Exporting one and
|
||||
importing it into Postgres is not something this branch does.
|
||||
|
||||
### Docker
|
||||
|
||||
`drizzle/` ships in the image. A compose service needs only the two variables:
|
||||
|
||||
Added to the compose file in the README, that is one service and two variables:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
termix:
|
||||
image: ghcr.io/lukegus/termix:latest
|
||||
environment:
|
||||
PORT: "8080"
|
||||
DATABASE_DIALECT: postgres
|
||||
DATABASE_URL: postgres://termix:termix@db:5432/termix
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
db:
|
||||
image: postgres:16
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: termix
|
||||
POSTGRES_PASSWORD: termix
|
||||
POSTGRES_DB: termix
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
```
|
||||
|
||||
`DATA_DIR` is still used for uploads and recordings on every backend. Only the
|
||||
database itself moves.
|
||||
|
||||
## What is verified, and how
|
||||
|
||||
`npm run verify:dialect -- <url>` applies the migrations to an empty database and
|
||||
drives the real repository classes against it, asserting values rather than the
|
||||
absence of exceptions.
|
||||
|
||||
The repository test suite also runs against each engine:
|
||||
|
||||
```
|
||||
TEST_DIALECT=postgres TEST_DATABASE_URL=<url> npx vitest run \
|
||||
src/backend/tests/database/repositories --no-file-parallelism
|
||||
```
|
||||
|
||||
CI runs both, against PostgreSQL 16 and MySQL 8 service containers. Eighteen
|
||||
tests assert on bytes stored by the SQLite driver and skip on other engines;
|
||||
they still run in the SQLite pass.
|
||||
|
||||
Tested against PostgreSQL 16 and MySQL 8. **MariaDB is not a substitute for
|
||||
MySQL when testing** — it accepts DDL that MySQL 8 rejects, which has hidden a
|
||||
real defect here more than once.
|
||||
|
||||
### What neither of them covers
|
||||
|
||||
Both harnesses build a `DatabaseContext` of their own, so neither runs
|
||||
`createCurrentRepositoryContext()` — the one the application actually uses.
|
||||
That gap hid a hardcoded `dialect: "sqlite"` in it: every engine reported
|
||||
itself as SQLite at runtime while all three test passes stayed green, which on
|
||||
MySQL meant `upsert` reached for `onConflictDoUpdate` and died with a
|
||||
TypeError on the first write.
|
||||
|
||||
Anything the factory decides from the dialect needs its own test against the
|
||||
factory. Asserting it through a hand-built context proves nothing about what
|
||||
runs in production.
|
||||
|
||||
## Known limits
|
||||
|
||||
- The desktop app always uses SQLite. It embeds its own backend and cannot ship
|
||||
a database server.
|
||||
- Repositories import the SQLite table definitions on every engine. That is
|
||||
correct — the query builder needs identifiers and value encoders, and those
|
||||
agree — but it means `PortableDatabase` is a named approximation rather than a
|
||||
guarantee. See `repositories/database-context.ts`.
|
||||
- `getCurrentSettingValue` is a synchronous read. On Postgres and MySQL it comes
|
||||
from a cache primed at startup and kept current by `SettingsRepository`,
|
||||
because those drivers have no synchronous query.
|
||||
|
||||
That cache is per-process, so on a **multi-replica** deployment a setting
|
||||
changed on one instance does not reach the others through the write path. Each
|
||||
replica re-reads the settings table every 30 seconds
|
||||
(`SETTINGS_CACHE_REFRESH_SECONDS`, 0 to disable), which does not make settings
|
||||
immediately consistent — it bounds how long they can disagree. Changing a
|
||||
setting takes effect on the replica that made the change at once, and on the
|
||||
others within the interval.
|
||||
|
||||
- **Importing a backup is SQLite-only.** The restore writes tables in an order
|
||||
that is not dependency-safe and relies on `PRAGMA foreign_keys = OFF`, which
|
||||
has no equivalent here: Postgres needs superuser to disable triggers, and
|
||||
MySQL's session-scoped switch is not guaranteed across a pool. It refuses with
|
||||
a message rather than failing partway through and leaving a half-restored
|
||||
database. Restore into Postgres or MySQL with their own tooling.
|
||||
- **`LIKE` is case-insensitive on SQLite and case-sensitive on Postgres.** The
|
||||
four places that use it match folder path prefixes and settings keys, so the
|
||||
practical effect is that renaming a folder `prod` on SQLite also catches
|
||||
`PROD / api` and on Postgres does not. Postgres is arguably the more correct
|
||||
of the two; nothing was changed to make them agree, because that would alter
|
||||
SQLite behaviour for existing deployments.
|
||||
- The SQLite-era data migrations — legacy shared-credential cleanup, the
|
||||
shared-host-secrets rebuild, per-user field-encryption backfill — do not run on
|
||||
the other engines. A database created by the drizzle migrations never had the
|
||||
shapes they repair.
|
||||
@@ -189,6 +189,20 @@ Termix هي منصة مفتوحة المصدر ومجانية للأبد وذا
|
||||
**اللغات:**
|
||||
دعم مدمج لحوالي 30 لغة (تُدار بواسطة [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**مشاركة الجلسة:**
|
||||
شارك جلسة طرفية أو RDP أو VNC أو Telnet مباشرة مع الآخرين في الوقت الفعلي. شارك عبر رابط (الانضمام بشكل مجهول، بدون الحاجة لحساب) أو مع مستخدم Termix محدد، واختر الوصول للقراءة فقط أو للقراءة والكتابة. يمكن أن تنتهي صلاحية المشاركات تلقائيًا أو يتم إلغاؤها في أي وقت، ويمكن تبديل مشاركة الجلسة عالميًا أو لكل مضيف على حدة.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**تطبيق سطح مكتب مستقل + مزامنة ثنائية الاتجاه:**
|
||||
يعمل تطبيق سطح المكتب Electron بشكل مستقل تمامًا مع خلفية وقاعدة بيانات محلية خاصة به، دون الحاجة لخادم. يمكن اختياريًا توصيله بخادم Termix عن بُعد للمزامنة التلقائية ثنائية الاتجاه للمضيفين وبيانات الاعتماد والمقتطفات والمزيد، واختيار ما إذا كانت اتصالات SSH تبدأ محليًا أو عبر الخادم البعيد.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Termix 是一个开源、永久免费、自托管的一体化服务器管理平
|
||||
**语言:**
|
||||
内置支持约 30 种语言(由 [Crowdin](https://docs.termix.site/translations) 管理)。
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**会话共享:**
|
||||
与他人实时共享终端、RDP、VNC 或 Telnet 会话。通过链接分享(匿名加入,无需帐户)或与特定的 Termix 用户分享,并选择只读或读写权限。共享可以自动过期或随时撤销,会话共享可以全局或按主机切换。
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**桌面独立运行 + 双向同步:**
|
||||
Electron 桌面应用可完全独立运行,拥有自己的本地后端和数据库,无需服务器。也可以选择连接到远程 Termix 服务器,实现主机、凭据、代码片段等的自动双向同步,并选择 SSH 连接是在本地启动还是通过远程服务器启动。
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ SSH-Sitzungen und Tabs bleiben uber Gerate/Aktualisierungen hinweg offen, wenn i
|
||||
**Sprachen:**
|
||||
Integrierte Unterstutzung fur ca. 30 Sprachen (verwaltet uber [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Sitzungsfreigabe:**
|
||||
Teilen Sie eine Live-Terminal-, RDP-, VNC- oder Telnet-Sitzung in Echtzeit mit anderen. Freigabe uber einen Link (anonymer Beitritt, kein Konto erforderlich) oder mit einem bestimmten Termix-Benutzer, mit Wahl zwischen Nur-Lese- oder Lese-/Schreibzugriff. Freigaben konnen automatisch ablaufen oder jederzeit widerrufen werden, und die Sitzungsfreigabe kann global oder pro Host umgeschaltet werden.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Eigenstandiger Desktop + bidirektionale Synchronisierung:**
|
||||
Die Electron-Desktop-App lauft vollstandig eigenstandig mit eigenem lokalem Backend und eigener Datenbank, kein Server erforderlich. Optional mit einem entfernten Termix-Server verbinden fur automatische bidirektionale Synchronisierung von Hosts, Zugangsdaten, Snippets und mehr, mit der Wahl, ob SSH-Verbindungen lokal oder uber den entfernten Server gestartet werden.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Las sesiones SSH y pestanas permanecen abiertas entre dispositivos/actualizacion
|
||||
**Idiomas:**
|
||||
Soporte integrado para aproximadamente 30 idiomas (gestionado por [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Uso compartido de sesion:**
|
||||
Comparte una sesion en vivo de terminal, RDP, VNC o Telnet con otras personas en tiempo real. Comparte mediante un enlace (se une de forma anonima, sin necesidad de cuenta) o con un usuario especifico de Termix, y elige acceso de solo lectura o de lectura y escritura. Las comparticiones pueden expirar automaticamente o revocarse en cualquier momento, y el uso compartido de sesiones se puede activar globalmente o por host.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Aplicacion de escritorio independiente + sincronizacion bidireccional:**
|
||||
La aplicacion de escritorio Electron funciona de forma totalmente independiente con su propio backend y base de datos locales, sin necesidad de servidor. Opcionalmente, conectala a un servidor Termix remoto para sincronizacion bidireccional automatica de hosts, credenciales, fragmentos y mas, y elige si las conexiones SSH se inician localmente o a traves del servidor remoto.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Les sessions SSH et les onglets restent ouverts sur tous les appareils/actualisa
|
||||
**Langues:**
|
||||
Support integre d'environ 30 langues (gere par [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Partage de session:**
|
||||
Partagez une session de terminal, RDP, VNC ou Telnet en direct avec d'autres personnes en temps reel. Partagez via un lien (rejoint anonymement, sans compte necessaire) ou avec un utilisateur Termix specifique, et choisissez un acces en lecture seule ou en lecture-ecriture. Les partages peuvent expirer automatiquement ou etre revoques a tout moment, et le partage de session peut etre active globalement ou par hote.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Application de bureau autonome + synchronisation bidirectionnelle:**
|
||||
L'application de bureau Electron fonctionne de maniere totalement autonome avec son propre backend et sa propre base de donnees locale, sans serveur requis. Connectez-la eventuellement a un serveur Termix distant pour une synchronisation bidirectionnelle automatique des hotes, des identifiants, des extraits de code et plus encore, et choisissez si les connexions SSH sont demarrees localement ou via le serveur distant.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Termix एक ओपन-सोर्स, हमेशा के लिए मु
|
||||
**भाषाएँ:**
|
||||
लगभग 30 भाषाओं का बिल्ट-इन सपोर्ट ([Crowdin](https://docs.termix.site/translations) द्वारा प्रबंधित)।
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**सेशन शेयरिंग:**
|
||||
लाइव टर्मिनल, RDP, VNC, या Telnet सेशन को दूसरों के साथ रीयल टाइम में शेयर करें। लिंक के जरिए शेयर करें (गुमनाम रूप से जुड़ें, अकाउंट की जरूरत नहीं) या किसी खास Termix यूजर के साथ, और रीड-ओनली या रीड-राइट एक्सेस चुनें। शेयर अपने आप एक्सपायर हो सकते हैं या कभी भी रद्द किए जा सकते हैं, और सेशन शेयरिंग को ग्लोबली या प्रति होस्ट टॉगल किया जा सकता है।
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**डेस्कटॉप स्टैंडअलोन + 2-वे सिंक:**
|
||||
Electron डेस्कटॉप ऐप अपने खुद के लोकल बैकएंड और डेटाबेस के साथ पूरी तरह से स्टैंडअलोन चलता है, किसी सर्वर की जरूरत नहीं। चाहें तो इसे किसी रिमोट Termix सर्वर से कनेक्ट करें ताकि होस्ट्स, क्रेडेंशियल्स, स्निपेट्स और अन्य चीज़ों का ऑटोमैटिक 2-वे सिंक हो सके, और चुनें कि SSH कनेक्शन लोकली शुरू हों या रिमोट सर्वर के जरिए।
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Le sessioni SSH e le schede rimangono aperte tra dispositivi/aggiornamenti se ab
|
||||
**Lingue:**
|
||||
Supporto integrato per circa 30 lingue (gestito da [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Condivisione Sessione:**
|
||||
Condividi una sessione di terminale, RDP, VNC o Telnet dal vivo con altri in tempo reale. Condividi tramite un link (accesso anonimo, nessun account necessario) o con un utente Termix specifico, e scegli l'accesso in sola lettura o lettura/scrittura. Le condivisioni possono scadere automaticamente o essere revocate in qualsiasi momento, e la condivisione della sessione puo essere attivata globalmente o per singolo host.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**App Desktop Standalone + Sincronizzazione Bidirezionale:**
|
||||
L'app desktop Electron funziona in modo completamente autonomo con il proprio backend e database locali, senza bisogno di un server. Facoltativamente, collegala a un server Termix remoto per la sincronizzazione bidirezionale automatica di host, credenziali, snippet e altro, scegliendo se le connessioni SSH vengono avviate localmente o tramite il server remoto.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Tailnetのデバイスをリストしてホストとしてすばやく追加し
|
||||
**多言語対応:**
|
||||
約30言語の組み込みサポート([Crowdin](https://docs.termix.site/translations)で管理されています)。
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**セッション共有:**
|
||||
ターミナル、RDP、VNC、Telnetのライブセッションを他のユーザーとリアルタイムで共有できます。リンクで共有(匿名参加、アカウント不要)するか、特定のTermixユーザーと共有し、読み取り専用または読み取り/書き込みアクセスを選択できます。共有は自動的に期限切れになるか、いつでも取り消すことができ、セッション共有はグローバルまたはホストごとに切り替えられます。
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**デスクトップスタンドアロン + 双方向同期:**
|
||||
Electronデスクトップアプリは、独自のローカルバックエンドとデータベースを使用して完全にスタンドアロンで動作し、サーバーは不要です。オプションでリモートのTermixサーバーに接続し、ホスト、認証情報、スニペットなどの自動双方向同期を行い、SSH接続をローカルで開始するかリモートサーバー経由で開始するかを選択できます。
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Tailscale 네트워크의 기기를 나열하여 호스트로 빠르게 추가
|
||||
**다국어 지원:**
|
||||
약 30개 언어 내장 지원([Crowdin](https://docs.termix.site/translations)으로 관리).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**세션 공유:**
|
||||
터미널, RDP, VNC, Telnet 세션을 다른 사람과 실시간으로 공유하세요. 링크를 통해 공유(계정 없이 익명으로 참여)하거나 특정 Termix 사용자와 공유할 수 있으며, 읽기 전용 또는 읽기/쓰기 권한을 선택할 수 있습니다. 공유는 자동으로 만료되거나 언제든지 취소될 수 있으며, 세션 공유는 전역 또는 호스트별로 전환할 수 있습니다.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**데스크톱 독립 실행 + 양방향 동기화:**
|
||||
Electron 데스크톱 앱은 자체 로컬 백엔드와 데이터베이스를 사용하여 서버 없이 완전히 독립적으로 실행됩니다. 선택적으로 원격 Termix 서버에 연결하여 호스트, 자격 증명, 스니펫 등을 자동으로 양방향 동기화하고, SSH 연결을 로컬에서 시작할지 원격 서버를 통해 시작할지 선택할 수 있습니다.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Sessoes SSH e abas permanecem abertas entre dispositivos/atualizacoes se habilit
|
||||
**Idiomas:**
|
||||
Suporte integrado para aproximadamente 30 idiomas (gerenciado pelo [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Compartilhamento de sessao:**
|
||||
Compartilhe uma sessao de terminal, RDP, VNC ou Telnet ao vivo com outras pessoas em tempo real. Compartilhe por meio de um link (entrada anonima, sem necessidade de conta) ou com um usuario especifico do Termix, e escolha acesso somente leitura ou leitura/gravacao. Os compartilhamentos podem expirar automaticamente ou ser revogados a qualquer momento, e o compartilhamento de sessao pode ser ativado globalmente ou por host.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Aplicativo de desktop autonomo + sincronizacao bidirecional:**
|
||||
O aplicativo de desktop Electron funciona de forma totalmente autonoma com seu proprio backend e banco de dados locais, sem necessidade de servidor. Opcionalmente, conecte-o a um servidor Termix remoto para sincronizacao bidirecional automatica de hosts, credenciais, snippets e muito mais, e escolha se as conexoes SSH sao iniciadas localmente ou por meio do servidor remoto.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ SSH-сессии и вкладки остаются открытыми на вс
|
||||
**Языки:**
|
||||
Встроенная поддержка около 30 языков (управляется через [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Общий доступ к сеансу:**
|
||||
Делитесь сеансом терминала, RDP, VNC или Telnet с другими в режиме реального времени. Делитесь по ссылке (анонимное присоединение, учетная запись не требуется) или с конкретным пользователем Termix, выбирая доступ только для чтения или для чтения и записи. Общий доступ может автоматически истекать или быть отозван в любое время, а общий доступ к сеансам можно включать глобально или для отдельного хоста.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Автономное настольное приложение + двусторонняя синхронизация:**
|
||||
Настольное приложение на Electron полностью автономно, с собственным локальным бэкендом и базой данных, сервер не требуется. При желании подключите его к удаленному серверу Termix для автоматической двусторонней синхронизации хостов, учетных данных, сниппетов и прочего, и выберите, запускаются ли SSH-соединения локально или через удаленный сервер.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Kullanici profilinde etkinlestirilmisse SSH oturumlari ve sekmeler cihazlar/yeni
|
||||
**Diller:**
|
||||
Yaklasik 30 dil icin yerlesik destek ([Crowdin](https://docs.termix.site/translations) tarafindan yonetilir).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Oturum Paylasimi:**
|
||||
Canli bir terminal, RDP, VNC veya Telnet oturumunu baskalariyla gercek zamanli olarak paylasin. Bir baglanti uzerinden (anonim olarak katilir, hesap gerekmez) veya belirli bir Termix kullanicisiyla paylasin ve salt okunur veya okuma/yazma erisimi secin. Paylasimlar otomatik olarak sona erebilir veya istediginiz zaman iptal edilebilir; oturum paylasimi genel olarak veya sunucu bazinda acilip kapatilabilir.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Bagimsiz Masaustu + Cift Yonlu Senkronizasyon:**
|
||||
Electron masaustu uygulamasi, kendi yerel arka ucu ve veritabaniyla tamamen bagimsiz calisir, sunucu gerekmez. Istege bagli olarak sunucular, kimlik bilgileri, kod parcaciklari ve daha fazlasinin otomatik cift yonlu senkronizasyonu icin uzak bir Termix sunucusuna baglayin ve SSH baglantilarinin yerel olarak mi yoksa uzak sunucu uzerinden mi baslatilacagini secin.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -189,6 +189,20 @@ Cac phien SSH va tab van mo tren cac thiet bi/lan lam moi neu duoc bat trong ho
|
||||
**Ngon Ngu:**
|
||||
Ho tro tich hop khoang 30 ngon ngu (duoc quan ly boi [Crowdin](https://docs.termix.site/translations)).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Chia Se Phien:**
|
||||
Chia se mot phien terminal, RDP, VNC, hoac Telnet truc tiep voi nguoi khac theo thoi gian thuc. Chia se qua lien ket (tham gia an danh, khong can tai khoan) hoac voi mot nguoi dung Termix cu the, va chon quyen truy cap chi doc hoac doc/ghi. Cac lien ket chia se co the tu dong het han hoac bi thu hoi bat cu luc nao, va tinh nang chia se phien co the duoc bat/tat toan cuc hoac theo tung host.
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
**Ung Dung Desktop Doc Lap + Dong Bo 2 Chieu:**
|
||||
Ung dung desktop Electron chay hoan toan doc lap voi backend va co so du lieu cuc bo rieng, khong can may chu. Tuy chon ket noi voi may chu Termix tu xa de tu dong dong bo 2 chieu cac host, thong tin dang nhap, doan ma va nhieu hon nua, va chon xem cac ket noi SSH duoc khoi tao cuc bo hay thong qua may chu tu xa.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "mysql",
|
||||
schema: "./src/backend/database/db/schema.mysql.ts",
|
||||
out: "./drizzle/mysql",
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "postgresql",
|
||||
schema: "./src/backend/database/db/schema.pg.ts",
|
||||
out: "./drizzle/postgres",
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "sqlite",
|
||||
schema: "./src/backend/database/db/schema.ts",
|
||||
out: "./drizzle/sqlite",
|
||||
});
|
||||
@@ -0,0 +1,890 @@
|
||||
CREATE TABLE `alert_firings` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`rule_id` int NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`host_name` text NOT NULL,
|
||||
`fired_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`resolved_at` text,
|
||||
`value` double,
|
||||
`message` text NOT NULL,
|
||||
`severity` text NOT NULL DEFAULT ('warning'),
|
||||
`acknowledged` boolean NOT NULL DEFAULT false,
|
||||
CONSTRAINT `alert_firings_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `alert_rule_channels` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`rule_id` int NOT NULL,
|
||||
`channel_id` int NOT NULL,
|
||||
CONSTRAINT `alert_rule_channels_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `alert_rules` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`enabled` boolean NOT NULL DEFAULT true,
|
||||
`trigger_type` text NOT NULL,
|
||||
`threshold_value` double,
|
||||
`threshold_duration_seconds` int,
|
||||
`cooldown_minutes` int NOT NULL DEFAULT 15,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `alert_rules_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `api_keys` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`token_hash` text NOT NULL,
|
||||
`token_prefix` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`expires_at` text,
|
||||
`last_used_at` text,
|
||||
`is_active` boolean NOT NULL DEFAULT true,
|
||||
CONSTRAINT `api_keys_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `audit_logs` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255),
|
||||
`username` text NOT NULL,
|
||||
`action` text NOT NULL,
|
||||
`resource_type` text NOT NULL,
|
||||
`resource_id` text,
|
||||
`resource_name` text,
|
||||
`details` text,
|
||||
`ip_address` text,
|
||||
`user_agent` text,
|
||||
`success` boolean NOT NULL,
|
||||
`error_message` text,
|
||||
`timestamp` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `audit_logs_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `c2s_tunnel_presets` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`platform` text,
|
||||
`computer_name` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `c2s_tunnel_presets_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `command_history` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`command` text NOT NULL,
|
||||
`executed_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `command_history_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `dashboard_service_links` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`label` text NOT NULL,
|
||||
`url` text NOT NULL,
|
||||
`order` int NOT NULL DEFAULT 0,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `dashboard_service_links_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `dashboard_service_links_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `dismissed_alerts` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`alert_id` text NOT NULL,
|
||||
`dismissed_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `dismissed_alerts_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `file_manager_pinned` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`pinned_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `file_manager_pinned_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `file_manager_recent` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`last_opened` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `file_manager_recent_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `file_manager_shortcuts` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `file_manager_shortcuts_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `homepage_items` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`type_id` text NOT NULL,
|
||||
`title` text,
|
||||
`config` text NOT NULL DEFAULT ('{}'),
|
||||
`folder_id` int,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `homepage_items_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `homepage_items_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `homepage_layouts` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`layout` text NOT NULL DEFAULT ('{}'),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `homepage_layouts_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `homepage_layouts_user_id_unique` UNIQUE(`user_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_access` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`user_id` varchar(255),
|
||||
`role_id` int,
|
||||
`granted_by` varchar(255) NOT NULL,
|
||||
`permission_level` text NOT NULL DEFAULT ('connect'),
|
||||
`expires_at` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`last_accessed_at` text,
|
||||
`access_count` int NOT NULL DEFAULT 0,
|
||||
CONSTRAINT `host_access_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_health_checks` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`checks` text NOT NULL,
|
||||
`interval_seconds` int NOT NULL DEFAULT 300,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `host_health_checks_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `idx_host_health_checks_user_host` UNIQUE(`user_id`,`host_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_health_history` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`check_id` text NOT NULL,
|
||||
`ts` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`ok` boolean NOT NULL,
|
||||
`latency_ms` int,
|
||||
`detail` text,
|
||||
CONSTRAINT `host_health_history_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_metrics_history` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`ts` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`cpu_percent` double,
|
||||
`mem_percent` double,
|
||||
`disk_percent` double,
|
||||
`net_rx_bytes` int,
|
||||
`net_tx_bytes` int,
|
||||
CONSTRAINT `host_metrics_history_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_metrics_preferences` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`layout` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `host_metrics_preferences_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `idx_host_metrics_prefs_user_host` UNIQUE(`user_id`,`host_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `ssh_data` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`connection_type` text NOT NULL DEFAULT ('ssh'),
|
||||
`name` varchar(255),
|
||||
`ip` text NOT NULL,
|
||||
`port` int NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`folder` text,
|
||||
`tags` text,
|
||||
`pin` boolean NOT NULL DEFAULT false,
|
||||
`auth_type` text NOT NULL,
|
||||
`use_warpgate` boolean NOT NULL DEFAULT false,
|
||||
`share_ssh_auth` boolean NOT NULL DEFAULT false,
|
||||
`force_keyboard_interactive` text,
|
||||
`password` text,
|
||||
`key` text,
|
||||
`key_password` text,
|
||||
`key_type` text,
|
||||
`sudo_password` text,
|
||||
`autostart_password` text,
|
||||
`autostart_key` text,
|
||||
`autostart_key_password` text,
|
||||
`credential_id` int,
|
||||
`override_credential_username` boolean,
|
||||
`vault_profile_id` int,
|
||||
`enable_terminal` boolean NOT NULL DEFAULT true,
|
||||
`enable_session_logging` boolean NOT NULL DEFAULT true,
|
||||
`allow_session_sharing` boolean NOT NULL DEFAULT true,
|
||||
`enable_command_history` boolean NOT NULL DEFAULT true,
|
||||
`enable_tunnel` boolean NOT NULL DEFAULT true,
|
||||
`tunnel_connections` text,
|
||||
`jump_hosts` text,
|
||||
`enable_file_manager` boolean NOT NULL DEFAULT true,
|
||||
`scp_legacy` boolean NOT NULL DEFAULT false,
|
||||
`enable_docker` boolean NOT NULL DEFAULT false,
|
||||
`enable_tmux_monitor` boolean NOT NULL DEFAULT false,
|
||||
`show_terminal_in_sidebar` boolean NOT NULL DEFAULT true,
|
||||
`show_file_manager_in_sidebar` boolean NOT NULL DEFAULT false,
|
||||
`show_tunnel_in_sidebar` boolean NOT NULL DEFAULT false,
|
||||
`show_docker_in_sidebar` boolean NOT NULL DEFAULT false,
|
||||
`show_server_stats_in_sidebar` boolean NOT NULL DEFAULT false,
|
||||
`default_path` text,
|
||||
`stats_config` text,
|
||||
`docker_config` text,
|
||||
`enable_proxmox` boolean NOT NULL DEFAULT false,
|
||||
`proxmox_config` text,
|
||||
`terminal_config` text,
|
||||
`quick_actions` text,
|
||||
`notes` text,
|
||||
`enable_ssh` boolean NOT NULL DEFAULT true,
|
||||
`enable_rdp` boolean NOT NULL DEFAULT false,
|
||||
`enable_vnc` boolean NOT NULL DEFAULT false,
|
||||
`enable_telnet` boolean NOT NULL DEFAULT false,
|
||||
`ssh_port` int DEFAULT 22,
|
||||
`rdp_port` int DEFAULT 3389,
|
||||
`vnc_port` int DEFAULT 5900,
|
||||
`telnet_port` int DEFAULT 23,
|
||||
`rdp_credential_id` int,
|
||||
`rdp_user` text,
|
||||
`rdp_password` text,
|
||||
`rdp_domain` text,
|
||||
`rdp_security` text,
|
||||
`rdp_ignore_cert` boolean DEFAULT false,
|
||||
`vnc_credential_id` int,
|
||||
`vnc_password` text,
|
||||
`vnc_user` text,
|
||||
`telnet_user` text,
|
||||
`telnet_password` text,
|
||||
`telnet_credential_id` int,
|
||||
`rdp_auth_type` text,
|
||||
`vnc_auth_type` text,
|
||||
`telnet_auth_type` text,
|
||||
`domain` text,
|
||||
`security` text,
|
||||
`ignore_cert` boolean DEFAULT false,
|
||||
`guacamole_config` text,
|
||||
`use_socks5` boolean,
|
||||
`socks5_host` text,
|
||||
`socks5_port` int,
|
||||
`socks5_username` text,
|
||||
`socks5_password` text,
|
||||
`socks5_proxy_chain` text,
|
||||
`connection_origin` text,
|
||||
`mac_address` text,
|
||||
`wol_broadcast_address` text,
|
||||
`port_knock_sequence` text,
|
||||
`host_key_fingerprint` text,
|
||||
`host_key_type` text,
|
||||
`host_key_algorithm` text DEFAULT ('sha256'),
|
||||
`host_key_first_seen` text,
|
||||
`host_key_last_verified` text,
|
||||
`host_key_changed_count` int DEFAULT 0,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `ssh_data_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `ssh_data_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `network_topology` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`topology` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `network_topology_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `notification_channels` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`enabled` boolean NOT NULL DEFAULT true,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `notification_channels_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `opkssh_tokens` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`ssh_cert` text NOT NULL,
|
||||
`private_key` text NOT NULL,
|
||||
`email` text,
|
||||
`sub` text,
|
||||
`issuer` text,
|
||||
`audience` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`expires_at` text NOT NULL,
|
||||
`last_used` text,
|
||||
CONSTRAINT `opkssh_tokens_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `idx_opkssh_tokens_user_host` UNIQUE(`user_id`,`host_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `recent_activity` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`host_name` text,
|
||||
`timestamp` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `recent_activity_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `roles` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`display_name` text NOT NULL,
|
||||
`description` text,
|
||||
`is_system` boolean NOT NULL DEFAULT false,
|
||||
`permissions` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `roles_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `roles_name_unique` UNIQUE(`name`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `session_recordings` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`user_id` varchar(255),
|
||||
`username` text,
|
||||
`access_id` int,
|
||||
`started_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`ended_at` text,
|
||||
`duration` int,
|
||||
`commands` text,
|
||||
`dangerous_actions` text,
|
||||
`recording_path` text,
|
||||
`protocol` varchar(255) NOT NULL DEFAULT 'ssh',
|
||||
`format` text NOT NULL DEFAULT ('text'),
|
||||
`terminated_by_owner` boolean DEFAULT false,
|
||||
`termination_reason` text,
|
||||
CONSTRAINT `session_recordings_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `session_share_participants` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`share_id` varchar(255) NOT NULL,
|
||||
`user_id` varchar(255),
|
||||
`guest_label` text,
|
||||
`joined_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`left_at` text,
|
||||
CONSTRAINT `session_share_participants_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `session_shares` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`owner_user_id` varchar(255) NOT NULL,
|
||||
`protocol` varchar(255) NOT NULL,
|
||||
`session_id` text NOT NULL,
|
||||
`tab_instance_id` text,
|
||||
`share_type` text NOT NULL,
|
||||
`target_user_id` varchar(255),
|
||||
`link_token` varchar(255),
|
||||
`permission_level` text NOT NULL DEFAULT ('read-only'),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`expires_at` text NOT NULL,
|
||||
`revoked_at` text,
|
||||
`last_joined_at` text,
|
||||
`join_count` int NOT NULL DEFAULT 0,
|
||||
CONSTRAINT `session_shares_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `session_shares_link_token_unique` UNIQUE(`link_token`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `sessions` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`jwt_token` text NOT NULL,
|
||||
`device_type` text NOT NULL,
|
||||
`device_info` text NOT NULL,
|
||||
`oidc_sub` text,
|
||||
`oidc_sid` text,
|
||||
`sso_provider_id` int,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`expires_at` text NOT NULL,
|
||||
`last_active_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `sessions_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `settings` (
|
||||
`key` varchar(255) NOT NULL,
|
||||
`value` text NOT NULL,
|
||||
CONSTRAINT `settings_key` PRIMARY KEY(`key`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `shared_host_auth_overrides` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`protocol` varchar(255) NOT NULL DEFAULT 'ssh',
|
||||
`credential_id` int NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `shared_host_auth_overrides_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `shared_host_auth_overrides_host_user_protocol_unique` UNIQUE(`host_id`,`user_id`,`protocol`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `shared_host_secrets` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`host_access_id` int NOT NULL,
|
||||
`target_user_id` varchar(255) NOT NULL,
|
||||
`protocol` varchar(255) NOT NULL DEFAULT 'ssh',
|
||||
`source_type` text NOT NULL DEFAULT ('credential'),
|
||||
`original_credential_id` int,
|
||||
`encrypted_username` text,
|
||||
`encrypted_auth_type` text,
|
||||
`encrypted_password` text,
|
||||
`encrypted_key` text,
|
||||
`encrypted_key_password` text,
|
||||
`encrypted_key_type` text,
|
||||
`encrypted_domain` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `shared_host_secrets_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `idx_shared_host_secrets_scope` UNIQUE(`host_access_id`,`target_user_id`,`protocol`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `snippet_access` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`snippet_id` int NOT NULL,
|
||||
`user_id` varchar(255),
|
||||
`role_id` int,
|
||||
`granted_by` varchar(255) NOT NULL,
|
||||
`permission_level` text NOT NULL DEFAULT ('view'),
|
||||
`expires_at` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `snippet_access_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `snippet_folders` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`color` text,
|
||||
`icon` text,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `snippet_folders_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `snippet_folders_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `snippets` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`content` text NOT NULL,
|
||||
`description` text,
|
||||
`folder` text,
|
||||
`order` int NOT NULL DEFAULT 0,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`host_filter` text,
|
||||
CONSTRAINT `snippets_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `snippets_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `ssh_credential_usage` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`credential_id` int NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`used_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `ssh_credential_usage_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `ssh_credentials` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`description` text,
|
||||
`folder` text,
|
||||
`tags` text,
|
||||
`auth_type` text NOT NULL,
|
||||
`username` text,
|
||||
`password` text,
|
||||
`key` text,
|
||||
`private_key` text,
|
||||
`public_key` text,
|
||||
`key_password` text,
|
||||
`key_type` text,
|
||||
`detected_key_type` text,
|
||||
`cert_public_key` text,
|
||||
`usage_count` int NOT NULL DEFAULT 0,
|
||||
`last_used` text,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `ssh_credentials_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `ssh_credentials_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `ssh_folders` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`color` text,
|
||||
`icon` text,
|
||||
`credential_id` int,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `ssh_folders_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `ssh_folders_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `sso_providers` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`enabled` boolean NOT NULL DEFAULT true,
|
||||
`display_order` int NOT NULL DEFAULT 0,
|
||||
`config` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `sso_providers_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `sync_tombstones` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`entity_type` text NOT NULL,
|
||||
`sync_id` varchar(255) NOT NULL,
|
||||
`deleted_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `sync_tombstones_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `termix_identities` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`handle` varchar(255) NOT NULL,
|
||||
`description` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `termix_identities_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `termix_identities_user_id_unique` UNIQUE(`user_id`),
|
||||
CONSTRAINT `termix_identities_handle_unique` UNIQUE(`handle`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `termix_identity_ca` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`identity_id` int NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`public_key` text NOT NULL,
|
||||
`private_key` text NOT NULL,
|
||||
`validity_days` int NOT NULL DEFAULT 90,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `termix_identity_ca_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `termix_identity_ca_identity_id_unique` UNIQUE(`identity_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `termix_identity_keys` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`identity_id` int NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`public_key` text NOT NULL,
|
||||
`key_type` text NOT NULL,
|
||||
`algorithm` text NOT NULL,
|
||||
`label` text,
|
||||
`comment` text,
|
||||
`source` text NOT NULL DEFAULT ('manual'),
|
||||
`credential_id` int,
|
||||
`enabled` boolean NOT NULL DEFAULT true,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `termix_identity_keys_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `tmux_session_tags` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`host_id` int NOT NULL,
|
||||
`session_name` text NOT NULL,
|
||||
`tag` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `tmux_session_tags_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `transfer_recent` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`source_host_id` int NOT NULL,
|
||||
`dest_host_id` int NOT NULL,
|
||||
`dest_path` text NOT NULL,
|
||||
`dest_path_label` text NOT NULL,
|
||||
`last_used` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `transfer_recent_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `trusted_devices` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`device_fingerprint` text NOT NULL,
|
||||
`device_type` text NOT NULL,
|
||||
`device_info` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`expires_at` text NOT NULL,
|
||||
`last_used_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `trusted_devices_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `user_open_tabs` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`tab_type` text NOT NULL,
|
||||
`host_id` int,
|
||||
`label` text NOT NULL,
|
||||
`tab_order` int NOT NULL DEFAULT 0,
|
||||
`backend_session_id` text,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `user_open_tabs_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `user_preferences` (
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`reopen_tabs_on_login` boolean NOT NULL DEFAULT false,
|
||||
`theme` text,
|
||||
`font_size` text,
|
||||
`accent_color` text,
|
||||
`language` text,
|
||||
`storage_mode` text,
|
||||
`command_autocomplete` boolean,
|
||||
`command_palette_enabled` boolean,
|
||||
`show_host_tags` boolean,
|
||||
`host_tray_on_click` boolean,
|
||||
`pin_app_rail` boolean,
|
||||
`expand_app_rail_on_hover` boolean,
|
||||
`folders_collapsed` boolean,
|
||||
`confirm_snippet_execution` boolean,
|
||||
`disable_update_check` boolean,
|
||||
`confirm_tab_close` boolean,
|
||||
`hidden_rail_tabs` text,
|
||||
`compact_host_view` boolean,
|
||||
`status_color_scheme` text,
|
||||
`custom_themes` text,
|
||||
`custom_keybindings` text,
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `user_preferences_user_id` PRIMARY KEY(`user_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `user_roles` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`role_id` int NOT NULL,
|
||||
`granted_by` varchar(255),
|
||||
`granted_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `user_roles_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `idx_user_roles_user_role` UNIQUE(`user_id`,`role_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `users` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`password_hash` text NOT NULL,
|
||||
`is_admin` boolean NOT NULL DEFAULT false,
|
||||
`is_oidc` boolean NOT NULL DEFAULT false,
|
||||
`oidc_identifier` text,
|
||||
`sso_provider_id` int,
|
||||
`client_id` text,
|
||||
`client_secret` text,
|
||||
`issuer_url` text,
|
||||
`authorization_url` text,
|
||||
`token_url` text,
|
||||
`identifier_path` text,
|
||||
`name_path` text,
|
||||
`scopes` text DEFAULT ('openid email profile'),
|
||||
`totp_secret` text,
|
||||
`totp_enabled` boolean NOT NULL DEFAULT false,
|
||||
`totp_backup_codes` text,
|
||||
`registered_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`donation_modal_dismissed` boolean NOT NULL DEFAULT false,
|
||||
CONSTRAINT `users_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `vault_profiles` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`description` text,
|
||||
`folder` text,
|
||||
`tags` text,
|
||||
`vault_addr` text NOT NULL,
|
||||
`vault_namespace` text,
|
||||
`oidc_mount` text,
|
||||
`oidc_role` text,
|
||||
`ssh_mount` text,
|
||||
`ssh_role` text NOT NULL,
|
||||
`valid_principals` text,
|
||||
`key_type` text,
|
||||
`shared` boolean NOT NULL DEFAULT false,
|
||||
`sync_id` varchar(255),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`updated_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
CONSTRAINT `vault_profiles_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `vault_profiles_sync_id_unique` UNIQUE(`sync_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `vault_tokens` (
|
||||
`id` int AUTO_INCREMENT NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`profile_id` int NOT NULL,
|
||||
`ssh_cert` text NOT NULL,
|
||||
`private_key` text NOT NULL,
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`expires_at` text NOT NULL,
|
||||
`last_used` text,
|
||||
CONSTRAINT `vault_tokens_id` PRIMARY KEY(`id`),
|
||||
CONSTRAINT `idx_vault_tokens_user_profile` UNIQUE(`user_id`,`profile_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `webauthn_credentials` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`user_id` varchar(255) NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`credential_id` text NOT NULL,
|
||||
`public_key` text NOT NULL,
|
||||
`counter` int NOT NULL DEFAULT 0,
|
||||
`device_type` text,
|
||||
`backed_up` boolean NOT NULL DEFAULT false,
|
||||
`transports` text,
|
||||
`user_verification` text NOT NULL DEFAULT ('preferred'),
|
||||
`created_at` text NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
`last_used_at` text,
|
||||
CONSTRAINT `webauthn_credentials_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `alert_firings` ADD CONSTRAINT `alert_firings_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `alert_firings` ADD CONSTRAINT `alert_firings_rule_id_alert_rules_id_fk` FOREIGN KEY (`rule_id`) REFERENCES `alert_rules`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `alert_rule_channels` ADD CONSTRAINT `alert_rule_channels_rule_id_alert_rules_id_fk` FOREIGN KEY (`rule_id`) REFERENCES `alert_rules`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `alert_rule_channels` ADD CONSTRAINT `alert_rule_channels_channel_id_notification_channels_id_fk` FOREIGN KEY (`channel_id`) REFERENCES `notification_channels`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `alert_rules` ADD CONSTRAINT `alert_rules_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `alert_rules` ADD CONSTRAINT `alert_rules_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `api_keys` ADD CONSTRAINT `api_keys_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `c2s_tunnel_presets` ADD CONSTRAINT `c2s_tunnel_presets_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `command_history` ADD CONSTRAINT `command_history_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `command_history` ADD CONSTRAINT `command_history_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `dashboard_service_links` ADD CONSTRAINT `dashboard_service_links_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `dismissed_alerts` ADD CONSTRAINT `dismissed_alerts_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `file_manager_pinned` ADD CONSTRAINT `file_manager_pinned_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `file_manager_pinned` ADD CONSTRAINT `file_manager_pinned_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `file_manager_recent` ADD CONSTRAINT `file_manager_recent_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `file_manager_recent` ADD CONSTRAINT `file_manager_recent_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `file_manager_shortcuts` ADD CONSTRAINT `file_manager_shortcuts_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `file_manager_shortcuts` ADD CONSTRAINT `file_manager_shortcuts_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `homepage_items` ADD CONSTRAINT `homepage_items_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `homepage_layouts` ADD CONSTRAINT `homepage_layouts_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_access` ADD CONSTRAINT `host_access_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_access` ADD CONSTRAINT `host_access_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_access` ADD CONSTRAINT `host_access_role_id_roles_id_fk` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_access` ADD CONSTRAINT `host_access_granted_by_users_id_fk` FOREIGN KEY (`granted_by`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_health_checks` ADD CONSTRAINT `host_health_checks_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_health_checks` ADD CONSTRAINT `host_health_checks_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_health_history` ADD CONSTRAINT `host_health_history_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_health_history` ADD CONSTRAINT `host_health_history_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_metrics_history` ADD CONSTRAINT `host_metrics_history_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_metrics_preferences` ADD CONSTRAINT `host_metrics_preferences_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `host_metrics_preferences` ADD CONSTRAINT `host_metrics_preferences_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_data` ADD CONSTRAINT `ssh_data_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_data` ADD CONSTRAINT `ssh_data_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_data` ADD CONSTRAINT `ssh_data_vault_profile_id_vault_profiles_id_fk` FOREIGN KEY (`vault_profile_id`) REFERENCES `vault_profiles`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_data` ADD CONSTRAINT `ssh_data_rdp_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`rdp_credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_data` ADD CONSTRAINT `ssh_data_vnc_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`vnc_credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_data` ADD CONSTRAINT `ssh_data_telnet_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`telnet_credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `network_topology` ADD CONSTRAINT `network_topology_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `notification_channels` ADD CONSTRAINT `notification_channels_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `opkssh_tokens` ADD CONSTRAINT `opkssh_tokens_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `opkssh_tokens` ADD CONSTRAINT `opkssh_tokens_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `recent_activity` ADD CONSTRAINT `recent_activity_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `recent_activity` ADD CONSTRAINT `recent_activity_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_recordings` ADD CONSTRAINT `session_recordings_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_recordings` ADD CONSTRAINT `session_recordings_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_recordings` ADD CONSTRAINT `session_recordings_access_id_host_access_id_fk` FOREIGN KEY (`access_id`) REFERENCES `host_access`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_share_participants` ADD CONSTRAINT `session_share_participants_share_id_session_shares_id_fk` FOREIGN KEY (`share_id`) REFERENCES `session_shares`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_share_participants` ADD CONSTRAINT `session_share_participants_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_shares` ADD CONSTRAINT `session_shares_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_shares` ADD CONSTRAINT `session_shares_owner_user_id_users_id_fk` FOREIGN KEY (`owner_user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `session_shares` ADD CONSTRAINT `session_shares_target_user_id_users_id_fk` FOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `sessions` ADD CONSTRAINT `sessions_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `shared_host_auth_overrides` ADD CONSTRAINT `shared_host_auth_overrides_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `shared_host_auth_overrides` ADD CONSTRAINT `shared_host_auth_overrides_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `shared_host_auth_overrides` ADD CONSTRAINT `shared_host_auth_overrides_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `shared_host_secrets` ADD CONSTRAINT `shared_host_secrets_host_access_id_host_access_id_fk` FOREIGN KEY (`host_access_id`) REFERENCES `host_access`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `shared_host_secrets` ADD CONSTRAINT `shared_host_secrets_target_user_id_users_id_fk` FOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `shared_host_secrets` ADD CONSTRAINT `shared_host_secrets_original_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`original_credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `snippet_access` ADD CONSTRAINT `snippet_access_snippet_id_snippets_id_fk` FOREIGN KEY (`snippet_id`) REFERENCES `snippets`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `snippet_access` ADD CONSTRAINT `snippet_access_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `snippet_access` ADD CONSTRAINT `snippet_access_role_id_roles_id_fk` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `snippet_access` ADD CONSTRAINT `snippet_access_granted_by_users_id_fk` FOREIGN KEY (`granted_by`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `snippet_folders` ADD CONSTRAINT `snippet_folders_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `snippets` ADD CONSTRAINT `snippets_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_credential_usage` ADD CONSTRAINT `ssh_credential_usage_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_credential_usage` ADD CONSTRAINT `ssh_credential_usage_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_credential_usage` ADD CONSTRAINT `ssh_credential_usage_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_credentials` ADD CONSTRAINT `ssh_credentials_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_folders` ADD CONSTRAINT `ssh_folders_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `ssh_folders` ADD CONSTRAINT `ssh_folders_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `sync_tombstones` ADD CONSTRAINT `sync_tombstones_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `termix_identities` ADD CONSTRAINT `termix_identities_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `termix_identity_ca` ADD CONSTRAINT `termix_identity_ca_identity_id_termix_identities_id_fk` FOREIGN KEY (`identity_id`) REFERENCES `termix_identities`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `termix_identity_ca` ADD CONSTRAINT `termix_identity_ca_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `termix_identity_keys` ADD CONSTRAINT `termix_identity_keys_identity_id_termix_identities_id_fk` FOREIGN KEY (`identity_id`) REFERENCES `termix_identities`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `termix_identity_keys` ADD CONSTRAINT `termix_identity_keys_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `termix_identity_keys` ADD CONSTRAINT `termix_identity_keys_credential_id_ssh_credentials_id_fk` FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `tmux_session_tags` ADD CONSTRAINT `tmux_session_tags_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `tmux_session_tags` ADD CONSTRAINT `tmux_session_tags_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `transfer_recent` ADD CONSTRAINT `transfer_recent_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `transfer_recent` ADD CONSTRAINT `transfer_recent_source_host_id_ssh_data_id_fk` FOREIGN KEY (`source_host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `transfer_recent` ADD CONSTRAINT `transfer_recent_dest_host_id_ssh_data_id_fk` FOREIGN KEY (`dest_host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `trusted_devices` ADD CONSTRAINT `trusted_devices_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `user_open_tabs` ADD CONSTRAINT `user_open_tabs_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `user_open_tabs` ADD CONSTRAINT `user_open_tabs_host_id_ssh_data_id_fk` FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `user_preferences` ADD CONSTRAINT `user_preferences_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `user_roles` ADD CONSTRAINT `user_roles_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `user_roles` ADD CONSTRAINT `user_roles_role_id_roles_id_fk` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `user_roles` ADD CONSTRAINT `user_roles_granted_by_users_id_fk` FOREIGN KEY (`granted_by`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `vault_profiles` ADD CONSTRAINT `vault_profiles_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `vault_tokens` ADD CONSTRAINT `vault_tokens_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `vault_tokens` ADD CONSTRAINT `vault_tokens_profile_id_vault_profiles_id_fk` FOREIGN KEY (`profile_id`) REFERENCES `vault_profiles`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `webauthn_credentials` ADD CONSTRAINT `webauthn_credentials_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "mysql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "5",
|
||||
"when": 1785738871436,
|
||||
"tag": "0000_clean_pretty_boy",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,837 @@
|
||||
CREATE TABLE "alert_firings" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"rule_id" integer NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"host_name" text NOT NULL,
|
||||
"fired_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"resolved_at" text,
|
||||
"value" double precision,
|
||||
"message" text NOT NULL,
|
||||
"severity" text DEFAULT 'warning' NOT NULL,
|
||||
"acknowledged" boolean DEFAULT false NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "alert_rule_channels" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"rule_id" integer NOT NULL,
|
||||
"channel_id" integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "alert_rules" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"trigger_type" text NOT NULL,
|
||||
"threshold_value" double precision,
|
||||
"threshold_duration_seconds" integer,
|
||||
"cooldown_minutes" integer DEFAULT 15 NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "api_keys" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"token_hash" text NOT NULL,
|
||||
"token_prefix" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"expires_at" text,
|
||||
"last_used_at" text,
|
||||
"is_active" boolean DEFAULT true NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "audit_logs" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255),
|
||||
"username" text NOT NULL,
|
||||
"action" text NOT NULL,
|
||||
"resource_type" text NOT NULL,
|
||||
"resource_id" text,
|
||||
"resource_name" text,
|
||||
"details" text,
|
||||
"ip_address" text,
|
||||
"user_agent" text,
|
||||
"success" boolean NOT NULL,
|
||||
"error_message" text,
|
||||
"timestamp" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "c2s_tunnel_presets" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"config" text NOT NULL,
|
||||
"platform" text,
|
||||
"computer_name" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "command_history" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"command" text NOT NULL,
|
||||
"executed_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "dashboard_service_links" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"label" text NOT NULL,
|
||||
"url" text NOT NULL,
|
||||
"order" integer DEFAULT 0 NOT NULL,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "dashboard_service_links_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "dismissed_alerts" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"alert_id" text NOT NULL,
|
||||
"dismissed_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "file_manager_pinned" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"path" text NOT NULL,
|
||||
"pinned_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "file_manager_recent" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"path" text NOT NULL,
|
||||
"last_opened" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "file_manager_shortcuts" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"path" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "homepage_items" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"type_id" text NOT NULL,
|
||||
"title" text,
|
||||
"config" text DEFAULT '{}' NOT NULL,
|
||||
"folder_id" integer,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "homepage_items_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "homepage_layouts" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"layout" text DEFAULT '{}' NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "homepage_layouts_user_id_unique" UNIQUE("user_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "host_access" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"user_id" varchar(255),
|
||||
"role_id" integer,
|
||||
"granted_by" varchar(255) NOT NULL,
|
||||
"permission_level" text DEFAULT 'connect' NOT NULL,
|
||||
"expires_at" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"last_accessed_at" text,
|
||||
"access_count" integer DEFAULT 0 NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "host_health_checks" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"checks" text NOT NULL,
|
||||
"interval_seconds" integer DEFAULT 300 NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "host_health_history" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"check_id" text NOT NULL,
|
||||
"ts" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"ok" boolean NOT NULL,
|
||||
"latency_ms" integer,
|
||||
"detail" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "host_metrics_history" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"ts" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"cpu_percent" double precision,
|
||||
"mem_percent" double precision,
|
||||
"disk_percent" double precision,
|
||||
"net_rx_bytes" integer,
|
||||
"net_tx_bytes" integer
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "host_metrics_preferences" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"layout" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "ssh_data" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"connection_type" text DEFAULT 'ssh' NOT NULL,
|
||||
"name" varchar(255),
|
||||
"ip" text NOT NULL,
|
||||
"port" integer NOT NULL,
|
||||
"username" text NOT NULL,
|
||||
"folder" text,
|
||||
"tags" text,
|
||||
"pin" boolean DEFAULT false NOT NULL,
|
||||
"auth_type" text NOT NULL,
|
||||
"use_warpgate" boolean DEFAULT false NOT NULL,
|
||||
"share_ssh_auth" boolean DEFAULT false NOT NULL,
|
||||
"force_keyboard_interactive" text,
|
||||
"password" text,
|
||||
"key" text,
|
||||
"key_password" text,
|
||||
"key_type" text,
|
||||
"sudo_password" text,
|
||||
"autostart_password" text,
|
||||
"autostart_key" text,
|
||||
"autostart_key_password" text,
|
||||
"credential_id" integer,
|
||||
"override_credential_username" boolean,
|
||||
"vault_profile_id" integer,
|
||||
"enable_terminal" boolean DEFAULT true NOT NULL,
|
||||
"enable_session_logging" boolean DEFAULT true NOT NULL,
|
||||
"allow_session_sharing" boolean DEFAULT true NOT NULL,
|
||||
"enable_command_history" boolean DEFAULT true NOT NULL,
|
||||
"enable_tunnel" boolean DEFAULT true NOT NULL,
|
||||
"tunnel_connections" text,
|
||||
"jump_hosts" text,
|
||||
"enable_file_manager" boolean DEFAULT true NOT NULL,
|
||||
"scp_legacy" boolean DEFAULT false NOT NULL,
|
||||
"enable_docker" boolean DEFAULT false NOT NULL,
|
||||
"enable_tmux_monitor" boolean DEFAULT false NOT NULL,
|
||||
"show_terminal_in_sidebar" boolean DEFAULT true NOT NULL,
|
||||
"show_file_manager_in_sidebar" boolean DEFAULT false NOT NULL,
|
||||
"show_tunnel_in_sidebar" boolean DEFAULT false NOT NULL,
|
||||
"show_docker_in_sidebar" boolean DEFAULT false NOT NULL,
|
||||
"show_server_stats_in_sidebar" boolean DEFAULT false NOT NULL,
|
||||
"default_path" text,
|
||||
"stats_config" text,
|
||||
"docker_config" text,
|
||||
"enable_proxmox" boolean DEFAULT false NOT NULL,
|
||||
"proxmox_config" text,
|
||||
"terminal_config" text,
|
||||
"quick_actions" text,
|
||||
"notes" text,
|
||||
"enable_ssh" boolean DEFAULT true NOT NULL,
|
||||
"enable_rdp" boolean DEFAULT false NOT NULL,
|
||||
"enable_vnc" boolean DEFAULT false NOT NULL,
|
||||
"enable_telnet" boolean DEFAULT false NOT NULL,
|
||||
"ssh_port" integer DEFAULT 22,
|
||||
"rdp_port" integer DEFAULT 3389,
|
||||
"vnc_port" integer DEFAULT 5900,
|
||||
"telnet_port" integer DEFAULT 23,
|
||||
"rdp_credential_id" integer,
|
||||
"rdp_user" text,
|
||||
"rdp_password" text,
|
||||
"rdp_domain" text,
|
||||
"rdp_security" text,
|
||||
"rdp_ignore_cert" boolean DEFAULT false,
|
||||
"vnc_credential_id" integer,
|
||||
"vnc_password" text,
|
||||
"vnc_user" text,
|
||||
"telnet_user" text,
|
||||
"telnet_password" text,
|
||||
"telnet_credential_id" integer,
|
||||
"rdp_auth_type" text,
|
||||
"vnc_auth_type" text,
|
||||
"telnet_auth_type" text,
|
||||
"domain" text,
|
||||
"security" text,
|
||||
"ignore_cert" boolean DEFAULT false,
|
||||
"guacamole_config" text,
|
||||
"use_socks5" boolean,
|
||||
"socks5_host" text,
|
||||
"socks5_port" integer,
|
||||
"socks5_username" text,
|
||||
"socks5_password" text,
|
||||
"socks5_proxy_chain" text,
|
||||
"connection_origin" text,
|
||||
"mac_address" text,
|
||||
"wol_broadcast_address" text,
|
||||
"port_knock_sequence" text,
|
||||
"host_key_fingerprint" text,
|
||||
"host_key_type" text,
|
||||
"host_key_algorithm" text DEFAULT 'sha256',
|
||||
"host_key_first_seen" text,
|
||||
"host_key_last_verified" text,
|
||||
"host_key_changed_count" integer DEFAULT 0,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "ssh_data_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "network_topology" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"topology" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "notification_channels" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"type" text NOT NULL,
|
||||
"config" text NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "opkssh_tokens" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"ssh_cert" text NOT NULL,
|
||||
"private_key" text NOT NULL,
|
||||
"email" text,
|
||||
"sub" text,
|
||||
"issuer" text,
|
||||
"audience" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"expires_at" text NOT NULL,
|
||||
"last_used" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "recent_activity" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"type" text NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"host_name" text,
|
||||
"timestamp" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "roles" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"display_name" text NOT NULL,
|
||||
"description" text,
|
||||
"is_system" boolean DEFAULT false NOT NULL,
|
||||
"permissions" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "roles_name_unique" UNIQUE("name")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "session_recordings" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"user_id" varchar(255),
|
||||
"username" text,
|
||||
"access_id" integer,
|
||||
"started_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"ended_at" text,
|
||||
"duration" integer,
|
||||
"commands" text,
|
||||
"dangerous_actions" text,
|
||||
"recording_path" text,
|
||||
"protocol" varchar(255) DEFAULT 'ssh' NOT NULL,
|
||||
"format" text DEFAULT 'text' NOT NULL,
|
||||
"terminated_by_owner" boolean DEFAULT false,
|
||||
"termination_reason" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "session_share_participants" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"share_id" varchar(255) NOT NULL,
|
||||
"user_id" varchar(255),
|
||||
"guest_label" text,
|
||||
"joined_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"left_at" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "session_shares" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"owner_user_id" varchar(255) NOT NULL,
|
||||
"protocol" varchar(255) NOT NULL,
|
||||
"session_id" text NOT NULL,
|
||||
"tab_instance_id" text,
|
||||
"share_type" text NOT NULL,
|
||||
"target_user_id" varchar(255),
|
||||
"link_token" varchar(255),
|
||||
"permission_level" text DEFAULT 'read-only' NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"expires_at" text NOT NULL,
|
||||
"revoked_at" text,
|
||||
"last_joined_at" text,
|
||||
"join_count" integer DEFAULT 0 NOT NULL,
|
||||
CONSTRAINT "session_shares_link_token_unique" UNIQUE("link_token")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "sessions" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"jwt_token" text NOT NULL,
|
||||
"device_type" text NOT NULL,
|
||||
"device_info" text NOT NULL,
|
||||
"oidc_sub" text,
|
||||
"oidc_sid" text,
|
||||
"sso_provider_id" integer,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"expires_at" text NOT NULL,
|
||||
"last_active_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "settings" (
|
||||
"key" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"value" text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "shared_host_auth_overrides" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"protocol" varchar(255) DEFAULT 'ssh' NOT NULL,
|
||||
"credential_id" integer NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "shared_host_secrets" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"host_access_id" integer NOT NULL,
|
||||
"target_user_id" varchar(255) NOT NULL,
|
||||
"protocol" varchar(255) DEFAULT 'ssh' NOT NULL,
|
||||
"source_type" text DEFAULT 'credential' NOT NULL,
|
||||
"original_credential_id" integer,
|
||||
"encrypted_username" text,
|
||||
"encrypted_auth_type" text,
|
||||
"encrypted_password" text,
|
||||
"encrypted_key" text,
|
||||
"encrypted_key_password" text,
|
||||
"encrypted_key_type" text,
|
||||
"encrypted_domain" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "snippet_access" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"snippet_id" integer NOT NULL,
|
||||
"user_id" varchar(255),
|
||||
"role_id" integer,
|
||||
"granted_by" varchar(255) NOT NULL,
|
||||
"permission_level" text DEFAULT 'view' NOT NULL,
|
||||
"expires_at" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "snippet_folders" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"color" text,
|
||||
"icon" text,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "snippet_folders_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "snippets" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"content" text NOT NULL,
|
||||
"description" text,
|
||||
"folder" text,
|
||||
"order" integer DEFAULT 0 NOT NULL,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"host_filter" text,
|
||||
CONSTRAINT "snippets_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "ssh_credential_usage" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"credential_id" integer NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"used_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "ssh_credentials" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"description" text,
|
||||
"folder" text,
|
||||
"tags" text,
|
||||
"auth_type" text NOT NULL,
|
||||
"username" text,
|
||||
"password" text,
|
||||
"key" text,
|
||||
"private_key" text,
|
||||
"public_key" text,
|
||||
"key_password" text,
|
||||
"key_type" text,
|
||||
"detected_key_type" text,
|
||||
"cert_public_key" text,
|
||||
"usage_count" integer DEFAULT 0 NOT NULL,
|
||||
"last_used" text,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "ssh_credentials_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "ssh_folders" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"color" text,
|
||||
"icon" text,
|
||||
"credential_id" integer,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "ssh_folders_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "sso_providers" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"type" text NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"display_order" integer DEFAULT 0 NOT NULL,
|
||||
"config" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "sync_tombstones" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"entity_type" text NOT NULL,
|
||||
"sync_id" varchar(255) NOT NULL,
|
||||
"deleted_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "termix_identities" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"handle" varchar(255) NOT NULL,
|
||||
"description" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "termix_identities_user_id_unique" UNIQUE("user_id"),
|
||||
CONSTRAINT "termix_identities_handle_unique" UNIQUE("handle")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "termix_identity_ca" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"identity_id" integer NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"public_key" text NOT NULL,
|
||||
"private_key" text NOT NULL,
|
||||
"validity_days" integer DEFAULT 90 NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "termix_identity_ca_identity_id_unique" UNIQUE("identity_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "termix_identity_keys" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"identity_id" integer NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"public_key" text NOT NULL,
|
||||
"key_type" text NOT NULL,
|
||||
"algorithm" text NOT NULL,
|
||||
"label" text,
|
||||
"comment" text,
|
||||
"source" text DEFAULT 'manual' NOT NULL,
|
||||
"credential_id" integer,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "tmux_session_tags" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"host_id" integer NOT NULL,
|
||||
"session_name" text NOT NULL,
|
||||
"tag" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "transfer_recent" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"source_host_id" integer NOT NULL,
|
||||
"dest_host_id" integer NOT NULL,
|
||||
"dest_path" text NOT NULL,
|
||||
"dest_path_label" text NOT NULL,
|
||||
"last_used" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "trusted_devices" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"device_fingerprint" text NOT NULL,
|
||||
"device_type" text NOT NULL,
|
||||
"device_info" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"expires_at" text NOT NULL,
|
||||
"last_used_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user_open_tabs" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"tab_type" text NOT NULL,
|
||||
"host_id" integer,
|
||||
"label" text NOT NULL,
|
||||
"tab_order" integer DEFAULT 0 NOT NULL,
|
||||
"backend_session_id" text,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user_preferences" (
|
||||
"user_id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"reopen_tabs_on_login" boolean DEFAULT false NOT NULL,
|
||||
"theme" text,
|
||||
"font_size" text,
|
||||
"accent_color" text,
|
||||
"language" text,
|
||||
"storage_mode" text,
|
||||
"command_autocomplete" boolean,
|
||||
"command_palette_enabled" boolean,
|
||||
"show_host_tags" boolean,
|
||||
"host_tray_on_click" boolean,
|
||||
"pin_app_rail" boolean,
|
||||
"expand_app_rail_on_hover" boolean,
|
||||
"folders_collapsed" boolean,
|
||||
"confirm_snippet_execution" boolean,
|
||||
"disable_update_check" boolean,
|
||||
"confirm_tab_close" boolean,
|
||||
"hidden_rail_tabs" text,
|
||||
"compact_host_view" boolean,
|
||||
"status_color_scheme" text,
|
||||
"custom_themes" text,
|
||||
"custom_keybindings" text,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user_roles" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"role_id" integer NOT NULL,
|
||||
"granted_by" varchar(255),
|
||||
"granted_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "users" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"username" text NOT NULL,
|
||||
"password_hash" text NOT NULL,
|
||||
"is_admin" boolean DEFAULT false NOT NULL,
|
||||
"is_oidc" boolean DEFAULT false NOT NULL,
|
||||
"oidc_identifier" text,
|
||||
"sso_provider_id" integer,
|
||||
"client_id" text,
|
||||
"client_secret" text,
|
||||
"issuer_url" text,
|
||||
"authorization_url" text,
|
||||
"token_url" text,
|
||||
"identifier_path" text,
|
||||
"name_path" text,
|
||||
"scopes" text DEFAULT 'openid email profile',
|
||||
"totp_secret" text,
|
||||
"totp_enabled" boolean DEFAULT false NOT NULL,
|
||||
"totp_backup_codes" text,
|
||||
"registered_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"donation_modal_dismissed" boolean DEFAULT false NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "vault_profiles" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"description" text,
|
||||
"folder" text,
|
||||
"tags" text,
|
||||
"vault_addr" text NOT NULL,
|
||||
"vault_namespace" text,
|
||||
"oidc_mount" text,
|
||||
"oidc_role" text,
|
||||
"ssh_mount" text,
|
||||
"ssh_role" text NOT NULL,
|
||||
"valid_principals" text,
|
||||
"key_type" text,
|
||||
"shared" boolean DEFAULT false NOT NULL,
|
||||
"sync_id" varchar(255),
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"updated_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
CONSTRAINT "vault_profiles_sync_id_unique" UNIQUE("sync_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "vault_tokens" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"profile_id" integer NOT NULL,
|
||||
"ssh_cert" text NOT NULL,
|
||||
"private_key" text NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"expires_at" text NOT NULL,
|
||||
"last_used" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "webauthn_credentials" (
|
||||
"id" varchar(255) PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(255) NOT NULL,
|
||||
"name" varchar(255) NOT NULL,
|
||||
"credential_id" text NOT NULL,
|
||||
"public_key" text NOT NULL,
|
||||
"counter" integer DEFAULT 0 NOT NULL,
|
||||
"device_type" text,
|
||||
"backed_up" boolean DEFAULT false NOT NULL,
|
||||
"transports" text,
|
||||
"user_verification" text DEFAULT 'preferred' NOT NULL,
|
||||
"created_at" text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
"last_used_at" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "alert_firings" ADD CONSTRAINT "alert_firings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "alert_firings" ADD CONSTRAINT "alert_firings_rule_id_alert_rules_id_fk" FOREIGN KEY ("rule_id") REFERENCES "public"."alert_rules"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "alert_rule_channels" ADD CONSTRAINT "alert_rule_channels_rule_id_alert_rules_id_fk" FOREIGN KEY ("rule_id") REFERENCES "public"."alert_rules"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "alert_rule_channels" ADD CONSTRAINT "alert_rule_channels_channel_id_notification_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."notification_channels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "alert_rules" ADD CONSTRAINT "alert_rules_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "alert_rules" ADD CONSTRAINT "alert_rules_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "c2s_tunnel_presets" ADD CONSTRAINT "c2s_tunnel_presets_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "command_history" ADD CONSTRAINT "command_history_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "command_history" ADD CONSTRAINT "command_history_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "dashboard_service_links" ADD CONSTRAINT "dashboard_service_links_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "dismissed_alerts" ADD CONSTRAINT "dismissed_alerts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "file_manager_pinned" ADD CONSTRAINT "file_manager_pinned_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "file_manager_pinned" ADD CONSTRAINT "file_manager_pinned_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "file_manager_recent" ADD CONSTRAINT "file_manager_recent_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "file_manager_recent" ADD CONSTRAINT "file_manager_recent_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "file_manager_shortcuts" ADD CONSTRAINT "file_manager_shortcuts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "file_manager_shortcuts" ADD CONSTRAINT "file_manager_shortcuts_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "homepage_items" ADD CONSTRAINT "homepage_items_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "homepage_layouts" ADD CONSTRAINT "homepage_layouts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_access" ADD CONSTRAINT "host_access_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_access" ADD CONSTRAINT "host_access_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_access" ADD CONSTRAINT "host_access_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_access" ADD CONSTRAINT "host_access_granted_by_users_id_fk" FOREIGN KEY ("granted_by") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_health_checks" ADD CONSTRAINT "host_health_checks_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_health_checks" ADD CONSTRAINT "host_health_checks_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_health_history" ADD CONSTRAINT "host_health_history_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_health_history" ADD CONSTRAINT "host_health_history_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_metrics_history" ADD CONSTRAINT "host_metrics_history_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_metrics_preferences" ADD CONSTRAINT "host_metrics_preferences_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "host_metrics_preferences" ADD CONSTRAINT "host_metrics_preferences_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_data" ADD CONSTRAINT "ssh_data_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_data" ADD CONSTRAINT "ssh_data_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_data" ADD CONSTRAINT "ssh_data_vault_profile_id_vault_profiles_id_fk" FOREIGN KEY ("vault_profile_id") REFERENCES "public"."vault_profiles"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_data" ADD CONSTRAINT "ssh_data_rdp_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("rdp_credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_data" ADD CONSTRAINT "ssh_data_vnc_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("vnc_credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_data" ADD CONSTRAINT "ssh_data_telnet_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("telnet_credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "network_topology" ADD CONSTRAINT "network_topology_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "notification_channels" ADD CONSTRAINT "notification_channels_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "opkssh_tokens" ADD CONSTRAINT "opkssh_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "opkssh_tokens" ADD CONSTRAINT "opkssh_tokens_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "recent_activity" ADD CONSTRAINT "recent_activity_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "recent_activity" ADD CONSTRAINT "recent_activity_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_recordings" ADD CONSTRAINT "session_recordings_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_recordings" ADD CONSTRAINT "session_recordings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_recordings" ADD CONSTRAINT "session_recordings_access_id_host_access_id_fk" FOREIGN KEY ("access_id") REFERENCES "public"."host_access"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_share_participants" ADD CONSTRAINT "session_share_participants_share_id_session_shares_id_fk" FOREIGN KEY ("share_id") REFERENCES "public"."session_shares"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_share_participants" ADD CONSTRAINT "session_share_participants_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_shares" ADD CONSTRAINT "session_shares_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_shares" ADD CONSTRAINT "session_shares_owner_user_id_users_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session_shares" ADD CONSTRAINT "session_shares_target_user_id_users_id_fk" FOREIGN KEY ("target_user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "shared_host_auth_overrides" ADD CONSTRAINT "shared_host_auth_overrides_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "shared_host_auth_overrides" ADD CONSTRAINT "shared_host_auth_overrides_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "shared_host_auth_overrides" ADD CONSTRAINT "shared_host_auth_overrides_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "shared_host_secrets" ADD CONSTRAINT "shared_host_secrets_host_access_id_host_access_id_fk" FOREIGN KEY ("host_access_id") REFERENCES "public"."host_access"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "shared_host_secrets" ADD CONSTRAINT "shared_host_secrets_target_user_id_users_id_fk" FOREIGN KEY ("target_user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "shared_host_secrets" ADD CONSTRAINT "shared_host_secrets_original_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("original_credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "snippet_access" ADD CONSTRAINT "snippet_access_snippet_id_snippets_id_fk" FOREIGN KEY ("snippet_id") REFERENCES "public"."snippets"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "snippet_access" ADD CONSTRAINT "snippet_access_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "snippet_access" ADD CONSTRAINT "snippet_access_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "snippet_access" ADD CONSTRAINT "snippet_access_granted_by_users_id_fk" FOREIGN KEY ("granted_by") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "snippet_folders" ADD CONSTRAINT "snippet_folders_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "snippets" ADD CONSTRAINT "snippets_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_credential_usage" ADD CONSTRAINT "ssh_credential_usage_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_credential_usage" ADD CONSTRAINT "ssh_credential_usage_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_credential_usage" ADD CONSTRAINT "ssh_credential_usage_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_credentials" ADD CONSTRAINT "ssh_credentials_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_folders" ADD CONSTRAINT "ssh_folders_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "ssh_folders" ADD CONSTRAINT "ssh_folders_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "sync_tombstones" ADD CONSTRAINT "sync_tombstones_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "termix_identities" ADD CONSTRAINT "termix_identities_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "termix_identity_ca" ADD CONSTRAINT "termix_identity_ca_identity_id_termix_identities_id_fk" FOREIGN KEY ("identity_id") REFERENCES "public"."termix_identities"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "termix_identity_ca" ADD CONSTRAINT "termix_identity_ca_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "termix_identity_keys" ADD CONSTRAINT "termix_identity_keys_identity_id_termix_identities_id_fk" FOREIGN KEY ("identity_id") REFERENCES "public"."termix_identities"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "termix_identity_keys" ADD CONSTRAINT "termix_identity_keys_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "termix_identity_keys" ADD CONSTRAINT "termix_identity_keys_credential_id_ssh_credentials_id_fk" FOREIGN KEY ("credential_id") REFERENCES "public"."ssh_credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "tmux_session_tags" ADD CONSTRAINT "tmux_session_tags_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "tmux_session_tags" ADD CONSTRAINT "tmux_session_tags_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "transfer_recent" ADD CONSTRAINT "transfer_recent_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "transfer_recent" ADD CONSTRAINT "transfer_recent_source_host_id_ssh_data_id_fk" FOREIGN KEY ("source_host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "transfer_recent" ADD CONSTRAINT "transfer_recent_dest_host_id_ssh_data_id_fk" FOREIGN KEY ("dest_host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "trusted_devices" ADD CONSTRAINT "trusted_devices_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_open_tabs" ADD CONSTRAINT "user_open_tabs_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_open_tabs" ADD CONSTRAINT "user_open_tabs_host_id_ssh_data_id_fk" FOREIGN KEY ("host_id") REFERENCES "public"."ssh_data"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_preferences" ADD CONSTRAINT "user_preferences_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_granted_by_users_id_fk" FOREIGN KEY ("granted_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "vault_profiles" ADD CONSTRAINT "vault_profiles_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "vault_tokens" ADD CONSTRAINT "vault_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "vault_tokens" ADD CONSTRAINT "vault_tokens_profile_id_vault_profiles_id_fk" FOREIGN KEY ("profile_id") REFERENCES "public"."vault_profiles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "webauthn_credentials" ADD CONSTRAINT "webauthn_credentials_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_host_health_checks_user_host" ON "host_health_checks" USING btree ("user_id","host_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_host_metrics_prefs_user_host" ON "host_metrics_preferences" USING btree ("user_id","host_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_opkssh_tokens_user_host" ON "opkssh_tokens" USING btree ("user_id","host_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "shared_host_auth_overrides_host_user_protocol_unique" ON "shared_host_auth_overrides" USING btree ("host_id","user_id","protocol");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_shared_host_secrets_scope" ON "shared_host_secrets" USING btree ("host_access_id","target_user_id","protocol");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_user_roles_user_role" ON "user_roles" USING btree ("user_id","role_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_vault_tokens_user_profile" ON "vault_tokens" USING btree ("user_id","profile_id");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1785738871078,
|
||||
"tag": "0000_jazzy_infant_terrible",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,836 @@
|
||||
CREATE TABLE `alert_firings` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`rule_id` integer NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`host_name` text NOT NULL,
|
||||
`fired_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`resolved_at` text,
|
||||
`value` real,
|
||||
`message` text NOT NULL,
|
||||
`severity` text DEFAULT 'warning' NOT NULL,
|
||||
`acknowledged` integer DEFAULT false NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`rule_id`) REFERENCES `alert_rules`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `alert_rule_channels` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`rule_id` integer NOT NULL,
|
||||
`channel_id` integer NOT NULL,
|
||||
FOREIGN KEY (`rule_id`) REFERENCES `alert_rules`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`channel_id`) REFERENCES `notification_channels`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `alert_rules` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer,
|
||||
`name` text NOT NULL,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`trigger_type` text NOT NULL,
|
||||
`threshold_value` real,
|
||||
`threshold_duration_seconds` integer,
|
||||
`cooldown_minutes` integer DEFAULT 15 NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `api_keys` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`token_hash` text NOT NULL,
|
||||
`token_prefix` text NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`expires_at` text,
|
||||
`last_used_at` text,
|
||||
`is_active` integer DEFAULT true NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `audit_logs` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text,
|
||||
`username` text NOT NULL,
|
||||
`action` text NOT NULL,
|
||||
`resource_type` text NOT NULL,
|
||||
`resource_id` text,
|
||||
`resource_name` text,
|
||||
`details` text,
|
||||
`ip_address` text,
|
||||
`user_agent` text,
|
||||
`success` integer NOT NULL,
|
||||
`error_message` text,
|
||||
`timestamp` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `c2s_tunnel_presets` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`platform` text,
|
||||
`computer_name` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `command_history` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`command` text NOT NULL,
|
||||
`executed_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `dashboard_service_links` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`label` text NOT NULL,
|
||||
`url` text NOT NULL,
|
||||
`order` integer DEFAULT 0 NOT NULL,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `dashboard_service_links_sync_id_unique` ON `dashboard_service_links` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `dismissed_alerts` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`alert_id` text NOT NULL,
|
||||
`dismissed_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `file_manager_pinned` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`pinned_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `file_manager_recent` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`last_opened` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `file_manager_shortcuts` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `homepage_items` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`type_id` text NOT NULL,
|
||||
`title` text,
|
||||
`config` text DEFAULT '{}' NOT NULL,
|
||||
`folder_id` integer,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `homepage_items_sync_id_unique` ON `homepage_items` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `homepage_layouts` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`layout` text DEFAULT '{}' NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `homepage_layouts_user_id_unique` ON `homepage_layouts` (`user_id`);--> statement-breakpoint
|
||||
CREATE TABLE `host_access` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`user_id` text,
|
||||
`role_id` integer,
|
||||
`granted_by` text NOT NULL,
|
||||
`permission_level` text DEFAULT 'connect' NOT NULL,
|
||||
`expires_at` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`last_accessed_at` text,
|
||||
`access_count` integer DEFAULT 0 NOT NULL,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`granted_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_health_checks` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`checks` text NOT NULL,
|
||||
`interval_seconds` integer DEFAULT 300 NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `idx_host_health_checks_user_host` ON `host_health_checks` (`user_id`,`host_id`);--> statement-breakpoint
|
||||
CREATE TABLE `host_health_history` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`check_id` text NOT NULL,
|
||||
`ts` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`ok` integer NOT NULL,
|
||||
`latency_ms` integer,
|
||||
`detail` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_metrics_history` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`ts` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`cpu_percent` real,
|
||||
`mem_percent` real,
|
||||
`disk_percent` real,
|
||||
`net_rx_bytes` integer,
|
||||
`net_tx_bytes` integer,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `host_metrics_preferences` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`layout` text NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `idx_host_metrics_prefs_user_host` ON `host_metrics_preferences` (`user_id`,`host_id`);--> statement-breakpoint
|
||||
CREATE TABLE `ssh_data` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`connection_type` text DEFAULT 'ssh' NOT NULL,
|
||||
`name` text,
|
||||
`ip` text NOT NULL,
|
||||
`port` integer NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`folder` text,
|
||||
`tags` text,
|
||||
`pin` integer DEFAULT false NOT NULL,
|
||||
`auth_type` text NOT NULL,
|
||||
`use_warpgate` integer DEFAULT false NOT NULL,
|
||||
`share_ssh_auth` integer DEFAULT false NOT NULL,
|
||||
`force_keyboard_interactive` text,
|
||||
`password` text,
|
||||
`key` text(8192),
|
||||
`key_password` text,
|
||||
`key_type` text,
|
||||
`sudo_password` text,
|
||||
`autostart_password` text,
|
||||
`autostart_key` text(8192),
|
||||
`autostart_key_password` text,
|
||||
`credential_id` integer,
|
||||
`override_credential_username` integer,
|
||||
`vault_profile_id` integer,
|
||||
`enable_terminal` integer DEFAULT true NOT NULL,
|
||||
`enable_session_logging` integer DEFAULT true NOT NULL,
|
||||
`allow_session_sharing` integer DEFAULT true NOT NULL,
|
||||
`enable_command_history` integer DEFAULT true NOT NULL,
|
||||
`enable_tunnel` integer DEFAULT true NOT NULL,
|
||||
`tunnel_connections` text,
|
||||
`jump_hosts` text,
|
||||
`enable_file_manager` integer DEFAULT true NOT NULL,
|
||||
`scp_legacy` integer DEFAULT false NOT NULL,
|
||||
`enable_docker` integer DEFAULT false NOT NULL,
|
||||
`enable_tmux_monitor` integer DEFAULT false NOT NULL,
|
||||
`show_terminal_in_sidebar` integer DEFAULT true NOT NULL,
|
||||
`show_file_manager_in_sidebar` integer DEFAULT false NOT NULL,
|
||||
`show_tunnel_in_sidebar` integer DEFAULT false NOT NULL,
|
||||
`show_docker_in_sidebar` integer DEFAULT false NOT NULL,
|
||||
`show_server_stats_in_sidebar` integer DEFAULT false NOT NULL,
|
||||
`default_path` text,
|
||||
`stats_config` text,
|
||||
`docker_config` text,
|
||||
`enable_proxmox` integer DEFAULT false NOT NULL,
|
||||
`proxmox_config` text,
|
||||
`terminal_config` text,
|
||||
`quick_actions` text,
|
||||
`notes` text,
|
||||
`enable_ssh` integer DEFAULT true NOT NULL,
|
||||
`enable_rdp` integer DEFAULT false NOT NULL,
|
||||
`enable_vnc` integer DEFAULT false NOT NULL,
|
||||
`enable_telnet` integer DEFAULT false NOT NULL,
|
||||
`ssh_port` integer DEFAULT 22,
|
||||
`rdp_port` integer DEFAULT 3389,
|
||||
`vnc_port` integer DEFAULT 5900,
|
||||
`telnet_port` integer DEFAULT 23,
|
||||
`rdp_credential_id` integer,
|
||||
`rdp_user` text,
|
||||
`rdp_password` text,
|
||||
`rdp_domain` text,
|
||||
`rdp_security` text,
|
||||
`rdp_ignore_cert` integer DEFAULT false,
|
||||
`vnc_credential_id` integer,
|
||||
`vnc_password` text,
|
||||
`vnc_user` text,
|
||||
`telnet_user` text,
|
||||
`telnet_password` text,
|
||||
`telnet_credential_id` integer,
|
||||
`rdp_auth_type` text,
|
||||
`vnc_auth_type` text,
|
||||
`telnet_auth_type` text,
|
||||
`domain` text,
|
||||
`security` text,
|
||||
`ignore_cert` integer DEFAULT false,
|
||||
`guacamole_config` text,
|
||||
`use_socks5` integer,
|
||||
`socks5_host` text,
|
||||
`socks5_port` integer,
|
||||
`socks5_username` text,
|
||||
`socks5_password` text,
|
||||
`socks5_proxy_chain` text,
|
||||
`connection_origin` text,
|
||||
`mac_address` text,
|
||||
`wol_broadcast_address` text,
|
||||
`port_knock_sequence` text,
|
||||
`host_key_fingerprint` text,
|
||||
`host_key_type` text,
|
||||
`host_key_algorithm` text DEFAULT 'sha256',
|
||||
`host_key_first_seen` text,
|
||||
`host_key_last_verified` text,
|
||||
`host_key_changed_count` integer DEFAULT 0,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE set null,
|
||||
FOREIGN KEY (`vault_profile_id`) REFERENCES `vault_profiles`(`id`) ON UPDATE no action ON DELETE set null,
|
||||
FOREIGN KEY (`rdp_credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE set null,
|
||||
FOREIGN KEY (`vnc_credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE set null,
|
||||
FOREIGN KEY (`telnet_credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `ssh_data_sync_id_unique` ON `ssh_data` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `network_topology` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`topology` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `notification_channels` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `opkssh_tokens` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`ssh_cert` text(8192) NOT NULL,
|
||||
`private_key` text(8192) NOT NULL,
|
||||
`email` text,
|
||||
`sub` text,
|
||||
`issuer` text,
|
||||
`audience` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`expires_at` text NOT NULL,
|
||||
`last_used` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `idx_opkssh_tokens_user_host` ON `opkssh_tokens` (`user_id`,`host_id`);--> statement-breakpoint
|
||||
CREATE TABLE `recent_activity` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`host_name` text,
|
||||
`timestamp` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `roles` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`display_name` text NOT NULL,
|
||||
`description` text,
|
||||
`is_system` integer DEFAULT false NOT NULL,
|
||||
`permissions` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `roles_name_unique` ON `roles` (`name`);--> statement-breakpoint
|
||||
CREATE TABLE `session_recordings` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`user_id` text,
|
||||
`username` text,
|
||||
`access_id` integer,
|
||||
`started_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`ended_at` text,
|
||||
`duration` integer,
|
||||
`commands` text,
|
||||
`dangerous_actions` text,
|
||||
`recording_path` text,
|
||||
`protocol` text DEFAULT 'ssh' NOT NULL,
|
||||
`format` text DEFAULT 'text' NOT NULL,
|
||||
`terminated_by_owner` integer DEFAULT false,
|
||||
`termination_reason` text,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,
|
||||
FOREIGN KEY (`access_id`) REFERENCES `host_access`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `session_share_participants` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`share_id` text NOT NULL,
|
||||
`user_id` text,
|
||||
`guest_label` text,
|
||||
`joined_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`left_at` text,
|
||||
FOREIGN KEY (`share_id`) REFERENCES `session_shares`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `session_shares` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`owner_user_id` text NOT NULL,
|
||||
`protocol` text NOT NULL,
|
||||
`session_id` text NOT NULL,
|
||||
`tab_instance_id` text,
|
||||
`share_type` text NOT NULL,
|
||||
`target_user_id` text,
|
||||
`link_token` text,
|
||||
`permission_level` text DEFAULT 'read-only' NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`expires_at` text NOT NULL,
|
||||
`revoked_at` text,
|
||||
`last_joined_at` text,
|
||||
`join_count` integer DEFAULT 0 NOT NULL,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`owner_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `session_shares_link_token_unique` ON `session_shares` (`link_token`);--> statement-breakpoint
|
||||
CREATE TABLE `sessions` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`jwt_token` text NOT NULL,
|
||||
`device_type` text NOT NULL,
|
||||
`device_info` text NOT NULL,
|
||||
`oidc_sub` text,
|
||||
`oidc_sid` text,
|
||||
`sso_provider_id` integer,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`expires_at` text NOT NULL,
|
||||
`last_active_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `settings` (
|
||||
`key` text PRIMARY KEY NOT NULL,
|
||||
`value` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `shared_host_auth_overrides` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`protocol` text DEFAULT 'ssh' NOT NULL,
|
||||
`credential_id` integer NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `shared_host_auth_overrides_host_user_protocol_unique` ON `shared_host_auth_overrides` (`host_id`,`user_id`,`protocol`);--> statement-breakpoint
|
||||
CREATE TABLE `shared_host_secrets` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`host_access_id` integer NOT NULL,
|
||||
`target_user_id` text NOT NULL,
|
||||
`protocol` text DEFAULT 'ssh' NOT NULL,
|
||||
`source_type` text DEFAULT 'credential' NOT NULL,
|
||||
`original_credential_id` integer,
|
||||
`encrypted_username` text,
|
||||
`encrypted_auth_type` text,
|
||||
`encrypted_password` text,
|
||||
`encrypted_key` text(16384),
|
||||
`encrypted_key_password` text,
|
||||
`encrypted_key_type` text,
|
||||
`encrypted_domain` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`host_access_id`) REFERENCES `host_access`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`original_credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `idx_shared_host_secrets_scope` ON `shared_host_secrets` (`host_access_id`,`target_user_id`,`protocol`);--> statement-breakpoint
|
||||
CREATE TABLE `snippet_access` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`snippet_id` integer NOT NULL,
|
||||
`user_id` text,
|
||||
`role_id` integer,
|
||||
`granted_by` text NOT NULL,
|
||||
`permission_level` text DEFAULT 'view' NOT NULL,
|
||||
`expires_at` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`snippet_id`) REFERENCES `snippets`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`granted_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `snippet_folders` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`color` text,
|
||||
`icon` text,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `snippet_folders_sync_id_unique` ON `snippet_folders` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `snippets` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`content` text NOT NULL,
|
||||
`description` text,
|
||||
`folder` text,
|
||||
`order` integer DEFAULT 0 NOT NULL,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`host_filter` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `snippets_sync_id_unique` ON `snippets` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `ssh_credential_usage` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`credential_id` integer NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`used_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `ssh_credentials` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text,
|
||||
`folder` text,
|
||||
`tags` text,
|
||||
`auth_type` text NOT NULL,
|
||||
`username` text,
|
||||
`password` text,
|
||||
`key` text(16384),
|
||||
`private_key` text(16384),
|
||||
`public_key` text(4096),
|
||||
`key_password` text,
|
||||
`key_type` text,
|
||||
`detected_key_type` text,
|
||||
`cert_public_key` text(8192),
|
||||
`usage_count` integer DEFAULT 0 NOT NULL,
|
||||
`last_used` text,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `ssh_credentials_sync_id_unique` ON `ssh_credentials` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `ssh_folders` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`color` text,
|
||||
`icon` text,
|
||||
`credential_id` integer,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `ssh_folders_sync_id_unique` ON `ssh_folders` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `sso_providers` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`display_order` integer DEFAULT 0 NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `sync_tombstones` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`entity_type` text NOT NULL,
|
||||
`sync_id` text NOT NULL,
|
||||
`deleted_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `termix_identities` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`handle` text NOT NULL,
|
||||
`description` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `termix_identities_user_id_unique` ON `termix_identities` (`user_id`);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `termix_identities_handle_unique` ON `termix_identities` (`handle`);--> statement-breakpoint
|
||||
CREATE TABLE `termix_identity_ca` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`identity_id` integer NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`public_key` text(4096) NOT NULL,
|
||||
`private_key` text(8192) NOT NULL,
|
||||
`validity_days` integer DEFAULT 90 NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`identity_id`) REFERENCES `termix_identities`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `termix_identity_ca_identity_id_unique` ON `termix_identity_ca` (`identity_id`);--> statement-breakpoint
|
||||
CREATE TABLE `termix_identity_keys` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`identity_id` integer NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`public_key` text(8192) NOT NULL,
|
||||
`key_type` text NOT NULL,
|
||||
`algorithm` text NOT NULL,
|
||||
`label` text,
|
||||
`comment` text,
|
||||
`source` text DEFAULT 'manual' NOT NULL,
|
||||
`credential_id` integer,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`identity_id`) REFERENCES `termix_identities`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`credential_id`) REFERENCES `ssh_credentials`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `tmux_session_tags` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`host_id` integer NOT NULL,
|
||||
`session_name` text NOT NULL,
|
||||
`tag` text NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `transfer_recent` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`source_host_id` integer NOT NULL,
|
||||
`dest_host_id` integer NOT NULL,
|
||||
`dest_path` text NOT NULL,
|
||||
`dest_path_label` text NOT NULL,
|
||||
`last_used` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`source_host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`dest_host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `trusted_devices` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`device_fingerprint` text NOT NULL,
|
||||
`device_type` text NOT NULL,
|
||||
`device_info` text NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`expires_at` text NOT NULL,
|
||||
`last_used_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `user_open_tabs` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`tab_type` text NOT NULL,
|
||||
`host_id` integer,
|
||||
`label` text NOT NULL,
|
||||
`tab_order` integer DEFAULT 0 NOT NULL,
|
||||
`backend_session_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`host_id`) REFERENCES `ssh_data`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `user_preferences` (
|
||||
`user_id` text PRIMARY KEY NOT NULL,
|
||||
`reopen_tabs_on_login` integer DEFAULT false NOT NULL,
|
||||
`theme` text,
|
||||
`font_size` text,
|
||||
`accent_color` text,
|
||||
`language` text,
|
||||
`storage_mode` text,
|
||||
`command_autocomplete` integer,
|
||||
`command_palette_enabled` integer,
|
||||
`show_host_tags` integer,
|
||||
`host_tray_on_click` integer,
|
||||
`pin_app_rail` integer,
|
||||
`expand_app_rail_on_hover` integer,
|
||||
`folders_collapsed` integer,
|
||||
`confirm_snippet_execution` integer,
|
||||
`disable_update_check` integer,
|
||||
`confirm_tab_close` integer,
|
||||
`hidden_rail_tabs` text,
|
||||
`compact_host_view` integer,
|
||||
`status_color_scheme` text,
|
||||
`custom_themes` text,
|
||||
`custom_keybindings` text,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `user_roles` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`role_id` integer NOT NULL,
|
||||
`granted_by` text,
|
||||
`granted_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`granted_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `idx_user_roles_user_role` ON `user_roles` (`user_id`,`role_id`);--> statement-breakpoint
|
||||
CREATE TABLE `users` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`password_hash` text NOT NULL,
|
||||
`is_admin` integer DEFAULT false NOT NULL,
|
||||
`is_oidc` integer DEFAULT false NOT NULL,
|
||||
`oidc_identifier` text,
|
||||
`sso_provider_id` integer,
|
||||
`client_id` text,
|
||||
`client_secret` text,
|
||||
`issuer_url` text,
|
||||
`authorization_url` text,
|
||||
`token_url` text,
|
||||
`identifier_path` text,
|
||||
`name_path` text,
|
||||
`scopes` text DEFAULT 'openid email profile',
|
||||
`totp_secret` text,
|
||||
`totp_enabled` integer DEFAULT false NOT NULL,
|
||||
`totp_backup_codes` text,
|
||||
`registered_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`donation_modal_dismissed` integer DEFAULT false NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `vault_profiles` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text,
|
||||
`folder` text,
|
||||
`tags` text,
|
||||
`vault_addr` text NOT NULL,
|
||||
`vault_namespace` text,
|
||||
`oidc_mount` text,
|
||||
`oidc_role` text,
|
||||
`ssh_mount` text,
|
||||
`ssh_role` text NOT NULL,
|
||||
`valid_principals` text,
|
||||
`key_type` text,
|
||||
`shared` integer DEFAULT false NOT NULL,
|
||||
`sync_id` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `vault_profiles_sync_id_unique` ON `vault_profiles` (`sync_id`);--> statement-breakpoint
|
||||
CREATE TABLE `vault_tokens` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`profile_id` integer NOT NULL,
|
||||
`ssh_cert` text(8192) NOT NULL,
|
||||
`private_key` text(8192) NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`expires_at` text NOT NULL,
|
||||
`last_used` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`profile_id`) REFERENCES `vault_profiles`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `idx_vault_tokens_user_profile` ON `vault_tokens` (`user_id`,`profile_id`);--> statement-breakpoint
|
||||
CREATE TABLE `webauthn_credentials` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`credential_id` text NOT NULL,
|
||||
`public_key` text NOT NULL,
|
||||
`counter` integer DEFAULT 0 NOT NULL,
|
||||
`device_type` text,
|
||||
`backed_up` integer DEFAULT false NOT NULL,
|
||||
`transports` text,
|
||||
`user_verification` text DEFAULT 'preferred' NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`last_used_at` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "sqlite",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "6",
|
||||
"when": 1785738870735,
|
||||
"tag": "0000_clever_hercules",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
function getUnpackedAppRoot(appRoot) {
|
||||
return appRoot.replace(
|
||||
/app(-[a-z0-9]+)?\.asar(?!\.unpacked)/,
|
||||
"app$1.asar.unpacked",
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = { getUnpackedAppRoot };
|
||||
+145
-105
@@ -12,6 +12,7 @@ const {
|
||||
nativeImage,
|
||||
} = require("electron");
|
||||
const path = require("path");
|
||||
const { getUnpackedAppRoot } = require("./backend-paths.cjs");
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const https = require("https");
|
||||
@@ -442,7 +443,10 @@ function isInvalidCertificateAllowedForUrl(url) {
|
||||
// fall through
|
||||
}
|
||||
|
||||
const config = getServerConfigSync();
|
||||
// The only remaining "connected remote server" a self-signed/invalid
|
||||
// certificate could legitimately apply to is the Remote Sync server
|
||||
// (also used for C2S tunnel relaying, see getC2SRelayUrl).
|
||||
const config = remoteSync.getRemoteSyncConfig();
|
||||
if (!config?.allowInvalidCertificate || !config?.serverUrl) return false;
|
||||
|
||||
return getOrigin(url) === getOrigin(config.serverUrl);
|
||||
@@ -797,10 +801,7 @@ function getBackendPaths() {
|
||||
// fork() does not go through Electron's asar redirector — use the unpacked path.
|
||||
// On macOS multi-arch builds (mergeASARs: false), electron-builder names the ASAR
|
||||
// app-arm64.asar / app-x64.asar instead of app.asar, so match all variants.
|
||||
const unpackedRoot = appRoot.replace(
|
||||
/app(-[a-z0-9]+)?\.asar(?!\.unpacked)/,
|
||||
"app.asar.unpacked",
|
||||
);
|
||||
const unpackedRoot = getUnpackedAppRoot(appRoot);
|
||||
const backendDir = path.join(unpackedRoot, "dist", "backend", "backend");
|
||||
return {
|
||||
entryPath: path.join(backendDir, "starter.js"),
|
||||
@@ -817,7 +818,62 @@ function getBackendDataDir() {
|
||||
return dataDir;
|
||||
}
|
||||
|
||||
function getBackendPidFilePath() {
|
||||
return path.join(app.getPath("userData"), "backend.pid");
|
||||
}
|
||||
|
||||
// If the app was previously killed abnormally (crash, force-quit, Task
|
||||
// Manager) rather than through the normal quit flow, will-quit never fires
|
||||
// and stopBackendServer() never runs -- the forked backend child is a
|
||||
// genuinely separate OS process on Windows/mac/Linux, so it keeps running
|
||||
// and holding every port the backend binds (30001, 30003-30008, 30010,
|
||||
// 30012...). Every subsequent launch's own backend then fails outright
|
||||
// with EADDRINUSE and the app is stuck until something manually kills the
|
||||
// orphan. Reap any such leftover process, identified by PID file, before
|
||||
// spawning a new one.
|
||||
function reapOrphanedBackendProcess() {
|
||||
const pidFilePath = getBackendPidFilePath();
|
||||
let recordedPid;
|
||||
try {
|
||||
recordedPid = parseInt(fs.readFileSync(pidFilePath, "utf8").trim(), 10);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!Number.isInteger(recordedPid) || recordedPid <= 0) return;
|
||||
|
||||
try {
|
||||
// Signal 0 does not kill the process -- it only checks whether a
|
||||
// process with this PID exists and is signalable, throwing ESRCH if
|
||||
// not. This avoids killing an unrelated process that happens to have
|
||||
// reused the same PID since the last run.
|
||||
process.kill(recordedPid, 0);
|
||||
} catch {
|
||||
// No live process at that PID; nothing to reap.
|
||||
try {
|
||||
fs.unlinkSync(pidFilePath);
|
||||
} catch {
|
||||
// already absent
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
logToFile(
|
||||
`Found orphaned backend process from a previous session (pid ${recordedPid}), terminating it before starting a new one`,
|
||||
);
|
||||
try {
|
||||
process.kill(recordedPid, "SIGKILL");
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
try {
|
||||
fs.unlinkSync(pidFilePath);
|
||||
} catch {
|
||||
// already absent
|
||||
}
|
||||
}
|
||||
|
||||
function startBackendServer() {
|
||||
reapOrphanedBackendProcess();
|
||||
return new Promise((resolve) => {
|
||||
const { entryPath, backendCwd } = getBackendPaths();
|
||||
|
||||
@@ -859,6 +915,11 @@ function startBackendServer() {
|
||||
});
|
||||
|
||||
logToFile("Backend process spawned, pid:", backendProcess.pid);
|
||||
try {
|
||||
fs.writeFileSync(getBackendPidFilePath(), String(backendProcess.pid));
|
||||
} catch {
|
||||
// Non-fatal: only means a future crash won't self-heal via reap.
|
||||
}
|
||||
|
||||
let resolved = false;
|
||||
const readyTimeout = setTimeout(() => {
|
||||
@@ -890,6 +951,7 @@ function startBackendServer() {
|
||||
backendStartFailed = true;
|
||||
}
|
||||
backendProcess = null;
|
||||
clearBackendPidFile();
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(readyTimeout);
|
||||
@@ -909,6 +971,14 @@ function startBackendServer() {
|
||||
});
|
||||
}
|
||||
|
||||
function clearBackendPidFile() {
|
||||
try {
|
||||
fs.unlinkSync(getBackendPidFilePath());
|
||||
} catch {
|
||||
// already absent
|
||||
}
|
||||
}
|
||||
|
||||
function stopBackendServer() {
|
||||
if (!backendProcess) return;
|
||||
|
||||
@@ -931,6 +1001,7 @@ function stopBackendServer() {
|
||||
backendProcess.on("exit", () => {
|
||||
clearTimeout(forceKillTimeout);
|
||||
backendProcess = null;
|
||||
clearBackendPidFile();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1445,6 +1516,16 @@ ipcMain.handle("save-server-config", (event, config) => {
|
||||
|
||||
// --- Remote sync (optional desktop <-> self-hosted server sync) ---
|
||||
|
||||
// Surfaces the pre-standalone-rework server-config.json (if a serverUrl was
|
||||
// ever set in it) so the renderer can prompt upgraded installs to set up
|
||||
// Remote Sync -- their hosts live on that old server and won't appear
|
||||
// locally until sync is enabled. A fresh install never had this file, so
|
||||
// this is naturally false for anyone who never used the old architecture.
|
||||
ipcMain.handle("get-legacy-server-config", () => {
|
||||
const config = getServerConfigSync();
|
||||
return { serverUrl: config?.serverUrl || null };
|
||||
});
|
||||
|
||||
ipcMain.handle("get-desktop-settings", () => {
|
||||
return remoteSync.getDesktopSettings();
|
||||
});
|
||||
@@ -1498,6 +1579,10 @@ ipcMain.handle("get-remote-sync-status", () => {
|
||||
return remoteSync.getRemoteSyncEngine()?.status || null;
|
||||
});
|
||||
|
||||
ipcMain.handle("get-remote-sync-user-info", () => {
|
||||
return remoteSync.getRemoteSyncUserInfo();
|
||||
});
|
||||
|
||||
ipcMain.handle("remote-sync-now", async () => {
|
||||
return (await remoteSync.getRemoteSyncEngine()?.syncNow()) || null;
|
||||
});
|
||||
@@ -1642,43 +1727,33 @@ const C2S_WS_HIGH_WATERMARK = 1024 * 1024;
|
||||
const C2S_WS_LOW_WATERMARK = 256 * 1024;
|
||||
const C2S_STREAM_WRITE_LIMIT = 8 * 1024 * 1024;
|
||||
|
||||
// C2S (client-to-server) tunnels relay through a connected, self-hosted
|
||||
// Termix server -- the same "remote server" concept Remote Sync connects
|
||||
// to, not the always-local embedded backend. There's no separate C2S
|
||||
// server-URL setting in the UI; it has always shared whatever remote
|
||||
// server the rest of the app was pointed at. Before the standalone-first
|
||||
// rework that was server-config.json; now it's remote-sync-config.json,
|
||||
// since that's the only remaining notion of "a connected remote server."
|
||||
function getC2SRelayUrl() {
|
||||
const config = getServerConfigSync();
|
||||
const serverUrl =
|
||||
config?.serverUrl || (!isDev ? "http://127.0.0.1:30003" : null);
|
||||
const config = remoteSync.getRemoteSyncConfig();
|
||||
const serverUrl = config?.serverUrl;
|
||||
if (!serverUrl) {
|
||||
throw new Error("No Termix server configured");
|
||||
throw new Error(
|
||||
"No remote Termix server connected -- enable Remote Sync first",
|
||||
);
|
||||
}
|
||||
|
||||
const base = serverUrl.replace(/\/$/, "");
|
||||
const relayHttpUrl = base.endsWith(":30003")
|
||||
? `${base}/ssh/tunnel/c2s/stream`
|
||||
: `${base}/ssh/tunnel/c2s/stream`;
|
||||
const relayHttpUrl = `${base}/ssh/tunnel/c2s/stream`;
|
||||
return relayHttpUrl.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
|
||||
}
|
||||
|
||||
async function getC2SRelayHeaders(relayUrl) {
|
||||
const cookieUrl = relayUrl
|
||||
.replace(/^ws:/, "http:")
|
||||
.replace(/^wss:/, "https:");
|
||||
|
||||
let jwt;
|
||||
if (mainWindow?.webContents?.session) {
|
||||
const cookies = await mainWindow.webContents.session.cookies.get({
|
||||
url: cookieUrl,
|
||||
name: "jwt",
|
||||
});
|
||||
jwt = cookies[0]?.value;
|
||||
}
|
||||
|
||||
if (!jwt) {
|
||||
jwt = getRememberedElectronAuthCookie("jwt", cookieUrl)?.value;
|
||||
}
|
||||
|
||||
async function getC2SRelayHeaders() {
|
||||
const jwt = remoteSync.getRemoteSyncJwt();
|
||||
if (!jwt) return {};
|
||||
|
||||
return {
|
||||
Cookie: `jwt=${encodeURIComponent(jwt)}`,
|
||||
Authorization: `Bearer ${jwt}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1778,7 +1853,7 @@ async function openC2SRelay(
|
||||
) {
|
||||
const tunnelName = tunnel.name || getC2STunnelName(tunnel);
|
||||
const relayUrl = getC2SRelayUrl();
|
||||
const headers = await getC2SRelayHeaders(relayUrl);
|
||||
const headers = await getC2SRelayHeaders();
|
||||
logToFile(`[c2s] opening relay for ${tunnelName}`, {
|
||||
relayUrl,
|
||||
targetHost,
|
||||
@@ -1883,7 +1958,7 @@ async function openC2SRelay(
|
||||
|
||||
async function testC2SRelay(tunnel, targetHost, targetPort) {
|
||||
const relayUrl = getC2SRelayUrl();
|
||||
const headers = await getC2SRelayHeaders(relayUrl);
|
||||
const headers = await getC2SRelayHeaders();
|
||||
const ws = new WebSocket(
|
||||
relayUrl,
|
||||
getWebSocketOptions(relayUrl, { headers }),
|
||||
@@ -2162,7 +2237,7 @@ async function startC2SRemoteTunnel(tunnel, index = 0) {
|
||||
}
|
||||
|
||||
const relayUrl = getC2SRelayUrl();
|
||||
const headers = await getC2SRelayHeaders(relayUrl);
|
||||
const headers = await getC2SRelayHeaders();
|
||||
const ws = new WebSocket(
|
||||
relayUrl,
|
||||
getWebSocketOptions(relayUrl, { headers }),
|
||||
@@ -2844,31 +2919,33 @@ ipcMain.handle("close-external-editor", (_event, editId) => {
|
||||
ipcMain.handle("test-server-connection", async (event, serverUrl) => {
|
||||
try {
|
||||
const normalizedServerUrl = serverUrl.replace(/\/$/, "");
|
||||
|
||||
const healthUrl = `${normalizedServerUrl}/health`;
|
||||
|
||||
// This is a best-effort reachability probe, not a hard gate: a reverse
|
||||
// proxy doing SSO in front of the real server (Pangolin, Authelia,
|
||||
// Cloudflare Access, etc.) intercepts this unauthenticated request
|
||||
// before it ever reaches Termix's own /health route, and returns its
|
||||
// own login page (HTML, or a redirect) instead of {"status":"ok"}.
|
||||
// That's a legitimate, working setup -- the login iframe shown right
|
||||
// after this check is what actually proves the server is real, by
|
||||
// completing an authenticated round-trip. So any response at all here
|
||||
// (any status code, any body) means "something is there, let the user
|
||||
// proceed"; only a network-level failure (nothing answered at all)
|
||||
// blocks continuing.
|
||||
try {
|
||||
const response = await httpFetch(healthUrl, {
|
||||
method: "GET",
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.text();
|
||||
|
||||
if (
|
||||
data.includes("<html") ||
|
||||
data.includes("<!DOCTYPE") ||
|
||||
data.includes("<head>") ||
|
||||
data.includes("<body>")
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Server returned HTML instead of JSON. This does not appear to be a Termix server.",
|
||||
};
|
||||
}
|
||||
const data = await response.text();
|
||||
const looksLikeHtml =
|
||||
data.includes("<html") ||
|
||||
data.includes("<!DOCTYPE") ||
|
||||
data.includes("<head>") ||
|
||||
data.includes("<body>");
|
||||
|
||||
if (response.ok && !looksLikeHtml) {
|
||||
try {
|
||||
const healthData = JSON.parse(data);
|
||||
if (
|
||||
@@ -2888,64 +2965,27 @@ ipcMain.handle("test-server-connection", async (event, serverUrl) => {
|
||||
console.log("Health endpoint did not return valid JSON");
|
||||
}
|
||||
}
|
||||
|
||||
// Reachable, but not a recognized Termix health response -- likely a
|
||||
// proxy/SSO login page in front of the real server. Let the user
|
||||
// proceed; the login step next will fail clearly if this really
|
||||
// isn't a Termix server.
|
||||
return {
|
||||
success: true,
|
||||
status: response.status,
|
||||
testedUrl: healthUrl,
|
||||
warning: looksLikeHtml
|
||||
? "Could not confirm this is a Termix server (the response looked like an HTML page, which can happen behind a login-protected reverse proxy). You can continue, and the next step will fail clearly if this isn't actually a Termix server."
|
||||
: "Server responded, but not with the expected health check format. Continuing anyway.",
|
||||
};
|
||||
} catch (urlError) {
|
||||
console.error("Health check failed:", urlError);
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Server is not responding. Please ensure the server is running and accessible.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const versionUrl = `${normalizedServerUrl}/version`;
|
||||
const response = await httpFetch(versionUrl, {
|
||||
method: "GET",
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.text();
|
||||
|
||||
if (
|
||||
data.includes("<html") ||
|
||||
data.includes("<!DOCTYPE") ||
|
||||
data.includes("<head>") ||
|
||||
data.includes("<body>")
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Server returned HTML instead of JSON. This does not appear to be a Termix server.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const versionData = JSON.parse(data);
|
||||
if (
|
||||
versionData &&
|
||||
(versionData.status === "up_to_date" ||
|
||||
versionData.status === "requires_update" ||
|
||||
(versionData.localVersion &&
|
||||
versionData.version &&
|
||||
versionData.latest_release))
|
||||
) {
|
||||
return {
|
||||
success: true,
|
||||
status: response.status,
|
||||
testedUrl: versionUrl,
|
||||
warning:
|
||||
"Health endpoint not available, but server appears to be running",
|
||||
};
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.log("Version endpoint did not return valid JSON");
|
||||
}
|
||||
}
|
||||
} catch (versionError) {
|
||||
console.error("Version check failed:", versionError);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Server is not responding or does not appear to be a valid Termix server. Please ensure the server is running and accessible.",
|
||||
};
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
const SYNCED_ENTITY_TYPES = Object.freeze([
|
||||
// Ordered by reference dependency: hosts and snippets resolve credential,
|
||||
// vault and folder syncIds, so those have to exist on the other side first.
|
||||
"sshCredentials",
|
||||
"vaultProfiles",
|
||||
"sshFolders",
|
||||
"snippetFolders",
|
||||
"hosts",
|
||||
"snippets",
|
||||
"dashboardServiceLinks",
|
||||
"homepageItems",
|
||||
"userPreferences",
|
||||
]);
|
||||
|
||||
module.exports = { SYNCED_ENTITY_TYPES };
|
||||
+130
-30
@@ -14,17 +14,7 @@
|
||||
const { app, safeStorage } = require("electron");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const SYNCED_ENTITY_TYPES = [
|
||||
"hosts",
|
||||
"sshCredentials",
|
||||
"sshFolders",
|
||||
"snippets",
|
||||
"snippetFolders",
|
||||
"vaultProfiles",
|
||||
"dashboardServiceLinks",
|
||||
"homepageItems",
|
||||
];
|
||||
const { SYNCED_ENTITY_TYPES } = require("./remote-sync-entities.cjs");
|
||||
|
||||
const SYNC_INTERVAL_MS = 90 * 1000;
|
||||
const EMBEDDED_BASE_URL = "http://127.0.0.1:30001";
|
||||
@@ -69,6 +59,7 @@ function getRemoteSyncStatePath() {
|
||||
function getDesktopSettings() {
|
||||
return readJson(getDesktopSettingsPath(), {
|
||||
defaultConnectionOrigin: "local",
|
||||
migrationNoticeAcknowledged: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -134,6 +125,41 @@ function clearRemoteSyncJwt() {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async function getRemoteSyncUserInfo() {
|
||||
const config = getRemoteSyncConfig();
|
||||
const token = getRemoteSyncJwt();
|
||||
if (!config?.serverUrl || !token || isJwtExpiredOrExpiringSoon(token)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const baseUrl = config.serverUrl.replace(/\/$/, "");
|
||||
const userResponse = await fetch(`${baseUrl}/users/me`, {
|
||||
headers: { Authorization: `Bearer ${token}`, "X-Electron-App": "true" },
|
||||
});
|
||||
if (!userResponse.ok) return null;
|
||||
|
||||
const user = await userResponse.json();
|
||||
const rolesResponse = await fetch(
|
||||
`${baseUrl}/rbac/users/${encodeURIComponent(user.userId)}/roles`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}`, "X-Electron-App": "true" },
|
||||
},
|
||||
);
|
||||
const roles = rolesResponse.ok
|
||||
? (await rolesResponse.json()).roles || []
|
||||
: [];
|
||||
|
||||
return {
|
||||
userId: user.userId,
|
||||
username: user.username,
|
||||
is_admin: !!user.is_admin,
|
||||
is_oidc: !!user.is_oidc,
|
||||
is_dual_auth: !!user.is_dual_auth,
|
||||
totp_enabled: !!user.totp_enabled,
|
||||
roles,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeJwtExpiry(token) {
|
||||
try {
|
||||
const payloadB64 = token.split(".")[1];
|
||||
@@ -229,8 +255,18 @@ class RemoteSyncEngine {
|
||||
return this.status;
|
||||
}
|
||||
if (!this.localJwt) {
|
||||
// Local login hasn't handed us a token yet (e.g. very early after
|
||||
// boot) -- skip this tick rather than fail loudly.
|
||||
// Local login hasn't handed us a token yet -- this is expected for the
|
||||
// first tick or two right after a cold boot (renderer hasn't finished
|
||||
// its own session check yet), but if it never arrives (e.g. a gap in
|
||||
// whichever code path establishes the local session), sync would
|
||||
// otherwise silently no-op forever with no visible error. Surface it
|
||||
// as a normal, non-alarming "not synced yet" status rather than
|
||||
// leaving lastSyncedAt/lastError untouched.
|
||||
this.updateStatus({
|
||||
connected: true,
|
||||
syncing: false,
|
||||
lastError: "Waiting for local session",
|
||||
});
|
||||
return this.status;
|
||||
}
|
||||
|
||||
@@ -321,7 +357,39 @@ class RemoteSyncEngine {
|
||||
if (!res.ok) {
|
||||
throw new Error(`Request failed (${res.status}): ${url}`);
|
||||
}
|
||||
return res.json();
|
||||
|
||||
const text = await res.text();
|
||||
// A reverse-proxy SSO in front of the remote server (Pangolin, Authelia,
|
||||
// etc.) can intercept even an authenticated, Bearer-token'd request and
|
||||
// serve its own login page instead of forwarding to Termix -- that comes
|
||||
// back as a normal 200 OK, so the status checks above don't catch it.
|
||||
// This is NOT the same as needsReauth/a bad Termix JWT: sync runs as a
|
||||
// plain server-to-server fetch() in this main process, with no browser
|
||||
// cookie jar at all, so re-authenticating through the login iframe (which
|
||||
// only affects the renderer's browser session) can never fix this --
|
||||
// reconnecting would tell the user to do something that doesn't help.
|
||||
// The proxy has to allow this traffic through some other way (an API
|
||||
// bypass rule, a separate hostname/port that isn't proxy-gated, etc.),
|
||||
// so this gets its own distinct, honest error rather than piggybacking
|
||||
// on needsReauth or a raw JSON.parse crash.
|
||||
const looksLikeHtml =
|
||||
text.includes("<html") ||
|
||||
text.includes("<!DOCTYPE") ||
|
||||
text.includes("<head>") ||
|
||||
text.includes("<body>");
|
||||
if (looksLikeHtml) {
|
||||
const err = new Error(
|
||||
"The reverse proxy in front of this server is blocking sync traffic with its own login page. Reconnecting won't fix this -- the proxy needs to let Termix's API requests through (e.g. an SSO bypass rule for the sync API, or a non-proxied hostname/port for it).",
|
||||
);
|
||||
err.proxyBlocked = true;
|
||||
throw err;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error(`Server returned invalid JSON: ${url}`);
|
||||
}
|
||||
}
|
||||
|
||||
async pullSide(baseUrl, token, entityType, since) {
|
||||
@@ -330,6 +398,15 @@ class RemoteSyncEngine {
|
||||
return data.rows || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Every syncId a side currently holds, ignoring the incremental window.
|
||||
* Used only to decide whether a deletion still has something to delete.
|
||||
*/
|
||||
async pullSyncIds(baseUrl, token, entityType) {
|
||||
const rows = await this.pullSide(baseUrl, token, entityType, null);
|
||||
return new Set(rows.filter((row) => row.syncId).map((row) => row.syncId));
|
||||
}
|
||||
|
||||
async pullTombstones(baseUrl, token, entityType, since) {
|
||||
const url = `${baseUrl}/sync/${entityType}/tombstones${since ? `?since=${encodeURIComponent(since)}` : ""}`;
|
||||
const data = await this.fetchJson(url, token);
|
||||
@@ -414,24 +491,46 @@ class RemoteSyncEngine {
|
||||
}
|
||||
|
||||
// Apply tombstones to whichever side hasn't already deleted the row.
|
||||
for (const tombstone of localTombstones) {
|
||||
if (remoteBySyncId.has(tombstone.syncId)) {
|
||||
await this.pushTombstone(
|
||||
remoteBaseUrl,
|
||||
remoteJwt,
|
||||
entityType,
|
||||
tombstone.syncId,
|
||||
);
|
||||
//
|
||||
// The presence check cannot use localRows/remoteRows: those are the
|
||||
// incremental window, and a row deleted on one side while untouched on
|
||||
// the other is by definition outside it, so every deletion was dropped.
|
||||
// It also cannot be skipped -- pushing unconditionally makes the
|
||||
// receiving side record a fresh tombstone, which the next pass would push
|
||||
// back, forever. So ask the receiving side what it actually still holds,
|
||||
// and only when there is a deletion to apply.
|
||||
if (localTombstones.length) {
|
||||
const remoteSyncIds = await this.pullSyncIds(
|
||||
remoteBaseUrl,
|
||||
remoteJwt,
|
||||
entityType,
|
||||
);
|
||||
for (const tombstone of localTombstones) {
|
||||
if (remoteSyncIds.has(tombstone.syncId)) {
|
||||
await this.pushTombstone(
|
||||
remoteBaseUrl,
|
||||
remoteJwt,
|
||||
entityType,
|
||||
tombstone.syncId,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const tombstone of remoteTombstones) {
|
||||
if (localBySyncId.has(tombstone.syncId)) {
|
||||
await this.pushTombstone(
|
||||
EMBEDDED_BASE_URL,
|
||||
this.localJwt,
|
||||
entityType,
|
||||
tombstone.syncId,
|
||||
);
|
||||
if (remoteTombstones.length) {
|
||||
const localSyncIds = await this.pullSyncIds(
|
||||
EMBEDDED_BASE_URL,
|
||||
this.localJwt,
|
||||
entityType,
|
||||
);
|
||||
for (const tombstone of remoteTombstones) {
|
||||
if (localSyncIds.has(tombstone.syncId)) {
|
||||
await this.pushTombstone(
|
||||
EMBEDDED_BASE_URL,
|
||||
this.localJwt,
|
||||
entityType,
|
||||
tombstone.syncId,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,6 +567,7 @@ module.exports = {
|
||||
saveRemoteSyncJwt,
|
||||
getRemoteSyncJwt,
|
||||
clearRemoteSyncJwt,
|
||||
getRemoteSyncUserInfo,
|
||||
isJwtExpiredOrExpiringSoon,
|
||||
decodeJwtExpiry,
|
||||
};
|
||||
|
||||
@@ -46,4 +46,57 @@ export default tseslint.config([
|
||||
"react-refresh/only-export-components": "warn",
|
||||
},
|
||||
},
|
||||
{
|
||||
// MySQL has no RETURNING clause, and drizzle's mysql-core does not expose
|
||||
// the method at all — a bare .returning() is a TypeError there, not a bad
|
||||
// query, and it only fails on the engine no test in this repo runs against.
|
||||
//
|
||||
// 175 call sites were migrated off it. This is what stops number 176.
|
||||
// Writes that need rows back go through repositories/returning.ts, which
|
||||
// picks one statement or a read-then-write transaction per dialect.
|
||||
files: ["src/backend/database/repositories/**/*.ts"],
|
||||
ignores: [
|
||||
// The two files whose job is to absorb these differences.
|
||||
"src/backend/database/repositories/returning.ts",
|
||||
"src/backend/database/repositories/mutation-result.ts",
|
||||
],
|
||||
rules: {
|
||||
"no-restricted-syntax": [
|
||||
"error",
|
||||
{
|
||||
selector: "CallExpression[callee.property.name='returning']",
|
||||
message:
|
||||
"MySQL has no RETURNING. Use insertReturning/updateReturning/deleteReturning from ./returning.js, or rowsAffected() if you only need a count. Inside a proven sqlite-only branch, disable this rule with a comment saying so.",
|
||||
},
|
||||
{
|
||||
// `||` concatenates on SQLite and Postgres. On MySQL it is logical OR
|
||||
// unless the server runs with PIPES_AS_CONCAT, so a folder path built
|
||||
// this way silently became 0. Use CONCAT, which all three agree on.
|
||||
selector:
|
||||
"TaggedTemplateExpression[tag.name='sql'] TemplateElement[value.raw=/\\|\\|/]",
|
||||
message:
|
||||
"`||` is logical OR on MySQL, not concatenation. Use CONCAT(...).",
|
||||
},
|
||||
{
|
||||
// Postgres and SQLite spell it ON CONFLICT; MySQL spells it ON
|
||||
// DUPLICATE KEY and names no columns, so drizzle's mysql-core has no
|
||||
// onConflictDoUpdate at all — another TypeError, not a bad query.
|
||||
selector: "CallExpression[callee.property.name='onConflictDoUpdate']",
|
||||
message:
|
||||
"MySQL has no ON CONFLICT. Use upsert() from ./returning.js.",
|
||||
},
|
||||
{
|
||||
// better-sqlite3 puts these on a write result; node-postgres and
|
||||
// mysql2 do not, so reading them directly yields undefined — and
|
||||
// Number(undefined) is NaN, which reaches the database as the string
|
||||
// "NaN" and fails an integer column. Three call sites did exactly
|
||||
// this and only broke on Postgres.
|
||||
selector:
|
||||
"MemberExpression[property.name=/^(lastInsertRowid|changes)$/]",
|
||||
message:
|
||||
"lastInsertRowid and changes are better-sqlite3 only. Use insertedId() or rowsAffected() from ./mutation-result.js.",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
Generated
+2656
-1691
File diff suppressed because it is too large
Load Diff
+62
-53
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "termix",
|
||||
"private": true,
|
||||
"version": "2.6.0",
|
||||
"version": "2.6.1",
|
||||
"description": "Self-hosted SSH and remote desktop management.",
|
||||
"author": "Karmaa",
|
||||
"main": "electron/main.cjs",
|
||||
@@ -16,10 +16,11 @@
|
||||
"biome:fix": "biome check --write biome.json package.json",
|
||||
"postinstall": "node scripts/patch-app-builder-lib.cjs && node scripts/patch-guacamole-lite.cjs && node scripts/patch-guacamole-common-js.cjs && node scripts/patch-better-sqlite3.cjs && node scripts/patch-nan.cjs && node scripts/patch-xterm-android-ime.cjs",
|
||||
"prebuild": "node scripts/write-electron-build-info.cjs",
|
||||
"lint": "eslint .",
|
||||
"lint": "node scripts/generate-dialect-schema.cjs --check && eslint .",
|
||||
"lint:fix": "eslint --fix .",
|
||||
"type-check": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"verify:dialect": "tsx scripts/verify-dialects.mjs",
|
||||
"test:watch": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
@@ -40,77 +41,82 @@
|
||||
"build:linux-appimage": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --linux AppImage",
|
||||
"build:linux-targz": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --linux tar.gz",
|
||||
"build:mac": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --mac --universal",
|
||||
"build:mac-dev": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --mac dir --publish=never"
|
||||
"build:mac-dev": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --mac dir --publish=never",
|
||||
"schema:generate": "node scripts/generate-dialect-schema.cjs",
|
||||
"schema:check": "node scripts/generate-dialect-schema.cjs --check",
|
||||
"schema:migrations": "drizzle-kit generate --config=drizzle.config.sqlite.ts && drizzle-kit generate --config=drizzle.config.pg.ts && drizzle-kit generate --config=drizzle.config.mysql.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@simplewebauthn/browser": "^13.3.0",
|
||||
"@simplewebauthn/server": "^13.3.2",
|
||||
"@tanstack/react-virtual": "^3.14.6",
|
||||
"@tanstack/react-virtual": "^3.14.9",
|
||||
"@types/ldapjs": "^3.0.6",
|
||||
"axios": "^1.18.1",
|
||||
"axios": "^1.19.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"better-sqlite3": "^13.0.2",
|
||||
"body-parser": "^2.3.0",
|
||||
"chalk": "^5.6.2",
|
||||
"chalk": "^6.0.0",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.6",
|
||||
"dotenv": "^17.4.2",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"express": "^5.2.1",
|
||||
"guacamole-lite": "^1.2.0",
|
||||
"jose": "^6.2.2",
|
||||
"js-yaml": "^5.2.1",
|
||||
"jose": "^6.2.5",
|
||||
"js-yaml": "^5.2.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"jszip": "^3.10.1",
|
||||
"ldapjs": "^3.0.7",
|
||||
"motion": "^12.42.2",
|
||||
"motion": "^12.43.0",
|
||||
"multer": "^2.2.0",
|
||||
"mysql2": "^3.23.2",
|
||||
"nanoid": "^6.0.0",
|
||||
"pg": "^8.22.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"serialport": "^13.0.0",
|
||||
"socks": "^2.8.7",
|
||||
"speakeasy": "^2.0.0",
|
||||
"ssh2": "^1.17.0",
|
||||
"undici": "^8.7.0",
|
||||
"undici": "^8.9.0",
|
||||
"ws": "^8.21.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.5.4",
|
||||
"@biomejs/biome": "2.5.6",
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.10.4",
|
||||
"@codemirror/search": "^6.7.1",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.6",
|
||||
"@commitlint/cli": "^21.0.2",
|
||||
"@commitlint/config-conventional": "^21.0.2",
|
||||
"@codemirror/view": "^6.43.7",
|
||||
"@commitlint/cli": "^21.2.1",
|
||||
"@commitlint/config-conventional": "^21.2.0",
|
||||
"@deadendjs/swagger-jsdoc": "^8.1.2",
|
||||
"@electron/notarize": "^3.1.1",
|
||||
"@electron/rebuild": "^4.0.4",
|
||||
"@electron/rebuild": "^4.2.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/fira-code": "^5.2.7",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/source-code-pro": "^5.2.7",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@fontsource/fira-code": "^5.3.0",
|
||||
"@fontsource/jetbrains-mono": "^5.3.0",
|
||||
"@fontsource/source-code-pro": "^5.3.0",
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@radix-ui/react-accordion": "^1.2.17",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.20",
|
||||
"@radix-ui/react-checkbox": "^1.3.8",
|
||||
"@radix-ui/react-dialog": "^1.1.20",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.21",
|
||||
"@radix-ui/react-label": "^2.1.12",
|
||||
"@radix-ui/react-popover": "^1.1.20",
|
||||
"@radix-ui/react-progress": "^1.1.13",
|
||||
"@radix-ui/react-scroll-area": "^1.2.15",
|
||||
"@radix-ui/react-select": "^2.3.4",
|
||||
"@radix-ui/react-separator": "^1.1.12",
|
||||
"@radix-ui/react-slider": "^1.4.4",
|
||||
"@radix-ui/react-slot": "^1.3.0",
|
||||
"@radix-ui/react-switch": "^1.3.4",
|
||||
"@radix-ui/react-tabs": "^1.1.18",
|
||||
"@radix-ui/react-tooltip": "^1.2.13",
|
||||
"@radix-ui/react-accordion": "^1.2.20",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.23",
|
||||
"@radix-ui/react-checkbox": "^1.3.11",
|
||||
"@radix-ui/react-dialog": "^1.1.23",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.24",
|
||||
"@radix-ui/react-label": "^2.1.15",
|
||||
"@radix-ui/react-popover": "^1.1.23",
|
||||
"@radix-ui/react-progress": "^1.1.16",
|
||||
"@radix-ui/react-scroll-area": "^1.2.18",
|
||||
"@radix-ui/react-select": "^2.3.7",
|
||||
"@radix-ui/react-separator": "^1.1.15",
|
||||
"@radix-ui/react-slider": "^1.4.7",
|
||||
"@radix-ui/react-slot": "^1.3.3",
|
||||
"@radix-ui/react-switch": "^1.3.7",
|
||||
"@radix-ui/react-tabs": "^1.1.21",
|
||||
"@radix-ui/react-tooltip": "^1.2.16",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/jest-dom": "^7.0.0",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
@@ -120,52 +126,55 @@
|
||||
"@types/guacamole-common-js": "^1.5.5",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/multer": "^2.1.0",
|
||||
"@types/node": "^26.0.0",
|
||||
"@types/multer": "^2.2.0",
|
||||
"@types/node": "^26.1.2",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@types/speakeasy": "^2.0.10",
|
||||
"@types/ssh2": "^1.15.5",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@uiw/codemirror-extensions-langs": "^4.25.11",
|
||||
"@uiw/codemirror-theme-github": "^4.25.11",
|
||||
"@uiw/react-codemirror": "^4.25.11",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"@vitest/coverage-v8": "^4.1.10",
|
||||
"@vitest/ui": "^4.1.10",
|
||||
"@xterm/addon-clipboard": "^0.2.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
"@xterm/addon-unicode11": "^0.9.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"concurrently": "^10.0.3",
|
||||
"concurrently": "^10.0.4",
|
||||
"cytoscape": "^3.34.0",
|
||||
"electron": "^43.0.0",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"electron": "^43.2.0",
|
||||
"electron-builder": "^26.15.3",
|
||||
"eslint": "^10.5.0",
|
||||
"eslint": "^10.8.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.3",
|
||||
"eslint-plugin-unused-imports": "^4.4.1",
|
||||
"globals": "^17.5.0",
|
||||
"globals": "^17.8.0",
|
||||
"guacamole-common-js": "^1.5.0",
|
||||
"husky": "^9.1.7",
|
||||
"i18next": "^26.3.6",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"jsdom": "^29.1.1",
|
||||
"lint-staged": "^17.0.8",
|
||||
"lucide-react": "^1.20.0",
|
||||
"prettier": "3.8.4",
|
||||
"radix-ui": "^1.6.3",
|
||||
"react": "^19.2.7",
|
||||
"lint-staged": "^17.2.0",
|
||||
"lucide-react": "^1.28.0",
|
||||
"prettier": "3.9.6",
|
||||
"radix-ui": "^1.6.7",
|
||||
"react": "^19.2.8",
|
||||
"react-cytoscapejs": "^2.0.0",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-h5-audio-player": "^3.10.2",
|
||||
"react-hook-form": "^7.79.0",
|
||||
"react-i18next": "^17.0.10",
|
||||
"react-i18next": "^17.0.11",
|
||||
"react-icons": "^5.6.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-pdf": "^10.4.1",
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Generates the Postgres and MySQL schema modules from the SQLite one.
|
||||
*
|
||||
* ## These files produce DDL. They are not used at runtime.
|
||||
*
|
||||
* drizzle-kit reads them to emit the migrations in drizzle/postgres and
|
||||
* drizzle/mysql. Nothing imports them to run a query.
|
||||
*
|
||||
* That is not an oversight. The query builder needs two things from a table
|
||||
* object — the identifiers to interpolate, and the encoders that turn JS values
|
||||
* into driver values — and the sqlite definitions supply both correctly for
|
||||
* every engine, which is why all 44 repositories import schema.ts directly:
|
||||
*
|
||||
* - text and integer encode as themselves everywhere
|
||||
* - integer({ mode: "boolean" }) writes 1/0, which Postgres and MySQL both
|
||||
* accept for a boolean column, and reads back through `Number(v) === 1`,
|
||||
* which is true for JS `true` as well as for 1
|
||||
* - real is a plain number on all three
|
||||
*
|
||||
* What genuinely differs between the dialects is DDL — column types, key
|
||||
* lengths, autoincrement syntax — and DDL is exactly what these files exist to
|
||||
* generate. See scripts/verify-dialects.mjs, which asserts the round-trips
|
||||
* above against real servers rather than trusting this comment.
|
||||
*
|
||||
* The schema is declared once, in sqlite-core, and the other two dialects are
|
||||
* derived. Hand-maintaining three copies of 52 tables would mean a renamed
|
||||
* table has to land in three places consistently or a foreign key silently
|
||||
* points at the wrong one — and the schema is regular enough that the mapping
|
||||
* is mechanical.
|
||||
*
|
||||
* What varies between dialects is small and closed:
|
||||
* - booleans are integers on sqlite, native elsewhere
|
||||
* - autoincrement keys are `integer primary key autoincrement`, `serial`,
|
||||
* and `int auto_increment`
|
||||
* - MySQL cannot index unbounded TEXT, so any column that is a primary key,
|
||||
* is unique, or participates in a foreign key must be varchar
|
||||
* - MySQL rejects a bare DEFAULT CURRENT_TIMESTAMP on a text column, so it is
|
||||
* written as a parenthesised expression default
|
||||
*
|
||||
* Usage: node scripts/generate-dialect-schema.cjs [--check]
|
||||
* --check verifies the committed files match what would be generated,
|
||||
* for CI to catch a schema edit that forgot to regenerate.
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const SOURCE = path.join(ROOT, "src/backend/database/db/schema.ts");
|
||||
const TARGETS = {
|
||||
postgres: path.join(ROOT, "src/backend/database/db/schema.pg.ts"),
|
||||
mysql: path.join(ROOT, "src/backend/database/db/schema.mysql.ts"),
|
||||
};
|
||||
|
||||
const KEY_LENGTH = 255;
|
||||
|
||||
/**
|
||||
* Columns that must be varchar rather than text on MySQL. A column qualifies if
|
||||
* it is a primary key, is unique, or is either end of a foreign key.
|
||||
*/
|
||||
function collectKeyColumns(source) {
|
||||
const keyed = new Set();
|
||||
|
||||
// `name: text("col")....primaryKey()` / `.unique()` / `.references(...)`
|
||||
const declaration =
|
||||
/(\w+):\s*text\("([a-z0-9_]+)"\)((?:\s*\.\w+\([^)]*\))*)/g;
|
||||
let match;
|
||||
while ((match = declaration.exec(source)) !== null) {
|
||||
const [, prop, column, modifiers] = match;
|
||||
if (/\.(primaryKey|unique|references)\(/.test(modifiers)) {
|
||||
keyed.add(column);
|
||||
}
|
||||
void prop;
|
||||
}
|
||||
|
||||
// Multi-line form: the modifiers land on following lines.
|
||||
const multiline =
|
||||
/(\w+):\s*text\("([a-z0-9_]+)"\)\s*\n(\s*\.\w+\([\s\S]*?\),)/g;
|
||||
while ((match = multiline.exec(source)) !== null) {
|
||||
if (/\.(primaryKey|unique|references)\(/.test(match[3])) {
|
||||
keyed.add(match[2]);
|
||||
}
|
||||
}
|
||||
|
||||
// A referenced column implies the referencing side too; both must match.
|
||||
const reference = /\.references\(\(\)\s*=>\s*\w+\.(\w+)/g;
|
||||
while ((match = reference.exec(source)) !== null) {
|
||||
keyed.add(camelToSnake(match[1]));
|
||||
}
|
||||
|
||||
// Table-level indexes: `(table) => [uniqueIndex("x").on(table.a, table.b)]`.
|
||||
// These were invisible here at first, and MySQL rejected the migration with
|
||||
// "BLOB/TEXT column used in key specification without a key length" — but
|
||||
// only on MySQL 8; MariaDB took it.
|
||||
const tableIndex = /uniqueIndex\("[a-z0-9_]+"\)\.on\(([^)]*)\)/g;
|
||||
while ((match = tableIndex.exec(source)) !== null) {
|
||||
for (const column of match[1].split(",")) {
|
||||
const name = column.trim().replace(/^\w+\./, "");
|
||||
if (name) keyed.add(camelToSnake(name));
|
||||
}
|
||||
}
|
||||
|
||||
return keyed;
|
||||
}
|
||||
|
||||
function camelToSnake(value) {
|
||||
return value.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
||||
}
|
||||
|
||||
function transform(source, dialect) {
|
||||
const keyed = collectKeyColumns(source);
|
||||
const isPg = dialect === "postgres";
|
||||
let out = source;
|
||||
|
||||
// Autoincrement primary keys, before the plain integer rule below.
|
||||
out = out.replace(
|
||||
/integer\("([a-z0-9_]+)"\)\.primaryKey\(\{\s*autoIncrement:\s*true\s*\}\)/g,
|
||||
(_, col) =>
|
||||
isPg
|
||||
? `serial("${col}").primaryKey()`
|
||||
: `int("${col}").autoincrement().primaryKey()`,
|
||||
);
|
||||
|
||||
// Integer-backed booleans become native ones. Prettier wraps the longer
|
||||
// declarations across lines, so this has to span newlines too.
|
||||
out = out.replace(
|
||||
/integer\(\s*"([a-z0-9_]+)",\s*\{\s*mode:\s*"boolean",?\s*\},?\s*\)/g,
|
||||
(_, col) => `boolean("${col}")`,
|
||||
);
|
||||
|
||||
// Remaining integers.
|
||||
if (!isPg) {
|
||||
out = out.replace(
|
||||
/\binteger\("([a-z0-9_]+)"\)/g,
|
||||
(_, col) => `int("${col}")`,
|
||||
);
|
||||
|
||||
// Timestamps are stored as text (see sql-timestamp.ts). MySQL only accepts
|
||||
// DEFAULT CURRENT_TIMESTAMP on a DATETIME or TIMESTAMP column — on a TEXT
|
||||
// one it is ER_INVALID_DEFAULT, "Invalid default value". Since 8.0.13 an
|
||||
// expression default works on any type, and an expression is written
|
||||
// parenthesised. MariaDB accepts the bare form, which is why this only
|
||||
// surfaces against real MySQL.
|
||||
out = out.replace(/sql`CURRENT_TIMESTAMP`/g, "sql`(CURRENT_TIMESTAMP)`");
|
||||
}
|
||||
|
||||
// Floating point.
|
||||
out = out.replace(/\breal\("([a-z0-9_]+)"\)/g, (_, col) =>
|
||||
isPg ? `doublePrecision("${col}")` : `double("${col}")`,
|
||||
);
|
||||
|
||||
// Key-bearing strings must be indexable.
|
||||
out = out.replace(/\btext\("([a-z0-9_]+)"\)/g, (whole, col) =>
|
||||
keyed.has(col) ? `varchar("${col}", { length: ${KEY_LENGTH} })` : whole,
|
||||
);
|
||||
|
||||
// text("x", { length: n }) is sqlite-only sugar; drop the length.
|
||||
out = out.replace(
|
||||
/\btext\("([a-z0-9_]+)",\s*\{\s*length:\s*\d+\s*\}\)/g,
|
||||
(_, col) => `text("${col}")`,
|
||||
);
|
||||
|
||||
out = out.replace(/\bsqliteTable\(/g, isPg ? "pgTable(" : "mysqlTable(");
|
||||
|
||||
const imports = isPg
|
||||
? `import {\n pgTable,\n text,\n varchar,\n integer,\n serial,\n boolean,\n doublePrecision,\n uniqueIndex,\n} from "drizzle-orm/pg-core";`
|
||||
: `import {\n mysqlTable,\n text,\n varchar,\n int,\n boolean,\n double,\n uniqueIndex,\n} from "drizzle-orm/mysql-core";`;
|
||||
|
||||
out = out.replace(
|
||||
/import\s*\{[^}]*\}\s*from\s*"drizzle-orm\/sqlite-core";/,
|
||||
imports,
|
||||
);
|
||||
|
||||
return `${header(dialect)}\n${out}`;
|
||||
}
|
||||
|
||||
function header(dialect) {
|
||||
return `// GENERATED FILE — do not edit.
|
||||
//
|
||||
// Produced from schema.ts by scripts/generate-dialect-schema.cjs.
|
||||
// Edit the sqlite schema and re-run \`node scripts/generate-dialect-schema.cjs\`.
|
||||
// Target dialect: ${dialect}.
|
||||
//
|
||||
// DDL source for drizzle-kit. NOT imported to run queries — repositories use
|
||||
// schema.ts on every dialect. See the generator header for why that is correct.
|
||||
`;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const check = process.argv.includes("--check");
|
||||
const source = fs.readFileSync(SOURCE, "utf8");
|
||||
let drift = false;
|
||||
|
||||
for (const [dialect, target] of Object.entries(TARGETS)) {
|
||||
const generated = transform(source, dialect);
|
||||
|
||||
if (check) {
|
||||
const current = fs.existsSync(target)
|
||||
? fs.readFileSync(target, "utf8")
|
||||
: "";
|
||||
if (current !== generated) {
|
||||
console.error(
|
||||
`[generate-dialect-schema] ${path.relative(ROOT, target)} is out of date`,
|
||||
);
|
||||
drift = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
fs.writeFileSync(target, generated);
|
||||
console.log(
|
||||
`[generate-dialect-schema] wrote ${path.relative(ROOT, target)}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (drift) {
|
||||
console.error(
|
||||
"[generate-dialect-schema] run `node scripts/generate-dialect-schema.cjs` and commit the result",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { transform, collectKeyColumns };
|
||||
|
||||
if (require.main === module) {
|
||||
main();
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { transform, collectKeyColumns } =
|
||||
require("./generate-dialect-schema.cjs") as {
|
||||
transform: (source: string, dialect: "postgres" | "mysql") => string;
|
||||
collectKeyColumns: (source: string) => Set<string>;
|
||||
};
|
||||
|
||||
const SOURCE = `import { sqliteTable, text, integer, real } from "drizzle-orm/sqlite-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
export const users = sqliteTable("users", {
|
||||
id: text("id").primaryKey(),
|
||||
username: text("username").notNull(),
|
||||
isAdmin: integer("is_admin", { mode: "boolean" }).notNull().default(false),
|
||||
wrapped: integer("wrapped", {
|
||||
mode: "boolean",
|
||||
})
|
||||
.notNull()
|
||||
.default(true),
|
||||
score: real("score"),
|
||||
ssoProviderId: integer("sso_provider_id"),
|
||||
});
|
||||
|
||||
export const folders = sqliteTable("folders", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
syncId: text("sync_id").unique(),
|
||||
cert: text("cert", { length: 8192 }),
|
||||
});
|
||||
`;
|
||||
|
||||
describe("collectKeyColumns", () => {
|
||||
it("finds columns that must be indexable", () => {
|
||||
const keyed = collectKeyColumns(SOURCE);
|
||||
|
||||
// primary key, unique, and both ends of the foreign key
|
||||
expect(keyed.has("id")).toBe(true);
|
||||
expect(keyed.has("sync_id")).toBe(true);
|
||||
expect(keyed.has("user_id")).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves ordinary strings alone", () => {
|
||||
const keyed = collectKeyColumns(SOURCE);
|
||||
|
||||
expect(keyed.has("username")).toBe(false);
|
||||
expect(keyed.has("name")).toBe(false);
|
||||
expect(keyed.has("cert")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("postgres output", () => {
|
||||
const out = transform(SOURCE, "postgres");
|
||||
|
||||
it("is marked generated", () => {
|
||||
expect(out.startsWith("// GENERATED FILE")).toBe(true);
|
||||
});
|
||||
|
||||
it("uses pg-core", () => {
|
||||
expect(out).toContain('from "drizzle-orm/pg-core"');
|
||||
expect(out).not.toContain("sqlite-core");
|
||||
expect(out).toContain("pgTable(");
|
||||
expect(out).not.toContain("sqliteTable(");
|
||||
});
|
||||
|
||||
it("maps autoincrement keys to serial", () => {
|
||||
expect(out).toContain('serial("id").primaryKey()');
|
||||
expect(out).not.toContain("autoIncrement");
|
||||
});
|
||||
|
||||
it("maps integer-backed booleans, including the wrapped form", () => {
|
||||
expect(out).toContain('boolean("is_admin")');
|
||||
// Prettier splits longer declarations across lines; both must convert.
|
||||
expect(out).toContain('boolean("wrapped")');
|
||||
expect(out).not.toMatch(/mode:\s*"boolean"/);
|
||||
});
|
||||
|
||||
it("keeps plain integers and maps real", () => {
|
||||
expect(out).toContain('integer("sso_provider_id")');
|
||||
expect(out).toContain('doublePrecision("score")');
|
||||
});
|
||||
|
||||
it("makes key columns varchar and leaves the rest text", () => {
|
||||
expect(out).toContain('varchar("id", { length: 255 })');
|
||||
expect(out).toContain('varchar("user_id", { length: 255 })');
|
||||
expect(out).toContain('varchar("sync_id", { length: 255 })');
|
||||
expect(out).toContain('text("username")');
|
||||
expect(out).toContain('text("name")');
|
||||
});
|
||||
|
||||
it("drops the sqlite-only text length", () => {
|
||||
expect(out).toContain('text("cert")');
|
||||
expect(out).not.toContain("length: 8192");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mysql output", () => {
|
||||
const out = transform(SOURCE, "mysql");
|
||||
|
||||
it("uses mysql-core", () => {
|
||||
expect(out).toContain('from "drizzle-orm/mysql-core"');
|
||||
expect(out).toContain("mysqlTable(");
|
||||
});
|
||||
|
||||
it("maps autoincrement keys to int auto_increment", () => {
|
||||
expect(out).toContain('int("id").autoincrement().primaryKey()');
|
||||
});
|
||||
|
||||
it("renames integer to int", () => {
|
||||
expect(out).toContain('int("sso_provider_id")');
|
||||
expect(out).not.toMatch(/\binteger\(/);
|
||||
});
|
||||
|
||||
it("maps real to double", () => {
|
||||
expect(out).toContain('double("score")');
|
||||
});
|
||||
|
||||
it("makes key columns varchar — MySQL cannot index unbounded TEXT", () => {
|
||||
expect(out).toContain('varchar("user_id", { length: 255 })');
|
||||
expect(out).toContain('text("name")');
|
||||
});
|
||||
});
|
||||
|
||||
describe("determinism", () => {
|
||||
it("produces identical output for identical input", () => {
|
||||
expect(transform(SOURCE, "postgres")).toBe(transform(SOURCE, "postgres"));
|
||||
expect(transform(SOURCE, "mysql")).toBe(transform(SOURCE, "mysql"));
|
||||
});
|
||||
|
||||
it("keeps foreign key behaviour verbatim", () => {
|
||||
for (const dialect of ["postgres", "mysql"] as const) {
|
||||
expect(transform(SOURCE, dialect)).toContain('onDelete: "cascade"');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,20 @@ if (
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Every patch below is required for correctness: protocol negotiation, the
|
||||
// guacd 1.6.0 name handshake, dynamic argument answering, UTF-8 tokens and
|
||||
// read-only joins. If an upstream release moves an anchor string, silently
|
||||
// skipping would ship a Termix that looks fine and then drops VNC/RDP sessions
|
||||
// at runtime, so a missing anchor has to stop the install instead.
|
||||
function missingAnchor(patch) {
|
||||
console.error(
|
||||
`[patch-guacamole-lite] ${patch} anchor not found in guacamole-lite. ` +
|
||||
"The upstream file has changed and this patch no longer applies — " +
|
||||
"update scripts/patch-guacamole-lite.cjs to match the new source.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let guacdClientContent = fs.readFileSync(guacdClientPath, "utf8");
|
||||
let cryptContent = fs.readFileSync(cryptPath, "utf8");
|
||||
let clientConnectionContent = fs.readFileSync(clientConnectionPath, "utf8");
|
||||
@@ -157,18 +171,14 @@ if (!guacdClientContent.includes("} else if (/^1_\\d+_0$/.test(version)) {")) {
|
||||
newVersionBlock,
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] Version check target not found, skipping",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("Version check");
|
||||
}
|
||||
patched = true;
|
||||
}
|
||||
|
||||
if (!guacdClientContent.includes(newTimezone)) {
|
||||
if (!guacdClientContent.includes(oldTimezone)) {
|
||||
console.log("[patch-guacamole-lite] Timezone target not found, skipping");
|
||||
process.exit(0);
|
||||
missingAnchor("Timezone");
|
||||
}
|
||||
guacdClientContent = guacdClientContent.replace(oldTimezone, newTimezone);
|
||||
patched = true;
|
||||
@@ -180,20 +190,14 @@ if (!guacdClientContent.includes(newConnect)) {
|
||||
} else if (guacdClientContent.includes(oldConnect)) {
|
||||
guacdClientContent = guacdClientContent.replace(oldConnect, newConnect);
|
||||
} else {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] Connect target not found, skipping name patch",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("Connect");
|
||||
}
|
||||
patched = true;
|
||||
}
|
||||
|
||||
if (!guacdClientContent.includes("this.nextArgumentStreamIndex = 0;")) {
|
||||
if (!guacdClientContent.includes(oldSendBuffer)) {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] Argument stream index target not found, skipping",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("Argument stream index");
|
||||
}
|
||||
guacdClientContent = guacdClientContent.replace(oldSendBuffer, newSendBuffer);
|
||||
patched = true;
|
||||
@@ -201,10 +205,7 @@ if (!guacdClientContent.includes("this.nextArgumentStreamIndex = 0;")) {
|
||||
|
||||
if (!guacdClientContent.includes("sendRequiredArguments(params) {")) {
|
||||
if (!guacdClientContent.includes(oldSendInstructionBlock)) {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] Required argument helper target not found, skipping",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("Required argument helper");
|
||||
}
|
||||
guacdClientContent = guacdClientContent.replace(
|
||||
oldSendInstructionBlock,
|
||||
@@ -217,10 +218,7 @@ if (
|
||||
!guacdClientContent.includes("opcode === 'required' || opcode === 'require'")
|
||||
) {
|
||||
if (!guacdClientContent.includes(oldReadyHandler)) {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] Required opcode target not found, skipping",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("Required opcode");
|
||||
}
|
||||
guacdClientContent = guacdClientContent.replace(
|
||||
oldReadyHandler,
|
||||
@@ -273,10 +271,7 @@ if (!cryptContent.includes(newDecryptBlock)) {
|
||||
newDecryptBlock,
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] UTF-8 token decrypt target not found, skipping",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("UTF-8 token decrypt");
|
||||
}
|
||||
patched = true;
|
||||
}
|
||||
@@ -329,10 +324,7 @@ const newSendMessageToGuacd =
|
||||
|
||||
if (!clientConnectionContent.includes("isReadOnlyJoin()")) {
|
||||
if (!clientConnectionContent.includes(oldSendMessageToGuacd)) {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] sendMessageToGuacd target not found, skipping read-only patch",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("sendMessageToGuacd");
|
||||
}
|
||||
clientConnectionContent = clientConnectionContent.replace(
|
||||
oldSendMessageToGuacd,
|
||||
@@ -357,10 +349,7 @@ const newPreserveJoin =
|
||||
|
||||
if (!clientConnectionContent.includes("compiledSettings.readOnly")) {
|
||||
if (!clientConnectionContent.includes(oldPreserveJoin)) {
|
||||
console.log(
|
||||
"[patch-guacamole-lite] join-preserve target not found, skipping readOnly propagation patch",
|
||||
);
|
||||
process.exit(0);
|
||||
missingAnchor("join-preserve");
|
||||
}
|
||||
clientConnectionContent = clientConnectionContent.replace(
|
||||
oldPreserveJoin,
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Runs the repository layer against a real Postgres or MySQL server.
|
||||
*
|
||||
* The unit tests only ever see SQLite, so the parts of this codebase that
|
||||
* differ per engine — the RETURNING replacements, the read-then-write
|
||||
* transactions, the value encoders — have no coverage there at all. This is
|
||||
* what covers them, and it needs a live server, which is why it is a script
|
||||
* rather than a test.
|
||||
*
|
||||
* Usage:
|
||||
* npm run verify:dialect -- postgres://user:pass@host:5432/db
|
||||
* npm run verify:dialect -- mysql://user:pass@host:3306/db
|
||||
*
|
||||
* Applies the migrations first, through the same runRemoteMigrations() the
|
||||
* application uses at startup — so a broken migration fails here rather than in
|
||||
* production. Writes real rows: point it at a scratch database.
|
||||
*/
|
||||
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
const url = process.argv[2];
|
||||
if (!url) {
|
||||
console.error("usage: node scripts/verify-dialects.mjs <DATABASE_URL>");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const scheme = url.split("://", 1)[0].toLowerCase();
|
||||
const dialect = scheme.startsWith("postgres")
|
||||
? "postgres"
|
||||
: scheme === "mysql" || scheme === "mariadb"
|
||||
? "mysql"
|
||||
: null;
|
||||
|
||||
if (!dialect) {
|
||||
console.error(`unsupported URL scheme "${scheme}://"`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const { drizzle } = await import(
|
||||
dialect === "postgres" ? "drizzle-orm/node-postgres" : "drizzle-orm/mysql2"
|
||||
);
|
||||
|
||||
// No schema option on purpose — see connect.ts.
|
||||
const db = drizzle(url);
|
||||
const context = { dialect, drizzle: db };
|
||||
|
||||
const { runRemoteMigrations } =
|
||||
await import("../src/backend/database/db/migrate.js");
|
||||
await runRemoteMigrations(dialect, db);
|
||||
|
||||
const { UserRepository } =
|
||||
await import("../src/backend/database/repositories/user-repository.js");
|
||||
const { HostRepository } =
|
||||
await import("../src/backend/database/repositories/host-repository.js");
|
||||
const { SettingsRepository } =
|
||||
await import("../src/backend/database/repositories/settings-repository.js");
|
||||
|
||||
let failures = 0;
|
||||
const check = (label, got, want) => {
|
||||
const ok = JSON.stringify(got) === JSON.stringify(want);
|
||||
if (!ok) failures++;
|
||||
console.log(
|
||||
` ${ok ? "ok " : "FAIL"} ${label}` +
|
||||
(ok
|
||||
? ""
|
||||
: `\n got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`),
|
||||
);
|
||||
};
|
||||
|
||||
console.log(`\nverifying ${dialect} at ${url.replace(/:[^:@]*@/, ":***@")}\n`);
|
||||
|
||||
const users = new UserRepository(context);
|
||||
const userId = `verify-${randomUUID()}`;
|
||||
|
||||
// insertReturning: on MySQL this is an insert plus a read inside a transaction.
|
||||
const created = await users.create({
|
||||
id: userId,
|
||||
username: "before",
|
||||
passwordHash: "x",
|
||||
isAdmin: true,
|
||||
});
|
||||
check("insert returns the stored row", created?.username, "before");
|
||||
|
||||
// The one non-identity value encoder in the schema. Booleans are integers in
|
||||
// the sqlite definitions the repositories import, so this asserts that 1/0
|
||||
// survives a round trip through a native boolean column.
|
||||
check("boolean true survives the round trip", created?.isAdmin, true);
|
||||
|
||||
// updateReturning must report the state AFTER the write. Reading first would
|
||||
// return the value the update replaced — silently, with no error.
|
||||
const updated = await users.update(userId, { username: "after" });
|
||||
check("update returns the new value", updated?.username, "after");
|
||||
|
||||
const hosts = new HostRepository(context);
|
||||
const host = await hosts.create({
|
||||
userId,
|
||||
name: "verify",
|
||||
ip: "127.0.0.1",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
enableTerminal: true,
|
||||
});
|
||||
check(
|
||||
"autoincrement id came back",
|
||||
typeof host?.id === "number" && host.id > 0,
|
||||
true,
|
||||
);
|
||||
check(
|
||||
"database-assigned createdAt came back",
|
||||
typeof host?.createdAt === "string" && host.createdAt.length > 0,
|
||||
true,
|
||||
);
|
||||
|
||||
// deleteReturning must report the state BEFORE the write. Reading afterwards
|
||||
// would find nothing at all.
|
||||
const settings = new SettingsRepository(context);
|
||||
const prefix = `verify-${randomUUID()}`;
|
||||
await settings.set(`${prefix}-a`, "1");
|
||||
await settings.set(`${prefix}-b`, "2");
|
||||
check(
|
||||
"delete reports the rows it removed",
|
||||
await settings.deleteLike(`${prefix}-%`),
|
||||
2,
|
||||
);
|
||||
check(
|
||||
"and they are actually gone",
|
||||
(await settings.listAll()).filter((row) => row.key.startsWith(prefix)).length,
|
||||
0,
|
||||
);
|
||||
|
||||
await hosts.deleteForUser(userId, host.id);
|
||||
check("host really deleted", await hosts.findById(host.id), null);
|
||||
|
||||
console.log(
|
||||
failures === 0
|
||||
? `\n${dialect}: all checks passed\n`
|
||||
: `\n${dialect}: ${failures} FAILED\n`,
|
||||
);
|
||||
process.exit(failures === 0 ? 0 : 1);
|
||||
@@ -713,7 +713,7 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const filename = `termix-export-${user[0].username}-${timestamp}.sqlite`;
|
||||
const filename = `termix-export-${user.username}-${timestamp}.sqlite`;
|
||||
const tempPath = path.join(tempDir, filename);
|
||||
|
||||
apiLogger.info("Creating export database", {
|
||||
@@ -882,7 +882,7 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
);
|
||||
`);
|
||||
|
||||
const userRecord = user[0];
|
||||
const userRecord = user;
|
||||
const insertUser = exportDb.prepare(`
|
||||
INSERT INTO users (id, username, password_hash, is_admin, is_oidc, oidc_identifier, client_id, client_secret, issuer_url, authorization_url, token_url, identifier_path, name_path, scopes, totp_secret, totp_enabled, totp_backup_codes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as sqlite from "drizzle-orm/sqlite-core";
|
||||
import * as pg from "drizzle-orm/pg-core";
|
||||
import * as mysql from "drizzle-orm/mysql-core";
|
||||
|
||||
/**
|
||||
* Per-dialect column constructors, so a table can be declared once instead of
|
||||
* three times.
|
||||
*
|
||||
* The existing schema only uses three column types (text, integer, real) plus
|
||||
* an integer-backed boolean, which is what makes this tractable — the surface
|
||||
* to abstract is small and closed. Anything a dialect cannot express the same
|
||||
* way is spelled out here rather than at 52 call sites.
|
||||
*
|
||||
* Notable differences this papers over:
|
||||
* - booleans are integers in SQLite, native in Postgres and tinyint in MySQL
|
||||
* - autoincrement keys are `integer primary key autoincrement`, `serial`, and
|
||||
* `int auto_increment` respectively
|
||||
* - MySQL cannot index an unbounded TEXT, so keyed/indexed strings must be
|
||||
* varchar; `shortText` exists for columns used as keys or in unique indexes
|
||||
*/
|
||||
export interface ColumnKit {
|
||||
table: typeof sqlite.sqliteTable | typeof pg.pgTable | typeof mysql.mysqlTable;
|
||||
/** Free-form string; unbounded where the engine allows it. */
|
||||
text: (name: string) => AnyColumnBuilder;
|
||||
/** String used as a key, unique or indexed — bounded so MySQL can index it. */
|
||||
shortText: (name: string, length?: number) => AnyColumnBuilder;
|
||||
int: (name: string) => AnyColumnBuilder;
|
||||
/** Auto-incrementing surrogate primary key. */
|
||||
serial: (name: string) => AnyColumnBuilder;
|
||||
bool: (name: string) => AnyColumnBuilder;
|
||||
real: (name: string) => AnyColumnBuilder;
|
||||
}
|
||||
|
||||
// drizzle's builders are heavily generic; the schema modules keep their own
|
||||
// precise types, so this alias only exists to describe the kit's shape.
|
||||
type AnyColumnBuilder = ReturnType<typeof sqlite.text>;
|
||||
|
||||
const DEFAULT_KEY_LENGTH = 255;
|
||||
|
||||
export const sqliteKit = {
|
||||
table: sqlite.sqliteTable,
|
||||
text: (name: string) => sqlite.text(name),
|
||||
shortText: (name: string) => sqlite.text(name),
|
||||
int: (name: string) => sqlite.integer(name),
|
||||
serial: (name: string) =>
|
||||
sqlite.integer(name).primaryKey({ autoIncrement: true }),
|
||||
bool: (name: string) => sqlite.integer(name, { mode: "boolean" }),
|
||||
real: (name: string) => sqlite.real(name),
|
||||
} as const;
|
||||
|
||||
export const pgKit = {
|
||||
table: pg.pgTable,
|
||||
text: (name: string) => pg.text(name),
|
||||
shortText: (name: string, length = DEFAULT_KEY_LENGTH) =>
|
||||
pg.varchar(name, { length }),
|
||||
int: (name: string) => pg.integer(name),
|
||||
serial: (name: string) => pg.serial(name).primaryKey(),
|
||||
bool: (name: string) => pg.boolean(name),
|
||||
real: (name: string) => pg.doublePrecision(name),
|
||||
} as const;
|
||||
|
||||
export const mysqlKit = {
|
||||
table: mysql.mysqlTable,
|
||||
text: (name: string) => mysql.text(name),
|
||||
shortText: (name: string, length = DEFAULT_KEY_LENGTH) =>
|
||||
mysql.varchar(name, { length }),
|
||||
int: (name: string) => mysql.int(name),
|
||||
serial: (name: string) => mysql.int(name).autoincrement().primaryKey(),
|
||||
bool: (name: string) => mysql.boolean(name),
|
||||
real: (name: string) => mysql.double(name),
|
||||
} as const;
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { DatabaseDialect } from "./dialect.js";
|
||||
import type { PortableDatabase } from "../repositories/database-context.js";
|
||||
|
||||
export const DATABASE_URL_ENV = "DATABASE_URL";
|
||||
|
||||
/**
|
||||
* Opens a connection to a client-server engine.
|
||||
*
|
||||
* SQLite is not handled here — it has its own lifecycle in db/index.ts, where
|
||||
* the database is decrypted into memory and serialised back to a file. This
|
||||
* covers the engines that connect to something already running.
|
||||
*
|
||||
* The returned handle is typed as PortableDatabase; see the note there on why
|
||||
* that is an approximation and what guarantees it.
|
||||
*/
|
||||
export function databaseUrl(env: NodeJS.ProcessEnv = process.env): string | null {
|
||||
const url = env[DATABASE_URL_ENV]?.trim();
|
||||
return url ? url : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the connection string suits the configured engine before trying to
|
||||
* open it, so a mismatch fails with something readable rather than a driver
|
||||
* error thirty frames down.
|
||||
*/
|
||||
export function assertUrlMatchesDialect(
|
||||
url: string,
|
||||
dialect: DatabaseDialect,
|
||||
): void {
|
||||
const scheme = url.split("://", 1)[0].toLowerCase();
|
||||
|
||||
const expected: Record<string, readonly string[]> = {
|
||||
postgres: ["postgres", "postgresql"],
|
||||
mysql: ["mysql", "mariadb"],
|
||||
};
|
||||
|
||||
const allowed = expected[dialect];
|
||||
if (!allowed) {
|
||||
throw new Error(`${dialect} does not use ${DATABASE_URL_ENV}`);
|
||||
}
|
||||
|
||||
if (!allowed.includes(scheme)) {
|
||||
throw new Error(
|
||||
`${DATABASE_URL_ENV} is a "${scheme}://" URL but DATABASE_DIALECT is "${dialect}". ` +
|
||||
`Expected one of ${allowed.map((s) => `${s}://`).join(", ")}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function connectRemoteDatabase(
|
||||
dialect: DatabaseDialect,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Promise<PortableDatabase> {
|
||||
const url = databaseUrl(env);
|
||||
if (!url) {
|
||||
throw new Error(
|
||||
`${DATABASE_URL_ENV} must be set when DATABASE_DIALECT is "${dialect}".`,
|
||||
);
|
||||
}
|
||||
|
||||
assertUrlMatchesDialect(url, dialect);
|
||||
|
||||
// No `schema` option: it only feeds drizzle's relational query API
|
||||
// (`db.query.*`), which nothing here uses. The query builder takes its table
|
||||
// names and value encoders from the table objects the repositories import —
|
||||
// see the note in schema.pg.ts on why the generated schemas are DDL-only.
|
||||
if (dialect === "postgres") {
|
||||
const { drizzle } = await import("drizzle-orm/node-postgres");
|
||||
return drizzle(url) as unknown as PortableDatabase;
|
||||
}
|
||||
|
||||
const { drizzle } = await import("drizzle-orm/mysql2");
|
||||
return drizzle(url) as unknown as PortableDatabase;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Which engine the schema and repositories are built against.
|
||||
*
|
||||
* SQLite is not going away: the desktop app embeds its backend and cannot ship
|
||||
* a database server, so it will always run on SQLite. Postgres and MySQL are
|
||||
* for self-hosted deployments that need more than one process to reach the
|
||||
* data. This is a multi-backend story, not a migration off SQLite.
|
||||
*/
|
||||
export type DatabaseDialect = "sqlite" | "postgres" | "mysql";
|
||||
|
||||
export const DATABASE_DIALECT_ENV = "DATABASE_DIALECT";
|
||||
|
||||
const SUPPORTED: readonly DatabaseDialect[] = ["sqlite", "postgres", "mysql"];
|
||||
|
||||
export function isDatabaseDialect(value: unknown): value is DatabaseDialect {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
(SUPPORTED as readonly string[]).includes(value)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the configured dialect, defaulting to SQLite so existing
|
||||
* deployments and the desktop build are unaffected by this being added.
|
||||
*/
|
||||
export function resolveDatabaseDialect(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): DatabaseDialect {
|
||||
const raw = env[DATABASE_DIALECT_ENV]?.trim().toLowerCase();
|
||||
if (!raw) return "sqlite";
|
||||
|
||||
if (!isDatabaseDialect(raw)) {
|
||||
throw new Error(
|
||||
`Unsupported ${DATABASE_DIALECT_ENV}: "${raw}". Expected one of ${SUPPORTED.join(", ")}.`,
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a write has to be explicitly persisted after it commits.
|
||||
*
|
||||
* SQLite here is an in-memory database serialised back to an encrypted file, so
|
||||
* every write needs a trigger to flush it. Client-server engines have already
|
||||
* durably committed by the time the query returns — there is no file to write
|
||||
* and nothing to schedule.
|
||||
*/
|
||||
export function needsExplicitPersist(dialect: DatabaseDialect): boolean {
|
||||
return dialect === "sqlite";
|
||||
}
|
||||
@@ -7,8 +7,21 @@ import { databaseLogger } from "../../utils/logger.js";
|
||||
import { DatabaseFileEncryption } from "../../utils/database-file-encryption.js";
|
||||
import { SystemCrypto } from "../../utils/system-crypto.js";
|
||||
import { DatabaseMigration } from "../../utils/database-migration.js";
|
||||
import {
|
||||
ensureSharedHostAuthOverrideProtocolSchema,
|
||||
migrateLegacySharedHostAuthOverrides,
|
||||
} from "../../utils/shared-host-auth-override-migration.js";
|
||||
import { DatabaseSaveTrigger } from "../../utils/database-save-trigger.js";
|
||||
import { migrateAuditRetention } from "../../utils/audit-retention-migration.js";
|
||||
import {
|
||||
assertDataDirIsNotMisconfigured,
|
||||
DataDirMisconfiguredError,
|
||||
} from "../../utils/data-dir-guard.js";
|
||||
import { getDefaultGuacdUrl } from "../../utils/guacd-config.js";
|
||||
import { resolveDatabaseDialect, type DatabaseDialect } from "./dialect.js";
|
||||
import { connectRemoteDatabase } from "./connect.js";
|
||||
import { runRemoteMigrations } from "./migrate.js";
|
||||
import type { PortableDatabase } from "../repositories/database-context.js";
|
||||
|
||||
const dataDir = process.env.DATA_DIR || "./db/data";
|
||||
const dbDir = path.resolve(dataDir);
|
||||
@@ -104,11 +117,16 @@ async function initializeDatabaseAsync(): Promise<void> {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assertDataDirIsNotMisconfigured(dataDir);
|
||||
memoryDatabase = new Database(":memory:");
|
||||
isNewDatabase = true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Not a decryption problem: the database is fine, we are pointed at the
|
||||
// wrong directory. Surface that message as-is.
|
||||
if (error instanceof DataDirMisconfiguredError) throw error;
|
||||
|
||||
databaseLogger.error("Failed to initialize memory database", error, {
|
||||
operation: "db_memory_init_failed",
|
||||
errorMessage: error instanceof Error ? error.message : "Unknown error",
|
||||
@@ -145,8 +163,35 @@ async function initializeDatabaseAsync(): Promise<void> {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
memoryDatabase = new Database(":memory:");
|
||||
isNewDatabase = true;
|
||||
assertDataDirIsNotMisconfigured(dataDir);
|
||||
|
||||
// The database still lives in memory and is serialised out on every write;
|
||||
// turning encryption off only changes whether that file is ciphertext. It
|
||||
// has to be read back, or each restart starts empty and silently discards
|
||||
// everything the previous run saved.
|
||||
const existing = readPlainDatabaseFile();
|
||||
if (existing) {
|
||||
memoryDatabase = new Database(existing);
|
||||
databaseLogger.info("Loaded unencrypted database from disk", {
|
||||
operation: "db_load_plain",
|
||||
path: dbPath,
|
||||
bytes: existing.length,
|
||||
});
|
||||
} else {
|
||||
memoryDatabase = new Database(":memory:");
|
||||
isNewDatabase = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The plain database file, or null when there is nothing to restore. */
|
||||
function readPlainDatabaseFile(): Buffer | null {
|
||||
try {
|
||||
const contents = fs.readFileSync(dbPath);
|
||||
return contents.length > 0 ? contents : null;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,13 +517,14 @@ async function initializeCompleteDatabase(): Promise<void> {
|
||||
success INTEGER NOT NULL,
|
||||
error_message TEXT,
|
||||
timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS session_recordings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
user_id TEXT,
|
||||
username TEXT,
|
||||
access_id INTEGER,
|
||||
started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ended_at TEXT,
|
||||
@@ -491,7 +537,7 @@ async function initializeCompleteDatabase(): Promise<void> {
|
||||
terminated_by_owner INTEGER DEFAULT 0,
|
||||
termination_reason TEXT,
|
||||
FOREIGN KEY (host_id) REFERENCES ssh_data (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL,
|
||||
FOREIGN KEY (access_id) REFERENCES host_access (id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
@@ -775,6 +821,7 @@ const migrateSchema = () => {
|
||||
addColumnIfNotExists("user_preferences", "compact_host_view", "INTEGER");
|
||||
addColumnIfNotExists("user_preferences", "status_color_scheme", "TEXT");
|
||||
addColumnIfNotExists("user_preferences", "custom_themes", "TEXT");
|
||||
addColumnIfNotExists("user_preferences", "custom_keybindings", "TEXT");
|
||||
|
||||
sqlite.exec(`
|
||||
CREATE TABLE IF NOT EXISTS dashboard_service_links (
|
||||
@@ -1417,6 +1464,28 @@ const migrateSchema = () => {
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
ensureSharedHostAuthOverrideProtocolSchema(sqlite);
|
||||
} catch (schemaError) {
|
||||
databaseLogger.warn("Failed to prepare shared_host_auth_overrides table", {
|
||||
operation: "schema_migration",
|
||||
error: schemaError,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
migrateLegacySharedHostAuthOverrides(
|
||||
sqlite,
|
||||
getRawSettingValue,
|
||||
setRawSettingValue,
|
||||
);
|
||||
} catch (migrateError) {
|
||||
databaseLogger.warn("Failed to migrate shared host auth overrides", {
|
||||
operation: "schema_migration",
|
||||
error: migrateError,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
sqlite.prepare("SELECT credential_id FROM ssh_folders LIMIT 1").get();
|
||||
} catch {
|
||||
@@ -1447,6 +1516,7 @@ const migrateSchema = () => {
|
||||
{ column: "connection_type", sql: "ALTER TABLE ssh_data ADD COLUMN connection_type TEXT NOT NULL DEFAULT 'ssh'" },
|
||||
{ column: "credential_id", sql: "ALTER TABLE ssh_data ADD COLUMN credential_id INTEGER" },
|
||||
{ column: "override_credential_username", sql: "ALTER TABLE ssh_data ADD COLUMN override_credential_username INTEGER" },
|
||||
{ column: "share_ssh_auth", sql: "ALTER TABLE ssh_data ADD COLUMN share_ssh_auth INTEGER NOT NULL DEFAULT 0" },
|
||||
{ column: "jump_hosts", sql: "ALTER TABLE ssh_data ADD COLUMN jump_hosts TEXT" },
|
||||
{ column: "show_terminal_in_sidebar", sql: "ALTER TABLE ssh_data ADD COLUMN show_terminal_in_sidebar INTEGER NOT NULL DEFAULT 1" },
|
||||
{ column: "show_file_manager_in_sidebar", sql: "ALTER TABLE ssh_data ADD COLUMN show_file_manager_in_sidebar INTEGER NOT NULL DEFAULT 0" },
|
||||
@@ -1636,7 +1706,7 @@ const migrateSchema = () => {
|
||||
sqlite.exec(`
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
user_id TEXT,
|
||||
username TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
resource_type TEXT NOT NULL,
|
||||
@@ -1648,7 +1718,7 @@ const migrateSchema = () => {
|
||||
success INTEGER NOT NULL,
|
||||
error_message TEXT,
|
||||
timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
|
||||
);
|
||||
`);
|
||||
} catch (createError) {
|
||||
@@ -2496,6 +2566,10 @@ const migrateSchema = () => {
|
||||
}
|
||||
// --- sync end ---
|
||||
|
||||
// Audit trails and session recordings used to be deleted along with the user
|
||||
// they referenced, which defeats the point of keeping them.
|
||||
migrateAuditRetention(sqlite);
|
||||
|
||||
databaseLogger.success("Schema migration completed", {
|
||||
operation: "schema_migration",
|
||||
});
|
||||
@@ -2579,10 +2653,54 @@ async function handlePostInitFileEncryption() {
|
||||
}
|
||||
|
||||
async function initializeDatabase(): Promise<void> {
|
||||
const dialect = resolveDatabaseDialect();
|
||||
|
||||
if (dialect !== "sqlite") {
|
||||
await initializeRemoteDatabase(dialect);
|
||||
return;
|
||||
}
|
||||
|
||||
await initializeCompleteDatabase();
|
||||
await handlePostInitFileEncryption();
|
||||
}
|
||||
|
||||
/**
|
||||
* Startup against Postgres or MySQL.
|
||||
*
|
||||
* Shorter than the SQLite path because most of what that one does has no
|
||||
* counterpart here: there is no file to decrypt, no in-memory copy to keep in
|
||||
* step with disk, and the schema comes from drizzle-kit migrations instead of
|
||||
* the inline DDL below.
|
||||
*
|
||||
* What does carry over is the settings cache. 27 call sites read settings
|
||||
* synchronously, which better-sqlite3 allows and no remote driver does, so the
|
||||
* table is loaded once here before anything asks for it.
|
||||
*/
|
||||
async function initializeRemoteDatabase(
|
||||
dialect: Exclude<DatabaseDialect, "sqlite">,
|
||||
): Promise<void> {
|
||||
databaseLogger.info(`Connecting to ${dialect} database`, {
|
||||
operation: "db_init",
|
||||
dialect,
|
||||
});
|
||||
|
||||
db = await connectRemoteDatabase(dialect);
|
||||
await runRemoteMigrations(dialect, db);
|
||||
|
||||
// Imported here rather than at the top: factory.ts imports getDb from this
|
||||
// module, and a static import would close the cycle at module-load time.
|
||||
const { primeCurrentSettingsCache, startSettingsCacheRefresh } = await import(
|
||||
"../repositories/factory.js"
|
||||
);
|
||||
await primeCurrentSettingsCache();
|
||||
startSettingsCacheRefresh();
|
||||
|
||||
databaseLogger.info(`${dialect} database ready`, {
|
||||
operation: "db_init_complete",
|
||||
dialect,
|
||||
});
|
||||
}
|
||||
|
||||
export { initializeDatabase };
|
||||
|
||||
async function cleanupDatabase() {
|
||||
@@ -2660,9 +2778,9 @@ process.on("SIGTERM", async () => {
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
let db: ReturnType<typeof drizzle<typeof schema>>;
|
||||
let db: PortableDatabase;
|
||||
|
||||
export function getDb(): ReturnType<typeof drizzle<typeof schema>> {
|
||||
export function getDb(): PortableDatabase {
|
||||
if (!db) {
|
||||
throw new Error(
|
||||
"Database not initialized. Ensure initializeDatabase() is called before accessing db.",
|
||||
@@ -2673,6 +2791,13 @@ export function getDb(): ReturnType<typeof drizzle<typeof schema>> {
|
||||
|
||||
export function getSqlite(): Database.Database {
|
||||
if (!sqlite) {
|
||||
const dialect = resolveDatabaseDialect();
|
||||
if (dialect !== "sqlite") {
|
||||
throw new Error(
|
||||
`No SQLite handle: DATABASE_DIALECT is "${dialect}". This caller needs a ` +
|
||||
`synchronous query, which only SQLite offers — give it an async path instead.`,
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
"SQLite not initialized. Ensure initializeDatabase() is called before accessing sqlite.",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import path from "path";
|
||||
import type { DatabaseDialect } from "./dialect.js";
|
||||
import type { PortableDatabase } from "../repositories/database-context.js";
|
||||
|
||||
export const MIGRATIONS_DIR_ENV = "DRIZZLE_MIGRATIONS_DIR";
|
||||
|
||||
/**
|
||||
* Where the generated migrations live.
|
||||
*
|
||||
* SQLite does not appear here: it builds its schema from the DDL in index.ts
|
||||
* and patches it forward with migrateSchema(). Only the client-server engines
|
||||
* use drizzle-kit migrations, and each has its own folder because the
|
||||
* generated SQL differs per dialect.
|
||||
*/
|
||||
export function migrationsFolder(
|
||||
dialect: DatabaseDialect,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): string {
|
||||
const override = env[MIGRATIONS_DIR_ENV]?.trim();
|
||||
const root = override || path.resolve(process.cwd(), "drizzle");
|
||||
return path.join(root, dialect);
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a remote database up to the current schema.
|
||||
*
|
||||
* drizzle's migrator records what it has applied in its own table, so this is
|
||||
* safe to run on every start — including against a database another instance
|
||||
* already migrated.
|
||||
*/
|
||||
export async function runRemoteMigrations(
|
||||
dialect: DatabaseDialect,
|
||||
db: PortableDatabase,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Promise<void> {
|
||||
if (dialect === "sqlite") {
|
||||
throw new Error("SQLite builds its schema in index.ts, not from drizzle/");
|
||||
}
|
||||
|
||||
const folder = migrationsFolder(dialect, env);
|
||||
|
||||
const { migrate } =
|
||||
dialect === "postgres"
|
||||
? await import("drizzle-orm/node-postgres/migrator")
|
||||
: await import("drizzle-orm/mysql2/migrator");
|
||||
|
||||
await (migrate as (db: unknown, config: { migrationsFolder: string }) => Promise<void>)(
|
||||
db,
|
||||
{ migrationsFolder: folder },
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+187
-100
@@ -1,4 +1,10 @@
|
||||
import { sqliteTable, text, integer, real } from "drizzle-orm/sqlite-core";
|
||||
import {
|
||||
sqliteTable,
|
||||
text,
|
||||
integer,
|
||||
real,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
export const users = sqliteTable("users", {
|
||||
@@ -124,6 +130,9 @@ export const hosts = sqliteTable("ssh_data", {
|
||||
pin: integer("pin", { mode: "boolean" }).notNull().default(false),
|
||||
authType: text("auth_type").notNull(),
|
||||
useWarpgate: integer("use_warpgate", { mode: "boolean" }).notNull().default(false),
|
||||
shareSshAuth: integer("share_ssh_auth", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
forceKeyboardInteractive: text("force_keyboard_interactive"),
|
||||
|
||||
password: text("password"),
|
||||
@@ -560,46 +569,85 @@ export const hostAccess = sqliteTable("host_access", {
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
lastAccessedAt: text("last_accessed_at"),
|
||||
accessCount: integer("access_count").notNull().default(0),
|
||||
overrideCredentialId: integer("override_credential_id").references(
|
||||
() => sshCredentials.id,
|
||||
{ onDelete: "set null" },
|
||||
),
|
||||
});
|
||||
|
||||
export const sharedHostSecrets = sqliteTable("shared_host_secrets", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
export const sharedHostAuthOverrides = sqliteTable(
|
||||
"shared_host_auth_overrides",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
hostId: integer("host_id")
|
||||
.notNull()
|
||||
.references(() => hosts.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
protocol: text("protocol").notNull().default("ssh"),
|
||||
credentialId: integer("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("shared_host_auth_overrides_host_user_protocol_unique").on(
|
||||
table.hostId,
|
||||
table.userId,
|
||||
table.protocol,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
hostAccessId: integer("host_access_id")
|
||||
.notNull()
|
||||
.references(() => hostAccess.id, { onDelete: "cascade" }),
|
||||
export const sharedHostSecrets = sqliteTable(
|
||||
"shared_host_secrets",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
|
||||
targetUserId: text("target_user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
hostAccessId: integer("host_access_id")
|
||||
.notNull()
|
||||
.references(() => hostAccess.id, { onDelete: "cascade" }),
|
||||
|
||||
protocol: text("protocol").notNull().default("ssh"),
|
||||
sourceType: text("source_type").notNull().default("credential"),
|
||||
targetUserId: text("target_user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
originalCredentialId: integer("original_credential_id").references(
|
||||
() => sshCredentials.id,
|
||||
{ onDelete: "cascade" },
|
||||
),
|
||||
protocol: text("protocol").notNull().default("ssh"),
|
||||
sourceType: text("source_type").notNull().default("credential"),
|
||||
|
||||
encryptedUsername: text("encrypted_username"),
|
||||
encryptedAuthType: text("encrypted_auth_type"),
|
||||
encryptedPassword: text("encrypted_password"),
|
||||
encryptedKey: text("encrypted_key", { length: 16384 }),
|
||||
encryptedKeyPassword: text("encrypted_key_password"),
|
||||
encryptedKeyType: text("encrypted_key_type"),
|
||||
encryptedDomain: text("encrypted_domain"),
|
||||
originalCredentialId: integer("original_credential_id").references(
|
||||
() => sshCredentials.id,
|
||||
{ onDelete: "cascade" },
|
||||
),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
encryptedUsername: text("encrypted_username"),
|
||||
encryptedAuthType: text("encrypted_auth_type"),
|
||||
encryptedPassword: text("encrypted_password"),
|
||||
encryptedKey: text("encrypted_key", { length: 16384 }),
|
||||
encryptedKeyPassword: text("encrypted_key_password"),
|
||||
encryptedKeyType: text("encrypted_key_type"),
|
||||
encryptedDomain: text("encrypted_domain"),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
// Declared inline in the production DDL as UNIQUE(...), but never here,
|
||||
// so the generated Postgres and MySQL schemas allowed duplicates the
|
||||
// SQLite deployment forbids — and the upsert had nothing to conflict on.
|
||||
(table) => [
|
||||
uniqueIndex("idx_shared_host_secrets_scope").on(
|
||||
table.hostAccessId,
|
||||
table.targetUserId,
|
||||
table.protocol,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const roles = sqliteTable("roles", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
@@ -621,29 +669,36 @@ export const roles = sqliteTable("roles", {
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
|
||||
export const userRoles = sqliteTable("user_roles", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: integer("role_id")
|
||||
.notNull()
|
||||
.references(() => roles.id, { onDelete: "cascade" }),
|
||||
|
||||
grantedBy: text("granted_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
grantedAt: text("granted_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
export const userRoles = sqliteTable(
|
||||
"user_roles",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: integer("role_id")
|
||||
.notNull()
|
||||
.references(() => roles.id, { onDelete: "cascade" }),
|
||||
|
||||
grantedBy: text("granted_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
grantedAt: text("granted_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
// Declared inline in the production DDL as UNIQUE(...), but never here,
|
||||
// so the generated Postgres and MySQL schemas allowed duplicates the
|
||||
// SQLite deployment forbids — and the upsert had nothing to conflict on.
|
||||
(table) => [uniqueIndex("idx_user_roles_user_role").on(table.userId, table.roleId)],
|
||||
);
|
||||
|
||||
export const auditLogs = sqliteTable("audit_logs", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
// Nullable on purpose: the trail outlives the account, and username keeps the
|
||||
// entry attributable once the reference is gone.
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "set null" }),
|
||||
username: text("username").notNull(),
|
||||
|
||||
action: text("action").notNull(),
|
||||
@@ -669,9 +724,10 @@ export const sessionRecordings = sqliteTable("session_recordings", {
|
||||
hostId: integer("host_id")
|
||||
.notNull()
|
||||
.references(() => hosts.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
// Nullable on purpose: a recording is evidence about the host as much as the
|
||||
// person, so it outlives the account. username keeps it attributable.
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "set null" }),
|
||||
username: text("username"),
|
||||
accessId: integer("access_id").references(() => hostAccess.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
@@ -750,29 +806,36 @@ export const sessionShareParticipants = sqliteTable(
|
||||
},
|
||||
);
|
||||
|
||||
export const opksshTokens = sqliteTable("opkssh_tokens", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
hostId: integer("host_id")
|
||||
.notNull()
|
||||
.references(() => hosts.id, { onDelete: "cascade" }),
|
||||
|
||||
sshCert: text("ssh_cert", { length: 8192 }).notNull(),
|
||||
privateKey: text("private_key", { length: 8192 }).notNull(),
|
||||
|
||||
email: text("email"),
|
||||
sub: text("sub"),
|
||||
issuer: text("issuer"),
|
||||
audience: text("audience"),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
expiresAt: text("expires_at").notNull(),
|
||||
lastUsed: text("last_used"),
|
||||
});
|
||||
export const opksshTokens = sqliteTable(
|
||||
"opkssh_tokens",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
hostId: integer("host_id")
|
||||
.notNull()
|
||||
.references(() => hosts.id, { onDelete: "cascade" }),
|
||||
|
||||
sshCert: text("ssh_cert", { length: 8192 }).notNull(),
|
||||
privateKey: text("private_key", { length: 8192 }).notNull(),
|
||||
|
||||
email: text("email"),
|
||||
sub: text("sub"),
|
||||
issuer: text("issuer"),
|
||||
audience: text("audience"),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
expiresAt: text("expires_at").notNull(),
|
||||
lastUsed: text("last_used"),
|
||||
},
|
||||
// Declared inline in the production DDL as UNIQUE(...), but never here,
|
||||
// so the generated Postgres and MySQL schemas allowed duplicates the
|
||||
// SQLite deployment forbids — and the upsert had nothing to conflict on.
|
||||
(table) => [uniqueIndex("idx_opkssh_tokens_user_host").on(table.userId, table.hostId)],
|
||||
);
|
||||
|
||||
// Vault SSH signer profiles. These hold ONLY non-secret connection settings and
|
||||
// are intended to be shared across users (shared === true makes a profile
|
||||
@@ -813,24 +876,31 @@ export const vaultProfiles = sqliteTable("vault_profiles", {
|
||||
// Per-user cache of the ephemeral SSH private key + Vault-signed certificate.
|
||||
// Transient: rows live only until the certificate expires. Secret fields are
|
||||
// encrypted under the user's data-encryption key (see field-crypto.ts).
|
||||
export const vaultTokens = sqliteTable("vault_tokens", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
profileId: integer("profile_id")
|
||||
.notNull()
|
||||
.references(() => vaultProfiles.id, { onDelete: "cascade" }),
|
||||
|
||||
sshCert: text("ssh_cert", { length: 8192 }).notNull(),
|
||||
privateKey: text("private_key", { length: 8192 }).notNull(),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
expiresAt: text("expires_at").notNull(),
|
||||
lastUsed: text("last_used"),
|
||||
});
|
||||
export const vaultTokens = sqliteTable(
|
||||
"vault_tokens",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
profileId: integer("profile_id")
|
||||
.notNull()
|
||||
.references(() => vaultProfiles.id, { onDelete: "cascade" }),
|
||||
|
||||
sshCert: text("ssh_cert", { length: 8192 }).notNull(),
|
||||
privateKey: text("private_key", { length: 8192 }).notNull(),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
expiresAt: text("expires_at").notNull(),
|
||||
lastUsed: text("last_used"),
|
||||
},
|
||||
// Declared inline in the production DDL as UNIQUE(...), but never here,
|
||||
// so the generated Postgres and MySQL schemas allowed duplicates the
|
||||
// SQLite deployment forbids — and the upsert had nothing to conflict on.
|
||||
(table) => [uniqueIndex("idx_vault_tokens_user_profile").on(table.userId, table.profileId)],
|
||||
);
|
||||
|
||||
export const apiKeys = sqliteTable("api_keys", {
|
||||
id: text("id").primaryKey(),
|
||||
@@ -892,12 +962,15 @@ export const userPreferences = sqliteTable("user_preferences", {
|
||||
compactHostView: integer("compact_host_view", { mode: "boolean" }),
|
||||
statusColorScheme: text("status_color_scheme"),
|
||||
customThemes: text("custom_themes"),
|
||||
customKeybindings: text("custom_keybindings"),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
|
||||
export const hostMetricsPreferences = sqliteTable("host_metrics_preferences", {
|
||||
export const hostMetricsPreferences = sqliteTable(
|
||||
"host_metrics_preferences",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
@@ -914,9 +987,18 @@ export const hostMetricsPreferences = sqliteTable("host_metrics_preferences", {
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
},
|
||||
// One layout per user per host. Enforced in production since the inline DDL
|
||||
// creates it, but it was never declared here, so the generated Postgres and
|
||||
// MySQL schemas lacked it — and the upsert has nothing to conflict on.
|
||||
(table) => [
|
||||
uniqueIndex("idx_host_metrics_prefs_user_host").on(table.userId, table.hostId),
|
||||
],
|
||||
);
|
||||
|
||||
export const hostHealthChecks = sqliteTable("host_health_checks", {
|
||||
export const hostHealthChecks = sqliteTable(
|
||||
"host_health_checks",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
@@ -933,7 +1015,12 @@ export const hostHealthChecks = sqliteTable("host_health_checks", {
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
},
|
||||
// Same as above: one set of checks per user per host.
|
||||
(table) => [
|
||||
uniqueIndex("idx_host_health_checks_user_host").on(table.userId, table.hostId),
|
||||
],
|
||||
);
|
||||
|
||||
export const hostHealthHistory = sqliteTable("host_health_history", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, count, desc, eq, inArray, isNull, or } from "drizzle-orm";
|
||||
import { and, count, desc, eq, inArray, isNull, lt, or } from "drizzle-orm";
|
||||
import {
|
||||
alertFirings,
|
||||
alertRuleChannels,
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
notificationChannels,
|
||||
} from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { sqlTimestampDaysAgo } from "./sql-timestamp.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning, updateReturning } from "./returning.js";
|
||||
|
||||
type AlertRuleRecord = typeof alertRules.$inferSelect;
|
||||
type NotificationChannelRecord = typeof notificationChannels.$inferSelect;
|
||||
@@ -117,16 +120,17 @@ export class AlertRepository {
|
||||
config: string;
|
||||
enabled: boolean;
|
||||
}): Promise<NotificationChannelRow> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(notificationChannels)
|
||||
.values({
|
||||
const [created] = await insertReturning(
|
||||
this.context,
|
||||
notificationChannels,
|
||||
{
|
||||
userId: input.userId,
|
||||
name: input.name,
|
||||
type: input.type,
|
||||
config: input.config,
|
||||
enabled: input.enabled,
|
||||
})
|
||||
.returning();
|
||||
},
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return mapChannelRow(created);
|
||||
@@ -146,16 +150,15 @@ export class AlertRepository {
|
||||
return this.findNotificationChannelForUser(id, userId);
|
||||
}
|
||||
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(notificationChannels)
|
||||
.set(input)
|
||||
.where(
|
||||
and(
|
||||
eq(notificationChannels.id, id),
|
||||
eq(notificationChannels.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
notificationChannels,
|
||||
input,
|
||||
and(
|
||||
eq(notificationChannels.id, id),
|
||||
eq(notificationChannels.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
if (!updated) return null;
|
||||
await this.afterWrite();
|
||||
@@ -166,17 +169,16 @@ export class AlertRepository {
|
||||
id: number,
|
||||
userId: string,
|
||||
): Promise<boolean> {
|
||||
const deleted = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(notificationChannels)
|
||||
.where(
|
||||
and(
|
||||
eq(notificationChannels.id, id),
|
||||
eq(notificationChannels.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning({ id: notificationChannels.id });
|
||||
);
|
||||
|
||||
if (deleted.length === 0) return false;
|
||||
if (rowsAffected(result) === 0) return false;
|
||||
await this.afterWrite();
|
||||
return true;
|
||||
}
|
||||
@@ -210,21 +212,18 @@ export class AlertRepository {
|
||||
channels: number[];
|
||||
now: string;
|
||||
}): Promise<AlertRuleWithChannelsRow> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(alertRules)
|
||||
.values({
|
||||
userId: input.userId,
|
||||
hostId: input.hostId,
|
||||
name: input.name,
|
||||
enabled: input.enabled,
|
||||
triggerType: input.triggerType,
|
||||
thresholdValue: input.thresholdValue,
|
||||
thresholdDurationSeconds: input.thresholdDurationSeconds,
|
||||
cooldownMinutes: input.cooldownMinutes,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
})
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, alertRules, {
|
||||
userId: input.userId,
|
||||
hostId: input.hostId,
|
||||
name: input.name,
|
||||
enabled: input.enabled,
|
||||
triggerType: input.triggerType,
|
||||
thresholdValue: input.thresholdValue,
|
||||
thresholdDurationSeconds: input.thresholdDurationSeconds,
|
||||
cooldownMinutes: input.cooldownMinutes,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
});
|
||||
|
||||
const channels = await this.replaceRuleChannels(
|
||||
created.id,
|
||||
@@ -263,9 +262,10 @@ export class AlertRepository {
|
||||
now: string;
|
||||
},
|
||||
): Promise<AlertRuleWithChannelsRow | null> {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(alertRules)
|
||||
.set({
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
alertRules,
|
||||
{
|
||||
...(input.name !== undefined ? { name: input.name } : {}),
|
||||
...(input.hostId !== undefined ? { hostId: input.hostId } : {}),
|
||||
...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
|
||||
@@ -282,9 +282,9 @@ export class AlertRepository {
|
||||
? { cooldownMinutes: input.cooldownMinutes }
|
||||
: {}),
|
||||
updatedAt: input.now,
|
||||
})
|
||||
.where(and(eq(alertRules.id, id), eq(alertRules.userId, userId)))
|
||||
.returning();
|
||||
},
|
||||
and(eq(alertRules.id, id), eq(alertRules.userId, userId)),
|
||||
);
|
||||
|
||||
if (!updated) return null;
|
||||
|
||||
@@ -298,12 +298,11 @@ export class AlertRepository {
|
||||
}
|
||||
|
||||
async deleteAlertRule(id: number, userId: string): Promise<boolean> {
|
||||
const deleted = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(alertRules)
|
||||
.where(and(eq(alertRules.id, id), eq(alertRules.userId, userId)))
|
||||
.returning({ id: alertRules.id });
|
||||
.where(and(eq(alertRules.id, id), eq(alertRules.userId, userId)));
|
||||
|
||||
if (deleted.length === 0) return false;
|
||||
if (rowsAffected(result) === 0) return false;
|
||||
await this.afterWrite();
|
||||
return true;
|
||||
}
|
||||
@@ -411,12 +410,15 @@ export class AlertRepository {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
pruneFiringsOlderThan(userId: string, days: number): void {
|
||||
this.context.sqlite
|
||||
?.prepare(
|
||||
"DELETE FROM alert_firings WHERE user_id = ? AND fired_at < datetime('now', ?)",
|
||||
)
|
||||
.run(userId, `-${days} days`);
|
||||
async pruneFiringsOlderThan(userId: string, days: number): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(alertFirings)
|
||||
.where(
|
||||
and(
|
||||
eq(alertFirings.userId, userId),
|
||||
lt(alertFirings.firedAt, sqlTimestampDaysAgo(days)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<{
|
||||
@@ -438,10 +440,9 @@ export class AlertRepository {
|
||||
.where(eq(notificationChannels.userId, userId))
|
||||
).map((row) => row.id);
|
||||
|
||||
const firingRows = await this.context.drizzle
|
||||
const firingResult = await this.context.drizzle
|
||||
.delete(alertFirings)
|
||||
.where(eq(alertFirings.userId, userId))
|
||||
.returning({ id: alertFirings.id });
|
||||
.where(eq(alertFirings.userId, userId));
|
||||
|
||||
const linkFilters = [
|
||||
...(ruleIds.length > 0
|
||||
@@ -451,37 +452,34 @@ export class AlertRepository {
|
||||
? [inArray(alertRuleChannels.channelId, channelIds)]
|
||||
: []),
|
||||
];
|
||||
const linkRows =
|
||||
const linkResult =
|
||||
linkFilters.length === 0
|
||||
? []
|
||||
? null
|
||||
: await this.context.drizzle
|
||||
.delete(alertRuleChannels)
|
||||
.where(or(...linkFilters))
|
||||
.returning({ id: alertRuleChannels.id });
|
||||
.where(or(...linkFilters));
|
||||
|
||||
const ruleRows = await this.context.drizzle
|
||||
const ruleResult = await this.context.drizzle
|
||||
.delete(alertRules)
|
||||
.where(eq(alertRules.userId, userId))
|
||||
.returning({ id: alertRules.id });
|
||||
const channelRows = await this.context.drizzle
|
||||
.where(eq(alertRules.userId, userId));
|
||||
const result = await this.context.drizzle
|
||||
.delete(notificationChannels)
|
||||
.where(eq(notificationChannels.userId, userId))
|
||||
.returning({ id: notificationChannels.id });
|
||||
.where(eq(notificationChannels.userId, userId));
|
||||
|
||||
if (
|
||||
firingRows.length > 0 ||
|
||||
linkRows.length > 0 ||
|
||||
ruleRows.length > 0 ||
|
||||
channelRows.length > 0
|
||||
rowsAffected(firingResult) > 0 ||
|
||||
rowsAffected(linkResult) > 0 ||
|
||||
rowsAffected(ruleResult) > 0 ||
|
||||
rowsAffected(result) > 0
|
||||
) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return {
|
||||
firingsDeleted: firingRows.length,
|
||||
ruleLinksDeleted: linkRows.length,
|
||||
rulesDeleted: ruleRows.length,
|
||||
channelsDeleted: channelRows.length,
|
||||
firingsDeleted: rowsAffected(firingResult),
|
||||
ruleLinksDeleted: rowsAffected(linkResult),
|
||||
rulesDeleted: rowsAffected(ruleResult),
|
||||
channelsDeleted: rowsAffected(result),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { apiKeys, users } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { deleteReturning, insertReturning } from "./returning.js";
|
||||
|
||||
export type ApiKeyRecord = typeof apiKeys.$inferSelect;
|
||||
export type NewApiKeyRecord = typeof apiKeys.$inferInsert;
|
||||
@@ -24,10 +26,7 @@ export class ApiKeyRepository {
|
||||
) {}
|
||||
|
||||
async create(apiKey: NewApiKeyRecord): Promise<ApiKeyRecord> {
|
||||
const rows = await this.context.drizzle
|
||||
.insert(apiKeys)
|
||||
.values(apiKey)
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, apiKeys, apiKey);
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
}
|
||||
@@ -78,23 +77,23 @@ export class ApiKeyRepository {
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<ApiKeyRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.delete(apiKeys)
|
||||
.where(eq(apiKeys.id, id))
|
||||
.returning();
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
apiKeys,
|
||||
eq(apiKeys.id, id),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(apiKeys)
|
||||
.where(eq(apiKeys.userId, userId))
|
||||
.returning({ id: apiKeys.id });
|
||||
.where(eq(apiKeys.userId, userId));
|
||||
|
||||
await this.afterWrite();
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { and, asc, desc, eq, gte, inArray, lte, sql } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, gte, inArray, lt, lte, sql } from "drizzle-orm";
|
||||
import { auditLogs } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { sqlTimestampDaysAgo } from "./sql-timestamp.js";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { countValue, rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type AuditLogRecord = typeof auditLogs.$inferSelect;
|
||||
export type NewAuditLogRecord = typeof auditLogs.$inferInsert;
|
||||
@@ -19,8 +22,31 @@ export type AuditLogPage = {
|
||||
total: number;
|
||||
};
|
||||
|
||||
const PRUNE_MAX = 10000;
|
||||
const PRUNE_TARGET = 9000;
|
||||
export const AUDIT_RETENTION_DAYS_ENV = "AUDIT_LOG_RETENTION_DAYS";
|
||||
export const AUDIT_MAX_ENTRIES_ENV = "AUDIT_LOG_MAX_ENTRIES";
|
||||
|
||||
const DEFAULT_MAX_ENTRIES = 10000;
|
||||
const PRUNE_TARGET_RATIO = 0.9;
|
||||
|
||||
function positiveIntEnv(key: string, env: NodeJS.ProcessEnv): number | null {
|
||||
const raw = Number(env[key]);
|
||||
return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long entries are kept. Unset means "no time limit", in which case only
|
||||
* the row cap applies.
|
||||
*/
|
||||
export function auditRetentionDays(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): number | null {
|
||||
return positiveIntEnv(AUDIT_RETENTION_DAYS_ENV, env);
|
||||
}
|
||||
|
||||
/** Hard ceiling on stored entries, so a busy install cannot fill the disk. */
|
||||
export function auditMaxEntries(env: NodeJS.ProcessEnv = process.env): number {
|
||||
return positiveIntEnv(AUDIT_MAX_ENTRIES_ENV, env) ?? DEFAULT_MAX_ENTRIES;
|
||||
}
|
||||
|
||||
export class AuditLogRepository {
|
||||
constructor(
|
||||
@@ -57,10 +83,31 @@ export class AuditLogRepository {
|
||||
|
||||
return {
|
||||
logs,
|
||||
total: totalResult[0]?.count ?? 0,
|
||||
total: countValue(totalResult[0]?.count),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads matching entries in ascending time order for export.
|
||||
*
|
||||
* Paged rather than fetched whole so an export cannot pull an unbounded
|
||||
* result set into memory, and ascending so a resumed or appended export
|
||||
* continues where the previous one stopped.
|
||||
*/
|
||||
async listForExport(input: {
|
||||
filters: AuditLogFilters;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}): Promise<AuditLogRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(auditLogs)
|
||||
.where(this.buildWhere(input.filters))
|
||||
.orderBy(asc(auditLogs.timestamp), asc(auditLogs.id))
|
||||
.limit(input.limit)
|
||||
.offset(input.offset);
|
||||
}
|
||||
|
||||
async listDistinctActions(): Promise<string[]> {
|
||||
const rows = await this.context.drizzle
|
||||
.selectDistinct({ action: auditLogs.action })
|
||||
@@ -70,17 +117,38 @@ export class AuditLogRepository {
|
||||
return rows.map((row) => row.action);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
.delete(auditLogs)
|
||||
.where(eq(auditLogs.userId, userId))
|
||||
.returning({ id: auditLogs.id });
|
||||
/**
|
||||
* Detaches entries from a user being deleted instead of removing them.
|
||||
*
|
||||
* The schema already relaxed this foreign key to ON DELETE SET NULL, but the
|
||||
* account-deletion path deletes the rows explicitly, which undoes that. An
|
||||
* audit trail that vanishes with the account it recorded cannot answer the
|
||||
* question it exists for, and offboarding is exactly when that question gets
|
||||
* asked. `username` is denormalised, so the entry stays attributable.
|
||||
*/
|
||||
async anonymizeByUserId(userId: string): Promise<number> {
|
||||
const result = await this.context.drizzle
|
||||
.update(auditLogs)
|
||||
.set({ userId: null })
|
||||
.where(eq(auditLogs.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const result = await this.context.drizzle
|
||||
.delete(auditLogs)
|
||||
.where(eq(auditLogs.userId, userId));
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private buildWhere(filters: AuditLogFilters) {
|
||||
@@ -105,28 +173,73 @@ export class AuditLogRepository {
|
||||
}
|
||||
|
||||
private async pruneIfNeeded(): Promise<void> {
|
||||
await this.pruneExpired();
|
||||
await this.pruneOverflow();
|
||||
}
|
||||
|
||||
/** Drops entries past the configured retention window. */
|
||||
private async pruneExpired(): Promise<void> {
|
||||
const days = auditRetentionDays();
|
||||
if (days === null) return;
|
||||
|
||||
const cutoff = sqlTimestampDaysAgo(days);
|
||||
const result = await this.context.drizzle
|
||||
.delete(auditLogs)
|
||||
.where(lt(auditLogs.timestamp, cutoff));
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
databaseLogger.info(
|
||||
`Pruned ${rowsAffected(result)} audit entries past retention`,
|
||||
{
|
||||
operation: "audit_retention_prune",
|
||||
removed: rowsAffected(result),
|
||||
retentionDays: days,
|
||||
cutoff,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforces the row cap. Unlike retention this discards entries that are still
|
||||
* within the window, so it is reported as a warning: it means the ceiling is
|
||||
* too low for how much this install audits, and evidence is being lost.
|
||||
*/
|
||||
private async pruneOverflow(): Promise<void> {
|
||||
const max = auditMaxEntries();
|
||||
const countResult = await this.context.drizzle
|
||||
.select({ count: sql<number>`COUNT(*)` })
|
||||
.from(auditLogs);
|
||||
const count = countResult[0]?.count ?? 0;
|
||||
const count = countValue(countResult[0]?.count);
|
||||
|
||||
if (count < PRUNE_MAX) {
|
||||
return;
|
||||
}
|
||||
if (count < max) return;
|
||||
|
||||
const deleteCount = count - PRUNE_TARGET;
|
||||
const deleteCount = count - Math.floor(max * PRUNE_TARGET_RATIO);
|
||||
const rows = await this.context.drizzle
|
||||
.select({ id: auditLogs.id })
|
||||
.select({ id: auditLogs.id, timestamp: auditLogs.timestamp })
|
||||
.from(auditLogs)
|
||||
.orderBy(asc(auditLogs.timestamp))
|
||||
.limit(deleteCount);
|
||||
const ids = rows.map((row) => row.id);
|
||||
if (rows.length === 0) return;
|
||||
|
||||
if (ids.length > 0) {
|
||||
await this.context.drizzle
|
||||
.delete(auditLogs)
|
||||
.where(inArray(auditLogs.id, ids));
|
||||
}
|
||||
await this.context.drizzle.delete(auditLogs).where(
|
||||
inArray(
|
||||
auditLogs.id,
|
||||
rows.map((row) => row.id),
|
||||
),
|
||||
);
|
||||
|
||||
databaseLogger.warn(
|
||||
`Audit log hit its ${max}-entry cap; discarded ${rows.length} entries`,
|
||||
{
|
||||
operation: "audit_overflow_prune",
|
||||
removed: rows.length,
|
||||
maxEntries: max,
|
||||
oldestRemoved: rows[0]?.timestamp,
|
||||
newestRemoved: rows[rows.length - 1]?.timestamp,
|
||||
hint: `Raise ${AUDIT_MAX_ENTRIES_ENV}, or set ${AUDIT_RETENTION_DAYS_ENV} and export older entries before they are dropped.`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { c2sTunnelPresets } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning, updateReturning } from "./returning.js";
|
||||
|
||||
export type C2sTunnelPresetRecord = typeof c2sTunnelPresets.$inferSelect;
|
||||
|
||||
@@ -64,16 +66,13 @@ export class C2sTunnelPresetRepository {
|
||||
userId: string,
|
||||
input: C2sTunnelPresetCreateInput,
|
||||
): Promise<C2sTunnelPresetRecord> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(c2sTunnelPresets)
|
||||
.values({
|
||||
userId,
|
||||
name: input.name,
|
||||
config: input.config,
|
||||
platform: input.platform ?? null,
|
||||
computerName: input.computerName ?? null,
|
||||
})
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, c2sTunnelPresets, {
|
||||
userId,
|
||||
name: input.name,
|
||||
config: input.config,
|
||||
platform: input.platform ?? null,
|
||||
computerName: input.computerName ?? null,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
@@ -84,16 +83,15 @@ export class C2sTunnelPresetRepository {
|
||||
id: number,
|
||||
updates: C2sTunnelPresetUpdateInput,
|
||||
): Promise<C2sTunnelPresetRecord | null> {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(c2sTunnelPresets)
|
||||
.set({
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
c2sTunnelPresets,
|
||||
{
|
||||
...updates,
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
})
|
||||
.where(
|
||||
and(eq(c2sTunnelPresets.id, id), eq(c2sTunnelPresets.userId, userId)),
|
||||
)
|
||||
.returning();
|
||||
},
|
||||
and(eq(c2sTunnelPresets.id, id), eq(c2sTunnelPresets.userId, userId)),
|
||||
);
|
||||
|
||||
if (updated) {
|
||||
await this.afterWrite();
|
||||
@@ -103,31 +101,29 @@ export class C2sTunnelPresetRepository {
|
||||
}
|
||||
|
||||
async deleteForUser(userId: string, id: number): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(c2sTunnelPresets)
|
||||
.where(
|
||||
and(eq(c2sTunnelPresets.id, id), eq(c2sTunnelPresets.userId, userId)),
|
||||
)
|
||||
.returning({ id: c2sTunnelPresets.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(c2sTunnelPresets)
|
||||
.where(eq(c2sTunnelPresets.userId, userId))
|
||||
.returning({ id: c2sTunnelPresets.id });
|
||||
.where(eq(c2sTunnelPresets.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { commandHistory } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type CommandHistoryRecord = typeof commandHistory.$inferSelect;
|
||||
|
||||
@@ -16,10 +18,12 @@ export class CommandHistoryRepository {
|
||||
command: string,
|
||||
executedAt = new Date().toISOString(),
|
||||
): Promise<CommandHistoryRecord> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(commandHistory)
|
||||
.values({ userId, hostId, command, executedAt })
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, commandHistory, {
|
||||
userId,
|
||||
hostId,
|
||||
command,
|
||||
executedAt,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
@@ -76,7 +80,7 @@ export class CommandHistoryRepository {
|
||||
hostId: number,
|
||||
command: string,
|
||||
): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(commandHistory)
|
||||
.where(
|
||||
and(
|
||||
@@ -84,45 +88,42 @@ export class CommandHistoryRepository {
|
||||
eq(commandHistory.hostId, hostId),
|
||||
eq(commandHistory.command, command),
|
||||
),
|
||||
)
|
||||
.returning({ id: commandHistory.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserAndHost(userId: string, hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(commandHistory)
|
||||
.where(
|
||||
and(
|
||||
eq(commandHistory.userId, userId),
|
||||
eq(commandHistory.hostId, hostId),
|
||||
),
|
||||
)
|
||||
.returning({ id: commandHistory.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByHostId(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(commandHistory)
|
||||
.where(eq(commandHistory.hostId, hostId))
|
||||
.returning({ id: commandHistory.id });
|
||||
.where(eq(commandHistory.hostId, hostId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByHostIds(hostIds: number[]): Promise<number> {
|
||||
@@ -130,29 +131,27 @@ export class CommandHistoryRepository {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(commandHistory)
|
||||
.where(inArray(commandHistory.hostId, hostIds))
|
||||
.returning({ id: commandHistory.id });
|
||||
.where(inArray(commandHistory.hostId, hostIds));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(commandHistory)
|
||||
.where(eq(commandHistory.userId, userId))
|
||||
.returning({ id: commandHistory.id });
|
||||
.where(eq(commandHistory.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -3,6 +3,12 @@ import { randomUUID } from "crypto";
|
||||
import { sshCredentials, sshCredentialUsage } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type CredentialRecord = typeof sshCredentials.$inferSelect;
|
||||
export type NewCredentialRecord = typeof sshCredentials.$inferInsert;
|
||||
@@ -17,10 +23,10 @@ export class CredentialRepository {
|
||||
) {}
|
||||
|
||||
async create(credential: NewCredentialRecord): Promise<CredentialRecord> {
|
||||
const rows = await this.context.drizzle
|
||||
.insert(sshCredentials)
|
||||
.values({ syncId: randomUUID(), ...credential })
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, sshCredentials, {
|
||||
syncId: randomUUID(),
|
||||
...credential,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
}
|
||||
@@ -46,10 +52,11 @@ export class CredentialRepository {
|
||||
delete (encryptedCredential as Partial<NewCredentialRecord>).id;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.insert(sshCredentials)
|
||||
.values(encryptedCredential as NewCredentialRecord)
|
||||
.returning();
|
||||
const rows = await insertReturning(
|
||||
this.context,
|
||||
sshCredentials,
|
||||
encryptedCredential as NewCredentialRecord,
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return DataCrypto.decryptRecord(
|
||||
@@ -143,22 +150,21 @@ export class CredentialRepository {
|
||||
oldName: string,
|
||||
newName: string,
|
||||
): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(sshCredentials)
|
||||
.set({ folder: newName })
|
||||
.set({ folder: newName, updatedAt: sql`CURRENT_TIMESTAMP` })
|
||||
.where(
|
||||
and(
|
||||
eq(sshCredentials.userId, userId),
|
||||
eq(sshCredentials.folder, oldName),
|
||||
),
|
||||
)
|
||||
.returning({ id: sshCredentials.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async updateForUser(
|
||||
@@ -166,16 +172,15 @@ export class CredentialRepository {
|
||||
credentialId: number,
|
||||
update: CredentialUpdate,
|
||||
): Promise<CredentialRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.update(sshCredentials)
|
||||
.set(update)
|
||||
.where(
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const rows = await updateReturning(
|
||||
this.context,
|
||||
sshCredentials,
|
||||
{ ...update, updatedAt: sql`CURRENT_TIMESTAMP` },
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
@@ -193,16 +198,15 @@ export class CredentialRepository {
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.update(sshCredentials)
|
||||
.set(encryptedUpdate)
|
||||
.where(
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const rows = await updateReturning(
|
||||
this.context,
|
||||
sshCredentials,
|
||||
{ ...encryptedUpdate, updatedAt: sql`CURRENT_TIMESTAMP` },
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return this.decryptOne(rows[0] ?? null, userId);
|
||||
@@ -212,31 +216,29 @@ export class CredentialRepository {
|
||||
userId: string,
|
||||
credentialId: number,
|
||||
): Promise<{ syncId: string | null } | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.delete(sshCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning({ syncId: sshCredentials.syncId });
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
sshCredentials,
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
return rows[0] ? { syncId: rows[0].syncId } : null;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sshCredentials)
|
||||
.where(eq(sshCredentials.userId, userId))
|
||||
.returning({ id: sshCredentials.id });
|
||||
.where(eq(sshCredentials.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async recordUsage(
|
||||
|
||||
@@ -2,6 +2,12 @@ import { and, asc, eq } from "drizzle-orm";
|
||||
import { randomUUID } from "crypto";
|
||||
import { dashboardServiceLinks } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type DashboardServiceLinkRecord =
|
||||
typeof dashboardServiceLinks.$inferSelect;
|
||||
@@ -38,9 +44,10 @@ export class DashboardServiceLinkRepository {
|
||||
const nextOrder =
|
||||
existing.length > 0 ? existing[existing.length - 1].order + 1 : 0;
|
||||
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(dashboardServiceLinks)
|
||||
.values({
|
||||
const [created] = await insertReturning(
|
||||
this.context,
|
||||
dashboardServiceLinks,
|
||||
{
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
label: input.label,
|
||||
@@ -48,8 +55,8 @@ export class DashboardServiceLinkRepository {
|
||||
order: nextOrder,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
})
|
||||
.returning();
|
||||
},
|
||||
);
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
@@ -77,16 +84,15 @@ export class DashboardServiceLinkRepository {
|
||||
id: number,
|
||||
updates: DashboardServiceLinkUpdate,
|
||||
): Promise<DashboardServiceLinkRecord | null> {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(dashboardServiceLinks)
|
||||
.set({ ...updates, updatedAt: new Date().toISOString() })
|
||||
.where(
|
||||
and(
|
||||
eq(dashboardServiceLinks.id, id),
|
||||
eq(dashboardServiceLinks.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
dashboardServiceLinks,
|
||||
{ ...updates, updatedAt: new Date().toISOString() },
|
||||
and(
|
||||
eq(dashboardServiceLinks.id, id),
|
||||
eq(dashboardServiceLinks.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
if (updated) {
|
||||
await this.afterWrite();
|
||||
@@ -99,32 +105,30 @@ export class DashboardServiceLinkRepository {
|
||||
userId: string,
|
||||
id: number,
|
||||
): Promise<{ syncId: string | null } | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.delete(dashboardServiceLinks)
|
||||
.where(
|
||||
and(
|
||||
eq(dashboardServiceLinks.id, id),
|
||||
eq(dashboardServiceLinks.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning({ syncId: dashboardServiceLinks.syncId });
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
dashboardServiceLinks,
|
||||
and(
|
||||
eq(dashboardServiceLinks.id, id),
|
||||
eq(dashboardServiceLinks.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
return { syncId: rows[0].syncId };
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(dashboardServiceLinks)
|
||||
.where(eq(dashboardServiceLinks.userId, userId))
|
||||
.returning({ id: dashboardServiceLinks.id });
|
||||
.where(eq(dashboardServiceLinks.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,9 +1,41 @@
|
||||
import type { BetterSQLite3Database } from "drizzle-orm/better-sqlite3";
|
||||
import type { Database as BetterSqliteDatabase } from "better-sqlite3";
|
||||
import type * as schema from "../db/schema.js";
|
||||
|
||||
// Re-exported so repositories can keep importing it from here, but defined in
|
||||
// db/dialect.ts — a local copy that said "sqlite" survived here for a while and
|
||||
// typed every context as SQLite-only while the runtime already carried all
|
||||
// three, which silently made the dialect branches unreachable to the checker.
|
||||
export type { DatabaseDialect } from "../db/dialect.js";
|
||||
import type { DatabaseDialect } from "../db/dialect.js";
|
||||
|
||||
/**
|
||||
* The database handle repositories work against.
|
||||
*
|
||||
* Typed as the SQLite instance on purpose. drizzle's three Database classes
|
||||
* share no base class and their signatures are incompatible: a union is not
|
||||
* callable, and a generic would have to be threaded through all 43
|
||||
* repositories and every method on them.
|
||||
*
|
||||
* This is a deliberate approximation, not an accident. The query-builder
|
||||
* surface the repositories actually use is the same on all three engines, and
|
||||
* that equivalence is asserted in multi-dialect.test.ts rather than assumed —
|
||||
* identifier quoting, placeholder style and value coercion are all covered
|
||||
* there. At runtime this may hold a Postgres or MySQL instance.
|
||||
*
|
||||
* The one place the surfaces genuinely differ is RETURNING, which MySQL lacks;
|
||||
* see mutation-result.ts for how that is absorbed.
|
||||
*/
|
||||
export type PortableDatabase = BetterSQLite3Database<typeof schema>;
|
||||
|
||||
/**
|
||||
* What a repository is allowed to touch.
|
||||
*
|
||||
* Deliberately drizzle-only: with no raw driver handle here, no repository can
|
||||
* reach for engine-specific SQL. Retention queries that previously needed
|
||||
* `datetime('now', ?)` compute their cutoff in JS instead — see
|
||||
* ./sql-timestamp.ts.
|
||||
*/
|
||||
export interface DatabaseContext {
|
||||
dialect: "sqlite";
|
||||
drizzle: BetterSQLite3Database<typeof schema>;
|
||||
sqlite?: BetterSqliteDatabase;
|
||||
dialect: DatabaseDialect;
|
||||
drizzle: PortableDatabase;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { dismissedAlerts } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type DismissedAlertRecord = typeof dismissedAlerts.$inferSelect;
|
||||
|
||||
@@ -72,34 +73,32 @@ export class DismissedAlertRepository {
|
||||
}
|
||||
|
||||
async deleteForUser(userId: string, alertId: string): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(dismissedAlerts)
|
||||
.where(
|
||||
and(
|
||||
eq(dismissedAlerts.userId, userId),
|
||||
eq(dismissedAlerts.alertId, alertId),
|
||||
),
|
||||
)
|
||||
.returning({ id: dismissedAlerts.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(dismissedAlerts)
|
||||
.where(eq(dismissedAlerts.userId, userId))
|
||||
.returning({ id: dismissedAlerts.id });
|
||||
.where(eq(dismissedAlerts.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { DatabaseSaveTrigger } from "../../utils/database-save-trigger.js";
|
||||
import { getDb, getSqlite } from "../db/index.js";
|
||||
import { needsExplicitPersist, resolveDatabaseDialect } from "../db/dialect.js";
|
||||
import { primeSettingsCache, readCachedSetting } from "./settings-cache.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { WebauthnCredentialRepository } from "./webauthn-credential-repository.js";
|
||||
import { AlertRepository } from "./alert-repository.js";
|
||||
@@ -29,6 +31,7 @@ import { SessionRecordingRepository } from "./session-recording-repository.js";
|
||||
import { SessionRepository } from "./session-repository.js";
|
||||
import { SessionShareRepository } from "./session-share-repository.js";
|
||||
import { SettingsRepository } from "./settings-repository.js";
|
||||
import { SharedHostAuthOverrideRepository } from "./shared-host-auth-override-repository.js";
|
||||
import { SharedHostSecretsRepository } from "./shared-host-secrets-repository.js";
|
||||
import { SnippetRepository } from "./snippet-repository.js";
|
||||
import { SshCredentialUsageRepository } from "./ssh-credential-usage-repository.js";
|
||||
@@ -45,25 +48,62 @@ import { UserRepository } from "./user-repository.js";
|
||||
import { VaultProfileRepository } from "./vault-profile-repository.js";
|
||||
import { VaultTokenRepository } from "./vault-token-repository.js";
|
||||
|
||||
/**
|
||||
* The context every repository runs against.
|
||||
*
|
||||
* The dialect has to be resolved, not assumed: it is what `returning.ts` reads
|
||||
* to decide whether it can ask for RETURNING, and whether an upsert spells
|
||||
* itself `onConflictDoUpdate` or `onDuplicateKeyUpdate`. Reporting "sqlite"
|
||||
* while connected to MySQL makes the second of those a TypeError on the first
|
||||
* write.
|
||||
*
|
||||
* Both cross-dialect harnesses build a DatabaseContext themselves, so neither
|
||||
* exercises this function — see tests/database/repositories/factory-context.
|
||||
*/
|
||||
export function createCurrentRepositoryContext(): DatabaseContext {
|
||||
return {
|
||||
dialect: "sqlite",
|
||||
dialect: resolveDatabaseDialect(),
|
||||
drizzle: getDb(),
|
||||
sqlite: getSqlite(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Post-write hook handed to every repository.
|
||||
*
|
||||
* Only meaningful for SQLite, where the database lives in memory and has to be
|
||||
* serialised back to its encrypted file. On Postgres and MySQL the write is
|
||||
* already durable, so no hook is installed at all rather than one that does
|
||||
* nothing — repositories call it as `this.onWrite?.()`.
|
||||
*/
|
||||
export function createCurrentRepositoryWriteHook(
|
||||
reason: string,
|
||||
): () => Promise<void> {
|
||||
): (() => Promise<void>) | undefined {
|
||||
if (!needsExplicitPersist(resolveDatabaseDialect())) return undefined;
|
||||
return () => DatabaseSaveTrigger.forceSave(reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw driver handle for the few synchronous call sites that cannot await —
|
||||
* getCurrentSettingValue below, and settings reads during startup. Repositories
|
||||
* must not use this: they take a DatabaseContext, which is drizzle-only.
|
||||
* Porting to another engine means giving these callers an async path first.
|
||||
*/
|
||||
export function getCurrentRepositorySqlite() {
|
||||
return getSqlite();
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous settings read.
|
||||
*
|
||||
* SQLite can be queried synchronously, so it is read directly and stays
|
||||
* authoritative. Other engines have no synchronous query, so the value comes
|
||||
* from the cache primed at startup and kept current by SettingsRepository.
|
||||
*/
|
||||
export function getCurrentSettingValue(key: string): string | null {
|
||||
if (!needsExplicitPersist(resolveDatabaseDialect())) {
|
||||
return readCachedSetting(key);
|
||||
}
|
||||
|
||||
const row = getCurrentRepositorySqlite()
|
||||
.prepare("SELECT value FROM settings WHERE key = ?")
|
||||
.get(key) as { value?: string } | undefined;
|
||||
@@ -283,6 +323,15 @@ export function createCurrentSharedHostSecretsRepository(): SharedHostSecretsRep
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentSharedHostAuthOverrideRepository(): SharedHostAuthOverrideRepository {
|
||||
return new SharedHostAuthOverrideRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook(
|
||||
"shared_host_auth_override_repository_write",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentSnippetRepository(): SnippetRepository {
|
||||
return new SnippetRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
@@ -370,3 +419,69 @@ export function createCurrentVaultTokenRepository(): VaultTokenRepository {
|
||||
createCurrentRepositoryWriteHook("vault_token_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the settings cache. Must run during startup on engines without a
|
||||
* synchronous read, before anything calls getCurrentSettingValue.
|
||||
*/
|
||||
export async function primeCurrentSettingsCache(): Promise<void> {
|
||||
const rows = await createCurrentSettingsRepository().listAll();
|
||||
primeSettingsCache(rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* How often a replica re-reads the settings table.
|
||||
*
|
||||
* Override with SETTINGS_CACHE_REFRESH_SECONDS; 0 disables the refresh.
|
||||
*/
|
||||
const REFRESH_SECONDS_ENV = "SETTINGS_CACHE_REFRESH_SECONDS";
|
||||
const DEFAULT_REFRESH_SECONDS = 30;
|
||||
|
||||
let refreshTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
/**
|
||||
* Keeps the settings cache from drifting on a multi-replica deployment.
|
||||
*
|
||||
* The cache is per-process and updated in the process that writes. That is
|
||||
* enough for SQLite, where there is only ever one process. On Postgres and
|
||||
* MySQL — which exist here precisely so more than one instance can share the
|
||||
* data — a setting changed on one replica would otherwise never reach the
|
||||
* others, because the synchronous read has no way to go back to the database.
|
||||
*
|
||||
* Periodic re-priming does not make the value immediately consistent. It bounds
|
||||
* how long it can be wrong, which is the difference between a setting that
|
||||
* takes effect on the next tick and one that takes effect at the next restart.
|
||||
*/
|
||||
export function startSettingsCacheRefresh(
|
||||
env = process.env,
|
||||
refresh: () => Promise<void> = primeCurrentSettingsCache,
|
||||
): void {
|
||||
if (refreshTimer) return;
|
||||
|
||||
const seconds = refreshIntervalSeconds(env);
|
||||
if (seconds === null) return;
|
||||
|
||||
refreshTimer = setInterval(() => {
|
||||
void refresh().catch(() => {
|
||||
// A failed refresh leaves the previous values in place, which is the
|
||||
// right outcome: a transient database blip should not blank the cache.
|
||||
// Every caller reads a missing setting as "use the default", so an empty
|
||||
// cache would silently revert configuration across the deployment.
|
||||
});
|
||||
}, seconds * 1000);
|
||||
|
||||
refreshTimer.unref();
|
||||
}
|
||||
|
||||
/** The configured interval, or null when refreshing is switched off. */
|
||||
export function refreshIntervalSeconds(env = process.env): number | null {
|
||||
const seconds = Number(env[REFRESH_SECONDS_ENV] ?? DEFAULT_REFRESH_SECONDS);
|
||||
return Number.isFinite(seconds) && seconds > 0 ? seconds : null;
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function stopSettingsCacheRefresh(): void {
|
||||
if (!refreshTimer) return;
|
||||
clearInterval(refreshTimer);
|
||||
refreshTimer = null;
|
||||
}
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
import { FieldCrypto } from "../../utils/field-crypto.js";
|
||||
import { LazyFieldEncryption } from "../../utils/lazy-field-encryption.js";
|
||||
|
||||
const FIELD_ENCRYPTION_POLICY = {
|
||||
users: {
|
||||
sensitive: new Set([
|
||||
"passwordHash",
|
||||
"clientSecret",
|
||||
"totpSecret",
|
||||
"totpBackupCodes",
|
||||
"oidcIdentifier",
|
||||
]),
|
||||
plaintext: new Set(["id", "username", "isAdmin", "isOidc"]),
|
||||
},
|
||||
ssh_data: {
|
||||
sensitive: new Set([
|
||||
"password",
|
||||
"key",
|
||||
"keyPassword",
|
||||
"sudoPassword",
|
||||
"autostartPassword",
|
||||
"autostartKey",
|
||||
"autostartKeyPassword",
|
||||
"socks5Password",
|
||||
"rdpPassword",
|
||||
"vncPassword",
|
||||
"telnetPassword",
|
||||
]),
|
||||
plaintext: new Set([
|
||||
"id",
|
||||
"userId",
|
||||
"connectionType",
|
||||
"name",
|
||||
"ip",
|
||||
"port",
|
||||
"username",
|
||||
"folder",
|
||||
"tags",
|
||||
"authType",
|
||||
"credentialId",
|
||||
]),
|
||||
},
|
||||
ssh_credentials: {
|
||||
sensitive: new Set([
|
||||
"password",
|
||||
"key",
|
||||
"privateKey",
|
||||
"publicKey",
|
||||
"keyPassword",
|
||||
]),
|
||||
plaintext: new Set([
|
||||
"id",
|
||||
"userId",
|
||||
"name",
|
||||
"description",
|
||||
"folder",
|
||||
"tags",
|
||||
"authType",
|
||||
"username",
|
||||
"keyType",
|
||||
"detectedKeyType",
|
||||
"usageCount",
|
||||
"lastUsed",
|
||||
]),
|
||||
},
|
||||
opkssh_tokens: {
|
||||
sensitive: new Set(["sshCert", "privateKey"]),
|
||||
plaintext: new Set(["id", "userId", "hostId", "createdAt", "expiresAt"]),
|
||||
},
|
||||
termix_identity_ca: {
|
||||
sensitive: new Set(["privateKey"]),
|
||||
plaintext: new Set(["id", "publicKey", "createdAt", "updatedAt"]),
|
||||
},
|
||||
vault_tokens: {
|
||||
sensitive: new Set(["sshCert", "privateKey"]),
|
||||
plaintext: new Set(["id", "userId", "profileId", "expiresAt"]),
|
||||
},
|
||||
} as const;
|
||||
|
||||
type PolicyTable = keyof typeof FIELD_ENCRYPTION_POLICY;
|
||||
export type FieldClassification = "sensitive" | "plaintext" | "unknown";
|
||||
|
||||
export class FieldEncryptionBoundary {
|
||||
static classifyField(
|
||||
tableName: string,
|
||||
fieldName: string,
|
||||
): FieldClassification {
|
||||
const policy = this.getPolicy(tableName);
|
||||
if (!policy) return "unknown";
|
||||
if (policy.sensitive.has(fieldName)) return "sensitive";
|
||||
if (policy.plaintext.has(fieldName)) return "plaintext";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
static getSensitiveFields(tableName: string): string[] {
|
||||
const policy = this.getPolicy(tableName);
|
||||
return policy ? [...policy.sensitive].sort() : [];
|
||||
}
|
||||
|
||||
static encryptRecord<T extends Record<string, unknown>>(
|
||||
tableName: string,
|
||||
record: T,
|
||||
userDataKey: Buffer,
|
||||
recordId = record.id,
|
||||
): T {
|
||||
const id = this.requireRecordId(recordId);
|
||||
const encryptedRecord: Record<string, unknown> = { ...record };
|
||||
|
||||
for (const fieldName of this.getSensitiveFields(tableName)) {
|
||||
const value = encryptedRecord[fieldName];
|
||||
if (typeof value === "string" && value) {
|
||||
encryptedRecord[fieldName] = FieldCrypto.encryptField(
|
||||
value,
|
||||
userDataKey,
|
||||
id,
|
||||
fieldName,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return encryptedRecord as T;
|
||||
}
|
||||
|
||||
static decryptRecord<T extends Record<string, unknown>>(
|
||||
tableName: string,
|
||||
record: T,
|
||||
userDataKey: Buffer,
|
||||
recordId = record.id,
|
||||
): T {
|
||||
const id = this.requireRecordId(recordId);
|
||||
const decryptedRecord: Record<string, unknown> = { ...record };
|
||||
|
||||
for (const fieldName of this.getSensitiveFields(tableName)) {
|
||||
const value = decryptedRecord[fieldName];
|
||||
if (typeof value === "string" && value) {
|
||||
decryptedRecord[fieldName] = LazyFieldEncryption.safeGetFieldValue(
|
||||
value,
|
||||
userDataKey,
|
||||
id,
|
||||
fieldName,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return decryptedRecord as T;
|
||||
}
|
||||
|
||||
private static getPolicy(tableName: string) {
|
||||
return FIELD_ENCRYPTION_POLICY[tableName as PolicyTable];
|
||||
}
|
||||
|
||||
private static requireRecordId(recordId: unknown): string {
|
||||
if (recordId === null || recordId === undefined || recordId === "") {
|
||||
throw new Error("Field encryption requires a stable record id.");
|
||||
}
|
||||
return String(recordId);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
fileManagerShortcuts,
|
||||
} from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type FileManagerRecentRecord = typeof fileManagerRecent.$inferSelect;
|
||||
export type FileManagerPinnedRecord = typeof fileManagerPinned.$inferSelect;
|
||||
@@ -112,7 +113,7 @@ export class FileManagerBookmarkRepository {
|
||||
userId: string,
|
||||
input: Pick<FileManagerBookmarkInput, "hostId" | "path">,
|
||||
): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerRecent)
|
||||
.where(
|
||||
and(
|
||||
@@ -120,14 +121,13 @@ export class FileManagerBookmarkRepository {
|
||||
eq(fileManagerRecent.hostId, input.hostId),
|
||||
eq(fileManagerRecent.path, input.path),
|
||||
),
|
||||
)
|
||||
.returning({ id: fileManagerRecent.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async listPinnedForHost(
|
||||
@@ -199,7 +199,7 @@ export class FileManagerBookmarkRepository {
|
||||
userId: string,
|
||||
input: Pick<FileManagerBookmarkInput, "hostId" | "path">,
|
||||
): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerPinned)
|
||||
.where(
|
||||
and(
|
||||
@@ -207,14 +207,13 @@ export class FileManagerBookmarkRepository {
|
||||
eq(fileManagerPinned.hostId, input.hostId),
|
||||
eq(fileManagerPinned.path, input.path),
|
||||
),
|
||||
)
|
||||
.returning({ id: fileManagerPinned.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async listShortcutsForHost(
|
||||
@@ -288,7 +287,7 @@ export class FileManagerBookmarkRepository {
|
||||
userId: string,
|
||||
input: Pick<FileManagerBookmarkInput, "hostId" | "path">,
|
||||
): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerShortcuts)
|
||||
.where(
|
||||
and(
|
||||
@@ -296,14 +295,13 @@ export class FileManagerBookmarkRepository {
|
||||
eq(fileManagerShortcuts.hostId, input.hostId),
|
||||
eq(fileManagerShortcuts.path, input.path),
|
||||
),
|
||||
)
|
||||
.returning({ id: fileManagerShortcuts.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
@@ -456,75 +454,66 @@ export class FileManagerBookmarkRepository {
|
||||
}
|
||||
|
||||
private async deleteRecentByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerRecent)
|
||||
.where(eq(fileManagerRecent.userId, userId))
|
||||
.returning({ id: fileManagerRecent.id });
|
||||
return rows.length;
|
||||
.where(eq(fileManagerRecent.userId, userId));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deletePinnedByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerPinned)
|
||||
.where(eq(fileManagerPinned.userId, userId))
|
||||
.returning({ id: fileManagerPinned.id });
|
||||
return rows.length;
|
||||
.where(eq(fileManagerPinned.userId, userId));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deleteShortcutsByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerShortcuts)
|
||||
.where(eq(fileManagerShortcuts.userId, userId))
|
||||
.returning({ id: fileManagerShortcuts.id });
|
||||
return rows.length;
|
||||
.where(eq(fileManagerShortcuts.userId, userId));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deleteRecentByHostId(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerRecent)
|
||||
.where(eq(fileManagerRecent.hostId, hostId))
|
||||
.returning({ id: fileManagerRecent.id });
|
||||
return rows.length;
|
||||
.where(eq(fileManagerRecent.hostId, hostId));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deletePinnedByHostId(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerPinned)
|
||||
.where(eq(fileManagerPinned.hostId, hostId))
|
||||
.returning({ id: fileManagerPinned.id });
|
||||
return rows.length;
|
||||
.where(eq(fileManagerPinned.hostId, hostId));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deleteShortcutsByHostId(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerShortcuts)
|
||||
.where(eq(fileManagerShortcuts.hostId, hostId))
|
||||
.returning({ id: fileManagerShortcuts.id });
|
||||
return rows.length;
|
||||
.where(eq(fileManagerShortcuts.hostId, hostId));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deleteRecentByHostIds(hostIds: number[]): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerRecent)
|
||||
.where(inArray(fileManagerRecent.hostId, hostIds))
|
||||
.returning({ id: fileManagerRecent.id });
|
||||
return rows.length;
|
||||
.where(inArray(fileManagerRecent.hostId, hostIds));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deletePinnedByHostIds(hostIds: number[]): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerPinned)
|
||||
.where(inArray(fileManagerPinned.hostId, hostIds))
|
||||
.returning({ id: fileManagerPinned.id });
|
||||
return rows.length;
|
||||
.where(inArray(fileManagerPinned.hostId, hostIds));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async deleteShortcutsByHostIds(hostIds: number[]): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(fileManagerShortcuts)
|
||||
.where(inArray(fileManagerShortcuts.hostId, hostIds))
|
||||
.returning({ id: fileManagerShortcuts.id });
|
||||
return rows.length;
|
||||
.where(inArray(fileManagerShortcuts.hostId, hostIds));
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -2,6 +2,12 @@ import { and, asc, eq } from "drizzle-orm";
|
||||
import { randomUUID } from "crypto";
|
||||
import { homepageItems } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type HomepageItemRecord = typeof homepageItems.$inferSelect;
|
||||
|
||||
@@ -35,18 +41,15 @@ export class HomepageItemRepository {
|
||||
input: HomepageItemCreateInput,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<HomepageItemRecord> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(homepageItems)
|
||||
.values({
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
typeId: input.typeId,
|
||||
title: input.title,
|
||||
config: input.config,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, homepageItems, {
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
typeId: input.typeId,
|
||||
title: input.title,
|
||||
config: input.config,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
@@ -71,11 +74,12 @@ export class HomepageItemRepository {
|
||||
updates: HomepageItemUpdateInput,
|
||||
updatedAt = new Date().toISOString(),
|
||||
): Promise<HomepageItemRecord | null> {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(homepageItems)
|
||||
.set({ ...updates, updatedAt })
|
||||
.where(and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)))
|
||||
.returning();
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
homepageItems,
|
||||
{ ...updates, updatedAt },
|
||||
and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)),
|
||||
);
|
||||
|
||||
if (updated) {
|
||||
await this.afterWrite();
|
||||
@@ -88,27 +92,27 @@ export class HomepageItemRepository {
|
||||
userId: string,
|
||||
id: number,
|
||||
): Promise<{ syncId: string | null } | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.delete(homepageItems)
|
||||
.where(and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)))
|
||||
.returning({ syncId: homepageItems.syncId });
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
homepageItems,
|
||||
and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)),
|
||||
);
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
return { syncId: rows[0].syncId };
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(homepageItems)
|
||||
.where(eq(homepageItems.userId, userId))
|
||||
.returning({ id: homepageItems.id });
|
||||
.where(eq(homepageItems.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { homepageLayouts } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning, updateReturning } from "./returning.js";
|
||||
|
||||
export type HomepageLayoutRecord = typeof homepageLayouts.$inferSelect;
|
||||
|
||||
@@ -28,34 +30,35 @@ export class HomepageLayoutRepository {
|
||||
const existing = await this.findByUserId(userId);
|
||||
|
||||
if (!existing) {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(homepageLayouts)
|
||||
.values({ userId, layout, updatedAt })
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, homepageLayouts, {
|
||||
userId,
|
||||
layout,
|
||||
updatedAt,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(homepageLayouts)
|
||||
.set({ layout, updatedAt })
|
||||
.where(eq(homepageLayouts.userId, userId))
|
||||
.returning();
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
homepageLayouts,
|
||||
{ layout, updatedAt },
|
||||
eq(homepageLayouts.userId, userId),
|
||||
);
|
||||
await this.afterWrite();
|
||||
return updated;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(homepageLayouts)
|
||||
.where(eq(homepageLayouts.userId, userId))
|
||||
.returning({ id: homepageLayouts.id });
|
||||
.where(eq(homepageLayouts.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -3,6 +3,12 @@ import { randomUUID } from "crypto";
|
||||
import type { SQLiteColumn } from "drizzle-orm/sqlite-core";
|
||||
import { hosts, sshCredentials, sshFolders } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type HostFolderRecord = typeof sshFolders.$inferSelect;
|
||||
export type HostFolderHostRecord = typeof hosts.$inferSelect;
|
||||
@@ -24,19 +30,31 @@ export class HostFolderRepository {
|
||||
newName: string,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<RenameFolderResult> {
|
||||
// CAST target: every engine spells the text type differently enough to
|
||||
// matter here — MySQL has no `text` cast and wants `char`.
|
||||
const textType = this.context.dialect === "mysql" ? "char" : "text";
|
||||
const oldPrefix = `${oldName} / `;
|
||||
const newPrefix = `${newName} / `;
|
||||
const childLike = `${oldPrefix}%`;
|
||||
// CONCAT, not `||`: MySQL reads `||` as logical OR unless the server runs
|
||||
// with PIPES_AS_CONCAT, so the child paths would have been rewritten to 0.
|
||||
// No error, just wrong folder names. CONCAT and SUBSTR mean the same thing
|
||||
// on all three engines.
|
||||
//
|
||||
// The prefix is inlined rather than bound: CONCAT is variadic, so Postgres
|
||||
// cannot infer a parameter's type from its position and rejects the
|
||||
// statement with 42P18 before it runs. The value is a folder name the
|
||||
// caller supplied, so it goes through a bound placeholder in a plain
|
||||
// concatenation instead of sql.raw.
|
||||
const renameExpr = (col: SQLiteColumn) =>
|
||||
sql`CASE WHEN ${col} = ${oldName} THEN ${newName} ELSE ${newPrefix} || substr(${col}, ${oldPrefix.length + 1}) END`;
|
||||
sql`CASE WHEN ${col} = ${oldName} THEN ${newName} ELSE CONCAT(CAST(${newPrefix} AS ${sql.raw(textType)}), SUBSTR(${col}, ${sql.raw(String(oldPrefix.length + 1))})) END`;
|
||||
const folderMatch = (col: SQLiteColumn) =>
|
||||
or(eq(col, oldName), like(col, childLike));
|
||||
|
||||
const updatedHosts = await this.context.drizzle
|
||||
.update(hosts)
|
||||
.set({ folder: renameExpr(hosts.folder), updatedAt: now })
|
||||
.where(and(eq(hosts.userId, userId), folderMatch(hosts.folder)))
|
||||
.returning({ id: hosts.id });
|
||||
.where(and(eq(hosts.userId, userId), folderMatch(hosts.folder)));
|
||||
|
||||
const updatedCredentials = await this.context.drizzle
|
||||
.update(sshCredentials)
|
||||
@@ -46,8 +64,7 @@ export class HostFolderRepository {
|
||||
eq(sshCredentials.userId, userId),
|
||||
folderMatch(sshCredentials.folder),
|
||||
),
|
||||
)
|
||||
.returning({ id: sshCredentials.id });
|
||||
);
|
||||
|
||||
await this.context.drizzle
|
||||
.update(sshFolders)
|
||||
@@ -56,8 +73,8 @@ export class HostFolderRepository {
|
||||
|
||||
await this.afterWrite();
|
||||
return {
|
||||
updatedHosts: updatedHosts.length,
|
||||
updatedCredentials: updatedCredentials.length,
|
||||
updatedHosts: rowsAffected(updatedHosts),
|
||||
updatedCredentials: rowsAffected(updatedCredentials),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -78,35 +95,33 @@ export class HostFolderRepository {
|
||||
): Promise<{ folder: HostFolderRecord; created: boolean }> {
|
||||
const existing = await this.findFolder(userId, name);
|
||||
if (existing) {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(sshFolders)
|
||||
.set({
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
sshFolders,
|
||||
{
|
||||
color,
|
||||
icon,
|
||||
credentialId:
|
||||
credentialId === undefined ? existing.credentialId : credentialId,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)))
|
||||
.returning();
|
||||
},
|
||||
and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return { folder: updated, created: false };
|
||||
}
|
||||
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(sshFolders)
|
||||
.values({
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name,
|
||||
color,
|
||||
icon,
|
||||
credentialId: credentialId ?? null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, sshFolders, {
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name,
|
||||
color,
|
||||
icon,
|
||||
credentialId: credentialId ?? null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return { folder: created, created: true };
|
||||
@@ -139,10 +154,11 @@ export class HostFolderRepository {
|
||||
.where(and(eq(hosts.userId, userId), folderMatch(hosts.folder)));
|
||||
}
|
||||
|
||||
const deletedFolders = await this.context.drizzle
|
||||
.delete(sshFolders)
|
||||
.where(and(eq(sshFolders.userId, userId), folderMatch(sshFolders.name)))
|
||||
.returning({ syncId: sshFolders.syncId });
|
||||
const deletedFolders = await deleteReturning(
|
||||
this.context,
|
||||
sshFolders,
|
||||
and(eq(sshFolders.userId, userId), folderMatch(sshFolders.name)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
|
||||
@@ -157,16 +173,15 @@ export class HostFolderRepository {
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sshFolders)
|
||||
.where(eq(sshFolders.userId, userId))
|
||||
.returning({ id: sshFolders.id });
|
||||
.where(eq(sshFolders.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async findFolder(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { and, desc, eq, notInArray } from "drizzle-orm";
|
||||
import { hostHealthChecks, hostHealthHistory } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning, updateReturning } from "./returning.js";
|
||||
|
||||
export type HostHealthCheckRecord = typeof hostHealthChecks.$inferSelect;
|
||||
export type HostHealthHistoryRecord = typeof hostHealthHistory.$inferSelect;
|
||||
@@ -45,27 +47,25 @@ export class HostHealthRepository {
|
||||
): Promise<HostHealthCheckRecord> {
|
||||
const existing = await this.findChecksByUserAndHost(userId, hostId);
|
||||
if (existing) {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(hostHealthChecks)
|
||||
.set({ checks, intervalSeconds, updatedAt: now })
|
||||
.where(eq(hostHealthChecks.id, existing.id))
|
||||
.returning();
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
hostHealthChecks,
|
||||
{ checks, intervalSeconds, updatedAt: now },
|
||||
eq(hostHealthChecks.id, existing.id),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return updated;
|
||||
}
|
||||
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(hostHealthChecks)
|
||||
.values({
|
||||
userId,
|
||||
hostId,
|
||||
checks,
|
||||
intervalSeconds,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, hostHealthChecks, {
|
||||
userId,
|
||||
hostId,
|
||||
checks,
|
||||
intervalSeconds,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
@@ -94,7 +94,7 @@ export class HostHealthRepository {
|
||||
})),
|
||||
);
|
||||
|
||||
this.pruneHistory(userId, hostId, keep);
|
||||
await this.pruneHistory(userId, hostId, keep);
|
||||
await this.afterWrite();
|
||||
return results.length;
|
||||
}
|
||||
@@ -121,41 +121,55 @@ export class HostHealthRepository {
|
||||
checksDeleted: number;
|
||||
historyDeleted: number;
|
||||
}> {
|
||||
const historyRows = await this.context.drizzle
|
||||
const historyResult = await this.context.drizzle
|
||||
.delete(hostHealthHistory)
|
||||
.where(eq(hostHealthHistory.userId, userId))
|
||||
.returning({ id: hostHealthHistory.id });
|
||||
.where(eq(hostHealthHistory.userId, userId));
|
||||
|
||||
const checkRows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostHealthChecks)
|
||||
.where(eq(hostHealthChecks.userId, userId))
|
||||
.returning({ id: hostHealthChecks.id });
|
||||
.where(eq(hostHealthChecks.userId, userId));
|
||||
|
||||
if (historyRows.length > 0 || checkRows.length > 0) {
|
||||
if (rowsAffected(historyResult) > 0 || rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return {
|
||||
checksDeleted: checkRows.length,
|
||||
historyDeleted: historyRows.length,
|
||||
checksDeleted: rowsAffected(result),
|
||||
historyDeleted: rowsAffected(historyResult),
|
||||
};
|
||||
}
|
||||
|
||||
private pruneHistory(userId: string, hostId: number, keep: number): void {
|
||||
this.context.sqlite
|
||||
?.prepare(
|
||||
`DELETE FROM host_health_history
|
||||
WHERE id IN (
|
||||
SELECT id FROM host_health_history
|
||||
WHERE user_id = ? AND host_id = ?
|
||||
AND id NOT IN (
|
||||
SELECT id FROM host_health_history
|
||||
WHERE user_id = ? AND host_id = ?
|
||||
ORDER BY ts DESC LIMIT ?
|
||||
)
|
||||
)`,
|
||||
)
|
||||
.run(userId, hostId, userId, hostId, keep);
|
||||
/** Keeps the newest `keep` rows for the host and drops the rest. */
|
||||
private async pruneHistory(
|
||||
userId: string,
|
||||
hostId: number,
|
||||
keep: number,
|
||||
): Promise<void> {
|
||||
const scope = and(
|
||||
eq(hostHealthHistory.userId, userId),
|
||||
eq(hostHealthHistory.hostId, hostId),
|
||||
);
|
||||
|
||||
const retained = await this.context.drizzle
|
||||
.select({ id: hostHealthHistory.id })
|
||||
.from(hostHealthHistory)
|
||||
.where(scope)
|
||||
.orderBy(desc(hostHealthHistory.ts))
|
||||
.limit(keep);
|
||||
|
||||
// Nothing retained means nothing to keep back, so the scope alone is the
|
||||
// delete condition.
|
||||
await this.context.drizzle.delete(hostHealthHistory).where(
|
||||
retained.length
|
||||
? and(
|
||||
scope,
|
||||
notInArray(
|
||||
hostHealthHistory.id,
|
||||
retained.map((row) => row.id),
|
||||
),
|
||||
)
|
||||
: scope,
|
||||
);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { and, asc, eq, gte, lte } from "drizzle-orm";
|
||||
import { and, asc, eq, gte, lt, lte } from "drizzle-orm";
|
||||
import { hostMetricsHistory } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { sqlTimestampDaysAgo } from "./sql-timestamp.js";
|
||||
|
||||
export type HostMetricsHistoryRecord = typeof hostMetricsHistory.$inferSelect;
|
||||
|
||||
@@ -32,12 +33,15 @@ export class HostMetricsHistoryRepository {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
pruneOlderThan(hostId: number, retentionDays: number): void {
|
||||
this.context.sqlite
|
||||
?.prepare(
|
||||
"DELETE FROM host_metrics_history WHERE host_id = ? AND ts < datetime('now', ?)",
|
||||
)
|
||||
.run(hostId, `-${retentionDays} days`);
|
||||
async pruneOlderThan(hostId: number, retentionDays: number): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(hostMetricsHistory)
|
||||
.where(
|
||||
and(
|
||||
eq(hostMetricsHistory.hostId, hostId),
|
||||
lt(hostMetricsHistory.ts, sqlTimestampDaysAgo(retentionDays)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async listRange(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { hostMetricsPreferences, hosts } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning, updateReturning } from "./returning.js";
|
||||
|
||||
export type HostMetricsPreferenceRecord =
|
||||
typeof hostMetricsPreferences.$inferSelect;
|
||||
@@ -37,26 +39,28 @@ export class HostMetricsPreferenceRepository {
|
||||
): Promise<HostMetricsPreferenceRecord> {
|
||||
const existing = await this.findByUserAndHost(userId, hostId);
|
||||
if (existing) {
|
||||
const [updated] = await this.context.drizzle
|
||||
.update(hostMetricsPreferences)
|
||||
.set({ layout, updatedAt: now })
|
||||
.where(eq(hostMetricsPreferences.id, existing.id))
|
||||
.returning();
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
hostMetricsPreferences,
|
||||
{ layout, updatedAt: now },
|
||||
eq(hostMetricsPreferences.id, existing.id),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return updated;
|
||||
}
|
||||
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(hostMetricsPreferences)
|
||||
.values({
|
||||
const [created] = await insertReturning(
|
||||
this.context,
|
||||
hostMetricsPreferences,
|
||||
{
|
||||
userId,
|
||||
hostId,
|
||||
layout,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning();
|
||||
},
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
@@ -67,28 +71,26 @@ export class HostMetricsPreferenceRepository {
|
||||
hostId: number,
|
||||
statsConfig: string,
|
||||
): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(hosts)
|
||||
.set({ statsConfig })
|
||||
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
|
||||
.returning({ id: hosts.id });
|
||||
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)));
|
||||
|
||||
if (rows.length === 0) return false;
|
||||
if (rowsAffected(result) === 0) return false;
|
||||
await this.afterWrite();
|
||||
return true;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostMetricsPreferences)
|
||||
.where(eq(hostMetricsPreferences.userId, userId))
|
||||
.returning({ id: hostMetricsPreferences.id });
|
||||
.where(eq(hostMetricsPreferences.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { randomUUID } from "crypto";
|
||||
import { hostAccess, hosts } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type HostRecord = typeof hosts.$inferSelect;
|
||||
export type NewHostRecord = typeof hosts.$inferInsert;
|
||||
@@ -21,10 +27,10 @@ export class HostRepository {
|
||||
) {}
|
||||
|
||||
async create(host: NewHostRecord): Promise<HostRecord> {
|
||||
const rows = await this.context.drizzle
|
||||
.insert(hosts)
|
||||
.values({ syncId: randomUUID(), ...host })
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, hosts, {
|
||||
syncId: randomUUID(),
|
||||
...host,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
}
|
||||
@@ -51,10 +57,11 @@ export class HostRepository {
|
||||
delete (encryptedHost as Partial<NewHostRecord>).id;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.insert(hosts)
|
||||
.values(encryptedHost as NewHostRecord)
|
||||
.returning();
|
||||
const rows = await insertReturning(
|
||||
this.context,
|
||||
hosts,
|
||||
encryptedHost as NewHostRecord,
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return DataCrypto.decryptRecord("ssh_data", rows[0], userId, userDataKey);
|
||||
@@ -150,11 +157,12 @@ export class HostRepository {
|
||||
hostId: number,
|
||||
update: HostUpdate,
|
||||
): Promise<HostRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.update(hosts)
|
||||
.set(update)
|
||||
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
|
||||
.returning();
|
||||
const rows = await updateReturning(
|
||||
this.context,
|
||||
hosts,
|
||||
{ ...update, updatedAt: sql`CURRENT_TIMESTAMP` },
|
||||
and(eq(hosts.id, hostId), eq(hosts.userId, userId)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
@@ -173,11 +181,12 @@ export class HostRepository {
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.update(hosts)
|
||||
.set(encryptedUpdate)
|
||||
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
|
||||
.returning();
|
||||
const rows = await updateReturning(
|
||||
this.context,
|
||||
hosts,
|
||||
{ ...encryptedUpdate, updatedAt: sql`CURRENT_TIMESTAMP` },
|
||||
and(eq(hosts.id, hostId), eq(hosts.userId, userId)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0]
|
||||
@@ -213,17 +222,16 @@ export class HostRepository {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(hosts)
|
||||
.set(update)
|
||||
.where(and(inArray(hosts.id, hostIds), eq(hosts.userId, userId)))
|
||||
.returning({ id: hosts.id });
|
||||
.set({ ...update, updatedAt: sql`CURRENT_TIMESTAMP` })
|
||||
.where(and(inArray(hosts.id, hostIds), eq(hosts.userId, userId)));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteForUser(
|
||||
@@ -232,39 +240,38 @@ export class HostRepository {
|
||||
): Promise<{ syncId: string | null } | null> {
|
||||
await this.deleteAccessForHost(hostId);
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.delete(hosts)
|
||||
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
|
||||
.returning({ syncId: hosts.syncId });
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
hosts,
|
||||
and(eq(hosts.id, hostId), eq(hosts.userId, userId)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
return rows[0] ? { syncId: rows[0].syncId } : null;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hosts)
|
||||
.where(eq(hosts.userId, userId))
|
||||
.returning({ id: hosts.id });
|
||||
.where(eq(hosts.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteAccessForHost(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
.where(eq(hostAccess.hostId, hostId))
|
||||
.returning({ id: hostAccess.id });
|
||||
.where(eq(hostAccess.hostId, hostId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { and, eq, inArray, isNotNull } from "drizzle-orm";
|
||||
import { hostAccess, hosts, sshCredentials, sshFolders } from "../db/schema.js";
|
||||
import { hosts, sshCredentials, sshFolders } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
|
||||
@@ -26,6 +26,28 @@ export interface HostListAccessEntry {
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
const HOST_PERMISSION_RANK: Record<string, number> = {
|
||||
connect: 1,
|
||||
view: 2,
|
||||
edit: 3,
|
||||
manage: 4,
|
||||
};
|
||||
|
||||
function preferHostAccess(
|
||||
current: HostListAccessEntry,
|
||||
candidate: HostListAccessEntry,
|
||||
): HostListAccessEntry {
|
||||
const currentRank = HOST_PERMISSION_RANK[current.permissionLevel] ?? 0;
|
||||
const candidateRank = HOST_PERMISSION_RANK[candidate.permissionLevel] ?? 0;
|
||||
if (candidateRank !== currentRank) {
|
||||
return candidateRank > currentRank ? candidate : current;
|
||||
}
|
||||
if (current.expiresAt === null) return current;
|
||||
if (candidate.expiresAt === null) return candidate;
|
||||
return candidate.expiresAt > current.expiresAt ? candidate : current;
|
||||
}
|
||||
|
||||
export type HostListRow = HostResolutionHostRecord & {
|
||||
ownerId: string;
|
||||
isShared: boolean;
|
||||
@@ -103,9 +125,15 @@ export class HostResolutionRepository {
|
||||
.from(hosts)
|
||||
.where(eq(hosts.userId, userId));
|
||||
|
||||
const sharedHostIds = Array.from(
|
||||
new Set(accessEntries.map((access) => access.hostId)),
|
||||
);
|
||||
const accessByHostId = new Map<number, HostListAccessEntry>();
|
||||
for (const access of accessEntries) {
|
||||
const current = accessByHostId.get(access.hostId);
|
||||
accessByHostId.set(
|
||||
access.hostId,
|
||||
current ? preferHostAccess(current, access) : access,
|
||||
);
|
||||
}
|
||||
const sharedHostIds = Array.from(accessByHostId.keys());
|
||||
const sharedHostRows =
|
||||
sharedHostIds.length > 0
|
||||
? await this.context.drizzle
|
||||
@@ -125,7 +153,7 @@ export class HostResolutionRepository {
|
||||
permissionLevel: undefined,
|
||||
expiresAt: undefined,
|
||||
})),
|
||||
...accessEntries.flatMap((access) => {
|
||||
...Array.from(accessByHostId.values()).flatMap((access) => {
|
||||
const host = sharedHostsById.get(access.hostId);
|
||||
if (!host || host.userId === userId) {
|
||||
return [];
|
||||
@@ -302,19 +330,6 @@ export class HostResolutionRepository {
|
||||
return this.decryptOne("ssh_credentials", rows[0], decryptUserId);
|
||||
}
|
||||
|
||||
async findOverrideCredentialId(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
): Promise<number | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({ overrideCredentialId: hostAccess.overrideCredentialId })
|
||||
.from(hostAccess)
|
||||
.where(and(eq(hostAccess.hostId, hostId), eq(hostAccess.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
return rows[0]?.overrideCredentialId ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the nearest assigned credential for a folder path, walking up
|
||||
* through parent folders (e.g. "Switches / Floor1" falls back to
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { DatabaseDialect } from "../db/dialect.js";
|
||||
|
||||
/**
|
||||
* Reading the outcome of a write without depending on RETURNING.
|
||||
*
|
||||
* SQLite and Postgres can attach `.returning()` to a delete or update and get
|
||||
* the affected rows back. **MySQL cannot** — it has no RETURNING clause, and
|
||||
* drizzle's mysql-core does not expose the method at all, so the call is a
|
||||
* TypeError rather than a bad query. 175 call sites here read a write's result,
|
||||
* so the difference has to be absorbed somewhere.
|
||||
*
|
||||
* The split that matters is what the caller actually needs:
|
||||
*
|
||||
* - **How many rows changed** — the majority, and none of them need the rows.
|
||||
* They used to ask for them anyway, via `.returning().length`. Dropping the
|
||||
* `.returning()` and reading the driver's own count is both portable and one
|
||||
* less thing for the database to send back.
|
||||
* - **The rows themselves** — cannot be emulated on MySQL without reading
|
||||
* first, which needs a transaction to stay correct under concurrency. Those
|
||||
* call sites are handled individually rather than behind a helper that hides
|
||||
* an extra round trip.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The count each driver reports for a write, under its own name.
|
||||
*
|
||||
* Every engine says how many rows a write touched. None of them agree on what
|
||||
* to call it:
|
||||
*
|
||||
* | driver | shape |
|
||||
* |----------------|----------------------------------------|
|
||||
* | better-sqlite3 | `{ changes, lastInsertRowid }` |
|
||||
* | node-postgres | `{ rowCount, rows, command }` |
|
||||
* | mysql2 | `[{ affectedRows, insertId }, fields]` |
|
||||
*
|
||||
* These are the shapes returned when NO `.returning()` is attached — which is
|
||||
* the portable way to write, since MySQL has no RETURNING clause at all.
|
||||
*/
|
||||
interface WriteHeader {
|
||||
changes?: number;
|
||||
rowCount?: number;
|
||||
affectedRows?: number;
|
||||
lastInsertRowid?: number | bigint;
|
||||
insertId?: number;
|
||||
}
|
||||
|
||||
const COUNT_FIELDS = ["changes", "rowCount", "affectedRows"] as const;
|
||||
|
||||
/**
|
||||
* mysql2 hands back `[ResultSetHeader, fields]`, which is itself an array — so
|
||||
* "is it an array" cannot distinguish a write header from a returning() result.
|
||||
* The header is identified by carrying one of the fields above instead.
|
||||
*/
|
||||
function asWriteHeader(result: unknown): WriteHeader | null {
|
||||
const candidate =
|
||||
Array.isArray(result) && result.length > 0 ? result[0] : result;
|
||||
|
||||
if (!candidate || typeof candidate !== "object") return null;
|
||||
const header = candidate as WriteHeader;
|
||||
|
||||
const known =
|
||||
COUNT_FIELDS.some((field) => typeof header[field] === "number") ||
|
||||
typeof header.insertId === "number" ||
|
||||
typeof header.lastInsertRowid === "number" ||
|
||||
typeof header.lastInsertRowid === "bigint";
|
||||
|
||||
return known ? header : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of rows a write touched.
|
||||
*
|
||||
* Pass the result of the write itself — every driver's header is understood, so
|
||||
* the caller neither branches on the dialect nor attaches `.returning()` just to
|
||||
* count what came back.
|
||||
*
|
||||
* A `.returning()` array is still accepted, for the call sites that need the
|
||||
* rows for their own reasons and would rather not count them twice.
|
||||
*/
|
||||
export function rowsAffected(result: unknown): number {
|
||||
const header = asWriteHeader(result);
|
||||
if (header) {
|
||||
for (const field of COUNT_FIELDS) {
|
||||
const count = header[field];
|
||||
if (typeof count === "number") return count;
|
||||
}
|
||||
// A header with only insertId: one row went in.
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (Array.isArray(result)) return result.length;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Id assigned by an insert.
|
||||
*
|
||||
* **Only meaningful on the result of an insert.** SQLite's `lastInsertRowid` and
|
||||
* MySQL's `insertId` are connection-level values that survive the statement that
|
||||
* set them — after a delete, SQLite still reports whatever the last insert
|
||||
* produced. Passing an update or delete result here gets a stale id, not null.
|
||||
*
|
||||
* Returns null when the table has no autoincrement key.
|
||||
*/
|
||||
export function insertedId(result: unknown): number | null {
|
||||
const header = asWriteHeader(result);
|
||||
if (header) {
|
||||
// MySQL and SQLite both use 0 for "no autoincrement column".
|
||||
if (typeof header.insertId === "number") {
|
||||
return header.insertId > 0 ? header.insertId : null;
|
||||
}
|
||||
if (typeof header.lastInsertRowid === "bigint") {
|
||||
return header.lastInsertRowid > 0n
|
||||
? Number(header.lastInsertRowid)
|
||||
: null;
|
||||
}
|
||||
if (typeof header.lastInsertRowid === "number") {
|
||||
return header.lastInsertRowid > 0 ? header.lastInsertRowid : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Array.isArray(result)) {
|
||||
const first = result[0] as { id?: unknown } | undefined;
|
||||
return typeof first?.id === "number" ? first.id : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `.returning()` can be attached to a write on this engine.
|
||||
*
|
||||
* Call sites that genuinely need the affected rows use this to choose between
|
||||
* one statement and a read-then-write inside a transaction.
|
||||
*/
|
||||
export function supportsReturning(dialect: DatabaseDialect): boolean {
|
||||
return dialect !== "mysql";
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an aggregate count as a number.
|
||||
*
|
||||
* `sql<number>` is a type assertion, not a conversion. Postgres returns COUNT()
|
||||
* as bigint, which node-postgres hands back as a **string** so that values past
|
||||
* 2^53 survive — so the annotation is a lie there and comparisons like
|
||||
* `count < max` compare a string to a number.
|
||||
*/
|
||||
export function countValue(value: unknown): number {
|
||||
if (typeof value === "number") return value;
|
||||
if (typeof value === "bigint") return Number(value);
|
||||
if (typeof value === "string") {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { networkTopology } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type NetworkTopologyRecord = typeof networkTopology.$inferSelect;
|
||||
|
||||
@@ -45,16 +46,15 @@ export class NetworkTopologyRepository {
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(networkTopology)
|
||||
.where(eq(networkTopology.userId, userId))
|
||||
.returning({ id: networkTopology.id });
|
||||
.where(eq(networkTopology.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { and, eq, gt } from "drizzle-orm";
|
||||
import { userOpenTabs } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type OpenTabRecord = typeof userOpenTabs.$inferSelect;
|
||||
export type NewOpenTabRecord = typeof userOpenTabs.$inferInsert;
|
||||
@@ -111,43 +112,40 @@ export class OpenTabRepository {
|
||||
update: OpenTabUpdate,
|
||||
updatedAt = new Date().toISOString(),
|
||||
): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(userOpenTabs)
|
||||
.set({ ...update, updatedAt })
|
||||
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
|
||||
.returning({ id: userOpenTabs.id });
|
||||
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteForUser(userId: string, id: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(userOpenTabs)
|
||||
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
|
||||
.returning({ id: userOpenTabs.id });
|
||||
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(userOpenTabs)
|
||||
.where(eq(userOpenTabs.userId, userId))
|
||||
.returning({ id: userOpenTabs.id });
|
||||
.where(eq(userOpenTabs.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async findByIdForUser(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { opksshTokens } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { upsert } from "./returning.js";
|
||||
|
||||
export type OpksshTokenRecord = typeof opksshTokens.$inferSelect;
|
||||
|
||||
@@ -26,9 +28,10 @@ export class OpksshTokenRepository {
|
||||
async upsert(input: OpksshTokenUpsertInput): Promise<void> {
|
||||
const createdAt = input.createdAt ?? new Date().toISOString();
|
||||
|
||||
await this.context.drizzle
|
||||
.insert(opksshTokens)
|
||||
.values({
|
||||
await upsert(
|
||||
this.context,
|
||||
opksshTokens,
|
||||
{
|
||||
userId: input.userId,
|
||||
hostId: input.hostId,
|
||||
sshCert: input.sshCert,
|
||||
@@ -38,8 +41,8 @@ export class OpksshTokenRepository {
|
||||
issuer: input.issuer,
|
||||
audience: input.audience,
|
||||
expiresAt: input.expiresAt,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
},
|
||||
{
|
||||
target: [opksshTokens.userId, opksshTokens.hostId],
|
||||
set: {
|
||||
sshCert: input.sshCert,
|
||||
@@ -51,7 +54,8 @@ export class OpksshTokenRepository {
|
||||
expiresAt: input.expiresAt,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
}
|
||||
@@ -76,47 +80,44 @@ export class OpksshTokenRepository {
|
||||
hostId: number,
|
||||
lastUsed = new Date().toISOString(),
|
||||
): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(opksshTokens)
|
||||
.set({ lastUsed })
|
||||
.where(
|
||||
and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
|
||||
)
|
||||
.returning({ id: opksshTokens.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteByUserAndHost(userId: string, hostId: number): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(opksshTokens)
|
||||
.where(
|
||||
and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
|
||||
)
|
||||
.returning({ id: opksshTokens.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(opksshTokens)
|
||||
.where(eq(opksshTokens.userId, userId))
|
||||
.returning({ id: opksshTokens.id });
|
||||
.where(eq(opksshTokens.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
users,
|
||||
} from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type RbacAccessTargetType = "user" | "role";
|
||||
|
||||
@@ -156,7 +158,7 @@ export class RbacAccessRepository {
|
||||
return { id: existing.id, created: false };
|
||||
}
|
||||
|
||||
const result = await this.context.drizzle.insert(hostAccess).values({
|
||||
const [created] = await insertReturning(this.context, hostAccess, {
|
||||
hostId: input.hostId,
|
||||
userId: input.targetType === "user" ? input.targetUserId : null,
|
||||
roleId: input.targetType === "role" ? input.targetRoleId : null,
|
||||
@@ -166,7 +168,7 @@ export class RbacAccessRepository {
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return { id: Number(result.lastInsertRowid), created: true };
|
||||
return { id: created.id, created: true };
|
||||
}
|
||||
|
||||
async revokeHostAccess(accessId: number, hostId: number): Promise<void> {
|
||||
@@ -177,16 +179,15 @@ export class RbacAccessRepository {
|
||||
}
|
||||
|
||||
async deleteHostAccessForHost(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
.where(eq(hostAccess.hostId, hostId))
|
||||
.returning({ id: hostAccess.id });
|
||||
.where(eq(hostAccess.hostId, hostId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteHostAccessForHosts(hostIds: number[]): Promise<number> {
|
||||
@@ -194,30 +195,27 @@ export class RbacAccessRepository {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
.where(inArray(hostAccess.hostId, hostIds))
|
||||
.returning({ id: hostAccess.id });
|
||||
.where(inArray(hostAccess.hostId, hostIds));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteHostAccessForUserReferences(userId: string): Promise<number> {
|
||||
const directRows = await this.context.drizzle
|
||||
const directResult = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
.where(eq(hostAccess.userId, userId))
|
||||
.returning({ id: hostAccess.id });
|
||||
.where(eq(hostAccess.userId, userId));
|
||||
|
||||
const grantedRows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
.where(eq(hostAccess.grantedBy, userId))
|
||||
.returning({ id: hostAccess.id });
|
||||
.where(eq(hostAccess.grantedBy, userId));
|
||||
|
||||
const deletedCount = directRows.length + grantedRows.length;
|
||||
const deletedCount = rowsAffected(directResult) + rowsAffected(result);
|
||||
if (deletedCount > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
@@ -238,17 +236,6 @@ export class RbacAccessRepository {
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async updateHostAccessOverrideCredential(
|
||||
accessId: number,
|
||||
credentialId: number | null,
|
||||
): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(hostAccess)
|
||||
.set({ overrideCredentialId: credentialId })
|
||||
.where(eq(hostAccess.id, accessId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async listSnippetAccess(snippetId: number): Promise<RbacAccessListItem[]> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({
|
||||
@@ -291,7 +278,7 @@ export class RbacAccessRepository {
|
||||
return { id: existing.id, created: false };
|
||||
}
|
||||
|
||||
const result = await this.context.drizzle.insert(snippetAccess).values({
|
||||
const [created] = await insertReturning(this.context, snippetAccess, {
|
||||
snippetId: input.snippetId,
|
||||
userId: input.targetType === "user" ? input.targetUserId : null,
|
||||
roleId: input.targetType === "role" ? input.targetRoleId : null,
|
||||
@@ -301,7 +288,7 @@ export class RbacAccessRepository {
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return { id: Number(result.lastInsertRowid), created: true };
|
||||
return { id: created.id, created: true };
|
||||
}
|
||||
|
||||
async revokeSnippetAccess(
|
||||
@@ -512,21 +499,20 @@ export class RbacAccessRepository {
|
||||
async deleteExpiredHostAccess(
|
||||
now = new Date().toISOString(),
|
||||
): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
.where(
|
||||
and(
|
||||
sql`${hostAccess.expiresAt} IS NOT NULL`,
|
||||
sql`${hostAccess.expiresAt} <= ${now}`,
|
||||
),
|
||||
)
|
||||
.returning({ id: hostAccess.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async findActiveHostAccess(
|
||||
@@ -635,17 +621,16 @@ export class RbacAccessRepository {
|
||||
hostId: number,
|
||||
update: { permissionLevel?: string; expiresAt?: string | null },
|
||||
): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(hostAccess)
|
||||
.set(update)
|
||||
.where(and(eq(hostAccess.id, accessId), eq(hostAccess.hostId, hostId)))
|
||||
.returning({ id: hostAccess.id });
|
||||
.where(and(eq(hostAccess.id, accessId), eq(hostAccess.hostId, hostId)));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async findHostAccessOwnerId(hostAccessId: number): Promise<string | null> {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { desc, eq, inArray } from "drizzle-orm";
|
||||
import { recentActivity } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type RecentActivityRecord = typeof recentActivity.$inferSelect;
|
||||
export type NewRecentActivityRecord = typeof recentActivity.$inferInsert;
|
||||
@@ -26,10 +28,7 @@ export class RecentActivityRepository {
|
||||
async create(
|
||||
activity: NewRecentActivityRecord,
|
||||
): Promise<RecentActivityRecord> {
|
||||
const rows = await this.context.drizzle
|
||||
.insert(recentActivity)
|
||||
.values(activity)
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, recentActivity, activity);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
@@ -51,42 +50,39 @@ export class RecentActivityRepository {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const deletedRows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(recentActivity)
|
||||
.where(inArray(recentActivity.id, idsToDelete))
|
||||
.returning({ id: recentActivity.id });
|
||||
.where(inArray(recentActivity.id, idsToDelete));
|
||||
|
||||
if (deletedRows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return deletedRows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(recentActivity)
|
||||
.where(eq(recentActivity.userId, userId))
|
||||
.returning({ id: recentActivity.id });
|
||||
.where(eq(recentActivity.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByHostId(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(recentActivity)
|
||||
.where(eq(recentActivity.hostId, hostId))
|
||||
.returning({ id: recentActivity.id });
|
||||
.where(eq(recentActivity.hostId, hostId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByHostIds(hostIds: number[]): Promise<number> {
|
||||
@@ -94,16 +90,15 @@ export class RecentActivityRepository {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(recentActivity)
|
||||
.where(inArray(recentActivity.hostId, hostIds))
|
||||
.returning({ id: recentActivity.id });
|
||||
.where(inArray(recentActivity.hostId, hostIds));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
import { eq, type SQL } from "drizzle-orm";
|
||||
import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import {
|
||||
insertedId,
|
||||
rowsAffected,
|
||||
supportsReturning,
|
||||
} from "./mutation-result.js";
|
||||
|
||||
/**
|
||||
* Writes that need the affected rows back.
|
||||
*
|
||||
* `mutation-result.ts` covers the call sites that only wanted a count. These are
|
||||
* the ones that genuinely read the rows — an updated record to return to the
|
||||
* caller, a deleted row's fields to clean up alongside it.
|
||||
*
|
||||
* SQLite and Postgres do this in one statement with RETURNING. MySQL has no
|
||||
* such clause, so the read is a second statement, and the pair has to be atomic:
|
||||
*
|
||||
* - **insert** — write, then read the row back by its key.
|
||||
* - **update** — write, then read. Reading first would return the old values.
|
||||
* - **delete** — read, then write. Reading after would return nothing.
|
||||
*
|
||||
* Both run in a transaction. Without one, a concurrent write between the two
|
||||
* statements makes the returned rows describe a state that never existed, and
|
||||
* with a connection pool the second statement might not even reach the same
|
||||
* connection.
|
||||
*
|
||||
* ## The trap, and why it cannot bite silently
|
||||
*
|
||||
* On MySQL the update path re-reads using the same `where`. If the update
|
||||
* changes a column that `where` tests, the read finds nothing — SQLite would
|
||||
* have returned the row. Every current caller filters on an id it does not
|
||||
* modify, but that is a convention, not a guarantee, so the mismatch is
|
||||
* detected and thrown rather than returned as an empty array. Same for an
|
||||
* insert whose row cannot be read back.
|
||||
*
|
||||
* Row types come from the table, so call sites keep the typing they had with
|
||||
* `.returning()` and nothing has to be annotated by hand.
|
||||
*/
|
||||
|
||||
/**
|
||||
* What `.set()` accepts: a column's own type, or a SQL expression in its place —
|
||||
* `updatedAt: sql`CURRENT_TIMESTAMP`` is the common one here.
|
||||
*/
|
||||
type UpdateValues<T extends SQLiteTable> = {
|
||||
[K in keyof T["$inferInsert"]]?: T["$inferInsert"][K] | SQL;
|
||||
};
|
||||
|
||||
export async function updateReturning<T extends SQLiteTable>(
|
||||
context: DatabaseContext,
|
||||
table: T,
|
||||
values: UpdateValues<T>,
|
||||
where: SQL,
|
||||
): Promise<T["$inferSelect"][]> {
|
||||
const db = context.drizzle;
|
||||
|
||||
if (supportsReturning(context.dialect)) {
|
||||
// The cast resolves a conditional in drizzle's return type that TypeScript
|
||||
// cannot narrow while T is still generic. The runtime shape is the rows.
|
||||
return db.update(table).set(values).where(where).returning() as Promise<
|
||||
T["$inferSelect"][]
|
||||
>;
|
||||
}
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const written = await tx.update(table).set(values).where(where);
|
||||
const rows = await tx.select().from(table).where(where);
|
||||
|
||||
// The trap this catches: if the update changed a column that `where` tests,
|
||||
// the read finds nothing and the caller gets [] — on MySQL only, with no
|
||||
// error, where SQLite would have returned the row. Rows changed but none
|
||||
// readable back is exactly that case, so make it loud instead.
|
||||
if (rows.length === 0 && rowsAffected(written) > 0) {
|
||||
throw new Error(
|
||||
`updateReturning wrote ${rowsAffected(written)} row(s) but could not read ` +
|
||||
`them back: the update changed a column the where clause filters on. ` +
|
||||
`Read the rows first, or filter on a column the update leaves alone.`,
|
||||
);
|
||||
}
|
||||
|
||||
return rows;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteReturning<T extends SQLiteTable>(
|
||||
context: DatabaseContext,
|
||||
table: T,
|
||||
where: SQL,
|
||||
): Promise<T["$inferSelect"][]> {
|
||||
const db = context.drizzle;
|
||||
|
||||
if (supportsReturning(context.dialect)) {
|
||||
return db.delete(table).where(where).returning() as Promise<
|
||||
T["$inferSelect"][]
|
||||
>;
|
||||
}
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const rows = await tx.select().from(table).where(where);
|
||||
await tx.delete(table).where(where);
|
||||
return rows;
|
||||
});
|
||||
}
|
||||
|
||||
/** A table this can read a single row back from. */
|
||||
type Keyed = SQLiteTable & { id: SQLiteColumn };
|
||||
|
||||
/**
|
||||
* Inserts one row and returns it as stored, including whatever the database
|
||||
* filled in — defaults, an autoincrement id, a CURRENT_TIMESTAMP.
|
||||
*
|
||||
* This is the one case Postgres cannot shortcut either: without RETURNING there
|
||||
* is no id to read back by. Hence the split is genuinely three-way — except
|
||||
* that sqlite and pg both have RETURNING, so it collapses to two again.
|
||||
*
|
||||
* On MySQL the key comes from one of two places:
|
||||
*
|
||||
* - the caller supplied it (tables keyed by a text id, like `users`)
|
||||
* - the engine assigned it, reported as `insertId`
|
||||
*
|
||||
* Restricted to tables with an `id` column, so a table keyed some other way is
|
||||
* a compile error here rather than a row that silently fails to come back.
|
||||
*/
|
||||
export async function insertReturning<T extends Keyed>(
|
||||
context: DatabaseContext,
|
||||
table: T,
|
||||
values: T["$inferInsert"],
|
||||
): Promise<T["$inferSelect"][]> {
|
||||
const db = context.drizzle;
|
||||
|
||||
if (supportsReturning(context.dialect)) {
|
||||
return db.insert(table).values(values).returning() as Promise<
|
||||
T["$inferSelect"][]
|
||||
>;
|
||||
}
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const result = await tx.insert(table).values(values);
|
||||
|
||||
const supplied = (values as { id?: string | number }).id;
|
||||
const key = supplied ?? insertedId(result);
|
||||
if (key === null || key === undefined) {
|
||||
throw new Error(
|
||||
`Insert into ${String(table)} returned no id to read the row back by.`,
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await tx.select().from(table).where(eq(table.id, key));
|
||||
if (rows.length === 0) {
|
||||
throw new Error(
|
||||
`Inserted into ${String(table)} but could not read the row back by id ${key}.`,
|
||||
);
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts one row into a table keyed by something other than `id`, reading it
|
||||
* back by an explicit condition.
|
||||
*
|
||||
* `user_preferences` is keyed by `userId` and has no `id` column at all, so
|
||||
* there is no insertId to read back by — the caller has to say what identifies
|
||||
* the row it just wrote.
|
||||
*/
|
||||
export async function insertReturningWhere<T extends SQLiteTable>(
|
||||
context: DatabaseContext,
|
||||
table: T,
|
||||
values: T["$inferInsert"],
|
||||
where: SQL,
|
||||
): Promise<T["$inferSelect"][]> {
|
||||
const db = context.drizzle;
|
||||
|
||||
if (supportsReturning(context.dialect)) {
|
||||
return db.insert(table).values(values).returning() as Promise<
|
||||
T["$inferSelect"][]
|
||||
>;
|
||||
}
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.insert(table).values(values);
|
||||
const rows = await tx.select().from(table).where(where);
|
||||
if (rows.length === 0) {
|
||||
throw new Error(
|
||||
`Inserted into ${String(table)} but the read-back condition matched nothing.`,
|
||||
);
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert, or update the row that collides with it.
|
||||
*
|
||||
* The clause has three spellings. SQLite and Postgres take
|
||||
* `ON CONFLICT (cols) DO UPDATE`; **MySQL takes `ON DUPLICATE KEY UPDATE` and
|
||||
* names no columns** — it uses whichever unique key was violated. drizzle
|
||||
* follows suit, so `onConflictDoUpdate` does not exist on mysql-core at all and
|
||||
* calling it is a TypeError rather than a rejected query.
|
||||
*
|
||||
* The conflict target still has to be passed: it is what SQLite and Postgres
|
||||
* need, and stating it keeps the caller honest about which unique constraint it
|
||||
* is relying on — four of those were missing from the schema entirely until the
|
||||
* cross-dialect tests went looking.
|
||||
*/
|
||||
export async function upsert<T extends SQLiteTable>(
|
||||
context: DatabaseContext,
|
||||
table: T,
|
||||
values: T["$inferInsert"],
|
||||
conflict: { target: SQLiteColumn[]; set: UpdateValues<T> },
|
||||
): Promise<void> {
|
||||
const db = context.drizzle;
|
||||
|
||||
if (context.dialect === "mysql") {
|
||||
const insert = db.insert(table).values(values) as unknown as {
|
||||
onDuplicateKeyUpdate: (config: { set: UpdateValues<T> }) => Promise<void>;
|
||||
};
|
||||
await insert.onDuplicateKeyUpdate({ set: conflict.set });
|
||||
return;
|
||||
}
|
||||
|
||||
await db
|
||||
.insert(table)
|
||||
.values(values)
|
||||
.onConflictDoUpdate({ target: conflict.target, set: conflict.set });
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { hostAccess, roles, userRoles } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { deleteReturning, insertReturning } from "./returning.js";
|
||||
|
||||
export type RoleRecord = typeof roles.$inferSelect;
|
||||
export type NewRoleRecord = typeof roles.$inferInsert;
|
||||
@@ -62,27 +64,27 @@ export class RoleRepository {
|
||||
}
|
||||
|
||||
async createRole(role: NewRoleRecord): Promise<number> {
|
||||
const result = await this.context.drizzle.insert(roles).values(role);
|
||||
const [created] = await insertReturning(this.context, roles, role);
|
||||
await this.afterWrite();
|
||||
return Number(result.lastInsertRowid);
|
||||
return created.id;
|
||||
}
|
||||
|
||||
async updateRole(id: number, update: RoleUpdate): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(roles)
|
||||
.set(update)
|
||||
.where(eq(roles.id, id))
|
||||
.returning({ id: roles.id });
|
||||
.where(eq(roles.id, id));
|
||||
|
||||
await this.afterWrite();
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteRole(id: number): Promise<{ deletedUserIds: string[] }> {
|
||||
const deletedUserRoles = await this.context.drizzle
|
||||
.delete(userRoles)
|
||||
.where(eq(userRoles.roleId, id))
|
||||
.returning({ userId: userRoles.userId });
|
||||
const deletedUserRoles = await deleteReturning(
|
||||
this.context,
|
||||
userRoles,
|
||||
eq(userRoles.roleId, id),
|
||||
);
|
||||
|
||||
await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
@@ -169,16 +171,15 @@ export class RoleRepository {
|
||||
}
|
||||
|
||||
if (removeRole) {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(userRoles)
|
||||
.where(
|
||||
and(
|
||||
eq(userRoles.userId, input.userId),
|
||||
eq(userRoles.roleId, removeRole.id),
|
||||
),
|
||||
)
|
||||
.returning({ id: userRoles.id });
|
||||
removed = rows.length > 0;
|
||||
);
|
||||
removed = rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
if (added || removed) {
|
||||
@@ -196,16 +197,15 @@ export class RoleRepository {
|
||||
}
|
||||
|
||||
async removeAllRolesFromUser(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(userRoles)
|
||||
.where(eq(userRoles.userId, userId))
|
||||
.returning({ id: userRoles.id });
|
||||
.where(eq(userRoles.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async listUserRoleIds(userId: string): Promise<number[]> {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, desc, eq, inArray, lt } from "drizzle-orm";
|
||||
import { hosts, sessionRecordings } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type SessionRecordingRecord = typeof sessionRecordings.$inferSelect;
|
||||
|
||||
@@ -47,10 +49,11 @@ export class SessionRecordingRepository {
|
||||
async create(
|
||||
input: SessionRecordingCreateInput,
|
||||
): Promise<SessionRecordingRecord> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(sessionRecordings)
|
||||
.values(input)
|
||||
.returning();
|
||||
const [created] = await insertReturning(
|
||||
this.context,
|
||||
sessionRecordings,
|
||||
input,
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
@@ -170,57 +173,71 @@ export class SessionRecordingRepository {
|
||||
}
|
||||
|
||||
async deleteById(id: number): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionRecordings)
|
||||
.where(eq(sessionRecordings.id, id))
|
||||
.returning({ id: sessionRecordings.id });
|
||||
.where(eq(sessionRecordings.id, id));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteForUser(userId: string, id: number): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionRecordings)
|
||||
.where(
|
||||
and(eq(sessionRecordings.id, id), eq(sessionRecordings.userId, userId)),
|
||||
)
|
||||
.returning({ id: sessionRecordings.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detaches recordings from a user being deleted instead of removing them.
|
||||
* A recording is evidence about the host as much as about the person, and the
|
||||
* file stays on disk regardless — deleting only the row would orphan it.
|
||||
*/
|
||||
async anonymizeByUserId(userId: string): Promise<number> {
|
||||
const result = await this.context.drizzle
|
||||
.update(sessionRecordings)
|
||||
.set({ userId: null })
|
||||
.where(eq(sessionRecordings.userId, userId));
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionRecordings)
|
||||
.where(eq(sessionRecordings.userId, userId))
|
||||
.returning({ id: sessionRecordings.id });
|
||||
.where(eq(sessionRecordings.userId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByHostId(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionRecordings)
|
||||
.where(eq(sessionRecordings.hostId, hostId))
|
||||
.returning({ id: sessionRecordings.id });
|
||||
.where(eq(sessionRecordings.hostId, hostId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByHostIds(hostIds: number[]): Promise<number> {
|
||||
@@ -228,16 +245,15 @@ export class SessionRecordingRepository {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionRecordings)
|
||||
.where(inArray(sessionRecordings.hostId, hostIds))
|
||||
.returning({ id: sessionRecordings.id });
|
||||
.where(inArray(sessionRecordings.hostId, hostIds));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { and, eq, lte, ne } from "drizzle-orm";
|
||||
import { sessions } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type SessionRecord = typeof sessions.$inferSelect;
|
||||
export type NewSessionRecord = typeof sessions.$inferInsert;
|
||||
@@ -12,10 +14,7 @@ export class SessionRepository {
|
||||
) {}
|
||||
|
||||
async create(session: NewSessionRecord): Promise<SessionRecord> {
|
||||
const rows = await this.context.drizzle
|
||||
.insert(sessions)
|
||||
.values(session)
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, sessions, session);
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
}
|
||||
@@ -72,13 +71,12 @@ export class SessionRepository {
|
||||
}
|
||||
|
||||
async revoke(id: string): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessions)
|
||||
.where(eq(sessions.id, id))
|
||||
.returning({ id: sessions.id });
|
||||
.where(eq(sessions.id, id));
|
||||
|
||||
await this.afterWrite();
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async revokeAllForUser(
|
||||
@@ -89,23 +87,19 @@ export class SessionRepository {
|
||||
? and(eq(sessions.userId, userId), ne(sessions.id, exceptSessionId))
|
||||
: eq(sessions.userId, userId);
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.delete(sessions)
|
||||
.where(where)
|
||||
.returning({ id: sessions.id });
|
||||
const result = await this.context.drizzle.delete(sessions).where(where);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteExpired(now = new Date()): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessions)
|
||||
.where(lte(sessions.expiresAt, now.toISOString()))
|
||||
.returning({ id: sessions.id });
|
||||
.where(lte(sessions.expiresAt, now.toISOString()));
|
||||
|
||||
await this.afterWrite();
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
users,
|
||||
} from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type SessionShareRecord = typeof sessionShares.$inferSelect;
|
||||
export type SessionShareParticipantRecord =
|
||||
@@ -49,22 +51,19 @@ export class SessionShareRepository {
|
||||
) {}
|
||||
|
||||
async create(input: SessionShareCreateInput): Promise<SessionShareRecord> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(sessionShares)
|
||||
.values({
|
||||
id: input.id,
|
||||
hostId: input.hostId,
|
||||
ownerUserId: input.ownerUserId,
|
||||
protocol: input.protocol,
|
||||
sessionId: input.sessionId,
|
||||
tabInstanceId: input.tabInstanceId ?? null,
|
||||
shareType: input.shareType,
|
||||
targetUserId: input.targetUserId ?? null,
|
||||
linkToken: input.linkToken ?? null,
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const [created] = await insertReturning(this.context, sessionShares, {
|
||||
id: input.id,
|
||||
hostId: input.hostId,
|
||||
ownerUserId: input.ownerUserId,
|
||||
protocol: input.protocol,
|
||||
sessionId: input.sessionId,
|
||||
tabInstanceId: input.tabInstanceId ?? null,
|
||||
shareType: input.shareType,
|
||||
targetUserId: input.targetUserId ?? null,
|
||||
linkToken: input.linkToken ?? null,
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
@@ -151,7 +150,7 @@ export class SessionShareRepository {
|
||||
}
|
||||
|
||||
async revoke(shareId: string, requestingUserId: string): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(sessionShares)
|
||||
.set({ revokedAt: new Date().toISOString() })
|
||||
.where(
|
||||
@@ -159,38 +158,35 @@ export class SessionShareRepository {
|
||||
eq(sessionShares.id, shareId),
|
||||
eq(sessionShares.ownerUserId, requestingUserId),
|
||||
),
|
||||
)
|
||||
.returning({ id: sessionShares.id });
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async revokeAsAdmin(shareId: string): Promise<boolean> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.update(sessionShares)
|
||||
.set({ revokedAt: new Date().toISOString() })
|
||||
.where(eq(sessionShares.id, shareId))
|
||||
.returning({ id: sessionShares.id });
|
||||
.where(eq(sessionShares.id, shareId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rows.length > 0;
|
||||
return rowsAffected(result) > 0;
|
||||
}
|
||||
|
||||
async deleteExpiredShares(now = new Date().toISOString()): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionShares)
|
||||
.where(lt(sessionShares.expiresAt, now))
|
||||
.returning({ id: sessionShares.id });
|
||||
.where(lt(sessionShares.expiresAt, now));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async touchShareUsage(
|
||||
@@ -213,10 +209,11 @@ export class SessionShareRepository {
|
||||
userId: string | null,
|
||||
guestLabel: string | null,
|
||||
): Promise<SessionShareParticipantRecord> {
|
||||
const [created] = await this.context.drizzle
|
||||
.insert(sessionShareParticipants)
|
||||
.values({ shareId, userId, guestLabel })
|
||||
.returning();
|
||||
const [created] = await insertReturning(
|
||||
this.context,
|
||||
sessionShareParticipants,
|
||||
{ shareId, userId, guestLabel },
|
||||
);
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
@@ -230,15 +227,14 @@ export class SessionShareRepository {
|
||||
}
|
||||
|
||||
async deleteSharesForHost(hostId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sessionShares)
|
||||
.where(eq(sessionShares.hostId, hostId))
|
||||
.returning({ id: sessionShares.id });
|
||||
.where(eq(sessionShares.hostId, hostId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Synchronous read-through cache for the settings table.
|
||||
*
|
||||
* 27 call sites read settings synchronously — during startup, inside request
|
||||
* handlers, and from the guacd server bootstrap. On SQLite that works because
|
||||
* better-sqlite3 is synchronous; on Postgres or MySQL there is no synchronous
|
||||
* query at all, and making all 27 async would push `await` through code paths
|
||||
* that have no business being asynchronous.
|
||||
*
|
||||
* Settings are a handful of low-cardinality configuration rows that change
|
||||
* rarely and are read constantly, so they are cached in full. Writes go through
|
||||
* SettingsRepository, which updates the cache in the same call, and the cache is
|
||||
* primed once at startup.
|
||||
*/
|
||||
|
||||
let cache: Map<string, string> | null = null;
|
||||
|
||||
export function isSettingsCachePrimed(): boolean {
|
||||
return cache !== null;
|
||||
}
|
||||
|
||||
/** Loads the full settings table. Called once during startup. */
|
||||
export function primeSettingsCache(
|
||||
rows: { key: string; value: string }[],
|
||||
): void {
|
||||
cache = new Map(rows.map((row) => [row.key, row.value]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a cached setting.
|
||||
*
|
||||
* Returns null both for "not set" and "cache not primed yet" — every caller
|
||||
* already treats a missing setting as "use the default", and startup ordering
|
||||
* means a read before priming should behave the same way rather than throw.
|
||||
*/
|
||||
export function readCachedSetting(key: string): string | null {
|
||||
return cache?.get(key) ?? null;
|
||||
}
|
||||
|
||||
/** Keeps the cache in step with a write. */
|
||||
export function updateCachedSetting(key: string, value: string): void {
|
||||
cache?.set(key, value);
|
||||
}
|
||||
|
||||
export function forgetCachedSetting(key: string): void {
|
||||
cache?.delete(key);
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function resetSettingsCache(): void {
|
||||
cache = null;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { eq, like } from "drizzle-orm";
|
||||
import { settings } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { forgetCachedSetting, updateCachedSetting } from "./settings-cache.js";
|
||||
import { deleteReturning } from "./returning.js";
|
||||
|
||||
export class SettingsRepository {
|
||||
constructor(
|
||||
@@ -34,6 +36,9 @@ export class SettingsRepository {
|
||||
const existing = await this.get(key);
|
||||
if (existing === null) {
|
||||
await this.context.drizzle.insert(settings).values({ key, value });
|
||||
// Kept in step here so the synchronous readers cannot observe a stale
|
||||
// value after a write in the same process.
|
||||
updateCachedSetting(key, value);
|
||||
await this.afterWrite();
|
||||
return;
|
||||
}
|
||||
@@ -42,6 +47,7 @@ export class SettingsRepository {
|
||||
.update(settings)
|
||||
.set({ value })
|
||||
.where(eq(settings.key, key));
|
||||
updateCachedSetting(key, value);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
@@ -51,14 +57,17 @@ export class SettingsRepository {
|
||||
|
||||
async delete(key: string): Promise<void> {
|
||||
await this.context.drizzle.delete(settings).where(eq(settings.key, key));
|
||||
forgetCachedSetting(key);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async deleteLike(pattern: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
.delete(settings)
|
||||
.where(like(settings.key, pattern))
|
||||
.returning({ key: settings.key });
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
settings,
|
||||
like(settings.key, pattern),
|
||||
);
|
||||
for (const row of rows) forgetCachedSetting(row.key);
|
||||
await this.afterWrite();
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { AuthOverrideProtocol } from "../../../types/auth-protocols.js";
|
||||
import { sharedHostAuthOverrides } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { deleteReturning, upsert } from "./returning.js";
|
||||
|
||||
export type SharedHostAuthOverrideRecord =
|
||||
typeof sharedHostAuthOverrides.$inferSelect;
|
||||
|
||||
export class SharedHostAuthOverrideRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async findForHostUser(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
protocol: AuthOverrideProtocol,
|
||||
): Promise<SharedHostAuthOverrideRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(sharedHostAuthOverrides)
|
||||
.where(
|
||||
and(
|
||||
eq(sharedHostAuthOverrides.hostId, hostId),
|
||||
eq(sharedHostAuthOverrides.userId, userId),
|
||||
eq(sharedHostAuthOverrides.protocol, protocol),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async findCredentialId(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
protocol: AuthOverrideProtocol,
|
||||
): Promise<number | null> {
|
||||
return (
|
||||
(await this.findForHostUser(hostId, userId, protocol))?.credentialId ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
async setCredential(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
protocol: AuthOverrideProtocol,
|
||||
credentialId: number,
|
||||
): Promise<void> {
|
||||
await upsert(
|
||||
this.context,
|
||||
sharedHostAuthOverrides,
|
||||
{
|
||||
hostId,
|
||||
userId,
|
||||
protocol,
|
||||
credentialId,
|
||||
},
|
||||
{
|
||||
target: [
|
||||
sharedHostAuthOverrides.hostId,
|
||||
sharedHostAuthOverrides.userId,
|
||||
sharedHostAuthOverrides.protocol,
|
||||
],
|
||||
set: {
|
||||
credentialId,
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async clearCredential(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
protocol: AuthOverrideProtocol,
|
||||
): Promise<boolean> {
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
sharedHostAuthOverrides,
|
||||
and(
|
||||
eq(sharedHostAuthOverrides.hostId, hostId),
|
||||
eq(sharedHostAuthOverrides.userId, userId),
|
||||
eq(sharedHostAuthOverrides.protocol, protocol),
|
||||
),
|
||||
);
|
||||
|
||||
if (rows.length > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { and, eq, inArray, or } from "drizzle-orm";
|
||||
import { hostAccess, hosts, sharedHostSecrets } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type SharedHostSecretRecord = typeof sharedHostSecrets.$inferSelect;
|
||||
export type NewSharedHostSecretRecord = typeof sharedHostSecrets.$inferInsert;
|
||||
@@ -108,16 +109,15 @@ export class SharedHostSecretsRepository {
|
||||
}
|
||||
|
||||
async deleteByHostAccessId(hostAccessId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sharedHostSecrets)
|
||||
.where(eq(sharedHostSecrets.hostAccessId, hostAccessId))
|
||||
.returning({ id: sharedHostSecrets.id });
|
||||
.where(eq(sharedHostSecrets.hostAccessId, hostAccessId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteForRoleMember(
|
||||
@@ -148,29 +148,27 @@ export class SharedHostSecretsRepository {
|
||||
}
|
||||
|
||||
async deleteByOriginalCredentialId(credentialId: number): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sharedHostSecrets)
|
||||
.where(eq(sharedHostSecrets.originalCredentialId, credentialId))
|
||||
.returning({ id: sharedHostSecrets.id });
|
||||
.where(eq(sharedHostSecrets.originalCredentialId, credentialId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async deleteByTargetUserId(userId: string): Promise<number> {
|
||||
const rows = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(sharedHostSecrets)
|
||||
.where(eq(sharedHostSecrets.targetUserId, userId))
|
||||
.returning({ id: sharedHostSecrets.id });
|
||||
.where(eq(sharedHostSecrets.targetUserId, userId));
|
||||
|
||||
if (rows.length > 0) {
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
async findHostIdsReferencingCredential(
|
||||
|
||||
@@ -2,6 +2,12 @@ import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { randomUUID } from "crypto";
|
||||
import { snippetFolders, snippets } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type SnippetRecord = typeof snippets.$inferSelect;
|
||||
export type SnippetFolderRecord = typeof snippetFolders.$inferSelect;
|
||||
@@ -84,11 +90,16 @@ export class SnippetRepository {
|
||||
}
|
||||
|
||||
async listSnippetsForExport(userId: string): Promise<SnippetRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(eq(snippets.userId, userId))
|
||||
.orderBy(asc(snippets.folder), asc(snippets.order));
|
||||
return (
|
||||
this.context.drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(eq(snippets.userId, userId))
|
||||
// coalesce, not asc(folder): folder is nullable, and NULLs sort first on
|
||||
// SQLite and MySQL but last on Postgres. An export whose row order depends
|
||||
// on the engine is not much of an export.
|
||||
.orderBy(sql`coalesce(${snippets.folder}, '')`, asc(snippets.order))
|
||||
);
|
||||
}
|
||||
|
||||
async listFoldersForExport(userId: string): Promise<SnippetFolderRecord[]> {
|
||||
@@ -149,19 +160,16 @@ export class SnippetRepository {
|
||||
? await this.nextOrderForFolder(userId, folderValue)
|
||||
: input.order;
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.insert(snippets)
|
||||
.values({
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name: input.name.trim(),
|
||||
content: input.content.trim(),
|
||||
description: input.description?.trim() || null,
|
||||
folder: input.folder?.trim() || null,
|
||||
order,
|
||||
hostFilter: input.hostFilter ? JSON.stringify(input.hostFilter) : null,
|
||||
})
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, snippets, {
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name: input.name.trim(),
|
||||
content: input.content.trim(),
|
||||
description: input.description?.trim() || null,
|
||||
folder: input.folder?.trim() || null,
|
||||
order,
|
||||
hostFilter: input.hostFilter ? JSON.stringify(input.hostFilter) : null,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0];
|
||||
@@ -200,11 +208,12 @@ export class SnippetRepository {
|
||||
? JSON.stringify(input.hostFilter)
|
||||
: null;
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.update(snippets)
|
||||
.set(updateFields)
|
||||
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)))
|
||||
.returning();
|
||||
const rows = await updateReturning(
|
||||
this.context,
|
||||
snippets,
|
||||
updateFields,
|
||||
and(eq(snippets.id, snippetId), eq(snippets.userId, userId)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return { existing, updated: rows[0] };
|
||||
@@ -229,23 +238,21 @@ export class SnippetRepository {
|
||||
snippetsDeleted: number;
|
||||
foldersDeleted: number;
|
||||
}> {
|
||||
const deletedSnippets = await this.context.drizzle
|
||||
const snippetResult = await this.context.drizzle
|
||||
.delete(snippets)
|
||||
.where(eq(snippets.userId, userId))
|
||||
.returning({ id: snippets.id });
|
||||
.where(eq(snippets.userId, userId));
|
||||
|
||||
const deletedFolders = await this.context.drizzle
|
||||
const result = await this.context.drizzle
|
||||
.delete(snippetFolders)
|
||||
.where(eq(snippetFolders.userId, userId))
|
||||
.returning({ id: snippetFolders.id });
|
||||
.where(eq(snippetFolders.userId, userId));
|
||||
|
||||
if (deletedSnippets.length > 0 || deletedFolders.length > 0) {
|
||||
if (rowsAffected(snippetResult) > 0 || rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
return {
|
||||
snippetsDeleted: deletedSnippets.length,
|
||||
foldersDeleted: deletedFolders.length,
|
||||
snippetsDeleted: rowsAffected(snippetResult),
|
||||
foldersDeleted: rowsAffected(result),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -377,16 +384,13 @@ export class SnippetRepository {
|
||||
const existing = await this.findFolderByName(userId, name);
|
||||
if (existing) return null;
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.insert(snippetFolders)
|
||||
.values({
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name: name.trim(),
|
||||
color: color?.trim() || null,
|
||||
icon: icon?.trim() || null,
|
||||
})
|
||||
.returning();
|
||||
const rows = await insertReturning(this.context, snippetFolders, {
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name: name.trim(),
|
||||
color: color?.trim() || null,
|
||||
icon: icon?.trim() || null,
|
||||
});
|
||||
|
||||
if (triggerSave) {
|
||||
await this.afterWrite();
|
||||
@@ -414,13 +418,12 @@ export class SnippetRepository {
|
||||
if (color !== undefined) updateFields.color = color?.trim() || null;
|
||||
if (icon !== undefined) updateFields.icon = icon?.trim() || null;
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.update(snippetFolders)
|
||||
.set(updateFields)
|
||||
.where(
|
||||
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
|
||||
)
|
||||
.returning();
|
||||
const rows = await updateReturning(
|
||||
this.context,
|
||||
snippetFolders,
|
||||
updateFields,
|
||||
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
@@ -465,15 +468,14 @@ export class SnippetRepository {
|
||||
.set({ folder: null })
|
||||
.where(and(eq(snippets.userId, userId), eq(snippets.folder, name)));
|
||||
|
||||
const rows = await this.context.drizzle
|
||||
.delete(snippetFolders)
|
||||
.where(
|
||||
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
|
||||
)
|
||||
.returning({ syncId: snippetFolders.syncId });
|
||||
const rows = await deleteReturning(
|
||||
this.context,
|
||||
snippetFolders,
|
||||
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return rows[0] ?? null;
|
||||
return rows[0] ? { syncId: rows[0].syncId } : null;
|
||||
}
|
||||
|
||||
private async findFolderByName(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user