@myrialabs/clopen 0.4.37 → 0.4.39

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.
Files changed (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Provider registry — the single source of truth for what Clopen can connect to.
3
+ *
4
+ * Mirrors the internal-MCP `defineServer()` pattern: a provider is added by
5
+ * writing one file under `providers/` and putting it in the array below.
6
+ * Everything else — the hub listing, the connect dialog's fields, the
7
+ * projection, the webhook route — is derived from that declaration.
8
+ */
9
+
10
+ import context7 from './providers/context7';
11
+ import firecrawl from './providers/firecrawl';
12
+ import github from './providers/github';
13
+ import supabase from './providers/supabase';
14
+ import vercel from './providers/vercel';
15
+ import type { IntegrationProvider } from './types';
16
+ import type { IntegrationProviderInfo } from '$shared/types/integrations';
17
+
18
+ export type { IntegrationProvider, McpPreset, WebhookSpec } from './types';
19
+ export { defineProvider } from './define';
20
+
21
+ /** Every declared provider. Add new ones here. */
22
+ export const PROVIDERS: readonly IntegrationProvider[] = [
23
+ context7,
24
+ firecrawl,
25
+ github,
26
+ supabase,
27
+ vercel
28
+ ];
29
+
30
+ const byId = new Map(PROVIDERS.map((provider) => [provider.id, provider]));
31
+
32
+ export function getProvider(id: string): IntegrationProvider | null {
33
+ return byId.get(id) ?? null;
34
+ }
35
+
36
+ /** Capabilities turned on when an account is first connected. */
37
+ export function defaultCapabilitiesOf(provider: IntegrationProvider): IntegrationProvider['capabilities'] {
38
+ return provider.defaultCapabilities ?? provider.capabilities;
39
+ }
40
+
41
+ /** The provider as the hub renders it — declaration minus anything internal. */
42
+ export function toProviderInfo(provider: IntegrationProvider): IntegrationProviderInfo {
43
+ return {
44
+ id: provider.id,
45
+ name: provider.name,
46
+ category: provider.category,
47
+ description: provider.description,
48
+ docsUrl: provider.docsUrl,
49
+ authMethod: provider.authMethod,
50
+ credentialFields: provider.credentialFields,
51
+ capabilities: [...provider.capabilities],
52
+ defaultCapabilities: [...defaultCapabilitiesOf(provider)],
53
+ providesAgentTools: provider.capabilities.includes('agent-tools'),
54
+ acceptsWebhooks: provider.capabilities.includes('inbound-events')
55
+ };
56
+ }
57
+
58
+ export function listProviderInfo(): IntegrationProviderInfo[] {
59
+ return PROVIDERS.map(toProviderInfo);
60
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Context7 — up-to-date library documentation for a coding agent.
3
+ *
4
+ * This is one of the two presets that prove the credential-projection paths.
5
+ * Context7 covers the REMOTE path: the stored API key is projected into a
6
+ * request HEADER on an HTTP MCP server, which is the shape every hosted MCP
7
+ * server with a static key uses.
8
+ */
9
+
10
+ import { defineProvider } from '../define';
11
+
12
+ export default defineProvider({
13
+ id: 'context7',
14
+ name: 'Context7',
15
+ category: 'research',
16
+ description:
17
+ 'Pulls current, version-accurate documentation for a library straight into the session, so the agent stops writing against the API it remembers.',
18
+ docsUrl: 'https://context7.com',
19
+ authMethod: 'api-key',
20
+ capabilities: ['agent-tools'],
21
+ credentialFields: [
22
+ {
23
+ name: 'apiKey',
24
+ label: 'API key',
25
+ placeholder: 'ctx7sk-…',
26
+ help: 'Created in your Context7 dashboard. The free tier is enough for everyday use.',
27
+ isSecret: true,
28
+ isRequired: true
29
+ }
30
+ ],
31
+ mcp: {
32
+ slug: 'context7',
33
+ name: 'Context7',
34
+ description: 'Library documentation lookup',
35
+ transport: 'http',
36
+ url: 'https://mcp.context7.com/mcp',
37
+ // The remote endpoint authenticates with the key in its own header
38
+ // rather than `Authorization`, which is why the preset declares the
39
+ // header name instead of assuming a bearer token.
40
+ headers: {
41
+ apiKey: { name: 'CONTEXT7_API_KEY' }
42
+ }
43
+ }
44
+ });
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Firecrawl — crawl a live site and hand the agent clean markdown.
3
+ *
4
+ * The second of the two proof presets, covering the STDIO path: the stored API
5
+ * key is projected into the child process's ENVIRONMENT, which is the shape
6
+ * every locally-spawned MCP server uses.
7
+ */
8
+
9
+ import { defineProvider } from '../define';
10
+
11
+ export default defineProvider({
12
+ id: 'firecrawl',
13
+ name: 'Firecrawl',
14
+ category: 'research',
15
+ description:
16
+ 'Crawls and converts live sites into clean markdown. Pairs with the browser automation tools rather than replacing them — this is for reading a site at scale, not driving one.',
17
+ docsUrl: 'https://firecrawl.dev',
18
+ authMethod: 'api-key',
19
+ capabilities: ['agent-tools'],
20
+ credentialFields: [
21
+ {
22
+ name: 'apiKey',
23
+ label: 'API key',
24
+ placeholder: 'fc-…',
25
+ help: 'From your Firecrawl dashboard.',
26
+ isSecret: true,
27
+ isRequired: true
28
+ }
29
+ ],
30
+ mcp: {
31
+ slug: 'firecrawl',
32
+ name: 'Firecrawl',
33
+ description: 'Web crawling and markdown extraction',
34
+ transport: 'stdio',
35
+ command: 'npx',
36
+ args: ['-y', 'firecrawl-mcp'],
37
+ env: {
38
+ apiKey: 'FIRECRAWL_API_KEY'
39
+ }
40
+ }
41
+ });
@@ -0,0 +1,78 @@
1
+ /**
2
+ * GitHub — the first provider behind the Issues & PRs surface.
3
+ *
4
+ * AUTH IS A PERSONAL ACCESS TOKEN, and the guidance is CLASSIC, not
5
+ * fine-grained. That is a correction: the first version recommended
6
+ * fine-grained tokens for least privilege, and least privilege is the wrong
7
+ * trade when it silently removes access the user already has.
8
+ *
9
+ * A fine-grained token is scoped to ONE resource owner. It cannot reach a
10
+ * repository owned by another person at all — being a collaborator does not
11
+ * help, because that owner never granted the token — and an organisation's
12
+ * repositories stay invisible until an owner approves it. Both failures arrive
13
+ * as an ordinary 404, which reads as "your repository does not exist". For a
14
+ * tool whose whole premise is working on the repositories you already
15
+ * collaborate on, that is the common case broken by default.
16
+ *
17
+ * A classic token with `repo` reaches exactly what its user reaches, which is
18
+ * the behaviour people expect. Fine-grained tokens still work where they apply
19
+ * and are not rejected — the diagnosis in the adapter names the difference when
20
+ * one of them cannot see a repository.
21
+ *
22
+ * The OAuth device flow the spec sketched is still not used: it needs an
23
+ * embedded client id that makes every self-hosted install depend on one app we
24
+ * own, and it can be added later without changing what is stored, since it is
25
+ * only another way to fill the same `token` field.
26
+ *
27
+ * `agent-tools` is DECLARED but OFF by default. GitHub's official remote MCP
28
+ * server accepts the same token, so offering it costs nothing — but adding a
29
+ * tool namespace to every engine in every session is a thing a user should turn
30
+ * on, not something that happens because they wanted to see their issues.
31
+ */
32
+
33
+ import { defineProvider } from '../define';
34
+
35
+ export default defineProvider({
36
+ id: 'github',
37
+ name: 'GitHub',
38
+ category: 'source-control',
39
+ description:
40
+ 'Issues, pull requests and Actions for the repository this project pushes to. Start work on an issue in its own worktree, open and merge pull requests, and send a failing CI run into the chat.',
41
+ docsUrl: 'https://github.com/settings/tokens/new?scopes=repo,read:org&description=Clopen',
42
+ authMethod: 'api-key',
43
+ capabilities: ['work', 'agent-tools'],
44
+ // Connecting GitHub means "show me my work", not "give every agent GitHub
45
+ // tools". The second is one switch away in the hub.
46
+ defaultCapabilities: ['work'],
47
+ credentialFields: [
48
+ {
49
+ name: 'token',
50
+ label: 'Personal access token (classic)',
51
+ placeholder: 'ghp_…',
52
+ // Deliberately short. The full explanation of why classic beats
53
+ // fine-grained belongs in the error a failing token produces, where
54
+ // it is actionable — not in a paragraph nobody reads while pasting.
55
+ help: 'Scope: "repo" (plus "read:org" for SAML organisations). Fine-grained tokens work too, but only for repositories their owner granted.',
56
+ isSecret: true,
57
+ isRequired: true
58
+ },
59
+ {
60
+ name: 'baseUrl',
61
+ label: 'Enterprise Server URL',
62
+ placeholder: 'https://github.your-company.com',
63
+ help: 'Leave empty for github.com. Set this only for GitHub Enterprise Server.',
64
+ isSecret: false,
65
+ isRequired: false
66
+ }
67
+ ],
68
+ mcp: {
69
+ slug: 'github',
70
+ name: 'GitHub',
71
+ description: 'Official GitHub MCP server — repositories, issues, pull requests and Actions',
72
+ transport: 'http',
73
+ url: 'https://api.githubcopilot.com/mcp/',
74
+ headers: {
75
+ token: { name: 'Authorization', format: 'Bearer {value}' }
76
+ }
77
+ }
78
+ });
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Supabase — the first provider behind the `database` capability.
3
+ *
4
+ * ONE CREDENTIAL FIELD, for the reason Vercel has one. A personal access token
5
+ * reaches every project in every organisation its user belongs to, so "which
6
+ * project" is not a property of the credential — it is a choice, made as many
7
+ * times as the user has databases worth opening. Those choices live in
8
+ * `integration_db_links`, and each one projects a `db_client_connections` row.
9
+ *
10
+ * SCOPED TOKENS are the thing to know about this provider. Supabase is rolling
11
+ * out personal access tokens that carry only the permissions you pick, and they
12
+ * are prefixed `sbp_fc` where a classic full-access token is plain `sbp_`. A
13
+ * scoped token that is missing a permission fails with an undecorated
14
+ * "Forbidden" at the moment the feature is reached, so the client reads that
15
+ * prefix and says which scope is likely absent — the same trick `Task 2` used on
16
+ * GitHub's fine-grained token prefix, and for the same reason.
17
+ *
18
+ * The DATABASE PASSWORD is deliberately not a credential field here. It is not
19
+ * a property of the account either: every project has its own, and no API can
20
+ * read any of them back. It belongs to the link, which is where it is stored.
21
+ *
22
+ * NO `agent-tools`, even though Supabase ships an MCP server that takes exactly
23
+ * this token. That server is scoped with `--project-ref` to ONE project, and an
24
+ * account here can hold several — so there is no honest single row to project.
25
+ * A user who wants those tools installs the server from the MCP registry, which
26
+ * the hub still offers; the day this becomes a per-link capability rather than a
27
+ * per-account one it can be revisited.
28
+ *
29
+ * NO `inbound-events`. Supabase's webhooks are database triggers rather than a
30
+ * signed platform delivery, and `Task 7` is the first entry with a subscriber
31
+ * worth registering one for.
32
+ */
33
+
34
+ import { defineProvider } from '../define';
35
+
36
+ export default defineProvider({
37
+ id: 'supabase',
38
+ name: 'Supabase',
39
+ category: 'database',
40
+ description:
41
+ 'Postgres projects as connections in DB Client, with the Supabase surface on top: migrations and what is still pending, RLS policies and the security advisor, edge functions, storage buckets, auth users, and generated TypeScript types written into the project.',
42
+ docsUrl: 'https://supabase.com/dashboard/account/tokens',
43
+ authMethod: 'api-key',
44
+ capabilities: ['database'],
45
+ credentialFields: [
46
+ {
47
+ name: 'accessToken',
48
+ label: 'Personal access token',
49
+ placeholder: 'sbp_…',
50
+ // Names the PERMISSIONS rather than describing the screen. Supabase is
51
+ // rolling out scoped tokens, and a scoped token missing one permission
52
+ // fails at the moment the feature is used, with a bare "Forbidden" that
53
+ // says nothing about which scope is absent — so the fix has to be
54
+ // stated before the token is created, not diagnosed afterwards.
55
+ help:
56
+ 'Account Settings → Access Tokens. A classic token works as is. A SCOPED token (they start with sbp_fc) needs: Projects (account-wide) Read to list, Project Settings Read, and Database Read-write. Add Organizations Read and Organization Projects Read-write to create projects from here.',
57
+ isSecret: true,
58
+ isRequired: true
59
+ }
60
+ ]
61
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Vercel — the first provider behind the Deployments surface.
3
+ *
4
+ * ONE CREDENTIAL FIELD, deliberately. A Vercel token reaches the personal
5
+ * account and every team its user belongs to, so "which team" is not a property
6
+ * of the credential — it is a property of the project you picked. Putting a
7
+ * `teamId` field here would force a user with two teams to connect the same
8
+ * token twice, and would make the first project they bind decide the second.
9
+ * The team is stored on the binding instead, where it belongs.
10
+ *
11
+ * NO `agent-tools`. Vercel does run an MCP server, but it authenticates with
12
+ * its own OAuth rather than this REST token — a different audience, which the
13
+ * account layer treats as a second credential rather than a reuse of this one.
14
+ * Declaring the capability would mean projecting an MCP row we cannot fill from
15
+ * what is stored here. It stays addable later as its own provider entry.
16
+ *
17
+ * NO `inbound-events`. Vercel can sign webhooks, but a Clopen that is usually
18
+ * reached on localhost has no public URL to register, and `Task 7` is the first
19
+ * entry that builds a subscriber worth registering one for.
20
+ */
21
+
22
+ import { defineProvider } from '../define';
23
+
24
+ export default defineProvider({
25
+ id: 'vercel',
26
+ name: 'Vercel',
27
+ category: 'deployment',
28
+ description:
29
+ 'Deployments for the project this repository builds to. Watch a build as it runs, send a failed build log into the chat, open a preview build in the browser panel, and redeploy, cancel, roll back or promote from here.',
30
+ docsUrl: 'https://vercel.com/account/tokens',
31
+ authMethod: 'api-key',
32
+ capabilities: ['deployments'],
33
+ credentialFields: [
34
+ {
35
+ name: 'token',
36
+ label: 'Access token',
37
+ placeholder: 'Vercel access token',
38
+ // Scope guidance rather than a tutorial: the failure this prevents is
39
+ // a token scoped to one team that then cannot see another team's
40
+ // project, which arrives as an empty list rather than an error.
41
+ help: 'Account Settings → Tokens. A token scoped to a team only reaches that team\'s projects — pick "Full Account" if this Clopen deploys for more than one.',
42
+ isSecret: true,
43
+ isRequired: true
44
+ }
45
+ ]
46
+ });
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Provider registry types.
3
+ *
4
+ * A provider is a DECLARATION, not code: what it is called, how it
5
+ * authenticates, which credential fields it needs, which capabilities it can
6
+ * offer, and — when it offers agent tools — how the stored credential maps onto
7
+ * the env vars or headers the upstream MCP server expects.
8
+ *
9
+ * Providers carry NO icon field. The brand mark is keyed by provider id in
10
+ * `shared/constants/tool-icons.ts`, so a provider whose artwork has not been
11
+ * added yet falls back to a generic glyph instead of blocking the entry.
12
+ */
13
+
14
+ import type {
15
+ IntegrationAuthMethod,
16
+ IntegrationCapability,
17
+ IntegrationCategory,
18
+ IntegrationCredentialField
19
+ } from '$shared/types/integrations';
20
+ import type { McpTransport } from '$backend/database/queries';
21
+
22
+ /**
23
+ * How a stored credential lands on an MCP server row.
24
+ *
25
+ * `env` is the stdio path and `headers` the remote path. A preset declares one
26
+ * or the other (or both, for a server that accepts either), and the projector
27
+ * writes only what the transport actually uses.
28
+ */
29
+ export interface McpPreset {
30
+ /** Slug of the projected `mcp_servers` row. Also the namespace engines see. */
31
+ slug: string;
32
+ name: string;
33
+ description: string;
34
+ transport: McpTransport;
35
+
36
+ /** stdio */
37
+ command?: string;
38
+ args?: string[];
39
+
40
+ /** http / sse */
41
+ url?: string;
42
+
43
+ /** Credential field name → environment variable name. */
44
+ env?: Record<string, string>;
45
+
46
+ /**
47
+ * Credential field name → header name, optionally wrapped.
48
+ * `format` receives the credential value as `{value}` — `Bearer {value}`
49
+ * being the common case.
50
+ */
51
+ headers?: Record<string, { name: string; format?: string }>;
52
+
53
+ /** Values that carry no secret and are written verbatim. */
54
+ staticEnv?: Record<string, string>;
55
+ staticHeaders?: Record<string, string>;
56
+ }
57
+
58
+ /** How an inbound delivery from this provider is authenticated. */
59
+ export interface WebhookSpec {
60
+ /**
61
+ * Signature scheme.
62
+ * - `hmac-sha256`: hex or base64 HMAC of the raw body, in `signatureHeader`.
63
+ * - `none`: no signature — only valid for providers that offer none, and
64
+ * the gateway still requires the account to be connected and enabled.
65
+ */
66
+ scheme: 'hmac-sha256' | 'none';
67
+ /** Header carrying the signature. */
68
+ signatureHeader?: string;
69
+ /** Optional prefix the provider puts in front of the digest, e.g. `sha256=`. */
70
+ signaturePrefix?: string;
71
+ /** Encoding of the digest in the header. */
72
+ digestEncoding?: 'hex' | 'base64';
73
+ /** Header carrying the provider's unique delivery id, used for replay rejection. */
74
+ deliveryIdHeader?: string;
75
+ /** Credential field holding the shared secret. */
76
+ secretField: string;
77
+ }
78
+
79
+ export interface IntegrationProvider {
80
+ /** Machine id. `[a-z0-9-]` only — it keys the brand mark and the hook URL. */
81
+ id: string;
82
+ name: string;
83
+ category: IntegrationCategory;
84
+ description: string;
85
+ docsUrl?: string;
86
+ authMethod: IntegrationAuthMethod;
87
+ credentialFields: IntegrationCredentialField[];
88
+ /** Everything this provider is able to offer. */
89
+ capabilities: IntegrationCapability[];
90
+ /** Turned on at connect time. Defaults to every capability when omitted. */
91
+ defaultCapabilities?: IntegrationCapability[];
92
+ /** Required when `capabilities` includes `agent-tools`. */
93
+ mcp?: McpPreset;
94
+ /** Required when `capabilities` includes `inbound-events`. */
95
+ webhook?: WebhookSpec;
96
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Inbound event gateway.
3
+ *
4
+ * ONE unauthenticated endpoint, `/api/integrations/hooks/<provider>`. Treat it
5
+ * as a new attack surface, because it is: it is the only route in Clopen that
6
+ * anyone on the internet can reach without a session.
7
+ *
8
+ * Deny by default. Every rejection answers 404 — for an unknown provider, for a
9
+ * provider nobody has connected, and for one that is disabled — so an
10
+ * unauthenticated caller cannot use response codes to enumerate what this
11
+ * install has connected. The body cap is applied BEFORE parsing, the signature
12
+ * is computed over raw bytes, and replay rejection is a unique-constraint
13
+ * insert rather than a read-then-write.
14
+ *
15
+ * It ships with no subscriber. Registering one is `Task 7`'s job; until then a
16
+ * verified delivery is accepted, counted and dropped.
17
+ */
18
+
19
+ import { integrationAccountQueries, integrationWebhookQueries } from '$backend/database/queries';
20
+ import { getProvider } from '../registry';
21
+ import { verifySignature } from './verify';
22
+ import { debug } from '$shared/utils/logger';
23
+
24
+ /** Applied before anything reads the body. A signature check on 50 MB is still 50 MB. */
25
+ export const MAX_BODY_BYTES = 1024 * 1024;
26
+
27
+ /** Per-provider window. Generous enough for a busy repo, small enough to be a limit. */
28
+ const RATE_LIMIT_WINDOW_MS = 60_000;
29
+ const RATE_LIMIT_MAX = 120;
30
+
31
+ /** Delivery ids older than this are pruned — replay protection does not need history. */
32
+ const DELIVERY_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
33
+
34
+ export interface WebhookEvent {
35
+ provider: string;
36
+ accountId: string;
37
+ deliveryId: string;
38
+ headers: Headers;
39
+ /** Parsed body. Parsing happens only AFTER the signature is verified. */
40
+ payload: unknown;
41
+ rawBody: Uint8Array;
42
+ }
43
+
44
+ export type WebhookSubscriber = (event: WebhookEvent) => void | Promise<void>;
45
+
46
+ const subscribers = new Map<string, WebhookSubscriber[]>();
47
+
48
+ /** Subscribe to verified deliveries for one provider. */
49
+ export function onWebhook(provider: string, subscriber: WebhookSubscriber): void {
50
+ const list = subscribers.get(provider) ?? [];
51
+ list.push(subscriber);
52
+ subscribers.set(provider, list);
53
+ }
54
+
55
+ const rateWindows = new Map<string, { count: number; resetAt: number }>();
56
+
57
+ function rateLimited(provider: string): boolean {
58
+ const now = Date.now();
59
+ const window = rateWindows.get(provider);
60
+
61
+ if (!window || now >= window.resetAt) {
62
+ rateWindows.set(provider, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
63
+ return false;
64
+ }
65
+ window.count += 1;
66
+ return window.count > RATE_LIMIT_MAX;
67
+ }
68
+
69
+ let lastPruneAt = 0;
70
+
71
+ function pruneDeliveriesOccasionally(): void {
72
+ const now = Date.now();
73
+ if (now - lastPruneAt < DELIVERY_RETENTION_MS / 24) return;
74
+ lastPruneAt = now;
75
+ integrationWebhookQueries.pruneBefore(new Date(now - DELIVERY_RETENTION_MS).toISOString());
76
+ }
77
+
78
+ /**
79
+ * Every rejection logs and answers 404.
80
+ *
81
+ * The status is deliberately uniform. A 401 would confirm the provider is
82
+ * connected, a 400 would confirm the signature header shape — both are free
83
+ * reconnaissance for something that costs us nothing to withhold.
84
+ */
85
+ function reject(provider: string, reason: string): Response {
86
+ debug.warn('integrations', `Rejected inbound ${provider} delivery: ${reason}`);
87
+ return new Response('Not found', { status: 404 });
88
+ }
89
+
90
+ /**
91
+ * Handle one inbound delivery.
92
+ *
93
+ * `rawBody` must be the untouched request bytes — see `verify.ts` for why.
94
+ */
95
+ export async function handleInboundDelivery(
96
+ providerId: string,
97
+ rawBody: Uint8Array,
98
+ headers: Headers
99
+ ): Promise<Response> {
100
+ const provider = getProvider(providerId);
101
+ if (!provider?.webhook) return reject(providerId, 'unknown provider or no webhook spec');
102
+
103
+ if (rateLimited(providerId)) return reject(providerId, 'rate limit exceeded');
104
+
105
+ // Every enabled account for this provider that opted into inbound events.
106
+ // More than one is legitimate: two projects, two orgs, one endpoint.
107
+ const accounts = integrationAccountQueries
108
+ .getEnabledForProvider(providerId)
109
+ .filter((row) => integrationAccountQueries.capabilitiesOf(row).includes('inbound-events'));
110
+
111
+ if (accounts.length === 0) return reject(providerId, 'no enabled account accepts inbound events');
112
+
113
+ const spec = provider.webhook;
114
+ const matched = accounts.find((account) => {
115
+ const secret = integrationAccountQueries.credentialsOf(account)[spec.secretField] ?? '';
116
+ return verifySignature(spec, secret, rawBody, headers).ok;
117
+ });
118
+
119
+ if (!matched) return reject(providerId, 'no connected account produced a matching signature');
120
+
121
+ // A provider that sends no delivery id gets one derived from its own bytes,
122
+ // so replay rejection still works — a byte-identical redelivery is exactly
123
+ // what we want to drop.
124
+ const deliveryId = (spec.deliveryIdHeader && headers.get(spec.deliveryIdHeader))
125
+ || Bun.hash(rawBody).toString(16);
126
+
127
+ if (!integrationWebhookQueries.claimDelivery(providerId, deliveryId)) {
128
+ debug.log('integrations', `Ignoring replayed ${providerId} delivery ${deliveryId}`);
129
+ return new Response('OK', { status: 200 });
130
+ }
131
+
132
+ pruneDeliveriesOccasionally();
133
+
134
+ let payload: unknown = null;
135
+ try {
136
+ payload = JSON.parse(new TextDecoder().decode(rawBody));
137
+ } catch {
138
+ // A provider that posts something other than JSON still gets delivered —
139
+ // subscribers have the raw bytes.
140
+ }
141
+
142
+ const event: WebhookEvent = {
143
+ provider: providerId,
144
+ accountId: matched.id,
145
+ deliveryId,
146
+ headers,
147
+ payload,
148
+ rawBody
149
+ };
150
+
151
+ // Answer the provider first. A subscriber that throws or hangs must not turn
152
+ // into a delivery failure and a retry storm on their side.
153
+ for (const subscriber of subscribers.get(providerId) ?? []) {
154
+ void Promise.resolve()
155
+ .then(() => subscriber(event))
156
+ .catch((error) => debug.error('integrations', `Webhook subscriber for ${providerId} failed:`, error));
157
+ }
158
+
159
+ return new Response('OK', { status: 200 });
160
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Inbound signature verification.
3
+ *
4
+ * The digest is computed over the RAW REQUEST BYTES. Not the parsed body, not a
5
+ * re-serialised copy of it: `JSON.parse` followed by `JSON.stringify` reorders
6
+ * keys, drops insignificant whitespace and normalises escapes, and a valid
7
+ * signature over the original bytes will not match the result. This is the
8
+ * single most common way a webhook verifier ends up rejecting every genuine
9
+ * delivery, or — worse — being "fixed" by disabling it.
10
+ */
11
+
12
+ import { createHmac, timingSafeEqual } from 'crypto';
13
+ import type { WebhookSpec } from '../registry';
14
+
15
+ export type VerifyOutcome =
16
+ | { ok: true }
17
+ | { ok: false; reason: string };
18
+
19
+ /**
20
+ * Compare in constant time.
21
+ *
22
+ * `timingSafeEqual` throws on a length mismatch, which would leak length
23
+ * through an exception, so the lengths are checked first and a mismatch is
24
+ * simply a failure.
25
+ */
26
+ function safeEqual(a: string, b: string): boolean {
27
+ const left = Buffer.from(a);
28
+ const right = Buffer.from(b);
29
+ if (left.length !== right.length) return false;
30
+ return timingSafeEqual(left, right);
31
+ }
32
+
33
+ export function verifySignature(
34
+ spec: WebhookSpec,
35
+ secret: string,
36
+ rawBody: Uint8Array,
37
+ headers: Headers
38
+ ): VerifyOutcome {
39
+ if (spec.scheme === 'none') return { ok: true };
40
+
41
+ if (!spec.signatureHeader) {
42
+ return { ok: false, reason: 'provider declares a signature scheme but no header' };
43
+ }
44
+ if (!secret) {
45
+ return { ok: false, reason: 'no signing secret configured on the account' };
46
+ }
47
+
48
+ const presented = headers.get(spec.signatureHeader);
49
+ if (!presented) {
50
+ return { ok: false, reason: `missing ${spec.signatureHeader}` };
51
+ }
52
+
53
+ const prefix = spec.signaturePrefix ?? '';
54
+ if (prefix && !presented.startsWith(prefix)) {
55
+ return { ok: false, reason: 'signature prefix mismatch' };
56
+ }
57
+
58
+ const digest = createHmac('sha256', secret)
59
+ .update(rawBody)
60
+ .digest(spec.digestEncoding ?? 'hex');
61
+
62
+ return safeEqual(presented.slice(prefix.length), digest)
63
+ ? { ok: true }
64
+ : { ok: false, reason: 'signature mismatch' };
65
+ }