omni-notify-mcp 1.3.372 → 1.3.373

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/dist/daemon.js CHANGED
@@ -47,7 +47,7 @@ function successor() {
47
47
  return spawn(process.execPath, [...process.execArgv, self], { detached: true, stdio: "ignore", windowsHide: true });
48
48
  if (!existsSync(SUPERVISE_LOOP))
49
49
  throw new Error(`the supervise loop is not in the config dir at ${SUPERVISE_LOOP} — the login entry and the boot task copy it there, so nothing can own the next run`);
50
- return spawn(process.execPath, [SUPERVISE_LOOP, "supervise"], { detached: true, stdio: "ignore", windowsHide: true });
50
+ return spawn(process.execPath, [SUPERVISE_LOOP, "supervise", self], { detached: true, stdio: "ignore", windowsHide: true });
51
51
  }
52
52
  /** The installed build has replaced this one on disk: a supervised process only exits and its owner starts that build; an unsupervised one starts its successor and names it in the heartbeat before it exits, so no other owner starts a second build meanwhile, and on Windows the supervise loop reads that beat as the claim on its first run. */
53
53
  function replaceWithInstalledBuild() {
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The agent stream (#3402): the live feed of a conversation's agent — its thinking and its output as they arrive, told
3
+ * apart — that an MCP caller attaches to instead of waiting for the finished reply alone. The session driver appends a
4
+ * frame for every delta the CLI's own `stream_event` carries (`claudeProvider.ts` reads them; the CLI is started with
5
+ * `--include-partial-messages`), beside a frame for the tool the turn is on and one for each discrete conversation
6
+ * event, so a reader sees the whole turn in arrival order from one stream.
7
+ *
8
+ * The stream is served over the SAME authenticated gateway door as everything else (a Server-Sent Events route in
9
+ * `restDoor.ts`) and is owned by the person, exactly as a native terminal is (#3370): the owner is the door's own
10
+ * `personId()` and another person's key is refused with 404.
11
+ *
12
+ * A frame's `seq` is monotonic per conversation and a reader resumes with `after` = the last `seq` it read, so a
13
+ * dropped client that re-attaches misses nothing it had not already received; frames are held for the conversation's
14
+ * life and freed when it is deleted. The feed is live and in memory, not a durable transcript: a BN restart empties it
15
+ * and its `seq` starts again, so a re-attach with a `seq` from before a restart resumes within the new stream — the
16
+ * finished turn stays readable through the conversation's own log.
17
+ *
18
+ * NOTHING IS CAPPED HERE — no buffer size, no retained-history window and no idle bound is applied, because every such
19
+ * bound is a gate that is Meni's to rule on before it ships (the proposal sits on #3402's decision field).
20
+ */
21
+ import { EventEmitter } from "events";
22
+ import { GatewayError, MAX_WAIT_SECONDS, readConversation } from "./conversations.js";
23
+ /**
24
+ * One conversation's live stream: the frames appended in order, the owner it belongs to, and the things waiting on a
25
+ * new frame. It is created by the session driver the moment the conversation's turn produces anything and bound to a
26
+ * person the first time the door serves it to one.
27
+ */
28
+ class AgentStream {
29
+ /** The person this stream belongs to, fixed by the first sign-in that reads it (#3370); absent until then. */
30
+ owner;
31
+ seq = 0;
32
+ frames = [];
33
+ changed = new EventEmitter();
34
+ /** Appends one frame and wakes every reader; the new frame's own `seq` is returned so a caller can echo it back as `after`. */
35
+ append(kind, text, turn, rest = {}) {
36
+ const frame = { seq: ++this.seq, ts: new Date().toISOString(), kind, text, turn, ...rest };
37
+ this.frames.push(frame);
38
+ this.changed.emit("change");
39
+ return frame;
40
+ }
41
+ /**
42
+ * The frames past `after`, or — a reader with no position — the whole stream so far; `after` is the last `seq` the
43
+ * reader had, so what it returns is exactly what the reader has not seen. `holdMs` bounds the wait for a new frame:
44
+ * the SSE route holds `MAX_WAIT_SECONDS` (the same cap every blocking BN call obeys) and writes each frame the moment
45
+ * it is produced instead of polling, while the MCP read a tool-only caller polls with is given 0 and answers at once.
46
+ */
47
+ async read(after, signal, holdMs = MAX_WAIT_SECONDS * 1000) {
48
+ for (;;) {
49
+ const frames = after === undefined ? this.frames.slice() : this.frames.filter((frame) => frame.seq > after);
50
+ if (frames.length > 0 || signal.aborted || holdMs === 0)
51
+ return { frames, seq: this.seq };
52
+ await new Promise((resolve) => {
53
+ const done = () => { clearTimeout(timer); this.changed.off("change", done); signal.removeEventListener("abort", done); resolve(); };
54
+ const timer = setTimeout(done, holdMs);
55
+ this.changed.once("change", done);
56
+ signal.addEventListener("abort", done, { once: true });
57
+ });
58
+ }
59
+ }
60
+ }
61
+ const streams = new Map();
62
+ /** This conversation's stream, made if it is not there yet: the session driver appends to it from the first frame of a turn. */
63
+ export function agentStream(id) {
64
+ const existing = streams.get(id);
65
+ if (existing !== undefined)
66
+ return existing;
67
+ const stream = new AgentStream();
68
+ streams.set(id, stream);
69
+ return stream;
70
+ }
71
+ /**
72
+ * The stream of `id` as `owner`'s, for the door: the conversation must exist, and the stream belongs to the first person
73
+ * who reads it — another person's key is refused with 404, never handed someone else's stream. Every later reader of the
74
+ * same person is served the same stream, so a re-attach resumes it.
75
+ */
76
+ export function agentStreamFor(owner, id) {
77
+ readConversation(id);
78
+ const stream = agentStream(id);
79
+ if (stream.owner === undefined)
80
+ stream.owner = owner;
81
+ else if (stream.owner !== owner)
82
+ throw new GatewayError(404, "No agent stream for this person.");
83
+ return stream;
84
+ }
85
+ /** The conversation is gone: its stream and every frame it held are dropped. */
86
+ export function dropAgentStream(id) {
87
+ streams.delete(id);
88
+ }
@@ -180,22 +180,14 @@ async function signIn(notice) {
180
180
  main.append(message);
181
181
  }
182
182
 
183
- // GATE: how long the page waits before asking the gateway again about its sign-in after a failed check.
184
- var RECHECK_MS = 3000;
185
183
  async function resumeSignIn() {
186
184
  var response = await fetch("/passkey/session", {headers:{authorization:"Bearer " + token}});
187
- if (response.status === 401) { signIn("Your sign-in expired or was revoked. Sign in again."); return; }
188
- if (!response.ok) throw new Error("the gateway answered " + response.status);
185
+ if (!response.ok) { signIn("Your sign-in expired or was revoked. Sign in again."); return; }
189
186
  var session = await response.json();
190
187
  keep(token, session.expiresIn === null ? 0 : Date.now() + session.expiresIn * 1000);
191
188
  home();
192
189
  }
193
- function recheckSignIn(err) {
194
- show("signin", "Sign in");
195
- main.append(el("div", "system", "Could not reach the gateway (" + err.message + ") — your sign-in is kept; checking again…"));
196
- setTimeout(startSignIn, RECHECK_MS);
197
- }
198
- function startSignIn() { if (token) resumeSignIn().catch(recheckSignIn); else signIn(""); }`;
190
+ function startSignIn() { if (token) resumeSignIn().catch(function (err) { signIn("Could not check sign-in: " + err.message); }); else signIn(""); }`;
199
191
  /**
200
192
  * The conversations half of BN's one page: the list he manages — the table, its per-row actions and the project picker.
201
193
  * It is carried from the deleted Conversations page (#3401) into the native CLI page because that capability lives
@@ -58,13 +58,13 @@ function stagedLifecycle() {
58
58
  return file;
59
59
  }
60
60
  /** The press itself, run in a process of its own: the row's own act, whose outcome is read afterwards with act=state. */
61
- const LIFECYCLE_ACTOR = "require(process.argv[1]).row().act(process.argv[2]).then(() => process.exit(0), () => process.exit(1))";
61
+ const LIFECYCLE_ACTOR = "require(process.argv[1]).row(process.argv[2]).act(process.argv[3]).then(() => process.exit(0), () => process.exit(1))";
62
62
  /** A launcher that starts the actor detached and exits at once, so no live parent links the actor to this daemon: the Stop inside a Restart ends this daemon's whole process tree, and an actor still in it would die before it started BN again. */
63
63
  const LIFECYCLE_LAUNCHER = `require("child_process").spawn(process.execPath, ["-e", ${JSON.stringify(LIFECYCLE_ACTOR)}, ...process.argv.slice(1)], { detached: true, stdio: "ignore", windowsHide: true }).unref()`;
64
64
  /** Start, Stop and Restart end or replace the process answering this very call, so they run in a process that outlives it; the outcome is read afterwards with act=state. */
65
65
  function pressLifecycle(file, press) {
66
66
  return new Promise((resolve, reject) => {
67
- const launcher = spawn(process.execPath, ["-e", LIFECYCLE_LAUNCHER, file, press], { stdio: "ignore", windowsHide: true });
67
+ const launcher = spawn(process.execPath, ["-e", LIFECYCLE_LAUNCHER, file, process.argv[1], press], { stdio: "ignore", windowsHide: true });
68
68
  launcher.once("error", (err) => reject(new GatewayError(500, `the ${press} could not be launched — ${err.message}`)));
69
69
  launcher.once("exit", (code) => (code === 0 ? resolve({ pressed: press, running: true, next: "read the outcome with bn_lifecycle act=state" }) : reject(new GatewayError(500, `the ${press} could not be launched — its launcher exited ${code}`))));
70
70
  });
@@ -352,7 +352,7 @@ function buildServer(caller, base, offer) {
352
352
  }));
353
353
  server.tool("bn_lifecycle", "BN's own Start, Stop and Restart as the dashboard row and the panel run them. act=state reads the measured state (running, stopped, unreachable ...) with its words and what a Stop would cut. start, stop and restart are pressed in a process that outlives this call — a Stop or Restart ends the process answering you — and the outcome is read afterwards with act=state; a Stop stays until Start. Restart takes and builds the newest main first, exactly as the row does.", { act: z.enum(["state", "start", "stop", "restart"]) }, ({ act: press }) => panelAct(async () => {
354
354
  const file = stagedLifecycle();
355
- return press === "state" ? createRequire(file)(file).row().state() : pressLifecycle(file, press);
355
+ return press === "state" ? createRequire(file)(file).row(process.argv[1]).state() : pressLifecycle(file, press);
356
356
  }));
357
357
  return server;
358
358
  }
@@ -56,39 +56,24 @@ export const OWNER_RP_ID = sharedDomain(OWNER_ORIGINS);
56
56
  const OWNER_RP_NAME = "Bullseye";
57
57
  // GATE: a lock file nobody can read as a lock (half written, damaged) is taken over once it is this old; a readable lock is only ever taken from a holder that is gone.
58
58
  const OWNER_LOCK_UNREADABLE_MS = 30_000;
59
- // GATE: a change to a file the doors share (the owner registry, a door's session store) waits this long for another process's change to finish, then answers 409 and changes nothing.
59
+ // GATE: a change to the owner registry waits this long for another process's change to finish, then answers 409 and changes nothing.
60
60
  const OWNER_LOCK_WAIT_MS = 5_000;
61
61
  const LOCK_POLL_MS = 25;
62
62
  // GATE: a lock written under a boot that began this much earlier or later than this one belongs to a process of an earlier boot.
63
63
  const OWNER_LOCK_BOOT_TOLERANCE_MS = 120_000;
64
64
  export function readOwnersFile(file) {
65
- return readJsonFile(file, () => ({ userId: randomBytes(16).toString("base64url"), credentials: [], legacyRetired: false }));
66
- }
67
- const errorCode = (err) => err.code;
68
- // GATE: a read that finds a file busy or gone is repeated this many times, this far apart, before the file is taken for absent or the read fails.
69
- const READ_ATTEMPTS = 6;
70
- const READ_RETRY_MS = 25;
71
- const filesRead = new Set();
72
- /** A JSON file another process replaces by a rename, read whole; a file read before that is now busy or absent is read again before it is taken for absent. */
73
- function readJsonFile(file, whenAbsent) {
74
- for (let attempt = 1;; attempt++) {
75
- try {
76
- const parsed = JSON.parse(readFileSync(file, "utf8"));
77
- filesRead.add(file);
78
- return parsed;
79
- }
80
- catch (err) {
81
- const code = errorCode(err);
82
- if (code === "ENOENT" && (!filesRead.has(file) || attempt >= READ_ATTEMPTS))
83
- return whenAbsent();
84
- if (err instanceof SyntaxError)
85
- throw new SyntaxError(`${file} is not valid JSON: ${err.message}`);
86
- if ((code !== "ENOENT" && code !== "EBUSY" && code !== "EPERM" && code !== "EACCES") || attempt >= READ_ATTEMPTS)
87
- throw err;
88
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, READ_RETRY_MS);
89
- }
65
+ if (statSync(file, { throwIfNoEntry: false }) === undefined)
66
+ return { userId: randomBytes(16).toString("base64url"), credentials: [], legacyRetired: false };
67
+ try {
68
+ return JSON.parse(readFileSync(file, "utf8"));
69
+ }
70
+ catch (err) {
71
+ if (!(err instanceof SyntaxError))
72
+ throw err;
73
+ throw new SyntaxError(`the owner registry ${file} is not valid JSON: ${err.message}`);
90
74
  }
91
75
  }
76
+ const errorCode = (err) => err.code;
92
77
  const bootAt = () => Math.round(Date.now() - uptime() * 1000);
93
78
  function removeIfPresent(file) {
94
79
  try {
@@ -188,27 +173,23 @@ function tryLock(lock, mine, token) {
188
173
  * brought back by a stale copy.
189
174
  */
190
175
  export function changeOwners(file, change) {
191
- return changeLocked(file, readOwnersFile, change);
192
- }
193
- /** The one lock-read-change-write step both the owner registry and a door's session store go through. */
194
- function changeLocked(file, read, change) {
195
176
  const lock = `${file}.lock`;
196
177
  const token = randomBytes(8).toString("hex");
197
178
  const mine = JSON.stringify({ pid: process.pid, bootAt: bootAt(), token });
198
179
  const giveUp = Date.now() + OWNER_LOCK_WAIT_MS;
199
180
  while (!tryLock(lock, mine, token)) {
200
181
  if (Date.now() > giveUp)
201
- throw new GatewayError(409, `${file} is being changed by another process — try again`);
182
+ throw new GatewayError(409, "the owner registry is being changed by another process — try again");
202
183
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_POLL_MS);
203
184
  }
204
185
  try {
205
- const store = read(file);
186
+ const store = readOwnersFile(file);
206
187
  const result = change(store);
207
188
  const temp = `${file}.${process.pid}.tmp`;
208
189
  writeFileSync(temp, JSON.stringify(store), { mode: 0o600 });
209
190
  if (readLock(lock) !== mine) {
210
191
  removeIfPresent(temp);
211
- throw new GatewayError(409, `${file} was changed by another process while this change was made — try again`);
192
+ throw new GatewayError(409, "the owner registry was changed by another process while this change was made — try again");
212
193
  }
213
194
  renameSync(temp, file);
214
195
  return result;
@@ -343,37 +324,21 @@ export function createSignInDoor({ storeFile, product, short, home, host: doorHo
343
324
  const pendingAuthenticators = new Map();
344
325
  const strikes = new Map();
345
326
  let textedCode;
346
- const readStoreAt = (file) => readJsonFile(file, () => ({ userId: randomBytes(16).toString("base64url"), passkeys: [], sessions: {} }));
347
- const readStore = () => readStoreAt(storeFile);
348
- /** Changes the store as one step no other process can interleave with, writing it without its expired sessions; a session ends only by expiry, revoke or logout. */
349
- function changeStore(change) {
350
- return changeLocked(storeFile, readStoreAt, (store) => {
351
- const result = change(store);
352
- // NULL-OK: field ownerModel is OPTIONAL and therefore it is ok to check for NULL
353
- if (store.ownerModel !== true && readOwners().legacyRetired)
354
- store.ownerModel = true;
355
- const now = Date.now();
356
- const gone = Object.keys(store.sessions).filter((key) => store.sessions[key].exp <= now);
357
- for (const key of gone)
358
- delete store.sessions[key];
359
- if (gone.length > 0)
360
- process.stderr.write(`[agent-gateway] ${short} ${gone.length} expired session(s) removed from the store
361
- `);
362
- return result;
363
- });
327
+ function readStore() {
328
+ if (!existsSync(storeFile))
329
+ return { userId: randomBytes(16).toString("base64url"), passkeys: [], sessions: {} };
330
+ return JSON.parse(readFileSync(storeFile, "utf8"));
364
331
  }
365
- /** Why a bearer is not a live session, in words; nothing when it is one. */
366
- function refusalOf(secret) {
367
- if (secret === null || secret === "")
368
- return "no session was presented";
369
- const store = readStore();
370
- const session = store.sessions[digest(secret)];
371
- if (session === undefined)
372
- return "no such session (signed out, revoked or never issued)";
373
- if (session.exp <= Date.now())
374
- return `expired at ${new Date(session.exp).toISOString()}`;
375
- const approval = approvalOfCredential(session.credentialId);
376
- return standing(approval, store) ? undefined : `the sign-in it was made with no longer stands (${approval.slice(0, 24)})`;
332
+ /** Writes the store without what can never be used again: expired sessions and sessions whose sign-in no longer stands. */
333
+ function writeStore(store) {
334
+ const now = Date.now();
335
+ for (const [key, session] of Object.entries(store.sessions)) {
336
+ if (session.exp <= now || !standing(approvalOfCredential(session.credentialId), store))
337
+ delete store.sessions[key];
338
+ }
339
+ const temp = `${storeFile}.${process.pid}.tmp`;
340
+ writeFileSync(temp, JSON.stringify(store), { mode: 0o600 });
341
+ renameSync(temp, storeFile);
377
342
  }
378
343
  const readOwners = () => readOwnersFile(ownerFile());
379
344
  // An owner passkey is registered on the owner rpID and signs in to every service the gateway serves on it, so a service added later needs no new registration.
@@ -382,7 +347,11 @@ export function createSignInDoor({ storeFile, product, short, home, host: doorHo
382
347
  function rememberRetirement() {
383
348
  if (!ownsStore)
384
349
  return;
385
- changeStore((store) => { store.ownerModel = true; });
350
+ const store = readStore();
351
+ store.ownerModel = true;
352
+ const temp = `${storeFile}.${process.pid}.tmp`;
353
+ writeFileSync(temp, JSON.stringify(store), { mode: 0o600 });
354
+ renameSync(temp, storeFile);
386
355
  }
387
356
  // NULL-OK: field ownerModel is OPTIONAL and therefore it is ok to check for NULL
388
357
  function legacyRetired(store) {
@@ -431,7 +400,11 @@ export function createSignInDoor({ storeFile, product, short, home, host: doorHo
431
400
  function activeSession(secret) {
432
401
  if (secret === null)
433
402
  return undefined;
434
- return refusalOf(secret) === undefined ? readStore().sessions[digest(secret)] : undefined;
403
+ const store = readStore();
404
+ const session = store.sessions[digest(secret)];
405
+ if (session === undefined || session.exp <= Date.now() || !standing(approvalOfCredential(session.credentialId), store))
406
+ return undefined;
407
+ return session;
435
408
  }
436
409
  const sessionSignIn = (secret) => activeSession(secret)?.credentialId;
437
410
  /** When a live session ends, in epoch milliseconds; otherwise nothing. */
@@ -444,9 +417,12 @@ export function createSignInDoor({ storeFile, product, short, home, host: doorHo
444
417
  * exist yet is written here because the machine's own token reaches the same person without signing in through the door.
445
418
  */
446
419
  function personId() {
447
- if (existsSync(storeFile) || !ownsStore)
448
- return readStore().userId;
449
- return changeStore((store) => store.userId);
420
+ const store = readStore();
421
+ if (existsSync(storeFile))
422
+ return store.userId;
423
+ if (ownsStore)
424
+ writeStore(store);
425
+ return store.userId;
450
426
  }
451
427
  /** What a live session approves an OAuth grant as: `passkey:<id>`, `authenticator:<id>` or `sms`; otherwise nothing. */
452
428
  function sessionApproval(secret) {
@@ -570,9 +546,10 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
570
546
  if (replaces !== undefined)
571
547
  owners.credentials = owners.credentials.filter((c) => c.id !== replaces);
572
548
  });
573
- changeStore((doorStore) => { doorStore.ownerModel = true; });
574
- process.stderr.write(`[agent-gateway] ${short} owner passkey registered from ${caller(req)} (${device})
575
- `);
549
+ const doorStore = readStore();
550
+ doorStore.ownerModel = true;
551
+ writeStore(doorStore);
552
+ process.stderr.write(`[agent-gateway] ${short} owner passkey registered from ${caller(req)} (${device})\n`);
576
553
  return { ok: true };
577
554
  }
578
555
  async function registerOptions(body, base) {
@@ -615,12 +592,12 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
615
592
  throw new GatewayError(401, "passkey sign-in refused: the signature did not verify");
616
593
  if (!ownerCredentials().some((c) => c.id === credential.id))
617
594
  throw new GatewayError(401, "that passkey was removed meanwhile");
618
- return issueSession(credential.id, "owner passkey", (store) => {
619
- // NULL-OK: field ownerCounters is OPTIONAL and therefore it is ok to check for NULL
620
- store.ownerCounters = { ...store.ownerCounters, [credential.id]: result.authenticationInfo.newCounter };
621
- store.ownerModel = true;
622
- delete store.codeMisses;
623
- });
595
+ const store = readStore();
596
+ // NULL-OK: field ownerCounters is OPTIONAL and therefore it is ok to check for NULL
597
+ store.ownerCounters = { ...store.ownerCounters, [credential.id]: result.authenticationInfo.newCounter };
598
+ store.ownerModel = true;
599
+ delete store.codeMisses;
600
+ return issueSession(store, credential.id);
624
601
  }
625
602
  async function loginVerify(body) {
626
603
  const challenge = signedChallenge(body.response);
@@ -637,23 +614,18 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
637
614
  }));
638
615
  if (!result.verified)
639
616
  throw new GatewayError(401, "passkey sign-in refused: the signature did not verify");
640
- return issueSession(passkey.id, "site passkey", (store) => {
641
- const current = store.passkeys.find((p) => p.id === passkey.id);
642
- if (current === undefined)
643
- throw new GatewayError(401, "that passkey was removed meanwhile");
644
- current.counter = result.authenticationInfo.newCounter;
645
- delete store.codeMisses;
646
- });
617
+ const store = readStore();
618
+ const current = store.passkeys.find((p) => p.id === passkey.id);
619
+ if (current === undefined)
620
+ throw new GatewayError(401, "that passkey was removed meanwhile");
621
+ current.counter = result.authenticationInfo.newCounter;
622
+ delete store.codeMisses;
623
+ return issueSession(store, current.id);
647
624
  }
648
- function issueSession(credentialId, how, touch) {
625
+ function issueSession(store, credentialId) {
649
626
  const session = mint();
650
- const key = digest(session);
651
- const exp = Date.now() + SESSION_LIFETIME_MS;
652
- changeStore((store) => {
653
- touch(store);
654
- store.sessions[key] = { credentialId, exp };
655
- });
656
- process.stderr.write(`[agent-gateway] ${short} session ${key.slice(0, SESSION_REF_LENGTH)} issued for ${how}, valid until ${new Date(exp).toISOString()}\n`);
627
+ store.sessions[digest(session)] = { credentialId, exp: Date.now() + SESSION_LIFETIME_MS };
628
+ writeStore(store);
657
629
  return { session, expiresIn: SESSION_LIFETIME_MS / 1000 };
658
630
  }
659
631
  /** Adding an authenticator app needs this machine, or a fingerprint sign-in made just before it on this page. */
@@ -690,17 +662,19 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
690
662
  if (step === undefined)
691
663
  throw new GatewayError(401, "that code does not match — type the code the app shows now");
692
664
  pendingAuthenticators.delete(key);
693
- changeStore((store) => { store.authenticator = { id: mint().slice(0, 16), secret: pending.secret, createdAt: Date.now(), lastStep: step }; });
665
+ const store = readStore();
666
+ store.authenticator = { id: mint().slice(0, 16), secret: pending.secret, createdAt: Date.now(), lastStep: step };
667
+ writeStore(store);
694
668
  process.stderr.write(`[agent-gateway] ${short} authenticator app enrolled from ${from}\n`);
695
669
  return { ok: true };
696
670
  }
697
671
  function authenticatorRemove() {
698
- changeStore((store) => {
699
- // NULL-OK: field authenticator is OPTIONAL and therefore it is ok to check for NULL
700
- if (store.authenticator === undefined)
701
- throw new GatewayError(404, "no authenticator app is enrolled");
702
- delete store.authenticator;
703
- });
672
+ const store = readStore();
673
+ // NULL-OK: field authenticator is OPTIONAL and therefore it is ok to check for NULL
674
+ if (store.authenticator === undefined)
675
+ throw new GatewayError(404, "no authenticator app is enrolled");
676
+ delete store.authenticator;
677
+ writeStore(store);
704
678
  return { ok: true };
705
679
  }
706
680
  function slowedDown(method) {
@@ -709,16 +683,14 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
709
683
  throw new GatewayError(429, `too many wrong codes — try again in ${Math.ceil((strike.until - Date.now()) / 1000)} s`);
710
684
  }
711
685
  /** A wrong code slows its method's next try and counts toward the shut, which is kept in the store so a restart does not reopen it. */
712
- function struck(method, why) {
686
+ function struck(method, why, store) {
713
687
  const count = (strikes.get(method)?.count ?? 0) + 1;
714
688
  strikes.set(method, { count, until: Date.now() + Math.min(1000 * 2 ** (count - 1), MAX_SLOWDOWN_MS) });
715
- const misses = changeStore((store) => {
716
- // NULL-OK: field codeMisses is OPTIONAL and therefore it is ok to check for NULL
717
- store.codeMisses = (store.codeMisses ?? 0) + 1;
718
- return store.codeMisses;
719
- });
720
- if (misses >= CODE_LOCK_MISSES)
721
- process.stderr.write(`[agent-gateway] ${short} code and text sign-in shut after ${misses} wrong codes; a passkey sign-in opens them\n`);
689
+ // NULL-OK: field codeMisses is OPTIONAL and therefore it is ok to check for NULL
690
+ store.codeMisses = (store.codeMisses ?? 0) + 1;
691
+ writeStore(store);
692
+ if (codesShut(store))
693
+ process.stderr.write(`[agent-gateway] ${short} code and text sign-in shut after ${store.codeMisses} wrong codes; a passkey sign-in opens them\n`);
722
694
  return new GatewayError(401, why);
723
695
  }
724
696
  /** Texts a fresh 6-digit code to Meni's mobile; it replaces any earlier one, and only one goes out a minute. */
@@ -760,7 +732,6 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
760
732
  codesOpen(store);
761
733
  slowedDown(method);
762
734
  let credentialId;
763
- let spendStep = () => { };
764
735
  if (method === "authenticator") {
765
736
  const app = store.authenticator;
766
737
  // NULL-OK: field authenticator is OPTIONAL and therefore it is ok to check for NULL
@@ -768,13 +739,8 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
768
739
  throw new GatewayError(401, "no authenticator app is enrolled");
769
740
  const step = matchingStep(app.secret, code, app.lastStep);
770
741
  if (step === undefined)
771
- throw struck(method, "that code is wrong or was already used");
772
- spendStep = (fresh) => {
773
- // NULL-OK: field authenticator is OPTIONAL and therefore it is ok to check for NULL
774
- if (fresh.authenticator === undefined || fresh.authenticator.id !== app.id || fresh.authenticator.lastStep >= step)
775
- throw new GatewayError(401, "that code was already used");
776
- fresh.authenticator.lastStep = step;
777
- };
742
+ throw struck(method, "that code is wrong or was already used", store);
743
+ app.lastStep = step;
778
744
  credentialId = `${AUTHENTICATOR}${app.id}`;
779
745
  }
780
746
  else {
@@ -782,23 +748,21 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
782
748
  if (textedCode === undefined || textedCode.exp <= Date.now())
783
749
  throw new GatewayError(401, "no texted code is waiting — tap Text me a code");
784
750
  if (!secretMatches(digest(code), textedCode.hash))
785
- throw struck(method, "that code is wrong");
751
+ throw struck(method, "that code is wrong", store);
786
752
  textedCode = undefined;
787
753
  credentialId = SMS;
788
754
  }
789
755
  strikes.delete(method);
790
- return issueSession(credentialId, method === "authenticator" ? "authenticator code" : "texted code", (fresh) => {
791
- spendStep(fresh);
792
- delete fresh.codeMisses;
793
- });
756
+ delete store.codeMisses;
757
+ return issueSession(store, credentialId);
794
758
  }
795
759
  function remove(body) {
796
- changeStore((store) => {
797
- const kept = store.passkeys.filter((p) => p.id !== body.id);
798
- if (kept.length === store.passkeys.length)
799
- throw new GatewayError(404, "no passkey has that id");
800
- store.passkeys = kept;
801
- });
760
+ const store = readStore();
761
+ const kept = store.passkeys.filter((p) => p.id !== body.id);
762
+ if (kept.length === store.passkeys.length)
763
+ throw new GatewayError(404, "no passkey has that id");
764
+ store.passkeys = kept;
765
+ writeStore(store);
802
766
  return { ok: true };
803
767
  }
804
768
  /** What an admin page may show of this door: ids, devices and dates, a session only by a reference to its hash — never a key, a secret or a session value. */
@@ -815,16 +779,16 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
815
779
  }
816
780
  /** Revokes one session by its reference, or every session when none is given; the next request carrying it is refused. Returns how many went. */
817
781
  function revokeSessions(ref) {
818
- const removed = changeStore((store) => {
819
- const keys = Object.keys(store.sessions).filter((key) => ref === undefined || key.startsWith(ref));
820
- if (ref !== undefined && (ref.length < SESSION_REF_LENGTH || keys.length !== 1))
821
- throw new GatewayError(404, "no single session has that reference");
822
- for (const key of keys)
823
- delete store.sessions[key];
824
- return keys.length;
825
- });
826
- process.stderr.write(`[agent-gateway] ${short} ${removed} session(s) revoked by the admin (${ref === undefined ? "all" : ref})\n`);
827
- return removed;
782
+ const store = readStore();
783
+ const keys = Object.keys(store.sessions).filter((key) => ref === undefined || key.startsWith(ref));
784
+ if (ref !== undefined && (ref.length < SESSION_REF_LENGTH || keys.length !== 1))
785
+ throw new GatewayError(404, "no single session has that reference");
786
+ if (keys.length === 0)
787
+ return 0;
788
+ for (const key of keys)
789
+ delete store.sessions[key];
790
+ writeStore(store);
791
+ return keys.length;
828
792
  }
829
793
  /** Removes a passkey; the last sign-in a service has needs `confirmLast`, because without it the service refuses everyone from outside until an owner passkey is registered. */
830
794
  function removePasskey(id, confirmLast) {
@@ -913,10 +877,8 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
913
877
  send(res, 200, { expiresIn: Math.max(0, Math.ceil((session.exp - Date.now()) / 1000)), expiresAt: session.exp });
914
878
  else if (bearerAdmitted(req, gatewayToken))
915
879
  send(res, 200, { expiresIn: null });
916
- else {
917
- process.stderr.write(`[agent-gateway] ${short} session check refused from ${caller(req)}: ${refusalOf(bearer(req))}\n`);
880
+ else
918
881
  send(res, 401, { error: "sign-in expired or signed out" });
919
- }
920
882
  return;
921
883
  }
922
884
  if (method !== "POST")
@@ -933,10 +895,12 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
933
895
  else if (path === `${PASSKEY_PREFIX}login/verify`)
934
896
  send(res, 200, await loginVerify(body));
935
897
  else if (path === `${PASSKEY_PREFIX}logout`) {
898
+ const store = readStore();
936
899
  const key = digest(bearer(req));
937
- const signedOut = changeStore((store) => key in store.sessions && delete store.sessions[key]);
938
- if (signedOut)
939
- process.stderr.write(`[agent-gateway] ${short} session ${key.slice(0, SESSION_REF_LENGTH)} removed: signed out\n`);
900
+ if (key in store.sessions) {
901
+ delete store.sessions[key];
902
+ writeStore(store);
903
+ }
940
904
  send(res, 200, { ok: true });
941
905
  }
942
906
  else if (path === `${PASSKEY_PREFIX}code/verify`)
@@ -963,10 +927,8 @@ ${locked(store) ? "" : `<p class="mut">Until an owner passkey is registered, not
963
927
  throw new GatewayError(404, "unknown route");
964
928
  }
965
929
  const admin = { view: adminView, act: adminAct };
966
- /** Why the request's bearer is no live session, in words; nothing when it is one or none was presented. */
967
- const refusalOfRequest = (req) => (bearer(req) === "" ? undefined : refusalOf(bearer(req)));
968
- return { handlePasskey, admin, refusalOfRequest, bearerAdmitted, sessionSignIn, sessionExpiresAt, personId, sessionApproval, approvalStands, signInEnrolled, tokenStands, doorState };
930
+ return { handlePasskey, admin, bearerAdmitted, sessionSignIn, sessionExpiresAt, personId, sessionApproval, approvalStands, signInEnrolled, tokenStands, doorState };
969
931
  }
970
932
  /** BN's own door: its store is `agent-passkeys.json` beside BN's config. */
971
933
  const bn = createSignInDoor({ storeFile: join(CONFIG_DIR, "agent-passkeys.json"), product: "BullseyeNotify", short: "BN", home: "Open BN chat", host: gatewaySettings?.host ?? "bn.bullseyecalc.com", ownerFile: () => join(CONFIG_DIR, "owner-passkeys.json"), ownsStore: process.env.NOTIFY_MCP_DOOR_READONLY !== "1" });
972
- export const { handlePasskey, admin, refusalOfRequest, bearerAdmitted, sessionSignIn, sessionExpiresAt, personId, sessionApproval, approvalStands, signInEnrolled, tokenStands, doorState } = bn;
934
+ export const { handlePasskey, admin, bearerAdmitted, sessionSignIn, sessionExpiresAt, personId, sessionApproval, approvalStands, signInEnrolled, tokenStands, doorState } = bn;
@@ -14,7 +14,7 @@ import { CHAT_HEADERS } from "./chatPage.js";
14
14
  import { isIconPath, serveIcon } from "./iconDoor.js";
15
15
  import { handleMcp } from "./mcpDoor.js";
16
16
  import { MCP_PATH, accessGranted, challenge, handleOAuth, isOAuthPath, publicBase } from "./oauthDoor.js";
17
- import { bearer, bearerAdmitted, fromThisMachine, handlePasskey, isPasskeyPath, localOnly, refusalOfRequest } from "./passkeyDoor.js";
17
+ import { bearer, bearerAdmitted, fromThisMachine, handlePasskey, isPasskeyPath, localOnly } from "./passkeyDoor.js";
18
18
  import { terminalConsole, terminalRoute, terminalSockets } from "./terminalDoor.js";
19
19
  import { conversationSwitchRead, panelState, saveConversationSwitch, saveSetting } from "./panel.js";
20
20
  import { PANEL_PAGES, panelHtml } from "./panelPage.js";
@@ -255,13 +255,8 @@ export function startRestDoor(settings) {
255
255
  await serveMcp(req, res, settings.token);
256
256
  return;
257
257
  }
258
- if (!bearerAdmitted(req, settings.token)) {
259
- const why = refusalOfRequest(req);
260
- if (why !== undefined)
261
- process.stderr.write(`[agent-gateway] ${req.method} ${url.pathname} refused a session: ${why}
262
- `);
258
+ if (!bearerAdmitted(req, settings.token))
263
259
  throw new GatewayError(401, `${BAD_TOKEN_ERROR}, or the gateway token used from outside this machine (it works on this machine only — sign in with the owner passkey)`);
264
- }
265
260
  // The conversation's own CLI output (#3434, #3916): the SAME CLI the browser shows, streamed to an MCP/REST caller.
266
261
  if (req.method === "GET" && url.pathname.startsWith("/v1/terminals/") && url.pathname.endsWith("/console")) {
267
262
  await terminalConsole(req, res, url);