@7h3/protocol 0.5.0 → 0.5.1

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 (294) hide show
  1. package/README.md +6 -1317
  2. package/agentAdapter.d.ts +26 -0
  3. package/auditLog.d.ts +54 -0
  4. package/capability.d.ts +67 -0
  5. package/cborCodec.d.ts +34 -0
  6. package/conformanceVectors.d.ts +20 -0
  7. package/encryption.d.ts +85 -0
  8. package/envelopeCbor.d.ts +33 -0
  9. package/frameworkAdapters.d.ts +72 -0
  10. package/gateway.d.ts +53 -0
  11. package/grpcBinding.d.ts +29 -0
  12. package/httpBinding.d.ts +50 -0
  13. package/index.d.ts +39 -0
  14. package/index.js +3662 -0
  15. package/keyInfra.d.ts +64 -0
  16. package/keyRegistry.d.ts +9 -0
  17. package/keyRotation.d.ts +20 -0
  18. package/mcpGateway.d.ts +37 -0
  19. package/mcpTransports.d.ts +62 -0
  20. package/mcpWrapper.d.ts +83 -0
  21. package/otel.d.ts +65 -0
  22. package/package.json +13 -121
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/{src/protocol.d.ts → protocol.d.ts} +1 -2
  26. package/protocolAgent.d.ts +58 -0
  27. package/protocolBinary.d.ts +8 -0
  28. package/protocolCapabilities.d.ts +24 -0
  29. package/protocolReplay.d.ts +35 -0
  30. package/protocolTransport.d.ts +73 -0
  31. package/queueBinding.d.ts +43 -0
  32. package/rateLimiter.d.ts +18 -0
  33. package/{src/redisClient.ts → redisClient.d.ts} +25 -75
  34. package/replayStores.d.ts +98 -0
  35. package/revocation.d.ts +71 -0
  36. package/routePolicy.d.ts +30 -0
  37. package/runtimePolicy.d.ts +24 -0
  38. package/runtimePolicyManager.d.ts +15 -0
  39. package/runtimePolicyPresets.d.ts +11 -0
  40. package/signedResponse.d.ts +21 -0
  41. package/stream.d.ts +59 -0
  42. package/telemetry.d.ts +79 -0
  43. package/webhookBinding.d.ts +30 -0
  44. package/wsBinding.d.ts +52 -0
  45. package/.dockerignore +0 -19
  46. package/.github/dependabot.yml +0 -32
  47. package/.github/workflows/ci.yml +0 -31
  48. package/.github/workflows/publish.yml +0 -59
  49. package/.github/workflows/scorecard.yml +0 -37
  50. package/7h3.example.yaml +0 -125
  51. package/CHANGELOG.md +0 -152
  52. package/CONTRIBUTING.md +0 -82
  53. package/Dockerfile +0 -73
  54. package/GOVERNANCE.md +0 -62
  55. package/SECURITY.md +0 -70
  56. package/bench-results/replay-cache-full-1777891033256.json +0 -10
  57. package/bench-results/replay-cache-full-1777896317488.json +0 -10
  58. package/bench-results/replay-cache-full-1777900993184.json +0 -10
  59. package/bench-results/replay-cache-full-1777901019285.json +0 -10
  60. package/bench-results/replay-cache-quick-1777870170126.json +0 -10
  61. package/bench-results/signature-profiles-quick-1775875160079.json +0 -85
  62. package/bench-results/signature-profiles-quick-1775983539716.json +0 -85
  63. package/bench-results/signature-profiles-quick-1776237913190.json +0 -85
  64. package/bench-results/wire-codecs-full-1777891019803.json +0 -93
  65. package/bench-results/wire-codecs-full-1777896260964.json +0 -93
  66. package/bench-results/wire-codecs-full-1777901004247.json +0 -93
  67. package/bench-results/wire-codecs-quick-1775972879056.json +0 -93
  68. package/bench-results/wire-codecs-quick-1775983541111.json +0 -93
  69. package/bench-results/wire-codecs-quick-1776237914299.json +0 -93
  70. package/bench-results/wire-codecs-quick-1777841285236.json +0 -93
  71. package/bench-results/wire-codecs-quick-1777841321772.json +0 -93
  72. package/bench-results/wire-codecs-quick-1777841330408.json +0 -93
  73. package/bench-results/wire-codecs-quick-1777852886082.json +0 -93
  74. package/bench-results/wire-codecs-quick-1777852988773.json +0 -93
  75. package/bench-results/wire-codecs-quick-1777870188095.json +0 -93
  76. package/bench-results/wire-codecs-quick-1777870263918.json +0 -93
  77. package/bench-results/wire-codecs-quick-1777870455034.json +0 -93
  78. package/bench-results/wire-codecs-quick-1778816163081.json +0 -93
  79. package/bench-results/wire-codecs-quick-1778843936130.json +0 -93
  80. package/bin/7h3.ts +0 -406
  81. package/conformance/7h3_v0_1.json +0 -77
  82. package/conformance/7h3_v0_1_binary.json +0 -20
  83. package/conformance/aip_v0_1_binary.json +0 -20
  84. package/docker-compose.yaml +0 -77
  85. package/docs/ADOPTION_PLAN.md +0 -120
  86. package/docs/AGENTS.md +0 -77
  87. package/docs/AIP_RFC_v0.1.md +0 -97
  88. package/docs/AI_DECISION_CARD.md +0 -122
  89. package/docs/AI_RUNTIME_POLICY.json +0 -126
  90. package/docs/AI_RUNTIME_POLICY.yaml +0 -110
  91. package/docs/BACKPRESSURE_TUNING.md +0 -65
  92. package/docs/BENCHMARK_CLAIM_MATRIX.md +0 -42
  93. package/docs/BENCHMARK_REPORT_TEMPLATE.md +0 -169
  94. package/docs/BINARY_CODEC_BENCH.md +0 -23
  95. package/docs/CLEAN_CLONE_RUNBOOK.md +0 -36
  96. package/docs/CLOCK_SKEW_POLICY.md +0 -30
  97. package/docs/DISTRIBUTED_REPLAY.md +0 -142
  98. package/docs/FUZZ_CAMPAIGN.md +0 -121
  99. package/docs/GATEWAY.md +0 -195
  100. package/docs/KEY_MANAGEMENT_POLICY.md +0 -53
  101. package/docs/KEY_REVOCATION.md +0 -69
  102. package/docs/MCP_WRAPPER.md +0 -159
  103. package/docs/MIGRATION_GUIDE.md +0 -40
  104. package/docs/OPERATORS.md +0 -184
  105. package/docs/PERF_REGRESSION_POLICY.md +0 -34
  106. package/docs/PROJECT_EXAMINATION_2026-05-31.md +0 -219
  107. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +0 -135
  108. package/docs/RELEASE_GATE.md +0 -25
  109. package/docs/RELEASE_NOTES_v0.1.0.md +0 -54
  110. package/docs/SECURITY_REVIEW_2026-06-05.md +0 -165
  111. package/docs/TELEMETRY.md +0 -41
  112. package/docs/THREAT_MODEL.md +0 -89
  113. package/docs/VERSIONING_POLICY.md +0 -30
  114. package/docs/assets/banner-github.png +0 -0
  115. package/docs/assets/banner.png +0 -0
  116. package/docs/assets/banner.svg +0 -123
  117. package/eslint.config.js +0 -15
  118. package/fuzz/ts/harness-decode.ts +0 -136
  119. package/fuzz/ts/harness-verify.ts +0 -121
  120. package/fuzz/ts/run.ts +0 -35
  121. package/mcp-server/README.md +0 -38
  122. package/mcp-server/package-lock.json +0 -1187
  123. package/mcp-server/package.json +0 -35
  124. package/mcp-server/src/index.ts +0 -236
  125. package/mcp-server/tsconfig.json +0 -14
  126. package/scripts/aip-framework-quickstart.ts +0 -110
  127. package/scripts/aip-mcp-gateway.ts +0 -38
  128. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  129. package/scripts/aip-quickstart.ts +0 -60
  130. package/scripts/bench-diff.ts +0 -118
  131. package/scripts/bench-protocol-e2e.ts +0 -937
  132. package/scripts/bench-protocol-openloop.ts +0 -1397
  133. package/scripts/bench-replay-cache.ts +0 -76
  134. package/scripts/bench-signature-profiles.ts +0 -180
  135. package/scripts/bench-wire-codecs.ts +0 -161
  136. package/scripts/build-binary-conformance.ts +0 -36
  137. package/scripts/build-release-dashboard.ts +0 -175
  138. package/scripts/canary-rollout.ts +0 -38
  139. package/scripts/mcpGatewayCli.test.ts +0 -116
  140. package/scripts/prepare-aip-package.ts +0 -88
  141. package/scripts/regen-conformance-sigs.ts +0 -18
  142. package/scripts/release-gate.ts +0 -19
  143. package/scripts/validate-runtime-policy.ts +0 -18
  144. package/sdk/browser/index.test.ts +0 -162
  145. package/sdk/browser/index.ts +0 -257
  146. package/sdk/browser/package.json +0 -13
  147. package/sdk/go/cbor.go +0 -551
  148. package/sdk/go/cbor_test.go +0 -232
  149. package/sdk/go/encryption.go +0 -280
  150. package/sdk/go/encryption_test.go +0 -318
  151. package/sdk/go/go.mod +0 -7
  152. package/sdk/go/go.sum +0 -4
  153. package/sdk/go/http.go +0 -135
  154. package/sdk/go/protocol.go +0 -324
  155. package/sdk/go/protocol_test.go +0 -334
  156. package/sdk/go/replay.go +0 -121
  157. package/sdk/go/replay_test.go +0 -149
  158. package/sdk/go/webhook.go +0 -136
  159. package/sdk/pq/package-lock.json +0 -1358
  160. package/sdk/pq/package.json +0 -42
  161. package/sdk/pq/src/index.test.ts +0 -143
  162. package/sdk/pq/src/index.ts +0 -166
  163. package/sdk/pq/tsconfig.json +0 -14
  164. package/sdk/pq/vitest.config.ts +0 -7
  165. package/sdk/python/README.md +0 -18
  166. package/sdk/python/protocol_7h3/__init__.py +0 -46
  167. package/sdk/python/protocol_7h3/encryption.py +0 -252
  168. package/sdk/python/protocol_7h3/http.py +0 -212
  169. package/sdk/python/protocol_7h3/keys.py +0 -149
  170. package/sdk/python/protocol_7h3/pq.py +0 -244
  171. package/sdk/python/protocol_7h3/protocol.py +0 -525
  172. package/sdk/python/protocol_7h3/queue.py +0 -118
  173. package/sdk/python/protocol_7h3/replay.py +0 -98
  174. package/sdk/python/protocol_7h3/webhook.py +0 -116
  175. package/sdk/python/pyproject.toml +0 -40
  176. package/sdk/python/tests/test_conformance.py +0 -110
  177. package/sdk/python/tests/test_encryption.py +0 -206
  178. package/sdk/python/tests/test_http.py +0 -305
  179. package/sdk/python/tests/test_keys.py +0 -417
  180. package/sdk/python/tests/test_queue.py +0 -120
  181. package/sdk/python/tests/test_webhook.py +0 -345
  182. package/sdk/rust/Cargo.lock +0 -371
  183. package/sdk/rust/Cargo.toml +0 -25
  184. package/sdk/rust/README.md +0 -31
  185. package/sdk/rust/fuzz/Cargo.toml +0 -29
  186. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  187. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  188. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  189. package/sdk/rust/src/http.rs +0 -145
  190. package/sdk/rust/src/keys.rs +0 -161
  191. package/sdk/rust/src/lib.rs +0 -688
  192. package/sdk/rust/src/queue.rs +0 -79
  193. package/sdk/rust/src/webhook.rs +0 -86
  194. package/sdk/rust/tests/conformance.rs +0 -148
  195. package/sdk/rust/tests/gateway.rs +0 -130
  196. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  197. package/sdk/rust/tests/keys.rs +0 -189
  198. package/sdk/threshold/index.d.ts +0 -68
  199. package/sdk/threshold/index.d.ts.map +0 -1
  200. package/sdk/threshold/index.js +0 -254
  201. package/sdk/threshold/package-lock.json +0 -1361
  202. package/sdk/threshold/package.json +0 -39
  203. package/sdk/threshold/src/index.d.ts +0 -68
  204. package/sdk/threshold/src/index.d.ts.map +0 -1
  205. package/sdk/threshold/src/index.js +0 -254
  206. package/sdk/threshold/src/index.test.ts +0 -238
  207. package/sdk/threshold/src/index.ts +0 -355
  208. package/sdk/threshold/tsconfig.json +0 -19
  209. package/sdk/threshold/vitest.config.ts +0 -12
  210. package/src/agentAdapter.test.ts +0 -48
  211. package/src/agentAdapter.ts +0 -56
  212. package/src/auditLog.test.ts +0 -145
  213. package/src/auditLog.ts +0 -147
  214. package/src/capability.test.ts +0 -504
  215. package/src/capability.ts +0 -380
  216. package/src/cborCodec.test.ts +0 -263
  217. package/src/cborCodec.ts +0 -339
  218. package/src/conformance.test.ts +0 -136
  219. package/src/conformanceVectors.ts +0 -99
  220. package/src/encryption.test.ts +0 -206
  221. package/src/encryption.ts +0 -245
  222. package/src/envelopeCbor.ts +0 -140
  223. package/src/frameworkAdapters.test.ts +0 -290
  224. package/src/frameworkAdapters.ts +0 -261
  225. package/src/gateway.test.ts +0 -343
  226. package/src/gateway.ts +0 -246
  227. package/src/grpcBinding.test.ts +0 -211
  228. package/src/grpcBinding.ts +0 -103
  229. package/src/httpBinding.test.ts +0 -376
  230. package/src/httpBinding.ts +0 -189
  231. package/src/index.ts +0 -39
  232. package/src/keyInfra.test.ts +0 -278
  233. package/src/keyInfra.ts +0 -228
  234. package/src/keyRegistry.ts +0 -59
  235. package/src/keyRotation.test.ts +0 -78
  236. package/src/keyRotation.ts +0 -72
  237. package/src/mcpGateway.test.ts +0 -129
  238. package/src/mcpGateway.ts +0 -250
  239. package/src/mcpTransports.test.ts +0 -92
  240. package/src/mcpTransports.ts +0 -169
  241. package/src/mcpWrapper.test.ts +0 -179
  242. package/src/mcpWrapper.ts +0 -206
  243. package/src/otel.ts +0 -136
  244. package/src/policyEnforcer.test.ts +0 -99
  245. package/src/policyEnforcer.ts +0 -169
  246. package/src/policyTelemetryFeedback.test.ts +0 -25
  247. package/src/policyTelemetryFeedback.ts +0 -38
  248. package/src/protocol.bench.ts +0 -37
  249. package/src/protocol.d.ts.map +0 -1
  250. package/src/protocol.js +0 -294
  251. package/src/protocol.test.ts +0 -155
  252. package/src/protocol.ts +0 -414
  253. package/src/protocolAgent.test.ts +0 -105
  254. package/src/protocolAgent.ts +0 -169
  255. package/src/protocolBinary.test.ts +0 -165
  256. package/src/protocolBinary.ts +0 -312
  257. package/src/protocolCapabilities.ts +0 -70
  258. package/src/protocolFuzz.advanced.test.ts +0 -235
  259. package/src/protocolFuzz.test.ts +0 -111
  260. package/src/protocolNegative.test.ts +0 -97
  261. package/src/protocolReplay.test.ts +0 -71
  262. package/src/protocolReplay.ts +0 -194
  263. package/src/protocolTransport.test.ts +0 -556
  264. package/src/protocolTransport.ts +0 -483
  265. package/src/queueBinding.test.ts +0 -130
  266. package/src/queueBinding.ts +0 -102
  267. package/src/rateLimiter.test.ts +0 -96
  268. package/src/rateLimiter.ts +0 -46
  269. package/src/redisIntegration.test.ts +0 -134
  270. package/src/replayStores.test.ts +0 -273
  271. package/src/replayStores.ts +0 -215
  272. package/src/revocation.test.ts +0 -98
  273. package/src/revocation.ts +0 -0
  274. package/src/routePolicy.test.ts +0 -87
  275. package/src/routePolicy.ts +0 -72
  276. package/src/runtimePolicy.test.ts +0 -49
  277. package/src/runtimePolicy.ts +0 -81
  278. package/src/runtimePolicyManager.test.ts +0 -29
  279. package/src/runtimePolicyManager.ts +0 -50
  280. package/src/runtimePolicyPresets.ts +0 -43
  281. package/src/signedResponse.test.ts +0 -111
  282. package/src/signedResponse.ts +0 -83
  283. package/src/stream.test.ts +0 -254
  284. package/src/stream.ts +0 -417
  285. package/src/telemetry.test.ts +0 -251
  286. package/src/telemetry.ts +0 -299
  287. package/src/webhookBinding.test.ts +0 -144
  288. package/src/webhookBinding.ts +0 -115
  289. package/src/wsBinding.test.ts +0 -221
  290. package/src/wsBinding.ts +0 -200
  291. package/tsconfig.json +0 -15
  292. package/tsconfig.lib.json +0 -23
  293. package/vite.lib.config.ts +0 -16
  294. package/vitest.config.ts +0 -11
package/src/auditLog.ts DELETED
@@ -1,147 +0,0 @@
1
- import {
2
- signCanonicalPayloadEd25519,
3
- verifyCanonicalPayloadEd25519,
4
- } from './protocol'
5
-
6
- export type AuditEventType =
7
- | 'verify-ok'
8
- | 'verify-fail'
9
- | 'rate-limited'
10
- | 'sender-denied'
11
- | 'response-signed'
12
-
13
- export interface AuditEntry {
14
- id: string
15
- timestampMs: number
16
- type: AuditEventType
17
- sender?: string
18
- path?: string
19
- method?: string
20
- envelopeId?: string
21
- failReason?: string
22
- upstream?: string
23
- responseStatus?: number
24
- entrySignature: string // Ed25519 sig over the entry (minus entrySignature itself)
25
- }
26
-
27
- /**
28
- * Produce a canonical payload string from an AuditEntry, excluding entrySignature.
29
- * Uses explicit key order and omits undefined fields for determinism.
30
- */
31
- function canonicalAuditPayload(entry: Omit<AuditEntry, 'entrySignature'> & { entrySignature?: string }): string {
32
- const parts: string[] = [
33
- `"id":${JSON.stringify(entry.id)}`,
34
- `"timestampMs":${entry.timestampMs}`,
35
- `"type":${JSON.stringify(entry.type)}`,
36
- ]
37
- if (entry.sender !== undefined) parts.push(`"sender":${JSON.stringify(entry.sender)}`)
38
- if (entry.path !== undefined) parts.push(`"path":${JSON.stringify(entry.path)}`)
39
- if (entry.method !== undefined) parts.push(`"method":${JSON.stringify(entry.method)}`)
40
- if (entry.envelopeId !== undefined) parts.push(`"envelopeId":${JSON.stringify(entry.envelopeId)}`)
41
- if (entry.failReason !== undefined) parts.push(`"failReason":${JSON.stringify(entry.failReason)}`)
42
- if (entry.upstream !== undefined) parts.push(`"upstream":${JSON.stringify(entry.upstream)}`)
43
- if (entry.responseStatus !== undefined) parts.push(`"responseStatus":${entry.responseStatus}`)
44
- return `{${parts.join(',')}}`
45
- }
46
-
47
- export interface AuditLogger {
48
- log(event: Omit<AuditEntry, 'id' | 'timestampMs' | 'entrySignature'>): Promise<void>
49
- query(opts?: { type?: AuditEventType; sender?: string; since?: number; limit?: number }): Promise<AuditEntry[]>
50
- verify(entry: AuditEntry, publicKey: string): Promise<boolean>
51
- }
52
-
53
- class InMemoryAuditLog implements AuditLogger {
54
- private entries: AuditEntry[] = []
55
- private privateKey: string
56
- private maxEntries: number
57
-
58
- constructor(privateKey: string, maxEntries = 10_000) {
59
- this.privateKey = privateKey
60
- this.maxEntries = maxEntries
61
- }
62
-
63
- async log(event: Omit<AuditEntry, 'id' | 'timestampMs' | 'entrySignature'>): Promise<void> {
64
- const id = `audit-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
65
- const timestampMs = Date.now()
66
-
67
- const partial: Omit<AuditEntry, 'entrySignature'> = { id, timestampMs, ...event }
68
- const payload = canonicalAuditPayload(partial)
69
- const entrySignature = await signCanonicalPayloadEd25519(payload, this.privateKey)
70
-
71
- const entry: AuditEntry = { ...partial, entrySignature }
72
-
73
- if (this.entries.length >= this.maxEntries) {
74
- this.entries.shift()
75
- }
76
- this.entries.push(entry)
77
- }
78
-
79
- async query(opts?: {
80
- type?: AuditEventType
81
- sender?: string
82
- since?: number
83
- limit?: number
84
- }): Promise<AuditEntry[]> {
85
- let results = [...this.entries]
86
-
87
- if (opts?.type !== undefined) {
88
- results = results.filter(e => e.type === opts.type)
89
- }
90
- if (opts?.sender !== undefined) {
91
- results = results.filter(e => e.sender === opts.sender)
92
- }
93
- if (opts?.since !== undefined) {
94
- results = results.filter(e => e.timestampMs >= opts.since!)
95
- }
96
- if (opts?.limit !== undefined) {
97
- results = results.slice(-opts.limit)
98
- }
99
-
100
- return results
101
- }
102
-
103
- async verify(entry: AuditEntry, publicKey: string): Promise<boolean> {
104
- const partial: Omit<AuditEntry, 'entrySignature'> = {
105
- id: entry.id,
106
- timestampMs: entry.timestampMs,
107
- type: entry.type,
108
- sender: entry.sender,
109
- path: entry.path,
110
- method: entry.method,
111
- envelopeId: entry.envelopeId,
112
- failReason: entry.failReason,
113
- upstream: entry.upstream,
114
- responseStatus: entry.responseStatus,
115
- }
116
- const payload = canonicalAuditPayload(partial)
117
- return verifyCanonicalPayloadEd25519(payload, entry.entrySignature, publicKey)
118
- }
119
-
120
- size(): number {
121
- return this.entries.length
122
- }
123
- }
124
-
125
- class NoopAuditLog implements AuditLogger {
126
- async log(_event: Omit<AuditEntry, 'id' | 'timestampMs' | 'entrySignature'>): Promise<void> {}
127
- async query(_opts?: {
128
- type?: AuditEventType
129
- sender?: string
130
- since?: number
131
- limit?: number
132
- }): Promise<AuditEntry[]> {
133
- return []
134
- }
135
- async verify(_entry: AuditEntry, _publicKey: string): Promise<boolean> {
136
- return false
137
- }
138
- size(): number {
139
- return 0
140
- }
141
- }
142
-
143
- export function createAuditLog(privateKey: string, opts?: { maxEntries?: number }): InMemoryAuditLog {
144
- return new InMemoryAuditLog(privateKey, opts?.maxEntries)
145
- }
146
-
147
- export { InMemoryAuditLog, NoopAuditLog }
@@ -1,504 +0,0 @@
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
- })