@7h3/protocol 0.4.0 → 0.5.0

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +1169 -175
  3. package/bin/7h3.ts +22 -1
  4. package/docs/assets/banner-github.png +0 -0
  5. package/docs/assets/banner.svg +123 -0
  6. package/package.json +55 -13
  7. package/sdk/browser/package.json +1 -1
  8. package/sdk/go/cbor.go +551 -0
  9. package/sdk/go/cbor_test.go +232 -0
  10. package/sdk/go/encryption.go +280 -0
  11. package/sdk/go/encryption_test.go +318 -0
  12. package/sdk/go/go.mod +5 -1
  13. package/sdk/go/go.sum +4 -0
  14. package/sdk/go/replay.go +121 -0
  15. package/sdk/go/replay_test.go +149 -0
  16. package/sdk/pq/package-lock.json +1358 -0
  17. package/sdk/pq/package.json +42 -0
  18. package/sdk/pq/src/index.test.ts +143 -0
  19. package/sdk/pq/src/index.ts +166 -0
  20. package/sdk/pq/tsconfig.json +14 -0
  21. package/sdk/pq/vitest.config.ts +7 -0
  22. package/sdk/python/protocol_7h3/encryption.py +252 -0
  23. package/sdk/python/protocol_7h3/pq.py +244 -0
  24. package/sdk/python/protocol_7h3/replay.py +98 -0
  25. package/sdk/python/pyproject.toml +1 -1
  26. package/sdk/python/tests/test_encryption.py +206 -0
  27. package/sdk/rust/Cargo.lock +1 -1
  28. package/sdk/rust/Cargo.toml +1 -1
  29. package/sdk/threshold/index.d.ts +68 -0
  30. package/sdk/threshold/index.d.ts.map +1 -0
  31. package/sdk/threshold/index.js +254 -0
  32. package/sdk/threshold/package-lock.json +1361 -0
  33. package/sdk/threshold/package.json +39 -0
  34. package/sdk/threshold/src/index.d.ts +68 -0
  35. package/sdk/threshold/src/index.d.ts.map +1 -0
  36. package/sdk/threshold/src/index.js +254 -0
  37. package/sdk/threshold/src/index.test.ts +238 -0
  38. package/sdk/threshold/src/index.ts +355 -0
  39. package/sdk/threshold/tsconfig.json +19 -0
  40. package/sdk/threshold/vitest.config.ts +12 -0
  41. package/src/capability.test.ts +504 -0
  42. package/src/capability.ts +380 -0
  43. package/src/cborCodec.test.ts +263 -0
  44. package/src/cborCodec.ts +339 -0
  45. package/src/encryption.test.ts +206 -0
  46. package/src/encryption.ts +245 -0
  47. package/src/envelopeCbor.ts +140 -0
  48. package/src/gateway.ts +75 -0
  49. package/src/httpBinding.ts +37 -11
  50. package/src/index.ts +7 -0
  51. package/src/otel.ts +136 -0
  52. package/src/protocol.d.ts +67 -0
  53. package/src/protocol.d.ts.map +1 -0
  54. package/src/protocol.js +294 -0
  55. package/src/protocol.ts +1 -0
  56. package/src/replayStores.test.ts +133 -1
  57. package/src/replayStores.ts +136 -3
  58. package/src/stream.test.ts +254 -0
  59. package/src/stream.ts +417 -0
  60. package/src/telemetry.test.ts +251 -0
  61. package/src/telemetry.ts +299 -0
  62. package/src/wsBinding.ts +100 -0
  63. package/vitest.config.ts +11 -0
@@ -0,0 +1,504 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ generateEd25519KeypairBase64Url,
4
+ issueCapabilityToken,
5
+ verifyCapabilityToken,
6
+ delegateCapabilityToken,
7
+ verifyCapabilityChain,
8
+ tokenMatchesScope,
9
+ serializeCapabilityChain,
10
+ parseCapabilityChain,
11
+ canonicalizeCapabilityToken,
12
+ type CapabilityToken,
13
+ type CapabilityScope,
14
+ } from './capability'
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Helpers
18
+ // ---------------------------------------------------------------------------
19
+
20
+ async function makeKeypair() {
21
+ return generateEd25519KeypairBase64Url()
22
+ }
23
+
24
+ function makeKeyRegistry(map: Record<string, string>): { getPublicKey(id: string): Promise<string | null> } {
25
+ return {
26
+ async getPublicKey(id: string) {
27
+ return map[id] ?? null
28
+ },
29
+ }
30
+ }
31
+
32
+ const paymentScopes: CapabilityScope[] = [
33
+ { pathGlob: '/api/payments/**', methods: ['POST', 'PUT'] },
34
+ ]
35
+
36
+ const readonlyPaymentScopes: CapabilityScope[] = [
37
+ { pathGlob: '/api/payments/**', methods: ['POST'] },
38
+ ]
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Test 1: issueCapabilityToken creates token with correct fields
42
+ // ---------------------------------------------------------------------------
43
+ describe('issueCapabilityToken', () => {
44
+ it('creates token with correct fields', async () => {
45
+ const root = await makeKeypair()
46
+ const now = Date.now()
47
+
48
+ const token = await issueCapabilityToken({
49
+ issuerPrivateKey: root.privateKey,
50
+ issuerId: 'agent-root',
51
+ subject: 'agent-b',
52
+ scopes: paymentScopes,
53
+ ttlMs: 60_000,
54
+ maxDelegations: 2,
55
+ })
56
+
57
+ expect(token.version).toBe('7h3-cap/1')
58
+ expect(token.issuer).toBe('agent-root')
59
+ expect(token.subject).toBe('agent-b')
60
+ expect(token.scopes).toEqual(paymentScopes)
61
+ expect(token.delegationDepth).toBe(0)
62
+ expect(token.maxDelegations).toBe(2)
63
+ expect(token.parentTokenId).toBeUndefined()
64
+ expect(token.issuedAt).toBeGreaterThanOrEqual(now)
65
+ expect(token.expiresAt).toBeGreaterThan(token.issuedAt)
66
+ expect(typeof token.id).toBe('string')
67
+ expect(typeof token.signature).toBe('string')
68
+ expect(typeof token.keyId).toBe('string')
69
+ })
70
+
71
+ it('defaults maxDelegations to 0 when not specified', async () => {
72
+ const root = await makeKeypair()
73
+ const token = await issueCapabilityToken({
74
+ issuerPrivateKey: root.privateKey,
75
+ issuerId: 'agent-root',
76
+ subject: 'agent-b',
77
+ scopes: paymentScopes,
78
+ ttlMs: 60_000,
79
+ })
80
+ expect(token.maxDelegations).toBe(0)
81
+ })
82
+ })
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // Test 2: verifyCapabilityToken succeeds with correct key
86
+ // ---------------------------------------------------------------------------
87
+ describe('verifyCapabilityToken', () => {
88
+ it('succeeds with correct key', async () => {
89
+ const root = await makeKeypair()
90
+ const token = await issueCapabilityToken({
91
+ issuerPrivateKey: root.privateKey,
92
+ issuerId: 'agent-root',
93
+ subject: 'agent-b',
94
+ scopes: paymentScopes,
95
+ ttlMs: 60_000,
96
+ })
97
+
98
+ const valid = await verifyCapabilityToken(token, root.publicKey)
99
+ expect(valid).toBe(true)
100
+ })
101
+
102
+ // Test 3: verifyCapabilityToken fails with wrong key
103
+ it('fails with wrong key', async () => {
104
+ const root = await makeKeypair()
105
+ const other = await makeKeypair()
106
+ const token = await issueCapabilityToken({
107
+ issuerPrivateKey: root.privateKey,
108
+ issuerId: 'agent-root',
109
+ subject: 'agent-b',
110
+ scopes: paymentScopes,
111
+ ttlMs: 60_000,
112
+ })
113
+
114
+ const valid = await verifyCapabilityToken(token, other.publicKey)
115
+ expect(valid).toBe(false)
116
+ })
117
+
118
+ // Test 4: verifyCapabilityToken fails on expired token
119
+ it('fails on expired token', async () => {
120
+ const root = await makeKeypair()
121
+ const token = await issueCapabilityToken({
122
+ issuerPrivateKey: root.privateKey,
123
+ issuerId: 'agent-root',
124
+ subject: 'agent-b',
125
+ scopes: paymentScopes,
126
+ ttlMs: 1, // 1ms — will be expired by the time we check
127
+ })
128
+
129
+ // Use a future "now" to simulate expiry
130
+ const futureNow = token.expiresAt + 1
131
+ const valid = await verifyCapabilityToken(token, root.publicKey, { now: futureNow })
132
+ expect(valid).toBe(false)
133
+ })
134
+ })
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // Test 5: delegateCapabilityToken creates valid delegation
138
+ // ---------------------------------------------------------------------------
139
+ describe('delegateCapabilityToken', () => {
140
+ it('creates valid delegation', async () => {
141
+ const rootKeys = await makeKeypair()
142
+ const agentBKeys = await makeKeypair()
143
+
144
+ const rootToken = await issueCapabilityToken({
145
+ issuerPrivateKey: rootKeys.privateKey,
146
+ issuerId: 'agent-root',
147
+ subject: 'agent-b',
148
+ scopes: paymentScopes,
149
+ ttlMs: 60_000,
150
+ maxDelegations: 2,
151
+ })
152
+
153
+ const delegated = await delegateCapabilityToken({
154
+ parentToken: rootToken,
155
+ delegatorPrivateKey: agentBKeys.privateKey,
156
+ delegatorId: 'agent-b',
157
+ newSubject: 'agent-c',
158
+ scopes: readonlyPaymentScopes,
159
+ ttlMs: 30_000,
160
+ })
161
+
162
+ expect(delegated.issuer).toBe('agent-b')
163
+ expect(delegated.subject).toBe('agent-c')
164
+ expect(delegated.delegationDepth).toBe(1)
165
+ expect(delegated.parentTokenId).toBe(rootToken.id)
166
+ expect(delegated.scopes).toEqual(readonlyPaymentScopes)
167
+ // maxDelegations should be decremented
168
+ expect(delegated.maxDelegations).toBe(1)
169
+
170
+ const valid = await verifyCapabilityToken(delegated, agentBKeys.publicKey)
171
+ expect(valid).toBe(true)
172
+ })
173
+
174
+ // Test 6: delegateCapabilityToken fails when maxDelegations=0
175
+ it('fails when maxDelegations=0', async () => {
176
+ const rootKeys = await makeKeypair()
177
+ const agentBKeys = await makeKeypair()
178
+
179
+ const rootToken = await issueCapabilityToken({
180
+ issuerPrivateKey: rootKeys.privateKey,
181
+ issuerId: 'agent-root',
182
+ subject: 'agent-b',
183
+ scopes: paymentScopes,
184
+ ttlMs: 60_000,
185
+ maxDelegations: 0, // no further delegation
186
+ })
187
+
188
+ await expect(
189
+ delegateCapabilityToken({
190
+ parentToken: rootToken,
191
+ delegatorPrivateKey: agentBKeys.privateKey,
192
+ delegatorId: 'agent-b',
193
+ newSubject: 'agent-c',
194
+ scopes: readonlyPaymentScopes,
195
+ ttlMs: 30_000,
196
+ }),
197
+ ).rejects.toThrow(/maxDelegations/)
198
+ })
199
+
200
+ // Test 7: delegateCapabilityToken fails when new scopes exceed parent scopes
201
+ it('fails when new scopes exceed parent scopes', async () => {
202
+ const rootKeys = await makeKeypair()
203
+ const agentBKeys = await makeKeypair()
204
+
205
+ const rootToken = await issueCapabilityToken({
206
+ issuerPrivateKey: rootKeys.privateKey,
207
+ issuerId: 'agent-root',
208
+ subject: 'agent-b',
209
+ scopes: [{ pathGlob: '/api/payments/**', methods: ['POST'] }],
210
+ ttlMs: 60_000,
211
+ maxDelegations: 2,
212
+ })
213
+
214
+ // Try to delegate with a method (DELETE) not in parent
215
+ await expect(
216
+ delegateCapabilityToken({
217
+ parentToken: rootToken,
218
+ delegatorPrivateKey: agentBKeys.privateKey,
219
+ delegatorId: 'agent-b',
220
+ newSubject: 'agent-c',
221
+ scopes: [{ pathGlob: '/api/payments/**', methods: ['POST', 'DELETE'] }],
222
+ ttlMs: 30_000,
223
+ }),
224
+ ).rejects.toThrow(/exceed|subset/i)
225
+ })
226
+
227
+ it('fails when delegatorId does not match parentToken.subject', async () => {
228
+ const rootKeys = await makeKeypair()
229
+ const wrongKeys = await makeKeypair()
230
+
231
+ const rootToken = await issueCapabilityToken({
232
+ issuerPrivateKey: rootKeys.privateKey,
233
+ issuerId: 'agent-root',
234
+ subject: 'agent-b',
235
+ scopes: paymentScopes,
236
+ ttlMs: 60_000,
237
+ maxDelegations: 2,
238
+ })
239
+
240
+ await expect(
241
+ delegateCapabilityToken({
242
+ parentToken: rootToken,
243
+ delegatorPrivateKey: wrongKeys.privateKey,
244
+ delegatorId: 'agent-wrong', // not agent-b
245
+ newSubject: 'agent-c',
246
+ ttlMs: 30_000,
247
+ }),
248
+ ).rejects.toThrow(/does not match/)
249
+ })
250
+ })
251
+
252
+ // ---------------------------------------------------------------------------
253
+ // Test 8: verifyCapabilityChain: 2-link chain (root→delegate) verifies
254
+ // ---------------------------------------------------------------------------
255
+ describe('verifyCapabilityChain', () => {
256
+ it('2-link chain (root→delegate) verifies', async () => {
257
+ const rootKeys = await makeKeypair()
258
+ const agentBKeys = await makeKeypair()
259
+
260
+ const rootToken = await issueCapabilityToken({
261
+ issuerPrivateKey: rootKeys.privateKey,
262
+ issuerId: 'agent-root',
263
+ subject: 'agent-b',
264
+ scopes: paymentScopes,
265
+ ttlMs: 60_000,
266
+ maxDelegations: 2,
267
+ })
268
+
269
+ const delegated = await delegateCapabilityToken({
270
+ parentToken: rootToken,
271
+ delegatorPrivateKey: agentBKeys.privateKey,
272
+ delegatorId: 'agent-b',
273
+ newSubject: 'agent-c',
274
+ scopes: readonlyPaymentScopes,
275
+ ttlMs: 30_000,
276
+ })
277
+
278
+ const registry = makeKeyRegistry({
279
+ 'agent-root': rootKeys.publicKey,
280
+ 'agent-b': agentBKeys.publicKey,
281
+ })
282
+
283
+ const result = await verifyCapabilityChain([rootToken, delegated], registry)
284
+ expect(result.ok).toBe(true)
285
+ if (result.ok) {
286
+ expect(result.token.subject).toBe('agent-c')
287
+ expect(result.chain).toHaveLength(2)
288
+ }
289
+ })
290
+
291
+ // Test 9: verifyCapabilityChain: tampered chain fails
292
+ it('tampered chain fails', async () => {
293
+ const rootKeys = await makeKeypair()
294
+ const agentBKeys = await makeKeypair()
295
+
296
+ const rootToken = await issueCapabilityToken({
297
+ issuerPrivateKey: rootKeys.privateKey,
298
+ issuerId: 'agent-root',
299
+ subject: 'agent-b',
300
+ scopes: paymentScopes,
301
+ ttlMs: 60_000,
302
+ maxDelegations: 2,
303
+ })
304
+
305
+ const delegated = await delegateCapabilityToken({
306
+ parentToken: rootToken,
307
+ delegatorPrivateKey: agentBKeys.privateKey,
308
+ delegatorId: 'agent-b',
309
+ newSubject: 'agent-c',
310
+ scopes: readonlyPaymentScopes,
311
+ ttlMs: 30_000,
312
+ })
313
+
314
+ // Tamper with the delegated token's subject
315
+ const tampered: CapabilityToken = { ...delegated, subject: 'agent-evil' }
316
+
317
+ const registry = makeKeyRegistry({
318
+ 'agent-root': rootKeys.publicKey,
319
+ 'agent-b': agentBKeys.publicKey,
320
+ })
321
+
322
+ const result = await verifyCapabilityChain([rootToken, tampered], registry)
323
+ expect(result.ok).toBe(false)
324
+ })
325
+
326
+ it('rejects when issuer key not in registry', async () => {
327
+ const rootKeys = await makeKeypair()
328
+
329
+ const rootToken = await issueCapabilityToken({
330
+ issuerPrivateKey: rootKeys.privateKey,
331
+ issuerId: 'agent-root',
332
+ subject: 'agent-b',
333
+ scopes: paymentScopes,
334
+ ttlMs: 60_000,
335
+ })
336
+
337
+ // Empty registry — no key for agent-root
338
+ const registry = makeKeyRegistry({})
339
+ const result = await verifyCapabilityChain([rootToken], registry)
340
+ expect(result.ok).toBe(false)
341
+ if (!result.ok) {
342
+ expect(result.reason).toMatch(/no-public-key/)
343
+ }
344
+ })
345
+
346
+ it('rejects when required scope not covered', async () => {
347
+ const rootKeys = await makeKeypair()
348
+
349
+ const rootToken = await issueCapabilityToken({
350
+ issuerPrivateKey: rootKeys.privateKey,
351
+ issuerId: 'agent-root',
352
+ subject: 'agent-b',
353
+ scopes: [{ pathGlob: '/api/payments/**' }],
354
+ ttlMs: 60_000,
355
+ })
356
+
357
+ const registry = makeKeyRegistry({ 'agent-root': rootKeys.publicKey })
358
+ const result = await verifyCapabilityChain([rootToken], registry, {
359
+ requiredPathGlob: '/api/admin/delete',
360
+ })
361
+ expect(result.ok).toBe(false)
362
+ })
363
+
364
+ it('rejects expired token in chain', async () => {
365
+ const rootKeys = await makeKeypair()
366
+
367
+ const rootToken = await issueCapabilityToken({
368
+ issuerPrivateKey: rootKeys.privateKey,
369
+ issuerId: 'agent-root',
370
+ subject: 'agent-b',
371
+ scopes: paymentScopes,
372
+ ttlMs: 60_000,
373
+ })
374
+
375
+ const registry = makeKeyRegistry({ 'agent-root': rootKeys.publicKey })
376
+
377
+ // Check with a future now that makes the token expired
378
+ const result = await verifyCapabilityChain([rootToken], registry, {
379
+ now: rootToken.expiresAt + 1,
380
+ })
381
+ expect(result.ok).toBe(false)
382
+ if (!result.ok) {
383
+ expect(result.reason).toMatch(/expired/)
384
+ }
385
+ })
386
+ })
387
+
388
+ // ---------------------------------------------------------------------------
389
+ // Test 10: tokenMatchesScope: glob matching works
390
+ // ---------------------------------------------------------------------------
391
+ describe('tokenMatchesScope', () => {
392
+ it('matches exact glob pattern', async () => {
393
+ const rootKeys = await makeKeypair()
394
+ const token = await issueCapabilityToken({
395
+ issuerPrivateKey: rootKeys.privateKey,
396
+ issuerId: 'agent-root',
397
+ subject: 'agent-b',
398
+ scopes: [{ pathGlob: '/api/payments/**', methods: ['POST', 'PUT'] }],
399
+ ttlMs: 60_000,
400
+ })
401
+
402
+ expect(tokenMatchesScope(token, '/api/payments/create', 'POST')).toBe(true)
403
+ expect(tokenMatchesScope(token, '/api/payments/update/123', 'PUT')).toBe(true)
404
+ })
405
+
406
+ it('rejects method not in scope', async () => {
407
+ const rootKeys = await makeKeypair()
408
+ const token = await issueCapabilityToken({
409
+ issuerPrivateKey: rootKeys.privateKey,
410
+ issuerId: 'agent-root',
411
+ subject: 'agent-b',
412
+ scopes: [{ pathGlob: '/api/payments/**', methods: ['POST'] }],
413
+ ttlMs: 60_000,
414
+ })
415
+
416
+ expect(tokenMatchesScope(token, '/api/payments/create', 'DELETE')).toBe(false)
417
+ })
418
+
419
+ it('matches any method when methods is undefined', async () => {
420
+ const rootKeys = await makeKeypair()
421
+ const token = await issueCapabilityToken({
422
+ issuerPrivateKey: rootKeys.privateKey,
423
+ issuerId: 'agent-root',
424
+ subject: 'agent-b',
425
+ scopes: [{ pathGlob: '/api/**' }], // no methods restriction
426
+ ttlMs: 60_000,
427
+ })
428
+
429
+ expect(tokenMatchesScope(token, '/api/anything', 'DELETE')).toBe(true)
430
+ expect(tokenMatchesScope(token, '/api/payments/create', 'GET')).toBe(true)
431
+ })
432
+
433
+ it('rejects path not matching glob', async () => {
434
+ const rootKeys = await makeKeypair()
435
+ const token = await issueCapabilityToken({
436
+ issuerPrivateKey: rootKeys.privateKey,
437
+ issuerId: 'agent-root',
438
+ subject: 'agent-b',
439
+ scopes: [{ pathGlob: '/api/payments/**' }],
440
+ ttlMs: 60_000,
441
+ })
442
+
443
+ expect(tokenMatchesScope(token, '/api/admin/delete', 'POST')).toBe(false)
444
+ })
445
+
446
+ it('handles single-segment wildcard', async () => {
447
+ const rootKeys = await makeKeypair()
448
+ const token = await issueCapabilityToken({
449
+ issuerPrivateKey: rootKeys.privateKey,
450
+ issuerId: 'agent-root',
451
+ subject: 'agent-b',
452
+ scopes: [{ pathGlob: '/api/*/status' }],
453
+ ttlMs: 60_000,
454
+ })
455
+
456
+ expect(tokenMatchesScope(token, '/api/payments/status', 'GET')).toBe(true)
457
+ // Multi-segment should NOT match single *
458
+ expect(tokenMatchesScope(token, '/api/a/b/status', 'GET')).toBe(false)
459
+ })
460
+ })
461
+
462
+ // ---------------------------------------------------------------------------
463
+ // Serialization round-trip
464
+ // ---------------------------------------------------------------------------
465
+ describe('serializeCapabilityChain / parseCapabilityChain', () => {
466
+ it('round-trips a chain', async () => {
467
+ const rootKeys = await makeKeypair()
468
+ const token = await issueCapabilityToken({
469
+ issuerPrivateKey: rootKeys.privateKey,
470
+ issuerId: 'agent-root',
471
+ subject: 'agent-b',
472
+ scopes: paymentScopes,
473
+ ttlMs: 60_000,
474
+ })
475
+
476
+ const serialized = serializeCapabilityChain([token])
477
+ const parsed = parseCapabilityChain(serialized)
478
+
479
+ expect(parsed).toHaveLength(1)
480
+ expect(parsed[0].id).toBe(token.id)
481
+ expect(parsed[0].signature).toBe(token.signature)
482
+ })
483
+ })
484
+
485
+ // ---------------------------------------------------------------------------
486
+ // Canonicalization determinism
487
+ // ---------------------------------------------------------------------------
488
+ describe('canonicalizeCapabilityToken', () => {
489
+ it('produces the same string for equivalent tokens', async () => {
490
+ const rootKeys = await makeKeypair()
491
+ const token = await issueCapabilityToken({
492
+ issuerPrivateKey: rootKeys.privateKey,
493
+ issuerId: 'agent-root',
494
+ subject: 'agent-b',
495
+ scopes: paymentScopes,
496
+ ttlMs: 60_000,
497
+ })
498
+
499
+ const { signature, ...unsigned } = token
500
+ const c1 = canonicalizeCapabilityToken(unsigned)
501
+ const c2 = canonicalizeCapabilityToken(unsigned)
502
+ expect(c1).toBe(c2)
503
+ })
504
+ })