@neko-makura/railid 0.0.0-stage → 1.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nekomakura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,183 @@
1
- # Temporary Holding Version
1
+ # @neko-makura/railid (Node.js)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Native N-API bindings for [RailID](https://crates.io/crates/railid).
4
+
5
+ ```bash
6
+ npm install @neko-makura/railid
7
+ ```
8
+
9
+ The package includes prebuilt N-API binaries. Node.js 18 or newer is required.
10
+
11
+ ## Platforms
12
+
13
+ | Platform | Architecture | libc | Backend |
14
+ |---|---|---|---|
15
+ | Linux | x64 | glibc | TPM (`libtss2`) + OS-only fallback |
16
+ | Linux | x64 | musl | OS-only |
17
+ | Linux | arm64 | glibc | OS-only |
18
+ | Linux | arm64 | musl | OS-only |
19
+ | Linux | armv7 | glibc (hard-float) | OS-only |
20
+ | Linux | riscv64 | glibc | OS-only |
21
+ | Windows | x64 | MSVC | TPM (TBS) |
22
+ | Windows | arm64 | MSVC | TPM (TBS) |
23
+ | macOS | x64 | — | OS-only |
24
+ | macOS | arm64 | — | OS-only |
25
+
26
+ `index.js` selects the addon from `process.platform`, `process.arch` and, on
27
+ Linux, whether the Node process runs on glibc or musl.
28
+
29
+ The riscv64 addon targets the `riscv64gc` glibc ABI used by distribution Node
30
+ builds (for example Ubuntu 24.04). Node.js does not publish official riscv64
31
+ binaries; use a distribution package.
32
+
33
+
34
+ ## Usage
35
+
36
+ ```js
37
+ const railid = require('@neko-makura/railid');
38
+
39
+ console.log(railid.version());
40
+ console.log(railid.backend()); // "tpm" or "os-only"
41
+
42
+ // Standard TPM hybrid profile. Throws if the backend is OS-only or no TPM
43
+ // device is available.
44
+ const id = railid.generate();
45
+ console.log(id);
46
+
47
+ // Explicitly degraded OS-only profile.
48
+ const osId = railid.generateOsOnly();
49
+
50
+ // Synchronous batch.
51
+ const ids = railid.generateMany(1000, true);
52
+ const batch = railid.generateManyEncoded(1000, true);
53
+ // batch is a Buffer of 1000 * 32 ASCII bytes.
54
+
55
+ // Asynchronous batch: runs on the libuv thread pool.
56
+ const asyncIds = await railid.generateManyAsync(1000, true);
57
+ const asyncBatch = await railid.generateManyEncodedAsync(1000, true);
58
+
59
+ const decoded = railid.decode(id);
60
+ console.log(decoded.timestampMs, decoded.randomHex, decoded.encoded);
61
+ ```
62
+
63
+ ## API
64
+
65
+ | Function | Result | Notes |
66
+ |---|---|---|
67
+ | `generate()` | `string` | TPM hybrid profile; throws `TpmUnavailable` if unavailable |
68
+ | `generateOsOnly()` | `string` | Explicit degraded profile |
69
+ | `generateBuffer()` | `Buffer` | TPM profile as 32 ASCII bytes, no JS string |
70
+ | `generateOsOnlyBuffer()` | `Buffer` | OS-only as 32 ASCII bytes, no JS string |
71
+ | `generateMany(count, osOnly?)` | `string[]` | Sync; `osOnly` defaults to `false` |
72
+ | `generateManyEncoded(count, osOnly?)` | `Buffer` | Sync; `count * 32` bytes |
73
+ | `generateManyAsync(count, osOnly?)` | `Promise<string[]>` | Bulk work off the JS thread |
74
+ | `generateManyEncodedAsync(count, osOnly?)` | `Promise<Buffer>` | Bulk work off the JS thread |
75
+ | `decode(input)` | `{ timestampMs, randomHex, encoded }` | Validates canonical Base64URL |
76
+ | `version()` | `string` | RailID crate version |
77
+ | `backend()` | `"tpm" \| "os-only"` | Backend compiled into the loaded binary |
78
+
79
+ Limits:
80
+
81
+ - OS-only strings: 100,000 IDs
82
+ - OS-only encoded: 1,000,000 IDs
83
+ - TPM: 1,024 IDs
84
+
85
+ Counts above the limit are rejected before allocation.
86
+
87
+ `generateBuffer()` avoids the JS string but still allocates a Node Buffer per
88
+ call; for throughput use `generateManyEncoded()` or
89
+ `generateManyEncodedAsync()`, which allocate one contiguous buffer.
90
+
91
+ ## Caller-provided buffer API (design, not shipped)
92
+
93
+ A zero-allocation single-ID API would look like:
94
+
95
+ ```ts
96
+ generateInto(target: Buffer, offset?: number): number;
97
+ generateOsOnlyInto(target: Buffer, offset?: number): number;
98
+ ```
99
+
100
+ - `offset` defaults to 0 and must satisfy `offset + 32 <= target.length`.
101
+ - The function writes 32 ASCII bytes and returns the end offset.
102
+ - It performs no allocation and no JS string creation.
103
+ - It is synchronous only.
104
+
105
+ This is **not shipped** because N-API buffers can be shared with other JS
106
+ execution contexts, and napi-rs documents mutable `Buffer` access as an aliasing
107
+ hazard. Shipping it safely needs an exclusive-ownership guarantee, a rejection
108
+ of `SharedArrayBuffer`-backed buffers, or a custom writer object. Until then,
109
+ use the batch APIs.
110
+
111
+ ## Linux and TPM
112
+
113
+ The Linux x64 glibc TPM binary links against `libtss2` (`tss-esapi`). The
114
+ package ships two Linux x64 glibc binaries:
115
+
116
+ - `railid-tpm.linux-x64-gnu.node` — TPM backend; needs `libtss2`
117
+ - `railid.linux-x64-gnu.node` — OS-only; no TSS dependency
118
+
119
+ `index.js` tries the TPM binary first and falls back to the OS-only binary when
120
+ the TPM binary cannot be loaded (for example, when `libtss2` is missing). In
121
+ that case `generate()` throws `TpmUnavailable`; `generateOsOnly()` still works.
122
+ This preserves fail-closed behavior.
123
+
124
+ Debian/Ubuntu TPM users need:
125
+
126
+ ```bash
127
+ sudo apt install libtss2
128
+ ```
129
+
130
+ Alpine, arm64, armv7 and riscv64 ship the OS-only backend only. Those
131
+ platforms load `railid.<platform>-<arch>[-<libc>].node` directly, so `generate()`
132
+ throws `TpmUnavailable` and `generateOsOnly()` is the supported profile.
133
+
134
+ Windows uses the system TBS service (`Tbs.dll`) and needs no extra DLL. macOS
135
+ ships the OS-only backend.
136
+
137
+ ## Build from source
138
+
139
+ Requirements:
140
+
141
+ - Rust 1.88+
142
+ - Linux TPM build: `pkg-config`, `libtss2-dev`
143
+ - Node.js 18+
144
+
145
+ ```bash
146
+ npm run build # host default
147
+ npm run build -- --os-only
148
+ npm run build -- --target linux-arm64-musl # cross target, OS-only
149
+ npm run verify # check every .node binary against its target tag
150
+ npm test
151
+ ```
152
+
153
+ `node scripts/build.js --list` prints the supported targets. On Linux the
154
+ default build produces both TPM and OS-only binaries for x64; other targets
155
+ produce the OS-only binary. On Windows it produces the TPM binary. On macOS it
156
+ produces both OS-only slices.
157
+
158
+ Cross-compiling without a matching host is easiest in a container. The helper
159
+ installs the toolchain for the requested target:
160
+
161
+ ```bash
162
+ docker run --rm -v "$PWD:/src" -w /src/node rust:1.88-alpine \
163
+ sh scripts/build-in-docker.sh linux-arm64-musl
164
+ ```
165
+
166
+ ## Benchmarks
167
+
168
+ The Node addon benchmark against UUIDv4 and NanoID is in
169
+ [`bench/`](bench/README.md). It includes the latest Windows result.
170
+
171
+ ## Security notes
172
+
173
+ RailID is an identifier generator. This package does not provide single-use
174
+ tokens, expiry, or revocation; enforce those in your application. A RailID
175
+ discloses its creation time at 100 ms precision. TPM presence does not prove
176
+ the firmware or boot chain is trustworthy.
177
+
178
+ TPM access is serialized inside the process. Use the async batch APIs for
179
+ server workloads so the event loop is not blocked by large batches.
180
+
181
+ ## License
182
+
183
+ MIT. Copyright (c) 2026 Nekomakura. See [LICENSE](LICENSE).
package/index.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ export type Backend = "tpm" | "os-only";
2
+
3
+ export interface DecodedRailId {
4
+ /** Unix timestamp in milliseconds. */
5
+ timestampMs: number;
6
+ /** 150-bit random field as 38 lowercase hex characters. */
7
+ randomHex: string;
8
+ /** Canonical 32-character Base64URL encoding. */
9
+ encoded: string;
10
+ }
11
+
12
+ /** Generate one RailID with the standard TPM hybrid profile. */
13
+ export declare function generate(): string;
14
+
15
+ /** Generate one RailID with the explicitly degraded OS-only profile. */
16
+ export declare function generateOsOnly(): string;
17
+
18
+ /** Generate one TPM-profile RailID as 32 ASCII bytes, without a JS string. */
19
+ export declare function generateBuffer(): Buffer;
20
+
21
+ /** Generate one OS-only RailID as 32 ASCII bytes, without a JS string. */
22
+ export declare function generateOsOnlyBuffer(): Buffer;
23
+
24
+ /** Generate `count` IDs synchronously as strings. */
25
+ export declare function generateMany(count: number, osOnly?: boolean): string[];
26
+
27
+ /** Generate `count` IDs synchronously as one contiguous `count * 32` Buffer. */
28
+ export declare function generateManyEncoded(count: number, osOnly?: boolean): Buffer;
29
+
30
+ /** Generate `count` IDs asynchronously as strings. */
31
+ export declare function generateManyAsync(count: number, osOnly?: boolean): Promise<string[]>;
32
+
33
+ /** Generate `count` IDs asynchronously as one contiguous `count * 32` Buffer. */
34
+ export declare function generateManyEncodedAsync(
35
+ count: number,
36
+ osOnly?: boolean,
37
+ ): Promise<Buffer>;
38
+
39
+ /** Decode and validate a RailID. */
40
+ export declare function decode(input: string): DecodedRailId;
41
+
42
+ /** RailID crate version. */
43
+ export declare function version(): string;
44
+
45
+ /** Native backend compiled into the loaded addon. */
46
+ export declare function backend(): Backend;
package/index.js ADDED
@@ -0,0 +1,73 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+
5
+ function linuxLibc() {
6
+ if (process.platform !== 'linux') {
7
+ return '';
8
+ }
9
+ try {
10
+ const report = process.report && process.report.getReport();
11
+ const version = report && report.header && report.header.glibcVersionRuntime;
12
+ return version ? 'gnu' : 'musl';
13
+ } catch {
14
+ return 'gnu';
15
+ }
16
+ }
17
+
18
+ function suffix() {
19
+ const platform = process.platform;
20
+ const arch = process.arch;
21
+ if (platform === 'win32') {
22
+ return `win32-${arch}-msvc`;
23
+ }
24
+ if (platform === 'linux') {
25
+ return `linux-${arch}-${linuxLibc()}`;
26
+ }
27
+ if (platform === 'darwin') {
28
+ return `darwin-${arch}`;
29
+ }
30
+ return `${platform}-${arch}`;
31
+ }
32
+
33
+ function candidates() {
34
+ const tag = suffix();
35
+ if (process.platform === 'win32') {
36
+ return [`railid.${tag}.node`];
37
+ }
38
+ if (process.platform === 'linux') {
39
+ return [`railid-tpm.${tag}.node`, `railid.${tag}.node`];
40
+ }
41
+ return [`railid.${tag}.node`];
42
+ }
43
+
44
+ let binding = null;
45
+ let backend = null;
46
+ const loadErrors = [];
47
+
48
+ for (const file of candidates()) {
49
+ try {
50
+ binding = require(path.join(__dirname, file));
51
+ backend = typeof binding.backend === 'function' ? binding.backend() : 'unknown';
52
+ break;
53
+ } catch (error) {
54
+ loadErrors.push(`${file}: ${error.message}`);
55
+ }
56
+ }
57
+
58
+ if (!binding) {
59
+ const error = new Error(
60
+ `No usable RailID native addon for ${process.platform}/${process.arch}. ` +
61
+ `Tried: ${candidates().join(', ')}. ` +
62
+ 'Install a prebuilt package or run `npm run build` with Rust and the platform TPM libraries.'
63
+ );
64
+ error.cause = loadErrors.join('\n');
65
+ throw error;
66
+ }
67
+
68
+ module.exports = {
69
+ ...binding,
70
+ // `backend` is the backend compiled into the loaded binary. A TPM build can
71
+ // still return TpmUnavailable at runtime when no TPM device is present.
72
+ backend: () => backend,
73
+ };
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@neko-makura/railid",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
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",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/nekomakura-nyan/rail-id.git",
11
+ "directory": "node"
12
+ },
13
+ "homepage": "https://github.com/nekomakura-nyan/rail-id",
14
+ "bugs": {
15
+ "url": "https://github.com/nekomakura-nyan/rail-id/issues"
16
+ },
17
+ "keywords": [
18
+ "railid",
19
+ "identifier",
20
+ "uuid",
21
+ "tpm",
22
+ "napi",
23
+ "native"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "files": [
29
+ "index.js",
30
+ "index.d.ts",
31
+ "*.node",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "scripts": {
36
+ "build": "node scripts/build.js",
37
+ "verify": "node scripts/verify.js",
38
+ "test": "node test.js",
39
+ "pack:check": "npm pack --dry-run"
40
+ }
41
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file