@infernetprotocol/auth 0.1.22
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 +15 -0
- package/package.json +29 -0
- package/src/index.js +14 -0
- package/src/keys.js +53 -0
- package/src/nostr.js +107 -0
- package/src/sig.js +43 -0
- package/src/signed-request.js +195 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Infernet Protocol
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
10
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
11
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
12
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
13
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
14
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
15
|
+
PERFORMANCE OF THIS SOFTWARE.
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@infernetprotocol/auth",
|
|
3
|
+
"version": "0.1.22",
|
|
4
|
+
"description": "Nostr-based authentication helpers for the Infernet Protocol.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./src/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js",
|
|
10
|
+
"./nostr": "./src/nostr.js"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src/**/*.js",
|
|
14
|
+
"README.md"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/profullstack/infernet-protocol.git",
|
|
22
|
+
"directory": "packages/auth"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/profullstack/infernet-protocol#readme",
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@noble/curves": "^2.2.0",
|
|
27
|
+
"@noble/hashes": "^2.2.0"
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @infernetprotocol/auth — Nostr identity + signed-request primitives.
|
|
3
|
+
*
|
|
4
|
+
* - `keys` : secp256k1 / BIP-340 key generation + derivation.
|
|
5
|
+
* - `sig` : Schnorr sign / verify over arbitrary messages.
|
|
6
|
+
* - `signed-request` : HTTP envelope that lets a node prove ownership of a
|
|
7
|
+
* Nostr pubkey on every request without sharing a DB credential.
|
|
8
|
+
* - `nostr` : legacy browser-extension helpers (NIP-07). Kept for the web UI.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export * from './keys.js';
|
|
12
|
+
export * from './sig.js';
|
|
13
|
+
export * from './signed-request.js';
|
|
14
|
+
export * from './nostr.js';
|
package/src/keys.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Nostr key helpers — real secp256k1 / BIP-340 derivation.
|
|
3
|
+
*
|
|
4
|
+
* Nostr (NIP-01) uses x-only Schnorr pubkeys over secp256k1: the private key
|
|
5
|
+
* is 32 random bytes, the public key is the x-coordinate of `priv * G`
|
|
6
|
+
* encoded as 32 bytes (64 hex chars). This module wraps @noble/curves so the
|
|
7
|
+
* rest of the codebase can treat keys as 64-hex-char strings.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
11
|
+
import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils.js';
|
|
12
|
+
|
|
13
|
+
const HEX64 = /^[0-9a-fA-F]{64}$/;
|
|
14
|
+
|
|
15
|
+
export function isHex64(value) {
|
|
16
|
+
return typeof value === 'string' && HEX64.test(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Generate a fresh Nostr keypair.
|
|
21
|
+
* @returns {{ publicKey: string, privateKey: string }} hex-encoded
|
|
22
|
+
*/
|
|
23
|
+
export function generateKeyPair() {
|
|
24
|
+
const privBytes = randomBytes(32);
|
|
25
|
+
const privateKey = bytesToHex(privBytes);
|
|
26
|
+
const publicKey = bytesToHex(schnorr.getPublicKey(privBytes));
|
|
27
|
+
return { publicKey, privateKey };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Derive the x-only Schnorr pubkey for a given hex privkey.
|
|
32
|
+
* @param {string} privateKey hex (64 chars)
|
|
33
|
+
* @returns {string} hex (64 chars)
|
|
34
|
+
*/
|
|
35
|
+
export function derivePublicKey(privateKey) {
|
|
36
|
+
if (!isHex64(privateKey)) {
|
|
37
|
+
throw new Error('privateKey must be 64 hex characters');
|
|
38
|
+
}
|
|
39
|
+
return bytesToHex(schnorr.getPublicKey(hexToBytes(privateKey)));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Check that a given (pubkey, privkey) pair is internally consistent —
|
|
44
|
+
* i.e. the pubkey really is the Schnorr pubkey of the privkey.
|
|
45
|
+
*/
|
|
46
|
+
export function keyPairIsValid(publicKey, privateKey) {
|
|
47
|
+
if (!isHex64(publicKey) || !isHex64(privateKey)) return false;
|
|
48
|
+
try {
|
|
49
|
+
return derivePublicKey(privateKey) === publicKey.toLowerCase();
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/nostr.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Nostr Authentication Utilities
|
|
3
|
+
*
|
|
4
|
+
* This module provides functions for authenticating users via Nostr protocol
|
|
5
|
+
* using browser extensions like nos2x-fox or other Nostr clients.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// Check if Nostr extension is available in the browser environment
|
|
9
|
+
export const checkNostrAvailability = async () => {
|
|
10
|
+
// For browser environments
|
|
11
|
+
if (typeof window !== 'undefined') {
|
|
12
|
+
// Check for window.nostr (NIP-07 compliant extensions)
|
|
13
|
+
return !!window.nostr;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// For React Native, we'll need to use a different approach
|
|
17
|
+
// This will be handled in the platform-specific implementations
|
|
18
|
+
return false;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// Get the public key from Nostr extension
|
|
22
|
+
export const getNostrPublicKey = async () => {
|
|
23
|
+
if (typeof window !== 'undefined' && window.nostr) {
|
|
24
|
+
try {
|
|
25
|
+
// Request public key from the extension (NIP-07)
|
|
26
|
+
const publicKey = await window.nostr.getPublicKey();
|
|
27
|
+
return { success: true, publicKey };
|
|
28
|
+
} catch (error) {
|
|
29
|
+
console.error('Error getting Nostr public key:', error);
|
|
30
|
+
return { success: false, error: error.message || 'Failed to get public key' };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return { success: false, error: 'Nostr extension not available' };
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// Sign an event with Nostr extension
|
|
38
|
+
export const signWithNostr = async (event) => {
|
|
39
|
+
if (typeof window !== 'undefined' && window.nostr) {
|
|
40
|
+
try {
|
|
41
|
+
// Sign the event with the extension (NIP-07)
|
|
42
|
+
const signedEvent = await window.nostr.signEvent(event);
|
|
43
|
+
return { success: true, signedEvent };
|
|
44
|
+
} catch (error) {
|
|
45
|
+
console.error('Error signing with Nostr:', error);
|
|
46
|
+
return { success: false, error: error.message || 'Failed to sign event' };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return { success: false, error: 'Nostr extension not available' };
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Create a challenge event for authentication
|
|
54
|
+
export const createAuthChallenge = (serverPublicKey) => {
|
|
55
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
kind: 22242, // Custom kind for auth challenge
|
|
59
|
+
created_at: timestamp,
|
|
60
|
+
tags: [
|
|
61
|
+
['p', serverPublicKey], // Server's public key
|
|
62
|
+
['challenge', `auth-${timestamp}`], // Unique challenge
|
|
63
|
+
],
|
|
64
|
+
content: 'Authenticate with Infernet Protocol',
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// Verify a Nostr public key against the Supabase `users` table
|
|
69
|
+
export const verifyNostrAuth = async (supabase, publicKey, signedEvent) => {
|
|
70
|
+
try {
|
|
71
|
+
const { data, error } = await supabase
|
|
72
|
+
.from('users')
|
|
73
|
+
.select('*')
|
|
74
|
+
.eq('nostr_public_key', publicKey)
|
|
75
|
+
.maybeSingle();
|
|
76
|
+
|
|
77
|
+
if (error) throw error;
|
|
78
|
+
if (!data) {
|
|
79
|
+
return { success: false, error: 'Unknown Nostr public key' };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Signature verification should be performed by the caller (e.g. a Next.js
|
|
83
|
+
// route handler) before this function is invoked — this helper only
|
|
84
|
+
// resolves the Nostr pubkey to a Supabase user row.
|
|
85
|
+
return { success: true, authData: { user: data, signedEvent } };
|
|
86
|
+
} catch (error) {
|
|
87
|
+
console.error('Error verifying Nostr auth with Supabase:', error);
|
|
88
|
+
return { success: false, error: error.message || 'Authentication failed' };
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// Register a new user with a Nostr public key
|
|
93
|
+
export const registerWithNostr = async (supabase, publicKey, userData) => {
|
|
94
|
+
try {
|
|
95
|
+
const { data, error } = await supabase
|
|
96
|
+
.from('users')
|
|
97
|
+
.insert({ nostr_public_key: publicKey, ...userData })
|
|
98
|
+
.select()
|
|
99
|
+
.single();
|
|
100
|
+
|
|
101
|
+
if (error) throw error;
|
|
102
|
+
return { success: true, user: data };
|
|
103
|
+
} catch (error) {
|
|
104
|
+
console.error('Error registering with Nostr:', error);
|
|
105
|
+
return { success: false, error: error.message || 'Registration failed' };
|
|
106
|
+
}
|
|
107
|
+
};
|
package/src/sig.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schnorr (BIP-340) sign / verify over arbitrary byte strings.
|
|
3
|
+
*
|
|
4
|
+
* We hash the message to 32 bytes with SHA-256 before handing it to
|
|
5
|
+
* @noble/curves so callers can pass anything (UTF-8 strings, JSON blobs,
|
|
6
|
+
* raw buffers). This matches the NIP-01 event-id convention.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
10
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
11
|
+
import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
|
|
12
|
+
|
|
13
|
+
function toBytes(message) {
|
|
14
|
+
if (message instanceof Uint8Array) return message;
|
|
15
|
+
if (typeof message === 'string') return new TextEncoder().encode(message);
|
|
16
|
+
throw new Error('message must be a string or Uint8Array');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Sign a message with a hex-encoded private key. Returns a 64-byte Schnorr
|
|
21
|
+
* signature as 128-char hex.
|
|
22
|
+
*/
|
|
23
|
+
export function signMessage(message, privateKeyHex) {
|
|
24
|
+
const digest = sha256(toBytes(message));
|
|
25
|
+
const sigBytes = schnorr.sign(digest, hexToBytes(privateKeyHex));
|
|
26
|
+
return bytesToHex(sigBytes);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Verify a Schnorr signature over a message.
|
|
31
|
+
* @param {string|Uint8Array} message
|
|
32
|
+
* @param {string} signatureHex 128 hex chars (64 bytes)
|
|
33
|
+
* @param {string} publicKeyHex 64 hex chars (x-only)
|
|
34
|
+
* @returns {boolean}
|
|
35
|
+
*/
|
|
36
|
+
export function verifyMessage(message, signatureHex, publicKeyHex) {
|
|
37
|
+
try {
|
|
38
|
+
const digest = sha256(toBytes(message));
|
|
39
|
+
return schnorr.verify(hexToBytes(signatureHex), digest, hexToBytes(publicKeyHex));
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Signed HTTP request envelope — lets a node prove ownership of a Nostr
|
|
3
|
+
* pubkey without ever handing a DB credential to the control plane.
|
|
4
|
+
*
|
|
5
|
+
* Protocol:
|
|
6
|
+
* - The client computes a canonical string:
|
|
7
|
+
* `${method}\n${path}\n${created_at}\n${nonce}\n${sha256_hex(body)}`
|
|
8
|
+
* - Signs it with Schnorr (BIP-340) using the node's 32-byte Nostr privkey.
|
|
9
|
+
* - Attaches an `X-Infernet-Auth` header with base64url-encoded JSON:
|
|
10
|
+
* { v, pubkey, created_at, nonce, sig }
|
|
11
|
+
*
|
|
12
|
+
* The server verifies:
|
|
13
|
+
* 1. `v === 1`
|
|
14
|
+
* 2. `created_at` is within +/- REPLAY_WINDOW_SECONDS of now
|
|
15
|
+
* 3. `nonce` has not been seen before (caller-provided replay cache)
|
|
16
|
+
* 4. signature is valid for (method, path, created_at, nonce, sha256(body))
|
|
17
|
+
* 5. `pubkey` is authorized for the target resource (caller check)
|
|
18
|
+
*
|
|
19
|
+
* `path` must be the request path + query (e.g. `/api/v1/node/heartbeat`),
|
|
20
|
+
* not the full URL, so proxies rewriting hostnames don't break the sig.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
24
|
+
import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils.js';
|
|
25
|
+
|
|
26
|
+
import { signMessage, verifyMessage } from './sig.js';
|
|
27
|
+
import { isHex64 } from './keys.js';
|
|
28
|
+
|
|
29
|
+
export const AUTH_HEADER = 'x-infernet-auth';
|
|
30
|
+
export const ENVELOPE_VERSION = 1;
|
|
31
|
+
export const REPLAY_WINDOW_SECONDS = 60;
|
|
32
|
+
|
|
33
|
+
function utf8(value) {
|
|
34
|
+
return new TextEncoder().encode(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function sha256Hex(bytes) {
|
|
38
|
+
return bytesToHex(sha256(bytes));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function canonicalString({ method, path, createdAt, nonce, bodyHashHex }) {
|
|
42
|
+
return `${method.toUpperCase()}\n${path}\n${createdAt}\n${nonce}\n${bodyHashHex}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function base64urlEncode(bytes) {
|
|
46
|
+
return Buffer.from(bytes).toString('base64')
|
|
47
|
+
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function base64urlDecode(str) {
|
|
51
|
+
const pad = '='.repeat((4 - (str.length % 4)) % 4);
|
|
52
|
+
const b64 = (str + pad).replace(/-/g, '+').replace(/_/g, '/');
|
|
53
|
+
return new Uint8Array(Buffer.from(b64, 'base64'));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Create a signed-request header + body-hash pair. Returns { header, bodyHashHex }.
|
|
58
|
+
*
|
|
59
|
+
* @param {Object} opts
|
|
60
|
+
* @param {string} opts.method - HTTP method
|
|
61
|
+
* @param {string} opts.path - request path + query string
|
|
62
|
+
* @param {string} opts.body - request body as a string (use '' for GET)
|
|
63
|
+
* @param {string} opts.privateKey - 64-char hex Nostr privkey
|
|
64
|
+
* @param {string} opts.publicKey - 64-char hex Nostr pubkey (x-only)
|
|
65
|
+
*/
|
|
66
|
+
export function signRequest({ method, path, body, privateKey, publicKey }) {
|
|
67
|
+
if (!isHex64(privateKey) || !isHex64(publicKey)) {
|
|
68
|
+
throw new Error('privateKey and publicKey must be 64 hex characters');
|
|
69
|
+
}
|
|
70
|
+
const createdAt = Math.floor(Date.now() / 1000);
|
|
71
|
+
const nonce = bytesToHex(randomBytes(16));
|
|
72
|
+
const bodyBytes = typeof body === 'string' ? utf8(body) : (body ?? new Uint8Array(0));
|
|
73
|
+
const bodyHashHex = sha256Hex(bodyBytes);
|
|
74
|
+
|
|
75
|
+
const canonical = canonicalString({ method, path, createdAt, nonce, bodyHashHex });
|
|
76
|
+
const sig = signMessage(canonical, privateKey);
|
|
77
|
+
|
|
78
|
+
const envelope = {
|
|
79
|
+
v: ENVELOPE_VERSION,
|
|
80
|
+
pubkey: publicKey.toLowerCase(),
|
|
81
|
+
created_at: createdAt,
|
|
82
|
+
nonce,
|
|
83
|
+
sig
|
|
84
|
+
};
|
|
85
|
+
const header = base64urlEncode(utf8(JSON.stringify(envelope)));
|
|
86
|
+
return { header, bodyHashHex };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Parse the X-Infernet-Auth header. Throws on structural problems.
|
|
91
|
+
*/
|
|
92
|
+
export function parseAuthHeader(headerValue) {
|
|
93
|
+
if (!headerValue || typeof headerValue !== 'string') {
|
|
94
|
+
throw new Error('missing X-Infernet-Auth header');
|
|
95
|
+
}
|
|
96
|
+
let json;
|
|
97
|
+
try {
|
|
98
|
+
json = JSON.parse(Buffer.from(base64urlDecode(headerValue)).toString('utf8'));
|
|
99
|
+
} catch (err) {
|
|
100
|
+
throw new Error(`invalid X-Infernet-Auth envelope: ${err?.message ?? err}`);
|
|
101
|
+
}
|
|
102
|
+
if (json?.v !== ENVELOPE_VERSION) {
|
|
103
|
+
throw new Error(`unsupported envelope version: ${json?.v}`);
|
|
104
|
+
}
|
|
105
|
+
if (!isHex64(json.pubkey)) {
|
|
106
|
+
throw new Error('envelope pubkey must be 64 hex chars');
|
|
107
|
+
}
|
|
108
|
+
if (typeof json.created_at !== 'number') {
|
|
109
|
+
throw new Error('envelope created_at must be a number');
|
|
110
|
+
}
|
|
111
|
+
if (typeof json.nonce !== 'string' || json.nonce.length === 0) {
|
|
112
|
+
throw new Error('envelope nonce must be a non-empty string');
|
|
113
|
+
}
|
|
114
|
+
if (typeof json.sig !== 'string' || json.sig.length !== 128) {
|
|
115
|
+
throw new Error('envelope sig must be a 128-char hex string');
|
|
116
|
+
}
|
|
117
|
+
return json;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Verify a signed request. Returns { ok: true, pubkey } on success or
|
|
122
|
+
* { ok: false, error } on failure.
|
|
123
|
+
*
|
|
124
|
+
* The caller is responsible for:
|
|
125
|
+
* - de-duplicating `nonce` values (replay cache)
|
|
126
|
+
* - authorizing `pubkey` against the target resource
|
|
127
|
+
*
|
|
128
|
+
* @param {Object} opts
|
|
129
|
+
* @param {string} opts.method
|
|
130
|
+
* @param {string} opts.path
|
|
131
|
+
* @param {string|Uint8Array} opts.body - exact bytes the client sent
|
|
132
|
+
* @param {string} opts.headerValue - value of X-Infernet-Auth
|
|
133
|
+
* @param {number} [opts.now] - override current time (seconds) for tests
|
|
134
|
+
*/
|
|
135
|
+
export function verifySignedRequest({ method, path, body, headerValue, now }) {
|
|
136
|
+
let env;
|
|
137
|
+
try {
|
|
138
|
+
env = parseAuthHeader(headerValue);
|
|
139
|
+
} catch (err) {
|
|
140
|
+
return { ok: false, error: err.message };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const nowSec = Number.isFinite(now) ? now : Math.floor(Date.now() / 1000);
|
|
144
|
+
const skew = Math.abs(nowSec - env.created_at);
|
|
145
|
+
if (skew > REPLAY_WINDOW_SECONDS) {
|
|
146
|
+
return { ok: false, error: `timestamp outside replay window (skew=${skew}s)` };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const bodyBytes = typeof body === 'string'
|
|
150
|
+
? utf8(body)
|
|
151
|
+
: (body instanceof Uint8Array ? body : new Uint8Array(0));
|
|
152
|
+
const bodyHashHex = sha256Hex(bodyBytes);
|
|
153
|
+
|
|
154
|
+
const canonical = canonicalString({
|
|
155
|
+
method,
|
|
156
|
+
path,
|
|
157
|
+
createdAt: env.created_at,
|
|
158
|
+
nonce: env.nonce,
|
|
159
|
+
bodyHashHex
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
if (!verifyMessage(canonical, env.sig, env.pubkey)) {
|
|
163
|
+
return { ok: false, error: 'signature verification failed' };
|
|
164
|
+
}
|
|
165
|
+
return { ok: true, pubkey: env.pubkey, nonce: env.nonce, createdAt: env.created_at };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* In-memory replay cache — LRU-ish Map keyed by nonce with a hard ceiling.
|
|
170
|
+
* For serverless/Next.js this is per-process; behind a load balancer you'd
|
|
171
|
+
* want to swap this for Redis / Supabase. Good enough for Phase 1.
|
|
172
|
+
*/
|
|
173
|
+
export class ReplayCache {
|
|
174
|
+
constructor({ max = 10_000, ttlSeconds = REPLAY_WINDOW_SECONDS * 2 } = {}) {
|
|
175
|
+
this.max = max;
|
|
176
|
+
this.ttlMs = ttlSeconds * 1000;
|
|
177
|
+
this.seen = new Map();
|
|
178
|
+
}
|
|
179
|
+
has(nonce) {
|
|
180
|
+
const expiresAt = this.seen.get(nonce);
|
|
181
|
+
if (!expiresAt) return false;
|
|
182
|
+
if (expiresAt < Date.now()) {
|
|
183
|
+
this.seen.delete(nonce);
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
add(nonce) {
|
|
189
|
+
if (this.seen.size >= this.max) {
|
|
190
|
+
const firstKey = this.seen.keys().next().value;
|
|
191
|
+
if (firstKey) this.seen.delete(firstKey);
|
|
192
|
+
}
|
|
193
|
+
this.seen.set(nonce, Date.now() + this.ttlMs);
|
|
194
|
+
}
|
|
195
|
+
}
|