@anizoptera/uuid-slug 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +381 -27
- package/dist/alphabet.d.ts +21 -0
- package/dist/alphabet.d.ts.map +1 -0
- package/dist/alphabet.js +132 -0
- package/dist/alphabet.js.map +1 -0
- package/dist/base64url.d.ts +20 -0
- package/dist/base64url.d.ts.map +1 -0
- package/dist/base64url.js +33 -0
- package/dist/base64url.js.map +1 -0
- package/dist/codec.d.ts +17 -0
- package/dist/codec.d.ts.map +1 -0
- package/dist/codec.js +192 -0
- package/dist/codec.js.map +1 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -0
- package/dist/feistel.js +105 -0
- package/dist/feistel.js.map +1 -0
- package/dist/index.d.ts +11 -168
- package/dist/index.js +10 -649
- package/dist/keyless.d.ts +31 -0
- package/dist/keyless.d.ts.map +1 -0
- package/dist/keyless.js +93 -0
- package/dist/keyless.js.map +1 -0
- package/dist/legacy-mask.js +55 -0
- package/dist/legacy-mask.js.map +1 -0
- package/dist/mask.js +108 -0
- package/dist/mask.js.map +1 -0
- package/dist/migration.js +66 -0
- package/dist/migration.js.map +1 -0
- package/dist/node/alphabet.js +130 -0
- package/dist/node/base64url.js +31 -0
- package/dist/node/codec.js +190 -0
- package/dist/node/errors.js +78 -0
- package/dist/node/feistel.js +103 -0
- package/dist/node/index.js +10 -647
- package/dist/node/keyless.js +91 -0
- package/dist/node/legacy-mask.js +53 -0
- package/dist/node/mask.js +106 -0
- package/dist/node/migration.js +64 -0
- package/dist/node/runtime/node.js +33 -0
- package/dist/node/runtime/pool.js +53 -0
- package/dist/node/schema.js +214 -0
- package/dist/node/siphash.js +106 -0
- package/dist/node/uuid.js +226 -0
- package/dist/node/v7.js +185 -0
- package/dist/node/yield.js +20 -0
- package/dist/runtime/pool.js +55 -0
- package/dist/runtime/pool.js.map +1 -0
- package/dist/runtime/web.js +39 -0
- package/dist/runtime/web.js.map +1 -0
- package/dist/schema.d.ts +20 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +216 -0
- package/dist/schema.js.map +1 -0
- package/dist/siphash.js +108 -0
- package/dist/siphash.js.map +1 -0
- package/dist/types.d.ts +255 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/uuid.d.ts +78 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +228 -0
- package/dist/uuid.js.map +1 -0
- package/dist/v7.d.ts +12 -0
- package/dist/v7.d.ts.map +1 -0
- package/dist/v7.js +187 -0
- package/dist/v7.js.map +1 -0
- package/dist/yield.js +22 -0
- package/dist/yield.js.map +1 -0
- package/package.json +8 -12
- package/src/alphabet.ts +187 -0
- package/src/base64url.ts +28 -63
- package/src/codec.ts +227 -125
- package/src/errors.ts +83 -9
- package/src/feistel.ts +128 -0
- package/src/index.ts +52 -26
- package/src/keyless.ts +136 -0
- package/src/legacy-mask.ts +25 -0
- package/src/mask.ts +129 -67
- package/src/migration.ts +104 -0
- package/src/runtime/bun.ts +49 -24
- package/src/runtime/node.ts +33 -15
- package/src/runtime/pool.ts +62 -0
- package/src/runtime/types.ts +42 -5
- package/src/runtime/web.ts +37 -9
- package/src/schema.ts +274 -97
- package/src/siphash.ts +127 -0
- package/src/types.ts +221 -37
- package/src/uuid.ts +189 -50
- package/src/v7.ts +217 -45
- package/src/yield.ts +22 -0
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/web/index.js +0 -648
|
@@ -0,0 +1,190 @@
|
|
|
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 };
|
|
@@ -0,0 +1,78 @@
|
|
|
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 };
|
|
@@ -0,0 +1,103 @@
|
|
|
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 };
|