@anizoptera/uuid-slug 0.3.0 → 0.5.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.
Files changed (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +373 -324
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +15 -8
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
@@ -1,31 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidSlugError } from "./errors.js";
4
- import { BASE64URL, decodeInto, encode, isEncoded } from "./alphabet.js";
5
- //#region src/base64url.ts
6
- function encodeBase64Url(bytes) {
7
- return encode(bytes, BASE64URL);
8
- }
9
- /**
10
- * Decodes into `out` at `offset` when given one, otherwise into a fresh array.
11
- *
12
- * Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
13
- * `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
14
- * size, with the data at `offset` and no way to learn how many bytes had been written short of
15
- * recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
16
- * makes the length usable and leaves the caller's own buffer reachable, since they own it.
17
- */
18
- function decodeBase64Url(value, out, offset = 0) {
19
- if (value.includes("=")) return new UuidSlugError("invalid_base64url", "Base64url value must be unpadded.");
20
- const byteLength = Math.floor(value.length * BASE64URL.bitsPerChar / 8);
21
- const target = out ?? new Uint8Array(byteLength);
22
- const result = decodeInto(value, BASE64URL, target, offset, byteLength);
23
- if (result instanceof Error) return result;
24
- return target.subarray(offset, offset + byteLength);
25
- }
26
- function isBase64Url(value) {
27
- if (!value) return false;
28
- return isEncoded(value, BASE64URL, Math.floor(value.length * BASE64URL.bitsPerChar / 8));
29
- }
30
- //#endregion
31
- export { decodeBase64Url, encodeBase64Url, isBase64Url };
@@ -1,190 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidSlugError, errorOrThrow, readClock } from "./errors.js";
4
- import { runtime } from "./runtime/node.js";
5
- import { extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isUuidV7Bytes, parseUuid, parseUuidSlug, resolveSlugAlphabet } from "./uuid.js";
6
- import { createRuntimeGenerator } from "./v7.js";
7
- import { uuidV4, uuidV4Bytes } from "./keyless.js";
8
- import { decodeMaskedSlug, uuidV7BytesToMaskedSlug } from "./mask.js";
9
- import { createMigration } from "./migration.js";
10
- import { DEFAULT_MASK_SCHEMA, createMaskSchema, verifyInvertible } from "./schema.js";
11
- //#region src/codec.ts
12
- const UUID_V7_SENTINEL_DEFINITIONS = [
13
- {
14
- name: "nil",
15
- uuid: "00000000-0000-7000-8000-000000000000"
16
- },
17
- {
18
- name: "anonymousUser",
19
- uuid: "00000000-0001-7000-8000-000000000000"
20
- },
21
- {
22
- name: "unknownUser",
23
- uuid: "00000000-0002-7000-8000-000000000000"
24
- }
25
- ];
26
- function schemaFromOption(mask) {
27
- if (!mask) return DEFAULT_MASK_SCHEMA;
28
- if (!("mix" in mask)) return createMaskSchema(mask);
29
- return verifyInvertible(mask);
30
- }
31
- function createSentinels(definitions) {
32
- const sentinels = [];
33
- const byUuid = /* @__PURE__ */ new Set();
34
- const encoded = [];
35
- const bySlug = /* @__PURE__ */ new Map();
36
- for (const definition of definitions) {
37
- const bytes = errorOrThrow(parseUuid(definition.uuid));
38
- if (!isUuidV7Bytes(bytes)) throw new UuidSlugError("invalid_uuid_version", `Sentinel "${definition.name}" must be a UUIDv7, got ${String(definition.uuid)}.`);
39
- if (byUuid.has(definition.uuid)) throw new UuidSlugError("invalid_uuid", `Sentinel "${definition.name}" repeats the UUID of an earlier sentinel.`);
40
- const slug = formatUuidSlug(bytes);
41
- if (slug instanceof Error) throw slug;
42
- const sentinel = Object.freeze({
43
- name: definition.name,
44
- slug,
45
- uuid: definition.uuid
46
- });
47
- sentinels.push(sentinel);
48
- byUuid.add(definition.uuid);
49
- encoded.push({
50
- bytes,
51
- slug: sentinel.slug
52
- });
53
- bySlug.set(sentinel.slug, {
54
- uuid: definition.uuid,
55
- bytes
56
- });
57
- }
58
- return {
59
- bySlug,
60
- encoded,
61
- sentinels: Object.freeze(sentinels)
62
- };
63
- }
64
- function createUuidSlugCodec(options = {}) {
65
- const schema = errorOrThrow(schemaFromOption(options.mask));
66
- const previousMasks = (options.previousMasks ?? []).map((mask) => errorOrThrow(schemaFromOption(mask)));
67
- const generator = options.generator ?? createRuntimeGenerator(runtime);
68
- const slugAlphabet = options.slugAlphabet ?? "base64url";
69
- errorOrThrow(resolveSlugAlphabet(slugAlphabet));
70
- const acceptUnmaskedSlugs = options.acceptUnmaskedSlugs === true;
71
- const nativeSlug = options.generator === void 0 && slugAlphabet === "base64url" ? runtime.uuidV7Slug : void 0;
72
- const sentinelState = createSentinels(options.sentinels ?? UUID_V7_SENTINEL_DEFINITIONS);
73
- function decodeMasked(slug) {
74
- const primary = decodeMaskedSlug(slug, schema, previousMasks);
75
- if (!(primary instanceof Error)) return primary;
76
- if (acceptUnmaskedSlugs) {
77
- const unmasked = parseUuidSlug(slug);
78
- if (!(unmasked instanceof Error)) return unmasked;
79
- }
80
- return primary;
81
- }
82
- function encodeMasked(bytes) {
83
- if (!isUuidV7Bytes(bytes)) return new UuidSlugError("invalid_uuid_version", "Masked UUID slugs require 16 UUIDv7 bytes.");
84
- for (const sentinel of sentinelState.encoded) {
85
- let index = 0;
86
- while (index < 16 && sentinel.bytes[index] === bytes[index]) index += 1;
87
- if (index === 16) return sentinel.slug;
88
- }
89
- const slug = uuidV7BytesToMaskedSlug(bytes, schema);
90
- if (slug instanceof Error) return slug;
91
- if (sentinelState.bySlug.has(slug)) return new UuidSlugError("invalid_mask_schema", "Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.");
92
- return slug;
93
- }
94
- function uuidV7ToMaskedSlug(uuid) {
95
- const bytes = parseUuid(uuid);
96
- return bytes instanceof Error ? bytes : encodeMasked(bytes);
97
- }
98
- function maskedSlugToUuidV7(slug) {
99
- const sentinel = sentinelState.bySlug.get(slug);
100
- if (sentinel) return sentinel.uuid;
101
- const decoded = decodeMasked(slug);
102
- if (decoded instanceof Error) return decoded;
103
- if (acceptUnmaskedSlugs && !isUuidV7Bytes(decoded)) return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
104
- return formatUuid(decoded);
105
- }
106
- return {
107
- sentinels: sentinelState.sentinels,
108
- migration(migrationOptions) {
109
- return createMigration([schema, ...previousMasks], sentinelState.bySlug, migrationOptions);
110
- },
111
- uuidV4,
112
- uuidV7() {
113
- return generator.uuidV7();
114
- },
115
- uuidV4Bytes,
116
- uuidV7Bytes: generator.uuidV7Bytes,
117
- uuidV7At: generator.uuidV7At,
118
- uuidV7BytesAt: generator.uuidV7BytesAt,
119
- uuidV4Slug() {
120
- return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, slugAlphabet));
121
- },
122
- uuidV7Slug() {
123
- if (nativeSlug) return nativeSlug();
124
- return errorOrThrow(formatUuidSlug(errorOrThrow(generator.uuidV7Bytes()), 0, slugAlphabet));
125
- },
126
- uuidV7MaskedSlug() {
127
- return errorOrThrow(encodeMasked(errorOrThrow(generator.uuidV7Bytes())));
128
- },
129
- uuidV7ToMaskedSlug,
130
- maskedSlugToUuidV7,
131
- maskedSlugToUuid(slug) {
132
- const sentinel = sentinelState.bySlug.get(slug);
133
- if (sentinel) return sentinel.uuid;
134
- const bytes = decodeMasked(slug);
135
- return bytes instanceof Error ? bytes : formatUuid(bytes);
136
- },
137
- /**
138
- * Unmask, then apply the same freshness rules as `validateUuidV7Fresh`, returning the slug.
139
- *
140
- * A METHOD rather than the module-level function it replaced: unmasking needs this codec's
141
- * key, and the old free function reached for `defaultCodec` — so it silently answered under
142
- * the seed published in this package's source and was wrong for every caller who supplied
143
- * their own. Nothing about that failure was visible at the call site; it returned a confident
144
- * Error for perfectly good slugs.
145
- *
146
- * Decode directly to bytes instead of formatting and reparsing a UUID. The method does not
147
- * access `this`, so it also works when detached from the codec.
148
- */
149
- validateMaskedSlugFresh(slug, freshness) {
150
- const bytes = sentinelState.bySlug.get(slug)?.bytes ?? decodeMasked(slug);
151
- if (bytes instanceof Error) return bytes;
152
- if (!isUuidV7Bytes(bytes)) return new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
153
- const valid = validateFreshBytes(bytes, freshness);
154
- return valid instanceof Error ? valid : slug;
155
- }
156
- };
157
- }
158
- /**
159
- * Uses the published default seed, so anyone can decode its masked slugs.
160
- * Use `createUuidSlugCodec({ mask: { seed } })` with your own seed to hide identifiers.
161
- */
162
- const defaultCodec = /*#__PURE__*/ createUuidSlugCodec();
163
- function validateUuidV7Fresh(uuid, options = {}) {
164
- const bytes = parseUuid(uuid);
165
- if (bytes instanceof Error) return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
166
- const valid = validateFreshBytes(bytes, options);
167
- return valid instanceof Error ? valid : uuid;
168
- }
169
- /** Capture decoded fields before calling an external clock, which can reenter a custom schema. */
170
- function validateFreshBytes(bytes, options = {}) {
171
- if (!isUuidV7Bytes(bytes)) return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
172
- const timestamp = extractUuidV7Timestamp(bytes);
173
- if (timestamp instanceof Error) return timestamp;
174
- const hasEntropy = hasUuidV7Entropy(bytes);
175
- const windowMs = options.windowMs ?? 864e5;
176
- if (!Number.isFinite(windowMs) || windowMs < 0) return new UuidSlugError("invalid_timestamp", "windowMs must be a finite, nonnegative number of milliseconds.");
177
- const now = readClock(options.now ?? Date.now);
178
- if (now instanceof Error) return now;
179
- if (!Number.isFinite(now)) return new UuidSlugError("invalid_timestamp", "now must return a finite number of Unix milliseconds.");
180
- if (timestamp < now - windowMs || timestamp > now + windowMs) return new UuidSlugError("stale_uuid", "UUIDv7 timestamp is outside the accepted window.");
181
- if (!hasEntropy) return new UuidSlugError("invalid_uuid", "UUIDv7 random payload is degenerate.");
182
- }
183
- function validateUuidV7SlugFresh(slug, options) {
184
- const bytes = parseUuidSlug(slug);
185
- if (bytes instanceof Error) return bytes;
186
- const valid = validateFreshBytes(bytes, options);
187
- return valid instanceof Error ? valid : slug;
188
- }
189
- //#endregion
190
- export { UUID_V7_SENTINEL_DEFINITIONS, createUuidSlugCodec, defaultCodec, validateUuidV7Fresh, validateUuidV7SlugFresh };
@@ -1,78 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- //#region src/errors.ts
4
- /** Consumers can enumerate error codes at runtime without duplicating the type's vocabulary. */
5
- const UUID_SLUG_ERROR_CODES = [
6
- "aborted",
7
- "invalid_base32",
8
- "invalid_base64url",
9
- "invalid_buffer",
10
- "invalid_mask_schema",
11
- "invalid_timestamp",
12
- "invalid_uuid",
13
- "invalid_uuid_slug",
14
- "invalid_uuid_version",
15
- "rng_unavailable",
16
- "stale_uuid"
17
- ];
18
- var UuidSlugError = class extends Error {
19
- code;
20
- constructor(code, message, options) {
21
- super(message, options);
22
- this.name = "UuidSlugError";
23
- this.code = code;
24
- }
25
- };
26
- var UuidRuntimeError = class extends UuidSlugError {
27
- constructor(message, options) {
28
- super("rng_unavailable", message, options);
29
- this.name = "UuidRuntimeError";
30
- }
31
- };
32
- /**
33
- * The bridge from this package's `Error | T` return convention to the generator convention, where
34
- * a failure throws. Shared rather than repeated because every module that has both conventions
35
- * meeting in it needs exactly this, and a local copy is one `instanceof` away from being written
36
- * as a truthiness test that swallows a legitimate falsy result.
37
- */
38
- function errorOrThrow(value) {
39
- if (value instanceof Error) throw value;
40
- return value;
41
- }
42
- /**
43
- * The one range check for every entry point that reads or writes a caller's buffer at an offset.
44
- *
45
- * `Number.isInteger` is the load-bearing half and the reason this is shared rather than repeated.
46
- * The obvious spelling — `offset < 0 || offset + need > capacity` — passes a fractional or
47
- * NaN offset, because both of its comparisons are false for NaN and neither notices `0.5`. What
48
- * follows is worse than a wrong answer: `bytes[0.5] = x` is not a store, so the write SILENTLY does
49
- * nothing while the guard reports success, and an id can come back half-written with the caller's
50
- * stale bytes in the rest of it. A string offset defeats the same test from the other side, by
51
- * concatenation: `"4" + 16` is `"416"`, which is not greater than any plausible length.
52
- *
53
- * Seven near-identical copies of that test existed across this package and not one checked
54
- * integrality — the copying is why. One copy is what stops the class returning.
55
- */
56
- function checkRange(capacity, offset, need) {
57
- if (!Number.isInteger(offset)) return new UuidSlugError("invalid_buffer", `Buffer offset must be a whole number, got ${typeof offset} ${String(offset)}.`);
58
- if (offset < 0 || offset + need > capacity) return new UuidSlugError("invalid_buffer", `Buffer needs ${need} bytes at offset ${offset}, but holds ${capacity}.`);
59
- }
60
- /** Preserve failures from an injected or platform entropy source without changing successful draws. */
61
- function fillRandomBytes(fill, bytes) {
62
- try {
63
- fill(bytes);
64
- return;
65
- } catch (cause) {
66
- return new UuidRuntimeError("Random byte generation failed.", { cause });
67
- }
68
- }
69
- /** Read once so a failing clock keeps its original cause and successful clocks have one observation. */
70
- function readClock(clock) {
71
- try {
72
- return clock();
73
- } catch (cause) {
74
- return new UuidSlugError("invalid_timestamp", "Clock reading failed.", { cause });
75
- }
76
- }
77
- //#endregion
78
- export { UUID_SLUG_ERROR_CODES, UuidRuntimeError, UuidSlugError, checkRange, errorOrThrow, fillRandomBytes, readClock };
@@ -1,103 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { halfSipHash } from "./siphash.js";
4
- //#region src/feistel.ts
5
- /**
6
- * A 4-round Feistel network over the 16 UUID bytes, used as the mask's mixing step.
7
- *
8
- * Why a Feistel rather than the byte permutation plus XOR it replaces: that construction is a
9
- * monoalphabetic substitution — one output byte per input byte — so bytes the inputs share, the
10
- * outputs share too. Measured over 3000 ids, masked slugs of UUIDv7s created in the same second
11
- * held 4 of 16 bytes constant, the same hour 3, the same day 2. The timestamp the mask exists to
12
- * hide was still legible in the output. A Feistel diffuses every input bit across the whole
13
- * block, so no output byte is a function of one input byte: the same measurement yields 0 of 16.
14
- *
15
- * The bijection is the property being bought, and it holds whatever the round function does: 16
16
- * bytes map to 16 bytes and the inverse is the same routine with the round keys reversed, so
17
- * `mask` and `unmask` cannot drift apart.
18
- *
19
- * The round function is HalfSipHash-2-4 keyed per round. What that fixes: the previous round
20
- * function was `mix32(word ^ roundKey)` — a FIXED, PUBLIC, UNKEYED bijection with the key merely
21
- * XORed in front, so an attacker inverts it and reads `word ^ roundKey` directly. Luby-Rackoff
22
- * makes a four-round Feistel a strong pseudorandom permutation only when the round functions are
23
- * pseudorandom functions, which `mix32` is not, so the theorem said nothing about what shipped and
24
- * an earlier version of this comment cited it wrongly. A keyed PRF meets that hypothesis in kind,
25
- * which is what makes ROUNDS = 4 a justified number rather than an unexamined margin. It is still
26
- * NOT a proof about what ships: the theorem wants four INDEPENDENTLY sampled round functions, and
27
- * `schema.ts` derives all four key pairs from one 128-bit key. Read it as the design rationale it
28
- * is, and see `docs/design.md` for what masking does and does not promise.
29
- *
30
- * Measured 2026-08-12 on Bun, both directions, medians of 9: the swap costs 2.5x on the mixing step
31
- * alone (30.85M -> 12.43M mixes/s) and about a quarter of end-to-end masking throughput, because
32
- * mixing is roughly a fifth of a mask. HalfSipHash is FASTER per round than `mix32` — pure
33
- * add/xor/rotate against two `Math.imul` calls — and loses only by doing 14 rounds where the old
34
- * function did the equivalent of 4.
35
- *
36
- * Nor does any measurement in this repository grade the round count or the round function. Strict
37
- * avalanche across all input/output bit pairs, a same-millisecond burst where only a 12-bit counter
38
- * varies, and a single-difference differential all PASS a TWO-round network, so none of them can
39
- * separate a weak setting from a strong one. Their agreement is evidence about the instruments.
40
- * `test/siphash.test.ts` is the exception and the reason a published primitive was worth taking:
41
- * it checks the round function against 64 vectors somebody else computed, and that CAN fail.
42
- */
43
- /**
44
- * Round count. Wire-format-bearing: changing it changes every masked slug this package has ever
45
- * issued, so it moves only alongside a deliberate format change. Four is Luby-Rackoff's number,
46
- * which the round function now makes relevant — see the note above for why that is a rationale
47
- * rather than a proof.
48
- */
49
- const ROUNDS = 4;
50
- /**
51
- * The `lowbias32` finalizer: an integer hash with near-ideal avalanche for its size. No longer the
52
- * round function — see above — but still what `mask.ts` derives its check tag with, where the input
53
- * is public and an unkeyed mixer is the right tool.
54
- */
55
- function mix32(value) {
56
- let x = (value ^ value >>> 16) >>> 0;
57
- x = Math.imul(x, 2146121005);
58
- x = (x ^ x >>> 15) >>> 0;
59
- x = Math.imul(x, 2221713035);
60
- return (x ^ x >>> 16) >>> 0;
61
- }
62
- /** Big-endian on purpose: the wire format must not depend on the host's byte order. */
63
- function read32(bytes, offset) {
64
- return bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3] | 0;
65
- }
66
- function write32(bytes, offset, value) {
67
- bytes[offset] = value >>> 24;
68
- bytes[offset + 1] = value >>> 16 & 255;
69
- bytes[offset + 2] = value >>> 8 & 255;
70
- bytes[offset + 3] = value & 255;
71
- }
72
- const roundInput = /* @__PURE__ */ new Int32Array(2);
73
- const roundOutput = /* @__PURE__ */ new Int32Array(2);
74
- /**
75
- * Transform 16 bytes from `input` into `output`, which may be the same array.
76
- *
77
- * `forward: false` is the exact inverse — the rounds are identical and only the key order
78
- * differs, which is why the final swap below is undone rather than performed.
79
- */
80
- function feistel16(input, inputOffset, keys, forward, output, outputOffset) {
81
- let left0 = read32(input, inputOffset);
82
- let left1 = read32(input, inputOffset + 4);
83
- let right0 = read32(input, inputOffset + 8);
84
- let right1 = read32(input, inputOffset + 12);
85
- for (let round = 0; round < ROUNDS; round += 1) {
86
- const key = (forward ? round : 3 - round) * 2;
87
- roundInput[0] = right0;
88
- roundInput[1] = right1;
89
- halfSipHash(keys[key], keys[key + 1], roundInput, 8, roundOutput);
90
- const next0 = left0 ^ roundOutput[0];
91
- const next1 = left1 ^ roundOutput[1];
92
- left0 = right0;
93
- left1 = right1;
94
- right0 = next0;
95
- right1 = next1;
96
- }
97
- write32(output, outputOffset, right0);
98
- write32(output, outputOffset + 4, right1);
99
- write32(output, outputOffset + 8, left0);
100
- write32(output, outputOffset + 12, left1);
101
- }
102
- //#endregion
103
- export { feistel16, mix32, read32 };
@@ -1,10 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UUID_SLUG_ERROR_CODES, UuidRuntimeError, UuidSlugError } from "./errors.js";
4
- import { decodeBase64Url, encodeBase64Url, isBase64Url } from "./base64url.js";
5
- import { extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Bytes, isUuidV7Slug, isUuidV7String, parseUuid, parseUuidSlug, slugToUuid, uuidToSlug } from "./uuid.js";
6
- import { createUuidV7Generator } from "./v7.js";
7
- import { uuidV4, uuidV4Bytes, uuidV4Slug, uuidV7, uuidV7At, uuidV7Bytes, uuidV7BytesAt, uuidV7Slug } from "./keyless.js";
8
- import { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync } from "./schema.js";
9
- import { UUID_V7_SENTINEL_DEFINITIONS, createUuidSlugCodec, defaultCodec, validateUuidV7Fresh, validateUuidV7SlugFresh } from "./codec.js";
10
- export { DEFAULT_MASK_SCHEMA, UUID_SLUG_ERROR_CODES, UUID_V7_SENTINEL_DEFINITIONS, UuidRuntimeError, UuidSlugError, createMaskSchema, createMaskSchemaAsync, createUuidSlugCodec, createUuidV7Generator, decodeBase64Url, defaultCodec, encodeBase64Url, extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isBase64Url, isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Bytes, isUuidV7Slug, isUuidV7String, parseUuid, parseUuidSlug, slugToUuid, uuidToSlug, uuidV4, uuidV4Bytes, uuidV4Slug, uuidV7, uuidV7At, uuidV7Bytes, uuidV7BytesAt, uuidV7Slug, validateUuidV7Fresh, validateUuidV7SlugFresh };
@@ -1,91 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidRuntimeError, checkRange, errorOrThrow, fillRandomBytes } from "./errors.js";
4
- import { runtime } from "./runtime/node.js";
5
- import { formatUuid, formatUuidSlug } from "./uuid.js";
6
- import { createRuntimeGenerator } from "./v7.js";
7
- //#region src/keyless.ts
8
- /**
9
- * The operations that need no key, built WITHOUT a codec.
10
- *
11
- * Generating an id and re-encoding one are keyless: the result is the same value whoever asks, so
12
- * a bare function is an honest shape for them. Reaching them through a codec is what made them
13
- * expensive — a codec carries a mask schema, a cipher and a sentinel table, none of which a caller
14
- * who never masks will ever execute, and all of which a bundler must keep once the graph reaches
15
- * them. Measured 2026-08-12 on the built package: an entry importing only `uuidV7Slug` minified to
16
- * 12,735 bytes through the codec and 4,559 from a bare generator; `uuidToSlug` alone, 12,725
17
- * against 2,188. `defaultCodec` still exists and still works — it is simply no longer on the path
18
- * every consumer walks.
19
- *
20
- * NOTHING KEYED MAY BE ADDED HERE (Art's ruling, 2026-08-12). The only key a bare function could
21
- * carry is `DEFAULT_MASK_SCHEMA`'s, whose seed is a string literal in this published package, so a
22
- * masked operation exported this way would be the shortest spelling of the headline feature and
23
- * the one that obfuscates nothing. Masking is reached through a codec built with your own seed.
24
- */
25
- /**
26
- * Built on first use, and the laziness is what the measurement above depends on: a module-scope
27
- * CONSTRUCTION call is a side effect a bundler may not remove, so an eager one would pin the
28
- * generator, the runtime adapter and the entropy pool into a bundle that only ever re-encodes a
29
- * UUID. Measured the same day, the eager spelling cost 5,130 bytes for `uuidToSlug` alone against
30
- * 2,188 here.
31
- *
32
- * It also keeps import-time work at zero, which `test/entropy.test.ts` gates for a different
33
- * reason — a heap snapshot taken at module load must capture no drawn randomness.
34
- */
35
- let generator;
36
- const v7 = () => generator ??= createRuntimeGenerator(runtime);
37
- /**
38
- * Randomness is drawn into a private buffer and copied out instead of filled through a view of the
39
- * caller's array: `fillRandom` requires a plain `ArrayBuffer` because Web Crypto rejects a
40
- * `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee. Reused rather
41
- * than allocated per call, matching the v7 generator, so the cost is one 16-byte copy.
42
- */
43
- const v4Random = /* @__PURE__ */ new Uint8Array(16);
44
- /** Shared with `createUuidSlugCodec`, so a v4 has one implementation however it is reached. */
45
- function uuidV4Bytes(out, offset = 0) {
46
- const target = out ?? /* @__PURE__ */ new Uint8Array(16);
47
- const badRange = checkRange(target.length, offset, 16);
48
- if (badRange) return badRange;
49
- const failed = fillRandomBytes(runtime.fillRandom, v4Random);
50
- if (failed) return failed;
51
- target.set(v4Random, offset);
52
- target[offset + 6] = (target[offset + 6] ?? 0) & 15 | 64;
53
- target[offset + 8] = (target[offset + 8] ?? 0) & 63 | 128;
54
- return target;
55
- }
56
- function uuidV4() {
57
- try {
58
- const native = runtime.uuidV4?.();
59
- if (native) return native;
60
- } catch (cause) {
61
- throw new UuidRuntimeError("Runtime UUIDv4 generation failed.", { cause });
62
- }
63
- return errorOrThrow(formatUuid(errorOrThrow(uuidV4Bytes())));
64
- }
65
- /**
66
- * Takes the alphabet for the same reason `uuidV7Slug` does, and NOT because a v4 slug sorts — it
67
- * does not. The alphabet is a choice of representation, so a project that has standardised on the
68
- * 26-character lowercase form for its public ids needs its v4 slugs in it too; the pair differing
69
- * would be an asymmetry with nothing behind it.
70
- */
71
- function uuidV4Slug(alphabet = "base64url") {
72
- return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, alphabet));
73
- }
74
- const uuidV7 = () => v7().uuidV7();
75
- const uuidV7Bytes = (out, offset) => v7().uuidV7Bytes(out, offset);
76
- const uuidV7At = (timestamp) => v7().uuidV7At(timestamp);
77
- const uuidV7BytesAt = (timestamp, out, offset) => v7().uuidV7BytesAt(timestamp, out, offset);
78
- /**
79
- * The alphabet is an argument here, exactly as it is on `uuidToSlug(uuid, alphabet)`, because
80
- * choosing it needs no key: without it the only way to GENERATE a base32hex slug was to build a
81
- * codec, so the sortable form cost the whole masking machinery while the unsortable one was free.
82
- * Positional and last, matching `uuidToSlug`, so the two spellings of "encode in this alphabet"
83
- * do not diverge.
84
- */
85
- function uuidV7Slug(alphabet = "base64url") {
86
- const native = alphabet === "base64url" ? runtime.uuidV7Slug : void 0;
87
- if (native) return native();
88
- return errorOrThrow(formatUuidSlug(errorOrThrow(v7().uuidV7Bytes()), 0, alphabet));
89
- }
90
- //#endregion
91
- export { uuidV4, uuidV4Bytes, uuidV4Slug, uuidV7, uuidV7At, uuidV7Bytes, uuidV7BytesAt, uuidV7Slug };
@@ -1,53 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidSlugError } from "./errors.js";
4
- //#region src/legacy-mask.ts
5
- const PERMUTE = [
6
- 9,
7
- 13,
8
- 3,
9
- 8,
10
- 14,
11
- 0,
12
- 11,
13
- 7,
14
- 6,
15
- 1,
16
- 15,
17
- 4,
18
- 2,
19
- 5,
20
- 10,
21
- 12
22
- ];
23
- const XOR = [
24
- 162,
25
- 112,
26
- 50,
27
- 127,
28
- 152,
29
- 184,
30
- 155,
31
- 94,
32
- 27,
33
- 38,
34
- 182,
35
- 22,
36
- 150,
37
- 249,
38
- 234,
39
- 62
40
- ];
41
- /** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */
42
- function decodeOriginalMask(mixed) {
43
- if (mixed.length !== 16) return new UuidSlugError("invalid_buffer", "Original masked slugs require 16 decoded bytes.");
44
- const bytes = /* @__PURE__ */ new Uint8Array(16);
45
- for (let i = 0; i < 16; i++) bytes[PERMUTE[i]] = mixed[i] ^ XOR[i];
46
- const found = bytes[6] >>> 4;
47
- bytes[6] = bytes[6] & 15 | 112;
48
- let checksum = 0;
49
- for (const byte of bytes) checksum ^= byte;
50
- return (checksum >>> 4 ^ checksum & 15) === found ? bytes : void 0;
51
- }
52
- //#endregion
53
- export { decodeOriginalMask };
package/dist/node/mask.js DELETED
@@ -1,106 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidSlugError } from "./errors.js";
4
- import { BASE64URL, decodeInto, encode, spareBits } from "./alphabet.js";
5
- import { formatUuid } from "./uuid.js";
6
- import { mix32, read32 } from "./feistel.js";
7
- //#region src/mask.ts
8
- /** Custom callbacks can fail after construction; preserve their cause in the public error contract. */
9
- function applyMix(schema, input, output, forward) {
10
- try {
11
- schema.mix(input, output, forward);
12
- return;
13
- } catch (cause) {
14
- return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" failed ${forward ? "encoding" : "decoding"}.`, { cause });
15
- }
16
- }
17
- /**
18
- * The check must fail a wrong key with probability 2^-width, which holds only if the function
19
- * spreads its input across its whole output — so this is an avalanche mixer, not a sum. Measured
20
- * over 100,000 draws: uniform to chi-squared/df 0.999 across all 65,536 buckets of its top 16 bits.
21
- *
22
- * Taken from the TOP so that widening the check never renumbers the bits below it.
23
- */
24
- function tagFor(bytes, width) {
25
- let acc = 0;
26
- for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));
27
- return acc >>> 32 - width;
28
- }
29
- /**
30
- * The 12 check bits a UUIDv7 can hold inside the block, because it spends them on nothing: bits
31
- * 0-3 in byte 6's version nibble, 4-5 in byte 8's variant bits, 6-11 in byte 0's top six — the
32
- * high end of the 48-bit timestamp, zero for every instant before 2109. The rest of the check
33
- * rides outside the block, in whatever the encoding has spare.
34
- *
35
- * Claiming byte 0 is why encoding must REFUSE an instant at or past 2^42 ms rather than truncate.
36
- */
37
- function injectTag(bytes, tag) {
38
- bytes[6] = (tag & 15) << 4 | (bytes[6] ?? 0) & 15;
39
- bytes[8] = (tag & 48) << 2 | (bytes[8] ?? 0) & 63;
40
- bytes[0] = (tag >>> 6 & 63) << 2 | (bytes[0] ?? 0) & 3;
41
- }
42
- function extractTag(bytes) {
43
- return (bytes[6] ?? 0) >>> 4 | (bytes[8] ?? 0) >>> 6 << 4 | (bytes[0] ?? 0) >>> 2 << 6;
44
- }
45
- /** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
46
- function restoreV7(bytes) {
47
- bytes[6] = (bytes[6] ?? 0) & 15 | 112;
48
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
49
- bytes[0] = (bytes[0] ?? 0) & 3;
50
- }
51
- /** The 12 check bits that fit inside the block; the rest ride in the encoding's spare bits. */
52
- const INNER_TAG_BITS = 12;
53
- /**
54
- * A masked slug is always 22 base64url characters (Art's ruling, 2026-08-12), so the outer half of
55
- * the check is a constant 4 bits. Derived rather than written as `4` because the derivation IS the
56
- * rule — the check is whatever the encoding has left over, never a number somebody chose.
57
- */
58
- const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
59
- const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
60
- function uuidV7BytesToMaskedSlug(raw, schema) {
61
- if ((raw[0] ?? 0) > 3) return new UuidSlugError("invalid_timestamp", "Masking requires a UUIDv7 timestamped before 2^42 ms (year 2109); its top six bits carry the check.");
62
- const tag = tagFor(raw, TAG_BITS);
63
- const tagged = new Uint8Array(raw);
64
- injectTag(tagged, tag >>> OUTER_TAG_BITS);
65
- const mixed = /* @__PURE__ */ new Uint8Array(16);
66
- const failed = applyMix(schema, tagged, mixed, true);
67
- if (failed) return failed;
68
- return encode(mixed, BASE64URL, tag & (1 << OUTER_TAG_BITS) - 1, OUTER_TAG_BITS);
69
- }
70
- function decodeMaskedSlug(slug, schema, previous = []) {
71
- const mixed = /* @__PURE__ */ new Uint8Array(16);
72
- const outerTag = decodeInto(slug, BASE64URL, mixed, 0, 16, OUTER_TAG_BITS);
73
- if (outerTag instanceof Error) return outerTag;
74
- const primary = unmix(previous.length ? mixed.slice() : mixed, outerTag, schema);
75
- if (primary && !(primary instanceof Error)) return primary;
76
- for (const older of previous) {
77
- const decoded = unmix(mixed.slice(), outerTag, older);
78
- if (decoded && !(decoded instanceof Error)) return decoded;
79
- }
80
- return primary ?? new UuidSlugError("invalid_uuid_slug", "Masked UUID slug failed schema validation.");
81
- }
82
- /** Append distinct UUIDs directly to the result, before another callback can mutate their bytes. */
83
- function decodeMaskedCandidates(mixed, outerTag, schemas, firstOnly = false, candidates = []) {
84
- for (const schema of schemas) {
85
- const decoded = unmix(mixed.slice(), outerTag, schema);
86
- if (decoded instanceof Error) return decoded;
87
- if (decoded) {
88
- const uuid = formatUuid(decoded);
89
- if (uuid instanceof Error) return uuid;
90
- if (!candidates.includes(uuid)) candidates.push(uuid);
91
- if (firstOnly) break;
92
- }
93
- }
94
- return candidates;
95
- }
96
- function unmix(mixed, outerTag, schema) {
97
- const unmixed = /* @__PURE__ */ new Uint8Array(16);
98
- const failed = applyMix(schema, mixed, unmixed, false);
99
- if (failed) return failed;
100
- const foundTag = extractTag(unmixed) << OUTER_TAG_BITS | outerTag;
101
- restoreV7(unmixed);
102
- if (tagFor(unmixed, TAG_BITS) !== foundTag) return void 0;
103
- return unmixed;
104
- }
105
- //#endregion
106
- export { decodeMaskedCandidates, decodeMaskedSlug, uuidV7BytesToMaskedSlug };