@neko-makura/railid 4.3.2 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,372 +1,382 @@
1
- # @neko-makura/railid (Node.js)
2
-
3
- Native N-API bindings for [RailID](https://crates.io/crates/railid).
4
-
5
- > Maintenance status: this binding remains supported, but Rust is the primary
6
- > optimization target. For throughput, prefer the batch APIs over per-ID calls.
7
-
8
- ```bash
9
- npm install @neko-makura/railid
10
- ```
11
-
12
- The package includes prebuilt N-API binaries. Node.js 18 or newer is required.
13
-
14
- ## Platforms
15
-
16
- | Platform | Architecture | libc | Backend |
17
- |---|---|---|---|
18
- | Linux | x64 | glibc | TPM (`libtss2`) + OS-only fallback |
19
- | Linux | x64 | musl | OS-only |
20
- | Linux | arm64 | glibc | OS-only |
21
- | Linux | arm64 | musl | OS-only |
22
- | Linux | armv7 | glibc (hard-float) | OS-only |
23
- | Linux | riscv64 | glibc | OS-only |
24
- | Windows | x64 | MSVC | TPM (TBS) |
25
- | Windows | arm64 | MSVC | TPM (TBS) |
26
- | macOS | x64 | — | OS-only |
27
- | macOS | arm64 | — | OS-only |
28
-
29
- `index.js` selects the addon from `process.platform`, `process.arch` and, on
30
- Linux, whether the Node process runs on glibc or musl.
31
-
32
- The riscv64 addon targets the `riscv64gc` glibc ABI used by distribution Node
33
- builds (for example Ubuntu 24.04). Node.js does not publish official riscv64
34
- binaries; use a distribution package.
35
-
36
-
37
- ## Usage
38
-
39
- ```js
40
- const railid = require('@neko-makura/railid');
41
-
42
- console.log(railid.version());
43
- console.log(railid.backend()); // "tpm" or "os-only"
44
-
45
- // Standard TPM hybrid profile. Throws if the backend is OS-only or no TPM
46
- // device is available.
47
- const id = railid.generate();
48
- console.log(id);
49
-
50
- // Explicitly degraded OS-only profile.
51
- const osId = railid.generateOsOnly();
52
-
53
- // Synchronous batch.
54
- const ids = railid.generateMany(1000, true);
55
- const batch = railid.generateManyEncoded(1000, true);
56
- // batch is a Buffer of 1000 * 32 ASCII bytes.
57
-
58
- // Asynchronous batch: runs on the libuv thread pool.
59
- const asyncIds = await railid.generateManyAsync(1000, true);
60
- const asyncBatch = await railid.generateManyEncodedAsync(1000, true);
61
-
62
- const decoded = railid.decode(id);
63
- console.log(decoded.timestampMs, decoded.randomHex, decoded.encoded);
64
- ```
65
-
66
- ## TPM-less deployments
67
-
68
- The default entry point keeps the fail-closed TPM hybrid profile: `generate()`
69
- throws `TpmUnavailable` when the backend or the device is missing. Hosts that
70
- never have a TPM (for example a Raspberry Pi 4) should import the explicit
71
- TPM-less entry point:
72
-
73
- ```js
74
- const railid = require('@neko-makura/railid/no-tpm');
75
-
76
- railid.backend(); // "os-only"
77
- const id = railid.generate();
78
- const ids = railid.generateMany(1000);
79
- ```
80
-
81
- It exposes the same functions and output format, but every generator uses the
82
- explicitly degraded OS-only profile and `generateMany(count)` takes no profile
83
- argument. The choice is visible at the import site, and the default entry point
84
- still never falls back implicitly.
85
-
86
- ## API
87
-
88
- | Function | Result | Notes |
89
- |---|---|---|
90
- | `generate()` | `string` | TPM hybrid profile; throws `TpmUnavailable` if unavailable |
91
- | `generateOsOnly()` | `string` | Explicit degraded profile |
92
- | `generateBuffer()` | `Buffer` | TPM profile as 32 ASCII bytes, no JS string |
93
- | `generateOsOnlyBuffer()` | `Buffer` | OS-only as 32 ASCII bytes, no JS string |
94
- | `generateV4()` | `string` | 126-bit v4; TPM hybrid profile, fails closed |
95
- | `generateV4OsOnly()` | `string` | 126-bit v4; explicit degraded OS-only profile |
96
- | `generateV4Buffer()` | `Buffer` | 126-bit v4; TPM profile as 21 ASCII bytes |
97
- | `generateV4BufferOsOnly()` | `Buffer` | 126-bit v4; OS-only as 21 ASCII bytes |
98
- | `generateV4ManyEncoded(count)` | `Buffer` | 126-bit v4; TPM profile; `count * 21` bytes |
99
- | `generateV4ManyEncodedOsOnly(count)` | `Buffer` | 126-bit v4; OS-only; `count * 21` bytes |
100
- | `generateV4ManyEncodedAsync(count)` | `Promise<Buffer>` | 126-bit v4; TPM profile; off the JS thread |
101
- | `generateV4ManyEncodedOsOnlyAsync(count)` | `Promise<Buffer>` | 126-bit v4; OS-only; off the JS thread |
102
- | `generateV4ManyEncodedInto(buffer)` | `void` | 126-bit v4; TPM profile; writes `buffer` (multiple of 21) |
103
- | `generateV4ManyEncodedOsOnlyInto(buffer)` | `void` | 126-bit v4; OS-only; writes `buffer` |
104
- | `generateMany(count, osOnly?)` | `string[]` | Sync; `osOnly` defaults to `false` |
105
- | `generateManyEncoded(count, osOnly?)` | `Buffer` | Sync; `count * 32` bytes |
106
- | `generateManyAsync(count, osOnly?)` | `Promise<string[]>` | Bulk work off the JS thread |
107
- | `generateManyEncodedAsync(count, osOnly?)` | `Promise<Buffer>` | Bulk work off the JS thread |
108
- | `decode(input)` | `{ timestampMs, randomHex, encoded }` | Validates canonical Base64URL |
109
- | `version()` | `string` | RailID crate version |
110
- | `backend()` | `"tpm" \| "os-only"` | Backend compiled into the loaded binary |
111
-
112
- v2 adds `generateV2`, `generateV2Buffer`, `generateV2Many`,
113
- `generateV2ManyEncoded`, `decodeV2`, and `formatV2`; see
114
- [RailID v2](#railid-v2) below.
115
-
116
- Limits:
117
-
118
- - OS-only strings: 100,000 IDs
119
- - OS-only encoded: 1,000,000 IDs
120
- - TPM: 1,024 IDs
121
-
122
- Counts above the limit are rejected before allocation. Every batch `count`
123
- must be a safe integer in `0..4294967295`; fractional, negative, `NaN`,
124
- `Infinity`, and out-of-range values throw instead of wrapping. v2 batches use
125
- the same caps (1,024 TPM / 1,000,000 OS-only), as do the v4 async batches. The
126
- v4 `*Into` functions derive their count from the buffer length, require an
127
- exact multiple of 21, and apply the same caps before writing.
128
-
129
- ## Errors
130
-
131
- Native N-API failures are mapped once at the JavaScript boundary to a stable
132
- `error.code`, so callers do not need to parse messages:
133
-
134
- | `error.code` | Meaning |
135
- |---|---|
136
- | `TpmUnavailable` | The fail-closed TPM hybrid profile has no usable TPM |
137
- | `TpmRandomFailure` | The TPM was reached but returned no random bytes |
138
- | `OsRandomFailure` | The operating system CSPRNG failed |
139
- | `TimestampOutOfRange` | A timestamp does not fit the requested field |
140
- | `InvalidInput` | Invalid count, format, length, or encoding |
141
- | `CapacityOverflow` | A batch cannot be represented in memory |
142
- | `WorkerFailure` | A libuv worker thread panicked during an async batch |
143
-
144
- `generate()` / `generateV4()` and the TPM batch APIs throw `TpmUnavailable`
145
- rather than falling back to OS randomness. The `no-tpm` entry point intentionally
146
- uses the OS-only profile, so it does not produce that error.
147
-
148
-
149
- `generateBuffer()` avoids the JS string but still allocates a Node Buffer per
150
- call; for throughput use `generateManyEncoded()` or
151
- `generateManyEncodedAsync()`, which allocate one contiguous buffer.
152
-
153
- ## RailID v4 (126-bit)
154
-
155
- v4 is a distinct 126-bit format that encodes to exactly 21 characters of
156
- unpadded Base64URL. It has single-value, Buffer, and contiguous batch APIs:
157
-
158
- ```js
159
- const railid = require('@neko-makura/railid');
160
-
161
- // TPM hybrid profile; throws TpmUnavailable instead of falling back.
162
- const id = railid.generateV4();
163
- console.log(id); // 21 characters
164
-
165
- // Explicit degraded OS-only profile.
166
- const osId = railid.generateV4OsOnly();
167
-
168
- // The Buffer contains the 21 encoded ASCII bytes, not the raw 16-byte value.
169
- const encoded = railid.generateV4BufferOsOnly();
170
-
171
- // One contiguous Buffer with no separators: count * 21 bytes.
172
- const batch = railid.generateV4ManyEncodedOsOnly(1000);
173
- for (let i = 0; i < 1000; i++) {
174
- const value = batch.toString('ascii', i * 21, (i + 1) * 21);
175
- }
176
-
177
- // Off the JS thread: resolves to the same contiguous Buffer.
178
- const asyncBatch = await railid.generateV4ManyEncodedOsOnlyAsync(100_000);
179
-
180
- // Caller-owned buffer: no 21 MB allocation per call. The length must be an
181
- // exact multiple of 21 and determines the count.
182
- const target = Buffer.allocUnsafe(100_000 * 21);
183
- railid.generateV4ManyEncodedOsOnlyInto(target);
184
- ```
185
-
186
- - `generateV4()` and `generateV4ManyEncoded()` use the TPM hybrid profile,
187
- which is fail-closed: if no TPM or TSS transport is available they throw
188
- `TpmUnavailable` and never silently use the OS CSPRNG.
189
- - `generateV4OsOnly()`, `generateV4BufferOsOnly()`,
190
- `generateV4ManyEncodedOsOnly()`, and the corresponding `*Async`/`*Into`
191
- functions are the explicit OS-only opt-ins. The `no-tpm` entry point maps
192
- the unsuffixed `generateV4`, `generateV4Buffer`, `generateV4ManyEncoded`,
193
- `generateV4ManyEncodedAsync`, and `generateV4ManyEncodedInto` to them.
194
- - A v4 batch samples the UTC day once, so every ID in one call carries the
195
- same day. `count == 0` returns an empty Buffer (or writes nothing).
196
- - v4 batch limits match v1: 1,024 IDs for the TPM profile and 1,000,000 IDs
197
- for OS-only. Counts above the limit are rejected before allocation and
198
- before a TPM is touched.
199
- - `generateV4ManyEncodedAsync()` and `generateV4ManyEncodedOsOnlyAsync()` run
200
- the same batch on a libuv worker thread and resolve to one Buffer. Worker
201
- panics are converted to an error instead of unwinding across FFI.
202
- - `generateV4ManyEncodedInto(buffer)` and
203
- `generateV4ManyEncodedOsOnlyInto(buffer)` write into a Buffer the caller
204
- owns. The length must be an exact multiple of 21; it is validated before
205
- writing, so a misaligned or over-limit buffer is never partially filled.
206
- These functions are the recommended high-throughput path: a 1,000,000-ID
207
- batch avoids a 21 MB external allocation and the associated GC churn.
208
- - Batch Buffers returned by the allocating APIs are registered with V8's
209
- external-memory accounting, so repeated batches trigger GC instead of
210
- growing RSS silently. `*Into` avoids that accounting entirely because the
211
- caller owns the storage.
212
- - Errors from v4 APIs carry the stable `code` values documented under
213
- [Errors](#errors), including `TpmUnavailable` and `InvalidInput`.
214
- - The v1 192-bit API above is unchanged: `generate()` and `generateOsOnly()`
215
- still return 32-character v1 IDs. v4 does **not** reuse those names.
216
-
217
- ## RailID v2
218
-
219
- v2 is a separate format generation for variable-length values with an optional
220
- timestamp. The v1 functions above are unchanged.
221
-
222
- ```js
223
- const railid = require('@neko-makura/railid');
224
-
225
- // Preset: 192 bits, 44-bit 100 ms timestamp.
226
- const id = railid.generateV2({ bits: 192 });
227
- const info = railid.decodeV2(id, { bits: 192 });
228
- // { encoded, bits, timestampBits, randomBits, ticks, timestampMs, timestampUs, randomHex }
229
-
230
- // No timestamp (a custom format needs force).
231
- const raw = railid.generateV2({ bits: 128, time: null, force: true });
232
-
233
- // Decoupled tick and width.
234
- const custom = railid.formatV2({
235
- bits: 192,
236
- time: { tick: '1ms', bits: 42 },
237
- force: true,
238
- });
239
- // custom.warnings: NON_DEFAULT_TIME, DECOUPLED_TIME, SHORT_RANGE
240
-
241
- // Batches use one format. The buffer has count * encodedLen bytes.
242
- const ids = railid.generateV2Many({ bits: 192 }, 1000); // string[]
243
- const buffer = railid.generateV2ManyEncoded({ bits: 192 }, 1000); // 32,000 bytes
244
- ```
245
-
246
- | Preset | Bits | Timestamp | Random | Characters |
247
- |---|---:|---|---:|---:|
248
- | `B32` | 32 | none | 32 | 6 |
249
- | `B64` | 64 | none | 64 | 11 |
250
- | `B126` | 126 | none | 126 | 21 |
251
- | `B192` (default) | 192 | 100 ms / 44 bit | 148 | 32 |
252
- | `B256` | 256 | 10 ms / 48 bit | 208 | 43 |
253
- | `B512` | 512 | 1 ms / 52 bit | 460 | 86 |
254
-
255
- - `time` omitted selects the default for `bits`; `time: null` disables the
256
- timestamp; a profile name such as `'1s'` selects the conventional pair. An
257
- object `time` requires both `tick` and `bits`.
258
- - `force: true` allows non-preset lengths, timestamps on short lengths, no
259
- timestamp on long lengths, and decoupled tick/width pairs.
260
- `generateV2`/`generateV2Buffer` emit the warnings on every call through
261
- `process.emitWarning`; `formatV2` returns them in `warnings`. Batch calls
262
- emit the format warnings once per call.
263
- - The v2 epoch is `2020-01-01T00:00:00Z`. Timestamps are returned as decimal
264
- strings to preserve 64-bit ticks and 128-bit microsecond values.
265
- - `generateV2Many` and `generateV2ManyEncoded` reject counts above 1,024 (TPM)
266
- or 1,000,000 (OS-only) before allocating. Errors use the stable codes in
267
- [Errors](#errors); invalid formats and lengths report `InvalidInput`.
268
- - v2 is not wire-compatible with v1. See `docs/SPEC-v2.md` in the repository.
269
- - The `no-tpm` entry point exposes `generateV2`, `generateV2Buffer`,
270
- `generateV2Many`, and `generateV2ManyEncoded` with the OS-only profile.
271
- Batch encoded buffers use `count * formatV2(format).encodedLen` bytes.
272
-
273
- ## Caller-provided buffer APIs
274
-
275
- The shipped batch form is `generateV4ManyEncodedInto(buffer)` (and its
276
- `OsOnly` counterpart): the caller owns the storage, the buffer length must be a
277
- multiple of 21, and nothing is allocated per call. Prefer it for sustained
278
- throughput; see [RailID v4](#railid-v4-126-bit).
279
-
280
- A zero-allocation **single-ID** API with an explicit offset is still not
281
- shipped. It would look like:
282
-
283
- ```ts
284
- generateInto(target: Buffer, offset?: number): number;
285
- generateOsOnlyInto(target: Buffer, offset?: number): number;
286
- ```
287
-
288
- - `offset` defaults to 0 and must satisfy `offset + 32 <= target.length`.
289
- - The function writes 32 ASCII bytes and returns the end offset.
290
- - It performs no allocation and no JS string creation.
291
- - It is synchronous only.
292
-
293
- That single-ID form is **not shipped** because N-API buffers can be shared
294
- with other JS execution contexts, and napi-rs documents mutable `Buffer` access
295
- as an aliasing hazard. Shipping it safely needs an exclusive-ownership
296
- guarantee, a rejection of `SharedArrayBuffer`-backed buffers, or a custom
297
- writer object. Until then, use the batch APIs.
298
-
299
- ## Linux and TPM
300
-
301
- The Linux x64 glibc TPM binary links against `libtss2` (`tss-esapi`). The
302
- package ships two Linux x64 glibc binaries:
303
-
304
- - `railid-tpm.linux-x64-gnu.node` — TPM backend; needs `libtss2`
305
- - `railid.linux-x64-gnu.node` — OS-only; no TSS dependency
306
-
307
- `index.js` tries the TPM binary first and falls back to the OS-only binary when
308
- the TPM binary cannot be loaded (for example, when `libtss2` is missing). In
309
- that case `generate()` throws `TpmUnavailable`; `generateOsOnly()` still works.
310
- This preserves fail-closed behavior.
311
-
312
- Debian/Ubuntu TPM users need:
313
-
314
- ```bash
315
- sudo apt install libtss2
316
- ```
317
-
318
- Alpine, arm64, armv7 and riscv64 ship the OS-only backend only. Those
319
- platforms load `railid.<platform>-<arch>[-<libc>].node` directly, so `generate()`
320
- throws `TpmUnavailable` and `generateOsOnly()` is the supported profile.
321
-
322
- Windows uses the system TBS service (`Tbs.dll`) and needs no extra DLL. macOS
323
- ships the OS-only backend.
324
-
325
- ## Build from source
326
-
327
- Requirements:
328
-
329
- - Rust 1.88+
330
- - Linux TPM build: `pkg-config`, `libtss2-dev`
331
- - Node.js 18+
332
-
333
- ```bash
334
- npm run build # host default
335
- npm run build -- --os-only
336
- npm run build -- --target linux-arm64-musl # cross target, OS-only
337
- npm run verify # check every .node binary against its target tag
338
- npm test
339
- ```
340
-
341
- `node scripts/build.js --list` prints the supported targets. On Linux the
342
- default build produces both TPM and OS-only binaries for x64; other targets
343
- produce the OS-only binary. On Windows it produces the TPM binary. On macOS it
344
- produces both OS-only slices.
345
-
346
- Cross-compiling without a matching host is easiest in a container. The helper
347
- installs the toolchain for the requested target:
348
-
349
- ```bash
350
- docker run --rm -v "$PWD:/src" -w /src/node rust:1.88-alpine \
351
- sh scripts/build-in-docker.sh linux-arm64-musl
352
- ```
353
-
354
- ## Benchmarks
355
-
356
- The Node addon benchmark against UUIDv4 and NanoID is in
357
- [`bench/`](bench/README.md). It includes the latest Windows and Raspberry Pi 4
358
- results.
359
-
360
- ## Security notes
361
-
362
- RailID is an identifier generator. This package does not provide single-use
363
- tokens, expiry, or revocation; enforce those in your application. A RailID
364
- discloses its creation time at 100 ms precision. TPM presence does not prove
365
- the firmware or boot chain is trustworthy.
366
-
367
- TPM access is serialized inside the process. Use the async batch APIs for
368
- server workloads so the event loop is not blocked by large batches.
369
-
370
- ## License
371
-
372
- MIT. Copyright (c) 2026 Nekomakura. See [LICENSE](LICENSE).
1
+ # @neko-makura/railid (Node.js)
2
+
3
+ Native N-API bindings for [RailID](https://crates.io/crates/railid).
4
+
5
+ > Maintenance status: this binding remains supported, but Rust is the primary
6
+ > optimization target. For throughput, prefer the batch APIs over per-ID calls.
7
+
8
+ ```bash
9
+ npm install @neko-makura/railid
10
+ ```
11
+
12
+ The package includes prebuilt N-API binaries. Node.js 18 or newer is required.
13
+
14
+ ## Platforms
15
+
16
+ | Platform | Architecture | libc | Backend |
17
+ |---|---|---|---|
18
+ | Linux | x64 | glibc | TPM (`libtss2`) + OS-only fallback |
19
+ | Linux | x64 | musl | OS-only |
20
+ | Linux | arm64 | glibc | OS-only |
21
+ | Linux | arm64 | musl | OS-only |
22
+ | Linux | armv7 | glibc (hard-float) | OS-only |
23
+ | Linux | riscv64 | glibc | OS-only |
24
+ | Windows | x64 | MSVC | TPM (TBS) |
25
+ | Windows | arm64 | MSVC | TPM (TBS) |
26
+ | macOS | x64 | — | OS-only |
27
+ | macOS | arm64 | — | OS-only |
28
+
29
+ `index.js` selects the addon from `process.platform`, `process.arch` and, on
30
+ Linux, whether the Node process runs on glibc or musl.
31
+
32
+ The riscv64 addon targets the `riscv64gc` glibc ABI used by distribution Node
33
+ builds (for example Ubuntu 24.04). Node.js does not publish official riscv64
34
+ binaries; use a distribution package.
35
+
36
+
37
+ ## Usage
38
+
39
+ ```js
40
+ const railid = require('@neko-makura/railid');
41
+
42
+ console.log(railid.version());
43
+ console.log(railid.backend()); // "tpm" or "os-only"
44
+
45
+ // Standard TPM hybrid profile. Throws if the backend is OS-only or no TPM
46
+ // device is available.
47
+ const id = railid.generate();
48
+ console.log(id);
49
+
50
+ // Explicitly degraded OS-only profile.
51
+ const osId = railid.generateOsOnly();
52
+
53
+ // Synchronous batch.
54
+ const ids = railid.generateMany(1000, true);
55
+ const batch = railid.generateManyEncoded(1000, true);
56
+ // batch is a Buffer of 1000 * 32 ASCII bytes.
57
+
58
+ // Asynchronous batch: runs on the libuv thread pool.
59
+ const asyncIds = await railid.generateManyAsync(1000, true);
60
+ const asyncBatch = await railid.generateManyEncodedAsync(1000, true);
61
+
62
+ const decoded = railid.decode(id);
63
+ console.log(decoded.timestampMs, decoded.randomHex, decoded.encoded);
64
+ ```
65
+
66
+ ## TPM-less deployments
67
+
68
+ The default entry point keeps the fail-closed TPM hybrid profile: `generate()`
69
+ throws `TpmUnavailable` when the backend or the device is missing. Hosts that
70
+ never have a TPM (for example a Raspberry Pi 4) should import the explicit
71
+ TPM-less entry point:
72
+
73
+ ```js
74
+ const railid = require('@neko-makura/railid/no-tpm');
75
+
76
+ railid.backend(); // "os-only"
77
+ const id = railid.generate();
78
+ const ids = railid.generateMany(1000);
79
+ ```
80
+
81
+ It exposes the same functions and output format, but every generator uses the
82
+ explicitly degraded OS-only profile and `generateMany(count)` takes no profile
83
+ argument. The choice is visible at the import site, and the default entry point
84
+ still never falls back implicitly.
85
+
86
+ ## API
87
+
88
+ | Function | Result | Notes |
89
+ |---|---|---|
90
+ | `generate()` | `string` | TPM hybrid profile; throws `TpmUnavailable` if unavailable |
91
+ | `generateOsOnly()` | `string` | Explicit degraded profile |
92
+ | `generateBuffer()` | `Buffer` | TPM profile as 32 ASCII bytes, no JS string |
93
+ | `generateOsOnlyBuffer()` | `Buffer` | OS-only as 32 ASCII bytes, no JS string |
94
+ | `generateV4()` | `string` | 126-bit v4; TPM hybrid profile, fails closed |
95
+ | `generateV4OsOnly()` | `string` | 126-bit v4; explicit degraded OS-only profile |
96
+ | `generateV4Buffer()` | `Buffer` | 126-bit v4; TPM profile as 21 ASCII bytes |
97
+ | `generateV4BufferOsOnly()` | `Buffer` | 126-bit v4; OS-only as 21 ASCII bytes |
98
+ | `generateV4ManyEncoded(count)` | `Buffer` | 126-bit v4; TPM profile; `count * 21` bytes |
99
+ | `generateV4ManyEncodedOsOnly(count)` | `Buffer` | 126-bit v4; OS-only; `count * 21` bytes |
100
+ | `generateV4ManyEncodedAsync(count)` | `Promise<Buffer>` | 126-bit v4; TPM profile; off the JS thread |
101
+ | `generateV4ManyEncodedOsOnlyAsync(count)` | `Promise<Buffer>` | 126-bit v4; OS-only; off the JS thread |
102
+ | `generateV4ManyEncodedInto(buffer)` | `void` | 126-bit v4; TPM profile; writes `buffer` (multiple of 21) |
103
+ | `generateV4ManyEncodedOsOnlyInto(buffer)` | `void` | 126-bit v4; OS-only; writes `buffer` |
104
+ | `generateMany(count, osOnly?)` | `string[]` | Sync; `osOnly` defaults to `false` |
105
+ | `generateManyEncoded(count, osOnly?)` | `Buffer` | Sync; `count * 32` bytes |
106
+ | `generateManyAsync(count, osOnly?)` | `Promise<string[]>` | Bulk work off the JS thread |
107
+ | `generateManyEncodedAsync(count, osOnly?)` | `Promise<Buffer>` | Bulk work off the JS thread |
108
+ | `decode(input)` | `{ timestampMs, randomHex, encoded }` | Validates canonical Base64URL |
109
+ | `version()` | `string` | RailID crate version |
110
+ | `backend()` | `"tpm" \| "os-only"` | Backend compiled into the loaded binary |
111
+
112
+ v2 adds `generateV2`, `generateV2Buffer`, `generateV2Many`,
113
+ `generateV2ManyEncoded`, `generateV2ManyAsync`, `generateV2ManyEncodedAsync`,
114
+ `decodeV2`, and `formatV2`; see [RailID v2](#railid-v2) below.
115
+
116
+ Limits:
117
+
118
+ - OS-only strings: 100,000 IDs
119
+ - OS-only encoded: 1,000,000 IDs
120
+ - TPM: 1,024 IDs
121
+
122
+ Counts above the limit are rejected before allocation. Every batch `count`
123
+ must be a safe integer in `0..4294967295`; fractional, negative, `NaN`,
124
+ `Infinity`, and out-of-range values throw instead of wrapping. v2 batches use
125
+ the same caps (1,024 TPM / 1,000,000 OS-only), as do the v4 async batches. The
126
+ v4 `*Into` functions derive their count from the buffer length, require an
127
+ exact multiple of 21, and apply the same caps before writing.
128
+
129
+ ## Errors
130
+
131
+ Native N-API failures are mapped once at the JavaScript boundary to a stable
132
+ `error.code`, so callers do not need to parse messages:
133
+
134
+ | `error.code` | Meaning |
135
+ |---|---|
136
+ | `TpmUnavailable` | The fail-closed TPM hybrid profile has no usable TPM |
137
+ | `TpmRandomFailure` | The TPM was reached but returned no random bytes |
138
+ | `OsRandomFailure` | The operating system CSPRNG failed |
139
+ | `TimestampOutOfRange` | A timestamp does not fit the requested field |
140
+ | `InvalidInput` | Invalid count, format, length, or encoding |
141
+ | `CapacityOverflow` | A batch cannot be represented in memory |
142
+ | `WorkerFailure` | A libuv worker thread panicked during an async batch |
143
+
144
+ `generate()` / `generateV4()` and the TPM batch APIs throw `TpmUnavailable`
145
+ rather than falling back to OS randomness. The `no-tpm` entry point intentionally
146
+ uses the OS-only profile, so it does not produce that error.
147
+
148
+
149
+ `generateBuffer()` avoids the JS string but still allocates a Node Buffer per
150
+ call; for throughput use `generateManyEncoded()` or
151
+ `generateManyEncodedAsync()`, which allocate one contiguous buffer.
152
+
153
+ ## RailID v4 (126-bit)
154
+
155
+ v4 is a distinct 126-bit format that encodes to exactly 21 characters of
156
+ unpadded Base64URL. It has single-value, Buffer, and contiguous batch APIs:
157
+
158
+ ```js
159
+ const railid = require('@neko-makura/railid');
160
+
161
+ // TPM hybrid profile; throws TpmUnavailable instead of falling back.
162
+ const id = railid.generateV4();
163
+ console.log(id); // 21 characters
164
+
165
+ // Explicit degraded OS-only profile.
166
+ const osId = railid.generateV4OsOnly();
167
+
168
+ // The Buffer contains the 21 encoded ASCII bytes, not the raw 16-byte value.
169
+ const encoded = railid.generateV4BufferOsOnly();
170
+
171
+ // One contiguous Buffer with no separators: count * 21 bytes.
172
+ const batch = railid.generateV4ManyEncodedOsOnly(1000);
173
+ for (let i = 0; i < 1000; i++) {
174
+ const value = batch.toString('ascii', i * 21, (i + 1) * 21);
175
+ }
176
+
177
+ // Off the JS thread: resolves to the same contiguous Buffer.
178
+ const asyncBatch = await railid.generateV4ManyEncodedOsOnlyAsync(100_000);
179
+
180
+ // Caller-owned buffer: no 21 MB allocation per call. The length must be an
181
+ // exact multiple of 21 and determines the count.
182
+ const target = Buffer.allocUnsafe(100_000 * 21);
183
+ railid.generateV4ManyEncodedOsOnlyInto(target);
184
+ ```
185
+
186
+ - `generateV4()` and `generateV4ManyEncoded()` use the TPM hybrid profile,
187
+ which is fail-closed: if no TPM or TSS transport is available they throw
188
+ `TpmUnavailable` and never silently use the OS CSPRNG.
189
+ - `generateV4OsOnly()`, `generateV4BufferOsOnly()`,
190
+ `generateV4ManyEncodedOsOnly()`, and the corresponding `*Async`/`*Into`
191
+ functions are the explicit OS-only opt-ins. The `no-tpm` entry point maps
192
+ the unsuffixed `generateV4`, `generateV4Buffer`, `generateV4ManyEncoded`,
193
+ `generateV4ManyEncodedAsync`, and `generateV4ManyEncodedInto` to them.
194
+ - A v4 batch samples the UTC day once, so every ID in one call carries the
195
+ same day. `count == 0` returns an empty Buffer (or writes nothing).
196
+ - v4 batch limits match v1: 1,024 IDs for the TPM profile and 1,000,000 IDs
197
+ for OS-only. Counts above the limit are rejected before allocation and
198
+ before a TPM is touched.
199
+ - `generateV4ManyEncodedAsync()` and `generateV4ManyEncodedOsOnlyAsync()` run
200
+ the same batch on a libuv worker thread and resolve to one Buffer. Worker
201
+ panics are converted to an error instead of unwinding across FFI.
202
+ - `generateV4ManyEncodedInto(buffer)` and
203
+ `generateV4ManyEncodedOsOnlyInto(buffer)` write into a Buffer the caller
204
+ owns. The length must be an exact multiple of 21; it is validated before
205
+ writing, so a misaligned or over-limit buffer is never partially filled.
206
+ These functions are the recommended high-throughput path: a 1,000,000-ID
207
+ batch avoids a 21 MB external allocation and the associated GC churn.
208
+ - Batch Buffers returned by the allocating APIs are registered with V8's
209
+ external-memory accounting, so repeated batches trigger GC instead of
210
+ growing RSS silently. `*Into` avoids that accounting entirely because the
211
+ caller owns the storage.
212
+ - Errors from v4 APIs carry the stable `code` values documented under
213
+ [Errors](#errors), including `TpmUnavailable` and `InvalidInput`.
214
+ - The v1 192-bit API above is unchanged: `generate()` and `generateOsOnly()`
215
+ still return 32-character v1 IDs. v4 does **not** reuse those names.
216
+
217
+ ## RailID v2
218
+
219
+ v2 is a separate format generation for variable-length values with an optional
220
+ timestamp. The v1 functions above are unchanged.
221
+
222
+ ```js
223
+ const railid = require('@neko-makura/railid');
224
+
225
+ // Preset: 192 bits, 44-bit 100 ms timestamp.
226
+ const id = railid.generateV2({ bits: 192 });
227
+ const info = railid.decodeV2(id, { bits: 192 });
228
+ // { encoded, bits, timestampBits, randomBits, ticks, timestampMs, timestampUs, randomHex }
229
+
230
+ // No timestamp (a custom format needs force).
231
+ const raw = railid.generateV2({ bits: 128, time: null, force: true });
232
+
233
+ // Decoupled tick and width.
234
+ const custom = railid.formatV2({
235
+ bits: 192,
236
+ time: { tick: '1ms', bits: 42 },
237
+ force: true,
238
+ });
239
+ // custom.warnings: NON_DEFAULT_TIME, DECOUPLED_TIME, SHORT_RANGE
240
+
241
+ // Batches use one format. The buffer has count * encodedLen bytes.
242
+ const ids = railid.generateV2Many({ bits: 192 }, 1000); // string[]
243
+ const buffer = railid.generateV2ManyEncoded({ bits: 192 }, 1000); // 32,000 bytes
244
+
245
+ // Async batches resolve with the same shapes after running off the JS thread.
246
+ const asyncIds = await railid.generateV2ManyAsync({ bits: 192 }, 1000);
247
+ const asyncBuffer = await railid.generateV2ManyEncodedAsync({ bits: 192 }, 1000);
248
+ ```
249
+
250
+ | Preset | Bits | Timestamp | Random | Characters |
251
+ |---|---:|---|---:|---:|
252
+ | `B32` | 32 | none | 32 | 6 |
253
+ | `B64` | 64 | none | 64 | 11 |
254
+ | `B126` | 126 | none | 126 | 21 |
255
+ | `B192` (default) | 192 | 100 ms / 44 bit | 148 | 32 |
256
+ | `B256` | 256 | 10 ms / 48 bit | 208 | 43 |
257
+ | `B512` | 512 | 1 ms / 52 bit | 460 | 86 |
258
+
259
+ - `time` omitted selects the default for `bits`; `time: null` disables the
260
+ timestamp; a profile name such as `'1s'` selects the conventional pair. An
261
+ object `time` requires both `tick` and `bits`.
262
+ - `force: true` allows non-preset lengths, timestamps on short lengths, no
263
+ timestamp on long lengths, and decoupled tick/width pairs.
264
+ `generateV2`/`generateV2Buffer` emit the warnings on every call through
265
+ `process.emitWarning`; `formatV2` returns them in `warnings`. Batch calls
266
+ emit the format warnings once per call.
267
+ - The v2 epoch is `2020-01-01T00:00:00Z`. Timestamps are returned as decimal
268
+ strings to preserve 64-bit ticks and 128-bit microsecond values.
269
+ - `generateV2Many` and `generateV2ManyEncoded` reject counts above 1,024 (TPM)
270
+ or 1,000,000 (OS-only) before allocating. The async variants
271
+ (`generateV2ManyAsync`, `generateV2ManyEncodedAsync`) apply the same caps
272
+ synchronously, before scheduling work on the libuv thread pool; only the
273
+ generation itself is asynchronous. Errors use the stable codes in
274
+ [Errors](#errors); invalid formats and lengths report `InvalidInput`.
275
+ - The async v2 batches keep the TPM profile fail-closed: without a usable TPM
276
+ they reject with `TpmUnavailable` instead of falling back to OS randomness.
277
+ - v2 is not wire-compatible with v1. See `docs/SPEC-v2.md` in the repository.
278
+ - The `no-tpm` entry point exposes `generateV2`, `generateV2Buffer`,
279
+ `generateV2Many`, `generateV2ManyEncoded`, `generateV2ManyAsync`, and
280
+ `generateV2ManyEncodedAsync` with the OS-only profile.
281
+ Batch encoded buffers use `count * formatV2(format).encodedLen` bytes.
282
+
283
+ ## Caller-provided buffer APIs
284
+
285
+ The shipped batch form is `generateV4ManyEncodedInto(buffer)` (and its
286
+ `OsOnly` counterpart): the caller owns the storage, the buffer length must be a
287
+ multiple of 21, and nothing is allocated per call. Prefer it for sustained
288
+ throughput; see [RailID v4](#railid-v4-126-bit).
289
+
290
+ A zero-allocation **single-ID** API with an explicit offset is still not
291
+ shipped. It would look like:
292
+
293
+ ```ts
294
+ generateInto(target: Buffer, offset?: number): number;
295
+ generateOsOnlyInto(target: Buffer, offset?: number): number;
296
+ ```
297
+
298
+ - `offset` defaults to 0 and must satisfy `offset + 32 <= target.length`.
299
+ - The function writes 32 ASCII bytes and returns the end offset.
300
+ - It performs no allocation and no JS string creation.
301
+ - It is synchronous only.
302
+
303
+ That single-ID form is **not shipped** because N-API buffers can be shared
304
+ with other JS execution contexts, and napi-rs documents mutable `Buffer` access
305
+ as an aliasing hazard. Shipping it safely needs an exclusive-ownership
306
+ guarantee, a rejection of `SharedArrayBuffer`-backed buffers, or a custom
307
+ writer object. Until then, use the batch APIs.
308
+
309
+ ## Linux and TPM
310
+
311
+ The Linux x64 glibc TPM binary links against `libtss2` (`tss-esapi`). The
312
+ package ships two Linux x64 glibc binaries:
313
+
314
+ - `railid-tpm.linux-x64-gnu.node` — TPM backend; needs `libtss2`
315
+ - `railid.linux-x64-gnu.node` — OS-only; no TSS dependency
316
+
317
+ `index.js` tries the TPM binary first and falls back to the OS-only binary when
318
+ the TPM binary cannot be loaded (for example, when `libtss2` is missing). In
319
+ that case `generate()` throws `TpmUnavailable`; `generateOsOnly()` still works.
320
+ This preserves fail-closed behavior.
321
+
322
+ Debian/Ubuntu TPM users need:
323
+
324
+ ```bash
325
+ sudo apt install libtss2
326
+ ```
327
+
328
+ Alpine, arm64, armv7 and riscv64 ship the OS-only backend only. Those
329
+ platforms load `railid.<platform>-<arch>[-<libc>].node` directly, so `generate()`
330
+ throws `TpmUnavailable` and `generateOsOnly()` is the supported profile.
331
+
332
+ Windows uses the system TBS service (`Tbs.dll`) and needs no extra DLL. macOS
333
+ ships the OS-only backend.
334
+
335
+ ## Build from source
336
+
337
+ Requirements:
338
+
339
+ - Rust 1.88+
340
+ - Linux TPM build: `pkg-config`, `libtss2-dev`
341
+ - Node.js 18+
342
+
343
+ ```bash
344
+ npm run build # host default
345
+ npm run build -- --os-only
346
+ npm run build -- --target linux-arm64-musl # cross target, OS-only
347
+ npm run verify # check every .node binary against its target tag
348
+ npm test
349
+ ```
350
+
351
+ `node scripts/build.js --list` prints the supported targets. On Linux the
352
+ default build produces both TPM and OS-only binaries for x64; other targets
353
+ produce the OS-only binary. On Windows it produces the TPM binary. On macOS it
354
+ produces both OS-only slices.
355
+
356
+ Cross-compiling without a matching host is easiest in a container. The helper
357
+ installs the toolchain for the requested target:
358
+
359
+ ```bash
360
+ docker run --rm -v "$PWD:/src" -w /src/node rust:1.88-alpine \
361
+ sh scripts/build-in-docker.sh linux-arm64-musl
362
+ ```
363
+
364
+ ## Benchmarks
365
+
366
+ The Node addon benchmark against UUIDv4 and NanoID is in
367
+ [`bench/`](bench/README.md). It includes the latest Windows and Raspberry Pi 4
368
+ results.
369
+
370
+ ## Security notes
371
+
372
+ RailID is an identifier generator. This package does not provide single-use
373
+ tokens, expiry, or revocation; enforce those in your application. A RailID
374
+ discloses its creation time at 100 ms precision. TPM presence does not prove
375
+ the firmware or boot chain is trustworthy.
376
+
377
+ TPM access is serialized inside the process. Use the async batch APIs for
378
+ server workloads so the event loop is not blocked by large batches.
379
+
380
+ ## License
381
+
382
+ MIT. Copyright (c) 2026 Nekomakura. See [LICENSE](LICENSE).