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