@proofoftech/flowsafe 0.3.0 → 0.6.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 (296) hide show
  1. package/CHANGELOG.md +336 -0
  2. package/dist/agent-runner/approval-shapes.d.ts +36 -0
  3. package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
  4. package/dist/agent-runner/approval-shapes.js +101 -0
  5. package/dist/agent-runner/approval-shapes.js.map +1 -0
  6. package/dist/agent-runner/durable-agent-runner.d.ts +154 -0
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
  8. package/dist/agent-runner/durable-agent-runner.js +291 -0
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -0
  10. package/dist/agent-runner/index.d.ts +3 -0
  11. package/dist/agent-runner/index.d.ts.map +1 -0
  12. package/dist/agent-runner/index.js +10 -0
  13. package/dist/agent-runner/index.js.map +1 -0
  14. package/dist/approval-api/contract.d.ts +29 -0
  15. package/dist/approval-api/contract.d.ts.map +1 -1
  16. package/dist/approval-api/d1-store.d.ts.map +1 -1
  17. package/dist/approval-api/d1-store.js +112 -18
  18. package/dist/approval-api/d1-store.js.map +1 -1
  19. package/dist/approval-api/grants.d.ts +1 -1
  20. package/dist/approval-api/grants.d.ts.map +1 -1
  21. package/dist/approval-api/grants.js +8 -32
  22. package/dist/approval-api/grants.js.map +1 -1
  23. package/dist/approval-api/index.d.ts +2 -2
  24. package/dist/approval-api/index.d.ts.map +1 -1
  25. package/dist/approval-api/index.js.map +1 -1
  26. package/dist/approval-api/router.d.ts +1 -1
  27. package/dist/approval-api/router.d.ts.map +1 -1
  28. package/dist/approval-api/router.js +1 -0
  29. package/dist/approval-api/router.js.map +1 -1
  30. package/dist/approval-api/service.d.ts +24 -3
  31. package/dist/approval-api/service.d.ts.map +1 -1
  32. package/dist/approval-api/service.js +116 -1
  33. package/dist/approval-api/service.js.map +1 -1
  34. package/dist/approval-api/store.d.ts +29 -6
  35. package/dist/approval-api/store.d.ts.map +1 -1
  36. package/dist/approval-api/store.js +62 -2
  37. package/dist/approval-api/store.js.map +1 -1
  38. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  39. package/dist/approval-api/tenant-context.js +17 -1
  40. package/dist/approval-api/tenant-context.js.map +1 -1
  41. package/dist/approval-api/tenant-store.d.ts.map +1 -1
  42. package/dist/approval-api/tenant-store.js +8 -2
  43. package/dist/approval-api/tenant-store.js.map +1 -1
  44. package/dist/approval-api/types.d.ts +19 -0
  45. package/dist/approval-api/types.d.ts.map +1 -1
  46. package/dist/approval-api/types.js +16 -0
  47. package/dist/approval-api/types.js.map +1 -1
  48. package/dist/approval-ui/App.d.ts +9 -1
  49. package/dist/approval-ui/App.d.ts.map +1 -1
  50. package/dist/approval-ui/App.js +10 -5
  51. package/dist/approval-ui/App.js.map +1 -1
  52. package/dist/approval-ui/DetailView.d.ts +4 -1
  53. package/dist/approval-ui/DetailView.d.ts.map +1 -1
  54. package/dist/approval-ui/DetailView.js +2 -2
  55. package/dist/approval-ui/DetailView.js.map +1 -1
  56. package/dist/approval-ui/QueueView.d.ts +7 -1
  57. package/dist/approval-ui/QueueView.d.ts.map +1 -1
  58. package/dist/approval-ui/QueueView.js +8 -3
  59. package/dist/approval-ui/QueueView.js.map +1 -1
  60. package/dist/approval-ui/client.d.ts +19 -0
  61. package/dist/approval-ui/client.d.ts.map +1 -1
  62. package/dist/approval-ui/client.js +29 -1
  63. package/dist/approval-ui/client.js.map +1 -1
  64. package/dist/approval-ui/components.d.ts +20 -0
  65. package/dist/approval-ui/components.d.ts.map +1 -1
  66. package/dist/approval-ui/components.js +2 -0
  67. package/dist/approval-ui/components.js.map +1 -1
  68. package/dist/approval-ui/index.d.ts +4 -2
  69. package/dist/approval-ui/index.d.ts.map +1 -1
  70. package/dist/approval-ui/index.js +3 -0
  71. package/dist/approval-ui/index.js.map +1 -1
  72. package/dist/approval-ui/stream.d.ts +142 -0
  73. package/dist/approval-ui/stream.d.ts.map +1 -0
  74. package/dist/approval-ui/stream.js +136 -0
  75. package/dist/approval-ui/stream.js.map +1 -0
  76. package/dist/approval-ui/use-approval-dashboard.d.ts +74 -1
  77. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
  78. package/dist/approval-ui/use-approval-dashboard.js +307 -7
  79. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  80. package/dist/approval-ui/use-web-socket-transport.d.ts +10 -0
  81. package/dist/approval-ui/use-web-socket-transport.d.ts.map +1 -0
  82. package/dist/approval-ui/use-web-socket-transport.js +46 -0
  83. package/dist/approval-ui/use-web-socket-transport.js.map +1 -0
  84. package/dist/background-tasks/d1-storage.d.ts +66 -0
  85. package/dist/background-tasks/d1-storage.d.ts.map +1 -0
  86. package/dist/background-tasks/d1-storage.js +196 -0
  87. package/dist/background-tasks/d1-storage.js.map +1 -0
  88. package/dist/background-tasks/host.d.ts +82 -0
  89. package/dist/background-tasks/host.d.ts.map +1 -0
  90. package/dist/background-tasks/host.js +275 -0
  91. package/dist/background-tasks/host.js.map +1 -0
  92. package/dist/background-tasks/index.d.ts +7 -0
  93. package/dist/background-tasks/index.d.ts.map +1 -0
  94. package/dist/background-tasks/index.js +10 -0
  95. package/dist/background-tasks/index.js.map +1 -0
  96. package/dist/background-tasks/routes.d.ts +15 -0
  97. package/dist/background-tasks/routes.d.ts.map +1 -0
  98. package/dist/background-tasks/routes.js +144 -0
  99. package/dist/background-tasks/routes.js.map +1 -0
  100. package/dist/do-runner/cf-types.d.ts +70 -2
  101. package/dist/do-runner/cf-types.d.ts.map +1 -1
  102. package/dist/do-runner/cf-types.js +30 -1
  103. package/dist/do-runner/cf-types.js.map +1 -1
  104. package/dist/do-runner/d1-storage.d.ts +343 -2
  105. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  106. package/dist/do-runner/d1-storage.js +566 -13
  107. package/dist/do-runner/d1-storage.js.map +1 -1
  108. package/dist/do-runner/do-error-response.d.ts +29 -0
  109. package/dist/do-runner/do-error-response.d.ts.map +1 -0
  110. package/dist/do-runner/do-error-response.js +73 -0
  111. package/dist/do-runner/do-error-response.js.map +1 -0
  112. package/dist/do-runner/durable-object.d.ts +5 -2
  113. package/dist/do-runner/durable-object.d.ts.map +1 -1
  114. package/dist/do-runner/durable-object.js +87 -20
  115. package/dist/do-runner/durable-object.js.map +1 -1
  116. package/dist/do-runner/hub-do.d.ts +55 -0
  117. package/dist/do-runner/hub-do.d.ts.map +1 -0
  118. package/dist/do-runner/hub-do.js +197 -0
  119. package/dist/do-runner/hub-do.js.map +1 -0
  120. package/dist/do-runner/index.d.ts +12 -4
  121. package/dist/do-runner/index.d.ts.map +1 -1
  122. package/dist/do-runner/index.js +9 -2
  123. package/dist/do-runner/index.js.map +1 -1
  124. package/dist/do-runner/init.d.ts +20 -0
  125. package/dist/do-runner/init.d.ts.map +1 -1
  126. package/dist/do-runner/init.js +12 -1
  127. package/dist/do-runner/init.js.map +1 -1
  128. package/dist/do-runner/path-safe-id.js +1 -1
  129. package/dist/do-runner/path-safe-id.js.map +1 -1
  130. package/dist/do-runner/pubsub.d.ts +18 -0
  131. package/dist/do-runner/pubsub.d.ts.map +1 -0
  132. package/dist/do-runner/pubsub.js +42 -0
  133. package/dist/do-runner/pubsub.js.map +1 -0
  134. package/dist/do-runner/runtime.d.ts +24 -0
  135. package/dist/do-runner/runtime.d.ts.map +1 -1
  136. package/dist/do-runner/runtime.js +29 -2
  137. package/dist/do-runner/runtime.js.map +1 -1
  138. package/dist/do-runner/thread-do.d.ts +74 -0
  139. package/dist/do-runner/thread-do.d.ts.map +1 -0
  140. package/dist/do-runner/thread-do.js +156 -0
  141. package/dist/do-runner/thread-do.js.map +1 -0
  142. package/dist/do-runner/thread-header.d.ts +16 -0
  143. package/dist/do-runner/thread-header.d.ts.map +1 -0
  144. package/dist/do-runner/thread-header.js +24 -0
  145. package/dist/do-runner/thread-header.js.map +1 -0
  146. package/dist/goals/index.d.ts +2 -0
  147. package/dist/goals/index.d.ts.map +1 -0
  148. package/dist/goals/index.js +7 -0
  149. package/dist/goals/index.js.map +1 -0
  150. package/dist/goals/objective-routes.d.ts +87 -0
  151. package/dist/goals/objective-routes.d.ts.map +1 -0
  152. package/dist/goals/objective-routes.js +375 -0
  153. package/dist/goals/objective-routes.js.map +1 -0
  154. package/dist/host-kit/approval-bridge.d.ts +24 -4
  155. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  156. package/dist/host-kit/approval-bridge.js +32 -10
  157. package/dist/host-kit/approval-bridge.js.map +1 -1
  158. package/dist/host-kit/env-vars.d.ts +20 -0
  159. package/dist/host-kit/env-vars.d.ts.map +1 -1
  160. package/dist/host-kit/env-vars.js +30 -0
  161. package/dist/host-kit/env-vars.js.map +1 -1
  162. package/dist/host-kit/flowsafe-worker.d.ts +134 -5
  163. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  164. package/dist/host-kit/flowsafe-worker.js +283 -47
  165. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  166. package/dist/host-kit/host-approval-service.d.ts +20 -1
  167. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  168. package/dist/host-kit/host-approval-service.js +15 -0
  169. package/dist/host-kit/host-approval-service.js.map +1 -1
  170. package/dist/host-kit/hub-topology.d.ts +35 -0
  171. package/dist/host-kit/hub-topology.d.ts.map +1 -0
  172. package/dist/host-kit/hub-topology.js +32 -0
  173. package/dist/host-kit/hub-topology.js.map +1 -0
  174. package/dist/host-kit/index.d.ts +8 -1
  175. package/dist/host-kit/index.d.ts.map +1 -1
  176. package/dist/host-kit/index.js +10 -0
  177. package/dist/host-kit/index.js.map +1 -1
  178. package/dist/host-kit/memory-boundary.d.ts +64 -0
  179. package/dist/host-kit/memory-boundary.d.ts.map +1 -0
  180. package/dist/host-kit/memory-boundary.js +109 -0
  181. package/dist/host-kit/memory-boundary.js.map +1 -0
  182. package/dist/host-kit/route-path.d.ts +17 -0
  183. package/dist/host-kit/route-path.d.ts.map +1 -0
  184. package/dist/host-kit/route-path.js +35 -0
  185. package/dist/host-kit/route-path.js.map +1 -0
  186. package/dist/host-kit/stream-router.d.ts +22 -0
  187. package/dist/host-kit/stream-router.d.ts.map +1 -0
  188. package/dist/host-kit/stream-router.js +191 -0
  189. package/dist/host-kit/stream-router.js.map +1 -0
  190. package/dist/host-kit/stream-ticket.d.ts +55 -0
  191. package/dist/host-kit/stream-ticket.d.ts.map +1 -0
  192. package/dist/host-kit/stream-ticket.js +156 -0
  193. package/dist/host-kit/stream-ticket.js.map +1 -0
  194. package/dist/host-kit/tenant-registry.js +1 -1
  195. package/dist/host-kit/tenant-registry.js.map +1 -1
  196. package/dist/host-kit/thread-topology.d.ts +44 -0
  197. package/dist/host-kit/thread-topology.d.ts.map +1 -0
  198. package/dist/host-kit/thread-topology.js +76 -0
  199. package/dist/host-kit/thread-topology.js.map +1 -0
  200. package/dist/index.d.ts +3 -3
  201. package/dist/index.d.ts.map +1 -1
  202. package/dist/index.js +1 -1
  203. package/dist/index.js.map +1 -1
  204. package/dist/internal-error-response.d.ts +3 -0
  205. package/dist/internal-error-response.d.ts.map +1 -0
  206. package/dist/internal-error-response.js +20 -0
  207. package/dist/internal-error-response.js.map +1 -0
  208. package/dist/numeric-config.d.ts +4 -0
  209. package/dist/numeric-config.d.ts.map +1 -0
  210. package/dist/numeric-config.js +23 -0
  211. package/dist/numeric-config.js.map +1 -0
  212. package/dist/schedules/index.d.ts +5 -0
  213. package/dist/schedules/index.d.ts.map +1 -0
  214. package/dist/schedules/index.js +13 -0
  215. package/dist/schedules/index.js.map +1 -0
  216. package/dist/schedules/router.d.ts +66 -0
  217. package/dist/schedules/router.d.ts.map +1 -0
  218. package/dist/schedules/router.js +827 -0
  219. package/dist/schedules/router.js.map +1 -0
  220. package/dist/schedules/schedules-d1.d.ts +30 -0
  221. package/dist/schedules/schedules-d1.d.ts.map +1 -0
  222. package/dist/schedules/schedules-d1.js +374 -0
  223. package/dist/schedules/schedules-d1.js.map +1 -0
  224. package/dist/schedules/storage.d.ts +11 -0
  225. package/dist/schedules/storage.d.ts.map +1 -0
  226. package/dist/schedules/storage.js +34 -0
  227. package/dist/schedules/storage.js.map +1 -0
  228. package/dist/schedules/tick.d.ts +131 -0
  229. package/dist/schedules/tick.d.ts.map +1 -0
  230. package/dist/schedules/tick.js +598 -0
  231. package/dist/schedules/tick.js.map +1 -0
  232. package/dist/signal-providers/delivery.d.ts +24 -0
  233. package/dist/signal-providers/delivery.d.ts.map +1 -0
  234. package/dist/signal-providers/delivery.js +62 -0
  235. package/dist/signal-providers/delivery.js.map +1 -0
  236. package/dist/signal-providers/github-provider.d.ts +33 -0
  237. package/dist/signal-providers/github-provider.d.ts.map +1 -0
  238. package/dist/signal-providers/github-provider.js +116 -0
  239. package/dist/signal-providers/github-provider.js.map +1 -0
  240. package/dist/signal-providers/host-do.d.ts +79 -0
  241. package/dist/signal-providers/host-do.d.ts.map +1 -0
  242. package/dist/signal-providers/host-do.js +216 -0
  243. package/dist/signal-providers/host-do.js.map +1 -0
  244. package/dist/signal-providers/index.d.ts +7 -0
  245. package/dist/signal-providers/index.d.ts.map +1 -0
  246. package/dist/signal-providers/index.js +19 -0
  247. package/dist/signal-providers/index.js.map +1 -0
  248. package/dist/signal-providers/provider.d.ts +92 -0
  249. package/dist/signal-providers/provider.d.ts.map +1 -0
  250. package/dist/signal-providers/provider.js +87 -0
  251. package/dist/signal-providers/provider.js.map +1 -0
  252. package/dist/signal-providers/subscription-d1.d.ts +88 -0
  253. package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
  254. package/dist/signal-providers/subscription-d1.js +259 -0
  255. package/dist/signal-providers/subscription-d1.js.map +1 -0
  256. package/dist/signal-providers/webhook-route.d.ts +88 -0
  257. package/dist/signal-providers/webhook-route.d.ts.map +1 -0
  258. package/dist/signal-providers/webhook-route.js +391 -0
  259. package/dist/signal-providers/webhook-route.js.map +1 -0
  260. package/dist/signals/client.d.ts +72 -0
  261. package/dist/signals/client.d.ts.map +1 -0
  262. package/dist/signals/client.js +87 -0
  263. package/dist/signals/client.js.map +1 -0
  264. package/dist/signals/d1-shared.d.ts +43 -0
  265. package/dist/signals/d1-shared.d.ts.map +1 -0
  266. package/dist/signals/d1-shared.js +46 -0
  267. package/dist/signals/d1-shared.js.map +1 -0
  268. package/dist/signals/index.d.ts +9 -0
  269. package/dist/signals/index.d.ts.map +1 -0
  270. package/dist/signals/index.js +15 -0
  271. package/dist/signals/index.js.map +1 -0
  272. package/dist/signals/notification-dispatch.d.ts +52 -0
  273. package/dist/signals/notification-dispatch.d.ts.map +1 -0
  274. package/dist/signals/notification-dispatch.js +198 -0
  275. package/dist/signals/notification-dispatch.js.map +1 -0
  276. package/dist/signals/notifications-d1.d.ts +28 -0
  277. package/dist/signals/notifications-d1.d.ts.map +1 -0
  278. package/dist/signals/notifications-d1.js +704 -0
  279. package/dist/signals/notifications-d1.js.map +1 -0
  280. package/dist/signals/router.d.ts +73 -0
  281. package/dist/signals/router.d.ts.map +1 -0
  282. package/dist/signals/router.js +240 -0
  283. package/dist/signals/router.js.map +1 -0
  284. package/dist/signals/storage.d.ts +11 -0
  285. package/dist/signals/storage.d.ts.map +1 -0
  286. package/dist/signals/storage.js +27 -0
  287. package/dist/signals/storage.js.map +1 -0
  288. package/dist/signals/thread-do-routes.d.ts +82 -0
  289. package/dist/signals/thread-do-routes.d.ts.map +1 -0
  290. package/dist/signals/thread-do-routes.js +660 -0
  291. package/dist/signals/thread-do-routes.js.map +1 -0
  292. package/dist/signals/thread-state-d1.d.ts +22 -0
  293. package/dist/signals/thread-state-d1.d.ts.map +1 -0
  294. package/dist/signals/thread-state-d1.js +83 -0
  295. package/dist/signals/thread-state-d1.js.map +1 -0
  296. package/package.json +11 -2
@@ -0,0 +1,92 @@
1
+ import type { SendNotificationSignalInput } from '@mastra/core/notifications';
2
+ import type { SignalSubscription } from '@mastra/core/signals';
3
+ export type { SendNotificationSignalInput } from '@mastra/core/notifications';
4
+ export type { SignalSubscription } from '@mastra/core/signals';
5
+ /**
6
+ * The minimal header reader a webhook signature check needs — a `Headers` or any
7
+ * case-insensitive `get(name) => string | null`. Structural so the module stays
8
+ * free of the DOM/Workers `Headers` lib choice.
9
+ */
10
+ export interface WebhookHeaders {
11
+ get(name: string): string | null;
12
+ }
13
+ /**
14
+ * One notification to deliver to one matched subscription — what a provider's
15
+ * poll or webhook parse produces, before the host routes it through the
16
+ * topology. The `subscription` carries the tenant/thread/resource the delivery
17
+ * is bound to (never the payload — the row is the authority).
18
+ */
19
+ export interface ProviderDelivery {
20
+ subscription: SignalSubscription;
21
+ notification: SendNotificationSignalInput;
22
+ }
23
+ /**
24
+ * The DO-host + webhook contract a flowsafe-hosted provider exposes. The host DO
25
+ * drives `pollForDeliveries`; the webhook route drives
26
+ * `verifyWebhookSignature` (over the RAW bytes, before any parse),
27
+ * `extractResourceIds`, and `buildNotification`. A provider implements only the
28
+ * seams its transport needs — a webhook-only provider omits `pollForDeliveries`,
29
+ * a poll-only one omits the webhook trio.
30
+ */
31
+ export interface SignalProviderAdapter {
32
+ readonly id: string;
33
+ /** Poll cadence in ms for the host DO's alarm; absent/0 ⇒ webhook-only (no alarm). */
34
+ readonly pollInterval?: number;
35
+ /**
36
+ * Verify a webhook's provider signature over the RAW request bytes, BEFORE the
37
+ * body is parsed — a forged signature must be refused without ever inspecting
38
+ * the payload. MUST be constant-time. Absent ⇒ the provider accepts no
39
+ * webhooks (every webhook fails closed), so a webhook provider MUST supply it.
40
+ */
41
+ verifyWebhookSignature?(rawBody: Uint8Array, headers: WebhookHeaders, secret: string): Promise<boolean> | boolean;
42
+ /**
43
+ * The external-resource key(s) a parsed webhook payload concerns, matched
44
+ * against subscriptions' `externalResourceId`. Returns an empty array when the
45
+ * payload names no resource this provider tracks.
46
+ */
47
+ extractResourceIds?(payload: unknown): string[];
48
+ /** Shape the notification a matched subscription receives (webhook AND poll). */
49
+ buildNotification(payload: unknown, subscription: SignalSubscription): SendNotificationSignalInput;
50
+ /**
51
+ * Check external state for a batch of REHYDRATED subscriptions (the host DO
52
+ * passes the D1 rows, not core's in-memory registry) and return the deliveries.
53
+ * The host routes each through the topology. Absent ⇒ webhook-only.
54
+ */
55
+ pollForDeliveries?(subscriptions: SignalSubscription[]): Promise<ProviderDelivery[]>;
56
+ }
57
+ /**
58
+ * Provider-id charset: a lowercase slug with NO underscore, because a provider
59
+ * host DO is named `${tenantId}_${providerId}` and the tenant is decoded by the
60
+ * FIRST '_' (tenantOfRunId) — a '_' in the providerId would split the name at
61
+ * the wrong place. Kept stricter than PATH_SAFE_ID_PATTERN for exactly that
62
+ * reason (the same discipline TENANT_ID_PATTERN keeps for the other half of the
63
+ * join).
64
+ */
65
+ export declare const PROVIDER_ID_PATTERN: RegExp;
66
+ /** Normalize `extractResourceId`'s string | string[] | undefined to an array. */
67
+ export declare function normalizeResourceIds(value: string | string[] | undefined): string[];
68
+ /**
69
+ * Config for the generic webhook provider — the core `WebhookSignalProvider`
70
+ * knobs (`extractResourceId`, `buildNotification`) PLUS the signature check core
71
+ * omits (a generic webhook has no signing scheme; a real one — GitHub — does).
72
+ */
73
+ export interface WebhookSignalProviderConfig {
74
+ id: string;
75
+ name?: string;
76
+ /** Optional poll cadence; a pure webhook provider omits it. */
77
+ pollInterval?: number;
78
+ /** Signature check (webhook providers). Omit ⇒ the provider accepts no webhooks. */
79
+ verifyWebhookSignature?: (rawBody: Uint8Array, headers: WebhookHeaders, secret: string) => Promise<boolean> | boolean;
80
+ /** The external-resource key(s) an incoming payload concerns (webhook providers). */
81
+ extractResourceIds?: (payload: unknown) => string | string[] | undefined;
82
+ /** Build the notification a matched subscription receives (REQUIRED — both paths). */
83
+ buildNotification: (payload: unknown, subscription: SignalSubscription) => SendNotificationSignalInput;
84
+ /** Poll seam (poll providers). Omit ⇒ webhook-only (no host-DO alarm). */
85
+ pollForDeliveries?: (subscriptions: SignalSubscription[]) => Promise<ProviderDelivery[]>;
86
+ }
87
+ /**
88
+ * Build a generic webhook signal provider. Returns the flowsafe adapter the DO
89
+ * host + webhook route depend on; the instance also IS a core `SignalProvider`.
90
+ */
91
+ export declare function createWebhookSignalProvider(config: WebhookSignalProviderConfig): SignalProviderAdapter;
92
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/signal-providers/provider.ts"],"names":[],"mappings":"AA0BA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D,YAAY,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAC9E,YAAY,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CAClC;AAED;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,kBAAkB,CAAC;IACjC,YAAY,EAAE,2BAA2B,CAAC;CAC3C;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,sFAAsF;IACtF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B;;;;;OAKG;IACH,sBAAsB,CAAC,CACrB,OAAO,EAAE,UAAU,EACnB,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAC9B;;;;OAIG;IACH,kBAAkB,CAAC,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,EAAE,CAAC;IAChD,iFAAiF;IACjF,iBAAiB,CACf,OAAO,EAAE,OAAO,EAChB,YAAY,EAAE,kBAAkB,GAC/B,2BAA2B,CAAC;IAC/B;;;;OAIG;IACH,iBAAiB,CAAC,CAChB,aAAa,EAAE,kBAAkB,EAAE,GAClC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;CAChC;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,QAA8B,CAAC;AAE/D,iFAAiF;AACjF,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,GACnC,MAAM,EAAE,CAGV;AAED;;;;GAIG;AACH,MAAM,WAAW,2BAA2B;IAC1C,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,+DAA+D;IAC/D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,sBAAsB,CAAC,EAAE,CACvB,OAAO,EAAE,UAAU,EACnB,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,MAAM,KACX,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAChC,qFAAqF;IACrF,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IACzE,sFAAsF;IACtF,iBAAiB,EAAE,CACjB,OAAO,EAAE,OAAO,EAChB,YAAY,EAAE,kBAAkB,KAC7B,2BAA2B,CAAC;IACjC,0EAA0E;IAC1E,iBAAiB,CAAC,EAAE,CAClB,aAAa,EAAE,kBAAkB,EAAE,KAChC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;CAClC;AAgDD;;;GAGG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,2BAA2B,GAClC,qBAAqB,CAEvB"}
@@ -0,0 +1,87 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track E (M-007) — the flowsafe signal-provider contract for the DO-host +
3
+ // webhook surface (DL-017).
4
+ //
5
+ // PRE-FLIGHT B/D FINDING (pinned against @mastra/core 1.50.0
6
+ // signals/signal-provider.d.ts). Core's SignalProvider delivers a signal into a
7
+ // thread IN-PROCESS: `poll()` / `handleWebhook()` call `this.notify(notification,
8
+ // target)`, which calls `this.agent.sendNotificationSignal(...)` on a CONNECTED
9
+ // agent, and it matches webhooks against a base-class subscription registry that
10
+ // lives in an in-memory Map. Neither fits a Cloudflare provider-host DO: the
11
+ // agent loop runs on a DIFFERENT (per-thread) DO, so there is no co-located
12
+ // agent to notify, and the in-memory registry is empty after eviction and
13
+ // tenant-blind. So flowsafe drives providers through THIS adapter seam and
14
+ // routes every delivery through `createThreadTopology.send` (host-kit) into
15
+ // Track C's `/signal/notification` thread-DO route — the DO alarm replaces
16
+ // core's `startPolling` timer and the D1 subscription store replaces its
17
+ // registry (DL-017).
18
+ //
19
+ // A provider built here IS a core `SignalProvider` (it extends the base), so
20
+ // `isSignalProvider(p)` holds and `new Agent({ signals: [p] })` still merges any
21
+ // processors/tools it exposes for IN-PROCESS use — the flowsafe DO host simply
22
+ // does not take that path. Core's `SignalSubscription` /
23
+ // `SendNotificationSignalInput` shapes are used DIRECTLY (both are
24
+ // exports-reachable — `@mastra/core/signals` and `@mastra/core/notifications`),
25
+ // so nothing is mirrored and there is no drift surface to pin.
26
+ import { SignalProvider } from '@mastra/core/signals';
27
+ /**
28
+ * Provider-id charset: a lowercase slug with NO underscore, because a provider
29
+ * host DO is named `${tenantId}_${providerId}` and the tenant is decoded by the
30
+ * FIRST '_' (tenantOfRunId) — a '_' in the providerId would split the name at
31
+ * the wrong place. Kept stricter than PATH_SAFE_ID_PATTERN for exactly that
32
+ * reason (the same discipline TENANT_ID_PATTERN keeps for the other half of the
33
+ * join).
34
+ */
35
+ export const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
36
+ /** Normalize `extractResourceId`'s string | string[] | undefined to an array. */
37
+ export function normalizeResourceIds(value) {
38
+ if (value === undefined)
39
+ return [];
40
+ return Array.isArray(value) ? value.filter((v) => v.length > 0) : [value];
41
+ }
42
+ /**
43
+ * A generic webhook signal provider (the DL-017 generic path). Extends core's
44
+ * `SignalProvider` so it remains a real, mergeable provider for in-process
45
+ * `new Agent({ signals: [p] })` use, while implementing the flowsafe adapter the
46
+ * DO host + webhook route drive. GitHub (github-provider.ts) is a specialization
47
+ * of this with a concrete signature scheme.
48
+ */
49
+ class WebhookSignalProviderAdapter extends SignalProvider {
50
+ id;
51
+ name;
52
+ pollInterval;
53
+ // The optional seams are PRESENCE-ACCURATE: assigned only when the config
54
+ // supplies them, so a webhook-only provider genuinely has no pollForDeliveries
55
+ // and a poll-only provider no verify/extract (the host + route optional-chain).
56
+ verifyWebhookSignature;
57
+ extractResourceIds;
58
+ buildNotification;
59
+ pollForDeliveries;
60
+ constructor(config) {
61
+ super();
62
+ if (!PROVIDER_ID_PATTERN.test(config.id)) {
63
+ throw new Error(`signal provider id '${config.id}' must match ${PROVIDER_ID_PATTERN} (lowercase slug, no '_': it delimits the tenant in the host-DO name)`);
64
+ }
65
+ this.id = config.id;
66
+ this.name = config.name;
67
+ this.pollInterval = config.pollInterval;
68
+ this.buildNotification = config.buildNotification;
69
+ const { verifyWebhookSignature, extractResourceIds, pollForDeliveries } = config;
70
+ if (verifyWebhookSignature) {
71
+ this.verifyWebhookSignature = verifyWebhookSignature;
72
+ }
73
+ if (extractResourceIds) {
74
+ this.extractResourceIds = (payload) => normalizeResourceIds(extractResourceIds(payload));
75
+ }
76
+ if (pollForDeliveries)
77
+ this.pollForDeliveries = pollForDeliveries;
78
+ }
79
+ }
80
+ /**
81
+ * Build a generic webhook signal provider. Returns the flowsafe adapter the DO
82
+ * host + webhook route depend on; the instance also IS a core `SignalProvider`.
83
+ */
84
+ export function createWebhookSignalProvider(config) {
85
+ return new WebhookSignalProviderAdapter(config);
86
+ }
87
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/signal-providers/provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,4EAA4E;AAC5E,4BAA4B;AAC5B,EAAE;AACF,6DAA6D;AAC7D,gFAAgF;AAChF,kFAAkF;AAClF,gFAAgF;AAChF,iFAAiF;A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,MAAM,CAAC,IAAI,CAAC;QACxB,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC;QACxC,IAAI,CAAC,iBAAiB,GAAG,MAAM,CAAC,iBAAiB,CAAC;QAClD,MAAM,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,GACrE,MAAM,CAAC;QACT,IAAI,sBAAsB,EAAE,CAAC;YAC3B,IAAI,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;QACvD,CAAC;QACD,IAAI,kBAAkB,EAAE,CAAC;YACvB,IAAI,CAAC,kBAAkB,GAAG,CAAC,OAAO,EAAE,EAAE,CACpC,oBAAoB,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;QACtD,CAAC;QACD,IAAI,iBAAiB;YAAE,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IACpE,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CACzC,MAAmC;IAEnC,OAAO,IAAI,4BAA4B,CAAC,MAAM,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,88 @@
1
+ import type { SignalSubscription } from '@mastra/core/signals';
2
+ import { type SignalDatabase } from '../signals/d1-shared.js';
3
+ /** The table this store owns. Kept in sync with do-runner's purgeTenant DELETE. */
4
+ export declare const SIGNAL_SUBSCRIPTIONS_TABLE = "flowsafe_signal_subscriptions";
5
+ /**
6
+ * A subscription row mapped to core's `SignalSubscription` shape PLUS its owning
7
+ * `tenantId` — the webhook path needs the tenant per row (its rows span tenants);
8
+ * the poll path ignores it (a host DO reads only its own tenant's rows). A
9
+ * superset of `SignalSubscription`, so it flows into `buildNotification` and
10
+ * `pollForDeliveries` unchanged.
11
+ */
12
+ export interface StoredSubscription extends SignalSubscription {
13
+ readonly tenantId: string;
14
+ }
15
+ /** What a subscribe writes — the memory ids are server-minted (never a client body). */
16
+ export interface SubscribeInput {
17
+ providerId: string;
18
+ externalResourceId: string;
19
+ /** Tenant-salted threadId (`${tenantId}_${uuid}`) the caller owns (path-checked upstream). */
20
+ threadId: string;
21
+ /** Tenant-salted resourceId (`${tenantId}_${key}`) — the thread's owner. */
22
+ resourceId: string;
23
+ metadata?: Record<string, unknown>;
24
+ }
25
+ /**
26
+ * The tenant-bound subscription store INV-2 keeps request scope on. Obtain via
27
+ * `SubscriptionStoreFactory.forTenant`; the brand makes an unbound/system store a
28
+ * compile error where one of these is required.
29
+ */
30
+ export interface TenantBoundSubscriptionStore {
31
+ readonly tenantId: string;
32
+ readonly [SUBSCRIPTION_TENANT_BOUND]: true;
33
+ /** Upsert a subscription (idempotent on provider × externalResourceId × thread). */
34
+ subscribe(input: SubscribeInput): Promise<StoredSubscription>;
35
+ /** Remove one subscription; true if a row was deleted. */
36
+ unsubscribe(providerId: string, externalResourceId: string, threadId: string): Promise<boolean>;
37
+ /** This tenant's subscriptions for one thread (the subscribe route's read). */
38
+ listForThread(threadId: string): Promise<StoredSubscription[]>;
39
+ /** This tenant's subscriptions for one provider (the host-DO rehydration query). */
40
+ listForProvider(providerId: string): Promise<StoredSubscription[]>;
41
+ }
42
+ /**
43
+ * The cron/webhook-only cross-tenant view. Deliberately NOT a
44
+ * TenantBoundSubscriptionStore (`[SUBSCRIPTION_TENANT_BOUND]?: never`) so it can
45
+ * never reach request-scoped code — the SystemApprovalStore posture.
46
+ */
47
+ export interface SystemSubscriptionStore {
48
+ readonly [SUBSCRIPTION_TENANT_BOUND]?: never;
49
+ /**
50
+ * Every subscription to `(providerId, externalResourceId)` ACROSS tenants —
51
+ * each carries its own `tenantId`. The webhook's tenant-resolution authority:
52
+ * a webhook payload NEVER names a tenant; the matched row does.
53
+ */
54
+ listByResource(providerId: string, externalResourceId: string): Promise<StoredSubscription[]>;
55
+ }
56
+ /** The brand (INV-2). A unique symbol, satisfied only by a store this module builds. */
57
+ export declare const SUBSCRIPTION_TENANT_BOUND: unique symbol;
58
+ export interface SubscriptionStoreFactory {
59
+ /** Bind a store to one tenant. Throws unless tenantId satisfies INV-3. */
60
+ forTenant(tenantId: string): TenantBoundSubscriptionStore;
61
+ /** The cron/webhook-only cross-tenant view. Never request-scoped. */
62
+ system(): SystemSubscriptionStore;
63
+ }
64
+ export declare class D1SubscriptionStoreFactory implements SubscriptionStoreFactory {
65
+ #private;
66
+ constructor(db: SignalDatabase, options?: {
67
+ uuid?: () => string;
68
+ });
69
+ forTenant(tenantId: string): TenantBoundSubscriptionStore;
70
+ system(): SystemSubscriptionStore;
71
+ }
72
+ /**
73
+ * In-memory factory over ONE shared Map — the mirror of `D1SubscriptionStoreFactory`
74
+ * for hosts/tests with no D1. Not decoration: two `forTenant` views share the
75
+ * backend, so a cross-tenant test is non-vacuous (the InMemoryApprovalStoreFactory
76
+ * rationale). `purgeTenant` mirrors the D1 offboarding delete for in-memory hosts.
77
+ */
78
+ export declare class InMemorySubscriptionStoreFactory implements SubscriptionStoreFactory {
79
+ #private;
80
+ constructor(options?: {
81
+ uuid?: () => string;
82
+ });
83
+ forTenant(tenantId: string): TenantBoundSubscriptionStore;
84
+ system(): SystemSubscriptionStore;
85
+ /** Delete every subscription stamped with this tenant; returns the count. */
86
+ purgeTenant(tenantId: string): number;
87
+ }
88
+ //# sourceMappingURL=subscription-d1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-d1.d.ts","sourceRoot":"","sources":["../../src/signal-providers/subscription-d1.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D,OAAO,EAML,KAAK,cAAc,EACpB,MAAM,yBAAyB,CAAC;AAEjC,mFAAmF;AACnF,eAAO,MAAM,0BAA0B,kCAAkC,CAAC;AAE1E;;;;;;GAMG;AACH,MAAM,WAAW,kBAAmB,SAAQ,kBAAkB;IAC5D,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,kBAAk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2B,YAAW,wBAAwB;;gBAK7D,EAAE,EAAE,cAAc,EAAE,OAAO,GAAE;QAAE,IAAI,CAAC,EAAE,MAAM,MAAM,CAAA;KAAO;IAiBrE,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,4BAA4B;IASzD,MAAM,IAAI,uBAAuB;CAoBlC;AAID;;;;;GAKG;AACH,qBAAa,gCACX,YAAW,wBAAwB;;gBAKvB,OAAO,GAAE;QAAE,IAAI,CAAC,EAAE,MAAM,MAAM,CAAA;KAAO;IAajD,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,4BAA4B;IA4CzD,MAAM,IAAI,uBAAuB;IAejC,6EAA6E;IAC7E,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;CAWtC"}
@@ -0,0 +1,259 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track E (M-007), CI-M-007-002 — the flowsafe-owned D1 subscription store.
3
+ //
4
+ // This is OUR table (`flowsafe_signal_subscriptions`), NOT a `mastra_*` domain:
5
+ // core's SignalProvider keeps subscriptions in an in-memory Map, which is lost on
6
+ // DO eviction and tenant-blind, so flowsafe persists them itself. It mirrors the
7
+ // approval store's INV-2 posture (tenant-store.ts / tenant-brand.ts /
8
+ // d1-store.ts): obtain a store ONLY through the factory, which hands request
9
+ // scope a store BOUND to one tenant at construction (every SELECT/DELETE carries
10
+ // `tenant_id = <ctor field>`) and hands the webhook route the cron/webhook-only
11
+ // `system()` view — a DISTINCT type that cannot flow into request-scoped code.
12
+ //
13
+ // The webhook's `system().listByResource` is the ONE legitimate cross-tenant read
14
+ // (a webhook arrives with no identity — the ROW is the tenant authority, exactly
15
+ // like sweepSLA over SystemApprovalStore). Offboarding is do-runner's `purgeTenant`
16
+ // (a `WHERE tenant_id = ?` delete, the flowsafe_approvals precedent); retention is
17
+ // `none` — a subscription is standing config a tenant means to keep, reaped only
18
+ // at offboarding (like `mastra_schedules`' `none`-with-because), so this table is
19
+ // deliberately absent from the run/thread TTL purges.
20
+ import { TENANT_ID_PATTERN } from '../do-runner/index.js';
21
+ import { d1Changes, dateOrUndefined, isoOrNull, jsonOrNull, parseJsonOrUndefined, } from '../signals/d1-shared.js';
22
+ /** The table this store owns. Kept in sync with do-runner's purgeTenant DELETE. */
23
+ export const SIGNAL_SUBSCRIPTIONS_TABLE = 'flowsafe_signal_subscriptions';
24
+ /** The brand (INV-2). A unique symbol, satisfied only by a store this module builds. */
25
+ export const SUBSCRIPTION_TENANT_BOUND = Symbol('flowsafe.signalSubscriptionTenantBound');
26
+ function assertTenantId(tenantId) {
27
+ if (typeof tenantId !== 'string' || !TENANT_ID_PATTERN.test(tenantId)) {
28
+ throw new Error(`forTenant: tenantId '${tenantId}' violates INV-3 (^[a-z0-9]{3,32}$)`);
29
+ }
30
+ }
31
+ const SCHEMA_STATEMENTS = [
32
+ `CREATE TABLE IF NOT EXISTS ${SIGNAL_SUBSCRIPTIONS_TABLE} (
33
+ id TEXT PRIMARY KEY,
34
+ tenant_id TEXT NOT NULL,
35
+ provider_id TEXT NOT NULL,
36
+ thread_id TEXT NOT NULL,
37
+ resource_id TEXT NOT NULL,
38
+ external_resource_id TEXT NOT NULL,
39
+ subscribed_at TEXT NOT NULL,
40
+ metadata TEXT
41
+ )`,
42
+ // One subscription per (tenant, provider, external resource, thread): a
43
+ // re-subscribe upserts rather than duplicating (the ON CONFLICT target below).
44
+ `CREATE UNIQUE INDEX IF NOT EXISTS ${SIGNAL_SUBSCRIPTIONS_TABLE}_key
45
+ ON ${SIGNAL_SUBSCRIPTIONS_TABLE} (tenant_id, provider_id, external_resource_id, thread_id)`,
46
+ // The webhook's cross-tenant lookup rides this: given a provider + external
47
+ // resource, find every subscribed (tenant, thread).
48
+ `CREATE INDEX IF NOT EXISTS ${SIGNAL_SUBSCRIPTIONS_TABLE}_resource
49
+ ON ${SIGNAL_SUBSCRIPTIONS_TABLE} (provider_id, external_resource_id)`,
50
+ // The host-DO rehydration rides this: one tenant's subscriptions for one provider.
51
+ `CREATE INDEX IF NOT EXISTS ${SIGNAL_SUBSCRIPTIONS_TABLE}_rehydrate
52
+ ON ${SIGNAL_SUBSCRIPTIONS_TABLE} (tenant_id, provider_id)`,
53
+ ];
54
+ async function createSubscriptionSchema(db) {
55
+ for (const statement of SCHEMA_STATEMENTS) {
56
+ await db.prepare(statement).run();
57
+ }
58
+ }
59
+ function rowToSubscription(row) {
60
+ return {
61
+ id: row.id,
62
+ providerId: row.provider_id,
63
+ threadId: row.thread_id,
64
+ resourceId: row.resource_id,
65
+ externalResourceId: row.external_resource_id,
66
+ subscribedAt: dateOrUndefined(row.subscribed_at) ?? new Date(0),
67
+ metadata: parseJsonOrUndefined(row.metadata) ?? {},
68
+ tenantId: row.tenant_id,
69
+ };
70
+ }
71
+ class D1TenantBoundSubscriptionStore {
72
+ [SUBSCRIPTION_TENANT_BOUND] = true;
73
+ tenantId;
74
+ #db;
75
+ #ready;
76
+ #uuid;
77
+ constructor(db, options) {
78
+ this.#db = db;
79
+ this.tenantId = options.tenantId;
80
+ this.#ready = options.ready;
81
+ this.#uuid = options.uuid;
82
+ }
83
+ async subscribe(input) {
84
+ await this.#ready();
85
+ // A server-minted salted id — a subscription id is tenant-owned like a runId,
86
+ // so a purge by the tenant range would ALSO reap it (belt to the tenant_id
87
+ // delete). Kept on re-subscribe (ON CONFLICT DO UPDATE never touches `id`).
88
+ const id = `${this.tenantId}_${this.#uuid()}`;
89
+ const subscribedAt = new Date();
90
+ const row = await this.#db
91
+ .prepare(`INSERT INTO ${SIGNAL_SUBSCRIPTIONS_TABLE}
92
+ (id, tenant_id, provider_id, thread_id, resource_id, external_resource_id, subscribed_at, metadata)
93
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
94
+ ON CONFLICT (tenant_id, provider_id, external_resource_id, thread_id)
95
+ DO UPDATE SET resource_id = excluded.resource_id,
96
+ metadata = COALESCE(excluded.metadata, metadata)
97
+ RETURNING *`)
98
+ .bind(id, this.tenantId, input.providerId, input.threadId, input.resourceId, input.externalResourceId, isoOrNull(subscribedAt),
99
+ // OMITTED metadata binds NULL, so the COALESCE above PRESERVES the
100
+ // existing value on a re-subscribe (an idempotent retry never wipes it);
101
+ // an explicit `{}` binds '{}' and REPLACES (clears) it.
102
+ jsonOrNull(input.metadata))
103
+ .first();
104
+ if (row === null) {
105
+ throw new Error('subscribe: upsert returned no row');
106
+ }
107
+ return rowToSubscription(row);
108
+ }
109
+ async unsubscribe(providerId, externalResourceId, threadId) {
110
+ await this.#ready();
111
+ const result = await this.#db
112
+ .prepare(`DELETE FROM ${SIGNAL_SUBSCRIPTIONS_TABLE}
113
+ WHERE tenant_id = ? AND provider_id = ? AND external_resource_id = ? AND thread_id = ?`)
114
+ .bind(this.tenantId, providerId, externalResourceId, threadId)
115
+ .run();
116
+ return d1Changes(result) > 0;
117
+ }
118
+ async listForThread(threadId) {
119
+ await this.#ready();
120
+ const { results } = await this.#db
121
+ .prepare(`SELECT * FROM ${SIGNAL_SUBSCRIPTIONS_TABLE}
122
+ WHERE tenant_id = ? AND thread_id = ? ORDER BY subscribed_at`)
123
+ .bind(this.tenantId, threadId)
124
+ .all();
125
+ return results.map(rowToSubscription);
126
+ }
127
+ async listForProvider(providerId) {
128
+ await this.#ready();
129
+ const { results } = await this.#db
130
+ .prepare(`SELECT * FROM ${SIGNAL_SUBSCRIPTIONS_TABLE}
131
+ WHERE tenant_id = ? AND provider_id = ? ORDER BY subscribed_at`)
132
+ .bind(this.tenantId, providerId)
133
+ .all();
134
+ return results.map(rowToSubscription);
135
+ }
136
+ }
137
+ export class D1SubscriptionStoreFactory {
138
+ #db;
139
+ #uuid;
140
+ #schemaReady;
141
+ constructor(db, options = {}) {
142
+ this.#db = db;
143
+ this.#uuid = options.uuid ?? (() => crypto.randomUUID());
144
+ }
145
+ // One memoized DDL pass per factory; a failed attempt clears the memo so the
146
+ // next call retries rather than pinning everything to a dead promise.
147
+ #ready = () => {
148
+ this.#schemaReady ??= createSubscriptionSchema(this.#db).catch((error) => {
149
+ this.#schemaReady = undefined;
150
+ throw error;
151
+ });
152
+ return this.#schemaReady;
153
+ };
154
+ forTenant(tenantId) {
155
+ assertTenantId(tenantId);
156
+ return new D1TenantBoundSubscriptionStore(this.#db, {
157
+ tenantId,
158
+ ready: this.#ready,
159
+ uuid: this.#uuid,
160
+ });
161
+ }
162
+ system() {
163
+ const db = this.#db;
164
+ const ready = this.#ready;
165
+ return {
166
+ async listByResource(providerId, externalResourceId) {
167
+ await ready();
168
+ const { results } = await db
169
+ .prepare(`SELECT * FROM ${SIGNAL_SUBSCRIPTIONS_TABLE}
170
+ WHERE provider_id = ? AND external_resource_id = ?`)
171
+ .bind(providerId, externalResourceId)
172
+ .all();
173
+ return results.map(rowToSubscription);
174
+ },
175
+ };
176
+ }
177
+ }
178
+ // --- In-memory (dev/test parity) -----------------------------------------
179
+ /**
180
+ * In-memory factory over ONE shared Map — the mirror of `D1SubscriptionStoreFactory`
181
+ * for hosts/tests with no D1. Not decoration: two `forTenant` views share the
182
+ * backend, so a cross-tenant test is non-vacuous (the InMemoryApprovalStoreFactory
183
+ * rationale). `purgeTenant` mirrors the D1 offboarding delete for in-memory hosts.
184
+ */
185
+ export class InMemorySubscriptionStoreFactory {
186
+ #rows = new Map();
187
+ #uuid;
188
+ constructor(options = {}) {
189
+ this.#uuid = options.uuid ?? (() => crypto.randomUUID());
190
+ }
191
+ #keyOf(sub) {
192
+ return `${sub.tenantId}${sub.providerId}${sub.externalResourceId}${sub.threadId}`;
193
+ }
194
+ forTenant(tenantId) {
195
+ assertTenantId(tenantId);
196
+ const rows = this.#rows;
197
+ const keyOf = this.#keyOf.bind(this);
198
+ const uuid = this.#uuid;
199
+ return {
200
+ [SUBSCRIPTION_TENANT_BOUND]: true,
201
+ tenantId,
202
+ async subscribe(input) {
203
+ const key = keyOf({ tenantId, ...input });
204
+ const existing = rows.get(key);
205
+ const sub = {
206
+ id: existing?.id ?? `${tenantId}_${uuid()}`,
207
+ providerId: input.providerId,
208
+ threadId: input.threadId,
209
+ resourceId: input.resourceId,
210
+ externalResourceId: input.externalResourceId,
211
+ subscribedAt: existing?.subscribedAt ?? new Date(),
212
+ // Omitted metadata PRESERVES the existing value (mirrors the D1
213
+ // COALESCE); an explicit `{}` replaces it.
214
+ metadata: input.metadata ?? existing?.metadata ?? {},
215
+ tenantId,
216
+ };
217
+ rows.set(key, sub);
218
+ return structuredClone(sub);
219
+ },
220
+ async unsubscribe(providerId, externalResourceId, threadId) {
221
+ return rows.delete(keyOf({ tenantId, providerId, externalResourceId, threadId }));
222
+ },
223
+ async listForThread(threadId) {
224
+ return [...rows.values()]
225
+ .filter((s) => s.tenantId === tenantId && s.threadId === threadId)
226
+ .map((s) => structuredClone(s));
227
+ },
228
+ async listForProvider(providerId) {
229
+ return [...rows.values()]
230
+ .filter((s) => s.tenantId === tenantId && s.providerId === providerId)
231
+ .map((s) => structuredClone(s));
232
+ },
233
+ };
234
+ }
235
+ system() {
236
+ const rows = this.#rows;
237
+ return {
238
+ async listByResource(providerId, externalResourceId) {
239
+ return [...rows.values()]
240
+ .filter((s) => s.providerId === providerId &&
241
+ s.externalResourceId === externalResourceId)
242
+ .map((s) => structuredClone(s));
243
+ },
244
+ };
245
+ }
246
+ /** Delete every subscription stamped with this tenant; returns the count. */
247
+ purgeTenant(tenantId) {
248
+ assertTenantId(tenantId);
249
+ let purged = 0;
250
+ for (const [key, sub] of this.#rows) {
251
+ if (sub.tenantId === tenantId) {
252
+ this.#rows.delete(key);
253
+ purged += 1;
254
+ }
255
+ }
256
+ return purged;
257
+ }
258
+ }
259
+ //# sourceMappingURL=subscription-d1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-d1.js","sourceRoot":"","sources":["../../src/signal-providers/subscription-d1.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,4EAA4E;AAC5E,EAAE;AACF,gFAAgF;AAChF,kFAAkF;AAClF,iFAAiF;AACjF,sEAAsE;AACtE,6EAA6E;AAC7E,iFAAiF;AACjF,gFAAgF;AACh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U,KAAK,UAAU,CAAC;qBACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;YACpC,CAAC;SACF,CAAC;IACJ,CAAC;IAED,MAAM;QACJ,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC;QACxB,OAAO;YACL,KAAK,CAAC,cAAc,CAAC,UAAU,EAAE,kBAAkB;gBACjD,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;qBACtB,MAAM,CACL,CAAC,CAAC,EAAE,EAAE,CACJ,CAAC,CAAC,UAAU,KAAK,UAAU;oBAC3B,CAAC,CAAC,kBAAkB,KAAK,kBAAkB,CAC9C;qBACA,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;YACpC,CAAC;SACF,CAAC;IACJ,CAAC;IAED,6EAA6E;IAC7E,WAAW,CAAC,QAAgB;QAC1B,cAAc,CAAC,QAAQ,CAAC,CAAC;QACzB,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,KAAK,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACpC,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;gBAC9B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,CAAC;YACd,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"}
@@ -0,0 +1,88 @@
1
+ import { type ApprovalRole, type TenantResolver } from '../approval-api/index.js';
2
+ import { type ThreadTopology } from '../host-kit/index.js';
3
+ import { type SignalProviderAdapter } from './provider.js';
4
+ import type { SubscriptionStoreFactory, SystemSubscriptionStore } from './subscription-d1.js';
5
+ export interface WebhookAuditEvent {
6
+ type: 'signal-provider.webhook';
7
+ providerId: string;
8
+ outcome: 'accepted' | 'rejected';
9
+ /** WHY, for rejected outcomes (or a partial-accept note). */
10
+ reason?: string;
11
+ /** Matched subscription rows (accepted path). */
12
+ matched?: number;
13
+ /** Rows actually delivered (accepted path). */
14
+ delivered?: number;
15
+ /** Raw body size in bytes the size cap measured. */
16
+ contentBytes: number;
17
+ timestamp: string;
18
+ }
19
+ export interface SubscriptionAuditEvent {
20
+ type: 'signal-provider.subscription';
21
+ tenantId: string;
22
+ actorId: string;
23
+ threadId: string;
24
+ /** The attempted action — `list` is a read (GET), never mislabeled a mutation. */
25
+ action: 'subscribe' | 'unsubscribe' | 'list';
26
+ outcome: 'accepted' | 'rejected';
27
+ providerId?: string;
28
+ externalResourceId?: string;
29
+ reason?: string;
30
+ timestamp: string;
31
+ }
32
+ export type SignalProviderAuditEvent = WebhookAuditEvent | SubscriptionAuditEvent;
33
+ export type SignalProviderAuditSink = (event: SignalProviderAuditEvent) => void | Promise<void>;
34
+ /** Per provider+tenant rate cap. false ⇒ REFUSE that tenant's deliveries. */
35
+ export type WebhookRateLimiter = (providerId: string, tenantId: string) => boolean | Promise<boolean>;
36
+ export interface WebhookRouterOptions {
37
+ /** Registered providers, keyed by id. Empty ⇒ every webhook is route-absent. */
38
+ providers: Record<string, SignalProviderAdapter>;
39
+ /** The cross-tenant subscription view — the webhook's tenant authority. */
40
+ subscriptions: SystemSubscriptionStore;
41
+ /** The sanctioned reach into a thread DO (stamps the tenant header, 404s a foreign thread). */
42
+ topology: ThreadTopology;
43
+ /** Per-provider signing secret (from a binding/env). undefined ⇒ provider route absent. */
44
+ secretForProvider: (providerId: string) => string | undefined;
45
+ /** Every ingest audited (accepted + rejected). Forgery audits are bounded (see below). */
46
+ audit?: SignalProviderAuditSink;
47
+ /** Per provider+tenant delivery rate cap. Absent ⇒ unmetered. */
48
+ rateLimit?: WebhookRateLimiter;
49
+ /** Route prefix. Default '/api/signal-providers'. */
50
+ basePath?: string;
51
+ /**
52
+ * Max raw webhook body in bytes. Must be a nonnegative safe integer; zero
53
+ * denies every non-empty body. Default 1 MiB.
54
+ */
55
+ maxBodyBytes?: number;
56
+ /**
57
+ * Forgery audits per provider per window. Must be a nonnegative safe integer;
58
+ * zero disables forgery audit writes without accepting forgeries. Default 10.
59
+ */
60
+ maxForgeryAuditsPerWindow?: number;
61
+ /** Positive safe-integer forgery-audit window in ms. Default 60000. */
62
+ forgeryAuditWindowMs?: number;
63
+ /** Epoch-ms clock for the forgery window, injectable for tests. Default Date.now. */
64
+ now?: () => number;
65
+ }
66
+ export type WebhookRouter = (request: Request) => Promise<Response | null>;
67
+ export declare function createWebhookRouter(options: WebhookRouterOptions): WebhookRouter;
68
+ export interface SubscriptionRouterOptions {
69
+ /** authenticate → INV-3 → bind; undefined ⇒ 401. */
70
+ resolve: TenantResolver;
71
+ /** Tenant-bound store factory — bound per request to the resolved tenant (INV-2). */
72
+ subscriptions: SubscriptionStoreFactory;
73
+ /** Who may manage subscriptions. Default RUN_START_ROLES (operator/admin). */
74
+ roles?: readonly ApprovalRole[];
75
+ /** The provider ids a subscription may name. Absent ⇒ any PROVIDER_ID_PATTERN slug. */
76
+ knownProviders?: readonly string[];
77
+ audit?: SignalProviderAuditSink;
78
+ /** Route prefix. Default '/api/threads'. Routes: `<base>/:threadId/subscriptions`. */
79
+ basePath?: string;
80
+ /**
81
+ * Max request body in bytes. Must be a nonnegative safe integer; zero denies
82
+ * every non-empty mutation body. Default 4096.
83
+ */
84
+ maxBodyBytes?: number;
85
+ }
86
+ export type SubscriptionRouter = (request: Request) => Promise<Response | null>;
87
+ export declare function createSubscriptionRouter(options: SubscriptionRouterOptions): SubscriptionRouter;
88
+ //# sourceMappingURL=webhook-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-route.d.ts","sourceRoot":"","sources":["../../src/signal-providers/webhook-route.ts"],"names":[],"mappings":"AAiCA,OAAO,EACL,KAAK,YAAY,EAIjB,KAAK,cAAc,EACpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAIL,KAAK,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