@cortexkit/common-auth 0.11.8 → 0.13.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 (43) hide show
  1. package/README.md +2 -2
  2. package/dist/auth-menu/accounts.d.ts +11 -2
  3. package/dist/auth-menu/accounts.js +12 -26
  4. package/dist/claustrum/enrollment.d.ts +26 -0
  5. package/dist/claustrum/enrollment.js +108 -0
  6. package/dist/claustrum/index.d.ts +1 -1
  7. package/dist/claustrum/index.js +1 -1
  8. package/dist/commands/builtins.js +123 -102
  9. package/dist/commands/model.d.ts +42 -1
  10. package/dist/commands/pi.d.ts +2 -1
  11. package/dist/commands/pi.js +40 -12
  12. package/dist/commands/seam.js +3 -0
  13. package/dist/fs/atomic-write.d.ts +13 -0
  14. package/dist/fs/atomic-write.js +52 -0
  15. package/dist/opencode2/index.d.ts +2 -2
  16. package/dist/opencode2/index.js +1 -1
  17. package/dist/opencode2/integration.d.ts +45 -11
  18. package/dist/opencode2/integration.js +58 -9
  19. package/dist/quota/format.d.ts +46 -0
  20. package/dist/quota/format.js +138 -0
  21. package/dist/quota/index.d.ts +2 -0
  22. package/dist/quota/index.js +1 -0
  23. package/dist/store/attribution.js +1 -0
  24. package/dist/store/errors.d.ts +2 -2
  25. package/dist/store/identity.js +2 -0
  26. package/dist/store/index.d.ts +2 -1
  27. package/dist/store/mutate.d.ts +22 -2
  28. package/dist/store/mutate.js +140 -34
  29. package/dist/store/pool.d.ts +9 -2
  30. package/dist/store/pool.js +4 -0
  31. package/dist/store/publication.d.ts +47 -0
  32. package/dist/store/publication.js +304 -0
  33. package/dist/store/pull.js +6 -1
  34. package/dist/store/refresh.js +2 -0
  35. package/dist/store/reserved.d.ts +3 -0
  36. package/dist/store/reserved.js +13 -0
  37. package/dist/store/rows.d.ts +62 -13
  38. package/dist/store/rows.js +331 -42
  39. package/dist/store/runtime.js +13 -1
  40. package/dist/store/schema.d.ts +18 -0
  41. package/dist/store/schema.js +58 -2
  42. package/dist/store/torn.js +1 -1
  43. package/package.json +1 -1
@@ -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
+ }
@@ -50,6 +50,11 @@ export class PullScheduler {
50
50
  const progress = { writes: 0 };
51
51
  try {
52
52
  const request = await withTransaction(ctx, locks, progress, { operation: 'pull', rowId: id }, async (tx) => {
53
+ // Even a skipped capture must not repair another row on a reserved
54
+ // row's behalf. Decide reservation before pool-wide torn repair.
55
+ if (tx.reservation(id) !== undefined)
56
+ return undefined;
57
+ await tx.completeTorn();
53
58
  const row = tx.row(id);
54
59
  // A row that would pull but for its unbound credential refuses, so
55
60
  // the failure hook hears of it instead of the pull vanishing.
@@ -78,7 +83,7 @@ export class PullScheduler {
78
83
  : {}),
79
84
  reason,
80
85
  };
81
- });
86
+ }, { completeTorn: false });
82
87
  await locks.releaseAll();
83
88
  if (!request) {
84
89
  this.firedAtLoad.delete(id);
@@ -4,11 +4,13 @@ import { assertNotInsideHook, runInsideHook } from './hooks.js';
4
4
  import { IDENTITY_CONTRADICTED_REASON_PREFIX, recordIdentityIn, } from './identity.js';
5
5
  import { runOperation, withTransaction } from './mutate.js';
6
6
  import { acceptProviderState, mergedProviderState } from './provider-state.js';
7
+ import { assertNotReserved } from './reserved.js';
7
8
  import { rotateIn } from './rows.js';
8
9
  import { readRow, refusal, requireBound, rowLockSpec, } from './runtime.js';
9
10
  import { rotationStamp, rotationStampUntrusted, rowLockKey, } from './schema.js';
10
11
  import { applyTransition } from './torn.js';
11
12
  function requireRefreshable(id, row) {
13
+ assertNotReserved('refresh', id, row?.staged);
12
14
  if (!row)
13
15
  throw refusal('refresh', id, 'unknown-row', `no row ${id} in the pool`);
14
16
  if (row.invalid)
@@ -0,0 +1,3 @@
1
+ import { type PoolOperation } from './errors.js';
2
+ /** A stored marker reserves the row even when the rest of its entry is invalid. */
3
+ export declare function assertNotReserved(operation: PoolOperation, id: string, reservation: unknown): void;
@@ -0,0 +1,13 @@
1
+ import { PoolOperationError } from './errors.js';
2
+ /** A stored marker reserves the row even when the rest of its entry is invalid. */
3
+ export function assertNotReserved(operation, id, reservation) {
4
+ if (reservation !== undefined)
5
+ throw new PoolOperationError({
6
+ operation,
7
+ rowId: id,
8
+ kind: 'row-staged',
9
+ phase: operation === 'pull' ? 'pull' : 'before-first-write',
10
+ retryable: false,
11
+ message: `row ${id} is reserved for roster publication`,
12
+ });
13
+ }
@@ -4,7 +4,7 @@ import { type Transaction } from './mutate.js';
4
4
  import { type ProviderStateWrite, type RowTransitionMutator, type UpdateProviderStateResult } from './provider-state.js';
5
5
  import type { PoolLockSpec } from './refresh-lock.js';
6
6
  import { type StoreRuntime } from './runtime.js';
7
- import { type CredentialBinding, type PoolCredential, type PoolRow, type RotateCredential, type StoredCredential } from './schema.js';
7
+ import { type CredentialBinding, type PoolCredential, type PoolRow, type RotateCredential, type StagedStamp, type StoredCredential } from './schema.js';
8
8
  import { type StampedTransition } from './torn.js';
9
9
  export type FailureHook = (rowId: string, error: PoolOperationError) => void | Promise<void>;
10
10
  export interface RowOperationOptions {
@@ -20,6 +20,33 @@ export interface RowOperationOptions {
20
20
  */
21
21
  extraLocks?: readonly PoolLockSpec[];
22
22
  }
23
+ export interface RowProjection {
24
+ id: string;
25
+ type: 'oauth' | 'api';
26
+ label?: string;
27
+ enabled: boolean;
28
+ disabledReason?: string;
29
+ identity?: string;
30
+ credentialEpoch?: number;
31
+ stamp?: PoolRow['stamp'];
32
+ staged?: {
33
+ reservation: string;
34
+ };
35
+ torn?: true;
36
+ invalid?: 'roster' | 'entry';
37
+ }
38
+ export interface ProtectView {
39
+ id: string;
40
+ row?: RowProjection;
41
+ rows: RowProjection[];
42
+ config: Readonly<Record<string, unknown>>;
43
+ }
44
+ export type ProtectFn = (view: ProtectView) => string | undefined | Promise<string | undefined>;
45
+ export interface AddOptions extends RowOperationOptions {
46
+ onExisting?: 'rotate' | 'refuse' | 'stage-duplicate';
47
+ protect?: ProtectFn;
48
+ }
49
+ export declare function protectIn(tx: Transaction, id: string, protect?: ProtectFn): Promise<void>;
23
50
  /** Options of `replace` and `rotate`. Without `attribution` a call behaves as before. */
24
51
  export interface RowWriteOptions extends RowOperationOptions {
25
52
  /**
@@ -55,6 +82,10 @@ export interface RemoveView {
55
82
  state: Readonly<Record<string, unknown>>;
56
83
  }
57
84
  export interface RemoveOptions extends RowToggleOptions {
85
+ /** Exact reservation required to remove a row that is still staged. */
86
+ staged?: {
87
+ reservation: string;
88
+ };
58
89
  /**
59
90
  * The credential the removal was decided for (since 0.11.7). Checked under
60
91
  * every lock, before `protect` and before anything is written or repaired:
@@ -119,6 +150,12 @@ export interface AddInput {
119
150
  credential: PoolCredential;
120
151
  identity?: string;
121
152
  label?: string;
153
+ disabled?: {
154
+ reason: string;
155
+ };
156
+ stage?: {
157
+ reservation: string;
158
+ };
122
159
  /**
123
160
  * Provider state for the credential, written in the same state write as
124
161
  * the credential (needs the store's provider-state codec). On an `add`
@@ -141,20 +178,19 @@ export interface CredentialWriteInput {
141
178
  export type AddResult = {
142
179
  /** The row holding the credential; an existing row's id on a re-add. */
143
180
  id: string;
144
- outcome: 'added' | 'added-disabled' | 'completed' | 'rotated';
181
+ outcome: 'added' | 'added-disabled' | 'completed' | 'rotated' | 'exists';
145
182
  credential: StoredCredential;
183
+ credentialEpoch: number;
146
184
  };
147
185
  /**
148
- * Writes a credential into the state file (one write), stamped with the
149
- * credential epoch the row's entry holds in `tx` (1 without an entry) and a
150
- * binding: for a replace, the one the config is about to get (and the stamp
151
- * is marked as a replace's); for every other write, the row's config as it
152
- * stands in `tx` with the identity the operation is about to record
153
- * (`identity`, see `bindingInTx`). A rotation is the same lineage: no epoch
154
- * bump, no identity or quota change. An API key must belong to the endpoint
155
- * the row holds in `tx` (see `onRowEndpoint`).
186
+ * Build the credential and its state entry without writing. The stamp records
187
+ * the credential's epoch, identity and API endpoint so readers can verify that
188
+ * they belong together. A replacement records the new epoch and account; a
189
+ * rotation keeps the current epoch, account and quota. Pending writes are read
190
+ * as completed when choosing those fields, even while disk config is behind.
191
+ * Endpoint checks and provider-state encoding finish here, before any repair.
156
192
  */
157
- export declare function rotateIn(rt: StoreRuntime, tx: Transaction, id: string, given: RotateCredential, extra?: {
193
+ declare function planRotationIn(rt: StoreRuntime, tx: Transaction, id: string, given: RotateCredential, extra?: {
158
194
  stamp?: number;
159
195
  clearErrors?: boolean;
160
196
  binding?: CredentialBinding;
@@ -162,8 +198,17 @@ export declare function rotateIn(rt: StoreRuntime, tx: Transaction, id: string,
162
198
  providerState?: ProviderStateWrite;
163
199
  /** Config transition persisted with the successor credential for crash recovery. */
164
200
  transition?: StampedTransition;
165
- }): Promise<StoredCredential>;
166
- export declare function addRow(rt: StoreRuntime, input: AddInput, options?: RowOperationOptions): Promise<AddResult>;
201
+ staged?: StagedStamp;
202
+ }): {
203
+ stored: StoredCredential;
204
+ account: Record<string, unknown>;
205
+ };
206
+ /** Validate the endpoint and encode provider state and its stamp before committing state. */
207
+ export declare function rotateIn(rt: StoreRuntime, tx: Transaction, id: string, given: RotateCredential, extra?: Parameters<typeof planRotationIn>[4]): Promise<StoredCredential>;
208
+ export declare function validateAttribution(operation: PoolOperationError['operation'], id: string, fence: Attribution | undefined): void;
209
+ /** Exact recorded identity, including absence, is part of a credential fence. */
210
+ export declare function assertRowAttribution(operation: PoolOperationError['operation'], id: string, row: PoolRow | undefined, fence: Attribution): void;
211
+ export declare function addRow(rt: StoreRuntime, input: AddInput, options?: AddOptions): Promise<AddResult>;
167
212
  export declare function replaceRow(rt: StoreRuntime, id: string, credential: PoolCredential, input?: CredentialWriteInput, options?: RowWriteOptions): Promise<{
168
213
  id: string;
169
214
  credential: StoredCredential;
@@ -178,6 +223,7 @@ export declare function rotateRow(rt: StoreRuntime, id: string, credential: Rota
178
223
  * `attribution` nor `providerState` behaves exactly as it did before 0.7.0.
179
224
  */
180
225
  export interface RowTransitionOptions extends RowToggleOptions {
226
+ protect?: ProtectFn;
181
227
  /**
182
228
  * The credential epoch and recorded identity the caller's evidence for the
183
229
  * transition was obtained under (as `recordQuota`'s attribution: an
@@ -239,6 +285,8 @@ export declare function enableRow(rt: StoreRuntime, id: string, options?: RowTra
239
285
  * past it (see `nextAddEpochIn`).
240
286
  */
241
287
  export declare function removeRow(rt: StoreRuntime, id: string, options?: RemoveOptions): Promise<RemoveResult>;
288
+ /** An attributed removal of a roster row: bound, not torn, same epoch and identity. */
289
+ export declare function assertBoundRowAttribution(id: string, row: PoolRow, fence: Attribution, operation?: PoolOperationError['operation']): void;
242
290
  /**
243
291
  * Sets the roster order in one config write. `ids` must name every roster id
244
292
  * exactly once; anything else refuses (`invalid-order`) before writing. The
@@ -262,3 +310,4 @@ export declare function recordRowIdentity(rt: StoreRuntime, id: string, identity
262
310
  id: string;
263
311
  disabled: string[];
264
312
  }>;
313
+ export {};