@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.
@@ -1,21 +1,26 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { writeJsonAtomic } from '../fs/atomic-write.js';
2
+ import { setTimeout as snapshotDelay } from 'node:timers/promises';
3
+ import { AtomicSyncError, syncJsonFile, writeJsonAtomic, writeJsonAtomicTracked, } from '../fs/atomic-write.js';
3
4
  import { LockContentionError, LockOwnershipError } from '../fs/with-lock.js';
4
5
  import { PoolOperationError, } from './errors.js';
5
6
  import { callFailureHook } from './hooks.js';
6
7
  import { LockStack, } from './refresh-lock.js';
7
- import { classifyConfig, classifyState, ensureEntries, entryIn, isRecord, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, retireEpochsIn, rosterOf, rosterRowIn, setEntryIn, } from './schema.js';
8
+ import { assertNotReserved } from './reserved.js';
9
+ import { CREDENTIAL_STAMP_KEY, classifyConfig, classifyState, ensureEntries, entryIn, isRecord, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, retireEpochsIn, rosterOf, rosterRowIn, setEntryIn, } from './schema.js';
8
10
  import { completeTornRows, loadRows } from './torn.js';
9
- async function readJson(path) {
10
- let text;
11
+ async function readText(path) {
11
12
  try {
12
- text = await readFile(path, 'utf8');
13
+ return await readFile(path, 'utf8');
13
14
  }
14
15
  catch (error) {
15
16
  if (error.code === 'ENOENT')
16
- return { exists: false };
17
+ return undefined;
17
18
  throw error;
18
19
  }
20
+ }
21
+ function parseFile(text) {
22
+ if (text === undefined)
23
+ return { exists: false };
19
24
  try {
20
25
  return { exists: true, value: JSON.parse(text) };
21
26
  }
@@ -23,30 +28,60 @@ async function readJson(path) {
23
28
  return { exists: true, parseError };
24
29
  }
25
30
  }
26
- /** Reads and classifies both files. Never writes. */
31
+ /**
32
+ * Validate config/state/config bytes without locks. Roster replacement writes
33
+ * config before deleting old state credentials. Re-read a changed config so an
34
+ * old roster cannot be paired with state from which its accounts were removed.
35
+ */
27
36
  export async function readPool(ctx) {
28
- const config = classifyConfig(await readJson(ctx.configPath));
29
- if (config.status === 'error')
30
- return { status: 'error', file: 'config', reason: config.reason };
31
- const state = classifyState(await readJson(ctx.statePath));
32
- if (state.status === 'error')
33
- return { status: 'error', file: 'state', reason: state.reason };
34
- if (config.status === 'pending-migration')
35
- return { status: 'pending-migration', config: config.config };
37
+ for (let attempt = 0; attempt < 3; attempt++) {
38
+ const configText = await readText(ctx.configPath);
39
+ const stateText = await readText(ctx.statePath);
40
+ const checkedConfigText = await readText(ctx.configPath);
41
+ if (configText !== checkedConfigText) {
42
+ if (attempt < 2)
43
+ await snapshotDelay(2 + Math.floor(Math.random() * 4));
44
+ continue;
45
+ }
46
+ const config = classifyConfig(parseFile(configText));
47
+ if (config.status === 'error')
48
+ return { status: 'error', file: 'config', reason: config.reason };
49
+ const state = classifyState(parseFile(stateText));
50
+ if (state.status === 'error')
51
+ return { status: 'error', file: 'state', reason: state.reason };
52
+ if (config.status === 'pending-migration')
53
+ return { status: 'pending-migration', config: config.config };
54
+ return {
55
+ status: 'ready',
56
+ configExists: config.exists,
57
+ stateExists: state.exists,
58
+ config: config.config,
59
+ state: state.state,
60
+ rows: loadRows(config.config, state.state, ctx.codec, {
61
+ requireCredentialStamps: ctx.requireCredentialStamps === true,
62
+ ...(ctx.providerState ? { providerState: ctx.providerState } : {}),
63
+ }),
64
+ };
65
+ }
36
66
  return {
37
- status: 'ready',
38
- configExists: config.exists,
39
- stateExists: state.exists,
40
- config: config.config,
41
- state: state.state,
42
- rows: loadRows(config.config, state.state, ctx.codec, {
43
- requireCredentialStamps: ctx.requireCredentialStamps === true,
44
- ...(ctx.providerState ? { providerState: ctx.providerState } : {}),
45
- }),
67
+ status: 'error',
68
+ file: 'config',
69
+ kind: 'snapshot-contended',
70
+ retryable: true,
71
+ reason: 'The store was changing; retry the operation once writes settle.',
46
72
  };
47
73
  }
48
74
  /** The refusal for a pool that is not ready, as a failure value. */
49
75
  export function notReadyError(result, operation, rowId, phase = 'before-first-write') {
76
+ if (result.status === 'error' && result.kind === 'snapshot-contended')
77
+ return new PoolOperationError({
78
+ operation,
79
+ ...(rowId !== undefined ? { rowId } : {}),
80
+ phase,
81
+ kind: 'snapshot-contended',
82
+ retryable: true,
83
+ message: result.reason,
84
+ });
50
85
  return new PoolOperationError({
51
86
  operation,
52
87
  ...(rowId !== undefined ? { rowId } : {}),
@@ -99,6 +134,20 @@ export class Transaction {
99
134
  row(id) {
100
135
  return this.rows().find((row) => row.id === id);
101
136
  }
137
+ /** Read the config marker, or an orphan's stamp; never use a caller's reservation. */
138
+ reservation(id) {
139
+ if (this.rosterRow(id)) {
140
+ const entry = this.entry(id);
141
+ return entry && Object.hasOwn(entry, 'staged') ? entry.staged : undefined;
142
+ }
143
+ const stamp = this.stateAccount(id)?.[CREDENTIAL_STAMP_KEY];
144
+ return isRecord(stamp) && Object.hasOwn(stamp, 'staged')
145
+ ? stamp.staged
146
+ : undefined;
147
+ }
148
+ assertNotStaged(id) {
149
+ assertNotReserved(this.info.operation, id, this.reservation(id));
150
+ }
102
151
  roster() {
103
152
  if (!Array.isArray(this.config.accounts))
104
153
  this.config.accounts = [];
@@ -200,9 +249,6 @@ export class Transaction {
200
249
  configurable: true,
201
250
  });
202
251
  }
203
- else {
204
- this.ctx.removedIds.add(id);
205
- }
206
252
  }
207
253
  const pool = this.config[POOL_KEY];
208
254
  const next = {
@@ -215,31 +261,68 @@ export class Transaction {
215
261
  [POOL_ROWS_KEY]: kept,
216
262
  },
217
263
  };
218
- await this.write(this.ctx.configPath, next, 'config', options.counted ?? true);
264
+ await this.write(this.ctx.configPath, next, 'config', options.counted ?? true, options.durable ?? false, () => {
265
+ if (options.publicationDecision)
266
+ this.markPublicationDecision();
267
+ for (const id of dropped)
268
+ this.ctx.removedIds.add(id);
269
+ this.config = next;
270
+ });
219
271
  this.config = next;
220
272
  }
221
273
  /** Writes the state: every unrecognised top-level and per-row key kept. */
222
- async commitState(committed) {
274
+ async commitState(committed, options = {}) {
223
275
  const next = {
224
276
  ...this.state,
225
277
  version: LEGACY_STORE_VERSION,
226
278
  accounts: isRecord(this.state.accounts) ? this.state.accounts : {},
227
279
  };
228
- await this.write(this.ctx.statePath, next, 'state');
280
+ await this.write(this.ctx.statePath, next, 'state', true, options.durable ?? false);
229
281
  this.state = next;
230
282
  if (committed)
231
283
  this.progress.committed = committed;
232
284
  }
233
- async write(path, value, file, counted = true) {
234
- await writeJsonAtomic(path, value, {
285
+ async assertAll() {
286
+ await this.locks.assertAll();
287
+ }
288
+ async syncState() {
289
+ await this.assertAll();
290
+ try {
291
+ if (this.snapshot.stateExists)
292
+ await syncJsonFile(this.ctx.statePath);
293
+ }
294
+ catch (cause) {
295
+ throw new PoolOperationError({
296
+ operation: this.info.operation,
297
+ rowId: this.info.rowId,
298
+ phase: 'before-first-write',
299
+ kind: 'publication-sync',
300
+ retryable: true,
301
+ message: 'Publication sync failed before the decision; nothing was written. Retry the same plan.',
302
+ cause,
303
+ });
304
+ }
305
+ }
306
+ markPublicationDecision() {
307
+ this.progress.publicationDecided = true;
308
+ }
309
+ async syncConfig() {
310
+ await this.assertAll();
311
+ await syncJsonFile(this.ctx.configPath);
312
+ }
313
+ async write(path, value, file, counted = true, durable = false, onRenamed) {
314
+ await writeJsonAtomicTracked(path, value, {
315
+ durable,
235
316
  beforeRename: async () => {
236
317
  await this.ctx.onStep?.(`before-${file}-write`, this.info);
237
318
  // Ownership is proved immediately before the rename, on every lease.
238
319
  await this.locks.assertAll();
239
320
  },
321
+ }, () => {
322
+ if (counted)
323
+ this.progress.writes++;
324
+ onRenamed?.();
240
325
  });
241
- if (counted)
242
- this.progress.writes++;
243
326
  await this.ctx.onStep?.(`after-${file}-write`, this.info);
244
327
  }
245
328
  }
@@ -304,6 +387,9 @@ export async function withTransaction(ctx, locks, progress, info, fn, options =
304
387
  if (result.status !== 'ready')
305
388
  throw notReadyError(result, info.operation, info.rowId, progress.writes > 0 ? 'after-first-write' : 'before-first-write');
306
389
  const tx = new Transaction(ctx, result, locks, progress, info);
390
+ if (info.rowId !== undefined &&
391
+ !['add', 'remove', 'pull', 'publishRoster', 'enable', 'disable'].includes(info.operation))
392
+ tx.assertNotStaged(info.rowId);
307
393
  if (options.completeTorn ?? true)
308
394
  await tx.completeTorn();
309
395
  return await fn(tx);
@@ -320,6 +406,26 @@ export function toFailure(error, operation, rowId, progress) {
320
406
  ? 'after-first-write'
321
407
  : 'before-first-write';
322
408
  const committed = phase === 'after-first-write' ? progress.committed : undefined;
409
+ if (operation === 'publishRoster' && progress.publicationDecided)
410
+ return new PoolOperationError({
411
+ operation,
412
+ ...(rowId !== undefined ? { rowId } : {}),
413
+ phase,
414
+ kind: 'publication-incomplete',
415
+ retryable: true,
416
+ message: 'The publication may already be decided. Replay the same plan or check publication(operationId).',
417
+ cause: error,
418
+ });
419
+ if (operation === 'publishRoster' && error instanceof AtomicSyncError)
420
+ return new PoolOperationError({
421
+ operation,
422
+ ...(rowId !== undefined ? { rowId } : {}),
423
+ phase,
424
+ kind: 'publication-sync',
425
+ retryable: true,
426
+ message: 'Publication sync failed before the decision; nothing was written. Retry the same plan.',
427
+ cause: error,
428
+ });
323
429
  if (error instanceof PoolOperationError) {
324
430
  if (error.phase === phase &&
325
431
  error.rowId === rowId &&
@@ -3,10 +3,11 @@ import type { PoolOperationError } from './errors.js';
3
3
  import type { PoolLogger } from './hooks.js';
4
4
  import { type HoldPoint, type InitializeOutcome, type StoreContext } from './mutate.js';
5
5
  import { type ProviderStateMutator, type UpdateProviderStateResult } from './provider-state.js';
6
+ import { type PublicationReceipt, type PublishOptions, type PublishPlan, type PublishResult } from './publication.js';
6
7
  import { type PullHook } from './pull.js';
7
8
  import { type ProviderRefresh, type RefreshOptions, type RefreshOutcome } from './refresh.js';
8
9
  import { type LockEnvironment, type PoolLockOptions, type PoolLockSpec } from './refresh-lock.js';
9
- import { type AddInput, type AddResult, type CredentialWriteInput, type RemoveOptions, type RemoveResult, type ReorderOptions, type ReorderResult, type RowOperationOptions, type RowToggleOptions, type RowTransitionOptions, type RowTransitionResult, type RowWriteOptions } from './rows.js';
10
+ import { type AddInput, type AddOptions, type AddResult, type CredentialWriteInput, type RemoveOptions, type RemoveResult, type ReorderOptions, type ReorderResult, type RowOperationOptions, type RowToggleOptions, type RowTransitionOptions, type RowTransitionResult, type RowWriteOptions } from './rows.js';
10
11
  import { type PoolCredential, type PoolRow, type ProviderStateCodec, type QuotaCodec, type RotateCredential, type StoredCredential } from './schema.js';
11
12
  import { type SettingsMutator, type SettingsRead, type UpdateSettingsOptions, type UpdateSettingsResult } from './settings.js';
12
13
  export interface OpenPoolStoreOptions {
@@ -39,6 +40,8 @@ export interface OpenPoolStoreOptions {
39
40
  * without writing; `remove(id)` explicitly discards the orphan.
40
41
  */
41
42
  requireCredentialStamps?: boolean;
43
+ /** Require an exact secret fingerprint for every roster-publication removal. */
44
+ requireRemovedFingerprint?: boolean;
42
45
  /** Injected clock for leases, refresh stamps and `addedAt`. */
43
46
  now?: () => number;
44
47
  /**
@@ -75,6 +78,8 @@ export type PoolLoad = {
75
78
  status: 'error';
76
79
  file: 'config' | 'state';
77
80
  reason: string;
81
+ kind?: 'snapshot-contended';
82
+ retryable?: true;
78
83
  };
79
84
  export interface PoolStore {
80
85
  /** Reads the pool and fires first-reading pulls; never writes a file itself. */
@@ -99,7 +104,9 @@ export interface PoolStore {
99
104
  * held (see `Attribution`), and an id that held `Number.MAX_SAFE_INTEGER`
100
105
  * refuses (`id-removed`) before writing.
101
106
  */
102
- add(input: AddInput, options?: RowOperationOptions): Promise<AddResult>;
107
+ add(input: AddInput, options?: AddOptions): Promise<AddResult>;
108
+ publishRoster(plan: PublishPlan, options?: PublishOptions): Promise<PublishResult>;
109
+ publication(operationId: string): Promise<PublicationReceipt | undefined>;
103
110
  /**
104
111
  * Gives a row a new credential and a new credential epoch. Since 0.6.0 the
105
112
  * row's provider state is whatever `ProviderStateCodec.onReplace` returns;
@@ -1,6 +1,7 @@
1
1
  import { recordQuota } from './attribution.js';
2
2
  import { initializePool, readPool, } from './mutate.js';
3
3
  import { updateProviderStateRow, } from './provider-state.js';
4
+ import { publication, publishRoster, } from './publication.js';
4
5
  import { PullScheduler } from './pull.js';
5
6
  import { refreshRow, } from './refresh.js';
6
7
  import { POOL_LOCK_DEFAULTS, } from './refresh-lock.js';
@@ -62,6 +63,7 @@ export function openPoolStore(options) {
62
63
  },
63
64
  removedIds: memory.removedIds,
64
65
  requireCredentialStamps: options.requireCredentialStamps === true,
66
+ requireRemovedFingerprint: options.requireRemovedFingerprint === true,
65
67
  ...(options.logger ? { logger: options.logger } : {}),
66
68
  ...(options.onStep ? { onStep: options.onStep } : {}),
67
69
  ...(options.hold ? { hold: options.hold } : {}),
@@ -98,6 +100,8 @@ export function openPoolStore(options) {
98
100
  return { status: await initializePool(ctx, input.dropKeys ?? []) };
99
101
  },
100
102
  add: (input, callOptions) => addRow(rt, input, callOptions),
103
+ publishRoster: (plan, callOptions) => publishRoster(rt, plan, callOptions),
104
+ publication: (operationId) => publication(rt, operationId),
101
105
  replace: (id, credential, input, callOptions) => replaceRow(rt, id, credential, input, callOptions),
102
106
  rotate: (id, credential, input, callOptions) => rotateRow(rt, id, credential, input, callOptions),
103
107
  updateProviderState: (id, fence, mutator, callOptions) => updateProviderStateRow(rt, id, fence, mutator, callOptions),
@@ -0,0 +1,47 @@
1
+ import type { Attribution } from './attribution.js';
2
+ import type { PoolLockSpec } from './refresh-lock.js';
3
+ import { type FailureHook, type ProtectFn } from './rows.js';
4
+ import { type StoreRuntime } from './runtime.js';
5
+ export interface PublishPlan {
6
+ operationId: string;
7
+ remove: Array<{
8
+ id: string;
9
+ attribution: Attribution;
10
+ fingerprint?: string;
11
+ }>;
12
+ finalize: Array<{
13
+ id: string;
14
+ attribution: Attribution;
15
+ reservation: string;
16
+ enabled: boolean;
17
+ disabledReason?: string;
18
+ }>;
19
+ order: string[];
20
+ }
21
+ export interface PublicationReceipt {
22
+ operationId: string;
23
+ planDigest: string;
24
+ phase: 'committed' | 'cleaned';
25
+ removed: Array<{
26
+ id: string;
27
+ credentialEpoch: number;
28
+ }>;
29
+ finalized: Array<{
30
+ id: string;
31
+ credentialEpoch: number;
32
+ reservation: string;
33
+ enabled: boolean;
34
+ }>;
35
+ }
36
+ export interface PublishOptions {
37
+ protect?: ProtectFn;
38
+ extraLocks?: PoolLockSpec[];
39
+ providerLock?: PoolLockSpec;
40
+ onFailure?: FailureHook;
41
+ }
42
+ export interface PublishResult {
43
+ outcome: 'published' | 'cleaned' | 'already-cleaned';
44
+ receipt: PublicationReceipt;
45
+ }
46
+ export declare function publication(rt: StoreRuntime, operationId: string): Promise<PublicationReceipt | undefined>;
47
+ export declare function publishRoster(rt: StoreRuntime, plan: PublishPlan, options?: PublishOptions): Promise<PublishResult>;
@@ -0,0 +1,304 @@
1
+ import { assertNotInsideHook } from './hooks.js';
2
+ import { notReadyError, readPool, runOperation, withTransaction, } from './mutate.js';
3
+ import { assertBoundRowAttribution, protectIn, validateAttribution, } from './rows.js';
4
+ import { refusal, rowLockSpec } from './runtime.js';
5
+ import { CREDENTIAL_STAMP_KEY, canonicalDigest, fingerprintOf, idProblem, isCredentialEpoch, isRecord, POOL_KEY, PROVIDER_STATE_KEY, parseStamp, rosterOf, rowLockKey, } from './schema.js';
6
+ function receiptsIn(config) {
7
+ const pool = config[POOL_KEY];
8
+ return isRecord(pool) && isRecord(pool.publications) ? pool.publications : {};
9
+ }
10
+ function receiptIn(config, operationId) {
11
+ const receipts = receiptsIn(config);
12
+ if (!Object.hasOwn(receipts, operationId))
13
+ return undefined;
14
+ const raw = receipts[operationId];
15
+ if (!isRecord(raw) ||
16
+ raw.operationId !== operationId ||
17
+ typeof raw.planDigest !== 'string' ||
18
+ !/^[a-f0-9]{64}$/.test(raw.planDigest) ||
19
+ !['committed', 'cleaned'].includes(String(raw.phase)) ||
20
+ !Array.isArray(raw.removed) ||
21
+ !Array.isArray(raw.finalized) ||
22
+ raw.removed.some((ref) => !isRecord(ref) ||
23
+ typeof ref.id !== 'string' ||
24
+ !isCredentialEpoch(ref.credentialEpoch)) ||
25
+ raw.finalized.some((ref) => !isRecord(ref) ||
26
+ typeof ref.id !== 'string' ||
27
+ !isCredentialEpoch(ref.credentialEpoch) ||
28
+ typeof ref.reservation !== 'string' ||
29
+ !ref.reservation ||
30
+ typeof ref.enabled !== 'boolean'))
31
+ throw refusal('publishRoster', operationId, 'invalid-input', 'the stored publication receipt is malformed');
32
+ return structuredClone(raw);
33
+ }
34
+ export async function publication(rt, operationId) {
35
+ const result = await readPool(rt.ctx);
36
+ if (result.status !== 'ready')
37
+ throw notReadyError(result, 'publishRoster', operationId);
38
+ return receiptIn(result.config, operationId);
39
+ }
40
+ function validatePlan(rt, plan) {
41
+ const fail = () => {
42
+ throw refusal('publishRoster', plan?.operationId ?? '', 'invalid-input', 'the publication plan is invalid');
43
+ };
44
+ if (!isRecord(plan) ||
45
+ typeof plan.operationId !== 'string' ||
46
+ !plan.operationId ||
47
+ !Array.isArray(plan.remove) ||
48
+ !Array.isArray(plan.finalize) ||
49
+ !Array.isArray(plan.order))
50
+ fail();
51
+ const ids = new Set();
52
+ for (const ref of [...plan.remove, ...plan.finalize]) {
53
+ if (!isRecord(ref) ||
54
+ typeof ref.id !== 'string' ||
55
+ idProblem(ref.id) ||
56
+ ids.has(ref.id) ||
57
+ !ref.attribution)
58
+ fail();
59
+ ids.add(ref.id);
60
+ validateAttribution('publishRoster', ref.id, ref.attribution);
61
+ if (ref.attribution.identity !== undefined &&
62
+ (typeof ref.attribution.identity !== 'string' ||
63
+ !ref.attribution.identity))
64
+ fail();
65
+ }
66
+ for (const ref of plan.remove)
67
+ if ((rt.ctx.requireRemovedFingerprint && !ref.fingerprint) ||
68
+ (ref.fingerprint !== undefined && typeof ref.fingerprint !== 'string'))
69
+ fail();
70
+ for (const ref of plan.finalize)
71
+ if (typeof ref.reservation !== 'string' ||
72
+ !ref.reservation ||
73
+ typeof ref.enabled !== 'boolean' ||
74
+ (ref.enabled
75
+ ? ref.disabledReason !== undefined
76
+ : typeof ref.disabledReason !== 'string'))
77
+ fail();
78
+ if (plan.order.some((id) => typeof id !== 'string' || idProblem(id)) ||
79
+ new Set(plan.order).size !== plan.order.length)
80
+ fail();
81
+ }
82
+ function saveReceipt(tx, receipt) {
83
+ tx.entries();
84
+ const pool = tx.config[POOL_KEY];
85
+ const receipts = { ...receiptsIn(tx.config) };
86
+ Object.defineProperty(receipts, receipt.operationId, {
87
+ value: receipt,
88
+ enumerable: true,
89
+ writable: true,
90
+ configurable: true,
91
+ });
92
+ pool.publications = receipts;
93
+ // Never forget which plan used an operation id or the actual row epochs it
94
+ // changed: otherwise an old replay could publish again against another pool.
95
+ delete pool.publicationOrder;
96
+ }
97
+ function publicationSurvivors(tx, plan, rows) {
98
+ const rosterIds = new Set();
99
+ for (const raw of rosterOf(tx.config)) {
100
+ if (!isRecord(raw) || typeof raw.id !== 'string')
101
+ continue;
102
+ if (rosterIds.has(raw.id))
103
+ throw refusal('publishRoster', plan.operationId, 'invalid-input', 'publication needs a roster of unique named rows');
104
+ rosterIds.add(raw.id);
105
+ }
106
+ const removedIds = new Set(plan.remove.map((ref) => ref.id));
107
+ const survivors = rows.filter((row) => row.invalid !== 'roster' && !removedIds.has(row.id));
108
+ if (survivors.length !== plan.order.length ||
109
+ plan.order.some((id) => !survivors.some((row) => row.id === id)) ||
110
+ survivors.some((row) => !plan.order.includes(row.id)))
111
+ throw refusal('publishRoster', plan.operationId, 'invalid-input', 'order must name exactly the surviving roster');
112
+ return survivors;
113
+ }
114
+ async function cleanup(tx, receipt) {
115
+ await tx.assertAll();
116
+ for (const ref of receipt.removed) {
117
+ const stamp = parseStamp(tx.stateAccount(ref.id)?.[CREDENTIAL_STAMP_KEY]);
118
+ // A later add uses a later epoch. Cleanup never deletes that successor.
119
+ if (stamp?.credentialEpoch === ref.credentialEpoch && !tx.rosterRow(ref.id))
120
+ tx.dropStateAccount(ref.id);
121
+ }
122
+ for (const ref of receipt.finalized) {
123
+ const account = tx.stateAccount(ref.id);
124
+ const stamp = parseStamp(account?.[CREDENTIAL_STAMP_KEY]);
125
+ if (account &&
126
+ stamp?.credentialEpoch === ref.credentialEpoch &&
127
+ stamp.staged?.reservation === ref.reservation) {
128
+ const next = {
129
+ ...account[CREDENTIAL_STAMP_KEY],
130
+ };
131
+ delete next.staged;
132
+ tx.setStateAccount(ref.id, { ...account, [CREDENTIAL_STAMP_KEY]: next });
133
+ }
134
+ }
135
+ await tx.commitState(undefined, { durable: true });
136
+ const cleaned = { ...receipt, phase: 'cleaned' };
137
+ saveReceipt(tx, cleaned);
138
+ await tx.commitConfig({ durable: true });
139
+ return cleaned;
140
+ }
141
+ export async function publishRoster(rt, plan, options = {}) {
142
+ assertNotInsideHook('publishRoster');
143
+ return runOperation(rt.ctx, 'publishRoster', plan?.operationId ?? '', options.onFailure, async (locks, progress) => {
144
+ if (!isRecord(plan) ||
145
+ typeof plan.operationId !== 'string' ||
146
+ !plan.operationId)
147
+ throw refusal('publishRoster', plan?.operationId ?? '', 'invalid-input', 'the publication needs an operation id');
148
+ plan = structuredClone(plan);
149
+ const planDigest = canonicalDigest(plan);
150
+ const named = [
151
+ ...(Array.isArray(plan.remove) ? plan.remove : []),
152
+ ...(Array.isArray(plan.finalize) ? plan.finalize : []),
153
+ ].filter((ref) => isRecord(ref) && typeof ref.id === 'string');
154
+ for (let attempt = 0;; attempt++) {
155
+ const seen = await readPool(rt.ctx);
156
+ if (seen.status !== 'ready')
157
+ throw notReadyError(seen, 'publishRoster', plan.operationId);
158
+ const keys = new Map(named.map(({ id }) => [
159
+ id,
160
+ rowLockKey(seen.rows.find((row) => row.id === id) ?? { id }),
161
+ ]));
162
+ // All row keys precede the provider lock. A refresh owns just one row
163
+ // before that lock, so it cannot wait for a second row this call holds.
164
+ for (const key of [...new Set(keys.values())].sort())
165
+ await locks.acquire(rowLockSpec(rt, { id: key }));
166
+ await locks.acquire(options.providerLock ?? rt.providerLock);
167
+ for (const extra of options.extraLocks ?? [])
168
+ await locks.acquire(extra);
169
+ const result = await withTransaction(rt.ctx, locks, progress, { operation: 'publishRoster', rowId: plan.operationId }, async (tx) => {
170
+ const rows = tx.rows();
171
+ if (named.some(({ id }) => rowLockKey(rows.find((row) => row.id === id) ?? { id }) !==
172
+ keys.get(id)))
173
+ return undefined;
174
+ const prior = receiptIn(tx.config, plan.operationId);
175
+ if (prior) {
176
+ if (prior.planDigest !== planDigest)
177
+ throw refusal('publishRoster', plan.operationId, 'publication-mismatch', 'the operation id belongs to a different publication plan');
178
+ if (prior.phase === 'cleaned')
179
+ return { outcome: 'already-cleaned', receipt: prior };
180
+ tx.markPublicationDecision();
181
+ await tx.syncConfig();
182
+ return { outcome: 'cleaned', receipt: await cleanup(tx, prior) };
183
+ }
184
+ validatePlan(rt, plan);
185
+ const survivors = publicationSurvivors(tx, plan, rows);
186
+ const removed = [];
187
+ for (const ref of plan.remove) {
188
+ tx.assertNotStaged(ref.id);
189
+ const row = rows.find((row) => row.id === ref.id);
190
+ if (!row)
191
+ throw refusal('publishRoster', ref.id, 'attribution', 'the removed row no longer exists');
192
+ assertBoundRowAttribution(ref.id, row, ref.attribution, 'publishRoster');
193
+ if (!row.credential ||
194
+ (ref.fingerprint !== undefined &&
195
+ fingerprintOf(row.credential) !== ref.fingerprint))
196
+ throw refusal('publishRoster', ref.id, 'attribution', 'the removed secret no longer matches');
197
+ removed.push(row);
198
+ }
199
+ const finalized = [];
200
+ for (const ref of plan.finalize) {
201
+ const row = rows.find((row) => row.id === ref.id);
202
+ const stamp = parseStamp(tx.stateAccount(ref.id)?.[CREDENTIAL_STAMP_KEY]);
203
+ if (!row ||
204
+ row.staged?.reservation !== ref.reservation ||
205
+ stamp?.staged?.reservation !== ref.reservation ||
206
+ row.enabled)
207
+ throw refusal('publishRoster', ref.id, 'row-staged', 'the finalized row is not disabled under this reservation');
208
+ const account = tx.stateAccount(ref.id);
209
+ const raw = tx.rosterRow(ref.id);
210
+ const storedProviderState = account?.[PROVIDER_STATE_KEY];
211
+ const fullProviderDigest = storedProviderState === undefined
212
+ ? undefined
213
+ : canonicalDigest(storedProviderState);
214
+ if (!stamp?.staged ||
215
+ stamp.staged.label !== raw?.label ||
216
+ stamp.staged.disabledReason !== row.disabledReason ||
217
+ stamp.staged.providerState !== fullProviderDigest)
218
+ throw refusal('publishRoster', ref.id, 'row-staged', 'the staged label, disabled reason or full provider state no longer matches its stamp');
219
+ assertBoundRowAttribution(ref.id, row, ref.attribution, 'publishRoster');
220
+ finalized.push(row);
221
+ }
222
+ const tornSurvivor = survivors.find((row) => row.torn);
223
+ if (tornSurvivor)
224
+ throw refusal('publishRoster', plan.operationId, 'attribution', `Row ${tornSurvivor.id} has an interrupted write; complete it with a normal store operation before publishing.`, false);
225
+ const identities = new Set();
226
+ for (const row of survivors) {
227
+ const enabled = plan.finalize.find((ref) => ref.id === row.id)?.enabled ??
228
+ row.enabled;
229
+ if (!enabled ||
230
+ row.type !== 'oauth' ||
231
+ row.identity === undefined)
232
+ continue;
233
+ if (identities.has(row.identity))
234
+ throw refusal('publishRoster', row.id, 'invalid-input', 'the final enabled roster repeats a known identity');
235
+ identities.add(row.identity);
236
+ }
237
+ for (const row of survivors) {
238
+ if (row.identity !== undefined &&
239
+ row.fingerprint !== undefined &&
240
+ survivors.some((other) => other.id !== row.id &&
241
+ other.identity !== undefined &&
242
+ other.identity !== row.identity &&
243
+ other.fingerprint === row.fingerprint))
244
+ throw refusal('publishRoster', row.id, 'attribution', 'the resulting pool gives the same secret different known identities');
245
+ }
246
+ for (const row of finalized)
247
+ if (row.identity !== undefined &&
248
+ removed.some((old) => old.identity !== undefined &&
249
+ old.identity !== row.identity &&
250
+ old.fingerprint === row.fingerprint))
251
+ throw refusal('publishRoster', row.id, 'attribution', 'the staged secret belonged to a different known identity');
252
+ await protectIn(tx, plan.operationId, options.protect);
253
+ const receipt = {
254
+ operationId: plan.operationId,
255
+ planDigest,
256
+ phase: 'committed',
257
+ removed: removed.map((row) => ({
258
+ id: row.id,
259
+ credentialEpoch: row.credentialEpoch ?? 1,
260
+ })),
261
+ finalized: plan.finalize.map((ref, index) => ({
262
+ id: ref.id,
263
+ credentialEpoch: finalized[index]?.credentialEpoch ?? 1,
264
+ reservation: ref.reservation,
265
+ enabled: ref.enabled,
266
+ })),
267
+ };
268
+ for (const ref of plan.remove)
269
+ tx.dropRosterRows(ref.id);
270
+ for (const ref of plan.finalize) {
271
+ const raw = tx.rosterRow(ref.id);
272
+ raw.enabled = ref.enabled;
273
+ const entry = { ...tx.entry(ref.id) };
274
+ delete entry.staged;
275
+ if (ref.enabled)
276
+ delete entry.disabledReason;
277
+ else
278
+ entry.disabledReason = ref.disabledReason;
279
+ tx.setEntry(ref.id, entry);
280
+ }
281
+ const preserved = tx
282
+ .roster()
283
+ .filter((raw) => !isRecord(raw) ||
284
+ typeof raw.id !== 'string' ||
285
+ rows.find((row) => row.id === raw.id)?.invalid === 'roster');
286
+ tx.config.accounts = [
287
+ ...plan.order.map((id) => tx.rosterRow(id)),
288
+ ...preserved,
289
+ ];
290
+ saveReceipt(tx, receipt);
291
+ // This durable rename is the irreversible roster decision. Everything
292
+ // after it follows only the receipt, including after a process restart.
293
+ await tx.syncState();
294
+ await tx.commitConfig({ durable: true, publicationDecision: true });
295
+ return { outcome: 'published', receipt: await cleanup(tx, receipt) };
296
+ }, { completeTorn: false });
297
+ if (result)
298
+ return result;
299
+ await locks.releaseAll();
300
+ if (attempt >= 1)
301
+ throw refusal('publishRoster', plan.operationId, 'row-key-changed', 'a named row changed lock key twice during publication', true);
302
+ }
303
+ });
304
+ }