@neko-makura/railid 4.2.1 → 4.2.2

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
@@ -115,7 +115,29 @@ Limits:
115
115
  - OS-only encoded: 1,000,000 IDs
116
116
  - TPM: 1,024 IDs
117
117
 
118
- Counts above the limit are rejected before allocation.
118
+ Counts above the limit are rejected before allocation. Every batch `count`
119
+ must be a safe integer in `0..4294967295`; fractional, negative, `NaN`,
120
+ `Infinity`, and out-of-range values throw instead of wrapping. v2 batches use
121
+ the same caps (1,024 TPM / 1,000,000 OS-only).
122
+
123
+ ## Errors
124
+
125
+ Native N-API failures are mapped once at the JavaScript boundary to a stable
126
+ `error.code`, so callers do not need to parse messages:
127
+
128
+ | `error.code` | Meaning |
129
+ |---|---|
130
+ | `TpmUnavailable` | The fail-closed TPM hybrid profile has no usable TPM |
131
+ | `TpmRandomFailure` | The TPM was reached but returned no random bytes |
132
+ | `OsRandomFailure` | The operating system CSPRNG failed |
133
+ | `TimestampOutOfRange` | A timestamp does not fit the requested field |
134
+ | `InvalidInput` | Invalid count, format, length, or encoding |
135
+ | `CapacityOverflow` | A batch cannot be represented in memory |
136
+
137
+ `generate()` / `generateV4()` and the TPM batch APIs throw `TpmUnavailable`
138
+ rather than falling back to OS randomness. The `no-tpm` entry point intentionally
139
+ uses the OS-only profile, so it does not produce that error.
140
+
119
141
 
120
142
  `generateBuffer()` avoids the JS string but still allocates a Node Buffer per
121
143
  call; for throughput use `generateManyEncoded()` or
@@ -157,6 +179,10 @@ for (let i = 0; i < 1000; i++) {
157
179
  same day. `count == 0` returns an empty Buffer.
158
180
  - v4 batch limits match v1: 1,024 IDs for the TPM profile and 1,000,000 IDs
159
181
  for OS-only. Counts above the limit are rejected before allocation.
182
+ - v4 has no asynchronous batch API yet; use the synchronous encoded batches,
183
+ or `@neko-makura/railid/no-tpm` for OS-only workloads.
184
+ - Errors from v4 APIs carry the stable `code` values documented under
185
+ [Errors](#errors), including `TpmUnavailable` and `InvalidInput`.
160
186
  - The v1 192-bit API above is unchanged: `generate()` and `generateOsOnly()`
161
187
  still return 32-character v1 IDs. v4 does **not** reuse those names.
162
188
 
@@ -208,6 +234,9 @@ const buffer = railid.generateV2ManyEncoded({ bits: 192 }, 1000); // 32,000 byte
208
234
  emit the format warnings once per call.
209
235
  - The v2 epoch is `2020-01-01T00:00:00Z`. Timestamps are returned as decimal
210
236
  strings to preserve 64-bit ticks and 128-bit microsecond values.
237
+ - `generateV2Many` and `generateV2ManyEncoded` reject counts above 1,024 (TPM)
238
+ or 1,000,000 (OS-only) before allocating. Errors use the stable codes in
239
+ [Errors](#errors); invalid formats and lengths report `InvalidInput`.
211
240
  - v2 is not wire-compatible with v1. See `docs/SPEC-v2.md` in the repository.
212
241
  - The `no-tpm` entry point exposes `generateV2`, `generateV2Buffer`,
213
242
  `generateV2Many`, and `generateV2ManyEncoded` with the OS-only profile.
package/errors.js ADDED
@@ -0,0 +1,152 @@
1
+ 'use strict';
2
+
3
+ // Shared validation and error-code mapping for the public JavaScript surface.
4
+ //
5
+ // N-API only exposes a small set of status strings (`GenericFailure`,
6
+ // `InvalidArg`, ...), so the bindings would otherwise report every failure as
7
+ // `GenericFailure`. The native functions throw our own crates' exact error
8
+ // messages; this module maps them once, at the boundary, to stable codes that
9
+ // callers can switch on.
10
+
11
+ const MAX_COUNT = 0xffffffff;
12
+ const TPM_BATCH_LIMIT = 1_024;
13
+ const OS_ONLY_BATCH_LIMIT = 1_000_000;
14
+ const OS_ONLY_STRING_BATCH_LIMIT = 100_000;
15
+
16
+ const ERROR_CODES = Object.freeze({
17
+ TpmUnavailable: 'TpmUnavailable',
18
+ TpmRandomFailure: 'TpmRandomFailure',
19
+ OsRandomFailure: 'OsRandomFailure',
20
+ TimestampOutOfRange: 'TimestampOutOfRange',
21
+ InvalidInput: 'InvalidInput',
22
+ CapacityOverflow: 'CapacityOverflow',
23
+ WorkerFailure: 'WorkerFailure',
24
+ });
25
+
26
+ // Ordered: the first matching rule wins. Capacity and timestamp rules must run
27
+ // before the generic invalid-input rule.
28
+ const RULES = [
29
+ [/TPM 2\.0 is unavailable/i, ERROR_CODES.TpmUnavailable],
30
+ [/TPM 2\.0 random generation failed/i, ERROR_CODES.TpmRandomFailure],
31
+ [/operating system CSPRNG failed/i, ERROR_CODES.OsRandomFailure],
32
+ [/worker (?:thread )?panicked/i, ERROR_CODES.WorkerFailure],
33
+ [/too large|capacity overflow|allocation failed/i, ERROR_CODES.CapacityOverflow],
34
+ [
35
+ /timestamp (?:is|does|arithmetic)|outside the 24-bit day range/i,
36
+ ERROR_CODES.TimestampOutOfRange,
37
+ ],
38
+ [
39
+ /invalid|must be|required|out of range|non-canonical|non-zero|padding|exceeds binding limit|buffer length|length does not match|unknown tick|unknown preset/i,
40
+ ERROR_CODES.InvalidInput,
41
+ ],
42
+ ];
43
+
44
+ function inputError(message) {
45
+ const error = new TypeError(message);
46
+ error.code = ERROR_CODES.InvalidInput;
47
+ return error;
48
+ }
49
+
50
+ function classify(message) {
51
+ for (const [pattern, code] of RULES) {
52
+ if (pattern.test(message)) {
53
+ return code;
54
+ }
55
+ }
56
+ return null;
57
+ }
58
+
59
+ function decorate(error) {
60
+ if (error === null || typeof error !== 'object') {
61
+ return error;
62
+ }
63
+ // JS validation errors already carry a stable code. Native errors arrive as
64
+ // `GenericFailure` (or `InvalidArg` if a native check used that status); map
65
+ // those to the documented public code.
66
+ const current = error.code;
67
+ if (
68
+ typeof current === 'string' &&
69
+ current !== 'GenericFailure' &&
70
+ current !== 'InvalidArg'
71
+ ) {
72
+ return error;
73
+ }
74
+ const message = typeof error.message === 'string' ? error.message : String(error);
75
+ const code = classify(message);
76
+ if (code === null) {
77
+ return error;
78
+ }
79
+ try {
80
+ error.code = code;
81
+ } catch {
82
+ try {
83
+ Object.defineProperty(error, 'code', {
84
+ value: code,
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ });
89
+ } catch {
90
+ // A frozen/native error object keeps its original code; the message is
91
+ // still available. This should not happen for N-API errors.
92
+ }
93
+ }
94
+ return error;
95
+ }
96
+
97
+ // Wrap a native/public function so synchronous throws and rejected promises
98
+ // carry the documented `code` property.
99
+ function wrap(fn) {
100
+ return function wrapped(...args) {
101
+ let result;
102
+ try {
103
+ result = fn.apply(this, args);
104
+ } catch (error) {
105
+ throw decorate(error);
106
+ }
107
+ if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
108
+ return result.catch((error) => {
109
+ throw decorate(error);
110
+ });
111
+ }
112
+ return result;
113
+ };
114
+ }
115
+
116
+ function checkCount(count, limit, name = 'count') {
117
+ if (
118
+ typeof count !== 'number' ||
119
+ !Number.isSafeInteger(count) ||
120
+ count < 0 ||
121
+ count > MAX_COUNT
122
+ ) {
123
+ throw inputError(`${name} must be an integer between 0 and 4294967295`);
124
+ }
125
+ if (count > limit) {
126
+ throw inputError(`${name} ${count} exceeds binding limit ${limit}`);
127
+ }
128
+ return count;
129
+ }
130
+
131
+ function batchLimit(osOnly) {
132
+ return osOnly ? OS_ONLY_BATCH_LIMIT : TPM_BATCH_LIMIT;
133
+ }
134
+
135
+ function stringBatchLimit(osOnly) {
136
+ return osOnly ? OS_ONLY_STRING_BATCH_LIMIT : TPM_BATCH_LIMIT;
137
+ }
138
+
139
+ module.exports = {
140
+ ERROR_CODES,
141
+ MAX_COUNT,
142
+ TPM_BATCH_LIMIT,
143
+ OS_ONLY_BATCH_LIMIT,
144
+ OS_ONLY_STRING_BATCH_LIMIT,
145
+ inputError,
146
+ classify,
147
+ decorate,
148
+ wrap,
149
+ checkCount,
150
+ batchLimit,
151
+ stringBatchLimit,
152
+ };
package/index.d.ts CHANGED
@@ -1,5 +1,26 @@
1
1
  export type Backend = "tpm" | "os-only";
2
2
 
3
+ /**
4
+ * Stable `error.code` values set by the bindings. Native N-API failures are
5
+ * mapped to these codes at the JavaScript boundary; `TpmUnavailable` is the
6
+ * fail-closed signal from the TPM hybrid profile.
7
+ */
8
+ export type RailIdErrorCode =
9
+ | "TpmUnavailable"
10
+ | "TpmRandomFailure"
11
+ | "OsRandomFailure"
12
+ | "TimestampOutOfRange"
13
+ | "InvalidInput"
14
+ | "CapacityOverflow";
15
+
16
+ /**
17
+ * Errors thrown by the bindings carry one of the {@link RailIdErrorCode}
18
+ * values in `code`.
19
+ */
20
+ export interface RailIdError extends Error {
21
+ code: RailIdErrorCode;
22
+ }
23
+
3
24
  export interface DecodedRailId {
4
25
  /** Unix timestamp in milliseconds. */
5
26
  timestampMs: number;
@@ -39,16 +60,19 @@ export declare function generateV4BufferOsOnly(): Buffer;
39
60
  /**
40
61
  * Generate `count` v4 IDs as one contiguous `count * 21` Buffer with the TPM
41
62
  * hybrid profile. Capped at 1,024 IDs and fails closed without a TPM.
63
+ * Counts are validated before allocation; invalid counts throw `InvalidInput`.
64
+ * v4 has no asynchronous batch API yet.
42
65
  */
43
66
  export declare function generateV4ManyEncoded(count: number): Buffer;
44
67
 
45
68
  /**
46
69
  * Generate `count` v4 IDs as one contiguous `count * 21` Buffer with the
47
- * explicitly degraded OS-only profile. Capped at 1,000,000 IDs.
70
+ * explicitly degraded OS-only profile. Capped at 1,000,000 IDs. Invalid
71
+ * counts throw `InvalidInput`.
48
72
  */
49
73
  export declare function generateV4ManyEncodedOsOnly(count: number): Buffer;
50
74
 
51
- /** Generate `count` IDs synchronously as strings. */
75
+ /** Generate `count` IDs synchronously as strings. OS-only strings cap at 100,000. */
52
76
  export declare function generateMany(count: number, osOnly?: boolean): string[];
53
77
 
54
78
  /** Generate `count` IDs synchronously as one contiguous `count * 32` Buffer. */
@@ -121,7 +145,7 @@ export declare function generateV2(format: V2Format): string;
121
145
  /** Generate one v2 value as 3-171 ASCII bytes. */
122
146
  export declare function generateV2Buffer(format: V2Format): Buffer;
123
147
 
124
- /** Generate `count` v2 values as a string array. */
148
+ /** Generate `count` v2 values as a string array. Capped at 1,024 (TPM) or 1,000,000 (OS-only). */
125
149
  export declare function generateV2Many(format: V2Format, count: number): string[];
126
150
 
127
151
  /** Generate `count` v2 values as one contiguous `count * encodedLen` Buffer. */
package/index.js CHANGED
@@ -65,6 +65,13 @@ if (!binding) {
65
65
  throw error;
66
66
  }
67
67
 
68
+ const {
69
+ checkCount,
70
+ batchLimit,
71
+ stringBatchLimit,
72
+ wrap,
73
+ } = require('./errors.js');
74
+
68
75
  const v2 = require('./v2.js')(binding);
69
76
  const publicBinding = { ...binding };
70
77
 
@@ -88,27 +95,62 @@ for (const key of Object.keys(publicBinding)) {
88
95
  }
89
96
 
90
97
  const V1_ENCODED_LEN = 32;
91
- const V1_OS_LIMIT = 1_000_000;
92
- const V1_TPM_LIMIT = 1_024;
98
+
99
+ function generateMany(count, osOnly) {
100
+ const degraded = Boolean(osOnly);
101
+ checkCount(count, stringBatchLimit(degraded));
102
+ return binding.generateMany(count, degraded);
103
+ }
104
+
105
+ function generateManyAsync(count, osOnly) {
106
+ const degraded = Boolean(osOnly);
107
+ checkCount(count, stringBatchLimit(degraded));
108
+ return binding.generateManyAsync(count, degraded);
109
+ }
93
110
 
94
111
  function generateManyEncoded(count, osOnly) {
95
- if (!Number.isInteger(count) || count < 0 || count > 0xffffffff) {
96
- throw new TypeError('count must be an integer between 0 and 4294967295');
97
- }
98
- const limit = osOnly ? V1_OS_LIMIT : V1_TPM_LIMIT;
99
- if (count > limit) {
100
- throw new Error(`count ${count} exceeds binding limit ${limit}`);
101
- }
112
+ const degraded = Boolean(osOnly);
113
+ checkCount(count, batchLimit(degraded));
102
114
  const buffer = Buffer.allocUnsafe(count * V1_ENCODED_LEN);
103
- binding.generateManyEncodedInto(buffer, Boolean(osOnly));
115
+ binding.generateManyEncodedInto(buffer, degraded);
104
116
  return buffer;
105
117
  }
106
118
 
107
- module.exports = {
119
+ function generateManyEncodedAsync(count, osOnly) {
120
+ const degraded = Boolean(osOnly);
121
+ checkCount(count, batchLimit(degraded));
122
+ return binding.generateManyEncodedAsync(count, degraded);
123
+ }
124
+
125
+ function generateV4ManyEncoded(count) {
126
+ checkCount(count, batchLimit(false));
127
+ return binding.generateV4ManyEncoded(count);
128
+ }
129
+
130
+ function generateV4ManyEncodedOsOnly(count) {
131
+ checkCount(count, batchLimit(true));
132
+ return binding.generateV4ManyEncodedOsOnly(count);
133
+ }
134
+
135
+ const api = {
108
136
  ...publicBinding,
137
+ generateMany,
138
+ generateManyAsync,
109
139
  generateManyEncoded,
140
+ generateManyEncodedAsync,
141
+ generateV4ManyEncoded,
142
+ generateV4ManyEncodedOsOnly,
110
143
  // `backend` is the backend compiled into the loaded binary. A TPM build can
111
144
  // still return TpmUnavailable at runtime when no TPM device is present.
112
145
  backend: () => backend,
113
146
  ...v2,
114
147
  };
148
+
149
+ // Map native errors to stable `code` values once, at the public boundary.
150
+ for (const [key, value] of Object.entries(api)) {
151
+ if (typeof value === 'function') {
152
+ api[key] = wrap(value);
153
+ }
154
+ }
155
+
156
+ module.exports = api;
package/no-tpm.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { DecodedRailId } from "./index";
1
+ import type { DecodedRailId, RailIdError, RailIdErrorCode } from "./index";
2
2
 
3
- export type { DecodedRailId };
3
+ export type { DecodedRailId, RailIdError, RailIdErrorCode };
4
4
  export type Backend = "os-only";
5
5
 
6
6
  /** Generate one RailID with the explicitly degraded OS-only profile. */
@@ -64,7 +64,7 @@ export type { V2Decoded, V2Format, V2FormatInfo };
64
64
  /** Generate one OS-only v2 value. */
65
65
  export declare function generateV2(format: V2Format): string;
66
66
 
67
- /** Generate one OS-only v2 value as 32-171 ASCII bytes. */
67
+ /** Generate one OS-only v2 value as 3-171 ASCII bytes. */
68
68
  export declare function generateV2Buffer(format: V2Format): Buffer;
69
69
 
70
70
  /** Generate `count` OS-only v2 values as a string array. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neko-makura/railid",
3
- "version": "4.2.1",
3
+ "version": "4.2.2",
4
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",
@@ -28,6 +28,7 @@
28
28
  "files": [
29
29
  "index.js",
30
30
  "index.d.ts",
31
+ "errors.js",
31
32
  "no-tpm.js",
32
33
  "no-tpm.d.ts",
33
34
  "v2.js",
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 CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { checkCount, batchLimit } = require('./errors.js');
4
+
3
5
  const TICKS = ['1d', '1h', '1s', '100ms', '10ms', '1ms', '0.1ms'];
4
6
 
5
7
  function tickIndex(name) {
@@ -182,33 +184,23 @@ module.exports = function createV2(binding) {
182
184
  return binding.v2GenerateBufferPacked(entry.key | (profile === 'os-only' ? 1 << 24 : 0));
183
185
  }
184
186
 
185
- function batchCount(count) {
186
- if (!Number.isInteger(count) || count < 0 || count > 0xFFFFFFFF) {
187
- throw new TypeError('count must be an integer between 0 and 4294967295');
188
- }
189
- return count;
190
- }
191
-
192
187
  function generateV2Many(format, count, profile) {
193
- batchCount(count);
188
+ const degraded = profile === 'os-only';
189
+ checkCount(count, batchLimit(degraded));
194
190
  const args = toNativeArguments(format);
195
191
  const entry = cachedInfo(args);
196
192
  emitWarnings(entry.commands);
197
- return binding.v2GenerateMany(...args, count, profile === 'os-only');
193
+ return binding.v2GenerateMany(...args, count, degraded);
198
194
  }
199
195
 
200
196
  function generateV2ManyEncoded(format, count, profile) {
201
- batchCount(count);
197
+ const degraded = profile === 'os-only';
198
+ checkCount(count, batchLimit(degraded));
202
199
  const args = toNativeArguments(format);
203
200
  const entry = cachedInfo(args);
204
201
  emitWarnings(entry.commands);
205
202
  const buffer = Buffer.allocUnsafe(count * entry.info.encodedLen);
206
- binding.v2GenerateManyEncodedInto(
207
- ...args,
208
- count,
209
- profile === 'os-only',
210
- buffer
211
- );
203
+ binding.v2GenerateManyEncodedInto(...args, count, degraded, buffer);
212
204
  return buffer;
213
205
  }
214
206