@zintrust/signer 0.1.49

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 ADDED
@@ -0,0 +1,561 @@
1
+ # @zintrust/signer
2
+
3
+ Zero-dependency WebCrypto library for signing and verifying HTTP requests using HMAC-SHA256. Works in browsers, Node.js 20+, and Cloudflare Workers — any runtime with `globalThis.crypto.subtle`.
4
+
5
+ Used by the [ZinTrust](https://github.com/ZinTrust/zintrust) Bulletproof Auth middleware to implement **proof-of-possession request signing**: a stolen JWT alone is not enough to access protected endpoints.
6
+
7
+ ---
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm i @zintrust/signer
13
+ ```
14
+
15
+ ---
16
+
17
+ ## How it works
18
+
19
+ Every request carries five headers that bind it to a specific key, timestamp, nonce, and body:
20
+
21
+ | Header | Description |
22
+ | ------------------ | ------------------------------------------------- |
23
+ | `x-zt-key-id` | Identifies the signing key (e.g. a device ID) |
24
+ | `x-zt-timestamp` | Unix timestamp in milliseconds at signing time |
25
+ | `x-zt-nonce` | Random UUID — consumed exactly once (anti-replay) |
26
+ | `x-zt-body-sha256` | SHA-256 hex of the raw request body |
27
+ | `x-zt-signature` | HMAC-SHA256 of the canonical request string |
28
+
29
+ The **canonical string** format (joined with `\n`):
30
+
31
+ ```
32
+ METHOD
33
+ /path/name
34
+ ?query=string
35
+ timestampMs
36
+ nonce
37
+ bodySha256Hex
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Quick start
43
+
44
+ ### Sign a request (client side)
45
+
46
+ ```ts
47
+ import { SignedRequest } from '@zintrust/signer';
48
+
49
+ const url = new URL('/api/orders', 'https://api.example.com');
50
+ const method = 'POST';
51
+ const body = JSON.stringify({ item: 'widget', qty: 3 });
52
+
53
+ const signed = await SignedRequest.createHeaders({
54
+ method,
55
+ url,
56
+ body,
57
+ keyId: 'device_abc123',
58
+ secret: 'base64:your-32-byte-secret-here',
59
+ });
60
+
61
+ await fetch(url, {
62
+ method,
63
+ headers: {
64
+ 'Content-Type': 'application/json',
65
+ Authorization: `Bearer ${jwt}`,
66
+ ...signed, // spreads all five x-zt-* headers
67
+ },
68
+ body,
69
+ });
70
+ ```
71
+
72
+ ### Verify a request (server side)
73
+
74
+ ```ts
75
+ import { SignedRequest } from '@zintrust/signer';
76
+
77
+ const result = await SignedRequest.verify({
78
+ method: req.method,
79
+ url: req.url,
80
+ body: await req.text(),
81
+ headers: req.headers,
82
+ getSecretForKeyId: async (keyId) => {
83
+ // Look up your DB / KV store
84
+ const device = await db.devices.findByKeyId(keyId);
85
+ return device?.signingSecret;
86
+ },
87
+ // Optional: reject replayed nonces
88
+ verifyNonce: async (keyId, nonce, ttlMs) => {
89
+ return await nonceStore.consumeOnce(keyId, nonce, ttlMs);
90
+ },
91
+ });
92
+
93
+ if (!result.ok) {
94
+ // result.code is one of the failure codes below
95
+ return new Response('Unauthorized', { status: 401 });
96
+ }
97
+
98
+ // result.keyId, result.timestampMs, result.nonce are available
99
+ ```
100
+
101
+ ---
102
+
103
+ ## API Reference
104
+
105
+ ### `SignedRequest.createHeaders(params)`
106
+
107
+ Generates the five signed-request headers for a given request.
108
+
109
+ ```ts
110
+ type SignedRequestCreateHeadersParams = {
111
+ method: string; // HTTP method — e.g. 'GET', 'POST'
112
+ url: string | URL; // Full URL including path and query
113
+ body?: string | Uint8Array | null; // Raw request body (default: empty string)
114
+ keyId: string; // Key identifier (sent in x-zt-key-id)
115
+ secret: string; // HMAC signing secret
116
+ timestampMs?: number; // Override timestamp (default: Date.now())
117
+ nonce?: string; // Override nonce (default: crypto.randomUUID())
118
+ };
119
+ ```
120
+
121
+ Returns: `Promise<SignedRequestHeaders>`
122
+
123
+ ```ts
124
+ type SignedRequestHeaders = {
125
+ 'x-zt-key-id': string;
126
+ 'x-zt-timestamp': string;
127
+ 'x-zt-nonce': string;
128
+ 'x-zt-body-sha256': string;
129
+ 'x-zt-signature': string;
130
+ };
131
+ ```
132
+
133
+ ---
134
+
135
+ ### `SignedRequest.verify(params)`
136
+
137
+ Verifies signed-request headers on an incoming request.
138
+
139
+ ```ts
140
+ type SignedRequestVerifyParams = {
141
+ method: string;
142
+ url: string | URL;
143
+ body?: string | Uint8Array | null;
144
+ headers: Headers | Record<string, string | undefined>;
145
+ getSecretForKeyId: (keyId: string) => string | undefined | Promise<string | undefined>;
146
+ nowMs?: number; // Override current time for testing (default: Date.now())
147
+ windowMs?: number; // Replay window in ms (default: 60_000 — 60 seconds)
148
+ verifyNonce?: (keyId: string, nonce: string, ttlMs: number) => Promise<boolean>;
149
+ };
150
+ ```
151
+
152
+ Returns: `Promise<SignedRequestVerifyResult>`
153
+
154
+ ```ts
155
+ type SignedRequestVerifyResult =
156
+ // Success
157
+ | { ok: true; keyId: string; timestampMs: number; nonce: string }
158
+ // Failure
159
+ | {
160
+ ok: false;
161
+ code:
162
+ | 'MISSING_HEADER' // One or more x-zt-* headers absent
163
+ | 'INVALID_TIMESTAMP' // x-zt-timestamp is not a valid integer
164
+ | 'EXPIRED' // Request timestamp outside the allowed window
165
+ | 'INVALID_BODY_SHA' // x-zt-body-sha256 does not match computed hash
166
+ | 'INVALID_SIGNATURE' // HMAC signature mismatch
167
+ | 'UNKNOWN_KEY' // getSecretForKeyId returned undefined or empty
168
+ | 'REPLAYED'; // verifyNonce hook returned false
169
+ message: string;
170
+ };
171
+ ```
172
+
173
+ ---
174
+
175
+ ### `SignedRequest.sha256Hex(data)`
176
+
177
+ Utility: computes the SHA-256 hex digest of a string or `Uint8Array`.
178
+
179
+ ```ts
180
+ const hash = await SignedRequest.sha256Hex('hello world');
181
+ // => 'b94d27b9934d3e08...'
182
+ ```
183
+
184
+ ---
185
+
186
+ ### `SignedRequest.canonicalString(params)`
187
+
188
+ Utility: builds the canonical string that is signed/verified. Useful for debugging.
189
+
190
+ ```ts
191
+ const canonical = await SignedRequest.canonicalString({
192
+ method: 'POST',
193
+ url: new URL('/api/orders?page=1', 'https://api.example.com'),
194
+ timestampMs: 1708000000000,
195
+ nonce: 'abc-123',
196
+ bodySha256Hex: 'e3b0c44298fc1c14...',
197
+ });
198
+
199
+ // => "POST\n/api/orders\n?page=1\n1708000000000\nabc-123\ne3b0c44298fc1c14..."
200
+ ```
201
+
202
+ ---
203
+
204
+ ## Browser / React example
205
+
206
+ ```ts
207
+ // lib/auth.ts
208
+ import { SignedRequest } from '@zintrust/signer';
209
+
210
+ interface LoginResult {
211
+ jwt: string;
212
+ deviceId: string;
213
+ deviceSecret: string;
214
+ }
215
+
216
+ export async function login(email: string, password: string): Promise<LoginResult> {
217
+ const res = await fetch('/auth/login', {
218
+ method: 'POST',
219
+ headers: { 'Content-Type': 'application/json' },
220
+ body: JSON.stringify({ email, password }),
221
+ });
222
+
223
+ if (!res.ok) throw new Error('Login failed');
224
+
225
+ const data = (await res.json()) as LoginResult;
226
+ sessionStorage.setItem('jwt', data.jwt);
227
+ sessionStorage.setItem('deviceId', data.deviceId);
228
+ sessionStorage.setItem('deviceSecret', data.deviceSecret);
229
+ return data;
230
+ }
231
+
232
+ // lib/api.ts
233
+ export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
234
+ const jwt = sessionStorage.getItem('jwt')!;
235
+ const deviceId = sessionStorage.getItem('deviceId')!;
236
+ const deviceSecret = sessionStorage.getItem('deviceSecret')!;
237
+
238
+ const method = (init.method ?? 'GET').toUpperCase();
239
+ const url = new URL(path, window.location.origin);
240
+ const body = typeof init.body === 'string' ? init.body : '';
241
+
242
+ const signed = await SignedRequest.createHeaders({
243
+ method,
244
+ url,
245
+ body,
246
+ keyId: deviceId,
247
+ secret: deviceSecret,
248
+ });
249
+
250
+ return fetch(url, {
251
+ ...init,
252
+ headers: {
253
+ 'Content-Type': 'application/json',
254
+ Authorization: `Bearer ${jwt}`,
255
+ 'x-zt-device-id': deviceId,
256
+ 'x-zt-timezone': Intl.DateTimeFormat().resolvedOptions().timeZone,
257
+ ...(init.headers as Record<string, string> | undefined),
258
+ ...signed,
259
+ },
260
+ });
261
+ }
262
+ ```
263
+
264
+ ---
265
+
266
+ ## Vue 3 example
267
+
268
+ ```ts
269
+ // composables/useAuth.ts
270
+ import { ref } from 'vue';
271
+ import { SignedRequest } from '@zintrust/signer';
272
+
273
+ interface LoginResult {
274
+ jwt: string;
275
+ deviceId: string;
276
+ deviceSecret: string;
277
+ }
278
+
279
+ const jwt = ref<string | null>(sessionStorage.getItem('jwt'));
280
+ const deviceId = ref<string | null>(sessionStorage.getItem('deviceId'));
281
+ const deviceSecret = ref<string | null>(sessionStorage.getItem('deviceSecret'));
282
+
283
+ export function useAuth() {
284
+ const isLoggedIn = computed(() => !!jwt.value);
285
+
286
+ async function login(email: string, password: string): Promise<void> {
287
+ const res = await fetch('/auth/login', {
288
+ method: 'POST',
289
+ headers: { 'Content-Type': 'application/json' },
290
+ body: JSON.stringify({ email, password }),
291
+ });
292
+
293
+ if (!res.ok) throw new Error('Login failed');
294
+
295
+ const data = (await res.json()) as LoginResult;
296
+
297
+ jwt.value = data.jwt;
298
+ deviceId.value = data.deviceId;
299
+ deviceSecret.value = data.deviceSecret;
300
+
301
+ sessionStorage.setItem('jwt', data.jwt);
302
+ sessionStorage.setItem('deviceId', data.deviceId);
303
+ sessionStorage.setItem('deviceSecret', data.deviceSecret);
304
+ }
305
+
306
+ async function logout(): Promise<void> {
307
+ // Call logout endpoint using a signed request
308
+ await apiFetch('/auth/logout', { method: 'POST' });
309
+
310
+ jwt.value = null;
311
+ deviceId.value = null;
312
+ deviceSecret.value = null;
313
+
314
+ sessionStorage.removeItem('jwt');
315
+ sessionStorage.removeItem('deviceId');
316
+ sessionStorage.removeItem('deviceSecret');
317
+ }
318
+
319
+ return { isLoggedIn, login, logout };
320
+ }
321
+ ```
322
+
323
+ ```ts
324
+ // composables/useApi.ts
325
+ import { SignedRequest } from '@zintrust/signer';
326
+
327
+ export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
328
+ const jwt = sessionStorage.getItem('jwt')!;
329
+ const deviceId = sessionStorage.getItem('deviceId')!;
330
+ const deviceSecret = sessionStorage.getItem('deviceSecret')!;
331
+
332
+ const method = (init.method ?? 'GET').toUpperCase();
333
+ const url = new URL(path, window.location.origin);
334
+ const body = typeof init.body === 'string' ? init.body : '';
335
+
336
+ const signed = await SignedRequest.createHeaders({
337
+ method,
338
+ url,
339
+ body,
340
+ keyId: deviceId,
341
+ secret: deviceSecret,
342
+ });
343
+
344
+ return fetch(url, {
345
+ ...init,
346
+ headers: {
347
+ 'Content-Type': 'application/json',
348
+ Authorization: `Bearer ${jwt}`,
349
+ 'x-zt-device-id': deviceId,
350
+ 'x-zt-timezone': Intl.DateTimeFormat().resolvedOptions().timeZone,
351
+ ...(init.headers as Record<string, string> | undefined),
352
+ ...signed,
353
+ },
354
+ });
355
+ }
356
+ ```
357
+
358
+ ```vue
359
+ <!-- components/LoginForm.vue -->
360
+ <script setup lang="ts">
361
+ import { ref } from 'vue';
362
+ import { useAuth } from '@/composables/useAuth';
363
+ import { useRouter } from 'vue-router';
364
+
365
+ const { login } = useAuth();
366
+ const router = useRouter();
367
+
368
+ const email = ref('');
369
+ const password = ref('');
370
+ const error = ref('');
371
+ const loading = ref(false);
372
+
373
+ async function handleSubmit() {
374
+ error.value = '';
375
+ loading.value = true;
376
+ try {
377
+ await login(email.value, password.value);
378
+ await router.push('/dashboard');
379
+ } catch {
380
+ error.value = 'Invalid email or password.';
381
+ } finally {
382
+ loading.value = false;
383
+ }
384
+ }
385
+ </script>
386
+
387
+ <template>
388
+ <form @submit.prevent="handleSubmit">
389
+ <input v-model="email" type="email" placeholder="Email" required />
390
+ <input v-model="password" type="password" placeholder="Password" required />
391
+ <p v-if="error" class="error">{{ error }}</p>
392
+ <button type="submit" :disabled="loading">
393
+ {{ loading ? 'Signing in…' : 'Sign in' }}
394
+ </button>
395
+ </form>
396
+ </template>
397
+ ```
398
+
399
+ ```vue
400
+ <!-- components/ProfileCard.vue — example of a signed API call -->
401
+ <script setup lang="ts">
402
+ import { ref, onMounted } from 'vue';
403
+ import { apiFetch } from '@/composables/useApi';
404
+
405
+ interface Profile {
406
+ id: string;
407
+ email: string;
408
+ role: string;
409
+ }
410
+
411
+ const profile = ref<Profile | null>(null);
412
+ const error = ref('');
413
+
414
+ onMounted(async () => {
415
+ const res = await apiFetch('/api/me');
416
+ if (res.ok) {
417
+ profile.value = (await res.json()) as Profile;
418
+ } else {
419
+ error.value = 'Failed to load profile.';
420
+ }
421
+ });
422
+ </script>
423
+
424
+ <template>
425
+ <div v-if="profile">
426
+ <p>{{ profile.email }} ({{ profile.role }})</p>
427
+ </div>
428
+ <p v-else-if="error">{{ error }}</p>
429
+ <p v-else>Loading…</p>
430
+ </template>
431
+ ```
432
+
433
+ ---
434
+
435
+ ## Node.js / server-to-server example
436
+
437
+ ```ts
438
+ import { SignedRequest } from '@zintrust/signer';
439
+
440
+ const secret = process.env.API_SIGNING_SECRET!;
441
+ const keyId = process.env.API_KEY_ID!;
442
+ const jwt = process.env.SERVICE_JWT!;
443
+
444
+ async function signedFetch(url: string, init: RequestInit = {}) {
445
+ const method = (init.method ?? 'GET').toUpperCase();
446
+ const body = typeof init.body === 'string' ? init.body : '';
447
+
448
+ const signed = await SignedRequest.createHeaders({
449
+ method,
450
+ url: new URL(url),
451
+ body,
452
+ keyId,
453
+ secret,
454
+ });
455
+
456
+ return fetch(url, {
457
+ ...init,
458
+ headers: {
459
+ 'Content-Type': 'application/json',
460
+ Authorization: `Bearer ${jwt}`,
461
+ ...signed,
462
+ },
463
+ });
464
+ }
465
+
466
+ const res = await signedFetch('https://api.example.com/internal/sync', {
467
+ method: 'POST',
468
+ body: JSON.stringify({ action: 'sync' }),
469
+ });
470
+ ```
471
+
472
+ ---
473
+
474
+ ## Cloudflare Workers example
475
+
476
+ ```ts
477
+ import { SignedRequest } from '@zintrust/signer';
478
+
479
+ export default {
480
+ async fetch(request: Request, env: Env): Promise<Response> {
481
+ const result = await SignedRequest.verify({
482
+ method: request.method,
483
+ url: request.url,
484
+ body: await request.clone().text(),
485
+ headers: request.headers,
486
+ getSecretForKeyId: async (keyId) => {
487
+ return (await env.KV.get(`signing_secret:${keyId}`)) ?? undefined;
488
+ },
489
+ windowMs: 30_000,
490
+ });
491
+
492
+ if (!result.ok) {
493
+ return Response.json({ error: result.code }, { status: 401 });
494
+ }
495
+
496
+ return Response.json({ keyId: result.keyId });
497
+ },
498
+ };
499
+ ```
500
+
501
+ ---
502
+
503
+ ## Nonce replay protection
504
+
505
+ The `verifyNonce` hook lets you plug in any store. Example using an in-memory `Map` (single instance only — use Redis/KV for multi-instance):
506
+
507
+ ```ts
508
+ const seenNonces = new Map<string, number>();
509
+
510
+ const result = await SignedRequest.verify({
511
+ // ...
512
+ verifyNonce: async (keyId, nonce, ttlMs) => {
513
+ const key = `${keyId}:${nonce}`;
514
+ if (seenNonces.has(key)) return false; // replayed
515
+ seenNonces.set(key, Date.now() + ttlMs);
516
+ return true;
517
+ },
518
+ });
519
+ ```
520
+
521
+ For multi-instance deployments, use a Redis/KV SET NX with TTL:
522
+
523
+ ```ts
524
+ verifyNonce: async (keyId, nonce, ttlMs) => {
525
+ const key = `nonce:${keyId}:${nonce}`;
526
+ const set = await redis.set(key, '1', 'PX', ttlMs, 'NX');
527
+ return set === 'OK';
528
+ },
529
+ ```
530
+
531
+ ---
532
+
533
+ ## Security notes
534
+
535
+ - **Secrets** should be at least 32 random bytes. Generate one with:
536
+ ```bash
537
+ node -e "console.log('base64:' + require('crypto').randomBytes(32).toString('base64'))"
538
+ # or with the ZinTrust CLI:
539
+ zin key:bulletproof
540
+ ```
541
+ - **Replay window** defaults to 60 seconds. Reduce for stricter security; increase if clients have clock skew issues.
542
+ - **Nonce replay protection** requires a shared store (Redis/KV) when running multiple instances.
543
+ - All HMAC comparisons use a timing-safe equality check to prevent timing attacks.
544
+
545
+ ---
546
+
547
+ ## Runtime requirements
548
+
549
+ | Runtime | Minimum version | Notes |
550
+ | ------------------ | ------------------------------------- | ----------------------------------- |
551
+ | Node.js | 20.0.0 | `globalThis.crypto.subtle` built-in |
552
+ | Bun | Any | WebCrypto built-in |
553
+ | Cloudflare Workers | Any | WebCrypto built-in |
554
+ | Browsers | Chrome 37+ / Firefox 34+ / Safari 11+ | WebCrypto available since 2014 |
555
+ | Deno | Any | WebCrypto built-in |
556
+
557
+ ---
558
+
559
+ ## License
560
+
561
+ MIT — part of the [ZinTrust](https://github.com/ZinTrust/zintrust) framework.
@@ -0,0 +1,53 @@
1
+ export type SignedRequestHeaders = {
2
+ 'x-zt-key-id': string;
3
+ 'x-zt-timestamp': string;
4
+ 'x-zt-nonce': string;
5
+ 'x-zt-body-sha256': string;
6
+ 'x-zt-signature': string;
7
+ };
8
+ export type SignedRequestCreateHeadersParams = {
9
+ method: string;
10
+ url: string | URL;
11
+ body?: string | Uint8Array | null;
12
+ keyId: string;
13
+ secret: string;
14
+ timestampMs?: number;
15
+ nonce?: string;
16
+ };
17
+ export type SignedRequestVerifyParams = {
18
+ method: string;
19
+ url: string | URL;
20
+ body?: string | Uint8Array | null;
21
+ headers: Headers | Record<string, string | undefined>;
22
+ getSecretForKeyId: (keyId: string) => string | undefined | Promise<string | undefined>;
23
+ nowMs?: number;
24
+ windowMs?: number;
25
+ /**
26
+ * Optional replay protection hook.
27
+ * Return true if the nonce is accepted and stored; false if replayed/invalid.
28
+ */
29
+ verifyNonce?: (keyId: string, nonce: string, ttlMs: number) => Promise<boolean>;
30
+ };
31
+ export type SignedRequestVerifyResult = {
32
+ ok: true;
33
+ keyId: string;
34
+ timestampMs: number;
35
+ nonce: string;
36
+ } | {
37
+ ok: false;
38
+ code: 'MISSING_HEADER' | 'INVALID_TIMESTAMP' | 'EXPIRED' | 'INVALID_BODY_SHA' | 'INVALID_SIGNATURE' | 'UNKNOWN_KEY' | 'REPLAYED';
39
+ message: string;
40
+ };
41
+ export declare const SignedRequest: Readonly<{
42
+ sha256Hex: (data: string | Uint8Array) => Promise<string>;
43
+ canonicalString: (params: {
44
+ method: string;
45
+ url: string | URL;
46
+ timestampMs: number;
47
+ nonce: string;
48
+ bodySha256Hex: string;
49
+ }) => string;
50
+ createHeaders(params: SignedRequestCreateHeadersParams): Promise<SignedRequestHeaders>;
51
+ verify(params: SignedRequestVerifyParams): Promise<SignedRequestVerifyResult>;
52
+ }>;
53
+ export default SignedRequest;
@@ -0,0 +1,171 @@
1
+ const getHeader = (headers, name) => {
2
+ if (typeof headers.get === 'function') {
3
+ const value = headers.get(name);
4
+ return value ?? undefined;
5
+ }
6
+ return headers[name];
7
+ };
8
+ const timingSafeEquals = (a, b) => {
9
+ if (a.length !== b.length)
10
+ return false;
11
+ let result = 0;
12
+ for (let i = 0; i < a.length; i++) {
13
+ result |= (a.codePointAt(i) ?? 0) ^ (b.codePointAt(i) ?? 0);
14
+ }
15
+ return result === 0;
16
+ };
17
+ const getCrypto = () => {
18
+ if (typeof crypto === 'undefined' || crypto.subtle === undefined) {
19
+ // eslint-disable-next-line no-restricted-syntax
20
+ throw new Error('WebCrypto is not available in this runtime');
21
+ }
22
+ return crypto;
23
+ };
24
+ const getSubtle = () => getCrypto().subtle;
25
+ const toBytes = (data) => {
26
+ const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
27
+ return new Uint8Array(bytes);
28
+ };
29
+ const toHex = (bytes) => {
30
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
31
+ let out = '';
32
+ for (const element of view) {
33
+ out += element.toString(16).padStart(2, '0');
34
+ }
35
+ return out;
36
+ };
37
+ const sha256Hex = async (data) => {
38
+ const digest = await getSubtle().digest('SHA-256', toBytes(data));
39
+ return toHex(digest);
40
+ };
41
+ const canonicalString = (params) => {
42
+ const u = typeof params.url === 'string' ? new URL(params.url) : params.url;
43
+ const method = params.method.toUpperCase();
44
+ return [
45
+ method,
46
+ u.pathname,
47
+ u.search,
48
+ String(params.timestampMs),
49
+ params.nonce,
50
+ params.bodySha256Hex,
51
+ ].join('\n');
52
+ };
53
+ export const SignedRequest = Object.freeze({
54
+ sha256Hex,
55
+ canonicalString,
56
+ async createHeaders(params) {
57
+ const timestampMs = params.timestampMs ?? Date.now();
58
+ const webCrypto = getCrypto();
59
+ const nonce = params.nonce ??
60
+ (typeof webCrypto.randomUUID === 'function'
61
+ ? webCrypto.randomUUID()
62
+ : toHex(webCrypto.getRandomValues(new Uint8Array(16))));
63
+ const body = params.body ?? '';
64
+ const bodySha = await sha256Hex(body);
65
+ const canonical = canonicalString({
66
+ method: params.method,
67
+ url: params.url,
68
+ timestampMs,
69
+ nonce,
70
+ bodySha256Hex: bodySha,
71
+ });
72
+ const subtle = getSubtle();
73
+ const key = await subtle.importKey('raw', toBytes(params.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
74
+ const signatureBytes = await subtle.sign('HMAC', key, toBytes(canonical));
75
+ const signature = toHex(signatureBytes);
76
+ return {
77
+ 'x-zt-key-id': params.keyId,
78
+ 'x-zt-timestamp': String(timestampMs),
79
+ 'x-zt-nonce': nonce,
80
+ 'x-zt-body-sha256': bodySha,
81
+ 'x-zt-signature': signature,
82
+ };
83
+ },
84
+ async verify(params) {
85
+ const parsed = parseAndValidateHeaders(params.headers);
86
+ if (!parsed.ok)
87
+ return parsed;
88
+ const { keyId, timestampMs, nonce, bodySha, signature } = parsed;
89
+ const nowMs = params.nowMs ?? Date.now();
90
+ const windowMs = params.windowMs ?? 60_000;
91
+ const windowFail = validateTimestampWindow({ nowMs, timestampMs, windowMs });
92
+ if (windowFail)
93
+ return windowFail;
94
+ const bodyFail = await validateBodyHash({ body: params.body ?? '', bodyShaHeader: bodySha });
95
+ if (bodyFail)
96
+ return bodyFail;
97
+ const secret = await params.getSecretForKeyId(keyId);
98
+ if (secret === undefined || secret.trim() === '') {
99
+ return { ok: false, code: 'UNKNOWN_KEY', message: 'Unknown key id' };
100
+ }
101
+ const sigFail = await validateSignature({
102
+ method: params.method,
103
+ url: params.url,
104
+ timestampMs,
105
+ nonce,
106
+ bodySha,
107
+ signature,
108
+ secret,
109
+ });
110
+ if (sigFail)
111
+ return sigFail;
112
+ if (params.verifyNonce !== undefined) {
113
+ const ok = await params.verifyNonce(keyId, nonce, windowMs);
114
+ if (!ok) {
115
+ return { ok: false, code: 'REPLAYED', message: 'Nonce replayed or rejected' };
116
+ }
117
+ }
118
+ return { ok: true, keyId, timestampMs, nonce };
119
+ },
120
+ });
121
+ const parseAndValidateHeaders = (headers) => {
122
+ const keyId = getHeader(headers, 'x-zt-key-id');
123
+ const ts = getHeader(headers, 'x-zt-timestamp');
124
+ const nonce = getHeader(headers, 'x-zt-nonce');
125
+ const bodySha = getHeader(headers, 'x-zt-body-sha256');
126
+ const signature = getHeader(headers, 'x-zt-signature');
127
+ if (keyId === undefined ||
128
+ ts === undefined ||
129
+ nonce === undefined ||
130
+ bodySha === undefined ||
131
+ signature === undefined) {
132
+ return { ok: false, code: 'MISSING_HEADER', message: 'Missing required signing headers' };
133
+ }
134
+ const timestampMs = Number.parseInt(ts, 10);
135
+ if (!Number.isFinite(timestampMs)) {
136
+ return { ok: false, code: 'INVALID_TIMESTAMP', message: 'Invalid x-zt-timestamp' };
137
+ }
138
+ return { ok: true, keyId, timestampMs, nonce, bodySha, signature };
139
+ };
140
+ const validateTimestampWindow = (params) => {
141
+ const diff = Math.abs(params.nowMs - params.timestampMs);
142
+ if (!Number.isFinite(diff) || diff > Math.max(1, params.windowMs)) {
143
+ return { ok: false, code: 'EXPIRED', message: 'Request timestamp outside allowed window' };
144
+ }
145
+ return null;
146
+ };
147
+ const validateBodyHash = async (params) => {
148
+ const computed = await sha256Hex(params.body);
149
+ if (!timingSafeEquals(computed, params.bodyShaHeader)) {
150
+ return { ok: false, code: 'INVALID_BODY_SHA', message: 'Invalid body hash' };
151
+ }
152
+ return null;
153
+ };
154
+ const validateSignature = async (params) => {
155
+ const canonical = canonicalString({
156
+ method: params.method,
157
+ url: params.url,
158
+ timestampMs: params.timestampMs,
159
+ nonce: params.nonce,
160
+ bodySha256Hex: params.bodySha,
161
+ });
162
+ const subtle = getSubtle();
163
+ const key = await subtle.importKey('raw', toBytes(params.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
164
+ const signatureBytes = await subtle.sign('HMAC', key, toBytes(canonical));
165
+ const computed = toHex(signatureBytes);
166
+ if (!timingSafeEquals(computed, params.signature)) {
167
+ return { ok: false, code: 'INVALID_SIGNATURE', message: 'Invalid signature' };
168
+ }
169
+ return null;
170
+ };
171
+ export default SignedRequest;
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@zintrust/signer",
3
+ "version": "0.1.47",
4
+ "buildDate": "2026-02-23T16:21:42.488Z",
5
+ "buildEnvironment": {
6
+ "node": "v20.20.0",
7
+ "platform": "linux",
8
+ "arch": "x64"
9
+ },
10
+ "git": {
11
+ "commit": "16b342c",
12
+ "branch": "master"
13
+ },
14
+ "package": {
15
+ "engines": {
16
+ "node": ">=20.0.0"
17
+ },
18
+ "dependencies": [],
19
+ "peerDependencies": []
20
+ },
21
+ "files": {
22
+ "SignedRequest.d.ts": {
23
+ "size": 1750,
24
+ "sha256": "d308d63499f3b7298581c14f21d5d6f9299ac1c68e31c10256c50da7381b597b"
25
+ },
26
+ "SignedRequest.js": {
27
+ "size": 6462,
28
+ "sha256": "d77715dbaba201311c4b42543d30e03a71a97bdffc8e64286de23dd792a68353"
29
+ },
30
+ "index.d.ts": {
31
+ "size": 180,
32
+ "sha256": "c06c81a970e75623446631798b080b4224efb4900992eec411a9ac468c6f3773"
33
+ },
34
+ "index.js": {
35
+ "size": 225,
36
+ "sha256": "26dde35f7583af546af97eda4696868f7d71e6b613bd9e14fc36bfd77f686aa1"
37
+ }
38
+ }
39
+ }
@@ -0,0 +1 @@
1
+ export { SignedRequest, type SignedRequestCreateHeadersParams, type SignedRequestHeaders, type SignedRequestVerifyParams, type SignedRequestVerifyResult, } from './SignedRequest';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { SignedRequest, } from './SignedRequest';
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@zintrust/signer",
3
+ "version": "0.1.49",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
+ }
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20.0.0"
16
+ },
17
+ "scripts": {
18
+ "build": "tsc -p tsconfig.json",
19
+ "type-check": "tsc -p tsconfig.json --noEmit"
20
+ },
21
+ "peerDependencies": {
22
+ "@zintrust/core": "^0.1.49"
23
+ }
24
+ }