@cortexkit/common-auth 0.11.1 → 0.11.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.
@@ -87,6 +87,12 @@ export interface ClaustrumScopedAttempt {
87
87
  * in from the roster or from a token parse.
88
88
  */
89
89
  readonly assertedAccountIdentity?: string;
90
+ /**
91
+ * The non-secret Google Cloud project id the vault served in get_scoped for
92
+ * this attempt, if any. Never filled in from list_scoped, the roster or a
93
+ * token parse. A project change in the vault takes effect on the next send.
94
+ */
95
+ readonly projectId?: string;
90
96
  /**
91
97
  * Kept in memory only and hidden from JSON.stringify and object spreads, so
92
98
  * logging a receipt never leaks it. Authorize again for every dispatch and retry.
@@ -298,6 +298,9 @@ export class ClaustrumScopedCustody {
298
298
  ...(assertedIdentity !== undefined && {
299
299
  assertedAccountIdentity: assertedIdentity,
300
300
  }),
301
+ ...(served.projectId !== undefined && {
302
+ projectId: served.projectId,
303
+ }),
301
304
  recordVersion: served.recordVersion,
302
305
  expiresAtMs,
303
306
  }, 'accessToken', { value: accessToken, enumerable: false }));
@@ -2,7 +2,9 @@
2
2
  * Why an OpenCode 2 auth hook refused a request.
3
3
  *
4
4
  * - `no-account`: the adapter had no account to offer for this request, so
5
- * the request is stopped before the host picks a transport.
5
+ * the request is stopped before the host picks a transport. Also used when
6
+ * session forgetting or installation disposal revokes an in-flight auth
7
+ * selection: that selection no longer has an account it may send under.
6
8
  * - `host-credential-on-wire`: after every rewrite, a header still carried
7
9
  * one of the host's placeholder credentials. Sending it would leak a
8
10
  * non-routable value to the provider and fail with a confusing error.
@@ -129,6 +129,9 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
129
129
  let warnedUnmarkedSend = false;
130
130
  const listeners = new Map();
131
131
  let seq = 0;
132
+ let disposed = false;
133
+ /** Only active hook calls are held; forgetting never leaves a session tombstone. */
134
+ const inFlight = new Map();
132
135
  const warn = (message, data) => {
133
136
  try {
134
137
  logger?.warn(message, data);
@@ -200,12 +203,47 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
200
203
  const accountOf = (rec) => rec.accountId === undefined
201
204
  ? undefined
202
205
  : { ...rec.scope, accountId: rec.accountId };
203
- const noAccount = (scope) => new OpenCode2AuthError({
206
+ const noAccount = (scope, message) => new OpenCode2AuthError({
204
207
  kind: 'no-account',
205
208
  providerID,
206
209
  sessionID: scope.sessionID,
207
210
  requestKind: scope.kind,
211
+ ...(message === undefined ? {} : { message }),
208
212
  });
213
+ const revokeSelections = (sessionID) => {
214
+ inFlight.get(sessionID)?.clear();
215
+ inFlight.delete(sessionID);
216
+ };
217
+ /**
218
+ * Owns selection through its transport handoff, not just the adapter calls.
219
+ * Deleting a session's set revokes its old calls without poisoning reuse of
220
+ * that id. Each await must recheck before calling the adapter or publishing.
221
+ */
222
+ const withSelection = async (scope, run) => {
223
+ const revoked = () => noAccount(scope, `${providerID} ${scope.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);
224
+ if (disposed)
225
+ throw revoked();
226
+ let selections = inFlight.get(scope.sessionID);
227
+ if (!selections) {
228
+ selections = new Set();
229
+ inFlight.set(scope.sessionID, selections);
230
+ }
231
+ const token = {};
232
+ selections.add(token);
233
+ const assertActive = () => {
234
+ if (!selections.has(token))
235
+ throw revoked();
236
+ };
237
+ try {
238
+ return await run(assertActive);
239
+ }
240
+ finally {
241
+ selections.delete(token);
242
+ // An old call may settle after a new call has reused the session id.
243
+ if (selections.size === 0 && inFlight.get(scope.sessionID) === selections)
244
+ inFlight.delete(scope.sessionID);
245
+ }
246
+ };
209
247
  const guard = (scope, headers) => {
210
248
  for (const [name, value] of headers) {
211
249
  if (forbidden.some((secret) => value.includes(secret))) {
@@ -240,7 +278,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
240
278
  }
241
279
  }
242
280
  };
243
- const select = async (scope, hook, transport) => {
281
+ const select = async (scope, hook, assertActive, transport) => {
244
282
  const key = keyOf(scope.sessionID, scope.kind);
245
283
  const retried = pendingRetries.get(key);
246
284
  pendingRetries.delete(key);
@@ -254,10 +292,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
254
292
  : { rerouteFrom: retried.rerouteFrom }),
255
293
  };
256
294
  const accountId = await adapter.chooseAccount(input);
295
+ assertActive();
257
296
  let headers = {};
258
297
  let data;
259
298
  if (accountId !== undefined) {
260
299
  const result = await adapter.accountHeaders({ ...scope, accountId });
300
+ assertActive();
261
301
  if (isHeadersResult(result)) {
262
302
  headers = result.headers;
263
303
  data = result.attempt;
@@ -306,7 +346,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
306
346
  // of the attempt it started. Choosing here too keeps a request that skipped
307
347
  // it from going out under the host credential, and a second send of the
308
348
  // same attempt from reusing the first send's attempt.
309
- const bind = async (scope, hook, transport, mark) => {
349
+ const bind = async (scope, hook, transport, mark, assertActive) => {
310
350
  const key = keyOf(scope.sessionID, scope.kind);
311
351
  let rec = mark === undefined ? undefined : attempts.get(mark);
312
352
  if (rec?.key !== key)
@@ -322,7 +362,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
322
362
  }
323
363
  }
324
364
  if (!rec || rec.transport !== undefined || rec.ended)
325
- rec = await select(scope, hook, transport);
365
+ rec = await select(scope, hook, assertActive, transport);
326
366
  else {
327
367
  rec.transport = transport;
328
368
  if (rec.attempt)
@@ -443,18 +483,20 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
443
483
  };
444
484
  const scoped = { providerID };
445
485
  const registrations = [];
446
- registrations.push(await ctx.session.hook('model.request', async (draft) => {
447
- const rec = await select(scopeOf(draft), 'model.request');
486
+ registrations.push(await ctx.session.hook('model.request', (draft) => withSelection(scopeOf(draft), async (assertActive) => {
487
+ const rec = await select(scopeOf(draft), 'model.request', assertActive);
488
+ assertActive();
448
489
  if (rec.accountId === undefined)
449
490
  throw noAccount(rec.scope);
450
491
  applyHeaderEdits(draft.headers, {
451
492
  ...rec.headers,
452
493
  [ATTEMPT_HEADER]: rec.id,
453
494
  });
454
- }, scoped));
455
- registrations.push(await ctx.session.hook('http.request', async (draft) => {
495
+ }), scoped));
496
+ registrations.push(await ctx.session.hook('http.request', (draft) => withSelection(scopeOf(draft), async (assertActive) => {
456
497
  const mark = draft.request.headers.get(ATTEMPT_HEADER) ?? undefined;
457
- const rec = await bind(scopeOf(draft), 'http.request', 'http', mark);
498
+ const rec = await bind(scopeOf(draft), 'http.request', 'http', mark, assertActive);
499
+ assertActive();
458
500
  const account = accountOf(rec);
459
501
  const attempt = rec.attempt;
460
502
  if (!account || !attempt)
@@ -475,6 +517,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
475
517
  request,
476
518
  attempt,
477
519
  })) ?? request;
520
+ assertActive();
478
521
  }
479
522
  const headers = new Headers(request.headers);
480
523
  headers.delete(ATTEMPT_HEADER);
@@ -484,7 +527,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
484
527
  byRequest.set(final, rec);
485
528
  draft.request = final;
486
529
  });
487
- }, scoped));
530
+ }), scoped));
488
531
  registrations.push(await ctx.session.hook('http.response', async (draft) => {
489
532
  const rec = byRequest.get(draft.request);
490
533
  if (!rec) {
@@ -554,7 +597,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
554
597
  if (response !== original)
555
598
  draft.response = response;
556
599
  }, scoped));
557
- registrations.push(await ctx.session.hook('experimental.ws.handshake', async (draft) => {
600
+ registrations.push(await ctx.session.hook('experimental.ws.handshake', (draft) => withSelection(scopeOf(draft), async (assertActive) => {
558
601
  let mark;
559
602
  for (const name of Object.keys(draft.headers)) {
560
603
  if (name.toLowerCase() !== ATTEMPT_HEADER)
@@ -562,7 +605,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
562
605
  mark ??= draft.headers[name];
563
606
  delete draft.headers[name];
564
607
  }
565
- const rec = await bind(scopeOf(draft), 'experimental.ws.handshake', 'ws', mark);
608
+ const rec = await bind(scopeOf(draft), 'experimental.ws.handshake', 'ws', mark, assertActive);
609
+ assertActive();
566
610
  const account = accountOf(rec);
567
611
  const attempt = rec.attempt;
568
612
  if (!account || !attempt)
@@ -578,7 +622,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
578
622
  draft.url = url;
579
623
  guard(rec.scope, Object.entries(draft.headers));
580
624
  });
581
- }, scoped));
625
+ }), scoped));
582
626
  const rewriteFrame = adapter.rewriteWebSocketFrame?.bind(adapter);
583
627
  if (rewriteFrame) {
584
628
  registrations.push(await ctx.session.hook('experimental.ws.send', async (draft) => {
@@ -624,68 +668,79 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
624
668
  return;
625
669
  }
626
670
  const rec = picked;
627
- rec.judged = true;
628
- let decision = hostDecision;
629
- let reason;
630
- let rerouteFrom;
631
- const attempt = rec.attempt;
632
- if (rec.accountId === undefined || !attempt) {
633
- decision = { retry: false };
634
- reason = 'no-account';
635
- }
636
- else if (rec.outputStarted) {
637
- // The user has already seen part of this answer; a retry would
638
- // send it again.
639
- decision = { retry: false };
640
- reason = 'output-started';
641
- }
642
- else {
643
- if (!rec.limit) {
644
- const signal = adapter.limitFromError?.(draft.error, attempt);
645
- if (signal)
646
- noteLimit(rec, signal, 'error');
671
+ await withSelection(rec.scope, async (assertActive) => {
672
+ rec.judged = true;
673
+ let decision = hostDecision;
674
+ let reason;
675
+ let rerouteFrom;
676
+ const attempt = rec.attempt;
677
+ if (rec.accountId === undefined || !attempt) {
678
+ decision = { retry: false };
679
+ reason = 'no-account';
647
680
  }
648
- // The next `chooseAccount` should see whatever the plugin learnt
649
- // from how this attempt ended.
650
- if (rec.ended)
651
- await rec.ended;
652
- if (rec.limit) {
653
- await rec.limit.delivered;
654
- rec.rerouted = true;
655
- rerouteFrom = { accountId: rec.accountId, limit: rec.limit.signal };
656
- // No delay: the next attempt goes to another account, and the
657
- // host would otherwise wait out the refused account's backoff,
658
- // or not retry at all for errors it deems final.
659
- decision = { retry: true, delay: 0 };
660
- reason = 'reroute';
681
+ else if (rec.outputStarted) {
682
+ // The user has already seen part of this answer; a retry would
683
+ // send it again.
684
+ decision = { retry: false };
685
+ reason = 'output-started';
661
686
  }
662
687
  else {
663
- reason = 'host-decides';
688
+ if (!rec.limit) {
689
+ const signal = adapter.limitFromError?.(draft.error, attempt);
690
+ if (signal)
691
+ noteLimit(rec, signal, 'error');
692
+ }
693
+ // The next `chooseAccount` should see whatever the plugin learnt
694
+ // from how this attempt ended.
695
+ if (rec.ended) {
696
+ await rec.ended;
697
+ assertActive();
698
+ }
699
+ if (rec.limit) {
700
+ await rec.limit.delivered;
701
+ assertActive();
702
+ rec.rerouted = true;
703
+ rerouteFrom = {
704
+ accountId: rec.accountId,
705
+ limit: rec.limit.signal,
706
+ };
707
+ // No delay: the next attempt goes to another account, and the
708
+ // host would otherwise wait out the refused account's backoff,
709
+ // or not retry at all for errors it deems final.
710
+ decision = { retry: true, delay: 0 };
711
+ reason = 'reroute';
712
+ }
713
+ else {
714
+ reason = 'host-decides';
715
+ }
664
716
  }
665
- }
666
- draft.decision = decision;
667
- // The host's retry runs `model.request` again for this attempt's
668
- // session and kind; that next attempt, and no other attempt of the
669
- // session, is told what this one ended with.
670
- if (decision.retry && rec.accountId !== undefined) {
671
- pendingRetries.set(rec.key, {
672
- sessionID: rec.scope.sessionID,
673
- accountId: rec.accountId,
674
- ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
717
+ draft.decision = decision;
718
+ // The host's retry runs `model.request` again for this attempt's
719
+ // session and kind; that next attempt, and no other attempt of the
720
+ // session, is told what this one ended with.
721
+ if (decision.retry && rec.accountId !== undefined) {
722
+ pendingRetries.set(rec.key, {
723
+ sessionID: rec.scope.sessionID,
724
+ accountId: rec.accountId,
725
+ ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
726
+ });
727
+ }
728
+ await emit('retry', {
729
+ sessionID: draft.sessionID,
730
+ ...(rec.accountId === undefined
731
+ ? {}
732
+ : { accountId: rec.accountId }),
733
+ kind: rec.scope.kind,
734
+ attempt: draft.attempt,
735
+ reason,
736
+ hostDecision,
737
+ decision,
738
+ ...(attempt === undefined ? {} : { handle: attempt }),
675
739
  });
676
- }
677
- await emit('retry', {
678
- sessionID: draft.sessionID,
679
- ...(rec.accountId === undefined ? {} : { accountId: rec.accountId }),
680
- kind: rec.scope.kind,
681
- attempt: draft.attempt,
682
- reason,
683
- hostDecision,
684
- decision,
685
- ...(attempt === undefined ? {} : { handle: attempt }),
686
740
  });
687
741
  }, scoped));
688
742
  const forgetSession = (sessionID) => {
743
+ revokeSelections(sessionID);
689
744
  for (const rec of [...attempts.values()]) {
690
745
  if (rec.scope.sessionID !== sessionID)
691
746
  continue;
@@ -716,7 +771,6 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
716
771
  }
717
772
  })();
718
773
  }
719
- let disposed = false;
720
774
  return {
721
775
  on(event, listener) {
722
776
  let set = listeners.get(event);
@@ -741,6 +795,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
741
795
  if (disposed)
742
796
  return;
743
797
  disposed = true;
798
+ for (const sessionID of inFlight.keys())
799
+ revokeSelections(sessionID);
744
800
  abort.abort();
745
801
  for (const rec of attempts.values())
746
802
  abandon(rec, 'the installation was disposed');
@@ -381,10 +381,13 @@ export interface OpenCode2AuthInstallation<Q, A = unknown> {
381
381
  * handle.
382
382
  */
383
383
  accountFor(sessionID: string, kind: RequestKind): string | undefined;
384
- /** Drops every attempt of a session. Session deletion does this itself. */
384
+ /**
385
+ * Drops every attempt and revokes in-flight auth selections of a session.
386
+ * Session deletion does this itself. Later requests may reuse the session id.
387
+ */
385
388
  forgetSession(sessionID: string): void;
386
389
  /** Number of attempts held. */
387
390
  readonly size: number;
388
- /** Removes every hook and stops listening for session deletion. */
391
+ /** Removes every hook, revokes in-flight auth and stops listening for session deletion. */
389
392
  dispose(): Promise<void>;
390
393
  }
@@ -293,10 +293,10 @@ export async function startRpcServer(options) {
293
293
  token,
294
294
  async stop() {
295
295
  await new Promise((resolve) => {
296
- server.close(() => resolve());
297
- // Stop accepting connections before ending requests that may never finish.
296
+ // Bun's close() disables closeAllConnections(), and a peer sending
297
+ // incomplete headers may not have reached the tracked connection set.
298
298
  server.closeAllConnections?.();
299
- // Bun exposes closeAllConnections but leaves partial requests open.
299
+ server.close(() => resolve());
300
300
  for (const socket of connections)
301
301
  socket.destroy();
302
302
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.11.1",
3
+ "version": "0.11.2",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {