@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
package/src/codec.ts
CHANGED
|
@@ -1,43 +1,35 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
1
3
|
import { runtime } from "#runtime";
|
|
2
|
-
import { UuidSlugError } from "./errors";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
} from "./
|
|
8
|
-
import {
|
|
4
|
+
import { errorOrThrow, readClock, UuidSlugError } from "./errors";
|
|
5
|
+
// A v4 has ONE implementation however it is reached. The keyless module owns it because that is
|
|
6
|
+
// the module a consumer who never masks pulls in; importing it here costs a codec consumer nothing
|
|
7
|
+
// it was not already paying, whereas the reverse direction would put the codec back on the keyless
|
|
8
|
+
// path and undo the whole saving that split exists for.
|
|
9
|
+
import { uuidV4Bytes as generateUuidV4Bytes, uuidV4 as generateUuidV4 } from "./keyless";
|
|
10
|
+
import { uuidV7BytesToMaskedSlug, decodeMaskedSlug } from "./mask";
|
|
11
|
+
import { createMigration } from "./migration";
|
|
12
|
+
import { createMaskSchema, DEFAULT_MASK_SCHEMA, verifyInvertible } from "./schema";
|
|
9
13
|
import type {
|
|
10
14
|
MaskSchema,
|
|
11
|
-
MaskedUuidSlug,
|
|
12
|
-
MaskedUuidV7Slug,
|
|
13
15
|
PublicUuidV7Slug,
|
|
14
16
|
SentinelUuidV7Slug,
|
|
15
|
-
UuidSlug,
|
|
16
17
|
UuidSlugCodec,
|
|
17
18
|
UuidSlugCodecOptions,
|
|
18
|
-
UuidString,
|
|
19
19
|
UuidV4Slug,
|
|
20
|
-
UuidV4String,
|
|
21
20
|
UuidV7Sentinel,
|
|
22
21
|
UuidV7String,
|
|
23
22
|
UuidV7Slug,
|
|
24
23
|
} from "./types";
|
|
25
24
|
import { createRuntimeGenerator } from "./v7";
|
|
26
25
|
import {
|
|
27
|
-
formatUuid,
|
|
28
26
|
formatUuidSlug,
|
|
29
27
|
hasUuidV7Entropy,
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
isUuidV4String,
|
|
33
|
-
isUuidV7Slug,
|
|
34
|
-
isUuidV7String,
|
|
35
|
-
isUuidString,
|
|
28
|
+
isUuidV7Bytes,
|
|
29
|
+
resolveSlugAlphabet,
|
|
36
30
|
parseUuid,
|
|
31
|
+
formatUuid,
|
|
37
32
|
parseUuidSlug,
|
|
38
|
-
slugToUuid,
|
|
39
|
-
uuidBytesToSlug,
|
|
40
|
-
uuidToSlug,
|
|
41
33
|
extractUuidV7Timestamp,
|
|
42
34
|
} from "./uuid";
|
|
43
35
|
import type { FreshValidationOptions, UuidV7SentinelDefinition } from "./types";
|
|
@@ -45,174 +37,284 @@ import type { FreshValidationOptions, UuidV7SentinelDefinition } from "./types";
|
|
|
45
37
|
export const UUID_V7_SENTINEL_DEFINITIONS: readonly UuidV7SentinelDefinition[] = [
|
|
46
38
|
{
|
|
47
39
|
name: "nil",
|
|
48
|
-
uuid: "00000000-0000-7000-8000-000000000000"
|
|
40
|
+
uuid: "00000000-0000-7000-8000-000000000000",
|
|
49
41
|
},
|
|
50
42
|
{
|
|
51
43
|
name: "anonymousUser",
|
|
52
|
-
uuid: "00000000-0001-7000-8000-000000000000"
|
|
44
|
+
uuid: "00000000-0001-7000-8000-000000000000",
|
|
53
45
|
},
|
|
54
46
|
{
|
|
55
47
|
name: "unknownUser",
|
|
56
|
-
uuid: "00000000-0002-7000-8000-000000000000"
|
|
48
|
+
uuid: "00000000-0002-7000-8000-000000000000",
|
|
57
49
|
},
|
|
58
50
|
];
|
|
59
51
|
|
|
60
|
-
function schemaFromOption(mask: UuidSlugCodecOptions["mask"]):
|
|
52
|
+
function schemaFromOption(mask: UuidSlugCodecOptions["mask"]): UuidSlugError | MaskSchema {
|
|
53
|
+
// Omitting `mask` yields a codec that masks under a seed published in this package's source, so
|
|
54
|
+
// its masked slugs are decodable by anyone. That is a real configuration — tests and demos want
|
|
55
|
+
// reproducible output — but it is never the one a caller protecting ids wants, and nothing about
|
|
56
|
+
// the resulting slug reveals which they got. See `defaultCodec` and `UuidSlugCodecOptions.mask`.
|
|
61
57
|
if (!mask) return DEFAULT_MASK_SCHEMA;
|
|
62
|
-
|
|
63
|
-
|
|
58
|
+
// A built schema carries its mixing step; an options object carries only a seed to derive one
|
|
59
|
+
// from. One discriminating property beats sniffing several, which silently stops discriminating
|
|
60
|
+
// when a scheme is added whose data fields differ.
|
|
61
|
+
//
|
|
62
|
+
// Every schema the codec will use passes through here, which is why the invertibility smoke test
|
|
63
|
+
// belongs here and nowhere else: a caller-supplied `mix` is the extension point now, and an
|
|
64
|
+
// unchecked one silently makes every id it encodes unreadable.
|
|
65
|
+
if (!("mix" in mask)) return createMaskSchema(mask);
|
|
66
|
+
return verifyInvertible(mask);
|
|
64
67
|
}
|
|
65
68
|
|
|
66
69
|
function createSentinels(definitions: readonly UuidV7SentinelDefinition[]) {
|
|
67
70
|
const sentinels: UuidV7Sentinel[] = [];
|
|
68
|
-
const byUuid = new
|
|
69
|
-
const
|
|
71
|
+
const byUuid = new Set<string>();
|
|
72
|
+
const encoded: { bytes: Uint8Array; slug: SentinelUuidV7Slug }[] = [];
|
|
73
|
+
const bySlug = new Map<string, { uuid: UuidV7String; bytes: Uint8Array }>();
|
|
70
74
|
for (const definition of definitions) {
|
|
71
|
-
|
|
75
|
+
// `uuid` is typed `UuidV7String`, and that types NOTHING: `Brand`'s marker is optional by
|
|
76
|
+
// design, so every string satisfies every brand and a v4 passed the declaration untouched.
|
|
77
|
+
// It then constructed fine, masked fine, and failed on EVERY decode forever after — a
|
|
78
|
+
// permanent, per-call error configured once at construction. Checked here for the same reason
|
|
79
|
+
// the invertibility smoke test is checked here: this is the last point at which a bad definition is
|
|
80
|
+
// still a caller's argument rather than a codec that cannot work.
|
|
81
|
+
const bytes = errorOrThrow(parseUuid(definition.uuid));
|
|
82
|
+
if (!isUuidV7Bytes(bytes))
|
|
83
|
+
throw new UuidSlugError(
|
|
84
|
+
"invalid_uuid_version",
|
|
85
|
+
`Sentinel "${definition.name}" must be a UUIDv7, got ${String(definition.uuid)}.`,
|
|
86
|
+
);
|
|
87
|
+
// A duplicate collapses SILENTLY: both entries stay in `codec.sentinels`, while the lookup maps
|
|
88
|
+
// keep only the last, so the codec reports a sentinel it will never match.
|
|
89
|
+
if (byUuid.has(definition.uuid))
|
|
90
|
+
throw new UuidSlugError(
|
|
91
|
+
"invalid_uuid",
|
|
92
|
+
`Sentinel "${definition.name}" repeats the UUID of an earlier sentinel.`,
|
|
93
|
+
);
|
|
94
|
+
// Always base64url, never the codec's `slugAlphabet`: a sentinel slug is matched against
|
|
95
|
+
// MASKED input, which is base64url by definition, so one written in another alphabet could
|
|
96
|
+
// never be recognised in the position it exists for.
|
|
97
|
+
const slug = formatUuidSlug(bytes);
|
|
72
98
|
if (slug instanceof Error) throw slug;
|
|
73
|
-
const sentinel = {
|
|
99
|
+
const sentinel = Object.freeze({
|
|
74
100
|
name: definition.name,
|
|
101
|
+
// `formatUuidSlug` returns the version-agnostic brand; the v7-ness comes
|
|
102
|
+
// from the check above.
|
|
75
103
|
slug: slug as SentinelUuidV7Slug,
|
|
76
104
|
uuid: definition.uuid,
|
|
77
|
-
};
|
|
105
|
+
});
|
|
78
106
|
sentinels.push(sentinel);
|
|
79
|
-
byUuid.
|
|
80
|
-
|
|
107
|
+
byUuid.add(definition.uuid);
|
|
108
|
+
encoded.push({ bytes, slug: sentinel.slug });
|
|
109
|
+
bySlug.set(sentinel.slug, { uuid: definition.uuid, bytes });
|
|
81
110
|
}
|
|
82
|
-
return { bySlug,
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Randomness is drawn into a private buffer and copied out instead of filled through a view
|
|
87
|
-
* of the caller's array. `fillRandom` requires a plain `ArrayBuffer` because Web Crypto
|
|
88
|
-
* rejects a `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee.
|
|
89
|
-
* Reused rather than allocated per call, matching the v7 generator, so the cost is one
|
|
90
|
-
* 16-byte copy.
|
|
91
|
-
*/
|
|
92
|
-
const v4Random = new Uint8Array(16);
|
|
93
|
-
|
|
94
|
-
function generateUuidV4Bytes(out?: Uint8Array, offset = 0): Error | Uint8Array {
|
|
95
|
-
const target = out ?? new Uint8Array(16);
|
|
96
|
-
if (offset < 0 || offset + 16 > target.length)
|
|
97
|
-
return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
|
|
98
|
-
runtime.fillRandom(v4Random);
|
|
99
|
-
target.set(v4Random, offset);
|
|
100
|
-
target[offset + 6] = ((target[offset + 6] ?? 0) & 0x0f) | 0x40;
|
|
101
|
-
target[offset + 8] = ((target[offset + 8] ?? 0) & 0x3f) | 0x80;
|
|
102
|
-
return target;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function errorOrThrow<T>(value: Error | T): T {
|
|
106
|
-
if (value instanceof Error) throw value;
|
|
107
|
-
return value;
|
|
111
|
+
return { bySlug, encoded, sentinels: Object.freeze(sentinels) };
|
|
108
112
|
}
|
|
109
113
|
|
|
110
114
|
export function createUuidSlugCodec(options: UuidSlugCodecOptions = {}): UuidSlugCodec {
|
|
111
115
|
const schema = errorOrThrow(schemaFromOption(options.mask));
|
|
112
|
-
|
|
116
|
+
// Every schema a decode may try, and NOTHING a caller did not list. A codec once appended two
|
|
117
|
+
// schemas of its own — a substitution partner derived from any seed, and the default seed's
|
|
118
|
+
// pre-Feistel scheme — on the reasoning that a marker bit would select one outright. No marker
|
|
119
|
+
// exists: each schema is tried in turn and the first whose check passes wins, so the codec's
|
|
120
|
+
// false-accept rate is the SUM over the list and is set by its weakest member. Measured
|
|
121
|
+
// 2026-08-12 over 200,000 wrong-key decodes, the auto-added 6-bit partner accepted 211 while
|
|
122
|
+
// the 16-bit schema it accompanied accepted 2 — a 16x widening nobody asked for.
|
|
123
|
+
const previousMasks = (options.previousMasks ?? []).map((mask) =>
|
|
124
|
+
errorOrThrow(schemaFromOption(mask)),
|
|
125
|
+
);
|
|
113
126
|
const generator = options.generator ?? createRuntimeGenerator(runtime);
|
|
127
|
+
const slugAlphabet = options.slugAlphabet ?? "base64url";
|
|
128
|
+
errorOrThrow(resolveSlugAlphabet(slugAlphabet));
|
|
129
|
+
const acceptUnmaskedSlugs = options.acceptUnmaskedSlugs === true;
|
|
130
|
+
// The runtime's own slug generator emits base64url and nothing else, so it can only serve the
|
|
131
|
+
// default. Resolved once here rather than per call: the branch is on configuration, which cannot
|
|
132
|
+
// change after construction.
|
|
133
|
+
const nativeSlug =
|
|
134
|
+
options.generator === undefined && slugAlphabet === "base64url"
|
|
135
|
+
? runtime.uuidV7Slug
|
|
136
|
+
: undefined;
|
|
114
137
|
const sentinelState = createSentinels(options.sentinels ?? UUID_V7_SENTINEL_DEFINITIONS);
|
|
115
138
|
|
|
116
|
-
function decodeMasked(slug: string):
|
|
117
|
-
const
|
|
118
|
-
if (sentinel) return sentinel;
|
|
119
|
-
const primary = maskedSlugToUuidWithSchema(slug, schema);
|
|
139
|
+
function decodeMasked(slug: string): UuidSlugError | Uint8Array {
|
|
140
|
+
const primary = decodeMaskedSlug(slug, schema, previousMasks);
|
|
120
141
|
if (!(primary instanceof Error)) return primary;
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
if (!(
|
|
142
|
+
if (acceptUnmaskedSlugs) {
|
|
143
|
+
const unmasked = parseUuidSlug(slug);
|
|
144
|
+
if (!(unmasked instanceof Error)) return unmasked;
|
|
124
145
|
}
|
|
125
|
-
|
|
146
|
+
// The fallback's error is DROPPED, deliberately, and this returns `primary` whether or not the
|
|
147
|
+
// fallback ran. It answers a different question — "is this a plain slug?" — and for the failure
|
|
148
|
+
// that actually brings people here, a wrong or rotated key, its answer is untrue: the input is
|
|
149
|
+
// perfectly good base64url whose trailing bits ARE the mask check, so it reported
|
|
150
|
+
// `invalid_base64url: non-canonical trailing bits` and sent operators hunting a typo.
|
|
151
|
+
// `primary` says the schema did not match, which is what happened.
|
|
126
152
|
return primary;
|
|
127
153
|
}
|
|
128
154
|
|
|
129
|
-
function
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
155
|
+
function encodeMasked(bytes: Uint8Array): UuidSlugError | PublicUuidV7Slug {
|
|
156
|
+
if (!isUuidV7Bytes(bytes))
|
|
157
|
+
return new UuidSlugError(
|
|
158
|
+
"invalid_uuid_version",
|
|
159
|
+
"Masked UUID slugs require 16 UUIDv7 bytes.",
|
|
160
|
+
);
|
|
161
|
+
for (const sentinel of sentinelState.encoded) {
|
|
162
|
+
let index = 0;
|
|
163
|
+
while (index < 16 && sentinel.bytes[index] === bytes[index]) index += 1;
|
|
164
|
+
if (index === 16) return sentinel.slug;
|
|
165
|
+
}
|
|
166
|
+
const slug = uuidV7BytesToMaskedSlug(bytes, schema);
|
|
167
|
+
if (slug instanceof Error) return slug;
|
|
168
|
+
// Sentinel decoding takes precedence, so returning this ciphertext would recover a different UUID.
|
|
169
|
+
if (sentinelState.bySlug.has(slug))
|
|
170
|
+
return new UuidSlugError(
|
|
171
|
+
"invalid_mask_schema",
|
|
172
|
+
"Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.",
|
|
173
|
+
);
|
|
174
|
+
return slug;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function uuidV7ToMaskedSlug(uuid: string): UuidSlugError | PublicUuidV7Slug {
|
|
178
|
+
const bytes = parseUuid(uuid);
|
|
179
|
+
return bytes instanceof Error ? bytes : encodeMasked(bytes);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function maskedSlugToUuidV7(slug: string): UuidSlugError | UuidV7String {
|
|
183
|
+
const sentinel = sentinelState.bySlug.get(slug);
|
|
184
|
+
if (sentinel) return sentinel.uuid;
|
|
185
|
+
const decoded = decodeMasked(slug);
|
|
186
|
+
if (decoded instanceof Error) return decoded;
|
|
187
|
+
// Mask decoding restores v7 constants; only the plain fallback can carry another version.
|
|
188
|
+
if (acceptUnmaskedSlugs && !isUuidV7Bytes(decoded))
|
|
189
|
+
return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
|
|
190
|
+
return formatUuid(decoded) as UuidSlugError | UuidV7String;
|
|
133
191
|
}
|
|
134
192
|
|
|
135
193
|
return {
|
|
136
194
|
sentinels: sentinelState.sentinels,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (native) return native as UuidV4String;
|
|
140
|
-
return errorOrThrow(formatUuid(errorOrThrow(generateUuidV4Bytes()))) as UuidV4String;
|
|
195
|
+
migration(migrationOptions) {
|
|
196
|
+
return createMigration([schema, ...previousMasks], sentinelState.bySlug, migrationOptions);
|
|
141
197
|
},
|
|
198
|
+
uuidV4: generateUuidV4,
|
|
142
199
|
uuidV7() {
|
|
143
200
|
return generator.uuidV7();
|
|
144
201
|
},
|
|
145
202
|
uuidV4Bytes: generateUuidV4Bytes,
|
|
146
203
|
uuidV7Bytes: generator.uuidV7Bytes,
|
|
204
|
+
uuidV7At: generator.uuidV7At,
|
|
205
|
+
uuidV7BytesAt: generator.uuidV7BytesAt,
|
|
147
206
|
uuidV4Slug() {
|
|
148
|
-
|
|
207
|
+
// The bytes came from `generateUuidV4Bytes`, which stamps version 4; the encoder sees only
|
|
208
|
+
// bytes and cannot carry that through.
|
|
209
|
+
return errorOrThrow(
|
|
210
|
+
formatUuidSlug(errorOrThrow(generateUuidV4Bytes()), 0, slugAlphabet),
|
|
211
|
+
) as UuidV4Slug;
|
|
149
212
|
},
|
|
150
213
|
uuidV7Slug() {
|
|
151
|
-
if (
|
|
152
|
-
|
|
214
|
+
if (nativeSlug) return nativeSlug();
|
|
215
|
+
// Same assertion `uuidV4Slug` makes for the same reason: the bytes come from a v7 generator,
|
|
216
|
+
// and the encoder sees only bytes so it cannot carry the version through. Until the runtime
|
|
217
|
+
// hooks were branded this cast was ABSENT and nothing complained — the native branch typed
|
|
218
|
+
// the union as bare `string`, which an optional brand accepts, so the promise went unchecked.
|
|
219
|
+
return errorOrThrow(
|
|
220
|
+
formatUuidSlug(errorOrThrow(generator.uuidV7Bytes()), 0, slugAlphabet),
|
|
221
|
+
) as UuidV7Slug;
|
|
153
222
|
},
|
|
154
223
|
uuidV7MaskedSlug() {
|
|
155
|
-
return errorOrThrow(
|
|
156
|
-
},
|
|
157
|
-
uuidToSlug,
|
|
158
|
-
slugToUuid,
|
|
159
|
-
uuidToMaskedSlug(uuid) {
|
|
160
|
-
return uuidV7ToMaskedSlug(uuid) as Error | MaskedUuidSlug;
|
|
224
|
+
return errorOrThrow(encodeMasked(errorOrThrow(generator.uuidV7Bytes())));
|
|
161
225
|
},
|
|
162
|
-
maskedSlugToUuid: decodeMasked,
|
|
163
226
|
uuidV7ToMaskedSlug,
|
|
164
|
-
maskedSlugToUuidV7
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
227
|
+
maskedSlugToUuidV7,
|
|
228
|
+
maskedSlugToUuid(slug) {
|
|
229
|
+
const sentinel = sentinelState.bySlug.get(slug);
|
|
230
|
+
if (sentinel) return sentinel.uuid;
|
|
231
|
+
const bytes = decodeMasked(slug);
|
|
232
|
+
return bytes instanceof Error ? bytes : formatUuid(bytes);
|
|
233
|
+
},
|
|
234
|
+
/**
|
|
235
|
+
* Unmask, then apply the same freshness rules as `validateUuidV7Fresh`, returning the slug.
|
|
236
|
+
*
|
|
237
|
+
* A METHOD rather than the module-level function it replaced: unmasking needs this codec's
|
|
238
|
+
* key, and the old free function reached for `defaultCodec` — so it silently answered under
|
|
239
|
+
* the seed published in this package's source and was wrong for every caller who supplied
|
|
240
|
+
* their own. Nothing about that failure was visible at the call site; it returned a confident
|
|
241
|
+
* Error for perfectly good slugs.
|
|
242
|
+
*
|
|
243
|
+
* Decode directly to bytes instead of formatting and reparsing a UUID. The method does not
|
|
244
|
+
* access `this`, so it also works when detached from the codec.
|
|
245
|
+
*/
|
|
246
|
+
validateMaskedSlugFresh(slug, freshness) {
|
|
247
|
+
const bytes = sentinelState.bySlug.get(slug)?.bytes ?? decodeMasked(slug);
|
|
248
|
+
if (bytes instanceof Error) return bytes;
|
|
249
|
+
// The v7-specific decoder reports this before freshness validation does.
|
|
250
|
+
if (!isUuidV7Bytes(bytes))
|
|
251
|
+
return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
|
|
252
|
+
const valid = validateFreshBytes(bytes, freshness);
|
|
253
|
+
return valid instanceof Error ? valid : slug;
|
|
170
254
|
},
|
|
171
|
-
parseUuid,
|
|
172
|
-
formatUuid,
|
|
173
|
-
parseUuidSlug,
|
|
174
|
-
formatUuidSlug,
|
|
175
255
|
};
|
|
176
256
|
}
|
|
177
257
|
|
|
178
|
-
|
|
258
|
+
/**
|
|
259
|
+
* Uses the published default seed, so anyone can decode its masked slugs.
|
|
260
|
+
* Use `createUuidSlugCodec({ mask: { seed } })` with your own seed to hide identifiers.
|
|
261
|
+
*/
|
|
262
|
+
// Annotated PURE so a bundle that never names it can drop it: a module-scope CONSTRUCTION call is
|
|
263
|
+
// otherwise a side effect no bundler may remove, and this one reaches the cipher, the mask schema
|
|
264
|
+
// and the sentinel table. Sound because `createUuidSlugCodec()` with no options cannot fail — the
|
|
265
|
+
// only throwing paths are caller-supplied sentinels and a caller-supplied mix — and nothing else
|
|
266
|
+
// observes the construction. The annotation is worth nothing on its own: it was measured saving
|
|
267
|
+
// ZERO bytes while `index.ts` bound its shortcuts as PROPERTY READS of this value, since a read at
|
|
268
|
+
// module scope forces the evaluation the annotation permits skipping. Keep the shortcuts keyless
|
|
269
|
+
// (see `keyless.ts`) or this goes dead again.
|
|
270
|
+
export const defaultCodec: UuidSlugCodec = /*#__PURE__*/ createUuidSlugCodec();
|
|
179
271
|
|
|
180
272
|
export function validateUuidV7Fresh(
|
|
181
273
|
uuid: string,
|
|
182
274
|
options: FreshValidationOptions = {},
|
|
183
|
-
):
|
|
184
|
-
if (!isUuidV7String(uuid))
|
|
185
|
-
return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
|
|
275
|
+
): UuidSlugError | UuidV7String {
|
|
186
276
|
const bytes = parseUuid(uuid);
|
|
187
|
-
if (bytes instanceof Error)
|
|
188
|
-
|
|
189
|
-
const
|
|
277
|
+
if (bytes instanceof Error)
|
|
278
|
+
return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
|
|
279
|
+
const valid = validateFreshBytes(bytes, options);
|
|
280
|
+
return valid instanceof Error ? valid : uuid;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Capture decoded fields before calling an external clock, which can reenter a custom schema. */
|
|
284
|
+
function validateFreshBytes(
|
|
285
|
+
bytes: Uint8Array,
|
|
286
|
+
options: FreshValidationOptions = {},
|
|
287
|
+
): UuidSlugError | undefined {
|
|
288
|
+
if (!isUuidV7Bytes(bytes))
|
|
289
|
+
return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
|
|
190
290
|
const timestamp = extractUuidV7Timestamp(bytes);
|
|
291
|
+
if (timestamp instanceof Error) return timestamp;
|
|
292
|
+
const hasEntropy = hasUuidV7Entropy(bytes);
|
|
293
|
+
const windowMs = options.windowMs ?? 86_400_000;
|
|
294
|
+
if (!Number.isFinite(windowMs) || windowMs < 0)
|
|
295
|
+
return new UuidSlugError(
|
|
296
|
+
"invalid_timestamp",
|
|
297
|
+
"windowMs must be a finite, nonnegative number of milliseconds.",
|
|
298
|
+
);
|
|
299
|
+
const now = readClock(options.now ?? Date.now);
|
|
300
|
+
if (now instanceof Error) return now;
|
|
301
|
+
if (!Number.isFinite(now))
|
|
302
|
+
return new UuidSlugError(
|
|
303
|
+
"invalid_timestamp",
|
|
304
|
+
"now must return a finite number of Unix milliseconds.",
|
|
305
|
+
);
|
|
191
306
|
if (timestamp < now - windowMs || timestamp > now + windowMs)
|
|
192
307
|
return new UuidSlugError("stale_uuid", "UUIDv7 timestamp is outside the accepted window.");
|
|
193
|
-
if (!
|
|
194
|
-
|
|
195
|
-
return uuid;
|
|
308
|
+
if (!hasEntropy) return new UuidSlugError("invalid_uuid", "UUIDv7 random payload is degenerate.");
|
|
309
|
+
return undefined;
|
|
196
310
|
}
|
|
197
311
|
|
|
198
312
|
export function validateUuidV7SlugFresh(
|
|
199
313
|
slug: string,
|
|
200
314
|
options?: FreshValidationOptions,
|
|
201
|
-
):
|
|
202
|
-
const
|
|
203
|
-
if (
|
|
204
|
-
const valid =
|
|
205
|
-
return valid instanceof Error ? valid :
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export function validateMaskedUuidV7SlugFresh(
|
|
209
|
-
slug: string,
|
|
210
|
-
options?: FreshValidationOptions,
|
|
211
|
-
): Error | MaskedUuidV7Slug {
|
|
212
|
-
const uuid = defaultCodec.maskedSlugToUuidV7(slug);
|
|
213
|
-
if (uuid instanceof Error) return uuid;
|
|
214
|
-
const valid = validateUuidV7Fresh(uuid, options);
|
|
215
|
-
return valid instanceof Error ? valid : (slug as MaskedUuidV7Slug);
|
|
315
|
+
): UuidSlugError | UuidV7Slug {
|
|
316
|
+
const bytes = parseUuidSlug(slug);
|
|
317
|
+
if (bytes instanceof Error) return bytes;
|
|
318
|
+
const valid = validateFreshBytes(bytes, options);
|
|
319
|
+
return valid instanceof Error ? valid : slug;
|
|
216
320
|
}
|
|
217
|
-
|
|
218
|
-
export { isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Slug, isUuidV7String };
|
package/src/errors.ts
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
/** Consumers can enumerate error codes at runtime without duplicating the type's vocabulary. */
|
|
4
|
+
export const UUID_SLUG_ERROR_CODES = [
|
|
5
|
+
"aborted",
|
|
6
|
+
"invalid_base32",
|
|
7
|
+
"invalid_base64url",
|
|
8
|
+
"invalid_buffer",
|
|
9
|
+
"invalid_mask_schema",
|
|
10
|
+
"invalid_timestamp",
|
|
11
|
+
"invalid_uuid",
|
|
12
|
+
"invalid_uuid_slug",
|
|
13
|
+
"invalid_uuid_version",
|
|
14
|
+
"rng_unavailable",
|
|
15
|
+
"stale_uuid",
|
|
16
|
+
] as const;
|
|
17
|
+
|
|
18
|
+
export type UuidSlugErrorCode = (typeof UUID_SLUG_ERROR_CODES)[number];
|
|
10
19
|
|
|
11
20
|
export class UuidSlugError extends Error {
|
|
12
21
|
readonly code: UuidSlugErrorCode;
|
|
@@ -24,3 +33,68 @@ export class UuidRuntimeError extends UuidSlugError {
|
|
|
24
33
|
this.name = "UuidRuntimeError";
|
|
25
34
|
}
|
|
26
35
|
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The bridge from this package's `Error | T` return convention to the generator convention, where
|
|
39
|
+
* a failure throws. Shared rather than repeated because every module that has both conventions
|
|
40
|
+
* meeting in it needs exactly this, and a local copy is one `instanceof` away from being written
|
|
41
|
+
* as a truthiness test that swallows a legitimate falsy result.
|
|
42
|
+
*/
|
|
43
|
+
export function errorOrThrow<T>(value: UuidSlugError | T): T {
|
|
44
|
+
if (value instanceof Error) throw value;
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The one range check for every entry point that reads or writes a caller's buffer at an offset.
|
|
50
|
+
*
|
|
51
|
+
* `Number.isInteger` is the load-bearing half and the reason this is shared rather than repeated.
|
|
52
|
+
* The obvious spelling — `offset < 0 || offset + need > capacity` — passes a fractional or
|
|
53
|
+
* NaN offset, because both of its comparisons are false for NaN and neither notices `0.5`. What
|
|
54
|
+
* follows is worse than a wrong answer: `bytes[0.5] = x` is not a store, so the write SILENTLY does
|
|
55
|
+
* nothing while the guard reports success, and an id can come back half-written with the caller's
|
|
56
|
+
* stale bytes in the rest of it. A string offset defeats the same test from the other side, by
|
|
57
|
+
* concatenation: `"4" + 16` is `"416"`, which is not greater than any plausible length.
|
|
58
|
+
*
|
|
59
|
+
* Seven near-identical copies of that test existed across this package and not one checked
|
|
60
|
+
* integrality — the copying is why. One copy is what stops the class returning.
|
|
61
|
+
*/
|
|
62
|
+
export function checkRange(
|
|
63
|
+
capacity: number,
|
|
64
|
+
offset: number,
|
|
65
|
+
need: number,
|
|
66
|
+
): undefined | UuidSlugError {
|
|
67
|
+
if (!Number.isInteger(offset))
|
|
68
|
+
return new UuidSlugError(
|
|
69
|
+
"invalid_buffer",
|
|
70
|
+
`Buffer offset must be a whole number, got ${typeof offset} ${String(offset)}.`,
|
|
71
|
+
);
|
|
72
|
+
if (offset < 0 || offset + need > capacity)
|
|
73
|
+
return new UuidSlugError(
|
|
74
|
+
"invalid_buffer",
|
|
75
|
+
`Buffer needs ${need} bytes at offset ${offset}, but holds ${capacity}.`,
|
|
76
|
+
);
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Preserve failures from an injected or platform entropy source without changing successful draws. */
|
|
81
|
+
export function fillRandomBytes(
|
|
82
|
+
fill: (bytes: Uint8Array<ArrayBuffer>) => void,
|
|
83
|
+
bytes: Uint8Array<ArrayBuffer>,
|
|
84
|
+
): UuidRuntimeError | undefined {
|
|
85
|
+
try {
|
|
86
|
+
fill(bytes);
|
|
87
|
+
return undefined;
|
|
88
|
+
} catch (cause) {
|
|
89
|
+
return new UuidRuntimeError("Random byte generation failed.", { cause });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Read once so a failing clock keeps its original cause and successful clocks have one observation. */
|
|
94
|
+
export function readClock(clock: () => number): number | UuidSlugError {
|
|
95
|
+
try {
|
|
96
|
+
return clock();
|
|
97
|
+
} catch (cause) {
|
|
98
|
+
return new UuidSlugError("invalid_timestamp", "Clock reading failed.", { cause });
|
|
99
|
+
}
|
|
100
|
+
}
|