@myrialabs/clopen 0.4.37 → 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.
- package/README.md +2 -2
- package/backend/auth/permissions.ts +14 -0
- package/backend/bootstrap.ts +16 -0
- package/backend/database/crypto/envelope.test.ts +93 -0
- package/backend/database/crypto/envelope.ts +127 -0
- package/backend/database/crypto/index.ts +22 -0
- package/backend/database/crypto/master-key.ts +129 -0
- package/backend/database/crypto/secret-columns.ts +147 -0
- package/backend/database/migrations/071_create_notes_tables.ts +90 -0
- package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
- package/backend/database/migrations/073_create_integration_tables.ts +119 -0
- package/backend/database/migrations/074_create_work_tables.ts +94 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/db-client-connection-queries.ts +23 -12
- package/backend/database/queries/engine-queries.ts +23 -10
- package/backend/database/queries/index.ts +6 -1
- package/backend/database/queries/integration-queries.ts +297 -0
- package/backend/database/queries/mcp-server-queries.ts +38 -11
- package/backend/database/queries/note-queries.test.ts +190 -0
- package/backend/database/queries/note-queries.ts +269 -0
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/ssh-connection-queries.ts +19 -8
- package/backend/database/queries/work-queries.ts +210 -0
- package/backend/engine/docs/artifacts.md +22 -9
- package/backend/files/os-clipboard.test.ts +209 -0
- package/backend/files/os-clipboard.ts +567 -0
- package/backend/http/integration-hooks.ts +42 -0
- package/backend/http/notes-images.test.ts +228 -0
- package/backend/http/notes-images.ts +196 -0
- package/backend/index.ts +9 -0
- package/backend/integrations/accounts.ts +229 -0
- package/backend/integrations/health.ts +146 -0
- package/backend/integrations/index.ts +36 -0
- package/backend/integrations/projections/index.ts +120 -0
- package/backend/integrations/projections/mcp-projector.test.ts +204 -0
- package/backend/integrations/projections/mcp-projector.ts +159 -0
- package/backend/integrations/projections/types.ts +51 -0
- package/backend/integrations/registry/define.ts +38 -0
- package/backend/integrations/registry/index.ts +56 -0
- package/backend/integrations/registry/providers/context7.ts +44 -0
- package/backend/integrations/registry/providers/firecrawl.ts +41 -0
- package/backend/integrations/registry/providers/github.ts +78 -0
- package/backend/integrations/registry/types.ts +96 -0
- package/backend/integrations/webhooks/gateway.ts +160 -0
- package/backend/integrations/webhooks/verify.ts +65 -0
- package/backend/mcp/README.md +25 -3
- package/backend/mcp/external/config.ts +35 -1
- package/backend/mcp/index.ts +1 -1
- package/backend/mcp/internal/config.ts +1 -1
- package/backend/notes/access.test.ts +82 -0
- package/backend/notes/access.ts +27 -0
- package/backend/notes/storage.test.ts +77 -0
- package/backend/notes/storage.ts +114 -0
- package/backend/permissions/service.ts +2 -2
- package/backend/profiles/service.ts +1 -1
- package/backend/projects/project-cleanup.ts +6 -0
- package/backend/work/bindings.ts +124 -0
- package/backend/work/index.ts +42 -0
- package/backend/work/prompts.ts +150 -0
- package/backend/work/providers/github/actions-logs.ts +180 -0
- package/backend/work/providers/github/adapter.test.ts +88 -0
- package/backend/work/providers/github/adapter.ts +1255 -0
- package/backend/work/providers/github/client.ts +280 -0
- package/backend/work/providers/github/list-range.test.ts +158 -0
- package/backend/work/providers/github/token-kind.test.ts +42 -0
- package/backend/work/pull-requests.ts +242 -0
- package/backend/work/registry.ts +27 -0
- package/backend/work/service.ts +436 -0
- package/backend/work/start-work.test.ts +71 -0
- package/backend/work/start-work.ts +232 -0
- package/backend/work/types.ts +180 -0
- package/backend/ws/files/clipboard.ts +78 -0
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/git/diff-budget.ts +70 -11
- package/backend/ws/index.ts +11 -1
- package/backend/ws/integrations/crud.ts +219 -0
- package/backend/ws/integrations/index.ts +22 -0
- package/backend/ws/mcp/crud.ts +25 -1
- package/backend/ws/notes/index.ts +278 -0
- package/backend/ws/profiles/crud.ts +1 -1
- package/backend/ws/work/actions.ts +206 -0
- package/backend/ws/work/context.ts +51 -0
- package/backend/ws/work/crud.ts +347 -0
- package/backend/ws/work/index.ts +17 -0
- package/backend/ws/work/pull-requests.ts +177 -0
- package/backend/ws/work/schemas.ts +226 -0
- package/dist/assets/{index-sJmS_CCm.js → index-CyH7fSbR.js} +1 -1
- package/dist/assets/{index-Bik9TCBi.js → index-DSHIANSy.js} +1 -1
- package/dist/assets/main-D2IOjftb.css +1 -0
- package/dist/assets/main-DM-tHKbW.js +1152 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/tool-icons.ts +33 -0
- package/shared/types/database/schema.ts +41 -0
- package/shared/types/integrations.ts +140 -0
- package/shared/types/stores/settings.ts +8 -0
- package/shared/types/work.ts +426 -0
- package/shared/utils/logger.ts +3 -0
- package/dist/assets/main-DLqolBI2.css +0 -1
- package/dist/assets/main-Df1I3hnw.js +0 -1096
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Projector contract.
|
|
3
|
+
*
|
|
4
|
+
* A projection is a row on another surface DERIVED from an account. Surfaces
|
|
5
|
+
* never learn that accounts exist: they keep reading their own tables, and a
|
|
6
|
+
* projector is the only thing that writes an integration-owned row into them.
|
|
7
|
+
*
|
|
8
|
+
* One projector per capability — but ONLY for capabilities whose surface owns a
|
|
9
|
+
* table to write into. `agent-tools` writes an `mcp_servers` row, `database`
|
|
10
|
+
* will write a `db_client_connections` one, and `deployments`,
|
|
11
|
+
* `worktree-branching` and `notifications` are registered by the tasks that
|
|
12
|
+
* build those surfaces.
|
|
13
|
+
*
|
|
14
|
+
* `work` deliberately has NO projector. Work items are never copied into the
|
|
15
|
+
* database (see migration 074 for why), so there is no derived row to keep in
|
|
16
|
+
* step — the Issues & PRs surface registers an ADAPTER in
|
|
17
|
+
* `backend/issues/registry.ts` and reads the account directly. A capability
|
|
18
|
+
* without a table is a capability without a projection.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { IntegrationCapability, IntegrationTargetKind } from '$shared/types/integrations';
|
|
22
|
+
import type { IntegrationAccountRow } from '$backend/database/queries';
|
|
23
|
+
import type { IntegrationProvider } from '../registry';
|
|
24
|
+
|
|
25
|
+
export interface ProjectionContext {
|
|
26
|
+
account: IntegrationAccountRow;
|
|
27
|
+
provider: IntegrationProvider;
|
|
28
|
+
/** Decoded credentials. Empty when the active key could not open them. */
|
|
29
|
+
credentials: Record<string, string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ProjectionResult {
|
|
33
|
+
targetKind: IntegrationTargetKind;
|
|
34
|
+
targetId: string;
|
|
35
|
+
/**
|
|
36
|
+
* True when the projection took over a row that already existed and was not
|
|
37
|
+
* created by us. Releasing an adopted row restores it instead of deleting it.
|
|
38
|
+
*/
|
|
39
|
+
adopted: boolean;
|
|
40
|
+
/** Snapshot of the adopted row, stored so release can put it back. */
|
|
41
|
+
restore: unknown | null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface Projector {
|
|
45
|
+
capability: IntegrationCapability;
|
|
46
|
+
targetKind: IntegrationTargetKind;
|
|
47
|
+
/** Create or refresh the derived row. Called on connect, credential change and capability enable. */
|
|
48
|
+
project(context: ProjectionContext): ProjectionResult;
|
|
49
|
+
/** Remove the derived row, or hand an adopted one back untouched. */
|
|
50
|
+
release(context: ProjectionContext, targetId: string, adopted: boolean, restore: unknown | null): void;
|
|
51
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineProvider()` lives in its own module so a provider file can import it
|
|
3
|
+
* without importing the registry that imports the provider file. The cycle
|
|
4
|
+
* would resolve today thanks to hoisting, but it is the kind of thing that
|
|
5
|
+
* breaks silently the moment someone adds a top-level const to the registry.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { IntegrationProvider } from './types';
|
|
9
|
+
|
|
10
|
+
const SLUG_PATTERN = /^[a-z0-9-]+$/;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Validate a provider at module load.
|
|
14
|
+
*
|
|
15
|
+
* These are declaration mistakes, not runtime conditions, so failing loudly at
|
|
16
|
+
* import is right: a provider that claims `agent-tools` without a preset would
|
|
17
|
+
* otherwise present a working connect dialog that silently projects nothing.
|
|
18
|
+
*/
|
|
19
|
+
export function defineProvider(provider: IntegrationProvider): IntegrationProvider {
|
|
20
|
+
if (!SLUG_PATTERN.test(provider.id)) {
|
|
21
|
+
throw new Error(`Integration provider id "${provider.id}" must match ${SLUG_PATTERN}`);
|
|
22
|
+
}
|
|
23
|
+
if (provider.capabilities.includes('agent-tools') && !provider.mcp) {
|
|
24
|
+
throw new Error(`Integration provider "${provider.id}" offers agent-tools but declares no MCP preset`);
|
|
25
|
+
}
|
|
26
|
+
if (provider.mcp && !SLUG_PATTERN.test(provider.mcp.slug)) {
|
|
27
|
+
throw new Error(`Integration provider "${provider.id}" has an invalid MCP preset slug`);
|
|
28
|
+
}
|
|
29
|
+
if (provider.capabilities.includes('inbound-events') && !provider.webhook) {
|
|
30
|
+
throw new Error(`Integration provider "${provider.id}" accepts inbound events but declares no webhook spec`);
|
|
31
|
+
}
|
|
32
|
+
for (const capability of provider.defaultCapabilities ?? []) {
|
|
33
|
+
if (!provider.capabilities.includes(capability)) {
|
|
34
|
+
throw new Error(`Integration provider "${provider.id}" defaults to a capability it does not offer: ${capability}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return provider;
|
|
38
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
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 type { IntegrationProvider } from './types';
|
|
14
|
+
import type { IntegrationProviderInfo } from '$shared/types/integrations';
|
|
15
|
+
|
|
16
|
+
export type { IntegrationProvider, McpPreset, WebhookSpec } from './types';
|
|
17
|
+
export { defineProvider } from './define';
|
|
18
|
+
|
|
19
|
+
/** Every declared provider. Add new ones here. */
|
|
20
|
+
export const PROVIDERS: readonly IntegrationProvider[] = [
|
|
21
|
+
context7,
|
|
22
|
+
firecrawl,
|
|
23
|
+
github
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
const byId = new Map(PROVIDERS.map((provider) => [provider.id, provider]));
|
|
27
|
+
|
|
28
|
+
export function getProvider(id: string): IntegrationProvider | null {
|
|
29
|
+
return byId.get(id) ?? null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Capabilities turned on when an account is first connected. */
|
|
33
|
+
export function defaultCapabilitiesOf(provider: IntegrationProvider): IntegrationProvider['capabilities'] {
|
|
34
|
+
return provider.defaultCapabilities ?? provider.capabilities;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The provider as the hub renders it — declaration minus anything internal. */
|
|
38
|
+
export function toProviderInfo(provider: IntegrationProvider): IntegrationProviderInfo {
|
|
39
|
+
return {
|
|
40
|
+
id: provider.id,
|
|
41
|
+
name: provider.name,
|
|
42
|
+
category: provider.category,
|
|
43
|
+
description: provider.description,
|
|
44
|
+
docsUrl: provider.docsUrl,
|
|
45
|
+
authMethod: provider.authMethod,
|
|
46
|
+
credentialFields: provider.credentialFields,
|
|
47
|
+
capabilities: [...provider.capabilities],
|
|
48
|
+
defaultCapabilities: [...defaultCapabilitiesOf(provider)],
|
|
49
|
+
providesAgentTools: provider.capabilities.includes('agent-tools'),
|
|
50
|
+
acceptsWebhooks: provider.capabilities.includes('inbound-events')
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function listProviderInfo(): IntegrationProviderInfo[] {
|
|
55
|
+
return PROVIDERS.map(toProviderInfo);
|
|
56
|
+
}
|
|
@@ -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,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
|
+
}
|