@ignitionai/cogitator 0.5.0 → 0.5.2

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 (63) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -44
  4. package/dist/extensions/index.js +66 -29
  5. package/dist/src/app-updates.js +15 -0
  6. package/dist/src/auth-cli.js +18 -8
  7. package/dist/src/auth-http.js +13 -3
  8. package/dist/src/auth-state.js +41 -6
  9. package/dist/src/board.js +3 -1
  10. package/dist/src/browser-http.js +143 -0
  11. package/dist/src/classic-configuration.js +12 -4
  12. package/dist/src/cli.js +30 -4
  13. package/dist/src/config.js +10 -0
  14. package/dist/src/cron.js +91 -15
  15. package/dist/src/db.js +55 -3
  16. package/dist/src/durable/approvals.js +17 -2
  17. package/dist/src/durable/effect-gateway.js +23 -16
  18. package/dist/src/durable/manager.js +15 -6
  19. package/dist/src/durable/mission-runtime.js +204 -46
  20. package/dist/src/durable/recovery.js +37 -0
  21. package/dist/src/durable/workers.js +22 -14
  22. package/dist/src/execution/confinement.js +2 -1
  23. package/dist/src/execution/worker-supervisor.js +222 -0
  24. package/dist/src/git-import.js +187 -0
  25. package/dist/src/github-login.js +101 -0
  26. package/dist/src/history.js +6 -1
  27. package/dist/src/host-pi.js +64 -0
  28. package/dist/src/json-files.js +7 -4
  29. package/dist/src/machine-metrics.js +49 -0
  30. package/dist/src/machine-types.js +1 -0
  31. package/dist/src/mcp-cli.js +63 -0
  32. package/dist/src/mcp-http.js +164 -0
  33. package/dist/src/mcp-oauth.js +502 -0
  34. package/dist/src/mcp-server.js +6 -136
  35. package/dist/src/mcp-tokens.js +104 -0
  36. package/dist/src/mcp-tools.js +264 -0
  37. package/dist/src/native-auth.js +9 -2
  38. package/dist/src/packages.js +190 -0
  39. package/dist/src/paths.js +1 -0
  40. package/dist/src/pi-child.js +180 -0
  41. package/dist/src/pi-rpc-wrap.js +84 -0
  42. package/dist/src/pool.js +58 -7
  43. package/dist/src/project-setup.js +63 -0
  44. package/dist/src/provider-login.js +73 -14
  45. package/dist/src/reap-orphans.js +138 -0
  46. package/dist/src/registry.js +68 -45
  47. package/dist/src/schemas.js +19 -4
  48. package/dist/src/server-compat.js +173 -0
  49. package/dist/src/server-identity.js +69 -0
  50. package/dist/src/server.js +534 -41
  51. package/dist/src/shared-browser.js +357 -0
  52. package/dist/src/skills-import.js +13 -4
  53. package/dist/src/skills-upload.js +68 -0
  54. package/dist/src/spawner.js +20 -4
  55. package/dist/src/subagents.js +242 -0
  56. package/dist/src/team-queue.js +262 -0
  57. package/package.json +13 -4
  58. package/web/dist/assets/BrandLogo3D-CHGXwTbZ.js +4035 -0
  59. package/web/dist/assets/index-DGLkhrE7.css +1 -0
  60. package/web/dist/assets/index-P0WoXBgX.js +84 -0
  61. package/web/dist/index.html +2 -2
  62. package/web/dist/assets/index-C3tRuOTh.js +0 -83
  63. package/web/dist/assets/index-DMQqB0r1.css +0 -1
@@ -0,0 +1,502 @@
1
+ /**
2
+ * OAuth 2.1 pour le serveur MCP HTTP — permet aux connecteurs web (ChatGPT, Claude.ai…)
3
+ * d'obtenir un accès à `/mcp` après consentement explicite du propriétaire.
4
+ *
5
+ * Disponible uniquement en mode protégé (origine HTTPS publique + login propriétaire).
6
+ * Conforme au profil d'autorisation MCP :
7
+ * - métadonnées RFC 9728 (`/.well-known/oauth-protected-resource`) et RFC 8414
8
+ * (`/.well-known/oauth-authorization-server`) ;
9
+ * - enregistrement dynamique RFC 7591 (`/oauth/register`), plafonné ;
10
+ * - code d'autorisation + PKCE S256 obligatoire, redirect_uri exact, `resource` vérifié ;
11
+ * - jetons d'accès courts (1 h) et refresh tokens tournants (réutilisation → révocation du grant).
12
+ *
13
+ * Seuls des hash SHA-256 sont persistés (`<home>/mcp-oauth.json`, 0600). Codes et demandes
14
+ * de consentement restent en mémoire (durée de vie de quelques minutes).
15
+ */
16
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
17
+ import { chmodSync, existsSync, mkdirSync, statSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { browserHeaders } from "./auth-http.js";
20
+ import { atomicWriteJson, readJson } from "./json-files.js";
21
+ import { MCP_SCOPES } from "./mcp-tools.js";
22
+ import { AuthError, ownerSession, requireApproved } from "./native-auth.js";
23
+ export const OAUTH_ACCESS_PREFIX = "cgo_";
24
+ const OAUTH_REFRESH_PREFIX = "cgr_";
25
+ const FILE = "mcp-oauth.json";
26
+ const ACCESS_TTL_S = 3600;
27
+ const REFRESH_TTL_MS = 30 * 24 * 3600_000;
28
+ const CODE_TTL_MS = 60_000;
29
+ const CONSENT_TTL_MS = 10 * 60_000;
30
+ const MAX_CLIENTS = 100;
31
+ const UNUSED_CLIENT_TTL_MS = 24 * 3600_000;
32
+ const MAX_REGISTRATIONS_PER_HOUR = 30;
33
+ const MAX_FORM_BYTES = 16 * 1024;
34
+ const MAX_PENDING = 200;
35
+ const sha = (value) => createHash("sha256").update(value, "utf8").digest("hex");
36
+ const secret = (prefix) => prefix + randomBytes(32).toString("base64url");
37
+ function sameHash(a, b) {
38
+ const x = Buffer.from(a, "hex");
39
+ const y = Buffer.from(b, "hex");
40
+ return x.length === y.length && timingSafeEqual(x, y);
41
+ }
42
+ export function mcpOAuthPath(home) { return join(home, FILE); }
43
+ /** Stockage persistant (clients + grants), relu sur changement de mtime (révocation CLI). */
44
+ export class OAuthStore {
45
+ home;
46
+ cache;
47
+ constructor(home) {
48
+ this.home = home;
49
+ }
50
+ read() {
51
+ const path = mcpOAuthPath(this.home);
52
+ if (!existsSync(path))
53
+ return { version: 1, clients: [], grants: [] };
54
+ const s = statSync(path);
55
+ const key = `${s.mtimeMs}:${s.size}:${s.ino}`;
56
+ if (this.cache?.key !== key) {
57
+ const raw = readJson(path, {});
58
+ this.cache = { key, data: {
59
+ version: 1,
60
+ clients: Array.isArray(raw.clients) ? raw.clients.filter((c) => c && typeof c.client_id === "string" && Array.isArray(c.redirect_uris)) : [],
61
+ grants: Array.isArray(raw.grants) ? raw.grants.filter((g) => g && typeof g.id === "string" && MCP_SCOPES.includes(g.scope)) : [],
62
+ } };
63
+ }
64
+ return structuredClone(this.cache.data);
65
+ }
66
+ write(data) {
67
+ mkdirSync(this.home, { recursive: true });
68
+ const path = mcpOAuthPath(this.home);
69
+ atomicWriteJson(path, data, 0o600);
70
+ chmodSync(path, 0o600);
71
+ this.cache = undefined;
72
+ }
73
+ update(fn) {
74
+ const data = this.read();
75
+ const result = fn(data);
76
+ this.write(data);
77
+ return result;
78
+ }
79
+ }
80
+ export function listOAuthGrants(home) {
81
+ const data = new OAuthStore(home).read();
82
+ return data.grants.map((g) => ({
83
+ id: g.id, client_id: g.client_id, scope: g.scope, created_at: g.created_at,
84
+ client_name: data.clients.find((c) => c.client_id === g.client_id)?.client_name ?? "?",
85
+ refresh_expires: new Date(g.refresh_expires).toISOString(),
86
+ }));
87
+ }
88
+ /** Révoque un grant (par id) ou tous les grants d'un client (par client_id ou nom). */
89
+ export function revokeOAuthGrant(home, idOrClient) {
90
+ return new OAuthStore(home).update((data) => {
91
+ const clientIds = new Set(data.clients.filter((c) => c.client_id === idOrClient || c.client_name === idOrClient).map((c) => c.client_id));
92
+ const before = data.grants.length;
93
+ data.grants = data.grants.filter((g) => g.id !== idOrClient && !clientIds.has(g.client_id));
94
+ return data.grants.length !== before;
95
+ });
96
+ }
97
+ class OAuthError extends Error {
98
+ status;
99
+ error;
100
+ description;
101
+ constructor(status, error, description) {
102
+ super(description);
103
+ this.status = status;
104
+ this.error = error;
105
+ this.description = description;
106
+ }
107
+ }
108
+ function validRedirectUri(raw) {
109
+ if (typeof raw !== "string" || raw.length > 2048)
110
+ return false;
111
+ let url;
112
+ try {
113
+ url = new URL(raw);
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ if (url.hash || url.username || url.password)
119
+ return false;
120
+ if (url.protocol === "https:")
121
+ return true;
122
+ // Clients natifs / outils locaux (RFC 8252) : boucle locale uniquement.
123
+ return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
124
+ }
125
+ function escapeHtml(value) {
126
+ return value.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
127
+ }
128
+ async function readForm(req) {
129
+ const chunks = [];
130
+ let size = 0;
131
+ for await (const chunk of req) {
132
+ const b = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
133
+ size += b.length;
134
+ if (size > MAX_FORM_BYTES)
135
+ throw new OAuthError(413, "invalid_request", "Request too large");
136
+ chunks.push(b);
137
+ }
138
+ const text = Buffer.concat(chunks).toString("utf8");
139
+ const type = String(req.headers["content-type"] ?? "");
140
+ if (/^application\/json/i.test(type)) {
141
+ let parsed;
142
+ try {
143
+ parsed = JSON.parse(text || "{}");
144
+ }
145
+ catch {
146
+ throw new OAuthError(400, "invalid_request", "Invalid JSON");
147
+ }
148
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
149
+ throw new OAuthError(400, "invalid_request", "Invalid body");
150
+ return parsed;
151
+ }
152
+ return Object.fromEntries(new URLSearchParams(text));
153
+ }
154
+ function sendJson(res, status, body, extra = {}) {
155
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", pragma: "no-cache", ...extra });
156
+ res.end(JSON.stringify(body));
157
+ }
158
+ const CORS = { "access-control-allow-origin": "*", "access-control-allow-headers": "authorization, content-type, mcp-protocol-version", "access-control-allow-methods": "GET, POST, OPTIONS" };
159
+ export class McpOAuth {
160
+ state;
161
+ store;
162
+ pending = new Map();
163
+ codes = new Map();
164
+ registrations = [];
165
+ constructor(home, state) {
166
+ this.state = state;
167
+ this.store = new OAuthStore(home);
168
+ }
169
+ get origin() { return this.state.config.origin; }
170
+ get resource() { return `${this.origin}/mcp`; }
171
+ get resourceMetadataUrl() { return `${this.origin}/.well-known/oauth-protected-resource`; }
172
+ /** Chemins publics gérés ici (avant la frontière navigateur). */
173
+ static handles(pathname) {
174
+ return pathname.startsWith("/.well-known/oauth-") || pathname === "/oauth/register" || pathname === "/oauth/authorize" || pathname === "/oauth/token";
175
+ }
176
+ // ---------- Vérification des jetons d'accès (utilisée par /mcp) ----------
177
+ verify(token) {
178
+ if (!token || !token.startsWith(OAUTH_ACCESS_PREFIX) || token.length > 128)
179
+ return undefined;
180
+ const hash = sha(token);
181
+ const data = this.store.read();
182
+ const grant = data.grants.find((g) => sameHash(g.access_hash, hash));
183
+ if (!grant || grant.access_expires <= Date.now())
184
+ return undefined;
185
+ const client = data.clients.find((c) => c.client_id === grant.client_id);
186
+ return { id: `oauth:${grant.id}`, name: client?.client_name ?? "OAuth client", scope: grant.scope, created_at: grant.created_at };
187
+ }
188
+ stillValid(id, scope) {
189
+ if (!id.startsWith("oauth:"))
190
+ return false;
191
+ const grantId = id.slice("oauth:".length);
192
+ return this.store.read().grants.some((g) => g.id === grantId && g.scope === scope && g.refresh_expires > Date.now());
193
+ }
194
+ // ---------- Routage ----------
195
+ async handle(req, res, url) {
196
+ const path = url.pathname;
197
+ try {
198
+ if (req.method === "OPTIONS" && path !== "/oauth/authorize") {
199
+ res.writeHead(204, { ...CORS, "access-control-max-age": "600" });
200
+ res.end();
201
+ return;
202
+ }
203
+ if (path === "/.well-known/oauth-protected-resource" || path === "/.well-known/oauth-protected-resource/mcp") {
204
+ if (req.method !== "GET")
205
+ throw new OAuthError(405, "invalid_request", "Method not allowed");
206
+ return sendJson(res, 200, {
207
+ resource: this.resource,
208
+ authorization_servers: [this.origin],
209
+ scopes_supported: [...MCP_SCOPES],
210
+ bearer_methods_supported: ["header"],
211
+ resource_name: "Cogitator",
212
+ }, CORS);
213
+ }
214
+ if (path === "/.well-known/oauth-authorization-server" || path === "/.well-known/oauth-authorization-server/mcp" || path === "/.well-known/openid-configuration") {
215
+ if (req.method !== "GET")
216
+ throw new OAuthError(405, "invalid_request", "Method not allowed");
217
+ return sendJson(res, 200, {
218
+ issuer: this.origin,
219
+ authorization_endpoint: `${this.origin}/oauth/authorize`,
220
+ token_endpoint: `${this.origin}/oauth/token`,
221
+ registration_endpoint: `${this.origin}/oauth/register`,
222
+ response_types_supported: ["code"],
223
+ grant_types_supported: ["authorization_code", "refresh_token"],
224
+ code_challenge_methods_supported: ["S256"],
225
+ token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"],
226
+ scopes_supported: [...MCP_SCOPES],
227
+ authorization_response_iss_parameter_supported: true,
228
+ }, CORS);
229
+ }
230
+ if (path === "/oauth/register") {
231
+ if (req.method !== "POST")
232
+ throw new OAuthError(405, "invalid_request", "Method not allowed");
233
+ return sendJson(res, 201, this.register(await readForm(req)), CORS);
234
+ }
235
+ if (path === "/oauth/token") {
236
+ if (req.method !== "POST")
237
+ throw new OAuthError(405, "invalid_request", "Method not allowed");
238
+ return sendJson(res, 200, this.token(await readForm(req), req.headers.authorization), CORS);
239
+ }
240
+ if (path === "/oauth/authorize") {
241
+ if (req.method === "GET")
242
+ return await this.authorizePage(req, res, url);
243
+ if (req.method === "POST")
244
+ return await this.authorizeDecision(req, res);
245
+ throw new OAuthError(405, "invalid_request", "Method not allowed");
246
+ }
247
+ throw new OAuthError(404, "invalid_request", "Not found");
248
+ }
249
+ catch (err) {
250
+ if (res.headersSent) {
251
+ res.end();
252
+ return;
253
+ }
254
+ if (err instanceof OAuthError) {
255
+ if (path === "/oauth/authorize")
256
+ return this.htmlError(res, err.status, err.description);
257
+ return sendJson(res, err.status, { error: err.error, error_description: err.description }, CORS);
258
+ }
259
+ if (err instanceof AuthError)
260
+ throw err;
261
+ sendJson(res, 500, { error: "server_error" }, CORS);
262
+ }
263
+ }
264
+ // ---------- Enregistrement dynamique (RFC 7591) ----------
265
+ register(body) {
266
+ const now = Date.now();
267
+ this.registrations = this.registrations.filter((t) => now - t < 3600_000);
268
+ if (this.registrations.length >= MAX_REGISTRATIONS_PER_HOUR)
269
+ throw new OAuthError(429, "invalid_request", "Too many registrations, retry later");
270
+ const uris = body.redirect_uris;
271
+ if (!Array.isArray(uris) || uris.length === 0 || uris.length > 10 || !uris.every(validRedirectUri)) {
272
+ throw new OAuthError(400, "invalid_redirect_uri", "redirect_uris must be 1-10 https (or loopback http) URLs");
273
+ }
274
+ const method = body.token_endpoint_auth_method ?? "none";
275
+ if (method !== "none" && method !== "client_secret_post" && method !== "client_secret_basic") {
276
+ throw new OAuthError(400, "invalid_client_metadata", "Unsupported token_endpoint_auth_method");
277
+ }
278
+ const grantTypes = body.grant_types;
279
+ if (grantTypes !== undefined && (!Array.isArray(grantTypes) || !grantTypes.includes("authorization_code"))) {
280
+ throw new OAuthError(400, "invalid_client_metadata", "grant_types must include authorization_code");
281
+ }
282
+ const name = typeof body.client_name === "string" && body.client_name.trim() ? body.client_name.trim().slice(0, 80) : "MCP client";
283
+ const clientSecret = method === "none" ? undefined : secret("cgs_");
284
+ const client = {
285
+ client_id: randomUUID(), client_name: name, redirect_uris: uris, token_endpoint_auth_method: method,
286
+ ...(clientSecret ? { secret_hash: sha(clientSecret) } : {}), created_at: new Date().toISOString(),
287
+ };
288
+ this.store.update((data) => {
289
+ // Purge : clients jamais autorisés après 24 h, puis plafond global.
290
+ const used = new Set(data.grants.map((g) => g.client_id));
291
+ data.clients = data.clients.filter((c) => used.has(c.client_id) || now - Date.parse(c.created_at) < UNUSED_CLIENT_TTL_MS);
292
+ if (data.clients.length >= MAX_CLIENTS)
293
+ throw new OAuthError(429, "invalid_request", "Client registry full; revoke unused clients");
294
+ data.clients.push(client);
295
+ });
296
+ this.registrations.push(now);
297
+ return {
298
+ client_id: client.client_id, client_name: client.client_name, redirect_uris: client.redirect_uris,
299
+ token_endpoint_auth_method: method, grant_types: ["authorization_code", "refresh_token"], response_types: ["code"],
300
+ client_id_issued_at: Math.floor(now / 1000),
301
+ ...(clientSecret ? { client_secret: clientSecret, client_secret_expires_at: 0 } : {}),
302
+ };
303
+ }
304
+ // ---------- Autorisation : page de consentement du propriétaire ----------
305
+ async session(req) {
306
+ const session = await ownerSession(this.state.auth, this.state.db, this.state.config, browserHeaders(req));
307
+ try {
308
+ requireApproved(session, this.state.config);
309
+ return session;
310
+ }
311
+ catch {
312
+ return null;
313
+ }
314
+ }
315
+ async authorizePage(req, res, url) {
316
+ const q = url.searchParams;
317
+ const client = this.store.read().clients.find((c) => c.client_id === q.get("client_id"));
318
+ if (!client)
319
+ throw new OAuthError(400, "invalid_client", "Unknown client_id. The application must register again.");
320
+ const redirectUri = q.get("redirect_uri") ?? (client.redirect_uris.length === 1 ? client.redirect_uris[0] : "");
321
+ if (!client.redirect_uris.includes(redirectUri))
322
+ throw new OAuthError(400, "invalid_request", "redirect_uri does not match the registered client.");
323
+ // À partir d'ici, les erreurs reviennent au client par redirection (RFC 6749 §4.1.2.1).
324
+ const state = q.get("state") ?? undefined;
325
+ const fail = (error, description) => this.redirect(res, redirectUri, { error, error_description: description, state });
326
+ if (q.get("response_type") !== "code")
327
+ return fail("unsupported_response_type", "response_type must be code");
328
+ const challenge = q.get("code_challenge");
329
+ if (!challenge || q.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43,128}$/.test(challenge))
330
+ return fail("invalid_request", "PKCE S256 required");
331
+ const resource = q.get("resource");
332
+ if (resource && resource !== this.resource && resource !== this.origin)
333
+ return fail("invalid_target", "Unknown resource");
334
+ const requested = (q.get("scope") ?? "").split(/\s+/).filter(Boolean);
335
+ if (requested.some((s) => !MCP_SCOPES.includes(s)))
336
+ return fail("invalid_scope", "Supported scopes: read, full");
337
+ // Pré-sélection prudente : lecture seule sauf demande explicite ; le propriétaire décide.
338
+ const scope = requested.includes("full") ? "full" : "read";
339
+ const session = await this.session(req);
340
+ if (!session)
341
+ return this.loginPage(res, url);
342
+ this.sweepPending();
343
+ const pending = { id: randomBytes(24).toString("base64url"), sessionId: session.id, client, redirectUri, state, challenge, scope, expires: Date.now() + CONSENT_TTL_MS };
344
+ this.pending.set(pending.id, pending);
345
+ this.consentPage(res, pending);
346
+ }
347
+ async authorizeDecision(req, res) {
348
+ // Formulaire de même origine uniquement (anti-CSRF, en plus de l'identifiant lié à la session).
349
+ if (req.headers.origin !== this.origin)
350
+ throw new OAuthError(403, "access_denied", "Cross-origin form refused.");
351
+ const form = await readForm(req);
352
+ const pending = this.pending.get(String(form.request_id ?? ""));
353
+ if (!pending || pending.expires <= Date.now())
354
+ throw new OAuthError(400, "invalid_request", "This authorization request expired. Restart the connection from the application.");
355
+ const session = await this.session(req);
356
+ if (!session || session.id !== pending.sessionId)
357
+ throw new OAuthError(403, "access_denied", "Owner session changed. Restart the connection from the application.");
358
+ this.pending.delete(pending.id);
359
+ if (form.decision !== "approve")
360
+ return this.redirect(res, pending.redirectUri, { error: "access_denied", state: pending.state });
361
+ const scope = form.scope === "read" ? "read" : form.scope === "full" ? "full" : pending.scope;
362
+ const code = randomBytes(32).toString("base64url");
363
+ this.codes.set(sha(code), { clientId: pending.client.client_id, redirectUri: pending.redirectUri, challenge: pending.challenge, scope, expires: Date.now() + CODE_TTL_MS });
364
+ this.redirect(res, pending.redirectUri, { code, state: pending.state });
365
+ }
366
+ redirect(res, redirectUri, params) {
367
+ const target = new URL(redirectUri);
368
+ for (const [k, v] of Object.entries(params))
369
+ if (v !== undefined)
370
+ target.searchParams.set(k, v);
371
+ target.searchParams.set("iss", this.origin);
372
+ res.writeHead(302, { location: target.toString(), "cache-control": "no-store" });
373
+ res.end();
374
+ }
375
+ sweepPending() {
376
+ const now = Date.now();
377
+ for (const [id, p] of this.pending)
378
+ if (p.expires <= now)
379
+ this.pending.delete(id);
380
+ for (const [h, c] of this.codes)
381
+ if (c.expires <= now)
382
+ this.codes.delete(h);
383
+ while (this.pending.size >= MAX_PENDING)
384
+ this.pending.delete(this.pending.keys().next().value);
385
+ }
386
+ // ---------- Jeton (code → accès, refresh tournant) ----------
387
+ authenticateClient(form, authorization) {
388
+ let clientId = form.client_id;
389
+ let clientSecret = form.client_secret;
390
+ const basic = /^Basic\s+(\S+)$/i.exec(authorization ?? "");
391
+ if (basic) {
392
+ const decoded = Buffer.from(basic[1], "base64").toString("utf8");
393
+ const i = decoded.indexOf(":");
394
+ if (i > 0) {
395
+ clientId = decodeURIComponent(decoded.slice(0, i));
396
+ clientSecret = decodeURIComponent(decoded.slice(i + 1));
397
+ }
398
+ }
399
+ const client = this.store.read().clients.find((c) => c.client_id === clientId);
400
+ if (!client)
401
+ throw new OAuthError(401, "invalid_client", "Unknown client");
402
+ if (client.token_endpoint_auth_method !== "none") {
403
+ if (!clientSecret || !client.secret_hash || !sameHash(sha(clientSecret), client.secret_hash))
404
+ throw new OAuthError(401, "invalid_client", "Invalid client credentials");
405
+ }
406
+ return client;
407
+ }
408
+ token(form, authorization) {
409
+ const client = this.authenticateClient(form, authorization);
410
+ if (form.resource && form.resource !== this.resource && form.resource !== this.origin)
411
+ throw new OAuthError(400, "invalid_target", "Unknown resource");
412
+ if (form.grant_type === "authorization_code") {
413
+ const key = sha(String(form.code ?? ""));
414
+ const code = this.codes.get(key);
415
+ this.codes.delete(key); // usage unique, même en cas d'échec
416
+ if (!code || code.expires <= Date.now() || code.clientId !== client.client_id)
417
+ throw new OAuthError(400, "invalid_grant", "Invalid or expired code");
418
+ if (form.redirect_uri !== undefined && form.redirect_uri !== code.redirectUri)
419
+ throw new OAuthError(400, "invalid_grant", "redirect_uri mismatch");
420
+ const verifier = String(form.code_verifier ?? "");
421
+ if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier))
422
+ throw new OAuthError(400, "invalid_grant", "Invalid code_verifier");
423
+ const computed = createHash("sha256").update(verifier).digest("base64url");
424
+ if (computed.length !== code.challenge.length || !timingSafeEqual(Buffer.from(computed), Buffer.from(code.challenge)))
425
+ throw new OAuthError(400, "invalid_grant", "PKCE verification failed");
426
+ const access = secret(OAUTH_ACCESS_PREFIX);
427
+ const refresh = secret(OAUTH_REFRESH_PREFIX);
428
+ const now = Date.now();
429
+ this.store.update((data) => {
430
+ data.grants.push({ id: randomUUID().slice(0, 8), client_id: client.client_id, scope: code.scope, access_hash: sha(access), access_expires: now + ACCESS_TTL_S * 1000,
431
+ refresh_hash: sha(refresh), refresh_expires: now + REFRESH_TTL_MS, created_at: new Date(now).toISOString() });
432
+ });
433
+ return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_S, refresh_token: refresh, scope: code.scope };
434
+ }
435
+ if (form.grant_type === "refresh_token") {
436
+ const presented = sha(String(form.refresh_token ?? ""));
437
+ const access = secret(OAUTH_ACCESS_PREFIX);
438
+ const refresh = secret(OAUTH_REFRESH_PREFIX);
439
+ const now = Date.now();
440
+ const scope = this.store.update((data) => {
441
+ const replayed = data.grants.find((g) => g.client_id === client.client_id && g.prev_refresh_hash && sameHash(g.prev_refresh_hash, presented));
442
+ if (replayed) {
443
+ // Refresh token déjà tourné présenté à nouveau : fuite probable, le grant est révoqué.
444
+ data.grants = data.grants.filter((g) => g.id !== replayed.id);
445
+ return undefined;
446
+ }
447
+ const grant = data.grants.find((g) => g.client_id === client.client_id && sameHash(g.refresh_hash, presented));
448
+ if (!grant || grant.refresh_expires <= now)
449
+ return null;
450
+ grant.prev_refresh_hash = grant.refresh_hash;
451
+ grant.refresh_hash = sha(refresh);
452
+ grant.refresh_expires = now + REFRESH_TTL_MS;
453
+ grant.access_hash = sha(access);
454
+ grant.access_expires = now + ACCESS_TTL_S * 1000;
455
+ return grant.scope;
456
+ });
457
+ if (!scope)
458
+ throw new OAuthError(400, "invalid_grant", "Invalid refresh token");
459
+ return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_S, refresh_token: refresh, scope };
460
+ }
461
+ throw new OAuthError(400, "unsupported_grant_type", "Supported: authorization_code, refresh_token");
462
+ }
463
+ // ---------- Pages HTML (sans JavaScript) ----------
464
+ page(res, status, body, formTarget) {
465
+ const formAction = formTarget ? ` ${new URL(formTarget).origin}` : "";
466
+ res.writeHead(status, {
467
+ "content-type": "text/html; charset=utf-8",
468
+ "cache-control": "no-store",
469
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; form-action 'self'${formAction}; frame-ancestors 'none'; base-uri 'none'`,
470
+ });
471
+ res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Cogitator · Authorize</title>
472
+ <style>:root{color-scheme:light dark;--bg:#f7f7f9;--card:#fff;--fg:#16161d;--muted:#6b6b78;--accent:#5e6ad2;--line:#e3e3ea}
473
+ @media (prefers-color-scheme:dark){:root{--bg:#111116;--card:#1b1b22;--fg:#ececf1;--muted:#9a9aa8;--line:#2c2c36}}
474
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif;display:grid;place-items:center;min-height:100vh;padding:16px;box-sizing:border-box}
475
+ main{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:24px;max-width:440px;width:100%}
476
+ h1{font-size:18px;margin:0 0 12px}p{margin:8px 0}.muted{color:var(--muted);font-size:13px}code{font-size:13px;overflow-wrap:anywhere}
477
+ label{display:flex;gap:8px;align-items:flex-start;margin:8px 0;padding:10px;border:1px solid var(--line);border-radius:8px;cursor:pointer}
478
+ .row{display:flex;gap:8px;margin-top:16px}button,a.btn{flex:1;padding:10px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--fg);font:inherit;cursor:pointer;text-align:center;text-decoration:none}
479
+ button.primary,a.primary{background:var(--accent);border-color:var(--accent);color:#fff}</style></head><body><main>${body}</main></body></html>`);
480
+ }
481
+ consentPage(res, p) {
482
+ const host = new URL(p.redirectUri).host;
483
+ const checked = (s) => (p.scope === s ? " checked" : "");
484
+ this.page(res, 200, `<h1>Allow “${escapeHtml(p.client.client_name)}” to access Cogitator?</h1>
485
+ <p class="muted">The application will be redirected to <code>${escapeHtml(host)}</code>. Only approve if you started this connection yourself.</p>
486
+ <form method="post" action="/oauth/authorize">
487
+ <input type="hidden" name="request_id" value="${escapeHtml(p.id)}">
488
+ <label><input type="radio" name="scope" value="read"${checked("read")}><span><b>Read only</b><br><span class="muted">List agents, workspaces, conversations, schedules and the board.</span></span></label>
489
+ <label><input type="radio" name="scope" value="full"${checked("full")}><span><b>Full control</b><br><span class="muted">Also create and delete resources, send messages to agents and start work. Agents can run commands on this server.</span></span></label>
490
+ <div class="row"><button type="submit" name="decision" value="deny">Deny</button><button class="primary" type="submit" name="decision" value="approve">Allow</button></div>
491
+ </form><p class="muted">You can revoke access later with <code>cogitator mcp token revoke</code>.</p>`, p.redirectUri);
492
+ }
493
+ loginPage(res, url) {
494
+ const back = `${url.pathname}${url.search}`;
495
+ this.page(res, 200, `<h1>Sign in to Cogitator</h1>
496
+ <p>An application asks to connect to your Cogitator. Sign in as the owner in this browser, then continue.</p>
497
+ <div class="row"><a class="btn" href="/" target="_blank" rel="noopener">Open Cogitator to sign in</a><a class="btn primary" href="${escapeHtml(back)}">Continue</a></div>`);
498
+ }
499
+ htmlError(res, status, message) {
500
+ this.page(res, status, `<h1>Authorization failed</h1><p>${escapeHtml(message)}</p>`);
501
+ }
502
+ }