@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/schema.ts CHANGED
@@ -1,123 +1,300 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import { UuidSlugError } from "./errors";
2
- import type { ExplicitMaskSchema, MaskSchema, MaskSchemaOptions } from "./types";
4
+ import { FEISTEL_KEY_WORDS, feistel16 } from "./feistel";
5
+ import { halfSipHash } from "./siphash";
6
+ import type { HashContinuation } from "./siphash";
7
+ import { yieldToHost } from "./yield";
8
+ import type { AsyncMaskSchemaOptions, MaskSchema, MaskSchemaOptions } from "./types";
9
+
10
+ /** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
11
+ const SEED_MIN_BYTES = 16;
12
+
13
+ /** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
14
+ const MAX_KEY_ITERATIONS = 1 << 24;
3
15
 
4
- const LEGACY_PERMUTE = Uint8Array.from([9, 13, 3, 8, 14, 0, 11, 7, 6, 1, 15, 4, 2, 5, 10, 12]);
5
- const LEGACY_XOR = Uint8Array.from([
6
- 0xa2, 0x70, 0x32, 0x7f, 0x98, 0xb8, 0x9b, 0x5e, 0x1b, 0x26, 0xb6, 0x16, 0x96, 0xf9, 0xea, 0x3e,
7
- ]);
16
+ /**
17
+ * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
18
+ * "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
19
+ *
20
+ * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
21
+ * seed different round keys and make every masked slug ever issued undecodable.
22
+ */
23
+ const CHAIN_A_KEY1 = 0x41676c73;
24
+ const CHAIN_B_KEY1 = 0x42676c73;
25
+ const CHAIN_KEY0 = 0x64697575;
8
26
 
9
- function clone16(bytes: Uint8Array, name: string): Error | Uint8Array {
10
- if (bytes.length !== 16)
11
- return new UuidSlugError("invalid_mask_schema", `${name} must contain exactly 16 bytes.`);
12
- return new Uint8Array(bytes);
27
+ function seedBytes(seed: string | Uint8Array) {
28
+ if (typeof seed !== "string") return new Uint8Array(seed);
29
+ return new TextEncoder().encode(seed);
13
30
  }
14
31
 
15
- function inversePermutation(permute: Uint8Array): Error | Uint8Array {
16
- if (permute.length !== 16)
17
- return new UuidSlugError("invalid_mask_schema", "Permutation must contain exactly 16 bytes.");
18
- const seen = new Uint8Array(16);
19
- const inverse = new Uint8Array(16);
20
- for (let i = 0; i < 16; i += 1) {
21
- const value = permute[i] ?? 255;
22
- if (value > 15 || seen[value] === 1)
23
- return new UuidSlugError(
24
- "invalid_mask_schema",
25
- "Permutation must be a bijection over 0..15.",
26
- );
27
- seen[value] = 1;
28
- inverse[value] = i;
29
- }
30
- return inverse;
32
+ /** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
33
+ function seedWords(seed: Uint8Array) {
34
+ const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
35
+ writeSeedWords(seed, words);
36
+ return words;
31
37
  }
32
38
 
33
- function fnv1a64(data: Uint8Array) {
34
- let hash = 0xcbf29ce484222325n;
35
- for (const byte of data) {
36
- hash ^= BigInt(byte);
37
- hash = BigInt.asUintN(64, hash * 0x100000001b3n);
39
+ /** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
40
+ function writeSeedWords(
41
+ seed: Uint8Array,
42
+ words: Int32Array,
43
+ offset = 0,
44
+ start = 0,
45
+ end = seed.length,
46
+ ) {
47
+ for (let index = start; index < end; index += 1) {
48
+ const absolute = offset + index;
49
+ words[absolute >>> 2] =
50
+ (words[absolute >>> 2] as number) | ((seed[index] as number) << ((absolute & 3) * 8));
38
51
  }
39
- return hash;
40
52
  }
41
53
 
42
- function seedBytes(seed: string | Uint8Array) {
43
- if (typeof seed !== "string") return new Uint8Array(seed);
44
- return new TextEncoder().encode(seed);
54
+ /**
55
+ * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
56
+ * at construction, never per id. The count changes key material and must remain stable for
57
+ * issued slugs; retain the old count with its seed when rotating schemas.
58
+ */
59
+ function chain(key0: number, key1: number, words: Int32Array, length: number, iterations: number) {
60
+ const out = new Int32Array(2);
61
+ halfSipHash(key0, key1, words, length, out);
62
+ for (let i = 1; i < iterations; i += 1)
63
+ halfSipHash(out[0] as number, out[1] as number, words, length, out);
64
+ return out;
65
+ }
66
+
67
+ /**
68
+ * Derive each round key by XORing outputs from two fixed derivation chains. Their combined
69
+ * state is 128 bits; that representation does not establish 128-bit security. Chain constants,
70
+ * word indices and byte order are frozen by the issued wire format.
71
+ */
72
+ function derivedKeys(seed: Uint8Array, iterations: number) {
73
+ const words = seedWords(seed);
74
+ const chainA = chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations);
75
+ const chainB = chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations);
76
+ return roundKeys(chainA, chainB);
45
77
  }
46
78
 
47
- function next64(state: { value: bigint }) {
48
- state.value ^= state.value << 13n;
49
- state.value ^= state.value >> 7n;
50
- state.value ^= state.value << 17n;
51
- state.value = BigInt.asUintN(64, state.value);
52
- return state.value;
79
+ /** The same final key expansion follows synchronous and cooperative derivation. */
80
+ function roundKeys(chainA: Int32Array, chainB: Int32Array) {
81
+ const keys = new Int32Array(FEISTEL_KEY_WORDS);
82
+ const index = new Int32Array(1);
83
+ const fromA = new Int32Array(2);
84
+ const fromB = new Int32Array(2);
85
+ for (let word = 0; word < FEISTEL_KEY_WORDS; word += 2) {
86
+ index[0] = word;
87
+ halfSipHash(chainA[0] as number, chainA[1] as number, index, 4, fromA);
88
+ halfSipHash(chainB[0] as number, chainB[1] as number, index, 4, fromB);
89
+ keys[word] = (fromA[0] as number) ^ (fromB[0] as number);
90
+ keys[word + 1] = (fromA[1] as number) ^ (fromB[1] as number);
91
+ }
92
+ return keys;
93
+ }
94
+
95
+ function feistelSchema(id: string, seed: Uint8Array, iterations: number): MaskSchema {
96
+ return schemaFromKeys(id, derivedKeys(seed, iterations));
53
97
  }
54
98
 
55
- function derivedBytes(seed: Uint8Array, purpose: number, length: number) {
56
- const state = {
57
- value: fnv1a64(Uint8Array.from([...seed, purpose])) || 0x9e3779b97f4a7c15n,
99
+ function schemaFromKeys(id: string, keys: Int32Array): MaskSchema {
100
+ return {
101
+ id,
102
+ mix(input, output, forward) {
103
+ feistel16(input, 0, keys, forward, output, 0);
104
+ },
58
105
  };
59
- const out = new Uint8Array(length);
60
- for (let i = 0; i < length; i += 1)
61
- out[i] = Number((next64(state) >> BigInt((i % 8) * 8)) & 0xffn);
62
- return out;
63
106
  }
64
107
 
65
- function derivedPermutation(seed: Uint8Array) {
66
- const random = derivedBytes(seed, 2, 64);
67
- const permute = Uint8Array.from({ length: 16 }, (_, i) => i);
68
- let cursor = 0;
69
- for (let i = 15; i > 0; i -= 1) {
70
- const j = (random[cursor] ?? 0) % (i + 1);
71
- cursor += 1;
72
- const tmp = permute[i] ?? 0;
73
- permute[i] = permute[j] ?? 0;
74
- permute[j] = tmp;
75
- }
76
- return permute;
108
+ export function createMaskSchema(options: MaskSchemaOptions): UuidSlugError | MaskSchema {
109
+ const seed = seedBytes(options.seed);
110
+ const short = invalidSeedLength(seed.length);
111
+ if (short) return short;
112
+ const iterations = options.keyIterations ?? 1;
113
+ const invalid = invalidIterations(iterations);
114
+ if (invalid) return invalid;
115
+ return feistelSchema(options.id ?? "seeded", seed, iterations);
116
+ }
117
+
118
+ function invalidSeedLength(length: number): UuidSlugError | undefined {
119
+ if (length < SEED_MIN_BYTES)
120
+ return new UuidSlugError(
121
+ "invalid_mask_schema",
122
+ `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.`,
123
+ );
124
+ return undefined;
77
125
  }
78
126
 
79
- function completeSchema(
80
- id: string,
81
- xorInput: Uint8Array,
82
- permuteInput: Uint8Array,
83
- tagBits: 4 | 6,
84
- ): Error | MaskSchema {
85
- const xor = clone16(xorInput, "XOR mask");
86
- if (xor instanceof Error) return xor;
87
- const permute = clone16(permuteInput, "Permutation");
88
- if (permute instanceof Error) return permute;
89
- const inverse = inversePermutation(permute);
90
- if (inverse instanceof Error) return inverse;
91
- return { id, inverse, permute, tagBits, xor };
127
+ function invalidIterations(iterations: number): UuidSlugError | undefined {
128
+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS)
129
+ return new UuidSlugError(
130
+ "invalid_mask_schema",
131
+ `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`,
132
+ );
133
+ return undefined;
92
134
  }
93
135
 
94
- export const LEGACY_MASK_SCHEMA_V1: MaskSchema = completeSchema(
95
- "legacy-mask-v1",
96
- LEGACY_XOR,
97
- LEGACY_PERMUTE,
98
- 4,
99
- ) as MaskSchema;
136
+ /** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
137
+ const CHUNK_BYTES = 4096;
100
138
 
101
- export function defineMaskSchema(schema: ExplicitMaskSchema): Error | MaskSchema {
102
- return completeSchema(schema.id ?? "explicit", schema.xor, schema.permute, schema.tagBits);
139
+ function* cooperativeChain(
140
+ key0: number,
141
+ key1: number,
142
+ words: Int32Array,
143
+ length: number,
144
+ iterations: number,
145
+ ): Generator<void, Int32Array, void> {
146
+ const out = new Int32Array(2);
147
+ out[0] = key0;
148
+ out[1] = key1;
149
+ const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
150
+ let sinceCheckpoint = 0;
151
+ for (let i = 0; i < iterations; i += 1) {
152
+ let continuation: HashContinuation | undefined;
153
+ do {
154
+ continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
155
+ if (continuation) yield;
156
+ } while (continuation);
157
+ sinceCheckpoint += 1;
158
+ if (sinceCheckpoint >= hashesPerChunk) {
159
+ sinceCheckpoint = 0;
160
+ yield;
161
+ }
162
+ }
163
+ return out;
103
164
  }
104
165
 
105
- export function createMaskSchema(options: MaskSchemaOptions): Error | MaskSchema {
106
- const seed = seedBytes(options.seed);
107
- if (seed.length === 0)
108
- return new UuidSlugError("invalid_mask_schema", "Mask seed must not be empty.");
109
- const tagBits = options.tagBits ?? 6;
110
- if (tagBits !== 4 && tagBits !== 6)
111
- return new UuidSlugError("invalid_mask_schema", "Mask tagBits must be 4 or 6.");
112
- return completeSchema(
113
- options.id ?? "seeded",
114
- derivedBytes(seed, 1, 16),
115
- derivedPermutation(seed),
116
- tagBits,
117
- );
166
+ function* cooperativeKeys(
167
+ seed: string | Uint8Array,
168
+ iterations: number,
169
+ ): Generator<void, Int32Array | UuidSlugError, void> {
170
+ // Byte seeds were snapshotted before suspension. Strings are immutable, so encoding can yield.
171
+ const chunks: Uint8Array[] = [];
172
+ let length = 0;
173
+ if (typeof seed === "string") {
174
+ const encoder = new TextEncoder();
175
+ for (let start = 0; start < seed.length;) {
176
+ let end = Math.min(seed.length, start + CHUNK_BYTES);
177
+ // Do not split a surrogate pair: encoding either half alone would substitute U+FFFD.
178
+ const last = seed.charCodeAt(end - 1);
179
+ const next = seed.charCodeAt(end);
180
+ if (end < seed.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)
181
+ end -= 1;
182
+ const bytes = encoder.encode(seed.slice(start, end));
183
+ chunks.push(bytes);
184
+ length += bytes.length;
185
+ start = end;
186
+ yield;
187
+ }
188
+ } else {
189
+ chunks.push(seed);
190
+ length = seed.length;
191
+ }
192
+ const short = invalidSeedLength(length);
193
+ if (short) return short;
194
+ const words = new Int32Array(Math.ceil(length / 4) + 1);
195
+ let offset = 0;
196
+ for (const bytes of chunks) {
197
+ for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
198
+ writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
199
+ yield;
200
+ }
201
+ offset += bytes.length;
202
+ }
203
+ chunks.length = 0;
204
+ const chainA = yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations);
205
+ const chainB = yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations);
206
+ return roundKeys(chainA, chainB);
207
+ }
208
+
209
+ /**
210
+ * Derive the same schema while allowing other host tasks to run. Options and byte contents are
211
+ * captured before suspension; cancellation returns an `aborted` error with the signal's reason
212
+ * as its cause. Checkpoints stop computation rather than racing a still-running derivation.
213
+ *
214
+ * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
215
+ * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
216
+ * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
217
+ */
218
+ export async function createMaskSchemaAsync(
219
+ options: AsyncMaskSchemaOptions,
220
+ ): Promise<MaskSchema | UuidSlugError> {
221
+ try {
222
+ const { signal } = options;
223
+ const aborted = () =>
224
+ new UuidSlugError("aborted", "Mask schema construction was aborted.", {
225
+ cause: signal?.reason,
226
+ });
227
+ if (signal?.aborted) return aborted();
228
+ const { seed: input, keyIterations = 1, id = "seeded" } = options;
229
+ const invalid = invalidIterations(keyIterations);
230
+ if (invalid) return invalid;
231
+ const seed = typeof input === "string" ? input : new Uint8Array(input);
232
+ const steps = cooperativeKeys(seed, keyIterations);
233
+ let deadline = performance.now() + 2;
234
+ while (true) {
235
+ if (signal?.aborted) {
236
+ const failure = aborted();
237
+ steps.return(failure);
238
+ return failure;
239
+ }
240
+ const step = steps.next();
241
+ if (step.done)
242
+ return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);
243
+ if (performance.now() >= deadline) {
244
+ // eslint-disable-next-line no-await-in-loop -- each slice must yield before continuing the dependent derivation
245
+ await yieldToHost();
246
+ deadline = performance.now() + 2;
247
+ }
248
+ }
249
+ } catch (cause) {
250
+ return new UuidSlugError("invalid_mask_schema", "Mask schema construction failed.", { cause });
251
+ }
118
252
  }
119
253
 
120
- export const DEFAULT_MASK_SCHEMA: MaskSchema = createMaskSchema({
121
- id: "default",
122
- seed: "anizoptera.uuid-slug.default-mask.v1",
123
- }) as MaskSchema;
254
+ /**
255
+ * Refuse schemas that cannot undo these representative blocks. The reverse call must invert
256
+ * the forward call; the same function need not be an involution. Finite probes are not a proof
257
+ * over the full domain. Preserve each original input separately so a mutating callback cannot
258
+ * rewrite the witness and make a destructive transformation appear reversible.
259
+ */
260
+ export function verifyInvertible(schema: MaskSchema): UuidSlugError | MaskSchema {
261
+ const mixed = new Uint8Array(16);
262
+ const restored = new Uint8Array(16);
263
+ for (const probe of [new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {
264
+ try {
265
+ schema.mix(probe.slice(), mixed, true);
266
+ schema.mix(mixed, restored, false);
267
+ } catch (cause) {
268
+ return new UuidSlugError(
269
+ "invalid_mask_schema",
270
+ `Mask schema "${schema.id}" failed its invertibility check.`,
271
+ { cause },
272
+ );
273
+ }
274
+ if (restored.some((byte, i) => byte !== probe[i]))
275
+ return new UuidSlugError(
276
+ "invalid_mask_schema",
277
+ `Mask schema "${schema.id}" does not reverse its own mixing step.`,
278
+ );
279
+ }
280
+ return schema;
281
+ }
282
+
283
+ /**
284
+ * A PUBLIC key. It ships in the tarball, so every masked slug produced under it is decodable by
285
+ * anyone who installed this package, and it therefore provides none of the obscurity masking
286
+ * exists for.
287
+ *
288
+ * It is exported rather than hidden so that choosing it can be DELIBERATE: a test or demo wanting
289
+ * byte-identical output across machines writes `mask: DEFAULT_MASK_SCHEMA` and says so at the call
290
+ * site. The hazard is the SILENT path — `createUuidSlugCodec()` with no `mask` lands here without
291
+ * the caller writing anything — which is why that fallback and `defaultCodec` both carry the same
292
+ * warning, and why the masked methods are not exported as bare functions.
293
+ */
294
+ const DEFAULT_SEED = "anizoptera.uuid-slug.default-mask.v1";
295
+
296
+ // Built from `feistelSchema` rather than through `createMaskSchema`, whose failures are a short seed and a
297
+ // bad iteration count — checks on CALLER input that the literals here cannot fail. Routing through it would return
298
+ // `UuidSlugError | MaskSchema` and force a cast that, at module scope, could only ever hide a real Error
299
+ // behind a `MaskSchema` type for every default codec in the process.
300
+ export const DEFAULT_MASK_SCHEMA: MaskSchema = feistelSchema("default", seedBytes(DEFAULT_SEED), 1);
package/src/siphash.ts ADDED
@@ -0,0 +1,127 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /**
4
+ * HalfSipHash-2-4 with 64-bit output — the 32-bit-word member of the SipHash family (Aumasson and
5
+ * Bernstein), transcribed from the reference implementation. It is a KEYED pseudorandom function:
6
+ * without the key its output on a chosen input is not computable, which is exactly what `mix32` — a
7
+ * fixed, public, unkeyed bijection — could never be, and the reason it replaced it.
8
+ *
9
+ * One primitive serves both callers that need one: the Feistel round function (`feistel.ts`) and the
10
+ * key derivation (`schema.ts`). Neither justifies its own.
11
+ *
12
+ * Chosen over full SipHash-2-4 because that is defined over 64-bit words, which JavaScript has only
13
+ * as `BigInt` or as hand-emulated 32-bit pairs — the first far too slow for a hot path, the second a
14
+ * re-implementation whose errors nothing would catch. HalfSipHash is 32-bit BY SPECIFICATION, so
15
+ * this is a transcription, and `test/siphash.test.ts` holds it to all 64 published vectors. That
16
+ * external check is the whole reason a standard primitive beat anything tuned here: nothing in this
17
+ * repository can grade a mixing function (see `feistel.ts` — every instrument here passes a
18
+ * two-round network), so agreement with a specification somebody else wrote is the only evidence
19
+ * available that can actually fail.
20
+ *
21
+ * Its key is 64 bits. `schema.ts` runs two independently keyed instances and XORs them, the standard
22
+ * cascade for widening a PRF's key; see there.
23
+ */
24
+
25
+ /** Message-absorption rounds per block — the `2` of HalfSipHash-**2**-4. */
26
+ const C_ROUNDS = 2;
27
+ /** Finalisation rounds per output word — the `4` of HalfSipHash-2-**4**. */
28
+ const D_ROUNDS = 4;
29
+
30
+ /** Private continuation: resume only with the same message, keys, byte length and output. */
31
+ export interface HashContinuation {
32
+ readonly block: number;
33
+ readonly v0: number;
34
+ readonly v1: number;
35
+ readonly v2: number;
36
+ readonly v3: number;
37
+ }
38
+
39
+ /**
40
+ * HalfSipHash-2-4 over a message supplied as 32-bit LITTLE-ENDIAN words, writing the two output
41
+ * words into `out`.
42
+ *
43
+ * Words rather than bytes because both callers already hold words, and the specification absorbs the
44
+ * message in 32-bit little-endian blocks regardless — so this is the same function with the byte
45
+ * reassembly left to whoever actually has bytes. Taking a `Uint8Array` would make the hot path pack
46
+ * bytes it had just unpacked.
47
+ *
48
+ * `byteLength` is the message length the specification hashes and stamps into the final block.
49
+ * `words` must therefore hold `ceil(byteLength / 4)` entries, with any trailing 1-3 bytes packed
50
+ * little-endian into the low bytes of the last one. Internal cooperative callers may pass a
51
+ * positive block limit and resume the returned continuation with exactly the same inputs.
52
+ */
53
+ export function halfSipHash(
54
+ key0: number,
55
+ key1: number,
56
+ words: Int32Array,
57
+ byteLength: number,
58
+ out: Int32Array,
59
+ continuation?: HashContinuation,
60
+ blockLimit = Infinity,
61
+ ): HashContinuation | undefined {
62
+ let v0 = key0 | 0;
63
+ let v1 = (key1 ^ 0xee) | 0;
64
+ let v2 = (key0 ^ 0x6c796765) | 0;
65
+ let v3 = (key1 ^ 0x74656462) | 0;
66
+ if (continuation) ({ v0, v1, v2, v3 } = continuation);
67
+
68
+ // The length-stamped final block is absorbed exactly like a message block, so it rides the same
69
+ // loop rather than a second copy of it. Seeds may end mid-word; mask blocks use whole words.
70
+ // The reference vectors exercise every tail length, including an empty message.
71
+ const fullWords = byteLength >>> 2;
72
+ const spare = byteLength & 3;
73
+ const tail = spare === 0 ? 0 : (words[fullWords] as number) & ((1 << (spare * 8)) - 1);
74
+ const lengthBlock = (byteLength << 24) | tail | 0;
75
+ const start = continuation?.block ?? 0;
76
+ const end = blockLimit === Infinity ? fullWords : Math.min(fullWords, start + blockLimit - 1);
77
+ for (let block = start; block <= end; block += 1) {
78
+ const m = block === fullWords ? lengthBlock : (words[block] as number);
79
+ v3 ^= m;
80
+ for (let round = 0; round < C_ROUNDS; round += 1) {
81
+ v0 = (v0 + v1) | 0;
82
+ v1 = (v1 << 5) | (v1 >>> 27);
83
+ v1 ^= v0;
84
+ v0 = (v0 << 16) | (v0 >>> 16);
85
+ v2 = (v2 + v3) | 0;
86
+ v3 = (v3 << 8) | (v3 >>> 24);
87
+ v3 ^= v2;
88
+ v0 = (v0 + v3) | 0;
89
+ v3 = (v3 << 7) | (v3 >>> 25);
90
+ v3 ^= v0;
91
+ v2 = (v2 + v1) | 0;
92
+ v1 = (v1 << 13) | (v1 >>> 19);
93
+ v1 ^= v2;
94
+ v2 = (v2 << 16) | (v2 >>> 16);
95
+ }
96
+ v0 ^= m;
97
+ }
98
+
99
+ // No output is published until absorption and finalisation are complete. The synchronous
100
+ // hot path has an unlimited block budget and never allocates a continuation.
101
+ if (end < fullWords) return { block: end + 1, v0, v1, v2, v3 };
102
+
103
+ // Two squeezes, and the `0xdd` between them is what makes the second output word something other
104
+ // than a rerun of the first.
105
+ v2 ^= 0xee;
106
+ for (let half = 0; half < 2; half += 1) {
107
+ for (let round = 0; round < D_ROUNDS; round += 1) {
108
+ v0 = (v0 + v1) | 0;
109
+ v1 = (v1 << 5) | (v1 >>> 27);
110
+ v1 ^= v0;
111
+ v0 = (v0 << 16) | (v0 >>> 16);
112
+ v2 = (v2 + v3) | 0;
113
+ v3 = (v3 << 8) | (v3 >>> 24);
114
+ v3 ^= v2;
115
+ v0 = (v0 + v3) | 0;
116
+ v3 = (v3 << 7) | (v3 >>> 25);
117
+ v3 ^= v0;
118
+ v2 = (v2 + v1) | 0;
119
+ v1 = (v1 << 13) | (v1 >>> 19);
120
+ v1 ^= v2;
121
+ v2 = (v2 << 16) | (v2 >>> 16);
122
+ }
123
+ out[half] = v1 ^ v3;
124
+ v1 ^= 0xdd;
125
+ }
126
+ return undefined;
127
+ }