@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.
- 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/git/conflict-state.test.ts +396 -0
- package/backend/git/git-executor.ts +6 -0
- package/backend/git/git-parser.ts +144 -48
- package/backend/git/git-service.ts +727 -57
- package/backend/git/push-target.test.ts +264 -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/project/status-manager.ts +20 -0
- 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/branch-name.ts +6 -5
- package/backend/ws/git/branch.ts +43 -1
- package/backend/ws/git/commit-message.ts +13 -10
- package/backend/ws/git/conflict.ts +106 -3
- package/backend/ws/git/diff-budget.test.ts +125 -0
- package/backend/ws/git/diff-budget.ts +279 -0
- package/backend/ws/git/log.ts +25 -0
- package/backend/ws/git/remote.ts +75 -1
- 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-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
- package/dist/assets/{index-Cz4YpHVi.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/git.ts +123 -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-9G7IpQpK.css +0 -1
- package/dist/assets/main-BofFsH8E.js +0 -1085
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP routes for note image upload / download.
|
|
3
|
+
*
|
|
4
|
+
* They sit next to the WebSocket router for the same reason the file routes do:
|
|
5
|
+
* a base64 image on the socket costs a third more bytes and holds the whole
|
|
6
|
+
* attachment in memory at both ends, while HTTP streams it.
|
|
7
|
+
*
|
|
8
|
+
* Storage: `<DATA_DIR>/notes/<collectionId>/<noteId>/<uuid>-<name>`, recorded
|
|
9
|
+
* relative to the data dir — see `backend/notes/storage.ts`. The UUID prefix
|
|
10
|
+
* only has to make the name unique within the note, so two uploads of
|
|
11
|
+
* `screenshot.png` don't collide.
|
|
12
|
+
*
|
|
13
|
+
* Auth: `Authorization: Bearer <session-token>` on both routes, then the same
|
|
14
|
+
* collection rule the WebSocket handlers use, resolved through the image's
|
|
15
|
+
* note. The bytes must never be reachable under a weaker rule than the
|
|
16
|
+
* metadata.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { Elysia } from 'elysia';
|
|
20
|
+
import { mkdir, rename, stat, unlink } from 'node:fs/promises';
|
|
21
|
+
import { join } from 'node:path';
|
|
22
|
+
import { fileTypeFromBuffer } from 'file-type';
|
|
23
|
+
|
|
24
|
+
import { debug } from '$shared/utils/logger';
|
|
25
|
+
import { authenticateRequest, type AuthIdentity } from './bearer-auth';
|
|
26
|
+
import { noteQueries, noteCollectionQueries, noteImageQueries } from '../database/queries/note-queries';
|
|
27
|
+
import { canAccessCollection } from '../notes/access';
|
|
28
|
+
import {
|
|
29
|
+
getNoteDir,
|
|
30
|
+
noteImageRelPath,
|
|
31
|
+
resolveNoteImagePath,
|
|
32
|
+
sanitizeImageFileName
|
|
33
|
+
} from '../notes/storage';
|
|
34
|
+
|
|
35
|
+
const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
|
|
36
|
+
const ALLOWED_MIMES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Bytes `file-type` needs before it can name a format. Sniffing the content is
|
|
40
|
+
* what makes the allow-list meaningful: a client-declared `Content-Type` is
|
|
41
|
+
* just a string, and an SVG or HTML file announced as `image/png` would other-
|
|
42
|
+
* wise be stored and later served back with a type the browser will script.
|
|
43
|
+
*/
|
|
44
|
+
const SNIFF_BYTES = 4100;
|
|
45
|
+
|
|
46
|
+
export const notesImagesRoute = new Elysia()
|
|
47
|
+
.post('/api/notes/images/upload', async ({ request, query }) => {
|
|
48
|
+
let identity: AuthIdentity;
|
|
49
|
+
try {
|
|
50
|
+
identity = authenticateRequest(request);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
const status = (error as { status?: number }).status ?? 401;
|
|
53
|
+
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
54
|
+
return new Response(message, { status });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const noteId = typeof query.noteId === 'string' ? query.noteId : '';
|
|
58
|
+
const fileNameParam = typeof query.fileName === 'string' ? query.fileName : 'image';
|
|
59
|
+
const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
|
|
60
|
+
|
|
61
|
+
if (!noteId) return new Response('Missing required query parameter: noteId', { status: 400 });
|
|
62
|
+
if (!Number.isFinite(fileSizeParam) || fileSizeParam <= 0) {
|
|
63
|
+
return new Response('Invalid fileSize query parameter', { status: 400 });
|
|
64
|
+
}
|
|
65
|
+
if (fileSizeParam > MAX_IMAGE_SIZE) {
|
|
66
|
+
return new Response(`File too large. Max ${MAX_IMAGE_SIZE} bytes`, { status: 413 });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const note = noteQueries.getRawById(noteId);
|
|
70
|
+
if (!note) return new Response('Note not found', { status: 404 });
|
|
71
|
+
|
|
72
|
+
const collection = noteCollectionQueries.getById(note.collection_id);
|
|
73
|
+
if (!collection || !canAccessCollection(identity.userId, collection)) {
|
|
74
|
+
return new Response('Access denied', { status: 403 });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (!request.body) return new Response('Request body is empty', { status: 400 });
|
|
78
|
+
|
|
79
|
+
const sanitized = sanitizeImageFileName(fileNameParam);
|
|
80
|
+
const storedName = `${crypto.randomUUID()}-${sanitized}`;
|
|
81
|
+
const dir = getNoteDir(collection.id, noteId);
|
|
82
|
+
await mkdir(dir, { recursive: true });
|
|
83
|
+
const finalPath = join(dir, storedName);
|
|
84
|
+
const tempPath = `${finalPath}.${crypto.randomUUID()}.partial`;
|
|
85
|
+
|
|
86
|
+
// Stream to a temp file with a hard ceiling instead of buffering the body.
|
|
87
|
+
// `fileSize` is a client claim: reading the whole request into memory first
|
|
88
|
+
// would let one member of one project decide how much RAM this process
|
|
89
|
+
// allocates, no matter what the query parameter said.
|
|
90
|
+
const writer = Bun.file(tempPath).writer();
|
|
91
|
+
const header: Uint8Array[] = [];
|
|
92
|
+
let headerBytes = 0;
|
|
93
|
+
let written = 0;
|
|
94
|
+
|
|
95
|
+
const discardTemp = async () => {
|
|
96
|
+
try { await writer.end(); } catch { /* best-effort */ }
|
|
97
|
+
await unlink(tempPath).catch(() => {});
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
const reader = request.body.getReader();
|
|
102
|
+
while (true) {
|
|
103
|
+
const { done, value } = await reader.read();
|
|
104
|
+
if (done) break;
|
|
105
|
+
if (!value) continue;
|
|
106
|
+
written += value.byteLength;
|
|
107
|
+
if (written > fileSizeParam || written > MAX_IMAGE_SIZE) {
|
|
108
|
+
await discardTemp();
|
|
109
|
+
return new Response('Received more bytes than declared file size', { status: 400 });
|
|
110
|
+
}
|
|
111
|
+
if (headerBytes < SNIFF_BYTES) {
|
|
112
|
+
// `slice` copies: the chunk is handed to the writer next and must
|
|
113
|
+
// not be read again through a view once that buffer is recycled.
|
|
114
|
+
header.push(value.slice(0, SNIFF_BYTES - headerBytes));
|
|
115
|
+
headerBytes += Math.min(value.byteLength, SNIFF_BYTES - headerBytes);
|
|
116
|
+
}
|
|
117
|
+
writer.write(value);
|
|
118
|
+
}
|
|
119
|
+
await writer.end();
|
|
120
|
+
} catch (error) {
|
|
121
|
+
await discardTemp();
|
|
122
|
+
debug.error('notes', 'Image upload stream failed:', error);
|
|
123
|
+
return new Response('Failed to read upload', { status: 500 });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (written !== fileSizeParam) {
|
|
127
|
+
await unlink(tempPath).catch(() => {});
|
|
128
|
+
return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const detected = await fileTypeFromBuffer(Buffer.concat(header));
|
|
132
|
+
const mime = detected?.mime ?? '';
|
|
133
|
+
if (!ALLOWED_MIMES.has(mime)) {
|
|
134
|
+
await unlink(tempPath).catch(() => {});
|
|
135
|
+
return new Response(
|
|
136
|
+
`Unsupported image type. Allowed: ${Array.from(ALLOWED_MIMES).join(', ')}`,
|
|
137
|
+
{ status: 400 }
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
// Same-directory rename is atomic on POSIX and Windows alike, so the
|
|
143
|
+
// final path only ever appears with the complete file behind it.
|
|
144
|
+
await rename(tempPath, finalPath);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
await unlink(tempPath).catch(() => {});
|
|
147
|
+
debug.error('notes', 'Failed to store note image:', error);
|
|
148
|
+
return new Response('Failed to save image', { status: 500 });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const record = noteImageQueries.create({
|
|
152
|
+
noteId,
|
|
153
|
+
fileName: sanitized,
|
|
154
|
+
mimeType: mime,
|
|
155
|
+
size: written,
|
|
156
|
+
storagePath: noteImageRelPath(collection.id, noteId, storedName)
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
return Response.json({ image: record, url: `/api/notes/images/${record.id}` });
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
.get('/api/notes/images/:id', async ({ request, params }) => {
|
|
163
|
+
let identity: AuthIdentity;
|
|
164
|
+
try {
|
|
165
|
+
identity = authenticateRequest(request);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
const status = (error as { status?: number }).status ?? 401;
|
|
168
|
+
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
169
|
+
return new Response(message, { status });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const img = noteImageQueries.getById((params as { id: string }).id);
|
|
173
|
+
if (!img) return new Response('Image not found', { status: 404 });
|
|
174
|
+
|
|
175
|
+
const collection = noteCollectionQueries.getForNote(img.note_id);
|
|
176
|
+
if (!collection) return new Response('Image not found', { status: 404 });
|
|
177
|
+
|
|
178
|
+
if (!canAccessCollection(identity.userId, collection)) {
|
|
179
|
+
return new Response('Access denied', { status: 403 });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const absolute = resolveNoteImagePath(img.storage_path);
|
|
183
|
+
if (!absolute) return new Response('File not found', { status: 404 });
|
|
184
|
+
|
|
185
|
+
const stats = await stat(absolute).catch(() => null);
|
|
186
|
+
if (!stats || !stats.isFile()) return new Response('File not found', { status: 404 });
|
|
187
|
+
|
|
188
|
+
return new Response(Bun.file(absolute).stream(), {
|
|
189
|
+
headers: {
|
|
190
|
+
'Content-Type': img.mime_type,
|
|
191
|
+
'Content-Length': String(stats.size),
|
|
192
|
+
// Attachments are immutable — the id changes when the bytes do.
|
|
193
|
+
'Cache-Control': 'private, max-age=3600'
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
});
|
package/backend/index.ts
CHANGED
|
@@ -51,6 +51,8 @@ import { audioRoute } from './http/audio';
|
|
|
51
51
|
|
|
52
52
|
// HTTP routes for SFTP transfer — same reason as the file upload route above.
|
|
53
53
|
import { sshSftpRoute } from './http/ssh-sftp';
|
|
54
|
+
import { notesImagesRoute } from './http/notes-images';
|
|
55
|
+
import { integrationHooksRoute } from './http/integration-hooks';
|
|
54
56
|
|
|
55
57
|
// Import browser preview manager for graceful shutdown
|
|
56
58
|
import { browserPreviewServiceManager } from './preview';
|
|
@@ -198,6 +200,13 @@ const app = new Elysia()
|
|
|
198
200
|
// SSH file transfer (SFTP download/upload).
|
|
199
201
|
.use(sshSftpRoute)
|
|
200
202
|
|
|
203
|
+
// Notes images
|
|
204
|
+
.use(notesImagesRoute)
|
|
205
|
+
|
|
206
|
+
// Inbound third-party events. Unauthenticated by necessity — it verifies a
|
|
207
|
+
// per-provider signature over the raw bytes instead of a session.
|
|
208
|
+
.use(integrationHooksRoute)
|
|
209
|
+
|
|
201
210
|
// Mount WebSocket router (all functionality now via WebSocket)
|
|
202
211
|
.use(wsRouter.asPlugin('/ws'));
|
|
203
212
|
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The account service — connect, reconfigure, disconnect.
|
|
3
|
+
*
|
|
4
|
+
* Every mutation ends in `reproject()`, so a surface row can never drift from
|
|
5
|
+
* the account it was derived from. Credential VALUES never leave this module:
|
|
6
|
+
* what the hub receives is which fields are set, never what they are set to.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
integrationAccountQueries,
|
|
11
|
+
integrationProjectionQueries,
|
|
12
|
+
type IntegrationAccountRow
|
|
13
|
+
} from '$backend/database/queries';
|
|
14
|
+
import type {
|
|
15
|
+
IntegrationAccountInfo,
|
|
16
|
+
IntegrationCapability,
|
|
17
|
+
IntegrationStatus
|
|
18
|
+
} from '$shared/types/integrations';
|
|
19
|
+
import { defaultCapabilitiesOf, getProvider, type IntegrationProvider } from './registry';
|
|
20
|
+
import { reproject, releaseAll } from './projections';
|
|
21
|
+
import { debug } from '$shared/utils/logger';
|
|
22
|
+
|
|
23
|
+
export interface ConnectInput {
|
|
24
|
+
provider: string;
|
|
25
|
+
label?: string;
|
|
26
|
+
projectId?: string | null;
|
|
27
|
+
credentials: Record<string, string>;
|
|
28
|
+
capabilities?: IntegrationCapability[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function requireProvider(id: string): IntegrationProvider {
|
|
32
|
+
const provider = getProvider(id);
|
|
33
|
+
if (!provider) throw new Error(`Unknown integration provider "${id}"`);
|
|
34
|
+
return provider;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Reject a connect that is missing a required field.
|
|
39
|
+
*
|
|
40
|
+
* Done before the row is written rather than at first use: an account saved
|
|
41
|
+
* without its key looks connected in the hub and fails much later, somewhere
|
|
42
|
+
* with no useful place to report it.
|
|
43
|
+
*/
|
|
44
|
+
function assertRequiredFields(provider: IntegrationProvider, credentials: Record<string, string>): void {
|
|
45
|
+
const missing = provider.credentialFields
|
|
46
|
+
.filter((field) => field.isRequired && !(credentials[field.name] ?? '').trim())
|
|
47
|
+
.map((field) => field.label);
|
|
48
|
+
|
|
49
|
+
if (missing.length > 0) {
|
|
50
|
+
throw new Error(`${provider.name} needs ${missing.join(', ')}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function assertKnownCapabilities(provider: IntegrationProvider, capabilities: IntegrationCapability[]): void {
|
|
55
|
+
const unknown = capabilities.filter((capability) => !provider.capabilities.includes(capability));
|
|
56
|
+
if (unknown.length > 0) {
|
|
57
|
+
throw new Error(`${provider.name} does not offer: ${unknown.join(', ')}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A label the user did not have to invent.
|
|
63
|
+
*
|
|
64
|
+
* `(provider, label)` is the identity, so a second account for the same
|
|
65
|
+
* provider needs a distinct one — "Firecrawl 2" is a better default than an
|
|
66
|
+
* error telling the user to think of a name.
|
|
67
|
+
*/
|
|
68
|
+
function defaultLabel(provider: IntegrationProvider): string {
|
|
69
|
+
const taken = new Set(integrationAccountQueries.getByProvider(provider.id).map((row) => row.label));
|
|
70
|
+
if (!taken.has(provider.name)) return provider.name;
|
|
71
|
+
for (let n = 2; ; n += 1) {
|
|
72
|
+
const candidate = `${provider.name} ${n}`;
|
|
73
|
+
if (!taken.has(candidate)) return candidate;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Which credential fields hold a value. The values themselves stay here. */
|
|
78
|
+
function configuredFieldsOf(provider: IntegrationProvider, credentials: Record<string, string>): string[] {
|
|
79
|
+
return provider.credentialFields
|
|
80
|
+
.filter((field) => (credentials[field.name] ?? '').trim().length > 0)
|
|
81
|
+
.map((field) => field.name);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function toAccountInfo(row: IntegrationAccountRow): IntegrationAccountInfo {
|
|
85
|
+
const provider = getProvider(row.provider);
|
|
86
|
+
const credentials = integrationAccountQueries.credentialsOf(row);
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
id: row.id,
|
|
90
|
+
provider: row.provider,
|
|
91
|
+
label: row.label,
|
|
92
|
+
projectId: row.project_id,
|
|
93
|
+
authMethod: row.auth_method,
|
|
94
|
+
configuredFields: provider ? configuredFieldsOf(provider, credentials) : Object.keys(credentials),
|
|
95
|
+
capabilities: integrationAccountQueries.capabilitiesOf(row),
|
|
96
|
+
status: row.status,
|
|
97
|
+
statusDetail: row.status_detail,
|
|
98
|
+
checkedAt: row.checked_at,
|
|
99
|
+
isEnabled: row.is_enabled === 1,
|
|
100
|
+
createdAt: row.created_at,
|
|
101
|
+
updatedAt: row.updated_at,
|
|
102
|
+
projections: integrationProjectionQueries.getForAccount(row.id).map((projection) => ({
|
|
103
|
+
capability: projection.capability,
|
|
104
|
+
targetKind: projection.target_kind,
|
|
105
|
+
targetId: projection.target_id,
|
|
106
|
+
adopted: projection.adopted === 1
|
|
107
|
+
}))
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const integrationAccounts = {
|
|
112
|
+
list(): IntegrationAccountInfo[] {
|
|
113
|
+
return integrationAccountQueries.getAll().map(toAccountInfo);
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
get(id: string): IntegrationAccountInfo | null {
|
|
117
|
+
const row = integrationAccountQueries.getById(id);
|
|
118
|
+
return row ? toAccountInfo(row) : null;
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
connect(input: ConnectInput): IntegrationAccountInfo {
|
|
122
|
+
const provider = requireProvider(input.provider);
|
|
123
|
+
assertRequiredFields(provider, input.credentials);
|
|
124
|
+
|
|
125
|
+
const capabilities = input.capabilities ?? [...defaultCapabilitiesOf(provider)];
|
|
126
|
+
assertKnownCapabilities(provider, capabilities);
|
|
127
|
+
|
|
128
|
+
const row = integrationAccountQueries.create({
|
|
129
|
+
provider: provider.id,
|
|
130
|
+
label: (input.label ?? '').trim() || defaultLabel(provider),
|
|
131
|
+
projectId: input.projectId ?? null,
|
|
132
|
+
authMethod: provider.authMethod,
|
|
133
|
+
credentials: input.credentials,
|
|
134
|
+
capabilities
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
reproject(row.id);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// A projection that cannot be made means the account is not usable, and
|
|
141
|
+
// a half-connected account is worse than none: it shows as connected in
|
|
142
|
+
// the hub while nothing behind it works.
|
|
143
|
+
integrationAccountQueries.remove(row.id);
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
debug.log('integrations', `Connected ${provider.id} account "${row.label}"`);
|
|
148
|
+
return this.get(row.id)!;
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Merge new credential values in.
|
|
153
|
+
*
|
|
154
|
+
* An empty value means "the form did not re-send this field", not "clear
|
|
155
|
+
* it" — the same rule the db-client and SSH forms follow, and the reason
|
|
156
|
+
* editing a label does not wipe a token.
|
|
157
|
+
*/
|
|
158
|
+
updateCredentials(id: string, patch: Record<string, string>): IntegrationAccountInfo {
|
|
159
|
+
const row = integrationAccountQueries.getById(id);
|
|
160
|
+
if (!row) throw new Error('Integration account not found');
|
|
161
|
+
const provider = requireProvider(row.provider);
|
|
162
|
+
|
|
163
|
+
const merged = { ...integrationAccountQueries.credentialsOf(row) };
|
|
164
|
+
for (const [field, value] of Object.entries(patch)) {
|
|
165
|
+
if (value === '') continue;
|
|
166
|
+
merged[field] = value;
|
|
167
|
+
}
|
|
168
|
+
assertRequiredFields(provider, merged);
|
|
169
|
+
|
|
170
|
+
integrationAccountQueries.setCredentials(id, merged);
|
|
171
|
+
integrationAccountQueries.setStatus(id, 'unknown', null);
|
|
172
|
+
reproject(id);
|
|
173
|
+
return this.get(id)!;
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
/** Rename. The label is how a user tells two accounts of one service apart. */
|
|
177
|
+
setLabel(id: string, label: string): IntegrationAccountInfo {
|
|
178
|
+
const row = integrationAccountQueries.getById(id);
|
|
179
|
+
if (!row) throw new Error('Integration account not found');
|
|
180
|
+
|
|
181
|
+
const trimmed = label.trim();
|
|
182
|
+
if (!trimmed) throw new Error('A name is required');
|
|
183
|
+
|
|
184
|
+
const taken = integrationAccountQueries
|
|
185
|
+
.getByProvider(row.provider)
|
|
186
|
+
.some((other) => other.id !== id && other.label === trimmed);
|
|
187
|
+
if (taken) throw new Error(`Another ${row.provider} account is already called "${trimmed}"`);
|
|
188
|
+
|
|
189
|
+
integrationAccountQueries.setLabel(id, trimmed);
|
|
190
|
+
return this.get(id)!;
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
setCapabilities(id: string, capabilities: IntegrationCapability[]): IntegrationAccountInfo {
|
|
194
|
+
const row = integrationAccountQueries.getById(id);
|
|
195
|
+
if (!row) throw new Error('Integration account not found');
|
|
196
|
+
assertKnownCapabilities(requireProvider(row.provider), capabilities);
|
|
197
|
+
|
|
198
|
+
integrationAccountQueries.setCapabilities(id, capabilities);
|
|
199
|
+
reproject(id);
|
|
200
|
+
return this.get(id)!;
|
|
201
|
+
},
|
|
202
|
+
|
|
203
|
+
setEnabled(id: string, enabled: boolean): IntegrationAccountInfo {
|
|
204
|
+
if (!integrationAccountQueries.getById(id)) throw new Error('Integration account not found');
|
|
205
|
+
integrationAccountQueries.setEnabled(id, enabled);
|
|
206
|
+
reproject(id);
|
|
207
|
+
return this.get(id)!;
|
|
208
|
+
},
|
|
209
|
+
|
|
210
|
+
setProject(id: string, projectId: string | null): IntegrationAccountInfo {
|
|
211
|
+
if (!integrationAccountQueries.getById(id)) throw new Error('Integration account not found');
|
|
212
|
+
integrationAccountQueries.setProject(id, projectId);
|
|
213
|
+
reproject(id);
|
|
214
|
+
return this.get(id)!;
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
setStatus(id: string, status: IntegrationStatus, detail: string | null): void {
|
|
218
|
+
integrationAccountQueries.setStatus(id, status, detail);
|
|
219
|
+
},
|
|
220
|
+
|
|
221
|
+
/** Release every derived row, then drop the account. Order matters. */
|
|
222
|
+
disconnect(id: string): void {
|
|
223
|
+
const row = integrationAccountQueries.getById(id);
|
|
224
|
+
if (!row) return;
|
|
225
|
+
releaseAll(id);
|
|
226
|
+
integrationAccountQueries.remove(id);
|
|
227
|
+
debug.log('integrations', `Disconnected ${row.provider} account "${row.label}"`);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account health, and the health of the secrets layer itself.
|
|
3
|
+
*
|
|
4
|
+
* Account health reuses the MCP probe rather than inventing a second notion of
|
|
5
|
+
* "is this connector working" — for an account whose only capability is agent
|
|
6
|
+
* tools, the probe against its projected row IS the answer.
|
|
7
|
+
*
|
|
8
|
+
* That answer runs out the moment a capability projects no MCP row. A GitHub
|
|
9
|
+
* account offering `work` has a credential that can be verified precisely —
|
|
10
|
+
* by calling the API it was issued for — but nothing for `probeServer()` to
|
|
11
|
+
* reach. So a surface may register its own probe for its providers, and the
|
|
12
|
+
* hub's status strip keeps meaning something for every account rather than
|
|
13
|
+
* reading "Nothing to probe yet" forever.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { probeServer, resolveServerRow } from '$backend/mcp';
|
|
17
|
+
import {
|
|
18
|
+
integrationAccountQueries,
|
|
19
|
+
integrationProjectionQueries,
|
|
20
|
+
mcpServerQueries
|
|
21
|
+
} from '$backend/database/queries';
|
|
22
|
+
import { getDatabase } from '$backend/database';
|
|
23
|
+
import { auditSecretColumns, getDecryptFailures, getMasterKey } from '$backend/database/crypto';
|
|
24
|
+
import type { IntegrationStatus, SecretsHealth } from '$shared/types/integrations';
|
|
25
|
+
import { integrationAccounts } from './accounts';
|
|
26
|
+
import { debug } from '$shared/utils/logger';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A probe contributed by a surface, keyed by provider id.
|
|
30
|
+
*
|
|
31
|
+
* Returning null means "this probe has nothing to say about this account" — for
|
|
32
|
+
* instance a GitHub account with `work` switched off — and the MCP path is
|
|
33
|
+
* used instead. That is what lets one account carry both kinds of capability
|
|
34
|
+
* without the two probes fighting over which one reports.
|
|
35
|
+
*/
|
|
36
|
+
export type AccountProbe = (
|
|
37
|
+
accountId: string,
|
|
38
|
+
projectId: string | null
|
|
39
|
+
) => Promise<{ status: IntegrationStatus; detail: string | null } | null>;
|
|
40
|
+
|
|
41
|
+
const providerProbes = new Map<string, AccountProbe>();
|
|
42
|
+
|
|
43
|
+
/** Register a provider-specific probe. Called at module load by the surface. */
|
|
44
|
+
export function registerAccountProbe(provider: string, probe: AccountProbe): void {
|
|
45
|
+
providerProbes.set(provider, probe);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Probe one account.
|
|
50
|
+
*
|
|
51
|
+
* An account with no projected MCP row has nothing probeable yet — its
|
|
52
|
+
* capabilities belong to surfaces that do not exist. That is reported as
|
|
53
|
+
* `unknown` rather than `ok`, because claiming health we never measured is the
|
|
54
|
+
* one answer worse than "not checked".
|
|
55
|
+
*/
|
|
56
|
+
export async function checkAccountHealth(accountId: string): Promise<{ status: IntegrationStatus; detail: string | null }> {
|
|
57
|
+
const account = integrationAccountQueries.getById(accountId);
|
|
58
|
+
if (!account) throw new Error('Integration account not found');
|
|
59
|
+
|
|
60
|
+
if (account.is_enabled !== 1) {
|
|
61
|
+
const result = { status: 'unknown' as const, detail: 'Disabled' };
|
|
62
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A surface probe is the more specific answer when there is one: it talks to
|
|
67
|
+
// the API the credential was issued for, rather than to an MCP server that
|
|
68
|
+
// happens to accept the same token.
|
|
69
|
+
const providerProbe = providerProbes.get(account.provider);
|
|
70
|
+
if (providerProbe) {
|
|
71
|
+
try {
|
|
72
|
+
const result = await providerProbe(accountId, account.project_id);
|
|
73
|
+
if (result) {
|
|
74
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
} catch (error) {
|
|
78
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
79
|
+
debug.error('integrations', `Provider probe failed for account ${accountId}:`, error);
|
|
80
|
+
integrationAccounts.setStatus(accountId, 'error', detail);
|
|
81
|
+
return { status: 'error', detail };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const projection = integrationProjectionQueries
|
|
86
|
+
.getForAccount(accountId)
|
|
87
|
+
.find((row) => row.target_kind === 'mcp_server');
|
|
88
|
+
|
|
89
|
+
if (!projection) {
|
|
90
|
+
const result = { status: 'unknown' as const, detail: 'Nothing to probe yet' };
|
|
91
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const row = mcpServerQueries.getById(Number(projection.target_id));
|
|
96
|
+
if (!row) {
|
|
97
|
+
const result = { status: 'error' as const, detail: 'Projected connector is missing' };
|
|
98
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const health = await probeServer(resolveServerRow(row));
|
|
104
|
+
// The probe's `unreachable` and `local` states have no account-level
|
|
105
|
+
// meaning: one is an error and the other means "nothing to reach".
|
|
106
|
+
const status: IntegrationStatus =
|
|
107
|
+
health.state === 'ok' ? 'ok'
|
|
108
|
+
: health.state === 'needs_auth' ? 'needs_auth'
|
|
109
|
+
: health.state === 'needs_config' ? 'needs_config'
|
|
110
|
+
: health.state === 'local' ? 'unknown'
|
|
111
|
+
: 'error';
|
|
112
|
+
|
|
113
|
+
integrationAccounts.setStatus(accountId, status, health.message ?? null);
|
|
114
|
+
return { status, detail: health.message ?? null };
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
117
|
+
debug.error('integrations', `Health check failed for account ${accountId}:`, error);
|
|
118
|
+
integrationAccounts.setStatus(accountId, 'error', detail);
|
|
119
|
+
return { status: 'error', detail };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* State of secrets at rest, rendered by the hub as a banner.
|
|
125
|
+
*
|
|
126
|
+
* A non-zero failure count is almost always a database restored next to a
|
|
127
|
+
* freshly generated key. Surfacing the fingerprints is what turns that from
|
|
128
|
+
* "some credentials stopped working" into "you are missing key 3f9a1c22".
|
|
129
|
+
*/
|
|
130
|
+
export function getSecretsHealth(): SecretsHealth {
|
|
131
|
+
const { fingerprint, source } = getMasterKey();
|
|
132
|
+
const failures = getDecryptFailures();
|
|
133
|
+
|
|
134
|
+
const unsealedColumns = auditSecretColumns(getDatabase())
|
|
135
|
+
.filter((entry) => entry.unsealed > 0)
|
|
136
|
+
.map((entry) => ({ table: entry.table, column: entry.column, count: entry.unsealed }));
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
keySource: source,
|
|
140
|
+
keyFingerprint: fingerprint,
|
|
141
|
+
failureCount: failures.count,
|
|
142
|
+
lastFailureAt: failures.lastAt,
|
|
143
|
+
unknownKeyFingerprints: failures.fingerprints,
|
|
144
|
+
unsealedColumns
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Third-party integrations.
|
|
3
|
+
*
|
|
4
|
+
* A connected account is a CREDENTIAL WITH CAPABILITIES, stored once in
|
|
5
|
+
* `integration_accounts`. Rows on other surfaces are projections derived from
|
|
6
|
+
* it, and nothing downstream of a projection needs to know accounts exist.
|
|
7
|
+
*
|
|
8
|
+
* registry/ what Clopen can connect to, declared in code
|
|
9
|
+
* accounts.ts connect / reconfigure / disconnect
|
|
10
|
+
* projections/ the derived rows, and the adopt-and-release rules
|
|
11
|
+
* webhooks/ the signed inbound endpoint
|
|
12
|
+
* health.ts account health, and the health of secrets at rest
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export {
|
|
16
|
+
PROVIDERS,
|
|
17
|
+
getProvider,
|
|
18
|
+
listProviderInfo,
|
|
19
|
+
toProviderInfo,
|
|
20
|
+
defaultCapabilitiesOf,
|
|
21
|
+
defineProvider
|
|
22
|
+
} from './registry';
|
|
23
|
+
export type { IntegrationProvider, McpPreset, WebhookSpec } from './registry';
|
|
24
|
+
|
|
25
|
+
export { integrationAccounts, toAccountInfo } from './accounts';
|
|
26
|
+
export type { ConnectInput } from './accounts';
|
|
27
|
+
|
|
28
|
+
export { reproject, releaseAll, registerProjector, projectableCapabilities } from './projections';
|
|
29
|
+
export type { Projector, ProjectionContext, ProjectionResult } from './projections';
|
|
30
|
+
|
|
31
|
+
export { handleInboundDelivery, onWebhook, MAX_BODY_BYTES } from './webhooks/gateway';
|
|
32
|
+
export type { WebhookEvent, WebhookSubscriber } from './webhooks/gateway';
|
|
33
|
+
export { verifySignature } from './webhooks/verify';
|
|
34
|
+
|
|
35
|
+
export { checkAccountHealth, getSecretsHealth, registerAccountProbe } from './health';
|
|
36
|
+
export type { AccountProbe } from './health';
|