@catamorphic/fastify-plugin 0.0.0-stage → 0.1.0-alpha.31

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 (160) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/README.md +143 -2
  4. package/dist/app-presentation-tools.d.ts +4 -0
  5. package/dist/app-presentation-tools.d.ts.map +1 -0
  6. package/dist/app.d.ts +27 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/chunk-baagvvm3.js +164 -0
  9. package/dist/chunk-baagvvm3.js.map +10 -0
  10. package/dist/http-identity.d.ts +52 -0
  11. package/dist/http-identity.d.ts.map +1 -0
  12. package/dist/hung-up.d.ts +7 -0
  13. package/dist/hung-up.d.ts.map +1 -0
  14. package/dist/index.d.ts +11 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +10884 -0
  17. package/dist/index.js.map +56 -0
  18. package/dist/mcp-shared.d.ts +117 -0
  19. package/dist/mcp-shared.d.ts.map +1 -0
  20. package/dist/mcp.d.ts +6 -0
  21. package/dist/mcp.d.ts.map +1 -0
  22. package/dist/mcp.js +13 -0
  23. package/dist/mcp.js.map +9 -0
  24. package/dist/plugin.d.ts +113 -0
  25. package/dist/plugin.d.ts.map +1 -0
  26. package/dist/project-capabilities.d.ts +25 -0
  27. package/dist/project-capabilities.d.ts.map +1 -0
  28. package/dist/project-mcp-program.d.ts +15 -0
  29. package/dist/project-mcp-program.d.ts.map +1 -0
  30. package/dist/project-mcp-surface.d.ts +16 -0
  31. package/dist/project-mcp-surface.d.ts.map +1 -0
  32. package/dist/request-logging.d.ts +18 -0
  33. package/dist/request-logging.d.ts.map +1 -0
  34. package/dist/routes/agent-capabilities.d.ts +4 -0
  35. package/dist/routes/agent-capabilities.d.ts.map +1 -0
  36. package/dist/routes/agent.d.ts +4 -0
  37. package/dist/routes/agent.d.ts.map +1 -0
  38. package/dist/routes/apps-mcp.d.ts +4 -0
  39. package/dist/routes/apps-mcp.d.ts.map +1 -0
  40. package/dist/routes/apps.d.ts +12 -0
  41. package/dist/routes/apps.d.ts.map +1 -0
  42. package/dist/routes/client-runners.d.ts +11 -0
  43. package/dist/routes/client-runners.d.ts.map +1 -0
  44. package/dist/routes/code-hosts.d.ts +11 -0
  45. package/dist/routes/code-hosts.d.ts.map +1 -0
  46. package/dist/routes/connection-mcp.d.ts +10 -0
  47. package/dist/routes/connection-mcp.d.ts.map +1 -0
  48. package/dist/routes/connections.d.ts +4 -0
  49. package/dist/routes/connections.d.ts.map +1 -0
  50. package/dist/routes/documents.d.ts +11 -0
  51. package/dist/routes/documents.d.ts.map +1 -0
  52. package/dist/routes/environments.d.ts +4 -0
  53. package/dist/routes/environments.d.ts.map +1 -0
  54. package/dist/routes/git-gateway.d.ts +21 -0
  55. package/dist/routes/git-gateway.d.ts.map +1 -0
  56. package/dist/routes/http-gateway.d.ts +13 -0
  57. package/dist/routes/http-gateway.d.ts.map +1 -0
  58. package/dist/routes/me.d.ts +12 -0
  59. package/dist/routes/me.d.ts.map +1 -0
  60. package/dist/routes/memberships.d.ts +12 -0
  61. package/dist/routes/memberships.d.ts.map +1 -0
  62. package/dist/routes/model-gateway.d.ts +12 -0
  63. package/dist/routes/model-gateway.d.ts.map +1 -0
  64. package/dist/routes/notifications.d.ts +4 -0
  65. package/dist/routes/notifications.d.ts.map +1 -0
  66. package/dist/routes/parse.d.ts +5 -0
  67. package/dist/routes/parse.d.ts.map +1 -0
  68. package/dist/routes/personal-environment.d.ts +13 -0
  69. package/dist/routes/personal-environment.d.ts.map +1 -0
  70. package/dist/routes/plugins.d.ts +4 -0
  71. package/dist/routes/plugins.d.ts.map +1 -0
  72. package/dist/routes/project-mcp.d.ts +25 -0
  73. package/dist/routes/project-mcp.d.ts.map +1 -0
  74. package/dist/routes/projects.d.ts +4 -0
  75. package/dist/routes/projects.d.ts.map +1 -0
  76. package/dist/routes/publications.d.ts +15 -0
  77. package/dist/routes/publications.d.ts.map +1 -0
  78. package/dist/routes/run-errors.d.ts +8 -0
  79. package/dist/routes/run-errors.d.ts.map +1 -0
  80. package/dist/routes/runs.d.ts +4 -0
  81. package/dist/routes/runs.d.ts.map +1 -0
  82. package/dist/routes/session-artifacts.d.ts +27 -0
  83. package/dist/routes/session-artifacts.d.ts.map +1 -0
  84. package/dist/routes/session-mailboxes.d.ts +4 -0
  85. package/dist/routes/session-mailboxes.d.ts.map +1 -0
  86. package/dist/routes/session-previews.d.ts +40 -0
  87. package/dist/routes/session-previews.d.ts.map +1 -0
  88. package/dist/routes/session-terminals.d.ts +15 -0
  89. package/dist/routes/session-terminals.d.ts.map +1 -0
  90. package/dist/routes/triggers.d.ts +20 -0
  91. package/dist/routes/triggers.d.ts.map +1 -0
  92. package/dist/routes/watchers.d.ts +4 -0
  93. package/dist/routes/watchers.d.ts.map +1 -0
  94. package/dist/routes/webhooks.d.ts +11 -0
  95. package/dist/routes/webhooks.d.ts.map +1 -0
  96. package/dist/routes/workflow-enablements.d.ts +4 -0
  97. package/dist/routes/workflow-enablements.d.ts.map +1 -0
  98. package/dist/routes/workflows.d.ts +4 -0
  99. package/dist/routes/workflows.d.ts.map +1 -0
  100. package/dist/schemas.d.ts +17776 -0
  101. package/dist/schemas.d.ts.map +1 -0
  102. package/dist/session-artifact-tools.d.ts +5 -0
  103. package/dist/session-artifact-tools.d.ts.map +1 -0
  104. package/dist/session-event-stream.d.ts +45 -0
  105. package/dist/session-event-stream.d.ts.map +1 -0
  106. package/dist/spa.d.ts +24 -0
  107. package/dist/spa.d.ts.map +1 -0
  108. package/dist/telemetry.d.ts +4 -0
  109. package/dist/telemetry.d.ts.map +1 -0
  110. package/package.json +73 -4
  111. package/src/app-presentation-tools.ts +46 -0
  112. package/src/app.ts +115 -0
  113. package/src/http-identity.ts +145 -0
  114. package/src/hung-up.ts +13 -0
  115. package/src/index.ts +25 -0
  116. package/src/mcp-shared.ts +331 -0
  117. package/src/mcp.ts +10 -0
  118. package/src/plugin.ts +332 -0
  119. package/src/project-capabilities.ts +153 -0
  120. package/src/project-mcp-program.ts +607 -0
  121. package/src/project-mcp-surface.ts +881 -0
  122. package/src/request-logging.ts +47 -0
  123. package/src/routes/agent-capabilities.ts +109 -0
  124. package/src/routes/agent.ts +1566 -0
  125. package/src/routes/apps-mcp.ts +303 -0
  126. package/src/routes/apps.ts +692 -0
  127. package/src/routes/client-runners.ts +251 -0
  128. package/src/routes/code-hosts.ts +247 -0
  129. package/src/routes/connection-mcp.ts +135 -0
  130. package/src/routes/connections.ts +494 -0
  131. package/src/routes/documents.ts +538 -0
  132. package/src/routes/environments.ts +72 -0
  133. package/src/routes/git-gateway.ts +106 -0
  134. package/src/routes/http-gateway.ts +141 -0
  135. package/src/routes/me.ts +122 -0
  136. package/src/routes/memberships.ts +173 -0
  137. package/src/routes/model-gateway.ts +134 -0
  138. package/src/routes/notifications.ts +101 -0
  139. package/src/routes/parse.ts +32 -0
  140. package/src/routes/personal-environment.ts +146 -0
  141. package/src/routes/plugins.ts +341 -0
  142. package/src/routes/project-mcp.ts +394 -0
  143. package/src/routes/projects.ts +708 -0
  144. package/src/routes/publications.ts +222 -0
  145. package/src/routes/run-errors.ts +86 -0
  146. package/src/routes/runs.ts +253 -0
  147. package/src/routes/session-artifacts.ts +293 -0
  148. package/src/routes/session-mailboxes.ts +80 -0
  149. package/src/routes/session-previews.ts +224 -0
  150. package/src/routes/session-terminals.ts +209 -0
  151. package/src/routes/triggers.ts +241 -0
  152. package/src/routes/watchers.ts +94 -0
  153. package/src/routes/webhooks.ts +171 -0
  154. package/src/routes/workflow-enablements.ts +331 -0
  155. package/src/routes/workflows.ts +323 -0
  156. package/src/schemas.ts +2735 -0
  157. package/src/session-artifact-tools.ts +170 -0
  158. package/src/session-event-stream.ts +122 -0
  159. package/src/spa.ts +135 -0
  160. package/src/telemetry.ts +93 -0
@@ -0,0 +1,692 @@
1
+ import {
2
+ APP_ICON_NAMES,
3
+ type AppHostTheme,
4
+ appGuestCsp,
5
+ buildAppGuestDocument,
6
+ } from "@catamorphic/app";
7
+ import {
8
+ AppBuildFailedError,
9
+ AppBundleTooLargeError,
10
+ AppNotFoundError,
11
+ AppPublishStateError,
12
+ AppStorageSnapshotTooLargeError,
13
+ AppVersionNotFoundError,
14
+ type Identity,
15
+ narrowIdentity,
16
+ RunNotFoundError,
17
+ } from "@catamorphic/core";
18
+ import type { FastifyInstance, FastifyRequest } from "fastify";
19
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
20
+ import { z } from "zod";
21
+ import type { RouteContext } from "../app.js";
22
+ import { resolveIdentity } from "../http-identity.js";
23
+ import {
24
+ AppPresentationSchema,
25
+ AppSummarySchema,
26
+ AppVersionSchema,
27
+ AppViewStateSchema,
28
+ BuildAppSchema,
29
+ CallRunSchema,
30
+ ErrorSchema,
31
+ ProjectAppParamsSchema,
32
+ ProjectAppVersionParamsSchema,
33
+ ProjectIdParamsSchema,
34
+ RunCallOutcomeSchema,
35
+ RunDetailSchema,
36
+ RunSchema,
37
+ TriggerRunSchema,
38
+ } from "../schemas.js";
39
+ import { replyForTriggerError } from "./run-errors.js";
40
+
41
+ const AppChannelSchema = z.enum(["published", "dev"]);
42
+
43
+ /**
44
+ * Every viewer-facing app route narrows whoever arrives to this one app
45
+ * (ADR 0053, 0158): an admin's identity is confined to the app while inside
46
+ * it (the untrusted bundle never inherits project access or permissions) and a viewer's
47
+ * scoped identity must cover the app or ends up with an empty scope. The
48
+ * narrowing is structural (it is the route, not a header the client sends),
49
+ * so there is no claim to validate and nothing to forge.
50
+ */
51
+ export function registerAppRoutes(app: FastifyInstance, ctx: RouteContext) {
52
+ async function appIdentity(
53
+ request: FastifyRequest,
54
+ params: { projectId: string; appName: string },
55
+ channel?: "published" | "dev",
56
+ versionId?: string,
57
+ ): Promise<Identity> {
58
+ const identity = resolveIdentity(request);
59
+ return ctx.core?.apps
60
+ ? ctx.core.apps.identityForApp({
61
+ identity,
62
+ ...params,
63
+ channel,
64
+ versionId,
65
+ })
66
+ : narrowIdentity(identity, {
67
+ kind: "app",
68
+ projectId: params.projectId,
69
+ name: params.appName,
70
+ channel,
71
+ versionId,
72
+ });
73
+ }
74
+
75
+ const typed = app.withTypeProvider<ZodTypeProvider>();
76
+
77
+ typed.route({
78
+ method: "GET",
79
+ url: "/projects/:projectId/apps/:appName/presentation",
80
+ schema: {
81
+ params: ProjectAppParamsSchema,
82
+ response: {
83
+ 200: AppPresentationSchema,
84
+ 404: ErrorSchema,
85
+ 503: ErrorSchema,
86
+ },
87
+ },
88
+ handler: async (request, reply) => {
89
+ if (!ctx.core?.apps)
90
+ return reply.status(503).send({ error: "Apps not configured" });
91
+ try {
92
+ return await ctx.core.apps.presentation({
93
+ ...request.params,
94
+ identity: resolveIdentity(request),
95
+ });
96
+ } catch (error) {
97
+ if (error instanceof AppNotFoundError)
98
+ return reply.status(404).send({ error: error.message });
99
+ throw error;
100
+ }
101
+ },
102
+ });
103
+ typed.route({
104
+ method: "PATCH",
105
+ url: "/projects/:projectId/apps/:appName/presentation",
106
+ schema: {
107
+ params: ProjectAppParamsSchema,
108
+ body: z
109
+ .object({
110
+ icon: z.enum(APP_ICON_NAMES).optional(),
111
+ title: z.string().trim().min(1).max(200).optional(),
112
+ })
113
+ .refine(
114
+ (value) => value.icon !== undefined || value.title !== undefined,
115
+ "Supply a title or icon",
116
+ ),
117
+ response: {
118
+ 200: AppPresentationSchema,
119
+ 404: ErrorSchema,
120
+ 503: ErrorSchema,
121
+ },
122
+ },
123
+ handler: async (request, reply) => {
124
+ if (!ctx.core?.apps)
125
+ return reply.status(503).send({ error: "Apps not configured" });
126
+ try {
127
+ return await ctx.core.apps.updatePresentation({
128
+ ...request.params,
129
+ ...request.body,
130
+ identity: resolveIdentity(request),
131
+ });
132
+ } catch (error) {
133
+ if (error instanceof AppNotFoundError)
134
+ return reply.status(404).send({ error: error.message });
135
+ throw error;
136
+ }
137
+ },
138
+ });
139
+
140
+ typed.route({
141
+ method: "GET",
142
+ url: "/projects/:projectId/apps",
143
+ schema: {
144
+ params: ProjectIdParamsSchema,
145
+ response: { 200: z.array(AppSummarySchema), 503: ErrorSchema },
146
+ },
147
+ handler: async (request, reply) => {
148
+ if (!ctx.core?.apps)
149
+ return reply.status(503).send({ error: "Apps not configured" });
150
+ const list = await ctx.core.apps.list({
151
+ identity: resolveIdentity(request),
152
+ projectId: request.params.projectId,
153
+ });
154
+ return reply.send(list);
155
+ },
156
+ });
157
+
158
+ typed.route({
159
+ method: "GET",
160
+ url: "/projects/:projectId/apps/:appName/versions",
161
+ schema: {
162
+ params: ProjectAppParamsSchema,
163
+ response: { 200: z.array(AppVersionSchema), 503: ErrorSchema },
164
+ },
165
+ handler: async (request, reply) => {
166
+ if (!ctx.core?.apps)
167
+ return reply.status(503).send({ error: "Apps not configured" });
168
+ const versions = await ctx.core.apps.listVersions({
169
+ identity: resolveIdentity(request),
170
+ projectId: request.params.projectId,
171
+ appName: request.params.appName,
172
+ });
173
+ return reply.send(versions);
174
+ },
175
+ });
176
+
177
+ typed.route({
178
+ method: "POST",
179
+ url: "/projects/:projectId/apps/:appName/builds",
180
+ schema: {
181
+ params: ProjectAppParamsSchema,
182
+ body: BuildAppSchema,
183
+ response: {
184
+ 201: AppVersionSchema,
185
+ 400: ErrorSchema,
186
+ 404: ErrorSchema,
187
+ 503: ErrorSchema,
188
+ },
189
+ },
190
+ handler: async (request, reply) => {
191
+ if (!ctx.core?.apps)
192
+ return reply.status(503).send({ error: "Apps not configured" });
193
+ try {
194
+ const version = await ctx.core.apps.build({
195
+ identity: resolveIdentity(request),
196
+ projectId: request.params.projectId,
197
+ appName: request.params.appName,
198
+ kind: request.body.kind,
199
+ commitSha: request.body.commitSha,
200
+ });
201
+ return reply.status(201).send(version);
202
+ } catch (err) {
203
+ if (err instanceof AppNotFoundError)
204
+ return reply.status(404).send({ error: err.message });
205
+ if (
206
+ err instanceof AppPublishStateError ||
207
+ err instanceof AppBuildFailedError ||
208
+ err instanceof AppBundleTooLargeError
209
+ )
210
+ return reply.status(400).send({ error: err.message });
211
+ throw err;
212
+ }
213
+ },
214
+ });
215
+
216
+ typed.route({
217
+ method: "POST",
218
+ url: "/projects/:projectId/app-versions/:versionId/publish",
219
+ schema: {
220
+ params: ProjectAppVersionParamsSchema,
221
+ response: {
222
+ 200: AppVersionSchema,
223
+ 400: ErrorSchema,
224
+ 404: ErrorSchema,
225
+ 503: ErrorSchema,
226
+ },
227
+ },
228
+ handler: async (request, reply) => {
229
+ if (!ctx.core?.apps)
230
+ return reply.status(503).send({ error: "Apps not configured" });
231
+ try {
232
+ const version = await ctx.core.apps.publish({
233
+ identity: resolveIdentity(request),
234
+ projectId: request.params.projectId,
235
+ versionId: request.params.versionId,
236
+ });
237
+ return reply.send(version);
238
+ } catch (err) {
239
+ if (err instanceof AppVersionNotFoundError)
240
+ return reply.status(404).send({ error: err.message });
241
+ if (err instanceof AppPublishStateError)
242
+ return reply.status(400).send({ error: err.message });
243
+ throw err;
244
+ }
245
+ },
246
+ });
247
+
248
+ typed.route({
249
+ method: "GET",
250
+ url: "/projects/:projectId/apps/:appName/view-state",
251
+ schema: {
252
+ params: ProjectAppParamsSchema,
253
+ querystring: z.object({
254
+ channel: AppChannelSchema.optional(),
255
+ versionId: z.string().uuid().optional(),
256
+ }),
257
+ response: { 200: AppViewStateSchema, 503: ErrorSchema },
258
+ },
259
+ handler: async (request, reply) => {
260
+ if (!ctx.core?.apps)
261
+ return reply.status(503).send({ error: "Apps not configured" });
262
+ const state = await ctx.core.apps.viewState({
263
+ identity: await appIdentity(
264
+ request,
265
+ request.params,
266
+ request.query.channel,
267
+ request.query.versionId,
268
+ ),
269
+ projectId: request.params.projectId,
270
+ appName: request.params.appName,
271
+ channel: request.query.channel,
272
+ versionId: request.query.versionId,
273
+ metadataOnly: true,
274
+ });
275
+ if (state.state !== "ready") return reply.send(state);
276
+ // The guest URL is origin-absolute (derived from this request) because
277
+ // the mount's iframe navigates to it directly — a relative path would
278
+ // resolve against the host shell's origin, not the API's.
279
+ const guestUrl = new URL(
280
+ (request.url.split("?")[0] ?? request.url).replace(
281
+ /\/view-state$/,
282
+ "/guest",
283
+ ),
284
+ `${request.protocol}://${request.host}`,
285
+ );
286
+ if (request.query.channel) {
287
+ guestUrl.searchParams.set("channel", request.query.channel);
288
+ }
289
+ guestUrl.searchParams.set("versionId", state.versionId);
290
+ return reply.send({
291
+ state: "ready",
292
+ appId: state.appId,
293
+ versionId: state.versionId,
294
+ guestUrl: guestUrl.toString(),
295
+ });
296
+ },
297
+ });
298
+
299
+ typed.route({
300
+ method: "PUT",
301
+ url: "/projects/:projectId/apps/:appName/storage",
302
+ schema: {
303
+ params: ProjectAppParamsSchema,
304
+ body: z.object({
305
+ /** Full localStorage snapshot from the guest's persistent shim. */
306
+ data: z.record(z.string().max(4096), z.string()),
307
+ }),
308
+ response: {
309
+ 204: z.null(),
310
+ 404: ErrorSchema,
311
+ 413: ErrorSchema,
312
+ 503: ErrorSchema,
313
+ },
314
+ },
315
+ handler: async (request, reply) => {
316
+ if (!ctx.core?.apps)
317
+ return reply.status(503).send({ error: "Apps not configured" });
318
+ try {
319
+ await ctx.core.appStorage.put(
320
+ await appIdentity(request, request.params),
321
+ request.params.projectId,
322
+ request.params.appName,
323
+ request.body.data,
324
+ );
325
+ } catch (err) {
326
+ if (err instanceof AppNotFoundError)
327
+ return reply.status(404).send({ error: err.message });
328
+ if (err instanceof AppStorageSnapshotTooLargeError)
329
+ return reply.status(413).send({ error: err.message });
330
+ throw err;
331
+ }
332
+ return reply.status(204).send(null);
333
+ },
334
+ });
335
+
336
+ // --- App-originated execution (ADR 0053) ---
337
+ // The mount forwards a guest's workflow calls here rather than to the
338
+ // project's run routes. The URL names the app, so the identity is narrowed
339
+ // structurally and the server re-authorizes every call against the app's
340
+ // active version's frozen workflow set.
341
+
342
+ typed.route({
343
+ method: "POST",
344
+ url: "/projects/:projectId/apps/:appName/calls/:workflowName",
345
+ schema: {
346
+ params: ProjectAppParamsSchema.extend({ workflowName: z.string() }),
347
+ querystring: z.object({
348
+ channel: AppChannelSchema.optional(),
349
+ versionId: z.string().uuid().optional(),
350
+ }),
351
+ body: CallRunSchema,
352
+ response: {
353
+ 200: RunCallOutcomeSchema,
354
+ 400: ErrorSchema,
355
+ 403: ErrorSchema,
356
+ 404: ErrorSchema,
357
+ 409: ErrorSchema,
358
+ 429: ErrorSchema,
359
+ 503: ErrorSchema,
360
+ },
361
+ },
362
+ handler: async (request, reply) => {
363
+ if (!ctx.core?.apps)
364
+ return reply.status(503).send({ error: "Apps not configured" });
365
+ try {
366
+ const outcome = await ctx.core.runs.call({
367
+ identity: await appIdentity(
368
+ request,
369
+ request.params,
370
+ request.query.channel,
371
+ request.query.versionId,
372
+ ),
373
+ projectId: request.params.projectId,
374
+ workflowName: request.params.workflowName,
375
+ input: request.body.input,
376
+ ...(request.body.correlationKey === undefined
377
+ ? {}
378
+ : { correlationKey: request.body.correlationKey }),
379
+ ...(request.body.onConflict === undefined
380
+ ? {}
381
+ : { onConflict: request.body.onConflict }),
382
+ ...(request.body.budgetMs === undefined
383
+ ? {}
384
+ : { budgetMs: request.body.budgetMs }),
385
+ });
386
+ return reply.send(outcome);
387
+ } catch (err) {
388
+ return replyForTriggerError(err, reply) ?? Promise.reject(err);
389
+ }
390
+ },
391
+ });
392
+
393
+ typed.route({
394
+ method: "POST",
395
+ url: "/projects/:projectId/apps/:appName/runs/:workflowName",
396
+ schema: {
397
+ params: ProjectAppParamsSchema.extend({ workflowName: z.string() }),
398
+ querystring: z.object({
399
+ channel: AppChannelSchema.optional(),
400
+ versionId: z.string().uuid().optional(),
401
+ }),
402
+ body: TriggerRunSchema,
403
+ response: {
404
+ 201: RunSchema,
405
+ 400: ErrorSchema,
406
+ 403: ErrorSchema,
407
+ 404: ErrorSchema,
408
+ 409: ErrorSchema,
409
+ 429: ErrorSchema,
410
+ 503: ErrorSchema,
411
+ },
412
+ },
413
+ handler: async (request, reply) => {
414
+ if (!ctx.core?.apps)
415
+ return reply.status(503).send({ error: "Apps not configured" });
416
+ try {
417
+ const run = await ctx.core.runs.triggerProduction({
418
+ identity: await appIdentity(
419
+ request,
420
+ request.params,
421
+ request.query.channel,
422
+ request.query.versionId,
423
+ ),
424
+ projectId: request.params.projectId,
425
+ workflowName: request.params.workflowName,
426
+ input: request.body.input,
427
+ ...(request.body.correlationKey === undefined
428
+ ? {}
429
+ : { correlationKey: request.body.correlationKey }),
430
+ ...(request.body.onConflict === undefined
431
+ ? {}
432
+ : { onConflict: request.body.onConflict }),
433
+ });
434
+ return reply.status(201).send(run);
435
+ } catch (err) {
436
+ return replyForTriggerError(err, reply) ?? Promise.reject(err);
437
+ }
438
+ },
439
+ });
440
+
441
+ typed.route({
442
+ method: "GET",
443
+ url: "/projects/:projectId/apps/:appName/runs/:runId",
444
+ schema: {
445
+ params: ProjectAppParamsSchema.extend({ runId: z.string().uuid() }),
446
+ querystring: z.object({
447
+ channel: AppChannelSchema.optional(),
448
+ versionId: z.string().uuid().optional(),
449
+ }),
450
+ response: {
451
+ 200: RunDetailSchema,
452
+ 403: ErrorSchema,
453
+ 404: ErrorSchema,
454
+ 503: ErrorSchema,
455
+ },
456
+ },
457
+ handler: async (request, reply) => {
458
+ if (!ctx.core?.apps)
459
+ return reply.status(503).send({ error: "Apps not configured" });
460
+ try {
461
+ return reply.send(
462
+ await ctx.core.runs.get({
463
+ identity: await appIdentity(
464
+ request,
465
+ request.params,
466
+ request.query.channel,
467
+ request.query.versionId,
468
+ ),
469
+ runId: request.params.runId,
470
+ }),
471
+ );
472
+ } catch (err) {
473
+ if (err instanceof RunNotFoundError) {
474
+ return reply.status(404).send({ error: err.message });
475
+ }
476
+ throw err;
477
+ }
478
+ },
479
+ });
480
+
481
+ typed.route({
482
+ method: "GET",
483
+ url: "/projects/:projectId/apps/:appName/guest",
484
+ schema: {
485
+ params: ProjectAppParamsSchema,
486
+ querystring: z.object({
487
+ channel: AppChannelSchema.optional(),
488
+ versionId: z.string().uuid().optional(),
489
+ // JSON-encoded AppHostTheme; validated by parseGuestTheme (a zod
490
+ // transform here would not survive OpenAPI spec generation).
491
+ theme: z.string().max(8192).optional(),
492
+ }),
493
+ },
494
+ handler: async (request, reply) => {
495
+ if (!ctx.core?.apps)
496
+ return reply.status(503).send({ error: "Apps not configured" });
497
+ const identity = await appIdentity(
498
+ request,
499
+ request.params,
500
+ request.query.channel,
501
+ request.query.versionId,
502
+ );
503
+ const state = await ctx.core.apps.viewState({
504
+ identity,
505
+ projectId: request.params.projectId,
506
+ appName: request.params.appName,
507
+ channel: request.query.channel,
508
+ versionId: request.query.versionId,
509
+ });
510
+ if (state.state !== "ready") {
511
+ return reply.status(404).send({ error: `App is ${state.state}` });
512
+ }
513
+ // The caller's persisted app-local storage is baked into the shim so
514
+ // the app's synchronous reads work from its first line.
515
+ const storage = await ctx.core.appStorage.get(
516
+ identity,
517
+ request.params.projectId,
518
+ request.params.appName,
519
+ );
520
+ // The document embeds the (channel-resolved) version's bundle AND the
521
+ // storage seed, so the validator carries both: a republish, a newer
522
+ // dev build, or a storage write changes it and the revalidation
523
+ // misses; otherwise the browser's copy is good.
524
+ const etag = `"${state.versionId}-${request.query.theme ? "t" : "n"}-${storage.revision}"`;
525
+ if (request.headers["if-none-match"] === etag) {
526
+ return reply
527
+ .status(304)
528
+ .header("etag", etag)
529
+ .header("cache-control", "private, no-cache")
530
+ .send();
531
+ }
532
+ // The CSP travels as a response header (authoritative before any
533
+ // parsing) and again as the document's own meta tag via the builder.
534
+ return reply
535
+ .header("content-type", "text/html; charset=utf-8")
536
+ .header(
537
+ "content-security-policy",
538
+ appGuestCsp(state.allowedNetworkOrigins),
539
+ )
540
+ .header("etag", etag)
541
+ .header("cache-control", "private, no-cache")
542
+ .send(
543
+ buildAppGuestDocument({
544
+ code: state.code,
545
+ css: state.css,
546
+ theme: parseGuestTheme(request.query.theme),
547
+ allowedNetworkOrigins: state.allowedNetworkOrigins,
548
+ storageSeed: storage.data,
549
+ }),
550
+ );
551
+ },
552
+ });
553
+
554
+ // Broad enough for any CSS value syntax (color functions, font stacks,
555
+ // cubic-bezier curves); excludes the characters that could close the style
556
+ // rule or the style element the theme lands in. Fonts get stack-length
557
+ // headroom; single values (radii, sizes, durations, easing) stay short.
558
+ const safeCssValue = (max: number) =>
559
+ z
560
+ .string()
561
+ .max(max)
562
+ .regex(/^[^<>{};]*$/);
563
+ // `.catch(undefined)` drops an invalid leaf while keeping its siblings.
564
+ const cssLeaf = (max: number) =>
565
+ safeCssValue(max).optional().catch(undefined);
566
+ const ColorTokenShape = z
567
+ .string()
568
+ .regex(/^[a-z][a-z0-9-]*$/i)
569
+ .max(40);
570
+ const ColorValueShape = safeCssValue(200);
571
+
572
+ const GuestFeelShapes = {
573
+ fonts: z.object({ sans: cssLeaf(200), mono: cssLeaf(200) }),
574
+ radii: z.object({ sm: cssLeaf(64), md: cssLeaf(64), lg: cssLeaf(64) }),
575
+ easing: safeCssValue(64),
576
+ baseFontSize: safeCssValue(64),
577
+ rowHeight: safeCssValue(64),
578
+ motion: z.object({
579
+ fast: cssLeaf(64),
580
+ base: cssLeaf(64),
581
+ slow: cssLeaf(64),
582
+ }),
583
+ } as const;
584
+
585
+ /**
586
+ * The theme rides the guest URL as JSON so the document paints in the
587
+ * host's look on first render (no flash, and the browser cache key
588
+ * naturally varies with it). The URL is caller-controlled, so the shape
589
+ * and character set are validated here — per field: an unknown or invalid
590
+ * field (or color entry) is dropped, never the whole theme. Only a theme
591
+ * without a valid appearance is unusable and yields an unthemed document.
592
+ */
593
+ function parseGuestTheme(raw: string | undefined): AppHostTheme | undefined {
594
+ if (!raw) return undefined;
595
+ let parsed: unknown;
596
+ try {
597
+ parsed = JSON.parse(raw);
598
+ } catch {
599
+ return undefined;
600
+ }
601
+ if (parsed === null || typeof parsed !== "object") return undefined;
602
+ const candidate = parsed as Record<string, unknown>;
603
+ const appearance = z
604
+ .enum(["dark", "light"])
605
+ .safeParse(candidate.appearance);
606
+ if (!appearance.success) return undefined;
607
+ const theme: AppHostTheme = { appearance: appearance.data, colors: {} };
608
+ // Colors survive entry-by-entry: one hostile value drops that entry.
609
+ if (candidate.colors !== null && typeof candidate.colors === "object") {
610
+ for (const [token, value] of Object.entries(
611
+ candidate.colors as Record<string, unknown>,
612
+ )) {
613
+ if (
614
+ ColorTokenShape.safeParse(token).success &&
615
+ ColorValueShape.safeParse(value).success
616
+ ) {
617
+ (theme.colors as Record<string, string>)[token] = value as string;
618
+ }
619
+ }
620
+ }
621
+ for (const key of [
622
+ "fonts",
623
+ "radii",
624
+ "easing",
625
+ "baseFontSize",
626
+ "rowHeight",
627
+ "motion",
628
+ ] as const) {
629
+ if (candidate[key] === undefined) continue;
630
+ const field = GuestFeelShapes[key].safeParse(candidate[key]);
631
+ if (field.success) theme[key] = field.data as never;
632
+ }
633
+ return theme;
634
+ }
635
+
636
+ typed.route({
637
+ method: "GET",
638
+ url: "/projects/:projectId/app-versions/:versionId/bundle",
639
+ schema: {
640
+ params: ProjectAppVersionParamsSchema,
641
+ response: {
642
+ 200: z.object({
643
+ code: z.string(),
644
+ css: z.string(),
645
+ etag: z.string(),
646
+ }),
647
+ 304: z.null(),
648
+ 404: ErrorSchema,
649
+ 503: ErrorSchema,
650
+ },
651
+ },
652
+ handler: async (request, reply) => {
653
+ if (!ctx.core?.apps)
654
+ return reply.status(503).send({ error: "Apps not configured" });
655
+ try {
656
+ const identity = resolveIdentity(request);
657
+ // Version-addressed and append-only: the same versionId always names
658
+ // the same bytes, so a revalidation can skip loading the bundle and a
659
+ // fresh response can be cached indefinitely. Authorization happens
660
+ // first either way — the validator comes from the caller's own URL,
661
+ // so a 304 answered before the access check would be an existence
662
+ // oracle for arbitrary version ids.
663
+ const etag = `"${request.params.versionId}"`;
664
+ if (request.headers["if-none-match"] === etag) {
665
+ await ctx.core.apps.assertBundleReadable({
666
+ identity,
667
+ projectId: request.params.projectId,
668
+ versionId: request.params.versionId,
669
+ });
670
+ return reply
671
+ .status(304)
672
+ .header("etag", etag)
673
+ .header("cache-control", "private, max-age=31536000, immutable")
674
+ .send(null);
675
+ }
676
+ const bundle = await ctx.core.apps.getBundle({
677
+ identity,
678
+ projectId: request.params.projectId,
679
+ versionId: request.params.versionId,
680
+ });
681
+ return reply
682
+ .header("etag", bundle.etag)
683
+ .header("cache-control", "private, max-age=31536000, immutable")
684
+ .send(bundle);
685
+ } catch (err) {
686
+ if (err instanceof AppVersionNotFoundError)
687
+ return reply.status(404).send({ error: err.message });
688
+ throw err;
689
+ }
690
+ },
691
+ });
692
+ }