@cortexkit/common-auth 0.11.6 → 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.
- package/README.md +2 -2
- package/dist/opencode2/install.d.ts +8 -0
- package/dist/opencode2/install.js +134 -66
- package/dist/opencode2/types.d.ts +25 -5
- package/dist/store/rows.d.ts +22 -0
- package/dist/store/rows.js +76 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,10 +11,10 @@ Shared libraries for the CortexKit auth plugins for OpenCode and Pi: openai-auth
|
|
|
11
11
|
|
|
12
12
|
A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in `src/` (or a CI scan script) and names the Bun test that must fail because of it, so a guard cannot silently stop guarding. A row earns its place by guarding a silent, costly failure: lock exclusion, crash safety, credential loss or leakage, a single-use token used twice, misattributed quota, a wire contract, data loss. Style and cosmetics do not.
|
|
13
13
|
|
|
14
|
-
The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/
|
|
14
|
+
The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/73c7e66145e131eadffdd874c82d93548868b668/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
|
|
15
15
|
|
|
16
16
|
```sh
|
|
17
|
-
cargo install --locked --git https://github.com/cortexkit/commons --rev
|
|
17
|
+
cargo install --locked --git https://github.com/cortexkit/commons --rev 73c7e66145e131eadffdd874c82d93548868b668 cortexkit-mutate
|
|
18
18
|
ckdev-mutate check
|
|
19
19
|
ckdev-mutate run --all
|
|
20
20
|
ckdev-mutate run --diff origin/main
|
|
@@ -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 =
|
|
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) =>
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
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
|
-
}
|
|
496
|
-
registrations.push(await ctx.session.hook('http.request', (draft) =>
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
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
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
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
|
-
}
|
|
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) =>
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
const
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
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
|
-
}
|
|
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
|
-
/**
|
|
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/dist/store/rows.d.ts
CHANGED
|
@@ -55,6 +55,28 @@ export interface RemoveView {
|
|
|
55
55
|
state: Readonly<Record<string, unknown>>;
|
|
56
56
|
}
|
|
57
57
|
export interface RemoveOptions extends RowToggleOptions {
|
|
58
|
+
/**
|
|
59
|
+
* The credential the removal was decided for (since 0.11.7). Checked under
|
|
60
|
+
* every lock, before `protect` and before anything is written or repaired:
|
|
61
|
+
* - a roster row must be bound to its credential stamp, not torn, and hold
|
|
62
|
+
* exactly this epoch and recorded identity (absence included);
|
|
63
|
+
* - an orphan (only a state-file entry left, by a removal or add
|
|
64
|
+
* interrupted between its writes) must carry a stamp this store can bind
|
|
65
|
+
* to the credential beside it, and that stamp must name exactly this
|
|
66
|
+
* epoch and identity.
|
|
67
|
+
* Epochs only grow per id (a removal records the dropped epoch, and a later
|
|
68
|
+
* add of the id starts past it), so an orphan an interrupted later add
|
|
69
|
+
* left under the same id never matches the epoch of the row the caller
|
|
70
|
+
* meant to remove. A mismatch refuses with kind `attribution`, an orphan
|
|
71
|
+
* or row with no bindable stamp with kind `unbound-credential`; both leave
|
|
72
|
+
* the files byte for byte unchanged. Without it, `remove` drops whatever
|
|
73
|
+
* the id holds, as before.
|
|
74
|
+
*
|
|
75
|
+
* The epoch survives a refresh or `rotate`, so it names a credential
|
|
76
|
+
* lineage, not one token: a caller that must remove only an exact token
|
|
77
|
+
* still checks the loaded credential in `protect`.
|
|
78
|
+
*/
|
|
79
|
+
attribution?: Attribution;
|
|
58
80
|
/**
|
|
59
81
|
* Awaited under every lock before anything is written; a reason refuses
|
|
60
82
|
* the removal (kind `row-protected`) with both files unchanged. The store
|
package/dist/store/rows.js
CHANGED
|
@@ -710,6 +710,8 @@ export async function removeRow(rt, id, options = {}) {
|
|
|
710
710
|
// older readers would trim is invalid, and removing it is a repair.
|
|
711
711
|
if (typeof id !== 'string' || id.length === 0)
|
|
712
712
|
throw refusal('remove', id, 'invalid-input', 'id must be non-empty');
|
|
713
|
+
const fence = options.attribution;
|
|
714
|
+
validateAttribution('remove', id, fence);
|
|
713
715
|
const result = await readPool(ctx);
|
|
714
716
|
if (result.status !== 'ready')
|
|
715
717
|
throw notReadyError(result, 'remove', id);
|
|
@@ -727,6 +729,12 @@ export async function removeRow(rt, id, options = {}) {
|
|
|
727
729
|
throw unknownRow('remove', id);
|
|
728
730
|
if (rowLockKey(row ?? { id }) !== seenKey)
|
|
729
731
|
throw keyChanged('remove', id);
|
|
732
|
+
if (fence !== undefined) {
|
|
733
|
+
if (row)
|
|
734
|
+
assertBoundRowAttribution(id, row, fence);
|
|
735
|
+
else
|
|
736
|
+
assertOrphanAttribution(rt, tx, id, fence);
|
|
737
|
+
}
|
|
730
738
|
const protect = options.protect;
|
|
731
739
|
if (protect) {
|
|
732
740
|
const view = {
|
|
@@ -747,9 +755,76 @@ export async function removeRow(rt, id, options = {}) {
|
|
|
747
755
|
await tx.commitState();
|
|
748
756
|
}
|
|
749
757
|
return { id, outcome: row ? 'removed' : 'completed' };
|
|
750
|
-
}
|
|
758
|
+
},
|
|
759
|
+
// An attributed removal is refused, when it is, with nothing written:
|
|
760
|
+
// completing another row's interrupted write first would be a write.
|
|
761
|
+
{ completeTorn: fence === undefined });
|
|
751
762
|
});
|
|
752
763
|
}
|
|
764
|
+
/** An attributed removal of a roster row: bound, not torn, same epoch and identity. */
|
|
765
|
+
function assertBoundRowAttribution(id, row, fence) {
|
|
766
|
+
assertRowAttribution('remove', id, row, fence);
|
|
767
|
+
// A torn row is between the two writes of another operation; which
|
|
768
|
+
// credential it holds is not settled, so no attribution can match it.
|
|
769
|
+
if (row.torn)
|
|
770
|
+
throw refusal('remove', id, 'attribution', `row ${id} is between the writes of another operation; retry once it completes`, true);
|
|
771
|
+
if (row.stamp !== 'bound')
|
|
772
|
+
throw refusal('remove', id, 'unbound-credential', `row ${id}'s credential is not bound to its stamp, so the removal cannot be attributed to it`);
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* An attributed removal of an orphan. The orphan is loaded the way an
|
|
776
|
+
* interrupted add's replay loads it (`matchingInterruptedAdd`): its stamp
|
|
777
|
+
* supplies the identity and endpoint the missing roster row would have held,
|
|
778
|
+
* and the credential beside it must be the one that stamp names (status
|
|
779
|
+
* `bound`). Only then does the stamp's epoch and identity mean anything.
|
|
780
|
+
*/
|
|
781
|
+
function assertOrphanAttribution(rt, tx, id, fence) {
|
|
782
|
+
const unbound = () => refusal('remove', id, 'unbound-credential', `orphan ${id} has no credential stamp this store can bind, so the removal cannot be attributed to it`);
|
|
783
|
+
const account = tx.stateAccount(id);
|
|
784
|
+
const stamp = parseStamp(account?.[CREDENTIAL_STAMP_KEY]);
|
|
785
|
+
// A replace's stamp only ever sits beside a roster row; one left without
|
|
786
|
+
// a row is not a state this store writes.
|
|
787
|
+
if (!account ||
|
|
788
|
+
!stamp?.binding ||
|
|
789
|
+
stamp.dispatch === undefined ||
|
|
790
|
+
stamp.replace)
|
|
791
|
+
throw unbound();
|
|
792
|
+
let descriptor;
|
|
793
|
+
if (typeof account.apiKey === 'string') {
|
|
794
|
+
if (stamp.binding.baseURL === undefined ||
|
|
795
|
+
stamp.binding.authHeader === undefined)
|
|
796
|
+
throw unbound();
|
|
797
|
+
descriptor = {
|
|
798
|
+
type: 'api',
|
|
799
|
+
apiKey: account.apiKey,
|
|
800
|
+
baseURL: stamp.binding.baseURL,
|
|
801
|
+
authHeader: stamp.binding.authHeader,
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
else if (typeof account.refresh === 'string') {
|
|
805
|
+
descriptor = { type: 'oauth', refresh: account.refresh };
|
|
806
|
+
}
|
|
807
|
+
else
|
|
808
|
+
throw unbound();
|
|
809
|
+
const [orphan] = buildRawRows({
|
|
810
|
+
accounts: [
|
|
811
|
+
rosterRowFor({
|
|
812
|
+
id,
|
|
813
|
+
credential: descriptor,
|
|
814
|
+
identity: stamp.binding.identity,
|
|
815
|
+
addedAt: 0,
|
|
816
|
+
}),
|
|
817
|
+
],
|
|
818
|
+
[POOL_KEY]: {
|
|
819
|
+
rows: { [id]: { credentialEpoch: stamp.credentialEpoch } },
|
|
820
|
+
},
|
|
821
|
+
}, tx.state, rt.ctx.codec, rt.ctx.providerState);
|
|
822
|
+
if (!orphan?.credential || orphan.invalid || orphan.stamp !== 'bound')
|
|
823
|
+
throw unbound();
|
|
824
|
+
if (stamp.credentialEpoch !== fence.credentialEpoch ||
|
|
825
|
+
stamp.binding.identity !== fence.identity)
|
|
826
|
+
throw refusal('remove', id, 'attribution', `orphan ${id} was written for a credential or account other than the one this removal was decided for`, true);
|
|
827
|
+
}
|
|
753
828
|
function hasStateAccount(state, id) {
|
|
754
829
|
const accounts = state.accounts;
|
|
755
830
|
return isRecord(accounts) && Object.hasOwn(accounts, id);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/common-auth",
|
|
3
|
-
"version": "0.11.
|
|
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": {
|