@wtfalch/keys 0.7.0 → 0.12.1

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 (59) hide show
  1. package/README.md +349 -7
  2. package/dist/held/index.d.ts +116 -6
  3. package/dist/held/index.js +247 -25
  4. package/dist/held/schema.d.ts +17 -0
  5. package/dist/held/schema.js +12 -0
  6. package/dist/held/shred.d.ts +6 -0
  7. package/dist/held/shred.js +6 -0
  8. package/dist/held-edge/index.d.ts +17 -2
  9. package/dist/held-edge/index.js +51 -9
  10. package/dist/host/audit-endpoint.js +2 -8
  11. package/dist/host/company-registrar-keys.d.ts +106 -0
  12. package/dist/host/company-registrar-keys.js +211 -0
  13. package/dist/host/events.d.ts +19 -3
  14. package/dist/host/events.js +55 -20
  15. package/dist/host/index.d.ts +15 -1
  16. package/dist/host/index.js +15 -1
  17. package/dist/host/native-build.d.ts +126 -0
  18. package/dist/host/native-build.js +322 -0
  19. package/dist/host/registrar.d.ts +87 -0
  20. package/dist/host/registrar.js +284 -0
  21. package/dist/host/rotation-sweep.d.ts +56 -0
  22. package/dist/host/rotation-sweep.js +89 -0
  23. package/dist/issued/encoding.d.ts +4 -0
  24. package/dist/issued/encoding.js +22 -0
  25. package/dist/issued/index.d.ts +148 -7
  26. package/dist/issued/index.js +320 -34
  27. package/dist/issued/resign.d.ts +16 -0
  28. package/dist/issued/resign.js +55 -2
  29. package/dist/issued/tables.d.ts +38 -0
  30. package/dist/issued/tables.js +6 -0
  31. package/dist/issued/verify.d.ts +14 -3
  32. package/dist/issued/verify.js +10 -3
  33. package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
  34. package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
  35. package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
  36. package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
  37. package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
  38. package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
  39. package/dist/service/body.d.ts +21 -0
  40. package/dist/service/body.js +128 -0
  41. package/dist/service/errors.d.ts +24 -0
  42. package/dist/service/errors.js +89 -0
  43. package/dist/service/handler.d.ts +35 -0
  44. package/dist/service/handler.js +328 -0
  45. package/dist/service/index.d.ts +7 -0
  46. package/dist/service/index.js +7 -0
  47. package/dist/service/policy.d.ts +130 -0
  48. package/dist/service/policy.js +123 -0
  49. package/dist/service/timeout.d.ts +6 -0
  50. package/dist/service/timeout.js +34 -0
  51. package/dist/testing/index.d.ts +3 -0
  52. package/dist/testing/index.js +3 -0
  53. package/dist/webhooks.d.ts +40 -17
  54. package/dist/webhooks.js +70 -26
  55. package/dist/worker-contract.d.ts +43 -6
  56. package/dist/worker-contract.js +37 -0
  57. package/dist/worker.d.ts +1 -1
  58. package/dist/worker.js +7 -28
  59. package/package.json +21 -3
@@ -1,18 +1,91 @@
1
1
  import { and, eq, inArray, isNull } from 'drizzle-orm';
2
2
  import { sql } from 'drizzle-orm';
3
+ import { ID_PATTERN, WORKER_ERROR_CODES } from '../worker-contract.js';
3
4
  import { fromBase64Url, toBase64Url } from './codec.js';
4
- import { canonicalJson } from './encoding.js';
5
+ import { canonicalJson, containsLoneSurrogate } from './encoding.js';
5
6
  import { keyPrefixOf, mintSecret, rotateSecret, secretMatches } from './secret.js';
6
7
  import { keysIssuedCredentials } from './tables.js';
7
8
  import { verifyIssuedRowSignature } from './verify.js';
8
9
  export { ID_PATTERN, SIGNED_PREFIX, } from '../worker-contract.js';
9
10
  export { createPostgresRateLimiter, } from './ratelimit.js';
10
- export { createSigningGenerationMigrator, MAX_RESIGN_BATCH_SIZE, } from './resign.js';
11
+ export { createSigningGenerationMigrator, MAX_RESIGN_BATCH_SIZE, RESIGN_GENERATION_REFUSAL_REASONS, } from './resign.js';
12
+ export const CREDENTIAL_PURPOSES = [
13
+ 'ordinary',
14
+ 'company_root',
15
+ 'platform_master',
16
+ ];
17
+ function asPurpose(value) {
18
+ return value !== null && CREDENTIAL_PURPOSES.includes(value)
19
+ ? value
20
+ : null;
21
+ }
22
+ /**
23
+ * Closed unions: each has a constant listing its members, pinned by `src/exports.test.ts`.
24
+ * Adding a member is a major change after 1.0.0. A union that embeds `WorkerErrorCode`
25
+ * spreads `WORKER_ERROR_CODES` into its list.
26
+ */
27
+ export { WORKER_ERROR_CODES } from '../worker-contract.js';
28
+ /** Every member of `IssueRefusalReason`. */
29
+ export const ISSUE_REFUSAL_REASONS = [
30
+ 'expires_at_required',
31
+ 'expires_at_past',
32
+ 'minter_not_found',
33
+ 'minter_revoked',
34
+ 'minter_expired',
35
+ 'expires_after_minter',
36
+ 'purpose_not_allowed',
37
+ 'organisation_mismatch',
38
+ 'idempotency_conflict',
39
+ 'idempotent_row_revoked',
40
+ 'idempotent_row_expired',
41
+ 'environment_mismatch',
42
+ 'bad_worker_signature',
43
+ ...WORKER_ERROR_CODES,
44
+ ];
45
+ /** Every member of `CheckRefusalReason`. */
46
+ export const CHECK_REFUSAL_REASONS = [
47
+ 'not_found',
48
+ 'signature_invalid',
49
+ 'revoked',
50
+ 'expired',
51
+ 'secret_mismatch',
52
+ 'rate_limited',
53
+ ];
54
+ /** Every member of `RotateRefusalReason`. */
55
+ export const ROTATE_REFUSAL_REASONS = [
56
+ 'signature_invalid',
57
+ 'conflict',
58
+ 'not_found',
59
+ 'revoked',
60
+ 'minter_not_found',
61
+ 'minter_revoked',
62
+ 'minter_expired',
63
+ 'bad_worker_signature',
64
+ ...WORKER_ERROR_CODES,
65
+ ];
66
+ /** Every reason `classify` refuses. Adding one is a major change after 1.0.0. */
67
+ export const CLASSIFY_REFUSAL_REASONS = ['bad_request', 'not_found', 'already_classified'];
68
+ /** Every reason `revokeForCompany` refuses. Adding one is a major change after 1.0.0. */
69
+ export const REVOKE_FOR_COMPANY_REFUSAL_REASONS = [
70
+ 'protected_credential',
71
+ 'purpose_unknown',
72
+ ];
73
+ function workerRefusal(error) {
74
+ return error.retryAfterMs === undefined
75
+ ? { ok: false, reason: error.code }
76
+ : { ok: false, reason: error.code, retryAfterMs: error.retryAfterMs };
77
+ }
11
78
  function rowsOf(result) {
12
79
  if (Array.isArray(result))
13
80
  return result;
14
81
  return (result.rows ?? []);
15
82
  }
83
+ const ENVIRONMENTS = ['live', 'test'];
84
+ const MAX_KEY_PREFIX_LENGTH = 64;
85
+ /** The rate-limit id every `not_found` key is charged to. With an organisation, the id is `<this>:<organisation>`. */
86
+ export const UNKNOWN_KEY_BUCKET = 'unknown-key';
87
+ // A JSON NUL escape (an even number of backslashes before the one that starts it); jsonb refuses it.
88
+ const JSON_NUL = /(?<!\\)(?:\\\\)*\\u0000/;
16
89
  function randomId() {
17
90
  return crypto.randomUUID();
18
91
  }
@@ -29,7 +102,7 @@ function toSignableRow(row) {
29
102
  };
30
103
  }
31
104
  export function createCredentialIssuer(options) {
32
- const { db, worker, credential, verifyKeys, audit, prefix, rateLimiter } = options;
105
+ const { db, worker, credential, verifyKeys, previousGenerationId, audit, onAuditError, auditInTransaction, prefix, rateLimiter, } = options;
33
106
  const now = options.now ?? (() => Date.now());
34
107
  const table = keysIssuedCredentials;
35
108
  async function loadById(id, handle = db) {
@@ -40,10 +113,34 @@ export function createCredentialIssuer(options) {
40
113
  const [row] = await db.select().from(table).where(eq(table.keyPrefix, keyPrefix)).limit(1);
41
114
  return row;
42
115
  }
43
- async function loadByIdempotencyKey(key) {
44
- const [row] = await db.select().from(table).where(eq(table.idempotencyKey, key)).limit(1);
116
+ // The unique index is on (coalesce(issued_by_id, ''), idempotency_key): a key
117
+ // belongs to one minter, so another minter's row is never a replay.
118
+ async function loadByIdempotencyKey(minter, key, handle = db) {
119
+ const [row] = await handle
120
+ .select()
121
+ .from(table)
122
+ .where(and(eq(table.idempotencyKey, key), sql `coalesce(${table.issuedById}, '') = ${minter ?? ''}`))
123
+ .limit(1);
45
124
  return row;
46
125
  }
126
+ const isStale = (row) => row.revokedAt !== null || row.expiresAt <= now();
127
+ /** What a request answers when its key is already held; `null` means a stale row `replaceStale` may take over. */
128
+ function replayOf(existing, wanted) {
129
+ if (wanted.replaceStale && isStale(existing))
130
+ return null;
131
+ // A row older than the purpose field is unknown; it only answers a request for the default.
132
+ const samePurpose = (existing.purpose ?? 'ordinary') === wanted.purpose;
133
+ if (existing.environment !== wanted.environment ||
134
+ !samePurpose ||
135
+ canonicalJson(existing.grants) !== canonicalJson(wanted.grants)) {
136
+ return { ok: false, reason: 'idempotency_conflict' };
137
+ }
138
+ if (existing.revokedAt !== null)
139
+ return { ok: false, reason: 'idempotent_row_revoked' };
140
+ if (existing.expiresAt <= now())
141
+ return { ok: false, reason: 'idempotent_row_expired' };
142
+ return { ok: true, id: existing.id, keyPrefix: existing.keyPrefix, secret: null };
143
+ }
47
144
  /** Every descendant of `id`, `id` itself included. Mirrors valet's `subtreeOf` (`self-service.ts`). */
48
145
  async function subtreeIds(id, handle) {
49
146
  const result = await handle.execute(sql `
@@ -64,15 +161,49 @@ export function createCredentialIssuer(options) {
64
161
  async function lockLifecycle(tx) {
65
162
  await tx.execute(sql `select pg_advisory_xact_lock(1801812339, 1)`);
66
163
  }
164
+ // Fails closed when no key is configured.
165
+ async function workerSignatureGenuine(row, signature) {
166
+ if (!verifyKeys?.[0])
167
+ return false;
168
+ return verifyIssuedRowSignature(row, signature, verifyKeys);
169
+ }
170
+ function generationLabel(row) {
171
+ return previousGenerationId === undefined
172
+ ? undefined
173
+ : { rowGenerationId: row.signingGenerationId, previousGenerationId };
174
+ }
67
175
  async function emit(event) {
68
- await audit?.(event);
176
+ try {
177
+ await audit?.(event);
178
+ }
179
+ catch (err) {
180
+ reportAuditError(event, err, onAuditError);
181
+ }
69
182
  }
70
183
  async function issue(request, attempt = 0) {
184
+ const purpose = request.purpose ?? 'ordinary';
185
+ if (!CREDENTIAL_PURPOSES.includes(purpose) ||
186
+ (request.organisationId !== undefined &&
187
+ !(typeof request.organisationId === 'string' && ID_PATTERN.test(request.organisationId)))) {
188
+ return { ok: false, reason: 'bad_request' };
189
+ }
190
+ if (request.minter !== null && purpose !== 'ordinary') {
191
+ return { ok: false, reason: 'purpose_not_allowed' };
192
+ }
193
+ const environment = request.environment ?? 'live';
194
+ const wanted = {
195
+ grants: request.grants,
196
+ environment,
197
+ purpose,
198
+ replaceStale: request.replaceStale === true,
199
+ };
200
+ let stale;
71
201
  if (request.idempotencyKey) {
72
- const existing = await loadByIdempotencyKey(request.idempotencyKey);
73
- if (existing) {
74
- return { ok: true, id: existing.id, keyPrefix: existing.keyPrefix, secret: null };
75
- }
202
+ const existing = await loadByIdempotencyKey(request.minter, request.idempotencyKey);
203
+ const replay = existing ? replayOf(existing, wanted) : null;
204
+ if (replay)
205
+ return replay;
206
+ stale = existing;
76
207
  }
77
208
  if (typeof request.expiresAt !== 'number' || !Number.isFinite(request.expiresAt)) {
78
209
  return { ok: false, reason: 'expires_at_required' };
@@ -80,7 +211,7 @@ export function createCredentialIssuer(options) {
80
211
  if (request.expiresAt <= now()) {
81
212
  return { ok: false, reason: 'expires_at_past' };
82
213
  }
83
- const environment = request.environment ?? 'live';
214
+ let organisationId = request.organisationId ?? null;
84
215
  let minterAttestation = null;
85
216
  if (request.minter !== null) {
86
217
  const minterRow = await loadById(request.minter);
@@ -93,11 +224,19 @@ export function createCredentialIssuer(options) {
93
224
  return { ok: false, reason: 'minter_revoked' };
94
225
  if (minterRow.expiresAt <= now())
95
226
  return { ok: false, reason: 'minter_expired' };
227
+ if (request.expiresAt > minterRow.expiresAt) {
228
+ return { ok: false, reason: 'expires_after_minter' };
229
+ }
96
230
  // #47: a test key can only mint a test key, a live key only a live
97
231
  // one -- the pairing the issue asked for, not just a label.
98
232
  if (minterRow.environment !== environment) {
99
233
  return { ok: false, reason: 'environment_mismatch' };
100
234
  }
235
+ if (request.organisationId !== undefined &&
236
+ request.organisationId !== minterRow.organisationId) {
237
+ return { ok: false, reason: 'organisation_mismatch' };
238
+ }
239
+ organisationId = minterRow.organisationId;
101
240
  minterAttestation = {
102
241
  row: toSignableRow(minterRow),
103
242
  signature: fromBase64Url(minterRow.signature),
@@ -105,6 +244,12 @@ export function createCredentialIssuer(options) {
105
244
  }
106
245
  const id = randomId();
107
246
  const minted = mintSecret(prefix);
247
+ if (!ENVIRONMENTS.includes(environment) ||
248
+ minted.keyPrefix.length > MAX_KEY_PREFIX_LENGTH ||
249
+ JSON_NUL.test(JSON.stringify(request.grants)) ||
250
+ containsLoneSurrogate(request.grants)) {
251
+ return { ok: false, reason: 'bad_request' };
252
+ }
108
253
  const candidate = {
109
254
  id,
110
255
  issuedById: request.minter,
@@ -123,26 +268,38 @@ export function createCredentialIssuer(options) {
123
268
  minter: minterAttestation,
124
269
  });
125
270
  if (!result.ok)
126
- return { ok: false, reason: result.error.code };
271
+ return workerRefusal(result.error);
272
+ if (!(await workerSignatureGenuine(candidate, result.signature))) {
273
+ return { ok: false, reason: 'bad_worker_signature' };
274
+ }
127
275
  try {
128
- const refusal = await db.transaction(async (tx) => {
276
+ const early = await db.transaction(async (tx) => {
129
277
  await lockLifecycle(tx);
130
278
  if (request.minter !== null) {
131
279
  const parent = await loadById(request.minter, tx);
132
280
  if (!parent)
133
- return 'minter_not_found';
281
+ return { ok: false, reason: 'minter_not_found' };
134
282
  if (parent.revokedAt !== null)
135
- return 'minter_revoked';
283
+ return { ok: false, reason: 'minter_revoked' };
136
284
  if (parent.expiresAt <= now())
137
- return 'minter_expired';
138
- if (parent.environment !== environment)
139
- return 'environment_mismatch';
285
+ return { ok: false, reason: 'minter_expired' };
286
+ if (parent.environment !== environment) {
287
+ return { ok: false, reason: 'environment_mismatch' };
288
+ }
140
289
  if (!minterAttestation ||
141
290
  parent.signature !== toBase64Url(minterAttestation.signature) ||
142
291
  canonicalJson(toSignableRow(parent)) !== canonicalJson(minterAttestation.row)) {
143
- return 'bad_minter_signature';
292
+ return { ok: false, reason: 'bad_minter_signature' };
144
293
  }
145
294
  }
295
+ if (stale && request.idempotencyKey) {
296
+ // The old row stays, with its key renamed, in the same transaction
297
+ // as the insert: if the insert fails, the old key is still in place.
298
+ await tx
299
+ .update(table)
300
+ .set({ idempotencyKey: `${request.idempotencyKey}:superseded:${stale.id}` })
301
+ .where(and(eq(table.id, stale.id), eq(table.idempotencyKey, request.idempotencyKey)));
302
+ }
146
303
  await tx.insert(table).values({
147
304
  id,
148
305
  issuedById: candidate.issuedById,
@@ -154,20 +311,28 @@ export function createCredentialIssuer(options) {
154
311
  signingGenerationId: result.generationId,
155
312
  idempotencyKey: request.idempotencyKey ?? null,
156
313
  environment,
314
+ purpose,
315
+ organisationId,
316
+ });
317
+ await auditInTransaction?.(tx, {
318
+ name: 'credential.minted',
319
+ credentialId: id,
320
+ requestId,
321
+ at: now(),
157
322
  });
158
323
  return null;
159
324
  });
160
- if (refusal)
161
- return { ok: false, reason: refusal };
325
+ if (early)
326
+ return early;
162
327
  }
163
328
  catch (err) {
164
- // A concurrent issue() with the same idempotencyKey won the race: the
165
- // partial unique index refused this insert. Replay rather than throw.
329
+ // A concurrent issue() with the same key won the race: the unique index
330
+ // refused this insert. Answer from the row that won.
166
331
  if (request.idempotencyKey && isUniqueViolation(err)) {
167
- const existing = await loadByIdempotencyKey(request.idempotencyKey);
168
- if (existing) {
169
- return { ok: true, id: existing.id, keyPrefix: existing.keyPrefix, secret: null };
170
- }
332
+ const winner = await loadByIdempotencyKey(request.minter, request.idempotencyKey);
333
+ const replay = winner ? replayOf(winner, wanted) : null;
334
+ if (replay)
335
+ return replay;
171
336
  }
172
337
  if (attempt < 3 && isUniqueViolation(err) && (await loadByPrefix(candidate.keyPrefix))) {
173
338
  return issue(request, attempt + 1);
@@ -177,13 +342,33 @@ export function createCredentialIssuer(options) {
177
342
  await emit({ name: 'credential.minted', credentialId: id, requestId, at: now() });
178
343
  return { ok: true, id, keyPrefix: candidate.keyPrefix, secret: minted.secret };
179
344
  }
180
- async function check(secret) {
345
+ // A key with this issuer's prefix that matches no row is charged to one shared bucket, so a flood of
346
+ // guesses is limited without a row to key the limit on. With an organisation the bucket is that
347
+ // organisation's own, so one organisation's guesses cannot limit another's. A known row's
348
+ // traffic never reaches this bucket.
349
+ async function unknownKey(organisationId) {
350
+ if (rateLimiter) {
351
+ const bucket = organisationId === undefined
352
+ ? UNKNOWN_KEY_BUCKET
353
+ : `${UNKNOWN_KEY_BUCKET}:${organisationId}`;
354
+ const limit = await rateLimiter.check(bucket, now());
355
+ if (limit.limited) {
356
+ return { ok: false, reason: 'rate_limited', retryAfterMs: limit.retryAfterMs };
357
+ }
358
+ }
359
+ return { ok: false, reason: 'not_found' };
360
+ }
361
+ async function check(secret, checkOptions = {}) {
181
362
  const keyPrefix = keyPrefixOf(secret, prefix);
182
363
  if (keyPrefix === null)
183
364
  return { ok: false, reason: 'not_found' };
184
365
  const row = await loadByPrefix(keyPrefix);
185
366
  if (!row)
186
- return { ok: false, reason: 'not_found' };
367
+ return unknownKey(checkOptions.organisationId);
368
+ if (checkOptions.organisationId !== undefined &&
369
+ row.organisationId !== checkOptions.organisationId) {
370
+ return unknownKey(checkOptions.organisationId);
371
+ }
187
372
  // #45: spent on every attempt against a known credential, matched
188
373
  // secret or not -- an unlimited number of wrong guesses against an
189
374
  // identified row would otherwise let an attacker brute-force it past
@@ -206,7 +391,7 @@ export function createCredentialIssuer(options) {
206
391
  // check over the row's CURRENT fields refuses a row a raw UPDATE
207
392
  // tampered with, whatever that tamper changed.
208
393
  const signable = toSignableRow(row);
209
- const genuine = await verifyIssuedRowSignature(signable, fromBase64Url(row.signature), verifyKeys);
394
+ const genuine = await verifyIssuedRowSignature(signable, fromBase64Url(row.signature), verifyKeys, generationLabel(row));
210
395
  if (!genuine)
211
396
  return { ok: false, reason: 'signature_invalid' };
212
397
  if (row.revokedAt !== null)
@@ -240,6 +425,8 @@ export function createCredentialIssuer(options) {
240
425
  issuedById: row.issuedById,
241
426
  grants: row.grants,
242
427
  environment: row.environment,
428
+ purpose: asPurpose(row.purpose),
429
+ organisationId: row.organisationId,
243
430
  };
244
431
  }
245
432
  async function rotate(id, opts) {
@@ -248,7 +435,7 @@ export function createCredentialIssuer(options) {
248
435
  return { ok: false, reason: 'not_found' };
249
436
  if (row.revokedAt !== null)
250
437
  return { ok: false, reason: 'revoked' };
251
- if (!(await verifyIssuedRowSignature(toSignableRow(row), fromBase64Url(row.signature), verifyKeys))) {
438
+ if (!(await verifyIssuedRowSignature(toSignableRow(row), fromBase64Url(row.signature), verifyKeys, generationLabel(row)))) {
252
439
  return { ok: false, reason: 'signature_invalid' };
253
440
  }
254
441
  if (!Number.isSafeInteger(opts.graceMs) ||
@@ -291,7 +478,10 @@ export function createCredentialIssuer(options) {
291
478
  minter: minterAttestation,
292
479
  });
293
480
  if (!result.ok)
294
- return { ok: false, reason: result.error.code };
481
+ return workerRefusal(result.error);
482
+ if (!(await workerSignatureGenuine(candidate, result.signature))) {
483
+ return { ok: false, reason: 'bad_worker_signature' };
484
+ }
295
485
  const refusal = await db.transaction(async (tx) => {
296
486
  await lockLifecycle(tx);
297
487
  const [current] = await tx.select().from(table).where(eq(table.id, id)).for('update');
@@ -322,6 +512,12 @@ export function createCredentialIssuer(options) {
322
512
  signingGenerationId: result.generationId,
323
513
  })
324
514
  .where(eq(table.id, id));
515
+ await auditInTransaction?.(tx, {
516
+ name: 'credential.rotated',
517
+ credentialId: id,
518
+ requestId,
519
+ at: now(),
520
+ });
325
521
  return null;
326
522
  });
327
523
  if (refusal)
@@ -335,11 +531,19 @@ export function createCredentialIssuer(options) {
335
531
  const ids = (opts.cascade ?? true) ? await subtreeIds(id, tx) : [id];
336
532
  if (ids.length === 0)
337
533
  return [];
338
- return tx
534
+ const revoked = await tx
339
535
  .update(table)
340
536
  .set({ revokedAt: new Date(now()) })
341
537
  .where(and(inArray(table.id, ids), isNull(table.revokedAt)))
342
538
  .returning({ id: table.id });
539
+ for (const r of revoked) {
540
+ await auditInTransaction?.(tx, {
541
+ name: 'credential.revoked',
542
+ credentialId: r.id,
543
+ at: now(),
544
+ });
545
+ }
546
+ return revoked;
343
547
  });
344
548
  for (const r of revokedRows) {
345
549
  await emit({ name: 'credential.revoked', credentialId: r.id, at: now() });
@@ -362,12 +566,94 @@ export function createCredentialIssuer(options) {
362
566
  expiresAt: row.expiresAt,
363
567
  revokedAt: row.revokedAt ? row.revokedAt.getTime() : null,
364
568
  environment: row.environment,
569
+ purpose: asPurpose(row.purpose),
570
+ organisationId: row.organisationId,
365
571
  });
366
572
  currentId = row.issuedById;
367
573
  }
368
574
  return chain;
369
575
  }
370
- return { issue, check, rotate, revoke, lineageOf };
576
+ async function revokeForCompany(id, opts = {}) {
577
+ const outcome = await db.transaction(async (tx) => {
578
+ await lockLifecycle(tx);
579
+ const ids = (opts.cascade ?? true) ? await subtreeIds(id, tx) : [id];
580
+ if (ids.length === 0)
581
+ return { ok: true, revoked: [] };
582
+ const live = await tx
583
+ .select({ id: table.id, purpose: table.purpose, organisationId: table.organisationId })
584
+ .from(table)
585
+ .where(and(inArray(table.id, ids), isNull(table.revokedAt)));
586
+ if (live.some((r) => r.purpose === 'company_root' || r.purpose === 'platform_master')) {
587
+ return { ok: false, reason: 'protected_credential' };
588
+ }
589
+ if (opts.organisationId !== undefined &&
590
+ live.some((r) => r.organisationId !== opts.organisationId)) {
591
+ return { ok: false, reason: 'protected_credential' };
592
+ }
593
+ if (live.some((r) => asPurpose(r.purpose) === null)) {
594
+ return { ok: false, reason: 'purpose_unknown' };
595
+ }
596
+ const rows = await tx
597
+ .update(table)
598
+ .set({ revokedAt: new Date(now()) })
599
+ .where(and(inArray(table.id, ids), isNull(table.revokedAt)))
600
+ .returning({ id: table.id });
601
+ for (const r of rows) {
602
+ await auditInTransaction?.(tx, {
603
+ name: 'credential.revoked',
604
+ credentialId: r.id,
605
+ at: now(),
606
+ });
607
+ }
608
+ return { ok: true, revoked: rows.map((r) => r.id) };
609
+ });
610
+ if (!outcome.ok)
611
+ return outcome;
612
+ for (const revokedId of outcome.revoked) {
613
+ await emit({ name: 'credential.revoked', credentialId: revokedId, at: now() });
614
+ }
615
+ return outcome;
616
+ }
617
+ async function classify(id, classification) {
618
+ if (!CREDENTIAL_PURPOSES.includes(classification.purpose) ||
619
+ (classification.organisationId !== undefined &&
620
+ !ID_PATTERN.test(classification.organisationId))) {
621
+ return { ok: false, reason: 'bad_request' };
622
+ }
623
+ return db.transaction(async (tx) => {
624
+ await lockLifecycle(tx);
625
+ const rows = await tx
626
+ .update(table)
627
+ .set({
628
+ purpose: classification.purpose,
629
+ organisationId: classification.organisationId ?? null,
630
+ })
631
+ .where(and(eq(table.id, id), isNull(table.purpose)))
632
+ .returning({ id: table.id });
633
+ if (rows.length === 1)
634
+ return { ok: true };
635
+ return (await loadById(id, tx))
636
+ ? { ok: false, reason: 'already_classified' }
637
+ : { ok: false, reason: 'not_found' };
638
+ });
639
+ }
640
+ return { issue, check, rotate, revoke, lineageOf, revokeForCompany, classify };
641
+ }
642
+ /** Logs a fixed line with the event name and the error's name; never the error's message or value. */
643
+ function reportAuditError(event, error, onAuditError) {
644
+ if (onAuditError) {
645
+ try {
646
+ onAuditError(event, error);
647
+ }
648
+ catch (hookError) {
649
+ console.error(`keys: onAuditError threw for ${event.name}: ${errorName(hookError)}`);
650
+ }
651
+ return;
652
+ }
653
+ console.error(`keys: audit failed for ${event.name}: ${errorName(error)}`);
654
+ }
655
+ function errorName(error) {
656
+ return error instanceof Error ? error.name : typeof error;
371
657
  }
372
658
  function isUniqueViolation(err) {
373
659
  if (!err || typeof err !== 'object')
@@ -28,6 +28,8 @@ export interface ResignGenerationBatchRequest {
28
28
  readonly cursor?: SigningGenerationCursor | null;
29
29
  readonly limit: number;
30
30
  }
31
+ /** Every member of `ResignGenerationRefusalReason`. */
32
+ export declare const RESIGN_GENERATION_REFUSAL_REASONS: readonly ["credential_invalid", "credential_expired", "credential_revoked", "grant_missing", "rate_limited", "bad_request", "aad_mismatch", "unknown_generation", "bad_minter_signature", "minter_expired", "minter_revoked", "minter_exceeded", "lineage_mismatch", "bad_old_signature", "unlogged_row", "not_in_lineage", "unreachable", "conflict", "generation_mismatch", "target_signature_invalid"];
31
33
  export type ResignGenerationRefusalReason = WorkerErrorCode | 'conflict' | 'generation_mismatch' | 'target_signature_invalid';
32
34
  interface ResignGenerationProgress {
33
35
  /** Rows durably published during this call, in cursor order. */
@@ -50,6 +52,20 @@ export interface SigningGenerationMigrator {
50
52
  resignBatch(request: ResignGenerationBatchRequest): Promise<ResignGenerationBatchResult>;
51
53
  /** An observation for rollout checks; it is not, by itself, proof that retirement is safe. */
52
54
  countGenerationRows(generationId: string): Promise<number>;
55
+ /** Every row not labelled `generationId`, revoked or expired or not. Counted from the stored labels. */
56
+ countNotGeneration(generationId: string): Promise<number>;
57
+ /** The distinct generation ids the rows carry. */
58
+ generationsInUse(): Promise<string[]>;
59
+ /**
60
+ * How many live rows (not revoked, not expired) carry `previousGenerationId`
61
+ * and would stop verifying if the `previous` key were dropped.
62
+ * `retirable` is true only when `blocking` is 0. A count is an observation:
63
+ * a writer that signs under the old generation after it is taken can add rows.
64
+ */
65
+ retirementCheck(previousGenerationId: string): Promise<{
66
+ readonly retirable: boolean;
67
+ readonly blocking: number;
68
+ }>;
53
69
  }
54
70
  export declare function createSigningGenerationMigrator<TGrant>(options: CreateSigningGenerationMigratorOptions<TGrant>): SigningGenerationMigrator;
55
71
  export {};
@@ -1,11 +1,21 @@
1
1
  import { and, asc, eq, gt, sql } from 'drizzle-orm';
2
- import { ID_PATTERN, } from '../worker-contract.js';
2
+ import { ID_PATTERN, WORKER_ERROR_CODES, } from '../worker-contract.js';
3
3
  import { fromBase64Url, toBase64Url } from './codec.js';
4
4
  import { canonicalJson } from './encoding.js';
5
5
  import { keysIssuedCredentials } from './tables.js';
6
6
  import { verifyIssuedRowSignature } from './verify.js';
7
7
  /** The hard ceiling keeps one operator call within the Worker's documented request budget. */
8
8
  export const MAX_RESIGN_BATCH_SIZE = 100;
9
+ /** Every member of `ResignGenerationRefusalReason`. */
10
+ export const RESIGN_GENERATION_REFUSAL_REASONS = [
11
+ ...WORKER_ERROR_CODES,
12
+ 'conflict',
13
+ 'generation_mismatch',
14
+ 'target_signature_invalid',
15
+ ];
16
+ function rowsOf(result) {
17
+ return Array.isArray(result) ? result : (result.rows ?? []);
18
+ }
9
19
  function toSignableRow(row) {
10
20
  return {
11
21
  id: row.id,
@@ -170,5 +180,48 @@ export function createSigningGenerationMigrator(options) {
170
180
  : (result.rows ?? []);
171
181
  return Number(rows[0]?.count ?? 0);
172
182
  }
173
- return { resignBatch, countGenerationRows };
183
+ async function countNotGeneration(generationId) {
184
+ if (!ID_PATTERN.test(generationId))
185
+ throw new TypeError('generationId must match ID_PATTERN');
186
+ const result = await db.execute(sql `
187
+ select count(*)::integer as count
188
+ from keys_issued_credentials
189
+ where signing_generation_id is distinct from ${generationId}
190
+ `);
191
+ return Number(rowsOf(result)[0]?.count ?? 0);
192
+ }
193
+ async function generationsInUse() {
194
+ const result = await db.execute(sql `
195
+ select distinct signing_generation_id as id
196
+ from keys_issued_credentials
197
+ where signing_generation_id is not null
198
+ `);
199
+ return rowsOf(result)
200
+ .map((r) => r.id)
201
+ .sort();
202
+ }
203
+ async function retirementCheck(previousGenerationId) {
204
+ if (!ID_PATTERN.test(previousGenerationId)) {
205
+ throw new TypeError('previousGenerationId must match ID_PATTERN');
206
+ }
207
+ const result = await db.execute(sql `
208
+ select count(*)::integer as count
209
+ from keys_issued_credentials
210
+ where signing_generation_id = ${previousGenerationId}
211
+ and revoked_at is null
212
+ and expires_at > ${Date.now()}
213
+ `);
214
+ const rows = Array.isArray(result)
215
+ ? result
216
+ : (result.rows ?? []);
217
+ const blocking = Number(rows[0]?.count ?? 0);
218
+ return { retirable: blocking === 0, blocking };
219
+ }
220
+ return {
221
+ resignBatch,
222
+ countGenerationRows,
223
+ countNotGeneration,
224
+ generationsInUse,
225
+ retirementCheck,
226
+ };
174
227
  }
@@ -22,6 +22,10 @@
22
22
  * `keys_issued_guard()` trigger is what keeps it trustworthy: set
23
23
  * once at `issue()`, immutable for the row's life.
24
24
  *
25
+ * `purpose` and `organisationId` (`0007_keys_purpose.sql`) are unsigned too, and
26
+ * `null` on an older row means unknown. `keys_issued_guard()` lets each move
27
+ * from `null` to a value once and never change after that.
28
+ *
25
29
  * `lastUsedAt`/`useCount` (#46, `0003_keys_usage.sql`) are the one pair on
26
30
  * this row that is NOT set-once: `check()` writes both on every successful
27
31
  * verification, so -- unlike `environment` -- `keys_issued_guard()` leaves
@@ -235,6 +239,40 @@ export declare const keysIssuedCredentials: import("drizzle-orm/pg-core").PgTabl
235
239
  identity: undefined;
236
240
  generated: undefined;
237
241
  }, {}, {}>;
242
+ purpose: import("drizzle-orm/pg-core").PgColumn<{
243
+ name: "purpose";
244
+ tableName: "keys_issued_credentials";
245
+ dataType: "string";
246
+ columnType: "PgText";
247
+ data: string;
248
+ driverParam: string;
249
+ notNull: false;
250
+ hasDefault: false;
251
+ isPrimaryKey: false;
252
+ isAutoincrement: false;
253
+ hasRuntimeDefault: false;
254
+ enumValues: [string, ...string[]];
255
+ baseColumn: never;
256
+ identity: undefined;
257
+ generated: undefined;
258
+ }, {}, {}>;
259
+ organisationId: import("drizzle-orm/pg-core").PgColumn<{
260
+ name: "organisation_id";
261
+ tableName: "keys_issued_credentials";
262
+ dataType: "string";
263
+ columnType: "PgText";
264
+ data: string;
265
+ driverParam: string;
266
+ notNull: false;
267
+ hasDefault: false;
268
+ isPrimaryKey: false;
269
+ isAutoincrement: false;
270
+ hasRuntimeDefault: false;
271
+ enumValues: [string, ...string[]];
272
+ baseColumn: never;
273
+ identity: undefined;
274
+ generated: undefined;
275
+ }, {}, {}>;
238
276
  createdAt: import("drizzle-orm/pg-core").PgColumn<{
239
277
  name: "created_at";
240
278
  tableName: "keys_issued_credentials";