@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/telemetry.ts DELETED
@@ -1,299 +0,0 @@
1
- /**
2
- * telemetry.ts — Prometheus metrics for 7h3 Protocol
3
- *
4
- * Zero runtime dependencies. Plain in-memory counters and histograms rendered
5
- * to standard Prometheus text exposition format.
6
- */
7
-
8
- // ─── Types ───────────────────────────────────────────────────────────────────
9
-
10
- export interface TelemetryConfig {
11
- enabled?: boolean
12
- prefix?: string // default '7h3'
13
- }
14
-
15
- export interface Counter {
16
- increment(labels?: Record<string, string>): void
17
- value(labels?: Record<string, string>): number
18
- }
19
-
20
- export interface HistogramSnapshot {
21
- count: number
22
- sum: number
23
- buckets: Record<string, number> // upper bound (as string) → cumulative count
24
- }
25
-
26
- export interface Histogram {
27
- observe(value: number, labels?: Record<string, string>): void
28
- snapshot(labels?: Record<string, string>): HistogramSnapshot
29
- }
30
-
31
- // ─── Helpers ─────────────────────────────────────────────────────────────────
32
-
33
- function labelKey(labels?: Record<string, string>): string {
34
- if (!labels || Object.keys(labels).length === 0) return '__default__'
35
- return Object.entries(labels)
36
- .sort(([a], [b]) => a.localeCompare(b))
37
- .map(([k, v]) => `${k}=${v}`)
38
- .join(',')
39
- }
40
-
41
- function renderLabels(labels?: Record<string, string>): string {
42
- if (!labels || Object.keys(labels).length === 0) return ''
43
- const parts = Object.entries(labels)
44
- .sort(([a], [b]) => a.localeCompare(b))
45
- .map(([k, v]) => `${k}="${v}"`)
46
- return `{${parts.join(',')}}`
47
- }
48
-
49
- // ─── SimpleCounter ────────────────────────────────────────────────────────────
50
-
51
- export class SimpleCounter implements Counter {
52
- private counts = new Map<string, number>()
53
- private labelSets = new Map<string, Record<string, string> | undefined>()
54
-
55
- increment(labels?: Record<string, string>): void {
56
- const key = labelKey(labels)
57
- this.counts.set(key, (this.counts.get(key) ?? 0) + 1)
58
- if (!this.labelSets.has(key)) {
59
- this.labelSets.set(key, labels)
60
- }
61
- }
62
-
63
- value(labels?: Record<string, string>): number {
64
- return this.counts.get(labelKey(labels)) ?? 0
65
- }
66
-
67
- entries(): Array<{ labels?: Record<string, string>; value: number }> {
68
- const result: Array<{ labels?: Record<string, string>; value: number }> = []
69
- for (const [key, value] of this.counts) {
70
- result.push({ labels: this.labelSets.get(key), value })
71
- }
72
- return result
73
- }
74
- }
75
-
76
- // ─── SimpleHistogram ──────────────────────────────────────────────────────────
77
-
78
- interface BucketState {
79
- count: number
80
- sum: number
81
- // bucket upper bounds → cumulative count (populated on snapshot)
82
- observations: number[]
83
- }
84
-
85
- export class SimpleHistogram implements Histogram {
86
- private bucketBounds: number[]
87
- private states = new Map<string, BucketState>()
88
- private labelSets = new Map<string, Record<string, string> | undefined>()
89
-
90
- constructor(buckets: number[] = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]) {
91
- this.bucketBounds = [...buckets].sort((a, b) => a - b)
92
- }
93
-
94
- observe(value: number, labels?: Record<string, string>): void {
95
- const key = labelKey(labels)
96
- if (!this.states.has(key)) {
97
- this.states.set(key, { count: 0, sum: 0, observations: [] })
98
- this.labelSets.set(key, labels)
99
- }
100
- const state = this.states.get(key)!
101
- state.count++
102
- state.sum += value
103
- state.observations.push(value)
104
- }
105
-
106
- snapshot(labels?: Record<string, string>): HistogramSnapshot {
107
- const key = labelKey(labels)
108
- const state = this.states.get(key) ?? { count: 0, sum: 0, observations: [] }
109
-
110
- const buckets: Record<string, number> = {}
111
- for (const bound of this.bucketBounds) {
112
- buckets[String(bound)] = state.observations.filter(v => v <= bound).length
113
- }
114
- // +Inf bucket
115
- buckets['+Inf'] = state.count
116
-
117
- return { count: state.count, sum: state.sum, buckets }
118
- }
119
-
120
- entries(): Array<{ labels?: Record<string, string>; snapshot: HistogramSnapshot }> {
121
- const result: Array<{ labels?: Record<string, string>; snapshot: HistogramSnapshot }> = []
122
- for (const [key] of this.states) {
123
- const labels = this.labelSets.get(key)
124
- result.push({ labels, snapshot: this.snapshot(labels) })
125
- }
126
- return result
127
- }
128
-
129
- getBounds(): number[] {
130
- return [...this.bucketBounds]
131
- }
132
- }
133
-
134
- // ─── Protocol7h3Metrics ───────────────────────────────────────────────────────
135
-
136
- export class Protocol7h3Metrics {
137
- /** labels: result (ok|fail), alg (ED25519|HS256|none), transport (http|ws|grpc|queue|webhook) */
138
- verifications_total = new SimpleCounter()
139
-
140
- /** buckets in ms */
141
- verification_duration_ms = new SimpleHistogram([0.1, 0.5, 1, 5, 10, 50, 100])
142
-
143
- /** labels: sender, path */
144
- rate_limit_hits_total = new SimpleCounter()
145
-
146
- /** labels: sender, path */
147
- sender_denials_total = new SimpleCounter()
148
-
149
- /** labels: transport */
150
- replay_detections_total = new SimpleCounter()
151
-
152
- /** labels: type */
153
- audit_entries_total = new SimpleCounter()
154
-
155
- /** labels: transport — use for WS/gRPC connection tracking */
156
- active_connections = new SimpleCounter()
157
- }
158
-
159
- // ─── Global instance ──────────────────────────────────────────────────────────
160
-
161
- export const metrics = new Protocol7h3Metrics()
162
-
163
- // ─── Prometheus text format renderer ─────────────────────────────────────────
164
-
165
- export function renderPrometheusText(m: Protocol7h3Metrics, prefix = '7h3'): string {
166
- const lines: string[] = []
167
-
168
- // Helper: emit a counter
169
- function emitCounter(name: string, help: string, counter: SimpleCounter): void {
170
- const fullName = `${prefix}_${name}`
171
- lines.push(`# HELP ${fullName} ${help}`)
172
- lines.push(`# TYPE ${fullName} counter`)
173
- const entries = counter.entries()
174
- if (entries.length === 0) {
175
- lines.push(`${fullName} 0`)
176
- } else {
177
- for (const { labels, value } of entries) {
178
- if (labels && Object.keys(labels).length > 0) {
179
- lines.push(`${fullName}${renderLabels(labels)} ${value}`)
180
- } else {
181
- lines.push(`${fullName} ${value}`)
182
- }
183
- }
184
- }
185
- }
186
-
187
- // Helper: emit a histogram
188
- function emitHistogram(name: string, help: string, histogram: SimpleHistogram): void {
189
- const fullName = `${prefix}_${name}`
190
- lines.push(`# HELP ${fullName} ${help}`)
191
- lines.push(`# TYPE ${fullName} histogram`)
192
- const entries = histogram.entries()
193
- if (entries.length === 0) {
194
- // Emit empty histogram with zero counts
195
- for (const bound of histogram.getBounds()) {
196
- lines.push(`${fullName}_bucket{le="${bound}"} 0`)
197
- }
198
- lines.push(`${fullName}_bucket{le="+Inf"} 0`)
199
- lines.push(`${fullName}_sum 0`)
200
- lines.push(`${fullName}_count 0`)
201
- } else {
202
- for (const { labels, snapshot } of entries) {
203
- const labelStr = labels && Object.keys(labels).length > 0
204
- ? renderLabels(labels)
205
- : ''
206
-
207
- for (const [bound, count] of Object.entries(snapshot.buckets)) {
208
- if (bound === '+Inf') continue
209
- const bucketLabels = labelStr
210
- ? labelStr.slice(0, -1) + `,le="${bound}"}`
211
- : `{le="${bound}"}`
212
- lines.push(`${fullName}_bucket${bucketLabels} ${count}`)
213
- }
214
- // +Inf bucket
215
- const infLabels = labelStr
216
- ? labelStr.slice(0, -1) + `,le="+Inf"}`
217
- : `{le="+Inf"}`
218
- lines.push(`${fullName}_bucket${infLabels} ${snapshot.count}`)
219
- lines.push(`${fullName}_sum${labelStr} ${snapshot.sum}`)
220
- lines.push(`${fullName}_count${labelStr} ${snapshot.count}`)
221
- }
222
- }
223
- }
224
-
225
- emitCounter(
226
- 'verifications_total',
227
- 'Total number of AIP envelope verifications, by result, algorithm, and transport',
228
- m.verifications_total,
229
- )
230
-
231
- emitHistogram(
232
- 'verification_duration_ms',
233
- 'Verification latency in milliseconds',
234
- m.verification_duration_ms,
235
- )
236
-
237
- emitCounter(
238
- 'rate_limit_hits_total',
239
- 'Total number of rate-limit rejections, by sender and path',
240
- m.rate_limit_hits_total,
241
- )
242
-
243
- emitCounter(
244
- 'sender_denials_total',
245
- 'Total number of sender-denied (403) rejections, by sender and path',
246
- m.sender_denials_total,
247
- )
248
-
249
- emitCounter(
250
- 'replay_detections_total',
251
- 'Total number of replay-detected events, by transport',
252
- m.replay_detections_total,
253
- )
254
-
255
- emitCounter(
256
- 'audit_entries_total',
257
- 'Total number of audit log entries written, by type',
258
- m.audit_entries_total,
259
- )
260
-
261
- emitCounter(
262
- 'active_connections',
263
- 'Current active connections, by transport (WS/gRPC)',
264
- m.active_connections,
265
- )
266
-
267
- return lines.join('\n') + '\n'
268
- }
269
-
270
- // ─── Node.js http-compatible metrics middleware ───────────────────────────────
271
-
272
- type NodeReq = { url?: string; method?: string }
273
- type NodeRes = {
274
- writeHead(status: number, headers: Record<string, string>): void
275
- end(body: string): void
276
- }
277
- type NextFn = () => void
278
-
279
- /**
280
- * Returns a Node.js http-compatible middleware that serves Prometheus metrics
281
- * at the given path (default: /metrics).
282
- */
283
- export function createMetricsMiddleware(
284
- path = '/metrics',
285
- m: Protocol7h3Metrics = metrics,
286
- prefix = '7h3',
287
- ): (req: NodeReq, res: NodeRes, next: NextFn) => void {
288
- return (req, res, next) => {
289
- if (req.url === path && (req.method === 'GET' || req.method === undefined)) {
290
- const body = renderPrometheusText(m, prefix)
291
- res.writeHead(200, {
292
- 'content-type': 'text/plain; version=0.0.4; charset=utf-8',
293
- })
294
- res.end(body)
295
- } else {
296
- next()
297
- }
298
- }
299
- }
@@ -1,144 +0,0 @@
1
- import { describe, it, expect } from 'vitest'
2
- import {
3
- signWebhook,
4
- verifyWebhook,
5
- signWebhookHmac,
6
- verifyWebhookHmac,
7
- consumeWebhook,
8
- generateEd25519KeypairBase64Url,
9
- WEBHOOK_SIG_HEADER,
10
- WEBHOOK_TS_HEADER,
11
- } from './webhookBinding'
12
-
13
- describe('webhookBinding', () => {
14
- // 1. Ed25519 sign + verify round trip
15
- it('signWebhook + verifyWebhook round trip (Ed25519)', async () => {
16
- const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
17
- const payload = JSON.stringify({ event: 'user.created', userId: '123' })
18
- const headers = await signWebhook(payload, { privateKey })
19
- const valid = await verifyWebhook(payload, headers, { publicKey })
20
- expect(valid).toBe(true)
21
- })
22
-
23
- // 2. HMAC sign + verify round trip
24
- it('signWebhookHmac + verifyWebhookHmac round trip', async () => {
25
- const secret = 'super-secret-webhook-key'
26
- const payload = JSON.stringify({ event: 'order.paid', orderId: 'abc' })
27
- const headers = await signWebhookHmac(payload, { secret })
28
- const valid = await verifyWebhookHmac(payload, headers, { secret })
29
- expect(valid).toBe(true)
30
- })
31
-
32
- // 3. Tampered payload returns false (Ed25519)
33
- it('tampered payload returns false (Ed25519)', async () => {
34
- const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
35
- const payload = JSON.stringify({ event: 'user.created', userId: '123' })
36
- const headers = await signWebhook(payload, { privateKey })
37
- const tamperedPayload = JSON.stringify({ event: 'user.created', userId: '999' })
38
- const valid = await verifyWebhook(tamperedPayload, headers, { publicKey })
39
- expect(valid).toBe(false)
40
- })
41
-
42
- // 3b. Tampered payload returns false (HMAC)
43
- it('tampered payload returns false (HMAC)', async () => {
44
- const secret = 'super-secret-webhook-key'
45
- const payload = JSON.stringify({ event: 'order.paid', orderId: 'abc' })
46
- const headers = await signWebhookHmac(payload, { secret })
47
- const tamperedPayload = JSON.stringify({ event: 'order.paid', orderId: 'TAMPERED' })
48
- const valid = await verifyWebhookHmac(tamperedPayload, headers, { secret })
49
- expect(valid).toBe(false)
50
- })
51
-
52
- // 4. Expired timestamp returns false
53
- it('expired timestamp returns false', async () => {
54
- const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
55
- const payload = JSON.stringify({ event: 'ping' })
56
- const headers = await signWebhook(payload, { privateKey })
57
- // Backdate the timestamp to be 10 minutes ago
58
- const expiredHeaders = {
59
- ...headers,
60
- [WEBHOOK_TS_HEADER]: String(Date.now() - 10 * 60 * 1000),
61
- }
62
- const valid = await verifyWebhook(payload, expiredHeaders, { publicKey, maxAgeMs: 300_000 })
63
- expect(valid).toBe(false)
64
- })
65
-
66
- // 5. Wrong key returns false
67
- it('wrong public key returns false', async () => {
68
- const { privateKey } = await generateEd25519KeypairBase64Url()
69
- const { publicKey: wrongPublicKey } = await generateEd25519KeypairBase64Url()
70
- const payload = JSON.stringify({ event: 'test' })
71
- const headers = await signWebhook(payload, { privateKey })
72
- const valid = await verifyWebhook(payload, headers, { publicKey: wrongPublicKey })
73
- expect(valid).toBe(false)
74
- })
75
-
76
- // 5b. Wrong HMAC secret returns false
77
- it('wrong HMAC secret returns false', async () => {
78
- const secret = 'correct-secret'
79
- const payload = JSON.stringify({ event: 'test' })
80
- const headers = await signWebhookHmac(payload, { secret })
81
- const valid = await verifyWebhookHmac(payload, headers, { secret: 'wrong-secret' })
82
- expect(valid).toBe(false)
83
- })
84
-
85
- // 6. consumeWebhook parses valid payload
86
- it('consumeWebhook parses valid payload and returns parsed object', async () => {
87
- const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
88
- const data = { event: 'invoice.paid', amount: 9900, currency: 'usd' }
89
- const payload = JSON.stringify(data)
90
- const headers = await signWebhook(payload, { privateKey })
91
- const result = await consumeWebhook<typeof data>(payload, headers as Record<string, string>, { publicKey })
92
- expect(result).toEqual(data)
93
- })
94
-
95
- // 7. consumeWebhook throws on invalid signature
96
- it('consumeWebhook throws on invalid signature', async () => {
97
- const { privateKey } = await generateEd25519KeypairBase64Url()
98
- const { publicKey: wrongPublicKey } = await generateEd25519KeypairBase64Url()
99
- const payload = JSON.stringify({ event: 'invoice.paid' })
100
- const headers = await signWebhook(payload, { privateKey })
101
- await expect(
102
- consumeWebhook(payload, headers as Record<string, string>, { publicKey: wrongPublicKey })
103
- ).rejects.toThrow('7h3: webhook signature verification failed')
104
- })
105
-
106
- // 7b. consumeWebhook throws on expired timestamp
107
- it('consumeWebhook throws on expired timestamp', async () => {
108
- const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
109
- const payload = JSON.stringify({ event: 'test' })
110
- const headers = await signWebhook(payload, { privateKey })
111
- const expiredHeaders = {
112
- ...headers,
113
- [WEBHOOK_TS_HEADER]: String(Date.now() - 10 * 60 * 1000),
114
- }
115
- await expect(
116
- consumeWebhook(payload, expiredHeaders as Record<string, string>, { publicKey, maxAgeMs: 300_000 })
117
- ).rejects.toThrow('7h3: webhook signature verification failed')
118
- })
119
-
120
- // Edge: missing headers return false
121
- it('missing sig header returns false', async () => {
122
- const { publicKey } = await generateEd25519KeypairBase64Url()
123
- const payload = 'hello'
124
- const valid = await verifyWebhook(payload, { [WEBHOOK_TS_HEADER]: String(Date.now()) } as Record<string, string>, { publicKey })
125
- expect(valid).toBe(false)
126
- })
127
-
128
- it('missing ts header returns false', async () => {
129
- const { publicKey } = await generateEd25519KeypairBase64Url()
130
- const payload = 'hello'
131
- const valid = await verifyWebhook(payload, { [WEBHOOK_SIG_HEADER]: 'fakesig' } as Record<string, string>, { publicKey })
132
- expect(valid).toBe(false)
133
- })
134
-
135
- // Uint8Array payload works (Ed25519)
136
- it('Uint8Array payload signs and verifies (Ed25519)', async () => {
137
- const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
138
- const payloadStr = JSON.stringify({ binary: true })
139
- const payloadBytes = new TextEncoder().encode(payloadStr)
140
- const headers = await signWebhook(payloadBytes, { privateKey })
141
- const valid = await verifyWebhook(payloadBytes, headers, { publicKey })
142
- expect(valid).toBe(true)
143
- })
144
- })
@@ -1,115 +0,0 @@
1
- import {
2
- signCanonicalPayloadEd25519,
3
- verifyCanonicalPayloadEd25519,
4
- signCanonicalPayloadHmac,
5
- verifyCanonicalPayloadHmac,
6
- generateEd25519KeypairBase64Url,
7
- } from './protocol'
8
-
9
- export const WEBHOOK_SIG_HEADER = 'x-7h3-sig'
10
- export const WEBHOOK_TS_HEADER = 'x-7h3-ts'
11
- export const WEBHOOK_DEFAULT_TTL_MS = 300_000 // 5 minutes
12
-
13
- // What gets signed: "${timestampMs}.${rawBody}" — binds time AND content
14
- function webhookSigningPayload(timestampMs: number, body: string): string {
15
- return `${timestampMs}.${body}`
16
- }
17
-
18
- export interface WebhookSignOptions {
19
- privateKey: string // Ed25519 PKCS8 base64url
20
- ttlMs?: number // default 5 min
21
- }
22
-
23
- export interface WebhookSignHmacOptions {
24
- secret: string
25
- ttlMs?: number
26
- }
27
-
28
- export interface WebhookVerifyOptions {
29
- publicKey: string // Ed25519 SPKI base64url
30
- maxAgeMs?: number // default 5 min
31
- }
32
-
33
- export interface WebhookVerifyHmacOptions {
34
- secret: string
35
- maxAgeMs?: number
36
- }
37
-
38
- export interface WebhookHeaders {
39
- [WEBHOOK_SIG_HEADER]: string
40
- [WEBHOOK_TS_HEADER]: string
41
- }
42
-
43
- // Sign a webhook payload with Ed25519
44
- export async function signWebhook(
45
- payload: string | Uint8Array,
46
- opts: WebhookSignOptions
47
- ): Promise<WebhookHeaders> {
48
- const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
49
- const timestampMs = Date.now()
50
- const signingPayload = webhookSigningPayload(timestampMs, body)
51
- const sig = await signCanonicalPayloadEd25519(signingPayload, opts.privateKey)
52
- return { [WEBHOOK_SIG_HEADER]: sig, [WEBHOOK_TS_HEADER]: String(timestampMs) }
53
- }
54
-
55
- // Sign with HMAC shared secret
56
- export async function signWebhookHmac(
57
- payload: string | Uint8Array,
58
- opts: WebhookSignHmacOptions
59
- ): Promise<WebhookHeaders> {
60
- const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
61
- const timestampMs = Date.now()
62
- const signingPayload = webhookSigningPayload(timestampMs, body)
63
- const sig = await signCanonicalPayloadHmac(signingPayload, opts.secret)
64
- return { [WEBHOOK_SIG_HEADER]: sig, [WEBHOOK_TS_HEADER]: String(timestampMs) }
65
- }
66
-
67
- // Verify Ed25519 webhook signature
68
- export async function verifyWebhook(
69
- payload: string | Uint8Array,
70
- headers: WebhookHeaders | Record<string, string>,
71
- opts: WebhookVerifyOptions
72
- ): Promise<boolean> {
73
- const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
74
- const sig = headers[WEBHOOK_SIG_HEADER]
75
- const tsStr = headers[WEBHOOK_TS_HEADER]
76
- if (!sig || !tsStr) return false
77
- const ts = Number(tsStr)
78
- if (!Number.isFinite(ts)) return false
79
- const maxAge = opts.maxAgeMs ?? WEBHOOK_DEFAULT_TTL_MS
80
- if (Date.now() - ts > maxAge) return false
81
- const signingPayload = webhookSigningPayload(ts, body)
82
- return verifyCanonicalPayloadEd25519(signingPayload, sig, opts.publicKey)
83
- }
84
-
85
- // Verify HMAC webhook signature
86
- export async function verifyWebhookHmac(
87
- payload: string | Uint8Array,
88
- headers: WebhookHeaders | Record<string, string>,
89
- opts: WebhookVerifyHmacOptions
90
- ): Promise<boolean> {
91
- const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
92
- const sig = headers[WEBHOOK_SIG_HEADER]
93
- const tsStr = headers[WEBHOOK_TS_HEADER]
94
- if (!sig || !tsStr) return false
95
- const ts = Number(tsStr)
96
- if (!Number.isFinite(ts)) return false
97
- const maxAge = opts.maxAgeMs ?? WEBHOOK_DEFAULT_TTL_MS
98
- if (Date.now() - ts > maxAge) return false
99
- const signingPayload = webhookSigningPayload(ts, body)
100
- return verifyCanonicalPayloadHmac(signingPayload, sig, opts.secret)
101
- }
102
-
103
- // Parse and verify in one call, throws on failure
104
- export async function consumeWebhook<T = unknown>(
105
- payload: string,
106
- headers: Record<string, string>,
107
- opts: WebhookVerifyOptions
108
- ): Promise<T> {
109
- const valid = await verifyWebhook(payload, headers, opts)
110
- if (!valid) throw new Error('7h3: webhook signature verification failed')
111
- return JSON.parse(payload) as T
112
- }
113
-
114
- // Re-export key generation for convenience
115
- export { generateEd25519KeypairBase64Url }