@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,91 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidRuntimeError, checkRange, errorOrThrow, fillRandomBytes } from "./errors.js";
|
|
4
|
+
import { runtime } from "./runtime/node.js";
|
|
5
|
+
import { formatUuid, formatUuidSlug } from "./uuid.js";
|
|
6
|
+
import { createRuntimeGenerator } from "./v7.js";
|
|
7
|
+
//#region src/keyless.ts
|
|
8
|
+
/**
|
|
9
|
+
* The operations that need no key, built WITHOUT a codec.
|
|
10
|
+
*
|
|
11
|
+
* Generating an id and re-encoding one are keyless: the result is the same value whoever asks, so
|
|
12
|
+
* a bare function is an honest shape for them. Reaching them through a codec is what made them
|
|
13
|
+
* expensive — a codec carries a mask schema, a cipher and a sentinel table, none of which a caller
|
|
14
|
+
* who never masks will ever execute, and all of which a bundler must keep once the graph reaches
|
|
15
|
+
* them. Measured 2026-08-12 on the built package: an entry importing only `uuidV7Slug` minified to
|
|
16
|
+
* 12,735 bytes through the codec and 4,559 from a bare generator; `uuidToSlug` alone, 12,725
|
|
17
|
+
* against 2,188. `defaultCodec` still exists and still works — it is simply no longer on the path
|
|
18
|
+
* every consumer walks.
|
|
19
|
+
*
|
|
20
|
+
* NOTHING KEYED MAY BE ADDED HERE (Art's ruling, 2026-08-12). The only key a bare function could
|
|
21
|
+
* carry is `DEFAULT_MASK_SCHEMA`'s, whose seed is a string literal in this published package, so a
|
|
22
|
+
* masked operation exported this way would be the shortest spelling of the headline feature and
|
|
23
|
+
* the one that obfuscates nothing. Masking is reached through a codec built with your own seed.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Built on first use, and the laziness is what the measurement above depends on: a module-scope
|
|
27
|
+
* CONSTRUCTION call is a side effect a bundler may not remove, so an eager one would pin the
|
|
28
|
+
* generator, the runtime adapter and the entropy pool into a bundle that only ever re-encodes a
|
|
29
|
+
* UUID. Measured the same day, the eager spelling cost 5,130 bytes for `uuidToSlug` alone against
|
|
30
|
+
* 2,188 here.
|
|
31
|
+
*
|
|
32
|
+
* It also keeps import-time work at zero, which `test/entropy.test.ts` gates for a different
|
|
33
|
+
* reason — a heap snapshot taken at module load must capture no drawn randomness.
|
|
34
|
+
*/
|
|
35
|
+
let generator;
|
|
36
|
+
const v7 = () => generator ??= createRuntimeGenerator(runtime);
|
|
37
|
+
/**
|
|
38
|
+
* Randomness is drawn into a private buffer and copied out instead of filled through a view of the
|
|
39
|
+
* caller's array: `fillRandom` requires a plain `ArrayBuffer` because Web Crypto rejects a
|
|
40
|
+
* `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee. Reused rather
|
|
41
|
+
* than allocated per call, matching the v7 generator, so the cost is one 16-byte copy.
|
|
42
|
+
*/
|
|
43
|
+
const v4Random = /* @__PURE__ */ new Uint8Array(16);
|
|
44
|
+
/** Shared with `createUuidSlugCodec`, so a v4 has one implementation however it is reached. */
|
|
45
|
+
function uuidV4Bytes(out, offset = 0) {
|
|
46
|
+
const target = out ?? /* @__PURE__ */ new Uint8Array(16);
|
|
47
|
+
const badRange = checkRange(target.length, offset, 16);
|
|
48
|
+
if (badRange) return badRange;
|
|
49
|
+
const failed = fillRandomBytes(runtime.fillRandom, v4Random);
|
|
50
|
+
if (failed) return failed;
|
|
51
|
+
target.set(v4Random, offset);
|
|
52
|
+
target[offset + 6] = (target[offset + 6] ?? 0) & 15 | 64;
|
|
53
|
+
target[offset + 8] = (target[offset + 8] ?? 0) & 63 | 128;
|
|
54
|
+
return target;
|
|
55
|
+
}
|
|
56
|
+
function uuidV4() {
|
|
57
|
+
try {
|
|
58
|
+
const native = runtime.uuidV4?.();
|
|
59
|
+
if (native) return native;
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
throw new UuidRuntimeError("Runtime UUIDv4 generation failed.", { cause });
|
|
62
|
+
}
|
|
63
|
+
return errorOrThrow(formatUuid(errorOrThrow(uuidV4Bytes())));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Takes the alphabet for the same reason `uuidV7Slug` does, and NOT because a v4 slug sorts — it
|
|
67
|
+
* does not. The alphabet is a choice of representation, so a project that has standardised on the
|
|
68
|
+
* 26-character lowercase form for its public ids needs its v4 slugs in it too; the pair differing
|
|
69
|
+
* would be an asymmetry with nothing behind it.
|
|
70
|
+
*/
|
|
71
|
+
function uuidV4Slug(alphabet = "base64url") {
|
|
72
|
+
return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, alphabet));
|
|
73
|
+
}
|
|
74
|
+
const uuidV7 = () => v7().uuidV7();
|
|
75
|
+
const uuidV7Bytes = (out, offset) => v7().uuidV7Bytes(out, offset);
|
|
76
|
+
const uuidV7At = (timestamp) => v7().uuidV7At(timestamp);
|
|
77
|
+
const uuidV7BytesAt = (timestamp, out, offset) => v7().uuidV7BytesAt(timestamp, out, offset);
|
|
78
|
+
/**
|
|
79
|
+
* The alphabet is an argument here, exactly as it is on `uuidToSlug(uuid, alphabet)`, because
|
|
80
|
+
* choosing it needs no key: without it the only way to GENERATE a base32hex slug was to build a
|
|
81
|
+
* codec, so the sortable form cost the whole masking machinery while the unsortable one was free.
|
|
82
|
+
* Positional and last, matching `uuidToSlug`, so the two spellings of "encode in this alphabet"
|
|
83
|
+
* do not diverge.
|
|
84
|
+
*/
|
|
85
|
+
function uuidV7Slug(alphabet = "base64url") {
|
|
86
|
+
const native = alphabet === "base64url" ? runtime.uuidV7Slug : void 0;
|
|
87
|
+
if (native) return native();
|
|
88
|
+
return errorOrThrow(formatUuidSlug(errorOrThrow(v7().uuidV7Bytes()), 0, alphabet));
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
export { uuidV4, uuidV4Bytes, uuidV4Slug, uuidV7, uuidV7At, uuidV7Bytes, uuidV7BytesAt, uuidV7Slug };
|
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
//#region src/legacy-mask.ts
|
|
5
|
+
const PERMUTE = [
|
|
6
|
+
9,
|
|
7
|
+
13,
|
|
8
|
+
3,
|
|
9
|
+
8,
|
|
10
|
+
14,
|
|
11
|
+
0,
|
|
12
|
+
11,
|
|
13
|
+
7,
|
|
14
|
+
6,
|
|
15
|
+
1,
|
|
16
|
+
15,
|
|
17
|
+
4,
|
|
18
|
+
2,
|
|
19
|
+
5,
|
|
20
|
+
10,
|
|
21
|
+
12
|
|
22
|
+
];
|
|
23
|
+
const XOR = [
|
|
24
|
+
162,
|
|
25
|
+
112,
|
|
26
|
+
50,
|
|
27
|
+
127,
|
|
28
|
+
152,
|
|
29
|
+
184,
|
|
30
|
+
155,
|
|
31
|
+
94,
|
|
32
|
+
27,
|
|
33
|
+
38,
|
|
34
|
+
182,
|
|
35
|
+
22,
|
|
36
|
+
150,
|
|
37
|
+
249,
|
|
38
|
+
234,
|
|
39
|
+
62
|
|
40
|
+
];
|
|
41
|
+
/** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */
|
|
42
|
+
function decodeOriginalMask(mixed) {
|
|
43
|
+
if (mixed.length !== 16) return new UuidSlugError("invalid_buffer", "Original masked slugs require 16 decoded bytes.");
|
|
44
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
45
|
+
for (let i = 0; i < 16; i++) bytes[PERMUTE[i]] = mixed[i] ^ XOR[i];
|
|
46
|
+
const found = bytes[6] >>> 4;
|
|
47
|
+
bytes[6] = bytes[6] & 15 | 112;
|
|
48
|
+
let checksum = 0;
|
|
49
|
+
for (const byte of bytes) checksum ^= byte;
|
|
50
|
+
return (checksum >>> 4 ^ checksum & 15) === found ? bytes : void 0;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { decodeOriginalMask };
|
|
@@ -0,0 +1,106 @@
|
|
|
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 { BASE64URL, decodeInto, encode, spareBits } from "./alphabet.js";
|
|
5
|
+
import { formatUuid } from "./uuid.js";
|
|
6
|
+
import { mix32, read32 } from "./feistel.js";
|
|
7
|
+
//#region src/mask.ts
|
|
8
|
+
/** Custom callbacks can fail after construction; preserve their cause in the public error contract. */
|
|
9
|
+
function applyMix(schema, input, output, forward) {
|
|
10
|
+
try {
|
|
11
|
+
schema.mix(input, output, forward);
|
|
12
|
+
return;
|
|
13
|
+
} catch (cause) {
|
|
14
|
+
return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" failed ${forward ? "encoding" : "decoding"}.`, { cause });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The check must fail a wrong key with probability 2^-width, which holds only if the function
|
|
19
|
+
* spreads its input across its whole output — so this is an avalanche mixer, not a sum. Measured
|
|
20
|
+
* over 100,000 draws: uniform to chi-squared/df 0.999 across all 65,536 buckets of its top 16 bits.
|
|
21
|
+
*
|
|
22
|
+
* Taken from the TOP so that widening the check never renumbers the bits below it.
|
|
23
|
+
*/
|
|
24
|
+
function tagFor(bytes, width) {
|
|
25
|
+
let acc = 0;
|
|
26
|
+
for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));
|
|
27
|
+
return acc >>> 32 - width;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The 12 check bits a UUIDv7 can hold inside the block, because it spends them on nothing: bits
|
|
31
|
+
* 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
|
|
32
|
+
* high end of the 48-bit timestamp, zero for every instant before 2109. The rest of the check
|
|
33
|
+
* rides outside the block, in whatever the encoding has spare.
|
|
34
|
+
*
|
|
35
|
+
* Claiming byte 0 is why encoding must REFUSE an instant at or past 2^42 ms rather than truncate.
|
|
36
|
+
*/
|
|
37
|
+
function injectTag(bytes, tag) {
|
|
38
|
+
bytes[6] = (tag & 15) << 4 | (bytes[6] ?? 0) & 15;
|
|
39
|
+
bytes[8] = (tag & 48) << 2 | (bytes[8] ?? 0) & 63;
|
|
40
|
+
bytes[0] = (tag >>> 6 & 63) << 2 | (bytes[0] ?? 0) & 3;
|
|
41
|
+
}
|
|
42
|
+
function extractTag(bytes) {
|
|
43
|
+
return (bytes[6] ?? 0) >>> 4 | (bytes[8] ?? 0) >>> 6 << 4 | (bytes[0] ?? 0) >>> 2 << 6;
|
|
44
|
+
}
|
|
45
|
+
/** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
|
|
46
|
+
function restoreV7(bytes) {
|
|
47
|
+
bytes[6] = (bytes[6] ?? 0) & 15 | 112;
|
|
48
|
+
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
49
|
+
bytes[0] = (bytes[0] ?? 0) & 3;
|
|
50
|
+
}
|
|
51
|
+
/** The 12 check bits that fit inside the block; the rest ride in the encoding's spare bits. */
|
|
52
|
+
const INNER_TAG_BITS = 12;
|
|
53
|
+
/**
|
|
54
|
+
* A masked slug is always 22 base64url characters (Art's ruling, 2026-08-12), so the outer half of
|
|
55
|
+
* the check is a constant 4 bits. Derived rather than written as `4` because the derivation IS the
|
|
56
|
+
* rule — the check is whatever the encoding has left over, never a number somebody chose.
|
|
57
|
+
*/
|
|
58
|
+
const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
|
|
59
|
+
const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
|
|
60
|
+
function uuidV7BytesToMaskedSlug(raw, schema) {
|
|
61
|
+
if ((raw[0] ?? 0) > 3) return new UuidSlugError("invalid_timestamp", "Masking requires a UUIDv7 timestamped before 2^42 ms (year 2109); its top six bits carry the check.");
|
|
62
|
+
const tag = tagFor(raw, TAG_BITS);
|
|
63
|
+
const tagged = new Uint8Array(raw);
|
|
64
|
+
injectTag(tagged, tag >>> OUTER_TAG_BITS);
|
|
65
|
+
const mixed = /* @__PURE__ */ new Uint8Array(16);
|
|
66
|
+
const failed = applyMix(schema, tagged, mixed, true);
|
|
67
|
+
if (failed) return failed;
|
|
68
|
+
return encode(mixed, BASE64URL, tag & (1 << OUTER_TAG_BITS) - 1, OUTER_TAG_BITS);
|
|
69
|
+
}
|
|
70
|
+
function decodeMaskedSlug(slug, schema, previous = []) {
|
|
71
|
+
const mixed = /* @__PURE__ */ new Uint8Array(16);
|
|
72
|
+
const outerTag = decodeInto(slug, BASE64URL, mixed, 0, 16, OUTER_TAG_BITS);
|
|
73
|
+
if (outerTag instanceof Error) return outerTag;
|
|
74
|
+
const primary = unmix(previous.length ? mixed.slice() : mixed, outerTag, schema);
|
|
75
|
+
if (primary && !(primary instanceof Error)) return primary;
|
|
76
|
+
for (const older of previous) {
|
|
77
|
+
const decoded = unmix(mixed.slice(), outerTag, older);
|
|
78
|
+
if (decoded && !(decoded instanceof Error)) return decoded;
|
|
79
|
+
}
|
|
80
|
+
return primary ?? new UuidSlugError("invalid_uuid_slug", "Masked UUID slug failed schema validation.");
|
|
81
|
+
}
|
|
82
|
+
/** Append distinct UUIDs directly to the result, before another callback can mutate their bytes. */
|
|
83
|
+
function decodeMaskedCandidates(mixed, outerTag, schemas, firstOnly = false, candidates = []) {
|
|
84
|
+
for (const schema of schemas) {
|
|
85
|
+
const decoded = unmix(mixed.slice(), outerTag, schema);
|
|
86
|
+
if (decoded instanceof Error) return decoded;
|
|
87
|
+
if (decoded) {
|
|
88
|
+
const uuid = formatUuid(decoded);
|
|
89
|
+
if (uuid instanceof Error) return uuid;
|
|
90
|
+
if (!candidates.includes(uuid)) candidates.push(uuid);
|
|
91
|
+
if (firstOnly) break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return candidates;
|
|
95
|
+
}
|
|
96
|
+
function unmix(mixed, outerTag, schema) {
|
|
97
|
+
const unmixed = /* @__PURE__ */ new Uint8Array(16);
|
|
98
|
+
const failed = applyMix(schema, mixed, unmixed, false);
|
|
99
|
+
if (failed) return failed;
|
|
100
|
+
const foundTag = extractTag(unmixed) << OUTER_TAG_BITS | outerTag;
|
|
101
|
+
restoreV7(unmixed);
|
|
102
|
+
if (tagFor(unmixed, TAG_BITS) !== foundTag) return void 0;
|
|
103
|
+
return unmixed;
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { decodeMaskedCandidates, decodeMaskedSlug, uuidV7BytesToMaskedSlug };
|
|
@@ -0,0 +1,64 @@
|
|
|
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 { BASE32HEX, BASE64URL, decodeInto, encode } from "./alphabet.js";
|
|
5
|
+
import { formatUuid } from "./uuid.js";
|
|
6
|
+
import { decodeMaskedCandidates } from "./mask.js";
|
|
7
|
+
import { decodeOriginalMask } from "./legacy-mask.js";
|
|
8
|
+
//#region src/migration.ts
|
|
9
|
+
/** Read old IDs with the codec's keys and sentinels; never change how new IDs are written. */
|
|
10
|
+
function createMigration(schemas, sentinels, options = {}) {
|
|
11
|
+
const original = options.original === true;
|
|
12
|
+
const plain = options.plain === true;
|
|
13
|
+
function read(slug, format, firstOnly) {
|
|
14
|
+
if (format !== void 0 && format !== "current" && format !== "original" && format !== "plain" || format === "original" && !original || format === "plain" && !plain) return new UuidSlugError("invalid_uuid_slug", "Enable the requested format when creating the migration reader.");
|
|
15
|
+
const sentinel = sentinels.get(slug);
|
|
16
|
+
if (sentinel) return [sentinel.uuid];
|
|
17
|
+
const useCurrent = format === void 0 || format === "current";
|
|
18
|
+
const useOriginal = original && (format === void 0 || format === "original");
|
|
19
|
+
const usePlain = plain && (format === void 0 || format === "plain");
|
|
20
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
21
|
+
const base32 = slug.length === 26 && usePlain;
|
|
22
|
+
const tail = decodeInto(slug, base32 ? BASE32HEX : BASE64URL, bytes, 0, 16, base32 ? 0 : 4);
|
|
23
|
+
if (tail instanceof Error) return tail;
|
|
24
|
+
const reserved = (useOriginal || usePlain) && sentinels.get(base32 ? encode(bytes, BASE64URL) : tail === 0 ? slug : slug.slice(0, 21) + BASE64URL.chars[(bytes[15] & 3) << 4]);
|
|
25
|
+
if (reserved && firstOnly) return [reserved.uuid];
|
|
26
|
+
const candidates = reserved ? [reserved.uuid] : [];
|
|
27
|
+
function add(value) {
|
|
28
|
+
const uuid = formatUuid(value);
|
|
29
|
+
if (uuid instanceof Error) return uuid;
|
|
30
|
+
if (!candidates.includes(uuid)) candidates.push(uuid);
|
|
31
|
+
}
|
|
32
|
+
if (useCurrent && !base32) {
|
|
33
|
+
const matches = decodeMaskedCandidates(bytes, tail, schemas, firstOnly, candidates);
|
|
34
|
+
if (matches instanceof Error) return matches;
|
|
35
|
+
if (firstOnly && candidates.length) return candidates;
|
|
36
|
+
}
|
|
37
|
+
if (reserved) return candidates;
|
|
38
|
+
if (useOriginal && slug.length === 22) {
|
|
39
|
+
const match = decodeOriginalMask(bytes);
|
|
40
|
+
if (match instanceof Error) return match;
|
|
41
|
+
if (match) {
|
|
42
|
+
const failed = add(match);
|
|
43
|
+
if (failed) return failed;
|
|
44
|
+
if (firstOnly) return candidates;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (usePlain) {
|
|
48
|
+
const failed = add(bytes);
|
|
49
|
+
if (failed) return failed;
|
|
50
|
+
}
|
|
51
|
+
return candidates;
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
decode(slug, format) {
|
|
55
|
+
const result = read(slug, format, true);
|
|
56
|
+
return result instanceof Error ? result : result[0] ?? new UuidSlugError("invalid_uuid_slug", "Slug does not match an enabled format.");
|
|
57
|
+
},
|
|
58
|
+
candidates(slug, format) {
|
|
59
|
+
return read(slug, format, false);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { createMigration };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { pooledFill } from "./pool.js";
|
|
4
|
+
import crypto from "node:crypto";
|
|
5
|
+
//#region src/runtime/node.ts
|
|
6
|
+
/**
|
|
7
|
+
* Node grew `crypto.randomUUIDv7` in 26.6.0, so on every earlier release this is `undefined`
|
|
8
|
+
* and the capability is simply absent. Probed once here rather than inside the method:
|
|
9
|
+
* `Runtime.uuidV7` is optional precisely so a consumer can branch on its presence, and a
|
|
10
|
+
* method that exists but always throws defeats that — the caller reaches for it, catches, and
|
|
11
|
+
* falls back on EVERY call. Measured 2026-08-11 on Node 24.15.0, that throw cost 64% of v7
|
|
12
|
+
* throughput (400k against 1.11M ops/s).
|
|
13
|
+
*/
|
|
14
|
+
const nativeUuidV7 = crypto.randomUUIDv7;
|
|
15
|
+
const nodeRuntime = {
|
|
16
|
+
/**
|
|
17
|
+
* `randomFillSync` writes into the buffer it is given. `randomBytes` would allocate a fresh
|
|
18
|
+
* `Buffer` per call and copy out of it, leaving a second, unzeroed copy of the random
|
|
19
|
+
* material on the heap for the collector to get to whenever it does. Measured 14% faster
|
|
20
|
+
* as well, but the copy is the reason. Pooled because the per-call cost dominates at 16
|
|
21
|
+
* bytes; see `pool.ts`.
|
|
22
|
+
*/
|
|
23
|
+
fillRandom: pooledFill((into) => {
|
|
24
|
+
crypto.randomFillSync(into);
|
|
25
|
+
}),
|
|
26
|
+
uuidV4() {
|
|
27
|
+
return crypto.randomUUID();
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
if (nativeUuidV7) nodeRuntime.uuidV7 = () => nativeUuidV7.call(crypto);
|
|
31
|
+
const runtime = nodeRuntime;
|
|
32
|
+
//#endregion
|
|
33
|
+
export { runtime };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
//#region src/runtime/pool.ts
|
|
4
|
+
/**
|
|
5
|
+
* Draws cryptographic randomness a page at a time instead of per id.
|
|
6
|
+
*
|
|
7
|
+
* The underlying primitives cost far more per call than per byte, and a v7 id needs only 16
|
|
8
|
+
* bytes, so per-id draws spend nearly all of their time on call overhead. Measured 2026-08-11
|
|
9
|
+
* filling 16 bytes: 1.94M/s (Node 24) and 4.85M/s (Bun) drawing directly, against 38.9M/s and
|
|
10
|
+
* 77.9M/s from an 8 KiB pool — 20x and 16x. Node's own `randomUUID` batches for the same reason,
|
|
11
|
+
* which is why `crypto.randomUUID` measures 8.9M/s against 1.5M/s with its cache disabled.
|
|
12
|
+
*
|
|
13
|
+
* 8 KiB is the knee: 64 KiB gains nothing further on Node and measured slightly worse on Bun,
|
|
14
|
+
* while holding eight times as much unissued material in memory.
|
|
15
|
+
*
|
|
16
|
+
* The source is unchanged — this batches the same CSPRNG, it does not replace or stretch it.
|
|
17
|
+
*/
|
|
18
|
+
const POOL_BYTES = 8192;
|
|
19
|
+
/**
|
|
20
|
+
* Wraps a direct random-fill primitive in a pool.
|
|
21
|
+
*
|
|
22
|
+
* Consumed bytes are zeroed as they are handed out. Batching is what creates the need: without
|
|
23
|
+
* a pool, material for an id is gone once used, whereas a live 8 KiB buffer would otherwise
|
|
24
|
+
* retain the random half of up to 512 already-issued ids, so a heap dump would expose ids the
|
|
25
|
+
* process had already handed out. Zeroing restores the property batching would remove; the cost
|
|
26
|
+
* is one write per byte already being copied.
|
|
27
|
+
*
|
|
28
|
+
* Each module instance owns its pool, so worker threads never share one. This is safe under
|
|
29
|
+
* Node's process model because a new process gets a fresh heap; it would NOT be safe under a
|
|
30
|
+
* POSIX `fork` that copies the heap, where parent and child would issue identical bytes.
|
|
31
|
+
*/
|
|
32
|
+
function pooledFill(fill) {
|
|
33
|
+
const pool = new Uint8Array(POOL_BYTES);
|
|
34
|
+
let offset = POOL_BYTES;
|
|
35
|
+
return (bytes) => {
|
|
36
|
+
const { length } = bytes;
|
|
37
|
+
if (length > POOL_BYTES) {
|
|
38
|
+
fill(bytes);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (offset + length > POOL_BYTES) {
|
|
42
|
+
fill(pool);
|
|
43
|
+
offset = 0;
|
|
44
|
+
}
|
|
45
|
+
for (let i = 0; i < length; i += 1) {
|
|
46
|
+
bytes[i] = pool[offset + i];
|
|
47
|
+
pool[offset + i] = 0;
|
|
48
|
+
}
|
|
49
|
+
offset += length;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { pooledFill };
|
|
@@ -0,0 +1,214 @@
|
|
|
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 };
|