@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.
- package/README.md +381 -27
- package/dist/alphabet.d.ts +21 -0
- package/dist/alphabet.d.ts.map +1 -0
- package/dist/alphabet.js +132 -0
- package/dist/alphabet.js.map +1 -0
- package/dist/base64url.d.ts +20 -0
- package/dist/base64url.d.ts.map +1 -0
- package/dist/base64url.js +33 -0
- package/dist/base64url.js.map +1 -0
- package/dist/codec.d.ts +17 -0
- package/dist/codec.d.ts.map +1 -0
- package/dist/codec.js +192 -0
- package/dist/codec.js.map +1 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -0
- package/dist/feistel.js +105 -0
- package/dist/feistel.js.map +1 -0
- package/dist/index.d.ts +11 -168
- package/dist/index.js +10 -649
- package/dist/keyless.d.ts +31 -0
- package/dist/keyless.d.ts.map +1 -0
- package/dist/keyless.js +93 -0
- package/dist/keyless.js.map +1 -0
- package/dist/legacy-mask.js +55 -0
- package/dist/legacy-mask.js.map +1 -0
- package/dist/mask.js +108 -0
- package/dist/mask.js.map +1 -0
- package/dist/migration.js +66 -0
- package/dist/migration.js.map +1 -0
- package/dist/node/alphabet.js +130 -0
- package/dist/node/base64url.js +31 -0
- package/dist/node/codec.js +190 -0
- package/dist/node/errors.js +78 -0
- package/dist/node/feistel.js +103 -0
- package/dist/node/index.js +10 -647
- package/dist/node/keyless.js +91 -0
- package/dist/node/legacy-mask.js +53 -0
- package/dist/node/mask.js +106 -0
- package/dist/node/migration.js +64 -0
- package/dist/node/runtime/node.js +33 -0
- package/dist/node/runtime/pool.js +53 -0
- package/dist/node/schema.js +214 -0
- package/dist/node/siphash.js +106 -0
- package/dist/node/uuid.js +226 -0
- package/dist/node/v7.js +185 -0
- package/dist/node/yield.js +20 -0
- package/dist/runtime/pool.js +55 -0
- package/dist/runtime/pool.js.map +1 -0
- package/dist/runtime/web.js +39 -0
- package/dist/runtime/web.js.map +1 -0
- package/dist/schema.d.ts +20 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +216 -0
- package/dist/schema.js.map +1 -0
- package/dist/siphash.js +108 -0
- package/dist/siphash.js.map +1 -0
- package/dist/types.d.ts +255 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/uuid.d.ts +78 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +228 -0
- package/dist/uuid.js.map +1 -0
- package/dist/v7.d.ts +12 -0
- package/dist/v7.d.ts.map +1 -0
- package/dist/v7.js +187 -0
- package/dist/v7.js.map +1 -0
- package/dist/yield.js +22 -0
- package/dist/yield.js.map +1 -0
- package/package.json +8 -12
- package/src/alphabet.ts +187 -0
- package/src/base64url.ts +28 -63
- package/src/codec.ts +227 -125
- package/src/errors.ts +83 -9
- package/src/feistel.ts +128 -0
- package/src/index.ts +52 -26
- package/src/keyless.ts +136 -0
- package/src/legacy-mask.ts +25 -0
- package/src/mask.ts +129 -67
- package/src/migration.ts +104 -0
- package/src/runtime/bun.ts +49 -24
- package/src/runtime/node.ts +33 -15
- package/src/runtime/pool.ts +62 -0
- package/src/runtime/types.ts +42 -5
- package/src/runtime/web.ts +37 -9
- package/src/schema.ts +274 -97
- package/src/siphash.ts +127 -0
- package/src/types.ts +221 -37
- package/src/uuid.ts +189 -50
- package/src/v7.ts +217 -45
- package/src/yield.ts +22 -0
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/web/index.js +0 -648
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;iBA2GgB,iBAAiB,SAAS,oBAAoB,gBAAgB;;;;;;;;;;iBA8GxD,sBACpB,SAAS,yBACR,QAAQ,aAAa;cAgFX,qBAAqB"}
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidSlugError } from "./errors.js";
|
|
4
|
+
import { halfSipHash } from "./siphash.js";
|
|
5
|
+
import { feistel16 } from "./feistel.js";
|
|
6
|
+
import { yieldToHost } from "./yield.js";
|
|
7
|
+
//#region src/schema.ts
|
|
8
|
+
/** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
|
|
9
|
+
const SEED_MIN_BYTES = 16;
|
|
10
|
+
/** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
|
|
11
|
+
const MAX_KEY_ITERATIONS = 1 << 24;
|
|
12
|
+
/**
|
|
13
|
+
* Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
|
|
14
|
+
* "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
|
|
15
|
+
*
|
|
16
|
+
* Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
|
|
17
|
+
* seed different round keys and make every masked slug ever issued undecodable.
|
|
18
|
+
*/
|
|
19
|
+
const CHAIN_A_KEY1 = 1097297011;
|
|
20
|
+
const CHAIN_B_KEY1 = 1114074227;
|
|
21
|
+
const CHAIN_KEY0 = 1684632949;
|
|
22
|
+
function seedBytes(seed) {
|
|
23
|
+
if (typeof seed !== "string") return new Uint8Array(seed);
|
|
24
|
+
return new TextEncoder().encode(seed);
|
|
25
|
+
}
|
|
26
|
+
/** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
|
|
27
|
+
function seedWords(seed) {
|
|
28
|
+
const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
|
|
29
|
+
writeSeedWords(seed, words);
|
|
30
|
+
return words;
|
|
31
|
+
}
|
|
32
|
+
/** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
|
|
33
|
+
function writeSeedWords(seed, words, offset = 0, start = 0, end = seed.length) {
|
|
34
|
+
for (let index = start; index < end; index += 1) {
|
|
35
|
+
const absolute = offset + index;
|
|
36
|
+
words[absolute >>> 2] = words[absolute >>> 2] | seed[index] << (absolute & 3) * 8;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
|
|
41
|
+
* at construction, never per id. The count changes key material and must remain stable for
|
|
42
|
+
* issued slugs; retain the old count with its seed when rotating schemas.
|
|
43
|
+
*/
|
|
44
|
+
function chain(key0, key1, words, length, iterations) {
|
|
45
|
+
const out = /* @__PURE__ */ new Int32Array(2);
|
|
46
|
+
halfSipHash(key0, key1, words, length, out);
|
|
47
|
+
for (let i = 1; i < iterations; i += 1) halfSipHash(out[0], out[1], words, length, out);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Derive each round key by XORing outputs from two fixed derivation chains. Their combined
|
|
52
|
+
* state is 128 bits; that representation does not establish 128-bit security. Chain constants,
|
|
53
|
+
* word indices and byte order are frozen by the issued wire format.
|
|
54
|
+
*/
|
|
55
|
+
function derivedKeys(seed, iterations) {
|
|
56
|
+
const words = seedWords(seed);
|
|
57
|
+
return roundKeys(chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations), chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations));
|
|
58
|
+
}
|
|
59
|
+
/** The same final key expansion follows synchronous and cooperative derivation. */
|
|
60
|
+
function roundKeys(chainA, chainB) {
|
|
61
|
+
const keys = /* @__PURE__ */ new Int32Array(8);
|
|
62
|
+
const index = /* @__PURE__ */ new Int32Array(1);
|
|
63
|
+
const fromA = /* @__PURE__ */ new Int32Array(2);
|
|
64
|
+
const fromB = /* @__PURE__ */ new Int32Array(2);
|
|
65
|
+
for (let word = 0; word < 8; word += 2) {
|
|
66
|
+
index[0] = word;
|
|
67
|
+
halfSipHash(chainA[0], chainA[1], index, 4, fromA);
|
|
68
|
+
halfSipHash(chainB[0], chainB[1], index, 4, fromB);
|
|
69
|
+
keys[word] = fromA[0] ^ fromB[0];
|
|
70
|
+
keys[word + 1] = fromA[1] ^ fromB[1];
|
|
71
|
+
}
|
|
72
|
+
return keys;
|
|
73
|
+
}
|
|
74
|
+
function feistelSchema(id, seed, iterations) {
|
|
75
|
+
return schemaFromKeys(id, derivedKeys(seed, iterations));
|
|
76
|
+
}
|
|
77
|
+
function schemaFromKeys(id, keys) {
|
|
78
|
+
return {
|
|
79
|
+
id,
|
|
80
|
+
mix(input, output, forward) {
|
|
81
|
+
feistel16(input, 0, keys, forward, output, 0);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function createMaskSchema(options) {
|
|
86
|
+
const seed = seedBytes(options.seed);
|
|
87
|
+
const short = invalidSeedLength(seed.length);
|
|
88
|
+
if (short) return short;
|
|
89
|
+
const iterations = options.keyIterations ?? 1;
|
|
90
|
+
const invalid = invalidIterations(iterations);
|
|
91
|
+
if (invalid) return invalid;
|
|
92
|
+
return feistelSchema(options.id ?? "seeded", seed, iterations);
|
|
93
|
+
}
|
|
94
|
+
function invalidSeedLength(length) {
|
|
95
|
+
if (length < SEED_MIN_BYTES) return new UuidSlugError("invalid_mask_schema", `Mask seed must be at least ${SEED_MIN_BYTES} bytes, got ${length}. Generate one with \`openssl rand -base64 32\` rather than choosing it; a guessable seed hides nothing however long it is.`);
|
|
96
|
+
}
|
|
97
|
+
function invalidIterations(iterations) {
|
|
98
|
+
if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS) return new UuidSlugError("invalid_mask_schema", `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`);
|
|
99
|
+
}
|
|
100
|
+
/** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
|
|
101
|
+
const CHUNK_BYTES = 4096;
|
|
102
|
+
function* cooperativeChain(key0, key1, words, length, iterations) {
|
|
103
|
+
const out = /* @__PURE__ */ new Int32Array(2);
|
|
104
|
+
out[0] = key0;
|
|
105
|
+
out[1] = key1;
|
|
106
|
+
const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
|
|
107
|
+
let sinceCheckpoint = 0;
|
|
108
|
+
for (let i = 0; i < iterations; i += 1) {
|
|
109
|
+
let continuation;
|
|
110
|
+
do {
|
|
111
|
+
continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
|
|
112
|
+
if (continuation) yield;
|
|
113
|
+
} while (continuation);
|
|
114
|
+
sinceCheckpoint += 1;
|
|
115
|
+
if (sinceCheckpoint >= hashesPerChunk) {
|
|
116
|
+
sinceCheckpoint = 0;
|
|
117
|
+
yield;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
function* cooperativeKeys(seed, iterations) {
|
|
123
|
+
const chunks = [];
|
|
124
|
+
let length = 0;
|
|
125
|
+
if (typeof seed === "string") {
|
|
126
|
+
const encoder = new TextEncoder();
|
|
127
|
+
for (let start = 0; start < seed.length;) {
|
|
128
|
+
let end = Math.min(seed.length, start + CHUNK_BYTES);
|
|
129
|
+
const last = seed.charCodeAt(end - 1);
|
|
130
|
+
const next = seed.charCodeAt(end);
|
|
131
|
+
if (end < seed.length && last >= 55296 && last <= 56319 && next >= 56320 && next <= 57343) end -= 1;
|
|
132
|
+
const bytes = encoder.encode(seed.slice(start, end));
|
|
133
|
+
chunks.push(bytes);
|
|
134
|
+
length += bytes.length;
|
|
135
|
+
start = end;
|
|
136
|
+
yield;
|
|
137
|
+
}
|
|
138
|
+
} else {
|
|
139
|
+
chunks.push(seed);
|
|
140
|
+
length = seed.length;
|
|
141
|
+
}
|
|
142
|
+
const short = invalidSeedLength(length);
|
|
143
|
+
if (short) return short;
|
|
144
|
+
const words = new Int32Array(Math.ceil(length / 4) + 1);
|
|
145
|
+
let offset = 0;
|
|
146
|
+
for (const bytes of chunks) {
|
|
147
|
+
for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
|
|
148
|
+
writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
|
|
149
|
+
yield;
|
|
150
|
+
}
|
|
151
|
+
offset += bytes.length;
|
|
152
|
+
}
|
|
153
|
+
chunks.length = 0;
|
|
154
|
+
return roundKeys(yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations), yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Derive the same schema while allowing other host tasks to run. Options and byte contents are
|
|
158
|
+
* captured before suspension; cancellation returns an `aborted` error with the signal's reason
|
|
159
|
+
* as its cause. Checkpoints stop computation rather than racing a still-running derivation.
|
|
160
|
+
*
|
|
161
|
+
* Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
|
|
162
|
+
* not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
|
|
163
|
+
* need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
|
|
164
|
+
*/
|
|
165
|
+
async function createMaskSchemaAsync(options) {
|
|
166
|
+
try {
|
|
167
|
+
const { signal } = options;
|
|
168
|
+
const aborted = () => new UuidSlugError("aborted", "Mask schema construction was aborted.", { cause: signal?.reason });
|
|
169
|
+
if (signal?.aborted) return aborted();
|
|
170
|
+
const { seed: input, keyIterations = 1, id = "seeded" } = options;
|
|
171
|
+
const invalid = invalidIterations(keyIterations);
|
|
172
|
+
if (invalid) return invalid;
|
|
173
|
+
const steps = cooperativeKeys(typeof input === "string" ? input : new Uint8Array(input), keyIterations);
|
|
174
|
+
let deadline = performance.now() + 2;
|
|
175
|
+
while (true) {
|
|
176
|
+
if (signal?.aborted) {
|
|
177
|
+
const failure = aborted();
|
|
178
|
+
steps.return(failure);
|
|
179
|
+
return failure;
|
|
180
|
+
}
|
|
181
|
+
const step = steps.next();
|
|
182
|
+
if (step.done) return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);
|
|
183
|
+
if (performance.now() >= deadline) {
|
|
184
|
+
await yieldToHost();
|
|
185
|
+
deadline = performance.now() + 2;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} catch (cause) {
|
|
189
|
+
return new UuidSlugError("invalid_mask_schema", "Mask schema construction failed.", { cause });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Refuse schemas that cannot undo these representative blocks. The reverse call must invert
|
|
194
|
+
* the forward call; the same function need not be an involution. Finite probes are not a proof
|
|
195
|
+
* over the full domain. Preserve each original input separately so a mutating callback cannot
|
|
196
|
+
* rewrite the witness and make a destructive transformation appear reversible.
|
|
197
|
+
*/
|
|
198
|
+
function verifyInvertible(schema) {
|
|
199
|
+
const mixed = /* @__PURE__ */ new Uint8Array(16);
|
|
200
|
+
const restored = /* @__PURE__ */ new Uint8Array(16);
|
|
201
|
+
for (const probe of [/* @__PURE__ */ new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {
|
|
202
|
+
try {
|
|
203
|
+
schema.mix(probe.slice(), mixed, true);
|
|
204
|
+
schema.mix(mixed, restored, false);
|
|
205
|
+
} catch (cause) {
|
|
206
|
+
return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" failed its invertibility check.`, { cause });
|
|
207
|
+
}
|
|
208
|
+
if (restored.some((byte, i) => byte !== probe[i])) return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" does not reverse its own mixing step.`);
|
|
209
|
+
}
|
|
210
|
+
return schema;
|
|
211
|
+
}
|
|
212
|
+
const DEFAULT_MASK_SCHEMA = feistelSchema("default", seedBytes("anizoptera.uuid-slug.default-mask.v1"), 1);
|
|
213
|
+
//#endregion
|
|
214
|
+
export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync, verifyInvertible };
|
|
215
|
+
|
|
216
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { UuidSlugError } from \"./errors\";\nimport { FEISTEL_KEY_WORDS, feistel16 } from \"./feistel\";\nimport { halfSipHash } from \"./siphash\";\nimport type { HashContinuation } from \"./siphash\";\nimport { yieldToHost } from \"./yield\";\nimport type { AsyncMaskSchemaOptions, MaskSchema, MaskSchemaOptions } from \"./types\";\n\n/** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */\nconst SEED_MIN_BYTES = 16;\n\n/** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */\nconst MAX_KEY_ITERATIONS = 1 << 24;\n\n/**\n * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of\n * \"uuid\" with \"slgA\" and \"slgB\", so a reader can check they conceal no chosen structure.\n *\n * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every\n * seed different round keys and make every masked slug ever issued undecodable.\n */\nconst CHAIN_A_KEY1 = 0x41676c73;\nconst CHAIN_B_KEY1 = 0x42676c73;\nconst CHAIN_KEY0 = 0x64697575;\n\nfunction seedBytes(seed: string | Uint8Array) {\n if (typeof seed !== \"string\") return new Uint8Array(seed);\n return new TextEncoder().encode(seed);\n}\n\n/** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */\nfunction seedWords(seed: Uint8Array) {\n const words = new Int32Array(Math.ceil(seed.length / 4) + 1);\n writeSeedWords(seed, words);\n return words;\n}\n\n/** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */\nfunction writeSeedWords(\n seed: Uint8Array,\n words: Int32Array,\n offset = 0,\n start = 0,\n end = seed.length,\n) {\n for (let index = start; index < end; index += 1) {\n const absolute = offset + index;\n words[absolute >>> 2] =\n (words[absolute >>> 2] as number) | ((seed[index] as number) << ((absolute & 3) * 8));\n }\n}\n\n/**\n * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid\n * at construction, never per id. The count changes key material and must remain stable for\n * issued slugs; retain the old count with its seed when rotating schemas.\n */\nfunction chain(key0: number, key1: number, words: Int32Array, length: number, iterations: number) {\n const out = new Int32Array(2);\n halfSipHash(key0, key1, words, length, out);\n for (let i = 1; i < iterations; i += 1)\n halfSipHash(out[0] as number, out[1] as number, words, length, out);\n return out;\n}\n\n/**\n * Derive each round key by XORing outputs from two fixed derivation chains. Their combined\n * state is 128 bits; that representation does not establish 128-bit security. Chain constants,\n * word indices and byte order are frozen by the issued wire format.\n */\nfunction derivedKeys(seed: Uint8Array, iterations: number) {\n const words = seedWords(seed);\n const chainA = chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations);\n const chainB = chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations);\n return roundKeys(chainA, chainB);\n}\n\n/** The same final key expansion follows synchronous and cooperative derivation. */\nfunction roundKeys(chainA: Int32Array, chainB: Int32Array) {\n const keys = new Int32Array(FEISTEL_KEY_WORDS);\n const index = new Int32Array(1);\n const fromA = new Int32Array(2);\n const fromB = new Int32Array(2);\n for (let word = 0; word < FEISTEL_KEY_WORDS; word += 2) {\n index[0] = word;\n halfSipHash(chainA[0] as number, chainA[1] as number, index, 4, fromA);\n halfSipHash(chainB[0] as number, chainB[1] as number, index, 4, fromB);\n keys[word] = (fromA[0] as number) ^ (fromB[0] as number);\n keys[word + 1] = (fromA[1] as number) ^ (fromB[1] as number);\n }\n return keys;\n}\n\nfunction feistelSchema(id: string, seed: Uint8Array, iterations: number): MaskSchema {\n return schemaFromKeys(id, derivedKeys(seed, iterations));\n}\n\nfunction schemaFromKeys(id: string, keys: Int32Array): MaskSchema {\n return {\n id,\n mix(input, output, forward) {\n feistel16(input, 0, keys, forward, output, 0);\n },\n };\n}\n\nexport function createMaskSchema(options: MaskSchemaOptions): UuidSlugError | MaskSchema {\n const seed = seedBytes(options.seed);\n const short = invalidSeedLength(seed.length);\n if (short) return short;\n const iterations = options.keyIterations ?? 1;\n const invalid = invalidIterations(iterations);\n if (invalid) return invalid;\n return feistelSchema(options.id ?? \"seeded\", seed, iterations);\n}\n\nfunction invalidSeedLength(length: number): UuidSlugError | undefined {\n if (length < SEED_MIN_BYTES)\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask seed must be at least ${SEED_MIN_BYTES} bytes, got ${length}. Generate one with \\`openssl rand -base64 32\\` rather than choosing it; a guessable seed hides nothing however long it is.`,\n );\n return undefined;\n}\n\nfunction invalidIterations(iterations: number): UuidSlugError | undefined {\n if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS)\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`,\n );\n return undefined;\n}\n\n/** Bounded byte work between checkpoints, independent of total seed size or iteration count. */\nconst CHUNK_BYTES = 4096;\n\nfunction* cooperativeChain(\n key0: number,\n key1: number,\n words: Int32Array,\n length: number,\n iterations: number,\n): Generator<void, Int32Array, void> {\n const out = new Int32Array(2);\n out[0] = key0;\n out[1] = key1;\n const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));\n let sinceCheckpoint = 0;\n for (let i = 0; i < iterations; i += 1) {\n let continuation: HashContinuation | undefined;\n do {\n continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);\n if (continuation) yield;\n } while (continuation);\n sinceCheckpoint += 1;\n if (sinceCheckpoint >= hashesPerChunk) {\n sinceCheckpoint = 0;\n yield;\n }\n }\n return out;\n}\n\nfunction* cooperativeKeys(\n seed: string | Uint8Array,\n iterations: number,\n): Generator<void, Int32Array | UuidSlugError, void> {\n // Byte seeds were snapshotted before suspension. Strings are immutable, so encoding can yield.\n const chunks: Uint8Array[] = [];\n let length = 0;\n if (typeof seed === \"string\") {\n const encoder = new TextEncoder();\n for (let start = 0; start < seed.length;) {\n let end = Math.min(seed.length, start + CHUNK_BYTES);\n // Do not split a surrogate pair: encoding either half alone would substitute U+FFFD.\n const last = seed.charCodeAt(end - 1);\n const next = seed.charCodeAt(end);\n if (end < seed.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)\n end -= 1;\n const bytes = encoder.encode(seed.slice(start, end));\n chunks.push(bytes);\n length += bytes.length;\n start = end;\n yield;\n }\n } else {\n chunks.push(seed);\n length = seed.length;\n }\n const short = invalidSeedLength(length);\n if (short) return short;\n const words = new Int32Array(Math.ceil(length / 4) + 1);\n let offset = 0;\n for (const bytes of chunks) {\n for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {\n writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));\n yield;\n }\n offset += bytes.length;\n }\n chunks.length = 0;\n const chainA = yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations);\n const chainB = yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations);\n return roundKeys(chainA, chainB);\n}\n\n/**\n * Derive the same schema while allowing other host tasks to run. Options and byte contents are\n * captured before suspension; cancellation returns an `aborted` error with the signal's reason\n * as its cause. Checkpoints stop computation rather than racing a still-running derivation.\n *\n * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,\n * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations\n * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.\n */\nexport async function createMaskSchemaAsync(\n options: AsyncMaskSchemaOptions,\n): Promise<MaskSchema | UuidSlugError> {\n try {\n const { signal } = options;\n const aborted = () =>\n new UuidSlugError(\"aborted\", \"Mask schema construction was aborted.\", {\n cause: signal?.reason,\n });\n if (signal?.aborted) return aborted();\n const { seed: input, keyIterations = 1, id = \"seeded\" } = options;\n const invalid = invalidIterations(keyIterations);\n if (invalid) return invalid;\n const seed = typeof input === \"string\" ? input : new Uint8Array(input);\n const steps = cooperativeKeys(seed, keyIterations);\n let deadline = performance.now() + 2;\n while (true) {\n if (signal?.aborted) {\n const failure = aborted();\n steps.return(failure);\n return failure;\n }\n const step = steps.next();\n if (step.done)\n return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);\n if (performance.now() >= deadline) {\n // eslint-disable-next-line no-await-in-loop -- each slice must yield before continuing the dependent derivation\n await yieldToHost();\n deadline = performance.now() + 2;\n }\n }\n } catch (cause) {\n return new UuidSlugError(\"invalid_mask_schema\", \"Mask schema construction failed.\", { cause });\n }\n}\n\n/**\n * Refuse schemas that cannot undo these representative blocks. The reverse call must invert\n * the forward call; the same function need not be an involution. Finite probes are not a proof\n * over the full domain. Preserve each original input separately so a mutating callback cannot\n * rewrite the witness and make a destructive transformation appear reversible.\n */\nexport function verifyInvertible(schema: MaskSchema): UuidSlugError | MaskSchema {\n const mixed = new Uint8Array(16);\n const restored = new Uint8Array(16);\n for (const probe of [new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {\n try {\n schema.mix(probe.slice(), mixed, true);\n schema.mix(mixed, restored, false);\n } catch (cause) {\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask schema \"${schema.id}\" failed its invertibility check.`,\n { cause },\n );\n }\n if (restored.some((byte, i) => byte !== probe[i]))\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask schema \"${schema.id}\" does not reverse its own mixing step.`,\n );\n }\n return schema;\n}\n\n/**\n * A PUBLIC key. It ships in the tarball, so every masked slug produced under it is decodable by\n * anyone who installed this package, and it therefore provides none of the obscurity masking\n * exists for.\n *\n * It is exported rather than hidden so that choosing it can be DELIBERATE: a test or demo wanting\n * byte-identical output across machines writes `mask: DEFAULT_MASK_SCHEMA` and says so at the call\n * site. The hazard is the SILENT path — `createUuidSlugCodec()` with no `mask` lands here without\n * the caller writing anything — which is why that fallback and `defaultCodec` both carry the same\n * warning, and why the masked methods are not exported as bare functions.\n */\nconst DEFAULT_SEED = \"anizoptera.uuid-slug.default-mask.v1\";\n\n// Built from `feistelSchema` rather than through `createMaskSchema`, whose failures are a short seed and a\n// bad iteration count — checks on CALLER input that the literals here cannot fail. Routing through it would return\n// `UuidSlugError | MaskSchema` and force a cast that, at module scope, could only ever hide a real Error\n// behind a `MaskSchema` type for every default codec in the process.\nexport const DEFAULT_MASK_SCHEMA: MaskSchema = feistelSchema(\"default\", seedBytes(DEFAULT_SEED), 1);\n"],"mappings":";;;;;;;;AAUA,MAAM,iBAAiB;;AAGvB,MAAM,qBAAqB,KAAK;;;;;;;;AAShC,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,aAAa;AAEnB,SAAS,UAAU,MAA2B;CAC5C,IAAI,OAAO,SAAS,UAAU,OAAO,IAAI,WAAW,IAAI;CACxD,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;AACtC;;AAGA,SAAS,UAAU,MAAkB;CACnC,MAAM,QAAQ,IAAI,WAAW,KAAK,KAAK,KAAK,SAAS,CAAC,IAAI,CAAC;CAC3D,eAAe,MAAM,KAAK;CAC1B,OAAO;AACT;;AAGA,SAAS,eACP,MACA,OACA,SAAS,GACT,QAAQ,GACR,MAAM,KAAK,QACX;CACA,KAAK,IAAI,QAAQ,OAAO,QAAQ,KAAK,SAAS,GAAG;EAC/C,MAAM,WAAW,SAAS;EAC1B,MAAM,aAAa,KAChB,MAAM,aAAa,KAAkB,KAAK,WAAuB,WAAW,KAAK;CACtF;AACF;;;;;;AAOA,SAAS,MAAM,MAAc,MAAc,OAAmB,QAAgB,YAAoB;CAChG,MAAM,sBAAM,IAAI,WAAW,CAAC;CAC5B,YAAY,MAAM,MAAM,OAAO,QAAQ,GAAG;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,YAAY,KAAK,GACnC,YAAY,IAAI,IAAc,IAAI,IAAc,OAAO,QAAQ,GAAG;CACpE,OAAO;AACT;;;;;;AAOA,SAAS,YAAY,MAAkB,YAAoB;CACzD,MAAM,QAAQ,UAAU,IAAI;CAG5B,OAAO,UAFQ,MAAM,YAAY,cAAc,OAAO,KAAK,QAAQ,UAE7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AAS,OAAO;EACd,OAAO,IAAI,cAAc,uBAAuB,oCAAoC,EAAE,MAAM,CAAC;CAC/F;AACF;;;;;;;AAQA,SAAgB,iBAAiB,QAAgD;CAC/E,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,MAAM,2BAAW,IAAI,WAAW,EAAE;CAClC,KAAK,MAAM,SAAS,iBAAC,IAAI,WAAW,EAAE,GAAG,WAAW,KAAK,EAAE,QAAQ,GAAG,IAAI,GAAG,MAAM,IAAI,EAAE,CAAC,GAAG;EAC3F,IAAI;GACF,OAAO,IAAI,MAAM,MAAM,GAAG,OAAO,IAAI;GACrC,OAAO,IAAI,OAAO,UAAU,KAAK;EACnC,SAAS,OAAO;GACd,OAAO,IAAI,cACT,uBACA,gBAAgB,OAAO,GAAG,oCAC1B,EAAE,MAAM,CACV;EACF;EACA,IAAI,SAAS,MAAM,MAAM,MAAM,SAAS,MAAM,EAAE,GAC9C,OAAO,IAAI,cACT,uBACA,gBAAgB,OAAO,GAAG,wCAC5B;CACJ;CACA,OAAO;AACT;AAmBA,MAAa,sBAAkC,cAAc,WAAW,UAAU,sCAAY,GAAG,CAAC"}
|
package/dist/siphash.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
//#region src/siphash.ts
|
|
4
|
+
/**
|
|
5
|
+
* HalfSipHash-2-4 with 64-bit output — the 32-bit-word member of the SipHash family (Aumasson and
|
|
6
|
+
* Bernstein), transcribed from the reference implementation. It is a KEYED pseudorandom function:
|
|
7
|
+
* without the key its output on a chosen input is not computable, which is exactly what `mix32` — a
|
|
8
|
+
* fixed, public, unkeyed bijection — could never be, and the reason it replaced it.
|
|
9
|
+
*
|
|
10
|
+
* One primitive serves both callers that need one: the Feistel round function (`feistel.ts`) and the
|
|
11
|
+
* key derivation (`schema.ts`). Neither justifies its own.
|
|
12
|
+
*
|
|
13
|
+
* Chosen over full SipHash-2-4 because that is defined over 64-bit words, which JavaScript has only
|
|
14
|
+
* as `BigInt` or as hand-emulated 32-bit pairs — the first far too slow for a hot path, the second a
|
|
15
|
+
* re-implementation whose errors nothing would catch. HalfSipHash is 32-bit BY SPECIFICATION, so
|
|
16
|
+
* this is a transcription, and `test/siphash.test.ts` holds it to all 64 published vectors. That
|
|
17
|
+
* external check is the whole reason a standard primitive beat anything tuned here: nothing in this
|
|
18
|
+
* repository can grade a mixing function (see `feistel.ts` — every instrument here passes a
|
|
19
|
+
* two-round network), so agreement with a specification somebody else wrote is the only evidence
|
|
20
|
+
* available that can actually fail.
|
|
21
|
+
*
|
|
22
|
+
* Its key is 64 bits. `schema.ts` runs two independently keyed instances and XORs them, the standard
|
|
23
|
+
* cascade for widening a PRF's key; see there.
|
|
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
|
+
* HalfSipHash-2-4 over a message supplied as 32-bit LITTLE-ENDIAN words, writing the two output
|
|
31
|
+
* words into `out`.
|
|
32
|
+
*
|
|
33
|
+
* Words rather than bytes because both callers already hold words, and the specification absorbs the
|
|
34
|
+
* message in 32-bit little-endian blocks regardless — so this is the same function with the byte
|
|
35
|
+
* reassembly left to whoever actually has bytes. Taking a `Uint8Array` would make the hot path pack
|
|
36
|
+
* bytes it had just unpacked.
|
|
37
|
+
*
|
|
38
|
+
* `byteLength` is the message length the specification hashes and stamps into the final block.
|
|
39
|
+
* `words` must therefore hold `ceil(byteLength / 4)` entries, with any trailing 1-3 bytes packed
|
|
40
|
+
* little-endian into the low bytes of the last one. Internal cooperative callers may pass a
|
|
41
|
+
* positive block limit and resume the returned continuation with exactly the same inputs.
|
|
42
|
+
*/
|
|
43
|
+
function halfSipHash(key0, key1, words, byteLength, out, continuation, blockLimit = Infinity) {
|
|
44
|
+
let v0 = key0 | 0;
|
|
45
|
+
let v1 = key1 ^ 238 | 0;
|
|
46
|
+
let v2 = key0 ^ 1819895653 | 0;
|
|
47
|
+
let v3 = key1 ^ 1952801890 | 0;
|
|
48
|
+
if (continuation) ({v0, v1, v2, v3} = continuation);
|
|
49
|
+
const fullWords = byteLength >>> 2;
|
|
50
|
+
const spare = byteLength & 3;
|
|
51
|
+
const tail = spare === 0 ? 0 : words[fullWords] & (1 << spare * 8) - 1;
|
|
52
|
+
const lengthBlock = byteLength << 24 | tail | 0;
|
|
53
|
+
const start = continuation?.block ?? 0;
|
|
54
|
+
const end = blockLimit === Infinity ? fullWords : Math.min(fullWords, start + blockLimit - 1);
|
|
55
|
+
for (let block = start; block <= end; block += 1) {
|
|
56
|
+
const m = block === fullWords ? lengthBlock : words[block];
|
|
57
|
+
v3 ^= m;
|
|
58
|
+
for (let round = 0; round < C_ROUNDS; round += 1) {
|
|
59
|
+
v0 = v0 + v1 | 0;
|
|
60
|
+
v1 = v1 << 5 | v1 >>> 27;
|
|
61
|
+
v1 ^= v0;
|
|
62
|
+
v0 = v0 << 16 | v0 >>> 16;
|
|
63
|
+
v2 = v2 + v3 | 0;
|
|
64
|
+
v3 = v3 << 8 | v3 >>> 24;
|
|
65
|
+
v3 ^= v2;
|
|
66
|
+
v0 = v0 + v3 | 0;
|
|
67
|
+
v3 = v3 << 7 | v3 >>> 25;
|
|
68
|
+
v3 ^= v0;
|
|
69
|
+
v2 = v2 + v1 | 0;
|
|
70
|
+
v1 = v1 << 13 | v1 >>> 19;
|
|
71
|
+
v1 ^= v2;
|
|
72
|
+
v2 = v2 << 16 | v2 >>> 16;
|
|
73
|
+
}
|
|
74
|
+
v0 ^= m;
|
|
75
|
+
}
|
|
76
|
+
if (end < fullWords) return {
|
|
77
|
+
block: end + 1,
|
|
78
|
+
v0,
|
|
79
|
+
v1,
|
|
80
|
+
v2,
|
|
81
|
+
v3
|
|
82
|
+
};
|
|
83
|
+
v2 ^= 238;
|
|
84
|
+
for (let half = 0; half < 2; half += 1) {
|
|
85
|
+
for (let round = 0; round < D_ROUNDS; round += 1) {
|
|
86
|
+
v0 = v0 + v1 | 0;
|
|
87
|
+
v1 = v1 << 5 | v1 >>> 27;
|
|
88
|
+
v1 ^= v0;
|
|
89
|
+
v0 = v0 << 16 | v0 >>> 16;
|
|
90
|
+
v2 = v2 + v3 | 0;
|
|
91
|
+
v3 = v3 << 8 | v3 >>> 24;
|
|
92
|
+
v3 ^= v2;
|
|
93
|
+
v0 = v0 + v3 | 0;
|
|
94
|
+
v3 = v3 << 7 | v3 >>> 25;
|
|
95
|
+
v3 ^= v0;
|
|
96
|
+
v2 = v2 + v1 | 0;
|
|
97
|
+
v1 = v1 << 13 | v1 >>> 19;
|
|
98
|
+
v1 ^= v2;
|
|
99
|
+
v2 = v2 << 16 | v2 >>> 16;
|
|
100
|
+
}
|
|
101
|
+
out[half] = v1 ^ v3;
|
|
102
|
+
v1 ^= 221;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { halfSipHash };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=siphash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"siphash.js","names":[],"sources":["../src/siphash.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * HalfSipHash-2-4 with 64-bit output — the 32-bit-word member of the SipHash family (Aumasson and\n * Bernstein), transcribed from the reference implementation. It is a KEYED pseudorandom function:\n * without the key its output on a chosen input is not computable, which is exactly what `mix32` — a\n * fixed, public, unkeyed bijection — could never be, and the reason it replaced it.\n *\n * One primitive serves both callers that need one: the Feistel round function (`feistel.ts`) and the\n * key derivation (`schema.ts`). Neither justifies its own.\n *\n * Chosen over full SipHash-2-4 because that is defined over 64-bit words, which JavaScript has only\n * as `BigInt` or as hand-emulated 32-bit pairs — the first far too slow for a hot path, the second a\n * re-implementation whose errors nothing would catch. HalfSipHash is 32-bit BY SPECIFICATION, so\n * this is a transcription, and `test/siphash.test.ts` holds it to all 64 published vectors. That\n * external check is the whole reason a standard primitive beat anything tuned here: nothing in this\n * repository can grade a mixing function (see `feistel.ts` — every instrument here passes a\n * two-round network), so agreement with a specification somebody else wrote is the only evidence\n * available that can actually fail.\n *\n * Its key is 64 bits. `schema.ts` runs two independently keyed instances and XORs them, the standard\n * cascade for widening a PRF's key; see there.\n */\n\n/** Message-absorption rounds per block — the `2` of HalfSipHash-**2**-4. */\nconst C_ROUNDS = 2;\n/** Finalisation rounds per output word — the `4` of HalfSipHash-2-**4**. */\nconst D_ROUNDS = 4;\n\n/** Private continuation: resume only with the same message, keys, byte length and output. */\nexport interface HashContinuation {\n readonly block: number;\n readonly v0: number;\n readonly v1: number;\n readonly v2: number;\n readonly v3: number;\n}\n\n/**\n * HalfSipHash-2-4 over a message supplied as 32-bit LITTLE-ENDIAN words, writing the two output\n * words into `out`.\n *\n * Words rather than bytes because both callers already hold words, and the specification absorbs the\n * message in 32-bit little-endian blocks regardless — so this is the same function with the byte\n * reassembly left to whoever actually has bytes. Taking a `Uint8Array` would make the hot path pack\n * bytes it had just unpacked.\n *\n * `byteLength` is the message length the specification hashes and stamps into the final block.\n * `words` must therefore hold `ceil(byteLength / 4)` entries, with any trailing 1-3 bytes packed\n * little-endian into the low bytes of the last one. Internal cooperative callers may pass a\n * positive block limit and resume the returned continuation with exactly the same inputs.\n */\nexport function halfSipHash(\n key0: number,\n key1: number,\n words: Int32Array,\n byteLength: number,\n out: Int32Array,\n continuation?: HashContinuation,\n blockLimit = Infinity,\n): HashContinuation | undefined {\n let v0 = key0 | 0;\n let v1 = (key1 ^ 0xee) | 0;\n let v2 = (key0 ^ 0x6c796765) | 0;\n let v3 = (key1 ^ 0x74656462) | 0;\n if (continuation) ({ v0, v1, v2, v3 } = continuation);\n\n // The length-stamped final block is absorbed exactly like a message block, so it rides the same\n // loop rather than a second copy of it. Seeds may end mid-word; mask blocks use whole words.\n // The reference vectors exercise every tail length, including an empty message.\n const fullWords = byteLength >>> 2;\n const spare = byteLength & 3;\n const tail = spare === 0 ? 0 : (words[fullWords] as number) & ((1 << (spare * 8)) - 1);\n const lengthBlock = (byteLength << 24) | tail | 0;\n const start = continuation?.block ?? 0;\n const end = blockLimit === Infinity ? fullWords : Math.min(fullWords, start + blockLimit - 1);\n for (let block = start; block <= end; block += 1) {\n const m = block === fullWords ? lengthBlock : (words[block] as number);\n v3 ^= m;\n for (let round = 0; round < C_ROUNDS; round += 1) {\n v0 = (v0 + v1) | 0;\n v1 = (v1 << 5) | (v1 >>> 27);\n v1 ^= v0;\n v0 = (v0 << 16) | (v0 >>> 16);\n v2 = (v2 + v3) | 0;\n v3 = (v3 << 8) | (v3 >>> 24);\n v3 ^= v2;\n v0 = (v0 + v3) | 0;\n v3 = (v3 << 7) | (v3 >>> 25);\n v3 ^= v0;\n v2 = (v2 + v1) | 0;\n v1 = (v1 << 13) | (v1 >>> 19);\n v1 ^= v2;\n v2 = (v2 << 16) | (v2 >>> 16);\n }\n v0 ^= m;\n }\n\n // No output is published until absorption and finalisation are complete. The synchronous\n // hot path has an unlimited block budget and never allocates a continuation.\n if (end < fullWords) return { block: end + 1, v0, v1, v2, v3 };\n\n // Two squeezes, and the `0xdd` between them is what makes the second output word something other\n // than a rerun of the first.\n v2 ^= 0xee;\n for (let half = 0; half < 2; half += 1) {\n for (let round = 0; round < D_ROUNDS; round += 1) {\n v0 = (v0 + v1) | 0;\n v1 = (v1 << 5) | (v1 >>> 27);\n v1 ^= v0;\n v0 = (v0 << 16) | (v0 >>> 16);\n v2 = (v2 + v3) | 0;\n v3 = (v3 << 8) | (v3 >>> 24);\n v3 ^= v2;\n v0 = (v0 + v3) | 0;\n v3 = (v3 << 7) | (v3 >>> 25);\n v3 ^= v0;\n v2 = (v2 + v1) | 0;\n v1 = (v1 << 13) | (v1 >>> 19);\n v1 ^= v2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,MAAM;EAAG;EAAI;EAAI;EAAI;CAAG;CAI7D,MAAM;CACN,KAAK,IAAI,OAAO,GAAG,OAAO,GAAG,QAAQ,GAAG;EACtC,KAAK,IAAI,QAAQ,GAAG,QAAQ,UAAU,SAAS,GAAG;GAChD,KAAM,KAAK,KAAM;GACjB,KAAM,MAAM,IAAM,OAAO;GACzB,MAAM;GACN,KAAM,MAAM,KAAO,OAAO;GAC1B,KAAM,KAAK,KAAM;GACjB,KAAM,MAAM,IAAM,OAAO;GACzB,MAAM;GACN,KAAM,KAAK,KAAM;GACjB,KAAM,MAAM,IAAM,OAAO;GACzB,MAAM;GACN,KAAM,KAAK,KAAM;GACjB,KAAM,MAAM,KAAO,OAAO;GAC1B,MAAM;GACN,KAAM,MAAM,KAAO,OAAO;EAC5B;EACA,IAAI,QAAQ,KAAK;EACjB,MAAM;CACR;AAEF"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidSlugError } from "./errors.js";
|
|
4
|
+
import { SlugAlphabet } from "./uuid.js";
|
|
5
|
+
//#region src/types.d.ts
|
|
6
|
+
declare const brand: unique symbol;
|
|
7
|
+
/**
|
|
8
|
+
* Nominal marker. The names ACCUMULATE as a key set rather than replacing one another, which is
|
|
9
|
+
* what makes nesting work: `Brand<Brand<string, "A">, "B">` carries both keys, so it is assignable
|
|
10
|
+
* to the "A" brand but not the reverse and not to a sibling "C".
|
|
11
|
+
*
|
|
12
|
+
* Writing the name as the property's TYPE instead — `{ [brand]?: Name }` — intersects to
|
|
13
|
+
* `"A" & "B"`, i.e. `never`, on the second level. Every nested brand then has the same `never`
|
|
14
|
+
* marker and they are all mutually assignable: measured 2026-08-12, `UuidV4Slug` and `UuidV7Slug`
|
|
15
|
+
* were interchangeable, as were a plain slug and a masked one, for the entire life of the type.
|
|
16
|
+
*
|
|
17
|
+
* The property stays OPTIONAL so a string literal is still accepted wherever a brand is asked for.
|
|
18
|
+
* These types separate values the package produces; they are not a parsing obligation on callers.
|
|
19
|
+
*/
|
|
20
|
+
type Brand<T, Name extends string> = T & {
|
|
21
|
+
readonly [brand]?: { [K in Name]: true; };
|
|
22
|
+
};
|
|
23
|
+
type Base64UrlString = Brand<string, "Base64UrlString">;
|
|
24
|
+
type UuidString = Brand<string, "UuidString">;
|
|
25
|
+
type UuidV4String = Brand<UuidString, "UuidV4String">;
|
|
26
|
+
type UuidV7String = Brand<UuidString, "UuidV7String">;
|
|
27
|
+
/** Either alphabet — 22 base64url characters or 26 base32hex — so NOT a `Base64UrlString`. */
|
|
28
|
+
type UuidSlug = Brand<string, "UuidSlug">;
|
|
29
|
+
type UuidV4Slug = Brand<UuidSlug, "UuidV4Slug">;
|
|
30
|
+
type UuidV7Slug = Brand<UuidSlug, "UuidV7Slug">;
|
|
31
|
+
/** Masked slugs are base64url only, so this narrows where `UuidSlug` cannot. */
|
|
32
|
+
type MaskedUuidSlug = Brand<Base64UrlString & UuidSlug, "MaskedUuidSlug">;
|
|
33
|
+
type MaskedUuidV7Slug = Brand<MaskedUuidSlug, "MaskedUuidV7Slug">;
|
|
34
|
+
type SentinelUuidV7Slug = Brand<UuidV7Slug, "SentinelUuidV7Slug">;
|
|
35
|
+
type PublicUuidV7Slug = MaskedUuidV7Slug | SentinelUuidV7Slug;
|
|
36
|
+
type UuidBytes = Brand<Uint8Array, "UuidBytes">;
|
|
37
|
+
interface FreshValidationOptions {
|
|
38
|
+
/** Finite Unix milliseconds; read once per validation. */
|
|
39
|
+
now?: () => number;
|
|
40
|
+
/** Finite, nonnegative radius around now, inclusive in both directions; default 24 hours. */
|
|
41
|
+
windowMs?: number;
|
|
42
|
+
}
|
|
43
|
+
interface UuidV7Generator {
|
|
44
|
+
uuidV7(this: void): UuidV7String;
|
|
45
|
+
uuidV7Bytes(this: void, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
46
|
+
/**
|
|
47
|
+
* Generate at a caller-supplied millisecond. A SEPARATE entry point rather than an optional
|
|
48
|
+
* trailing parameter on the pair above, because an optional positional timestamp is silently
|
|
49
|
+
* mappable: `Array.from({length: n}, gen.uuidV7Bytes)` would pass the index as the instant and
|
|
50
|
+
* mint n ids dated 1970, with no type error. Taking the timestamp FIRST makes that impossible.
|
|
51
|
+
*
|
|
52
|
+
* Returns an Error rather than throwing on a bad instant: a caller-supplied value out of range
|
|
53
|
+
* is ordinary input validation, not an exceptional condition.
|
|
54
|
+
*/
|
|
55
|
+
uuidV7At(this: void, timestamp: number): UuidSlugError | UuidV7String;
|
|
56
|
+
uuidV7BytesAt(this: void, timestamp: number, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* A schema is its mixing step, not the data behind one. Holding `mix` as a function rather than
|
|
60
|
+
* exposing a permutation and an XOR table is what lets the masking code stay ignorant of which
|
|
61
|
+
* scheme it is running: adding one is a new constructor in `schema.ts` and no branch anywhere.
|
|
62
|
+
*
|
|
63
|
+
* It is also the ONLY extension point, and deliberately so. This interface is public, so a caller
|
|
64
|
+
* with a scheme of their own supplies it directly; the package ships no table-shaped constructor
|
|
65
|
+
* beside it, because one would privilege a single foreign layout while being strictly less
|
|
66
|
+
* capable than the function it wraps. `createUuidSlugCodec` smoke-tests supplied schemas; callers remain responsible for
|
|
67
|
+
* invertibility across their full input domain.
|
|
68
|
+
*/
|
|
69
|
+
interface MaskSchema {
|
|
70
|
+
readonly id: string;
|
|
71
|
+
/**
|
|
72
|
+
* Transforms 16 bytes; `forward: false` MUST be the exact inverse. `input` and `output` MUST
|
|
73
|
+
* NOT be the same array: a scheme that permutes reads source bytes it would already have
|
|
74
|
+
* overwritten, which corrupts silently rather than failing.
|
|
75
|
+
*/
|
|
76
|
+
mix(input: Uint8Array, output: Uint8Array, forward: boolean): void;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* There is no scheme to choose. The check's width is fixed by arithmetic — a UUIDv7 carries 116
|
|
80
|
+
* bits of content, so the encoding's remainder is the check — and the mixing step is the Feistel,
|
|
81
|
+
* because the only alternative this package ever shipped left the timestamp legible: one output
|
|
82
|
+
* byte per input byte meant 4 of 16 bytes held constant across a second, defeating the entire
|
|
83
|
+
* point of masking. A caller who genuinely needs a different cipher passes a `MaskSchema`.
|
|
84
|
+
*/
|
|
85
|
+
interface MaskSchemaOptions {
|
|
86
|
+
readonly id?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Generate a secret, for example with `openssl rand -base64 32`, and keep it outside source
|
|
89
|
+
* control. At least 16 bytes are required; strings are UTF-8 encoded. A known UUID/slug pair
|
|
90
|
+
* permits offline guesses, so length alone is not protection. Preserve old seeds for decoding
|
|
91
|
+
* issued slugs; rotate by retaining their schema settings in `previousMasks`.
|
|
92
|
+
*/
|
|
93
|
+
readonly seed: string | Uint8Array;
|
|
94
|
+
/**
|
|
95
|
+
* Work factor for turning the seed into key material, default 1 — the cheapest setting, chosen so
|
|
96
|
+
* that codec construction does only the requested work. Higher counts add construction and
|
|
97
|
+
* seed-guessing cost; they are paid when the schema is built, never per id.
|
|
98
|
+
*
|
|
99
|
+
* WIRE-FORMAT-BEARING, exactly as `seed` is: a different count derives different keys, so every
|
|
100
|
+
* masked slug issued under the old count stops decoding. Rotate it the way a seed is rotated —
|
|
101
|
+
* the new setting in `mask`, the old one kept in `previousMasks` — never by editing in place.
|
|
102
|
+
*/
|
|
103
|
+
readonly keyIterations?: number;
|
|
104
|
+
}
|
|
105
|
+
/** The synchronous seed options plus cooperative cancellation; no scheduling knobs are required. */
|
|
106
|
+
interface AsyncMaskSchemaOptions extends MaskSchemaOptions {
|
|
107
|
+
readonly signal?: AbortSignal;
|
|
108
|
+
}
|
|
109
|
+
interface UuidV7SentinelDefinition {
|
|
110
|
+
readonly name: string;
|
|
111
|
+
readonly uuid: UuidV7String;
|
|
112
|
+
}
|
|
113
|
+
interface UuidV7Sentinel {
|
|
114
|
+
readonly name: string;
|
|
115
|
+
readonly slug: SentinelUuidV7Slug;
|
|
116
|
+
readonly uuid: UuidV7String;
|
|
117
|
+
}
|
|
118
|
+
/** Select a known encoding instead of guessing from overlapping slug text. */
|
|
119
|
+
type MigrationFormat = "current" | "original" | "plain";
|
|
120
|
+
/** Enable only formats your application has issued; writers keep using the codec. */
|
|
121
|
+
interface UuidSlugMigrationOptions {
|
|
122
|
+
readonly original?: boolean;
|
|
123
|
+
readonly plain?: boolean;
|
|
124
|
+
}
|
|
125
|
+
interface UuidSlugMigration {
|
|
126
|
+
/** Return the first candidate: sentinel, current keys, original mask, then plain UUID. */
|
|
127
|
+
decode(this: void, slug: string, format?: MigrationFormat): UuidSlugError | UuidString;
|
|
128
|
+
/** Return distinct candidates for one application lookup; an empty array means no match. */
|
|
129
|
+
candidates(this: void, slug: string, format?: MigrationFormat): UuidSlugError | UuidString[];
|
|
130
|
+
}
|
|
131
|
+
interface UuidSlugCodecOptions {
|
|
132
|
+
readonly generator?: UuidV7Generator;
|
|
133
|
+
/**
|
|
134
|
+
* Also decode plain, unmasked slugs when no schema matches — the migration path for ids issued
|
|
135
|
+
* before masking existed. Its own option rather than a field beside the key list, because the
|
|
136
|
+
* two answer different questions and share only the accident of both concerning the past.
|
|
137
|
+
*
|
|
138
|
+
* Turn it off once the migration ends. It costs one wrong answer per 2^checkBits: a direct slug
|
|
139
|
+
* that happens to satisfy a mask's check decodes as that mask instead, and both are the same 22
|
|
140
|
+
* characters of the same alphabet, so nothing else can tell them apart.
|
|
141
|
+
*/
|
|
142
|
+
readonly acceptUnmaskedSlugs?: boolean;
|
|
143
|
+
/**
|
|
144
|
+
* Schemas to try after `mask`, in the order given — how a seed is rotated. Takes a seed exactly
|
|
145
|
+
* as `mask` does: a rotated seed is the ordinary reason this list exists, and requiring a
|
|
146
|
+
* pre-built schema for it cost the commonest case a constructor and an error branch that naming
|
|
147
|
+
* the current seed never needed. Named for rotation rather than for legacy, because a previous
|
|
148
|
+
* key is not a different kind of thing from the current one — rotation is only a change of
|
|
149
|
+
* position between this list and `mask`.
|
|
150
|
+
*
|
|
151
|
+
* Keep it short. Each entry is tried in turn, so the codec's wrong-answer rate is the sum over
|
|
152
|
+
* the whole list.
|
|
153
|
+
*/
|
|
154
|
+
readonly previousMasks?: readonly (MaskSchema | MaskSchemaOptions)[];
|
|
155
|
+
/**
|
|
156
|
+
* The schema that ENCODES, and the first tried when decoding. Kept separate from the list above
|
|
157
|
+
* rather than folded into one ordered array: in a single list the encoding schema is whichever
|
|
158
|
+
* happens to be first, so appending a rotated seed leaves you still issuing ids under the old
|
|
159
|
+
* one while believing you rotated. Nothing about that failure is visible.
|
|
160
|
+
*
|
|
161
|
+
* OPTIONAL, and omitting it is the one choice here with a security consequence: the codec then
|
|
162
|
+
* masks under `DEFAULT_MASK_SCHEMA`, whose seed is a string literal in this published package,
|
|
163
|
+
* so its masked slugs are readable by anyone who installed it. Supply `{ seed }` — any stable
|
|
164
|
+
* string you keep out of the repository — for masking to obfuscate anything at all.
|
|
165
|
+
*/
|
|
166
|
+
readonly mask?: MaskSchema | MaskSchemaOptions;
|
|
167
|
+
readonly sentinels?: readonly UuidV7SentinelDefinition[];
|
|
168
|
+
/**
|
|
169
|
+
* Alphabet for PLAIN slugs from `uuidV4Slug` and `uuidV7Slug`. `"base32hex"` costs four characters
|
|
170
|
+
* (26 rather than 22) and buys chronological sort order: its characters are in ASCII order and a
|
|
171
|
+
* UUIDv7's leading bytes are its timestamp, so base32hex slugs sort by creation time as plain
|
|
172
|
+
* strings. base64url's alphabet cannot — it runs `A-Za-z0-9-_`, so its character order and its
|
|
173
|
+
* value order disagree. Being alphanumeric also spares base32hex the `-` and `_` that make a
|
|
174
|
+
* base64url slug awkward to select by double-click.
|
|
175
|
+
*
|
|
176
|
+
* Codec-level rather than per call so a system cannot mint half its ids in each spelling.
|
|
177
|
+
* Decoding takes no such option: the two lengths are disjoint, so `slugToUuid` reads both and a
|
|
178
|
+
* change of alphabet leaves every previously issued slug working.
|
|
179
|
+
*
|
|
180
|
+
* It does NOT reach masked slugs or sentinels, which stay base64url. Masked bytes are ciphertext
|
|
181
|
+
* and sort in no useful order, and a sentinel is matched against masked input, so a sentinel in a
|
|
182
|
+
* different alphabet could never be recognised there.
|
|
183
|
+
*
|
|
184
|
+
* Costs throughput when set: `uuidV7Slug` can no longer use a runtime's native base64url slug
|
|
185
|
+
* generator and falls back to generating bytes and encoding them.
|
|
186
|
+
*/
|
|
187
|
+
readonly slugAlphabet?: SlugAlphabet;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Only what depends on the codec's own state: the generator it draws from, and the mask schema
|
|
191
|
+
* plus sentinels it was built with.
|
|
192
|
+
*
|
|
193
|
+
* The plain conversions (`uuidToSlug`, `parseUuid`, `formatUuidSlug`, …) are module-level
|
|
194
|
+
* functions and deliberately absent here. They are pure — the same input gives the same output
|
|
195
|
+
* whatever seed the codec holds — so carrying them as methods implied a dependency on the seed
|
|
196
|
+
* that does not exist, and was the single most misleading thing about the previous shape.
|
|
197
|
+
*
|
|
198
|
+
* Extending `UuidV7Generator` makes the compiler require forwarding every generator method.
|
|
199
|
+
*/
|
|
200
|
+
interface UuidSlugCodec extends UuidV7Generator {
|
|
201
|
+
readonly sentinels: readonly UuidV7Sentinel[];
|
|
202
|
+
/** Create an opt-in reader without changing generation or ordinary codec decoding. */
|
|
203
|
+
migration(this: void, options?: UuidSlugMigrationOptions): UuidSlugMigration;
|
|
204
|
+
/**
|
|
205
|
+
* `this: void` lets callers detach methods without `.bind`; implementations cannot rely on `this`.
|
|
206
|
+
*/
|
|
207
|
+
uuidV4(this: void): UuidV4String;
|
|
208
|
+
uuidV4Bytes(this: void, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
209
|
+
uuidV4Slug(this: void): UuidV4Slug;
|
|
210
|
+
uuidV7Slug(this: void): UuidV7Slug;
|
|
211
|
+
uuidV7MaskedSlug(this: void): PublicUuidV7Slug;
|
|
212
|
+
/**
|
|
213
|
+
* Masking is UUIDv7-only, and the reason is that the whole format is spent. The check rides in
|
|
214
|
+
* bits a v7 provably wastes — its constant version and variant, and the timestamp's top six —
|
|
215
|
+
* plus whatever the encoding has left over. Another version would have to store its real
|
|
216
|
+
* version and its full timestamp somewhere, and there is no somewhere: every one of the 132
|
|
217
|
+
* bits in 22 characters already has a job. Supporting all versions would cost a 23rd character
|
|
218
|
+
* on every masked slug forever, to hide a creation time only v7 discloses.
|
|
219
|
+
*/
|
|
220
|
+
uuidV7ToMaskedSlug(this: void, uuid: string): UuidSlugError | PublicUuidV7Slug;
|
|
221
|
+
maskedSlugToUuidV7(this: void, slug: string): UuidSlugError | UuidV7String;
|
|
222
|
+
/**
|
|
223
|
+
* Decodes to whatever version comes out, where `maskedSlugToUuidV7` insists on v7.
|
|
224
|
+
*
|
|
225
|
+
* NOT a redundant widening of that method, which is what it looks like: with
|
|
226
|
+
* `acceptUnmaskedSlugs` enabled a slug that matches no schema is tried as a plain unmasked
|
|
227
|
+
* slug, and a system migrating off unmasked ids may well have UUIDv4 ones. Those decode here
|
|
228
|
+
* and are rejected by the v7 form. Deleting this on the assumption it was a duplicate was
|
|
229
|
+
* measured to break exactly that migration path.
|
|
230
|
+
*/
|
|
231
|
+
maskedSlugToUuid(this: void, slug: string): UuidSlugError | UuidString;
|
|
232
|
+
/**
|
|
233
|
+
* `maskedSlugToUuidV7` plus the freshness rules of `validateUuidV7Fresh`, returning the slug.
|
|
234
|
+
*
|
|
235
|
+
* Lives on the codec because unmasking needs the codec's key. Its module-level predecessor
|
|
236
|
+
* `validateMaskedUuidV7SlugFresh` did not: it reached for `defaultCodec`, whose seed is
|
|
237
|
+
* published in this package's source, so it answered under the wrong key for every caller who
|
|
238
|
+
* supplied their own and returned a confident Error for valid slugs. There is no keyless
|
|
239
|
+
* counterpart to this for the same reason; `validateUuidV7SlugFresh` stays module-level because
|
|
240
|
+
* a PLAIN slug decodes without one.
|
|
241
|
+
*
|
|
242
|
+
* Returns the slug it was GIVEN, at the type it was given, which is the only type that is true
|
|
243
|
+
* of it. Declaring `MaskedUuidV7Slug` was a lie the compiler could not catch: that brand is
|
|
244
|
+
* `Base64UrlString & UuidSlug`, but with `acceptUnmaskedSlugs` the decode falls through to
|
|
245
|
+
* `slugToUuid`, which accepts 26-character base32hex too — so a base32hex slug came back typed as
|
|
246
|
+
* base64url and `isBase64Url` on it was false. Narrowing the fallback to base64url would have
|
|
247
|
+
* been the wrong repair: a codec built with `slugAlphabet: "base32hex"` has exactly those legacy
|
|
248
|
+
* ids, and refusing them breaks the migration this flag exists for. The behaviour is right; the
|
|
249
|
+
* claim about it was not.
|
|
250
|
+
*/
|
|
251
|
+
validateMaskedSlugFresh<S extends string>(this: void, slug: S, freshness?: FreshValidationOptions): UuidSlugError | S;
|
|
252
|
+
}
|
|
253
|
+
//#endregion
|
|
254
|
+
export { AsyncMaskSchemaOptions, Base64UrlString, Brand, FreshValidationOptions, MaskSchema, MaskSchemaOptions, MaskedUuidSlug, MaskedUuidV7Slug, MigrationFormat, PublicUuidV7Slug, SentinelUuidV7Slug, UuidBytes, UuidSlug, UuidSlugCodec, UuidSlugCodecOptions, UuidSlugMigration, UuidSlugMigrationOptions, UuidString, UuidV4Slug, UuidV4String, UuidV7Generator, UuidV7Sentinel, UuidV7SentinelDefinition, UuidV7Slug, UuidV7String };
|
|
255
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;cAKc;;;;;;;;;;;;;;KAeF,MAAM,GAAG,uBAAuB;YAAgB,YAAY,KAAK;;KAEjE,kBAAkB;KAClB,aAAa;KACb,eAAe,MAAM;KACrB,eAAe,MAAM;;KAErB,WAAW;KACX,aAAa,MAAM;KACnB,aAAa,MAAM;;KAEnB,iBAAiB,MAAM,kBAAkB;KACzC,mBAAmB,MAAM;KACzB,q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