@anizoptera/uuid-slug 0.3.0 → 0.4.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/LICENSE +54 -31
- package/README.md +1052 -261
- package/dist/alphabet.d.ts +5 -17
- package/dist/alphabet.d.ts.map +1 -1
- package/dist/alphabet.js +146 -112
- package/dist/alphabet.js.map +1 -1
- package/dist/base64url-name.d.ts +7 -0
- package/dist/base64url-name.d.ts.map +1 -0
- package/dist/base64url-name.js +8 -0
- package/dist/base64url-name.js.map +1 -0
- package/dist/errors.d.ts +50 -9
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +145 -63
- package/dist/errors.js.map +1 -1
- package/dist/feistel.js +29 -95
- package/dist/feistel.js.map +1 -1
- package/dist/generation-options.js +20 -0
- package/dist/generation-options.js.map +1 -0
- package/dist/index.d.ts +22 -10
- package/dist/index.js +21 -9
- package/dist/instant.js +83 -0
- package/dist/instant.js.map +1 -0
- package/dist/mask-handle.d.ts +16 -0
- package/dist/mask-handle.d.ts.map +1 -0
- package/dist/mask-handle.js +60 -0
- package/dist/mask-handle.js.map +1 -0
- package/dist/mask.d.ts +27 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +151 -95
- package/dist/mask.js.map +1 -1
- package/dist/masking-codec-protocol.js +23 -0
- package/dist/masking-codec-protocol.js.map +1 -0
- package/dist/masking-codec-types.d.ts +245 -0
- package/dist/masking-codec-types.d.ts.map +1 -0
- package/dist/masking-codec.d.ts +19 -0
- package/dist/masking-codec.d.ts.map +1 -0
- package/dist/masking-codec.js +391 -0
- package/dist/masking-codec.js.map +1 -0
- package/dist/migration.js +114 -51
- package/dist/migration.js.map +1 -1
- package/dist/node/runtime.js +39 -0
- package/dist/node/runtime.js.map +1 -0
- package/dist/payload.d.ts +7 -0
- package/dist/payload.d.ts.map +1 -0
- package/dist/payload.js +118 -0
- package/dist/payload.js.map +1 -0
- package/dist/runtime/pool.js +21 -46
- package/dist/runtime/pool.js.map +1 -1
- package/dist/runtime/portable.js +27 -0
- package/dist/runtime/portable.js.map +1 -0
- package/dist/sentinel.js +10 -0
- package/dist/sentinel.js.map +1 -0
- package/dist/siphash.js +20 -99
- package/dist/siphash.js.map +1 -1
- package/dist/slug.d.ts +169 -0
- package/dist/slug.d.ts.map +1 -0
- package/dist/slug.js +268 -0
- package/dist/slug.js.map +1 -0
- package/dist/timestamp.d.ts +19 -0
- package/dist/timestamp.d.ts.map +1 -0
- package/dist/timestamp.js +44 -0
- package/dist/timestamp.js.map +1 -0
- package/dist/types.d.ts +480 -200
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +8 -0
- package/dist/types.js.map +1 -0
- package/dist/uuid-value-protocol.js +46 -0
- package/dist/uuid-value-protocol.js.map +1 -0
- package/dist/uuid-value.d.ts +17 -0
- package/dist/uuid-value.d.ts.map +1 -0
- package/dist/uuid-value.js +127 -0
- package/dist/uuid-value.js.map +1 -0
- package/dist/uuid.d.ts +51 -64
- package/dist/uuid.d.ts.map +1 -1
- package/dist/uuid.js +203 -199
- package/dist/uuid.js.map +1 -1
- package/dist/v4-slug.d.ts +16 -0
- package/dist/v4-slug.d.ts.map +1 -0
- package/dist/v4-slug.js +16 -0
- package/dist/v4-slug.js.map +1 -0
- package/dist/v4.d.ts +42 -0
- package/dist/v4.d.ts.map +1 -0
- package/dist/v4.js +85 -0
- package/dist/v4.js.map +1 -0
- package/dist/v7-bounds.d.ts +36 -0
- package/dist/v7-bounds.d.ts.map +1 -0
- package/dist/v7-bounds.js +49 -0
- package/dist/v7-bounds.js.map +1 -0
- package/dist/v7-generator-input.js +75 -0
- package/dist/v7-generator-input.js.map +1 -0
- package/dist/v7-generator.d.ts +43 -0
- package/dist/v7-generator.d.ts.map +1 -0
- package/dist/v7-generator.js +105 -0
- package/dist/v7-generator.js.map +1 -0
- package/dist/v7-keyless.d.ts +46 -0
- package/dist/v7-keyless.d.ts.map +1 -0
- package/dist/v7-keyless.js +106 -0
- package/dist/v7-keyless.js.map +1 -0
- package/dist/v7-payload.js +54 -0
- package/dist/v7-payload.js.map +1 -0
- package/dist/v7-slug.d.ts +46 -0
- package/dist/v7-slug.d.ts.map +1 -0
- package/dist/v7-slug.js +127 -0
- package/dist/v7-slug.js.map +1 -0
- package/dist/v7-timestamp.js +9 -0
- package/dist/v7-timestamp.js.map +1 -0
- package/dist/v7-value-options.js +28 -0
- package/dist/v7-value-options.js.map +1 -0
- package/dist/v7-value.d.ts +23 -0
- package/dist/v7-value.d.ts.map +1 -0
- package/dist/v7-value.js +31 -0
- package/dist/v7-value.js.map +1 -0
- package/dist/v7.js +127 -171
- package/dist/v7.js.map +1 -1
- package/package.json +14 -9
- package/src/alphabet.ts +456 -27
- package/src/base64url-name.ts +5 -0
- package/src/errors.ts +373 -37
- package/src/feistel.ts +69 -56
- package/src/generation-options.ts +48 -0
- package/src/index.ts +134 -80
- package/src/instant.ts +196 -0
- package/src/keyless.ts +7 -134
- package/src/mask-handle.ts +141 -0
- package/src/mask.ts +354 -129
- package/src/masking-codec-protocol.ts +29 -0
- package/src/masking-codec-types.ts +380 -0
- package/src/masking-codec.ts +923 -0
- package/src/migration.ts +195 -42
- package/src/payload.ts +321 -0
- package/src/runtime/bun.ts +30 -49
- package/src/runtime/node.ts +43 -24
- package/src/runtime/pool.ts +49 -21
- package/src/runtime/portable.ts +68 -0
- package/src/runtime/types.ts +23 -35
- package/src/sentinel.ts +13 -0
- package/src/siphash.ts +5 -4
- package/src/slug.ts +884 -0
- package/src/timestamp.ts +122 -0
- package/src/types.ts +759 -205
- package/src/uuid-value-protocol.ts +77 -0
- package/src/uuid-value.ts +341 -0
- package/src/uuid.ts +514 -234
- package/src/v4-slug.ts +27 -0
- package/src/v4.ts +234 -0
- package/src/v7-bounds.ts +171 -0
- package/src/v7-generator-input.ts +169 -0
- package/src/v7-generator.ts +245 -0
- package/src/v7-keyless.ts +354 -0
- package/src/v7-payload.ts +121 -0
- package/src/v7-slug.ts +293 -0
- package/src/v7-timestamp.ts +21 -0
- package/src/v7-value-options.ts +62 -0
- package/src/v7-value.ts +54 -0
- package/src/v7.ts +377 -200
- package/dist/base64url.d.ts +0 -20
- package/dist/base64url.d.ts.map +0 -1
- package/dist/base64url.js +0 -33
- package/dist/base64url.js.map +0 -1
- package/dist/codec.d.ts +0 -17
- package/dist/codec.d.ts.map +0 -1
- package/dist/codec.js +0 -192
- package/dist/codec.js.map +0 -1
- package/dist/keyless.d.ts +0 -31
- package/dist/keyless.d.ts.map +0 -1
- package/dist/keyless.js +0 -93
- package/dist/keyless.js.map +0 -1
- package/dist/legacy-mask.js +0 -55
- package/dist/legacy-mask.js.map +0 -1
- package/dist/node/alphabet.js +0 -130
- package/dist/node/base64url.js +0 -31
- package/dist/node/codec.js +0 -190
- package/dist/node/errors.js +0 -78
- package/dist/node/feistel.js +0 -103
- package/dist/node/index.js +0 -10
- package/dist/node/keyless.js +0 -91
- package/dist/node/legacy-mask.js +0 -53
- package/dist/node/mask.js +0 -106
- package/dist/node/migration.js +0 -64
- package/dist/node/runtime/node.js +0 -33
- package/dist/node/runtime/pool.js +0 -53
- package/dist/node/schema.js +0 -214
- package/dist/node/siphash.js +0 -106
- package/dist/node/uuid.js +0 -226
- package/dist/node/v7.js +0 -185
- package/dist/node/yield.js +0 -20
- package/dist/runtime/web.js +0 -39
- package/dist/runtime/web.js.map +0 -1
- package/dist/schema.d.ts +0 -20
- package/dist/schema.d.ts.map +0 -1
- package/dist/schema.js +0 -216
- package/dist/schema.js.map +0 -1
- package/dist/v7.d.ts +0 -12
- package/dist/v7.d.ts.map +0 -1
- package/dist/yield.js +0 -22
- package/dist/yield.js.map +0 -1
- package/src/base64url.ts +0 -41
- package/src/codec.ts +0 -320
- package/src/legacy-mask.ts +0 -25
- package/src/runtime/web.ts +0 -48
- package/src/schema.ts +0 -300
- package/src/yield.ts +0 -22
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
findUnknownOption,
|
|
5
|
+
INVALID_MASK,
|
|
6
|
+
isUint8Array,
|
|
7
|
+
isUuidSlugError,
|
|
8
|
+
stringInput,
|
|
9
|
+
UuidSlugError,
|
|
10
|
+
} from "./errors.ts";
|
|
11
|
+
import type { CustomUuidV7MaskOptions, UuidV7Mask } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
const MASK_PROTOCOL = Symbol.for("@anizoptera/uuid-slug/mask/1");
|
|
14
|
+
const CUSTOM_MASK_FAILURE_MESSAGE = "Custom mask construction failed.";
|
|
15
|
+
const MASK_DIRECTION = "mask";
|
|
16
|
+
const CUSTOM_MASK_OPTIONS = {
|
|
17
|
+
diagnosticLabel: true,
|
|
18
|
+
[MASK_DIRECTION]: true,
|
|
19
|
+
unmask: true,
|
|
20
|
+
} as const satisfies Record<keyof CustomUuidV7MaskOptions, true>;
|
|
21
|
+
|
|
22
|
+
interface MaskProtocol {
|
|
23
|
+
readonly version: 1;
|
|
24
|
+
readonly mix: (
|
|
25
|
+
input: Uint8Array,
|
|
26
|
+
output: Uint8Array,
|
|
27
|
+
direction: "mask" | "unmask",
|
|
28
|
+
) => undefined | UuidSlugError;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type MaskHandle = UuidV7Mask & { readonly [MASK_PROTOCOL]: MaskProtocol };
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The versioned global symbol lets genuine handles cross duplicate same-version package copies.
|
|
35
|
+
* The protocol is internal representation, not an authenticity boundary for trusted codec options.
|
|
36
|
+
*/
|
|
37
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
38
|
+
export function createMaskHandle(diagnosticLabel: string, mix: MaskProtocol["mix"]): UuidV7Mask {
|
|
39
|
+
const mask = { diagnosticLabel } as MaskHandle;
|
|
40
|
+
Object.defineProperty(mask, MASK_PROTOCOL, {
|
|
41
|
+
value: Object.freeze<MaskProtocol>({ version: 1, mix }),
|
|
42
|
+
});
|
|
43
|
+
return Object.freeze(mask);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function maskProtocol(mask: UuidV7Mask): MaskProtocol | undefined {
|
|
47
|
+
if (typeof mask !== "object" || mask === null) return undefined;
|
|
48
|
+
const protocol = (mask as Partial<MaskHandle>)[MASK_PROTOCOL];
|
|
49
|
+
return protocol?.version === 1 && typeof protocol.mix === "function" ? protocol : undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function isMaskHandle(mask: unknown): mask is UuidV7Mask {
|
|
53
|
+
return maskProtocol(mask as UuidV7Mask) !== undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function applyMask(
|
|
57
|
+
mask: UuidV7Mask,
|
|
58
|
+
input: Uint8Array,
|
|
59
|
+
output: Uint8Array,
|
|
60
|
+
direction: "mask" | "unmask",
|
|
61
|
+
): undefined | UuidSlugError {
|
|
62
|
+
const protocol = maskProtocol(mask);
|
|
63
|
+
if (!protocol) return new UuidSlugError(INVALID_MASK, "Mask handle is invalid or incompatible.");
|
|
64
|
+
return protocol.mix(input, output, direction);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function runCustom(
|
|
68
|
+
transform: CustomUuidV7MaskOptions["mask"],
|
|
69
|
+
input: Uint8Array,
|
|
70
|
+
): Uint8Array | UuidSlugError {
|
|
71
|
+
// Callbacks never receive package or caller storage. Copy their result at the codec boundary too,
|
|
72
|
+
// because a callback may retain and mutate the array it returns.
|
|
73
|
+
const output = transform(input.slice());
|
|
74
|
+
if (isUuidSlugError(output)) return output;
|
|
75
|
+
if (!isUint8Array(output) || output.length !== 16)
|
|
76
|
+
return new UuidSlugError(INVALID_MASK, "A custom mask transform must return exactly 16 bytes.");
|
|
77
|
+
return output;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Build an immutable mask from reversible 16-byte callbacks. Each callback receives isolated bytes,
|
|
82
|
+
* so returning the same array is safe. Invalid results and thrown values return `UuidSlugError`.
|
|
83
|
+
* The caller must ensure `unmask(mask(bytes))` restores every possible 16-byte input.
|
|
84
|
+
*
|
|
85
|
+
* @param options - Diagnostic label and mutually inverse 16-byte transforms.
|
|
86
|
+
* @returns The validated mask, or `UuidSlugError` for an invalid contract or callback result.
|
|
87
|
+
*/
|
|
88
|
+
export function createCustomUuidV7Mask(
|
|
89
|
+
options: CustomUuidV7MaskOptions,
|
|
90
|
+
): UuidV7Mask | UuidSlugError {
|
|
91
|
+
try {
|
|
92
|
+
if (typeof options !== "object" || options === null || Array.isArray(options))
|
|
93
|
+
return new UuidSlugError(INVALID_MASK, "Custom mask options must be an object.");
|
|
94
|
+
const unknown = findUnknownOption(options, CUSTOM_MASK_OPTIONS);
|
|
95
|
+
if (unknown !== undefined)
|
|
96
|
+
return new UuidSlugError(INVALID_MASK, `Unknown custom mask option: ${unknown}.`);
|
|
97
|
+
const { mask, unmask } = options;
|
|
98
|
+
const diagnosticLabel = stringInput(options.diagnosticLabel);
|
|
99
|
+
if (
|
|
100
|
+
typeof diagnosticLabel !== "string" ||
|
|
101
|
+
typeof mask !== "function" ||
|
|
102
|
+
typeof unmask !== "function"
|
|
103
|
+
)
|
|
104
|
+
return new UuidSlugError(
|
|
105
|
+
INVALID_MASK,
|
|
106
|
+
"A custom UUIDv7 mask requires a string diagnosticLabel plus mask and unmask functions.",
|
|
107
|
+
);
|
|
108
|
+
// These probes reject common non-inverses cheaply; no finite sample can prove a bijection over
|
|
109
|
+
// 128 bits, so the public contract keeps full invertibility as the callback author's duty.
|
|
110
|
+
for (const probe of [
|
|
111
|
+
new Uint8Array(16),
|
|
112
|
+
Uint8Array.from({ length: 16 }, (_, index) => index * 17),
|
|
113
|
+
]) {
|
|
114
|
+
const mixed = runCustom(mask, probe);
|
|
115
|
+
if (isUuidSlugError(mixed))
|
|
116
|
+
return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
|
|
117
|
+
cause: mixed,
|
|
118
|
+
});
|
|
119
|
+
const restored = runCustom(unmask, mixed);
|
|
120
|
+
if (isUuidSlugError(restored))
|
|
121
|
+
return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
|
|
122
|
+
cause: restored,
|
|
123
|
+
});
|
|
124
|
+
if (restored.some((byte, index) => byte !== probe[index]))
|
|
125
|
+
return new UuidSlugError(
|
|
126
|
+
INVALID_MASK,
|
|
127
|
+
`UUIDv7 mask "${diagnosticLabel}" does not unmask its own masked output.`,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
return createMaskHandle(diagnosticLabel, (input, output, direction) => {
|
|
131
|
+
const mixed = runCustom(direction === MASK_DIRECTION ? mask : unmask, input);
|
|
132
|
+
if (isUuidSlugError(mixed)) return mixed;
|
|
133
|
+
output.set(mixed);
|
|
134
|
+
return undefined;
|
|
135
|
+
});
|
|
136
|
+
} catch (cause) {
|
|
137
|
+
return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
|
|
138
|
+
cause,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
package/src/mask.ts
CHANGED
|
@@ -1,157 +1,382 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
3
|
+
import {
|
|
4
|
+
ABORTED,
|
|
5
|
+
findUnknownOption,
|
|
6
|
+
INVALID_MASK,
|
|
7
|
+
isUint8Array,
|
|
8
|
+
stringInput,
|
|
9
|
+
UuidSlugError,
|
|
10
|
+
} from "./errors.ts";
|
|
11
|
+
import { FEISTEL_KEY_WORDS, feistel16 } from "./feistel.ts";
|
|
12
|
+
import { createMaskHandle } from "./mask-handle.ts";
|
|
13
|
+
import { halfSipHash } from "./siphash.ts";
|
|
14
|
+
import type { HashContinuation } from "./siphash.ts";
|
|
15
|
+
import { encodeUtf8 } from "#runtime";
|
|
16
|
+
import type { AsyncUuidV7MaskOptions, UuidV7Mask, UuidV7MaskOptions } from "./types.ts";
|
|
17
|
+
|
|
18
|
+
const MASK_CONSTRUCTION_FAILURE_MESSAGE = "Mask construction failed.";
|
|
19
|
+
const SEED_PROPERTY = "seed";
|
|
20
|
+
const MASK_OPTIONS = {
|
|
21
|
+
keyDerivationIterations: true,
|
|
22
|
+
diagnosticLabel: true,
|
|
23
|
+
[SEED_PROPERTY]: true,
|
|
24
|
+
} as const satisfies Record<keyof UuidV7MaskOptions, true>;
|
|
25
|
+
const ASYNC_MASK_OPTIONS = {
|
|
26
|
+
...MASK_OPTIONS,
|
|
27
|
+
signal: true,
|
|
28
|
+
} as const satisfies Record<keyof AsyncUuidV7MaskOptions, true>;
|
|
29
|
+
|
|
30
|
+
/** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
|
|
31
|
+
const SEED_MIN_BYTES = 16;
|
|
32
|
+
|
|
33
|
+
/** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
|
|
34
|
+
const MAX_KEY_ITERATIONS = 1 << 24;
|
|
35
|
+
|
|
36
|
+
/** Large aligned byte seeds can share their owned buffer without changing HalfSipHash's byte order. */
|
|
37
|
+
const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
|
|
38
|
+
const SEED_WORD_VIEW_MIN_BYTES = 4096;
|
|
39
|
+
|
|
40
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
41
|
+
function canViewSeedWords(seed: Uint8Array) {
|
|
42
|
+
return LITTLE_ENDIAN && (seed.byteOffset & 3) === 0 && (seed.length & 3) === 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
|
|
47
|
+
* "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
|
|
48
|
+
*
|
|
49
|
+
* Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
|
|
50
|
+
* seed different round keys and make every masked slug ever issued undecodable.
|
|
51
|
+
*/
|
|
52
|
+
const CHAIN_A_KEY1 = 0x41676c73;
|
|
53
|
+
const CHAIN_B_KEY1 = 0x42676c73;
|
|
54
|
+
const CHAIN_KEY0 = 0x64697575;
|
|
55
|
+
|
|
56
|
+
function seedBytes(seed: string | Uint8Array) {
|
|
57
|
+
if (typeof seed !== "string") return new Uint8Array(seed);
|
|
58
|
+
return encodeUtf8(seed);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Reject coercible JavaScript values before they can allocate storage or become key material. */
|
|
62
|
+
function validateOptions(options: unknown, accepted: Readonly<Record<string, true>>) {
|
|
63
|
+
if (typeof options !== "object" || options === null)
|
|
20
64
|
return new UuidSlugError(
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
{ cause },
|
|
65
|
+
INVALID_MASK,
|
|
66
|
+
"Mask options must contain a string or Uint8Array seed.",
|
|
24
67
|
);
|
|
68
|
+
const input = options as {
|
|
69
|
+
readonly diagnosticLabel?: unknown;
|
|
70
|
+
readonly keyDerivationIterations?: unknown;
|
|
71
|
+
readonly seed?: unknown;
|
|
72
|
+
};
|
|
73
|
+
const unknown = findUnknownOption(input, accepted);
|
|
74
|
+
if (unknown !== undefined)
|
|
75
|
+
return new UuidSlugError(INVALID_MASK, `Unknown mask option: ${unknown}.`);
|
|
76
|
+
// An accessor must not choose different key material between recognition and derivation.
|
|
77
|
+
// Capture once; a byte seed also needs only one intrinsic brand check.
|
|
78
|
+
const givenSeed = input.seed;
|
|
79
|
+
const seed =
|
|
80
|
+
typeof givenSeed === "string" || isUint8Array(givenSeed) ? givenSeed : stringInput(givenSeed);
|
|
81
|
+
if (seed === undefined)
|
|
82
|
+
return new UuidSlugError(INVALID_MASK, "Mask seed must be a string or Uint8Array.");
|
|
83
|
+
const givenLabel = input.diagnosticLabel;
|
|
84
|
+
const diagnosticLabel = givenLabel === undefined ? "seeded" : givenLabel;
|
|
85
|
+
const normalizedLabel = stringInput(diagnosticLabel);
|
|
86
|
+
if (normalizedLabel === undefined)
|
|
87
|
+
return new UuidSlugError(INVALID_MASK, "Mask diagnosticLabel must be a string.");
|
|
88
|
+
const givenIterations = input.keyDerivationIterations;
|
|
89
|
+
const keyDerivationIterations = givenIterations === undefined ? 1 : givenIterations;
|
|
90
|
+
const iterations = validatedIterations(keyDerivationIterations);
|
|
91
|
+
if (typeof iterations !== "number") return iterations;
|
|
92
|
+
return { diagnosticLabel: normalizedLabel, iterations, seed };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
|
|
96
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
97
|
+
function seedWords(seed: Uint8Array) {
|
|
98
|
+
if (seed.length >= SEED_WORD_VIEW_MIN_BYTES && canViewSeedWords(seed))
|
|
99
|
+
return new Int32Array(seed.buffer, seed.byteOffset, seed.length >>> 2);
|
|
100
|
+
const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
|
|
101
|
+
writeSeedWords(seed, words);
|
|
102
|
+
return words;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
|
|
106
|
+
function writeSeedWords(
|
|
107
|
+
seed: Uint8Array,
|
|
108
|
+
words: Int32Array,
|
|
109
|
+
offset = 0,
|
|
110
|
+
start = 0,
|
|
111
|
+
end = seed.length,
|
|
112
|
+
) {
|
|
113
|
+
for (let index = start; index < end; index += 1) {
|
|
114
|
+
const absolute = offset + index;
|
|
115
|
+
words[absolute >>> 2] =
|
|
116
|
+
(words[absolute >>> 2] as number) | ((seed[index] as number) << ((absolute & 3) * 8));
|
|
25
117
|
}
|
|
26
118
|
}
|
|
27
119
|
|
|
28
120
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* Taken from the TOP so that widening the check never renumbers the bits below it.
|
|
121
|
+
* Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
|
|
122
|
+
* at construction, never per id. The count changes key material and must remain stable for
|
|
123
|
+
* issued slugs; retain the old count with its seed when rotating masks.
|
|
34
124
|
*/
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
125
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
126
|
+
function chain(key0: number, key1: number, words: Int32Array, length: number, iterations: number) {
|
|
127
|
+
const out = new Int32Array(2);
|
|
128
|
+
halfSipHash(key0, key1, words, length, out);
|
|
129
|
+
for (let i = 1; i < iterations; i += 1)
|
|
130
|
+
halfSipHash(out[0] as number, out[1] as number, words, length, out);
|
|
131
|
+
return out;
|
|
39
132
|
}
|
|
40
133
|
|
|
41
134
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* rides outside the block, in whatever the encoding has spare.
|
|
46
|
-
*
|
|
47
|
-
* Claiming byte 0 is why encoding must REFUSE an instant at or past 2^42 ms rather than truncate.
|
|
135
|
+
* Derive each round key by XORing outputs from two fixed derivation chains. Their combined
|
|
136
|
+
* state is 128 bits; that representation does not establish 128-bit security. Chain constants,
|
|
137
|
+
* word indices and byte order are frozen by the issued wire format.
|
|
48
138
|
*/
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
139
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
140
|
+
function derivedKeys(seed: Uint8Array, iterations: number) {
|
|
141
|
+
const words = seedWords(seed);
|
|
142
|
+
const chainA = chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations);
|
|
143
|
+
const chainB = chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations);
|
|
144
|
+
return roundKeys(chainA, chainB);
|
|
53
145
|
}
|
|
54
146
|
|
|
55
|
-
|
|
56
|
-
|
|
147
|
+
/** The same final key expansion follows synchronous and cooperative derivation. */
|
|
148
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
149
|
+
function roundKeys(chainA: Int32Array, chainB: Int32Array) {
|
|
150
|
+
const keys = new Int32Array(FEISTEL_KEY_WORDS);
|
|
151
|
+
const index = new Int32Array(1);
|
|
152
|
+
const fromA = new Int32Array(2);
|
|
153
|
+
const fromB = new Int32Array(2);
|
|
154
|
+
for (let word = 0; word < FEISTEL_KEY_WORDS; word += 2) {
|
|
155
|
+
index[0] = word;
|
|
156
|
+
halfSipHash(chainA[0] as number, chainA[1] as number, index, 4, fromA);
|
|
157
|
+
halfSipHash(chainB[0] as number, chainB[1] as number, index, 4, fromB);
|
|
158
|
+
keys[word] = (fromA[0] as number) ^ (fromB[0] as number);
|
|
159
|
+
keys[word + 1] = (fromA[1] as number) ^ (fromB[1] as number);
|
|
160
|
+
}
|
|
161
|
+
return keys;
|
|
57
162
|
}
|
|
58
163
|
|
|
59
|
-
|
|
60
|
-
function
|
|
61
|
-
|
|
62
|
-
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
63
|
-
bytes[0] = (bytes[0] ?? 0) & 0x03;
|
|
164
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
165
|
+
function feistelMask(diagnosticLabel: string, seed: Uint8Array, iterations: number): UuidV7Mask {
|
|
166
|
+
return maskFromKeys(diagnosticLabel, derivedKeys(seed, iterations));
|
|
64
167
|
}
|
|
65
168
|
|
|
66
|
-
|
|
67
|
-
|
|
169
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
170
|
+
function maskFromKeys(diagnosticLabel: string, keys: Int32Array): UuidV7Mask {
|
|
171
|
+
return createMaskHandle(diagnosticLabel, (input, output, direction) => {
|
|
172
|
+
feistel16(input, 0, keys, direction, output, 0);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
68
175
|
|
|
69
176
|
/**
|
|
70
|
-
*
|
|
71
|
-
* the
|
|
72
|
-
*
|
|
177
|
+
* Derive an immutable mask from a secret seed of at least 16 bytes. The seed and iteration count
|
|
178
|
+
* define the wire format; retain the old mask in `previousMasks` before changing either. Invalid
|
|
179
|
+
* options return `invalid_mask`.
|
|
180
|
+
*
|
|
181
|
+
* @param options - Stable secret seed, optional diagnostic label, and derivation work factor.
|
|
182
|
+
* @returns The mask, or `UuidSlugError` when an option or seed is invalid.
|
|
73
183
|
*/
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
184
|
+
export function deriveUuidV7Mask(options: UuidV7MaskOptions): UuidV7Mask | UuidSlugError {
|
|
185
|
+
try {
|
|
186
|
+
const validated = validateOptions(options, MASK_OPTIONS);
|
|
187
|
+
if (!(SEED_PROPERTY in validated)) return validated;
|
|
188
|
+
const seed = seedBytes(validated.seed);
|
|
189
|
+
const short = invalidSeedLength(seed.length);
|
|
190
|
+
return short ?? feistelMask(validated.diagnosticLabel, seed, validated.iterations);
|
|
191
|
+
} catch (cause) {
|
|
192
|
+
return new UuidSlugError(INVALID_MASK, MASK_CONSTRUCTION_FAILURE_MESSAGE, { cause });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
197
|
+
function invalidSeedLength(length: number): undefined | UuidSlugError {
|
|
198
|
+
if (length < SEED_MIN_BYTES)
|
|
84
199
|
return new UuidSlugError(
|
|
85
|
-
|
|
86
|
-
|
|
200
|
+
INVALID_MASK,
|
|
201
|
+
`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.`,
|
|
87
202
|
);
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
)
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function validatedIterations(iterations: unknown): number | UuidSlugError {
|
|
207
|
+
if (
|
|
208
|
+
typeof iterations !== "number" ||
|
|
209
|
+
!Number.isInteger(iterations) ||
|
|
210
|
+
iterations < 1 ||
|
|
211
|
+
iterations > MAX_KEY_ITERATIONS
|
|
212
|
+
)
|
|
213
|
+
return new UuidSlugError(
|
|
214
|
+
INVALID_MASK,
|
|
215
|
+
`Mask keyDerivationIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`,
|
|
216
|
+
);
|
|
217
|
+
return iterations;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
|
|
221
|
+
const CHUNK_BYTES = 4096;
|
|
222
|
+
|
|
223
|
+
const host = globalThis as { setImmediate?: (callback: () => void) => void };
|
|
224
|
+
const immediate = host.setImmediate?.bind(host);
|
|
225
|
+
|
|
226
|
+
/** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */
|
|
227
|
+
function yieldToHost(): Promise<void> {
|
|
228
|
+
// Prioritized scheduler continuations can overtake queued cancellation tasks in browsers.
|
|
229
|
+
if (immediate) return new Promise((resolve) => immediate(resolve));
|
|
230
|
+
return new Promise((resolve) => {
|
|
231
|
+
const channel = new MessageChannel();
|
|
232
|
+
// eslint-disable-next-line unicorn/prefer-add-event-listener -- this private port has one handler; assignment also starts delivery
|
|
233
|
+
channel.port1.onmessage = () => {
|
|
234
|
+
channel.port1.close();
|
|
235
|
+
channel.port2.close();
|
|
236
|
+
resolve();
|
|
237
|
+
};
|
|
238
|
+
channel.port2.postMessage(null);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function* cooperativeChain(
|
|
243
|
+
key0: number,
|
|
244
|
+
key1: number,
|
|
245
|
+
words: Int32Array,
|
|
246
|
+
length: number,
|
|
247
|
+
iterations: number,
|
|
248
|
+
): Generator<void, Int32Array, void> {
|
|
249
|
+
const out = new Int32Array(2);
|
|
250
|
+
out[0] = key0;
|
|
251
|
+
out[1] = key1;
|
|
252
|
+
const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
|
|
253
|
+
let sinceCheckpoint = 0;
|
|
254
|
+
for (let i = 0; i < iterations; i += 1) {
|
|
255
|
+
let continuation: HashContinuation | undefined;
|
|
256
|
+
do {
|
|
257
|
+
continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
|
|
258
|
+
if (continuation) yield;
|
|
259
|
+
} while (continuation);
|
|
260
|
+
sinceCheckpoint += 1;
|
|
261
|
+
if (sinceCheckpoint >= hashesPerChunk) {
|
|
262
|
+
sinceCheckpoint = 0;
|
|
263
|
+
yield;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function* cooperativeKeys(
|
|
270
|
+
seed: string | Uint8Array,
|
|
271
|
+
iterations: number,
|
|
272
|
+
): Generator<void, Int32Array | UuidSlugError, void> {
|
|
273
|
+
// Byte seeds were snapshotted before suspension. Strings are immutable, so encoding can yield.
|
|
274
|
+
const chunks: Uint8Array[] = [];
|
|
275
|
+
let length = 0;
|
|
276
|
+
if (typeof seed === "string") {
|
|
277
|
+
for (let start = 0; start < seed.length;) {
|
|
278
|
+
let end = Math.min(seed.length, start + CHUNK_BYTES);
|
|
279
|
+
// Do not split a surrogate pair: encoding either half alone would substitute U+FFFD.
|
|
280
|
+
const last = seed.charCodeAt(end - 1);
|
|
281
|
+
const next = seed.charCodeAt(end);
|
|
282
|
+
if (end < seed.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)
|
|
283
|
+
end -= 1;
|
|
284
|
+
const bytes = encodeUtf8(seed.slice(start, end));
|
|
285
|
+
chunks.push(bytes);
|
|
286
|
+
length += bytes.length;
|
|
287
|
+
start = end;
|
|
288
|
+
yield;
|
|
289
|
+
}
|
|
290
|
+
} else {
|
|
291
|
+
chunks.push(seed);
|
|
292
|
+
length = seed.length;
|
|
112
293
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
for (const schema of schemas) {
|
|
129
|
-
// Custom callbacks may mutate their input; no key may alter what the next one sees.
|
|
130
|
-
const decoded = unmix(mixed.slice(), outerTag, schema);
|
|
131
|
-
// A failed callback means the candidate list is incomplete, not that its key mismatched.
|
|
132
|
-
if (decoded instanceof Error) return decoded;
|
|
133
|
-
if (decoded) {
|
|
134
|
-
const uuid = formatUuid(decoded);
|
|
135
|
-
if (uuid instanceof Error) return uuid;
|
|
136
|
-
if (!candidates.includes(uuid)) candidates.push(uuid);
|
|
137
|
-
if (firstOnly) break;
|
|
294
|
+
const short = invalidSeedLength(length);
|
|
295
|
+
if (short) return short;
|
|
296
|
+
const viewBytes =
|
|
297
|
+
typeof seed !== "string" && seed.length >= SEED_WORD_VIEW_MIN_BYTES && canViewSeedWords(seed);
|
|
298
|
+
const words = viewBytes
|
|
299
|
+
? new Int32Array(seed.buffer, seed.byteOffset, seed.length >>> 2)
|
|
300
|
+
: new Int32Array(Math.ceil(length / 4) + 1);
|
|
301
|
+
if (!viewBytes) {
|
|
302
|
+
let offset = 0;
|
|
303
|
+
for (const bytes of chunks) {
|
|
304
|
+
for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
|
|
305
|
+
writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
|
|
306
|
+
yield;
|
|
307
|
+
}
|
|
308
|
+
offset += bytes.length;
|
|
138
309
|
}
|
|
139
310
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
mixed: Uint8Array,
|
|
145
|
-
outerTag: number,
|
|
146
|
-
schema: MaskSchema,
|
|
147
|
-
): UuidSlugError | Uint8Array | undefined {
|
|
148
|
-
const unmixed = new Uint8Array(16);
|
|
149
|
-
const failed = applyMix(schema, mixed, unmixed, false);
|
|
150
|
-
if (failed) return failed;
|
|
151
|
-
// Both halves come out of the same decryption, so a wrong key garbles the observed check as
|
|
152
|
-
// thoroughly as the payload: the tag needs no key of its own to tell keys apart.
|
|
153
|
-
const foundTag = (extractTag(unmixed) << OUTER_TAG_BITS) | outerTag;
|
|
154
|
-
restoreV7(unmixed);
|
|
155
|
-
if (tagFor(unmixed, TAG_BITS) !== foundTag) return undefined;
|
|
156
|
-
return unmixed;
|
|
311
|
+
chunks.length = 0;
|
|
312
|
+
const chainA = yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations);
|
|
313
|
+
const chainB = yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations);
|
|
314
|
+
return roundKeys(chainA, chainB);
|
|
157
315
|
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Derive the same mask without monopolizing the host task. Later mutation of a byte seed does not
|
|
319
|
+
* affect the result. Cancellation returns `aborted` with `signal.reason` as its cause; invalid
|
|
320
|
+
* options return `invalid_mask`. Construct once and reuse the result.
|
|
321
|
+
*
|
|
322
|
+
* @param options - Synchronous mask options plus an optional cancellation signal.
|
|
323
|
+
* @returns A promise for the mask or an expected construction error.
|
|
324
|
+
*/
|
|
325
|
+
export async function deriveUuidV7MaskAsync(
|
|
326
|
+
options: AsyncUuidV7MaskOptions,
|
|
327
|
+
): Promise<UuidV7Mask | UuidSlugError> {
|
|
328
|
+
try {
|
|
329
|
+
const signal = options?.signal;
|
|
330
|
+
const aborted = () =>
|
|
331
|
+
new UuidSlugError(ABORTED, "Mask construction was aborted.", {
|
|
332
|
+
cause: signal?.reason,
|
|
333
|
+
});
|
|
334
|
+
if (signal?.aborted) return aborted();
|
|
335
|
+
const validated = validateOptions(options, ASYNC_MASK_OPTIONS);
|
|
336
|
+
if (!(SEED_PROPERTY in validated)) return validated;
|
|
337
|
+
const seed =
|
|
338
|
+
typeof validated.seed === "string" ? validated.seed : new Uint8Array(validated.seed);
|
|
339
|
+
const steps = cooperativeKeys(seed, validated.iterations);
|
|
340
|
+
let deadline = performance.now() + 2;
|
|
341
|
+
while (true) {
|
|
342
|
+
if (signal?.aborted) {
|
|
343
|
+
const failure = aborted();
|
|
344
|
+
steps.return(failure);
|
|
345
|
+
return failure;
|
|
346
|
+
}
|
|
347
|
+
const step = steps.next();
|
|
348
|
+
if (step.done)
|
|
349
|
+
return ArrayBuffer.isView(step.value)
|
|
350
|
+
? maskFromKeys(validated.diagnosticLabel, step.value)
|
|
351
|
+
: step.value;
|
|
352
|
+
if (performance.now() >= deadline) {
|
|
353
|
+
// eslint-disable-next-line no-await-in-loop -- each slice must yield before continuing the dependent derivation
|
|
354
|
+
await yieldToHost();
|
|
355
|
+
deadline = performance.now() + 2;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
} catch (cause) {
|
|
359
|
+
return new UuidSlugError(INVALID_MASK, MASK_CONSTRUCTION_FAILURE_MESSAGE, { cause });
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* A PUBLIC key. It ships in the tarball, so every masked slug produced under it is decodable by
|
|
365
|
+
* anyone who installed this package, and it therefore provides none of the obscurity masking
|
|
366
|
+
* exists for.
|
|
367
|
+
*
|
|
368
|
+
* It is exported so a deterministic test or example can opt in visibly with
|
|
369
|
+
* `mask: UUID_V7_TEST_MASK`; codec construction never selects it by omission.
|
|
370
|
+
*/
|
|
371
|
+
const DEFAULT_SEED = "anizoptera.uuid-slug.default-mask.v1";
|
|
372
|
+
|
|
373
|
+
// Built from `feistelMask` rather than through `deriveUuidV7Mask`, whose failures are a short seed and a
|
|
374
|
+
// bad iteration count — checks on CALLER input that the literals here cannot fail. Routing through it would return
|
|
375
|
+
// `UuidV7Mask | UuidSlugError` and force a cast that, at module scope, could only ever hide a real Error
|
|
376
|
+
// behind a `UuidV7Mask` type at module scope.
|
|
377
|
+
/** Public-key mask for deterministic tests and examples. Never use it to hide production IDs. */
|
|
378
|
+
export const UUID_V7_TEST_MASK: UuidV7Mask = /*#__PURE__*/ feistelMask(
|
|
379
|
+
"default",
|
|
380
|
+
/*#__PURE__*/ seedBytes(DEFAULT_SEED),
|
|
381
|
+
1,
|
|
382
|
+
);
|