@cortexkit/common-auth 0.11.7 → 0.12.0
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/commands/builtins.js +2 -0
- package/dist/fs/atomic-write.d.ts +13 -0
- package/dist/fs/atomic-write.js +52 -0
- package/dist/opencode2/install.d.ts +8 -0
- package/dist/opencode2/install.js +134 -66
- package/dist/opencode2/integration.d.ts +6 -7
- package/dist/opencode2/integration.js +12 -8
- package/dist/opencode2/types.d.ts +25 -5
- package/dist/store/attribution.js +1 -0
- package/dist/store/errors.d.ts +2 -2
- package/dist/store/identity.js +2 -0
- package/dist/store/index.d.ts +2 -1
- package/dist/store/mutate.d.ts +22 -2
- package/dist/store/mutate.js +140 -34
- package/dist/store/pool.d.ts +9 -2
- package/dist/store/pool.js +4 -0
- package/dist/store/publication.d.ts +47 -0
- package/dist/store/publication.js +304 -0
- package/dist/store/pull.js +6 -1
- package/dist/store/refresh.js +2 -0
- package/dist/store/reserved.d.ts +3 -0
- package/dist/store/reserved.js +13 -0
- package/dist/store/rows.d.ts +62 -13
- package/dist/store/rows.js +331 -42
- package/dist/store/runtime.js +13 -1
- package/dist/store/schema.d.ts +18 -0
- package/dist/store/schema.js +58 -2
- package/dist/store/torn.js +1 -1
- package/package.json +1 -1
|
@@ -98,6 +98,8 @@ function addedText(name, result) {
|
|
|
98
98
|
return `Finished adding ${name}.`;
|
|
99
99
|
case 'rotated':
|
|
100
100
|
return `${name} was already in the pool; its credential was updated.`;
|
|
101
|
+
case 'exists':
|
|
102
|
+
return `${name} was already in the pool; its credential is unchanged.`;
|
|
101
103
|
}
|
|
102
104
|
}
|
|
103
105
|
/**
|
|
@@ -3,5 +3,18 @@ export interface AtomicWriteOptions {
|
|
|
3
3
|
beforeRename?: () => Promise<void>;
|
|
4
4
|
/** Test seam for forcing staging-name collisions; defaults to randomUUID. */
|
|
5
5
|
stageName?: () => string;
|
|
6
|
+
/** Sync the staged file and, after rename, its parent directory. Opt-in. */
|
|
7
|
+
durable?: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** Internal classification of fsync failures, including a failure after rename. */
|
|
10
|
+
export declare class AtomicSyncError extends Error {
|
|
11
|
+
constructor(cause: unknown);
|
|
6
12
|
}
|
|
7
13
|
export declare function writeJsonAtomic(path: string, value: unknown, options?: AtomicWriteOptions): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Notify internal callers at the rename. The store records committed writes
|
|
16
|
+
* and removed ids here, because a later directory sync cannot undo the rename.
|
|
17
|
+
*/
|
|
18
|
+
export declare function writeJsonAtomicTracked(path: string, value: unknown, options: AtomicWriteOptions, onRenamed?: () => void): Promise<void>;
|
|
19
|
+
/** Make an already renamed file and its directory durable without rewriting bytes. */
|
|
20
|
+
export declare function syncJsonFile(path: string): Promise<void>;
|
package/dist/fs/atomic-write.js
CHANGED
|
@@ -1,7 +1,21 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { mkdir, open, rename, rm } from 'node:fs/promises';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
|
+
/** Internal classification of fsync failures, including a failure after rename. */
|
|
5
|
+
export class AtomicSyncError extends Error {
|
|
6
|
+
constructor(cause) {
|
|
7
|
+
super('file or directory sync failed', { cause });
|
|
8
|
+
this.name = 'AtomicSyncError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
4
11
|
export async function writeJsonAtomic(path, value, options = {}) {
|
|
12
|
+
await writeJsonAtomicTracked(path, value, options);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Notify internal callers at the rename. The store records committed writes
|
|
16
|
+
* and removed ids here, because a later directory sync cannot undo the rename.
|
|
17
|
+
*/
|
|
18
|
+
export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
|
|
5
19
|
await mkdir(dirname(path), { recursive: true });
|
|
6
20
|
const tempPath = `${path}.${(options.stageName ?? randomUUID)()}.tmp`;
|
|
7
21
|
let handle;
|
|
@@ -13,11 +27,32 @@ export async function writeJsonAtomic(path, value, options = {}) {
|
|
|
13
27
|
? options.serialize(value)
|
|
14
28
|
: `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
15
29
|
await handle.chmod(0o600);
|
|
30
|
+
if (options.durable) {
|
|
31
|
+
try {
|
|
32
|
+
await handle.sync();
|
|
33
|
+
}
|
|
34
|
+
catch (cause) {
|
|
35
|
+
throw new AtomicSyncError(cause);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
16
38
|
await handle.close();
|
|
17
39
|
handle = undefined;
|
|
18
40
|
await options.beforeRename?.();
|
|
19
41
|
await rename(tempPath, path);
|
|
20
42
|
created = false;
|
|
43
|
+
onRenamed?.();
|
|
44
|
+
if (options.durable) {
|
|
45
|
+
const directory = await open(dirname(path), 'r');
|
|
46
|
+
try {
|
|
47
|
+
await directory.sync();
|
|
48
|
+
}
|
|
49
|
+
catch (cause) {
|
|
50
|
+
throw new AtomicSyncError(cause);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
await directory.close();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
21
56
|
}
|
|
22
57
|
finally {
|
|
23
58
|
await handle?.close().catch(() => { });
|
|
@@ -26,3 +61,20 @@ export async function writeJsonAtomic(path, value, options = {}) {
|
|
|
26
61
|
await rm(tempPath, { force: true }).catch(() => { });
|
|
27
62
|
}
|
|
28
63
|
}
|
|
64
|
+
/** Make an already renamed file and its directory durable without rewriting bytes. */
|
|
65
|
+
export async function syncJsonFile(path) {
|
|
66
|
+
const file = await open(path, 'r');
|
|
67
|
+
try {
|
|
68
|
+
await file.sync();
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
await file.close();
|
|
72
|
+
}
|
|
73
|
+
const directory = await open(dirname(path), 'r');
|
|
74
|
+
try {
|
|
75
|
+
await directory.sync();
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await directory.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -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 {
|
|
@@ -64,14 +64,13 @@ export interface RegisterOpenCode2AuthMethodsOptions<T> {
|
|
|
64
64
|
readonly now?: () => number;
|
|
65
65
|
}
|
|
66
66
|
/**
|
|
67
|
-
* Registers the plugin's login methods with the host so that a login lands
|
|
68
|
-
* the plugin's pool and the host keeps only a placeholder credential.
|
|
67
|
+
* Registers the plugin's own login methods with the host so that a login lands
|
|
68
|
+
* in the plugin's pool and the host keeps only a placeholder credential.
|
|
69
69
|
*
|
|
70
|
-
* Host-driven refresh never reaches the pool: it
|
|
71
|
-
* placeholder
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
* it (`ctx.integration.connection`) before that happens.
|
|
70
|
+
* Host-driven refresh never reaches the pool: it renews only this integration's
|
|
71
|
+
* placeholder and refuses every other credential without replacing it. Plugins
|
|
72
|
+
* must register under their own method IDs; a plugin importing an existing
|
|
73
|
+
* host login should read it through `ctx.integration.connection` instead.
|
|
75
74
|
*/
|
|
76
75
|
export declare function registerOpenCode2AuthMethods<T>(ctx: {
|
|
77
76
|
readonly integration: Pick<Plugin.Context['integration'], 'transform'>;
|
|
@@ -39,14 +39,13 @@ export function isPlaceholderCredential(value, integrationID) {
|
|
|
39
39
|
return matches(value.access) && matches(value.refresh);
|
|
40
40
|
}
|
|
41
41
|
/**
|
|
42
|
-
* Registers the plugin's login methods with the host so that a login lands
|
|
43
|
-
* the plugin's pool and the host keeps only a placeholder credential.
|
|
42
|
+
* Registers the plugin's own login methods with the host so that a login lands
|
|
43
|
+
* in the plugin's pool and the host keeps only a placeholder credential.
|
|
44
44
|
*
|
|
45
|
-
* Host-driven refresh never reaches the pool: it
|
|
46
|
-
* placeholder
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* it (`ctx.integration.connection`) before that happens.
|
|
45
|
+
* Host-driven refresh never reaches the pool: it renews only this integration's
|
|
46
|
+
* placeholder and refuses every other credential without replacing it. Plugins
|
|
47
|
+
* must register under their own method IDs; a plugin importing an existing
|
|
48
|
+
* host login should read it through `ctx.integration.connection` instead.
|
|
50
49
|
*/
|
|
51
50
|
export async function registerOpenCode2AuthMethods(ctx, options) {
|
|
52
51
|
const now = options.now ?? Date.now;
|
|
@@ -86,7 +85,12 @@ export async function registerOpenCode2AuthMethods(ctx, options) {
|
|
|
86
85
|
integrationID,
|
|
87
86
|
method: login.method,
|
|
88
87
|
authorize: authorizeWith(login),
|
|
89
|
-
refresh: async (credential) =>
|
|
88
|
+
refresh: async (credential) => {
|
|
89
|
+
if (!isPlaceholderCredential(credential, integrationID)) {
|
|
90
|
+
throw new Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");
|
|
91
|
+
}
|
|
92
|
+
return placeholderFor(credential.methodID);
|
|
93
|
+
},
|
|
90
94
|
...(options.label === undefined ? {} : { label: () => options.label }),
|
|
91
95
|
});
|
|
92
96
|
}
|
|
@@ -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. */
|
|
@@ -16,6 +16,7 @@ export async function recordQuota(rt, id, attribution, observation) {
|
|
|
16
16
|
if (!isCredentialEpoch(attribution?.credentialEpoch))
|
|
17
17
|
throw refusal('pull', id, 'invalid-input', 'the credential epoch the reading was issued for must be a positive safe integer');
|
|
18
18
|
await withTransaction(ctx, locks, progress, { operation: 'pull', rowId: id }, async (tx) => {
|
|
19
|
+
tx.assertNotStaged(id);
|
|
19
20
|
const row = tx.row(id);
|
|
20
21
|
if (!row)
|
|
21
22
|
throw unknownRow('pull', id);
|
package/dist/store/errors.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { StoredCredential } from './schema.js';
|
|
2
2
|
/** Every library operation that can fail, as named in the failure value. */
|
|
3
|
-
export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull';
|
|
3
|
+
export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
|
|
4
4
|
/**
|
|
5
5
|
* How far an operation got before it failed.
|
|
6
6
|
*
|
|
@@ -19,7 +19,7 @@ export type PoolFailurePhase = 'before-first-write' | 'after-first-write' | 'pul
|
|
|
19
19
|
* lock outcomes (a wait that ran out, and a lease found lost); the rest are
|
|
20
20
|
* refusals and failures of the operation itself.
|
|
21
21
|
*/
|
|
22
|
-
export type PoolFailureKind = 'lock-contention' | 'lock-ownership' | 'pending-migration' | 'load-error' | 'unknown-row' | 'invalid-row' | 'invalid-input' | 'id-exists' | 'id-removed' | 'type-mismatch' | 'no-credential' | 'row-disabled' | 'row-protected' | 'duplicate-identity' | 'identity-mismatch' | 'identity-contradicted' | 'endpoint-mismatch' | 'row-key-changed' | 'invalid-order' | 'refresh-stamp-ahead' | 'unbound-credential' | 'attribution' | 'provider' | 'pull' | 'invalid-quota' | 'invalid-provider-state' | 'after-persist-hook' | 'unexpected';
|
|
22
|
+
export type PoolFailureKind = 'lock-contention' | 'lock-ownership' | 'pending-migration' | 'load-error' | 'snapshot-contended' | 'publication-sync' | 'publication-incomplete' | 'unknown-row' | 'invalid-row' | 'invalid-input' | 'id-exists' | 'id-removed' | 'type-mismatch' | 'no-credential' | 'row-disabled' | 'row-protected' | 'row-staged' | 'credential-exists' | 'publication-mismatch' | 'duplicate-identity' | 'identity-mismatch' | 'identity-contradicted' | 'endpoint-mismatch' | 'row-key-changed' | 'invalid-order' | 'refresh-stamp-ahead' | 'unbound-credential' | 'attribution' | 'provider' | 'pull' | 'invalid-quota' | 'invalid-provider-state' | 'after-persist-hook' | 'unexpected';
|
|
23
23
|
/**
|
|
24
24
|
* The single failure value of every store operation. `committed` is present
|
|
25
25
|
* only when the operation had already written a credential to the state file
|
package/dist/store/identity.js
CHANGED
|
@@ -8,6 +8,7 @@ export const DUPLICATE_IDENTITY_REASON = 'duplicate-identity';
|
|
|
8
8
|
*/
|
|
9
9
|
export function countUnknownIdentityRows(rows) {
|
|
10
10
|
return rows.filter((row) => row.invalid === undefined &&
|
|
11
|
+
!row.staged &&
|
|
11
12
|
row.type === 'oauth' &&
|
|
12
13
|
row.enabled &&
|
|
13
14
|
row.credential !== undefined &&
|
|
@@ -57,6 +58,7 @@ export function disableIdentityDuplicates(tx, identity) {
|
|
|
57
58
|
const holders = tx
|
|
58
59
|
.rows()
|
|
59
60
|
.filter((row) => row.invalid === undefined &&
|
|
61
|
+
!row.staged &&
|
|
60
62
|
row.type === 'oauth' &&
|
|
61
63
|
row.enabled &&
|
|
62
64
|
row.identity === identity);
|
package/dist/store/index.d.ts
CHANGED
|
@@ -8,11 +8,12 @@ export type { OpenPoolStoreOptions, PoolLoad, PoolStore, } from './pool.js';
|
|
|
8
8
|
export { openPoolStore } from './pool.js';
|
|
9
9
|
export type { ProviderStateMutator, RowTransitionMutator, UpdateProviderStateResult, } from './provider-state.js';
|
|
10
10
|
export { DECLINE_TRANSITION } from './provider-state.js';
|
|
11
|
+
export type { PublicationReceipt, PublishOptions, PublishPlan, PublishResult, } from './publication.js';
|
|
11
12
|
export type { PullHook, PullRequest } from './pull.js';
|
|
12
13
|
export type { ProviderRefresh, ProviderRefreshResult, RefreshOptions, RefreshOutcome, } from './refresh.js';
|
|
13
14
|
export type { LockEvent, PoolLockOptions, PoolLockSpec, } from './refresh-lock.js';
|
|
14
15
|
export { POOL_LOCK_DEFAULTS } from './refresh-lock.js';
|
|
15
|
-
export type { AddInput, AddResult, CredentialWriteInput, FailureHook, RemoveOptions, RemoveResult, RemoveView, ReorderOptions, ReorderResult, RowOperationOptions, RowToggleOptions, RowTransitionOptions, RowTransitionResult, RowWriteOptions, } from './rows.js';
|
|
16
|
+
export type { AddInput, AddOptions, AddResult, CredentialWriteInput, FailureHook, ProtectFn, ProtectView, RemoveOptions, RemoveResult, RemoveView, ReorderOptions, ReorderResult, RowOperationOptions, RowProjection, RowToggleOptions, RowTransitionOptions, RowTransitionResult, RowWriteOptions, } from './rows.js';
|
|
16
17
|
export type { PullReason } from './runtime.js';
|
|
17
18
|
export type { ApiKeyCredential, CredentialStampStatus, OAuthCredential, PoolCredential, PoolRow, ProviderStateCodec, ProviderStateDrop, ProviderStateReplacement, QuotaCodec, RotateCredential, StoredCredential, } from './schema.js';
|
|
18
19
|
export { fingerprintOf, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, PROVIDER_STATE_KEY, REFRESH_STAMP_TOLERANCE_MS, rowLockKey, } from './schema.js';
|
package/dist/store/mutate.d.ts
CHANGED
|
@@ -31,6 +31,7 @@ export interface StoreContext {
|
|
|
31
31
|
* `OpenPoolStoreOptions.requireCredentialStamps`).
|
|
32
32
|
*/
|
|
33
33
|
requireCredentialStamps?: boolean;
|
|
34
|
+
requireRemovedFingerprint?: boolean;
|
|
34
35
|
}
|
|
35
36
|
export interface Snapshot {
|
|
36
37
|
configExists: boolean;
|
|
@@ -48,8 +49,14 @@ export type ReadResult = ({
|
|
|
48
49
|
status: 'error';
|
|
49
50
|
file: 'config' | 'state';
|
|
50
51
|
reason: string;
|
|
52
|
+
kind?: 'snapshot-contended';
|
|
53
|
+
retryable?: true;
|
|
51
54
|
};
|
|
52
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* Validate config/state/config bytes without locks. Roster replacement writes
|
|
57
|
+
* config before deleting old state credentials. Re-read a changed config so an
|
|
58
|
+
* old roster cannot be paired with state from which its accounts were removed.
|
|
59
|
+
*/
|
|
53
60
|
export declare function readPool(ctx: StoreContext): Promise<ReadResult>;
|
|
54
61
|
/** The refusal for a pool that is not ready, as a failure value. */
|
|
55
62
|
export declare function notReadyError(result: Exclude<ReadResult, {
|
|
@@ -58,6 +65,8 @@ export declare function notReadyError(result: Exclude<ReadResult, {
|
|
|
58
65
|
/** What an operation has written so far; decides the failure phase. */
|
|
59
66
|
export interface Progress {
|
|
60
67
|
writes: number;
|
|
68
|
+
/** The roster config was renamed into place, or its committed receipt was found. */
|
|
69
|
+
publicationDecided?: true;
|
|
61
70
|
/** The credential the operation's state write put on disk, once it has. */
|
|
62
71
|
committed?: StoredCredential;
|
|
63
72
|
}
|
|
@@ -89,6 +98,9 @@ export declare class Transaction {
|
|
|
89
98
|
*/
|
|
90
99
|
rows(): PoolRow[];
|
|
91
100
|
row(id: string): PoolRow | undefined;
|
|
101
|
+
/** Read the config marker, or an orphan's stamp; never use a caller's reservation. */
|
|
102
|
+
reservation(id: string): unknown;
|
|
103
|
+
assertNotStaged(id: string): void;
|
|
92
104
|
roster(): unknown[];
|
|
93
105
|
/** The first roster row with this id (the one the pool loads). */
|
|
94
106
|
rosterRow(id: string): Record<string, unknown> | undefined;
|
|
@@ -126,9 +138,17 @@ export declare class Transaction {
|
|
|
126
138
|
*/
|
|
127
139
|
commitConfig(options?: {
|
|
128
140
|
counted?: boolean;
|
|
141
|
+
durable?: boolean;
|
|
142
|
+
publicationDecision?: boolean;
|
|
129
143
|
}): Promise<void>;
|
|
130
144
|
/** Writes the state: every unrecognised top-level and per-row key kept. */
|
|
131
|
-
commitState(committed?: StoredCredential
|
|
145
|
+
commitState(committed?: StoredCredential, options?: {
|
|
146
|
+
durable?: boolean;
|
|
147
|
+
}): Promise<void>;
|
|
148
|
+
assertAll(): Promise<void>;
|
|
149
|
+
syncState(): Promise<void>;
|
|
150
|
+
markPublicationDecision(): void;
|
|
151
|
+
syncConfig(): Promise<void>;
|
|
132
152
|
private write;
|
|
133
153
|
}
|
|
134
154
|
/** What `initializePool` did. */
|