@myrialabs/clopen 0.4.47 → 0.4.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/backend/artifacts/project/sources.ts +1 -1
- package/backend/auth/auth-service.ts +52 -358
- package/backend/auth/onboarding.test.ts +2 -3
- package/backend/auth/permissions.test.ts +10 -20
- package/backend/auth/permissions.ts +4 -290
- package/backend/auth/rate-limiter.test.ts +8 -9
- package/backend/auth/rate-limiter.ts +0 -2
- package/backend/auth/tokens.ts +1 -8
- package/backend/bootstrap.ts +7 -0
- package/backend/chat/attachments.test.ts +88 -0
- package/backend/chat/attachments.ts +159 -0
- package/backend/chat/engine-handoff.test.ts +0 -2
- package/backend/chat/message-pages.test.ts +163 -0
- package/backend/chat/message-pages.ts +233 -0
- package/backend/chat/stream-manager.ts +91 -67
- package/backend/chat/turn-answer.test.ts +64 -0
- package/backend/chat/turn-answer.ts +125 -0
- package/backend/chat-apps/awaiting.test.ts +39 -0
- package/backend/chat-apps/awaiting.ts +49 -0
- package/backend/chat-apps/conversation.ts +746 -0
- package/backend/chat-apps/inbound.ts +324 -0
- package/backend/chat-apps/index.ts +309 -0
- package/backend/chat-apps/link-events.ts +20 -0
- package/backend/chat-apps/media.test.ts +62 -0
- package/backend/chat-apps/media.ts +208 -0
- package/backend/chat-apps/messages.test.ts +229 -0
- package/backend/chat-apps/messages.ts +365 -0
- package/backend/chat-apps/outbound.ts +243 -0
- package/backend/chat-apps/pairing.test.ts +45 -0
- package/backend/chat-apps/pairing.ts +74 -0
- package/backend/chat-apps/platforms/index.ts +20 -0
- package/backend/chat-apps/platforms/telegram.test.ts +35 -0
- package/backend/chat-apps/platforms/telegram.ts +191 -0
- package/backend/chat-apps/platforms/types.ts +114 -0
- package/backend/chat-apps/questions.ts +133 -0
- package/backend/chat-apps/runtime.ts +572 -0
- package/backend/chat-apps/storage.test.ts +201 -0
- package/backend/chat-apps/turns.test.ts +45 -0
- package/backend/chat-apps/turns.ts +208 -0
- package/backend/containers/pty.ts +3 -11
- package/backend/control/actions/accounts.ts +89 -0
- package/backend/control/actions/files.ts +116 -0
- package/backend/control/actions/models.ts +188 -0
- package/backend/control/actions/projects.ts +272 -0
- package/backend/control/actions/sessions.ts +280 -0
- package/backend/control/actions/skills.ts +111 -0
- package/backend/control/control.test.ts +169 -0
- package/backend/control/define.ts +20 -0
- package/backend/control/folders.test.ts +67 -0
- package/backend/control/index.ts +213 -0
- package/backend/control/invoke.ts +44 -0
- package/backend/control/links.ts +35 -0
- package/backend/control/paging.ts +26 -0
- package/backend/control/types.ts +117 -0
- package/backend/control/workspace.ts +127 -0
- package/backend/database/migrations/084_create_channel_links.ts +71 -0
- package/backend/database/migrations/085_add_home_projects.ts +36 -0
- package/backend/database/migrations/086_single_owner.ts +418 -0
- package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/blob-line-stats-queries.ts +48 -0
- package/backend/database/queries/channel-queries.ts +270 -0
- package/backend/database/queries/db-client-connection-queries.ts +18 -56
- package/backend/database/queries/file-share-queries.ts +5 -23
- package/backend/database/queries/git-identity-queries.ts +31 -42
- package/backend/database/queries/graph-queries.ts +1 -1
- package/backend/database/queries/index.ts +15 -1
- package/backend/database/queries/message-queries.test.ts +146 -0
- package/backend/database/queries/message-queries.ts +42 -1
- package/backend/database/queries/permission-set-queries.ts +1 -1
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
- package/backend/database/queries/project-queries.ts +50 -63
- package/backend/database/queries/session-queries.ts +28 -56
- package/backend/database/queries/ssh-connection-queries.ts +18 -41
- package/backend/db-client/env/diff.ts +9 -33
- package/backend/db-client/env/env.test.ts +8 -8
- package/backend/db-client/env/service.ts +1 -1
- package/backend/db-client/integrations/projector.ts +0 -5
- package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
- package/backend/engine/adapters/claude/message-converter.ts +25 -2
- package/backend/engine/adapters/cline/message-converter.ts +0 -1
- package/backend/engine/adapters/cline/stream.ts +11 -15
- package/backend/engine/adapters/codex/message-converter.ts +0 -2
- package/backend/engine/adapters/copilot/message-converter.ts +1 -2
- package/backend/engine/adapters/cursor/message-converter.ts +0 -1
- package/backend/engine/adapters/opencode/message-converter.ts +2 -4
- package/backend/engine/adapters/opencode/stream.ts +11 -0
- package/backend/engine/adapters/parent-scope.test.ts +38 -0
- package/backend/engine/adapters/parent-scope.ts +44 -0
- package/backend/engine/adapters/pi/message-converter.ts +0 -1
- package/backend/engine/adapters/pi/stream.ts +4 -5
- package/backend/engine/adapters/qwen/message-converter.ts +0 -2
- package/backend/engine/bootstrap-default-engine.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +8 -1
- package/backend/engine/install-runner.ts +8 -17
- package/backend/files/file-shares.ts +20 -44
- package/backend/files/file-size-limit.ts +3 -3
- package/backend/files/file-watcher.ts +19 -0
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/contributors.test.ts +35 -0
- package/backend/git/contributors.ts +46 -0
- package/backend/git/git-executor.ts +25 -5
- package/backend/git/git-service.ts +420 -19
- package/backend/git/identity/credential-helper.test.ts +2 -7
- package/backend/git/identity/import-local.test.ts +11 -16
- package/backend/git/identity/import-local.ts +12 -12
- package/backend/git/identity/index.ts +10 -24
- package/backend/git/identity/resolve.ts +13 -14
- package/backend/git/identity/scope-config.ts +33 -28
- package/backend/git/identity/service.ts +44 -47
- package/backend/git/op-lock.test.ts +111 -0
- package/backend/git/op-lock.ts +180 -0
- package/backend/git/remote-sync.test.ts +249 -0
- package/backend/host/metrics.ts +1 -1
- package/backend/http/bearer-auth.ts +1 -2
- package/backend/http/files-download.test.ts +8 -9
- package/backend/http/files-download.ts +2 -2
- package/backend/http/files-shared.test.ts +62 -89
- package/backend/http/files-shared.ts +2 -2
- package/backend/http/files-upload.test.ts +3 -7
- package/backend/http/files-upload.ts +3 -3
- package/backend/http/notes-images.test.ts +15 -38
- package/backend/http/notes-images.ts +6 -8
- package/backend/http/ssh-sftp.ts +5 -10
- package/backend/http/static-assets.test.ts +78 -0
- package/backend/http/static-assets.ts +104 -0
- package/backend/index.ts +32 -16
- package/backend/integrations/accounts.ts +61 -3
- package/backend/integrations/index.ts +2 -2
- package/backend/integrations/registry/define.ts +15 -0
- package/backend/integrations/registry/index.ts +2 -0
- package/backend/integrations/registry/providers/telegram.ts +54 -0
- package/backend/integrations/registry/types.ts +21 -1
- package/backend/integrations/webhooks/gateway.ts +7 -6
- package/backend/integrations/webhooks/verify.test.ts +30 -0
- package/backend/integrations/webhooks/verify.ts +4 -0
- package/backend/mcp/external/project.ts +1 -1
- package/backend/mcp/internal/remote-server.test.ts +1 -3
- package/backend/mcp/internal/remote-server.ts +4 -4
- package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
- package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
- package/backend/memory/redact.ts +1 -1
- package/backend/notes/access.test.ts +28 -29
- package/backend/notes/access.ts +6 -11
- package/backend/permissions/service.ts +1 -1
- package/backend/preview/browser/browser-clipboard.test.ts +46 -0
- package/backend/preview/browser/browser-clipboard.ts +67 -0
- package/backend/preview/browser/browser-dialog-handler.ts +95 -6
- package/backend/preview/browser/browser-host-bridge.ts +9 -0
- package/backend/preview/browser/browser-interaction-handler.ts +316 -86
- package/backend/preview/browser/browser-mcp-control.ts +34 -0
- package/backend/preview/browser/browser-pool.ts +67 -6
- package/backend/preview/browser/browser-preview-service.ts +383 -29
- package/backend/preview/browser/browser-tab-manager.ts +66 -23
- package/backend/preview/browser/browser-video-capture.ts +92 -5
- package/backend/preview/browser/element-locator.ts +190 -17
- package/backend/preview/browser/keyboard-chords.test.ts +68 -0
- package/backend/preview/browser/keyboard-chords.ts +132 -0
- package/backend/preview/browser/paste.ts +81 -0
- package/backend/preview/browser/process-usage.ts +142 -0
- package/backend/preview/browser/profile-lock.ts +209 -0
- package/backend/preview/browser/scripts/host-bridge.ts +59 -0
- package/backend/preview/browser/scripts/video-stream.ts +58 -0
- package/backend/preview/browser/types.ts +40 -2
- package/backend/preview/browser/viewport.test.ts +45 -0
- package/backend/preview/browser/viewport.ts +96 -0
- package/backend/profiles/service.ts +2 -2
- package/backend/project/status-manager.ts +43 -172
- package/backend/projects/home.ts +61 -0
- package/backend/projects/project-cleanup.integration.test.ts +2 -2
- package/backend/projects/project-cleanup.ts +0 -8
- package/backend/skills/service.ts +2 -3
- package/backend/snapshot/blob-store.ts +9 -1
- package/backend/snapshot/helpers.ts +3 -11
- package/backend/snapshot/line-stats.test.ts +80 -0
- package/backend/snapshot/line-stats.ts +64 -0
- package/backend/snapshot/restore.ts +252 -0
- package/backend/snapshot/snapshot-service.ts +14 -27
- package/backend/snapshot/turn-changes.test.ts +10 -5
- package/backend/snapshot/turn-changes.ts +78 -40
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +10 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws-wire.test.ts +87 -0
- package/backend/utils/ws-wire.ts +189 -0
- package/backend/utils/ws.ts +101 -192
- package/backend/worktrees/branching/engine.ts +3 -16
- package/backend/worktrees/branching/index.ts +1 -1
- package/backend/worktrees/branching/projector.ts +1 -1
- package/backend/worktrees/branching/service.ts +13 -25
- package/backend/ws/access.ts +12 -21
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/auth/device.ts +16 -71
- package/backend/ws/auth/index.ts +4 -22
- package/backend/ws/auth/login.test.ts +14 -60
- package/backend/ws/auth/login.ts +24 -124
- package/backend/ws/auth/status.ts +0 -1
- package/backend/ws/chat/composer.ts +118 -118
- package/backend/ws/chat/stream.ts +105 -57
- package/backend/ws/chat-apps/index.ts +117 -0
- package/backend/ws/containers/actions.ts +11 -25
- package/backend/ws/containers/index.ts +3 -4
- package/backend/ws/containers/list.ts +10 -36
- package/backend/ws/containers/logs.ts +2 -2
- package/backend/ws/containers/tunnel.ts +1 -2
- package/backend/ws/db-client/access.ts +2 -16
- package/backend/ws/db-client/accounts.ts +5 -15
- package/backend/ws/db-client/connections.ts +17 -25
- package/backend/ws/db-client/context.ts +1 -1
- package/backend/ws/db-client/env.ts +7 -10
- package/backend/ws/db-client/index.ts +2 -2
- package/backend/ws/db-client/io.ts +5 -5
- package/backend/ws/db-client/query-history-retention.test.ts +8 -8
- package/backend/ws/db-client/query.ts +18 -17
- package/backend/ws/db-client/schema.ts +13 -13
- package/backend/ws/db-client/structure.ts +35 -35
- package/backend/ws/db-client/supabase.ts +4 -21
- package/backend/ws/deployments/context.ts +1 -1
- package/backend/ws/deployments/crud.ts +0 -5
- package/backend/ws/engine/access.ts +7 -20
- package/backend/ws/engine/claude/accounts.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +5 -5
- package/backend/ws/engine/codex/accounts.ts +3 -3
- package/backend/ws/engine/pi/accounts.ts +5 -5
- package/backend/ws/files/clipboard.ts +8 -27
- package/backend/ws/files/image-edit.ts +6 -6
- package/backend/ws/files/index.ts +1 -1
- package/backend/ws/files/path-access.test.ts +32 -131
- package/backend/ws/files/path-access.ts +8 -87
- package/backend/ws/files/read.ts +45 -19
- package/backend/ws/files/reveal.ts +3 -3
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/share.ts +9 -13
- package/backend/ws/files/state.ts +9 -12
- package/backend/ws/files/watch.ts +3 -3
- package/backend/ws/files/write.ts +30 -31
- package/backend/ws/git/branch.ts +80 -59
- package/backend/ws/git/commit.ts +63 -44
- package/backend/ws/git/conflict.ts +16 -18
- package/backend/ws/git/identity-context.ts +8 -17
- package/backend/ws/git/identity.ts +17 -27
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/log.ts +52 -0
- package/backend/ws/git/op-state.ts +139 -0
- package/backend/ws/git/remote.ts +241 -141
- package/backend/ws/git/repo-context.ts +67 -0
- package/backend/ws/git/staging.ts +18 -28
- package/backend/ws/git/status.ts +5 -2
- package/backend/ws/index.ts +5 -1
- package/backend/ws/instructions/crud.ts +1 -1
- package/backend/ws/integrations/crud.ts +1 -3
- package/backend/ws/mcp/crud.ts +3 -5
- package/backend/ws/mcp/tools.ts +1 -1
- package/backend/ws/memory/crud.ts +14 -46
- package/backend/ws/memory/index.ts +2 -2
- package/backend/ws/messages/crud.ts +78 -8
- package/backend/ws/notes/index.ts +33 -39
- package/backend/ws/permissions/crud.ts +3 -4
- package/backend/ws/ports/index.ts +1 -2
- package/backend/ws/ports/kill.ts +5 -10
- package/backend/ws/ports/list.ts +4 -10
- package/backend/ws/preview/access.ts +1 -1
- package/backend/ws/preview/browser/interact.ts +52 -79
- package/backend/ws/preview/browser/native-ui.ts +24 -0
- package/backend/ws/preview/browser/stats.ts +98 -1
- package/backend/ws/preview/browser/tab-info.ts +15 -0
- package/backend/ws/preview/browser/tab.ts +19 -4
- package/backend/ws/preview/index.ts +29 -0
- package/backend/ws/preview/watchers.ts +84 -0
- package/backend/ws/profiles/crud.ts +6 -8
- package/backend/ws/project-artifacts/index.ts +30 -31
- package/backend/ws/projects/crud.ts +33 -35
- package/backend/ws/projects/index.ts +3 -8
- package/backend/ws/projects/info.ts +3 -3
- package/backend/ws/projects/overview.ts +19 -30
- package/backend/ws/projects/status.ts +17 -57
- package/backend/ws/sessions/crud.ts +42 -57
- package/backend/ws/sessions/index.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/skills/crud.ts +3 -4
- package/backend/ws/skills/index.ts +1 -1
- package/backend/ws/snapshot/changes.ts +12 -13
- package/backend/ws/snapshot/restore.ts +11 -295
- package/backend/ws/snapshot/timeline.ts +2 -4
- package/backend/ws/ssh/access.ts +6 -21
- package/backend/ws/ssh/connections.ts +21 -31
- package/backend/ws/ssh/forwards.ts +12 -12
- package/backend/ws/ssh/sftp.ts +34 -34
- package/backend/ws/ssh/tunnel.ts +1 -2
- package/backend/ws/stack/install.ts +7 -17
- package/backend/ws/subagents/crud.ts +1 -1
- package/backend/ws/terminal/tunnel.ts +2 -2
- package/backend/ws/tunnel/share.ts +0 -2
- package/backend/ws/user/crud.ts +1 -59
- package/backend/ws/user/index.ts +1 -1
- package/backend/ws/work/context.ts +1 -1
- package/backend/ws/work/crud.ts +0 -5
- package/backend/ws/workspace/state.ts +10 -13
- package/backend/ws/worktrees/branching.ts +7 -36
- package/backend/ws/worktrees/crud.ts +2 -2
- package/bin/clopen.ts +46 -41
- package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
- package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
- package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
- package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
- package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
- package/dist/assets/index-CrVWZH_D.js.br +0 -0
- package/dist/assets/index-CrVWZH_D.js.gz +0 -0
- package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
- package/dist/assets/index-DD0-3EWg.js.br +0 -0
- package/dist/assets/index-DD0-3EWg.js.gz +0 -0
- package/dist/assets/main-D2_TmcwQ.js +1240 -0
- package/dist/assets/main-D2_TmcwQ.js.br +0 -0
- package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
- package/dist/assets/main-Yucigcmf.css +1 -0
- package/dist/assets/main-Yucigcmf.css.br +0 -0
- package/dist/assets/main-Yucigcmf.css.gz +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
- package/dist/fonts/dm-sans.css.br +0 -0
- package/dist/fonts/dm-sans.css.gz +0 -0
- package/dist/index.html +2 -2
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/dist/sw.js.br +0 -0
- package/dist/sw.js.gz +0 -0
- package/package.json +3 -3
- package/shared/constants/attachments.ts +14 -0
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/preview.test.ts +259 -0
- package/shared/constants/preview.ts +1018 -57
- package/shared/constants/tool-icons.ts +5 -0
- package/shared/types/containers/container.ts +1 -1
- package/shared/types/database/schema.ts +9 -6
- package/shared/types/git-identity.ts +1 -1
- package/shared/types/git.ts +116 -0
- package/shared/types/integrations.ts +7 -0
- package/shared/types/stores/settings.ts +1 -1
- package/shared/types/unified/index.ts +1 -1
- package/shared/types/unified/message.ts +0 -7
- package/shared/types/unified/stream.ts +13 -5
- package/shared/types/unified/tool.ts +15 -1
- package/shared/utils/ask-user-question.test.ts +319 -0
- package/shared/utils/ask-user-question.ts +154 -0
- package/shared/utils/diff-calculator.test.ts +178 -41
- package/shared/utils/diff-calculator.ts +383 -100
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/process-supervisor.test.ts +172 -0
- package/shared/utils/process-supervisor.ts +251 -0
- package/shared/utils/ws-chunk.test.ts +33 -0
- package/shared/utils/ws-chunk.ts +73 -0
- package/shared/utils/ws-client-chunks.test.ts +45 -0
- package/shared/utils/ws-client.ts +43 -0
- package/shared/utils/ws-server.ts +49 -21
- package/backend/auth/session-invalidation.test.ts +0 -112
- package/backend/auth/session-invalidation.ts +0 -77
- package/backend/project/status-manager.test.ts +0 -32
- package/backend/ws/auth/invites.ts +0 -94
- package/backend/ws/auth/users.ts +0 -112
- package/backend/ws/projects/presence.ts +0 -46
- package/backend/ws/stack/access.ts +0 -31
- package/dist/assets/main-BiDNMWb3.css +0 -1
- package/dist/assets/main-BlhKWz2B.js +0 -1241
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { afterAll, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { brotliCompressSync, brotliDecompressSync, gunzipSync, gzipSync } from 'node:zlib';
|
|
6
|
+
|
|
7
|
+
import { cacheControlFor, pickEncoding, serveIndexHtml, serveStaticFile } from './static-assets';
|
|
8
|
+
|
|
9
|
+
const dir = mkdtempSync(join(tmpdir(), 'clopen-static-'));
|
|
10
|
+
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
|
11
|
+
|
|
12
|
+
const source = 'console.log("hello");\n'.repeat(200);
|
|
13
|
+
const asset = join(dir, 'main-nBOb9YOA.js');
|
|
14
|
+
writeFileSync(asset, source);
|
|
15
|
+
writeFileSync(`${asset}.br`, brotliCompressSync(source));
|
|
16
|
+
writeFileSync(`${asset}.gz`, gzipSync(source));
|
|
17
|
+
const plain = join(dir, 'favicon.svg');
|
|
18
|
+
writeFileSync(plain, '<svg/>');
|
|
19
|
+
|
|
20
|
+
const request = (headers: Record<string, string> = {}) => new Request('http://localhost/x', { headers });
|
|
21
|
+
|
|
22
|
+
describe('cache policy', () => {
|
|
23
|
+
test('content-hashed build output is immutable; everything else revalidates', () => {
|
|
24
|
+
expect(cacheControlFor('/assets/main-nBOb9YOA.js')).toContain('immutable');
|
|
25
|
+
expect(cacheControlFor('/assets/xterm-B-qIQCd3.js')).toContain('immutable');
|
|
26
|
+
expect(cacheControlFor('/assets/zipkit-engine-CaR0t_Uy.wasm')).toContain('immutable');
|
|
27
|
+
expect(cacheControlFor('/sw.js')).toBe('no-cache');
|
|
28
|
+
expect(cacheControlFor('/index.html')).toBe('no-cache');
|
|
29
|
+
expect(cacheControlFor('/favicon.svg')).toBe('no-cache');
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('encoding negotiation', () => {
|
|
34
|
+
const both = new Set(['br', 'gzip'] as const);
|
|
35
|
+
test('prefers brotli, falls back to gzip, honours q=0', () => {
|
|
36
|
+
expect(pickEncoding('gzip, deflate, br', both)).toBe('br');
|
|
37
|
+
expect(pickEncoding('gzip', both)).toBe('gzip');
|
|
38
|
+
expect(pickEncoding('br;q=0, gzip', both)).toBe('gzip');
|
|
39
|
+
expect(pickEncoding('identity', both)).toBeNull();
|
|
40
|
+
expect(pickEncoding(null, both)).toBeNull();
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('serveStaticFile', () => {
|
|
45
|
+
test('sends the brotli copy with the original type, and decodes to the original', async () => {
|
|
46
|
+
const res = serveStaticFile(request({ 'accept-encoding': 'br, gzip' }), '/assets/main-nBOb9YOA.js', asset);
|
|
47
|
+
expect(res.headers.get('content-encoding')).toBe('br');
|
|
48
|
+
expect(res.headers.get('content-type')).toContain('javascript');
|
|
49
|
+
expect(res.headers.get('vary')).toBe('Accept-Encoding');
|
|
50
|
+
expect(res.headers.get('cache-control')).toContain('immutable');
|
|
51
|
+
expect(brotliDecompressSync(Buffer.from(await res.arrayBuffer())).toString()).toBe(source);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('sends gzip to a client without brotli, and the raw file to one without either', async () => {
|
|
55
|
+
const gz = serveStaticFile(request({ 'accept-encoding': 'gzip' }), '/assets/main-nBOb9YOA.js', asset);
|
|
56
|
+
expect(gunzipSync(Buffer.from(await gz.arrayBuffer())).toString()).toBe(source);
|
|
57
|
+
const raw = serveStaticFile(request(), '/assets/main-nBOb9YOA.js', asset);
|
|
58
|
+
expect(raw.headers.get('content-encoding')).toBeNull();
|
|
59
|
+
expect(await raw.text()).toBe(source);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('answers 304 when the browser already holds this version', () => {
|
|
63
|
+
const first = serveStaticFile(request(), '/favicon.svg', plain);
|
|
64
|
+
const etag = first.headers.get('etag')!;
|
|
65
|
+
const again = serveStaticFile(request({ 'if-none-match': etag }), '/favicon.svg', plain);
|
|
66
|
+
expect(again.status).toBe(304);
|
|
67
|
+
expect(again.headers.get('cache-control')).toBe('no-cache');
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('serveIndexHtml', () => {
|
|
72
|
+
test('is always revalidated and answers 304 for the current version', () => {
|
|
73
|
+
const fresh = serveIndexHtml(request(), '<html></html>', 'W/"1"');
|
|
74
|
+
expect(fresh.headers.get('cache-control')).toBe('no-cache');
|
|
75
|
+
expect(serveIndexHtml(request({ 'if-none-match': 'W/"1"' }), '<html></html>', 'W/"1"').status).toBe(304);
|
|
76
|
+
expect(serveIndexHtml(request({ 'if-none-match': 'W/"0"' }), '<html></html>', 'W/"1"').status).toBe(200);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serving the built frontend (`dist/`) in production.
|
|
3
|
+
*
|
|
4
|
+
* It used to go out with no caching headers and no compression, so a browser
|
|
5
|
+
* had nothing to revalidate against and every page load — a refresh, a new tab,
|
|
6
|
+
* reopening the app on a phone — downloaded the whole bundle again: ~8 MB,
|
|
7
|
+
* ~1.6 MB of it after brotli.
|
|
8
|
+
*
|
|
9
|
+
* - Content-hashed build output (`/assets/name-<hash>.ext`) never changes under
|
|
10
|
+
* its name, so it is cached for a year as immutable.
|
|
11
|
+
* - Everything else (`index.html`, `sw.js`, the manifest, fonts, sounds) is
|
|
12
|
+
* revalidated on every use with an ETag, so an update is picked up at once
|
|
13
|
+
* and an unchanged file costs a 304. A new release's `index.html` names new
|
|
14
|
+
* hashed assets; the old ones simply stop being requested.
|
|
15
|
+
* - Brotli or gzip copies written at build time (scripts/vite-precompress.ts)
|
|
16
|
+
* are sent when the browser accepts them — no compression at request time.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { statSync } from 'node:fs';
|
|
20
|
+
|
|
21
|
+
/** Build output named by its content hash, e.g. `main-nBOb9YOA.js`. */
|
|
22
|
+
const HASHED_ASSET = /^\/assets\/.+-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/;
|
|
23
|
+
|
|
24
|
+
const IMMUTABLE = 'public, max-age=31536000, immutable';
|
|
25
|
+
const REVALIDATE = 'no-cache';
|
|
26
|
+
|
|
27
|
+
type Encoding = 'br' | 'gzip';
|
|
28
|
+
const SUFFIX: Record<Encoding, string> = { br: '.br', gzip: '.gz' };
|
|
29
|
+
|
|
30
|
+
/** Which precompressed siblings exist — the build output does not change while running. */
|
|
31
|
+
const siblings = new Map<string, Set<Encoding>>();
|
|
32
|
+
|
|
33
|
+
function availableEncodings(filePath: string): Set<Encoding> {
|
|
34
|
+
let found = siblings.get(filePath);
|
|
35
|
+
if (!found) {
|
|
36
|
+
found = new Set();
|
|
37
|
+
for (const encoding of ['br', 'gzip'] as const) {
|
|
38
|
+
try {
|
|
39
|
+
if (statSync(filePath + SUFFIX[encoding]).isFile()) found.add(encoding);
|
|
40
|
+
} catch {
|
|
41
|
+
// No such copy.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
siblings.set(filePath, found);
|
|
45
|
+
}
|
|
46
|
+
return found;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The best encoding both sides support: brotli, then gzip, else none. */
|
|
50
|
+
export function pickEncoding(acceptEncoding: string | null, available: Set<Encoding>): Encoding | null {
|
|
51
|
+
if (!acceptEncoding) return null;
|
|
52
|
+
const accepted = new Set(
|
|
53
|
+
acceptEncoding
|
|
54
|
+
.split(',')
|
|
55
|
+
.map((part) => part.trim())
|
|
56
|
+
.filter((part) => !/;\s*q=0(\.0+)?$/.test(part))
|
|
57
|
+
.map((part) => part.split(';')[0].trim().toLowerCase())
|
|
58
|
+
);
|
|
59
|
+
if (available.has('br') && accepted.has('br')) return 'br';
|
|
60
|
+
if (available.has('gzip') && (accepted.has('gzip') || accepted.has('*'))) return 'gzip';
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Cache policy for a request path. */
|
|
65
|
+
export function cacheControlFor(urlPath: string): string {
|
|
66
|
+
return HASHED_ASSET.test(urlPath) ? IMMUTABLE : REVALIDATE;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A response for a file under `dist/`, or a 304 when the browser's copy is
|
|
71
|
+
* current. `filePath` must already be resolved and confined to `dist/`.
|
|
72
|
+
*/
|
|
73
|
+
export function serveStaticFile(request: Request, urlPath: string, filePath: string): Response {
|
|
74
|
+
const stats = statSync(filePath);
|
|
75
|
+
const etag = `W/"${stats.size.toString(36)}-${Math.floor(stats.mtimeMs).toString(36)}"`;
|
|
76
|
+
const headers: Record<string, string> = {
|
|
77
|
+
'Cache-Control': cacheControlFor(urlPath),
|
|
78
|
+
ETag: etag,
|
|
79
|
+
Vary: 'Accept-Encoding'
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
if (request.headers.get('if-none-match') === etag) {
|
|
83
|
+
return new Response(null, { status: 304, headers });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const original = Bun.file(filePath);
|
|
87
|
+
headers['Content-Type'] = original.type || 'application/octet-stream';
|
|
88
|
+
|
|
89
|
+
const encoding = pickEncoding(request.headers.get('accept-encoding'), availableEncodings(filePath));
|
|
90
|
+
if (encoding) {
|
|
91
|
+
headers['Content-Encoding'] = encoding;
|
|
92
|
+
return new Response(Bun.file(filePath + SUFFIX[encoding]), { headers });
|
|
93
|
+
}
|
|
94
|
+
return new Response(original, { headers });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The SPA shell (`index.html`), always revalidated so a release is picked up at once. */
|
|
98
|
+
export function serveIndexHtml(request: Request, html: string, etag: string): Response {
|
|
99
|
+
const headers = { 'Cache-Control': REVALIDATE, ETag: etag, 'Content-Type': 'text/html; charset=utf-8' };
|
|
100
|
+
if (request.headers.get('if-none-match') === etag) {
|
|
101
|
+
return new Response(null, { status: 304, headers });
|
|
102
|
+
}
|
|
103
|
+
return new Response(html, { headers });
|
|
104
|
+
}
|
package/backend/index.ts
CHANGED
|
@@ -64,7 +64,7 @@ import { filesUploadRoute } from './http/files-upload';
|
|
|
64
64
|
import { filesDownloadRoute } from './http/files-download';
|
|
65
65
|
import { filesSharedRoute } from './http/files-shared';
|
|
66
66
|
|
|
67
|
-
// HTTP routes for
|
|
67
|
+
// HTTP routes for custom notification sounds (upload / serve / delete).
|
|
68
68
|
import { audioRoute } from './http/audio';
|
|
69
69
|
|
|
70
70
|
// HTTP routes for Web Push subscriptions + test (mobile background notifications).
|
|
@@ -91,28 +91,33 @@ import { portMonitor } from './ports/monitor';
|
|
|
91
91
|
import { containerMonitor } from './containers/monitor';
|
|
92
92
|
import { stopAllLogStreams as stopAllContainerLogStreams } from './containers/logs';
|
|
93
93
|
import { stopAllBuildLogStreams } from './deployments/log-streams';
|
|
94
|
+
import { startChatApps, stopChatApps } from './chat-apps';
|
|
95
|
+
import { registerControlRouter } from './control';
|
|
94
96
|
import { uploadTempCleanup } from './http/upload-temp-cleanup';
|
|
95
97
|
import { ws as wsServer } from './utils/ws';
|
|
96
98
|
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
97
99
|
import { flushEpisodicIngest, stopExtractionRunner } from './memory/extract';
|
|
98
100
|
import { stopMemoryMaintenance } from './memory/maintenance';
|
|
101
|
+
import { WS_SERVER_OPTIONS } from './utils/ws-wire';
|
|
102
|
+
import { serveIndexHtml, serveStaticFile } from './http/static-assets';
|
|
99
103
|
|
|
100
104
|
/** How often (ms) the auth gate re-confirms a connection's session against the DB. */
|
|
101
105
|
const SESSION_REVALIDATE_MS = 15_000;
|
|
102
106
|
|
|
103
|
-
// Register auth gate on WebSocket router — blocks unauthenticated
|
|
107
|
+
// Register auth gate on WebSocket router — blocks unauthenticated access
|
|
104
108
|
wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
105
109
|
const isAuth = wsServer.isAuthenticated(conn);
|
|
106
|
-
const
|
|
107
|
-
const result = checkRouteAccess(action, isAuth, role);
|
|
110
|
+
const result = checkRouteAccess(action, isAuth);
|
|
108
111
|
if (!result.allowed) return result;
|
|
109
112
|
|
|
110
113
|
// Defense-in-depth: an authenticated connection trusts the in-memory auth set
|
|
111
114
|
// at login. If its session was revoked/expired/deleted afterwards (sign-out
|
|
112
|
-
// from another device,
|
|
115
|
+
// from another device, expiry), the live socket would otherwise
|
|
113
116
|
// keep full access until it reconnects. Periodically re-confirm the session
|
|
114
117
|
// still exists in the DB and kick the connection the moment it doesn't.
|
|
115
|
-
|
|
118
|
+
// A virtual connection has no session token: its identity is vouched for by
|
|
119
|
+
// whoever opened it (a paired chat app), per call, so there is nothing to revalidate.
|
|
120
|
+
if (isAuth && getAuthMode() === 'required' && !PUBLIC_ROUTES.has(action) && !wsServer.isVirtual(conn)) {
|
|
116
121
|
if (wsServer.dueForSessionCheck(conn, SESSION_REVALIDATE_MS)) {
|
|
117
122
|
const hash = wsServer.getSessionTokenHash(conn);
|
|
118
123
|
const session = hash ? authQueries.getSessionByTokenHash(hash) : null;
|
|
@@ -127,6 +132,10 @@ wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
|
127
132
|
return result;
|
|
128
133
|
});
|
|
129
134
|
|
|
135
|
+
// The control catalog runs routes in-process through this router, so remote
|
|
136
|
+
// control (chat apps, later MCP) obeys the same auth gate as the web UI.
|
|
137
|
+
registerControlRouter(wsRouter);
|
|
138
|
+
|
|
130
139
|
// Register message rate limiter on WebSocket router — prevents DoS via message spam
|
|
131
140
|
wsRouter.setRateLimiter((conn, action, isRequest) => {
|
|
132
141
|
return messageRateLimiter.checkRateLimit(conn, action, isRequest);
|
|
@@ -154,7 +163,10 @@ const PORT = SERVER_ENV.PORT;
|
|
|
154
163
|
const HOST = SERVER_ENV.HOST;
|
|
155
164
|
|
|
156
165
|
// Create Elysia app
|
|
157
|
-
|
|
166
|
+
// Socket options must be given at the app level: Elysia only passes the
|
|
167
|
+
// server-wide `websocket` config to Bun.serve and silently ignores the same
|
|
168
|
+
// keys on a `.ws()` route (see WS_SERVER_OPTIONS).
|
|
169
|
+
const app = new Elysia({ websocket: WS_SERVER_OPTIONS })
|
|
158
170
|
// Apply middleware
|
|
159
171
|
.use(corsMiddleware)
|
|
160
172
|
.use(securityMiddleware)
|
|
@@ -190,7 +202,7 @@ const app = new Elysia()
|
|
|
190
202
|
})
|
|
191
203
|
|
|
192
204
|
// Per-project proxy for servers a repository declares in `.agents/mcp.json`.
|
|
193
|
-
// Only served while
|
|
205
|
+
// Only served while the file's current content has been approved — see
|
|
194
206
|
// backend/mcp/external/project.ts.
|
|
195
207
|
.all('/mcp/proj/:projectId/:name', async ({ request, params, server }) => {
|
|
196
208
|
server?.timeout(request, 0);
|
|
@@ -253,27 +265,24 @@ if (!isDevelopment) {
|
|
|
253
265
|
// an actual file before serving avoids this issue.
|
|
254
266
|
const distDir = resolve(process.cwd(), 'dist');
|
|
255
267
|
const indexHtml = await Bun.file(resolve(distDir, 'index.html')).text();
|
|
268
|
+
const indexEtag = `W/"${Bun.hash(indexHtml).toString(36)}"`;
|
|
256
269
|
|
|
257
|
-
|
|
270
|
+
// Caching and compression are decided in backend/http/static-assets.ts.
|
|
271
|
+
app.all('/*', ({ path, request }) => {
|
|
258
272
|
// Serve static files from dist/
|
|
259
273
|
if (path !== '/' && !path.includes('..')) {
|
|
260
274
|
const filePath = resolve(distDir, path.slice(1));
|
|
261
275
|
if (filePath.startsWith(distDir)) {
|
|
262
276
|
try {
|
|
263
277
|
if (statSync(filePath).isFile()) {
|
|
264
|
-
|
|
265
|
-
return new Response(file, {
|
|
266
|
-
headers: { 'Content-Type': file.type || 'application/octet-stream' }
|
|
267
|
-
});
|
|
278
|
+
return serveStaticFile(request, path, filePath);
|
|
268
279
|
}
|
|
269
280
|
} catch {}
|
|
270
281
|
}
|
|
271
282
|
}
|
|
272
283
|
|
|
273
284
|
// SPA fallback: serve cached index.html
|
|
274
|
-
return
|
|
275
|
-
headers: { 'Content-Type': 'text/html; charset=utf-8' }
|
|
276
|
-
});
|
|
285
|
+
return serveIndexHtml(request, indexHtml, indexEtag);
|
|
277
286
|
});
|
|
278
287
|
}
|
|
279
288
|
|
|
@@ -351,6 +360,10 @@ async function startServer() {
|
|
|
351
360
|
console.log(`🌐 Network access: http://${ip}:${PORT}`);
|
|
352
361
|
}
|
|
353
362
|
}
|
|
363
|
+
// Chat apps open only once the server can answer: registering a
|
|
364
|
+
// webhook makes the platform deliver to it right away, and a tunnel
|
|
365
|
+
// started for it forwards to this port.
|
|
366
|
+
void startChatApps();
|
|
354
367
|
});
|
|
355
368
|
}
|
|
356
369
|
|
|
@@ -405,6 +418,9 @@ async function gracefulShutdown() {
|
|
|
405
418
|
// Build-log follows are open HTTPS responses against a provider; nothing
|
|
406
419
|
// closes them but us.
|
|
407
420
|
stopAllBuildLogStreams();
|
|
421
|
+
// Chat-app bots: abort long-polls and close ChatKit's state store
|
|
422
|
+
// before the database (and the process) goes.
|
|
423
|
+
await stopChatApps();
|
|
408
424
|
// Close MCP remote server (before engines, as they may still reference it)
|
|
409
425
|
await closeMcpServer();
|
|
410
426
|
// Cleanup browser preview sessions
|
|
@@ -17,9 +17,54 @@ import type {
|
|
|
17
17
|
IntegrationStatus
|
|
18
18
|
} from '$shared/types/integrations';
|
|
19
19
|
import { defaultCapabilitiesOf, getProvider, type IntegrationProvider } from './registry';
|
|
20
|
+
import { randomBytes } from 'crypto';
|
|
20
21
|
import { reproject, releaseAll } from './projections';
|
|
21
22
|
import { debug } from '$shared/utils/logger';
|
|
22
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Told after any account is connected, reconfigured, toggled, rebound or
|
|
26
|
+
* disconnected — with the id, which may no longer exist.
|
|
27
|
+
*
|
|
28
|
+
* Projections cover surfaces whose state is a ROW. A surface whose state is a
|
|
29
|
+
* live connection instead (a chat channel's bot, held open by the backend)
|
|
30
|
+
* has nothing to project and needs to know when to reconnect; this is how.
|
|
31
|
+
* Listeners must be cheap and must not throw — they run inside the mutation.
|
|
32
|
+
*/
|
|
33
|
+
export type AccountsChangedListener = (accountId: string) => void;
|
|
34
|
+
|
|
35
|
+
const changeListeners = new Set<AccountsChangedListener>();
|
|
36
|
+
|
|
37
|
+
export function onAccountsChanged(listener: AccountsChangedListener): () => void {
|
|
38
|
+
changeListeners.add(listener);
|
|
39
|
+
return () => changeListeners.delete(listener);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function notifyChanged(accountId: string): void {
|
|
43
|
+
for (const listener of changeListeners) {
|
|
44
|
+
try {
|
|
45
|
+
listener(accountId);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
debug.error('integrations', 'Account change listener failed:', error);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Fill every credential the provider mints itself. 32 random bytes in
|
|
54
|
+
* base64url fits every secret alphabet seen so far — Telegram's secret token
|
|
55
|
+
* allows only `A-Za-z0-9_-`, up to 256 characters.
|
|
56
|
+
*/
|
|
57
|
+
export function withGeneratedCredentials(
|
|
58
|
+
provider: IntegrationProvider,
|
|
59
|
+
credentials: Record<string, string>
|
|
60
|
+
): Record<string, string> {
|
|
61
|
+
const filled = { ...credentials };
|
|
62
|
+
for (const field of provider.generatedCredentials ?? []) {
|
|
63
|
+
if (!(filled[field] ?? '').trim()) filled[field] = randomBytes(32).toString('base64url');
|
|
64
|
+
}
|
|
65
|
+
return filled;
|
|
66
|
+
}
|
|
67
|
+
|
|
23
68
|
export interface ConnectInput {
|
|
24
69
|
provider: string;
|
|
25
70
|
label?: string;
|
|
@@ -51,6 +96,11 @@ function assertRequiredFields(provider: IntegrationProvider, credentials: Record
|
|
|
51
96
|
}
|
|
52
97
|
}
|
|
53
98
|
|
|
99
|
+
function stripGenerated(provider: IntegrationProvider, credentials: Record<string, string>): Record<string, string> {
|
|
100
|
+
const generated = new Set(provider.generatedCredentials ?? []);
|
|
101
|
+
return Object.fromEntries(Object.entries(credentials).filter(([field]) => !generated.has(field)));
|
|
102
|
+
}
|
|
103
|
+
|
|
54
104
|
function assertKnownCapabilities(provider: IntegrationProvider, capabilities: IntegrationCapability[]): void {
|
|
55
105
|
const unknown = capabilities.filter((capability) => !provider.capabilities.includes(capability));
|
|
56
106
|
if (unknown.length > 0) {
|
|
@@ -130,7 +180,9 @@ export const integrationAccounts = {
|
|
|
130
180
|
label: (input.label ?? '').trim() || defaultLabel(provider),
|
|
131
181
|
projectId: input.projectId ?? null,
|
|
132
182
|
authMethod: provider.authMethod,
|
|
133
|
-
|
|
183
|
+
// Generated fields are Clopen's, not the form's: whatever a client sent
|
|
184
|
+
// for one is dropped rather than trusted as a secret.
|
|
185
|
+
credentials: withGeneratedCredentials(provider, stripGenerated(provider, input.credentials)),
|
|
134
186
|
capabilities
|
|
135
187
|
});
|
|
136
188
|
|
|
@@ -145,6 +197,7 @@ export const integrationAccounts = {
|
|
|
145
197
|
}
|
|
146
198
|
|
|
147
199
|
debug.log('integrations', `Connected ${provider.id} account "${row.label}"`);
|
|
200
|
+
notifyChanged(row.id);
|
|
148
201
|
return this.get(row.id)!;
|
|
149
202
|
},
|
|
150
203
|
|
|
@@ -161,15 +214,16 @@ export const integrationAccounts = {
|
|
|
161
214
|
const provider = requireProvider(row.provider);
|
|
162
215
|
|
|
163
216
|
const merged = { ...integrationAccountQueries.credentialsOf(row) };
|
|
164
|
-
for (const [field, value] of Object.entries(patch)) {
|
|
217
|
+
for (const [field, value] of Object.entries(stripGenerated(provider, patch))) {
|
|
165
218
|
if (value === '') continue;
|
|
166
219
|
merged[field] = value;
|
|
167
220
|
}
|
|
168
221
|
assertRequiredFields(provider, merged);
|
|
169
222
|
|
|
170
|
-
integrationAccountQueries.setCredentials(id, merged);
|
|
223
|
+
integrationAccountQueries.setCredentials(id, withGeneratedCredentials(provider, merged));
|
|
171
224
|
integrationAccountQueries.setStatus(id, 'unknown', null);
|
|
172
225
|
reproject(id);
|
|
226
|
+
notifyChanged(id);
|
|
173
227
|
return this.get(id)!;
|
|
174
228
|
},
|
|
175
229
|
|
|
@@ -197,6 +251,7 @@ export const integrationAccounts = {
|
|
|
197
251
|
|
|
198
252
|
integrationAccountQueries.setCapabilities(id, capabilities);
|
|
199
253
|
reproject(id);
|
|
254
|
+
notifyChanged(id);
|
|
200
255
|
return this.get(id)!;
|
|
201
256
|
},
|
|
202
257
|
|
|
@@ -204,6 +259,7 @@ export const integrationAccounts = {
|
|
|
204
259
|
if (!integrationAccountQueries.getById(id)) throw new Error('Integration account not found');
|
|
205
260
|
integrationAccountQueries.setEnabled(id, enabled);
|
|
206
261
|
reproject(id);
|
|
262
|
+
notifyChanged(id);
|
|
207
263
|
return this.get(id)!;
|
|
208
264
|
},
|
|
209
265
|
|
|
@@ -211,6 +267,7 @@ export const integrationAccounts = {
|
|
|
211
267
|
if (!integrationAccountQueries.getById(id)) throw new Error('Integration account not found');
|
|
212
268
|
integrationAccountQueries.setProject(id, projectId);
|
|
213
269
|
reproject(id);
|
|
270
|
+
notifyChanged(id);
|
|
214
271
|
return this.get(id)!;
|
|
215
272
|
},
|
|
216
273
|
|
|
@@ -225,5 +282,6 @@ export const integrationAccounts = {
|
|
|
225
282
|
releaseAll(id);
|
|
226
283
|
integrationAccountQueries.remove(id);
|
|
227
284
|
debug.log('integrations', `Disconnected ${row.provider} account "${row.label}"`);
|
|
285
|
+
notifyChanged(id);
|
|
228
286
|
}
|
|
229
287
|
};
|
|
@@ -22,8 +22,8 @@ export {
|
|
|
22
22
|
} from './registry';
|
|
23
23
|
export type { IntegrationProvider, McpPreset, WebhookSpec } from './registry';
|
|
24
24
|
|
|
25
|
-
export { integrationAccounts, toAccountInfo } from './accounts';
|
|
26
|
-
export type { ConnectInput } from './accounts';
|
|
25
|
+
export { integrationAccounts, toAccountInfo, onAccountsChanged, withGeneratedCredentials } from './accounts';
|
|
26
|
+
export type { ConnectInput, AccountsChangedListener } from './accounts';
|
|
27
27
|
|
|
28
28
|
export { reproject, releaseAll, registerProjector, projectableCapabilities } from './projections';
|
|
29
29
|
export type { Projector, ProjectionContext, ProjectionResult } from './projections';
|
|
@@ -29,6 +29,21 @@ export function defineProvider(provider: IntegrationProvider): IntegrationProvid
|
|
|
29
29
|
if (provider.capabilities.includes('inbound-events') && !provider.webhook) {
|
|
30
30
|
throw new Error(`Integration provider "${provider.id}" accepts inbound events but declares no webhook spec`);
|
|
31
31
|
}
|
|
32
|
+
for (const gate of provider.webhook?.capabilities ?? (provider.webhook ? ['inbound-events' as const] : [])) {
|
|
33
|
+
// The gateway only delivers to accounts holding one of these, so a spec
|
|
34
|
+
// naming one the provider cannot offer would accept nothing through it.
|
|
35
|
+
if (!provider.capabilities.includes(gate)) {
|
|
36
|
+
throw new Error(`Integration provider "${provider.id}" gates its webhook on a capability it does not offer: ${gate}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (provider.webhook?.scheme === 'header-token' && !provider.webhook.signatureHeader) {
|
|
40
|
+
throw new Error(`Integration provider "${provider.id}" uses a header token but names no header`);
|
|
41
|
+
}
|
|
42
|
+
for (const field of provider.generatedCredentials ?? []) {
|
|
43
|
+
if (provider.credentialFields.some((declared) => declared.name === field)) {
|
|
44
|
+
throw new Error(`Integration provider "${provider.id}" both asks for and generates "${field}"`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
32
47
|
for (const capability of provider.defaultCapabilities ?? []) {
|
|
33
48
|
if (!provider.capabilities.includes(capability)) {
|
|
34
49
|
throw new Error(`Integration provider "${provider.id}" defaults to a capability it does not offer: ${capability}`);
|
|
@@ -12,6 +12,7 @@ import firecrawl from './providers/firecrawl';
|
|
|
12
12
|
import github from './providers/github';
|
|
13
13
|
import neon from './providers/neon';
|
|
14
14
|
import supabase from './providers/supabase';
|
|
15
|
+
import telegram from './providers/telegram';
|
|
15
16
|
import vercel from './providers/vercel';
|
|
16
17
|
import type { IntegrationProvider } from './types';
|
|
17
18
|
import type { IntegrationProviderInfo } from '$shared/types/integrations';
|
|
@@ -26,6 +27,7 @@ export const PROVIDERS: readonly IntegrationProvider[] = [
|
|
|
26
27
|
github,
|
|
27
28
|
neon,
|
|
28
29
|
supabase,
|
|
30
|
+
telegram,
|
|
29
31
|
vercel
|
|
30
32
|
];
|
|
31
33
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram — the first chat app.
|
|
3
|
+
*
|
|
4
|
+
* ONE FIELD: the bot token. A bot is the account; WHO it talks to is not a
|
|
5
|
+
* property of the credential. A chat is paired with the bot from Settings →
|
|
6
|
+
* Chat Apps, so pairing another chat never means pasting the token twice.
|
|
7
|
+
*
|
|
8
|
+
* The webhook secret is GENERATED rather than asked for. Telegram has no
|
|
9
|
+
* console where a user would find one — Clopen picks it and tells Telegram in
|
|
10
|
+
* `setWebhook`, and Telegram echoes it back verbatim on every delivery. That
|
|
11
|
+
* echo is also what tells two connected bots' deliveries apart at the one
|
|
12
|
+
* shared hook URL.
|
|
13
|
+
*
|
|
14
|
+
* ONE capability: `control`. A paired chat is a remote control for Clopen
|
|
15
|
+
* (sessions, projects, files, skills, models, engine accounts: the whole
|
|
16
|
+
* control catalog in `backend/control/`), and the questions and answers it
|
|
17
|
+
* gets are part of that conversation, not a separate notification mode to
|
|
18
|
+
* switch on. Offering two capabilities for one bot only produced a bot
|
|
19
|
+
* that could ping you but not be answered.
|
|
20
|
+
*
|
|
21
|
+
* Deliveries are gated on `control`, not on `inbound-events`: a button press
|
|
22
|
+
* IS the channel working, and a further toggle to receive replies would be a
|
|
23
|
+
* trap.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { defineProvider } from '../define';
|
|
27
|
+
|
|
28
|
+
export default defineProvider({
|
|
29
|
+
id: 'telegram',
|
|
30
|
+
name: 'Telegram',
|
|
31
|
+
category: 'chat',
|
|
32
|
+
description:
|
|
33
|
+
'Control Clopen from Telegram: chat with any session (or none, from Home), send and get files, run your skills, switch projects and models, and answer questions or continue from any earlier message.',
|
|
34
|
+
docsUrl: 'https://t.me/BotFather',
|
|
35
|
+
authMethod: 'api-key',
|
|
36
|
+
capabilities: ['control'],
|
|
37
|
+
credentialFields: [
|
|
38
|
+
{
|
|
39
|
+
name: 'botToken',
|
|
40
|
+
label: 'Bot token',
|
|
41
|
+
placeholder: '123456789:AA…',
|
|
42
|
+
help: 'Message @BotFather on Telegram, send /newbot, and paste the token it replies with. Then link your chat from Settings → Chat Apps.',
|
|
43
|
+
isSecret: true,
|
|
44
|
+
isRequired: true
|
|
45
|
+
}
|
|
46
|
+
],
|
|
47
|
+
generatedCredentials: ['webhookSecret'],
|
|
48
|
+
webhook: {
|
|
49
|
+
scheme: 'header-token',
|
|
50
|
+
signatureHeader: 'x-telegram-bot-api-secret-token',
|
|
51
|
+
secretField: 'webhookSecret',
|
|
52
|
+
capabilities: ['control']
|
|
53
|
+
}
|
|
54
|
+
});
|
|
@@ -60,10 +60,15 @@ export interface WebhookSpec {
|
|
|
60
60
|
/**
|
|
61
61
|
* Signature scheme.
|
|
62
62
|
* - `hmac-sha256`: hex or base64 HMAC of the raw body, in `signatureHeader`.
|
|
63
|
+
* - `header-token`: the shared secret itself, echoed verbatim in
|
|
64
|
+
* `signatureHeader` (Telegram's `X-Telegram-Bot-Api-Secret-Token`). It
|
|
65
|
+
* proves the sender knows the secret, not that the body is untouched —
|
|
66
|
+
* which is all such a provider offers, and still enough to tell two
|
|
67
|
+
* connected accounts' deliveries apart.
|
|
63
68
|
* - `none`: no signature — only valid for providers that offer none, and
|
|
64
69
|
* the gateway still requires the account to be connected and enabled.
|
|
65
70
|
*/
|
|
66
|
-
scheme: 'hmac-sha256' | 'none';
|
|
71
|
+
scheme: 'hmac-sha256' | 'header-token' | 'none';
|
|
67
72
|
/** Header carrying the signature. */
|
|
68
73
|
signatureHeader?: string;
|
|
69
74
|
/** Optional prefix the provider puts in front of the digest, e.g. `sha256=`. */
|
|
@@ -74,6 +79,14 @@ export interface WebhookSpec {
|
|
|
74
79
|
deliveryIdHeader?: string;
|
|
75
80
|
/** Credential field holding the shared secret. */
|
|
76
81
|
secretField: string;
|
|
82
|
+
/**
|
|
83
|
+
* The capabilities that turn deliveries on for an account — ANY one of them
|
|
84
|
+
* is enough. Defaults to `['inbound-events']`. A provider whose webhook IS
|
|
85
|
+
* the transport of other capabilities — a chat channel's button presses and
|
|
86
|
+
* messages — names those instead, so receiving them does not depend on a
|
|
87
|
+
* further toggle the user would have no reason to understand.
|
|
88
|
+
*/
|
|
89
|
+
capabilities?: IntegrationCapability[];
|
|
77
90
|
}
|
|
78
91
|
|
|
79
92
|
export interface IntegrationProvider {
|
|
@@ -95,4 +108,11 @@ export interface IntegrationProvider {
|
|
|
95
108
|
mcp?: McpPreset;
|
|
96
109
|
/** Required when `capabilities` includes `inbound-events`. */
|
|
97
110
|
webhook?: WebhookSpec;
|
|
111
|
+
/**
|
|
112
|
+
* Credential fields Clopen mints itself at connect time — a webhook secret
|
|
113
|
+
* the provider is TOLD rather than one the user copies out of a console.
|
|
114
|
+
* Never rendered in the connect form and never reported as configured, but
|
|
115
|
+
* stored, sealed and read exactly like any other credential.
|
|
116
|
+
*/
|
|
117
|
+
generatedCredentials?: string[];
|
|
98
118
|
}
|
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
* is computed over raw bytes, and replay rejection is a unique-constraint
|
|
13
13
|
* insert rather than a read-then-write.
|
|
14
14
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
15
|
+
* Subscribers register per provider with `onWebhook()`. A verified delivery
|
|
16
|
+
* nobody subscribed to is accepted, counted and dropped.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { integrationAccountQueries, integrationWebhookQueries } from '$backend/database/queries';
|
|
@@ -102,15 +102,16 @@ export async function handleInboundDelivery(
|
|
|
102
102
|
|
|
103
103
|
if (rateLimited(providerId)) return reject(providerId, 'rate limit exceeded');
|
|
104
104
|
|
|
105
|
-
// Every enabled account for this provider that opted into
|
|
105
|
+
// Every enabled account for this provider that opted into deliveries.
|
|
106
106
|
// More than one is legitimate: two projects, two orgs, one endpoint.
|
|
107
|
+
const spec = provider.webhook;
|
|
108
|
+
const gates = spec.capabilities ?? ['inbound-events'];
|
|
107
109
|
const accounts = integrationAccountQueries
|
|
108
110
|
.getEnabledForProvider(providerId)
|
|
109
|
-
.filter((row) => integrationAccountQueries.capabilitiesOf(row).includes(
|
|
111
|
+
.filter((row) => integrationAccountQueries.capabilitiesOf(row).some((capability) => gates.includes(capability)));
|
|
110
112
|
|
|
111
|
-
if (accounts.length === 0) return reject(providerId,
|
|
113
|
+
if (accounts.length === 0) return reject(providerId, `no enabled account has ${gates.join(' or ')} on`);
|
|
112
114
|
|
|
113
|
-
const spec = provider.webhook;
|
|
114
115
|
const matched = accounts.find((account) => {
|
|
115
116
|
const secret = integrationAccountQueries.credentialsOf(account)[spec.secretField] ?? '';
|
|
116
117
|
return verifySignature(spec, secret, rawBody, headers).ok;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { describe, it, expect } from 'bun:test';
|
|
2
|
+
import { createHmac } from 'crypto';
|
|
3
|
+
import { verifySignature } from './verify';
|
|
4
|
+
import type { WebhookSpec } from '../registry';
|
|
5
|
+
|
|
6
|
+
const body = new TextEncoder().encode('{"update_id":1}');
|
|
7
|
+
|
|
8
|
+
describe('header-token', () => {
|
|
9
|
+
const spec: WebhookSpec = { scheme: 'header-token', signatureHeader: 'x-telegram-bot-api-secret-token', secretField: 'webhookSecret' };
|
|
10
|
+
|
|
11
|
+
it('accepts the exact secret', () => {
|
|
12
|
+
const headers = new Headers({ 'x-telegram-bot-api-secret-token': 's3cret' });
|
|
13
|
+
expect(verifySignature(spec, 's3cret', body, headers).ok).toBe(true);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('rejects another account\'s secret, a missing header and an empty secret', () => {
|
|
17
|
+
expect(verifySignature(spec, 's3cret', body, new Headers({ 'x-telegram-bot-api-secret-token': 'other' })).ok).toBe(false);
|
|
18
|
+
expect(verifySignature(spec, 's3cret', body, new Headers()).ok).toBe(false);
|
|
19
|
+
expect(verifySignature(spec, '', body, new Headers({ 'x-telegram-bot-api-secret-token': '' })).ok).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe('hmac-sha256', () => {
|
|
24
|
+
it('still verifies over the raw bytes', () => {
|
|
25
|
+
const spec: WebhookSpec = { scheme: 'hmac-sha256', signatureHeader: 'x-signature', signaturePrefix: 'sha256=', secretField: 'secret' };
|
|
26
|
+
const digest = createHmac('sha256', 'k').update(body).digest('hex');
|
|
27
|
+
expect(verifySignature(spec, 'k', body, new Headers({ 'x-signature': `sha256=${digest}` })).ok).toBe(true);
|
|
28
|
+
expect(verifySignature(spec, 'k', body, new Headers({ 'x-signature': `sha256=${digest.slice(1)}0` })).ok).toBe(false);
|
|
29
|
+
});
|
|
30
|
+
});
|