@proofoftech/flowsafe 0.1.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 (204) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +202 -0
  3. package/README.md +273 -0
  4. package/dist/approval-api/contract.d.ts +45 -0
  5. package/dist/approval-api/contract.d.ts.map +1 -0
  6. package/dist/approval-api/contract.js +37 -0
  7. package/dist/approval-api/contract.js.map +1 -0
  8. package/dist/approval-api/d1-store.d.ts +52 -0
  9. package/dist/approval-api/d1-store.d.ts.map +1 -0
  10. package/dist/approval-api/d1-store.js +468 -0
  11. package/dist/approval-api/d1-store.js.map +1 -0
  12. package/dist/approval-api/grants.d.ts +52 -0
  13. package/dist/approval-api/grants.d.ts.map +1 -0
  14. package/dist/approval-api/grants.js +200 -0
  15. package/dist/approval-api/grants.js.map +1 -0
  16. package/dist/approval-api/index.d.ts +21 -0
  17. package/dist/approval-api/index.d.ts.map +1 -0
  18. package/dist/approval-api/index.js +18 -0
  19. package/dist/approval-api/index.js.map +1 -0
  20. package/dist/approval-api/retention.d.ts +32 -0
  21. package/dist/approval-api/retention.d.ts.map +1 -0
  22. package/dist/approval-api/retention.js +81 -0
  23. package/dist/approval-api/retention.js.map +1 -0
  24. package/dist/approval-api/router.d.ts +51 -0
  25. package/dist/approval-api/router.d.ts.map +1 -0
  26. package/dist/approval-api/router.js +245 -0
  27. package/dist/approval-api/router.js.map +1 -0
  28. package/dist/approval-api/service.d.ts +134 -0
  29. package/dist/approval-api/service.d.ts.map +1 -0
  30. package/dist/approval-api/service.js +537 -0
  31. package/dist/approval-api/service.js.map +1 -0
  32. package/dist/approval-api/store.d.ts +126 -0
  33. package/dist/approval-api/store.d.ts.map +1 -0
  34. package/dist/approval-api/store.js +189 -0
  35. package/dist/approval-api/store.js.map +1 -0
  36. package/dist/approval-api/tenant-brand.d.ts +35 -0
  37. package/dist/approval-api/tenant-brand.d.ts.map +1 -0
  38. package/dist/approval-api/tenant-brand.js +18 -0
  39. package/dist/approval-api/tenant-brand.js.map +1 -0
  40. package/dist/approval-api/tenant-context.d.ts +44 -0
  41. package/dist/approval-api/tenant-context.d.ts.map +1 -0
  42. package/dist/approval-api/tenant-context.js +49 -0
  43. package/dist/approval-api/tenant-context.js.map +1 -0
  44. package/dist/approval-api/tenant-store.d.ts +36 -0
  45. package/dist/approval-api/tenant-store.d.ts.map +1 -0
  46. package/dist/approval-api/tenant-store.js +122 -0
  47. package/dist/approval-api/tenant-store.js.map +1 -0
  48. package/dist/approval-api/types.d.ts +247 -0
  49. package/dist/approval-api/types.d.ts.map +1 -0
  50. package/dist/approval-api/types.js +157 -0
  51. package/dist/approval-api/types.js.map +1 -0
  52. package/dist/approval-ui/App.d.ts +11 -0
  53. package/dist/approval-ui/App.d.ts.map +1 -0
  54. package/dist/approval-ui/App.js +15 -0
  55. package/dist/approval-ui/App.js.map +1 -0
  56. package/dist/approval-ui/DetailView.d.ts +13 -0
  57. package/dist/approval-ui/DetailView.d.ts.map +1 -0
  58. package/dist/approval-ui/DetailView.js +20 -0
  59. package/dist/approval-ui/DetailView.js.map +1 -0
  60. package/dist/approval-ui/MetricsView.d.ts +7 -0
  61. package/dist/approval-ui/MetricsView.d.ts.map +1 -0
  62. package/dist/approval-ui/MetricsView.js +22 -0
  63. package/dist/approval-ui/MetricsView.js.map +1 -0
  64. package/dist/approval-ui/QueueView.d.ts +11 -0
  65. package/dist/approval-ui/QueueView.d.ts.map +1 -0
  66. package/dist/approval-ui/QueueView.js +59 -0
  67. package/dist/approval-ui/QueueView.js.map +1 -0
  68. package/dist/approval-ui/client.d.ts +34 -0
  69. package/dist/approval-ui/client.d.ts.map +1 -0
  70. package/dist/approval-ui/client.js +103 -0
  71. package/dist/approval-ui/client.js.map +1 -0
  72. package/dist/approval-ui/components.d.ts +125 -0
  73. package/dist/approval-ui/components.d.ts.map +1 -0
  74. package/dist/approval-ui/components.js +54 -0
  75. package/dist/approval-ui/components.js.map +1 -0
  76. package/dist/approval-ui/index.d.ts +21 -0
  77. package/dist/approval-ui/index.d.ts.map +1 -0
  78. package/dist/approval-ui/index.js +21 -0
  79. package/dist/approval-ui/index.js.map +1 -0
  80. package/dist/approval-ui/mount.d.ts +23 -0
  81. package/dist/approval-ui/mount.d.ts.map +1 -0
  82. package/dist/approval-ui/mount.js +17 -0
  83. package/dist/approval-ui/mount.js.map +1 -0
  84. package/dist/approval-ui/tips.d.ts +32 -0
  85. package/dist/approval-ui/tips.d.ts.map +1 -0
  86. package/dist/approval-ui/tips.js +32 -0
  87. package/dist/approval-ui/tips.js.map +1 -0
  88. package/dist/approval-ui/use-approval-dashboard.d.ts +70 -0
  89. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -0
  90. package/dist/approval-ui/use-approval-dashboard.js +148 -0
  91. package/dist/approval-ui/use-approval-dashboard.js.map +1 -0
  92. package/dist/approval-ui/view-model.d.ts +24 -0
  93. package/dist/approval-ui/view-model.d.ts.map +1 -0
  94. package/dist/approval-ui/view-model.js +62 -0
  95. package/dist/approval-ui/view-model.js.map +1 -0
  96. package/dist/artifacts/index.d.ts +123 -0
  97. package/dist/artifacts/index.d.ts.map +1 -0
  98. package/dist/artifacts/index.js +223 -0
  99. package/dist/artifacts/index.js.map +1 -0
  100. package/dist/audit-export/index.d.ts +71 -0
  101. package/dist/audit-export/index.d.ts.map +1 -0
  102. package/dist/audit-export/index.js +124 -0
  103. package/dist/audit-export/index.js.map +1 -0
  104. package/dist/do-runner/breakwater-keys.d.ts +23 -0
  105. package/dist/do-runner/breakwater-keys.d.ts.map +1 -0
  106. package/dist/do-runner/breakwater-keys.js +38 -0
  107. package/dist/do-runner/breakwater-keys.js.map +1 -0
  108. package/dist/do-runner/cf-types.d.ts +26 -0
  109. package/dist/do-runner/cf-types.d.ts.map +1 -0
  110. package/dist/do-runner/cf-types.js +13 -0
  111. package/dist/do-runner/cf-types.js.map +1 -0
  112. package/dist/do-runner/d1-storage.d.ts +128 -0
  113. package/dist/do-runner/d1-storage.d.ts.map +1 -0
  114. package/dist/do-runner/d1-storage.js +287 -0
  115. package/dist/do-runner/d1-storage.js.map +1 -0
  116. package/dist/do-runner/durable-object.d.ts +28 -0
  117. package/dist/do-runner/durable-object.d.ts.map +1 -0
  118. package/dist/do-runner/durable-object.js +164 -0
  119. package/dist/do-runner/durable-object.js.map +1 -0
  120. package/dist/do-runner/index.d.ts +12 -0
  121. package/dist/do-runner/index.d.ts.map +1 -0
  122. package/dist/do-runner/index.js +11 -0
  123. package/dist/do-runner/index.js.map +1 -0
  124. package/dist/do-runner/init.d.ts +38 -0
  125. package/dist/do-runner/init.d.ts.map +1 -0
  126. package/dist/do-runner/init.js +45 -0
  127. package/dist/do-runner/init.js.map +1 -0
  128. package/dist/do-runner/path-safe-id.d.ts +19 -0
  129. package/dist/do-runner/path-safe-id.d.ts.map +1 -0
  130. package/dist/do-runner/path-safe-id.js +70 -0
  131. package/dist/do-runner/path-safe-id.js.map +1 -0
  132. package/dist/do-runner/resume-ledger.d.ts +48 -0
  133. package/dist/do-runner/resume-ledger.d.ts.map +1 -0
  134. package/dist/do-runner/resume-ledger.js +59 -0
  135. package/dist/do-runner/resume-ledger.js.map +1 -0
  136. package/dist/do-runner/runtime.d.ts +161 -0
  137. package/dist/do-runner/runtime.d.ts.map +1 -0
  138. package/dist/do-runner/runtime.js +509 -0
  139. package/dist/do-runner/runtime.js.map +1 -0
  140. package/dist/host-kit/approval-bridge.d.ts +109 -0
  141. package/dist/host-kit/approval-bridge.d.ts.map +1 -0
  142. package/dist/host-kit/approval-bridge.js +262 -0
  143. package/dist/host-kit/approval-bridge.js.map +1 -0
  144. package/dist/host-kit/bearer-auth.d.ts +19 -0
  145. package/dist/host-kit/bearer-auth.d.ts.map +1 -0
  146. package/dist/host-kit/bearer-auth.js +67 -0
  147. package/dist/host-kit/bearer-auth.js.map +1 -0
  148. package/dist/host-kit/do-response.d.ts +13 -0
  149. package/dist/host-kit/do-response.d.ts.map +1 -0
  150. package/dist/host-kit/do-response.js +24 -0
  151. package/dist/host-kit/do-response.js.map +1 -0
  152. package/dist/host-kit/do-run-topology.d.ts +32 -0
  153. package/dist/host-kit/do-run-topology.d.ts.map +1 -0
  154. package/dist/host-kit/do-run-topology.js +39 -0
  155. package/dist/host-kit/do-run-topology.js.map +1 -0
  156. package/dist/host-kit/env-vars.d.ts +26 -0
  157. package/dist/host-kit/env-vars.d.ts.map +1 -0
  158. package/dist/host-kit/env-vars.js +48 -0
  159. package/dist/host-kit/env-vars.js.map +1 -0
  160. package/dist/host-kit/host-approval-service.d.ts +125 -0
  161. package/dist/host-kit/host-approval-service.d.ts.map +1 -0
  162. package/dist/host-kit/host-approval-service.js +187 -0
  163. package/dist/host-kit/host-approval-service.js.map +1 -0
  164. package/dist/host-kit/index.d.ts +18 -0
  165. package/dist/host-kit/index.d.ts.map +1 -0
  166. package/dist/host-kit/index.js +34 -0
  167. package/dist/host-kit/index.js.map +1 -0
  168. package/dist/host-kit/module.d.ts +34 -0
  169. package/dist/host-kit/module.d.ts.map +1 -0
  170. package/dist/host-kit/module.js +17 -0
  171. package/dist/host-kit/module.js.map +1 -0
  172. package/dist/host-kit/registration.d.ts +11 -0
  173. package/dist/host-kit/registration.d.ts.map +1 -0
  174. package/dist/host-kit/registration.js +21 -0
  175. package/dist/host-kit/registration.js.map +1 -0
  176. package/dist/host-kit/run-route-error.d.ts +11 -0
  177. package/dist/host-kit/run-route-error.d.ts.map +1 -0
  178. package/dist/host-kit/run-route-error.js +22 -0
  179. package/dist/host-kit/run-route-error.js.map +1 -0
  180. package/dist/host-kit/run-router.d.ts +60 -0
  181. package/dist/host-kit/run-router.d.ts.map +1 -0
  182. package/dist/host-kit/run-router.js +212 -0
  183. package/dist/host-kit/run-router.js.map +1 -0
  184. package/dist/host-kit/subdomain-check.d.ts +23 -0
  185. package/dist/host-kit/subdomain-check.d.ts.map +1 -0
  186. package/dist/host-kit/subdomain-check.js +60 -0
  187. package/dist/host-kit/subdomain-check.js.map +1 -0
  188. package/dist/host-kit/tenant-registry.d.ts +51 -0
  189. package/dist/host-kit/tenant-registry.d.ts.map +1 -0
  190. package/dist/host-kit/tenant-registry.js +87 -0
  191. package/dist/host-kit/tenant-registry.js.map +1 -0
  192. package/dist/host-kit/verifier.d.ts +63 -0
  193. package/dist/host-kit/verifier.d.ts.map +1 -0
  194. package/dist/host-kit/verifier.js +191 -0
  195. package/dist/host-kit/verifier.js.map +1 -0
  196. package/dist/host-kit/workflow-meta.d.ts +25 -0
  197. package/dist/host-kit/workflow-meta.d.ts.map +1 -0
  198. package/dist/host-kit/workflow-meta.js +12 -0
  199. package/dist/host-kit/workflow-meta.js.map +1 -0
  200. package/dist/index.d.ts +9 -0
  201. package/dist/index.d.ts.map +1 -0
  202. package/dist/index.js +25 -0
  203. package/dist/index.js.map +1 -0
  204. package/package.json +95 -0
@@ -0,0 +1,212 @@
1
+ // HTTP surface for the run catalog + run lifecycle, shared by every host.
2
+ //
3
+ // Mirrors createApprovalRouter's contract — plain fetch routing, an injected
4
+ // `authenticate`, and `null` for paths outside its ownership so a host Worker
5
+ // can compose it after the approval router. (Its two paths are fixed rather
6
+ // than configurable: unlike the approval surface, a host mounts exactly one run
7
+ // surface.) What it owns that the hosts used to triplicate is the AUTHORIZATION
8
+ // order:
9
+ //
10
+ // 1. authenticate -> 401
11
+ // 2. any POST, coarse RUN_START_ROLES -> 403 (reviewer/viewer are read-only)
12
+ // 3. per-workflow meta.allowedRoles -> 403 (a module may narrow further;
13
+ // applied to EVERY mutating
14
+ // route — start via the body's
15
+ // workflowId, resume and any
16
+ // future POST via the path's)
17
+ //
18
+ // and the suspension bridge: a start that suspends queues its approval
19
+ // attributed to the STARTING actor, so that actor cannot later decide their own
20
+ // run (separation of duties).
21
+ //
22
+ // The resume route deliberately carries NO grants. A forged `resumeData.approved`
23
+ // can flip a workflow boolean, but capability comes only from the server-derived
24
+ // grant the runtime mints per leg (approval-api/grants.ts), so a side-effecting
25
+ // step re-checks and fails closed. Approve through the queue, not this route.
26
+ import { RUN_START_ROLES, TenantResolutionError, } from '../approval-api/index.js';
27
+ import { InvalidRunRequestError, RunAlreadyExistsError, RunNotSuspendedError, UnknownRunError, UnknownWorkflowError, } from '../do-runner/index.js';
28
+ import { queueApprovalForSuspension } from './approval-bridge.js';
29
+ import { RunRouteError } from './run-route-error.js';
30
+ // no-store is defense in depth: this is an authenticated API served from the
31
+ // same origin as (and under) the SPA's `assets` block, and a run projection
32
+ // names the actors and payloads of an approval.
33
+ function json(payload, status = 200) {
34
+ return new Response(JSON.stringify(payload), {
35
+ status,
36
+ headers: {
37
+ 'content-type': 'application/json',
38
+ 'cache-control': 'no-store',
39
+ },
40
+ });
41
+ }
42
+ function errorResponse(error) {
43
+ if (error instanceof RunRouteError) {
44
+ return json({ error: error.message }, error.status);
45
+ }
46
+ if (error instanceof TenantResolutionError) {
47
+ // Authenticated but with a malformed tenant claim — a verifier bug,
48
+ // surfaced as forbidden rather than a retryable 500.
49
+ return json({ error: 'forbidden' }, 403);
50
+ }
51
+ if (error instanceof UnknownWorkflowError ||
52
+ error instanceof UnknownRunError) {
53
+ return json({ error: error.message }, 404);
54
+ }
55
+ if (error instanceof RunNotSuspendedError ||
56
+ error instanceof RunAlreadyExistsError) {
57
+ return json({ error: error.message }, 409);
58
+ }
59
+ if (error instanceof InvalidRunRequestError) {
60
+ return json({ error: error.message }, 400);
61
+ }
62
+ return json({ error: error instanceof Error ? error.message : String(error) }, 500);
63
+ }
64
+ async function readJson(request) {
65
+ try {
66
+ return await request.json();
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ export function createRunRouter(options) {
73
+ const { workflows, resolve } = options;
74
+ const systemActorId = options.systemActorId ?? 'flowsafe-system';
75
+ const metaById = new Map(workflows.map((meta) => [meta.id, meta]));
76
+ function metaFor(workflowId) {
77
+ return metaById.get(workflowId);
78
+ }
79
+ return async (request) => {
80
+ const url = new URL(request.url);
81
+ const segments = url.pathname.split('/').filter(Boolean);
82
+ if (url.pathname !== '/workflows' && segments[0] !== 'runs')
83
+ return null;
84
+ try {
85
+ // Resolution is authentication + INV-3 validation + tenant binding in
86
+ // one step (tenant-context.ts): a malformed tenant claim throws (403
87
+ // below), never concatenates into a runId or an ownership prefix.
88
+ const tenant = await resolve(request);
89
+ if (!tenant)
90
+ return json({ error: 'authentication required' }, 401);
91
+ const actor = tenant.actor;
92
+ // Coarse gate: reviewers and viewers may inspect runs, never advance
93
+ // them. Applied before any route so a new POST route cannot forget it.
94
+ if (request.method === 'POST' && !RUN_START_ROLES.includes(actor.role)) {
95
+ return json({ error: 'forbidden' }, 403);
96
+ }
97
+ if (request.method === 'GET' && url.pathname === '/workflows') {
98
+ // The catalog echoes the AUTHENTICATED identity so the SPA renders
99
+ // role gates from the server's view of the actor — a client that
100
+ // guesses its own role from a local token table is fail-open (an
101
+ // unknown token must not default to admin).
102
+ return json({
103
+ workflows,
104
+ actor: { id: actor.id, role: actor.role, tenantId: actor.tenantId },
105
+ });
106
+ }
107
+ if (segments[0] !== 'runs')
108
+ return json({ error: 'not found' }, 404);
109
+ const [, workflowId, runId, action] = segments;
110
+ if (request.method === 'POST' && segments.length === 1) {
111
+ const body = (await readJson(request));
112
+ if (!body || typeof body.workflowId !== 'string') {
113
+ return json({ error: 'workflowId is required' }, 400);
114
+ }
115
+ // INV-1: the runId IS the tenant carrier; a client may never choose
116
+ // it. 400 (not silent override) so a caller pinning ids finds out.
117
+ if (body.runId !== undefined) {
118
+ return json({ error: 'runId is server-assigned' }, 400);
119
+ }
120
+ const meta = metaFor(body.workflowId);
121
+ if (!meta) {
122
+ return json({ error: `unknown workflow '${body.workflowId}'` }, 404);
123
+ }
124
+ // Per-workflow RBAC: a workflow may restrict who can START it — a finer
125
+ // gate than the coarse "can start any run" check above.
126
+ const { allowedRoles } = meta;
127
+ if (allowedRoles && !allowedRoles.includes(actor.role)) {
128
+ return json({
129
+ error: `role '${actor.role}' may not start '${body.workflowId}'`,
130
+ }, 403);
131
+ }
132
+ // The router mints the tenant-salted runId and hands it to the host,
133
+ // so a DO-routing host has its instance key up front.
134
+ const summary = await options.start(body.workflowId, tenant.newRunId(), body.inputData);
135
+ if (summary.status !== 'suspended')
136
+ return json(summary);
137
+ const systemActor = {
138
+ id: systemActorId,
139
+ role: 'operator',
140
+ tenantId: tenant.tenantId,
141
+ };
142
+ const approvals = await queueApprovalForSuspension(tenant.service(), body.workflowId, summary, actor.id, systemActor);
143
+ // `approval` remains the single-gate response contract (what the SPA
144
+ // links); `approvals` carries every record a parallel multi-step
145
+ // suspension filed, so no gate is invisible to the caller.
146
+ return json({ ...summary, approval: approvals[0], approvals });
147
+ }
148
+ // Status and resume both validate the workflow against the catalog: the
149
+ // start route already did, and a passthrough that did not would answer
150
+ // for workflow ids this host never registered.
151
+ if (workflowId && runId && !metaFor(workflowId)) {
152
+ return json({ error: `unknown workflow '${workflowId}'` }, 404);
153
+ }
154
+ // Ownership: attribution is not authorization. A run belongs to the
155
+ // tenant its runId carries; any other tenant gets 404 — not 403, so the
156
+ // route is not an existence oracle for other tenants' runIds.
157
+ if (workflowId &&
158
+ runId &&
159
+ segments.length >= 3 &&
160
+ !tenant.ownsRun(runId)) {
161
+ return json({ error: 'run not found' }, 404);
162
+ }
163
+ // Per-workflow RBAC, mirrored from the start route: a module that
164
+ // narrows who may START a workflow also narrows who may ADVANCE it —
165
+ // resume drives the same state machine. Hoisted above dispatch so a
166
+ // future mutating route cannot forget it; GETs stay coarse
167
+ // (reviewer/viewer inspect runs they may not drive). Placed after the
168
+ // 404s above so another tenant's probe learns nothing it could not read
169
+ // from its own /workflows catalog.
170
+ if (request.method !== 'GET' && workflowId) {
171
+ const allowedRoles = metaFor(workflowId)?.allowedRoles;
172
+ if (allowedRoles && !allowedRoles.includes(actor.role)) {
173
+ return json({ error: `role '${actor.role}' may not advance '${workflowId}'` }, 403);
174
+ }
175
+ }
176
+ if (request.method === 'GET' &&
177
+ segments.length === 3 &&
178
+ workflowId &&
179
+ runId) {
180
+ const summary = await options.status(workflowId, runId);
181
+ if (!summary)
182
+ return json({ error: 'run not found' }, 404);
183
+ if (summary.status === 'suspended' && options.reconcileApprovals) {
184
+ try {
185
+ await options.reconcileApprovals(tenant, workflowId, summary);
186
+ }
187
+ catch (error) {
188
+ console.error(JSON.stringify({
189
+ type: 'reconcile-error',
190
+ workflowId,
191
+ runId,
192
+ error: error instanceof Error ? error.message : String(error),
193
+ }));
194
+ }
195
+ }
196
+ return json(summary);
197
+ }
198
+ if (request.method === 'POST' &&
199
+ segments.length === 4 &&
200
+ action === 'resume' &&
201
+ workflowId &&
202
+ runId) {
203
+ return json(await options.resume(workflowId, runId, (await readJson(request)) ?? {}));
204
+ }
205
+ return json({ error: 'not found' }, 404);
206
+ }
207
+ catch (error) {
208
+ return errorResponse(error);
209
+ }
210
+ };
211
+ }
212
+ //# sourceMappingURL=run-router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-router.js","sourceRoot":"","sources":["../../src/host-kit/run-router.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAAS;AACT,EAAE;AACF,kDAAkD;AAClD,oFAAoF;AACpF,kFAAkF;AAClF,+EAA+E;AAC/E,kFAAkF;AAClF,gFAAgF;AAChF,iFAAiF;AACjF,EAAE;AACF,uEAAuE;AACvE,gFAAgF;AAChF,8BAA8B;AAC9B,EAAE;AACF,kFAAkF;AAClF,iFAAiF;AACjF,gFAAgF;AAChF,8EAA8E;AAE9E,OAAO,EAEL,eAAe,EAEf,qBAAqB,GAEtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EAEpB,eAAe,EACf,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,M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,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { TenantResolver } from '../approval-api/index.js';
2
+ export interface SubdomainCrossCheckOptions {
3
+ /**
4
+ * The apex under which tenant subdomains live, e.g. 'example.com'. Hosts
5
+ * NOT under it (workers.dev previews, localhost) skip the check.
6
+ */
7
+ apexDomain: string;
8
+ /** Subdomains that are shared infrastructure, never tenants. */
9
+ reserved?: readonly string[];
10
+ }
11
+ /**
12
+ * The tenant slug a hostname addresses: `<slug>.<apex>` => slug; the apex
13
+ * itself, hosts outside the apex, multi-level subdomains, and reserved slugs
14
+ * => undefined (not tenant-addressed).
15
+ */
16
+ export declare function subdomainTenantOf(hostname: string, options: SubdomainCrossCheckOptions): string | undefined;
17
+ /**
18
+ * Decorate a TenantResolver: when the request addresses a tenant subdomain,
19
+ * the resolved token tenant must BE that tenant — mismatch throws
20
+ * TenantResolutionError (the routers' 403). Non-tenant hosts pass through.
21
+ */
22
+ export declare function withSubdomainCrossCheck(resolve: TenantResolver, options: SubdomainCrossCheckOptions): TenantResolver;
23
+ //# sourceMappingURL=subdomain-check.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subdomain-check.d.ts","sourceRoot":"","sources":["../../src/host-kit/subdomain-check.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAI9E,MAAM,WAAW,0BAA0B;IACzC;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC9B;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,0BAA0B,GAClC,MAAM,GAAG,SAAS,CAkBpB;AAMD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,0BAA0B,GAClC,cAAc,CAehB"}
@@ -0,0 +1,60 @@
1
+ // Subdomain <-> tenant cross-check for client-per-subdomain commercial hosts
2
+ // (<tenant>.example.com). DEFENSE IN DEPTH ONLY: the subdomain identifies the
3
+ // tenant for ROUTING; authorization is the token's verified tenant claim and
4
+ // the bound stores (INV-2). What this closes is the confused-deputy UX bug —
5
+ // tenant A's user pasting their token into tenant B's subdomain and quietly
6
+ // operating on A's data while LOOKING at B's branded host.
7
+ //
8
+ // The Host header is client-controllable at the edge of the internet but not
9
+ // through Cloudflare's routing to this worker (requests reach the zone's
10
+ // worker only for hosts the zone serves) — still, this check treats it as a
11
+ // cross-check, never the authorization boundary.
12
+ import { TenantResolutionError } from '../approval-api/index.js';
13
+ import { RESERVED_FOR_ALLOCATION } from './tenant-registry.js';
14
+ /**
15
+ * The tenant slug a hostname addresses: `<slug>.<apex>` => slug; the apex
16
+ * itself, hosts outside the apex, multi-level subdomains, and reserved slugs
17
+ * => undefined (not tenant-addressed).
18
+ */
19
+ export function subdomainTenantOf(hostname, options) {
20
+ // DNS-equivalent normalization: 'bravo.example.com.' (the FQDN root-dot
21
+ // form browsers pass through Host and URL untouched) names the same host
22
+ // as 'bravo.example.com' — without stripping it, the dotted form would
23
+ // silently SKIP the cross-check this module exists to apply. The WHOLE
24
+ // trailing run goes, not one dot: multi-dot forms are not valid DNS, but
25
+ // stripping them errs toward APPLYING the check (fail closed), and a
26
+ // fat-fingered apex config ('example.com..') keeps matching instead of
27
+ // silently disabling the check for every host.
28
+ const apex = stripTrailingDots(options.apexDomain.toLowerCase());
29
+ const host = stripTrailingDots(hostname.toLowerCase());
30
+ if (host === apex || !host.endsWith(`.${apex}`))
31
+ return undefined;
32
+ const label = host.slice(0, -(apex.length + 1));
33
+ if (label.includes('.'))
34
+ return undefined; // deeper levels are not tenants
35
+ if ((options.reserved ?? RESERVED_FOR_ALLOCATION).includes(label)) {
36
+ return undefined;
37
+ }
38
+ return label;
39
+ }
40
+ function stripTrailingDots(name) {
41
+ return name.replace(/\.+$/, '');
42
+ }
43
+ /**
44
+ * Decorate a TenantResolver: when the request addresses a tenant subdomain,
45
+ * the resolved token tenant must BE that tenant — mismatch throws
46
+ * TenantResolutionError (the routers' 403). Non-tenant hosts pass through.
47
+ */
48
+ export function withSubdomainCrossCheck(resolve, options) {
49
+ return async (request) => {
50
+ const tenant = await resolve(request);
51
+ if (!tenant)
52
+ return undefined;
53
+ const hostTenant = subdomainTenantOf(new URL(request.url).hostname, options);
54
+ if (hostTenant !== undefined && hostTenant !== tenant.tenantId) {
55
+ throw new TenantResolutionError(`token tenant '${tenant.tenantId}' does not match this host's tenant subdomain — sign in on your own tenant's host`);
56
+ }
57
+ return tenant;
58
+ };
59
+ }
60
+ //# sourceMappingURL=subdomain-check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subdomain-check.js","sourceRoot":"","sources":["../../src/host-kit/subdomain-check.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,6EAA6E;AAC7E,6EAA6E;AAC7E,4EAA4E;AAC5E,2DAA2D;AAC3D,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,4EAA4E;AAC5E,iDAAiD;AAGjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAY/D;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,QAAgB,EAChB,OAAmC;IAEnC,wEAAwE;IACxE,yEAAyE;IACzE,uEAAuE;IACvE,uEAAuE;IACvE,yEAAyE;IACzE,qEAAqE;IACrE,uEAAuE;IACvE,+CAA+C;IAC/C,MAAM,IAAI,GAAG,iBAAiB,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;IACjE,MAAM,IAAI,GAAG,iBAAiB,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IACvD,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,EAAE,CAAC;QAAE,OAAO,SAAS,CAAC;IAClE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;IAChD,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC,CAAC,gCAAgC;IAC3E,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,uBAAuB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAClE,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAY;IACrC,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAClC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACrC,OAAuB,EACvB,OAAmC;IAEnC,OAAO,KAAK,EAAE,OAAgB,EAAsC,EAAE;QACpE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC;QAC9B,MAAM,UAAU,GAAG,iBAAiB,CAClC,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,QAAQ,EAC7B,OAAO,CACR,CAAC;QACF,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,MAAM,CAAC,QAAQ,EAAE,CAAC;YAC/D,MAAM,IAAI,qBAAqB,CAC7B,iBAAiB,MAAM,CAAC,QAAQ,mFAAmF,CACpH,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,51 @@
1
+ /** Structural D1 subset (tests back it with node:sqlite, Workers pass env.DB). */
2
+ export interface TenantRegistryDatabase {
3
+ prepare(query: string): TenantRegistryStatement;
4
+ }
5
+ export interface TenantRegistryStatement {
6
+ bind(...values: unknown[]): TenantRegistryStatement;
7
+ run(): Promise<unknown>;
8
+ }
9
+ /**
10
+ * The TCB's own audit identity ('system'). Defined in the path-safe-id leaf —
11
+ * approval-api's createTenantResolver enforces it too, and importing host-kit
12
+ * from there would invert the layering — and re-exported here so the public
13
+ * surface stays `./host-kit`. Full rationale at the definition.
14
+ */
15
+ export { RESERVED_TENANT_IDS } from '../do-runner/path-safe-id.js';
16
+ /**
17
+ * Slugs that can never be ALLOCATED to a client, for three distinct reasons:
18
+ * the TCB identity above; shared-infrastructure subdomains the commercial
19
+ * host's subdomain cross-check treats as non-tenant hosts (rejecting them AT
20
+ * PROVISIONING is the robust half of that check — a tenant literally named
21
+ * 'www' could otherwise satisfy `host-tenant === token-tenant` on a shared
22
+ * host); and 'default', the conventional single-tenant id (deploy/README.md),
23
+ * reserved so a community host running it can adopt this registry later
24
+ * without finding 'default' sold to a client. Of these only
25
+ * RESERVED_TENANT_IDS bites at authentication — a single-tenant host whose
26
+ * tenant is named 'api' or 'default' still authenticates. 'default' is
27
+ * deliberately a list entry, not an exported constant: a blessed
28
+ * DEFAULT_TENANT value would invite the `tenantId ?? DEFAULT_TENANT`
29
+ * fail-open this design exists to prevent.
30
+ */
31
+ export declare const RESERVED_FOR_ALLOCATION: readonly string[];
32
+ /** A provisioning attempt for a tenantId that already exists. */
33
+ export declare class TenantCollisionError extends Error {
34
+ constructor(tenantId: string);
35
+ }
36
+ export interface ProvisionTenantOptions {
37
+ tenantId: string;
38
+ /** 'commercial' for paying clients, 'demo' for ephemeral demo tenants. */
39
+ kind: 'commercial' | 'demo';
40
+ /** Clock override for tests. */
41
+ now?: () => number;
42
+ }
43
+ /**
44
+ * Allocate a tenantId, or throw. INV-3 is validated here too — a tenant that
45
+ * cannot be range-purged or prefix-matched must never exist in the first
46
+ * place. Insert-or-fail: a collision throws TenantCollisionError instead of
47
+ * silently adopting the existing row, because "provisioned twice" means two
48
+ * parties believe they own the slug.
49
+ */
50
+ export declare function provisionTenant(db: TenantRegistryDatabase, options: ProvisionTenantOptions): Promise<void>;
51
+ //# sourceMappingURL=tenant-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenant-registry.d.ts","sourceRoot":"","sources":["../../src/host-kit/tenant-registry.ts"],"names":[],"mappings":"AAcA,kFAAkF;AAClF,MAAM,WAAW,sBAAsB;IACrC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,uBAAuB,CAAC;CACjD;AAED,MAAM,WAAW,uBAAuB;IACtC,IAAI,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,uBAAuB,CAAC;IACpD,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CACzB;AAQD;;;;;GAKG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAEnE;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB,EAAE,SAAS,MAAM,EASpD,CAAC;AAEF,iEAAiE;AACjE,qBAAa,oBAAqB,SAAQ,KAAK;gBACjC,QAAQ,EAAE,MAAM;CAM7B;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,0EAA0E;IAC1E,IAAI,EAAE,YAAY,GAAG,MAAM,CAAC;IAC5B,gCAAgC;IAChC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AASD;;;;;;GAMG;AACH,wBAAsB,eAAe,CACnC,EAAE,EAAE,sBAAsB,EAC1B,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAyBf"}
@@ -0,0 +1,87 @@
1
+ // The tenantId allocation authority. Every isolation invariant treats
2
+ // tenantId as axiomatically unique — the salted runId prefix, the bound
3
+ // store's tenant_id predicate, the R2 key segment — and NOTHING else enforces
4
+ // that. An ops-side collision (two paying clients both slugged 'acme') would
5
+ // silently merge runs, approvals, rate limits, and artifacts, so provisioning
6
+ // must INSERT here — insert-or-fail on the PRIMARY KEY — BEFORE any token
7
+ // naming that tenantId is issued. The demo worker's ephemeral tenants go
8
+ // through the same gate (its demo_tenants registry references this table).
9
+ import { RESERVED_TENANT_IDS, TENANT_ID_PATTERN, } from '../do-runner/path-safe-id.js';
10
+ const CREATE_TENANTS_TABLE = `CREATE TABLE IF NOT EXISTS tenants (
11
+ tenant_id TEXT PRIMARY KEY,
12
+ kind TEXT NOT NULL,
13
+ created_at TEXT NOT NULL
14
+ )`;
15
+ /**
16
+ * The TCB's own audit identity ('system'). Defined in the path-safe-id leaf —
17
+ * approval-api's createTenantResolver enforces it too, and importing host-kit
18
+ * from there would invert the layering — and re-exported here so the public
19
+ * surface stays `./host-kit`. Full rationale at the definition.
20
+ */
21
+ export { RESERVED_TENANT_IDS } from '../do-runner/path-safe-id.js';
22
+ /**
23
+ * Slugs that can never be ALLOCATED to a client, for three distinct reasons:
24
+ * the TCB identity above; shared-infrastructure subdomains the commercial
25
+ * host's subdomain cross-check treats as non-tenant hosts (rejecting them AT
26
+ * PROVISIONING is the robust half of that check — a tenant literally named
27
+ * 'www' could otherwise satisfy `host-tenant === token-tenant` on a shared
28
+ * host); and 'default', the conventional single-tenant id (deploy/README.md),
29
+ * reserved so a community host running it can adopt this registry later
30
+ * without finding 'default' sold to a client. Of these only
31
+ * RESERVED_TENANT_IDS bites at authentication — a single-tenant host whose
32
+ * tenant is named 'api' or 'default' still authenticates. 'default' is
33
+ * deliberately a list entry, not an exported constant: a blessed
34
+ * DEFAULT_TENANT value would invite the `tenantId ?? DEFAULT_TENANT`
35
+ * fail-open this design exists to prevent.
36
+ */
37
+ export const RESERVED_FOR_ALLOCATION = [
38
+ ...RESERVED_TENANT_IDS,
39
+ 'app',
40
+ 'www',
41
+ 'api',
42
+ 'docs',
43
+ 'admin',
44
+ 'status',
45
+ 'default',
46
+ ];
47
+ /** A provisioning attempt for a tenantId that already exists. */
48
+ export class TenantCollisionError extends Error {
49
+ constructor(tenantId) {
50
+ super(`tenant '${tenantId}' is already provisioned — tenant ids are never reused; pick a different slug`);
51
+ this.name = 'TenantCollisionError';
52
+ }
53
+ }
54
+ function isUniqueViolation(error) {
55
+ return (error instanceof Error &&
56
+ /UNIQUE constraint failed|PRIMARY KEY constraint/i.test(error.message));
57
+ }
58
+ /**
59
+ * Allocate a tenantId, or throw. INV-3 is validated here too — a tenant that
60
+ * cannot be range-purged or prefix-matched must never exist in the first
61
+ * place. Insert-or-fail: a collision throws TenantCollisionError instead of
62
+ * silently adopting the existing row, because "provisioned twice" means two
63
+ * parties believe they own the slug.
64
+ */
65
+ export async function provisionTenant(db, options) {
66
+ const { tenantId, kind } = options;
67
+ if (!TENANT_ID_PATTERN.test(tenantId)) {
68
+ throw new Error(`tenantId '${tenantId}' violates INV-3 (^[a-z0-9]{3,32}$) — not provisioned`);
69
+ }
70
+ if (RESERVED_FOR_ALLOCATION.includes(tenantId)) {
71
+ throw new Error(`tenantId '${tenantId}' is a reserved slug — not provisioned`);
72
+ }
73
+ await db.prepare(CREATE_TENANTS_TABLE).run();
74
+ const createdAt = new Date((options.now ?? Date.now)()).toISOString();
75
+ try {
76
+ await db
77
+ .prepare('INSERT INTO tenants (tenant_id, kind, created_at) VALUES (?, ?, ?)')
78
+ .bind(tenantId, kind, createdAt)
79
+ .run();
80
+ }
81
+ catch (error) {
82
+ if (isUniqueViolation(error))
83
+ throw new TenantCollisionError(tenantId);
84
+ throw error;
85
+ }
86
+ }
87
+ //# sourceMappingURL=tenant-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenant-registry.js","sourceRoot":"","sources":["../../src/host-kit/tenant-registry.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,wEAAwE;AACxE,8EAA8E;AAC9E,6EAA6E;AAC7E,8EAA8E;AAC9E,0EAA0E;AAC1E,yEAAyE;AACzE,2EAA2E;AAE3E,OAAO,EACL,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,8BAA8B,CAAC;AAYtC,MAAM,oBA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AAE,CAAC;IACtE,IAAI,CAAC;QACH,MAAM,EAAE;aACL,OAAO,CACN,oEAAoE,CACrE;aACA,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,SAAS,CAAC;aAC/B,GAAG,EAAE,CAAC;IACX,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,iBAAiB,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,oBAAoB,CAAC,QAAQ,CAAC,CAAC;QACvE,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -0,0 +1,63 @@
1
+ import { type ApprovalActor } from '../approval-api/index.js';
2
+ export interface TokenVerifier {
3
+ verify(token: string): Promise<ApprovalActor | undefined>;
4
+ }
5
+ /**
6
+ * Validate an untyped candidate into an ApprovalActor — the ONE place a
7
+ * decoded token/map entry becomes an identity. No `as`-casting at the JSON
8
+ * boundary: id non-empty, role recognized, tenantId INV-3-valid and not a
9
+ * reserved identity.
10
+ */
11
+ export declare function toApprovalActor(candidate: unknown): ApprovalActor | undefined;
12
+ /** The parsed bearer map as a TokenVerifier (entries are pre-validated). */
13
+ export declare function staticTokenVerifier(actors: ReadonlyMap<string, ApprovalActor>): TokenVerifier;
14
+ export interface HmacVerifierOptions {
15
+ /**
16
+ * kid -> HMAC secret. A plain Map lookup by design: a kid must never be
17
+ * interpreted as a path or URL (kid-injection). With exactly one key, a
18
+ * token without a kid falls back to it; with several, kid is required.
19
+ */
20
+ keys: ReadonlyMap<string, string>;
21
+ issuer: string;
22
+ audience: string;
23
+ /** Epoch-ms clock, injectable for tests. Default Date.now. */
24
+ now?: () => number;
25
+ }
26
+ export declare function base64UrlEncode(bytes: Uint8Array): string;
27
+ /**
28
+ * HMAC-SHA256 a payload with `secret`, base64url-encoded. The canonical
29
+ * signer — the demo's OAuth state signing reuses it rather than re-rolling
30
+ * importKey + subtle.sign (two HMAC paths drift; the base64url pair already
31
+ * did).
32
+ */
33
+ export declare function hmacSign(secret: string, payload: string): Promise<string>;
34
+ /**
35
+ * HS256 JWT verifier over Worker-secret keys.
36
+ *
37
+ * The algorithm is PINNED: only `alg: "HS256"` verifies — `none` and every
38
+ * negotiated value are rejected before any cryptography runs, so a token
39
+ * cannot choose its own verification scheme. Signature comparison goes
40
+ * through crypto.subtle.verify (constant-time), never a hand-rolled string
41
+ * compare. Claims checked: exp (required), nbf (when present), iss, aud
42
+ * (string or array), then sub/role/tenantId through toApprovalActor.
43
+ */
44
+ export declare function hmacVerifier(options: HmacVerifierOptions): TokenVerifier;
45
+ export interface MintHmacTokenOptions {
46
+ /** The signing secret; `kid` names it for the verifier's key map. */
47
+ secret: string;
48
+ kid: string;
49
+ issuer: string;
50
+ audience: string;
51
+ actor: ApprovalActor;
52
+ /** Token lifetime in seconds (exp = now + ttl). */
53
+ ttlSeconds: number;
54
+ /** Epoch-ms clock, injectable for tests. Default Date.now. */
55
+ now?: () => number;
56
+ }
57
+ /**
58
+ * Mint an HS256 JWT hmacVerifier accepts — the demo worker's token factory
59
+ * and the test suite's fixture builder. Server-side only: the secret must
60
+ * never reach a client.
61
+ */
62
+ export declare function mintHmacToken(options: MintHmacTokenOptions): Promise<string>;
63
+ //# sourceMappingURL=verifier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifier.d.ts","sourceRoot":"","sources":["../../src/host-kit/verifier.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAM9E,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;CAC3D;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,OAAO,GAAG,aAAa,GAAG,SAAS,CAyB7E;AAED,4EAA4E;AAC5E,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,GACzC,aAAa,CAMf;AAED,MAAM,WAAW,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