@anizoptera/uuid-slug 0.3.0 → 0.4.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 (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1052 -261
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +14 -9
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
package/dist/schema.js DELETED
@@ -1,216 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidSlugError } from "./errors.js";
4
- import { halfSipHash } from "./siphash.js";
5
- import { feistel16 } from "./feistel.js";
6
- import { yieldToHost } from "./yield.js";
7
- //#region src/schema.ts
8
- /** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
9
- const SEED_MIN_BYTES = 16;
10
- /** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
11
- const MAX_KEY_ITERATIONS = 1 << 24;
12
- /**
13
- * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
14
- * "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
15
- *
16
- * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
17
- * seed different round keys and make every masked slug ever issued undecodable.
18
- */
19
- const CHAIN_A_KEY1 = 1097297011;
20
- const CHAIN_B_KEY1 = 1114074227;
21
- const CHAIN_KEY0 = 1684632949;
22
- function seedBytes(seed) {
23
- if (typeof seed !== "string") return new Uint8Array(seed);
24
- return new TextEncoder().encode(seed);
25
- }
26
- /** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
27
- function seedWords(seed) {
28
- const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
29
- writeSeedWords(seed, words);
30
- return words;
31
- }
32
- /** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
33
- function writeSeedWords(seed, words, offset = 0, start = 0, end = seed.length) {
34
- for (let index = start; index < end; index += 1) {
35
- const absolute = offset + index;
36
- words[absolute >>> 2] = words[absolute >>> 2] | seed[index] << (absolute & 3) * 8;
37
- }
38
- }
39
- /**
40
- * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
41
- * at construction, never per id. The count changes key material and must remain stable for
42
- * issued slugs; retain the old count with its seed when rotating schemas.
43
- */
44
- function chain(key0, key1, words, length, iterations) {
45
- const out = /* @__PURE__ */ new Int32Array(2);
46
- halfSipHash(key0, key1, words, length, out);
47
- for (let i = 1; i < iterations; i += 1) halfSipHash(out[0], out[1], words, length, out);
48
- return out;
49
- }
50
- /**
51
- * Derive each round key by XORing outputs from two fixed derivation chains. Their combined
52
- * state is 128 bits; that representation does not establish 128-bit security. Chain constants,
53
- * word indices and byte order are frozen by the issued wire format.
54
- */
55
- function derivedKeys(seed, iterations) {
56
- const words = seedWords(seed);
57
- return roundKeys(chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations), chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations));
58
- }
59
- /** The same final key expansion follows synchronous and cooperative derivation. */
60
- function roundKeys(chainA, chainB) {
61
- const keys = /* @__PURE__ */ new Int32Array(8);
62
- const index = /* @__PURE__ */ new Int32Array(1);
63
- const fromA = /* @__PURE__ */ new Int32Array(2);
64
- const fromB = /* @__PURE__ */ new Int32Array(2);
65
- for (let word = 0; word < 8; word += 2) {
66
- index[0] = word;
67
- halfSipHash(chainA[0], chainA[1], index, 4, fromA);
68
- halfSipHash(chainB[0], chainB[1], index, 4, fromB);
69
- keys[word] = fromA[0] ^ fromB[0];
70
- keys[word + 1] = fromA[1] ^ fromB[1];
71
- }
72
- return keys;
73
- }
74
- function feistelSchema(id, seed, iterations) {
75
- return schemaFromKeys(id, derivedKeys(seed, iterations));
76
- }
77
- function schemaFromKeys(id, keys) {
78
- return {
79
- id,
80
- mix(input, output, forward) {
81
- feistel16(input, 0, keys, forward, output, 0);
82
- }
83
- };
84
- }
85
- function createMaskSchema(options) {
86
- const seed = seedBytes(options.seed);
87
- const short = invalidSeedLength(seed.length);
88
- if (short) return short;
89
- const iterations = options.keyIterations ?? 1;
90
- const invalid = invalidIterations(iterations);
91
- if (invalid) return invalid;
92
- return feistelSchema(options.id ?? "seeded", seed, iterations);
93
- }
94
- function invalidSeedLength(length) {
95
- if (length < SEED_MIN_BYTES) return new UuidSlugError("invalid_mask_schema", `Mask seed must be at least ${SEED_MIN_BYTES} bytes, got ${length}. Generate one with \`openssl rand -base64 32\` rather than choosing it; a guessable seed hides nothing however long it is.`);
96
- }
97
- function invalidIterations(iterations) {
98
- if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS) return new UuidSlugError("invalid_mask_schema", `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`);
99
- }
100
- /** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
101
- const CHUNK_BYTES = 4096;
102
- function* cooperativeChain(key0, key1, words, length, iterations) {
103
- const out = /* @__PURE__ */ new Int32Array(2);
104
- out[0] = key0;
105
- out[1] = key1;
106
- const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
107
- let sinceCheckpoint = 0;
108
- for (let i = 0; i < iterations; i += 1) {
109
- let continuation;
110
- do {
111
- continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
112
- if (continuation) yield;
113
- } while (continuation);
114
- sinceCheckpoint += 1;
115
- if (sinceCheckpoint >= hashesPerChunk) {
116
- sinceCheckpoint = 0;
117
- yield;
118
- }
119
- }
120
- return out;
121
- }
122
- function* cooperativeKeys(seed, iterations) {
123
- const chunks = [];
124
- let length = 0;
125
- if (typeof seed === "string") {
126
- const encoder = new TextEncoder();
127
- for (let start = 0; start < seed.length;) {
128
- let end = Math.min(seed.length, start + CHUNK_BYTES);
129
- const last = seed.charCodeAt(end - 1);
130
- const next = seed.charCodeAt(end);
131
- if (end < seed.length && last >= 55296 && last <= 56319 && next >= 56320 && next <= 57343) end -= 1;
132
- const bytes = encoder.encode(seed.slice(start, end));
133
- chunks.push(bytes);
134
- length += bytes.length;
135
- start = end;
136
- yield;
137
- }
138
- } else {
139
- chunks.push(seed);
140
- length = seed.length;
141
- }
142
- const short = invalidSeedLength(length);
143
- if (short) return short;
144
- const words = new Int32Array(Math.ceil(length / 4) + 1);
145
- let offset = 0;
146
- for (const bytes of chunks) {
147
- for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
148
- writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
149
- yield;
150
- }
151
- offset += bytes.length;
152
- }
153
- chunks.length = 0;
154
- return roundKeys(yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations), yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations));
155
- }
156
- /**
157
- * Derive the same schema while allowing other host tasks to run. Options and byte contents are
158
- * captured before suspension; cancellation returns an `aborted` error with the signal's reason
159
- * as its cause. Checkpoints stop computation rather than racing a still-running derivation.
160
- *
161
- * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
162
- * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
163
- * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
164
- */
165
- async function createMaskSchemaAsync(options) {
166
- try {
167
- const { signal } = options;
168
- const aborted = () => new UuidSlugError("aborted", "Mask schema construction was aborted.", { cause: signal?.reason });
169
- if (signal?.aborted) return aborted();
170
- const { seed: input, keyIterations = 1, id = "seeded" } = options;
171
- const invalid = invalidIterations(keyIterations);
172
- if (invalid) return invalid;
173
- const steps = cooperativeKeys(typeof input === "string" ? input : new Uint8Array(input), keyIterations);
174
- let deadline = performance.now() + 2;
175
- while (true) {
176
- if (signal?.aborted) {
177
- const failure = aborted();
178
- steps.return(failure);
179
- return failure;
180
- }
181
- const step = steps.next();
182
- if (step.done) return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);
183
- if (performance.now() >= deadline) {
184
- await yieldToHost();
185
- deadline = performance.now() + 2;
186
- }
187
- }
188
- } catch (cause) {
189
- return new UuidSlugError("invalid_mask_schema", "Mask schema construction failed.", { cause });
190
- }
191
- }
192
- /**
193
- * Refuse schemas that cannot undo these representative blocks. The reverse call must invert
194
- * the forward call; the same function need not be an involution. Finite probes are not a proof
195
- * over the full domain. Preserve each original input separately so a mutating callback cannot
196
- * rewrite the witness and make a destructive transformation appear reversible.
197
- */
198
- function verifyInvertible(schema) {
199
- const mixed = /* @__PURE__ */ new Uint8Array(16);
200
- const restored = /* @__PURE__ */ new Uint8Array(16);
201
- for (const probe of [/* @__PURE__ */ new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {
202
- try {
203
- schema.mix(probe.slice(), mixed, true);
204
- schema.mix(mixed, restored, false);
205
- } catch (cause) {
206
- return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" failed its invertibility check.`, { cause });
207
- }
208
- if (restored.some((byte, i) => byte !== probe[i])) return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" does not reverse its own mixing step.`);
209
- }
210
- return schema;
211
- }
212
- const DEFAULT_MASK_SCHEMA = feistelSchema("default", seedBytes("anizoptera.uuid-slug.default-mask.v1"), 1);
213
- //#endregion
214
- export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync, verifyInvertible };
215
-
216
- //# sourceMappingURL=schema.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { UuidSlugError } from \"./errors\";\nimport { FEISTEL_KEY_WORDS, feistel16 } from \"./feistel\";\nimport { halfSipHash } from \"./siphash\";\nimport type { HashContinuation } from \"./siphash\";\nimport { yieldToHost } from \"./yield\";\nimport type { AsyncMaskSchemaOptions, MaskSchema, MaskSchemaOptions } from \"./types\";\n\n/** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */\nconst SEED_MIN_BYTES = 16;\n\n/** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */\nconst MAX_KEY_ITERATIONS = 1 << 24;\n\n/**\n * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of\n * \"uuid\" with \"slgA\" and \"slgB\", so a reader can check they conceal no chosen structure.\n *\n * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every\n * seed different round keys and make every masked slug ever issued undecodable.\n */\nconst CHAIN_A_KEY1 = 0x41676c73;\nconst CHAIN_B_KEY1 = 0x42676c73;\nconst CHAIN_KEY0 = 0x64697575;\n\nfunction seedBytes(seed: string | Uint8Array) {\n if (typeof seed !== \"string\") return new Uint8Array(seed);\n return new TextEncoder().encode(seed);\n}\n\n/** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */\nfunction seedWords(seed: Uint8Array) {\n const words = new Int32Array(Math.ceil(seed.length / 4) + 1);\n writeSeedWords(seed, words);\n return words;\n}\n\n/** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */\nfunction writeSeedWords(\n seed: Uint8Array,\n words: Int32Array,\n offset = 0,\n start = 0,\n end = seed.length,\n) {\n for (let index = start; index < end; index += 1) {\n const absolute = offset + index;\n words[absolute >>> 2] =\n (words[absolute >>> 2] as number) | ((seed[index] as number) << ((absolute & 3) * 8));\n }\n}\n\n/**\n * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid\n * at construction, never per id. The count changes key material and must remain stable for\n * issued slugs; retain the old count with its seed when rotating schemas.\n */\nfunction chain(key0: number, key1: number, words: Int32Array, length: number, iterations: number) {\n const out = new Int32Array(2);\n halfSipHash(key0, key1, words, length, out);\n for (let i = 1; i < iterations; i += 1)\n halfSipHash(out[0] as number, out[1] as number, words, length, out);\n return out;\n}\n\n/**\n * Derive each round key by XORing outputs from two fixed derivation chains. Their combined\n * state is 128 bits; that representation does not establish 128-bit security. Chain constants,\n * word indices and byte order are frozen by the issued wire format.\n */\nfunction derivedKeys(seed: Uint8Array, iterations: number) {\n const words = seedWords(seed);\n const chainA = chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations);\n const chainB = chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations);\n return roundKeys(chainA, chainB);\n}\n\n/** The same final key expansion follows synchronous and cooperative derivation. */\nfunction roundKeys(chainA: Int32Array, chainB: Int32Array) {\n const keys = new Int32Array(FEISTEL_KEY_WORDS);\n const index = new Int32Array(1);\n const fromA = new Int32Array(2);\n const fromB = new Int32Array(2);\n for (let word = 0; word < FEISTEL_KEY_WORDS; word += 2) {\n index[0] = word;\n halfSipHash(chainA[0] as number, chainA[1] as number, index, 4, fromA);\n halfSipHash(chainB[0] as number, chainB[1] as number, index, 4, fromB);\n keys[word] = (fromA[0] as number) ^ (fromB[0] as number);\n keys[word + 1] = (fromA[1] as number) ^ (fromB[1] as number);\n }\n return keys;\n}\n\nfunction feistelSchema(id: string, seed: Uint8Array, iterations: number): MaskSchema {\n return schemaFromKeys(id, derivedKeys(seed, iterations));\n}\n\nfunction schemaFromKeys(id: string, keys: Int32Array): MaskSchema {\n return {\n id,\n mix(input, output, forward) {\n feistel16(input, 0, keys, forward, output, 0);\n },\n };\n}\n\nexport function createMaskSchema(options: MaskSchemaOptions): UuidSlugError | MaskSchema {\n const seed = seedBytes(options.seed);\n const short = invalidSeedLength(seed.length);\n if (short) return short;\n const iterations = options.keyIterations ?? 1;\n const invalid = invalidIterations(iterations);\n if (invalid) return invalid;\n return feistelSchema(options.id ?? \"seeded\", seed, iterations);\n}\n\nfunction invalidSeedLength(length: number): UuidSlugError | undefined {\n if (length < SEED_MIN_BYTES)\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask seed must be at least ${SEED_MIN_BYTES} bytes, got ${length}. Generate one with \\`openssl rand -base64 32\\` rather than choosing it; a guessable seed hides nothing however long it is.`,\n );\n return undefined;\n}\n\nfunction invalidIterations(iterations: number): UuidSlugError | undefined {\n if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS)\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`,\n );\n return undefined;\n}\n\n/** Bounded byte work between checkpoints, independent of total seed size or iteration count. */\nconst CHUNK_BYTES = 4096;\n\nfunction* cooperativeChain(\n key0: number,\n key1: number,\n words: Int32Array,\n length: number,\n iterations: number,\n): Generator<void, Int32Array, void> {\n const out = new Int32Array(2);\n out[0] = key0;\n out[1] = key1;\n const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));\n let sinceCheckpoint = 0;\n for (let i = 0; i < iterations; i += 1) {\n let continuation: HashContinuation | undefined;\n do {\n continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);\n if (continuation) yield;\n } while (continuation);\n sinceCheckpoint += 1;\n if (sinceCheckpoint >= hashesPerChunk) {\n sinceCheckpoint = 0;\n yield;\n }\n }\n return out;\n}\n\nfunction* cooperativeKeys(\n seed: string | Uint8Array,\n iterations: number,\n): Generator<void, Int32Array | UuidSlugError, void> {\n // Byte seeds were snapshotted before suspension. Strings are immutable, so encoding can yield.\n const chunks: Uint8Array[] = [];\n let length = 0;\n if (typeof seed === \"string\") {\n const encoder = new TextEncoder();\n for (let start = 0; start < seed.length;) {\n let end = Math.min(seed.length, start + CHUNK_BYTES);\n // Do not split a surrogate pair: encoding either half alone would substitute U+FFFD.\n const last = seed.charCodeAt(end - 1);\n const next = seed.charCodeAt(end);\n if (end < seed.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)\n end -= 1;\n const bytes = encoder.encode(seed.slice(start, end));\n chunks.push(bytes);\n length += bytes.length;\n start = end;\n yield;\n }\n } else {\n chunks.push(seed);\n length = seed.length;\n }\n const short = invalidSeedLength(length);\n if (short) return short;\n const words = new Int32Array(Math.ceil(length / 4) + 1);\n let offset = 0;\n for (const bytes of chunks) {\n for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {\n writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));\n yield;\n }\n offset += bytes.length;\n }\n chunks.length = 0;\n const chainA = yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations);\n const chainB = yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations);\n return roundKeys(chainA, chainB);\n}\n\n/**\n * Derive the same schema while allowing other host tasks to run. Options and byte contents are\n * captured before suspension; cancellation returns an `aborted` error with the signal's reason\n * as its cause. Checkpoints stop computation rather than racing a still-running derivation.\n *\n * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,\n * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations\n * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.\n */\nexport async function createMaskSchemaAsync(\n options: AsyncMaskSchemaOptions,\n): Promise<MaskSchema | UuidSlugError> {\n try {\n const { signal } = options;\n const aborted = () =>\n new UuidSlugError(\"aborted\", \"Mask schema construction was aborted.\", {\n cause: signal?.reason,\n });\n if (signal?.aborted) return aborted();\n const { seed: input, keyIterations = 1, id = \"seeded\" } = options;\n const invalid = invalidIterations(keyIterations);\n if (invalid) return invalid;\n const seed = typeof input === \"string\" ? input : new Uint8Array(input);\n const steps = cooperativeKeys(seed, keyIterations);\n let deadline = performance.now() + 2;\n while (true) {\n if (signal?.aborted) {\n const failure = aborted();\n steps.return(failure);\n return failure;\n }\n const step = steps.next();\n if (step.done)\n return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);\n if (performance.now() >= deadline) {\n // eslint-disable-next-line no-await-in-loop -- each slice must yield before continuing the dependent derivation\n await yieldToHost();\n deadline = performance.now() + 2;\n }\n }\n } catch (cause) {\n return new UuidSlugError(\"invalid_mask_schema\", \"Mask schema construction failed.\", { cause });\n }\n}\n\n/**\n * Refuse schemas that cannot undo these representative blocks. The reverse call must invert\n * the forward call; the same function need not be an involution. Finite probes are not a proof\n * over the full domain. Preserve each original input separately so a mutating callback cannot\n * rewrite the witness and make a destructive transformation appear reversible.\n */\nexport function verifyInvertible(schema: MaskSchema): UuidSlugError | MaskSchema {\n const mixed = new Uint8Array(16);\n const restored = new Uint8Array(16);\n for (const probe of [new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {\n try {\n schema.mix(probe.slice(), mixed, true);\n schema.mix(mixed, restored, false);\n } catch (cause) {\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask schema \"${schema.id}\" failed its invertibility check.`,\n { cause },\n );\n }\n if (restored.some((byte, i) => byte !== probe[i]))\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask schema \"${schema.id}\" does not reverse its own mixing step.`,\n );\n }\n return schema;\n}\n\n/**\n * A PUBLIC key. It ships in the tarball, so every masked slug produced under it is decodable by\n * anyone who installed this package, and it therefore provides none of the obscurity masking\n * exists for.\n *\n * It is exported rather than hidden so that choosing it can be DELIBERATE: a test or demo wanting\n * byte-identical output across machines writes `mask: DEFAULT_MASK_SCHEMA` and says so at the call\n * site. The hazard is the SILENT path — `createUuidSlugCodec()` with no `mask` lands here without\n * the caller writing anything — which is why that fallback and `defaultCodec` both carry the same\n * warning, and why the masked methods are not exported as bare functions.\n */\nconst DEFAULT_SEED = \"anizoptera.uuid-slug.default-mask.v1\";\n\n// Built from `feistelSchema` rather than through `createMaskSchema`, whose failures are a short seed and a\n// bad iteration count — checks on CALLER input that the literals here cannot fail. Routing through it would return\n// `UuidSlugError | MaskSchema` and force a cast that, at module scope, could only ever hide a real Error\n// behind a `MaskSchema` type for every default codec in the process.\nexport const DEFAULT_MASK_SCHEMA: M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AE;CAC/B,MAAM,2BAAW,IAAI,WAAW,EAAE;CAClC,KAAK,MAAM,SAAS,iBAAC,IAAI,WAAW,EAAE,GAAG,WAAW,KAAK,EAAE,QAAQ,GAAG,IAAI,GAAG,MAAM,IAAI,EAAE,CAAC,GAAG;EAC3F,IAAI;GACF,OAAO,IAAI,MAAM,MAAM,GAAG,OAAO,IAAI;GACrC,OAAO,IAAI,OAAO,UAAU,KAAK;EACnC,SAAS,OAAO;GACd,OAAO,IAAI,cACT,uBACA,gBAAgB,OAAO,GAAG,oCAC1B,EAAE,MAAM,CACV;EACF;EACA,IAAI,SAAS,MAAM,MAAM,MAAM,SAAS,MAAM,EAAE,GAC9C,OAAO,IAAI,cACT,uBACA,gBAAgB,OAAO,GAAG,wCAC5B;CACJ;CACA,OAAO;AACT;AAmBA,MAAa,sBAAkC,cAAc,WAAW,UAAU,sCAAY,GAAG,CAAC"}
package/dist/v7.d.ts DELETED
@@ -1,12 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidV7Generator } from "./types.js";
4
- //#region src/v7.d.ts
5
- interface UuidV7GeneratorOptions {
6
- readonly clock?: () => number;
7
- readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => void;
8
- }
9
- declare function createUuidV7Generator(options: UuidV7GeneratorOptions): UuidV7Generator;
10
- //#endregion
11
- export { UuidV7GeneratorOptions, createUuidV7Generator };
12
- //# sourceMappingURL=v7.d.ts.map
package/dist/v7.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"v7.d.ts","names":[],"sources":["../src/v7.ts"],"mappings":";;;;UAOiB;WACN;WACA,aAAa,OAAO,WAAW;;iBAiF1B,sBAAsB,SAAS,yBAAyB"}
package/dist/yield.js DELETED
@@ -1,22 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- //#region src/yield.ts
4
- const host = globalThis;
5
- const immediate = host.setImmediate?.bind(host);
6
- /** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */
7
- function yieldToHost() {
8
- if (immediate) return new Promise((resolve) => immediate(resolve));
9
- return new Promise((resolve) => {
10
- const channel = new MessageChannel();
11
- channel.port1.onmessage = () => {
12
- channel.port1.close();
13
- channel.port2.close();
14
- resolve();
15
- };
16
- channel.port2.postMessage(null);
17
- });
18
- }
19
- //#endregion
20
- export { yieldToHost };
21
-
22
- //# sourceMappingURL=yield.js.map
package/dist/yield.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"yield.js","names":[],"sources":["../src/yield.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nconst host = globalThis as {\n setImmediate?: (callback: () => void) => unknown;\n};\nconst immediate = host.setImmediate?.bind(host);\n\n/** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */\nexport function yieldToHost(): Promise<void> {\n // Prioritized scheduler continuations can overtake queued cancellation tasks in browsers.\n if (immediate) return new Promise((resolve) => immediate(resolve));\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n // eslint-disable-next-line unicorn/prefer-add-event-listener -- this private port has one handler; assignment also starts delivery\n channel.port1.onmessage = () => {\n channel.port1.close();\n channel.port2.close();\n resolve();\n };\n channel.port2.postMessage(null);\n });\n}\n"],"mappings":";;;AAEA,MAAM,OAAO;AAGb,MAAM,YAAY,KAAK,cAAc,KAAK,IAAI;;AAG9C,SAAgB,cAA6B;CAE3C,IAAI,WAAW,OAAO,IAAI,SAAS,YAAY,UAAU,OAAO,CAAC;CACjE,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,UAAU,IAAI,eAAe;EAEnC,QAAQ,MAAM,kBAAkB;GAC9B,QAAQ,MAAM,MAAM;GACpB,QAAQ,MAAM,MAAM;GACpB,QAAQ;EACV;EACA,QAAQ,MAAM,YAAY,IAAI;CAChC,CAAC;AACH"}
package/src/base64url.ts DELETED
@@ -1,41 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- import { BASE64URL, decodeInto, encode, isEncoded } from "./alphabet";
4
- import { UuidSlugError } from "./errors";
5
- import type { Base64UrlString } from "./types";
6
-
7
- export function encodeBase64Url(bytes: Uint8Array): Base64UrlString {
8
- return encode(bytes, BASE64URL);
9
- }
10
-
11
- /**
12
- * Decodes into `out` at `offset` when given one, otherwise into a fresh array.
13
- *
14
- * Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
15
- * `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
16
- * size, with the data at `offset` and no way to learn how many bytes had been written short of
17
- * recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
18
- * makes the length usable and leaves the caller's own buffer reachable, since they own it.
19
- */
20
- export function decodeBase64Url(
21
- value: string,
22
- out?: Uint8Array,
23
- offset = 0,
24
- ): UuidSlugError | Uint8Array {
25
- // Padding is the most common malformed input by far, and the generic "invalid character"
26
- // message sends the reader looking for a typo instead of a stray "=".
27
- if (value.includes("="))
28
- return new UuidSlugError("invalid_base64url", "Base64url value must be unpadded.");
29
- const byteLength = Math.floor((value.length * BASE64URL.bitsPerChar) / 8);
30
- const target = out ?? new Uint8Array(byteLength);
31
- const result = decodeInto(value, BASE64URL, target, offset, byteLength);
32
- if (result instanceof Error) return result;
33
- return target.subarray(offset, offset + byteLength);
34
- }
35
-
36
- export function isBase64Url(value: null | string | undefined): value is Base64UrlString {
37
- // The empty string decodes to zero bytes without error, but an identifier of no characters is
38
- // never what a caller means by "is this a slug"; rejecting it keeps the guard usable as one.
39
- if (!value) return false;
40
- return isEncoded(value, BASE64URL, Math.floor((value.length * BASE64URL.bitsPerChar) / 8));
41
- }
package/src/codec.ts DELETED
@@ -1,320 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- import { runtime } from "#runtime";
4
- import { errorOrThrow, readClock, UuidSlugError } from "./errors";
5
- // A v4 has ONE implementation however it is reached. The keyless module owns it because that is
6
- // the module a consumer who never masks pulls in; importing it here costs a codec consumer nothing
7
- // it was not already paying, whereas the reverse direction would put the codec back on the keyless
8
- // path and undo the whole saving that split exists for.
9
- import { uuidV4Bytes as generateUuidV4Bytes, uuidV4 as generateUuidV4 } from "./keyless";
10
- import { uuidV7BytesToMaskedSlug, decodeMaskedSlug } from "./mask";
11
- import { createMigration } from "./migration";
12
- import { createMaskSchema, DEFAULT_MASK_SCHEMA, verifyInvertible } from "./schema";
13
- import type {
14
- MaskSchema,
15
- PublicUuidV7Slug,
16
- SentinelUuidV7Slug,
17
- UuidSlugCodec,
18
- UuidSlugCodecOptions,
19
- UuidV4Slug,
20
- UuidV7Sentinel,
21
- UuidV7String,
22
- UuidV7Slug,
23
- } from "./types";
24
- import { createRuntimeGenerator } from "./v7";
25
- import {
26
- formatUuidSlug,
27
- hasUuidV7Entropy,
28
- isUuidV7Bytes,
29
- resolveSlugAlphabet,
30
- parseUuid,
31
- formatUuid,
32
- parseUuidSlug,
33
- extractUuidV7Timestamp,
34
- } from "./uuid";
35
- import type { FreshValidationOptions, UuidV7SentinelDefinition } from "./types";
36
-
37
- export const UUID_V7_SENTINEL_DEFINITIONS: readonly UuidV7SentinelDefinition[] = [
38
- {
39
- name: "nil",
40
- uuid: "00000000-0000-7000-8000-000000000000",
41
- },
42
- {
43
- name: "anonymousUser",
44
- uuid: "00000000-0001-7000-8000-000000000000",
45
- },
46
- {
47
- name: "unknownUser",
48
- uuid: "00000000-0002-7000-8000-000000000000",
49
- },
50
- ];
51
-
52
- function schemaFromOption(mask: UuidSlugCodecOptions["mask"]): UuidSlugError | MaskSchema {
53
- // Omitting `mask` yields a codec that masks under a seed published in this package's source, so
54
- // its masked slugs are decodable by anyone. That is a real configuration — tests and demos want
55
- // reproducible output — but it is never the one a caller protecting ids wants, and nothing about
56
- // the resulting slug reveals which they got. See `defaultCodec` and `UuidSlugCodecOptions.mask`.
57
- if (!mask) return DEFAULT_MASK_SCHEMA;
58
- // A built schema carries its mixing step; an options object carries only a seed to derive one
59
- // from. One discriminating property beats sniffing several, which silently stops discriminating
60
- // when a scheme is added whose data fields differ.
61
- //
62
- // Every schema the codec will use passes through here, which is why the invertibility smoke test
63
- // belongs here and nowhere else: a caller-supplied `mix` is the extension point now, and an
64
- // unchecked one silently makes every id it encodes unreadable.
65
- if (!("mix" in mask)) return createMaskSchema(mask);
66
- return verifyInvertible(mask);
67
- }
68
-
69
- function createSentinels(definitions: readonly UuidV7SentinelDefinition[]) {
70
- const sentinels: UuidV7Sentinel[] = [];
71
- const byUuid = new Set<string>();
72
- const encoded: { bytes: Uint8Array; slug: SentinelUuidV7Slug }[] = [];
73
- const bySlug = new Map<string, { uuid: UuidV7String; bytes: Uint8Array }>();
74
- for (const definition of definitions) {
75
- // `uuid` is typed `UuidV7String`, and that types NOTHING: `Brand`'s marker is optional by
76
- // design, so every string satisfies every brand and a v4 passed the declaration untouched.
77
- // It then constructed fine, masked fine, and failed on EVERY decode forever after — a
78
- // permanent, per-call error configured once at construction. Checked here for the same reason
79
- // the invertibility smoke test is checked here: this is the last point at which a bad definition is
80
- // still a caller's argument rather than a codec that cannot work.
81
- const bytes = errorOrThrow(parseUuid(definition.uuid));
82
- if (!isUuidV7Bytes(bytes))
83
- throw new UuidSlugError(
84
- "invalid_uuid_version",
85
- `Sentinel "${definition.name}" must be a UUIDv7, got ${String(definition.uuid)}.`,
86
- );
87
- // A duplicate collapses SILENTLY: both entries stay in `codec.sentinels`, while the lookup maps
88
- // keep only the last, so the codec reports a sentinel it will never match.
89
- if (byUuid.has(definition.uuid))
90
- throw new UuidSlugError(
91
- "invalid_uuid",
92
- `Sentinel "${definition.name}" repeats the UUID of an earlier sentinel.`,
93
- );
94
- // Always base64url, never the codec's `slugAlphabet`: a sentinel slug is matched against
95
- // MASKED input, which is base64url by definition, so one written in another alphabet could
96
- // never be recognised in the position it exists for.
97
- const slug = formatUuidSlug(bytes);
98
- if (slug instanceof Error) throw slug;
99
- const sentinel = Object.freeze({
100
- name: definition.name,
101
- // `formatUuidSlug` returns the version-agnostic brand; the v7-ness comes
102
- // from the check above.
103
- slug: slug as SentinelUuidV7Slug,
104
- uuid: definition.uuid,
105
- });
106
- sentinels.push(sentinel);
107
- byUuid.add(definition.uuid);
108
- encoded.push({ bytes, slug: sentinel.slug });
109
- bySlug.set(sentinel.slug, { uuid: definition.uuid, bytes });
110
- }
111
- return { bySlug, encoded, sentinels: Object.freeze(sentinels) };
112
- }
113
-
114
- export function createUuidSlugCodec(options: UuidSlugCodecOptions = {}): UuidSlugCodec {
115
- const schema = errorOrThrow(schemaFromOption(options.mask));
116
- // Every schema a decode may try, and NOTHING a caller did not list. A codec once appended two
117
- // schemas of its own — a substitution partner derived from any seed, and the default seed's
118
- // pre-Feistel scheme — on the reasoning that a marker bit would select one outright. No marker
119
- // exists: each schema is tried in turn and the first whose check passes wins, so the codec's
120
- // false-accept rate is the SUM over the list and is set by its weakest member. Measured
121
- // 2026-08-12 over 200,000 wrong-key decodes, the auto-added 6-bit partner accepted 211 while
122
- // the 16-bit schema it accompanied accepted 2 — a 16x widening nobody asked for.
123
- const previousMasks = (options.previousMasks ?? []).map((mask) =>
124
- errorOrThrow(schemaFromOption(mask)),
125
- );
126
- const generator = options.generator ?? createRuntimeGenerator(runtime);
127
- const slugAlphabet = options.slugAlphabet ?? "base64url";
128
- errorOrThrow(resolveSlugAlphabet(slugAlphabet));
129
- const acceptUnmaskedSlugs = options.acceptUnmaskedSlugs === true;
130
- // The runtime's own slug generator emits base64url and nothing else, so it can only serve the
131
- // default. Resolved once here rather than per call: the branch is on configuration, which cannot
132
- // change after construction.
133
- const nativeSlug =
134
- options.generator === undefined && slugAlphabet === "base64url"
135
- ? runtime.uuidV7Slug
136
- : undefined;
137
- const sentinelState = createSentinels(options.sentinels ?? UUID_V7_SENTINEL_DEFINITIONS);
138
-
139
- function decodeMasked(slug: string): UuidSlugError | Uint8Array {
140
- const primary = decodeMaskedSlug(slug, schema, previousMasks);
141
- if (!(primary instanceof Error)) return primary;
142
- if (acceptUnmaskedSlugs) {
143
- const unmasked = parseUuidSlug(slug);
144
- if (!(unmasked instanceof Error)) return unmasked;
145
- }
146
- // The fallback's error is DROPPED, deliberately, and this returns `primary` whether or not the
147
- // fallback ran. It answers a different question — "is this a plain slug?" — and for the failure
148
- // that actually brings people here, a wrong or rotated key, its answer is untrue: the input is
149
- // perfectly good base64url whose trailing bits ARE the mask check, so it reported
150
- // `invalid_base64url: non-canonical trailing bits` and sent operators hunting a typo.
151
- // `primary` says the schema did not match, which is what happened.
152
- return primary;
153
- }
154
-
155
- function encodeMasked(bytes: Uint8Array): UuidSlugError | PublicUuidV7Slug {
156
- if (!isUuidV7Bytes(bytes))
157
- return new UuidSlugError(
158
- "invalid_uuid_version",
159
- "Masked UUID slugs require 16 UUIDv7 bytes.",
160
- );
161
- for (const sentinel of sentinelState.encoded) {
162
- let index = 0;
163
- while (index < 16 && sentinel.bytes[index] === bytes[index]) index += 1;
164
- if (index === 16) return sentinel.slug;
165
- }
166
- const slug = uuidV7BytesToMaskedSlug(bytes, schema);
167
- if (slug instanceof Error) return slug;
168
- // Sentinel decoding takes precedence, so returning this ciphertext would recover a different UUID.
169
- if (sentinelState.bySlug.has(slug))
170
- return new UuidSlugError(
171
- "invalid_mask_schema",
172
- "Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.",
173
- );
174
- return slug;
175
- }
176
-
177
- function uuidV7ToMaskedSlug(uuid: string): UuidSlugError | PublicUuidV7Slug {
178
- const bytes = parseUuid(uuid);
179
- return bytes instanceof Error ? bytes : encodeMasked(bytes);
180
- }
181
-
182
- function maskedSlugToUuidV7(slug: string): UuidSlugError | UuidV7String {
183
- const sentinel = sentinelState.bySlug.get(slug);
184
- if (sentinel) return sentinel.uuid;
185
- const decoded = decodeMasked(slug);
186
- if (decoded instanceof Error) return decoded;
187
- // Mask decoding restores v7 constants; only the plain fallback can carry another version.
188
- if (acceptUnmaskedSlugs && !isUuidV7Bytes(decoded))
189
- return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
190
- return formatUuid(decoded) as UuidSlugError | UuidV7String;
191
- }
192
-
193
- return {
194
- sentinels: sentinelState.sentinels,
195
- migration(migrationOptions) {
196
- return createMigration([schema, ...previousMasks], sentinelState.bySlug, migrationOptions);
197
- },
198
- uuidV4: generateUuidV4,
199
- uuidV7() {
200
- return generator.uuidV7();
201
- },
202
- uuidV4Bytes: generateUuidV4Bytes,
203
- uuidV7Bytes: generator.uuidV7Bytes,
204
- uuidV7At: generator.uuidV7At,
205
- uuidV7BytesAt: generator.uuidV7BytesAt,
206
- uuidV4Slug() {
207
- // The bytes came from `generateUuidV4Bytes`, which stamps version 4; the encoder sees only
208
- // bytes and cannot carry that through.
209
- return errorOrThrow(
210
- formatUuidSlug(errorOrThrow(generateUuidV4Bytes()), 0, slugAlphabet),
211
- ) as UuidV4Slug;
212
- },
213
- uuidV7Slug() {
214
- if (nativeSlug) return nativeSlug();
215
- // Same assertion `uuidV4Slug` makes for the same reason: the bytes come from a v7 generator,
216
- // and the encoder sees only bytes so it cannot carry the version through. Until the runtime
217
- // hooks were branded this cast was ABSENT and nothing complained — the native branch typed
218
- // the union as bare `string`, which an optional brand accepts, so the promise went unchecked.
219
- return errorOrThrow(
220
- formatUuidSlug(errorOrThrow(generator.uuidV7Bytes()), 0, slugAlphabet),
221
- ) as UuidV7Slug;
222
- },
223
- uuidV7MaskedSlug() {
224
- return errorOrThrow(encodeMasked(errorOrThrow(generator.uuidV7Bytes())));
225
- },
226
- uuidV7ToMaskedSlug,
227
- maskedSlugToUuidV7,
228
- maskedSlugToUuid(slug) {
229
- const sentinel = sentinelState.bySlug.get(slug);
230
- if (sentinel) return sentinel.uuid;
231
- const bytes = decodeMasked(slug);
232
- return bytes instanceof Error ? bytes : formatUuid(bytes);
233
- },
234
- /**
235
- * Unmask, then apply the same freshness rules as `validateUuidV7Fresh`, returning the slug.
236
- *
237
- * A METHOD rather than the module-level function it replaced: unmasking needs this codec's
238
- * key, and the old free function reached for `defaultCodec` — so it silently answered under
239
- * the seed published in this package's source and was wrong for every caller who supplied
240
- * their own. Nothing about that failure was visible at the call site; it returned a confident
241
- * Error for perfectly good slugs.
242
- *
243
- * Decode directly to bytes instead of formatting and reparsing a UUID. The method does not
244
- * access `this`, so it also works when detached from the codec.
245
- */
246
- validateMaskedSlugFresh(slug, freshness) {
247
- const bytes = sentinelState.bySlug.get(slug)?.bytes ?? decodeMasked(slug);
248
- if (bytes instanceof Error) return bytes;
249
- // The v7-specific decoder reports this before freshness validation does.
250
- if (!isUuidV7Bytes(bytes))
251
- return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
252
- const valid = validateFreshBytes(bytes, freshness);
253
- return valid instanceof Error ? valid : slug;
254
- },
255
- };
256
- }
257
-
258
- /**
259
- * Uses the published default seed, so anyone can decode its masked slugs.
260
- * Use `createUuidSlugCodec({ mask: { seed } })` with your own seed to hide identifiers.
261
- */
262
- // Annotated PURE so a bundle that never names it can drop it: a module-scope CONSTRUCTION call is
263
- // otherwise a side effect no bundler may remove, and this one reaches the cipher, the mask schema
264
- // and the sentinel table. Sound because `createUuidSlugCodec()` with no options cannot fail — the
265
- // only throwing paths are caller-supplied sentinels and a caller-supplied mix — and nothing else
266
- // observes the construction. The annotation is worth nothing on its own: it was measured saving
267
- // ZERO bytes while `index.ts` bound its shortcuts as PROPERTY READS of this value, since a read at
268
- // module scope forces the evaluation the annotation permits skipping. Keep the shortcuts keyless
269
- // (see `keyless.ts`) or this goes dead again.
270
- export const defaultCodec: UuidSlugCodec = /*#__PURE__*/ createUuidSlugCodec();
271
-
272
- export function validateUuidV7Fresh(
273
- uuid: string,
274
- options: FreshValidationOptions = {},
275
- ): UuidSlugError | UuidV7String {
276
- const bytes = parseUuid(uuid);
277
- if (bytes instanceof Error)
278
- return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
279
- const valid = validateFreshBytes(bytes, options);
280
- return valid instanceof Error ? valid : uuid;
281
- }
282
-
283
- /** Capture decoded fields before calling an external clock, which can reenter a custom schema. */
284
- function validateFreshBytes(
285
- bytes: Uint8Array,
286
- options: FreshValidationOptions = {},
287
- ): UuidSlugError | undefined {
288
- if (!isUuidV7Bytes(bytes))
289
- return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
290
- const timestamp = extractUuidV7Timestamp(bytes);
291
- if (timestamp instanceof Error) return timestamp;
292
- const hasEntropy = hasUuidV7Entropy(bytes);
293
- const windowMs = options.windowMs ?? 86_400_000;
294
- if (!Number.isFinite(windowMs) || windowMs < 0)
295
- return new UuidSlugError(
296
- "invalid_timestamp",
297
- "windowMs must be a finite, nonnegative number of milliseconds.",
298
- );
299
- const now = readClock(options.now ?? Date.now);
300
- if (now instanceof Error) return now;
301
- if (!Number.isFinite(now))
302
- return new UuidSlugError(
303
- "invalid_timestamp",
304
- "now must return a finite number of Unix milliseconds.",
305
- );
306
- if (timestamp < now - windowMs || timestamp > now + windowMs)
307
- return new UuidSlugError("stale_uuid", "UUIDv7 timestamp is outside the accepted window.");
308
- if (!hasEntropy) return new UuidSlugError("invalid_uuid", "UUIDv7 random payload is degenerate.");
309
- return undefined;
310
- }
311
-
312
- export function validateUuidV7SlugFresh(
313
- slug: string,
314
- options?: FreshValidationOptions,
315
- ): UuidSlugError | UuidV7Slug {
316
- const bytes = parseUuidSlug(slug);
317
- if (bytes instanceof Error) return bytes;
318
- const valid = validateFreshBytes(bytes, options);
319
- return valid instanceof Error ? valid : slug;
320
- }