@neko-makura/railid 1.1.1 → 2.0.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 CHANGED
@@ -60,6 +60,26 @@ const decoded = railid.decode(id);
60
60
  console.log(decoded.timestampMs, decoded.randomHex, decoded.encoded);
61
61
  ```
62
62
 
63
+ ## TPM-less deployments
64
+
65
+ The default entry point keeps the fail-closed TPM hybrid profile: `generate()`
66
+ throws `TpmUnavailable` when the backend or the device is missing. Hosts that
67
+ never have a TPM (for example a Raspberry Pi 4) should import the explicit
68
+ TPM-less entry point:
69
+
70
+ ```js
71
+ const railid = require('@neko-makura/railid/no-tpm');
72
+
73
+ railid.backend(); // "os-only"
74
+ const id = railid.generate();
75
+ const ids = railid.generateMany(1000);
76
+ ```
77
+
78
+ It exposes the same functions and output format, but every generator uses the
79
+ explicitly degraded OS-only profile and `generateMany(count)` takes no profile
80
+ argument. The choice is visible at the import site, and the default entry point
81
+ still never falls back implicitly.
82
+
63
83
  ## API
64
84
 
65
85
  | Function | Result | Notes |
@@ -76,6 +96,9 @@ console.log(decoded.timestampMs, decoded.randomHex, decoded.encoded);
76
96
  | `version()` | `string` | RailID crate version |
77
97
  | `backend()` | `"tpm" \| "os-only"` | Backend compiled into the loaded binary |
78
98
 
99
+ v2 adds `generateV2`, `generateV2Buffer`, `decodeV2`, and `formatV2`; see
100
+ [RailID v2](#railid-v2) below.
101
+
79
102
  Limits:
80
103
 
81
104
  - OS-only strings: 100,000 IDs
@@ -88,6 +111,53 @@ Counts above the limit are rejected before allocation.
88
111
  call; for throughput use `generateManyEncoded()` or
89
112
  `generateManyEncodedAsync()`, which allocate one contiguous buffer.
90
113
 
114
+ ## RailID v2
115
+
116
+ v2 is a separate format generation for variable-length values with an optional
117
+ timestamp. The v1 functions above are unchanged.
118
+
119
+ ```js
120
+ const railid = require('@neko-makura/railid');
121
+
122
+ // Preset: 192 bits, 44-bit 100 ms timestamp.
123
+ const id = railid.generateV2({ bits: 192 });
124
+ const info = railid.decodeV2(id, { bits: 192 });
125
+ // { encoded, bits, timestampBits, randomBits, ticks, timestampMs, timestampUs, randomHex }
126
+
127
+ // No timestamp (a custom format needs force).
128
+ const raw = railid.generateV2({ bits: 128, time: null, force: true });
129
+
130
+ // Decoupled tick and width.
131
+ const custom = railid.formatV2({
132
+ bits: 192,
133
+ time: { tick: '1ms', bits: 42 },
134
+ force: true,
135
+ });
136
+ // custom.warnings: NON_DEFAULT_TIME, DECOUPLED_TIME, SHORT_RANGE
137
+ ```
138
+
139
+ | Preset | Bits | Timestamp | Random | Characters |
140
+ |---|---:|---|---:|---:|
141
+ | `B32` | 32 | none | 32 | 6 |
142
+ | `B64` | 64 | none | 64 | 11 |
143
+ | `B126` | 126 | none | 126 | 21 |
144
+ | `B192` (default) | 192 | 100 ms / 44 bit | 148 | 32 |
145
+ | `B256` | 256 | 10 ms / 48 bit | 208 | 43 |
146
+ | `B512` | 512 | 1 ms / 52 bit | 460 | 86 |
147
+
148
+ - `time` omitted selects the default for `bits`; `time: null` disables the
149
+ timestamp; a profile name such as `'1s'` selects the conventional pair. An
150
+ object `time` requires both `tick` and `bits`.
151
+ - `force: true` allows non-preset lengths, timestamps on short lengths, no
152
+ timestamp on long lengths, and decoupled tick/width pairs.
153
+ `generateV2`/`generateV2Buffer` emit the warnings on every call through
154
+ `process.emitWarning`; `formatV2` returns them in `warnings`.
155
+ - The v2 epoch is `2020-01-01T00:00:00Z`. Timestamps are returned as decimal
156
+ strings to preserve 64-bit ticks and 128-bit microsecond values.
157
+ - v2 is not wire-compatible with v1. See `docs/SPEC-v2.md` in the repository.
158
+ - The `no-tpm` entry point exposes `generateV2` and `generateV2Buffer` with the
159
+ OS-only profile.
160
+
91
161
  ## Caller-provided buffer API (design, not shipped)
92
162
 
93
163
  A zero-allocation single-ID API would look like:
@@ -166,7 +236,8 @@ docker run --rm -v "$PWD:/src" -w /src/node rust:1.88-alpine \
166
236
  ## Benchmarks
167
237
 
168
238
  The Node addon benchmark against UUIDv4 and NanoID is in
169
- [`bench/`](bench/README.md). It includes the latest Windows result.
239
+ [`bench/`](bench/README.md). It includes the latest Windows and Raspberry Pi 4
240
+ results.
170
241
 
171
242
  ## Security notes
172
243
 
package/index.d.ts CHANGED
@@ -44,3 +44,58 @@ export declare function version(): string;
44
44
 
45
45
  /** Native backend compiled into the loaded addon. */
46
46
  export declare function backend(): Backend;
47
+
48
+ export type V2Tick = "1d" | "1h" | "1s" | "100ms" | "10ms" | "1ms" | "0.1ms";
49
+
50
+ /** A timestamp tick and field width. */
51
+ export interface V2TimeSpec {
52
+ tick: V2Tick;
53
+ bits: number;
54
+ }
55
+
56
+ /** A v2 format description. `time` omitted means the default for `bits`. */
57
+ export interface V2Format {
58
+ bits: number;
59
+ time?: V2Tick | V2TimeSpec | null;
60
+ force?: boolean;
61
+ }
62
+
63
+ /** A non-fatal v2 format warning. */
64
+ export interface V2Warning {
65
+ code: string;
66
+ reason: string;
67
+ }
68
+
69
+ /** A normalized v2 format. */
70
+ export interface V2FormatInfo {
71
+ totalBits: number;
72
+ timestampBits: number;
73
+ randomBits: number;
74
+ tick: V2Tick | null;
75
+ encodedLen: number;
76
+ warnings: V2Warning[];
77
+ }
78
+
79
+ /** Decoded v2 fields. Timestamps are decimal strings for full precision. */
80
+ export interface V2Decoded {
81
+ encoded: string;
82
+ bits: number;
83
+ timestampBits: number;
84
+ randomBits: number;
85
+ ticks: string | null;
86
+ timestampMs: string | null;
87
+ timestampUs: string | null;
88
+ randomHex: string;
89
+ }
90
+
91
+ /** Generate one v2 value. */
92
+ export declare function generateV2(format: V2Format): string;
93
+
94
+ /** Generate one v2 value as 3-171 ASCII bytes. */
95
+ export declare function generateV2Buffer(format: V2Format): Buffer;
96
+
97
+ /** Decode a v2 value with the expected format. */
98
+ export declare function decodeV2(input: string, format: V2Format): V2Decoded;
99
+
100
+ /** Normalize and validate a v2 format. */
101
+ export declare function formatV2(format: V2Format): V2FormatInfo;
package/index.js CHANGED
@@ -65,9 +65,28 @@ if (!binding) {
65
65
  throw error;
66
66
  }
67
67
 
68
+ const v2 = require('./v2.js')(binding);
69
+ const publicBinding = { ...binding };
70
+
71
+ // The OS-only preset entry points are selected by the v2 wrapper, and the
72
+ // packed preset helpers are binding implementation details. Neither is part of
73
+ // the public surface.
74
+ for (const key of Object.keys(publicBinding)) {
75
+ if (
76
+ key.startsWith('v2InternalPreset') ||
77
+ key === 'v2GeneratePreset' ||
78
+ key === 'v2GeneratePresetBuffer' ||
79
+ key === 'v2GeneratePacked' ||
80
+ key === 'v2GenerateBufferPacked'
81
+ ) {
82
+ delete publicBinding[key];
83
+ }
84
+ }
85
+
68
86
  module.exports = {
69
- ...binding,
87
+ ...publicBinding,
70
88
  // `backend` is the backend compiled into the loaded binary. A TPM build can
71
89
  // still return TpmUnavailable at runtime when no TPM device is present.
72
90
  backend: () => backend,
91
+ ...v2,
73
92
  };
package/no-tpm.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { DecodedRailId } from "./index";
2
+
3
+ export type { DecodedRailId };
4
+ export type Backend = "os-only";
5
+
6
+ /** Generate one RailID with the explicitly degraded OS-only profile. */
7
+ export declare function generate(): string;
8
+
9
+ /** Same as `generate()`; kept for symmetry with the default entry point. */
10
+ export declare function generateOsOnly(): string;
11
+
12
+ /** Generate one OS-only RailID as 32 ASCII bytes, without a JS string. */
13
+ export declare function generateBuffer(): Buffer;
14
+
15
+ /** Same as `generateBuffer()`; kept for symmetry. */
16
+ export declare function generateOsOnlyBuffer(): Buffer;
17
+
18
+ /** Generate `count` IDs synchronously as strings. */
19
+ export declare function generateMany(count: number): string[];
20
+
21
+ /** Generate `count` IDs synchronously as one contiguous `count * 32` Buffer. */
22
+ export declare function generateManyEncoded(count: number): Buffer;
23
+
24
+ /** Generate `count` IDs asynchronously as strings. */
25
+ export declare function generateManyAsync(count: number): Promise<string[]>;
26
+
27
+ /** Generate `count` IDs asynchronously as one contiguous `count * 32` Buffer. */
28
+ export declare function generateManyEncodedAsync(count: number): Promise<Buffer>;
29
+
30
+ /** Decode and validate a RailID. */
31
+ export declare function decode(input: string): DecodedRailId;
32
+
33
+ /** RailID crate version. */
34
+ export declare function version(): string;
35
+
36
+ /** Always `"os-only"` for this entry point. */
37
+ export declare function backend(): Backend;
38
+
39
+ import type { V2Decoded, V2Format, V2FormatInfo } from "./index";
40
+
41
+ export type { V2Decoded, V2Format, V2FormatInfo };
42
+
43
+ /** Generate one OS-only v2 value. */
44
+ export declare function generateV2(format: V2Format): string;
45
+
46
+ /** Generate one OS-only v2 value as 32-171 ASCII bytes. */
47
+ export declare function generateV2Buffer(format: V2Format): Buffer;
48
+
49
+ /** Decode a v2 value with the expected format. */
50
+ export declare function decodeV2(input: string, format: V2Format): V2Decoded;
51
+
52
+ /** Normalize and validate a v2 format. */
53
+ export declare function formatV2(format: V2Format): V2FormatInfo;
package/no-tpm.js ADDED
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ // TPM-less entry point.
4
+ //
5
+ // The default entry point keeps the fail-closed TPM hybrid profile: `generate()`
6
+ // throws when no TPM is available. This module is the explicit opt-in for hosts
7
+ // that never have a TPM. Every generator here uses the degraded OS-only
8
+ // profile, and the choice is visible at the import site.
9
+ const core = require('./index.js');
10
+
11
+ module.exports = {
12
+ ...core,
13
+ generate: core.generateOsOnly,
14
+ generateBuffer: core.generateOsOnlyBuffer,
15
+ // The `osOnly` argument is accepted for signature compatibility and always
16
+ // resolves to the OS-only profile.
17
+ generateMany: (count) => core.generateMany(count, true),
18
+ generateManyEncoded: (count) => core.generateManyEncoded(count, true),
19
+ generateManyAsync: (count) => core.generateManyAsync(count, true),
20
+ generateManyEncodedAsync: (count) => core.generateManyEncodedAsync(count, true),
21
+ // v2 generation uses the OS-only profile; decoding is profile-independent.
22
+ generateV2: (format) => core.generateV2(format, 'os-only'),
23
+ generateV2Buffer: (format) => core.generateV2Buffer(format, 'os-only'),
24
+ // The loaded binary may still contain the TPM backend, but this module never
25
+ // calls it.
26
+ backend: () => 'os-only',
27
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@neko-makura/railid",
3
- "version": "1.1.1",
4
- "description": "Native N-API bindings for RailID: 192-bit timestamp-first identifiers with TPM 2.0 + OS CSPRNG randomness",
3
+ "version": "2.0.0",
4
+ "description": "Native N-API bindings for RailID: 192-bit v1 and variable-length v2 timestamp-first identifiers with TPM 2.0 + OS CSPRNG randomness",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "license": "MIT",
@@ -28,6 +28,9 @@
28
28
  "files": [
29
29
  "index.js",
30
30
  "index.d.ts",
31
+ "no-tpm.js",
32
+ "no-tpm.d.ts",
33
+ "v2.js",
31
34
  "*.node",
32
35
  "README.md",
33
36
  "LICENSE"
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/v2.js ADDED
@@ -0,0 +1,193 @@
1
+ 'use strict';
2
+
3
+ const TICKS = ['1d', '1h', '1s', '100ms', '10ms', '1ms', '0.1ms'];
4
+
5
+ function tickIndex(name) {
6
+ const index = TICKS.indexOf(name);
7
+ if (index < 0) {
8
+ throw new TypeError(
9
+ `unknown tick: ${String(name)} (expected ${TICKS.join(', ')})`
10
+ );
11
+ }
12
+ return index;
13
+ }
14
+
15
+ function toNativeArguments(format) {
16
+ if (format === null || typeof format !== 'object') {
17
+ throw new TypeError('format must be an object');
18
+ }
19
+ const bits = format.bits;
20
+ if (!Number.isInteger(bits) || bits < 16 || bits > 1024) {
21
+ throw new TypeError('format.bits must be an integer between 16 and 1024');
22
+ }
23
+ const force = Boolean(format.force);
24
+ const time = format.time;
25
+
26
+ if (time === undefined) {
27
+ return [bits, 0, undefined, undefined, force];
28
+ }
29
+ if (time === null) {
30
+ return [bits, 1, undefined, undefined, force];
31
+ }
32
+ if (typeof time === 'string') {
33
+ return [bits, 2, tickIndex(time), undefined, force];
34
+ }
35
+ if (typeof time === 'object') {
36
+ if (time.tick === undefined) {
37
+ throw new TypeError('format.time.tick is required');
38
+ }
39
+ if (time.bits === undefined) {
40
+ throw new TypeError(
41
+ 'format.time.bits is required for an object time; use a tick string for the conventional width'
42
+ );
43
+ }
44
+ if (!Number.isInteger(time.bits)) {
45
+ throw new TypeError('format.time.bits must be an integer');
46
+ }
47
+ return [bits, 2, tickIndex(time.tick), time.bits, force];
48
+ }
49
+ throw new TypeError('format.time must be a tick name, an object, null, or undefined');
50
+ }
51
+
52
+ function formatKey(args) {
53
+ return (
54
+ args[0] |
55
+ (args[1] << 11) |
56
+ ((args[2] ?? 7) << 13) |
57
+ ((args[3] ?? 127) << 16) |
58
+ (args[4] ? 1 << 23 : 0)
59
+ );
60
+ }
61
+
62
+ function prepareWarnings(warnings) {
63
+ return warnings.map((warning) => ({
64
+ reason: warning.reason,
65
+ options: Object.freeze({ code: `RAILID_V2_${warning.code}` }),
66
+ }));
67
+ }
68
+
69
+ function emitWarnings(commands) {
70
+ for (const command of commands) {
71
+ process.emitWarning(command.reason, command.options);
72
+ }
73
+ }
74
+
75
+ module.exports = function createV2(binding) {
76
+ const infoCache = new Map();
77
+ const MAX_CACHE_ENTRIES = 256;
78
+
79
+ function presetIndex(format) {
80
+ if (
81
+ format === null ||
82
+ typeof format !== 'object' ||
83
+ format.force ||
84
+ format.time !== undefined
85
+ ) {
86
+ return -1;
87
+ }
88
+ switch (format.bits) {
89
+ case 32:
90
+ return 0;
91
+ case 64:
92
+ return 1;
93
+ case 126:
94
+ return 2;
95
+ case 192:
96
+ return 3;
97
+ case 256:
98
+ return 4;
99
+ case 512:
100
+ return 5;
101
+ default:
102
+ return -1;
103
+ }
104
+ }
105
+
106
+ function normalizeInfo(info) {
107
+ return {
108
+ ...info,
109
+ tick: info.tick ?? null,
110
+ warnings: info.warnings ?? [],
111
+ };
112
+ }
113
+
114
+ function normalizeDecoded(decoded) {
115
+ return {
116
+ ...decoded,
117
+ ticks: decoded.ticks ?? null,
118
+ timestampMs: decoded.timestampMs ?? null,
119
+ timestampUs: decoded.timestampUs ?? null,
120
+ };
121
+ }
122
+
123
+ // Format construction is deterministic for a given argument tuple. Cache the
124
+ // normalized descriptor so `generateV2` does not rebuild it (and allocate a
125
+ // N-API object) for every ID. The cache key is a packed integer, not a
126
+ // joined string, so the hot path does not allocate.
127
+ function cachedInfo(args) {
128
+ const key = formatKey(args);
129
+ let entry = infoCache.get(key);
130
+ if (entry === undefined) {
131
+ if (infoCache.size >= MAX_CACHE_ENTRIES) {
132
+ infoCache.clear();
133
+ }
134
+ const info = normalizeInfo(binding.v2Format(...args));
135
+ entry = { key, info, commands: prepareWarnings(info.warnings) };
136
+ infoCache.set(key, entry);
137
+ }
138
+ return entry;
139
+ }
140
+
141
+ function formatV2(format) {
142
+ const { info } = cachedInfo(toNativeArguments(format));
143
+ return { ...info, warnings: info.warnings.map((warning) => ({ ...warning })) };
144
+ }
145
+
146
+ // The OS-only profile is the throughput-critical path. Each preset has a
147
+ // dedicated zero-argument N-API entry point so V8 does not pay the argument
148
+ // marshalling cost on every ID.
149
+ const OS_PRESETS = [
150
+ binding.v2InternalPresetB32Os,
151
+ binding.v2InternalPresetB64Os,
152
+ binding.v2InternalPresetB126Os,
153
+ binding.v2InternalPresetB192Os,
154
+ binding.v2InternalPresetB256Os,
155
+ binding.v2InternalPresetB512Os,
156
+ ];
157
+
158
+ function presetArgument(preset, profile) {
159
+ return preset | (profile === 'os-only' ? 0x100 : 0);
160
+ }
161
+
162
+ function generateV2(format, profile) {
163
+ const preset = presetIndex(format);
164
+ if (preset >= 0) {
165
+ if (profile === 'os-only') {
166
+ return OS_PRESETS[preset]();
167
+ }
168
+ return binding.v2GeneratePreset(presetArgument(preset, profile));
169
+ }
170
+ const entry = cachedInfo(toNativeArguments(format));
171
+ emitWarnings(entry.commands);
172
+ return binding.v2GeneratePacked(entry.key | (profile === 'os-only' ? 1 << 24 : 0));
173
+ }
174
+
175
+ function generateV2Buffer(format, profile) {
176
+ const preset = presetIndex(format);
177
+ if (preset >= 0) {
178
+ return binding.v2GeneratePresetBuffer(presetArgument(preset, profile));
179
+ }
180
+ const entry = cachedInfo(toNativeArguments(format));
181
+ emitWarnings(entry.commands);
182
+ return binding.v2GenerateBufferPacked(entry.key | (profile === 'os-only' ? 1 << 24 : 0));
183
+ }
184
+
185
+ function decodeV2(input, format) {
186
+ if (typeof input !== 'string') {
187
+ throw new TypeError('input must be a string');
188
+ }
189
+ return normalizeDecoded(binding.v2Decode(input, ...toNativeArguments(format)));
190
+ }
191
+
192
+ return { generateV2, generateV2Buffer, decodeV2, formatV2 };
193
+ };