@cortexkit/common-auth 0.25.0 → 0.27.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.
Files changed (38) hide show
  1. package/dist/claustrum/consumer.d.ts +63 -2
  2. package/dist/claustrum/consumer.js +250 -9
  3. package/dist/claustrum/custody.d.ts +36 -1
  4. package/dist/claustrum/custody.js +95 -11
  5. package/dist/claustrum/hub.d.ts +187 -0
  6. package/dist/claustrum/hub.js +960 -0
  7. package/dist/claustrum/index.d.ts +3 -2
  8. package/dist/claustrum/index.js +2 -1
  9. package/dist/claustrum/quota-writer.js +4 -54
  10. package/dist/claustrum/roster.d.ts +47 -0
  11. package/dist/claustrum/roster.js +74 -3
  12. package/dist/claustrum/shutdown.d.ts +8 -0
  13. package/dist/claustrum/shutdown.js +42 -0
  14. package/dist/fs/refresh-file-lock.d.ts +1 -1
  15. package/dist/fs/refresh-file-lock.js +20 -11
  16. package/dist/opencode2/errors.d.ts +4 -1
  17. package/dist/opencode2/index.d.ts +2 -2
  18. package/dist/opencode2/index.js +1 -1
  19. package/dist/opencode2/install.d.ts +7 -5
  20. package/dist/opencode2/install.js +139 -13
  21. package/dist/opencode2/types.d.ts +42 -10
  22. package/dist/quota/pending.d.ts +11 -0
  23. package/dist/quota/pending.js +48 -0
  24. package/dist/redaction/index.d.ts +8 -0
  25. package/dist/redaction/index.js +490 -0
  26. package/dist/rpc/rpc-server.js +29 -19
  27. package/dist/setup/command.js +52 -14
  28. package/dist/setup/register.d.ts +2 -0
  29. package/dist/setup/register.js +90 -11
  30. package/dist/store/attribution.d.ts +5 -0
  31. package/dist/store/attribution.js +39 -25
  32. package/dist/store/pool.d.ts +17 -0
  33. package/dist/store/pool.js +18 -3
  34. package/dist/store/pull.js +3 -1
  35. package/dist/store/quota-writer.d.ts +40 -0
  36. package/dist/store/quota-writer.js +298 -0
  37. package/dist/store/runtime.d.ts +2 -0
  38. package/package.json +6 -2
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability
4
4
  import { readClaustrumEnrollmentToken } from './enrollment.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
7
+ import { drainShutdown, shutdownWarning } from './shutdown.js';
7
8
  import { ScopedRosterWatch, } from './watch.js';
8
9
  /** Only a new version of the same account may replace an in-flight 401. */
9
10
  export function isScopedCredentialRotation(served, current) {
@@ -79,15 +80,56 @@ function accessTokenFromMaterial(material) {
79
80
  return access;
80
81
  }
81
82
  function credentialTypeOf(row, family) {
83
+ const notMine = { kind: 'not-mine' };
82
84
  if (!row.operations.includes('read'))
83
- return undefined;
85
+ return notMine;
84
86
  if (!row.categories.includes(family.category))
85
- return undefined;
87
+ return notMine;
88
+ if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
89
+ return notMine;
90
+ if ('classify' in family) {
91
+ // Older clients omit these facts entirely; do not call a policy that needs them.
92
+ const facts = {
93
+ credentialId: row.id,
94
+ credentialType: row.credentialType,
95
+ categories: row.categories,
96
+ refreshAdapter: row.refreshAdapter,
97
+ ...rowFactsOf(row),
98
+ };
99
+ if (facts.providerIds === undefined)
100
+ return { kind: 'refused', code: 'unmapped' };
101
+ try {
102
+ const result = family.classify(facts);
103
+ if (result.kind === 'not-mine')
104
+ return notMine;
105
+ if (result.kind === 'mine' && typeof result.member === 'string')
106
+ return { kind: 'mine', type: row.credentialType, member: result.member };
107
+ if (result.kind === 'refused' &&
108
+ typeof result.code === 'string' &&
109
+ /^[a-z][a-z0-9-]{0,31}$/.test(result.code) &&
110
+ !result.code.includes('\n') &&
111
+ family.refusalCodes.includes(result.code))
112
+ return { kind: 'refused', code: result.code };
113
+ }
114
+ catch {
115
+ // A classifier error may contain vault data; expose only a fixed code.
116
+ }
117
+ return { kind: 'refused', code: 'unclassified' };
118
+ }
86
119
  if (row.credentialType === 'oauth')
87
- return row.refreshAdapter === family.refreshAdapter ? 'oauth' : undefined;
120
+ return row.refreshAdapter === family.refreshAdapter
121
+ ? { kind: 'mine', type: 'oauth' }
122
+ : notMine;
88
123
  if (row.credentialType === 'api_key' && family.apiKeys)
89
- return row.refreshAdapter === undefined ? 'api_key' : undefined;
90
- return undefined;
124
+ return row.refreshAdapter === undefined
125
+ ? { kind: 'mine', type: 'api_key' }
126
+ : notMine;
127
+ return notMine;
128
+ }
129
+ /** Structural access keeps the public facts independent of client declarations. */
130
+ function rowFactsOf(row) {
131
+ const metadata = row;
132
+ return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
91
133
  }
92
134
  /**
93
135
  * The grants named in the vault's list reply, or undefined when it names none.
@@ -136,6 +178,9 @@ export class ClaustrumScopedCustody {
136
178
  /** The view of the last successful `discover()`, for `watchRoster`. */
137
179
  #discoveredView;
138
180
  #watches = new Set();
181
+ #tokenReads = new Set();
182
+ #warnShutdown;
183
+ #disposing;
139
184
  constructor(options) {
140
185
  const tokenPath = options.tokenPath;
141
186
  if (options.readToken) {
@@ -153,6 +198,7 @@ export class ClaustrumScopedCustody {
153
198
  this.#requireAssertion = options.requireAssertion ?? false;
154
199
  this.#now = options.now ?? Date.now;
155
200
  this.#logger = options.logger ?? defaultLogger;
201
+ this.#warnShutdown = shutdownWarning(this.#logger);
156
202
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
157
203
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
158
204
  }
@@ -220,7 +266,15 @@ export class ClaustrumScopedCustody {
220
266
  }
221
267
  async #token(signal) {
222
268
  this.#check(signal);
223
- const value = await this.#readToken();
269
+ const pending = this.#readToken();
270
+ this.#tokenReads.add(pending);
271
+ let value;
272
+ try {
273
+ value = await pending;
274
+ }
275
+ finally {
276
+ this.#tokenReads.delete(pending);
277
+ }
224
278
  this.#check(signal);
225
279
  if (!/^[0-9a-f]{64}$/.test(value.token) ||
226
280
  !Number.isSafeInteger(value.token_generation) ||
@@ -299,17 +353,32 @@ export class ClaustrumScopedCustody {
299
353
  throw error;
300
354
  }
301
355
  const skipped = [];
356
+ const refused = [];
357
+ let notMine = 0;
302
358
  const candidates = [];
303
359
  const counts = new Map();
304
360
  for (const row of inventory.rows) {
305
- const type = credentialTypeOf(row, this.#family);
306
- if (!type)
361
+ const classified = credentialTypeOf(row, this.#family);
362
+ if (classified.kind === 'not-mine') {
363
+ notMine++;
364
+ continue;
365
+ }
366
+ if (classified.kind === 'refused') {
367
+ refused.push({
368
+ ...(row.id.trim() && { credentialId: row.id }),
369
+ code: classified.code,
370
+ });
307
371
  continue;
308
- candidates.push({ row, type });
372
+ }
373
+ candidates.push({
374
+ row,
375
+ type: classified.type,
376
+ ...(classified.member !== undefined && { member: classified.member }),
377
+ });
309
378
  counts.set(row.id, (counts.get(row.id) ?? 0) + 1);
310
379
  }
311
380
  const credentials = [];
312
- for (const { row, type } of candidates) {
381
+ for (const { row, type, member } of candidates) {
313
382
  let reason;
314
383
  if (!row.id.trim())
315
384
  reason = 'empty credential id';
@@ -320,12 +389,17 @@ export class ClaustrumScopedCustody {
320
389
  else if (!row.state.trim())
321
390
  reason = 'empty state';
322
391
  if (reason) {
323
- skipped.push({ ...(row.id.trim() && { credentialId: row.id }), reason });
392
+ skipped.push({
393
+ ...(row.id.trim() && { credentialId: row.id }),
394
+ ...(member !== undefined && { member }),
395
+ reason,
396
+ });
324
397
  continue;
325
398
  }
326
399
  credentials.push(Object.freeze({
327
400
  credentialId: row.id,
328
401
  credentialType: type,
402
+ ...(member !== undefined && { member }),
329
403
  ...(row.accountId !== undefined && {
330
404
  accountIdentity: row.accountId,
331
405
  }),
@@ -341,6 +415,10 @@ export class ClaustrumScopedCustody {
341
415
  view: inventory.view,
342
416
  credentials: Object.freeze(credentials),
343
417
  skipped: Object.freeze(skipped),
418
+ ...('classify' in this.#family && {
419
+ refused: Object.freeze(refused),
420
+ notMine,
421
+ }),
344
422
  ...(grantReach && { grantReach }),
345
423
  };
346
424
  }
@@ -646,4 +724,10 @@ export class ClaustrumScopedCustody {
646
724
  this.#kept.clear();
647
725
  this.#client.close();
648
726
  }
727
+ /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
728
+ async dispose(onTimeout = this.#warnShutdown) {
729
+ this.close();
730
+ this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
731
+ await this.#disposing;
732
+ }
649
733
  }
@@ -0,0 +1,187 @@
1
+ import type { QuotaObservation } from '../quota/index.js';
2
+ import { type ClaustrumConsumer } from './consumer.js';
3
+ import { type ClassifyingClaustrumFamily, type ClaustrumScopedClient, ClaustrumScopedCustody, type IdentityParser, type KeptReceiptState, type VaultGrantReach } from './custody.js';
4
+ import { type ClaustrumLogger } from './errors.js';
5
+ import { type AccountMapper, type VaultRosterFile } from './roster.js';
6
+ import { type WatchMode } from './watch.js';
7
+ export interface ClaustrumDiscoveryHubOptions {
8
+ /**
9
+ * The plugin's owner-only state directory. Member rosters live under
10
+ * `<stateDir>/rosters/<hostGeneration>/<fingerprint>/<provider>.json`.
11
+ */
12
+ stateDir: string;
13
+ /**
14
+ * Which host generation this process runs (for example `opencode1`,
15
+ * `opencode2` or `pi`). Hosts that classify rows differently keep separate
16
+ * roster directories.
17
+ */
18
+ hostGeneration: string;
19
+ /**
20
+ * Everything the plugin's classifier decides with, as plain JSON: the
21
+ * exact object it hands the classifier (its version, the supported-table
22
+ * entries, the reserved provider set and every host fact it reads). The
23
+ * hub hashes it, with the member set, `routePrefix` and `mapAccount`, into
24
+ * the roster key, so processes whose classifiers or projections could
25
+ * disagree never share a roster file. Configuration that `mapAccount`
26
+ * reads, beyond its own source text, belongs here too.
27
+ */
28
+ classifierInput: unknown;
29
+ /**
30
+ * Every provider the plugin serves on this host, fixed for the hub's life.
31
+ * Each is the `member` a classified row names and a roster file name, so
32
+ * it is lowercase ASCII: letters, digits, `.`, `_` and `-`.
33
+ */
34
+ members: readonly string[];
35
+ /** Prefix of every member's vault route ids; part of the roster key. */
36
+ routePrefix?: string;
37
+ /**
38
+ * How every member presents a vault credential (the credential names its
39
+ * member). Part of the roster key by its source text.
40
+ */
41
+ mapAccount?: AccountMapper;
42
+ /** This host's enrollment token, written by setup. */
43
+ tokenPath: string;
44
+ /**
45
+ * The plugin's classifying family. A legacy `ClaustrumFamily` names no
46
+ * member for any row and is refused.
47
+ */
48
+ family: ClassifyingClaustrumFamily<string>;
49
+ connect: () => Promise<ClaustrumScopedClient>;
50
+ /**
51
+ * Whether the plugin takes its accounts from the vault. Read from local
52
+ * state only, never from the vault: on every hub tick, and when a member
53
+ * refreshes or authorizes. The first false read revokes every lease,
54
+ * closes the connection and clears every member.
55
+ */
56
+ isCustodyActive?: () => boolean | Promise<boolean>;
57
+ parseIdentity?: IdentityParser;
58
+ /** As `ClaustrumConsumerOptions.requireAssertion`, for every member. */
59
+ requireAssertion?: boolean;
60
+ /**
61
+ * How often the hub ticks (default 5 s). A tick reads authority, installs
62
+ * member roster files another writer changed under the same view, and
63
+ * lists when a list is due: on every tick while no vault watch is open,
64
+ * when a pending member's retry is due (a member the last list did not
65
+ * commit, retried with a backoff), otherwise every five minutes as a
66
+ * safety net.
67
+ */
68
+ pollIntervalMs?: number;
69
+ setTimeoutImpl?: typeof setTimeout;
70
+ clearTimeoutImpl?: typeof clearTimeout;
71
+ now?: () => number;
72
+ logger?: ClaustrumLogger;
73
+ /**
74
+ * Errors of the hub's own tick, list and watch. A failed list and a vault
75
+ * refusal of the watch also reach every member's `onError`.
76
+ */
77
+ onError?: (error: unknown) => void;
78
+ }
79
+ /**
80
+ * What one hub member takes: only what is per provider. The hub owns the
81
+ * roster path, the enrollment token, the family, the connection, the
82
+ * authority check, the poll timer and the projection inputs that are part of
83
+ * the roster key (`routePrefix`, `mapAccount`), so none of them can be given
84
+ * here. The type parameter matches the consumer `member` returns; members
85
+ * have no insula source.
86
+ */
87
+ export interface ClaustrumHubMemberOptions<_Q = QuotaObservation> {
88
+ /**
89
+ * Ids of the plugin's local pool rows; no vault route id may equal one.
90
+ * Read on every projection and install, so it may change at any time.
91
+ */
92
+ reservedRouteIds?: () => Iterable<string>;
93
+ /** As `ClaustrumConsumerOptions.onRoster`: once per change of view. */
94
+ onRoster?: (roster: VaultRosterFile) => void;
95
+ /** This member's own failures, such as a roster commit that failed. */
96
+ onError?: (error: unknown) => void;
97
+ logger?: ClaustrumLogger;
98
+ }
99
+ /** What a lease may do with the shared custody. */
100
+ export type ClaustrumLeasedCustody = Pick<ClaustrumScopedCustody, 'authorize' | 'reportFailure' | 'forget' | 'keptReceiptState'>;
101
+ /**
102
+ * One acquisition of the hub's shared custody. `custody` throws `closed`
103
+ * after `release()`, and once the connection it belongs to ended for any
104
+ * reason, vault mode going off included. `release()` is idempotent.
105
+ */
106
+ export interface CustodyLease {
107
+ readonly custody: ClaustrumLeasedCustody;
108
+ /** The connection this lease belongs to; each new connection counts up. */
109
+ readonly generation: number;
110
+ release(): void;
111
+ }
112
+ /** The rows the hub's last complete discovery refused or left to others. */
113
+ export interface ClaustrumHubRefusals {
114
+ readonly view: string;
115
+ readonly refused: readonly {
116
+ credentialId?: string;
117
+ code: string;
118
+ }[];
119
+ readonly notMine: number;
120
+ }
121
+ /**
122
+ * One discovery hub per host process: the only vault connection and the only
123
+ * `ClaustrumScopedCustody`, one vault watch and one list per refresh, fanned
124
+ * out to one roster per provider. Members (`member()`) are ordinary
125
+ * `ClaustrumConsumer`s that never connect, list or watch themselves; each
126
+ * holds a custody lease. The connection stays open while vault mode is on,
127
+ * because the hub's own discovery holds a lease of its own, and closes when
128
+ * the last lease of a connection is released, when vault mode goes off, or
129
+ * at `close()`.
130
+ */
131
+ export declare class ClaustrumDiscoveryHub {
132
+ #private;
133
+ constructor(options: ClaustrumDiscoveryHubOptions);
134
+ /** The roster file member `provider` reads and the hub commits. */
135
+ rosterPath(provider: string): string;
136
+ /**
137
+ * Build the consumer for `provider`, once. It is an ordinary
138
+ * `ClaustrumConsumer` whose roster path is `rosterPath(provider)`; it
139
+ * connects, lists and watches only through this hub.
140
+ */
141
+ member<Q = QuotaObservation>(provider: string, options: ClaustrumHubMemberOptions<Q>): ClaustrumConsumer<Q>;
142
+ /**
143
+ * Take a lease on the current connection, connecting first when there is
144
+ * none. The acquirer's count is taken before anything is awaited, so a
145
+ * release elsewhere meanwhile cannot end the connection under it. An abort
146
+ * or a failed connect gives that count back; an acquirer whose connection
147
+ * ended while it waited tries once more on the current one. Rejects with
148
+ * `not-active` while vault mode is off.
149
+ */
150
+ acquire(signal?: AbortSignal): Promise<CustodyLease>;
151
+ /** The current connection and its lease count, for status and tests. */
152
+ leaseState(): {
153
+ readonly generation?: number;
154
+ readonly count: number;
155
+ };
156
+ /**
157
+ * Start the hub's tick, which runs until `close()`. While vault mode is
158
+ * off a tick only reads authority and makes no vault request.
159
+ */
160
+ start(): void;
161
+ /**
162
+ * List once and commit every member, as a tick does. Resolves once every
163
+ * member's memory holds its new roster. Rejects when the list fails; a
164
+ * member's own commit error goes to that member's `onError`.
165
+ */
166
+ refresh(): Promise<void>;
167
+ /**
168
+ * Rows the last discovery every member committed refused, with their fixed
169
+ * codes, and how many rows it left to other plugins. Undefined while
170
+ * unknown: before a complete discovery, and while vault mode is off.
171
+ */
172
+ refusals(): ClaustrumHubRefusals | undefined;
173
+ /** The grant reach of the same discovery as `refusals()`. */
174
+ grantReach(): VaultGrantReach | undefined;
175
+ /** How the hub learns about changes; `polling` until a watch is open. */
176
+ watchState(): WatchMode;
177
+ /** The shared custody's kept receipts, host-wide. */
178
+ keptReceiptState(): KeptReceiptState;
179
+ /**
180
+ * Stop the tick and the watch and close the connection. Members are not
181
+ * closed; they fail `closed` from then on. Use `dispose()` to also allow
182
+ * in-flight discovery up to two seconds to release its file handles.
183
+ */
184
+ close(): void;
185
+ /** Close immediately, then join background work for at most two seconds. */
186
+ dispose(): Promise<void>;
187
+ }