@cortexkit/common-auth 0.11.7 → 0.11.8

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.
@@ -43,5 +43,13 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
43
43
  * WebSocket: the host runs one exchange at a time on a session's socket.
44
44
  * Anything else is attributed to no attempt and reaches no adapter callback
45
45
  * or listener.
46
+ *
47
+ * With `gateOnPlaceholder`, `model.request` is a no-op. Each transport hook
48
+ * compares the host-prepared secret exactly, then selects a fresh attempt only
49
+ * for an owned send. Request-object attribution therefore needs no attempt
50
+ * header. Frames are owned by the latest handshake of their session and kind;
51
+ * retry runs only when the session's latest transport was owned. The host's
52
+ * retry hook has no request identity, so concurrent mixed-ownership calls
53
+ * cannot be distinguished there; owned retries retain the heuristic above.
46
54
  */
47
55
  export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
@@ -114,17 +114,37 @@ function applyHeaderEditsTo(target, edits) {
114
114
  * WebSocket: the host runs one exchange at a time on a session's socket.
115
115
  * Anything else is attributed to no attempt and reaches no adapter callback
116
116
  * or listener.
117
+ *
118
+ * With `gateOnPlaceholder`, `model.request` is a no-op. Each transport hook
119
+ * compares the host-prepared secret exactly, then selects a fresh attempt only
120
+ * for an owned send. Request-object attribution therefore needs no attempt
121
+ * header. Frames are owned by the latest handshake of their session and kind;
122
+ * retry runs only when the session's latest transport was owned. The host's
123
+ * retry hook has no request identity, so concurrent mixed-ownership calls
124
+ * cannot be distinguished there; owned retries retain the heuristic above.
117
125
  */
118
126
  export async function installOpenCode2Auth(ctx, adapter, options = {}) {
119
127
  const { providerID } = adapter;
128
+ const ownership = options.gateOnPlaceholder;
129
+ const owns = (headers) => ownership === undefined ||
130
+ ownership.credential(headers) === placeholderSecret(providerID);
120
131
  const logger = options.logger;
121
132
  const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
122
- const forbidden = (options.hostCredentials ?? [placeholderSecret(providerID)]).filter((value) => value !== '');
133
+ const forbidden = [
134
+ ...(options.hostCredentials ?? [placeholderSecret(providerID)]),
135
+ // An owned request must replace its placeholder even if a caller customizes
136
+ // the list of other host credentials forbidden on the wire.
137
+ ...(ownership ? [placeholderSecret(providerID)] : []),
138
+ ].filter((value) => value !== '');
123
139
  /** Every attempt still held, oldest first. */
124
140
  const attempts = new Map();
125
141
  const byRequest = new WeakMap();
126
142
  /** Retries the retry hook asked for, by `sessionID:kind`. */
127
143
  const pendingRetries = new Map();
144
+ // The host names only session/kind for frames and only session for retry.
145
+ // A transport's prepared credential, never global login state, owns these.
146
+ const ownedSockets = new Set();
147
+ const latestTransportOwned = new Map();
128
148
  let warnedUnprovenResponse = false;
129
149
  let warnedUnmarkedSend = false;
130
150
  const listeners = new Map();
@@ -483,54 +503,72 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
483
503
  };
484
504
  const scoped = { providerID };
485
505
  const registrations = [];
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();
489
- if (rec.accountId === undefined)
490
- throw noAccount(rec.scope);
491
- applyHeaderEdits(draft.headers, {
492
- ...rec.headers,
493
- [ATTEMPT_HEADER]: rec.id,
506
+ registrations.push(await ctx.session.hook('model.request', (draft) => {
507
+ if (ownership)
508
+ return;
509
+ return withSelection(scopeOf(draft), async (assertActive) => {
510
+ const rec = await select(scopeOf(draft), 'model.request', assertActive);
511
+ assertActive();
512
+ if (rec.accountId === undefined)
513
+ throw noAccount(rec.scope);
514
+ applyHeaderEdits(draft.headers, {
515
+ ...rec.headers,
516
+ [ATTEMPT_HEADER]: rec.id,
517
+ });
494
518
  });
495
- }), scoped));
496
- registrations.push(await ctx.session.hook('http.request', (draft) => withSelection(scopeOf(draft), async (assertActive) => {
497
- const mark = draft.request.headers.get(ATTEMPT_HEADER) ?? undefined;
498
- const rec = await bind(scopeOf(draft), 'http.request', 'http', mark, assertActive);
499
- assertActive();
500
- const account = accountOf(rec);
501
- const attempt = rec.attempt;
502
- if (!account || !attempt)
503
- throw noAccount(rec.scope);
504
- await failing(rec, async () => {
505
- let request = draft.request;
506
- if (adapter.rewriteRequest) {
507
- if (mark !== undefined) {
508
- // The mark is the installer's own; the adapter's rewrite never
509
- // sees it.
510
- const unmarked = new Headers(request.headers);
511
- unmarked.delete(ATTEMPT_HEADER);
512
- request = new Request(request, { headers: unmarked });
519
+ }, scoped));
520
+ registrations.push(await ctx.session.hook('http.request', (draft) => {
521
+ if (ownership) {
522
+ const owned = owns(draft.request.headers);
523
+ latestTransportOwned.set(draft.sessionID, owned);
524
+ if (!owned)
525
+ return;
526
+ }
527
+ return withSelection(scopeOf(draft), async (assertActive) => {
528
+ const mark = draft.request.headers.get(ATTEMPT_HEADER) ?? undefined;
529
+ // With gateOnPlaceholder, each owned transport call creates its own
530
+ // attempt. No ATTEMPT_HEADER is needed to link it to model.request.
531
+ const rec = ownership
532
+ ? await select(scopeOf(draft), 'http.request', assertActive, 'http')
533
+ : await bind(scopeOf(draft), 'http.request', 'http', mark, assertActive);
534
+ assertActive();
535
+ const account = accountOf(rec);
536
+ const attempt = rec.attempt;
537
+ if (!account || !attempt)
538
+ throw noAccount(rec.scope);
539
+ await failing(rec, async () => {
540
+ let request = draft.request;
541
+ if (adapter.rewriteRequest) {
542
+ if (mark !== undefined) {
543
+ // The mark is the installer's own; the adapter's rewrite never
544
+ // sees it.
545
+ const unmarked = new Headers(request.headers);
546
+ unmarked.delete(ATTEMPT_HEADER);
547
+ request = new Request(request, { headers: unmarked });
548
+ }
549
+ request =
550
+ (await adapter.rewriteRequest({
551
+ ...account,
552
+ request,
553
+ attempt,
554
+ })) ?? request;
555
+ assertActive();
513
556
  }
514
- request =
515
- (await adapter.rewriteRequest({
516
- ...account,
517
- request,
518
- attempt,
519
- })) ?? request;
520
- assertActive();
521
- }
522
- const headers = new Headers(request.headers);
523
- headers.delete(ATTEMPT_HEADER);
524
- applyHeaderEditsTo(headers, rec.headers);
525
- guard(rec.scope, headers.entries());
526
- const final = new Request(request, { headers });
527
- byRequest.set(final, rec);
528
- draft.request = final;
557
+ const headers = new Headers(request.headers);
558
+ headers.delete(ATTEMPT_HEADER);
559
+ applyHeaderEditsTo(headers, rec.headers);
560
+ guard(rec.scope, headers.entries());
561
+ const final = new Request(request, { headers });
562
+ byRequest.set(final, rec);
563
+ draft.request = final;
564
+ });
529
565
  });
530
- }), scoped));
566
+ }, scoped));
531
567
  registrations.push(await ctx.session.hook('http.response', async (draft) => {
532
568
  const rec = byRequest.get(draft.request);
533
569
  if (!rec) {
570
+ if (ownership)
571
+ return;
534
572
  if (!warnedUnprovenResponse) {
535
573
  warnedUnprovenResponse = true;
536
574
  warn('opencode2 auth dropped an http.response whose request it did not produce', { sessionID: draft.sessionID, kind: draft.kind });
@@ -597,36 +635,55 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
597
635
  if (response !== original)
598
636
  draft.response = response;
599
637
  }, scoped));
600
- registrations.push(await ctx.session.hook('experimental.ws.handshake', (draft) => withSelection(scopeOf(draft), async (assertActive) => {
601
- let mark;
602
- for (const name of Object.keys(draft.headers)) {
603
- if (name.toLowerCase() !== ATTEMPT_HEADER)
604
- continue;
605
- mark ??= draft.headers[name];
606
- delete draft.headers[name];
638
+ registrations.push(await ctx.session.hook('experimental.ws.handshake', (draft) => {
639
+ if (ownership) {
640
+ const owned = owns(new Headers(draft.headers));
641
+ const key = keyOf(draft.sessionID, draft.kind);
642
+ latestTransportOwned.set(draft.sessionID, owned);
643
+ // Clear the previous handshake's ownership before selecting: if no
644
+ // account can serve, subsequent frames must not use the old attempt.
645
+ ownedSockets.delete(key);
646
+ if (!owned)
647
+ return;
607
648
  }
608
- const rec = await bind(scopeOf(draft), 'experimental.ws.handshake', 'ws', mark, assertActive);
609
- assertActive();
610
- const account = accountOf(rec);
611
- const attempt = rec.attempt;
612
- if (!account || !attempt)
613
- throw noAccount(rec.scope);
614
- await failing(rec, async () => {
615
- applyHeaderEdits(draft.headers, rec.headers);
616
- const url = adapter.rewriteHandshakeURL?.({
617
- ...account,
618
- url: draft.url,
619
- attempt,
649
+ return withSelection(scopeOf(draft), async (assertActive) => {
650
+ let mark;
651
+ for (const name of Object.keys(draft.headers)) {
652
+ if (name.toLowerCase() !== ATTEMPT_HEADER)
653
+ continue;
654
+ mark ??= draft.headers[name];
655
+ delete draft.headers[name];
656
+ }
657
+ const rec = ownership
658
+ ? await select(scopeOf(draft), 'experimental.ws.handshake', assertActive, 'ws')
659
+ : await bind(scopeOf(draft), 'experimental.ws.handshake', 'ws', mark, assertActive);
660
+ assertActive();
661
+ const account = accountOf(rec);
662
+ const attempt = rec.attempt;
663
+ if (!account || !attempt)
664
+ throw noAccount(rec.scope);
665
+ await failing(rec, async () => {
666
+ applyHeaderEdits(draft.headers, rec.headers);
667
+ const url = adapter.rewriteHandshakeURL?.({
668
+ ...account,
669
+ url: draft.url,
670
+ attempt,
671
+ });
672
+ if (url !== undefined)
673
+ draft.url = url;
674
+ guard(rec.scope, Object.entries(draft.headers));
675
+ if (ownership)
676
+ ownedSockets.add(rec.key);
620
677
  });
621
- if (url !== undefined)
622
- draft.url = url;
623
- guard(rec.scope, Object.entries(draft.headers));
624
678
  });
625
- }), scoped));
679
+ }, scoped));
626
680
  const rewriteFrame = adapter.rewriteWebSocketFrame?.bind(adapter);
627
681
  if (rewriteFrame) {
628
682
  registrations.push(await ctx.session.hook('experimental.ws.send', async (draft) => {
629
683
  const scope = scopeOf(draft);
684
+ if (ownership &&
685
+ !ownedSockets.has(keyOf(scope.sessionID, scope.kind)))
686
+ return;
630
687
  const rec = liveOnSocket(scope.sessionID, scope.kind);
631
688
  const frame = await rewriteFrame({
632
689
  ...scope,
@@ -638,6 +695,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
638
695
  }, scoped));
639
696
  }
640
697
  registrations.push(await ctx.session.hook('experimental.ws.receive', (draft) => {
698
+ if (ownership && !ownedSockets.has(keyOf(draft.sessionID, draft.kind)))
699
+ return;
641
700
  const rec = liveOnSocket(draft.sessionID, draft.kind);
642
701
  if (!rec)
643
702
  return;
@@ -651,6 +710,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
651
710
  }
652
711
  }, scoped));
653
712
  registrations.push(await ctx.session.hook('retry', async (draft) => {
713
+ if (ownership && latestTransportOwned.get(draft.sessionID) !== true)
714
+ return;
654
715
  const picked = pickForRetry(draft.sessionID);
655
716
  if (!picked)
656
717
  return;
@@ -741,6 +802,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
741
802
  }, scoped));
742
803
  const forgetSession = (sessionID) => {
743
804
  revokeSelections(sessionID);
805
+ latestTransportOwned.delete(sessionID);
806
+ for (const key of ownedSockets) {
807
+ if (JSON.parse(key)[0] === sessionID)
808
+ ownedSockets.delete(key);
809
+ }
744
810
  for (const rec of [...attempts.values()]) {
745
811
  if (rec.scope.sessionID !== sessionID)
746
812
  continue;
@@ -802,6 +868,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
802
868
  abandon(rec, 'the installation was disposed');
803
869
  attempts.clear();
804
870
  pendingRetries.clear();
871
+ ownedSockets.clear();
872
+ latestTransportOwned.clear();
805
873
  listeners.clear();
806
874
  await Promise.all(registrations.map(async (registration) => {
807
875
  try {
@@ -175,7 +175,9 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
175
175
  * The credential and per-account headers for an account, applied in
176
176
  * `model.request`, `http.request` and `experimental.ws.handshake`. The last
177
177
  * two run after the host has applied its own credential, so these headers
178
- * win on the wire.
178
+ * win on the wire. With `gateOnPlaceholder`, only the transport hook applies
179
+ * them, and only to owned requests. Put per-account and session headers here
180
+ * rather than in a separate `model.request` hook.
179
181
  *
180
182
  * Called once per attempt, when the account is chosen. Returning
181
183
  * `{headers, attempt}` instead of the bare edits stores `attempt` as the
@@ -184,7 +186,9 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
184
186
  accountHeaders(input: AccountRequest): Promise<HeaderEdits | AccountHeadersResult<A>> | HeaderEdits | AccountHeadersResult<A>;
185
187
  /**
186
188
  * Optional request rewrite (URL, body) before the account headers are
187
- * applied. Return `undefined` to keep the request.
189
+ * applied. Return `undefined` to keep the request. With `gateOnPlaceholder`,
190
+ * runs only for owned requests; move endpoint and body edits here rather
191
+ * than changing `model.request`.
188
192
  */
189
193
  rewriteRequest?(input: AccountRequest & {
190
194
  readonly request: Request;
@@ -219,7 +223,11 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
219
223
  readonly response: Response;
220
224
  readonly attempt: Attempt<A>;
221
225
  }): Promise<ResponseAccount<A> | undefined> | ResponseAccount<A> | undefined;
222
- /** Optional WebSocket URL rewrite. Return `undefined` to keep the URL. */
226
+ /**
227
+ * Optional WebSocket URL rewrite. With `gateOnPlaceholder`, runs only for
228
+ * handshakes whose prepared credential belongs to this plugin's login.
229
+ * Return `undefined` to keep the URL.
230
+ */
223
231
  rewriteHandshakeURL?(input: AccountRequest & {
224
232
  readonly url: string;
225
233
  readonly attempt: Attempt<A>;
@@ -257,7 +265,8 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
257
265
  *
258
266
  * It runs for every frame, including one no attempt can be tied to
259
267
  * (`attempt` is then `undefined`), so the rewrite never depends on
260
- * attribution.
268
+ * attribution. With `gateOnPlaceholder`, it runs only after an owned
269
+ * handshake, including frames after that socket's attempt has ended.
261
270
  */
262
271
  rewriteWebSocketFrame?(input: RequestScope & {
263
272
  readonly attempt: Attempt<A> | undefined;
@@ -307,10 +316,21 @@ export interface OpenCode2AuthLogger {
307
316
  warn(message: string, data?: unknown): void;
308
317
  }
309
318
  export interface InstallOpenCode2AuthOptions {
319
+ /**
320
+ * Opt in to acting only on this plugin's login. Extract the request-bound
321
+ * prepared secret from the host's transport headers (not global connection
322
+ * state). The installer compares it byte for byte with
323
+ * `placeholderSecret(adapter.providerID)`; any other value passes untouched.
324
+ * `model.request` becomes a no-op; selection and rewrites happen at transport.
325
+ */
326
+ readonly gateOnPlaceholder?: {
327
+ readonly credential: (headers: Headers) => string | undefined;
328
+ };
310
329
  /**
311
330
  * Values that must never reach the wire, normally the placeholder the host
312
331
  * holds as its credential. Defaults to the placeholder secret for the
313
- * adapter's provider.
332
+ * adapter's provider. With `gateOnPlaceholder`, that placeholder is always
333
+ * forbidden, even if this list is customized.
314
334
  */
315
335
  readonly hostCredentials?: readonly string[];
316
336
  /** Most attempts kept before the oldest is abandoned and dropped. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.11.7",
3
+ "version": "0.11.8",
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": {