@happyvertical/secrets 0.106.1 → 0.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { syncSchema } from "@happyvertical/sql";
2
- import { createId } from "@happyvertical/utils";
3
- import * as crypto from "node:crypto";
4
- import { createHash, randomUUID, sign, verify } from "node:crypto";
5
1
  import { AsyncLocalStorage } from "node:async_hooks";
6
2
  import { spawn } from "node:child_process";
3
+ import * as crypto from "node:crypto";
4
+ import { createHash, randomUUID, sign, verify } from "node:crypto";
5
+ import { syncSchema } from "@happyvertical/sql";
6
+ import { createId } from "@happyvertical/utils";
7
7
  //#region \0rolldown/runtime.js
8
8
  var __defProp = Object.defineProperty;
9
9
  var __exportAll = (all, no_symbols) => {
@@ -16,1699 +16,2036 @@ var __exportAll = (all, no_symbols) => {
16
16
  return target;
17
17
  };
18
18
  //#endregion
19
- //#region src/shared/envelope.ts
20
- /**
21
- * Core envelope encryption primitives using AES-256-GCM
22
- *
23
- * This class provides the cryptographic operations for envelope encryption:
24
- * - Generate data encryption keys (DEKs)
25
- * - Wrap/unwrap DEKs with a master key
26
- * - Encrypt/decrypt data with DEKs
27
- *
28
- * @example
29
- * ```typescript
30
- * // Generate a new data key
31
- * const dataKey = EnvelopeEncryption.generateDataKey();
32
- *
33
- * // Wrap the data key with an AMK
34
- * const wrapped = EnvelopeEncryption.wrapKey(dataKey, amk);
35
- *
36
- * // Encrypt data with the data key
37
- * const encrypted = EnvelopeEncryption.encryptData('secret', dataKey);
38
- *
39
- * // Later: unwrap and decrypt
40
- * const unwrappedKey = EnvelopeEncryption.unwrapKey(wrapped.wrappedKey, wrapped.iv, wrapped.authTag, amk);
41
- * const plaintext = EnvelopeEncryption.decryptData(encrypted.ciphertext, encrypted.iv, encrypted.authTag, unwrappedKey);
42
- * ```
43
- */
44
- var EnvelopeEncryption = class EnvelopeEncryption {
45
- static ALGORITHM = "aes-256-gcm";
46
- static KEY_LENGTH = 32;
47
- static IV_LENGTH = 12;
48
- static AUTH_TAG_LENGTH = 16;
49
- /**
50
- * Generate a new random data encryption key
51
- *
52
- * @returns A 32-byte (256-bit) random key
53
- */
54
- static generateDataKey() {
55
- return crypto.randomBytes(EnvelopeEncryption.KEY_LENGTH);
56
- }
57
- /**
58
- * Generate a random IV for encryption
59
- *
60
- * @returns A 12-byte (96-bit) random IV
61
- */
62
- static generateIV() {
63
- return crypto.randomBytes(EnvelopeEncryption.IV_LENGTH);
19
+ //#region src/shared/custody.ts
20
+ var REDACTED = "[REDACTED]";
21
+ var MAX_TIMER_DELAY_MS = 2147483647;
22
+ var SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;
23
+ var ENVIRONMENT_VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
+ var CREDENTIAL_PATTERNS = [
25
+ {
26
+ pattern: /\b(?:gh[pousr]|github_pat|hvwk|sk|xox[baprs])_[A-Za-z0-9_-]{16,}\b/gi,
27
+ replacement: REDACTED
28
+ },
29
+ {
30
+ pattern: /\b[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\b/g,
31
+ replacement: REDACTED
32
+ },
33
+ {
34
+ pattern: /((?:authorization|credential|password|secret|token)\s*[:=]\s*(?:bearer\s+)?)[^\s,;]+/gi,
35
+ replacement: `$1${REDACTED}`
64
36
  }
65
- /**
66
- * Wrap (encrypt) a data encryption key with a master key
67
- *
68
- * @param dataKey - The data key to wrap (32 bytes)
69
- * @param masterKey - The master key to wrap with (32 bytes)
70
- * @returns Object containing wrapped key, IV, and auth tag (all base64-encoded)
71
- */
72
- static wrapKey(dataKey, masterKey) {
73
- EnvelopeEncryption.validateKeyLength(dataKey);
74
- EnvelopeEncryption.validateKeyLength(masterKey);
75
- const iv = EnvelopeEncryption.generateIV();
76
- const cipher = crypto.createCipheriv(EnvelopeEncryption.ALGORITHM, masterKey, iv);
77
- const encrypted = Buffer.concat([cipher.update(dataKey), cipher.final()]);
78
- const authTag = cipher.getAuthTag();
79
- return {
80
- wrappedKey: encrypted.toString("base64"),
81
- iv: iv.toString("base64"),
82
- authTag: authTag.toString("base64")
83
- };
37
+ ];
38
+ var environmentLock = Promise.resolve();
39
+ var environmentLockContext = new AsyncLocalStorage();
40
+ async function withEnvironmentLock(operation) {
41
+ if (environmentLockContext.getStore()) throw new CustodyError("REENTRANT_ENVIRONMENT_INJECTION", "inject", "Nested environment credential injection is not allowed");
42
+ const previous = environmentLock;
43
+ let release = () => void 0;
44
+ const current = new Promise((resolve) => {
45
+ release = resolve;
46
+ });
47
+ const queued = previous.then(() => current);
48
+ environmentLock = queued;
49
+ await previous;
50
+ try {
51
+ return await environmentLockContext.run(true, operation);
52
+ } finally {
53
+ release();
54
+ if (environmentLock === queued) environmentLock = Promise.resolve();
84
55
  }
85
- /**
86
- * Unwrap (decrypt) a data encryption key with a master key
87
- *
88
- * @param wrappedKey - Base64-encoded wrapped key
89
- * @param iv - Base64-encoded IV
90
- * @param authTag - Base64-encoded authentication tag
91
- * @param masterKey - The master key to unwrap with (32 bytes)
92
- * @returns The unwrapped data key (32 bytes)
93
- * @throws Error if decryption fails (invalid key, tampered data, etc.)
94
- */
95
- static unwrapKey(wrappedKey, iv, authTag, masterKey) {
96
- EnvelopeEncryption.validateKeyLength(masterKey);
97
- const decipher = crypto.createDecipheriv(EnvelopeEncryption.ALGORITHM, masterKey, Buffer.from(iv, "base64"));
98
- decipher.setAuthTag(Buffer.from(authTag, "base64"));
99
- return Buffer.concat([decipher.update(Buffer.from(wrappedKey, "base64")), decipher.final()]);
56
+ }
57
+ var CustodyError = class extends Error {
58
+ code;
59
+ stage;
60
+ details;
61
+ constructor(code, stage, message, options) {
62
+ super(redactCredentialText(message));
63
+ this.name = "CustodyError";
64
+ this.code = SAFE_IDENTIFIER.test(code) && redactCredentialText(code) === code ? code : "INVALID_CUSTODY_ERROR_CODE";
65
+ this.stage = stage;
66
+ this.details = options?.details ? redactCredentialValues(options.details) : void 0;
100
67
  }
101
- /**
102
- * Encrypt data with a data encryption key
103
- *
104
- * @param plaintext - The plaintext string to encrypt
105
- * @param dataKey - The data encryption key (32 bytes)
106
- * @returns Object containing ciphertext, IV, and auth tag (all base64-encoded)
107
- */
108
- static encryptData(plaintext, dataKey) {
109
- EnvelopeEncryption.validateKeyLength(dataKey);
110
- const iv = EnvelopeEncryption.generateIV();
111
- const cipher = crypto.createCipheriv(EnvelopeEncryption.ALGORITHM, dataKey, iv);
112
- const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
113
- const authTag = cipher.getAuthTag();
68
+ toJSON() {
114
69
  return {
115
- ciphertext: encrypted.toString("base64"),
116
- iv: iv.toString("base64"),
117
- authTag: authTag.toString("base64")
70
+ name: this.name,
71
+ code: this.code,
72
+ stage: this.stage,
73
+ message: this.message,
74
+ ...this.details ? { details: this.details } : {}
118
75
  };
119
76
  }
120
- /**
121
- * Decrypt data with a data encryption key
122
- *
123
- * @param ciphertext - Base64-encoded ciphertext
124
- * @param iv - Base64-encoded IV
125
- * @param authTag - Base64-encoded authentication tag
126
- * @param dataKey - The data encryption key (32 bytes)
127
- * @returns The decrypted plaintext string
128
- * @throws Error if decryption fails (invalid key, tampered data, etc.)
129
- */
130
- static decryptData(ciphertext, iv, authTag, dataKey) {
131
- EnvelopeEncryption.validateKeyLength(dataKey);
132
- const decipher = crypto.createDecipheriv(EnvelopeEncryption.ALGORITHM, dataKey, Buffer.from(iv, "base64"));
133
- decipher.setAuthTag(Buffer.from(authTag, "base64"));
134
- return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
77
+ };
78
+ var SecretMaterial = class SecretMaterial {
79
+ #bytes;
80
+ #destroyed = false;
81
+ constructor(value) {
82
+ this.#bytes = Buffer.from(value, "utf8");
135
83
  }
136
- /**
137
- * Create a full encrypted envelope
138
- *
139
- * This combines key wrapping and data encryption into a single envelope
140
- * that can be stored and later decrypted.
141
- *
142
- * @param plaintext - The plaintext string to encrypt
143
- * @param dataKey - The data encryption key (32 bytes)
144
- * @param wrappedKeyInfo - The wrapped key info (from wrapKey)
145
- * @param amkKeyId - The ID of the AMK used to wrap the key
146
- * @param metadata - Optional metadata to include in the envelope
147
- * @returns A complete encrypted envelope
148
- */
149
- static createEnvelope(plaintext, dataKey, wrappedKeyInfo, amkKeyId, metadata) {
150
- const encrypted = EnvelopeEncryption.encryptData(plaintext, dataKey);
151
- return {
152
- version: 1,
153
- algorithm: "aes-256-gcm",
154
- wrappedKey: `${wrappedKeyInfo.wrappedKey}:${wrappedKeyInfo.iv}:${wrappedKeyInfo.authTag}`,
155
- amkKeyId,
156
- iv: encrypted.iv,
157
- authTag: encrypted.authTag,
158
- ciphertext: encrypted.ciphertext,
159
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
160
- metadata
161
- };
84
+ static fromString(value) {
85
+ if (!value) throw new CustodyError("EMPTY_SECRET_MATERIAL", "issue", "Secret material must not be empty");
86
+ return new SecretMaterial(value);
162
87
  }
163
- /**
164
- * Parse a combined wrapped key string
165
- *
166
- * @param combinedWrappedKey - The combined wrapped key string (wrappedKey:iv:authTag)
167
- * @returns Object with wrappedKey, iv, and authTag
168
- */
169
- static parseWrappedKey(combinedWrappedKey) {
170
- const parts = combinedWrappedKey.split(":");
171
- if (parts.length !== 3) throw new Error("Invalid wrapped key format: expected wrappedKey:iv:authTag");
172
- const [wrappedKey, iv, authTag] = parts;
173
- if (!wrappedKey || !iv || !authTag) throw new Error("Invalid wrapped key format: wrappedKey, iv, and authTag must all be non-empty");
174
- return {
175
- wrappedKey,
176
- iv,
177
- authTag
178
- };
88
+ get destroyed() {
89
+ return this.#destroyed;
179
90
  }
180
- /**
181
- * Decrypt a full envelope
182
- *
183
- * @param envelope - The encrypted envelope
184
- * @param masterKey - The master key to unwrap the data key
185
- * @returns The decrypted plaintext string
186
- */
187
- static decryptEnvelope(envelope, masterKey) {
188
- const { wrappedKey, iv: keyIv, authTag: keyAuthTag } = EnvelopeEncryption.parseWrappedKey(envelope.wrappedKey);
189
- const dataKey = EnvelopeEncryption.unwrapKey(wrappedKey, keyIv, keyAuthTag, masterKey);
190
- return EnvelopeEncryption.decryptData(envelope.ciphertext, envelope.iv, envelope.authTag, dataKey);
91
+ async use(operation) {
92
+ if (this.#destroyed) throw new CustodyError("SECRET_MATERIAL_DESTROYED", "inject", "Secret material is no longer available");
93
+ const plaintext = this.#bytes.toString("utf8");
94
+ try {
95
+ await operation(plaintext);
96
+ } catch (cause) {
97
+ if (cause instanceof CustodyError) throw new CustodyError(redactCredentialText(cause.code, [plaintext]) === cause.code ? cause.code : "INVALID_CUSTODY_ERROR_CODE", cause.stage, redactCredentialText(cause.message, [plaintext]), { details: redactCredentialValues(cause.details, [plaintext]) });
98
+ throw new CustodyError("SECRET_MATERIAL_OPERATION_FAILED", "inject", "Secret material operation failed", { cause });
99
+ }
191
100
  }
192
- /**
193
- * Validate that a key is the correct length
194
- *
195
- * @param key - The key to validate
196
- * @param expectedLength - Expected length in bytes (default: 32)
197
- * @throws Error if key length is invalid
198
- */
199
- static validateKeyLength(key, expectedLength = EnvelopeEncryption.KEY_LENGTH) {
200
- if (key.length !== expectedLength) throw new Error(`Invalid key length: expected ${expectedLength} bytes, got ${key.length} bytes`);
101
+ destroy() {
102
+ this.#bytes.fill(0);
103
+ this.#destroyed = true;
201
104
  }
202
- /**
203
- * Parse a hex-encoded key from string
204
- *
205
- * @param hexKey - Hex-encoded key string (64 chars for 32 bytes)
206
- * @returns The key as a Buffer
207
- * @throws Error if the hex string is invalid
208
- */
209
- static parseHexKey(hexKey) {
210
- if (!/^[0-9a-fA-F]+$/.test(hexKey)) throw new Error("Invalid hex key: contains non-hex characters");
211
- const key = Buffer.from(hexKey, "hex");
212
- EnvelopeEncryption.validateKeyLength(key);
213
- return key;
105
+ toJSON() {
106
+ return REDACTED;
214
107
  }
215
- };
216
- //#endregion
217
- //#region src/shared/errors.ts
218
- /**
219
- * Base error class for secret operations
220
- */
221
- var SecretError = class extends Error {
222
- code;
223
- adapterType;
224
- cause;
225
- constructor(message, code, options) {
226
- super(message);
227
- this.name = "SecretError";
228
- this.code = code;
229
- this.adapterType = options?.adapterType;
230
- this.cause = options?.cause;
108
+ toString() {
109
+ return REDACTED;
231
110
  }
232
- };
233
- /**
234
- * Error thrown when a key is not found
235
- */
236
- var KeyNotFoundError = class extends SecretError {
237
- constructor(keyId, adapterType) {
238
- super(`Key not found: ${keyId}`, "KEY_NOT_FOUND", { adapterType });
239
- this.name = "KeyNotFoundError";
111
+ [Symbol.for("nodejs.util.inspect.custom")]() {
112
+ return REDACTED;
240
113
  }
241
114
  };
242
- /**
243
- * Error thrown when decryption fails
244
- */
245
- var DecryptionError = class extends SecretError {
246
- constructor(message, adapterType, cause) {
247
- super(message, "DECRYPTION_FAILED", {
248
- adapterType,
249
- cause
250
- });
251
- this.name = "DecryptionError";
115
+ var Ed25519CustodyReceiptAttestor = class {
116
+ name;
117
+ keyId;
118
+ #privateKey;
119
+ constructor(options) {
120
+ if (options.privateKey.type !== "private" || options.privateKey.asymmetricKeyType !== "ed25519") throw new CustodyError("INVALID_ATTESTATION_KEY", "record", "Custody attestation requires a private signing key");
121
+ this.#privateKey = options.privateKey;
122
+ this.name = options.name ?? "ed25519";
123
+ this.keyId = options.keyId;
124
+ assertSafeIdentifier(this.name, "attestor.name", "record");
125
+ assertSafeIdentifier(this.keyId, "attestor.keyId", "record");
252
126
  }
253
- };
254
- /**
255
- * Error thrown when encryption fails
256
- */
257
- var EncryptionError = class extends SecretError {
258
- constructor(message, adapterType, cause) {
259
- super(message, "ENCRYPTION_FAILED", {
260
- adapterType,
261
- cause
262
- });
263
- this.name = "EncryptionError";
127
+ async attest(payload) {
128
+ return sign(null, Buffer.from(payload), this.#privateKey).toString("base64url");
264
129
  }
265
130
  };
266
- /**
267
- * Error thrown when key rotation fails
268
- */
269
- var KeyRotationError = class extends SecretError {
270
- constructor(message, adapterType, cause) {
271
- super(message, "KEY_ROTATION_FAILED", {
272
- adapterType,
273
- cause
274
- });
275
- this.name = "KeyRotationError";
131
+ var InMemoryCustodyLedger = class {
132
+ #receipts = [];
133
+ #events = [];
134
+ #issuanceCommits = /* @__PURE__ */ new Map();
135
+ async recordIssuance(receipt, event) {
136
+ if (event.type !== "finalization-pending" || event.receiptId !== receipt.receiptId) throw new CustodyError("INVALID_CUSTODY_EVENT", "record", "Prepared receipt requires a finalization-pending event");
137
+ if (this.#receipts.some((item) => item.receiptId === receipt.receiptId)) throw new CustodyError("DUPLICATE_CUSTODY_RECEIPT", "record", "Custody receipt already exists");
138
+ if (receipt.replacesReceiptId) {
139
+ const predecessor = this.#receipts.find((item) => item.receiptId === receipt.replacesReceiptId);
140
+ const predecessorTerminal = this.#events.some((item) => item.receiptId === receipt.replacesReceiptId && [
141
+ "revoked",
142
+ "expired",
143
+ "replaced"
144
+ ].includes(item.type));
145
+ const predecessorIssued = this.#events.some((item) => item.receiptId === receipt.replacesReceiptId && item.type === "issued");
146
+ const existingChild = this.#receipts.some((item) => item.replacesReceiptId === receipt.replacesReceiptId && !this.#events.some((event) => event.receiptId === item.receiptId && [
147
+ "revoked",
148
+ "expired",
149
+ "replaced"
150
+ ].includes(event.type)));
151
+ if (!predecessor || !predecessorIssued || predecessorTerminal || existingChild) throw new CustodyError("CUSTODY_ROTATION_CONFLICT", "record", "Custody predecessor is not active and replaceable");
152
+ }
153
+ if (this.#assertEventIdentity(event)) throw new CustodyError("CUSTODY_EVENT_ID_CONFLICT", "record", "Prepared event already exists");
154
+ this.#receipts.push(structuredClone(receipt));
155
+ this.#events.push(structuredClone(event));
276
156
  }
277
- };
278
- /**
279
- * Error thrown when a tenant's encryption key is missing
280
- */
281
- var TenantKeyMissingError = class extends SecretError {
282
- constructor(tenantId) {
283
- super(`No active encryption key for tenant: ${tenantId}`, "TENANT_KEY_MISSING");
284
- this.name = "TenantKeyMissingError";
157
+ #assertEventIdentity(event) {
158
+ const existing = this.#events.find((item) => item.eventId === event.eventId);
159
+ if (!existing) return false;
160
+ if (sameCustodyEvent(existing, event)) return true;
161
+ throw new CustodyError("CUSTODY_EVENT_ID_CONFLICT", "record", "Custody event ID is already bound to different content");
285
162
  }
286
- };
287
- /**
288
- * Error thrown when the Application Master Key is unavailable
289
- */
290
- var AMKUnavailableError = class extends SecretError {
291
- constructor(message) {
292
- super(message, "AMK_UNAVAILABLE");
293
- this.name = "AMKUnavailableError";
163
+ async appendEvent(event) {
164
+ if (!this.#assertEventIdentity(event)) this.#events.push(structuredClone(event));
294
165
  }
295
- };
296
- /**
297
- * Error thrown when the store is not initialized
298
- */
299
- var StoreNotInitializedError = class extends SecretError {
300
- constructor(adapterType) {
301
- super("Secret store not initialized", "STORE_NOT_INITIALIZED", { adapterType });
302
- this.name = "StoreNotInitializedError";
166
+ async commitIssuance(receiptId, event, followup) {
167
+ if (event.type !== "issued" || event.receiptId !== receiptId || followup !== void 0 && followup.type !== "retirement-pending") throw new CustodyError("INVALID_CUSTODY_EVENT", "record", "Issuance commit requires issued and optional retirement-pending events");
168
+ if (!this.#receipts.some((receipt) => receipt.receiptId === receiptId)) throw new CustodyError("CUSTODY_RECEIPT_NOT_FOUND", "record", "Prepared custody receipt was not found");
169
+ const existing = this.#assertEventIdentity(event);
170
+ if (followup) {
171
+ this.#assertEventIdentity(followup);
172
+ if (followup.eventId === event.eventId) throw new CustodyError("CUSTODY_EVENT_ID_CONFLICT", "record", "Issuance events require distinct IDs");
173
+ }
174
+ const issued = this.#events.find((item) => item.receiptId === receiptId && item.type === "issued");
175
+ if (issued && !sameCustodyEvent(issued, event)) throw new CustodyError("CUSTODY_EVENT_ID_CONFLICT", "record", "Receipt issuance is already committed");
176
+ const binding = {
177
+ receiptId,
178
+ eventId: event.eventId,
179
+ followupEventId: followup?.eventId ?? null
180
+ };
181
+ const original = this.#issuanceCommits.get(receiptId);
182
+ if (original && (original.eventId !== binding.eventId || original.followupEventId !== binding.followupEventId)) throw new CustodyError("CUSTODY_EVENT_ID_CONFLICT", "record", "Committed issuance requires its original followup association");
183
+ const nextEvent = existing ? void 0 : structuredClone(event);
184
+ const nextFollowup = followup && !this.#events.some((item) => item.eventId === followup.eventId) ? structuredClone(followup) : void 0;
185
+ if (nextEvent) this.#events.push(nextEvent);
186
+ if (nextFollowup) this.#events.push(nextFollowup);
187
+ this.#issuanceCommits.set(receiptId, binding);
188
+ }
189
+ /** @internal Snapshot metadata for durable ledger recovery. */
190
+ async listIssuanceCommits() {
191
+ return structuredClone([...this.#issuanceCommits.values()]);
303
192
  }
304
- };
305
- /**
306
- * Error thrown when an invalid key format is encountered
307
- */
308
- var InvalidKeyFormatError = class extends SecretError {
309
- constructor(message, adapterType) {
310
- super(message, "INVALID_KEY_FORMAT", { adapterType });
311
- this.name = "InvalidKeyFormatError";
193
+ async listReceipts() {
194
+ return structuredClone(this.#receipts);
195
+ }
196
+ async listEvents() {
197
+ return structuredClone(this.#events);
312
198
  }
313
199
  };
314
- //#endregion
315
- //#region src/adapters/database.ts
316
- var database_exports = /* @__PURE__ */ __exportAll({
317
- DatabaseSecretStore: () => DatabaseSecretStore,
318
- default: () => DatabaseSecretStore
319
- });
320
- /**
321
- * Default rotation period in milliseconds (90 days)
322
- */
323
- var DEFAULT_ROTATION_PERIOD_MS = 2160 * 60 * 60 * 1e3;
324
- /**
325
- * Database-backed secret store
326
- *
327
- * Uses envelope encryption with AES-256-GCM:
328
- * - Application Master Key (AMK) from environment variable
329
- * - Per-tenant Data Encryption Keys (TDEKs) wrapped by AMK
330
- * - Secrets encrypted by unwrapped TDEKs
331
- *
332
- * @example
333
- * ```typescript
334
- * const store = new DatabaseSecretStore({
335
- * type: 'database',
336
- * db,
337
- * amk: {
338
- * provider: 'env',
339
- * keyEnvVar: 'SECRET_MASTER_KEY',
340
- * keyId: 'amk-v1'
341
- * }
342
- * });
343
- *
344
- * await store.initialize();
345
- *
346
- * // Encrypt a secret for a tenant
347
- * const envelope = await store.encrypt('tenant-123', 'api-key', 'synthetic-secret');
348
- *
349
- * // Decrypt
350
- * const { value } = await store.decrypt('tenant-123', envelope);
351
- * ```
352
- */
353
- var DatabaseSecretStore = class {
354
- db;
355
- keysTable;
356
- amkConfig;
357
- cachedAmk = null;
358
- initialized = false;
359
- listeners = [];
200
+ var CredentialCustody = class {
201
+ #issuer;
202
+ #verifier;
203
+ #ledger;
204
+ #attestor;
205
+ #finalizer;
206
+ #sink;
207
+ #ephemeralTtlMs;
208
+ #ephemeralRevokeRetryMs;
209
+ #orphanGraceMs;
210
+ #finalizationTakeoverMs;
211
+ #now;
212
+ #onBackgroundError;
213
+ #leaseInvalidators = /* @__PURE__ */ new Map();
214
+ #pendingTimers = /* @__PURE__ */ new Map();
360
215
  constructor(options) {
361
- this.db = options.db;
362
- const tableName = options.keysTable ?? "tenant_encryption_keys";
363
- if (!/^[A-Za-z0-9_]+$/.test(tableName)) throw new Error(`Invalid keysTable name "${tableName}". Table name must contain only alphanumeric characters and underscores.`);
364
- this.keysTable = tableName;
365
- this.amkConfig = options.amk;
216
+ assertSafeIdentifier(options.issuer.name, "issuer.name", "issue");
217
+ assertSafeIdentifier(options.verifier.name, "verifier.name", "verify");
218
+ assertSafeIdentifier(options.attestor.name, "attestor.name", "record");
219
+ assertSafeIdentifier(options.attestor.keyId, "attestor.keyId", "record");
220
+ assertSafeIdentifier(options.finalizer.name, "finalizer.name", "activate");
221
+ if (options.sink) assertSafeIdentifier(options.sink.name, "sink.name", "store");
222
+ this.#issuer = options.issuer;
223
+ this.#verifier = options.verifier;
224
+ this.#ledger = options.ledger;
225
+ this.#attestor = options.attestor;
226
+ this.#finalizer = options.finalizer;
227
+ this.#sink = options.sink;
228
+ this.#ephemeralTtlMs = options.ephemeralTtlMs ?? 5 * 6e4;
229
+ this.#ephemeralRevokeRetryMs = options.ephemeralRevokeRetryMs ?? 1e3;
230
+ this.#orphanGraceMs = options.orphanGraceMs ?? 5 * 6e4;
231
+ this.#finalizationTakeoverMs = options.finalizationTakeoverMs ?? 3e4;
232
+ if (!Number.isFinite(this.#ephemeralTtlMs) || !Number.isFinite(this.#ephemeralRevokeRetryMs) || !Number.isFinite(this.#orphanGraceMs) || !Number.isFinite(this.#finalizationTakeoverMs) || this.#ephemeralTtlMs <= 0 || this.#ephemeralRevokeRetryMs <= 0 || this.#orphanGraceMs < 0 || this.#finalizationTakeoverMs < 0) throw new CustodyError("INVALID_CUSTODY_DURATION", "issue", "Custody durations must be positive");
233
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
234
+ this.#onBackgroundError = options.onBackgroundError;
366
235
  }
367
- /**
368
- * Initialize the store (create schema if needed)
369
- */
370
- async initialize() {
371
- if (this.initialized) return;
372
- const schema = `
373
- CREATE TABLE IF NOT EXISTS "${this.keysTable}" (
374
- id TEXT PRIMARY KEY,
375
- tenant_id TEXT NOT NULL,
376
- wrapped_key TEXT NOT NULL,
377
- amk_key_id TEXT NOT NULL,
378
- status TEXT NOT NULL DEFAULT 'active',
379
- version INTEGER NOT NULL DEFAULT 1,
380
- rotate_after TEXT,
381
- retired_at TEXT,
382
- created_at TEXT NOT NULL,
383
- updated_at TEXT NOT NULL
384
- );
385
-
386
- CREATE INDEX IF NOT EXISTS "idx_${this.keysTable}_tenant_status"
387
- ON "${this.keysTable}" (tenant_id, status);
388
-
389
- CREATE INDEX IF NOT EXISTS "idx_${this.keysTable}_rotate_after"
390
- ON "${this.keysTable}" (rotate_after)
391
- WHERE status = 'active';
392
- `;
393
- await syncSchema({
394
- db: this.db,
395
- schema
396
- });
397
- this.initialized = true;
398
- }
399
- /**
400
- * Get the Application Master Key from environment
401
- */
402
- getAMK() {
403
- if (this.cachedAmk) return this.cachedAmk;
404
- const keyHex = process.env[this.amkConfig.keyEnvVar];
405
- if (!keyHex) throw new AMKUnavailableError(`Application Master Key not found in environment variable: ${this.amkConfig.keyEnvVar}`);
406
- try {
407
- const key = EnvelopeEncryption.parseHexKey(keyHex);
408
- this.cachedAmk = key;
409
- return key;
410
- } catch (error) {
411
- throw new AMKUnavailableError(`Invalid AMK in ${this.amkConfig.keyEnvVar}: ${error.message}`);
412
- }
413
- }
414
- /**
415
- * Ensure the store is initialized
416
- */
417
- ensureInitialized() {
418
- if (!this.initialized) throw new StoreNotInitializedError("database");
419
- }
420
- /**
421
- * Emit an event to all listeners
422
- */
423
- async emitEvent(event) {
424
- for (const listener of this.listeners) await listener(event);
425
- }
426
- /**
427
- * Subscribe to store events
428
- */
429
- subscribe(listener) {
430
- this.listeners.push(listener);
431
- return () => {
432
- const index = this.listeners.indexOf(listener);
433
- if (index !== -1) this.listeners.splice(index, 1);
434
- };
435
- }
436
- async encrypt(tenantId, secretName, plaintext, options) {
437
- this.ensureInitialized();
438
- if (typeof tenantId !== "string" || tenantId.trim().length === 0) throw new EncryptionError("Invalid tenantId provided for encryption", "database");
439
- if (typeof secretName !== "string" || secretName.trim().length === 0) throw new EncryptionError("Invalid secretName provided for encryption", "database");
440
- let dataKey = null;
236
+ async issue(request) {
237
+ if (request.mode === "durable" && !this.#sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "store", "Durable credential issuance requires a secret sink");
238
+ if (request.replacesReceiptId && request.mode !== "durable") throw new CustodyError("DURABLE_ROTATION_REQUIRED", "issue", "Credential replacement requires durable mode");
239
+ assertSafeIdentifier(request.subject, "subject", "issue");
240
+ assertAttribution(request.attribution);
241
+ const replacedReceipt = request.replacesReceiptId ? await this.#findReceipt(request.replacesReceiptId) : void 0;
242
+ if (replacedReceipt?.mode !== void 0 && replacedReceipt.mode !== "durable") throw new CustodyError("DURABLE_ROTATION_REQUIRED", "issue", "Only durable credentials can be replaced");
243
+ const now = this.#now();
244
+ const expiresAt = request.expiresAt ?? (request.mode === "ephemeral" ? new Date(now.getTime() + this.#ephemeralTtlMs).toISOString() : void 0);
245
+ const requestedExpiryMs = expiresAt ? parseTimestamp(expiresAt, "expiresAt", "issue") : void 0;
246
+ if (requestedExpiryMs !== void 0 && requestedExpiryMs <= now.getTime()) throw new CustodyError("INVALID_EXPIRY", "issue", "Credential expiry must be in the future");
247
+ const metadata = sanitizeMetadata(request.metadata);
248
+ let issued;
249
+ let sinkRecord;
250
+ let retrieved;
251
+ let preparedReceipt;
252
+ let receiptRecorded = false;
253
+ let stage = "issue";
441
254
  try {
442
- let tenantKey = await this.getTenantKey(tenantId);
443
- if (!tenantKey) tenantKey = await this.createTenantKey(tenantId);
444
- const amk = this.getAMK();
445
- const { wrappedKey, iv: keyIv, authTag: keyAuthTag } = EnvelopeEncryption.parseWrappedKey(tenantKey.wrappedKey);
446
- dataKey = EnvelopeEncryption.unwrapKey(wrappedKey, keyIv, keyAuthTag, amk);
447
- const envelope = EnvelopeEncryption.createEnvelope(plaintext, dataKey, {
448
- wrappedKey,
449
- iv: keyIv,
450
- authTag: keyAuthTag
451
- }, tenantKey.amkKeyId, options?.metadata);
452
- await this.emitEvent({
453
- type: "secret.encrypted",
454
- tenantId,
455
- keyId: tenantKey.keyId,
456
- secretName,
457
- timestamp: /* @__PURE__ */ new Date()
255
+ issued = await this.#issuer.issue({
256
+ mode: request.mode,
257
+ subject: request.subject,
258
+ expiresAt,
259
+ metadata
458
260
  });
459
- return envelope;
460
- } catch (error) {
461
- if (error instanceof AMKUnavailableError || error instanceof TenantKeyMissingError) throw error;
462
- throw new EncryptionError(`Failed to encrypt secret '${secretName}' for tenant ${tenantId}: ${error.message}`, "database", error instanceof Error ? error : void 0);
463
- } finally {
464
- if (dataKey && Buffer.isBuffer(dataKey)) dataKey.fill(0);
465
- }
466
- }
467
- async decrypt(tenantId, envelope) {
468
- this.ensureInitialized();
469
- if (typeof tenantId !== "string" || tenantId.trim().length === 0) throw new DecryptionError("Invalid tenantId provided for decryption", "database");
470
- const tenantKeys = await this.listKeyVersions(tenantId);
471
- if (tenantKeys.length === 0) throw new TenantKeyMissingError(tenantId);
472
- const envelopeWrappedKey = envelope.wrappedKey.split(":")[0];
473
- const matchingKey = tenantKeys.find((key) => {
474
- return key.wrappedKey.split(":")[0] === envelopeWrappedKey;
475
- });
476
- if (!matchingKey) throw new DecryptionError(`Envelope was not encrypted with a key belonging to tenant ${tenantId}`, "database");
477
- try {
478
- const amk = this.getAMK();
479
- const plaintext = EnvelopeEncryption.decryptEnvelope(envelope, amk);
480
- await this.emitEvent({
481
- type: "secret.decrypted",
482
- tenantId,
483
- keyId: matchingKey.keyId,
484
- timestamp: /* @__PURE__ */ new Date()
261
+ assertSafeIdentifier(issued.credentialId, "credentialId", "issue");
262
+ if (issued.issuedAt) parseTimestamp(issued.issuedAt, "issuedAt", "issue");
263
+ if (issued.expiresAt) {
264
+ const providerExpiryMs = parseTimestamp(issued.expiresAt, "provider expiresAt", "issue");
265
+ if (providerExpiryMs <= now.getTime()) throw new CustodyError("INVALID_EXPIRY", "issue", "Credential provider returned an expired credential");
266
+ if (requestedExpiryMs !== void 0 && providerExpiryMs > requestedExpiryMs) throw new CustodyError("EXPIRY_BOUND_EXCEEDED", "issue", "Credential provider exceeded the requested expiry bound");
267
+ }
268
+ let material = issued.secret;
269
+ if (request.mode === "durable") {
270
+ const sink = this.#sink;
271
+ if (!sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "store", "Durable credential issuance requires a secret sink");
272
+ stage = "store";
273
+ sinkRecord = await sink.store({
274
+ credentialId: issued.credentialId,
275
+ secret: issued.secret,
276
+ metadata
277
+ });
278
+ assertSinkRecord(sinkRecord, sink.name);
279
+ stage = "retrieve";
280
+ retrieved = await sink.retrieve(sinkRecord);
281
+ material = retrieved;
282
+ }
283
+ stage = "verify";
284
+ const verification = await this.#verifier.verify({
285
+ credentialId: issued.credentialId,
286
+ secret: material
485
287
  });
486
- return {
487
- value: plaintext,
488
- keyId: matchingKey.keyId,
489
- createdAt: new Date(envelope.createdAt),
490
- metadata: envelope.metadata
288
+ if (!verification.verified) throw new CustodyError("CREDENTIAL_VERIFICATION_FAILED", "verify", "Credential verification failed");
289
+ if (verification.verificationId) assertSafeIdentifier(verification.verificationId, "verificationId", "verify");
290
+ const receiptId = randomUUID();
291
+ const finalizationId = randomUUID();
292
+ const unsignedReceipt = {
293
+ receiptId,
294
+ mode: request.mode,
295
+ credentialId: issued.credentialId,
296
+ subject: request.subject,
297
+ issuer: this.#issuer.name,
298
+ verifier: this.#verifier.name,
299
+ ...verification.verificationId ? { verificationId: verification.verificationId } : {},
300
+ verificationState: "verified",
301
+ issuedAt: issued.issuedAt ?? now.toISOString(),
302
+ verifiedAt: this.#now().toISOString(),
303
+ ...issued.expiresAt ?? expiresAt ? { expiresAt: issued.expiresAt ?? expiresAt } : {},
304
+ ...sinkRecord ? { sink: sinkRecord } : {},
305
+ ...request.replacesReceiptId ? { replacesReceiptId: request.replacesReceiptId } : {},
306
+ rotationRootReceiptId: replacedReceipt?.rotationRootReceiptId ?? receiptId,
307
+ attribution: { ...request.attribution },
308
+ metadata,
309
+ finalizer: this.#finalizer.name,
310
+ finalizationId
491
311
  };
492
- } catch (error) {
493
- if (error instanceof AMKUnavailableError) throw error;
494
- throw new DecryptionError(`Failed to decrypt secret for tenant ${tenantId}: ${error.message}`, "database", error instanceof Error ? error : void 0);
495
- }
496
- }
497
- async getTenantKey(tenantId) {
498
- this.ensureInitialized();
499
- const row = await this.db.get(this.keysTable, {
500
- tenant_id: tenantId,
501
- status: "active"
502
- });
503
- if (!row) return null;
504
- return this.parseKeyRow(row);
505
- }
506
- async createTenantKey(tenantId) {
507
- this.ensureInitialized();
508
- const amk = this.getAMK();
509
- const dataKey = EnvelopeEncryption.generateDataKey();
510
- const wrapped = EnvelopeEncryption.wrapKey(dataKey, amk);
511
- const keyId = createId();
512
- const wrappedKeyStr = `${wrapped.wrappedKey}:${wrapped.iv}:${wrapped.authTag}`;
513
- const now = /* @__PURE__ */ new Date();
514
- const rotateAfter = new Date(now.getTime() + DEFAULT_ROTATION_PERIOD_MS);
515
- await this.db.insert(this.keysTable, {
516
- id: keyId,
517
- tenant_id: tenantId,
518
- wrapped_key: wrappedKeyStr,
519
- amk_key_id: this.amkConfig.keyId,
520
- status: "active",
521
- version: 1,
522
- rotate_after: rotateAfter.toISOString(),
523
- created_at: now.toISOString(),
524
- updated_at: now.toISOString()
525
- });
526
- await this.emitEvent({
527
- type: "key.created",
528
- tenantId,
529
- keyId,
530
- timestamp: now
531
- });
532
- return {
533
- keyId,
534
- tenantId,
535
- wrappedKey: wrappedKeyStr,
536
- amkKeyId: this.amkConfig.keyId,
537
- status: "active",
538
- version: 1,
539
- createdAt: now,
540
- rotateAfter
541
- };
542
- }
543
- async rotateTenantKey(tenantId) {
544
- this.ensureInitialized();
545
- const currentKey = await this.getTenantKey(tenantId);
546
- if (!currentKey) throw new TenantKeyMissingError(tenantId);
547
- const now = /* @__PURE__ */ new Date();
548
- try {
549
- await this.db.update(this.keysTable, { id: currentKey.keyId }, {
550
- status: "rotating",
551
- updated_at: now.toISOString()
312
+ stage = "record";
313
+ let signature = "";
314
+ await material.use(async (plaintext) => {
315
+ signature = await this.#attestor.attest(custodyAttestationPayload(unsignedReceipt, credentialCommitment(plaintext), {
316
+ algorithm: "Ed25519",
317
+ attestor: this.#attestor.name,
318
+ keyId: this.#attestor.keyId
319
+ }));
552
320
  });
553
- const amk = this.getAMK();
554
- const dataKey = EnvelopeEncryption.generateDataKey();
555
- const wrapped = EnvelopeEncryption.wrapKey(dataKey, amk);
556
- const newKeyId = createId();
557
- const wrappedKeyStr = `${wrapped.wrappedKey}:${wrapped.iv}:${wrapped.authTag}`;
558
- const rotateAfter = new Date(now.getTime() + DEFAULT_ROTATION_PERIOD_MS);
559
- await this.db.insert(this.keysTable, {
560
- id: newKeyId,
561
- tenant_id: tenantId,
562
- wrapped_key: wrappedKeyStr,
563
- amk_key_id: this.amkConfig.keyId,
564
- status: "active",
565
- version: currentKey.version + 1,
566
- rotate_after: rotateAfter.toISOString(),
567
- created_at: now.toISOString(),
568
- updated_at: now.toISOString()
569
- });
570
- await this.db.update(this.keysTable, { id: currentKey.keyId }, {
571
- status: "retired",
572
- retired_at: now.toISOString(),
573
- updated_at: now.toISOString()
574
- });
575
- await this.emitEvent({
576
- type: "key.rotated",
577
- tenantId,
578
- keyId: newKeyId,
579
- timestamp: now
580
- });
581
- return {
582
- keyId: newKeyId,
583
- tenantId,
584
- wrappedKey: wrappedKeyStr,
585
- amkKeyId: this.amkConfig.keyId,
586
- status: "active",
587
- version: currentKey.version + 1,
588
- createdAt: now,
589
- rotateAfter
321
+ if (!/^[A-Za-z0-9_-]{86}$/.test(signature) || Buffer.from(signature, "base64url").byteLength !== 64 || Buffer.from(signature, "base64url").toString("base64url") !== signature || redactCredentialText(signature) !== signature) throw new CustodyError("INVALID_CUSTODY_ATTESTATION", "record", "Custody attestor returned an invalid signature");
322
+ const receipt = {
323
+ ...unsignedReceipt,
324
+ attestation: {
325
+ algorithm: "Ed25519",
326
+ attestor: this.#attestor.name,
327
+ keyId: this.#attestor.keyId,
328
+ signature
329
+ }
590
330
  };
591
- } catch (error) {
592
- throw new KeyRotationError(`Failed to rotate key for tenant ${tenantId}: ${error.message}`, "database", error instanceof Error ? error : void 0);
331
+ stage = "record";
332
+ await this.#ledger.recordIssuance(receipt, this.#event("finalization-pending", receiptId));
333
+ receiptRecorded = true;
334
+ stage = "activate";
335
+ preparedReceipt = receipt;
336
+ if (!(await this.#finalizer.prepare({
337
+ receipt: structuredClone(receipt),
338
+ secret: material
339
+ })).prepared) throw new CustodyError("CREDENTIAL_ACTIVATION_FAILED", "activate", "Credential post-attestation activation failed");
340
+ retrieved?.destroy();
341
+ retrieved = void 0;
342
+ if (request.mode === "durable") issued.secret.destroy();
343
+ stage = "activate";
344
+ await this.#finalizer.commit({ receipt: structuredClone(receipt) });
345
+ stage = "record";
346
+ const retirementRecoveryId = replacedReceipt ? randomUUID() : void 0;
347
+ const retirementPending = replacedReceipt && retirementRecoveryId ? {
348
+ ...this.#event("retirement-pending", replacedReceipt.receiptId),
349
+ eventId: retirementRecoveryId,
350
+ recoveryId: retirementRecoveryId,
351
+ credentialId: replacedReceipt.credentialId,
352
+ recoveryReceipt: structuredClone(replacedReceipt),
353
+ replacementReceiptId: receipt.receiptId
354
+ } : void 0;
355
+ await this.#ledger.commitIssuance(receipt.receiptId, this.#event("issued", receipt.receiptId), retirementPending);
356
+ const lease = this.#createLease(receipt, request.mode === "ephemeral" ? issued.secret : void 0);
357
+ if (replacedReceipt) try {
358
+ this.#leaseInvalidators.get(replacedReceipt.receiptId)?.();
359
+ await this.#revokeReceipt(replacedReceipt, "replaced", "replaced");
360
+ this.#leaseInvalidators.delete(replacedReceipt.receiptId);
361
+ await this.#ledger.appendEvent({
362
+ ...this.#event("retirement-complete", replacedReceipt.receiptId),
363
+ recoveryId: retirementRecoveryId
364
+ });
365
+ } catch (cause) {
366
+ if (retirementRecoveryId) this.#scheduleRetirement(retirementRecoveryId, replacedReceipt, receipt.receiptId);
367
+ try {
368
+ this.#onBackgroundError?.(new CustodyError("PREDECESSOR_RETIREMENT_PENDING", "revoke", "Replacement is active while predecessor retirement retries", {
369
+ cause,
370
+ details: { recoveryId: retirementRecoveryId }
371
+ }));
372
+ } catch {}
373
+ }
374
+ preparedReceipt = void 0;
375
+ return lease;
376
+ } catch (cause) {
377
+ const safeCause = await sanitizeCustodyCause(cause, [retrieved, issued?.secret]);
378
+ retrieved?.destroy();
379
+ issued?.secret.destroy();
380
+ if (issued) {
381
+ const requiresSink = request.mode === "durable";
382
+ try {
383
+ if (receiptRecorded && preparedReceipt) await this.#abortAndRevoke(preparedReceipt, `rollback after ${stage}`);
384
+ else await this.#rollback(issued.credentialId, sinkRecord, stage, requiresSink);
385
+ } catch (rollbackCause) {
386
+ const recoveryId = randomUUID();
387
+ const pendingEvent = {
388
+ ...this.#event("rollback-pending", receiptRecorded ? preparedReceipt?.receiptId : void 0, sinkRecord?.reference, `rollback after ${stage}`),
389
+ eventId: recoveryId,
390
+ recoveryId,
391
+ credentialId: issued.credentialId,
392
+ requiresSink,
393
+ finalizationReceipt: preparedReceipt ? structuredClone(preparedReceipt) : void 0
394
+ };
395
+ try {
396
+ await this.#ledger.appendEvent(pendingEvent);
397
+ } catch {}
398
+ this.#scheduleRollback(recoveryId, issued.credentialId, sinkRecord, stage, requiresSink, preparedReceipt, receiptRecorded);
399
+ throw new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Credential rollback is pending automatic retry", {
400
+ cause: rollbackCause,
401
+ details: {
402
+ recoveryId,
403
+ credentialId: issued.credentialId,
404
+ requiresSink,
405
+ failedStage: stage
406
+ }
407
+ });
408
+ }
409
+ }
410
+ if (safeCause instanceof CustodyError) throw safeCause;
411
+ throw new CustodyError(`CUSTODY_${stage.toUpperCase()}_FAILED`, stage, `Credential custody failed during ${stage}`, { cause: safeCause });
593
412
  }
594
413
  }
595
- async retireTenantKey(tenantId, keyId) {
596
- this.ensureInitialized();
597
- const now = /* @__PURE__ */ new Date();
598
- await this.db.update(this.keysTable, {
599
- id: keyId,
600
- tenant_id: tenantId
601
- }, {
602
- status: "retired",
603
- retired_at: now.toISOString(),
604
- updated_at: now.toISOString()
605
- });
606
- await this.emitEvent({
607
- type: "key.retired",
608
- tenantId,
609
- keyId,
610
- timestamp: now
414
+ async rotate(receiptId, request) {
415
+ if ((await this.#findReceipt(receiptId)).mode !== "durable") throw new CustodyError("DURABLE_ROTATION_REQUIRED", "issue", "Only durable credentials can be rotated");
416
+ return this.issue({
417
+ ...request,
418
+ mode: "durable",
419
+ replacesReceiptId: receiptId
611
420
  });
612
421
  }
613
- async getActiveAMK() {
614
- this.getAMK();
615
- return {
616
- keyId: this.amkConfig.keyId,
617
- description: `AMK from env var ${this.amkConfig.keyEnvVar}`,
618
- status: "active",
619
- provider: "env",
620
- keyReference: this.amkConfig.keyEnvVar,
621
- createdAt: /* @__PURE__ */ new Date()
622
- };
422
+ async revoke(receiptId, reason = "recovery") {
423
+ const receipt = await this.#findReceipt(receiptId);
424
+ this.#leaseInvalidators.get(receiptId)?.();
425
+ await this.#revokeReceipt(receipt, reason);
426
+ this.#leaseInvalidators.delete(receiptId);
623
427
  }
624
- async rewrapTenantKey(_tenantId, _newAmkKeyId) {
625
- throw new Error("AMK rotation not supported for env-based keys. Use AWS KMS, Vault, or Azure Key Vault for AMK rotation support.");
428
+ async recoverPendingRollbacks() {
429
+ const events = await this.#ledger.listEvents();
430
+ const receipts = await this.#ledger.listReceipts();
431
+ const activeIds = new Set(events.filter((event) => event.type === "issued").map((event) => event.receiptId));
432
+ const terminalIds = new Set(events.filter((event) => [
433
+ "revoked",
434
+ "expired",
435
+ "replaced"
436
+ ].includes(event.type)).map((event) => event.receiptId));
437
+ const completedRollbackIds = new Set(events.filter((event) => event.type === "rollback-complete").map((event) => event.recoveryId));
438
+ const rollbackReceiptIds = new Set(events.filter((event) => event.type === "rollback-pending" && !completedRollbackIds.has(event.recoveryId)).map((event) => event.receiptId));
439
+ const pendingByReceipt = new Map(events.filter((event) => event.type === "finalization-pending" && event.receiptId).map((event) => [event.receiptId, event]));
440
+ const takeoverCutoff = this.#now().getTime() - this.#finalizationTakeoverMs;
441
+ const failures = [];
442
+ for (const receipt of receipts.filter((item) => !activeIds.has(item.receiptId) && !terminalIds.has(item.receiptId) && !rollbackReceiptIds.has(item.receiptId) && (() => {
443
+ const pending = pendingByReceipt.get(item.receiptId);
444
+ if (pending) {
445
+ const pendingAt = parseTimestamp(pending.occurredAt, "occurredAt", "reconcile");
446
+ if (pendingAt > takeoverCutoff) {
447
+ this.#scheduleFinalizationTakeover(item.finalizationId, pendingAt + this.#finalizationTakeoverMs);
448
+ return false;
449
+ }
450
+ }
451
+ return pending !== void 0 && parseTimestamp(pending.occurredAt, "occurredAt", "reconcile") <= takeoverCutoff;
452
+ })())) try {
453
+ if (await this.#finalizer.status({ receipt: structuredClone(receipt) }) === "committed") {
454
+ const predecessor = receipt.replacesReceiptId ? receipts.find((item) => item.receiptId === receipt.replacesReceiptId) : void 0;
455
+ const recoveryId = predecessor ? randomUUID() : void 0;
456
+ await this.#ledger.commitIssuance(receipt.receiptId, this.#event("issued", receipt.receiptId), predecessor && recoveryId ? {
457
+ ...this.#event("retirement-pending", predecessor.receiptId),
458
+ eventId: recoveryId,
459
+ recoveryId,
460
+ credentialId: predecessor.credentialId,
461
+ recoveryReceipt: structuredClone(predecessor),
462
+ replacementReceiptId: receipt.receiptId
463
+ } : void 0);
464
+ activeIds.add(receipt.receiptId);
465
+ if (predecessor && recoveryId) this.#scheduleRetirement(recoveryId, predecessor, receipt.receiptId);
466
+ } else await this.#abortAndRevoke(receipt, "incomplete finalization recovery");
467
+ } catch {
468
+ failures.push(receipt.finalizationId);
469
+ this.#scheduleFinalizationTakeover(receipt.finalizationId, this.#now().getTime() + this.#ephemeralRevokeRetryMs);
470
+ }
471
+ for (const receipt of receipts.filter((item) => item.mode === "ephemeral" && activeIds.has(item.receiptId) && !terminalIds.has(item.receiptId) && item.expiresAt !== void 0)) try {
472
+ const deadline = parseTimestamp(receipt.expiresAt ?? "", "expiresAt", "revoke");
473
+ if (deadline <= this.#now().getTime()) await this.#revokeReceipt(receipt, "restart expiry recovery", "expired");
474
+ else this.#scheduleReceiptExpiry(receipt, deadline);
475
+ } catch {
476
+ failures.push(receipt.receiptId);
477
+ }
478
+ const completed = new Set(events.filter((event) => event.type === "rollback-complete").map((event) => event.recoveryId));
479
+ const pendingRollbacks = new Map(events.filter((event) => event.type === "rollback-pending" && event.recoveryId && !completed.has(event.recoveryId)).map((event) => [event.recoveryId, event]));
480
+ for (const pending of pendingRollbacks.values()) {
481
+ if (!pending.credentialId || !pending.recoveryId) continue;
482
+ const timer = this.#pendingTimers.get(pending.recoveryId);
483
+ if (timer) clearTimeout(timer);
484
+ this.#pendingTimers.delete(pending.recoveryId);
485
+ try {
486
+ assertSafeIdentifier(pending.credentialId, "credentialId", "revoke");
487
+ if (pending.receiptId && pending.finalizationReceipt) await this.#abortAndRevoke(pending.finalizationReceipt, "pending rollback recovery");
488
+ else await this.#rollback(pending.credentialId, void 0, "revoke", pending.requiresSink === true);
489
+ await this.#completeRollback(pending.recoveryId, pending.credentialId, pending.sinkReference);
490
+ if (pending.receiptId) {
491
+ terminalIds.add(pending.receiptId);
492
+ this.#leaseInvalidators.delete(pending.receiptId);
493
+ }
494
+ } catch {
495
+ failures.push(pending.recoveryId);
496
+ this.#scheduleRollback(pending.recoveryId, pending.credentialId, void 0, "revoke", pending.requiresSink === true, pending.finalizationReceipt, Boolean(pending.receiptId));
497
+ }
498
+ }
499
+ const retired = new Set(events.filter((event) => event.type === "retirement-complete").map((event) => event.recoveryId));
500
+ for (const pending of events.filter((event) => event.type === "retirement-pending" && event.recoveryId && !retired.has(event.recoveryId))) {
501
+ if (!pending.recoveryId || !pending.recoveryReceipt) continue;
502
+ if (pending.replacementReceiptId && (!activeIds.has(pending.replacementReceiptId) || terminalIds.has(pending.replacementReceiptId))) {
503
+ await this.#ledger.appendEvent({
504
+ ...this.#event("retirement-complete", pending.recoveryReceipt.receiptId),
505
+ recoveryId: pending.recoveryId,
506
+ reason: "replacement is not active"
507
+ });
508
+ continue;
509
+ }
510
+ try {
511
+ await this.#revokeReceipt(pending.recoveryReceipt, "replacement retirement recovery", "replaced");
512
+ await this.#ledger.appendEvent({
513
+ ...this.#event("retirement-complete", pending.recoveryReceipt.receiptId),
514
+ recoveryId: pending.recoveryId
515
+ });
516
+ this.#leaseInvalidators.delete(pending.recoveryReceipt.receiptId);
517
+ } catch {
518
+ failures.push(pending.recoveryId);
519
+ this.#scheduleRetirement(pending.recoveryId, pending.recoveryReceipt, pending.replacementReceiptId);
520
+ }
521
+ }
522
+ if (failures.length) throw new CustodyError("PENDING_ROLLBACK_RECOVERY_FAILED", "revoke", "One or more pending credential rollbacks could not be recovered", { details: { recoveryIds: failures } });
626
523
  }
627
- async listKeyVersions(tenantId) {
628
- this.ensureInitialized();
629
- const { rows } = await this.db.query(`SELECT * FROM "${this.keysTable}" WHERE tenant_id = ? ORDER BY version DESC`, tenantId);
630
- return rows.map((row) => this.parseKeyRow(row));
524
+ async recoverCredential(credentialId, options = {}) {
525
+ assertSafeIdentifier(credentialId, "credentialId", "revoke");
526
+ await this.#rollback(credentialId, void 0, "revoke", options.requiresSink === true);
631
527
  }
632
- /**
633
- * Parse a database row into a TenantDataEncryptionKey
634
- */
635
- parseKeyRow(row) {
528
+ async reconcile() {
529
+ if (!this.#sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "reconcile", "Reconciliation requires a secret sink");
530
+ const [receipts, events, inventory] = await Promise.all([
531
+ this.#ledger.listReceipts(),
532
+ this.#ledger.listEvents(),
533
+ this.#sink.inventory()
534
+ ]);
535
+ for (const entry of inventory) {
536
+ assertSinkRecord(entry, this.#sink.name);
537
+ assertSafeIdentifier(entry.credentialId, "credentialId", "reconcile");
538
+ }
539
+ const terminal = new Set(events.filter((event) => [
540
+ "revoked",
541
+ "expired",
542
+ "replaced"
543
+ ].includes(event.type)).map((event) => event.receiptId));
544
+ const issued = new Set(events.filter((event) => event.type === "issued").map((event) => event.receiptId));
545
+ for (const replacement of receipts) if (replacement.replacesReceiptId && issued.has(replacement.receiptId) && !terminal.has(replacement.receiptId)) terminal.add(replacement.replacesReceiptId);
546
+ const active = receipts.filter((receipt) => receipt.mode === "durable" && receipt.sink !== void 0 && issued.has(receipt.receiptId) && !terminal.has(receipt.receiptId));
547
+ const orphanCutoff = this.#now().getTime() - this.#orphanGraceMs;
636
548
  return {
637
- keyId: row.id,
638
- tenantId: row.tenant_id,
639
- wrappedKey: row.wrapped_key,
640
- amkKeyId: row.amk_key_id,
641
- status: row.status,
642
- version: row.version,
643
- createdAt: new Date(row.created_at),
644
- rotateAfter: row.rotate_after ? new Date(row.rotate_after) : void 0,
645
- retiredAt: row.retired_at ? new Date(row.retired_at) : void 0
549
+ checkedAt: this.#now().toISOString(),
550
+ orphaned: inventory.filter((entry) => parseTimestamp(entry.storedAt, "storedAt", "reconcile") <= orphanCutoff && !active.some((receipt) => sameSinkRecord(receipt.sink, entry) && entry.credentialId === receipt.credentialId)),
551
+ missing: active.filter((receipt) => !inventory.some((entry) => sameSinkRecord(receipt.sink, entry) && entry.credentialId === receipt.credentialId))
646
552
  };
647
553
  }
648
- };
649
- //#endregion
650
- //#region src/shared/custody.ts
651
- var REDACTED = "[REDACTED]";
652
- var MAX_TIMER_DELAY_MS = 2147483647;
653
- var SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;
654
- var ENVIRONMENT_VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
655
- var CREDENTIAL_PATTERNS = [
656
- {
657
- pattern: /\b(?:gh[pousr]|github_pat|hvwk|sk|xox[baprs])_[A-Za-z0-9_-]{16,}\b/gi,
658
- replacement: REDACTED
659
- },
660
- {
661
- pattern: /\b[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\b/g,
662
- replacement: REDACTED
663
- },
664
- {
665
- pattern: /((?:authorization|credential|password|secret|token)\s*[:=]\s*(?:bearer\s+)?)[^\s,;]+/gi,
666
- replacement: `$1${REDACTED}`
667
- }
668
- ];
669
- var environmentLock = Promise.resolve();
670
- var environmentLockContext = new AsyncLocalStorage();
671
- async function withEnvironmentLock(operation) {
672
- if (environmentLockContext.getStore()) throw new CustodyError("REENTRANT_ENVIRONMENT_INJECTION", "inject", "Nested environment credential injection is not allowed");
673
- const previous = environmentLock;
674
- let release = () => void 0;
675
- const current = new Promise((resolve) => {
676
- release = resolve;
677
- });
678
- const queued = previous.then(() => current);
679
- environmentLock = queued;
680
- await previous;
681
- try {
682
- return await environmentLockContext.run(true, operation);
683
- } finally {
684
- release();
685
- if (environmentLock === queued) environmentLock = Promise.resolve();
686
- }
687
- }
688
- var CustodyError = class extends Error {
689
- code;
690
- stage;
691
- details;
692
- constructor(code, stage, message, options) {
693
- super(redactCredentialText(message));
694
- this.name = "CustodyError";
695
- this.code = SAFE_IDENTIFIER.test(code) && redactCredentialText(code) === code ? code : "INVALID_CUSTODY_ERROR_CODE";
696
- this.stage = stage;
697
- this.details = options?.details ? redactCredentialValues(options.details) : void 0;
554
+ async recoverOrphans(report) {
555
+ if (!this.#sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "reconcile", "Orphan recovery requires a secret sink");
556
+ const current = await this.reconcile();
557
+ const requested = new Set(report.orphaned.map((entry) => sinkIdentity(entry, entry.credentialId)));
558
+ const confirmed = current.orphaned.filter((entry) => requested.has(sinkIdentity(entry, entry.credentialId)));
559
+ for (const orphan of confirmed) {
560
+ assertSinkRecord(orphan, this.#sink.name);
561
+ await this.#ledger.appendEvent(this.#event("orphan-detected", void 0, orphan.reference));
562
+ assertSafeIdentifier(orphan.credentialId, "credentialId", "reconcile");
563
+ try {
564
+ await this.#issuer.revoke(orphan.credentialId, "orphan recovery");
565
+ } catch {
566
+ throw new CustodyError("ORPHAN_REVOCATION_FAILED", "reconcile", "Orphan credential revocation failed");
567
+ }
568
+ await this.#sink.remove(orphan, "orphan recovery");
569
+ await this.#ledger.appendEvent(this.#event("orphan-removed", void 0, orphan.reference));
570
+ }
698
571
  }
699
- toJSON() {
572
+ #createLease(receipt, ephemeralMaterial) {
573
+ let unavailable = false;
574
+ let revocationComplete = false;
575
+ let revocationInFlight;
576
+ let timer;
577
+ const revoke = async (reason = "requested", terminalType = "revoked") => {
578
+ unavailable = true;
579
+ if (timer) clearTimeout(timer);
580
+ ephemeralMaterial?.destroy();
581
+ if (revocationComplete) return;
582
+ if (revocationInFlight) return revocationInFlight;
583
+ revocationInFlight = this.#revokeReceipt(receipt, reason, terminalType).then(() => {
584
+ revocationComplete = true;
585
+ this.#leaseInvalidators.delete(receipt.receiptId);
586
+ }).finally(() => {
587
+ revocationInFlight = void 0;
588
+ });
589
+ return revocationInFlight;
590
+ };
591
+ const invalidate = () => {
592
+ unavailable = true;
593
+ if (timer) clearTimeout(timer);
594
+ ephemeralMaterial?.destroy();
595
+ };
596
+ this.#leaseInvalidators.set(receipt.receiptId, invalidate);
597
+ if (receipt.mode === "ephemeral" && receipt.expiresAt) {
598
+ const deadline = parseTimestamp(receipt.expiresAt, "expiresAt", "issue");
599
+ const schedule = (delay) => {
600
+ timer = setTimeout(() => {
601
+ const remaining = deadline - this.#now().getTime();
602
+ if (remaining > 0) {
603
+ schedule(Math.min(remaining, MAX_TIMER_DELAY_MS));
604
+ return;
605
+ }
606
+ revoke("expired", "expired").catch((cause) => {
607
+ try {
608
+ this.#onBackgroundError?.(cause instanceof CustodyError ? cause : new CustodyError("EPHEMERAL_CLEANUP_FAILED", "revoke", "Ephemeral credential cleanup failed", { cause }));
609
+ } catch {} finally {
610
+ schedule(this.#ephemeralRevokeRetryMs);
611
+ }
612
+ });
613
+ }, Math.min(Math.max(0, delay), MAX_TIMER_DELAY_MS));
614
+ timer.unref?.();
615
+ };
616
+ schedule(deadline - this.#now().getTime());
617
+ }
700
618
  return {
701
- name: this.name,
702
- code: this.code,
703
- stage: this.stage,
704
- message: this.message,
705
- ...this.details ? { details: this.details } : {}
619
+ receipt: structuredClone(receipt),
620
+ withEnvironment: async (variableName, operation) => {
621
+ this.#assertLeaseAvailable(receipt, unavailable);
622
+ if (!ENVIRONMENT_VARIABLE.test(variableName)) throw new CustodyError("INVALID_ENVIRONMENT_VARIABLE", "inject", "Environment variable name is invalid");
623
+ let material = ephemeralMaterial;
624
+ if (!material) {
625
+ if (!this.#sink || !receipt.sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "retrieve", "Durable credential retrieval requires a secret sink record");
626
+ material = await this.#sink.retrieve(receipt.sink);
627
+ }
628
+ try {
629
+ this.#assertLeaseAvailable(receipt, unavailable);
630
+ await withEnvironmentSecret(material, variableName, operation, { expiresAt: receipt.expiresAt });
631
+ } finally {
632
+ if (!ephemeralMaterial) material.destroy();
633
+ }
634
+ },
635
+ withChildProcess: async (options) => {
636
+ this.#assertLeaseAvailable(receipt, unavailable);
637
+ let material = ephemeralMaterial;
638
+ if (!material) {
639
+ if (!this.#sink || !receipt.sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "retrieve", "Durable credential retrieval requires a secret sink record");
640
+ material = await this.#sink.retrieve(receipt.sink);
641
+ }
642
+ try {
643
+ this.#assertLeaseAvailable(receipt, unavailable);
644
+ return await runCredentialChildProcess(material, options, { expiresAt: receipt.expiresAt });
645
+ } catch (cause) {
646
+ if (cause instanceof CustodyError && cause.code === "CREDENTIAL_CHILD_PROCESS_CLEANUP_FAILED") {
647
+ invalidate();
648
+ await this.#recoverChildProcessCleanupFailure(receipt);
649
+ }
650
+ throw cause;
651
+ } finally {
652
+ if (!ephemeralMaterial) material.destroy();
653
+ }
654
+ },
655
+ revoke: (reason) => revoke(reason)
706
656
  };
707
657
  }
708
- };
709
- var SecretMaterial = class SecretMaterial {
710
- #bytes;
711
- #destroyed = false;
712
- constructor(value) {
713
- this.#bytes = Buffer.from(value, "utf8");
714
- }
715
- static fromString(value) {
716
- if (!value) throw new CustodyError("EMPTY_SECRET_MATERIAL", "issue", "Secret material must not be empty");
717
- return new SecretMaterial(value);
718
- }
719
- get destroyed() {
720
- return this.#destroyed;
658
+ #assertLeaseAvailable(receipt, unavailable) {
659
+ const expired = receipt.expiresAt !== void 0 && parseTimestamp(receipt.expiresAt, "expiresAt", "inject") <= this.#now().getTime();
660
+ if (unavailable || expired) throw new CustodyError("CREDENTIAL_REVOKED", "inject", "Credential is no longer available");
721
661
  }
722
- async use(operation) {
723
- if (this.#destroyed) throw new CustodyError("SECRET_MATERIAL_DESTROYED", "inject", "Secret material is no longer available");
724
- const plaintext = this.#bytes.toString("utf8");
662
+ async #revokeReceipt(receipt, reason, terminalType = "revoked") {
663
+ const failures = [];
725
664
  try {
726
- await operation(plaintext);
727
- } catch (cause) {
728
- if (cause instanceof CustodyError) throw new CustodyError(redactCredentialText(cause.code, [plaintext]) === cause.code ? cause.code : "INVALID_CUSTODY_ERROR_CODE", cause.stage, redactCredentialText(cause.message, [plaintext]), { details: redactCredentialValues(cause.details, [plaintext]) });
729
- throw new CustodyError("SECRET_MATERIAL_OPERATION_FAILED", "inject", "Secret material operation failed", { cause });
665
+ await this.#issuer.revoke(receipt.credentialId, reason);
666
+ } catch {
667
+ failures.push("issuer");
730
668
  }
669
+ if (!failures.length && receipt.sink && this.#sink) try {
670
+ await this.#sink.remove(receipt.sink, reason);
671
+ } catch {
672
+ failures.push("sink");
673
+ }
674
+ if (failures.length) throw new CustodyError("CREDENTIAL_REVOCATION_FAILED", "revoke", "Credential revocation did not complete", { details: { failedOperations: failures } });
675
+ await this.#appendEventEventually(this.#event(terminalType, receipt.receiptId, void 0, reason));
731
676
  }
732
- destroy() {
733
- this.#bytes.fill(0);
734
- this.#destroyed = true;
735
- }
736
- toJSON() {
737
- return REDACTED;
738
- }
739
- toString() {
740
- return REDACTED;
741
- }
742
- [Symbol.for("nodejs.util.inspect.custom")]() {
743
- return REDACTED;
677
+ async #rollback(credentialId, sinkRecord, failedStage, requiresSink = false) {
678
+ const failures = [];
679
+ try {
680
+ await this.#issuer.revoke(credentialId, `rollback after ${failedStage}`);
681
+ } catch {
682
+ failures.push("issuer");
683
+ }
684
+ if (!failures.length && requiresSink && !this.#sink) failures.push("sink");
685
+ if (!failures.length && requiresSink && this.#sink) try {
686
+ if (sinkRecord) await this.#sink.remove(sinkRecord, `rollback after ${failedStage}`);
687
+ else await this.#sink.removeByCredentialId(credentialId, `rollback after ${failedStage}`);
688
+ } catch {
689
+ failures.push("sink");
690
+ }
691
+ if (failures.length) throw new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Credential rollback did not complete", { details: {
692
+ failedOperations: failures,
693
+ failedStage
694
+ } });
744
695
  }
745
- };
746
- var Ed25519CustodyReceiptAttestor = class {
747
- name;
748
- keyId;
749
- #privateKey;
750
- constructor(options) {
751
- if (options.privateKey.type !== "private" || options.privateKey.asymmetricKeyType !== "ed25519") throw new CustodyError("INVALID_ATTESTATION_KEY", "record", "Custody attestation requires a private signing key");
752
- this.#privateKey = options.privateKey;
753
- this.name = options.name ?? "ed25519";
754
- this.keyId = options.keyId;
755
- assertSafeIdentifier(this.name, "attestor.name", "record");
756
- assertSafeIdentifier(this.keyId, "attestor.keyId", "record");
757
- }
758
- async attest(payload) {
759
- return sign(null, Buffer.from(payload), this.#privateKey).toString("base64url");
696
+ async #abortAndRevoke(receipt, reason) {
697
+ const failures = [];
698
+ try {
699
+ await this.#finalizer.abort({
700
+ receipt: structuredClone(receipt),
701
+ reason
702
+ });
703
+ } catch {
704
+ failures.push("finalizer");
705
+ }
706
+ try {
707
+ await this.#revokeReceipt(receipt, reason);
708
+ } catch {
709
+ failures.push("credential");
710
+ }
711
+ if (failures.length) throw new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Finalization rollback did not complete", { details: { failedOperations: failures } });
760
712
  }
761
- };
762
- var InMemoryCustodyLedger = class {
763
- #receipts = [];
764
- #events = [];
765
- async recordIssuance(receipt, event) {
766
- if (event.type !== "finalization-pending") throw new CustodyError("INVALID_CUSTODY_EVENT", "record", "Prepared receipt requires a finalization-pending event");
767
- if (this.#receipts.some((item) => item.receiptId === receipt.receiptId)) throw new CustodyError("DUPLICATE_CUSTODY_RECEIPT", "record", "Custody receipt already exists");
768
- if (receipt.replacesReceiptId) {
769
- const predecessor = this.#receipts.find((item) => item.receiptId === receipt.replacesReceiptId);
770
- const predecessorTerminal = this.#events.some((item) => item.receiptId === receipt.replacesReceiptId && [
771
- "revoked",
772
- "expired",
773
- "replaced"
774
- ].includes(item.type));
775
- const predecessorIssued = this.#events.some((item) => item.receiptId === receipt.replacesReceiptId && item.type === "issued");
776
- const existingChild = this.#receipts.some((item) => item.replacesReceiptId === receipt.replacesReceiptId && !this.#events.some((event) => event.receiptId === item.receiptId && [
777
- "revoked",
778
- "expired",
779
- "replaced"
780
- ].includes(event.type)));
781
- if (!predecessor || !predecessorIssued || predecessorTerminal || existingChild) throw new CustodyError("CUSTODY_ROTATION_CONFLICT", "record", "Custody predecessor is not active and replaceable");
713
+ async #recoverChildProcessCleanupFailure(receipt) {
714
+ const reason = "child process cleanup could not be verified";
715
+ try {
716
+ await this.#abortAndRevoke(receipt, reason);
717
+ this.#leaseInvalidators.delete(receipt.receiptId);
718
+ return;
719
+ } catch (cause) {
720
+ const recoveryId = randomUUID();
721
+ const pendingEvent = {
722
+ ...this.#event("rollback-pending", receipt.receiptId, receipt.sink?.reference, reason),
723
+ eventId: recoveryId,
724
+ recoveryId,
725
+ credentialId: receipt.credentialId,
726
+ requiresSink: receipt.mode === "durable",
727
+ finalizationReceipt: structuredClone(receipt)
728
+ };
729
+ await this.#persistRollbackIntent(pendingEvent);
730
+ this.#scheduleRollback(recoveryId, receipt.credentialId, receipt.sink, "inject", receipt.mode === "durable", receipt, true);
731
+ try {
732
+ this.#onBackgroundError?.(new CustodyError("CREDENTIAL_CHILD_PROCESS_CLEANUP_PENDING", "revoke", "Credential revocation is pending after child process cleanup failure", {
733
+ cause,
734
+ details: { recoveryId }
735
+ }));
736
+ } catch {}
782
737
  }
783
- this.#receipts.push(structuredClone(receipt));
784
- this.#events.push(structuredClone(event));
785
738
  }
786
- async appendEvent(event) {
787
- const existing = this.#events.find((item) => item.eventId === event.eventId);
788
- if (existing) {
789
- if (sameCustodyEvent(existing, event)) return;
790
- throw new CustodyError("CUSTODY_EVENT_ID_CONFLICT", "record", "Custody event ID is already bound to different content");
739
+ async #persistRollbackIntent(event) {
740
+ for (;;) try {
741
+ await this.#ledger.appendEvent(event);
742
+ return;
743
+ } catch (cause) {
744
+ try {
745
+ if ((await this.#ledger.listEvents()).some((existing) => existing.eventId === event.eventId && sameCustodyEvent(existing, event))) return;
746
+ } catch {}
747
+ try {
748
+ this.#onBackgroundError?.(new CustodyError("ROLLBACK_INTENT_PERSISTENCE_FAILED", "record", "Credential rollback intent persistence is retrying", {
749
+ cause,
750
+ details: { recoveryId: event.recoveryId }
751
+ }));
752
+ } catch {}
753
+ await new Promise((resolve) => {
754
+ setTimeout(resolve, this.#ephemeralRevokeRetryMs);
755
+ });
791
756
  }
792
- this.#events.push(structuredClone(event));
793
757
  }
794
- async commitIssuance(receiptId, event, followup) {
795
- if (event.type !== "issued" || followup !== void 0 && followup.type !== "retirement-pending") throw new CustodyError("INVALID_CUSTODY_EVENT", "record", "Issuance commit requires issued and optional retirement-pending events");
796
- if (!this.#receipts.some((receipt) => receipt.receiptId === receiptId)) throw new CustodyError("CUSTODY_RECEIPT_NOT_FOUND", "record", "Prepared custody receipt was not found");
797
- if (!this.#events.some((item) => item.receiptId === receiptId && item.type === "issued")) {
798
- this.#events.push(structuredClone(event));
799
- if (followup) this.#events.push(structuredClone(followup));
758
+ #scheduleRollback(recoveryId, credentialId, sinkRecord, failedStage, requiresSink, finalizationReceipt, receiptRecorded = false) {
759
+ if (this.#pendingTimers.has(recoveryId)) return;
760
+ const timer = setTimeout(() => {
761
+ this.#pendingTimers.delete(recoveryId);
762
+ Promise.resolve().then(async () => {
763
+ if (receiptRecorded && finalizationReceipt) await this.#abortAndRevoke(finalizationReceipt, `rollback after ${failedStage}`);
764
+ else await this.#rollback(credentialId, sinkRecord, failedStage, requiresSink);
765
+ }).then(() => this.#completeRollback(recoveryId, credentialId, sinkRecord?.reference)).then(() => {
766
+ if (receiptRecorded && finalizationReceipt) this.#leaseInvalidators.delete(finalizationReceipt.receiptId);
767
+ }).catch((cause) => {
768
+ try {
769
+ this.#onBackgroundError?.(cause instanceof CustodyError ? cause : new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Credential rollback retry failed", { cause }));
770
+ } catch {} finally {
771
+ this.#scheduleRollback(recoveryId, credentialId, sinkRecord, failedStage, requiresSink, finalizationReceipt, receiptRecorded);
772
+ }
773
+ });
774
+ }, this.#ephemeralRevokeRetryMs);
775
+ this.#pendingTimers.set(recoveryId, timer);
776
+ timer.unref?.();
777
+ }
778
+ #scheduleRetirement(recoveryId, receipt, replacementReceiptId) {
779
+ if (this.#pendingTimers.has(recoveryId)) return;
780
+ const timer = setTimeout(() => {
781
+ this.#pendingTimers.delete(recoveryId);
782
+ this.#ledger.listEvents().then(async (events) => {
783
+ if (replacementReceiptId && (!events.some((event) => event.receiptId === replacementReceiptId && event.type === "issued") || events.some((event) => event.receiptId === replacementReceiptId && [
784
+ "revoked",
785
+ "expired",
786
+ "replaced"
787
+ ].includes(event.type)))) return;
788
+ await this.#revokeReceipt(receipt, "replacement retirement retry", "replaced");
789
+ this.#leaseInvalidators.delete(receipt.receiptId);
790
+ }).then(() => this.#ledger.appendEvent({
791
+ ...this.#event("retirement-complete", receipt.receiptId),
792
+ recoveryId
793
+ })).catch(() => this.#scheduleRetirement(recoveryId, receipt, replacementReceiptId));
794
+ }, this.#ephemeralRevokeRetryMs);
795
+ this.#pendingTimers.set(recoveryId, timer);
796
+ timer.unref?.();
797
+ }
798
+ #scheduleReceiptExpiry(receipt, deadline) {
799
+ if (this.#pendingTimers.has(receipt.receiptId)) return;
800
+ const delay = Math.min(Math.max(0, deadline - this.#now().getTime()), MAX_TIMER_DELAY_MS);
801
+ const timer = setTimeout(() => {
802
+ this.#pendingTimers.delete(receipt.receiptId);
803
+ if (deadline > this.#now().getTime()) {
804
+ this.#scheduleReceiptExpiry(receipt, deadline);
805
+ return;
806
+ }
807
+ this.#revokeReceipt(receipt, "restart expiry recovery", "expired").catch(() => this.#scheduleReceiptExpiry(receipt, deadline));
808
+ }, delay);
809
+ this.#pendingTimers.set(receipt.receiptId, timer);
810
+ timer.unref?.();
811
+ }
812
+ #scheduleFinalizationTakeover(recoveryId, deadline) {
813
+ if (this.#pendingTimers.has(recoveryId)) return;
814
+ const timer = setTimeout(() => {
815
+ this.#pendingTimers.delete(recoveryId);
816
+ this.recoverPendingRollbacks().catch((cause) => {
817
+ try {
818
+ this.#onBackgroundError?.(cause instanceof CustodyError ? cause : new CustodyError("PENDING_ROLLBACK_RECOVERY_FAILED", "revoke", "Finalization takeover recovery failed", { cause }));
819
+ } catch {}
820
+ });
821
+ }, Math.min(Math.max(0, deadline - this.#now().getTime()), MAX_TIMER_DELAY_MS));
822
+ this.#pendingTimers.set(recoveryId, timer);
823
+ timer.unref?.();
824
+ }
825
+ async #completeRollback(recoveryId, credentialId, sinkReference) {
826
+ await this.#ledger.appendEvent({
827
+ ...this.#event("rollback-complete", void 0, sinkReference, "credential rollback completed"),
828
+ recoveryId,
829
+ credentialId
830
+ });
831
+ }
832
+ async #appendEventEventually(event) {
833
+ try {
834
+ await this.#ledger.appendEvent(event);
835
+ } catch (cause) {
836
+ const recoveryId = `event-${event.eventId}`;
837
+ if (this.#pendingTimers.has(recoveryId)) return;
838
+ const timer = setTimeout(() => {
839
+ this.#pendingTimers.delete(recoveryId);
840
+ this.#appendEventEventually(event).catch(() => void 0);
841
+ }, this.#ephemeralRevokeRetryMs);
842
+ this.#pendingTimers.set(recoveryId, timer);
843
+ try {
844
+ this.#onBackgroundError?.(new CustodyError("CUSTODY_EVENT_RECORD_FAILED", "record", "Custody terminal event recording is pending retry", { cause }));
845
+ } catch {}
800
846
  }
801
847
  }
802
- async listReceipts() {
803
- return structuredClone(this.#receipts);
848
+ async #findReceipt(receiptId) {
849
+ assertSafeIdentifier(receiptId, "receiptId", "record");
850
+ const receipt = (await this.#ledger.listReceipts()).find((candidate) => candidate.receiptId === receiptId);
851
+ if (!receipt) throw new CustodyError("CUSTODY_RECEIPT_NOT_FOUND", "record", "Custody receipt was not found");
852
+ return receipt;
804
853
  }
805
- async listEvents() {
806
- return structuredClone(this.#events);
854
+ #event(type, receiptId, sinkReference, reason) {
855
+ return {
856
+ eventId: randomUUID(),
857
+ type,
858
+ occurredAt: this.#now().toISOString(),
859
+ ...receiptId ? { receiptId } : {},
860
+ ...sinkReference ? { sinkReference } : {},
861
+ ...reason ? { reason: redactCredentialText(reason) } : {}
862
+ };
807
863
  }
808
864
  };
809
- var CredentialCustody = class {
810
- #issuer;
811
- #verifier;
812
- #ledger;
813
- #attestor;
814
- #finalizer;
815
- #sink;
816
- #ephemeralTtlMs;
817
- #ephemeralRevokeRetryMs;
818
- #orphanGraceMs;
819
- #finalizationTakeoverMs;
820
- #now;
821
- #onBackgroundError;
822
- #leaseInvalidators = /* @__PURE__ */ new Map();
823
- #pendingTimers = /* @__PURE__ */ new Map();
824
- constructor(options) {
825
- assertSafeIdentifier(options.issuer.name, "issuer.name", "issue");
826
- assertSafeIdentifier(options.verifier.name, "verifier.name", "verify");
827
- assertSafeIdentifier(options.attestor.name, "attestor.name", "record");
828
- assertSafeIdentifier(options.attestor.keyId, "attestor.keyId", "record");
829
- assertSafeIdentifier(options.finalizer.name, "finalizer.name", "activate");
830
- if (options.sink) assertSafeIdentifier(options.sink.name, "sink.name", "store");
831
- this.#issuer = options.issuer;
832
- this.#verifier = options.verifier;
833
- this.#ledger = options.ledger;
834
- this.#attestor = options.attestor;
835
- this.#finalizer = options.finalizer;
836
- this.#sink = options.sink;
837
- this.#ephemeralTtlMs = options.ephemeralTtlMs ?? 5 * 6e4;
838
- this.#ephemeralRevokeRetryMs = options.ephemeralRevokeRetryMs ?? 1e3;
839
- this.#orphanGraceMs = options.orphanGraceMs ?? 5 * 6e4;
840
- this.#finalizationTakeoverMs = options.finalizationTakeoverMs ?? 3e4;
841
- if (!Number.isFinite(this.#ephemeralTtlMs) || !Number.isFinite(this.#ephemeralRevokeRetryMs) || !Number.isFinite(this.#orphanGraceMs) || !Number.isFinite(this.#finalizationTakeoverMs) || this.#ephemeralTtlMs <= 0 || this.#ephemeralRevokeRetryMs <= 0 || this.#orphanGraceMs < 0 || this.#finalizationTakeoverMs < 0) throw new CustodyError("INVALID_CUSTODY_DURATION", "issue", "Custody durations must be positive");
842
- this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
843
- this.#onBackgroundError = options.onBackgroundError;
865
+ async function withEnvironmentSecret(material, variableName, operation, bounds) {
866
+ if (!ENVIRONMENT_VARIABLE.test(variableName)) throw new CustodyError("INVALID_ENVIRONMENT_VARIABLE", "inject", "Environment variable name is invalid");
867
+ if (bounds?.expiresAt) {
868
+ parseTimestamp(bounds.expiresAt, "expiresAt", "inject");
869
+ throw new CustodyError("EXPIRING_ENVIRONMENT_CALLBACK_UNSAFE", "inject", "Expiring credentials require bounded child-process injection");
844
870
  }
845
- async issue(request) {
846
- if (request.mode === "durable" && !this.#sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "store", "Durable credential issuance requires a secret sink");
847
- if (request.replacesReceiptId && request.mode !== "durable") throw new CustodyError("DURABLE_ROTATION_REQUIRED", "issue", "Credential replacement requires durable mode");
848
- assertSafeIdentifier(request.subject, "subject", "issue");
849
- assertAttribution(request.attribution);
850
- const replacedReceipt = request.replacesReceiptId ? await this.#findReceipt(request.replacesReceiptId) : void 0;
851
- if (replacedReceipt?.mode !== void 0 && replacedReceipt.mode !== "durable") throw new CustodyError("DURABLE_ROTATION_REQUIRED", "issue", "Only durable credentials can be replaced");
852
- const now = this.#now();
853
- const expiresAt = request.expiresAt ?? (request.mode === "ephemeral" ? new Date(now.getTime() + this.#ephemeralTtlMs).toISOString() : void 0);
854
- const requestedExpiryMs = expiresAt ? parseTimestamp(expiresAt, "expiresAt", "issue") : void 0;
855
- if (requestedExpiryMs !== void 0 && requestedExpiryMs <= now.getTime()) throw new CustodyError("INVALID_EXPIRY", "issue", "Credential expiry must be in the future");
856
- const metadata = sanitizeMetadata(request.metadata);
857
- let issued;
858
- let sinkRecord;
859
- let retrieved;
860
- let preparedReceipt;
861
- let receiptRecorded = false;
862
- let stage = "issue";
871
+ await withEnvironmentLock(async () => {
872
+ const existed = Object.hasOwn(process.env, variableName);
873
+ const previous = process.env[variableName];
863
874
  try {
864
- issued = await this.#issuer.issue({
865
- mode: request.mode,
866
- subject: request.subject,
867
- expiresAt,
868
- metadata
875
+ await material.use(async (value) => {
876
+ process.env[variableName] = value;
877
+ await operation();
869
878
  });
870
- assertSafeIdentifier(issued.credentialId, "credentialId", "issue");
871
- if (issued.issuedAt) parseTimestamp(issued.issuedAt, "issuedAt", "issue");
872
- if (issued.expiresAt) {
873
- const providerExpiryMs = parseTimestamp(issued.expiresAt, "provider expiresAt", "issue");
874
- if (providerExpiryMs <= now.getTime()) throw new CustodyError("INVALID_EXPIRY", "issue", "Credential provider returned an expired credential");
875
- if (requestedExpiryMs !== void 0 && providerExpiryMs > requestedExpiryMs) throw new CustodyError("EXPIRY_BOUND_EXCEEDED", "issue", "Credential provider exceeded the requested expiry bound");
876
- }
877
- let material = issued.secret;
878
- if (request.mode === "durable") {
879
- const sink = this.#sink;
880
- if (!sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "store", "Durable credential issuance requires a secret sink");
881
- stage = "store";
882
- sinkRecord = await sink.store({
883
- credentialId: issued.credentialId,
884
- secret: issued.secret,
885
- metadata
886
- });
887
- assertSinkRecord(sinkRecord, sink.name);
888
- stage = "retrieve";
889
- retrieved = await sink.retrieve(sinkRecord);
890
- material = retrieved;
891
- }
892
- stage = "verify";
893
- const verification = await this.#verifier.verify({
894
- credentialId: issued.credentialId,
895
- secret: material
879
+ } catch (cause) {
880
+ if (cause instanceof CustodyError) throw cause;
881
+ throw new CustodyError("SECRET_OPERATION_FAILED", "inject", "Bounded secret operation failed", { cause });
882
+ } finally {
883
+ if (existed) process.env[variableName] = previous;
884
+ else delete process.env[variableName];
885
+ }
886
+ });
887
+ }
888
+ async function runCredentialChildProcess(material, options, bounds) {
889
+ if (options.trust !== "cooperative-process-group" || !options.command || !ENVIRONMENT_VARIABLE.test(options.environmentVariable)) throw new CustodyError("INVALID_CHILD_PROCESS_OPTIONS", "inject", "Credential child-process options are invalid");
890
+ if (process.platform === "win32") throw new CustodyError("CREDENTIAL_CHILD_PROCESS_UNSUPPORTED", "inject", "Credential child-process group custody is unavailable on this platform");
891
+ const timeoutMs = options.timeoutMs ?? 6e4;
892
+ const maxOutputBytes = options.maxOutputBytes ?? 1024 * 1024;
893
+ if (!Number.isFinite(timeoutMs) || !Number.isFinite(maxOutputBytes) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DELAY_MS || maxOutputBytes <= 0) throw new CustodyError("INVALID_CHILD_PROCESS_BOUNDS", "inject", "Credential child-process bounds must be positive");
894
+ let result;
895
+ await material.use(async (secret) => {
896
+ const expiryLimit = bounds?.expiresAt ? parseTimestamp(bounds.expiresAt, "expiresAt", "inject") - Date.now() : Number.POSITIVE_INFINITY;
897
+ const effectiveTimeout = Math.min(timeoutMs, expiryLimit);
898
+ if (effectiveTimeout <= 0) throw new CustodyError("CREDENTIAL_EXPIRED", "inject", "Credential expired before child-process launch");
899
+ const childEnvironment = await withEnvironmentLock(() => ({
900
+ ...process.env,
901
+ ...options.environment,
902
+ [options.environmentVariable]: secret
903
+ }));
904
+ result = await new Promise((resolve, reject) => {
905
+ const child = spawn(options.command, [...options.args ?? []], {
906
+ cwd: options.cwd,
907
+ detached: true,
908
+ env: childEnvironment,
909
+ shell: false,
910
+ stdio: [
911
+ "ignore",
912
+ "pipe",
913
+ "pipe"
914
+ ]
896
915
  });
897
- if (!verification.verified) throw new CustodyError("CREDENTIAL_VERIFICATION_FAILED", "verify", "Credential verification failed");
898
- if (verification.verificationId) assertSafeIdentifier(verification.verificationId, "verificationId", "verify");
899
- const receiptId = randomUUID();
900
- const finalizationId = randomUUID();
901
- const unsignedReceipt = {
902
- receiptId,
903
- mode: request.mode,
904
- credentialId: issued.credentialId,
905
- subject: request.subject,
906
- issuer: this.#issuer.name,
907
- verifier: this.#verifier.name,
908
- ...verification.verificationId ? { verificationId: verification.verificationId } : {},
909
- verificationState: "verified",
910
- issuedAt: issued.issuedAt ?? now.toISOString(),
911
- verifiedAt: this.#now().toISOString(),
912
- ...issued.expiresAt ?? expiresAt ? { expiresAt: issued.expiresAt ?? expiresAt } : {},
913
- ...sinkRecord ? { sink: sinkRecord } : {},
914
- ...request.replacesReceiptId ? { replacesReceiptId: request.replacesReceiptId } : {},
915
- rotationRootReceiptId: replacedReceipt?.rotationRootReceiptId ?? receiptId,
916
- attribution: { ...request.attribution },
917
- metadata,
918
- finalizer: this.#finalizer.name,
919
- finalizationId
916
+ const stdout = [];
917
+ const stderr = [];
918
+ let outputBytes = 0;
919
+ let outputExceeded = false;
920
+ let timedOut = false;
921
+ let settled = false;
922
+ let escalationTimer;
923
+ const terminateGroup = (signal) => {
924
+ if (child.pid) try {
925
+ process.kill(-child.pid, signal);
926
+ return;
927
+ } catch {}
928
+ child.kill(signal);
920
929
  };
921
- stage = "record";
922
- let signature = "";
923
- await material.use(async (plaintext) => {
924
- signature = await this.#attestor.attest(custodyAttestationPayload(unsignedReceipt, credentialCommitment(plaintext), {
925
- algorithm: "Ed25519",
926
- attestor: this.#attestor.name,
927
- keyId: this.#attestor.keyId
928
- }));
929
- });
930
- if (!/^[A-Za-z0-9_-]{86}$/.test(signature) || Buffer.from(signature, "base64url").byteLength !== 64 || Buffer.from(signature, "base64url").toString("base64url") !== signature || redactCredentialText(signature) !== signature) throw new CustodyError("INVALID_CUSTODY_ATTESTATION", "record", "Custody attestor returned an invalid signature");
931
- const receipt = {
932
- ...unsignedReceipt,
933
- attestation: {
934
- algorithm: "Ed25519",
935
- attestor: this.#attestor.name,
936
- keyId: this.#attestor.keyId,
937
- signature
930
+ const waitForGroupExit = async () => {
931
+ if (!child.pid) return true;
932
+ const deadline = Date.now() + 2e3;
933
+ while (Date.now() < deadline) {
934
+ try {
935
+ process.kill(-child.pid, 0);
936
+ } catch (cause) {
937
+ if (cause.code === "ESRCH") return true;
938
+ }
939
+ await new Promise((next) => setTimeout(next, 10));
938
940
  }
941
+ return false;
939
942
  };
940
- stage = "record";
941
- await this.#ledger.recordIssuance(receipt, this.#event("finalization-pending", receiptId));
942
- receiptRecorded = true;
943
- stage = "activate";
944
- preparedReceipt = receipt;
945
- if (!(await this.#finalizer.prepare({
946
- receipt: structuredClone(receipt),
947
- secret: material
948
- })).prepared) throw new CustodyError("CREDENTIAL_ACTIVATION_FAILED", "activate", "Credential post-attestation activation failed");
949
- retrieved?.destroy();
950
- retrieved = void 0;
951
- if (request.mode === "durable") issued.secret.destroy();
952
- stage = "activate";
953
- await this.#finalizer.commit({ receipt: structuredClone(receipt) });
954
- stage = "record";
955
- const retirementRecoveryId = replacedReceipt ? randomUUID() : void 0;
956
- const retirementPending = replacedReceipt && retirementRecoveryId ? {
957
- ...this.#event("retirement-pending", replacedReceipt.receiptId),
958
- eventId: retirementRecoveryId,
959
- recoveryId: retirementRecoveryId,
960
- credentialId: replacedReceipt.credentialId,
961
- recoveryReceipt: structuredClone(replacedReceipt),
962
- replacementReceiptId: receipt.receiptId
963
- } : void 0;
964
- await this.#ledger.commitIssuance(receipt.receiptId, this.#event("issued", receipt.receiptId), retirementPending);
965
- const lease = this.#createLease(receipt, request.mode === "ephemeral" ? issued.secret : void 0);
966
- if (replacedReceipt) try {
967
- this.#leaseInvalidators.get(replacedReceipt.receiptId)?.();
968
- await this.#revokeReceipt(replacedReceipt, "replaced", "replaced");
969
- this.#leaseInvalidators.delete(replacedReceipt.receiptId);
970
- await this.#ledger.appendEvent({
971
- ...this.#event("retirement-complete", replacedReceipt.receiptId),
972
- recoveryId: retirementRecoveryId
973
- });
974
- } catch (cause) {
975
- if (retirementRecoveryId) this.#scheduleRetirement(retirementRecoveryId, replacedReceipt, receipt.receiptId);
976
- try {
977
- this.#onBackgroundError?.(new CustodyError("PREDECESSOR_RETIREMENT_PENDING", "revoke", "Replacement is active while predecessor retirement retries", {
978
- cause,
979
- details: { recoveryId: retirementRecoveryId }
980
- }));
981
- } catch {}
982
- }
983
- preparedReceipt = void 0;
984
- return lease;
985
- } catch (cause) {
986
- const safeCause = await sanitizeCustodyCause(cause, [retrieved, issued?.secret]);
987
- retrieved?.destroy();
988
- issued?.secret.destroy();
989
- if (issued) {
990
- const requiresSink = request.mode === "durable";
991
- try {
992
- if (receiptRecorded && preparedReceipt) await this.#abortAndRevoke(preparedReceipt, `rollback after ${stage}`);
993
- else await this.#rollback(issued.credentialId, sinkRecord, stage, requiresSink);
994
- } catch (rollbackCause) {
995
- const recoveryId = randomUUID();
996
- const pendingEvent = {
997
- ...this.#event("rollback-pending", receiptRecorded ? preparedReceipt?.receiptId : void 0, sinkRecord?.reference, `rollback after ${stage}`),
998
- eventId: recoveryId,
999
- recoveryId,
1000
- credentialId: issued.credentialId,
1001
- requiresSink,
1002
- finalizationReceipt: preparedReceipt ? structuredClone(preparedReceipt) : void 0
1003
- };
1004
- try {
1005
- await this.#ledger.appendEvent(pendingEvent);
1006
- } catch {}
1007
- this.#scheduleRollback(recoveryId, issued.credentialId, sinkRecord, stage, requiresSink, preparedReceipt, receiptRecorded);
1008
- throw new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Credential rollback is pending automatic retry", {
1009
- cause: rollbackCause,
1010
- details: {
1011
- recoveryId,
1012
- credentialId: issued.credentialId,
1013
- requiresSink,
1014
- failedStage: stage
1015
- }
1016
- });
943
+ const beginTermination = () => {
944
+ terminateGroup("SIGTERM");
945
+ if (!escalationTimer) {
946
+ escalationTimer = setTimeout(() => {
947
+ escalationTimer = void 0;
948
+ terminateGroup("SIGKILL");
949
+ }, 1e3);
950
+ escalationTimer.unref?.();
1017
951
  }
1018
- }
1019
- if (safeCause instanceof CustodyError) throw safeCause;
1020
- throw new CustodyError(`CUSTODY_${stage.toUpperCase()}_FAILED`, stage, `Credential custody failed during ${stage}`, { cause: safeCause });
952
+ };
953
+ const timer = setTimeout(() => {
954
+ timedOut = true;
955
+ beginTermination();
956
+ }, effectiveTimeout);
957
+ timer.unref?.();
958
+ const capture = (target) => (chunk) => {
959
+ outputBytes += chunk.length;
960
+ if (outputBytes > maxOutputBytes) {
961
+ timedOut = true;
962
+ outputExceeded = true;
963
+ target.length = 0;
964
+ beginTermination();
965
+ return;
966
+ }
967
+ if (outputExceeded) return;
968
+ target.push(Buffer.from(chunk));
969
+ };
970
+ child.stdout.on("data", capture(stdout));
971
+ child.stderr.on("data", capture(stderr));
972
+ child.once("error", () => {
973
+ if (settled) return;
974
+ settled = true;
975
+ clearTimeout(timer);
976
+ if (escalationTimer) clearTimeout(escalationTimer);
977
+ terminateGroup("SIGKILL");
978
+ reject(new CustodyError("CREDENTIAL_CHILD_PROCESS_FAILED", "inject", "Credential child process could not start"));
979
+ });
980
+ child.once("close", async (exitCode, signal) => {
981
+ if (settled) return;
982
+ settled = true;
983
+ clearTimeout(timer);
984
+ if (escalationTimer) clearTimeout(escalationTimer);
985
+ terminateGroup("SIGTERM");
986
+ terminateGroup("SIGKILL");
987
+ if (!await waitForGroupExit()) {
988
+ reject(new CustodyError("CREDENTIAL_CHILD_PROCESS_CLEANUP_FAILED", "inject", "Credential child process group cleanup could not be verified"));
989
+ return;
990
+ }
991
+ resolve({
992
+ exitCode,
993
+ signal,
994
+ stdout: outputExceeded ? REDACTED : redactCredentialText(Buffer.concat(stdout).toString("utf8"), [secret]),
995
+ stderr: outputExceeded ? REDACTED : redactCredentialText(Buffer.concat(stderr).toString("utf8"), [secret]),
996
+ timedOut
997
+ });
998
+ });
999
+ });
1000
+ });
1001
+ if (!result) throw new CustodyError("CREDENTIAL_CHILD_PROCESS_FAILED", "inject", "Credential child process did not return a result");
1002
+ return result;
1003
+ }
1004
+ async function verifyCustodyReceiptAttestation(receipt, material, publicKey) {
1005
+ if (receipt.attestation.algorithm !== "Ed25519" || publicKey.type !== "public" || publicKey.asymmetricKeyType !== "ed25519" || !/^[A-Za-z0-9_-]{86}$/.test(receipt.attestation.signature) || Buffer.from(receipt.attestation.signature, "base64url").byteLength !== 64 || Buffer.from(receipt.attestation.signature, "base64url").toString("base64url") !== receipt.attestation.signature) return false;
1006
+ let verified = false;
1007
+ await material.use((plaintext) => {
1008
+ const payload = custodyAttestationPayload(receipt, credentialCommitment(plaintext));
1009
+ try {
1010
+ verified = verify(null, Buffer.from(payload), publicKey, Buffer.from(receipt.attestation.signature, "base64url"));
1011
+ } catch {
1012
+ verified = false;
1013
+ }
1014
+ });
1015
+ return verified;
1016
+ }
1017
+ function redactCredentialText(input, knownSecrets = []) {
1018
+ let output = input;
1019
+ for (const secret of knownSecrets.filter(Boolean)) output = output.replaceAll(secret, REDACTED);
1020
+ for (const { pattern, replacement } of CREDENTIAL_PATTERNS) output = output.replace(pattern, replacement);
1021
+ return output;
1022
+ }
1023
+ function redactCredentialValues(value, knownSecrets = []) {
1024
+ if (value instanceof SecretMaterial) return REDACTED;
1025
+ if (typeof value === "string") return redactCredentialText(value, knownSecrets);
1026
+ if (Array.isArray(value)) return value.map((entry) => redactCredentialValues(entry, knownSecrets));
1027
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [redactCredentialText(key, knownSecrets), redactCredentialValues(entry, knownSecrets)]));
1028
+ return value;
1029
+ }
1030
+ async function sanitizeCustodyCause(cause, materials) {
1031
+ if (!(cause instanceof CustodyError)) return cause;
1032
+ const knownSecrets = [];
1033
+ for (const material of materials) {
1034
+ if (!material || material.destroyed) continue;
1035
+ await material.use((value) => {
1036
+ knownSecrets.push(value);
1037
+ });
1038
+ }
1039
+ return new CustodyError(redactCredentialText(cause.code, knownSecrets) === cause.code ? cause.code : "INVALID_CUSTODY_ERROR_CODE", cause.stage, redactCredentialText(cause.message, knownSecrets), cause.details ? { details: redactCredentialValues(cause.details, knownSecrets) } : void 0);
1040
+ }
1041
+ function credentialCommitment(plaintext) {
1042
+ return createHash("sha256").update(plaintext).digest("base64url");
1043
+ }
1044
+ function custodyAttestationPayload(receipt, commitment, identity) {
1045
+ const { attestation, ...unsigned } = receipt;
1046
+ return JSON.stringify(canonicalize({
1047
+ schema: "happyvertical.credential-custody-attestation.v1",
1048
+ receipt: unsigned,
1049
+ attestation: identity ?? {
1050
+ algorithm: attestation.algorithm,
1051
+ attestor: attestation.attestor,
1052
+ keyId: attestation.keyId
1053
+ },
1054
+ credentialCommitment: commitment
1055
+ }));
1056
+ }
1057
+ function canonicalize(value) {
1058
+ if (Array.isArray(value)) return value.map(canonicalize);
1059
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => [key, canonicalize(entry)]));
1060
+ return value;
1061
+ }
1062
+ function sameCustodyEvent(left, right) {
1063
+ return JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right));
1064
+ }
1065
+ function assertAttribution(attribution) {
1066
+ assertSafeIdentifier(attribution.actor, "attribution.actor", "issue");
1067
+ assertSafeIdentifier(attribution.runtime, "attribution.runtime", "issue");
1068
+ assertSafeIdentifier(attribution.session, "attribution.session", "issue");
1069
+ }
1070
+ function assertSinkRecord(record, sinkName) {
1071
+ if (record.sinkName !== sinkName) throw new CustodyError("SINK_IDENTITY_MISMATCH", "store", "Secret sink returned a mismatched identity");
1072
+ assertSafeIdentifier(record.sinkName, "sinkName", "store");
1073
+ assertSafeIdentifier(record.reference, "sinkReference", "store");
1074
+ assertSafeIdentifier(record.version, "sinkVersion", "store");
1075
+ if (!Number.isFinite(new Date(record.storedAt).getTime())) throw new CustodyError("INVALID_SINK_TIMESTAMP", "store", "Secret sink returned an invalid timestamp");
1076
+ }
1077
+ function assertSafeIdentifier(value, field, stage) {
1078
+ if (!SAFE_IDENTIFIER.test(value) || redactCredentialText(value) !== value) throw new CustodyError("UNSAFE_CUSTODY_IDENTIFIER", stage, `Custody ${field} must be a non-secret identifier`);
1079
+ }
1080
+ function sanitizeMetadata(metadata) {
1081
+ return Object.freeze(Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => {
1082
+ if (redactCredentialText(key) !== key) throw new CustodyError("UNSAFE_CUSTODY_METADATA_KEY", "issue", "Custody metadata key must not contain credential material");
1083
+ return [key, redactCredentialText(value)];
1084
+ })));
1085
+ }
1086
+ function parseTimestamp(value, field, stage) {
1087
+ const timestamp = new Date(value).getTime();
1088
+ if (!Number.isFinite(timestamp)) throw new CustodyError("INVALID_CUSTODY_TIMESTAMP", stage, `Custody ${field} timestamp is invalid`);
1089
+ return timestamp;
1090
+ }
1091
+ function sameSinkRecord(left, right) {
1092
+ return left.sinkName === right.sinkName && left.reference === right.reference && left.version === right.version && left.storedAt === right.storedAt;
1093
+ }
1094
+ function sinkIdentity(record, credentialId) {
1095
+ return [
1096
+ record.sinkName,
1097
+ record.reference,
1098
+ record.version,
1099
+ record.storedAt,
1100
+ credentialId ?? ""
1101
+ ].join("\0");
1102
+ }
1103
+ //#endregion
1104
+ //#region src/shared/custody-schema.ts
1105
+ function invalid() {
1106
+ throw new CustodyError("INVALID_CUSTODY_LEDGER_STATE", "record", "Custody ledger requires non-secret, schema-valid metadata");
1107
+ }
1108
+ function object(value, required, optional = []) {
1109
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) invalid();
1110
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1111
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string" || !required.includes(key) && !optional.includes(key))) invalid();
1112
+ if (Object.values(descriptors).some((entry) => !("value" in entry) || !entry.enumerable)) invalid();
1113
+ if (required.some((key) => !Object.hasOwn(value, key))) invalid();
1114
+ return value;
1115
+ }
1116
+ function text(value, allowEmpty = false) {
1117
+ if (typeof value !== "string" || !allowEmpty && !value || value.length > 4096 || redactCredentialText(value) !== value) invalid();
1118
+ }
1119
+ function timestamp(value) {
1120
+ text(value);
1121
+ if (!Number.isFinite(Date.parse(value))) invalid();
1122
+ }
1123
+ function strings(record, keys) {
1124
+ for (const key of keys) text(record[key]);
1125
+ }
1126
+ function optional(record, keys) {
1127
+ for (const key of keys) if (record[key] !== void 0) text(record[key]);
1128
+ }
1129
+ function receipt(value) {
1130
+ const row = object(value, [
1131
+ "receiptId",
1132
+ "mode",
1133
+ "credentialId",
1134
+ "subject",
1135
+ "issuer",
1136
+ "verifier",
1137
+ "verificationState",
1138
+ "issuedAt",
1139
+ "verifiedAt",
1140
+ "rotationRootReceiptId",
1141
+ "attribution",
1142
+ "metadata",
1143
+ "finalizer",
1144
+ "finalizationId",
1145
+ "attestation"
1146
+ ], [
1147
+ "verificationId",
1148
+ "expiresAt",
1149
+ "sink",
1150
+ "replacesReceiptId"
1151
+ ]);
1152
+ strings(row, [
1153
+ "receiptId",
1154
+ "credentialId",
1155
+ "subject",
1156
+ "issuer",
1157
+ "verifier",
1158
+ "rotationRootReceiptId",
1159
+ "finalizer",
1160
+ "finalizationId"
1161
+ ]);
1162
+ optional(row, ["verificationId", "replacesReceiptId"]);
1163
+ if (typeof row.mode !== "string" || !["ephemeral", "durable"].includes(row.mode) || row.verificationState !== "verified") invalid();
1164
+ timestamp(row.issuedAt);
1165
+ timestamp(row.verifiedAt);
1166
+ if (row.expiresAt !== void 0) timestamp(row.expiresAt);
1167
+ strings(object(row.attribution, [
1168
+ "actor",
1169
+ "runtime",
1170
+ "session"
1171
+ ]), [
1172
+ "actor",
1173
+ "runtime",
1174
+ "session"
1175
+ ]);
1176
+ const metadata = row.metadata;
1177
+ if (!metadata || typeof metadata !== "object" || Object.getPrototypeOf(metadata) !== Object.prototype) invalid();
1178
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(metadata))) {
1179
+ text(key, true);
1180
+ if (!("value" in descriptor) || !descriptor.enumerable) invalid();
1181
+ text(descriptor.value, true);
1182
+ }
1183
+ if (Object.getOwnPropertySymbols(metadata).length) invalid();
1184
+ const attestation = object(row.attestation, [
1185
+ "algorithm",
1186
+ "attestor",
1187
+ "keyId",
1188
+ "signature"
1189
+ ]);
1190
+ strings(attestation, [
1191
+ "attestor",
1192
+ "keyId",
1193
+ "signature"
1194
+ ]);
1195
+ if (attestation.algorithm !== "Ed25519" || !/^[A-Za-z0-9_-]{86}$/.test(attestation.signature) || Buffer.from(attestation.signature, "base64url").toString("base64url") !== attestation.signature) invalid();
1196
+ if (row.sink !== void 0) {
1197
+ const sink = object(row.sink, [
1198
+ "sinkName",
1199
+ "reference",
1200
+ "version",
1201
+ "storedAt"
1202
+ ]);
1203
+ strings(sink, [
1204
+ "sinkName",
1205
+ "reference",
1206
+ "version"
1207
+ ]);
1208
+ timestamp(sink.storedAt);
1209
+ }
1210
+ }
1211
+ var EVENT_TYPES = [
1212
+ "issued",
1213
+ "revoked",
1214
+ "expired",
1215
+ "replaced",
1216
+ "rollback-pending",
1217
+ "rollback-complete",
1218
+ "finalization-pending",
1219
+ "retirement-pending",
1220
+ "retirement-complete",
1221
+ "orphan-detected",
1222
+ "orphan-removed"
1223
+ ];
1224
+ function event(value) {
1225
+ const row = object(value, [
1226
+ "eventId",
1227
+ "type",
1228
+ "occurredAt"
1229
+ ], [
1230
+ "receiptId",
1231
+ "recoveryId",
1232
+ "credentialId",
1233
+ "requiresSink",
1234
+ "finalizationReceipt",
1235
+ "recoveryReceipt",
1236
+ "replacementReceiptId",
1237
+ "sinkReference",
1238
+ "reason"
1239
+ ]);
1240
+ text(row.eventId);
1241
+ if (typeof row.type !== "string" || !EVENT_TYPES.includes(row.type)) invalid();
1242
+ timestamp(row.occurredAt);
1243
+ optional(row, [
1244
+ "receiptId",
1245
+ "recoveryId",
1246
+ "credentialId",
1247
+ "replacementReceiptId",
1248
+ "sinkReference",
1249
+ "reason"
1250
+ ]);
1251
+ if (row.requiresSink !== void 0 && typeof row.requiresSink !== "boolean") invalid();
1252
+ if (row.finalizationReceipt !== void 0) receipt(row.finalizationReceipt);
1253
+ if (row.recoveryReceipt !== void 0) receipt(row.recoveryReceipt);
1254
+ }
1255
+ /** Internal serialization boundary: rejects unknown fields and non-data objects. */
1256
+ function validateCustodySnapshot(value) {
1257
+ const row = object(value, [
1258
+ "schema",
1259
+ "receipts",
1260
+ "events",
1261
+ "issuanceCommits"
1262
+ ]);
1263
+ if (row.schema !== 1 || !Array.isArray(row.receipts) || !Array.isArray(row.events) || !Array.isArray(row.issuanceCommits)) invalid();
1264
+ for (const entries of [
1265
+ row.receipts,
1266
+ row.events,
1267
+ row.issuanceCommits
1268
+ ]) {
1269
+ if (Object.getPrototypeOf(entries) !== Array.prototype || Reflect.ownKeys(entries).length !== entries.length + 1) invalid();
1270
+ for (let index = 0; index < entries.length; index++) {
1271
+ const descriptor = Object.getOwnPropertyDescriptor(entries, index);
1272
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) invalid();
1021
1273
  }
1022
1274
  }
1023
- async rotate(receiptId, request) {
1024
- if ((await this.#findReceipt(receiptId)).mode !== "durable") throw new CustodyError("DURABLE_ROTATION_REQUIRED", "issue", "Only durable credentials can be rotated");
1025
- return this.issue({
1026
- ...request,
1027
- mode: "durable",
1028
- replacesReceiptId: receiptId
1029
- });
1275
+ for (const entry of row.receipts) receipt(entry);
1276
+ for (const entry of row.events) event(entry);
1277
+ for (const entry of row.issuanceCommits) {
1278
+ const binding = object(entry, [
1279
+ "receiptId",
1280
+ "eventId",
1281
+ "followupEventId"
1282
+ ]);
1283
+ strings(binding, ["receiptId", "eventId"]);
1284
+ if (binding.followupEventId !== null) text(binding.followupEventId);
1030
1285
  }
1031
- async revoke(receiptId, reason = "recovery") {
1032
- const receipt = await this.#findReceipt(receiptId);
1033
- this.#leaseInvalidators.get(receiptId)?.();
1034
- await this.#revokeReceipt(receipt, reason);
1035
- this.#leaseInvalidators.delete(receiptId);
1286
+ if (new Set(row.receipts.map((entry) => entry.receiptId)).size !== row.receipts.length || new Set(row.events.map((entry) => entry.eventId)).size !== row.events.length || new Set(row.issuanceCommits.map((entry) => entry.receiptId)).size !== row.issuanceCommits.length || new Set(row.issuanceCommits.map((entry) => entry.eventId)).size !== row.issuanceCommits.length) invalid();
1287
+ return JSON.parse(JSON.stringify(row));
1288
+ }
1289
+ //#endregion
1290
+ //#region src/adapters/custody-database.ts
1291
+ /**
1292
+ * Durable runtime metadata ledger. Validated with the SDK SQLite adapter.
1293
+ * Use secureFile trusted-parent acquisition beneath a private runtime directory.
1294
+ * The supplied database remains owned by the caller. No credential is stored.
1295
+ */
1296
+ var DatabaseCustodyLedger = class {
1297
+ #db;
1298
+ #ledgerId;
1299
+ #initialized = false;
1300
+ constructor(options) {
1301
+ this.#db = options.db;
1302
+ this.#ledgerId = options.ledgerId ?? "default";
1303
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(this.#ledgerId) || redactCredentialText(this.#ledgerId) !== this.#ledgerId) throw new CustodyError("INVALID_CUSTODY_LEDGER_ID", "record", "Ledger ID must be a non-secret identifier");
1036
1304
  }
1037
- async recoverPendingRollbacks() {
1038
- const events = await this.#ledger.listEvents();
1039
- const receipts = await this.#ledger.listReceipts();
1040
- const activeIds = new Set(events.filter((event) => event.type === "issued").map((event) => event.receiptId));
1041
- const terminalIds = new Set(events.filter((event) => [
1042
- "revoked",
1043
- "expired",
1044
- "replaced"
1045
- ].includes(event.type)).map((event) => event.receiptId));
1046
- const completedRollbackIds = new Set(events.filter((event) => event.type === "rollback-complete").map((event) => event.recoveryId));
1047
- const rollbackReceiptIds = new Set(events.filter((event) => event.type === "rollback-pending" && !completedRollbackIds.has(event.recoveryId)).map((event) => event.receiptId));
1048
- const pendingByReceipt = new Map(events.filter((event) => event.type === "finalization-pending" && event.receiptId).map((event) => [event.receiptId, event]));
1049
- const takeoverCutoff = this.#now().getTime() - this.#finalizationTakeoverMs;
1050
- const failures = [];
1051
- for (const receipt of receipts.filter((item) => !activeIds.has(item.receiptId) && !terminalIds.has(item.receiptId) && !rollbackReceiptIds.has(item.receiptId) && (() => {
1052
- const pending = pendingByReceipt.get(item.receiptId);
1053
- if (pending) {
1054
- const pendingAt = parseTimestamp(pending.occurredAt, "occurredAt", "reconcile");
1055
- if (pendingAt > takeoverCutoff) {
1056
- this.#scheduleFinalizationTakeover(item.finalizationId, pendingAt + this.#finalizationTakeoverMs);
1057
- return false;
1058
- }
1059
- }
1060
- return pending !== void 0 && parseTimestamp(pending.occurredAt, "occurredAt", "reconcile") <= takeoverCutoff;
1061
- })())) try {
1062
- if (await this.#finalizer.status({ receipt: structuredClone(receipt) }) === "committed") {
1063
- const predecessor = receipt.replacesReceiptId ? receipts.find((item) => item.receiptId === receipt.replacesReceiptId) : void 0;
1064
- const recoveryId = predecessor ? randomUUID() : void 0;
1065
- await this.#ledger.commitIssuance(receipt.receiptId, this.#event("issued", receipt.receiptId), predecessor && recoveryId ? {
1066
- ...this.#event("retirement-pending", predecessor.receiptId),
1067
- eventId: recoveryId,
1068
- recoveryId,
1069
- credentialId: predecessor.credentialId,
1070
- recoveryReceipt: structuredClone(predecessor),
1071
- replacementReceiptId: receipt.receiptId
1072
- } : void 0);
1073
- activeIds.add(receipt.receiptId);
1074
- if (predecessor && recoveryId) this.#scheduleRetirement(recoveryId, predecessor, receipt.receiptId);
1075
- } else await this.#abortAndRevoke(receipt, "incomplete finalization recovery");
1305
+ async initialize() {
1306
+ if (this.#initialized) return;
1307
+ if (!this.#db.transaction) throw new CustodyError("CUSTODY_LEDGER_TRANSACTIONS_REQUIRED", "record", "Custody ledger requires database transactions");
1308
+ await this.#db.query(`CREATE TABLE IF NOT EXISTS custody_ledger_state (
1309
+ ledger_id TEXT PRIMARY KEY,
1310
+ revision INTEGER NOT NULL,
1311
+ payload TEXT NOT NULL
1312
+ )`);
1313
+ await this.#db.query("INSERT INTO custody_ledger_state (ledger_id, revision, payload) VALUES (?, ?, ?) ON CONFLICT (ledger_id) DO NOTHING", this.#ledgerId, 0, JSON.stringify({
1314
+ schema: 1,
1315
+ receipts: [],
1316
+ events: [],
1317
+ issuanceCommits: []
1318
+ }));
1319
+ await this.#load(this.#db);
1320
+ this.#initialized = true;
1321
+ }
1322
+ async #load(db) {
1323
+ const row = (await db.query("SELECT revision, payload FROM custody_ledger_state WHERE ledger_id = ?", this.#ledgerId)).rows[0];
1324
+ if (!row || !Number.isSafeInteger(row.revision) || row.revision < 0 || typeof row.payload !== "string") throw new CustodyError("INVALID_CUSTODY_LEDGER_STATE", "record", "Custody ledger state is invalid");
1325
+ let state;
1326
+ try {
1327
+ state = validateCustodySnapshot(JSON.parse(row.payload));
1076
1328
  } catch {
1077
- failures.push(receipt.finalizationId);
1078
- this.#scheduleFinalizationTakeover(receipt.finalizationId, this.#now().getTime() + this.#ephemeralRevokeRetryMs);
1329
+ throw new CustodyError("INVALID_CUSTODY_LEDGER_STATE", "record", "Custody ledger state is invalid");
1079
1330
  }
1080
- for (const receipt of receipts.filter((item) => item.mode === "ephemeral" && activeIds.has(item.receiptId) && !terminalIds.has(item.receiptId) && item.expiresAt !== void 0)) try {
1081
- const deadline = parseTimestamp(receipt.expiresAt ?? "", "expiresAt", "revoke");
1082
- if (deadline <= this.#now().getTime()) await this.#revokeReceipt(receipt, "restart expiry recovery", "expired");
1083
- else this.#scheduleReceiptExpiry(receipt, deadline);
1331
+ return {
1332
+ ledger: await this.#restore(state),
1333
+ revision: row.revision
1334
+ };
1335
+ }
1336
+ async #restore(state) {
1337
+ const ledger = new InMemoryCustodyLedger();
1338
+ const receipts = new Map(state.receipts.map((receipt) => [receipt.receiptId, receipt]));
1339
+ const commits = new Map(state.issuanceCommits.map((binding) => [binding.eventId, binding]));
1340
+ const events = new Map(state.events.map((event) => [event.eventId, event]));
1341
+ try {
1342
+ for (const event of state.events) if (event.type === "finalization-pending") {
1343
+ const receipt = event.receiptId ? receipts.get(event.receiptId) : void 0;
1344
+ if (!receipt) throw new Error("Missing receipt");
1345
+ await ledger.recordIssuance(receipt, event);
1346
+ receipts.delete(receipt.receiptId);
1347
+ } else if (event.type === "issued" && commits.has(event.eventId)) {
1348
+ const binding = commits.get(event.eventId);
1349
+ if (!binding) throw new Error("Missing commit");
1350
+ const followup = binding.followupEventId === null ? void 0 : events.get(binding.followupEventId);
1351
+ if (binding.followupEventId !== null && !followup) throw new Error("Missing followup");
1352
+ await ledger.commitIssuance(binding.receiptId, event, followup);
1353
+ commits.delete(event.eventId);
1354
+ } else await ledger.appendEvent(event);
1355
+ if (receipts.size || commits.size) throw new Error("Missing issuance");
1356
+ if ((await ledger.listEvents()).some((event, index) => event.eventId !== state.events[index]?.eventId)) throw new Error("Invalid transaction order");
1084
1357
  } catch {
1085
- failures.push(receipt.receiptId);
1086
- }
1087
- const completed = new Set(events.filter((event) => event.type === "rollback-complete").map((event) => event.recoveryId));
1088
- const pendingRollbacks = new Map(events.filter((event) => event.type === "rollback-pending" && event.recoveryId && !completed.has(event.recoveryId)).map((event) => [event.recoveryId, event]));
1089
- for (const pending of pendingRollbacks.values()) {
1090
- if (!pending.credentialId || !pending.recoveryId) continue;
1091
- const timer = this.#pendingTimers.get(pending.recoveryId);
1092
- if (timer) clearTimeout(timer);
1093
- this.#pendingTimers.delete(pending.recoveryId);
1094
- try {
1095
- assertSafeIdentifier(pending.credentialId, "credentialId", "revoke");
1096
- if (pending.receiptId && pending.finalizationReceipt) await this.#abortAndRevoke(pending.finalizationReceipt, "pending rollback recovery");
1097
- else await this.#rollback(pending.credentialId, void 0, "revoke", pending.requiresSink === true);
1098
- await this.#completeRollback(pending.recoveryId, pending.credentialId, pending.sinkReference);
1099
- if (pending.receiptId) {
1100
- terminalIds.add(pending.receiptId);
1101
- this.#leaseInvalidators.delete(pending.receiptId);
1102
- }
1103
- } catch {
1104
- failures.push(pending.recoveryId);
1105
- this.#scheduleRollback(pending.recoveryId, pending.credentialId, void 0, "revoke", pending.requiresSink === true, pending.finalizationReceipt, Boolean(pending.receiptId));
1106
- }
1107
- }
1108
- const retired = new Set(events.filter((event) => event.type === "retirement-complete").map((event) => event.recoveryId));
1109
- for (const pending of events.filter((event) => event.type === "retirement-pending" && event.recoveryId && !retired.has(event.recoveryId))) {
1110
- if (!pending.recoveryId || !pending.recoveryReceipt) continue;
1111
- if (pending.replacementReceiptId && (!activeIds.has(pending.replacementReceiptId) || terminalIds.has(pending.replacementReceiptId))) {
1112
- await this.#ledger.appendEvent({
1113
- ...this.#event("retirement-complete", pending.recoveryReceipt.receiptId),
1114
- recoveryId: pending.recoveryId,
1115
- reason: "replacement is not active"
1116
- });
1117
- continue;
1118
- }
1119
- try {
1120
- await this.#revokeReceipt(pending.recoveryReceipt, "replacement retirement recovery", "replaced");
1121
- await this.#ledger.appendEvent({
1122
- ...this.#event("retirement-complete", pending.recoveryReceipt.receiptId),
1123
- recoveryId: pending.recoveryId
1124
- });
1125
- this.#leaseInvalidators.delete(pending.recoveryReceipt.receiptId);
1126
- } catch {
1127
- failures.push(pending.recoveryId);
1128
- this.#scheduleRetirement(pending.recoveryId, pending.recoveryReceipt, pending.replacementReceiptId);
1129
- }
1358
+ throw new CustodyError("INVALID_CUSTODY_LEDGER_STATE", "record", "Custody ledger history is invalid");
1130
1359
  }
1131
- if (failures.length) throw new CustodyError("PENDING_ROLLBACK_RECOVERY_FAILED", "revoke", "One or more pending credential rollbacks could not be recovered", { details: { recoveryIds: failures } });
1360
+ return ledger;
1361
+ }
1362
+ #assertInitialized() {
1363
+ if (!this.#initialized) throw new CustodyError("CUSTODY_LEDGER_NOT_INITIALIZED", "record", "Initialize custody ledger before use");
1364
+ }
1365
+ async #mutate(operation) {
1366
+ this.#assertInitialized();
1367
+ if (!this.#db.transaction) throw new CustodyError("CUSTODY_LEDGER_TRANSACTIONS_REQUIRED", "record", "Custody ledger requires database transactions");
1368
+ await this.#db.transaction(async (tx) => {
1369
+ const { ledger, revision } = await this.#load(tx);
1370
+ await operation(ledger);
1371
+ const state = validateCustodySnapshot({
1372
+ schema: 1,
1373
+ receipts: await ledger.listReceipts(),
1374
+ events: await ledger.listEvents(),
1375
+ issuanceCommits: await ledger.listIssuanceCommits()
1376
+ });
1377
+ await this.#restore(state);
1378
+ if (revision >= Number.MAX_SAFE_INTEGER) throw new CustodyError("CUSTODY_LEDGER_REVISION_EXHAUSTED", "record", "Custody ledger revision exhausted");
1379
+ if ((await tx.query("UPDATE custody_ledger_state SET revision = ?, payload = ? WHERE ledger_id = ? AND revision = ?", revision + 1, JSON.stringify(state), this.#ledgerId, revision)).rowCount !== 1) throw new CustodyError("CUSTODY_LEDGER_CONFLICT", "record", "Custody ledger changed concurrently; retry after reloading");
1380
+ });
1132
1381
  }
1133
- async recoverCredential(credentialId, options = {}) {
1134
- assertSafeIdentifier(credentialId, "credentialId", "revoke");
1135
- await this.#rollback(credentialId, void 0, "revoke", options.requiresSink === true);
1382
+ async recordIssuance(receipt, event) {
1383
+ const state = validateCustodySnapshot({
1384
+ schema: 1,
1385
+ receipts: [receipt],
1386
+ events: [event],
1387
+ issuanceCommits: []
1388
+ });
1389
+ await this.#mutate((ledger) => ledger.recordIssuance(state.receipts[0], state.events[0]));
1136
1390
  }
1137
- async reconcile() {
1138
- if (!this.#sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "reconcile", "Reconciliation requires a secret sink");
1139
- const [receipts, events, inventory] = await Promise.all([
1140
- this.#ledger.listReceipts(),
1141
- this.#ledger.listEvents(),
1142
- this.#sink.inventory()
1143
- ]);
1144
- for (const entry of inventory) {
1145
- assertSinkRecord(entry, this.#sink.name);
1146
- assertSafeIdentifier(entry.credentialId, "credentialId", "reconcile");
1147
- }
1148
- const terminal = new Set(events.filter((event) => [
1149
- "revoked",
1150
- "expired",
1151
- "replaced"
1152
- ].includes(event.type)).map((event) => event.receiptId));
1153
- const issued = new Set(events.filter((event) => event.type === "issued").map((event) => event.receiptId));
1154
- for (const replacement of receipts) if (replacement.replacesReceiptId && issued.has(replacement.receiptId) && !terminal.has(replacement.receiptId)) terminal.add(replacement.replacesReceiptId);
1155
- const active = receipts.filter((receipt) => receipt.mode === "durable" && receipt.sink !== void 0 && issued.has(receipt.receiptId) && !terminal.has(receipt.receiptId));
1156
- const orphanCutoff = this.#now().getTime() - this.#orphanGraceMs;
1391
+ async commitIssuance(receiptId, event, followup) {
1392
+ const state = validateCustodySnapshot({
1393
+ schema: 1,
1394
+ receipts: [],
1395
+ events: followup ? [event, followup] : [event],
1396
+ issuanceCommits: []
1397
+ });
1398
+ await this.#mutate((ledger) => ledger.commitIssuance(receiptId, state.events[0], state.events[1]));
1399
+ }
1400
+ async appendEvent(event) {
1401
+ const state = validateCustodySnapshot({
1402
+ schema: 1,
1403
+ receipts: [],
1404
+ events: [event],
1405
+ issuanceCommits: []
1406
+ });
1407
+ await this.#mutate((ledger) => ledger.appendEvent(state.events[0]));
1408
+ }
1409
+ async listReceipts() {
1410
+ this.#assertInitialized();
1411
+ return (await this.#load(this.#db)).ledger.listReceipts();
1412
+ }
1413
+ async listEvents() {
1414
+ this.#assertInitialized();
1415
+ return (await this.#load(this.#db)).ledger.listEvents();
1416
+ }
1417
+ };
1418
+ //#endregion
1419
+ //#region src/shared/envelope.ts
1420
+ /**
1421
+ * Core envelope encryption primitives using AES-256-GCM
1422
+ *
1423
+ * This class provides the cryptographic operations for envelope encryption:
1424
+ * - Generate data encryption keys (DEKs)
1425
+ * - Wrap/unwrap DEKs with a master key
1426
+ * - Encrypt/decrypt data with DEKs
1427
+ *
1428
+ * @example
1429
+ * ```typescript
1430
+ * // Generate a new data key
1431
+ * const dataKey = EnvelopeEncryption.generateDataKey();
1432
+ *
1433
+ * // Wrap the data key with an AMK
1434
+ * const wrapped = EnvelopeEncryption.wrapKey(dataKey, amk);
1435
+ *
1436
+ * // Encrypt data with the data key
1437
+ * const encrypted = EnvelopeEncryption.encryptData('secret', dataKey);
1438
+ *
1439
+ * // Later: unwrap and decrypt
1440
+ * const unwrappedKey = EnvelopeEncryption.unwrapKey(wrapped.wrappedKey, wrapped.iv, wrapped.authTag, amk);
1441
+ * const plaintext = EnvelopeEncryption.decryptData(encrypted.ciphertext, encrypted.iv, encrypted.authTag, unwrappedKey);
1442
+ * ```
1443
+ */
1444
+ var EnvelopeEncryption = class EnvelopeEncryption {
1445
+ static ALGORITHM = "aes-256-gcm";
1446
+ static KEY_LENGTH = 32;
1447
+ static IV_LENGTH = 12;
1448
+ static AUTH_TAG_LENGTH = 16;
1449
+ /**
1450
+ * Generate a new random data encryption key
1451
+ *
1452
+ * @returns A 32-byte (256-bit) random key
1453
+ */
1454
+ static generateDataKey() {
1455
+ return crypto.randomBytes(EnvelopeEncryption.KEY_LENGTH);
1456
+ }
1457
+ /**
1458
+ * Generate a random IV for encryption
1459
+ *
1460
+ * @returns A 12-byte (96-bit) random IV
1461
+ */
1462
+ static generateIV() {
1463
+ return crypto.randomBytes(EnvelopeEncryption.IV_LENGTH);
1464
+ }
1465
+ /**
1466
+ * Wrap (encrypt) a data encryption key with a master key
1467
+ *
1468
+ * @param dataKey - The data key to wrap (32 bytes)
1469
+ * @param masterKey - The master key to wrap with (32 bytes)
1470
+ * @returns Object containing wrapped key, IV, and auth tag (all base64-encoded)
1471
+ */
1472
+ static wrapKey(dataKey, masterKey) {
1473
+ EnvelopeEncryption.validateKeyLength(dataKey);
1474
+ EnvelopeEncryption.validateKeyLength(masterKey);
1475
+ const iv = EnvelopeEncryption.generateIV();
1476
+ const cipher = crypto.createCipheriv(EnvelopeEncryption.ALGORITHM, masterKey, iv);
1477
+ const encrypted = Buffer.concat([cipher.update(dataKey), cipher.final()]);
1478
+ const authTag = cipher.getAuthTag();
1479
+ return {
1480
+ wrappedKey: encrypted.toString("base64"),
1481
+ iv: iv.toString("base64"),
1482
+ authTag: authTag.toString("base64")
1483
+ };
1484
+ }
1485
+ /**
1486
+ * Unwrap (decrypt) a data encryption key with a master key
1487
+ *
1488
+ * @param wrappedKey - Base64-encoded wrapped key
1489
+ * @param iv - Base64-encoded IV
1490
+ * @param authTag - Base64-encoded authentication tag
1491
+ * @param masterKey - The master key to unwrap with (32 bytes)
1492
+ * @returns The unwrapped data key (32 bytes)
1493
+ * @throws Error if decryption fails (invalid key, tampered data, etc.)
1494
+ */
1495
+ static unwrapKey(wrappedKey, iv, authTag, masterKey) {
1496
+ EnvelopeEncryption.validateKeyLength(masterKey);
1497
+ const decipher = crypto.createDecipheriv(EnvelopeEncryption.ALGORITHM, masterKey, Buffer.from(iv, "base64"));
1498
+ decipher.setAuthTag(Buffer.from(authTag, "base64"));
1499
+ return Buffer.concat([decipher.update(Buffer.from(wrappedKey, "base64")), decipher.final()]);
1500
+ }
1501
+ /**
1502
+ * Encrypt data with a data encryption key
1503
+ *
1504
+ * @param plaintext - The plaintext string to encrypt
1505
+ * @param dataKey - The data encryption key (32 bytes)
1506
+ * @returns Object containing ciphertext, IV, and auth tag (all base64-encoded)
1507
+ */
1508
+ static encryptData(plaintext, dataKey) {
1509
+ EnvelopeEncryption.validateKeyLength(dataKey);
1510
+ const iv = EnvelopeEncryption.generateIV();
1511
+ const cipher = crypto.createCipheriv(EnvelopeEncryption.ALGORITHM, dataKey, iv);
1512
+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
1513
+ const authTag = cipher.getAuthTag();
1157
1514
  return {
1158
- checkedAt: this.#now().toISOString(),
1159
- orphaned: inventory.filter((entry) => parseTimestamp(entry.storedAt, "storedAt", "reconcile") <= orphanCutoff && !active.some((receipt) => sameSinkRecord(receipt.sink, entry) && entry.credentialId === receipt.credentialId)),
1160
- missing: active.filter((receipt) => !inventory.some((entry) => sameSinkRecord(receipt.sink, entry) && entry.credentialId === receipt.credentialId))
1515
+ ciphertext: encrypted.toString("base64"),
1516
+ iv: iv.toString("base64"),
1517
+ authTag: authTag.toString("base64")
1161
1518
  };
1162
1519
  }
1163
- async recoverOrphans(report) {
1164
- if (!this.#sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "reconcile", "Orphan recovery requires a secret sink");
1165
- const current = await this.reconcile();
1166
- const requested = new Set(report.orphaned.map((entry) => sinkIdentity(entry, entry.credentialId)));
1167
- const confirmed = current.orphaned.filter((entry) => requested.has(sinkIdentity(entry, entry.credentialId)));
1168
- for (const orphan of confirmed) {
1169
- assertSinkRecord(orphan, this.#sink.name);
1170
- await this.#ledger.appendEvent(this.#event("orphan-detected", void 0, orphan.reference));
1171
- assertSafeIdentifier(orphan.credentialId, "credentialId", "reconcile");
1172
- try {
1173
- await this.#issuer.revoke(orphan.credentialId, "orphan recovery");
1174
- } catch {
1175
- throw new CustodyError("ORPHAN_REVOCATION_FAILED", "reconcile", "Orphan credential revocation failed");
1176
- }
1177
- await this.#sink.remove(orphan, "orphan recovery");
1178
- await this.#ledger.appendEvent(this.#event("orphan-removed", void 0, orphan.reference));
1179
- }
1520
+ /**
1521
+ * Decrypt data with a data encryption key
1522
+ *
1523
+ * @param ciphertext - Base64-encoded ciphertext
1524
+ * @param iv - Base64-encoded IV
1525
+ * @param authTag - Base64-encoded authentication tag
1526
+ * @param dataKey - The data encryption key (32 bytes)
1527
+ * @returns The decrypted plaintext string
1528
+ * @throws Error if decryption fails (invalid key, tampered data, etc.)
1529
+ */
1530
+ static decryptData(ciphertext, iv, authTag, dataKey) {
1531
+ EnvelopeEncryption.validateKeyLength(dataKey);
1532
+ const decipher = crypto.createDecipheriv(EnvelopeEncryption.ALGORITHM, dataKey, Buffer.from(iv, "base64"));
1533
+ decipher.setAuthTag(Buffer.from(authTag, "base64"));
1534
+ return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
1180
1535
  }
1181
- #createLease(receipt, ephemeralMaterial) {
1182
- let unavailable = false;
1183
- let revocationComplete = false;
1184
- let revocationInFlight;
1185
- let timer;
1186
- const revoke = async (reason = "requested", terminalType = "revoked") => {
1187
- unavailable = true;
1188
- if (timer) clearTimeout(timer);
1189
- ephemeralMaterial?.destroy();
1190
- if (revocationComplete) return;
1191
- if (revocationInFlight) return revocationInFlight;
1192
- revocationInFlight = this.#revokeReceipt(receipt, reason, terminalType).then(() => {
1193
- revocationComplete = true;
1194
- this.#leaseInvalidators.delete(receipt.receiptId);
1195
- }).finally(() => {
1196
- revocationInFlight = void 0;
1197
- });
1198
- return revocationInFlight;
1199
- };
1200
- const invalidate = () => {
1201
- unavailable = true;
1202
- if (timer) clearTimeout(timer);
1203
- ephemeralMaterial?.destroy();
1536
+ /**
1537
+ * Create a full encrypted envelope
1538
+ *
1539
+ * This combines key wrapping and data encryption into a single envelope
1540
+ * that can be stored and later decrypted.
1541
+ *
1542
+ * @param plaintext - The plaintext string to encrypt
1543
+ * @param dataKey - The data encryption key (32 bytes)
1544
+ * @param wrappedKeyInfo - The wrapped key info (from wrapKey)
1545
+ * @param amkKeyId - The ID of the AMK used to wrap the key
1546
+ * @param metadata - Optional metadata to include in the envelope
1547
+ * @returns A complete encrypted envelope
1548
+ */
1549
+ static createEnvelope(plaintext, dataKey, wrappedKeyInfo, amkKeyId, metadata) {
1550
+ const encrypted = EnvelopeEncryption.encryptData(plaintext, dataKey);
1551
+ return {
1552
+ version: 1,
1553
+ algorithm: "aes-256-gcm",
1554
+ wrappedKey: `${wrappedKeyInfo.wrappedKey}:${wrappedKeyInfo.iv}:${wrappedKeyInfo.authTag}`,
1555
+ amkKeyId,
1556
+ iv: encrypted.iv,
1557
+ authTag: encrypted.authTag,
1558
+ ciphertext: encrypted.ciphertext,
1559
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1560
+ metadata
1204
1561
  };
1205
- this.#leaseInvalidators.set(receipt.receiptId, invalidate);
1206
- if (receipt.mode === "ephemeral" && receipt.expiresAt) {
1207
- const deadline = parseTimestamp(receipt.expiresAt, "expiresAt", "issue");
1208
- const schedule = (delay) => {
1209
- timer = setTimeout(() => {
1210
- const remaining = deadline - this.#now().getTime();
1211
- if (remaining > 0) {
1212
- schedule(Math.min(remaining, MAX_TIMER_DELAY_MS));
1213
- return;
1214
- }
1215
- revoke("expired", "expired").catch((cause) => {
1216
- try {
1217
- this.#onBackgroundError?.(cause instanceof CustodyError ? cause : new CustodyError("EPHEMERAL_CLEANUP_FAILED", "revoke", "Ephemeral credential cleanup failed", { cause }));
1218
- } catch {} finally {
1219
- schedule(this.#ephemeralRevokeRetryMs);
1220
- }
1221
- });
1222
- }, Math.min(Math.max(0, delay), MAX_TIMER_DELAY_MS));
1223
- timer.unref?.();
1224
- };
1225
- schedule(deadline - this.#now().getTime());
1226
- }
1562
+ }
1563
+ /**
1564
+ * Parse a combined wrapped key string
1565
+ *
1566
+ * @param combinedWrappedKey - The combined wrapped key string (wrappedKey:iv:authTag)
1567
+ * @returns Object with wrappedKey, iv, and authTag
1568
+ */
1569
+ static parseWrappedKey(combinedWrappedKey) {
1570
+ const parts = combinedWrappedKey.split(":");
1571
+ if (parts.length !== 3) throw new Error("Invalid wrapped key format: expected wrappedKey:iv:authTag");
1572
+ const [wrappedKey, iv, authTag] = parts;
1573
+ if (!wrappedKey || !iv || !authTag) throw new Error("Invalid wrapped key format: wrappedKey, iv, and authTag must all be non-empty");
1227
1574
  return {
1228
- receipt: structuredClone(receipt),
1229
- withEnvironment: async (variableName, operation) => {
1230
- this.#assertLeaseAvailable(receipt, unavailable);
1231
- if (!ENVIRONMENT_VARIABLE.test(variableName)) throw new CustodyError("INVALID_ENVIRONMENT_VARIABLE", "inject", "Environment variable name is invalid");
1232
- let material = ephemeralMaterial;
1233
- if (!material) {
1234
- if (!this.#sink || !receipt.sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "retrieve", "Durable credential retrieval requires a secret sink record");
1235
- material = await this.#sink.retrieve(receipt.sink);
1236
- }
1237
- try {
1238
- this.#assertLeaseAvailable(receipt, unavailable);
1239
- await withEnvironmentSecret(material, variableName, operation, { expiresAt: receipt.expiresAt });
1240
- } finally {
1241
- if (!ephemeralMaterial) material.destroy();
1242
- }
1243
- },
1244
- withChildProcess: async (options) => {
1245
- this.#assertLeaseAvailable(receipt, unavailable);
1246
- let material = ephemeralMaterial;
1247
- if (!material) {
1248
- if (!this.#sink || !receipt.sink) throw new CustodyError("DURABLE_SINK_REQUIRED", "retrieve", "Durable credential retrieval requires a secret sink record");
1249
- material = await this.#sink.retrieve(receipt.sink);
1250
- }
1251
- try {
1252
- this.#assertLeaseAvailable(receipt, unavailable);
1253
- return await runCredentialChildProcess(material, options, { expiresAt: receipt.expiresAt });
1254
- } catch (cause) {
1255
- if (cause instanceof CustodyError && cause.code === "CREDENTIAL_CHILD_PROCESS_CLEANUP_FAILED") {
1256
- invalidate();
1257
- await this.#recoverChildProcessCleanupFailure(receipt);
1258
- }
1259
- throw cause;
1260
- } finally {
1261
- if (!ephemeralMaterial) material.destroy();
1262
- }
1263
- },
1264
- revoke: (reason) => revoke(reason)
1575
+ wrappedKey,
1576
+ iv,
1577
+ authTag
1265
1578
  };
1266
1579
  }
1267
- #assertLeaseAvailable(receipt, unavailable) {
1268
- const expired = receipt.expiresAt !== void 0 && parseTimestamp(receipt.expiresAt, "expiresAt", "inject") <= this.#now().getTime();
1269
- if (unavailable || expired) throw new CustodyError("CREDENTIAL_REVOKED", "inject", "Credential is no longer available");
1580
+ /**
1581
+ * Decrypt a full envelope
1582
+ *
1583
+ * @param envelope - The encrypted envelope
1584
+ * @param masterKey - The master key to unwrap the data key
1585
+ * @returns The decrypted plaintext string
1586
+ */
1587
+ static decryptEnvelope(envelope, masterKey) {
1588
+ const { wrappedKey, iv: keyIv, authTag: keyAuthTag } = EnvelopeEncryption.parseWrappedKey(envelope.wrappedKey);
1589
+ const dataKey = EnvelopeEncryption.unwrapKey(wrappedKey, keyIv, keyAuthTag, masterKey);
1590
+ return EnvelopeEncryption.decryptData(envelope.ciphertext, envelope.iv, envelope.authTag, dataKey);
1591
+ }
1592
+ /**
1593
+ * Validate that a key is the correct length
1594
+ *
1595
+ * @param key - The key to validate
1596
+ * @param expectedLength - Expected length in bytes (default: 32)
1597
+ * @throws Error if key length is invalid
1598
+ */
1599
+ static validateKeyLength(key, expectedLength = EnvelopeEncryption.KEY_LENGTH) {
1600
+ if (key.length !== expectedLength) throw new Error(`Invalid key length: expected ${expectedLength} bytes, got ${key.length} bytes`);
1601
+ }
1602
+ /**
1603
+ * Parse a hex-encoded key from string
1604
+ *
1605
+ * @param hexKey - Hex-encoded key string (64 chars for 32 bytes)
1606
+ * @returns The key as a Buffer
1607
+ * @throws Error if the hex string is invalid
1608
+ */
1609
+ static parseHexKey(hexKey) {
1610
+ if (!/^[0-9a-fA-F]+$/.test(hexKey)) throw new Error("Invalid hex key: contains non-hex characters");
1611
+ const key = Buffer.from(hexKey, "hex");
1612
+ EnvelopeEncryption.validateKeyLength(key);
1613
+ return key;
1614
+ }
1615
+ };
1616
+ //#endregion
1617
+ //#region src/shared/errors.ts
1618
+ /**
1619
+ * Base error class for secret operations
1620
+ */
1621
+ var SecretError = class extends Error {
1622
+ code;
1623
+ adapterType;
1624
+ cause;
1625
+ constructor(message, code, options) {
1626
+ super(message);
1627
+ this.name = "SecretError";
1628
+ this.code = code;
1629
+ this.adapterType = options?.adapterType;
1630
+ this.cause = options?.cause;
1631
+ }
1632
+ };
1633
+ /**
1634
+ * Error thrown when a key is not found
1635
+ */
1636
+ var KeyNotFoundError = class extends SecretError {
1637
+ constructor(keyId, adapterType) {
1638
+ super(`Key not found: ${keyId}`, "KEY_NOT_FOUND", { adapterType });
1639
+ this.name = "KeyNotFoundError";
1640
+ }
1641
+ };
1642
+ /**
1643
+ * Error thrown when decryption fails
1644
+ */
1645
+ var DecryptionError = class extends SecretError {
1646
+ constructor(message, adapterType, cause) {
1647
+ super(message, "DECRYPTION_FAILED", {
1648
+ adapterType,
1649
+ cause
1650
+ });
1651
+ this.name = "DecryptionError";
1652
+ }
1653
+ };
1654
+ /**
1655
+ * Error thrown when encryption fails
1656
+ */
1657
+ var EncryptionError = class extends SecretError {
1658
+ constructor(message, adapterType, cause) {
1659
+ super(message, "ENCRYPTION_FAILED", {
1660
+ adapterType,
1661
+ cause
1662
+ });
1663
+ this.name = "EncryptionError";
1664
+ }
1665
+ };
1666
+ /**
1667
+ * Error thrown when key rotation fails
1668
+ */
1669
+ var KeyRotationError = class extends SecretError {
1670
+ constructor(message, adapterType, cause) {
1671
+ super(message, "KEY_ROTATION_FAILED", {
1672
+ adapterType,
1673
+ cause
1674
+ });
1675
+ this.name = "KeyRotationError";
1270
1676
  }
1271
- async #revokeReceipt(receipt, reason, terminalType = "revoked") {
1272
- const failures = [];
1273
- try {
1274
- await this.#issuer.revoke(receipt.credentialId, reason);
1275
- } catch {
1276
- failures.push("issuer");
1277
- }
1278
- if (!failures.length && receipt.sink && this.#sink) try {
1279
- await this.#sink.remove(receipt.sink, reason);
1280
- } catch {
1281
- failures.push("sink");
1282
- }
1283
- if (failures.length) throw new CustodyError("CREDENTIAL_REVOCATION_FAILED", "revoke", "Credential revocation did not complete", { details: { failedOperations: failures } });
1284
- await this.#appendEventEventually(this.#event(terminalType, receipt.receiptId, void 0, reason));
1677
+ };
1678
+ /**
1679
+ * Error thrown when a tenant's encryption key is missing
1680
+ */
1681
+ var TenantKeyMissingError = class extends SecretError {
1682
+ constructor(tenantId) {
1683
+ super(`No active encryption key for tenant: ${tenantId}`, "TENANT_KEY_MISSING");
1684
+ this.name = "TenantKeyMissingError";
1285
1685
  }
1286
- async #rollback(credentialId, sinkRecord, failedStage, requiresSink = false) {
1287
- const failures = [];
1288
- try {
1289
- await this.#issuer.revoke(credentialId, `rollback after ${failedStage}`);
1290
- } catch {
1291
- failures.push("issuer");
1292
- }
1293
- if (!failures.length && requiresSink && !this.#sink) failures.push("sink");
1294
- if (!failures.length && requiresSink && this.#sink) try {
1295
- if (sinkRecord) await this.#sink.remove(sinkRecord, `rollback after ${failedStage}`);
1296
- else await this.#sink.removeByCredentialId(credentialId, `rollback after ${failedStage}`);
1297
- } catch {
1298
- failures.push("sink");
1299
- }
1300
- if (failures.length) throw new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Credential rollback did not complete", { details: {
1301
- failedOperations: failures,
1302
- failedStage
1303
- } });
1686
+ };
1687
+ /**
1688
+ * Error thrown when the Application Master Key is unavailable
1689
+ */
1690
+ var AMKUnavailableError = class extends SecretError {
1691
+ constructor(message) {
1692
+ super(message, "AMK_UNAVAILABLE");
1693
+ this.name = "AMKUnavailableError";
1304
1694
  }
1305
- async #abortAndRevoke(receipt, reason) {
1306
- const failures = [];
1307
- try {
1308
- await this.#finalizer.abort({
1309
- receipt: structuredClone(receipt),
1310
- reason
1311
- });
1312
- } catch {
1313
- failures.push("finalizer");
1314
- }
1315
- try {
1316
- await this.#revokeReceipt(receipt, reason);
1317
- } catch {
1318
- failures.push("credential");
1319
- }
1320
- if (failures.length) throw new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Finalization rollback did not complete", { details: { failedOperations: failures } });
1695
+ };
1696
+ /**
1697
+ * Error thrown when the store is not initialized
1698
+ */
1699
+ var StoreNotInitializedError = class extends SecretError {
1700
+ constructor(adapterType) {
1701
+ super("Secret store not initialized", "STORE_NOT_INITIALIZED", { adapterType });
1702
+ this.name = "StoreNotInitializedError";
1321
1703
  }
1322
- async #recoverChildProcessCleanupFailure(receipt) {
1323
- const reason = "child process cleanup could not be verified";
1324
- try {
1325
- await this.#abortAndRevoke(receipt, reason);
1326
- this.#leaseInvalidators.delete(receipt.receiptId);
1327
- return;
1328
- } catch (cause) {
1329
- const recoveryId = randomUUID();
1330
- const pendingEvent = {
1331
- ...this.#event("rollback-pending", receipt.receiptId, receipt.sink?.reference, reason),
1332
- eventId: recoveryId,
1333
- recoveryId,
1334
- credentialId: receipt.credentialId,
1335
- requiresSink: receipt.mode === "durable",
1336
- finalizationReceipt: structuredClone(receipt)
1337
- };
1338
- await this.#persistRollbackIntent(pendingEvent);
1339
- this.#scheduleRollback(recoveryId, receipt.credentialId, receipt.sink, "inject", receipt.mode === "durable", receipt, true);
1340
- try {
1341
- this.#onBackgroundError?.(new CustodyError("CREDENTIAL_CHILD_PROCESS_CLEANUP_PENDING", "revoke", "Credential revocation is pending after child process cleanup failure", {
1342
- cause,
1343
- details: { recoveryId }
1344
- }));
1345
- } catch {}
1346
- }
1704
+ };
1705
+ /**
1706
+ * Error thrown when an invalid key format is encountered
1707
+ */
1708
+ var InvalidKeyFormatError = class extends SecretError {
1709
+ constructor(message, adapterType) {
1710
+ super(message, "INVALID_KEY_FORMAT", { adapterType });
1711
+ this.name = "InvalidKeyFormatError";
1347
1712
  }
1348
- async #persistRollbackIntent(event) {
1349
- for (;;) try {
1350
- await this.#ledger.appendEvent(event);
1351
- return;
1352
- } catch (cause) {
1353
- try {
1354
- if ((await this.#ledger.listEvents()).some((existing) => existing.eventId === event.eventId && sameCustodyEvent(existing, event))) return;
1355
- } catch {}
1356
- try {
1357
- this.#onBackgroundError?.(new CustodyError("ROLLBACK_INTENT_PERSISTENCE_FAILED", "record", "Credential rollback intent persistence is retrying", {
1358
- cause,
1359
- details: { recoveryId: event.recoveryId }
1360
- }));
1361
- } catch {}
1362
- await new Promise((resolve) => {
1363
- setTimeout(resolve, this.#ephemeralRevokeRetryMs);
1364
- });
1365
- }
1713
+ };
1714
+ //#endregion
1715
+ //#region src/adapters/database.ts
1716
+ var database_exports = /* @__PURE__ */ __exportAll({
1717
+ DatabaseSecretStore: () => DatabaseSecretStore,
1718
+ default: () => DatabaseSecretStore
1719
+ });
1720
+ /**
1721
+ * Default rotation period in milliseconds (90 days)
1722
+ */
1723
+ var DEFAULT_ROTATION_PERIOD_MS = 2160 * 60 * 60 * 1e3;
1724
+ /**
1725
+ * Database-backed secret store
1726
+ *
1727
+ * Uses envelope encryption with AES-256-GCM:
1728
+ * - Application Master Key (AMK) from environment variable
1729
+ * - Per-tenant Data Encryption Keys (TDEKs) wrapped by AMK
1730
+ * - Secrets encrypted by unwrapped TDEKs
1731
+ *
1732
+ * @example
1733
+ * ```typescript
1734
+ * const store = new DatabaseSecretStore({
1735
+ * type: 'database',
1736
+ * db,
1737
+ * amk: {
1738
+ * provider: 'env',
1739
+ * keyEnvVar: 'SECRET_MASTER_KEY',
1740
+ * keyId: 'amk-v1'
1741
+ * }
1742
+ * });
1743
+ *
1744
+ * await store.initialize();
1745
+ *
1746
+ * // Encrypt a secret for a tenant
1747
+ * const envelope = await store.encrypt('tenant-123', 'api-key', 'synthetic-secret');
1748
+ *
1749
+ * // Decrypt
1750
+ * const { value } = await store.decrypt('tenant-123', envelope);
1751
+ * ```
1752
+ */
1753
+ var DatabaseSecretStore = class {
1754
+ db;
1755
+ keysTable;
1756
+ amkConfig;
1757
+ cachedAmk = null;
1758
+ initialized = false;
1759
+ listeners = [];
1760
+ constructor(options) {
1761
+ this.db = options.db;
1762
+ const tableName = options.keysTable ?? "tenant_encryption_keys";
1763
+ if (!/^[A-Za-z0-9_]+$/.test(tableName)) throw new Error(`Invalid keysTable name "${tableName}". Table name must contain only alphanumeric characters and underscores.`);
1764
+ this.keysTable = tableName;
1765
+ this.amkConfig = options.amk;
1366
1766
  }
1367
- #scheduleRollback(recoveryId, credentialId, sinkRecord, failedStage, requiresSink, finalizationReceipt, receiptRecorded = false) {
1368
- if (this.#pendingTimers.has(recoveryId)) return;
1369
- const timer = setTimeout(() => {
1370
- this.#pendingTimers.delete(recoveryId);
1371
- Promise.resolve().then(async () => {
1372
- if (receiptRecorded && finalizationReceipt) await this.#abortAndRevoke(finalizationReceipt, `rollback after ${failedStage}`);
1373
- else await this.#rollback(credentialId, sinkRecord, failedStage, requiresSink);
1374
- }).then(() => this.#completeRollback(recoveryId, credentialId, sinkRecord?.reference)).then(() => {
1375
- if (receiptRecorded && finalizationReceipt) this.#leaseInvalidators.delete(finalizationReceipt.receiptId);
1376
- }).catch((cause) => {
1377
- try {
1378
- this.#onBackgroundError?.(cause instanceof CustodyError ? cause : new CustodyError("CUSTODY_ROLLBACK_FAILED", "revoke", "Credential rollback retry failed", { cause }));
1379
- } catch {} finally {
1380
- this.#scheduleRollback(recoveryId, credentialId, sinkRecord, failedStage, requiresSink, finalizationReceipt, receiptRecorded);
1381
- }
1382
- });
1383
- }, this.#ephemeralRevokeRetryMs);
1384
- this.#pendingTimers.set(recoveryId, timer);
1385
- timer.unref?.();
1767
+ /**
1768
+ * Initialize the store (create schema if needed)
1769
+ */
1770
+ async initialize() {
1771
+ if (this.initialized) return;
1772
+ const schema = `
1773
+ CREATE TABLE IF NOT EXISTS "${this.keysTable}" (
1774
+ id TEXT PRIMARY KEY,
1775
+ tenant_id TEXT NOT NULL,
1776
+ wrapped_key TEXT NOT NULL,
1777
+ amk_key_id TEXT NOT NULL,
1778
+ status TEXT NOT NULL DEFAULT 'active',
1779
+ version INTEGER NOT NULL DEFAULT 1,
1780
+ rotate_after TEXT,
1781
+ retired_at TEXT,
1782
+ created_at TEXT NOT NULL,
1783
+ updated_at TEXT NOT NULL
1784
+ );
1785
+
1786
+ CREATE INDEX IF NOT EXISTS "idx_${this.keysTable}_tenant_status"
1787
+ ON "${this.keysTable}" (tenant_id, status);
1788
+
1789
+ CREATE INDEX IF NOT EXISTS "idx_${this.keysTable}_rotate_after"
1790
+ ON "${this.keysTable}" (rotate_after)
1791
+ WHERE status = 'active';
1792
+ `;
1793
+ await syncSchema({
1794
+ db: this.db,
1795
+ schema
1796
+ });
1797
+ this.initialized = true;
1386
1798
  }
1387
- #scheduleRetirement(recoveryId, receipt, replacementReceiptId) {
1388
- if (this.#pendingTimers.has(recoveryId)) return;
1389
- const timer = setTimeout(() => {
1390
- this.#pendingTimers.delete(recoveryId);
1391
- this.#ledger.listEvents().then(async (events) => {
1392
- if (replacementReceiptId && (!events.some((event) => event.receiptId === replacementReceiptId && event.type === "issued") || events.some((event) => event.receiptId === replacementReceiptId && [
1393
- "revoked",
1394
- "expired",
1395
- "replaced"
1396
- ].includes(event.type)))) return;
1397
- await this.#revokeReceipt(receipt, "replacement retirement retry", "replaced");
1398
- this.#leaseInvalidators.delete(receipt.receiptId);
1399
- }).then(() => this.#ledger.appendEvent({
1400
- ...this.#event("retirement-complete", receipt.receiptId),
1401
- recoveryId
1402
- })).catch(() => this.#scheduleRetirement(recoveryId, receipt, replacementReceiptId));
1403
- }, this.#ephemeralRevokeRetryMs);
1404
- this.#pendingTimers.set(recoveryId, timer);
1405
- timer.unref?.();
1799
+ /**
1800
+ * Get the Application Master Key from environment
1801
+ */
1802
+ getAMK() {
1803
+ if (this.cachedAmk) return this.cachedAmk;
1804
+ const keyHex = process.env[this.amkConfig.keyEnvVar];
1805
+ if (!keyHex) throw new AMKUnavailableError(`Application Master Key not found in environment variable: ${this.amkConfig.keyEnvVar}`);
1806
+ try {
1807
+ const key = EnvelopeEncryption.parseHexKey(keyHex);
1808
+ this.cachedAmk = key;
1809
+ return key;
1810
+ } catch (error) {
1811
+ throw new AMKUnavailableError(`Invalid AMK in ${this.amkConfig.keyEnvVar}: ${error.message}`);
1812
+ }
1406
1813
  }
1407
- #scheduleReceiptExpiry(receipt, deadline) {
1408
- if (this.#pendingTimers.has(receipt.receiptId)) return;
1409
- const delay = Math.min(Math.max(0, deadline - this.#now().getTime()), MAX_TIMER_DELAY_MS);
1410
- const timer = setTimeout(() => {
1411
- this.#pendingTimers.delete(receipt.receiptId);
1412
- if (deadline > this.#now().getTime()) {
1413
- this.#scheduleReceiptExpiry(receipt, deadline);
1414
- return;
1415
- }
1416
- this.#revokeReceipt(receipt, "restart expiry recovery", "expired").catch(() => this.#scheduleReceiptExpiry(receipt, deadline));
1417
- }, delay);
1418
- this.#pendingTimers.set(receipt.receiptId, timer);
1419
- timer.unref?.();
1814
+ /**
1815
+ * Ensure the store is initialized
1816
+ */
1817
+ ensureInitialized() {
1818
+ if (!this.initialized) throw new StoreNotInitializedError("database");
1420
1819
  }
1421
- #scheduleFinalizationTakeover(recoveryId, deadline) {
1422
- if (this.#pendingTimers.has(recoveryId)) return;
1423
- const timer = setTimeout(() => {
1424
- this.#pendingTimers.delete(recoveryId);
1425
- this.recoverPendingRollbacks().catch((cause) => {
1426
- try {
1427
- this.#onBackgroundError?.(cause instanceof CustodyError ? cause : new CustodyError("PENDING_ROLLBACK_RECOVERY_FAILED", "revoke", "Finalization takeover recovery failed", { cause }));
1428
- } catch {}
1820
+ /**
1821
+ * Emit an event to all listeners
1822
+ */
1823
+ async emitEvent(event) {
1824
+ for (const listener of this.listeners) await listener(event);
1825
+ }
1826
+ /**
1827
+ * Subscribe to store events
1828
+ */
1829
+ subscribe(listener) {
1830
+ this.listeners.push(listener);
1831
+ return () => {
1832
+ const index = this.listeners.indexOf(listener);
1833
+ if (index !== -1) this.listeners.splice(index, 1);
1834
+ };
1835
+ }
1836
+ async encrypt(tenantId, secretName, plaintext, options) {
1837
+ this.ensureInitialized();
1838
+ if (typeof tenantId !== "string" || tenantId.trim().length === 0) throw new EncryptionError("Invalid tenantId provided for encryption", "database");
1839
+ if (typeof secretName !== "string" || secretName.trim().length === 0) throw new EncryptionError("Invalid secretName provided for encryption", "database");
1840
+ let dataKey = null;
1841
+ try {
1842
+ let tenantKey = await this.getTenantKey(tenantId);
1843
+ if (!tenantKey) tenantKey = await this.createTenantKey(tenantId);
1844
+ const amk = this.getAMK();
1845
+ const { wrappedKey, iv: keyIv, authTag: keyAuthTag } = EnvelopeEncryption.parseWrappedKey(tenantKey.wrappedKey);
1846
+ dataKey = EnvelopeEncryption.unwrapKey(wrappedKey, keyIv, keyAuthTag, amk);
1847
+ const envelope = EnvelopeEncryption.createEnvelope(plaintext, dataKey, {
1848
+ wrappedKey,
1849
+ iv: keyIv,
1850
+ authTag: keyAuthTag
1851
+ }, tenantKey.amkKeyId, options?.metadata);
1852
+ await this.emitEvent({
1853
+ type: "secret.encrypted",
1854
+ tenantId,
1855
+ keyId: tenantKey.keyId,
1856
+ secretName,
1857
+ timestamp: /* @__PURE__ */ new Date()
1429
1858
  });
1430
- }, Math.min(Math.max(0, deadline - this.#now().getTime()), MAX_TIMER_DELAY_MS));
1431
- this.#pendingTimers.set(recoveryId, timer);
1432
- timer.unref?.();
1859
+ return envelope;
1860
+ } catch (error) {
1861
+ if (error instanceof AMKUnavailableError || error instanceof TenantKeyMissingError) throw error;
1862
+ throw new EncryptionError(`Failed to encrypt secret '${secretName}' for tenant ${tenantId}: ${error.message}`, "database", error instanceof Error ? error : void 0);
1863
+ } finally {
1864
+ if (dataKey && Buffer.isBuffer(dataKey)) dataKey.fill(0);
1865
+ }
1433
1866
  }
1434
- async #completeRollback(recoveryId, credentialId, sinkReference) {
1435
- await this.#ledger.appendEvent({
1436
- ...this.#event("rollback-complete", void 0, sinkReference, "credential rollback completed"),
1437
- recoveryId,
1438
- credentialId
1867
+ async decrypt(tenantId, envelope) {
1868
+ this.ensureInitialized();
1869
+ if (typeof tenantId !== "string" || tenantId.trim().length === 0) throw new DecryptionError("Invalid tenantId provided for decryption", "database");
1870
+ const tenantKeys = await this.listKeyVersions(tenantId);
1871
+ if (tenantKeys.length === 0) throw new TenantKeyMissingError(tenantId);
1872
+ const envelopeWrappedKey = envelope.wrappedKey.split(":")[0];
1873
+ const matchingKey = tenantKeys.find((key) => {
1874
+ return key.wrappedKey.split(":")[0] === envelopeWrappedKey;
1439
1875
  });
1440
- }
1441
- async #appendEventEventually(event) {
1876
+ if (!matchingKey) throw new DecryptionError(`Envelope was not encrypted with a key belonging to tenant ${tenantId}`, "database");
1442
1877
  try {
1443
- await this.#ledger.appendEvent(event);
1444
- } catch (cause) {
1445
- const recoveryId = `event-${event.eventId}`;
1446
- if (this.#pendingTimers.has(recoveryId)) return;
1447
- const timer = setTimeout(() => {
1448
- this.#pendingTimers.delete(recoveryId);
1449
- this.#appendEventEventually(event).catch(() => void 0);
1450
- }, this.#ephemeralRevokeRetryMs);
1451
- this.#pendingTimers.set(recoveryId, timer);
1452
- try {
1453
- this.#onBackgroundError?.(new CustodyError("CUSTODY_EVENT_RECORD_FAILED", "record", "Custody terminal event recording is pending retry", { cause }));
1454
- } catch {}
1878
+ const amk = this.getAMK();
1879
+ const plaintext = EnvelopeEncryption.decryptEnvelope(envelope, amk);
1880
+ await this.emitEvent({
1881
+ type: "secret.decrypted",
1882
+ tenantId,
1883
+ keyId: matchingKey.keyId,
1884
+ timestamp: /* @__PURE__ */ new Date()
1885
+ });
1886
+ return {
1887
+ value: plaintext,
1888
+ keyId: matchingKey.keyId,
1889
+ createdAt: new Date(envelope.createdAt),
1890
+ metadata: envelope.metadata
1891
+ };
1892
+ } catch (error) {
1893
+ if (error instanceof AMKUnavailableError) throw error;
1894
+ throw new DecryptionError(`Failed to decrypt secret for tenant ${tenantId}: ${error.message}`, "database", error instanceof Error ? error : void 0);
1455
1895
  }
1456
1896
  }
1457
- async #findReceipt(receiptId) {
1458
- assertSafeIdentifier(receiptId, "receiptId", "record");
1459
- const receipt = (await this.#ledger.listReceipts()).find((candidate) => candidate.receiptId === receiptId);
1460
- if (!receipt) throw new CustodyError("CUSTODY_RECEIPT_NOT_FOUND", "record", "Custody receipt was not found");
1461
- return receipt;
1897
+ async getTenantKey(tenantId) {
1898
+ this.ensureInitialized();
1899
+ const row = await this.db.get(this.keysTable, {
1900
+ tenant_id: tenantId,
1901
+ status: "active"
1902
+ });
1903
+ if (!row) return null;
1904
+ return this.parseKeyRow(row);
1462
1905
  }
1463
- #event(type, receiptId, sinkReference, reason) {
1906
+ async createTenantKey(tenantId) {
1907
+ this.ensureInitialized();
1908
+ const amk = this.getAMK();
1909
+ const dataKey = EnvelopeEncryption.generateDataKey();
1910
+ const wrapped = EnvelopeEncryption.wrapKey(dataKey, amk);
1911
+ const keyId = createId();
1912
+ const wrappedKeyStr = `${wrapped.wrappedKey}:${wrapped.iv}:${wrapped.authTag}`;
1913
+ const now = /* @__PURE__ */ new Date();
1914
+ const rotateAfter = new Date(now.getTime() + DEFAULT_ROTATION_PERIOD_MS);
1915
+ await this.db.insert(this.keysTable, {
1916
+ id: keyId,
1917
+ tenant_id: tenantId,
1918
+ wrapped_key: wrappedKeyStr,
1919
+ amk_key_id: this.amkConfig.keyId,
1920
+ status: "active",
1921
+ version: 1,
1922
+ rotate_after: rotateAfter.toISOString(),
1923
+ created_at: now.toISOString(),
1924
+ updated_at: now.toISOString()
1925
+ });
1926
+ await this.emitEvent({
1927
+ type: "key.created",
1928
+ tenantId,
1929
+ keyId,
1930
+ timestamp: now
1931
+ });
1464
1932
  return {
1465
- eventId: randomUUID(),
1466
- type,
1467
- occurredAt: this.#now().toISOString(),
1468
- ...receiptId ? { receiptId } : {},
1469
- ...sinkReference ? { sinkReference } : {},
1470
- ...reason ? { reason: redactCredentialText(reason) } : {}
1933
+ keyId,
1934
+ tenantId,
1935
+ wrappedKey: wrappedKeyStr,
1936
+ amkKeyId: this.amkConfig.keyId,
1937
+ status: "active",
1938
+ version: 1,
1939
+ createdAt: now,
1940
+ rotateAfter
1471
1941
  };
1472
1942
  }
1473
- };
1474
- async function withEnvironmentSecret(material, variableName, operation, bounds) {
1475
- if (!ENVIRONMENT_VARIABLE.test(variableName)) throw new CustodyError("INVALID_ENVIRONMENT_VARIABLE", "inject", "Environment variable name is invalid");
1476
- if (bounds?.expiresAt) {
1477
- parseTimestamp(bounds.expiresAt, "expiresAt", "inject");
1478
- throw new CustodyError("EXPIRING_ENVIRONMENT_CALLBACK_UNSAFE", "inject", "Expiring credentials require bounded child-process injection");
1479
- }
1480
- await withEnvironmentLock(async () => {
1481
- const existed = Object.hasOwn(process.env, variableName);
1482
- const previous = process.env[variableName];
1943
+ async rotateTenantKey(tenantId) {
1944
+ this.ensureInitialized();
1945
+ const currentKey = await this.getTenantKey(tenantId);
1946
+ if (!currentKey) throw new TenantKeyMissingError(tenantId);
1947
+ const now = /* @__PURE__ */ new Date();
1483
1948
  try {
1484
- await material.use(async (value) => {
1485
- process.env[variableName] = value;
1486
- await operation();
1949
+ await this.db.update(this.keysTable, { id: currentKey.keyId }, {
1950
+ status: "rotating",
1951
+ updated_at: now.toISOString()
1487
1952
  });
1488
- } catch (cause) {
1489
- if (cause instanceof CustodyError) throw cause;
1490
- throw new CustodyError("SECRET_OPERATION_FAILED", "inject", "Bounded secret operation failed", { cause });
1491
- } finally {
1492
- if (existed) process.env[variableName] = previous;
1493
- else delete process.env[variableName];
1494
- }
1495
- });
1496
- }
1497
- async function runCredentialChildProcess(material, options, bounds) {
1498
- if (options.trust !== "cooperative-process-group" || !options.command || !ENVIRONMENT_VARIABLE.test(options.environmentVariable)) throw new CustodyError("INVALID_CHILD_PROCESS_OPTIONS", "inject", "Credential child-process options are invalid");
1499
- if (process.platform === "win32") throw new CustodyError("CREDENTIAL_CHILD_PROCESS_UNSUPPORTED", "inject", "Credential child-process group custody is unavailable on this platform");
1500
- const timeoutMs = options.timeoutMs ?? 6e4;
1501
- const maxOutputBytes = options.maxOutputBytes ?? 1024 * 1024;
1502
- if (!Number.isFinite(timeoutMs) || !Number.isFinite(maxOutputBytes) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DELAY_MS || maxOutputBytes <= 0) throw new CustodyError("INVALID_CHILD_PROCESS_BOUNDS", "inject", "Credential child-process bounds must be positive");
1503
- let result;
1504
- await material.use(async (secret) => {
1505
- const expiryLimit = bounds?.expiresAt ? parseTimestamp(bounds.expiresAt, "expiresAt", "inject") - Date.now() : Number.POSITIVE_INFINITY;
1506
- const effectiveTimeout = Math.min(timeoutMs, expiryLimit);
1507
- if (effectiveTimeout <= 0) throw new CustodyError("CREDENTIAL_EXPIRED", "inject", "Credential expired before child-process launch");
1508
- const childEnvironment = await withEnvironmentLock(() => ({
1509
- ...process.env,
1510
- ...options.environment,
1511
- [options.environmentVariable]: secret
1512
- }));
1513
- result = await new Promise((resolve, reject) => {
1514
- const child = spawn(options.command, [...options.args ?? []], {
1515
- cwd: options.cwd,
1516
- detached: true,
1517
- env: childEnvironment,
1518
- shell: false,
1519
- stdio: [
1520
- "ignore",
1521
- "pipe",
1522
- "pipe"
1523
- ]
1953
+ const amk = this.getAMK();
1954
+ const dataKey = EnvelopeEncryption.generateDataKey();
1955
+ const wrapped = EnvelopeEncryption.wrapKey(dataKey, amk);
1956
+ const newKeyId = createId();
1957
+ const wrappedKeyStr = `${wrapped.wrappedKey}:${wrapped.iv}:${wrapped.authTag}`;
1958
+ const rotateAfter = new Date(now.getTime() + DEFAULT_ROTATION_PERIOD_MS);
1959
+ await this.db.insert(this.keysTable, {
1960
+ id: newKeyId,
1961
+ tenant_id: tenantId,
1962
+ wrapped_key: wrappedKeyStr,
1963
+ amk_key_id: this.amkConfig.keyId,
1964
+ status: "active",
1965
+ version: currentKey.version + 1,
1966
+ rotate_after: rotateAfter.toISOString(),
1967
+ created_at: now.toISOString(),
1968
+ updated_at: now.toISOString()
1524
1969
  });
1525
- const stdout = [];
1526
- const stderr = [];
1527
- let outputBytes = 0;
1528
- let outputExceeded = false;
1529
- let timedOut = false;
1530
- let settled = false;
1531
- let escalationTimer;
1532
- const terminateGroup = (signal) => {
1533
- if (child.pid) try {
1534
- process.kill(-child.pid, signal);
1535
- return;
1536
- } catch {}
1537
- child.kill(signal);
1538
- };
1539
- const waitForGroupExit = async () => {
1540
- if (!child.pid) return true;
1541
- const deadline = Date.now() + 2e3;
1542
- while (Date.now() < deadline) {
1543
- try {
1544
- process.kill(-child.pid, 0);
1545
- } catch (cause) {
1546
- if (cause.code === "ESRCH") return true;
1547
- }
1548
- await new Promise((next) => setTimeout(next, 10));
1549
- }
1550
- return false;
1551
- };
1552
- const beginTermination = () => {
1553
- terminateGroup("SIGTERM");
1554
- if (!escalationTimer) {
1555
- escalationTimer = setTimeout(() => {
1556
- escalationTimer = void 0;
1557
- terminateGroup("SIGKILL");
1558
- }, 1e3);
1559
- escalationTimer.unref?.();
1560
- }
1561
- };
1562
- const timer = setTimeout(() => {
1563
- timedOut = true;
1564
- beginTermination();
1565
- }, effectiveTimeout);
1566
- timer.unref?.();
1567
- const capture = (target) => (chunk) => {
1568
- outputBytes += chunk.length;
1569
- if (outputBytes > maxOutputBytes) {
1570
- timedOut = true;
1571
- outputExceeded = true;
1572
- target.length = 0;
1573
- beginTermination();
1574
- return;
1575
- }
1576
- if (outputExceeded) return;
1577
- target.push(Buffer.from(chunk));
1578
- };
1579
- child.stdout.on("data", capture(stdout));
1580
- child.stderr.on("data", capture(stderr));
1581
- child.once("error", () => {
1582
- if (settled) return;
1583
- settled = true;
1584
- clearTimeout(timer);
1585
- if (escalationTimer) clearTimeout(escalationTimer);
1586
- terminateGroup("SIGKILL");
1587
- reject(new CustodyError("CREDENTIAL_CHILD_PROCESS_FAILED", "inject", "Credential child process could not start"));
1970
+ await this.db.update(this.keysTable, { id: currentKey.keyId }, {
1971
+ status: "retired",
1972
+ retired_at: now.toISOString(),
1973
+ updated_at: now.toISOString()
1588
1974
  });
1589
- child.once("close", async (exitCode, signal) => {
1590
- if (settled) return;
1591
- settled = true;
1592
- clearTimeout(timer);
1593
- if (escalationTimer) clearTimeout(escalationTimer);
1594
- terminateGroup("SIGTERM");
1595
- terminateGroup("SIGKILL");
1596
- if (!await waitForGroupExit()) {
1597
- reject(new CustodyError("CREDENTIAL_CHILD_PROCESS_CLEANUP_FAILED", "inject", "Credential child process group cleanup could not be verified"));
1598
- return;
1599
- }
1600
- resolve({
1601
- exitCode,
1602
- signal,
1603
- stdout: outputExceeded ? REDACTED : redactCredentialText(Buffer.concat(stdout).toString("utf8"), [secret]),
1604
- stderr: outputExceeded ? REDACTED : redactCredentialText(Buffer.concat(stderr).toString("utf8"), [secret]),
1605
- timedOut
1606
- });
1975
+ await this.emitEvent({
1976
+ type: "key.rotated",
1977
+ tenantId,
1978
+ keyId: newKeyId,
1979
+ timestamp: now
1607
1980
  });
1608
- });
1609
- });
1610
- if (!result) throw new CustodyError("CREDENTIAL_CHILD_PROCESS_FAILED", "inject", "Credential child process did not return a result");
1611
- return result;
1612
- }
1613
- async function verifyCustodyReceiptAttestation(receipt, material, publicKey) {
1614
- if (receipt.attestation.algorithm !== "Ed25519" || publicKey.type !== "public" || publicKey.asymmetricKeyType !== "ed25519" || !/^[A-Za-z0-9_-]{86}$/.test(receipt.attestation.signature) || Buffer.from(receipt.attestation.signature, "base64url").byteLength !== 64 || Buffer.from(receipt.attestation.signature, "base64url").toString("base64url") !== receipt.attestation.signature) return false;
1615
- let verified = false;
1616
- await material.use((plaintext) => {
1617
- const payload = custodyAttestationPayload(receipt, credentialCommitment(plaintext));
1618
- try {
1619
- verified = verify(null, Buffer.from(payload), publicKey, Buffer.from(receipt.attestation.signature, "base64url"));
1620
- } catch {
1621
- verified = false;
1981
+ return {
1982
+ keyId: newKeyId,
1983
+ tenantId,
1984
+ wrappedKey: wrappedKeyStr,
1985
+ amkKeyId: this.amkConfig.keyId,
1986
+ status: "active",
1987
+ version: currentKey.version + 1,
1988
+ createdAt: now,
1989
+ rotateAfter
1990
+ };
1991
+ } catch (error) {
1992
+ throw new KeyRotationError(`Failed to rotate key for tenant ${tenantId}: ${error.message}`, "database", error instanceof Error ? error : void 0);
1622
1993
  }
1623
- });
1624
- return verified;
1625
- }
1626
- function redactCredentialText(input, knownSecrets = []) {
1627
- let output = input;
1628
- for (const secret of knownSecrets.filter(Boolean)) output = output.replaceAll(secret, REDACTED);
1629
- for (const { pattern, replacement } of CREDENTIAL_PATTERNS) output = output.replace(pattern, replacement);
1630
- return output;
1631
- }
1632
- function redactCredentialValues(value, knownSecrets = []) {
1633
- if (value instanceof SecretMaterial) return REDACTED;
1634
- if (typeof value === "string") return redactCredentialText(value, knownSecrets);
1635
- if (Array.isArray(value)) return value.map((entry) => redactCredentialValues(entry, knownSecrets));
1636
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [redactCredentialText(key, knownSecrets), redactCredentialValues(entry, knownSecrets)]));
1637
- return value;
1638
- }
1639
- async function sanitizeCustodyCause(cause, materials) {
1640
- if (!(cause instanceof CustodyError)) return cause;
1641
- const knownSecrets = [];
1642
- for (const material of materials) {
1643
- if (!material || material.destroyed) continue;
1644
- await material.use((value) => {
1645
- knownSecrets.push(value);
1994
+ }
1995
+ async retireTenantKey(tenantId, keyId) {
1996
+ this.ensureInitialized();
1997
+ const now = /* @__PURE__ */ new Date();
1998
+ await this.db.update(this.keysTable, {
1999
+ id: keyId,
2000
+ tenant_id: tenantId
2001
+ }, {
2002
+ status: "retired",
2003
+ retired_at: now.toISOString(),
2004
+ updated_at: now.toISOString()
2005
+ });
2006
+ await this.emitEvent({
2007
+ type: "key.retired",
2008
+ tenantId,
2009
+ keyId,
2010
+ timestamp: now
1646
2011
  });
1647
2012
  }
1648
- return new CustodyError(redactCredentialText(cause.code, knownSecrets) === cause.code ? cause.code : "INVALID_CUSTODY_ERROR_CODE", cause.stage, redactCredentialText(cause.message, knownSecrets), cause.details ? { details: redactCredentialValues(cause.details, knownSecrets) } : void 0);
1649
- }
1650
- function credentialCommitment(plaintext) {
1651
- return createHash("sha256").update(plaintext).digest("base64url");
1652
- }
1653
- function custodyAttestationPayload(receipt, commitment, identity) {
1654
- const { attestation, ...unsigned } = receipt;
1655
- return JSON.stringify(canonicalize({
1656
- schema: "happyvertical.credential-custody-attestation.v1",
1657
- receipt: unsigned,
1658
- attestation: identity ?? {
1659
- algorithm: attestation.algorithm,
1660
- attestor: attestation.attestor,
1661
- keyId: attestation.keyId
1662
- },
1663
- credentialCommitment: commitment
1664
- }));
1665
- }
1666
- function canonicalize(value) {
1667
- if (Array.isArray(value)) return value.map(canonicalize);
1668
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => [key, canonicalize(entry)]));
1669
- return value;
1670
- }
1671
- function sameCustodyEvent(left, right) {
1672
- return JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right));
1673
- }
1674
- function assertAttribution(attribution) {
1675
- assertSafeIdentifier(attribution.actor, "attribution.actor", "issue");
1676
- assertSafeIdentifier(attribution.runtime, "attribution.runtime", "issue");
1677
- assertSafeIdentifier(attribution.session, "attribution.session", "issue");
1678
- }
1679
- function assertSinkRecord(record, sinkName) {
1680
- if (record.sinkName !== sinkName) throw new CustodyError("SINK_IDENTITY_MISMATCH", "store", "Secret sink returned a mismatched identity");
1681
- assertSafeIdentifier(record.sinkName, "sinkName", "store");
1682
- assertSafeIdentifier(record.reference, "sinkReference", "store");
1683
- assertSafeIdentifier(record.version, "sinkVersion", "store");
1684
- if (!Number.isFinite(new Date(record.storedAt).getTime())) throw new CustodyError("INVALID_SINK_TIMESTAMP", "store", "Secret sink returned an invalid timestamp");
1685
- }
1686
- function assertSafeIdentifier(value, field, stage) {
1687
- if (!SAFE_IDENTIFIER.test(value) || redactCredentialText(value) !== value) throw new CustodyError("UNSAFE_CUSTODY_IDENTIFIER", stage, `Custody ${field} must be a non-secret identifier`);
1688
- }
1689
- function sanitizeMetadata(metadata) {
1690
- return Object.freeze(Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => {
1691
- if (redactCredentialText(key) !== key) throw new CustodyError("UNSAFE_CUSTODY_METADATA_KEY", "issue", "Custody metadata key must not contain credential material");
1692
- return [key, redactCredentialText(value)];
1693
- })));
1694
- }
1695
- function parseTimestamp(value, field, stage) {
1696
- const timestamp = new Date(value).getTime();
1697
- if (!Number.isFinite(timestamp)) throw new CustodyError("INVALID_CUSTODY_TIMESTAMP", stage, `Custody ${field} timestamp is invalid`);
1698
- return timestamp;
1699
- }
1700
- function sameSinkRecord(left, right) {
1701
- return left.sinkName === right.sinkName && left.reference === right.reference && left.version === right.version && left.storedAt === right.storedAt;
1702
- }
1703
- function sinkIdentity(record, credentialId) {
1704
- return [
1705
- record.sinkName,
1706
- record.reference,
1707
- record.version,
1708
- record.storedAt,
1709
- credentialId ?? ""
1710
- ].join("\0");
1711
- }
2013
+ async getActiveAMK() {
2014
+ this.getAMK();
2015
+ return {
2016
+ keyId: this.amkConfig.keyId,
2017
+ description: `AMK from env var ${this.amkConfig.keyEnvVar}`,
2018
+ status: "active",
2019
+ provider: "env",
2020
+ keyReference: this.amkConfig.keyEnvVar,
2021
+ createdAt: /* @__PURE__ */ new Date()
2022
+ };
2023
+ }
2024
+ async rewrapTenantKey(_tenantId, _newAmkKeyId) {
2025
+ throw new Error("AMK rotation not supported for env-based keys. Use AWS KMS, Vault, or Azure Key Vault for AMK rotation support.");
2026
+ }
2027
+ async listKeyVersions(tenantId) {
2028
+ this.ensureInitialized();
2029
+ const { rows } = await this.db.query(`SELECT * FROM "${this.keysTable}" WHERE tenant_id = ? ORDER BY version DESC`, tenantId);
2030
+ return rows.map((row) => this.parseKeyRow(row));
2031
+ }
2032
+ /**
2033
+ * Parse a database row into a TenantDataEncryptionKey
2034
+ */
2035
+ parseKeyRow(row) {
2036
+ return {
2037
+ keyId: row.id,
2038
+ tenantId: row.tenant_id,
2039
+ wrappedKey: row.wrapped_key,
2040
+ amkKeyId: row.amk_key_id,
2041
+ status: row.status,
2042
+ version: row.version,
2043
+ createdAt: new Date(row.created_at),
2044
+ rotateAfter: row.rotate_after ? new Date(row.rotate_after) : void 0,
2045
+ retiredAt: row.retired_at ? new Date(row.retired_at) : void 0
2046
+ };
2047
+ }
2048
+ };
1712
2049
  //#endregion
1713
2050
  //#region src/shared/factory.ts
1714
2051
  /**
@@ -1777,6 +2114,6 @@ async function getSecretStore(options) {
1777
2114
  /** @internal */
1778
2115
  var PACKAGE_VERSION_INITIALIZED = true;
1779
2116
  //#endregion
1780
- export { AMKUnavailableError, CredentialCustody, CustodyError, DatabaseSecretStore, DecryptionError, Ed25519CustodyReceiptAttestor, EncryptionError, EnvelopeEncryption, InMemoryCustodyLedger, InvalidKeyFormatError, KeyNotFoundError, KeyRotationError, PACKAGE_VERSION_INITIALIZED, SecretError, SecretMaterial, StoreNotInitializedError, TenantKeyMissingError, getSecretStore, isAWSKMSOptions, isAzureKeyVaultOptions, isDatabaseOptions, isVaultOptions, redactCredentialText, redactCredentialValues, runCredentialChildProcess, verifyCustodyReceiptAttestation, withEnvironmentSecret };
2117
+ export { AMKUnavailableError, CredentialCustody, CustodyError, DatabaseCustodyLedger, DatabaseSecretStore, DecryptionError, Ed25519CustodyReceiptAttestor, EncryptionError, EnvelopeEncryption, InMemoryCustodyLedger, InvalidKeyFormatError, KeyNotFoundError, KeyRotationError, PACKAGE_VERSION_INITIALIZED, SecretError, SecretMaterial, StoreNotInitializedError, TenantKeyMissingError, getSecretStore, isAWSKMSOptions, isAzureKeyVaultOptions, isDatabaseOptions, isVaultOptions, redactCredentialText, redactCredentialValues, runCredentialChildProcess, verifyCustodyReceiptAttestation, withEnvironmentSecret };
1781
2118
 
1782
2119
  //# sourceMappingURL=index.js.map