anonyma 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +273 -144
  2. package/README.md +427 -143
  3. package/dist/ai/index.cjs +522 -0
  4. package/dist/ai/index.cjs.map +1 -0
  5. package/dist/ai/index.d.cts +322 -0
  6. package/dist/ai/index.d.ts +322 -0
  7. package/dist/ai/index.js +505 -0
  8. package/dist/ai/index.js.map +1 -0
  9. package/dist/audit/index.cjs +359 -0
  10. package/dist/audit/index.cjs.map +1 -0
  11. package/dist/audit/index.d.cts +287 -0
  12. package/dist/audit/index.d.ts +287 -0
  13. package/dist/audit/index.js +340 -0
  14. package/dist/audit/index.js.map +1 -0
  15. package/dist/chunk-26IHMQHL.cjs +662 -0
  16. package/dist/chunk-26IHMQHL.cjs.map +1 -0
  17. package/dist/chunk-2F2GWGTB.js +174 -0
  18. package/dist/chunk-2F2GWGTB.js.map +1 -0
  19. package/dist/chunk-2NNMJ55L.cjs +45 -0
  20. package/dist/chunk-2NNMJ55L.cjs.map +1 -0
  21. package/dist/chunk-2YG7R4KJ.cjs +114 -0
  22. package/dist/chunk-2YG7R4KJ.cjs.map +1 -0
  23. package/dist/chunk-2ZZHLCEJ.js +237 -0
  24. package/dist/chunk-2ZZHLCEJ.js.map +1 -0
  25. package/dist/chunk-3CY6ATKS.cjs +308 -0
  26. package/dist/chunk-3CY6ATKS.cjs.map +1 -0
  27. package/dist/chunk-3D5ZCJ7R.js +268 -0
  28. package/dist/chunk-3D5ZCJ7R.js.map +1 -0
  29. package/dist/chunk-6LDAIJBL.js +103 -0
  30. package/dist/chunk-6LDAIJBL.js.map +1 -0
  31. package/dist/chunk-7HK2V5Q4.js +111 -0
  32. package/dist/chunk-7HK2V5Q4.js.map +1 -0
  33. package/dist/chunk-AAP472NG.js +177 -0
  34. package/dist/chunk-AAP472NG.js.map +1 -0
  35. package/dist/chunk-AP4JIUNW.js +42 -0
  36. package/dist/chunk-AP4JIUNW.js.map +1 -0
  37. package/dist/chunk-BBJPQPGP.js +457 -0
  38. package/dist/chunk-BBJPQPGP.js.map +1 -0
  39. package/dist/chunk-CRXRJZEV.cjs +82 -0
  40. package/dist/chunk-CRXRJZEV.cjs.map +1 -0
  41. package/dist/chunk-E3PICZYI.js +20 -0
  42. package/dist/chunk-E3PICZYI.js.map +1 -0
  43. package/dist/chunk-F7O2FA3F.cjs +1255 -0
  44. package/dist/chunk-F7O2FA3F.cjs.map +1 -0
  45. package/dist/chunk-FB56NAAH.cjs +243 -0
  46. package/dist/chunk-FB56NAAH.cjs.map +1 -0
  47. package/dist/chunk-G4AN7FND.js +1063 -0
  48. package/dist/chunk-G4AN7FND.js.map +1 -0
  49. package/dist/chunk-GS3FRH4K.js +294 -0
  50. package/dist/chunk-GS3FRH4K.js.map +1 -0
  51. package/dist/chunk-GYMG5OI3.cjs +186 -0
  52. package/dist/chunk-GYMG5OI3.cjs.map +1 -0
  53. package/dist/chunk-IHEIYZPL.cjs +301 -0
  54. package/dist/chunk-IHEIYZPL.cjs.map +1 -0
  55. package/dist/chunk-IJAMLYOT.cjs +1087 -0
  56. package/dist/chunk-IJAMLYOT.cjs.map +1 -0
  57. package/dist/chunk-ISL5B4LU.cjs +181 -0
  58. package/dist/chunk-ISL5B4LU.cjs.map +1 -0
  59. package/dist/chunk-JKW36IPT.js +179 -0
  60. package/dist/chunk-JKW36IPT.js.map +1 -0
  61. package/dist/chunk-KOCQBDI4.cjs +179 -0
  62. package/dist/chunk-KOCQBDI4.cjs.map +1 -0
  63. package/dist/chunk-OGNLB2KA.js +79 -0
  64. package/dist/chunk-OGNLB2KA.js.map +1 -0
  65. package/dist/chunk-PKHZ7CVI.js +28 -0
  66. package/dist/chunk-PKHZ7CVI.js.map +1 -0
  67. package/dist/chunk-QYD4F6T7.cjs +114 -0
  68. package/dist/chunk-QYD4F6T7.cjs.map +1 -0
  69. package/dist/chunk-RCW5IPPR.js +1288 -0
  70. package/dist/chunk-RCW5IPPR.js.map +1 -0
  71. package/dist/chunk-RMMKYHUN.cjs +35 -0
  72. package/dist/chunk-RMMKYHUN.cjs.map +1 -0
  73. package/dist/chunk-S4BJ2ADB.cjs +22 -0
  74. package/dist/chunk-S4BJ2ADB.cjs.map +1 -0
  75. package/dist/chunk-S7NH6CHY.cjs +462 -0
  76. package/dist/chunk-S7NH6CHY.cjs.map +1 -0
  77. package/dist/chunk-SIHPDZXA.js +176 -0
  78. package/dist/chunk-SIHPDZXA.js.map +1 -0
  79. package/dist/chunk-TW7PM3UJ.cjs +30 -0
  80. package/dist/chunk-TW7PM3UJ.cjs.map +1 -0
  81. package/dist/chunk-UA3EOFBS.cjs +1322 -0
  82. package/dist/chunk-UA3EOFBS.cjs.map +1 -0
  83. package/dist/chunk-VE4CCW7W.js +32 -0
  84. package/dist/chunk-VE4CCW7W.js.map +1 -0
  85. package/dist/chunk-W6RBCHYF.js +651 -0
  86. package/dist/chunk-W6RBCHYF.js.map +1 -0
  87. package/dist/chunk-WLJN7GIS.cjs +189 -0
  88. package/dist/chunk-WLJN7GIS.cjs.map +1 -0
  89. package/dist/chunk-YMLR375Z.js +1244 -0
  90. package/dist/chunk-YMLR375Z.js.map +1 -0
  91. package/dist/compliance/index.cjs +88 -0
  92. package/dist/compliance/index.cjs.map +1 -0
  93. package/dist/compliance/index.d.cts +277 -0
  94. package/dist/compliance/index.d.ts +277 -0
  95. package/dist/compliance/index.js +47 -0
  96. package/dist/compliance/index.js.map +1 -0
  97. package/dist/crypto.cjs +12 -136
  98. package/dist/crypto.cjs.map +1 -1
  99. package/dist/crypto.d.cts +4 -3
  100. package/dist/crypto.d.ts +4 -3
  101. package/dist/crypto.js +3 -137
  102. package/dist/crypto.js.map +1 -1
  103. package/dist/detectors/index.cjs +146 -1483
  104. package/dist/detectors/index.cjs.map +1 -1
  105. package/dist/detectors/index.d.cts +1 -1
  106. package/dist/detectors/index.d.ts +1 -1
  107. package/dist/detectors/index.js +3 -1449
  108. package/dist/detectors/index.js.map +1 -1
  109. package/dist/engine/index.cjs +441 -0
  110. package/dist/engine/index.cjs.map +1 -0
  111. package/dist/engine/index.d.cts +728 -0
  112. package/dist/engine/index.d.ts +728 -0
  113. package/dist/engine/index.js +189 -0
  114. package/dist/engine/index.js.map +1 -0
  115. package/dist/hash-2PSYNDMM.cjs +14 -0
  116. package/dist/hash-2PSYNDMM.cjs.map +1 -0
  117. package/dist/hash-CELLDNKN.js +5 -0
  118. package/dist/hash-CELLDNKN.js.map +1 -0
  119. package/dist/index.cjs +153 -2816
  120. package/dist/index.cjs.map +1 -1
  121. package/dist/index.d.cts +93 -11
  122. package/dist/index.d.ts +93 -11
  123. package/dist/index.js +13 -2791
  124. package/dist/index.js.map +1 -1
  125. package/dist/json-CKDvlRtl.d.ts +147 -0
  126. package/dist/json-s8ny-RCo.d.cts +147 -0
  127. package/dist/mcp/index.cjs +751 -0
  128. package/dist/mcp/index.cjs.map +1 -0
  129. package/dist/mcp/index.d.cts +226 -0
  130. package/dist/mcp/index.d.ts +226 -0
  131. package/dist/mcp/index.js +744 -0
  132. package/dist/mcp/index.js.map +1 -0
  133. package/dist/middleware/express.cjs +93 -0
  134. package/dist/middleware/express.cjs.map +1 -0
  135. package/dist/middleware/express.d.cts +90 -0
  136. package/dist/middleware/express.d.ts +90 -0
  137. package/dist/middleware/express.js +91 -0
  138. package/dist/middleware/express.js.map +1 -0
  139. package/dist/middleware/hono.cjs +58 -0
  140. package/dist/middleware/hono.cjs.map +1 -0
  141. package/dist/middleware/hono.d.cts +75 -0
  142. package/dist/middleware/hono.d.ts +75 -0
  143. package/dist/middleware/hono.js +56 -0
  144. package/dist/middleware/hono.js.map +1 -0
  145. package/dist/middleware/index.cjs +24 -0
  146. package/dist/middleware/index.cjs.map +1 -0
  147. package/dist/middleware/index.d.cts +106 -0
  148. package/dist/middleware/index.d.ts +106 -0
  149. package/dist/middleware/index.js +15 -0
  150. package/dist/middleware/index.js.map +1 -0
  151. package/dist/schemas.cjs +5 -5
  152. package/dist/schemas.cjs.map +1 -1
  153. package/dist/schemas.d.cts +20 -10
  154. package/dist/schemas.d.ts +20 -10
  155. package/dist/schemas.js +5 -5
  156. package/dist/schemas.js.map +1 -1
  157. package/dist/session-BdRftyZ5.d.cts +102 -0
  158. package/dist/session-Cs2zlNQp.d.ts +102 -0
  159. package/dist/stream.cjs +13 -2262
  160. package/dist/stream.cjs.map +1 -1
  161. package/dist/stream.d.cts +1 -1
  162. package/dist/stream.d.ts +1 -1
  163. package/dist/stream.js +6 -2255
  164. package/dist/stream.js.map +1 -1
  165. package/dist/types--tPm_AjY.d.ts +199 -0
  166. package/dist/types-0BJH_wqc.d.cts +199 -0
  167. package/dist/types-CPUhjvl8.d.cts +629 -0
  168. package/dist/types-Dtht33aq.d.ts +629 -0
  169. package/dist/{types-D-9HzVuy.d.cts → types-EJTj_BKY.d.cts} +38 -7
  170. package/dist/{types-D-9HzVuy.d.ts → types-EJTj_BKY.d.ts} +38 -7
  171. package/dist/types-Zt_bZvwS.d.cts +182 -0
  172. package/dist/types-Zt_bZvwS.d.ts +182 -0
  173. package/dist/validators.cjs +39 -181
  174. package/dist/validators.cjs.map +1 -1
  175. package/dist/validators.js +1 -174
  176. package/dist/validators.js.map +1 -1
  177. package/dist/vault/index.cjs +688 -0
  178. package/dist/vault/index.cjs.map +1 -0
  179. package/dist/vault/index.d.cts +385 -0
  180. package/dist/vault/index.d.ts +385 -0
  181. package/dist/vault/index.js +669 -0
  182. package/dist/vault/index.js.map +1 -0
  183. package/package.json +128 -11
@@ -0,0 +1,688 @@
1
+ 'use strict';
2
+
3
+ var chunk2NNMJ55L_cjs = require('../chunk-2NNMJ55L.cjs');
4
+ var chunkQYD4F6T7_cjs = require('../chunk-QYD4F6T7.cjs');
5
+ var chunkFB56NAAH_cjs = require('../chunk-FB56NAAH.cjs');
6
+ var chunkTW7PM3UJ_cjs = require('../chunk-TW7PM3UJ.cjs');
7
+ var chunkWLJN7GIS_cjs = require('../chunk-WLJN7GIS.cjs');
8
+
9
+ // src/vault/keyring.ts
10
+ var DEFAULT_PBKDF2_ITERATIONS = 6e5;
11
+ var MIN_PBKDF2_ITERATIONS = 1e5;
12
+ var MIN_RAW_BYTES = 32;
13
+ var SALT_BYTES = 32;
14
+ var MIN_SALT_BYTES = 16;
15
+ var STATES = /* @__PURE__ */ new Set(["active", "retired", "destroyed"]);
16
+ async function importBase(crypto, id, material, salt, iterations) {
17
+ let keyingMaterial;
18
+ if (material.kind === "raw") {
19
+ if (!(material.bytes instanceof Uint8Array) || material.bytes.length < MIN_RAW_BYTES) {
20
+ throw new chunkWLJN7GIS_cjs.KeyManagementError(
21
+ `raw key material must be at least ${String(MIN_RAW_BYTES)} bytes`,
22
+ id
23
+ );
24
+ }
25
+ keyingMaterial = new Uint8Array(material.bytes);
26
+ } else {
27
+ if (typeof material.passphrase !== "string" || material.passphrase.length === 0) {
28
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("the passphrase must not be empty", id);
29
+ }
30
+ const passphraseKey = await crypto.subtle.importKey(
31
+ "raw",
32
+ chunkQYD4F6T7_cjs.utf8(material.passphrase),
33
+ "PBKDF2",
34
+ false,
35
+ ["deriveBits"]
36
+ );
37
+ const bits = await crypto.subtle.deriveBits(
38
+ {
39
+ name: "PBKDF2",
40
+ hash: "SHA-256",
41
+ salt,
42
+ iterations: iterations ?? DEFAULT_PBKDF2_ITERATIONS
43
+ },
44
+ passphraseKey,
45
+ 256
46
+ );
47
+ keyingMaterial = new Uint8Array(bits);
48
+ }
49
+ return crypto.subtle.importKey("raw", keyingMaterial, "HKDF", false, ["deriveKey"]);
50
+ }
51
+ function resolveIterations(id, material, fromManifest) {
52
+ if (material.kind !== "passphrase") return void 0;
53
+ if (fromManifest !== void 0 && material.iterations !== void 0 && material.iterations !== fromManifest) {
54
+ throw new chunkWLJN7GIS_cjs.KeyManagementError(
55
+ "the iteration count differs from the one this version was created with",
56
+ id
57
+ );
58
+ }
59
+ const iterations = fromManifest ?? material.iterations ?? DEFAULT_PBKDF2_ITERATIONS;
60
+ if (!Number.isInteger(iterations) || iterations < MIN_PBKDF2_ITERATIONS) {
61
+ throw new chunkWLJN7GIS_cjs.KeyManagementError(
62
+ `PBKDF2 needs at least ${String(MIN_PBKDF2_ITERATIONS)} iterations`,
63
+ id
64
+ );
65
+ }
66
+ return iterations;
67
+ }
68
+ async function generateKeyMaterial() {
69
+ return { kind: "raw", bytes: chunkQYD4F6T7_cjs.randomBytes(await chunkTW7PM3UJ_cjs.webCrypto(), MIN_RAW_BYTES) };
70
+ }
71
+ async function createKeyRing(options) {
72
+ const { namespace, keys, manifest } = options;
73
+ const now = options.now ?? Date.now;
74
+ if (typeof namespace !== "string" || namespace.length === 0 || !chunkQYD4F6T7_cjs.isWellFormed(namespace)) {
75
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("the namespace must be a non-empty, well-formed string");
76
+ }
77
+ const crypto = await chunkTW7PM3UJ_cjs.webCrypto();
78
+ const versions = /* @__PURE__ */ new Map();
79
+ const derived = /* @__PURE__ */ new Map();
80
+ let active;
81
+ let mac = "";
82
+ const supplied = /* @__PURE__ */ new Map();
83
+ for (const { id, material } of keys) {
84
+ if (!chunkFB56NAAH_cjs.isKeyId(id)) {
85
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("key identifiers are 1-16 characters of A-Z, a-z and 0-9");
86
+ }
87
+ if (supplied.has(id)) throw new chunkWLJN7GIS_cjs.KeyManagementError("the identifier is used more than once", id);
88
+ supplied.set(id, material);
89
+ }
90
+ if (manifest === void 0) {
91
+ for (const [id, material] of supplied) await add(id, material);
92
+ if (active === void 0)
93
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("a key ring needs one active key version");
94
+ mac = await sign();
95
+ } else {
96
+ const infos = readManifest(manifest, namespace);
97
+ for (const info of infos) {
98
+ const material = supplied.get(info.id);
99
+ supplied.delete(info.id);
100
+ const salt = chunkQYD4F6T7_cjs.fromBase64Url(info.salt) ?? new Uint8Array(0);
101
+ if (info.state === "destroyed") {
102
+ versions.set(info.id, { ...info, salt, iterations: info.iterations, base: void 0 });
103
+ continue;
104
+ }
105
+ if (material === void 0) {
106
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("no key material was supplied for a live version", info.id);
107
+ }
108
+ if (material.kind === "raw" !== (info.kdf === "hkdf")) {
109
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("the key material does not match the manifest", info.id);
110
+ }
111
+ const iterations = resolveIterations(info.id, material, info.iterations);
112
+ versions.set(info.id, {
113
+ id: info.id,
114
+ state: info.state,
115
+ createdAt: info.createdAt,
116
+ kdf: info.kdf,
117
+ salt,
118
+ iterations,
119
+ base: await importBase(crypto, info.id, material, salt, iterations)
120
+ });
121
+ }
122
+ const [unlisted] = supplied.keys();
123
+ if (unlisted !== void 0) {
124
+ throw new chunkWLJN7GIS_cjs.KeyManagementError(
125
+ "the manifest does not list this key version; add new versions with rotate()",
126
+ unlisted
127
+ );
128
+ }
129
+ active = manifest.activeKeyId;
130
+ const expected = chunkQYD4F6T7_cjs.fromBase64Url(typeof manifest.mac === "string" ? manifest.mac : "");
131
+ const genuine = expected !== void 0 && await crypto.subtle.verify("HMAC", await macKey(), expected, chunkQYD4F6T7_cjs.utf8(macInput()));
132
+ if (!genuine) {
133
+ throw new chunkWLJN7GIS_cjs.KeyManagementError(
134
+ "the manifest failed authentication: it was edited, or the key material is not the one it was created with"
135
+ );
136
+ }
137
+ mac = manifest.mac;
138
+ }
139
+ function macKey() {
140
+ return derive(activeKeyId(), "manifest-mac");
141
+ }
142
+ function macInput() {
143
+ return JSON.stringify([
144
+ 1,
145
+ namespace,
146
+ activeKeyId(),
147
+ [...versions.values()].map((version) => [
148
+ version.id,
149
+ version.state === "active",
150
+ version.createdAt,
151
+ version.kdf,
152
+ chunkQYD4F6T7_cjs.toBase64Url(version.salt),
153
+ version.iterations ?? null
154
+ ])
155
+ ]);
156
+ }
157
+ async function sign() {
158
+ const signature = await crypto.subtle.sign("HMAC", await macKey(), chunkQYD4F6T7_cjs.utf8(macInput()));
159
+ return chunkQYD4F6T7_cjs.toBase64Url(new Uint8Array(signature));
160
+ }
161
+ async function add(id, material) {
162
+ const salt = chunkQYD4F6T7_cjs.randomBytes(crypto, SALT_BYTES);
163
+ const iterations = resolveIterations(id, material);
164
+ const base = await importBase(crypto, id, material, salt, iterations);
165
+ const previous = active === void 0 ? void 0 : versions.get(active);
166
+ if (previous !== void 0) previous.state = "retired";
167
+ versions.set(id, {
168
+ id,
169
+ state: "active",
170
+ createdAt: now(),
171
+ kdf: material.kind === "raw" ? "hkdf" : "pbkdf2-hkdf",
172
+ salt,
173
+ iterations,
174
+ base
175
+ });
176
+ active = id;
177
+ }
178
+ function activeKeyId() {
179
+ if (active === void 0) throw new chunkWLJN7GIS_cjs.KeyManagementError("the key ring has no active version");
180
+ return active;
181
+ }
182
+ function describe(version) {
183
+ return Object.freeze({
184
+ id: version.id,
185
+ state: version.state,
186
+ createdAt: version.createdAt,
187
+ kdf: version.kdf,
188
+ salt: chunkQYD4F6T7_cjs.toBase64Url(version.salt),
189
+ ...version.iterations !== void 0 ? { iterations: version.iterations } : {}
190
+ });
191
+ }
192
+ function derive(keyId, purpose) {
193
+ const version = versions.get(keyId);
194
+ if (version === void 0) {
195
+ return Promise.reject(
196
+ new chunkWLJN7GIS_cjs.KeyManagementError("unknown key version", chunkFB56NAAH_cjs.isKeyId(keyId) ? keyId : void 0)
197
+ );
198
+ }
199
+ const base = version.base;
200
+ if (base === void 0) {
201
+ return Promise.reject(new chunkWLJN7GIS_cjs.KeyManagementError("the key version has been destroyed", keyId));
202
+ }
203
+ const cacheKey = `${keyId}/${purpose}`;
204
+ let key = derived.get(cacheKey);
205
+ if (key === void 0) {
206
+ key = crypto.subtle.deriveKey(
207
+ {
208
+ name: "HKDF",
209
+ hash: "SHA-256",
210
+ salt: version.salt,
211
+ info: chunkQYD4F6T7_cjs.utf8(`anonyma/v1/${purpose}\0${namespace}`)
212
+ },
213
+ base,
214
+ purpose === "token-seal" ? { name: "AES-GCM", length: 256 } : { name: "HMAC", hash: "SHA-256", length: 256 },
215
+ false,
216
+ purpose === "token-seal" ? ["encrypt", "decrypt"] : ["sign", "verify"]
217
+ );
218
+ derived.set(cacheKey, key);
219
+ }
220
+ return key;
221
+ }
222
+ const reserved = /* @__PURE__ */ new Set();
223
+ let rotations = Promise.resolve();
224
+ function rotate(version) {
225
+ const { id, material } = version;
226
+ if (!chunkFB56NAAH_cjs.isKeyId(id)) {
227
+ return Promise.reject(
228
+ new chunkWLJN7GIS_cjs.KeyManagementError("key identifiers are 1-16 characters of A-Z, a-z and 0-9")
229
+ );
230
+ }
231
+ if (versions.has(id) || reserved.has(id)) {
232
+ return Promise.reject(new chunkWLJN7GIS_cjs.KeyManagementError("the identifier is already in use", id));
233
+ }
234
+ reserved.add(id);
235
+ const run = rotations.then(async () => {
236
+ try {
237
+ await add(id, material);
238
+ mac = await sign();
239
+ } finally {
240
+ reserved.delete(id);
241
+ }
242
+ });
243
+ rotations = run.catch(() => void 0);
244
+ return run;
245
+ }
246
+ function destroy(keyId) {
247
+ const version = versions.get(keyId);
248
+ if (version === void 0) {
249
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("unknown key version", chunkFB56NAAH_cjs.isKeyId(keyId) ? keyId : void 0);
250
+ }
251
+ if (version.state === "active") {
252
+ throw new chunkWLJN7GIS_cjs.KeyManagementError(
253
+ "the active key version cannot be destroyed; rotate first",
254
+ keyId
255
+ );
256
+ }
257
+ version.state = "destroyed";
258
+ version.base = void 0;
259
+ for (const cacheKey of [...derived.keys()]) {
260
+ if (cacheKey.startsWith(`${keyId}/`)) derived.delete(cacheKey);
261
+ }
262
+ }
263
+ return Object.freeze({
264
+ activeKeyId,
265
+ manifest: () => Object.freeze({
266
+ v: 1,
267
+ namespace,
268
+ activeKeyId: activeKeyId(),
269
+ versions: Object.freeze([...versions.values()].map(describe)),
270
+ mac
271
+ }),
272
+ deriveKey: (keyId, purpose) => derive(keyId, purpose),
273
+ rotate,
274
+ destroy
275
+ });
276
+ }
277
+ function readManifest(manifest, namespace) {
278
+ const malformed = new chunkWLJN7GIS_cjs.KeyManagementError("the manifest is malformed");
279
+ const candidate = manifest;
280
+ if (typeof manifest !== "object" || candidate["v"] !== 1 || !Array.isArray(candidate["versions"])) {
281
+ throw malformed;
282
+ }
283
+ if (candidate["namespace"] !== namespace) {
284
+ throw new chunkWLJN7GIS_cjs.KeyManagementError("the manifest belongs to a different namespace");
285
+ }
286
+ const seen = /* @__PURE__ */ new Set();
287
+ let activeCount = 0;
288
+ for (const entry of candidate["versions"]) {
289
+ if (typeof entry !== "object" || entry === null) throw malformed;
290
+ const info = entry;
291
+ const { id, state, createdAt, kdf, salt, iterations } = info;
292
+ const saltBytes = typeof salt === "string" ? chunkQYD4F6T7_cjs.fromBase64Url(salt) : void 0;
293
+ if (!chunkFB56NAAH_cjs.isKeyId(id) || seen.has(id) || !STATES.has(state) || typeof createdAt !== "number" || !Number.isFinite(createdAt) || kdf !== "hkdf" && kdf !== "pbkdf2-hkdf" || saltBytes === void 0 || saltBytes.length < MIN_SALT_BYTES || (kdf === "hkdf" ? iterations !== void 0 : typeof iterations !== "number")) {
294
+ throw malformed;
295
+ }
296
+ seen.add(id);
297
+ if (state === "active") {
298
+ activeCount++;
299
+ if (id !== candidate["activeKeyId"]) throw malformed;
300
+ }
301
+ }
302
+ if (activeCount !== 1) throw malformed;
303
+ return manifest.versions;
304
+ }
305
+
306
+ // src/vault/seal.ts
307
+ var IV_BYTES = 12;
308
+ var TAG_BYTES = 16;
309
+ async function macOf(crypto, key, category, value) {
310
+ const input = chunkQYD4F6T7_cjs.concatBytes(chunkQYD4F6T7_cjs.encodeText(category), new Uint8Array(1), chunkQYD4F6T7_cjs.encodeText(value));
311
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, input));
312
+ }
313
+ async function seal(crypto, key, value, additionalData, iv = chunkQYD4F6T7_cjs.randomBytes(crypto, IV_BYTES)) {
314
+ const sealed = await crypto.subtle.encrypt(
315
+ { name: "AES-GCM", iv, additionalData: chunkQYD4F6T7_cjs.utf8(additionalData), tagLength: TAG_BYTES * 8 },
316
+ key,
317
+ chunkQYD4F6T7_cjs.encodeText(value)
318
+ );
319
+ return chunkQYD4F6T7_cjs.toBase64Url(chunkQYD4F6T7_cjs.concatBytes(iv, new Uint8Array(sealed)));
320
+ }
321
+ async function unseal(crypto, key, sealed, additionalData) {
322
+ const bytes = chunkQYD4F6T7_cjs.fromBase64Url(sealed);
323
+ if (bytes === void 0 || bytes.length < IV_BYTES + TAG_BYTES) return void 0;
324
+ try {
325
+ const plain = await crypto.subtle.decrypt(
326
+ {
327
+ name: "AES-GCM",
328
+ iv: bytes.subarray(0, IV_BYTES),
329
+ additionalData: chunkQYD4F6T7_cjs.utf8(additionalData),
330
+ tagLength: TAG_BYTES * 8
331
+ },
332
+ key,
333
+ bytes.subarray(IV_BYTES)
334
+ );
335
+ return chunkQYD4F6T7_cjs.decodeText(new Uint8Array(plain));
336
+ } catch {
337
+ return void 0;
338
+ }
339
+ }
340
+
341
+ // src/vault/keyed.ts
342
+ var MAX_ATTEMPTS = 5;
343
+ async function subjectTagOf(keyring, keyId, subject) {
344
+ const key = await keyring.deriveKey(keyId, "subject-tag");
345
+ return chunkQYD4F6T7_cjs.toBase64Url(await macOf(await chunkTW7PM3UJ_cjs.webCrypto(), key, "subject", subject));
346
+ }
347
+ function subjectContext(token) {
348
+ return `${token}\0subject`;
349
+ }
350
+ function valueContext(record) {
351
+ return `${record.token}\0${String(record.createdAt)}\0${String(record.expiresAt ?? "")}`;
352
+ }
353
+ function createKeyedTokenizer(options) {
354
+ const { keyring, vault, idKeyId, idLength = 12, ttlMs } = options;
355
+ const now = options.now ?? Date.now;
356
+ if (!Number.isInteger(idLength) || idLength < 8 || idLength > 26) {
357
+ throw new chunkWLJN7GIS_cjs.ValidationError("idLength", "must be an integer between 8 and 26");
358
+ }
359
+ if (idKeyId !== void 0 && !chunkFB56NAAH_cjs.isKeyId(idKeyId)) {
360
+ throw new chunkWLJN7GIS_cjs.ValidationError("idKeyId", "is not a valid key version identifier");
361
+ }
362
+ if (ttlMs !== void 0 && !(ttlMs > 0)) {
363
+ throw new chunkWLJN7GIS_cjs.ValidationError("ttlMs", "must be a positive number");
364
+ }
365
+ const prefixOf = chunkFB56NAAH_cjs.prefixResolver(options.prefixes);
366
+ const tokenSource = `\\[${chunkFB56NAAH_cjs.PREFIX_SOURCE}_${chunkFB56NAAH_cjs.KEY_ID_SOURCE}_[0-9A-HJKMNP-TV-Z]{${String(idLength)}}\\]`;
367
+ const wholeToken = new RegExp(`^${tokenSource}$`);
368
+ async function tokenize(value, context) {
369
+ if (typeof value !== "string") throw new chunkWLJN7GIS_cjs.ValidationError("value", "must be a string");
370
+ const crypto = await chunkTW7PM3UJ_cjs.webCrypto();
371
+ const keyId = idKeyId ?? keyring.activeKeyId();
372
+ const mac = await macOf(
373
+ crypto,
374
+ await keyring.deriveKey(keyId, "token-id"),
375
+ context.category,
376
+ value
377
+ );
378
+ const token = `[${prefixOf(context.category)}_${keyId}_${chunkQYD4F6T7_cjs.toBase32(mac, idLength)}]`;
379
+ if (vault === void 0) return token;
380
+ const check = chunkQYD4F6T7_cjs.toBase64Url(mac);
381
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
382
+ let existing = await vault.get(token);
383
+ if (existing === void 0) {
384
+ const record = await create(crypto, token, check, value, context);
385
+ existing = await vault.putIfAbsent(record);
386
+ if (existing.sealed === record.sealed && existing.check === check) return token;
387
+ }
388
+ const same = await holdsValue(crypto, existing, check, value);
389
+ if (same === void 0 || isExpired(existing)) {
390
+ const record = await create(crypto, token, check, value, context);
391
+ if (await vault.replace(record, existing)) return token;
392
+ continue;
393
+ }
394
+ if (!same) throw new chunkWLJN7GIS_cjs.TokenVaultError("token identifier collision; increase idLength");
395
+ if (context.subject === void 0) return token;
396
+ const tagged = await withSubject(crypto, existing, context.subject);
397
+ if (tagged === existing || await vault.replace(tagged, existing)) return token;
398
+ }
399
+ throw new chunkWLJN7GIS_cjs.TokenVaultError("the vault record kept changing; try again");
400
+ }
401
+ function isExpired(record) {
402
+ return record.expiresAt !== void 0 && record.expiresAt <= now();
403
+ }
404
+ async function create(crypto, token, check, value, context) {
405
+ const keyId = keyring.activeKeyId();
406
+ const sealKey = await keyring.deriveKey(keyId, "token-seal");
407
+ const createdAt = now();
408
+ const lifetime = {
409
+ token,
410
+ createdAt,
411
+ ...ttlMs !== void 0 ? { expiresAt: createdAt + ttlMs } : {}
412
+ };
413
+ return {
414
+ ...lifetime,
415
+ category: context.category,
416
+ keyId,
417
+ sealed: await seal(crypto, sealKey, value, valueContext(lifetime)),
418
+ check,
419
+ ...context.subject !== void 0 ? { subjects: [await subjectReference(crypto, token, keyId, context.subject)] } : {}
420
+ };
421
+ }
422
+ async function subjectReference(crypto, token, keyId, subject) {
423
+ const sealKey = await keyring.deriveKey(keyId, "token-seal");
424
+ return {
425
+ tag: await subjectTagOf(keyring, keyId, subject),
426
+ sealed: await seal(crypto, sealKey, subject, subjectContext(token))
427
+ };
428
+ }
429
+ async function holdsValue(crypto, record, check, value) {
430
+ if (record.check !== void 0) {
431
+ return record.check === check;
432
+ }
433
+ try {
434
+ const key = await keyring.deriveKey(record.keyId, "token-seal");
435
+ return await unseal(crypto, key, record.sealed, valueContext(record)) === value;
436
+ } catch {
437
+ return void 0;
438
+ }
439
+ }
440
+ async function withSubject(crypto, record, subject) {
441
+ const subjects = record.subjects ?? [];
442
+ const tag = await subjectTagOf(keyring, record.keyId, subject);
443
+ if (subjects.some((entry) => entry.tag === tag)) return record;
444
+ const reference = await subjectReference(crypto, record.token, record.keyId, subject);
445
+ return { ...record, subjects: [...subjects, reference] };
446
+ }
447
+ async function detokenize(token) {
448
+ if (vault === void 0 || typeof token !== "string" || !wholeToken.test(token))
449
+ return void 0;
450
+ const record = await vault.get(token);
451
+ if (record === void 0 || isExpired(record)) return void 0;
452
+ let key;
453
+ try {
454
+ key = await keyring.deriveKey(record.keyId, "token-seal");
455
+ } catch {
456
+ return void 0;
457
+ }
458
+ return unseal(await chunkTW7PM3UJ_cjs.webCrypto(), key, record.sealed, valueContext(record));
459
+ }
460
+ async function forgetToken(token) {
461
+ return vault === void 0 ? false : vault.delete(token);
462
+ }
463
+ async function forgetSubject(subject) {
464
+ if (typeof subject !== "string" || subject.length === 0) {
465
+ throw new chunkWLJN7GIS_cjs.ValidationError("subject", "must be a non-empty string");
466
+ }
467
+ const tags = /* @__PURE__ */ new Map();
468
+ for (const version of keyring.manifest().versions) {
469
+ if (version.state !== "destroyed") {
470
+ tags.set(version.id, await subjectTagOf(keyring, version.id, subject));
471
+ }
472
+ }
473
+ const isSubject = (record) => {
474
+ const tag = tags.get(record.keyId);
475
+ return tag !== void 0 && (record.subjects ?? []).some((entry) => entry.tag === tag);
476
+ };
477
+ let erased = 0;
478
+ const keyIds = /* @__PURE__ */ new Set();
479
+ if (vault !== void 0) {
480
+ const doomed = [];
481
+ for await (const record of vault.list()) {
482
+ if (isSubject(record)) doomed.push(record);
483
+ }
484
+ for (const record of doomed) {
485
+ if (await vault.delete(record.token)) {
486
+ erased++;
487
+ keyIds.add(record.keyId);
488
+ }
489
+ }
490
+ }
491
+ const activeTag = tags.get(keyring.activeKeyId());
492
+ return Object.freeze({
493
+ method: "vault-delete",
494
+ erased,
495
+ keyIds: Object.freeze([...keyIds].sort()),
496
+ ...activeTag !== void 0 ? { subjectTag: activeTag } : {},
497
+ completedAt: now()
498
+ });
499
+ }
500
+ return Object.freeze({
501
+ scheme: "keyed",
502
+ reversible: vault !== void 0,
503
+ tokenPattern: new RegExp(tokenSource, "g"),
504
+ partialTokenPattern: /\[[A-Za-z0-9_]{0,80}$/,
505
+ maxTokenLength: 40 + 1 + 16 + 1 + idLength + 2,
506
+ tokenize,
507
+ detokenize,
508
+ forgetToken,
509
+ forgetSubject
510
+ });
511
+ }
512
+
513
+ // src/vault/sealed.ts
514
+ function createSealedTokenizer(options) {
515
+ const { keyring, maxValueBytes = 256 } = options;
516
+ if (!Number.isInteger(maxValueBytes) || maxValueBytes < 1) {
517
+ throw new chunkWLJN7GIS_cjs.ValidationError("maxValueBytes", "must be a positive integer");
518
+ }
519
+ const prefixOf = chunkFB56NAAH_cjs.prefixResolver(options.prefixes);
520
+ const tokenSource = `\\[(${chunkFB56NAAH_cjs.PREFIX_SOURCE})_(${chunkFB56NAAH_cjs.KEY_ID_SOURCE})\\.([A-Za-z0-9_-]{38,})\\]`;
521
+ const wholeToken = new RegExp(`^${tokenSource}$`);
522
+ async function tokenize(value, context) {
523
+ if (typeof value !== "string") throw new chunkWLJN7GIS_cjs.ValidationError("value", "must be a string");
524
+ if (chunkQYD4F6T7_cjs.encodeText(value).length > maxValueBytes) {
525
+ throw new chunkWLJN7GIS_cjs.ValidationError("value", "is longer than maxValueBytes and cannot be sealed");
526
+ }
527
+ const crypto = await chunkTW7PM3UJ_cjs.webCrypto();
528
+ const keyId = keyring.activeKeyId();
529
+ const header = `${prefixOf(context.category)}_${keyId}`;
530
+ const mac = await macOf(crypto, await keyring.deriveKey(keyId, "token-id"), header, value);
531
+ const sealed = await seal(
532
+ crypto,
533
+ await keyring.deriveKey(keyId, "token-seal"),
534
+ value,
535
+ header,
536
+ mac.slice(0, 12)
537
+ );
538
+ return `[${header}.${sealed}]`;
539
+ }
540
+ async function detokenize(token) {
541
+ if (typeof token !== "string") return void 0;
542
+ const match = wholeToken.exec(token);
543
+ const prefix = match?.[1];
544
+ const keyId = match?.[2];
545
+ const sealed = match?.[3];
546
+ if (prefix === void 0 || keyId === void 0 || sealed === void 0) return void 0;
547
+ let key;
548
+ try {
549
+ key = await keyring.deriveKey(keyId, "token-seal");
550
+ } catch {
551
+ return void 0;
552
+ }
553
+ return unseal(await chunkTW7PM3UJ_cjs.webCrypto(), key, sealed, `${prefix}_${keyId}`);
554
+ }
555
+ return Object.freeze({
556
+ scheme: "sealed",
557
+ reversible: true,
558
+ tokenPattern: new RegExp(tokenSource.replace(/\((?!\?)/g, "(?:"), "g"),
559
+ partialTokenPattern: /\[[A-Za-z0-9_.-]*$/,
560
+ // prefix + "_" + key id + "." + base64url(12-byte nonce, value, 16-byte tag) + brackets
561
+ maxTokenLength: 2 + 40 + 1 + 16 + 1 + Math.ceil((12 + maxValueBytes + 16) * 4 / 3),
562
+ tokenize,
563
+ detokenize
564
+ });
565
+ }
566
+
567
+ // src/vault/memory-vault.ts
568
+ function sameRecord(a, b) {
569
+ if (a.keyId !== b.keyId || a.sealed !== b.sealed) return false;
570
+ const left = a.subjects ?? [];
571
+ const right = b.subjects ?? [];
572
+ return left.length === right.length && left.every((subject, index) => subject.tag === right[index]?.tag);
573
+ }
574
+ function createMemoryVault(records = []) {
575
+ const store = /* @__PURE__ */ new Map();
576
+ for (const record of records) store.set(record.token, Object.freeze({ ...record }));
577
+ return Object.freeze({
578
+ get: (token) => store.get(token),
579
+ putIfAbsent(record) {
580
+ const existing = store.get(record.token);
581
+ if (existing !== void 0) return existing;
582
+ const stored = Object.freeze({ ...record });
583
+ store.set(record.token, stored);
584
+ return stored;
585
+ },
586
+ replace(record, expected) {
587
+ const stored = store.get(record.token);
588
+ if (stored === void 0 || !sameRecord(stored, expected)) return false;
589
+ store.set(record.token, Object.freeze({ ...record }));
590
+ return true;
591
+ },
592
+ delete: (token) => store.delete(token),
593
+ list: () => [...store.values()],
594
+ size: () => store.size
595
+ });
596
+ }
597
+
598
+ // src/vault/rotation.ts
599
+ async function rewrapVault(vault, keyring) {
600
+ const crypto = await chunkTW7PM3UJ_cjs.webCrypto();
601
+ const active = keyring.activeKeyId();
602
+ const activeKey = await keyring.deriveKey(active, "token-seal");
603
+ const stale = [];
604
+ let current = 0;
605
+ for await (const record of vault.list()) {
606
+ if (record.keyId === active) current++;
607
+ else stale.push(record);
608
+ }
609
+ let rewrapped = 0;
610
+ let unrecoverable = 0;
611
+ let skipped = 0;
612
+ for (const record of stale) {
613
+ let value;
614
+ const subjects = [];
615
+ try {
616
+ const oldKey = await keyring.deriveKey(record.keyId, "token-seal");
617
+ value = await unseal(crypto, oldKey, record.sealed, valueContext(record));
618
+ for (const entry of record.subjects ?? []) {
619
+ const subject = await unseal(crypto, oldKey, entry.sealed, subjectContext(record.token));
620
+ if (subject === void 0) value = void 0;
621
+ else subjects.push(subject);
622
+ }
623
+ } catch {
624
+ value = void 0;
625
+ }
626
+ if (value === void 0) {
627
+ unrecoverable++;
628
+ continue;
629
+ }
630
+ const references = [];
631
+ for (const subject of subjects) {
632
+ references.push({
633
+ tag: await subjectTagOf(keyring, active, subject),
634
+ sealed: await seal(crypto, activeKey, subject, subjectContext(record.token))
635
+ });
636
+ }
637
+ const next = {
638
+ ...record,
639
+ keyId: active,
640
+ sealed: await seal(crypto, activeKey, value, valueContext(record)),
641
+ ...references.length > 0 ? { subjects: references } : {}
642
+ };
643
+ if (await vault.replace(next, record)) rewrapped++;
644
+ else skipped++;
645
+ }
646
+ return { rewrapped, current, unrecoverable, skipped };
647
+ }
648
+ async function shredKey(keyring, keyId, vault, now = Date.now) {
649
+ keyring.destroy(keyId);
650
+ let erased = 0;
651
+ if (vault !== void 0) {
652
+ const doomed = [];
653
+ for await (const record of vault.list()) {
654
+ if (record.keyId === keyId) doomed.push(record.token);
655
+ }
656
+ for (const token of doomed) {
657
+ if (await vault.delete(token)) erased++;
658
+ }
659
+ }
660
+ return Object.freeze({
661
+ method: "crypto-shred",
662
+ erased,
663
+ keyIds: Object.freeze([keyId]),
664
+ completedAt: now()
665
+ });
666
+ }
667
+
668
+ Object.defineProperty(exports, "restoreTokens", {
669
+ enumerable: true,
670
+ get: function () { return chunk2NNMJ55L_cjs.restoreTokens; }
671
+ });
672
+ Object.defineProperty(exports, "tokenizeWith", {
673
+ enumerable: true,
674
+ get: function () { return chunk2NNMJ55L_cjs.tokenizeWith; }
675
+ });
676
+ Object.defineProperty(exports, "createSessionTokenizer", {
677
+ enumerable: true,
678
+ get: function () { return chunkFB56NAAH_cjs.createSessionTokenizer; }
679
+ });
680
+ exports.createKeyRing = createKeyRing;
681
+ exports.createKeyedTokenizer = createKeyedTokenizer;
682
+ exports.createMemoryVault = createMemoryVault;
683
+ exports.createSealedTokenizer = createSealedTokenizer;
684
+ exports.generateKeyMaterial = generateKeyMaterial;
685
+ exports.rewrapVault = rewrapVault;
686
+ exports.shredKey = shredKey;
687
+ //# sourceMappingURL=index.cjs.map
688
+ //# sourceMappingURL=index.cjs.map