@anizoptera/uuid-slug 0.2.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 +1175 -30
- package/dist/alphabet.d.ts +9 -0
- package/dist/alphabet.d.ts.map +1 -0
- package/dist/alphabet.js +166 -0
- package/dist/alphabet.js.map +1 -0
- 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 +57 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +162 -0
- package/dist/errors.js.map +1 -0
- package/dist/feistel.js +39 -0
- package/dist/feistel.js.map +1 -0
- package/dist/generation-options.js +20 -0
- package/dist/generation-options.js.map +1 -0
- package/dist/index.d.ts +23 -168
- package/dist/index.js +22 -649
- 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 +164 -0
- package/dist/mask.js.map +1 -0
- 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 +129 -0
- package/dist/migration.js.map +1 -0
- 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 +30 -0
- package/dist/runtime/pool.js.map +1 -0
- 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 +29 -0
- package/dist/siphash.js.map +1 -0
- 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 +535 -0
- package/dist/types.d.ts.map +1 -0
- 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 +65 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +232 -0
- package/dist/uuid.js.map +1 -0
- 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 +143 -0
- package/dist/v7.js.map +1 -0
- package/package.json +18 -17
- package/src/alphabet.ts +616 -0
- package/src/base64url-name.ts +5 -0
- package/src/errors.ts +423 -13
- package/src/feistel.ts +141 -0
- package/src/generation-options.ts +48 -0
- package/src/index.ts +137 -57
- package/src/instant.ts +196 -0
- package/src/keyless.ts +9 -0
- package/src/mask-handle.ts +141 -0
- package/src/mask.ts +377 -90
- 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 +257 -0
- package/src/payload.ts +321 -0
- package/src/runtime/bun.ts +31 -25
- package/src/runtime/node.ts +55 -18
- package/src/runtime/pool.ts +90 -0
- package/src/runtime/portable.ts +68 -0
- package/src/runtime/types.ts +30 -5
- package/src/sentinel.ts +13 -0
- package/src/siphash.ts +128 -0
- package/src/slug.ts +884 -0
- package/src/timestamp.ts +122 -0
- package/src/types.ts +799 -61
- package/src/uuid-value-protocol.ts +77 -0
- package/src/uuid-value.ts +341 -0
- package/src/uuid.ts +527 -108
- 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 +433 -84
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/node/index.js +0 -647
- package/dist/web/index.js +0 -648
- package/src/base64url.ts +0 -76
- package/src/codec.ts +0 -218
- package/src/runtime/web.ts +0 -20
- package/src/schema.ts +0 -123
package/src/mask.ts
CHANGED
|
@@ -1,95 +1,382 @@
|
|
|
1
|
-
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
2
3
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
} from "./
|
|
10
|
-
import
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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)
|
|
64
|
+
return new UuidSlugError(
|
|
65
|
+
INVALID_MASK,
|
|
66
|
+
"Mask options must contain a string or Uint8Array seed.",
|
|
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));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
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.
|
|
124
|
+
*/
|
|
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;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
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.
|
|
138
|
+
*/
|
|
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);
|
|
145
|
+
}
|
|
146
|
+
|
|
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);
|
|
81
160
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
161
|
+
return keys;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
165
|
+
function feistelMask(diagnosticLabel: string, seed: Uint8Array, iterations: number): UuidV7Mask {
|
|
166
|
+
return maskFromKeys(diagnosticLabel, derivedKeys(seed, iterations));
|
|
87
167
|
}
|
|
88
168
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
return uuid instanceof Error ? uuid : (uuid as UuidV7String);
|
|
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
|
+
});
|
|
95
174
|
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
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.
|
|
183
|
+
*/
|
|
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)
|
|
199
|
+
return new UuidSlugError(
|
|
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.`,
|
|
202
|
+
);
|
|
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;
|
|
293
|
+
}
|
|
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;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
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);
|
|
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
|
+
);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
// Only this package's frozen codecs may borrow private UUID storage. Structural callbacks can
|
|
4
|
+
// retain or mutate their input; public shape checks cannot establish ownership.
|
|
5
|
+
// A private stamp follows the generator ownership protocol without a WeakSet registration or lookup;
|
|
6
|
+
// construction and conversion measurements are owned by bench/PERFORMANCE.md.
|
|
7
|
+
// Remeasure construction and parsed conversions if engines change private-field storage.
|
|
8
|
+
// eslint-disable-next-line typescript/no-extraneous-class -- returning the codec lets the subclass stamp the existing plain object
|
|
9
|
+
class ReturnCodec {
|
|
10
|
+
constructor(codec: object) {
|
|
11
|
+
return codec;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
class PackageMaskingCodec extends ReturnCodec {
|
|
16
|
+
readonly #local = true;
|
|
17
|
+
|
|
18
|
+
static is(codec: object): boolean {
|
|
19
|
+
return typeof codec === "object" && codec !== null && #local in codec && codec.#local;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function registerMaskingCodec<Codec extends object>(codec: Codec): Codec {
|
|
24
|
+
return new PackageMaskingCodec(codec) as object as Codec;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isLocalMaskingCodec(codec: object): boolean {
|
|
28
|
+
return PackageMaskingCodec.is(codec);
|
|
29
|
+
}
|