@anizoptera/uuid-slug 0.3.0 → 0.5.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 +373 -324
  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 +15 -8
  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
@@ -0,0 +1,141 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import {
4
+ findUnknownOption,
5
+ INVALID_MASK,
6
+ isUint8Array,
7
+ isUuidSlugError,
8
+ stringInput,
9
+ UuidSlugError,
10
+ } from "./errors.ts";
11
+ import type { CustomUuidV7MaskOptions, UuidV7Mask } from "./types.ts";
12
+
13
+ const MASK_PROTOCOL = Symbol.for("@anizoptera/uuid-slug/mask/1");
14
+ const CUSTOM_MASK_FAILURE_MESSAGE = "Custom mask construction failed.";
15
+ const MASK_DIRECTION = "mask";
16
+ const CUSTOM_MASK_OPTIONS = {
17
+ diagnosticLabel: true,
18
+ [MASK_DIRECTION]: true,
19
+ unmask: true,
20
+ } as const satisfies Record<keyof CustomUuidV7MaskOptions, true>;
21
+
22
+ interface MaskProtocol {
23
+ readonly version: 1;
24
+ readonly mix: (
25
+ input: Uint8Array,
26
+ output: Uint8Array,
27
+ direction: "mask" | "unmask",
28
+ ) => undefined | UuidSlugError;
29
+ }
30
+
31
+ type MaskHandle = UuidV7Mask & { readonly [MASK_PROTOCOL]: MaskProtocol };
32
+
33
+ /**
34
+ * The versioned global symbol lets genuine handles cross duplicate same-version package copies.
35
+ * The protocol is internal representation, not an authenticity boundary for trusted codec options.
36
+ */
37
+ /*#__NO_SIDE_EFFECTS__*/
38
+ export function createMaskHandle(diagnosticLabel: string, mix: MaskProtocol["mix"]): UuidV7Mask {
39
+ const mask = { diagnosticLabel } as MaskHandle;
40
+ Object.defineProperty(mask, MASK_PROTOCOL, {
41
+ value: Object.freeze<MaskProtocol>({ version: 1, mix }),
42
+ });
43
+ return Object.freeze(mask);
44
+ }
45
+
46
+ function maskProtocol(mask: UuidV7Mask): MaskProtocol | undefined {
47
+ if (typeof mask !== "object" || mask === null) return undefined;
48
+ const protocol = (mask as Partial<MaskHandle>)[MASK_PROTOCOL];
49
+ return protocol?.version === 1 && typeof protocol.mix === "function" ? protocol : undefined;
50
+ }
51
+
52
+ export function isMaskHandle(mask: unknown): mask is UuidV7Mask {
53
+ return maskProtocol(mask as UuidV7Mask) !== undefined;
54
+ }
55
+
56
+ export function applyMask(
57
+ mask: UuidV7Mask,
58
+ input: Uint8Array,
59
+ output: Uint8Array,
60
+ direction: "mask" | "unmask",
61
+ ): undefined | UuidSlugError {
62
+ const protocol = maskProtocol(mask);
63
+ if (!protocol) return new UuidSlugError(INVALID_MASK, "Mask handle is invalid or incompatible.");
64
+ return protocol.mix(input, output, direction);
65
+ }
66
+
67
+ function runCustom(
68
+ transform: CustomUuidV7MaskOptions["mask"],
69
+ input: Uint8Array,
70
+ ): Uint8Array | UuidSlugError {
71
+ // Callbacks never receive package or caller storage. Copy their result at the codec boundary too,
72
+ // because a callback may retain and mutate the array it returns.
73
+ const output = transform(input.slice());
74
+ if (isUuidSlugError(output)) return output;
75
+ if (!isUint8Array(output) || output.length !== 16)
76
+ return new UuidSlugError(INVALID_MASK, "A custom mask transform must return exactly 16 bytes.");
77
+ return output;
78
+ }
79
+
80
+ /**
81
+ * Build an immutable mask from reversible 16-byte callbacks. Each callback receives isolated bytes,
82
+ * so returning the same array is safe. Invalid results and thrown values return `UuidSlugError`.
83
+ * The caller must ensure `unmask(mask(bytes))` restores every possible 16-byte input.
84
+ *
85
+ * @param options - Diagnostic label and mutually inverse 16-byte transforms.
86
+ * @returns The validated mask, or `UuidSlugError` for an invalid contract or callback result.
87
+ */
88
+ export function createCustomUuidV7Mask(
89
+ options: CustomUuidV7MaskOptions,
90
+ ): UuidV7Mask | UuidSlugError {
91
+ try {
92
+ if (typeof options !== "object" || options === null || Array.isArray(options))
93
+ return new UuidSlugError(INVALID_MASK, "Custom mask options must be an object.");
94
+ const unknown = findUnknownOption(options, CUSTOM_MASK_OPTIONS);
95
+ if (unknown !== undefined)
96
+ return new UuidSlugError(INVALID_MASK, `Unknown custom mask option: ${unknown}.`);
97
+ const { mask, unmask } = options;
98
+ const diagnosticLabel = stringInput(options.diagnosticLabel);
99
+ if (
100
+ typeof diagnosticLabel !== "string" ||
101
+ typeof mask !== "function" ||
102
+ typeof unmask !== "function"
103
+ )
104
+ return new UuidSlugError(
105
+ INVALID_MASK,
106
+ "A custom UUIDv7 mask requires a string diagnosticLabel plus mask and unmask functions.",
107
+ );
108
+ // These probes reject common non-inverses cheaply; no finite sample can prove a bijection over
109
+ // 128 bits, so the public contract keeps full invertibility as the callback author's duty.
110
+ for (const probe of [
111
+ new Uint8Array(16),
112
+ Uint8Array.from({ length: 16 }, (_, index) => index * 17),
113
+ ]) {
114
+ const mixed = runCustom(mask, probe);
115
+ if (isUuidSlugError(mixed))
116
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
117
+ cause: mixed,
118
+ });
119
+ const restored = runCustom(unmask, mixed);
120
+ if (isUuidSlugError(restored))
121
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
122
+ cause: restored,
123
+ });
124
+ if (restored.some((byte, index) => byte !== probe[index]))
125
+ return new UuidSlugError(
126
+ INVALID_MASK,
127
+ `UUIDv7 mask "${diagnosticLabel}" does not unmask its own masked output.`,
128
+ );
129
+ }
130
+ return createMaskHandle(diagnosticLabel, (input, output, direction) => {
131
+ const mixed = runCustom(direction === MASK_DIRECTION ? mask : unmask, input);
132
+ if (isUuidSlugError(mixed)) return mixed;
133
+ output.set(mixed);
134
+ return undefined;
135
+ });
136
+ } catch (cause) {
137
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
138
+ cause,
139
+ });
140
+ }
141
+ }
package/src/mask.ts CHANGED
@@ -1,157 +1,382 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { BASE64URL, decodeInto, encode, spareBits } from "./alphabet";
4
- import { UuidSlugError } from "./errors";
5
- import { mix32, read32 } from "./feistel";
6
- import { formatUuid } from "./uuid";
7
- import type { MaskSchema, MaskedUuidV7Slug, UuidString } from "./types";
8
-
9
- /** Custom callbacks can fail after construction; preserve their cause in the public error contract. */
10
- function applyMix(
11
- schema: MaskSchema,
12
- input: Uint8Array,
13
- output: Uint8Array,
14
- forward: boolean,
15
- ): UuidSlugError | undefined {
16
- try {
17
- schema.mix(input, output, forward);
18
- return undefined;
19
- } catch (cause) {
3
+ import {
4
+ ABORTED,
5
+ findUnknownOption,
6
+ INVALID_MASK,
7
+ isUint8Array,
8
+ stringInput,
9
+ UuidSlugError,
10
+ } from "./errors.ts";
11
+ import { FEISTEL_KEY_WORDS, feistel16 } from "./feistel.ts";
12
+ import { createMaskHandle } from "./mask-handle.ts";
13
+ import { halfSipHash } from "./siphash.ts";
14
+ import type { HashContinuation } from "./siphash.ts";
15
+ import { encodeUtf8 } from "#runtime";
16
+ import type { AsyncUuidV7MaskOptions, UuidV7Mask, UuidV7MaskOptions } from "./types.ts";
17
+
18
+ const MASK_CONSTRUCTION_FAILURE_MESSAGE = "Mask construction failed.";
19
+ const SEED_PROPERTY = "seed";
20
+ const MASK_OPTIONS = {
21
+ keyDerivationIterations: true,
22
+ diagnosticLabel: true,
23
+ [SEED_PROPERTY]: true,
24
+ } as const satisfies Record<keyof UuidV7MaskOptions, true>;
25
+ const ASYNC_MASK_OPTIONS = {
26
+ ...MASK_OPTIONS,
27
+ signal: true,
28
+ } as const satisfies Record<keyof AsyncUuidV7MaskOptions, true>;
29
+
30
+ /** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
31
+ const SEED_MIN_BYTES = 16;
32
+
33
+ /** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
34
+ const MAX_KEY_ITERATIONS = 1 << 24;
35
+
36
+ /** Large aligned byte seeds can share their owned buffer without changing HalfSipHash's byte order. */
37
+ const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
38
+ const SEED_WORD_VIEW_MIN_BYTES = 4096;
39
+
40
+ /*#__NO_SIDE_EFFECTS__*/
41
+ function canViewSeedWords(seed: Uint8Array) {
42
+ return LITTLE_ENDIAN && (seed.byteOffset & 3) === 0 && (seed.length & 3) === 0;
43
+ }
44
+
45
+ /**
46
+ * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
47
+ * "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
48
+ *
49
+ * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
50
+ * seed different round keys and make every masked slug ever issued undecodable.
51
+ */
52
+ const CHAIN_A_KEY1 = 0x41676c73;
53
+ const CHAIN_B_KEY1 = 0x42676c73;
54
+ const CHAIN_KEY0 = 0x64697575;
55
+
56
+ function seedBytes(seed: string | Uint8Array) {
57
+ if (typeof seed !== "string") return new Uint8Array(seed);
58
+ return encodeUtf8(seed);
59
+ }
60
+
61
+ /** Reject coercible JavaScript values before they can allocate storage or become key material. */
62
+ function validateOptions(options: unknown, accepted: Readonly<Record<string, true>>) {
63
+ if (typeof options !== "object" || options === null)
20
64
  return new UuidSlugError(
21
- "invalid_mask_schema",
22
- `Mask schema "${schema.id}" failed ${forward ? "encoding" : "decoding"}.`,
23
- { cause },
65
+ INVALID_MASK,
66
+ "Mask options must contain a string or Uint8Array seed.",
24
67
  );
68
+ const input = options as {
69
+ readonly diagnosticLabel?: unknown;
70
+ readonly keyDerivationIterations?: unknown;
71
+ readonly seed?: unknown;
72
+ };
73
+ const unknown = findUnknownOption(input, accepted);
74
+ if (unknown !== undefined)
75
+ return new UuidSlugError(INVALID_MASK, `Unknown mask option: ${unknown}.`);
76
+ // An accessor must not choose different key material between recognition and derivation.
77
+ // Capture once; a byte seed also needs only one intrinsic brand check.
78
+ const givenSeed = input.seed;
79
+ const seed =
80
+ typeof givenSeed === "string" || isUint8Array(givenSeed) ? givenSeed : stringInput(givenSeed);
81
+ if (seed === undefined)
82
+ return new UuidSlugError(INVALID_MASK, "Mask seed must be a string or Uint8Array.");
83
+ const givenLabel = input.diagnosticLabel;
84
+ const diagnosticLabel = givenLabel === undefined ? "seeded" : givenLabel;
85
+ const normalizedLabel = stringInput(diagnosticLabel);
86
+ if (normalizedLabel === undefined)
87
+ return new UuidSlugError(INVALID_MASK, "Mask diagnosticLabel must be a string.");
88
+ const givenIterations = input.keyDerivationIterations;
89
+ const keyDerivationIterations = givenIterations === undefined ? 1 : givenIterations;
90
+ const iterations = validatedIterations(keyDerivationIterations);
91
+ if (typeof iterations !== "number") return iterations;
92
+ return { diagnosticLabel: normalizedLabel, iterations, seed };
93
+ }
94
+
95
+ /** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
96
+ /*#__NO_SIDE_EFFECTS__*/
97
+ function seedWords(seed: Uint8Array) {
98
+ if (seed.length >= SEED_WORD_VIEW_MIN_BYTES && canViewSeedWords(seed))
99
+ return new Int32Array(seed.buffer, seed.byteOffset, seed.length >>> 2);
100
+ const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
101
+ writeSeedWords(seed, words);
102
+ return words;
103
+ }
104
+
105
+ /** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
106
+ function writeSeedWords(
107
+ seed: Uint8Array,
108
+ words: Int32Array,
109
+ offset = 0,
110
+ start = 0,
111
+ end = seed.length,
112
+ ) {
113
+ for (let index = start; index < end; index += 1) {
114
+ const absolute = offset + index;
115
+ words[absolute >>> 2] =
116
+ (words[absolute >>> 2] as number) | ((seed[index] as number) << ((absolute & 3) * 8));
25
117
  }
26
118
  }
27
119
 
28
120
  /**
29
- * The check must fail a wrong key with probability 2^-width, which holds only if the function
30
- * spreads its input across its whole output — so this is an avalanche mixer, not a sum. Measured
31
- * over 100,000 draws: uniform to chi-squared/df 0.999 across all 65,536 buckets of its top 16 bits.
32
- *
33
- * Taken from the TOP so that widening the check never renumbers the bits below it.
121
+ * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
122
+ * at construction, never per id. The count changes key material and must remain stable for
123
+ * issued slugs; retain the old count with its seed when rotating masks.
34
124
  */
35
- function tagFor(bytes: Uint8Array, width: number) {
36
- let acc = 0;
37
- for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));
38
- return acc >>> (32 - width);
125
+ /*#__NO_SIDE_EFFECTS__*/
126
+ function chain(key0: number, key1: number, words: Int32Array, length: number, iterations: number) {
127
+ const out = new Int32Array(2);
128
+ halfSipHash(key0, key1, words, length, out);
129
+ for (let i = 1; i < iterations; i += 1)
130
+ halfSipHash(out[0] as number, out[1] as number, words, length, out);
131
+ return out;
39
132
  }
40
133
 
41
134
  /**
42
- * The 12 check bits a UUIDv7 can hold inside the block, because it spends them on nothing: bits
43
- * 0-3 in byte 6's version nibble, 4-5 in byte 8's variant bits, 6-11 in byte 0's top six — the
44
- * high end of the 48-bit timestamp, zero for every instant before 2109. The rest of the check
45
- * rides outside the block, in whatever the encoding has spare.
46
- *
47
- * Claiming byte 0 is why encoding must REFUSE an instant at or past 2^42 ms rather than truncate.
135
+ * Derive each round key by XORing outputs from two fixed derivation chains. Their combined
136
+ * state is 128 bits; that representation does not establish 128-bit security. Chain constants,
137
+ * word indices and byte order are frozen by the issued wire format.
48
138
  */
49
- function injectTag(bytes: Uint8Array, tag: number) {
50
- bytes[6] = ((tag & 0x0f) << 4) | ((bytes[6] ?? 0) & 0x0f);
51
- bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] ?? 0) & 0x3f);
52
- bytes[0] = (((tag >>> 6) & 0x3f) << 2) | ((bytes[0] ?? 0) & 0x03);
139
+ /*#__NO_SIDE_EFFECTS__*/
140
+ function derivedKeys(seed: Uint8Array, iterations: number) {
141
+ const words = seedWords(seed);
142
+ const chainA = chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations);
143
+ const chainB = chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations);
144
+ return roundKeys(chainA, chainB);
53
145
  }
54
146
 
55
- function extractTag(bytes: Uint8Array) {
56
- return ((bytes[6] ?? 0) >>> 4) | (((bytes[8] ?? 0) >>> 6) << 4) | (((bytes[0] ?? 0) >>> 2) << 6);
147
+ /** The same final key expansion follows synchronous and cooperative derivation. */
148
+ /*#__NO_SIDE_EFFECTS__*/
149
+ function roundKeys(chainA: Int32Array, chainB: Int32Array) {
150
+ const keys = new Int32Array(FEISTEL_KEY_WORDS);
151
+ const index = new Int32Array(1);
152
+ const fromA = new Int32Array(2);
153
+ const fromB = new Int32Array(2);
154
+ for (let word = 0; word < FEISTEL_KEY_WORDS; word += 2) {
155
+ index[0] = word;
156
+ halfSipHash(chainA[0] as number, chainA[1] as number, index, 4, fromA);
157
+ halfSipHash(chainB[0] as number, chainB[1] as number, index, 4, fromB);
158
+ keys[word] = (fromA[0] as number) ^ (fromB[0] as number);
159
+ keys[word + 1] = (fromA[1] as number) ^ (fromB[1] as number);
160
+ }
161
+ return keys;
57
162
  }
58
163
 
59
- /** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
60
- function restoreV7(bytes: Uint8Array) {
61
- bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70;
62
- bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
63
- bytes[0] = (bytes[0] ?? 0) & 0x03;
164
+ /*#__NO_SIDE_EFFECTS__*/
165
+ function feistelMask(diagnosticLabel: string, seed: Uint8Array, iterations: number): UuidV7Mask {
166
+ return maskFromKeys(diagnosticLabel, derivedKeys(seed, iterations));
64
167
  }
65
168
 
66
- /** The 12 check bits that fit inside the block; the rest ride in the encoding's spare bits. */
67
- const INNER_TAG_BITS = 12;
169
+ /*#__NO_SIDE_EFFECTS__*/
170
+ function maskFromKeys(diagnosticLabel: string, keys: Int32Array): UuidV7Mask {
171
+ return createMaskHandle(diagnosticLabel, (input, output, direction) => {
172
+ feistel16(input, 0, keys, direction, output, 0);
173
+ });
174
+ }
68
175
 
69
176
  /**
70
- * A masked slug is always 22 base64url characters (Art's ruling, 2026-08-12), so the outer half of
71
- * the check is a constant 4 bits. Derived rather than written as `4` because the derivation IS the
72
- * rule — the check is whatever the encoding has left over, never a number somebody chose.
177
+ * Derive an immutable mask from a secret seed of at least 16 bytes. The seed and iteration count
178
+ * define the wire format; retain the old mask in `previousMasks` before changing either. Invalid
179
+ * options return `invalid_mask`.
180
+ *
181
+ * @param options - Stable secret seed, optional diagnostic label, and derivation work factor.
182
+ * @returns The mask, or `UuidSlugError` when an option or seed is invalid.
73
183
  */
74
- const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
75
- const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
76
-
77
- export function uuidV7BytesToMaskedSlug(
78
- raw: Uint8Array,
79
- schema: MaskSchema,
80
- ): UuidSlugError | MaskedUuidV7Slug {
81
- // Truncating instead would make encoding non-injective — two UUIDs would share one slug, and no
82
- // decoder could ever tell which was meant. Refusing is the only recoverable answer.
83
- if ((raw[0] ?? 0) > 0x03)
184
+ export function deriveUuidV7Mask(options: UuidV7MaskOptions): UuidV7Mask | UuidSlugError {
185
+ try {
186
+ const validated = validateOptions(options, MASK_OPTIONS);
187
+ if (!(SEED_PROPERTY in validated)) return validated;
188
+ const seed = seedBytes(validated.seed);
189
+ const short = invalidSeedLength(seed.length);
190
+ return short ?? feistelMask(validated.diagnosticLabel, seed, validated.iterations);
191
+ } catch (cause) {
192
+ return new UuidSlugError(INVALID_MASK, MASK_CONSTRUCTION_FAILURE_MESSAGE, { cause });
193
+ }
194
+ }
195
+
196
+ /*#__NO_SIDE_EFFECTS__*/
197
+ function invalidSeedLength(length: number): undefined | UuidSlugError {
198
+ if (length < SEED_MIN_BYTES)
84
199
  return new UuidSlugError(
85
- "invalid_timestamp",
86
- "Masking requires a UUIDv7 timestamped before 2^42 ms (year 2109); its top six bits carry the check.",
200
+ INVALID_MASK,
201
+ `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.`,
87
202
  );
88
- const tag = tagFor(raw, TAG_BITS);
89
- const tagged = new Uint8Array(raw);
90
- injectTag(tagged, tag >>> OUTER_TAG_BITS);
91
- const mixed = new Uint8Array(16);
92
- const failed = applyMix(schema, tagged, mixed, true);
93
- if (failed) return failed;
94
- return encode(mixed, BASE64URL, tag & ((1 << OUTER_TAG_BITS) - 1), OUTER_TAG_BITS);
95
- }
96
-
97
- export function decodeMaskedSlug(
98
- slug: string,
99
- schema: MaskSchema,
100
- previous: readonly MaskSchema[] = [],
101
- ): UuidSlugError | Uint8Array {
102
- const mixed = new Uint8Array(16);
103
- const outerTag = decodeInto(slug, BASE64URL, mixed, 0, 16, OUTER_TAG_BITS);
104
- if (outerTag instanceof Error) return outerTag;
105
- // A callback may mutate or retain its input. Each attempted key must receive fresh original
106
- // ciphertext, as it would when decoding the text again; only the text validation is shared.
107
- const primary = unmix(previous.length ? mixed.slice() : mixed, outerTag, schema);
108
- if (primary && !(primary instanceof Error)) return primary;
109
- for (const older of previous) {
110
- const decoded = unmix(mixed.slice(), outerTag, older);
111
- if (decoded && !(decoded instanceof Error)) return decoded;
203
+ return undefined;
204
+ }
205
+
206
+ function validatedIterations(iterations: unknown): number | UuidSlugError {
207
+ if (
208
+ typeof iterations !== "number" ||
209
+ !Number.isInteger(iterations) ||
210
+ iterations < 1 ||
211
+ iterations > MAX_KEY_ITERATIONS
212
+ )
213
+ return new UuidSlugError(
214
+ INVALID_MASK,
215
+ `Mask keyDerivationIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`,
216
+ );
217
+ return iterations;
218
+ }
219
+
220
+ /** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
221
+ const CHUNK_BYTES = 4096;
222
+
223
+ const host = globalThis as { setImmediate?: (callback: () => void) => void };
224
+ const immediate = host.setImmediate?.bind(host);
225
+
226
+ /** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */
227
+ function yieldToHost(): Promise<void> {
228
+ // Prioritized scheduler continuations can overtake queued cancellation tasks in browsers.
229
+ if (immediate) return new Promise((resolve) => immediate(resolve));
230
+ return new Promise((resolve) => {
231
+ const channel = new MessageChannel();
232
+ // eslint-disable-next-line unicorn/prefer-add-event-listener -- this private port has one handler; assignment also starts delivery
233
+ channel.port1.onmessage = () => {
234
+ channel.port1.close();
235
+ channel.port2.close();
236
+ resolve();
237
+ };
238
+ channel.port2.postMessage(null);
239
+ });
240
+ }
241
+
242
+ function* cooperativeChain(
243
+ key0: number,
244
+ key1: number,
245
+ words: Int32Array,
246
+ length: number,
247
+ iterations: number,
248
+ ): Generator<void, Int32Array, void> {
249
+ const out = new Int32Array(2);
250
+ out[0] = key0;
251
+ out[1] = key1;
252
+ const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
253
+ let sinceCheckpoint = 0;
254
+ for (let i = 0; i < iterations; i += 1) {
255
+ let continuation: HashContinuation | undefined;
256
+ do {
257
+ continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
258
+ if (continuation) yield;
259
+ } while (continuation);
260
+ sinceCheckpoint += 1;
261
+ if (sinceCheckpoint >= hashesPerChunk) {
262
+ sinceCheckpoint = 0;
263
+ yield;
264
+ }
265
+ }
266
+ return out;
267
+ }
268
+
269
+ function* cooperativeKeys(
270
+ seed: string | Uint8Array,
271
+ iterations: number,
272
+ ): Generator<void, Int32Array | UuidSlugError, void> {
273
+ // Byte seeds were snapshotted before suspension. Strings are immutable, so encoding can yield.
274
+ const chunks: Uint8Array[] = [];
275
+ let length = 0;
276
+ if (typeof seed === "string") {
277
+ for (let start = 0; start < seed.length;) {
278
+ let end = Math.min(seed.length, start + CHUNK_BYTES);
279
+ // Do not split a surrogate pair: encoding either half alone would substitute U+FFFD.
280
+ const last = seed.charCodeAt(end - 1);
281
+ const next = seed.charCodeAt(end);
282
+ if (end < seed.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)
283
+ end -= 1;
284
+ const bytes = encodeUtf8(seed.slice(start, end));
285
+ chunks.push(bytes);
286
+ length += bytes.length;
287
+ start = end;
288
+ yield;
289
+ }
290
+ } else {
291
+ chunks.push(seed);
292
+ length = seed.length;
112
293
  }
113
- // A key mismatch is ordinary rotation control flow. Allocate its diagnostic only if no key
114
- // succeeds, while keeping the primary callback's error and cause when that was the failure.
115
- return (
116
- primary ?? new UuidSlugError("invalid_uuid_slug", "Masked UUID slug failed schema validation.")
117
- );
118
- }
119
-
120
- /** Append distinct UUIDs directly to the result, before another callback can mutate their bytes. */
121
- export function decodeMaskedCandidates(
122
- mixed: Uint8Array,
123
- outerTag: number,
124
- schemas: readonly MaskSchema[],
125
- firstOnly = false,
126
- candidates: UuidString[] = [],
127
- ): UuidSlugError | UuidString[] {
128
- for (const schema of schemas) {
129
- // Custom callbacks may mutate their input; no key may alter what the next one sees.
130
- const decoded = unmix(mixed.slice(), outerTag, schema);
131
- // A failed callback means the candidate list is incomplete, not that its key mismatched.
132
- if (decoded instanceof Error) return decoded;
133
- if (decoded) {
134
- const uuid = formatUuid(decoded);
135
- if (uuid instanceof Error) return uuid;
136
- if (!candidates.includes(uuid)) candidates.push(uuid);
137
- if (firstOnly) break;
294
+ const short = invalidSeedLength(length);
295
+ if (short) return short;
296
+ const viewBytes =
297
+ typeof seed !== "string" && seed.length >= SEED_WORD_VIEW_MIN_BYTES && canViewSeedWords(seed);
298
+ const words = viewBytes
299
+ ? new Int32Array(seed.buffer, seed.byteOffset, seed.length >>> 2)
300
+ : new Int32Array(Math.ceil(length / 4) + 1);
301
+ if (!viewBytes) {
302
+ let offset = 0;
303
+ for (const bytes of chunks) {
304
+ for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
305
+ writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
306
+ yield;
307
+ }
308
+ offset += bytes.length;
138
309
  }
139
310
  }
140
- return candidates;
141
- }
142
-
143
- function unmix(
144
- mixed: Uint8Array,
145
- outerTag: number,
146
- schema: MaskSchema,
147
- ): UuidSlugError | Uint8Array | undefined {
148
- const unmixed = new Uint8Array(16);
149
- const failed = applyMix(schema, mixed, unmixed, false);
150
- if (failed) return failed;
151
- // Both halves come out of the same decryption, so a wrong key garbles the observed check as
152
- // thoroughly as the payload: the tag needs no key of its own to tell keys apart.
153
- const foundTag = (extractTag(unmixed) << OUTER_TAG_BITS) | outerTag;
154
- restoreV7(unmixed);
155
- if (tagFor(unmixed, TAG_BITS) !== foundTag) return undefined;
156
- return unmixed;
311
+ chunks.length = 0;
312
+ const chainA = yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations);
313
+ const chainB = yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations);
314
+ return roundKeys(chainA, chainB);
157
315
  }
316
+
317
+ /**
318
+ * Derive the same mask without monopolizing the host task. Later mutation of a byte seed does not
319
+ * affect the result. Cancellation returns `aborted` with `signal.reason` as its cause; invalid
320
+ * options return `invalid_mask`. Construct once and reuse the result.
321
+ *
322
+ * @param options - Synchronous mask options plus an optional cancellation signal.
323
+ * @returns A promise for the mask or an expected construction error.
324
+ */
325
+ export async function deriveUuidV7MaskAsync(
326
+ options: AsyncUuidV7MaskOptions,
327
+ ): Promise<UuidV7Mask | UuidSlugError> {
328
+ try {
329
+ const signal = options?.signal;
330
+ const aborted = () =>
331
+ new UuidSlugError(ABORTED, "Mask construction was aborted.", {
332
+ cause: signal?.reason,
333
+ });
334
+ if (signal?.aborted) return aborted();
335
+ const validated = validateOptions(options, ASYNC_MASK_OPTIONS);
336
+ if (!(SEED_PROPERTY in validated)) return validated;
337
+ const seed =
338
+ typeof validated.seed === "string" ? validated.seed : new Uint8Array(validated.seed);
339
+ const steps = cooperativeKeys(seed, validated.iterations);
340
+ let deadline = performance.now() + 2;
341
+ while (true) {
342
+ if (signal?.aborted) {
343
+ const failure = aborted();
344
+ steps.return(failure);
345
+ return failure;
346
+ }
347
+ const step = steps.next();
348
+ if (step.done)
349
+ return ArrayBuffer.isView(step.value)
350
+ ? maskFromKeys(validated.diagnosticLabel, step.value)
351
+ : step.value;
352
+ if (performance.now() >= deadline) {
353
+ // eslint-disable-next-line no-await-in-loop -- each slice must yield before continuing the dependent derivation
354
+ await yieldToHost();
355
+ deadline = performance.now() + 2;
356
+ }
357
+ }
358
+ } catch (cause) {
359
+ return new UuidSlugError(INVALID_MASK, MASK_CONSTRUCTION_FAILURE_MESSAGE, { cause });
360
+ }
361
+ }
362
+
363
+ /**
364
+ * A PUBLIC key. It ships in the tarball, so every masked slug produced under it is decodable by
365
+ * anyone who installed this package, and it therefore provides none of the obscurity masking
366
+ * exists for.
367
+ *
368
+ * It is exported so a deterministic test or example can opt in visibly with
369
+ * `mask: UUID_V7_TEST_MASK`; codec construction never selects it by omission.
370
+ */
371
+ const DEFAULT_SEED = "anizoptera.uuid-slug.default-mask.v1";
372
+
373
+ // Built from `feistelMask` rather than through `deriveUuidV7Mask`, whose failures are a short seed and a
374
+ // bad iteration count — checks on CALLER input that the literals here cannot fail. Routing through it would return
375
+ // `UuidV7Mask | UuidSlugError` and force a cast that, at module scope, could only ever hide a real Error
376
+ // behind a `UuidV7Mask` type at module scope.
377
+ /** Public-key mask for deterministic tests and examples. Never use it to hide production IDs. */
378
+ export const UUID_V7_TEST_MASK: UuidV7Mask = /*#__PURE__*/ feistelMask(
379
+ "default",
380
+ /*#__PURE__*/ seedBytes(DEFAULT_SEED),
381
+ 1,
382
+ );