@ignitionai/cogitator 0.3.0 → 0.4.1

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.
@@ -0,0 +1,277 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { betterAuth } from "better-auth";
4
+ import { APIError, createAuthMiddleware, isAPIError } from "better-auth/api";
5
+ import { expireCookie } from "better-auth/cookies";
6
+ import { getMigrations } from "better-auth/db/migration";
7
+ import { twoFactor } from "better-auth/plugins";
8
+ export const ENROLLMENT_MS = 10 * 60_000;
9
+ export const REPLAY_MS = 5 * 60_000;
10
+ // Carries validated/original and SQL-observed replacement IDs, never credentials or an approval cache.
11
+ export const authMutationAuthorization = new AsyncLocalStorage();
12
+ function installFactorMutationGuard(db) {
13
+ db.function("cogitator_factor_session", () => authMutationAuthorization.getStore()?.sessionId ?? null);
14
+ db.function("cogitator_factor_mode", () => authMutationAuthorization.getStore()?.mode ?? null);
15
+ db.function("cogitator_rotated_session", () => authMutationAuthorization.getStore()?.rotatedId ?? null);
16
+ db.function("cogitator_record_rotation", (id) => {
17
+ const scope = authMutationAuthorization.getStore();
18
+ if (scope && typeof id === "string")
19
+ scope.rotatedId = id;
20
+ return null;
21
+ });
22
+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='twoFactor'").get())
23
+ return;
24
+ // The supported library adapter has asynchronous work after its before-hooks. TEMP SQLite
25
+ // constraints re-check authoritative rows within the actual write, after all that async work.
26
+ const check = `SELECT CASE WHEN NOT EXISTS (
27
+ SELECT 1 FROM session s JOIN user u ON u.id=s.userId JOIN authPolicy p ON p.singleton=1
28
+ WHERE s.id=cogitator_factor_session() AND s.userId=p.ownerId AND NEW.userId=s.userId
29
+ AND julianday(s.expiresAt)>julianday('now') AND (
30
+ (cogitator_factor_mode()='approved' AND s.mfaApproved=1 AND u.twoFactorEnabled=1
31
+ AND EXISTS(SELECT 1 FROM twoFactor f WHERE f.userId=u.id AND f.verified=1))
32
+ OR (cogitator_factor_mode()='enrollment' AND u.twoFactorEnabled=0
33
+ AND p.claimId=s.id AND p.claimExpires>unixepoch('subsec')*1000)
34
+ )
35
+ ) THEN RAISE(ABORT, 'COGITATOR_AUTHORITY_EXPIRED') END;`;
36
+ db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS cogitator_factor_insert BEFORE INSERT ON main.twoFactor
37
+ WHEN cogitator_factor_session() IS NOT NULL BEGIN ${check} END;
38
+ CREATE TEMP TRIGGER IF NOT EXISTS cogitator_factor_codes BEFORE UPDATE OF backupCodes ON main.twoFactor
39
+ WHEN cogitator_factor_session() IS NOT NULL BEGIN ${check} END;`);
40
+ const authority = `SELECT CASE WHEN NOT EXISTS (
41
+ SELECT 1 FROM session s JOIN authPolicy p ON p.singleton=1 AND p.ownerId=s.userId
42
+ WHERE s.id=cogitator_factor_session() AND s.mfaApproved=0
43
+ AND julianday(s.expiresAt)>julianday('now')
44
+ AND p.claimId=s.id AND p.claimExpires>unixepoch('subsec')*1000
45
+ ) THEN RAISE(ABORT, 'COGITATOR_AUTHORITY_EXPIRED') END;`;
46
+ // 1.7.7 rotates between user activation and factor verification. Keep the old row
47
+ // authoritative through those awaits: defer ONLY this request's deletion, then retire
48
+ // it in the final verified statement. Other requests' logout deletions are not deferred.
49
+ db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS cogitator_activate BEFORE UPDATE OF twoFactorEnabled ON main.user
50
+ WHEN cogitator_factor_mode()='activation' BEGIN
51
+ ${authority}
52
+ SELECT CASE WHEN OLD.twoFactorEnabled<>0 OR NEW.twoFactorEnabled<>1
53
+ OR NEW.id<>(SELECT ownerId FROM authPolicy WHERE singleton=1)
54
+ THEN RAISE(ABORT, 'COGITATOR_AUTHORITY_EXPIRED') END;
55
+ END;
56
+ CREATE TEMP TRIGGER IF NOT EXISTS cogitator_rotate BEFORE INSERT ON main.session
57
+ WHEN cogitator_factor_mode()='activation' BEGIN
58
+ ${authority}
59
+ SELECT CASE WHEN NEW.mfaApproved<>0 OR NEW.userId<>(SELECT ownerId FROM authPolicy WHERE singleton=1)
60
+ OR cogitator_rotated_session() IS NOT NULL
61
+ THEN RAISE(ABORT, 'COGITATOR_AUTHORITY_EXPIRED') END;
62
+ END;
63
+ CREATE TEMP TRIGGER IF NOT EXISTS cogitator_rotation AFTER INSERT ON main.session
64
+ WHEN cogitator_factor_mode()='activation' BEGIN SELECT cogitator_record_rotation(NEW.id); END;
65
+ CREATE TEMP TRIGGER IF NOT EXISTS cogitator_defer_retirement BEFORE DELETE ON main.session
66
+ WHEN cogitator_factor_mode()='activation' AND OLD.id=cogitator_factor_session()
67
+ AND EXISTS(SELECT 1 FROM twoFactor WHERE userId=OLD.userId AND verified=0)
68
+ BEGIN ${authority} SELECT RAISE(IGNORE); END;
69
+ CREATE TEMP TRIGGER IF NOT EXISTS cogitator_verify BEFORE UPDATE OF verified ON main.twoFactor
70
+ WHEN cogitator_factor_mode()='activation' BEGIN
71
+ ${authority}
72
+ SELECT CASE WHEN NEW.verified<>1 OR OLD.verified<>0 OR NOT EXISTS (
73
+ SELECT 1 FROM session s JOIN user u ON u.id=s.userId
74
+ WHERE s.id=cogitator_rotated_session() AND s.id<>cogitator_factor_session()
75
+ AND s.userId=NEW.userId AND s.mfaApproved=0 AND u.twoFactorEnabled=1
76
+ AND julianday(s.expiresAt)>julianday('now')
77
+ ) THEN RAISE(ABORT, 'COGITATOR_AUTHORITY_EXPIRED') END;
78
+ END;
79
+ CREATE TEMP TRIGGER IF NOT EXISTS cogitator_retire AFTER UPDATE OF verified ON main.twoFactor
80
+ WHEN cogitator_factor_mode()='activation' BEGIN
81
+ DELETE FROM session WHERE id=cogitator_factor_session();
82
+ SELECT CASE WHEN EXISTS(SELECT 1 FROM session WHERE id=cogitator_factor_session())
83
+ THEN RAISE(ABORT, 'COGITATOR_AUTHORITY_EXPIRED') END;
84
+ END;`);
85
+ }
86
+ /** No transaction spans library awaits. Failed partial activation remains offline-recovery-only. */
87
+ export async function verifyEnrollment(db, sessionId, invoke) {
88
+ const scope = { sessionId, mode: "activation" };
89
+ let complete = false;
90
+ try {
91
+ const response = await authMutationAuthorization.run(scope, invoke);
92
+ if (!response.ok)
93
+ return response;
94
+ const rotated = db.prepare(`SELECT 1 FROM session s JOIN twoFactor f ON f.userId=s.userId
95
+ JOIN authPolicy p ON p.ownerId=s.userId WHERE s.id=? AND s.mfaApproved=0 AND f.verified=1
96
+ AND julianday(s.expiresAt)>julianday('now') AND p.claimId=? AND p.claimExpires>?`).get(scope.rotatedId ?? "", sessionId, Date.now());
97
+ if (db.inTransaction || !rotated || db.prepare("SELECT 1 FROM session WHERE id=?").get(sessionId))
98
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
99
+ complete = true;
100
+ return response;
101
+ }
102
+ finally {
103
+ if (!complete && scope.rotatedId) {
104
+ db.prepare("DELETE FROM session WHERE id=?").run(scope.rotatedId);
105
+ if (db.inTransaction || db.prepare("SELECT 1 FROM session WHERE id=?").get(scope.rotatedId))
106
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
107
+ }
108
+ }
109
+ }
110
+ export class AuthError extends Error {
111
+ code;
112
+ status;
113
+ retryAt;
114
+ constructor(code, status = 403, retryAt) {
115
+ super(code);
116
+ this.code = code;
117
+ this.status = status;
118
+ this.retryAt = retryAt;
119
+ }
120
+ }
121
+ export function createNativeAuth(db, config, offline = false, captureReset) {
122
+ installFactorMutationGuard(db);
123
+ const options = {
124
+ appName: "Cogitator", baseURL: config.origin, basePath: "/api/auth", secret: config.secret,
125
+ database: db, trustedOrigins: [config.origin],
126
+ hooks: { before: createAuthMiddleware(async (ctx) => {
127
+ if (ctx.path !== "/sign-out")
128
+ return;
129
+ const cookie = ctx.context.createAuthCookie("two_factor");
130
+ const identifier = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
131
+ if (identifier) {
132
+ // Use the library's signed-cookie and atomic single-use capability primitives.
133
+ try {
134
+ await ctx.context.internalAdapter.consumeVerificationValue(identifier);
135
+ await ctx.context.internalAdapter.consumeVerificationValue(`2fa-attempts-${identifier}`);
136
+ if (db.inTransaction || await ctx.context.internalAdapter.findVerificationValue(identifier))
137
+ throw new Error("Challenge revocation incomplete");
138
+ }
139
+ catch {
140
+ throw new APIError("SERVICE_UNAVAILABLE", { code: "AUTH_UNAVAILABLE", message: "AUTH_UNAVAILABLE" });
141
+ }
142
+ }
143
+ expireCookie(ctx, cookie);
144
+ }) },
145
+ logger: { disabled: true }, telemetry: { enabled: false },
146
+ onAPIError: { onError: (error) => {
147
+ if (error instanceof Error && error.message === "COGITATOR_AUTHORITY_EXPIRED")
148
+ throw new APIError("UNAUTHORIZED", { code: "AUTH_REQUIRED", message: "AUTH_REQUIRED" });
149
+ if (!isAPIError(error))
150
+ throw new APIError("INTERNAL_SERVER_ERROR", { code: "AUTH_UNAVAILABLE", message: "AUTH_UNAVAILABLE" });
151
+ } },
152
+ emailAndPassword: {
153
+ enabled: true, disableSignUp: !offline, minPasswordLength: 12, maxPasswordLength: 128,
154
+ revokeSessionsOnPasswordReset: true,
155
+ ...(captureReset ? { sendResetPassword: async ({ token }) => { captureReset(token); } } : {}),
156
+ },
157
+ advanced: { useSecureCookies: true, trustedProxyHeaders: false, ipAddress: { ipAddressHeaders: ["x-cogitator-peer"] } },
158
+ session: {
159
+ expiresIn: 24 * 60 * 60, disableSessionRefresh: true, cookieCache: { enabled: false },
160
+ additionalFields: { mfaApproved: { type: "boolean", required: true, defaultValue: false, input: false, returned: false } },
161
+ },
162
+ rateLimit: { enabled: true, storage: "database", window: 60, max: 60,
163
+ customRules: { "/sign-in/email": { window: 60, max: 10 }, "/two-factor/*": { window: 10, max: 3 } } },
164
+ plugins: [twoFactor({ issuer: "Cogitator", allowPasswordless: false, skipVerificationOnEnable: false })],
165
+ databaseHooks: { session: { create: { before: async (session, ctx) => {
166
+ const eligible = session.userId === config.ownerId && !ctx?.context.session &&
167
+ (ctx?.path === "/two-factor/verify-totp" || ctx?.path === "/two-factor/verify-backup-code");
168
+ if (eligible) {
169
+ const factor = db.prepare('SELECT verified FROM twoFactor WHERE userId = ?').get(config.ownerId);
170
+ if (factor?.verified !== 1)
171
+ throw new APIError("FORBIDDEN", { code: "MFA_REQUIRED", message: "MFA_REQUIRED" });
172
+ if (ctx?.path === "/two-factor/verify-totp") {
173
+ if (typeof ctx.body?.code !== "string" || db.inTransaction)
174
+ throw new APIError("SERVICE_UNAVAILABLE", { code: "AUTH_UNAVAILABLE", message: "AUTH_UNAVAILABLE" });
175
+ const digest = createHmac("sha256", config.replayKey).update(JSON.stringify([config.ownerId, ctx.body.code])).digest("hex");
176
+ const now = Date.now();
177
+ const claimed = db.prepare(`INSERT INTO authReplay(digest, expires) VALUES (?, ?)
178
+ ON CONFLICT(digest) DO UPDATE SET expires=excluded.expires WHERE authReplay.expires <= ?`).run(digest, now + REPLAY_MS, now);
179
+ if (!claimed.changes)
180
+ throw new APIError("CONFLICT", { code: "CODE_ALREADY_USED", message: "CODE_ALREADY_USED" });
181
+ db.prepare("DELETE FROM authReplay WHERE expires < ?").run(now);
182
+ }
183
+ }
184
+ return { data: { ...session, mfaApproved: eligible,
185
+ ...(!eligible ? { expiresAt: new Date(Math.min(new Date(session.expiresAt).getTime(), Date.now() + ENROLLMENT_MS)) } : {}) } };
186
+ } } } },
187
+ };
188
+ const auth = betterAuth(options);
189
+ return { auth, options };
190
+ }
191
+ export async function migrateAuth(db, options) {
192
+ const plan = await getMigrations(options);
193
+ if (plan.schemaProblems.length || plan.unsafeChanges.length)
194
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
195
+ await plan.runMigrations();
196
+ db.exec(`CREATE TABLE IF NOT EXISTS authPolicy (
197
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), ownerId TEXT NOT NULL,
198
+ setupDigest TEXT, setupExpires INTEGER NOT NULL DEFAULT 0, claimId TEXT, claimExpires INTEGER NOT NULL DEFAULT 0);
199
+ CREATE TABLE IF NOT EXISTS authReplay(digest TEXT PRIMARY KEY, expires INTEGER NOT NULL);
200
+ CREATE TABLE IF NOT EXISTS authThrottle(path TEXT PRIMARY KEY, count INTEGER NOT NULL, until INTEGER NOT NULL);
201
+ CREATE UNIQUE INDEX IF NOT EXISTS authOneFactor ON twoFactor(userId);
202
+ CREATE TRIGGER IF NOT EXISTS authOneOwner BEFORE INSERT ON user
203
+ WHEN EXISTS(SELECT 1 FROM user) BEGIN SELECT RAISE(ABORT, 'single owner'); END;
204
+ CREATE TRIGGER IF NOT EXISTS authOwnerImmutable BEFORE UPDATE OF id ON user
205
+ BEGIN SELECT RAISE(ABORT, 'immutable owner'); END;`);
206
+ installFactorMutationGuard(db);
207
+ }
208
+ export function policy(db) {
209
+ const row = db.prepare("SELECT * FROM authPolicy WHERE singleton=1").get();
210
+ if (!row)
211
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
212
+ return row;
213
+ }
214
+ export function assertOwner(db, config) {
215
+ const owners = db.prepare('SELECT id, twoFactorEnabled FROM user').all();
216
+ if (owners.length !== 1 || owners[0]?.id !== config.ownerId || policy(db).ownerId !== config.ownerId)
217
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
218
+ const factors = db.prepare('SELECT userId, verified FROM twoFactor').all();
219
+ if (factors.length > 1 || factors.some(f => f.userId !== config.ownerId) ||
220
+ Boolean(owners[0].twoFactorEnabled) !== Boolean(factors[0]?.verified))
221
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
222
+ }
223
+ export function sessionById(db, config, id) {
224
+ assertOwner(db, config);
225
+ const row = db.prepare(`SELECT s.id, s.expiresAt, s.mfaApproved, u.email, u.twoFactorEnabled FROM session s
226
+ JOIN user u ON u.id=s.userId WHERE s.id=? AND s.userId=?`).get(id, config.ownerId);
227
+ if (!row)
228
+ return null;
229
+ const expiresAt = new Date(row.expiresAt).getTime();
230
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now())
231
+ return null;
232
+ return { id: row.id, email: row.email, expiresAt, approved: row.mfaApproved === 1, enrolled: row.twoFactorEnabled === 1 };
233
+ }
234
+ export async function ownerSession(auth, db, config, headers) {
235
+ const result = await auth.api.getSession({ headers, query: { disableCookieCache: true } });
236
+ return result ? sessionById(db, config, result.session.id) : null;
237
+ }
238
+ export function requireApproved(session) {
239
+ if (!session)
240
+ throw new AuthError("AUTH_REQUIRED", 401);
241
+ if (!session.approved || !session.enrolled)
242
+ throw new AuthError("MFA_REQUIRED", 403);
243
+ }
244
+ export function issueSetupKey(db, config) {
245
+ const key = randomBytes(32).toString("base64url");
246
+ db.prepare("UPDATE authPolicy SET setupDigest=?, setupExpires=?, claimId=NULL, claimExpires=0 WHERE singleton=1")
247
+ .run(createHmac("sha256", config.replayKey).update(key).digest("hex"), Date.now() + 30 * 60_000);
248
+ return key;
249
+ }
250
+ export function selectEnrollment(db, config, session, key) {
251
+ if (!session)
252
+ throw new AuthError("AUTH_REQUIRED", 401);
253
+ if (session.enrolled || session.approved)
254
+ throw new AuthError("REAUTH_REQUIRED", 403);
255
+ db.transaction(() => {
256
+ const p = policy(db);
257
+ const now = Date.now();
258
+ const live = p.claimId && p.claimExpires > now && sessionById(db, config, p.claimId);
259
+ if (live && p.claimId === session.id)
260
+ return;
261
+ if (live)
262
+ throw new AuthError("ENROLLMENT_BUSY", 409, new Date(p.claimExpires).toISOString());
263
+ if (!p.setupDigest || p.setupExpires <= now)
264
+ throw new AuthError("SETUP_KEY_EXPIRED", 403);
265
+ const digest = createHmac("sha256", config.replayKey).update(key ?? "").digest("hex");
266
+ if (!timingSafeEqual(Buffer.from(digest), Buffer.from(p.setupDigest)))
267
+ throw new AuthError("SETUP_KEY_INVALID", 403);
268
+ db.prepare("UPDATE authPolicy SET claimId=?, claimExpires=? WHERE singleton=1").run(session.id, Math.min(session.expiresAt, now + ENROLLMENT_MS));
269
+ }).immediate();
270
+ }
271
+ export function requireEnrollment(db, session) {
272
+ if (!session)
273
+ throw new AuthError("AUTH_REQUIRED", 401);
274
+ const p = policy(db);
275
+ if (session.enrolled || p.claimId !== session.id || p.claimExpires <= Date.now())
276
+ throw new AuthError("REAUTH_REQUIRED", 403);
277
+ }
@@ -0,0 +1,127 @@
1
+ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { request } from "node:http";
3
+ import { connect } from "node:net";
4
+ import { authPaths, checkPrivate, protectedRequired, validateOwnerSocketPath } from "./auth-state.js";
5
+ import { authenticationRequired, BASE_URL } from "./config.js";
6
+ import { getPaths } from "./paths.js";
7
+ import { createPrivateServer } from "./server.js";
8
+ async function socketLive(path) {
9
+ return new Promise((done, reject) => {
10
+ const socket = connect(path);
11
+ socket.setTimeout(1000, () => { socket.destroy(); reject(new Error("Owner socket probe timed out")); });
12
+ socket.once("connect", () => { socket.destroy(); done(true); });
13
+ socket.once("error", (err) => err.code === "ECONNREFUSED" ? done(false) : reject(err));
14
+ });
15
+ }
16
+ /** TCP must already be reserved. Only reconcile a stale inode recorded by this implementation.
17
+ * A SIGKILL between bind and receipt leaves an unrecognized socket: fail closed for stopped-owner inspection. */
18
+ export async function listenOwnerSocket(app, home) {
19
+ validateOwnerSocketPath(home);
20
+ const { directory, socket } = authPaths(home);
21
+ const receipt = `${socket}.json`;
22
+ checkPrivate(directory, true);
23
+ if (existsSync(socket)) {
24
+ const s = lstatSync(socket);
25
+ if (!s.isSocket() || s.isSymbolicLink() || (s.mode & 0o077) || (process.getuid && s.uid !== process.getuid()))
26
+ throw new Error("Unsafe owner socket");
27
+ checkPrivate(receipt);
28
+ const recorded = JSON.parse(readFileSync(receipt, "utf8"));
29
+ if (!recorded || typeof recorded !== "object" || !("ino" in recorded) || !("dev" in recorded) || recorded.ino !== s.ino || recorded.dev !== s.dev)
30
+ throw new Error("Unrecognized owner socket");
31
+ if (await socketLive(socket))
32
+ throw new Error("Owner socket is already live");
33
+ unlinkSync(socket);
34
+ unlinkSync(receipt);
35
+ }
36
+ else if (existsSync(receipt)) {
37
+ checkPrivate(receipt);
38
+ unlinkSync(receipt);
39
+ }
40
+ const server = createPrivateServer(app);
41
+ let ownSocket;
42
+ let ownReceipt;
43
+ const cleanup = () => { removeOwnedFile(socket, ownSocket); removeOwnedFile(receipt, ownReceipt); };
44
+ try {
45
+ await new Promise((done, reject) => { server.once("error", reject); server.listen(socket, done); });
46
+ ownSocket = lstatSync(socket);
47
+ chmodSync(socket, 0o600);
48
+ // Capture the exclusive receipt's identity before any write/fsync can fail.
49
+ const fd = openSync(receipt, "wx", 0o600);
50
+ try {
51
+ ownReceipt = fstatSync(fd);
52
+ writeFileSync(fd, JSON.stringify({ ino: ownSocket.ino, dev: ownSocket.dev }));
53
+ fsyncSync(fd);
54
+ }
55
+ finally {
56
+ closeSync(fd);
57
+ }
58
+ const directoryFd = openSync(directory, "r");
59
+ try {
60
+ fsyncSync(directoryFd);
61
+ }
62
+ finally {
63
+ closeSync(directoryFd);
64
+ }
65
+ server.once("close", cleanup);
66
+ return server;
67
+ }
68
+ catch (error) {
69
+ // The caller has no server handle until this function returns successfully.
70
+ server.closeAllConnections();
71
+ await new Promise(done => server.close(() => done()));
72
+ try {
73
+ cleanup();
74
+ }
75
+ catch (cleanupError) {
76
+ throw new AggregateError([error, cleanupError], "Owner socket setup and cleanup failed");
77
+ }
78
+ throw error;
79
+ }
80
+ }
81
+ function removeOwnedFile(path, own) {
82
+ if (!own || !existsSync(path))
83
+ return;
84
+ const current = lstatSync(path);
85
+ if (current.ino === own.ino && current.dev === own.dev)
86
+ unlinkSync(path);
87
+ }
88
+ /** Explicit URLs, including loopback overrides, always retain ordinary HTTP semantics. */
89
+ export async function ownerRequest(method, path, body, env = process.env) {
90
+ const home = getPaths(env).home;
91
+ const required = authenticationRequired(env);
92
+ if (env.COGITATOR_URL !== undefined || !protectedRequired(home, required)) {
93
+ const response = await fetch(`${env.COGITATOR_URL ?? BASE_URL}${path}`, { method,
94
+ ...(body !== undefined ? { headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {}) });
95
+ const data = await response.json();
96
+ if (!response.ok)
97
+ throw new Error(typeof data.error === "string" ? data.error : `HTTP ${response.status}`);
98
+ return data;
99
+ }
100
+ validateOwnerSocketPath(home);
101
+ const { directory, socket } = authPaths(home);
102
+ checkPrivate(directory, true);
103
+ const s = lstatSync(socket);
104
+ if (!s.isSocket() || (s.mode & 0o077) || (process.getuid && s.uid !== process.getuid()))
105
+ throw new Error("Unsafe owner socket");
106
+ return new Promise((done, reject) => {
107
+ const req = request({ socketPath: socket, method, path, headers: { "content-type": "application/json" }, timeout: 30_000 }, res => {
108
+ const chunks = [];
109
+ res.on("data", chunk => chunks.push(Buffer.from(chunk)));
110
+ res.on("error", reject);
111
+ res.on("end", () => {
112
+ try {
113
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
114
+ if ((res.statusCode ?? 500) >= 400)
115
+ throw new Error(typeof data.error === "string" ? data.error : `HTTP ${res.statusCode}`);
116
+ done(data);
117
+ }
118
+ catch (err) {
119
+ reject(err);
120
+ }
121
+ });
122
+ });
123
+ req.on("error", reject);
124
+ req.on("timeout", () => req.destroy(new Error("Owner request timed out")));
125
+ req.end(body === undefined ? undefined : JSON.stringify(body));
126
+ });
127
+ }
package/dist/src/pool.js CHANGED
@@ -1,7 +1,4 @@
1
- /**
2
- * PiProcessPool — un process `pi --mode rpc` par conversation active (I3 : unique point de spawn).
3
- * Spawn paresseux, recyclage idle, plafond avec éviction du plus vieux non-streaming.
4
- */
1
+ import { checkRequestAuthorization } from "./request-authorization.js";
5
2
  export class PoolError extends Error {
6
3
  code;
7
4
  constructor(message, code) {
@@ -57,7 +54,9 @@ export class PiPool {
57
54
  existing.lastActivityAt = Date.now();
58
55
  return {};
59
56
  }
57
+ checkRequestAuthorization();
60
58
  await this.makeRoom();
59
+ checkRequestAuthorization();
61
60
  const args = spawn.resumeSessionFile ? [...spawn.args, "--session", spawn.resumeSessionFile] : spawn.args;
62
61
  const client = this.opts.factory({ cwd: spawn.cwd, args, env: spawn.env });
63
62
  const handle = { convId, client, lastActivityAt: Date.now(), dead: false };
@@ -91,6 +90,7 @@ export class PiPool {
91
90
  for (const h of oldestFirst) {
92
91
  if (await this.streaming(h))
93
92
  continue; // jamais de kill d'un travail en cours
93
+ checkRequestAuthorization();
94
94
  await this.evict(h.convId);
95
95
  return;
96
96
  }
@@ -0,0 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // Carries a fresh DB check through asynchronous route helpers, never a token or a cached approval.
3
+ export const requestAuthorization = new AsyncLocalStorage();
4
+ export function checkRequestAuthorization() { requestAuthorization.getStore()?.(); }
@@ -49,6 +49,7 @@ export const agentInputSchema = z.object({
49
49
  tools_allowlist: z.array(z.string()).nullable().optional(),
50
50
  mcp_servers: z.array(mcpServerEntrySchema).optional(),
51
51
  subagents: z.array(subagentInputSchema).optional(),
52
+ default_workspace_id: z.string().nullable().optional(),
52
53
  });
53
54
  // ---------- Workspaces ----------
54
55
  export const workspaceCreateSchema = z.object({