@7h3/protocol-pq 0.5.0 → 0.5.4

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.
@@ -1,66 +0,0 @@
1
- export type ProtocolVersion = '7h3/0.1';
2
- export type IntentKind = 'PING' | 'PONG' | 'CAPS' | 'TASK' | 'RESULT' | 'ERROR';
3
- export interface ProtocolHeader {
4
- version: ProtocolVersion;
5
- messageId: string;
6
- timestampMs: number;
7
- ttlMs: number;
8
- sender: string;
9
- recipient?: string;
10
- nonce: string;
11
- }
12
- export interface ProtocolBody {
13
- intent: IntentKind;
14
- content: string;
15
- capability?: string;
16
- correlationId?: string;
17
- }
18
- export interface ProtocolSignature {
19
- alg: 'HS256' | 'ED25519';
20
- keyId: string;
21
- value: string;
22
- }
23
- export interface ProtocolEnvelope {
24
- header: ProtocolHeader;
25
- body: ProtocolBody;
26
- signature?: ProtocolSignature;
27
- }
28
- export interface ProtocolDiagnostic {
29
- level: 'error' | 'warning';
30
- message: string;
31
- }
32
- export type SignatureVerificationMaterial = {
33
- alg: 'HS256';
34
- secret: string;
35
- } | {
36
- alg: 'ED25519';
37
- publicKey: string;
38
- };
39
- export declare function canonicalizeEnvelope(envelope: Omit<ProtocolEnvelope, 'signature'>): string;
40
- export declare function signCanonicalPayloadHmac(payload: string, secret: string): Promise<string>;
41
- export declare function verifyCanonicalPayloadHmac(payload: string, signature: string, secret: string): Promise<boolean>;
42
- export declare function generateEd25519KeypairBase64Url(): Promise<{
43
- publicKey: string;
44
- privateKey: string;
45
- }>;
46
- export declare function signCanonicalPayloadEd25519(payload: string, privateKeyPkcs8Base64Url: string): Promise<string>;
47
- export declare function verifyCanonicalPayloadEd25519(payload: string, signature: string, publicKeySpkiBase64Url: string): Promise<boolean>;
48
- export declare function signEnvelopeHmac(envelope: Omit<ProtocolEnvelope, 'signature'>, secret: string, keyId?: string): Promise<ProtocolEnvelope>;
49
- export declare function verifyEnvelopeHmac(envelope: ProtocolEnvelope, secret: string): Promise<boolean>;
50
- export declare function signEnvelopeEd25519(envelope: Omit<ProtocolEnvelope, 'signature'>, privateKeyPkcs8Base64Url: string, keyId?: string): Promise<ProtocolEnvelope>;
51
- export declare function verifyEnvelopeEd25519(envelope: ProtocolEnvelope, publicKeySpkiBase64Url: string): Promise<boolean>;
52
- export declare function verifyEnvelopeSignature(envelope: ProtocolEnvelope, material: SignatureVerificationMaterial): Promise<boolean>;
53
- export declare function verifyCanonicalPayloadSignature(payload: string, signature: ProtocolSignature | undefined, material: SignatureVerificationMaterial): Promise<boolean>;
54
- export declare function validateEnvelope(envelope: ProtocolEnvelope, nowMs?: number): ProtocolDiagnostic[];
55
- export declare function createEnvelope(input: {
56
- sender: string;
57
- recipient?: string;
58
- intent: IntentKind;
59
- content: string;
60
- capability?: string;
61
- correlationId?: string;
62
- ttlMs?: number;
63
- messageId?: string;
64
- nonce?: string;
65
- nowMs?: number;
66
- }): Omit<ProtocolEnvelope, 'signature'>;
@@ -1,294 +0,0 @@
1
- const textEncoder = new TextEncoder();
2
- const HMAC_KEY_CACHE_LIMIT = 256;
3
- const hmacKeyCache = new Map();
4
- const ED25519_KEY_CACHE_LIMIT = 256;
5
- const ed25519PrivateKeyCache = new Map();
6
- const ed25519PublicKeyCache = new Map();
7
- function getBufferLike() {
8
- const candidate = globalThis;
9
- return candidate.Buffer ?? null;
10
- }
11
- function serializeHeaderCanonical(header) {
12
- const parts = [
13
- `"messageId":${JSON.stringify(header.messageId)}`,
14
- `"nonce":${JSON.stringify(header.nonce)}`,
15
- ];
16
- if (header.recipient !== undefined) {
17
- parts.push(`"recipient":${JSON.stringify(header.recipient)}`);
18
- }
19
- parts.push(`"sender":${JSON.stringify(header.sender)}`);
20
- parts.push(`"timestampMs":${header.timestampMs}`);
21
- parts.push(`"ttlMs":${header.ttlMs}`);
22
- parts.push(`"version":${JSON.stringify(header.version)}`);
23
- return `{${parts.join(',')}}`;
24
- }
25
- function serializeBodyCanonical(body) {
26
- const parts = [];
27
- if (body.capability !== undefined) {
28
- parts.push(`"capability":${JSON.stringify(body.capability)}`);
29
- }
30
- parts.push(`"content":${JSON.stringify(body.content)}`);
31
- if (body.correlationId !== undefined) {
32
- parts.push(`"correlationId":${JSON.stringify(body.correlationId)}`);
33
- }
34
- parts.push(`"intent":${JSON.stringify(body.intent)}`);
35
- return `{${parts.join(',')}}`;
36
- }
37
- function getCachedHmacKey(secret) {
38
- const cacheKey = `hs256:${secret}`;
39
- const cached = hmacKeyCache.get(cacheKey);
40
- if (cached)
41
- return cached;
42
- if (hmacKeyCache.size >= HMAC_KEY_CACHE_LIMIT) {
43
- hmacKeyCache.clear();
44
- }
45
- const subtle = requireCryptoSubtle();
46
- const imported = subtle
47
- .importKey('raw', textEncoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify'])
48
- .catch((error) => {
49
- hmacKeyCache.delete(cacheKey);
50
- throw error;
51
- });
52
- hmacKeyCache.set(cacheKey, imported);
53
- return imported;
54
- }
55
- function getCachedEd25519PrivateKey(privateKeyPkcs8Base64Url) {
56
- const cacheKey = `ed25519:pkcs8:${privateKeyPkcs8Base64Url}`;
57
- const cached = ed25519PrivateKeyCache.get(cacheKey);
58
- if (cached)
59
- return cached;
60
- if (ed25519PrivateKeyCache.size >= ED25519_KEY_CACHE_LIMIT) {
61
- ed25519PrivateKeyCache.clear();
62
- }
63
- const subtle = requireCryptoSubtle();
64
- const imported = subtle
65
- .importKey('pkcs8', toArrayBuffer(fromBase64Url(privateKeyPkcs8Base64Url)), { name: 'Ed25519' }, false, ['sign'])
66
- .catch((error) => {
67
- ed25519PrivateKeyCache.delete(cacheKey);
68
- throw error;
69
- });
70
- ed25519PrivateKeyCache.set(cacheKey, imported);
71
- return imported;
72
- }
73
- function getCachedEd25519PublicKey(publicKeySpkiBase64Url) {
74
- const cacheKey = `ed25519:spki:${publicKeySpkiBase64Url}`;
75
- const cached = ed25519PublicKeyCache.get(cacheKey);
76
- if (cached)
77
- return cached;
78
- if (ed25519PublicKeyCache.size >= ED25519_KEY_CACHE_LIMIT) {
79
- ed25519PublicKeyCache.clear();
80
- }
81
- const subtle = requireCryptoSubtle();
82
- const imported = subtle
83
- .importKey('spki', toArrayBuffer(fromBase64Url(publicKeySpkiBase64Url)), { name: 'Ed25519' }, false, ['verify'])
84
- .catch((error) => {
85
- ed25519PublicKeyCache.delete(cacheKey);
86
- throw error;
87
- });
88
- ed25519PublicKeyCache.set(cacheKey, imported);
89
- return imported;
90
- }
91
- function toBase64Url(bytes) {
92
- const bufferLike = getBufferLike();
93
- const base64 = bufferLike ? bufferLike.from(bytes).toString('base64') : btoa(String.fromCharCode(...bytes));
94
- return base64
95
- .replace(/\+/g, '-')
96
- .replace(/\//g, '_')
97
- .replace(/=+$/g, '');
98
- }
99
- function fromBase64Url(value) {
100
- const padded = value
101
- .replace(/-/g, '+')
102
- .replace(/_/g, '/')
103
- .padEnd(Math.ceil(value.length / 4) * 4, '=');
104
- const bufferLike = getBufferLike();
105
- if (bufferLike) {
106
- return new Uint8Array(bufferLike.from(padded, 'base64'));
107
- }
108
- const binary = atob(padded);
109
- const bytes = new Uint8Array(binary.length);
110
- for (let i = 0; i < binary.length; i += 1) {
111
- bytes[i] = binary.charCodeAt(i);
112
- }
113
- return bytes;
114
- }
115
- function toArrayBuffer(bytes) {
116
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
117
- }
118
- export function canonicalizeEnvelope(envelope) {
119
- return `{"body":${serializeBodyCanonical(envelope.body)},"header":${serializeHeaderCanonical(envelope.header)}}`;
120
- }
121
- function requireCryptoSubtle() {
122
- if (typeof crypto === 'undefined' || !crypto.subtle) {
123
- throw new Error('Web Crypto API is not available in this runtime');
124
- }
125
- return crypto.subtle;
126
- }
127
- async function hmacSign(payload, secret) {
128
- const subtle = requireCryptoSubtle();
129
- const key = await getCachedHmacKey(secret);
130
- const signature = await subtle.sign('HMAC', key, textEncoder.encode(payload));
131
- return toBase64Url(new Uint8Array(signature));
132
- }
133
- async function hmacVerify(payload, signature, secret) {
134
- const subtle = requireCryptoSubtle();
135
- const key = await getCachedHmacKey(secret);
136
- const signatureBytes = fromBase64Url(signature);
137
- return subtle.verify('HMAC', key, signatureBytes.buffer, textEncoder.encode(payload));
138
- }
139
- async function ed25519Sign(payload, privateKeyPkcs8Base64Url) {
140
- const subtle = requireCryptoSubtle();
141
- const key = await getCachedEd25519PrivateKey(privateKeyPkcs8Base64Url);
142
- const signature = await subtle.sign('Ed25519', key, textEncoder.encode(payload));
143
- return toBase64Url(new Uint8Array(signature));
144
- }
145
- async function ed25519Verify(payload, signature, publicKeySpkiBase64Url) {
146
- const subtle = requireCryptoSubtle();
147
- const key = await getCachedEd25519PublicKey(publicKeySpkiBase64Url);
148
- const signatureBytes = fromBase64Url(signature);
149
- return subtle.verify('Ed25519', key, signatureBytes.buffer, textEncoder.encode(payload));
150
- }
151
- export async function signCanonicalPayloadHmac(payload, secret) {
152
- return hmacSign(payload, secret);
153
- }
154
- export async function verifyCanonicalPayloadHmac(payload, signature, secret) {
155
- return hmacVerify(payload, signature, secret);
156
- }
157
- export async function generateEd25519KeypairBase64Url() {
158
- const subtle = requireCryptoSubtle();
159
- const pair = await subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
160
- const privateKeyRaw = await subtle.exportKey('pkcs8', pair.privateKey);
161
- const publicKeyRaw = await subtle.exportKey('spki', pair.publicKey);
162
- return {
163
- privateKey: toBase64Url(new Uint8Array(privateKeyRaw)),
164
- publicKey: toBase64Url(new Uint8Array(publicKeyRaw)),
165
- };
166
- }
167
- export async function signCanonicalPayloadEd25519(payload, privateKeyPkcs8Base64Url) {
168
- return ed25519Sign(payload, privateKeyPkcs8Base64Url);
169
- }
170
- export async function verifyCanonicalPayloadEd25519(payload, signature, publicKeySpkiBase64Url) {
171
- return ed25519Verify(payload, signature, publicKeySpkiBase64Url);
172
- }
173
- export async function signEnvelopeHmac(envelope, secret, keyId = 'local-dev-key') {
174
- const payload = canonicalizeEnvelope(envelope);
175
- const signature = await hmacSign(payload, secret);
176
- return {
177
- ...envelope,
178
- signature: {
179
- alg: 'HS256',
180
- keyId,
181
- value: signature,
182
- },
183
- };
184
- }
185
- export async function verifyEnvelopeHmac(envelope, secret) {
186
- if (!envelope.signature)
187
- return false;
188
- if (envelope.signature.alg !== 'HS256')
189
- return false;
190
- const unsigned = {
191
- header: envelope.header,
192
- body: envelope.body,
193
- };
194
- const payload = canonicalizeEnvelope(unsigned);
195
- return hmacVerify(payload, envelope.signature.value, secret);
196
- }
197
- export async function signEnvelopeEd25519(envelope, privateKeyPkcs8Base64Url, keyId = 'local-ed25519-key') {
198
- const payload = canonicalizeEnvelope(envelope);
199
- const signature = await ed25519Sign(payload, privateKeyPkcs8Base64Url);
200
- return {
201
- ...envelope,
202
- signature: {
203
- alg: 'ED25519',
204
- keyId,
205
- value: signature,
206
- },
207
- };
208
- }
209
- export async function verifyEnvelopeEd25519(envelope, publicKeySpkiBase64Url) {
210
- if (!envelope.signature)
211
- return false;
212
- if (envelope.signature.alg !== 'ED25519')
213
- return false;
214
- const unsigned = {
215
- header: envelope.header,
216
- body: envelope.body,
217
- };
218
- const payload = canonicalizeEnvelope(unsigned);
219
- return ed25519Verify(payload, envelope.signature.value, publicKeySpkiBase64Url);
220
- }
221
- export async function verifyEnvelopeSignature(envelope, material) {
222
- if (!envelope.signature)
223
- return false;
224
- if (envelope.signature.alg !== material.alg)
225
- return false;
226
- if (material.alg === 'HS256') {
227
- return verifyEnvelopeHmac(envelope, material.secret);
228
- }
229
- return verifyEnvelopeEd25519(envelope, material.publicKey);
230
- }
231
- export async function verifyCanonicalPayloadSignature(payload, signature, material) {
232
- if (!signature)
233
- return false;
234
- if (signature.alg !== material.alg)
235
- return false;
236
- if (material.alg === 'HS256') {
237
- return verifyCanonicalPayloadHmac(payload, signature.value, material.secret);
238
- }
239
- return verifyCanonicalPayloadEd25519(payload, signature.value, material.publicKey);
240
- }
241
- export function validateEnvelope(envelope, nowMs = Date.now()) {
242
- const diagnostics = [];
243
- const header = envelope.header ?? {};
244
- const body = envelope.body ?? {};
245
- const version = typeof header.version === 'string' ? header.version : '';
246
- const messageId = typeof header.messageId === 'string' ? header.messageId : '';
247
- const sender = typeof header.sender === 'string' ? header.sender : '';
248
- const nonce = typeof header.nonce === 'string' ? header.nonce : '';
249
- const timestampMs = typeof header.timestampMs === 'number' ? header.timestampMs : 0;
250
- const ttlMs = typeof header.ttlMs === 'number' ? header.ttlMs : 0;
251
- const content = typeof body.content === 'string' ? body.content : '';
252
- if (version !== '7h3/0.1') {
253
- diagnostics.push({ level: 'error', message: `Unsupported protocol version '${version}'` });
254
- }
255
- if (!messageId.trim()) {
256
- diagnostics.push({ level: 'error', message: 'Missing messageId' });
257
- }
258
- if (!sender.trim()) {
259
- diagnostics.push({ level: 'error', message: 'Missing sender identity' });
260
- }
261
- if (!nonce.trim()) {
262
- diagnostics.push({ level: 'error', message: 'Missing nonce — replay protection requires a unique nonce per message' });
263
- }
264
- if (ttlMs <= 0) {
265
- diagnostics.push({ level: 'error', message: 'ttlMs must be greater than zero' });
266
- }
267
- if (timestampMs + ttlMs < nowMs) {
268
- diagnostics.push({ level: 'error', message: 'Message TTL expired' });
269
- }
270
- if (!content.trim()) {
271
- diagnostics.push({ level: 'warning', message: 'Empty content payload' });
272
- }
273
- return diagnostics;
274
- }
275
- export function createEnvelope(input) {
276
- const nowMs = input.nowMs ?? Date.now();
277
- return {
278
- header: {
279
- version: '7h3/0.1',
280
- messageId: input.messageId ?? `msg-${nowMs}-${Math.random().toString(36).slice(2, 10)}`,
281
- timestampMs: nowMs,
282
- ttlMs: input.ttlMs ?? 60_000,
283
- sender: input.sender,
284
- recipient: input.recipient,
285
- nonce: input.nonce ?? Math.random().toString(36).slice(2, 12),
286
- },
287
- body: {
288
- intent: input.intent,
289
- content: input.content,
290
- capability: input.capability,
291
- correlationId: input.correlationId,
292
- },
293
- };
294
- }