@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,20 @@
|
|
|
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 { Base64UrlString } from "./types.js";
|
|
5
|
+
//#region src/base64url.d.ts
|
|
6
|
+
declare function encodeBase64Url(bytes: Uint8Array): Base64UrlString;
|
|
7
|
+
/**
|
|
8
|
+
* Decodes into `out` at `offset` when given one, otherwise into a fresh array.
|
|
9
|
+
*
|
|
10
|
+
* Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
|
|
11
|
+
* `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
|
|
12
|
+
* size, with the data at `offset` and no way to learn how many bytes had been written short of
|
|
13
|
+
* recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
|
|
14
|
+
* makes the length usable and leaves the caller's own buffer reachable, since they own it.
|
|
15
|
+
*/
|
|
16
|
+
declare function decodeBase64Url(value: string, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
17
|
+
declare function isBase64Url(value: null | string | undefined): value is Base64UrlString;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { decodeBase64Url, encodeBase64Url, isBase64Url };
|
|
20
|
+
//# sourceMappingURL=base64url.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base64url.d.ts","names":[],"sources":["../src/base64url.ts"],"mappings":";;;;;iBAMgB,gBAAgB,OAAO,aAAa;;;;;;;;;;iBAapC,gBACd,eACA,MAAM,YACN,kBACC,gBAAgB;iBAYH,YAAY,mCAAmC,SAAS"}
|
|
@@ -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 { UuidSlugError } from "./errors.js";
|
|
4
|
+
import { BASE64URL, decodeInto, encode, isEncoded } from "./alphabet.js";
|
|
5
|
+
//#region src/base64url.ts
|
|
6
|
+
function encodeBase64Url(bytes) {
|
|
7
|
+
return encode(bytes, BASE64URL);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Decodes into `out` at `offset` when given one, otherwise into a fresh array.
|
|
11
|
+
*
|
|
12
|
+
* Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
|
|
13
|
+
* `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
|
|
14
|
+
* size, with the data at `offset` and no way to learn how many bytes had been written short of
|
|
15
|
+
* recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
|
|
16
|
+
* makes the length usable and leaves the caller's own buffer reachable, since they own it.
|
|
17
|
+
*/
|
|
18
|
+
function decodeBase64Url(value, out, offset = 0) {
|
|
19
|
+
if (value.includes("=")) return new UuidSlugError("invalid_base64url", "Base64url value must be unpadded.");
|
|
20
|
+
const byteLength = Math.floor(value.length * BASE64URL.bitsPerChar / 8);
|
|
21
|
+
const target = out ?? new Uint8Array(byteLength);
|
|
22
|
+
const result = decodeInto(value, BASE64URL, target, offset, byteLength);
|
|
23
|
+
if (result instanceof Error) return result;
|
|
24
|
+
return target.subarray(offset, offset + byteLength);
|
|
25
|
+
}
|
|
26
|
+
function isBase64Url(value) {
|
|
27
|
+
if (!value) return false;
|
|
28
|
+
return isEncoded(value, BASE64URL, Math.floor(value.length * BASE64URL.bitsPerChar / 8));
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { decodeBase64Url, encodeBase64Url, isBase64Url };
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=base64url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base64url.js","names":[],"sources":["../src/base64url.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { BASE64URL, decodeInto, encode, isEncoded } from \"./alphabet\";\nimport { UuidSlugError } from \"./errors\";\nimport type { Base64UrlString } from \"./types\";\n\nexport function encodeBase64Url(bytes: Uint8Array): Base64UrlString {\n return encode(bytes, BASE64URL);\n}\n\n/**\n * Decodes into `out` at `offset` when given one, otherwise into a fresh array.\n *\n * Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without\n * `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full\n * size, with the data at `offset` and no way to learn how many bytes had been written short of\n * recomputing `floor(value.length * 6 / 8)` by hand. One rule — \"the bytes this call produced\" —\n * makes the length usable and leaves the caller's own buffer reachable, since they own it.\n */\nexport function decodeBase64Url(\n value: string,\n out?: Uint8Array,\n offset = 0,\n): UuidSlugError | Uint8Array {\n // Padding is the most common malformed input by far, and the generic \"invalid character\"\n // message sends the reader looking for a typo instead of a stray \"=\".\n if (value.includes(\"=\"))\n return new UuidSlugError(\"invalid_base64url\", \"Base64url value must be unpadded.\");\n const byteLength = Math.floor((value.length * BASE64URL.bitsPerChar) / 8);\n const target = out ?? new Uint8Array(byteLength);\n const result = decodeInto(value, BASE64URL, target, offset, byteLength);\n if (result instanceof Error) return result;\n return target.subarray(offset, offset + byteLength);\n}\n\nexport function isBase64Url(value: null | string | undefined): value is Base64UrlString {\n // The empty string decodes to zero bytes without error, but an identifier of no characters is\n // never what a caller means by \"is this a slug\"; rejecting it keeps the guard usable as one.\n if (!value) return false;\n return isEncoded(value, BASE64URL, Math.floor((value.length * BASE64URL.bitsPerChar) / 8));\n}\n"],"mappings":";;;;;AAMA,SAAgB,gBAAgB,OAAoC;CAClE,OAAO,OAAO,OAAO,SAAS;AAChC;;;;;;;;;;AAWA,SAAgB,gBACd,OACA,KACA,SAAS,GACmB;CAG5B,IAAI,MAAM,SAAS,GAAG,GACpB,OAAO,IAAI,cAAc,qBAAqB,mCAAmC;CACnF,MAAM,aAAa,KAAK,MAAO,MAAM,SAAS,UAAU,cAAe,CAAC;CACxE,MAAM,SAAS,OAAO,IAAI,WAAW,UAAU;CAC/C,MAAM,SAAS,WAAW,OAAO,WAAW,QAAQ,QAAQ,UAAU;CACtE,IAAI,kBAAkB,OAAO,OAAO;CACpC,OAAO,OAAO,SAAS,QAAQ,SAAS,UAAU;AACpD;AAEA,SAAgB,YAAY,OAA4D;CAGtF,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,UAAU,OAAO,WAAW,KAAK,MAAO,MAAM,SAAS,UAAU,cAAe,CAAC,CAAC;AAC3F"}
|
package/dist/codec.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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 { FreshValidationOptions, UuidSlugCodec, UuidSlugCodecOptions, UuidV7SentinelDefinition, UuidV7Slug, UuidV7String } from "./types.js";
|
|
5
|
+
//#region src/codec.d.ts
|
|
6
|
+
declare const UUID_V7_SENTINEL_DEFINITIONS: readonly UuidV7SentinelDefinition[];
|
|
7
|
+
declare function createUuidSlugCodec(options?: UuidSlugCodecOptions): UuidSlugCodec;
|
|
8
|
+
/**
|
|
9
|
+
* Uses the published default seed, so anyone can decode its masked slugs.
|
|
10
|
+
* Use `createUuidSlugCodec({ mask: { seed } })` with your own seed to hide identifiers.
|
|
11
|
+
*/
|
|
12
|
+
declare const defaultCodec: UuidSlugCodec;
|
|
13
|
+
declare function validateUuidV7Fresh(uuid: string, options?: FreshValidationOptions): UuidSlugError | UuidV7String;
|
|
14
|
+
declare function validateUuidV7SlugFresh(slug: string, options?: FreshValidationOptions): UuidSlugError | UuidV7Slug;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { UUID_V7_SENTINEL_DEFINITIONS, createUuidSlugCodec, defaultCodec, validateUuidV7Fresh, validateUuidV7SlugFresh };
|
|
17
|
+
//# sourceMappingURL=codec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec.d.ts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;cAoCa,uCAAuC;iBA6EpC,oBAAoB,UAAS,uBAA4B;;;;;cA4J5D,cAAc;iBAEX,oBACd,cACA,UAAS,yBACR,gBAAgB;iBAqCH,wBACd,cACA,UAAU,yBACT,gBAAgB"}
|
package/dist/codec.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidSlugError, errorOrThrow, readClock } from "./errors.js";
|
|
4
|
+
import { runtime } from "./runtime/web.js";
|
|
5
|
+
import { extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isUuidV7Bytes, parseUuid, parseUuidSlug, resolveSlugAlphabet } from "./uuid.js";
|
|
6
|
+
import { createRuntimeGenerator } from "./v7.js";
|
|
7
|
+
import { uuidV4, uuidV4Bytes } from "./keyless.js";
|
|
8
|
+
import { decodeMaskedSlug, uuidV7BytesToMaskedSlug } from "./mask.js";
|
|
9
|
+
import { createMigration } from "./migration.js";
|
|
10
|
+
import { DEFAULT_MASK_SCHEMA, createMaskSchema, verifyInvertible } from "./schema.js";
|
|
11
|
+
//#region src/codec.ts
|
|
12
|
+
const UUID_V7_SENTINEL_DEFINITIONS = [
|
|
13
|
+
{
|
|
14
|
+
name: "nil",
|
|
15
|
+
uuid: "00000000-0000-7000-8000-000000000000"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
name: "anonymousUser",
|
|
19
|
+
uuid: "00000000-0001-7000-8000-000000000000"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: "unknownUser",
|
|
23
|
+
uuid: "00000000-0002-7000-8000-000000000000"
|
|
24
|
+
}
|
|
25
|
+
];
|
|
26
|
+
function schemaFromOption(mask) {
|
|
27
|
+
if (!mask) return DEFAULT_MASK_SCHEMA;
|
|
28
|
+
if (!("mix" in mask)) return createMaskSchema(mask);
|
|
29
|
+
return verifyInvertible(mask);
|
|
30
|
+
}
|
|
31
|
+
function createSentinels(definitions) {
|
|
32
|
+
const sentinels = [];
|
|
33
|
+
const byUuid = /* @__PURE__ */ new Set();
|
|
34
|
+
const encoded = [];
|
|
35
|
+
const bySlug = /* @__PURE__ */ new Map();
|
|
36
|
+
for (const definition of definitions) {
|
|
37
|
+
const bytes = errorOrThrow(parseUuid(definition.uuid));
|
|
38
|
+
if (!isUuidV7Bytes(bytes)) throw new UuidSlugError("invalid_uuid_version", `Sentinel "${definition.name}" must be a UUIDv7, got ${String(definition.uuid)}.`);
|
|
39
|
+
if (byUuid.has(definition.uuid)) throw new UuidSlugError("invalid_uuid", `Sentinel "${definition.name}" repeats the UUID of an earlier sentinel.`);
|
|
40
|
+
const slug = formatUuidSlug(bytes);
|
|
41
|
+
if (slug instanceof Error) throw slug;
|
|
42
|
+
const sentinel = Object.freeze({
|
|
43
|
+
name: definition.name,
|
|
44
|
+
slug,
|
|
45
|
+
uuid: definition.uuid
|
|
46
|
+
});
|
|
47
|
+
sentinels.push(sentinel);
|
|
48
|
+
byUuid.add(definition.uuid);
|
|
49
|
+
encoded.push({
|
|
50
|
+
bytes,
|
|
51
|
+
slug: sentinel.slug
|
|
52
|
+
});
|
|
53
|
+
bySlug.set(sentinel.slug, {
|
|
54
|
+
uuid: definition.uuid,
|
|
55
|
+
bytes
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
bySlug,
|
|
60
|
+
encoded,
|
|
61
|
+
sentinels: Object.freeze(sentinels)
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function createUuidSlugCodec(options = {}) {
|
|
65
|
+
const schema = errorOrThrow(schemaFromOption(options.mask));
|
|
66
|
+
const previousMasks = (options.previousMasks ?? []).map((mask) => errorOrThrow(schemaFromOption(mask)));
|
|
67
|
+
const generator = options.generator ?? createRuntimeGenerator(runtime);
|
|
68
|
+
const slugAlphabet = options.slugAlphabet ?? "base64url";
|
|
69
|
+
errorOrThrow(resolveSlugAlphabet(slugAlphabet));
|
|
70
|
+
const acceptUnmaskedSlugs = options.acceptUnmaskedSlugs === true;
|
|
71
|
+
const nativeSlug = options.generator === void 0 && slugAlphabet === "base64url" ? runtime.uuidV7Slug : void 0;
|
|
72
|
+
const sentinelState = createSentinels(options.sentinels ?? UUID_V7_SENTINEL_DEFINITIONS);
|
|
73
|
+
function decodeMasked(slug) {
|
|
74
|
+
const primary = decodeMaskedSlug(slug, schema, previousMasks);
|
|
75
|
+
if (!(primary instanceof Error)) return primary;
|
|
76
|
+
if (acceptUnmaskedSlugs) {
|
|
77
|
+
const unmasked = parseUuidSlug(slug);
|
|
78
|
+
if (!(unmasked instanceof Error)) return unmasked;
|
|
79
|
+
}
|
|
80
|
+
return primary;
|
|
81
|
+
}
|
|
82
|
+
function encodeMasked(bytes) {
|
|
83
|
+
if (!isUuidV7Bytes(bytes)) return new UuidSlugError("invalid_uuid_version", "Masked UUID slugs require 16 UUIDv7 bytes.");
|
|
84
|
+
for (const sentinel of sentinelState.encoded) {
|
|
85
|
+
let index = 0;
|
|
86
|
+
while (index < 16 && sentinel.bytes[index] === bytes[index]) index += 1;
|
|
87
|
+
if (index === 16) return sentinel.slug;
|
|
88
|
+
}
|
|
89
|
+
const slug = uuidV7BytesToMaskedSlug(bytes, schema);
|
|
90
|
+
if (slug instanceof Error) return slug;
|
|
91
|
+
if (sentinelState.bySlug.has(slug)) return new UuidSlugError("invalid_mask_schema", "Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.");
|
|
92
|
+
return slug;
|
|
93
|
+
}
|
|
94
|
+
function uuidV7ToMaskedSlug(uuid) {
|
|
95
|
+
const bytes = parseUuid(uuid);
|
|
96
|
+
return bytes instanceof Error ? bytes : encodeMasked(bytes);
|
|
97
|
+
}
|
|
98
|
+
function maskedSlugToUuidV7(slug) {
|
|
99
|
+
const sentinel = sentinelState.bySlug.get(slug);
|
|
100
|
+
if (sentinel) return sentinel.uuid;
|
|
101
|
+
const decoded = decodeMasked(slug);
|
|
102
|
+
if (decoded instanceof Error) return decoded;
|
|
103
|
+
if (acceptUnmaskedSlugs && !isUuidV7Bytes(decoded)) return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
|
|
104
|
+
return formatUuid(decoded);
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
sentinels: sentinelState.sentinels,
|
|
108
|
+
migration(migrationOptions) {
|
|
109
|
+
return createMigration([schema, ...previousMasks], sentinelState.bySlug, migrationOptions);
|
|
110
|
+
},
|
|
111
|
+
uuidV4,
|
|
112
|
+
uuidV7() {
|
|
113
|
+
return generator.uuidV7();
|
|
114
|
+
},
|
|
115
|
+
uuidV4Bytes,
|
|
116
|
+
uuidV7Bytes: generator.uuidV7Bytes,
|
|
117
|
+
uuidV7At: generator.uuidV7At,
|
|
118
|
+
uuidV7BytesAt: generator.uuidV7BytesAt,
|
|
119
|
+
uuidV4Slug() {
|
|
120
|
+
return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, slugAlphabet));
|
|
121
|
+
},
|
|
122
|
+
uuidV7Slug() {
|
|
123
|
+
if (nativeSlug) return nativeSlug();
|
|
124
|
+
return errorOrThrow(formatUuidSlug(errorOrThrow(generator.uuidV7Bytes()), 0, slugAlphabet));
|
|
125
|
+
},
|
|
126
|
+
uuidV7MaskedSlug() {
|
|
127
|
+
return errorOrThrow(encodeMasked(errorOrThrow(generator.uuidV7Bytes())));
|
|
128
|
+
},
|
|
129
|
+
uuidV7ToMaskedSlug,
|
|
130
|
+
maskedSlugToUuidV7,
|
|
131
|
+
maskedSlugToUuid(slug) {
|
|
132
|
+
const sentinel = sentinelState.bySlug.get(slug);
|
|
133
|
+
if (sentinel) return sentinel.uuid;
|
|
134
|
+
const bytes = decodeMasked(slug);
|
|
135
|
+
return bytes instanceof Error ? bytes : formatUuid(bytes);
|
|
136
|
+
},
|
|
137
|
+
/**
|
|
138
|
+
* Unmask, then apply the same freshness rules as `validateUuidV7Fresh`, returning the slug.
|
|
139
|
+
*
|
|
140
|
+
* A METHOD rather than the module-level function it replaced: unmasking needs this codec's
|
|
141
|
+
* key, and the old free function reached for `defaultCodec` — so it silently answered under
|
|
142
|
+
* the seed published in this package's source and was wrong for every caller who supplied
|
|
143
|
+
* their own. Nothing about that failure was visible at the call site; it returned a confident
|
|
144
|
+
* Error for perfectly good slugs.
|
|
145
|
+
*
|
|
146
|
+
* Decode directly to bytes instead of formatting and reparsing a UUID. The method does not
|
|
147
|
+
* access `this`, so it also works when detached from the codec.
|
|
148
|
+
*/
|
|
149
|
+
validateMaskedSlugFresh(slug, freshness) {
|
|
150
|
+
const bytes = sentinelState.bySlug.get(slug)?.bytes ?? decodeMasked(slug);
|
|
151
|
+
if (bytes instanceof Error) return bytes;
|
|
152
|
+
if (!isUuidV7Bytes(bytes)) return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
|
|
153
|
+
const valid = validateFreshBytes(bytes, freshness);
|
|
154
|
+
return valid instanceof Error ? valid : slug;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Uses the published default seed, so anyone can decode its masked slugs.
|
|
160
|
+
* Use `createUuidSlugCodec({ mask: { seed } })` with your own seed to hide identifiers.
|
|
161
|
+
*/
|
|
162
|
+
const defaultCodec = /*#__PURE__*/ createUuidSlugCodec();
|
|
163
|
+
function validateUuidV7Fresh(uuid, options = {}) {
|
|
164
|
+
const bytes = parseUuid(uuid);
|
|
165
|
+
if (bytes instanceof Error) return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
|
|
166
|
+
const valid = validateFreshBytes(bytes, options);
|
|
167
|
+
return valid instanceof Error ? valid : uuid;
|
|
168
|
+
}
|
|
169
|
+
/** Capture decoded fields before calling an external clock, which can reenter a custom schema. */
|
|
170
|
+
function validateFreshBytes(bytes, options = {}) {
|
|
171
|
+
if (!isUuidV7Bytes(bytes)) return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
|
|
172
|
+
const timestamp = extractUuidV7Timestamp(bytes);
|
|
173
|
+
if (timestamp instanceof Error) return timestamp;
|
|
174
|
+
const hasEntropy = hasUuidV7Entropy(bytes);
|
|
175
|
+
const windowMs = options.windowMs ?? 864e5;
|
|
176
|
+
if (!Number.isFinite(windowMs) || windowMs < 0) return new UuidSlugError("invalid_timestamp", "windowMs must be a finite, nonnegative number of milliseconds.");
|
|
177
|
+
const now = readClock(options.now ?? Date.now);
|
|
178
|
+
if (now instanceof Error) return now;
|
|
179
|
+
if (!Number.isFinite(now)) return new UuidSlugError("invalid_timestamp", "now must return a finite number of Unix milliseconds.");
|
|
180
|
+
if (timestamp < now - windowMs || timestamp > now + windowMs) return new UuidSlugError("stale_uuid", "UUIDv7 timestamp is outside the accepted window.");
|
|
181
|
+
if (!hasEntropy) return new UuidSlugError("invalid_uuid", "UUIDv7 random payload is degenerate.");
|
|
182
|
+
}
|
|
183
|
+
function validateUuidV7SlugFresh(slug, options) {
|
|
184
|
+
const bytes = parseUuidSlug(slug);
|
|
185
|
+
if (bytes instanceof Error) return bytes;
|
|
186
|
+
const valid = validateFreshBytes(bytes, options);
|
|
187
|
+
return valid instanceof Error ? valid : slug;
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
export { UUID_V7_SENTINEL_DEFINITIONS, createUuidSlugCodec, defaultCodec, validateUuidV7Fresh, validateUuidV7SlugFresh };
|
|
191
|
+
|
|
192
|
+
//# sourceMappingURL=codec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec.js","names":["generateUuidV4","generateUuidV4Bytes"],"sources":["../src/codec.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { runtime } from \"#runtime\";\nimport { errorOrThrow, readClock, UuidSlugError } from \"./errors\";\n// A v4 has ONE implementation however it is reached. The keyless module owns it because that is\n// the module a consumer who never masks pulls in; importing it here costs a codec consumer nothing\n// it was not already paying, whereas the reverse direction would put the codec back on the keyless\n// path and undo the whole saving that split exists for.\nimport { uuidV4Bytes as generateUuidV4Bytes, uuidV4 as generateUuidV4 } from \"./keyless\";\nimport { uuidV7BytesToMaskedSlug, decodeMaskedSlug } from \"./mask\";\nimport { createMigration } from \"./migration\";\nimport { createMaskSchema, DEFAULT_MASK_SCHEMA, verifyInvertible } from \"./schema\";\nimport type {\n MaskSchema,\n PublicUuidV7Slug,\n SentinelUuidV7Slug,\n UuidSlugCodec,\n UuidSlugCodecOptions,\n UuidV4Slug,\n UuidV7Sentinel,\n UuidV7String,\n UuidV7Slug,\n} from \"./types\";\nimport { createRuntimeGenerator } from \"./v7\";\nimport {\n formatUuidSlug,\n hasUuidV7Entropy,\n isUuidV7Bytes,\n resolveSlugAlphabet,\n parseUuid,\n formatUuid,\n parseUuidSlug,\n extractUuidV7Timestamp,\n} from \"./uuid\";\nimport type { FreshValidationOptions, UuidV7SentinelDefinition } from \"./types\";\n\nexport const UUID_V7_SENTINEL_DEFINITIONS: readonly UuidV7SentinelDefinition[] = [\n {\n name: \"nil\",\n uuid: \"00000000-0000-7000-8000-000000000000\",\n },\n {\n name: \"anonymousUser\",\n uuid: \"00000000-0001-7000-8000-000000000000\",\n },\n {\n name: \"unknownUser\",\n uuid: \"00000000-0002-7000-8000-000000000000\",\n },\n];\n\nfunction schemaFromOption(mask: UuidSlugCodecOptions[\"mask\"]): UuidSlugError | MaskSchema {\n // Omitting `mask` yields a codec that masks under a seed published in this package's source, so\n // its masked slugs are decodable by anyone. That is a real configuration — tests and demos want\n // reproducible output — but it is never the one a caller protecting ids wants, and nothing about\n // the resulting slug reveals which they got. See `defaultCodec` and `UuidSlugCodecOptions.mask`.\n if (!mask) return DEFAULT_MASK_SCHEMA;\n // A built schema carries its mixing step; an options object carries only a seed to derive one\n // from. One discriminating property beats sniffing several, which silently stops discriminating\n // when a scheme is added whose data fields differ.\n //\n // Every schema the codec will use passes through here, which is why the invertibility smoke test\n // belongs here and nowhere else: a caller-supplied `mix` is the extension point now, and an\n // unchecked one silently makes every id it encodes unreadable.\n if (!(\"mix\" in mask)) return createMaskSchema(mask);\n return verifyInvertible(mask);\n}\n\nfunction createSentinels(definitions: readonly UuidV7SentinelDefinition[]) {\n const sentinels: UuidV7Sentinel[] = [];\n const byUuid = new Set<string>();\n const encoded: { bytes: Uint8Array; slug: SentinelUuidV7Slug }[] = [];\n const bySlug = new Map<string, { uuid: UuidV7String; bytes: Uint8Array }>();\n for (const definition of definitions) {\n // `uuid` is typed `UuidV7String`, and that types NOTHING: `Brand`'s marker is optional by\n // design, so every string satisfies every brand and a v4 passed the declaration untouched.\n // It then constructed fine, masked fine, and failed on EVERY decode forever after — a\n // permanent, per-call error configured once at construction. Checked here for the same reason\n // the invertibility smoke test is checked here: this is the last point at which a bad definition is\n // still a caller's argument rather than a codec that cannot work.\n const bytes = errorOrThrow(parseUuid(definition.uuid));\n if (!isUuidV7Bytes(bytes))\n throw new UuidSlugError(\n \"invalid_uuid_version\",\n `Sentinel \"${definition.name}\" must be a UUIDv7, got ${String(definition.uuid)}.`,\n );\n // A duplicate collapses SILENTLY: both entries stay in `codec.sentinels`, while the lookup maps\n // keep only the last, so the codec reports a sentinel it will never match.\n if (byUuid.has(definition.uuid))\n throw new UuidSlugError(\n \"invalid_uuid\",\n `Sentinel \"${definition.name}\" repeats the UUID of an earlier sentinel.`,\n );\n // Always base64url, never the codec's `slugAlphabet`: a sentinel slug is matched against\n // MASKED input, which is base64url by definition, so one written in another alphabet could\n // never be recognised in the position it exists for.\n const slug = formatUuidSlug(bytes);\n if (slug instanceof Error) throw slug;\n const sentinel = Object.freeze({\n name: definition.name,\n // `formatUuidSlug` returns the version-agnostic brand; the v7-ness comes\n // from the check above.\n slug: slug as SentinelUuidV7Slug,\n uuid: definition.uuid,\n });\n sentinels.push(sentinel);\n byUuid.add(definition.uuid);\n encoded.push({ bytes, slug: sentinel.slug });\n bySlug.set(sentinel.slug, { uuid: definition.uuid, bytes });\n }\n return { bySlug, encoded, sentinels: Object.freeze(sentinels) };\n}\n\nexport function createUuidSlugCodec(options: UuidSlugCodecOptions = {}): UuidSlugCodec {\n const schema = errorOrThrow(schemaFromOption(options.mask));\n // Every schema a decode may try, and NOTHING a caller did not list. A codec once appended two\n // schemas of its own — a substitution partner derived from any seed, and the default seed's\n // pre-Feistel scheme — on the reasoning that a marker bit would select one outright. No marker\n // exists: each schema is tried in turn and the first whose check passes wins, so the codec's\n // false-accept rate is the SUM over the list and is set by its weakest member. Measured\n // 2026-08-12 over 200,000 wrong-key decodes, the auto-added 6-bit partner accepted 211 while\n // the 16-bit schema it accompanied accepted 2 — a 16x widening nobody asked for.\n const previousMasks = (options.previousMasks ?? []).map((mask) =>\n errorOrThrow(schemaFromOption(mask)),\n );\n const generator = options.generator ?? createRuntimeGenerator(runtime);\n const slugAlphabet = options.slugAlphabet ?? \"base64url\";\n errorOrThrow(resolveSlugAlphabet(slugAlphabet));\n const acceptUnmaskedSlugs = options.acceptUnmaskedSlugs === true;\n // The runtime's own slug generator emits base64url and nothing else, so it can only serve the\n // default. Resolved once here rather than per call: the branch is on configuration, which cannot\n // change after construction.\n const nativeSlug =\n options.generator === undefined && slugAlphabet === \"base64url\"\n ? runtime.uuidV7Slug\n : undefined;\n const sentinelState = createSentinels(options.sentinels ?? UUID_V7_SENTINEL_DEFINITIONS);\n\n function decodeMasked(slug: string): UuidSlugError | Uint8Array {\n const primary = decodeMaskedSlug(slug, schema, previousMasks);\n if (!(primary instanceof Error)) return primary;\n if (acceptUnmaskedSlugs) {\n const unmasked = parseUuidSlug(slug);\n if (!(unmasked instanceof Error)) return unmasked;\n }\n // The fallback's error is DROPPED, deliberately, and this returns `primary` whether or not the\n // fallback ran. It answers a different question — \"is this a plain slug?\" — and for the failure\n // that actually brings people here, a wrong or rotated key, its answer is untrue: the input is\n // perfectly good base64url whose trailing bits ARE the mask check, so it reported\n // `invalid_base64url: non-canonical trailing bits` and sent operators hunting a typo.\n // `primary` says the schema did not match, which is what happened.\n return primary;\n }\n\n function encodeMasked(bytes: Uint8Array): UuidSlugError | PublicUuidV7Slug {\n if (!isUuidV7Bytes(bytes))\n return new UuidSlugError(\n \"invalid_uuid_version\",\n \"Masked UUID slugs require 16 UUIDv7 bytes.\",\n );\n for (const sentinel of sentinelState.encoded) {\n let index = 0;\n while (index < 16 && sentinel.bytes[index] === bytes[index]) index += 1;\n if (index === 16) return sentinel.slug;\n }\n const slug = uuidV7BytesToMaskedSlug(bytes, schema);\n if (slug instanceof Error) return slug;\n // Sentinel decoding takes precedence, so returning this ciphertext would recover a different UUID.\n if (sentinelState.bySlug.has(slug))\n return new UuidSlugError(\n \"invalid_mask_schema\",\n \"Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.\",\n );\n return slug;\n }\n\n function uuidV7ToMaskedSlug(uuid: string): UuidSlugError | PublicUuidV7Slug {\n const bytes = parseUuid(uuid);\n return bytes instanceof Error ? bytes : encodeMasked(bytes);\n }\n\n function maskedSlugToUuidV7(slug: string): UuidSlugError | UuidV7String {\n const sentinel = sentinelState.bySlug.get(slug);\n if (sentinel) return sentinel.uuid;\n const decoded = decodeMasked(slug);\n if (decoded instanceof Error) return decoded;\n // Mask decoding restores v7 constants; only the plain fallback can carry another version.\n if (acceptUnmaskedSlugs && !isUuidV7Bytes(decoded))\n return new UuidSlugError(\"invalid_uuid_version\", \"Decoded UUID is not UUIDv7.\");\n return formatUuid(decoded) as UuidSlugError | UuidV7String;\n }\n\n return {\n sentinels: sentinelState.sentinels,\n migration(migrationOptions) {\n return createMigration([schema, ...previousMasks], sentinelState.bySlug, migrationOptions);\n },\n uuidV4: generateUuidV4,\n uuidV7() {\n return generator.uuidV7();\n },\n uuidV4Bytes: generateUuidV4Bytes,\n uuidV7Bytes: generator.uuidV7Bytes,\n uuidV7At: generator.uuidV7At,\n uuidV7BytesAt: generator.uuidV7BytesAt,\n uuidV4Slug() {\n // The bytes came from `generateUuidV4Bytes`, which stamps version 4; the encoder sees only\n // bytes and cannot carry that through.\n return errorOrThrow(\n formatUuidSlug(errorOrThrow(generateUuidV4Bytes()), 0, slugAlphabet),\n ) as UuidV4Slug;\n },\n uuidV7Slug() {\n if (nativeSlug) return nativeSlug();\n // Same assertion `uuidV4Slug` makes for the same reason: the bytes come from a v7 generator,\n // and the encoder sees only bytes so it cannot carry the version through. Until the runtime\n // hooks were branded this cast was ABSENT and nothing complained — the native branch typed\n // the union as bare `string`, which an optional brand accepts, so the promise went unchecked.\n return errorOrThrow(\n formatUuidSlug(errorOrThrow(generator.uuidV7Bytes()), 0, slugAlphabet),\n ) as UuidV7Slug;\n },\n uuidV7MaskedSlug() {\n return errorOrThrow(encodeMasked(errorOrThrow(generator.uuidV7Bytes())));\n },\n uuidV7ToMaskedSlug,\n maskedSlugToUuidV7,\n maskedSlugToUuid(slug) {\n const sentinel = sentinelState.bySlug.get(slug);\n if (sentinel) return sentinel.uuid;\n const bytes = decodeMasked(slug);\n return bytes instanceof Error ? bytes : formatUuid(bytes);\n },\n /**\n * Unmask, then apply the same freshness rules as `validateUuidV7Fresh`, returning the slug.\n *\n * A METHOD rather than the module-level function it replaced: unmasking needs this codec's\n * key, and the old free function reached for `defaultCodec` — so it silently answered under\n * the seed published in this package's source and was wrong for every caller who supplied\n * their own. Nothing about that failure was visible at the call site; it returned a confident\n * Error for perfectly good slugs.\n *\n * Decode directly to bytes instead of formatting and reparsing a UUID. The method does not\n * access `this`, so it also works when detached from the codec.\n */\n validateMaskedSlugFresh(slug, freshness) {\n const bytes = sentinelState.bySlug.get(slug)?.bytes ?? decodeMasked(slug);\n if (bytes instanceof Error) return bytes;\n // The v7-specific decoder reports this before freshness validation does.\n if (!isUuidV7Bytes(bytes))\n return new UuidSlugError(\"invalid_uuid_version\", \"Decoded UUID is not UUIDv7.\");\n const valid = validateFreshBytes(bytes, freshness);\n return valid instanceof Error ? valid : slug;\n },\n };\n}\n\n/**\n * Uses the published default seed, so anyone can decode its masked slugs.\n * Use `createUuidSlugCodec({ mask: { seed } })` with your own seed to hide identifiers.\n */\n// Annotated PURE so a bundle that never names it can drop it: a module-scope CONSTRUCTION call is\n// otherwise a side effect no bundler may remove, and this one reaches the cipher, the mask schema\n// and the sentinel table. Sound because `createUuidSlugCodec()` with no options cannot fail — the\n// only throwing paths are caller-supplied sentinels and a caller-supplied mix — and nothing else\n// observes the construction. The annotation is worth nothing on its own: it was measured saving\n// ZERO bytes while `index.ts` bound its shortcuts as PROPERTY READS of this value, since a read at\n// module scope forces the evaluation the annotation permits skipping. Keep the shortcuts keyless\n// (see `keyless.ts`) or this goes dead again.\nexport const defaultCodec: UuidSlugCodec = /*#__PURE__*/ createUuidSlugCodec();\n\nexport function validateUuidV7Fresh(\n uuid: string,\n options: FreshValidationOptions = {},\n): UuidSlugError | UuidV7String {\n const bytes = parseUuid(uuid);\n if (bytes instanceof Error)\n return new UuidSlugError(\"invalid_uuid\", \"Expected canonical UUIDv7 string.\");\n const valid = validateFreshBytes(bytes, options);\n return valid instanceof Error ? valid : uuid;\n}\n\n/** Capture decoded fields before calling an external clock, which can reenter a custom schema. */\nfunction validateFreshBytes(\n bytes: Uint8Array,\n options: FreshValidationOptions = {},\n): UuidSlugError | undefined {\n if (!isUuidV7Bytes(bytes))\n return new UuidSlugError(\"invalid_uuid\", \"Expected canonical UUIDv7 string.\");\n const timestamp = extractUuidV7Timestamp(bytes);\n if (timestamp instanceof Error) return timestamp;\n const hasEntropy = hasUuidV7Entropy(bytes);\n const windowMs = options.windowMs ?? 86_400_000;\n if (!Number.isFinite(windowMs) || windowMs < 0)\n return new UuidSlugError(\n \"invalid_timestamp\",\n \"windowMs must be a finite, nonnegative number of milliseconds.\",\n );\n const now = readClock(options.now ?? Date.now);\n if (now instanceof Error) return now;\n if (!Number.isFinite(now))\n return new UuidSlugError(\n \"invalid_timestamp\",\n \"now must return a finite number of Unix milliseconds.\",\n );\n if (timestamp < now - windowMs || timestamp > now + windowMs)\n return new UuidSlugError(\"stale_uuid\", \"UUIDv7 timestamp is outside the accepted window.\");\n if (!hasEntropy) return new UuidSlugError(\"invalid_uuid\", \"UUIDv7 random payload is degenerate.\");\n return undefined;\n}\n\nexport function validateUuidV7SlugFresh(\n slug: string,\n options?: FreshValidationOptions,\n): UuidSlugError | UuidV7Slug {\n const bytes = parseUuidSlug(slug);\n if (bytes instanceof Error) return byt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ors.d.ts
|
|
4
|
+
/** Consumers can enumerate error codes at runtime without duplicating the type's vocabulary. */
|
|
5
|
+
declare const UUID_SLUG_ERROR_CODES: readonly ["aborted", "invalid_base32", "invalid_base64url", "invalid_buffer", "invalid_mask_schema", "invalid_timestamp", "invalid_uuid", "invalid_uuid_slug", "invalid_uuid_version", "rng_unavailable", "stale_uuid"];
|
|
6
|
+
type UuidSlugErrorCode = (typeof UUID_SLUG_ERROR_CODES)[number];
|
|
7
|
+
declare class UuidSlugError extends Error {
|
|
8
|
+
readonly code: UuidSlugErrorCode;
|
|
9
|
+
constructor(code: UuidSlugErrorCode, message: string, options?: ErrorOptions);
|
|
10
|
+
}
|
|
11
|
+
declare class UuidRuntimeError extends UuidSlugError {
|
|
12
|
+
constructor(message: string, options?: ErrorOptions);
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { UUID_SLUG_ERROR_CODES, UuidRuntimeError, UuidSlugError, UuidSlugErrorCode };
|
|
16
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;;;cAGa;KAcD,4BAA4B;cAE3B,sBAAsB;WACxB,MAAM;EAEf,YAAY,MAAM,mBAAmB,iBAAiB,UAAU;;cAOrD,yBAAyB;EACpC,YAAY,iBAAiB,UAAU"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
//#region src/errors.ts
|
|
4
|
+
/** Consumers can enumerate error codes at runtime without duplicating the type's vocabulary. */
|
|
5
|
+
const UUID_SLUG_ERROR_CODES = [
|
|
6
|
+
"aborted",
|
|
7
|
+
"invalid_base32",
|
|
8
|
+
"invalid_base64url",
|
|
9
|
+
"invalid_buffer",
|
|
10
|
+
"invalid_mask_schema",
|
|
11
|
+
"invalid_timestamp",
|
|
12
|
+
"invalid_uuid",
|
|
13
|
+
"invalid_uuid_slug",
|
|
14
|
+
"invalid_uuid_version",
|
|
15
|
+
"rng_unavailable",
|
|
16
|
+
"stale_uuid"
|
|
17
|
+
];
|
|
18
|
+
var UuidSlugError = class extends Error {
|
|
19
|
+
code;
|
|
20
|
+
constructor(code, message, options) {
|
|
21
|
+
super(message, options);
|
|
22
|
+
this.name = "UuidSlugError";
|
|
23
|
+
this.code = code;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var UuidRuntimeError = class extends UuidSlugError {
|
|
27
|
+
constructor(message, options) {
|
|
28
|
+
super("rng_unavailable", message, options);
|
|
29
|
+
this.name = "UuidRuntimeError";
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* The bridge from this package's `Error | T` return convention to the generator convention, where
|
|
34
|
+
* a failure throws. Shared rather than repeated because every module that has both conventions
|
|
35
|
+
* meeting in it needs exactly this, and a local copy is one `instanceof` away from being written
|
|
36
|
+
* as a truthiness test that swallows a legitimate falsy result.
|
|
37
|
+
*/
|
|
38
|
+
function errorOrThrow(value) {
|
|
39
|
+
if (value instanceof Error) throw value;
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The one range check for every entry point that reads or writes a caller's buffer at an offset.
|
|
44
|
+
*
|
|
45
|
+
* `Number.isInteger` is the load-bearing half and the reason this is shared rather than repeated.
|
|
46
|
+
* The obvious spelling — `offset < 0 || offset + need > capacity` — passes a fractional or
|
|
47
|
+
* NaN offset, because both of its comparisons are false for NaN and neither notices `0.5`. What
|
|
48
|
+
* follows is worse than a wrong answer: `bytes[0.5] = x` is not a store, so the write SILENTLY does
|
|
49
|
+
* nothing while the guard reports success, and an id can come back half-written with the caller's
|
|
50
|
+
* stale bytes in the rest of it. A string offset defeats the same test from the other side, by
|
|
51
|
+
* concatenation: `"4" + 16` is `"416"`, which is not greater than any plausible length.
|
|
52
|
+
*
|
|
53
|
+
* Seven near-identical copies of that test existed across this package and not one checked
|
|
54
|
+
* integrality — the copying is why. One copy is what stops the class returning.
|
|
55
|
+
*/
|
|
56
|
+
function checkRange(capacity, offset, need) {
|
|
57
|
+
if (!Number.isInteger(offset)) return new UuidSlugError("invalid_buffer", `Buffer offset must be a whole number, got ${typeof offset} ${String(offset)}.`);
|
|
58
|
+
if (offset < 0 || offset + need > capacity) return new UuidSlugError("invalid_buffer", `Buffer needs ${need} bytes at offset ${offset}, but holds ${capacity}.`);
|
|
59
|
+
}
|
|
60
|
+
/** Preserve failures from an injected or platform entropy source without changing successful draws. */
|
|
61
|
+
function fillRandomBytes(fill, bytes) {
|
|
62
|
+
try {
|
|
63
|
+
fill(bytes);
|
|
64
|
+
return;
|
|
65
|
+
} catch (cause) {
|
|
66
|
+
return new UuidRuntimeError("Random byte generation failed.", { cause });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Read once so a failing clock keeps its original cause and successful clocks have one observation. */
|
|
70
|
+
function readClock(clock) {
|
|
71
|
+
try {
|
|
72
|
+
return clock();
|
|
73
|
+
} catch (cause) {
|
|
74
|
+
return new UuidSlugError("invalid_timestamp", "Clock reading failed.", { cause });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
export { UUID_SLUG_ERROR_CODES, UuidRuntimeError, UuidSlugError, checkRange, errorOrThrow, fillRandomBytes, readClock };
|
|
79
|
+
|
|
80
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/** Consumers can enumerate error codes at runtime without duplicating the type's vocabulary. */\nexport const UUID_SLUG_ERROR_CODES = [\n \"aborted\",\n \"invalid_base32\",\n \"invalid_base64url\",\n \"invalid_buffer\",\n \"invalid_mask_schema\",\n \"invalid_timestamp\",\n \"invalid_uuid\",\n \"invalid_uuid_slug\",\n \"invalid_uuid_version\",\n \"rng_unavailable\",\n \"stale_uuid\",\n] as const;\n\nexport type UuidSlugErrorCode = (typeof UUID_SLUG_ERROR_CODES)[number];\n\nexport class UuidSlugError extends Error {\n readonly code: UuidSlugErrorCode;\n\n constructor(code: UuidSlugErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"UuidSlugError\";\n this.code = code;\n }\n}\n\nexport class UuidRuntimeError extends UuidSlugError {\n constructor(message: string, options?: ErrorOptions) {\n super(\"rng_unavailable\", message, options);\n this.name = \"UuidRuntimeError\";\n }\n}\n\n/**\n * The bridge from this package's `Error | T` return convention to the generator convention, where\n * a failure throws. Shared rather than repeated because every module that has both conventions\n * meeting in it needs exactly this, and a local copy is one `instanceof` away from being written\n * as a truthiness test that swallows a legitimate falsy result.\n */\nexport function errorOrThrow<T>(value: UuidSlugError | T): T {\n if (value instanceof Error) throw value;\n return value;\n}\n\n/**\n * The one range check for every entry point that reads or writes a caller's buffer at an offset.\n *\n * `Number.isInteger` is the load-bearing half and the reason this is shared rather than repeated.\n * The obvious spelling — `offset < 0 || offset + need > capacity` — passes a fractional or\n * NaN offset, because both of its comparisons are false for NaN and neither notices `0.5`. What\n * follows is worse than a wrong answer: `bytes[0.5] = x` is not a store, so the write SILENTLY does\n * nothing while the guard reports success, and an id can come back half-written with the caller's\n * stale bytes in the rest of it. A string offset defeats the same test from the other side, by\n * concatenation: `\"4\" + 16` is `\"416\"`, which is not greater than any plausible length.\n *\n * Seven near-identical copies of that test existed across this package and not one checked\n * integrality — the copying is why. One copy is what stops the class returning.\n */\nexport function checkRange(\n capacity: number,\n offset: number,\n need: number,\n): undefined | UuidSlugError {\n if (!Number.isInteger(offset))\n return new UuidSlugError(\n \"invalid_buffer\",\n `Buffer offset must be a whole number, got ${typeof offset} ${String(offset)}.`,\n );\n if (offset < 0 || offset + need > capacity)\n return new UuidSlugError(\n \"invalid_buffer\",\n `Buffer needs ${need} bytes at offset ${offset}, but holds ${capacity}.`,\n );\n return undefined;\n}\n\n/** Preserve failures from an injected or platform entropy source without changing successful draws. */\nexport function fillRandomBytes(\n fill: (bytes: Uint8Array<ArrayBuffer>) => void,\n bytes: Uint8Array<ArrayBuffer>,\n): UuidRuntimeError | undefined {\n try {\n fill(bytes);\n return undefined;\n } catch (cause) {\n return new UuidRuntimeError(\"Random byte generation failed.\", { cause });\n }\n}\n\n/** Read once so a failing clock keeps its original cause and successful clocks have one observation. */\nexport function readClock(clock: () => number): number | UuidSlugError {\n try {\n return clock();\n } catch (cause) {\n return new UuidSlugError(\"invalid_timestamp\", \"Clock reading failed.\", { cause });\n }\n}\n"],"mappings":";;;;AAGA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CAEA,YAAY,MAAyB,SAAiB,SAAwB;EAC5E,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,IAAa,mBAAb,cAAsC,cAAc;CAClD,YAAY,SAAiB,SAAwB;EACnD,MAAM,mBAAmB,SAAS,OAAO;EACzC,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,SAAgB,aAAgB,OAA6B;CAC3D,IAAI,iBAAiB,OAAO,MAAM;CAClC,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAgB,WACd,UACA,QACA,MAC2B;CAC3B,IAAI,CAAC,OAAO,UAAU,MAAM,GAC1B,OAAO,IAAI,cACT,kBACA,6CAA6C,OAAO,OAAO,GAAG,OAAO,MAAM,EAAE,EAC/E;CACF,IAAI,SAAS,KAAK,SAAS,OAAO,UAChC,OAAO,IAAI,cACT,kBACA,gBAAgB,KAAK,mBAAmB,OAAO,cAAc,SAAS,EACxE;AAEJ;;AAGA,SAAgB,gBACd,MACA,OAC8B;CAC9B,IAAI;EACF,KAAK,KAAK;EACV;CACF,SAAS,OAAO;EACd,OAAO,IAAI,iBAAiB,kCAAkC,EAAE,MAAM,CAAC;CACzE;AACF;;AAGA,SAAgB,UAAU,OAA6C;CACrE,IAAI;EACF,OAAO,MAAM;CACf,SAAS,OAAO;EACd,OAAO,IAAI,cAAc,qBAAqB,yBAAyB,EAAE,MAAM,CAAC;CAClF;AACF"}
|
package/dist/feistel.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { halfSipHash } from "./siphash.js";
|
|
4
|
+
//#region src/feistel.ts
|
|
5
|
+
/**
|
|
6
|
+
* A 4-round Feistel network over the 16 UUID bytes, used as the mask's mixing step.
|
|
7
|
+
*
|
|
8
|
+
* Why a Feistel rather than the byte permutation plus XOR it replaces: that construction is a
|
|
9
|
+
* monoalphabetic substitution — one output byte per input byte — so bytes the inputs share, the
|
|
10
|
+
* outputs share too. Measured over 3000 ids, masked slugs of UUIDv7s created in the same second
|
|
11
|
+
* held 4 of 16 bytes constant, the same hour 3, the same day 2. The timestamp the mask exists to
|
|
12
|
+
* hide was still legible in the output. A Feistel diffuses every input bit across the whole
|
|
13
|
+
* block, so no output byte is a function of one input byte: the same measurement yields 0 of 16.
|
|
14
|
+
*
|
|
15
|
+
* The bijection is the property being bought, and it holds whatever the round function does: 16
|
|
16
|
+
* bytes map to 16 bytes and the inverse is the same routine with the round keys reversed, so
|
|
17
|
+
* `mask` and `unmask` cannot drift apart.
|
|
18
|
+
*
|
|
19
|
+
* The round function is HalfSipHash-2-4 keyed per round. What that fixes: the previous round
|
|
20
|
+
* function was `mix32(word ^ roundKey)` — a FIXED, PUBLIC, UNKEYED bijection with the key merely
|
|
21
|
+
* XORed in front, so an attacker inverts it and reads `word ^ roundKey` directly. Luby-Rackoff
|
|
22
|
+
* makes a four-round Feistel a strong pseudorandom permutation only when the round functions are
|
|
23
|
+
* pseudorandom functions, which `mix32` is not, so the theorem said nothing about what shipped and
|
|
24
|
+
* an earlier version of this comment cited it wrongly. A keyed PRF meets that hypothesis in kind,
|
|
25
|
+
* which is what makes ROUNDS = 4 a justified number rather than an unexamined margin. It is still
|
|
26
|
+
* NOT a proof about what ships: the theorem wants four INDEPENDENTLY sampled round functions, and
|
|
27
|
+
* `schema.ts` derives all four key pairs from one 128-bit key. Read it as the design rationale it
|
|
28
|
+
* is, and see `docs/design.md` for what masking does and does not promise.
|
|
29
|
+
*
|
|
30
|
+
* Measured 2026-08-12 on Bun, both directions, medians of 9: the swap costs 2.5x on the mixing step
|
|
31
|
+
* alone (30.85M -> 12.43M mixes/s) and about a quarter of end-to-end masking throughput, because
|
|
32
|
+
* mixing is roughly a fifth of a mask. HalfSipHash is FASTER per round than `mix32` — pure
|
|
33
|
+
* add/xor/rotate against two `Math.imul` calls — and loses only by doing 14 rounds where the old
|
|
34
|
+
* function did the equivalent of 4.
|
|
35
|
+
*
|
|
36
|
+
* Nor does any measurement in this repository grade the round count or the round function. Strict
|
|
37
|
+
* avalanche across all input/output bit pairs, a same-millisecond burst where only a 12-bit counter
|
|
38
|
+
* varies, and a single-difference differential all PASS a TWO-round network, so none of them can
|
|
39
|
+
* separate a weak setting from a strong one. Their agreement is evidence about the instruments.
|
|
40
|
+
* `test/siphash.test.ts` is the exception and the reason a published primitive was worth taking:
|
|
41
|
+
* it checks the round function against 64 vectors somebody else computed, and that CAN fail.
|
|
42
|
+
*/
|
|
43
|
+
/**
|
|
44
|
+
* Round count. Wire-format-bearing: changing it changes every masked slug this package has ever
|
|
45
|
+
* issued, so it moves only alongside a deliberate format change. Four is Luby-Rackoff's number,
|
|
46
|
+
* which the round function now makes relevant — see the note above for why that is a rationale
|
|
47
|
+
* rather than a proof.
|
|
48
|
+
*/
|
|
49
|
+
const ROUNDS = 4;
|
|
50
|
+
/**
|
|
51
|
+
* The `lowbias32` finalizer: an integer hash with near-ideal avalanche for its size. No longer the
|
|
52
|
+
* round function — see above — but still what `mask.ts` derives its check tag with, where the input
|
|
53
|
+
* is public and an unkeyed mixer is the right tool.
|
|
54
|
+
*/
|
|
55
|
+
function mix32(value) {
|
|
56
|
+
let x = (value ^ value >>> 16) >>> 0;
|
|
57
|
+
x = Math.imul(x, 2146121005);
|
|
58
|
+
x = (x ^ x >>> 15) >>> 0;
|
|
59
|
+
x = Math.imul(x, 2221713035);
|
|
60
|
+
return (x ^ x >>> 16) >>> 0;
|
|
61
|
+
}
|
|
62
|
+
/** Big-endian on purpose: the wire format must not depend on the host's byte order. */
|
|
63
|
+
function read32(bytes, offset) {
|
|
64
|
+
return bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3] | 0;
|
|
65
|
+
}
|
|
66
|
+
function write32(bytes, offset, value) {
|
|
67
|
+
bytes[offset] = value >>> 24;
|
|
68
|
+
bytes[offset + 1] = value >>> 16 & 255;
|
|
69
|
+
bytes[offset + 2] = value >>> 8 & 255;
|
|
70
|
+
bytes[offset + 3] = value & 255;
|
|
71
|
+
}
|
|
72
|
+
const roundInput = /* @__PURE__ */ new Int32Array(2);
|
|
73
|
+
const roundOutput = /* @__PURE__ */ new Int32Array(2);
|
|
74
|
+
/**
|
|
75
|
+
* Transform 16 bytes from `input` into `output`, which may be the same array.
|
|
76
|
+
*
|
|
77
|
+
* `forward: false` is the exact inverse — the rounds are identical and only the key order
|
|
78
|
+
* differs, which is why the final swap below is undone rather than performed.
|
|
79
|
+
*/
|
|
80
|
+
function feistel16(input, inputOffset, keys, forward, output, outputOffset) {
|
|
81
|
+
let left0 = read32(input, inputOffset);
|
|
82
|
+
let left1 = read32(input, inputOffset + 4);
|
|
83
|
+
let right0 = read32(input, inputOffset + 8);
|
|
84
|
+
let right1 = read32(input, inputOffset + 12);
|
|
85
|
+
for (let round = 0; round < ROUNDS; round += 1) {
|
|
86
|
+
const key = (forward ? round : 3 - round) * 2;
|
|
87
|
+
roundInput[0] = right0;
|
|
88
|
+
roundInput[1] = right1;
|
|
89
|
+
halfSipHash(keys[key], keys[key + 1], roundInput, 8, roundOutput);
|
|
90
|
+
const next0 = left0 ^ roundOutput[0];
|
|
91
|
+
const next1 = left1 ^ roundOutput[1];
|
|
92
|
+
left0 = right0;
|
|
93
|
+
left1 = right1;
|
|
94
|
+
right0 = next0;
|
|
95
|
+
right1 = next1;
|
|
96
|
+
}
|
|
97
|
+
write32(output, outputOffset, right0);
|
|
98
|
+
write32(output, outputOffset + 4, right1);
|
|
99
|
+
write32(output, outputOffset + 8, left0);
|
|
100
|
+
write32(output, outputOffset + 12, left1);
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
export { feistel16, mix32, read32 };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=feistel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"feistel.js","names":[],"sources":["../src/feistel.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { halfSipHash } from \"./siphash\";\n\n/**\n * A 4-round Feistel network over the 16 UUID bytes, used as the mask's mixing step.\n *\n * Why a Feistel rather than the byte permutation plus XOR it replaces: that construction is a\n * monoalphabetic substitution — one output byte per input byte — so bytes the inputs share, the\n * outputs share too. Measured over 3000 ids, masked slugs of UUIDv7s created in the same second\n * held 4 of 16 bytes constant, the same hour 3, the same day 2. The timestamp the mask exists to\n * hide was still legible in the output. A Feistel diffuses every input bit across the whole\n * block, so no output byte is a function of one input byte: the same measurement yields 0 of 16.\n *\n * The bijection is the property being bought, and it holds whatever the round function does: 16\n * bytes map to 16 bytes and the inverse is the same routine with the round keys reversed, so\n * `mask` and `unmask` cannot drift apart.\n *\n * The round function is HalfSipHash-2-4 keyed per round. What that fixes: the previous round\n * function was `mix32(word ^ roundKey)` — a FIXED, PUBLIC, UNKEYED bijection with the key merely\n * XORed in front, so an attacker inverts it and reads `word ^ roundKey` directly. Luby-Rackoff\n * makes a four-round Feistel a strong pseudorandom permutation only when the round functions are\n * pseudorandom functions, which `mix32` is not, so the theorem said nothing about what shipped and\n * an earlier version of this comment cited it wrongly. A keyed PRF meets that hypothesis in kind,\n * which is what makes ROUNDS = 4 a justified number rather than an unexamined margin. It is still\n * NOT a proof about what ships: the theorem wants four INDEPENDENTLY sampled round functions, and\n * `schema.ts` derives all four key pairs from one 128-bit key. Read it as the design rationale it\n * is, and see `docs/design.md` for what masking does and does not promise.\n *\n * Measured 2026-08-12 on Bun, both directions, medians of 9: the swap costs 2.5x on the mixing step\n * alone (30.85M -> 12.43M mixes/s) and about a quarter of end-to-end masking throughput, because\n * mixing is roughly a fifth of a mask. HalfSipHash is FASTER per round than `mix32` — pure\n * add/xor/rotate against two `Math.imul` calls — and loses only by doing 14 rounds where the old\n * function did the equivalent of 4.\n *\n * Nor does any measurement in this repository grade the round count or the round function. Strict\n * avalanche across all input/output bit pairs, a same-millisecond burst where only a 12-bit counter\n * varies, and a single-difference differential all PASS a TWO-round network, so none of them can\n * separate a weak setting from a strong one. Their agreement is evidence about the instruments.\n * `test/siphash.test.ts` is the exception and the reason a published primitive was worth taking:\n * it checks the round function against 64 vectors somebody else computed, and that CAN fail.\n */\n\n/**\n * Round count. Wire-format-bearing: changing it changes every masked slug this package has ever\n * issued, so it moves only alongside a deliberate format change. Four is Luby-Rackoff's number,\n * which the round function now makes relevant — see the note above for why that is a rationale\n * rather than a proof.\n */\nconst ROUNDS = 4;\n\n/** Two 32-bit round keys per round, consumed as one flat array to keep the hot loop indexed. */\nexport const FEISTEL_KEY_WORDS = ROUNDS * 2;\n\n/**\n * The `lowbias32` finalizer: an integer hash with near-ideal avalanche for its size. No longer the\n * round function — see above — but still what `mask.ts` derives its check tag with, where the input\n * is public and an unkeyed mixer is the right tool.\n */\nexport function mix32(value: number): number {\n let x = (value ^ (value >>> 16)) >>> 0;\n x = Math.imul(x, 0x7feb352d);\n x = (x ^ (x >>> 15)) >>> 0;\n x = Math.imul(x, 0x846ca68b);\n return (x ^ (x >>> 16)) >>> 0;\n}\n\n/** Big-endian on purpose: the wire format must not depend on the host's byte order. */\nexport function read32(bytes: Uint8Array, offset: number): number {\n return (\n ((bytes[offset] as number) << 24) |\n ((bytes[offset + 1] as number) << 16) |\n ((bytes[offset + 2] as number) << 8) |\n (bytes[offset + 3] as number) |\n 0\n );\n}\n\nfunction write32(bytes: Uint8Array, offset: number, value: number) {\n bytes[offset] = value >>> 24;\n bytes[offset + 1] = (value >>> 16) & 0xff;\n bytes[offset + 2] = (value >>> 8) & 0xff;\n bytes[offset + 3] = value & 0xff;\n}\n\n// Scratch for the round function, at module scope because allocating two 2-word arrays per call\n// dominated the mix. Safe because nothing here is reentrant: `feistel16` is synchronous, calls only\n// `halfSipHash`, and that calls nothing.\nconst roundInput = new Int32Array(2);\nconst roundOutput = new Int32Array(2);\n\n/**\n * Transform 16 bytes from `input` into `output`, which may be the same array.\n *\n * `forward: false` is the exact inverse — the rounds are identical and only the key order\n * differs, which is why the final swap below is undone rather than performed.\n */\nexport function feistel16(\n input: Uint8Array,\n inputOffset: number,\n keys: Int32Array,\n forward: boolean,\n output: Uint8Array,\n outputOffset: number,\n) {\n let left0 = read32(input, inputOffset);\n let left1 = read32(input, inputOffset + 4);\n let right0 = read32(input, inputOffset + 8);\n let right1 = read32(input, inputOffset + 12);\n for (let round = 0; round < ROUNDS; round += 1) {\n const key = (forward ? round : ROUNDS - 1 - round) * 2;\n roundInput[0] = right0;\n roundInput[1] = right1;\n halfSipHash(keys[key] as number, keys[key + 1] as number, roundInput, 8, roundOutput);\n const next0 = left0 ^ (roundOutput[0] as number);\n const next1 = left1 ^ (roundOutput[1] as number);\n left0 = right0;\n left1 = right1;\n right0 = next0;\n right1 = next1;\n }\n // Undoing the last round's swap is what collapses encode and decode into one routine. Perform\n // it, and decoding would need its own mirrored loop that can silently disagree with this one.\n write32(output, outputOffset, right0);\n write32(output, outputOffset + 4, right1);\n write32(output, outputOffset + 8, left0);\n write32(output, outputOffset + 12, left1);\n}\n"],"mappings":";;;;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