@7h3/protocol 0.1.2 → 0.4.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 (230) hide show
  1. package/.dockerignore +19 -0
  2. package/.github/dependabot.yml +32 -0
  3. package/.github/workflows/ci.yml +31 -0
  4. package/.github/workflows/publish.yml +59 -0
  5. package/.github/workflows/scorecard.yml +37 -0
  6. package/7h3.example.yaml +125 -0
  7. package/CHANGELOG.md +92 -0
  8. package/CONTRIBUTING.md +82 -0
  9. package/Dockerfile +73 -0
  10. package/GOVERNANCE.md +62 -0
  11. package/README.md +323 -6
  12. package/SECURITY.md +70 -0
  13. package/bench-results/replay-cache-full-1777891033256.json +10 -0
  14. package/bench-results/replay-cache-full-1777896317488.json +10 -0
  15. package/bench-results/replay-cache-full-1777900993184.json +10 -0
  16. package/bench-results/replay-cache-full-1777901019285.json +10 -0
  17. package/bench-results/replay-cache-quick-1777870170126.json +10 -0
  18. package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
  19. package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
  20. package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
  21. package/bench-results/wire-codecs-full-1777891019803.json +93 -0
  22. package/bench-results/wire-codecs-full-1777896260964.json +93 -0
  23. package/bench-results/wire-codecs-full-1777901004247.json +93 -0
  24. package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
  25. package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
  26. package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
  27. package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
  28. package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
  29. package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
  30. package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
  31. package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
  32. package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
  33. package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
  34. package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
  35. package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
  36. package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
  37. package/bin/7h3.ts +385 -0
  38. package/conformance/7h3_v0_1.json +77 -0
  39. package/conformance/7h3_v0_1_binary.json +20 -0
  40. package/conformance/aip_v0_1_binary.json +20 -0
  41. package/docker-compose.yaml +77 -0
  42. package/docs/ADOPTION_PLAN.md +120 -0
  43. package/docs/AGENTS.md +77 -0
  44. package/docs/AIP_RFC_v0.1.md +97 -0
  45. package/docs/AI_DECISION_CARD.md +122 -0
  46. package/docs/AI_RUNTIME_POLICY.json +126 -0
  47. package/docs/AI_RUNTIME_POLICY.yaml +110 -0
  48. package/docs/BACKPRESSURE_TUNING.md +65 -0
  49. package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
  50. package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
  51. package/docs/BINARY_CODEC_BENCH.md +23 -0
  52. package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
  53. package/docs/CLOCK_SKEW_POLICY.md +30 -0
  54. package/docs/DISTRIBUTED_REPLAY.md +142 -0
  55. package/docs/FUZZ_CAMPAIGN.md +121 -0
  56. package/docs/GATEWAY.md +195 -0
  57. package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
  58. package/docs/KEY_REVOCATION.md +69 -0
  59. package/docs/MCP_WRAPPER.md +159 -0
  60. package/docs/MIGRATION_GUIDE.md +40 -0
  61. package/docs/OPERATORS.md +184 -0
  62. package/docs/PERF_REGRESSION_POLICY.md +34 -0
  63. package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
  64. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
  65. package/docs/RELEASE_GATE.md +25 -0
  66. package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
  67. package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
  68. package/docs/TELEMETRY.md +41 -0
  69. package/docs/THREAT_MODEL.md +89 -0
  70. package/docs/VERSIONING_POLICY.md +30 -0
  71. package/docs/assets/banner.png +0 -0
  72. package/eslint.config.js +15 -0
  73. package/fuzz/ts/harness-decode.ts +136 -0
  74. package/fuzz/ts/harness-verify.ts +121 -0
  75. package/fuzz/ts/run.ts +35 -0
  76. package/mcp-server/README.md +38 -0
  77. package/mcp-server/package-lock.json +1187 -0
  78. package/mcp-server/package.json +35 -0
  79. package/mcp-server/src/index.ts +236 -0
  80. package/mcp-server/tsconfig.json +14 -0
  81. package/package.json +79 -13
  82. package/scripts/aip-framework-quickstart.ts +110 -0
  83. package/scripts/aip-mcp-gateway.ts +38 -0
  84. package/scripts/aip-mcp-wrap-demo.ts +72 -0
  85. package/scripts/aip-quickstart.ts +60 -0
  86. package/scripts/bench-diff.ts +118 -0
  87. package/scripts/bench-protocol-e2e.ts +937 -0
  88. package/scripts/bench-protocol-openloop.ts +1397 -0
  89. package/scripts/bench-replay-cache.ts +76 -0
  90. package/scripts/bench-signature-profiles.ts +180 -0
  91. package/scripts/bench-wire-codecs.ts +161 -0
  92. package/scripts/build-binary-conformance.ts +36 -0
  93. package/scripts/build-release-dashboard.ts +175 -0
  94. package/scripts/canary-rollout.ts +38 -0
  95. package/scripts/mcpGatewayCli.test.ts +116 -0
  96. package/scripts/prepare-aip-package.ts +88 -0
  97. package/scripts/regen-conformance-sigs.ts +18 -0
  98. package/scripts/release-gate.ts +19 -0
  99. package/scripts/validate-runtime-policy.ts +18 -0
  100. package/sdk/browser/index.test.ts +162 -0
  101. package/sdk/browser/index.ts +257 -0
  102. package/sdk/browser/package.json +13 -0
  103. package/sdk/go/go.mod +3 -0
  104. package/sdk/go/http.go +135 -0
  105. package/sdk/go/protocol.go +324 -0
  106. package/sdk/go/protocol_test.go +334 -0
  107. package/sdk/go/webhook.go +136 -0
  108. package/sdk/python/README.md +18 -0
  109. package/sdk/python/protocol_7h3/__init__.py +46 -0
  110. package/sdk/python/protocol_7h3/http.py +212 -0
  111. package/sdk/python/protocol_7h3/keys.py +149 -0
  112. package/sdk/python/protocol_7h3/protocol.py +525 -0
  113. package/sdk/python/protocol_7h3/queue.py +118 -0
  114. package/sdk/python/protocol_7h3/webhook.py +116 -0
  115. package/sdk/python/pyproject.toml +40 -0
  116. package/sdk/python/tests/test_conformance.py +110 -0
  117. package/sdk/python/tests/test_http.py +305 -0
  118. package/sdk/python/tests/test_keys.py +417 -0
  119. package/sdk/python/tests/test_queue.py +120 -0
  120. package/sdk/python/tests/test_webhook.py +345 -0
  121. package/sdk/rust/Cargo.lock +371 -0
  122. package/sdk/rust/Cargo.toml +25 -0
  123. package/sdk/rust/README.md +31 -0
  124. package/sdk/rust/fuzz/Cargo.toml +29 -0
  125. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
  126. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
  127. package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
  128. package/sdk/rust/src/http.rs +145 -0
  129. package/sdk/rust/src/keys.rs +161 -0
  130. package/sdk/rust/src/lib.rs +688 -0
  131. package/sdk/rust/src/queue.rs +79 -0
  132. package/sdk/rust/src/webhook.rs +86 -0
  133. package/sdk/rust/tests/conformance.rs +148 -0
  134. package/sdk/rust/tests/gateway.rs +130 -0
  135. package/sdk/rust/tests/http_webhook_queue.rs +201 -0
  136. package/sdk/rust/tests/keys.rs +189 -0
  137. package/src/agentAdapter.test.ts +48 -0
  138. package/src/agentAdapter.ts +56 -0
  139. package/src/auditLog.test.ts +145 -0
  140. package/src/auditLog.ts +147 -0
  141. package/src/conformance.test.ts +136 -0
  142. package/src/conformanceVectors.ts +99 -0
  143. package/src/frameworkAdapters.test.ts +290 -0
  144. package/src/frameworkAdapters.ts +261 -0
  145. package/src/gateway.test.ts +343 -0
  146. package/src/gateway.ts +171 -0
  147. package/src/grpcBinding.test.ts +211 -0
  148. package/src/grpcBinding.ts +103 -0
  149. package/src/httpBinding.test.ts +376 -0
  150. package/src/httpBinding.ts +163 -0
  151. package/src/index.ts +32 -0
  152. package/src/keyInfra.test.ts +278 -0
  153. package/src/keyInfra.ts +228 -0
  154. package/src/keyRegistry.ts +59 -0
  155. package/src/keyRotation.test.ts +78 -0
  156. package/src/keyRotation.ts +72 -0
  157. package/src/mcpGateway.test.ts +129 -0
  158. package/src/mcpGateway.ts +250 -0
  159. package/src/mcpTransports.test.ts +92 -0
  160. package/src/mcpTransports.ts +169 -0
  161. package/src/mcpWrapper.test.ts +179 -0
  162. package/src/mcpWrapper.ts +206 -0
  163. package/src/policyEnforcer.test.ts +99 -0
  164. package/src/policyEnforcer.ts +169 -0
  165. package/src/policyTelemetryFeedback.test.ts +25 -0
  166. package/src/policyTelemetryFeedback.ts +38 -0
  167. package/src/protocol.bench.ts +37 -0
  168. package/src/protocol.test.ts +155 -0
  169. package/src/protocol.ts +413 -0
  170. package/src/protocolAgent.test.ts +105 -0
  171. package/src/protocolAgent.ts +169 -0
  172. package/src/protocolBinary.test.ts +165 -0
  173. package/src/protocolBinary.ts +312 -0
  174. package/src/protocolCapabilities.ts +70 -0
  175. package/src/protocolFuzz.advanced.test.ts +235 -0
  176. package/src/protocolFuzz.test.ts +111 -0
  177. package/src/protocolNegative.test.ts +97 -0
  178. package/src/protocolReplay.test.ts +71 -0
  179. package/src/protocolReplay.ts +194 -0
  180. package/src/protocolTransport.test.ts +556 -0
  181. package/src/protocolTransport.ts +483 -0
  182. package/src/queueBinding.test.ts +130 -0
  183. package/src/queueBinding.ts +102 -0
  184. package/src/rateLimiter.test.ts +96 -0
  185. package/src/rateLimiter.ts +46 -0
  186. package/src/redisClient.ts +140 -0
  187. package/src/redisIntegration.test.ts +134 -0
  188. package/src/replayStores.test.ts +141 -0
  189. package/src/replayStores.ts +82 -0
  190. package/src/revocation.test.ts +98 -0
  191. package/src/revocation.ts +0 -0
  192. package/src/routePolicy.test.ts +87 -0
  193. package/src/routePolicy.ts +72 -0
  194. package/src/runtimePolicy.test.ts +49 -0
  195. package/src/runtimePolicy.ts +81 -0
  196. package/src/runtimePolicyManager.test.ts +29 -0
  197. package/src/runtimePolicyManager.ts +50 -0
  198. package/src/runtimePolicyPresets.ts +43 -0
  199. package/src/signedResponse.test.ts +111 -0
  200. package/src/signedResponse.ts +83 -0
  201. package/src/webhookBinding.test.ts +144 -0
  202. package/src/webhookBinding.ts +115 -0
  203. package/src/wsBinding.test.ts +221 -0
  204. package/src/wsBinding.ts +100 -0
  205. package/tsconfig.json +15 -0
  206. package/tsconfig.lib.json +23 -0
  207. package/vite.lib.config.ts +16 -0
  208. package/agentAdapter.d.ts +0 -26
  209. package/conformanceVectors.d.ts +0 -20
  210. package/frameworkAdapters.d.ts +0 -72
  211. package/index.d.ts +0 -20
  212. package/index.js +0 -1702
  213. package/keyRotation.d.ts +0 -20
  214. package/mcpGateway.d.ts +0 -37
  215. package/mcpTransports.d.ts +0 -62
  216. package/mcpWrapper.d.ts +0 -83
  217. package/policyEnforcer.d.ts +0 -50
  218. package/policyTelemetryFeedback.d.ts +0 -11
  219. package/protocol.d.ts +0 -66
  220. package/protocolAgent.d.ts +0 -58
  221. package/protocolBinary.d.ts +0 -8
  222. package/protocolCapabilities.d.ts +0 -24
  223. package/protocolReplay.d.ts +0 -35
  224. package/protocolTransport.d.ts +0 -73
  225. package/redisClient.d.ts +0 -49
  226. package/replayStores.d.ts +0 -32
  227. package/revocation.d.ts +0 -71
  228. package/runtimePolicy.d.ts +0 -24
  229. package/runtimePolicyManager.d.ts +0 -15
  230. package/runtimePolicyPresets.d.ts +0 -11
@@ -0,0 +1,82 @@
1
+ import type { DistributedReplayStore } from './protocolReplay'
2
+ import { InMemoryRedisLikeClient, type RedisLikeClient } from './redisClient'
3
+
4
+ /**
5
+ * What to do when the Redis client throws (network blip, server down).
6
+ *
7
+ * - `fallback` (default): degrade to a local in-memory store so traffic keeps
8
+ * flowing with single-node replay protection still in force. Quality +
9
+ * reliability + scalability: Redis is never a fleet-wide kill switch.
10
+ * - `reject`: fail closed — deny the message because uniqueness cannot be confirmed.
11
+ * - `allow`: fail open — accept the message (skip the check) to maximise uptime.
12
+ */
13
+ export type ReplayErrorBehavior = 'fallback' | 'reject' | 'allow'
14
+
15
+ export interface RedisReplayStoreOptions {
16
+ /** Key namespace in Redis. Default `aip:replay:`. */
17
+ keyPrefix?: string
18
+ /** Behavior when the Redis client throws. Default `fallback`. */
19
+ errorBehavior?: ReplayErrorBehavior
20
+ /** Local store used when `errorBehavior` is `fallback`. Defaults to an in-memory-backed store. */
21
+ fallback?: DistributedReplayStore
22
+ /** Observability hook fired whenever a Redis error forces degraded handling. */
23
+ onDegraded?: (error: unknown, context: { key: string; behavior: ReplayErrorBehavior }) => void
24
+ }
25
+
26
+ /**
27
+ * Creates a {@link DistributedReplayStore} backed by Redis-style `SET NX PX`.
28
+ *
29
+ * Drop the returned store into `new DistributedReplayCache(store)` (or pass a
30
+ * `DistributedReplayCache` as the transport `replayCache`).
31
+ */
32
+ export function createRedisReplayStore(
33
+ client: RedisLikeClient,
34
+ options: RedisReplayStoreOptions = {},
35
+ ): DistributedReplayStore {
36
+ const keyPrefix = options.keyPrefix ?? 'aip:replay:'
37
+ const errorBehavior = options.errorBehavior ?? 'fallback'
38
+ const onDegraded = options.onDegraded
39
+ const fallback =
40
+ options.fallback ??
41
+ (errorBehavior === 'fallback'
42
+ ? // The local fallback runs over a non-throwing in-memory client, so it
43
+ // needs no fallback of its own — `reject` terminates the chain.
44
+ createRedisReplayStore(new InMemoryRedisLikeClient(), { keyPrefix, errorBehavior: 'reject' })
45
+ : undefined)
46
+
47
+ function degrade(error: unknown, key: string, expiresAtMs: number, nowMs: number): Promise<boolean> | boolean {
48
+ onDegraded?.(error, { key, behavior: errorBehavior })
49
+ if (errorBehavior === 'allow') return true
50
+ if (errorBehavior === 'reject') return false
51
+ return fallback ? fallback.reserve(key, expiresAtMs, nowMs) : false
52
+ }
53
+
54
+ return {
55
+ async reserve(key: string, expiresAtMs: number, nowMs: number): Promise<boolean> {
56
+ const pxMs = Math.max(1, expiresAtMs - nowMs)
57
+ try {
58
+ const result = await client.set(`${keyPrefix}${key}`, '1', { nx: true, pxMs })
59
+ return result === 'OK'
60
+ } catch (error) {
61
+ return degrade(error, key, expiresAtMs, nowMs)
62
+ }
63
+ },
64
+
65
+ async reserveMany(entries: Array<{ key: string; expiresAtMs: number }>, nowMs: number): Promise<boolean[]> {
66
+ if (entries.length === 0) return []
67
+ if (client.pipeline) {
68
+ try {
69
+ const batch = client.pipeline()
70
+ for (const { key, expiresAtMs } of entries) {
71
+ batch.set(`${keyPrefix}${key}`, '1', { nx: true, pxMs: Math.max(1, expiresAtMs - nowMs) })
72
+ }
73
+ const results = await batch.exec()
74
+ return results.map((result) => result === 'OK')
75
+ } catch (error) {
76
+ return Promise.all(entries.map((entry) => degrade(error, entry.key, entry.expiresAtMs, nowMs)))
77
+ }
78
+ }
79
+ return Promise.all(entries.map((entry) => this.reserve(entry.key, entry.expiresAtMs, nowMs)))
80
+ },
81
+ }
82
+ }
@@ -0,0 +1,98 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { InMemoryRedisLikeClient } from './redisClient'
3
+ import {
4
+ InMemoryRevocationStore,
5
+ createRedisRevocationStore,
6
+ withRevocationCheck,
7
+ } from './revocation'
8
+ import type { SignatureVerificationMaterial } from './protocol'
9
+
10
+ describe('InMemoryRevocationStore', () => {
11
+ it('reports a key as not revoked until it is revoked', async () => {
12
+ const store = new InMemoryRevocationStore()
13
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(false)
14
+ await store.revoke('agent.a', 'k1')
15
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(true)
16
+ })
17
+
18
+ it('scopes revocation to the exact (sender, keyId) pair', async () => {
19
+ const store = new InMemoryRevocationStore()
20
+ await store.revoke('agent.a', 'k1')
21
+ expect(await store.isRevoked('agent.a', 'k2')).toBe(false)
22
+ expect(await store.isRevoked('agent.b', 'k1')).toBe(false)
23
+ })
24
+
25
+ it('honors a time-bounded revocation (untilMs)', async () => {
26
+ let now = 1000
27
+ const store = new InMemoryRevocationStore({ now: () => now })
28
+ await store.revoke('agent.a', 'k1', { untilMs: 2000 })
29
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(true)
30
+ now = 2500
31
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(false)
32
+ })
33
+ })
34
+
35
+ describe('createRedisRevocationStore', () => {
36
+ it('revoke writes a key that isRevoked reads back', async () => {
37
+ const store = createRedisRevocationStore(new InMemoryRedisLikeClient())
38
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(false)
39
+ await store.revoke('agent.a', 'k1')
40
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(true)
41
+ })
42
+
43
+ it('caches reads so repeated checks within the freshness window hit Redis once', async () => {
44
+ let now = 1000
45
+ const client = new InMemoryRedisLikeClient({ now: () => now })
46
+ const getSpy = vi.spyOn(client, 'get')
47
+ const store = createRedisRevocationStore(client, { cacheTtlMs: 5000, now: () => now })
48
+ await store.isRevoked('agent.a', 'k1')
49
+ await store.isRevoked('agent.a', 'k1')
50
+ expect(getSpy).toHaveBeenCalledOnce()
51
+ now = 7000 // past the cache window
52
+ await store.isRevoked('agent.a', 'k1')
53
+ expect(getSpy).toHaveBeenCalledTimes(2)
54
+ })
55
+
56
+ it('fails closed by default: a Redis error means the key is treated as revoked', async () => {
57
+ const onDegraded = vi.fn()
58
+ const throwing = {
59
+ set: async () => 'OK' as const,
60
+ get: async () => {
61
+ throw new Error('redis unreachable')
62
+ },
63
+ }
64
+ const store = createRedisRevocationStore(throwing, { onDegraded })
65
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(true)
66
+ expect(onDegraded).toHaveBeenCalledOnce()
67
+ })
68
+
69
+ it('errorBehavior "allow" treats a Redis error as not revoked', async () => {
70
+ const throwing = {
71
+ set: async () => 'OK' as const,
72
+ get: async () => {
73
+ throw new Error('redis unreachable')
74
+ },
75
+ }
76
+ const store = createRedisRevocationStore(throwing, { errorBehavior: 'allow' })
77
+ expect(await store.isRevoked('agent.a', 'k1')).toBe(false)
78
+ })
79
+ })
80
+
81
+ describe('withRevocationCheck (signature resolver wrapper)', () => {
82
+ const material: SignatureVerificationMaterial = { alg: 'HS256', secret: 's3cret' }
83
+ const innerResolver = async () => material
84
+ const signature = { alg: 'HS256' as const, keyId: 'k1', value: 'sig' }
85
+
86
+ it('returns material for a key that is not revoked', async () => {
87
+ const store = new InMemoryRevocationStore()
88
+ const resolver = withRevocationCheck(innerResolver, store)
89
+ expect(await resolver(signature, 'agent.a')).toEqual(material)
90
+ })
91
+
92
+ it('returns undefined (verification fails) for a revoked key', async () => {
93
+ const store = new InMemoryRevocationStore()
94
+ await store.revoke('agent.a', 'k1')
95
+ const resolver = withRevocationCheck(innerResolver, store)
96
+ expect(await resolver(signature, 'agent.a')).toBeUndefined()
97
+ })
98
+ })
Binary file
@@ -0,0 +1,87 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { matchGlob, matchPolicy, isAllowedSender, type RoutePolicy } from './routePolicy'
3
+
4
+ describe('matchGlob', () => {
5
+ it('exact match', () => {
6
+ expect(matchGlob('/health', '/health')).toBe(true)
7
+ expect(matchGlob('/health', '/healthz')).toBe(false)
8
+ })
9
+
10
+ it('single * does not cross segments', () => {
11
+ expect(matchGlob('/api/*', '/api/users')).toBe(true)
12
+ expect(matchGlob('/api/*', '/api/users/list')).toBe(false)
13
+ expect(matchGlob('/api/*', '/api/')).toBe(true) // empty segment is still "within"
14
+ })
15
+
16
+ it('double ** matches any depth', () => {
17
+ expect(matchGlob('/api/**', '/api/users')).toBe(true)
18
+ expect(matchGlob('/api/**', '/api/users/list')).toBe(true)
19
+ expect(matchGlob('/api/**', '/api/a/b/c/d')).toBe(true)
20
+ expect(matchGlob('/api/**', '/other/users')).toBe(false)
21
+ })
22
+
23
+ it('? matches single non-slash char', () => {
24
+ expect(matchGlob('/v?/api', '/v1/api')).toBe(true)
25
+ expect(matchGlob('/v?/api', '/v12/api')).toBe(false)
26
+ expect(matchGlob('/v?/api', '/v//api')).toBe(false)
27
+ })
28
+
29
+ it('handles regex metacharacters in literal path', () => {
30
+ expect(matchGlob('/api/v1.0/health', '/api/v1.0/health')).toBe(true)
31
+ expect(matchGlob('/api/v1.0/health', '/api/v100/health')).toBe(false)
32
+ })
33
+ })
34
+
35
+ describe('matchPolicy', () => {
36
+ const policies: RoutePolicy[] = [
37
+ { path: '/health', require: 'none' },
38
+ { path: '/api/admin/**', require: 'ed25519', allowedSenders: ['admin-agent'] },
39
+ { path: '/api/*', require: 'any' },
40
+ { path: '/webhook/**', require: 'hmac' },
41
+ ]
42
+
43
+ it('returns first matching policy (exact before wildcard)', () => {
44
+ const result = matchPolicy(policies, '/health')
45
+ expect(result?.require).toBe('none')
46
+ })
47
+
48
+ it('matches /api/users with /api/*', () => {
49
+ const result = matchPolicy(policies, '/api/users')
50
+ expect(result?.require).toBe('any')
51
+ })
52
+
53
+ it('/api/admin/delete matches /api/admin/** before /api/*', () => {
54
+ const result = matchPolicy(policies, '/api/admin/delete')
55
+ expect(result?.require).toBe('ed25519')
56
+ })
57
+
58
+ it('matches deep webhook path', () => {
59
+ const result = matchPolicy(policies, '/webhook/stripe/events')
60
+ expect(result?.require).toBe('hmac')
61
+ })
62
+
63
+ it('returns null for no match', () => {
64
+ const result = matchPolicy(policies, '/unknown')
65
+ expect(result).toBeNull()
66
+ })
67
+ })
68
+
69
+ describe('isAllowedSender', () => {
70
+ it('allows all senders when allowedSenders not set', () => {
71
+ const policy: RoutePolicy = { path: '/api/*', require: 'any' }
72
+ expect(isAllowedSender(policy, 'any-agent')).toBe(true)
73
+ expect(isAllowedSender(policy, 'another-agent')).toBe(true)
74
+ })
75
+
76
+ it('allows only listed senders', () => {
77
+ const policy: RoutePolicy = { path: '/api/*', require: 'ed25519', allowedSenders: ['trusted-agent', 'another-agent'] }
78
+ expect(isAllowedSender(policy, 'trusted-agent')).toBe(true)
79
+ expect(isAllowedSender(policy, 'another-agent')).toBe(true)
80
+ expect(isAllowedSender(policy, 'unknown-agent')).toBe(false)
81
+ })
82
+
83
+ it('empty allowedSenders array allows all', () => {
84
+ const policy: RoutePolicy = { path: '/api/*', require: 'any', allowedSenders: [] }
85
+ expect(isAllowedSender(policy, 'anyone')).toBe(true)
86
+ })
87
+ })
@@ -0,0 +1,72 @@
1
+ export type PolicyRequirement = 'ed25519' | 'hmac' | 'any' | 'none'
2
+
3
+ export interface RoutePolicy {
4
+ path: string
5
+ require: PolicyRequirement
6
+ rateLimit?: { requests: number; windowMs: number }
7
+ allowedSenders?: string[]
8
+ signResponse?: boolean
9
+ }
10
+
11
+ /**
12
+ * Translate a glob pattern to a RegExp.
13
+ * Supported:
14
+ * - exact: '/health'
15
+ * - '?' → any single non-slash char
16
+ * - '*' → any chars within a single segment (no slash)
17
+ * - '**' → any chars at any depth (including slashes)
18
+ */
19
+ export function matchGlob(pattern: string, path: string): boolean {
20
+ // Build regex from pattern, handling ** before * to avoid double-expanding
21
+ let regexStr = '^'
22
+ let i = 0
23
+ while (i < pattern.length) {
24
+ const ch = pattern[i]
25
+ if (ch === '*') {
26
+ if (pattern[i + 1] === '*') {
27
+ // Double star: matches anything including /
28
+ regexStr += '.*'
29
+ i += 2
30
+ } else {
31
+ // Single star: matches any non-slash sequence
32
+ regexStr += '[^/]*'
33
+ i += 1
34
+ }
35
+ } else if (ch === '?') {
36
+ // Single char, not slash
37
+ regexStr += '[^/]'
38
+ i += 1
39
+ } else {
40
+ // Escape regex metacharacters in literal segments
41
+ regexStr += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&')
42
+ i += 1
43
+ }
44
+ }
45
+ regexStr += '$'
46
+
47
+ return new RegExp(regexStr).test(path)
48
+ }
49
+
50
+ /**
51
+ * Find the first matching policy for a given path.
52
+ * Returns null if no policy matches.
53
+ */
54
+ export function matchPolicy(policies: RoutePolicy[], path: string): RoutePolicy | null {
55
+ for (const policy of policies) {
56
+ if (matchGlob(policy.path, path)) {
57
+ return policy
58
+ }
59
+ }
60
+ return null
61
+ }
62
+
63
+ /**
64
+ * Check whether a sender is permitted by a policy.
65
+ * If allowedSenders is not set, all senders are allowed.
66
+ */
67
+ export function isAllowedSender(policy: RoutePolicy, sender: string): boolean {
68
+ if (!policy.allowedSenders || policy.allowedSenders.length === 0) {
69
+ return true
70
+ }
71
+ return policy.allowedSenders.includes(sender)
72
+ }
@@ -0,0 +1,49 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { loadRuntimePolicy, parseRuntimePolicyJson, validateRuntimePolicy } from './runtimePolicy'
3
+
4
+ describe('runtime policy loader', () => {
5
+ it('parses valid policy JSON', () => {
6
+ const policy = parseRuntimePolicyJson(
7
+ JSON.stringify({
8
+ version: '1.0',
9
+ name: 'gluv-runtime-policy',
10
+ status: 'active',
11
+ }),
12
+ )
13
+
14
+ expect(policy.version).toBe('1.0')
15
+ expect(policy.name).toBe('gluv-runtime-policy')
16
+ expect(policy.status).toBe('active')
17
+ })
18
+
19
+ it('rejects invalid JSON', () => {
20
+ expect(() => parseRuntimePolicyJson('{')).toThrow(/Invalid runtime policy JSON/i)
21
+ })
22
+
23
+ it('rejects invalid root object', () => {
24
+ expect(() => validateRuntimePolicy('not-an-object')).toThrow(/root must be an object/i)
25
+ })
26
+
27
+ it('rejects missing required fields', () => {
28
+ expect(() => validateRuntimePolicy({ name: 'x', status: 'active' })).toThrow(/version/i)
29
+ expect(() => validateRuntimePolicy({ version: '1.0', status: 'active' })).toThrow(/name/i)
30
+ expect(() => validateRuntimePolicy({ version: '1.0', name: 'x' })).toThrow(/status/i)
31
+ })
32
+
33
+ it('loads policy using injected reader and path', async () => {
34
+ const policy = await loadRuntimePolicy({
35
+ path: '/virtual/AI_RUNTIME_POLICY.json',
36
+ readTextFile: async (filePath) => {
37
+ expect(filePath).toBe('/virtual/AI_RUNTIME_POLICY.json')
38
+ return JSON.stringify({
39
+ version: '1.0',
40
+ name: 'gluv-runtime-policy',
41
+ status: 'active',
42
+ owner: 'platform-ai-ops',
43
+ })
44
+ },
45
+ })
46
+
47
+ expect(policy.owner).toBe('platform-ai-ops')
48
+ })
49
+ })
@@ -0,0 +1,81 @@
1
+ export interface RuntimePolicy {
2
+ version: string
3
+ name: string
4
+ status: string
5
+ owner?: string
6
+ updated_at?: string
7
+ hard_invariants?: Record<string, unknown>
8
+ slo_defaults?: Record<string, unknown>
9
+ mode_selection?: Record<string, unknown>
10
+ guardrails?: Record<string, unknown>
11
+ tuning?: Record<string, unknown>
12
+ adaptive_flow?: Record<string, unknown>
13
+ benchmark_policy?: Record<string, unknown>
14
+ runtime_decision_tree?: unknown[]
15
+ operator_handoff_required_fields?: string[]
16
+ [key: string]: unknown
17
+ }
18
+
19
+ export interface LoadRuntimePolicyOptions {
20
+ path?: string
21
+ readTextFile?: (filePath: string) => Promise<string>
22
+ }
23
+
24
+ function isRecord(value: unknown): value is Record<string, unknown> {
25
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
26
+ }
27
+
28
+ function asNonEmptyString(value: unknown, field: string): string {
29
+ if (typeof value !== 'string' || value.trim().length === 0) {
30
+ throw new Error(`Invalid runtime policy: '${field}' must be a non-empty string`)
31
+ }
32
+ return value
33
+ }
34
+
35
+ export function validateRuntimePolicy(value: unknown): RuntimePolicy {
36
+ if (!isRecord(value)) {
37
+ throw new Error('Invalid runtime policy: root must be an object')
38
+ }
39
+
40
+ const version = asNonEmptyString(value.version, 'version')
41
+ const name = asNonEmptyString(value.name, 'name')
42
+ const status = asNonEmptyString(value.status, 'status')
43
+
44
+ return {
45
+ ...value,
46
+ version,
47
+ name,
48
+ status,
49
+ }
50
+ }
51
+
52
+ export function parseRuntimePolicyJson(jsonText: string): RuntimePolicy {
53
+ let parsed: unknown
54
+ try {
55
+ parsed = JSON.parse(jsonText)
56
+ } catch (error) {
57
+ const message = error instanceof Error ? error.message : String(error)
58
+ throw new Error(`Invalid runtime policy JSON: ${message}`)
59
+ }
60
+ return validateRuntimePolicy(parsed)
61
+ }
62
+
63
+ async function defaultReadTextFile(filePath: string): Promise<string> {
64
+ if (typeof fetch === 'function') {
65
+ const response = await fetch(filePath)
66
+ if (!response.ok) {
67
+ throw new Error(`Failed to fetch runtime policy at '${filePath}': ${response.status} ${response.statusText}`)
68
+ }
69
+ return response.text()
70
+ }
71
+ throw new Error(
72
+ "No default runtime file reader available in this environment. Provide 'readTextFile' in loadRuntimePolicy(options).",
73
+ )
74
+ }
75
+
76
+ export async function loadRuntimePolicy(options: LoadRuntimePolicyOptions = {}): Promise<RuntimePolicy> {
77
+ const filePath = options.path ?? 'AI_RUNTIME_POLICY.json'
78
+ const readTextFile = options.readTextFile ?? defaultReadTextFile
79
+ const text = await readTextFile(filePath)
80
+ return parseRuntimePolicyJson(text)
81
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { RuntimePolicyManager } from './runtimePolicyManager'
3
+
4
+ describe('runtime policy manager', () => {
5
+ it('loads initial policy and exposes snapshot', async () => {
6
+ const manager = new RuntimePolicyManager({
7
+ path: '/virtual/AI_RUNTIME_POLICY.json',
8
+ readTextFile: async () =>
9
+ JSON.stringify({
10
+ version: '1.0',
11
+ name: 'gluv-runtime-policy',
12
+ status: 'active',
13
+ hard_invariants: {},
14
+ slo_defaults: {},
15
+ tuning: {
16
+ batch_size: { low_traffic: [4, 8], medium_traffic: [8, 32], high_traffic: [32, 64] },
17
+ inflight_cap: { low_traffic: [16, 64], medium_traffic: [64, 256], high_traffic: [256, 1024] },
18
+ retry_backoff_ms: { low_traffic: [1, 2], medium_traffic: [2, 8], high_traffic: [4, 16] },
19
+ max_retry_attempts: 3,
20
+ retriable_status_codes: [503],
21
+ },
22
+ }),
23
+ })
24
+
25
+ const loaded = await manager.loadInitial()
26
+ expect(loaded.policy.name).toBe('gluv-runtime-policy')
27
+ expect(manager.current().policy.version).toBe('1.0')
28
+ })
29
+ })
@@ -0,0 +1,50 @@
1
+ import { bootstrapRuntimePolicyEnforcer, type BootstrapRuntimePolicyEnforcerOptions, type PolicyEnforcer } from './policyEnforcer'
2
+ import type { RuntimePolicy } from './runtimePolicy'
3
+
4
+ export interface RuntimePolicySnapshot {
5
+ policy: RuntimePolicy
6
+ enforcer: PolicyEnforcer
7
+ loadedAtMs: number
8
+ }
9
+
10
+ export class RuntimePolicyManager {
11
+ private snapshot: RuntimePolicySnapshot | null = null
12
+ private readonly options: BootstrapRuntimePolicyEnforcerOptions
13
+
14
+ constructor(options: BootstrapRuntimePolicyEnforcerOptions = {}) {
15
+ this.options = options
16
+ }
17
+
18
+ async loadInitial(): Promise<RuntimePolicySnapshot> {
19
+ const loaded = await bootstrapRuntimePolicyEnforcer(this.options)
20
+ this.snapshot = {
21
+ ...loaded,
22
+ loadedAtMs: Date.now(),
23
+ }
24
+ return this.snapshot
25
+ }
26
+
27
+ current(): RuntimePolicySnapshot {
28
+ if (!this.snapshot) {
29
+ throw new Error('Runtime policy not loaded. Call loadInitial() first.')
30
+ }
31
+ return this.snapshot
32
+ }
33
+
34
+ async refresh(): Promise<RuntimePolicySnapshot> {
35
+ const previous = this.snapshot
36
+ try {
37
+ const loaded = await bootstrapRuntimePolicyEnforcer(this.options)
38
+ this.snapshot = {
39
+ ...loaded,
40
+ loadedAtMs: Date.now(),
41
+ }
42
+ return this.snapshot
43
+ } catch (error) {
44
+ if (previous) {
45
+ return previous
46
+ }
47
+ throw error
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,43 @@
1
+ import type { RuntimeMode } from './policyEnforcer'
2
+
3
+ export type RuntimeEnvironment = 'dev' | 'staging' | 'prod'
4
+
5
+ export interface RuntimeTuningPreset {
6
+ environment: RuntimeEnvironment
7
+ mode: RuntimeMode
8
+ poolSize: number
9
+ batchSize: number
10
+ inflightCap: number
11
+ retryMaxAttempts: number
12
+ }
13
+
14
+ const PRESETS: Record<RuntimeEnvironment, RuntimeTuningPreset> = {
15
+ dev: {
16
+ environment: 'dev',
17
+ mode: 'ws-batch',
18
+ poolSize: 1,
19
+ batchSize: 8,
20
+ inflightCap: 64,
21
+ retryMaxAttempts: 2,
22
+ },
23
+ staging: {
24
+ environment: 'staging',
25
+ mode: 'http-binary-batch',
26
+ poolSize: 2,
27
+ batchSize: 32,
28
+ inflightCap: 256,
29
+ retryMaxAttempts: 3,
30
+ },
31
+ prod: {
32
+ environment: 'prod',
33
+ mode: 'http-binary-batch',
34
+ poolSize: 4,
35
+ batchSize: 64,
36
+ inflightCap: 1024,
37
+ retryMaxAttempts: 3,
38
+ },
39
+ }
40
+
41
+ export function getRuntimeTuningPreset(environment: RuntimeEnvironment): RuntimeTuningPreset {
42
+ return PRESETS[environment]
43
+ }