@anizoptera/uuid-slug 0.2.0 → 0.3.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 (95) hide show
  1. package/README.md +381 -27
  2. package/dist/alphabet.d.ts +21 -0
  3. package/dist/alphabet.d.ts.map +1 -0
  4. package/dist/alphabet.js +132 -0
  5. package/dist/alphabet.js.map +1 -0
  6. package/dist/base64url.d.ts +20 -0
  7. package/dist/base64url.d.ts.map +1 -0
  8. package/dist/base64url.js +33 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/codec.d.ts +17 -0
  11. package/dist/codec.d.ts.map +1 -0
  12. package/dist/codec.js +192 -0
  13. package/dist/codec.js.map +1 -0
  14. package/dist/errors.d.ts +16 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +80 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/feistel.js +105 -0
  19. package/dist/feistel.js.map +1 -0
  20. package/dist/index.d.ts +11 -168
  21. package/dist/index.js +10 -649
  22. package/dist/keyless.d.ts +31 -0
  23. package/dist/keyless.d.ts.map +1 -0
  24. package/dist/keyless.js +93 -0
  25. package/dist/keyless.js.map +1 -0
  26. package/dist/legacy-mask.js +55 -0
  27. package/dist/legacy-mask.js.map +1 -0
  28. package/dist/mask.js +108 -0
  29. package/dist/mask.js.map +1 -0
  30. package/dist/migration.js +66 -0
  31. package/dist/migration.js.map +1 -0
  32. package/dist/node/alphabet.js +130 -0
  33. package/dist/node/base64url.js +31 -0
  34. package/dist/node/codec.js +190 -0
  35. package/dist/node/errors.js +78 -0
  36. package/dist/node/feistel.js +103 -0
  37. package/dist/node/index.js +10 -647
  38. package/dist/node/keyless.js +91 -0
  39. package/dist/node/legacy-mask.js +53 -0
  40. package/dist/node/mask.js +106 -0
  41. package/dist/node/migration.js +64 -0
  42. package/dist/node/runtime/node.js +33 -0
  43. package/dist/node/runtime/pool.js +53 -0
  44. package/dist/node/schema.js +214 -0
  45. package/dist/node/siphash.js +106 -0
  46. package/dist/node/uuid.js +226 -0
  47. package/dist/node/v7.js +185 -0
  48. package/dist/node/yield.js +20 -0
  49. package/dist/runtime/pool.js +55 -0
  50. package/dist/runtime/pool.js.map +1 -0
  51. package/dist/runtime/web.js +39 -0
  52. package/dist/runtime/web.js.map +1 -0
  53. package/dist/schema.d.ts +20 -0
  54. package/dist/schema.d.ts.map +1 -0
  55. package/dist/schema.js +216 -0
  56. package/dist/schema.js.map +1 -0
  57. package/dist/siphash.js +108 -0
  58. package/dist/siphash.js.map +1 -0
  59. package/dist/types.d.ts +255 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/uuid.d.ts +78 -0
  62. package/dist/uuid.d.ts.map +1 -0
  63. package/dist/uuid.js +228 -0
  64. package/dist/uuid.js.map +1 -0
  65. package/dist/v7.d.ts +12 -0
  66. package/dist/v7.d.ts.map +1 -0
  67. package/dist/v7.js +187 -0
  68. package/dist/v7.js.map +1 -0
  69. package/dist/yield.js +22 -0
  70. package/dist/yield.js.map +1 -0
  71. package/package.json +8 -12
  72. package/src/alphabet.ts +187 -0
  73. package/src/base64url.ts +28 -63
  74. package/src/codec.ts +227 -125
  75. package/src/errors.ts +83 -9
  76. package/src/feistel.ts +128 -0
  77. package/src/index.ts +52 -26
  78. package/src/keyless.ts +136 -0
  79. package/src/legacy-mask.ts +25 -0
  80. package/src/mask.ts +129 -67
  81. package/src/migration.ts +104 -0
  82. package/src/runtime/bun.ts +49 -24
  83. package/src/runtime/node.ts +33 -15
  84. package/src/runtime/pool.ts +62 -0
  85. package/src/runtime/types.ts +42 -5
  86. package/src/runtime/web.ts +37 -9
  87. package/src/schema.ts +274 -97
  88. package/src/siphash.ts +127 -0
  89. package/src/types.ts +221 -37
  90. package/src/uuid.ts +189 -50
  91. package/src/v7.ts +217 -45
  92. package/src/yield.ts +22 -0
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/index.js.map +0 -1
  95. package/dist/web/index.js +0 -648
package/src/feistel.ts ADDED
@@ -0,0 +1,128 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { halfSipHash } from "./siphash";
4
+
5
+ /**
6
+ * A 4-round Feistel network over the 16 UUID bytes, used as the mask's mixing step.
7
+ *
8
+ * Why a Feistel rather than the byte permutation plus XOR it replaces: that construction is a
9
+ * monoalphabetic substitution — one output byte per input byte — so bytes the inputs share, the
10
+ * outputs share too. Measured over 3000 ids, masked slugs of UUIDv7s created in the same second
11
+ * held 4 of 16 bytes constant, the same hour 3, the same day 2. The timestamp the mask exists to
12
+ * hide was still legible in the output. A Feistel diffuses every input bit across the whole
13
+ * block, so no output byte is a function of one input byte: the same measurement yields 0 of 16.
14
+ *
15
+ * The bijection is the property being bought, and it holds whatever the round function does: 16
16
+ * bytes map to 16 bytes and the inverse is the same routine with the round keys reversed, so
17
+ * `mask` and `unmask` cannot drift apart.
18
+ *
19
+ * The round function is HalfSipHash-2-4 keyed per round. What that fixes: the previous round
20
+ * function was `mix32(word ^ roundKey)` — a FIXED, PUBLIC, UNKEYED bijection with the key merely
21
+ * XORed in front, so an attacker inverts it and reads `word ^ roundKey` directly. Luby-Rackoff
22
+ * makes a four-round Feistel a strong pseudorandom permutation only when the round functions are
23
+ * pseudorandom functions, which `mix32` is not, so the theorem said nothing about what shipped and
24
+ * an earlier version of this comment cited it wrongly. A keyed PRF meets that hypothesis in kind,
25
+ * which is what makes ROUNDS = 4 a justified number rather than an unexamined margin. It is still
26
+ * NOT a proof about what ships: the theorem wants four INDEPENDENTLY sampled round functions, and
27
+ * `schema.ts` derives all four key pairs from one 128-bit key. Read it as the design rationale it
28
+ * is, and see `docs/design.md` for what masking does and does not promise.
29
+ *
30
+ * Measured 2026-08-12 on Bun, both directions, medians of 9: the swap costs 2.5x on the mixing step
31
+ * alone (30.85M -> 12.43M mixes/s) and about a quarter of end-to-end masking throughput, because
32
+ * mixing is roughly a fifth of a mask. HalfSipHash is FASTER per round than `mix32` — pure
33
+ * add/xor/rotate against two `Math.imul` calls — and loses only by doing 14 rounds where the old
34
+ * function did the equivalent of 4.
35
+ *
36
+ * Nor does any measurement in this repository grade the round count or the round function. Strict
37
+ * avalanche across all input/output bit pairs, a same-millisecond burst where only a 12-bit counter
38
+ * varies, and a single-difference differential all PASS a TWO-round network, so none of them can
39
+ * separate a weak setting from a strong one. Their agreement is evidence about the instruments.
40
+ * `test/siphash.test.ts` is the exception and the reason a published primitive was worth taking:
41
+ * it checks the round function against 64 vectors somebody else computed, and that CAN fail.
42
+ */
43
+
44
+ /**
45
+ * Round count. Wire-format-bearing: changing it changes every masked slug this package has ever
46
+ * issued, so it moves only alongside a deliberate format change. Four is Luby-Rackoff's number,
47
+ * which the round function now makes relevant — see the note above for why that is a rationale
48
+ * rather than a proof.
49
+ */
50
+ const ROUNDS = 4;
51
+
52
+ /** Two 32-bit round keys per round, consumed as one flat array to keep the hot loop indexed. */
53
+ export const FEISTEL_KEY_WORDS = ROUNDS * 2;
54
+
55
+ /**
56
+ * The `lowbias32` finalizer: an integer hash with near-ideal avalanche for its size. No longer the
57
+ * round function — see above — but still what `mask.ts` derives its check tag with, where the input
58
+ * is public and an unkeyed mixer is the right tool.
59
+ */
60
+ export function mix32(value: number): number {
61
+ let x = (value ^ (value >>> 16)) >>> 0;
62
+ x = Math.imul(x, 0x7feb352d);
63
+ x = (x ^ (x >>> 15)) >>> 0;
64
+ x = Math.imul(x, 0x846ca68b);
65
+ return (x ^ (x >>> 16)) >>> 0;
66
+ }
67
+
68
+ /** Big-endian on purpose: the wire format must not depend on the host's byte order. */
69
+ export function read32(bytes: Uint8Array, offset: number): number {
70
+ return (
71
+ ((bytes[offset] as number) << 24) |
72
+ ((bytes[offset + 1] as number) << 16) |
73
+ ((bytes[offset + 2] as number) << 8) |
74
+ (bytes[offset + 3] as number) |
75
+ 0
76
+ );
77
+ }
78
+
79
+ function write32(bytes: Uint8Array, offset: number, value: number) {
80
+ bytes[offset] = value >>> 24;
81
+ bytes[offset + 1] = (value >>> 16) & 0xff;
82
+ bytes[offset + 2] = (value >>> 8) & 0xff;
83
+ bytes[offset + 3] = value & 0xff;
84
+ }
85
+
86
+ // Scratch for the round function, at module scope because allocating two 2-word arrays per call
87
+ // dominated the mix. Safe because nothing here is reentrant: `feistel16` is synchronous, calls only
88
+ // `halfSipHash`, and that calls nothing.
89
+ const roundInput = new Int32Array(2);
90
+ const roundOutput = new Int32Array(2);
91
+
92
+ /**
93
+ * Transform 16 bytes from `input` into `output`, which may be the same array.
94
+ *
95
+ * `forward: false` is the exact inverse — the rounds are identical and only the key order
96
+ * differs, which is why the final swap below is undone rather than performed.
97
+ */
98
+ export function feistel16(
99
+ input: Uint8Array,
100
+ inputOffset: number,
101
+ keys: Int32Array,
102
+ forward: boolean,
103
+ output: Uint8Array,
104
+ outputOffset: number,
105
+ ) {
106
+ let left0 = read32(input, inputOffset);
107
+ let left1 = read32(input, inputOffset + 4);
108
+ let right0 = read32(input, inputOffset + 8);
109
+ let right1 = read32(input, inputOffset + 12);
110
+ for (let round = 0; round < ROUNDS; round += 1) {
111
+ const key = (forward ? round : ROUNDS - 1 - round) * 2;
112
+ roundInput[0] = right0;
113
+ roundInput[1] = right1;
114
+ halfSipHash(keys[key] as number, keys[key + 1] as number, roundInput, 8, roundOutput);
115
+ const next0 = left0 ^ (roundOutput[0] as number);
116
+ const next1 = left1 ^ (roundOutput[1] as number);
117
+ left0 = right0;
118
+ left1 = right1;
119
+ right0 = next0;
120
+ right1 = next1;
121
+ }
122
+ // Undoing the last round's swap is what collapses encode and decode into one routine. Perform
123
+ // it, and decoding would need its own mirrored loop that can silently disagree with this one.
124
+ write32(output, outputOffset, right0);
125
+ write32(output, outputOffset + 4, right1);
126
+ write32(output, outputOffset + 8, left0);
127
+ write32(output, outputOffset + 12, left1);
128
+ }
package/src/index.ts CHANGED
@@ -1,25 +1,29 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  export { decodeBase64Url, encodeBase64Url, isBase64Url } from "./base64url";
2
4
  export {
3
5
  UUID_V7_SENTINEL_DEFINITIONS,
4
6
  createUuidSlugCodec,
5
7
  defaultCodec,
6
- validateMaskedUuidV7SlugFresh,
7
8
  validateUuidV7Fresh,
8
9
  validateUuidV7SlugFresh,
9
10
  } from "./codec";
10
- export { UuidRuntimeError, UuidSlugError } from "./errors";
11
- export {
12
- DEFAULT_MASK_SCHEMA,
13
- LEGACY_MASK_SCHEMA_V1,
14
- createMaskSchema,
15
- defineMaskSchema,
16
- } from "./schema";
11
+ export { UUID_SLUG_ERROR_CODES, UuidRuntimeError, UuidSlugError } from "./errors";
12
+ /**
13
+ * Exported because `UuidSlugError.code` is public and the README tells consumers to branch on it.
14
+ * The type was emitted into the declarations and left out of the export list, so the property had
15
+ * a type no consumer could name — a switch over it could not be written without restating the
16
+ * literals by hand, which is exactly the duplication `UUID_SLUG_ERROR_CODES` exists to prevent.
17
+ */
18
+ export type { UuidSlugErrorCode } from "./errors";
19
+ export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync } from "./schema";
17
20
  export type {
21
+ AsyncMaskSchemaOptions,
18
22
  Base64UrlString,
19
- ExplicitMaskSchema,
20
23
  FreshValidationOptions,
21
24
  MaskSchema,
22
25
  MaskSchemaOptions,
26
+ MigrationFormat,
23
27
  MaskedUuidSlug,
24
28
  MaskedUuidV7Slug,
25
29
  PublicUuidV7Slug,
@@ -28,6 +32,8 @@ export type {
28
32
  UuidSlug,
29
33
  UuidSlugCodec,
30
34
  UuidSlugCodecOptions,
35
+ UuidSlugMigration,
36
+ UuidSlugMigrationOptions,
31
37
  UuidString,
32
38
  UuidV4Slug,
33
39
  UuidV4String,
@@ -52,23 +58,43 @@ export {
52
58
  parseUuid,
53
59
  parseUuidSlug,
54
60
  slugToUuid,
55
- slugToUuidBytes,
56
- uuidBytesToSlug,
57
61
  uuidToSlug,
58
62
  } from "./uuid";
59
- export { createRuntimeGenerator, createUuidV7Generator } from "./v7";
63
+ export type { SlugAlphabet } from "./uuid";
64
+ /**
65
+ * `createRuntimeGenerator` is NOT exported (Art's ruling, 2026-08-12), pending the whole-API-shape
66
+ * review. It takes a `Runtime`, which is not exported either, so no consumer could construct an
67
+ * argument for it — a public function nobody could call. The capability it provides is already
68
+ * applied: every codec built without an explicit `generator` gets one.
69
+ */
70
+ export { createUuidV7Generator } from "./v7";
71
+ export type { UuidV7GeneratorOptions } from "./v7";
60
72
 
61
- import { defaultCodec } from "./codec";
62
-
63
- export const uuidV4 = defaultCodec.uuidV4;
64
- export const uuidV7 = defaultCodec.uuidV7;
65
- export const uuidV4Bytes = defaultCodec.uuidV4Bytes;
66
- export const uuidV7Bytes = defaultCodec.uuidV7Bytes;
67
- export const uuidV4Slug = defaultCodec.uuidV4Slug;
68
- export const uuidV7Slug = defaultCodec.uuidV7Slug;
69
- export const uuidV7MaskedSlug = defaultCodec.uuidV7MaskedSlug;
70
- export const uuidToMaskedSlug = defaultCodec.uuidToMaskedSlug;
71
- export const maskedSlugToUuid = defaultCodec.maskedSlugToUuid;
72
- export const uuidV7ToMaskedSlug = defaultCodec.uuidV7ToMaskedSlug;
73
- export const maskedSlugToUuidV7 = defaultCodec.maskedSlugToUuidV7;
74
- export const UUID_V7_SENTINELS = defaultCodec.sentinels;
73
+ /*
74
+ * The keyless shortcuts. They come from `keyless.ts`, which builds them from a bare generator and
75
+ * never touches a codec — see that file for the measured cost of the alternative. They were once
76
+ * bound here as `export const uuidV7 = defaultCodec.uuidV7`, and that spelling is the defect: a
77
+ * property read at module scope evaluates the singleton, so every consumer of ANY export in this
78
+ * barrel carried the cipher, the mask schema and the sentinel table whether or not it masked.
79
+ *
80
+ * The MASKED methods are deliberately absent, and must stay absent (Art's ruling, 2026-08-12).
81
+ * Everything below is keyless — the same value whoever calls it — so a bare function is an honest
82
+ * shape for it. Masking is keyed, and the only key a bare function could carry is `defaultCodec`'s,
83
+ * which is derived from a seed published in this package's source. Exported that way, the
84
+ * easiest-to-reach spelling of the headline feature was the one that obfuscates nothing, and a
85
+ * README paragraph was the only thing standing between a caller and it.
86
+ *
87
+ * Reach masking through a codec you built with your own seed: `createUuidSlugCodec({ mask: {
88
+ * seed } })`. Sentinels went with them for the same reason — a sentinel exists to be matched
89
+ * against masked input, so a sentinel list has no meaning apart from the codec that masks.
90
+ */
91
+ export {
92
+ uuidV4,
93
+ uuidV4Bytes,
94
+ uuidV4Slug,
95
+ uuidV7,
96
+ uuidV7At,
97
+ uuidV7Bytes,
98
+ uuidV7BytesAt,
99
+ uuidV7Slug,
100
+ } from "./keyless";
package/src/keyless.ts ADDED
@@ -0,0 +1,136 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /**
4
+ * The operations that need no key, built WITHOUT a codec.
5
+ *
6
+ * Generating an id and re-encoding one are keyless: the result is the same value whoever asks, so
7
+ * a bare function is an honest shape for them. Reaching them through a codec is what made them
8
+ * expensive — a codec carries a mask schema, a cipher and a sentinel table, none of which a caller
9
+ * who never masks will ever execute, and all of which a bundler must keep once the graph reaches
10
+ * them. Measured 2026-08-12 on the built package: an entry importing only `uuidV7Slug` minified to
11
+ * 12,735 bytes through the codec and 4,559 from a bare generator; `uuidToSlug` alone, 12,725
12
+ * against 2,188. `defaultCodec` still exists and still works — it is simply no longer on the path
13
+ * every consumer walks.
14
+ *
15
+ * NOTHING KEYED MAY BE ADDED HERE (Art's ruling, 2026-08-12). The only key a bare function could
16
+ * carry is `DEFAULT_MASK_SCHEMA`'s, whose seed is a string literal in this published package, so a
17
+ * masked operation exported this way would be the shortest spelling of the headline feature and
18
+ * the one that obfuscates nothing. Masking is reached through a codec built with your own seed.
19
+ */
20
+ import { runtime } from "#runtime";
21
+ import {
22
+ checkRange,
23
+ errorOrThrow,
24
+ fillRandomBytes,
25
+ UuidRuntimeError,
26
+ UuidSlugError,
27
+ } from "./errors";
28
+ import type { UuidV4Slug, UuidV4String, UuidV7Generator, UuidV7Slug, UuidV7String } from "./types";
29
+ import { formatUuid, formatUuidSlug } from "./uuid";
30
+ import type { SlugAlphabet } from "./uuid";
31
+ import { createRuntimeGenerator } from "./v7";
32
+
33
+ /**
34
+ * Built on first use, and the laziness is what the measurement above depends on: a module-scope
35
+ * CONSTRUCTION call is a side effect a bundler may not remove, so an eager one would pin the
36
+ * generator, the runtime adapter and the entropy pool into a bundle that only ever re-encodes a
37
+ * UUID. Measured the same day, the eager spelling cost 5,130 bytes for `uuidToSlug` alone against
38
+ * 2,188 here.
39
+ *
40
+ * It also keeps import-time work at zero, which `test/entropy.test.ts` gates for a different
41
+ * reason — a heap snapshot taken at module load must capture no drawn randomness.
42
+ */
43
+ let generator: UuidV7Generator | undefined;
44
+ const v7 = () => (generator ??= createRuntimeGenerator(runtime));
45
+
46
+ /**
47
+ * Randomness is drawn into a private buffer and copied out instead of filled through a view of the
48
+ * caller's array: `fillRandom` requires a plain `ArrayBuffer` because Web Crypto rejects a
49
+ * `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee. Reused rather
50
+ * than allocated per call, matching the v7 generator, so the cost is one 16-byte copy.
51
+ */
52
+ const v4Random = new Uint8Array(16);
53
+
54
+ /** Shared with `createUuidSlugCodec`, so a v4 has one implementation however it is reached. */
55
+ export function uuidV4Bytes(out?: Uint8Array, offset = 0): UuidSlugError | Uint8Array {
56
+ const target = out ?? new Uint8Array(16);
57
+ const badRange = checkRange(target.length, offset, 16);
58
+ if (badRange) return badRange;
59
+ const failed = fillRandomBytes(runtime.fillRandom, v4Random);
60
+ if (failed) return failed;
61
+ target.set(v4Random, offset);
62
+ target[offset + 6] = ((target[offset + 6] ?? 0) & 0x0f) | 0x40;
63
+ target[offset + 8] = ((target[offset + 8] ?? 0) & 0x3f) | 0x80;
64
+ return target;
65
+ }
66
+
67
+ export function uuidV4(): UuidV4String {
68
+ try {
69
+ const native = runtime.uuidV4?.();
70
+ if (native) return native;
71
+ } catch (cause) {
72
+ throw new UuidRuntimeError("Runtime UUIDv4 generation failed.", { cause });
73
+ }
74
+ return errorOrThrow(formatUuid(errorOrThrow(uuidV4Bytes()))) as UuidV4String;
75
+ }
76
+
77
+ /**
78
+ * Takes the alphabet for the same reason `uuidV7Slug` does, and NOT because a v4 slug sorts — it
79
+ * does not. The alphabet is a choice of representation, so a project that has standardised on the
80
+ * 26-character lowercase form for its public ids needs its v4 slugs in it too; the pair differing
81
+ * would be an asymmetry with nothing behind it.
82
+ */
83
+ export function uuidV4Slug(alphabet: SlugAlphabet = "base64url"): UuidV4Slug {
84
+ // The bytes came from `uuidV4Bytes`, which stamps version 4; the encoder sees only bytes and
85
+ // cannot carry that through, which is what the assertion stands in for.
86
+ return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, alphabet)) as UuidV4Slug;
87
+ }
88
+
89
+ /*
90
+ * Return types are DECLARED, not inferred, on all four. Inference reads them off the generator, so
91
+ * a widened method there silently widens the package's public surface — and this package has
92
+ * already been bitten by exactly that: `uuidV7Slug` once inferred `string | UuidSlug`, which
93
+ * collapses to `string` because `Brand`'s marker is optional, so a branded return was promised that
94
+ * nothing checked. A declared type turns that into a compile error at the one site that is wrong.
95
+ */
96
+ export const uuidV7 = (): UuidV7String => v7().uuidV7();
97
+
98
+ export const uuidV7Bytes = (out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array =>
99
+ v7().uuidV7Bytes(out, offset);
100
+
101
+ export const uuidV7At = (timestamp: number): UuidSlugError | UuidV7String =>
102
+ v7().uuidV7At(timestamp);
103
+
104
+ export const uuidV7BytesAt = (
105
+ timestamp: number,
106
+ out?: Uint8Array,
107
+ offset?: number,
108
+ ): UuidSlugError | Uint8Array => v7().uuidV7BytesAt(timestamp, out, offset);
109
+
110
+ /**
111
+ * The alphabet is an argument here, exactly as it is on `uuidToSlug(uuid, alphabet)`, because
112
+ * choosing it needs no key: without it the only way to GENERATE a base32hex slug was to build a
113
+ * codec, so the sortable form cost the whole masking machinery while the unsortable one was free.
114
+ * Positional and last, matching `uuidToSlug`, so the two spellings of "encode in this alphabet"
115
+ * do not diverge.
116
+ */
117
+ export function uuidV7Slug(alphabet: SlugAlphabet = "base64url"): UuidV7Slug {
118
+ // Gated on the ALPHABET, not merely on the hook's presence. The runtime's slug generator emits
119
+ // base64url and nothing else, so an ungated branch answers a base32hex request with a 22-char
120
+ // base64url string — and only Bun defines the hook, so vitest on Node cannot reach the branch at
121
+ // all and the entire suite stays green. `test/runtime.bun.test.ts` is what actually covers it.
122
+ // Probed per call rather than resolved once: resolving at module scope would reintroduce the
123
+ // eager work the lazy cell above exists to avoid.
124
+ //
125
+ // The gate is also where the two alphabets stop costing the same, which is worth knowing before
126
+ // standardising on the sortable one: measured on Bun 2026-08-12, base64url runs 17.0M/s and
127
+ // base32hex 4.2M/s. Not an encoder deficiency -- base64url is handed straight to the engine's
128
+ // own slug generator here, while base32hex must draw bytes and encode them in JavaScript. 4M
129
+ // ids/sec is ample for identifier issuance; the number is recorded so the 4x is not rediscovered
130
+ // as a mystery.
131
+ const native = alphabet === "base64url" ? runtime.uuidV7Slug : undefined;
132
+ if (native) return native();
133
+ // Asserted for the same reason `uuidV4Slug` asserts: the bytes come from a v7 generator and the
134
+ // encoder sees only bytes, so it returns the version-agnostic brand.
135
+ return errorOrThrow(formatUuidSlug(errorOrThrow(v7().uuidV7Bytes()), 0, alphabet)) as UuidV7Slug;
136
+ }
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { UuidSlugError } from "./errors";
4
+
5
+ // These tables and the four-bit checksum define the original wire format.
6
+ // Changing them would change the UUID recovered from an existing slug.
7
+ const PERMUTE = [9, 13, 3, 8, 14, 0, 11, 7, 6, 1, 15, 4, 2, 5, 10, 12] as const;
8
+ const XOR = [
9
+ 0xa2, 0x70, 0x32, 0x7f, 0x98, 0xb8, 0x9b, 0x5e, 0x1b, 0x26, 0xb6, 0x16, 0x96, 0xf9, 0xea, 0x3e,
10
+ ] as const;
11
+
12
+ /** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */
13
+ export function decodeOriginalMask(mixed: Uint8Array): Uint8Array | UuidSlugError | undefined {
14
+ if (mixed.length !== 16)
15
+ return new UuidSlugError("invalid_buffer", "Original masked slugs require 16 decoded bytes.");
16
+ const bytes = new Uint8Array(16);
17
+ for (let i = 0; i < 16; i++)
18
+ bytes[PERMUTE[i] as number] = (mixed[i] as number) ^ (XOR[i] as number);
19
+ const found = (bytes[6] as number) >>> 4;
20
+ bytes[6] = ((bytes[6] as number) & 15) | 0x70;
21
+ let checksum = 0;
22
+ for (const byte of bytes) checksum ^= byte;
23
+ // A mismatch is expected while trying formats; allocate diagnostics only if the reader fails.
24
+ return ((checksum >>> 4) ^ (checksum & 15)) === found ? bytes : undefined;
25
+ }
package/src/mask.ts CHANGED
@@ -1,95 +1,157 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { BASE64URL, decodeInto, encode, spareBits } from "./alphabet";
1
4
  import { UuidSlugError } from "./errors";
2
- import {
3
- formatUuid,
4
- isRfcVariant,
5
- parseUuid,
6
- slugToUuidBytes,
7
- uuidBytesToSlug,
8
- uuidVersion,
9
- } from "./uuid";
10
- import type {
11
- MaskSchema,
12
- MaskedUuidSlug,
13
- MaskedUuidV7Slug,
14
- UuidString,
15
- UuidV7String,
16
- } from "./types";
5
+ import { mix32, read32 } from "./feistel";
6
+ import { formatUuid } from "./uuid";
7
+ import type { MaskSchema, MaskedUuidV7Slug, UuidString } from "./types";
17
8
 
18
- function checksum4(bytes: Uint8Array): number {
19
- let acc = 0;
20
- for (const byte of bytes) acc ^= byte;
21
- return (acc >>> 4) ^ (acc & 0x0f);
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) {
20
+ return new UuidSlugError(
21
+ "invalid_mask_schema",
22
+ `Mask schema "${schema.id}" failed ${forward ? "encoding" : "decoding"}.`,
23
+ { cause },
24
+ );
25
+ }
22
26
  }
23
27
 
24
- function checksum6(bytes: Uint8Array): number {
28
+ /**
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.
34
+ */
35
+ function tagFor(bytes: Uint8Array, width: number) {
25
36
  let acc = 0;
26
- for (let i = 0; i < bytes.length; i += 1) acc = (acc + (bytes[i] ?? 0) * (i + 17)) & 0xff;
27
- return ((acc >>> 2) ^ acc) & 0x3f;
37
+ for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));
38
+ return acc >>> (32 - width);
28
39
  }
29
40
 
30
- function tagFor(bytes: Uint8Array, tagBits: 4 | 6) {
31
- return tagBits === 4 ? checksum4(bytes) : checksum6(bytes);
32
- }
33
-
34
- function injectTag(bytes: Uint8Array, tag: number, tagBits: 4 | 6) {
41
+ /**
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.
48
+ */
49
+ function injectTag(bytes: Uint8Array, tag: number) {
35
50
  bytes[6] = ((tag & 0x0f) << 4) | ((bytes[6] ?? 0) & 0x0f);
36
- if (tagBits === 6) bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] ?? 0) & 0x3f);
51
+ bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] ?? 0) & 0x3f);
52
+ bytes[0] = (((tag >>> 6) & 0x3f) << 2) | ((bytes[0] ?? 0) & 0x03);
37
53
  }
38
54
 
39
- function extractTag(bytes: Uint8Array, tagBits: 4 | 6) {
40
- const versionBits = (bytes[6] ?? 0) >>> 4;
41
- if (tagBits === 4) return versionBits;
42
- return versionBits | (((bytes[8] ?? 0) >>> 6) << 4);
55
+ function extractTag(bytes: Uint8Array) {
56
+ return ((bytes[6] ?? 0) >>> 4) | (((bytes[8] ?? 0) >>> 6) << 4) | (((bytes[0] ?? 0) >>> 2) << 6);
43
57
  }
44
58
 
45
- function restoreV7(bytes: Uint8Array, tagBits: 4 | 6) {
59
+ /** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
60
+ function restoreV7(bytes: Uint8Array) {
46
61
  bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70;
47
- if (tagBits === 6) bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
62
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
63
+ bytes[0] = (bytes[0] ?? 0) & 0x03;
48
64
  }
49
65
 
50
- export function uuidToMaskedSlugWithSchema(
51
- uuid: string,
52
- schema: MaskSchema,
53
- ): Error | MaskedUuidSlug {
54
- const raw = parseUuid(uuid);
55
- if (raw instanceof Error) return raw;
56
- if (uuidVersion(raw) !== 7 || !isRfcVariant(raw))
57
- return new UuidSlugError("invalid_uuid_version", "Masked UUID slugs currently require UUIDv7.");
58
- return uuidV7BytesToMaskedSlug(raw, schema);
59
- }
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;
68
+
69
+ /**
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.
73
+ */
74
+ const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
75
+ const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
60
76
 
61
77
  export function uuidV7BytesToMaskedSlug(
62
78
  raw: Uint8Array,
63
79
  schema: MaskSchema,
64
- ): Error | MaskedUuidV7Slug {
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)
84
+ 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.",
87
+ );
88
+ const tag = tagFor(raw, TAG_BITS);
65
89
  const tagged = new Uint8Array(raw);
66
- injectTag(tagged, tagFor(raw, schema.tagBits), schema.tagBits);
90
+ injectTag(tagged, tag >>> OUTER_TAG_BITS);
67
91
  const mixed = new Uint8Array(16);
68
- for (let i = 0; i < 16; i += 1)
69
- mixed[i] = (tagged[schema.permute[i] ?? 0] ?? 0) ^ (schema.xor[i] ?? 0);
70
- const slug = uuidBytesToSlug(mixed);
71
- return slug instanceof Error ? slug : (slug as MaskedUuidV7Slug);
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);
72
95
  }
73
96
 
74
- export function maskedSlugToUuidWithSchema(slug: string, schema: MaskSchema): Error | UuidString {
75
- const mixed = slugToUuidBytes(slug);
76
- if (mixed instanceof Error) return mixed;
77
- const unmixed = new Uint8Array(16);
78
- for (let i = 0; i < 16; i += 1) {
79
- const source = schema.inverse[i] ?? 0;
80
- unmixed[i] = (mixed[source] ?? 0) ^ (schema.xor[source] ?? 0);
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;
81
112
  }
82
- const foundTag = extractTag(unmixed, schema.tagBits);
83
- restoreV7(unmixed, schema.tagBits);
84
- if (tagFor(unmixed, schema.tagBits) !== foundTag)
85
- return new UuidSlugError("invalid_uuid_slug", "Masked UUID slug failed schema validation.");
86
- return formatUuid(unmixed);
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
+ );
87
118
  }
88
119
 
89
- export function maskedSlugToUuidV7WithSchema(
90
- slug: string,
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;
138
+ }
139
+ }
140
+ return candidates;
141
+ }
142
+
143
+ function unmix(
144
+ mixed: Uint8Array,
145
+ outerTag: number,
91
146
  schema: MaskSchema,
92
- ): Error | UuidV7String {
93
- const uuid = maskedSlugToUuidWithSchema(slug, schema);
94
- return uuid instanceof Error ? uuid : (uuid as UuidV7String);
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;
95
157
  }