@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -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,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
+ }
@@ -6,7 +6,7 @@ disk and in their namespace keys:
6
6
  | | **Internal** (`internal/`) | **External** (`external/`) |
7
7
  |---|---|---|
8
8
  | What | Custom tools defined in code via `defineServer()` | Servers the user installs from the official MCP registry |
9
- | Managed | By developers (this README) | By users in **Settings → MCP** |
9
+ | Managed | By developers (this README) | By users in **Settings → Integrations** |
10
10
  | Stored | In code (`internal/servers/`) | In the DB (`mcp_servers` table) |
11
11
  | Namespace | `clopen-mcp` bridge (non-Claude) / server name (Claude) | one bare `<slug>` per server (no prefix) |
12
12
  | Execution | In-process (no subprocess) | Engine connects to Clopen's `/mcp/ext/<slug>` proxy; Clopen connects to the real upstream (stdio subprocess or remote HTTP) |
@@ -19,6 +19,27 @@ The rest of this document covers the **internal** custom-tool system. External
19
19
  servers need no code — see `external/registry-client.ts`, `external/config.ts`,
20
20
  and `external/proxy.ts` (the per-server `/mcp/ext/<slug>` proxy bridge).
21
21
 
22
+ ### Where `backend/integrations/` fits
23
+
24
+ MCP is a **protocol**; an integration is a **credential with capabilities**.
25
+ They are separate modules on purpose, and `backend/integrations/` is the newer
26
+ of the two:
27
+
28
+ - `backend/mcp/` owns installing, proxying, per-engine tool exposure and
29
+ MCP-level OAuth. It knows nothing about accounts.
30
+ - `backend/integrations/` owns the account and its credential. One of the
31
+ capabilities an account can offer — `agent-tools` — **projects** a row into
32
+ `mcp_servers`, which is the only place the two meet.
33
+
34
+ That direction matters. A projected row is read by `resolveServerRow()` and by
35
+ every per-engine config builder exactly as a hand-installed one is, so nothing
36
+ in this subsystem has to know accounts exist. And most integrations project no
37
+ MCP server at all — a database provider projects a `db_client_connections` row,
38
+ a chat provider registers a notification channel.
39
+
40
+ Both appear under one UI, **Settings → Integrations**, which absorbed the old
41
+ Connectors section.
42
+
22
43
  > **External servers are proxied, not direct.** Engines never connect straight
23
44
  > to a third-party MCP server. Clopen connects to it (as an MCP client) and
24
45
  > re-exposes its **sanitized** tools through a per-server endpoint on the same
@@ -199,7 +220,7 @@ backend/mcp/
199
220
  │ ├── types.ts # CatalogServer / ResolvedExternalServer
200
221
  │ ├── registry-client.ts # Fetch + normalise registry.modelcontextprotocol.io
201
222
  │ ├── proxy.ts # `/mcp/ext/<slug>` proxy: Clopen ↔ upstream, schema sanitiser
202
- │ ├── probe.ts # Connection health probe (Settings → MCP status)
223
+ │ ├── probe.ts # Connection health probe (Settings → Integrations status)
203
224
  │ ├── oauth.ts # Centralized OAuth (discovery + dynamic reg + PKCE)
204
225
  │ └── config.ts # Per-engine builders (bridge URL, bare <slug>) + resolveExternalToolName
205
226
  └── README.md # This file
@@ -1305,7 +1326,8 @@ checklist in `backend/engine/README.md` §10.12. The summary:
1305
1326
 
1306
1327
  Everything above describes **internal** custom tools (the `clopen-mcp`
1307
1328
  bridge). **External** servers are the ones a user installs from the official
1308
- registry (Settings → MCP → Browse), stored in the `mcp_servers` table.
1329
+ registry (Settings → Integrations → Add → Browse the MCP registry), stored in
1330
+ the `mcp_servers` table.
1309
1331
 
1310
1332
  ### Proxied through the bridge (not direct)
1311
1333
 
@@ -110,7 +110,7 @@ export function getEnabledExternalServers(profileFilter?: Set<string>): Resolved
110
110
  //
111
111
  // When a Profile is active it is the source of truth for which connectors run:
112
112
  // a connector it references is emitted even if globally disabled in the
113
- // Connectors settings, and the global enable toggle is ignored. Without a
113
+ // Integrations settings, and the global enable toggle is ignored. Without a
114
114
  // profile filter, only enabled servers apply (unchanged).
115
115
  const rows = profileFilter ? mcpServerQueries.getAll() : mcpServerQueries.getEnabled();
116
116
  return rows
@@ -268,3 +268,37 @@ function logBuilt(engine: string, out: Record<string, unknown>): void {
268
268
  const count = Object.keys(out).length;
269
269
  if (count > 0) debug.log('mcp', `🧩 ${engine} external MCP: ${count} server(s)`);
270
270
  }
271
+
272
+ /**
273
+ * The config each engine is handed for ONE external server, keyed by engine.
274
+ *
275
+ * Surfaced in the Integrations detail view. It exists because "what does the
276
+ * engine actually receive" is otherwise unanswerable from the UI: every server,
277
+ * whatever its real transport, is emitted as a Streamable-HTTP remote pointing
278
+ * at the `/mcp/ext/<slug>` proxy, so the row a user configured and the config an
279
+ * engine sees do not look alike. Showing the row and calling it the engine's
280
+ * config would be a lie of omission.
281
+ *
282
+ * Returns `{}` for a server that is disabled or unknown — the honest answer,
283
+ * since a disabled server is handed to nobody.
284
+ */
285
+ export function getEngineConfigsForServer(slug: string): Record<string, unknown> {
286
+ const namespace = externalNamespace(slug);
287
+ const pick = (config: Record<string, unknown>): unknown => config[namespace];
288
+
289
+ const out: Record<string, unknown> = {};
290
+ const builders: Record<string, () => Record<string, unknown>> = {
291
+ 'claude-code': () => getClaudeExternalMcpConfig() as Record<string, unknown>,
292
+ opencode: () => getOpenCodeExternalMcpConfig() as Record<string, unknown>,
293
+ codex: () => getCodexExternalMcpConfig() as Record<string, unknown>,
294
+ copilot: () => getCopilotExternalMcpConfig() as Record<string, unknown>,
295
+ cursor: () => getCursorExternalMcpConfig() as Record<string, unknown>,
296
+ qwen: () => getQwenExternalMcpConfig() as Record<string, unknown>
297
+ };
298
+
299
+ for (const [engine, build] of Object.entries(builders)) {
300
+ const config = pick(build());
301
+ if (config !== undefined) out[engine] = config;
302
+ }
303
+ return out;
304
+ }
@@ -75,7 +75,7 @@ export {
75
75
 
76
76
  // External catalog + types (used by the WS layer and Settings → MCP)
77
77
  export { listRegistryServers, mapRegistryServer } from './external/registry-client';
78
- export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth } from './external/config';
78
+ export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth, getEngineConfigsForServer } from './external/config';
79
79
  export { listExternalServerTools, callExternalServerTool } from './external/proxy';
80
80
  export { parseToolOverrides, resolveToolExposure, pruneToolOverrides, MCP_ENGINES } from './external/tools';
81
81
  export type { ToolExposure } from './external/tools';
@@ -289,7 +289,7 @@ export function getEnabledServerNames(): string[] {
289
289
  * Internal server names ACTIVE for a stream. When a Profile is active, its
290
290
  * referenced connector set is the source of truth — a referenced internal server
291
291
  * counts even if globally disabled, and one NOT referenced is excluded (built-in
292
- * connectors appear in the profile's Connectors picker, so this is an explicit
292
+ * connectors appear in the profile's Integrations picker, so this is an explicit
293
293
  * choice). Without a profile, every globally-enabled server is active (unchanged).
294
294
  */
295
295
  export function activeInternalServerNames(profileFilter?: Set<string>): string[] {
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Tests for the note collection access rule.
3
+ *
4
+ * This one function decides who can read notes and who can read the image bytes
5
+ * behind them. Both answers have to stay in step, and the global case has to
6
+ * stay deliberate: it grants every signed-in account, so a regression that
7
+ * quietly widened the project case into it would be invisible in the UI.
8
+ */
9
+
10
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ import { initializeDatabase, closeDatabase } from '../database';
14
+ import { projectQueries } from '../database/queries/project-queries';
15
+ import { noteCollectionQueries } from '../database/queries/note-queries';
16
+ import { canAccessCollection } from './access';
17
+ import type { NoteCollection } from '$shared/types/database/schema';
18
+
19
+ let memberId: string;
20
+ let outsiderId: string;
21
+ let projectId: string;
22
+
23
+ beforeAll(async () => {
24
+ await initializeDatabase();
25
+ memberId = randomUUID();
26
+ outsiderId = randomUUID();
27
+ projectId = projectQueries.create({
28
+ name: 'notes-access-test',
29
+ // `projects.path` is unique, so a fixed path collides with whatever an
30
+ // earlier run left behind in the test data dir.
31
+ path: `/tmp/notes-access-test-${randomUUID()}`,
32
+ created_at: new Date().toISOString(),
33
+ last_opened_at: new Date().toISOString()
34
+ }).id;
35
+ projectQueries.addUserProject(memberId, projectId);
36
+ });
37
+
38
+ afterAll(() => {
39
+ projectQueries.deleteProject(projectId);
40
+ closeDatabase();
41
+ });
42
+
43
+ describe('canAccessCollection — project scope', () => {
44
+ it('admits a member of the project', () => {
45
+ const collection = noteCollectionQueries.create({ name: 'P', scope: 'project', projectId });
46
+ expect(canAccessCollection(memberId, collection)).toBe(true);
47
+ noteCollectionQueries.delete(collection.id);
48
+ });
49
+
50
+ it('refuses someone who is not a member', () => {
51
+ const collection = noteCollectionQueries.create({ name: 'P', scope: 'project', projectId });
52
+ expect(canAccessCollection(outsiderId, collection)).toBe(false);
53
+ noteCollectionQueries.delete(collection.id);
54
+ });
55
+
56
+ it('refuses a project collection with no project rather than admitting everyone', () => {
57
+ // The table's CHECK makes this unreachable through the queries, but a row
58
+ // in this shape must fail closed rather than fall through to the global
59
+ // branch and become readable by the whole instance.
60
+ const malformed = {
61
+ id: 'x',
62
+ name: 'Malformed',
63
+ scope: 'project',
64
+ project_id: null,
65
+ created_by: null,
66
+ created_at: '',
67
+ updated_at: ''
68
+ } as NoteCollection;
69
+ expect(canAccessCollection(memberId, malformed)).toBe(false);
70
+ });
71
+ });
72
+
73
+ describe('canAccessCollection — global scope', () => {
74
+ it('admits any signed-in user, including one in no project at all', () => {
75
+ // Deliberate: a global collection has no per-note ACL, so everything in it
76
+ // is readable by every account that can sign in.
77
+ const collection = noteCollectionQueries.create({ name: 'G', scope: 'global' });
78
+ expect(canAccessCollection(memberId, collection)).toBe(true);
79
+ expect(canAccessCollection(outsiderId, collection)).toBe(true);
80
+ noteCollectionQueries.delete(collection.id);
81
+ });
82
+ });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Who may read and write a note collection.
3
+ *
4
+ * The rule lives here rather than in each route because three call sites need
5
+ * to agree on it — the WebSocket handlers, the image upload, and the image
6
+ * download — and a note whose bytes are reachable through a rule its metadata
7
+ * is not would be worse than no rule at all.
8
+ */
9
+
10
+ import type { NoteCollection } from '$shared/types/database/schema';
11
+ import { projectQueries } from '../database/queries/project-queries';
12
+
13
+ /**
14
+ * Whether `userId` may see and edit everything in `collection`.
15
+ *
16
+ * - `project` — members of that project, the same check the rest of the
17
+ * project-scoped API uses.
18
+ * - `global` — every signed-in user on this instance. Global collections are
19
+ * deliberately instance-wide: there is no per-note ACL, so anything put in
20
+ * one is readable by every account that can sign in, including members of
21
+ * unrelated projects.
22
+ */
23
+ export function canAccessCollection(userId: string, collection: NoteCollection): boolean {
24
+ if (collection.scope === 'global') return true;
25
+ if (!collection.project_id) return false;
26
+ return projectQueries.userHasProject(userId, collection.project_id);
27
+ }