@facilis.dev/nitro 0.0.0-stage → 0.1.2

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 (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/config.d.ts +30 -0
  4. package/dist/config.js +112 -0
  5. package/dist/constants.d.ts +24 -0
  6. package/dist/constants.js +24 -0
  7. package/dist/facade.d.ts +37 -0
  8. package/dist/facade.js +121 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +14 -0
  11. package/dist/middleware/context.d.ts +5 -0
  12. package/dist/middleware/context.js +86 -0
  13. package/dist/middleware/cors.d.ts +10 -0
  14. package/dist/middleware/cors.js +34 -0
  15. package/dist/middleware/session.d.ts +9 -0
  16. package/dist/middleware/session.js +18 -0
  17. package/dist/module.d.ts +7 -0
  18. package/dist/module.js +234 -0
  19. package/dist/rolldown-parser.d.ts +3 -0
  20. package/dist/rolldown-parser.js +66 -0
  21. package/dist/route-metadata.d.ts +22 -0
  22. package/dist/route-metadata.js +161 -0
  23. package/dist/routes/dev-query.post.d.ts +10 -0
  24. package/dist/routes/dev-query.post.js +49 -0
  25. package/dist/routes/dev-schema.get.d.ts +9 -0
  26. package/dist/routes/dev-schema.get.js +34 -0
  27. package/dist/routes/dev-view.post.d.ts +11 -0
  28. package/dist/routes/dev-view.post.js +61 -0
  29. package/dist/routes/health.get.d.ts +8 -0
  30. package/dist/routes/health.get.js +18 -0
  31. package/dist/routes/manifest-revision.get.d.ts +8 -0
  32. package/dist/routes/manifest-revision.get.js +26 -0
  33. package/dist/routes/manifest.get.d.ts +8 -0
  34. package/dist/routes/manifest.get.js +68 -0
  35. package/dist/routes/openapi.get.d.ts +8 -0
  36. package/dist/routes/openapi.get.js +29 -0
  37. package/dist/routes/sso.d.ts +2 -0
  38. package/dist/routes/sso.js +216 -0
  39. package/dist/routes/token.post.d.ts +10 -0
  40. package/dist/routes/token.post.js +75 -0
  41. package/dist/runtime/boot-runtimes.d.ts +21 -0
  42. package/dist/runtime/boot-runtimes.js +38 -0
  43. package/dist/runtime/bootstrap.d.ts +47 -0
  44. package/dist/runtime/bootstrap.js +214 -0
  45. package/dist/runtime/config.d.ts +27 -0
  46. package/dist/runtime/config.js +44 -0
  47. package/dist/runtime/cors-policy.d.ts +16 -0
  48. package/dist/runtime/cors-policy.js +88 -0
  49. package/dist/runtime/db-bootstrap.d.ts +9 -0
  50. package/dist/runtime/db-bootstrap.js +87 -0
  51. package/dist/runtime/db-target.d.ts +21 -0
  52. package/dist/runtime/db-target.js +52 -0
  53. package/dist/runtime/dev-db-persistence.d.ts +39 -0
  54. package/dist/runtime/dev-db-persistence.js +124 -0
  55. package/dist/runtime/dev-query.d.ts +38 -0
  56. package/dist/runtime/dev-query.js +87 -0
  57. package/dist/runtime/env.d.ts +9 -0
  58. package/dist/runtime/env.js +14 -0
  59. package/dist/runtime/http-guard.d.ts +16 -0
  60. package/dist/runtime/http-guard.js +42 -0
  61. package/dist/runtime/http.d.ts +11 -0
  62. package/dist/runtime/http.js +18 -0
  63. package/dist/runtime/jobs/boot.d.ts +20 -0
  64. package/dist/runtime/jobs/boot.js +77 -0
  65. package/dist/runtime/jobs/contracts.d.ts +161 -0
  66. package/dist/runtime/jobs/contracts.js +1 -0
  67. package/dist/runtime/jobs/db-store.d.ts +21 -0
  68. package/dist/runtime/jobs/db-store.js +210 -0
  69. package/dist/runtime/jobs/definitions.d.ts +14 -0
  70. package/dist/runtime/jobs/definitions.js +31 -0
  71. package/dist/runtime/jobs/engine-support.d.ts +22 -0
  72. package/dist/runtime/jobs/engine-support.js +32 -0
  73. package/dist/runtime/jobs/engine.d.ts +6 -0
  74. package/dist/runtime/jobs/engine.js +261 -0
  75. package/dist/runtime/jobs/executor.d.ts +11 -0
  76. package/dist/runtime/jobs/executor.js +27 -0
  77. package/dist/runtime/jobs/memory-store.d.ts +7 -0
  78. package/dist/runtime/jobs/memory-store.js +183 -0
  79. package/dist/runtime/jobs/row-mapping.d.ts +28 -0
  80. package/dist/runtime/jobs/row-mapping.js +61 -0
  81. package/dist/runtime/jobs/runtime.d.ts +24 -0
  82. package/dist/runtime/jobs/runtime.js +86 -0
  83. package/dist/runtime/logging/audit-chain.d.ts +54 -0
  84. package/dist/runtime/logging/audit-chain.js +102 -0
  85. package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
  86. package/dist/runtime/logging/bootstrap-logging.js +26 -0
  87. package/dist/runtime/logging/entry.d.ts +14 -0
  88. package/dist/runtime/logging/entry.js +85 -0
  89. package/dist/runtime/logging/file-sink.d.ts +24 -0
  90. package/dist/runtime/logging/file-sink.js +128 -0
  91. package/dist/runtime/logging/log-settings.d.ts +52 -0
  92. package/dist/runtime/logging/log-settings.js +93 -0
  93. package/dist/runtime/logging/log-sink.d.ts +18 -0
  94. package/dist/runtime/logging/log-sink.js +22 -0
  95. package/dist/runtime/logging/redact.d.ts +31 -0
  96. package/dist/runtime/logging/redact.js +106 -0
  97. package/dist/runtime/logging/runtime.d.ts +25 -0
  98. package/dist/runtime/logging/runtime.js +114 -0
  99. package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
  100. package/dist/runtime/logging/sudo-bridge.js +38 -0
  101. package/dist/runtime/manifest-data.d.ts +28 -0
  102. package/dist/runtime/manifest-data.js +70 -0
  103. package/dist/runtime/manifest-response.d.ts +45 -0
  104. package/dist/runtime/manifest-response.js +50 -0
  105. package/dist/runtime/manifest-sections.d.ts +20 -0
  106. package/dist/runtime/manifest-sections.js +59 -0
  107. package/dist/runtime/manifest-service.d.ts +16 -0
  108. package/dist/runtime/manifest-service.js +66 -0
  109. package/dist/runtime/project-config.d.ts +8 -0
  110. package/dist/runtime/project-config.js +22 -0
  111. package/dist/runtime/project-files.d.ts +12 -0
  112. package/dist/runtime/project-files.js +99 -0
  113. package/dist/runtime/rate-limit.d.ts +6 -0
  114. package/dist/runtime/rate-limit.js +6 -0
  115. package/dist/runtime/revision-service.d.ts +15 -0
  116. package/dist/runtime/revision-service.js +26 -0
  117. package/dist/runtime/sql.d.ts +8 -0
  118. package/dist/runtime/sql.js +23 -0
  119. package/dist/runtime/sso.d.ts +40 -0
  120. package/dist/runtime/sso.js +98 -0
  121. package/dist/runtime/state.d.ts +7 -0
  122. package/dist/runtime/state.js +7 -0
  123. package/dist/runtime/storage-keys.d.ts +9 -0
  124. package/dist/runtime/storage-keys.js +82 -0
  125. package/dist/runtime/storage-target.d.ts +25 -0
  126. package/dist/runtime/storage-target.js +155 -0
  127. package/dist/runtime/system-role.d.ts +9 -0
  128. package/dist/runtime/system-role.js +21 -0
  129. package/dist/runtime/tasks/boot.d.ts +20 -0
  130. package/dist/runtime/tasks/boot.js +32 -0
  131. package/dist/runtime/tasks/contracts.d.ts +70 -0
  132. package/dist/runtime/tasks/contracts.js +1 -0
  133. package/dist/runtime/tasks/db-store.d.ts +18 -0
  134. package/dist/runtime/tasks/db-store.js +139 -0
  135. package/dist/runtime/tasks/row-mapping.d.ts +11 -0
  136. package/dist/runtime/tasks/row-mapping.js +69 -0
  137. package/dist/runtime/tasks/runtime.d.ts +7 -0
  138. package/dist/runtime/tasks/runtime.js +162 -0
  139. package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
  140. package/dist/runtime/tasks/tasks-test-harness.js +70 -0
  141. package/dist/runtime/tenant.d.ts +10 -0
  142. package/dist/runtime/tenant.js +13 -0
  143. package/dist/runtime/workflows/boot.d.ts +25 -0
  144. package/dist/runtime/workflows/boot.js +75 -0
  145. package/dist/runtime/workflows/contracts.d.ts +96 -0
  146. package/dist/runtime/workflows/contracts.js +1 -0
  147. package/dist/runtime/workflows/db-store.d.ts +18 -0
  148. package/dist/runtime/workflows/db-store.js +128 -0
  149. package/dist/runtime/workflows/definitions.d.ts +14 -0
  150. package/dist/runtime/workflows/definitions.js +50 -0
  151. package/dist/runtime/workflows/dispatch.d.ts +4 -0
  152. package/dist/runtime/workflows/dispatch.js +119 -0
  153. package/dist/runtime/workflows/row-mapping.d.ts +5 -0
  154. package/dist/runtime/workflows/row-mapping.js +38 -0
  155. package/dist/runtime/workflows/runner.d.ts +15 -0
  156. package/dist/runtime/workflows/runner.js +89 -0
  157. package/dist/runtime/workflows/runtime.d.ts +14 -0
  158. package/dist/runtime/workflows/runtime.js +129 -0
  159. package/dist/runtime/workflows/steps.d.ts +14 -0
  160. package/dist/runtime/workflows/steps.js +49 -0
  161. package/dist/runtime/workflows/support.d.ts +20 -0
  162. package/dist/runtime/workflows/support.js +36 -0
  163. package/dist/runtime/workflows/transitions.d.ts +8 -0
  164. package/dist/runtime/workflows/transitions.js +184 -0
  165. package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
  166. package/dist/runtime/workflows/workflows-test-harness.js +178 -0
  167. package/dist/session-cookie.d.ts +13 -0
  168. package/dist/session-cookie.js +48 -0
  169. package/dist/storage.d.ts +50 -0
  170. package/dist/storage.js +118 -0
  171. package/dist/types.d.ts +44 -0
  172. package/dist/types.js +1 -0
  173. package/dist/virtual-ids.d.ts +17 -0
  174. package/dist/virtual-ids.js +17 -0
  175. package/dist/vite.d.ts +22 -0
  176. package/dist/vite.js +135 -0
  177. package/package.json +61 -4
  178. package/src/config.ts +120 -0
  179. package/src/constants.ts +24 -0
  180. package/src/facade.ts +153 -0
  181. package/src/index.ts +44 -0
  182. package/src/middleware/context.ts +106 -0
  183. package/src/middleware/cors.ts +42 -0
  184. package/src/middleware/session.ts +23 -0
  185. package/src/module.ts +278 -0
  186. package/src/rolldown-parser.ts +79 -0
  187. package/src/route-metadata-test-harness.ts +62 -0
  188. package/src/route-metadata.ts +194 -0
  189. package/src/routes/dev-query.post.ts +53 -0
  190. package/src/routes/dev-schema.get.ts +43 -0
  191. package/src/routes/dev-view.post.ts +66 -0
  192. package/src/routes/health.get.ts +26 -0
  193. package/src/routes/manifest-revision.get.ts +38 -0
  194. package/src/routes/manifest.get.ts +111 -0
  195. package/src/routes/openapi.get.ts +34 -0
  196. package/src/routes/sso.ts +247 -0
  197. package/src/routes/token.post.ts +89 -0
  198. package/src/runtime/boot-runtimes.ts +69 -0
  199. package/src/runtime/bootstrap.ts +300 -0
  200. package/src/runtime/config.ts +60 -0
  201. package/src/runtime/cors-policy.ts +107 -0
  202. package/src/runtime/db-bootstrap.ts +99 -0
  203. package/src/runtime/db-target.ts +87 -0
  204. package/src/runtime/dev-db-persistence.ts +146 -0
  205. package/src/runtime/dev-query.ts +124 -0
  206. package/src/runtime/env.ts +18 -0
  207. package/src/runtime/http-guard.ts +50 -0
  208. package/src/runtime/http.ts +30 -0
  209. package/src/runtime/jobs/boot.ts +97 -0
  210. package/src/runtime/jobs/contracts.ts +165 -0
  211. package/src/runtime/jobs/db-store-test-harness.ts +98 -0
  212. package/src/runtime/jobs/db-store.ts +273 -0
  213. package/src/runtime/jobs/definitions.ts +42 -0
  214. package/src/runtime/jobs/engine-support.ts +44 -0
  215. package/src/runtime/jobs/engine.ts +296 -0
  216. package/src/runtime/jobs/executor.ts +37 -0
  217. package/src/runtime/jobs/memory-store.ts +222 -0
  218. package/src/runtime/jobs/row-mapping.ts +67 -0
  219. package/src/runtime/jobs/runtime.ts +110 -0
  220. package/src/runtime/logging/audit-chain.ts +135 -0
  221. package/src/runtime/logging/bootstrap-logging.ts +62 -0
  222. package/src/runtime/logging/entry.ts +99 -0
  223. package/src/runtime/logging/file-sink.ts +157 -0
  224. package/src/runtime/logging/log-settings.ts +166 -0
  225. package/src/runtime/logging/log-sink.ts +31 -0
  226. package/src/runtime/logging/redact.ts +108 -0
  227. package/src/runtime/logging/runtime.ts +163 -0
  228. package/src/runtime/logging/sudo-bridge.ts +41 -0
  229. package/src/runtime/manifest-data.ts +103 -0
  230. package/src/runtime/manifest-response.ts +95 -0
  231. package/src/runtime/manifest-sections.ts +79 -0
  232. package/src/runtime/manifest-service.ts +83 -0
  233. package/src/runtime/project-config.ts +25 -0
  234. package/src/runtime/project-files.ts +103 -0
  235. package/src/runtime/rate-limit.ts +12 -0
  236. package/src/runtime/revision-service.ts +38 -0
  237. package/src/runtime/sql.ts +24 -0
  238. package/src/runtime/sso.ts +153 -0
  239. package/src/runtime/state.ts +7 -0
  240. package/src/runtime/storage-keys.ts +95 -0
  241. package/src/runtime/storage-target.ts +238 -0
  242. package/src/runtime/system-role.ts +26 -0
  243. package/src/runtime/tasks/boot.ts +49 -0
  244. package/src/runtime/tasks/contracts.ts +77 -0
  245. package/src/runtime/tasks/db-store.ts +191 -0
  246. package/src/runtime/tasks/row-mapping.ts +75 -0
  247. package/src/runtime/tasks/runtime.ts +192 -0
  248. package/src/runtime/tasks/tasks-test-harness.ts +92 -0
  249. package/src/runtime/tenant.ts +15 -0
  250. package/src/runtime/workflows/boot.ts +97 -0
  251. package/src/runtime/workflows/contracts.ts +114 -0
  252. package/src/runtime/workflows/db-store.ts +156 -0
  253. package/src/runtime/workflows/definitions.ts +75 -0
  254. package/src/runtime/workflows/dispatch.ts +148 -0
  255. package/src/runtime/workflows/row-mapping.ts +54 -0
  256. package/src/runtime/workflows/runner.ts +105 -0
  257. package/src/runtime/workflows/runtime.ts +161 -0
  258. package/src/runtime/workflows/steps.ts +74 -0
  259. package/src/runtime/workflows/support.ts +60 -0
  260. package/src/runtime/workflows/transitions.ts +259 -0
  261. package/src/runtime/workflows/workflows-test-harness.ts +238 -0
  262. package/src/session-cookie.ts +69 -0
  263. package/src/storage.ts +173 -0
  264. package/src/types.ts +51 -0
  265. package/src/virtual-ids.ts +18 -0
  266. package/src/virtual-modules.d.ts +53 -0
  267. package/src/vite.ts +175 -0
@@ -0,0 +1,8 @@
1
+ /**
2
+ * GET /__facilis/health — boot detector used by Studio (SPEC §6.3/§6.7).
3
+ *
4
+ * Reaching this handler already means the Nitro worker is up; `status` stays "ok"
5
+ * and the revision tells the client whether a full manifest fetch is needed.
6
+ */
7
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
8
+ export default _default;
@@ -0,0 +1,18 @@
1
+ import { defineHandler } from "nitro";
2
+ import { guardDevRequest } from "../runtime/http-guard.js";
3
+ import { jsonResult, toResponse } from "../runtime/http.js";
4
+ import { getRevisionSnapshot } from "../runtime/revision-service.js";
5
+ import { bootedAt } from "../runtime/state.js";
6
+ /**
7
+ * GET /__facilis/health — boot detector used by Studio (SPEC §6.3/§6.7).
8
+ *
9
+ * Reaching this handler already means the Nitro worker is up; `status` stays "ok"
10
+ * and the revision tells the client whether a full manifest fetch is needed.
11
+ */
12
+ export default defineHandler(async (event) => {
13
+ const guard = guardDevRequest(event.req.headers);
14
+ if (guard)
15
+ return toResponse(guard);
16
+ const snapshot = await getRevisionSnapshot();
17
+ return toResponse(jsonResult(200, { status: "ok", bootedAt, revision: snapshot.revision }, { "cache-control": "no-cache" }));
18
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * GET /__facilis/manifest/revision — cheap freshness poll (SPEC §6.3).
3
+ *
4
+ * Deliberately skips the database: the revision only depends on project files and
5
+ * the AST-pass metadata, so Studio can poll this every 2s (SPEC §6.6).
6
+ */
7
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
8
+ export default _default;
@@ -0,0 +1,26 @@
1
+ import { defineHandler } from "nitro";
2
+ import { guardDevRequest } from "../runtime/http-guard.js";
3
+ import { jsonResult, parseRequestUrl, toResponse } from "../runtime/http.js";
4
+ import { isNotModified, manifestHeaders, notModifiedResult } from "../runtime/manifest-response.js";
5
+ import { getRevisionSnapshot } from "../runtime/revision-service.js";
6
+ /**
7
+ * GET /__facilis/manifest/revision — cheap freshness poll (SPEC §6.3).
8
+ *
9
+ * Deliberately skips the database: the revision only depends on project files and
10
+ * the AST-pass metadata, so Studio can poll this every 2s (SPEC §6.6).
11
+ */
12
+ export default defineHandler(async (event) => {
13
+ const guard = guardDevRequest(event.req.headers);
14
+ if (guard)
15
+ return toResponse(guard);
16
+ const url = parseRequestUrl(event.req.url);
17
+ const snapshot = await getRevisionSnapshot();
18
+ if (isNotModified({
19
+ ifNoneMatch: event.req.headers.get("if-none-match"),
20
+ since: url.searchParams.get("since"),
21
+ revision: snapshot.revision,
22
+ })) {
23
+ return toResponse(notModifiedResult(snapshot.revision));
24
+ }
25
+ return toResponse(jsonResult(200, { revision: snapshot.revision, generatedAt: snapshot.generatedAt }, manifestHeaders(snapshot.revision, false)));
26
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * GET /__facilis/manifest — dev-only runtime projection of the project (SPEC §6).
3
+ *
4
+ * 200 full/partial, 304 on If-None-Match/since, 400 on invalid sections/format,
5
+ * 403 origin mismatch, 404 in production, 503 when the project config is unusable.
6
+ */
7
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
8
+ export default _default;
@@ -0,0 +1,68 @@
1
+ import { defineHandler } from "nitro";
2
+ import { summarizeManifest } from "@facilis.dev/core";
3
+ import { guardDevRequest } from "../runtime/http-guard.js";
4
+ import { jsonResult, parseRequestUrl, toResponse } from "../runtime/http.js";
5
+ import { isNotModified, manifestResponse, notModifiedResult, summaryResponse, } from "../runtime/manifest-response.js";
6
+ import { ALL_MANIFEST_SECTIONS, parseSectionsParameter, selectManifestSections, } from "../runtime/manifest-sections.js";
7
+ import { getManifestSnapshot } from "../runtime/manifest-service.js";
8
+ const NO_CACHE = { "cache-control": "no-cache" };
9
+ function parseFormat(value) {
10
+ if (value === null || value === "" || value === "full")
11
+ return "full";
12
+ if (value === "summary")
13
+ return "summary";
14
+ return undefined;
15
+ }
16
+ /**
17
+ * GET /__facilis/manifest — dev-only runtime projection of the project (SPEC §6).
18
+ *
19
+ * 200 full/partial, 304 on If-None-Match/since, 400 on invalid sections/format,
20
+ * 403 origin mismatch, 404 in production, 503 when the project config is unusable.
21
+ */
22
+ export default defineHandler(async (event) => {
23
+ const guard = guardDevRequest(event.req.headers);
24
+ if (guard)
25
+ return toResponse(guard);
26
+ const url = parseRequestUrl(event.req.url);
27
+ const sections = parseSectionsParameter(url.searchParams.get("sections"));
28
+ if (!sections.ok) {
29
+ return toResponse(jsonResult(400, { code: "invalid_input", details: { parameter: "sections", invalid: sections.invalid } }, { ...NO_CACHE }));
30
+ }
31
+ const format = parseFormat(url.searchParams.get("format"));
32
+ if (format === undefined) {
33
+ return toResponse(jsonResult(400, { code: "invalid_input", details: { parameter: "format", expected: ["full", "summary"] } }, { ...NO_CACHE }));
34
+ }
35
+ const snapshot = await getManifestSnapshot();
36
+ if (snapshot === null) {
37
+ return toResponse(jsonResult(503, { code: "internal_error", details: { reason: "config_unavailable" } }, { ...NO_CACHE }));
38
+ }
39
+ if (isNotModified({
40
+ ifNoneMatch: event.req.headers.get("if-none-match"),
41
+ since: url.searchParams.get("since"),
42
+ revision: snapshot.revision,
43
+ })) {
44
+ return toResponse(notModifiedResult(snapshot.revision));
45
+ }
46
+ const requestedSections = sections.sections ?? ALL_MANIFEST_SECTIONS;
47
+ if (format === "summary") {
48
+ return toResponse(summaryResponse({
49
+ revision: snapshot.revision,
50
+ generatedAt: snapshot.generatedAt,
51
+ sections: requestedSections,
52
+ summary: summarizeManifest(snapshot.data.manifest),
53
+ warnings: snapshot.warnings,
54
+ }));
55
+ }
56
+ const selected = selectManifestSections(snapshot.data.manifest, sections.sections);
57
+ // A failed section is omitted from the payload; the envelope warning explains why.
58
+ if (snapshot.data.partial)
59
+ delete selected.schema;
60
+ return toResponse(manifestResponse({
61
+ revision: snapshot.revision,
62
+ generatedAt: snapshot.generatedAt,
63
+ sections: requestedSections,
64
+ manifest: selected,
65
+ warnings: snapshot.warnings,
66
+ partial: snapshot.data.partial,
67
+ }));
68
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * GET /_openapi.json — the public, AST-augmented OpenAPI document (SPEC §6.9).
3
+ *
4
+ * Nitro's own generator stays intact on /_facilis/openapi.json; this handler fetches
5
+ * it in-process and merges the metadata Nitro's scanner cannot see.
6
+ */
7
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
8
+ export default _default;
@@ -0,0 +1,29 @@
1
+ import { defineHandler, serverFetch } from "nitro";
2
+ import routeMetadata from "#facilis/openapi-meta";
3
+ import { buildOpenApiFacadeResponse, NATIVE_OPENAPI_ROUTE, } from "../facade.js";
4
+ import { toResponse } from "../runtime/http.js";
5
+ async function fetchNativeSpec() {
6
+ try {
7
+ const response = await serverFetch(NATIVE_OPENAPI_ROUTE);
8
+ if (!response.ok)
9
+ return null;
10
+ return (await response.json());
11
+ }
12
+ catch {
13
+ // OpenAPI disabled or the internal route is not built yet: the facade reports it.
14
+ return null;
15
+ }
16
+ }
17
+ /**
18
+ * GET /_openapi.json — the public, AST-augmented OpenAPI document (SPEC §6.9).
19
+ *
20
+ * Nitro's own generator stays intact on /_facilis/openapi.json; this handler fetches
21
+ * it in-process and merges the metadata Nitro's scanner cannot see.
22
+ */
23
+ export default defineHandler(async () => {
24
+ const result = await buildOpenApiFacadeResponse({
25
+ metadata: routeMetadata,
26
+ fetchNativeSpec,
27
+ });
28
+ return toResponse(result);
29
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("@facilis.dev/core").AuthorizedHandler;
2
+ export default _default;
@@ -0,0 +1,216 @@
1
+ import { createSession, SsoError } from "@facilis.dev/auth";
2
+ import { defineAuthorizedHandler, fail, } from "@facilis.dev/core";
3
+ import { getBootstrap } from "../runtime/bootstrap.js";
4
+ import { jsonResult, parseRequestUrl, toResponse } from "../runtime/http.js";
5
+ import { completeSsoLogin, listSsoProviders, SSO_ROUTE_PREFIX, SSO_ROUTE_TABLES, ssoFailureLocation, startSsoLogin, } from "../runtime/sso.js";
6
+ import { setSessionCookie } from "../session-cookie.js";
7
+ /**
8
+ * The framework-owned SSO namespace (D-120, SPEC §5.3).
9
+ *
10
+ * GET /api/auth/sso/providers -> { providers } (no-store, no secrets)
11
+ * GET /api/auth/sso/:provider/start -> 302 to the IdP (creates the single-use state)
12
+ * GET /api/auth/sso/:provider/callback -> OIDC/OAuth2 code callback
13
+ * POST /api/auth/sso/:provider/callback -> SAML ACS (application/x-www-form-urlencoded)
14
+ *
15
+ * One handler answers the whole namespace; the Lead registers it at `/api/auth/sso/**`.
16
+ * Failures in a browser navigation are a 302 to `failureRedirect?sso_error=<code>`, never a
17
+ * JSON body that could leak a library message; an unknown path/method is a plain 404.
18
+ *
19
+ * There is deliberately no log endpoint here, and neither the request body nor a SAML payload is
20
+ * ever logged (D-119/D-120).
21
+ */
22
+ const MAX_SAML_BODY_BYTES = 1024 * 1024;
23
+ const MAX_CODE_LENGTH = 8192;
24
+ const MAX_STATE_LENGTH = 256;
25
+ function notFound() {
26
+ return toResponse(jsonResult(404, { code: "not_found" }));
27
+ }
28
+ function redirect(location) {
29
+ return new Response(null, { status: 302, headers: { location } });
30
+ }
31
+ function failure(config, error) {
32
+ return redirect(ssoFailureLocation(config, error));
33
+ }
34
+ /** A malformed percent-encoding is caller input, not a server error: answer 404. */
35
+ function decodeSegment(segment) {
36
+ try {
37
+ return decodeURIComponent(segment);
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ /** Splits `/api/auth/sso/<provider>/<action>` into at most two decoded segments. */
44
+ function routeSegments(pathname) {
45
+ if (pathname !== SSO_ROUTE_PREFIX && !pathname.startsWith(`${SSO_ROUTE_PREFIX}/`))
46
+ return null;
47
+ const rest = pathname.slice(SSO_ROUTE_PREFIX.length).replace(/^\/+|\/+$/g, "");
48
+ if (rest.length === 0)
49
+ return [];
50
+ const raw = rest.split("/");
51
+ if (raw.length > 2 || raw.some((segment) => segment.length === 0))
52
+ return null;
53
+ const decoded = [];
54
+ for (const segment of raw) {
55
+ const value = decodeSegment(segment);
56
+ if (value === null)
57
+ return null;
58
+ decoded.push(value);
59
+ }
60
+ return decoded;
61
+ }
62
+ /** The declared body size, when the client sent one. */
63
+ function contentLengthOf(event) {
64
+ const raw = event.req.headers.get("content-length");
65
+ if (raw === null)
66
+ return null;
67
+ const value = Number(raw);
68
+ return Number.isSafeInteger(value) && value >= 0 ? value : null;
69
+ }
70
+ /** Reads the urlencoded ACS body; null when the runtime cannot provide a text reader. */
71
+ async function readBodyText(event) {
72
+ const reader = event.req.text;
73
+ if (typeof reader !== "function")
74
+ return null;
75
+ try {
76
+ return await reader.call(event.req);
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ /**
83
+ * The two ACS form fields. This is a hand-written check rather than a Zod schema because the
84
+ * framework route lives in @facilis.dev/nitro, whose dependency set has no zod (and the route wrapper
85
+ * has no urlencoded `form` schema); the validation is the same length/presence check a schema
86
+ * would express, and every failure maps to a safe redirect code.
87
+ */
88
+ function readSamlForm(body) {
89
+ if (body.length > MAX_SAML_BODY_BYTES)
90
+ return null;
91
+ let params;
92
+ try {
93
+ params = new URLSearchParams(body);
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ const samlResponse = params.get("SAMLResponse");
99
+ const relayState = params.get("RelayState");
100
+ if (samlResponse === null || samlResponse.length === 0)
101
+ return null;
102
+ if (relayState === null || relayState.length === 0 || relayState.length > MAX_STATE_LENGTH) {
103
+ return null;
104
+ }
105
+ return { samlResponse, relayState };
106
+ }
107
+ function callbackGetInput(url) {
108
+ const providerError = url.searchParams.get("error");
109
+ const code = url.searchParams.get("code");
110
+ const state = url.searchParams.get("state");
111
+ // A provider-side error (e.g. access_denied) and a missing code are the same failure to us.
112
+ if (providerError !== null || code === null || code.length === 0) {
113
+ return { input: null, error: new SsoError("sso_exchange_failed") };
114
+ }
115
+ if (code.length > MAX_CODE_LENGTH)
116
+ return { input: null, error: new SsoError("sso_exchange_failed") };
117
+ if (state === null || state.length > MAX_STATE_LENGTH) {
118
+ return { input: null, error: new SsoError("sso_state_invalid") };
119
+ }
120
+ return { input: { method: "GET", code, state }, error: null };
121
+ }
122
+ async function finishLogin(event, config, db, result) {
123
+ const session = await createSession(db, result.userId, { ttlMs: config.auth.sessionDurationMs });
124
+ // h3 stages the Set-Cookie on the event response; a cookie on a returned Response is dropped
125
+ // in the in-VM path (D-038), so the framework helper is the only correct surface.
126
+ setSessionCookie(event, session.id, { ttlMs: config.auth.sessionDurationMs });
127
+ return redirect(result.redirectTo);
128
+ }
129
+ export default defineAuthorizedHandler({
130
+ permission: [],
131
+ dbTables: [...SSO_ROUTE_TABLES],
132
+ // A SAML ACS is a cross-site POST from the IdP by design; the signed assertion is the
133
+ // protocol's own authenticity check, so the generic CSRF gate must not refuse it.
134
+ originCheck: "skip",
135
+ description: "Framework-owned SSO endpoints: provider list, start and callback.",
136
+ }, async (event, ctx) => {
137
+ const state = await getBootstrap();
138
+ const config = state.config;
139
+ if (config === null)
140
+ return fail("db_unavailable");
141
+ const url = parseRequestUrl(event.req.url ?? SSO_ROUTE_PREFIX);
142
+ const segments = routeSegments(url.pathname);
143
+ if (segments === null)
144
+ return notFound();
145
+ const context = {
146
+ event,
147
+ config,
148
+ system: ctx.system,
149
+ log: ctx.log,
150
+ };
151
+ const method = (event.req.method ?? "GET").toUpperCase();
152
+ // GET /api/auth/sso/providers
153
+ if (segments.length === 1 && segments[0] === "providers") {
154
+ if (method !== "GET")
155
+ return notFound();
156
+ const providers = listSsoProviders(config);
157
+ return toResponse(jsonResult(200, { providers }, { "cache-control": "no-store" }));
158
+ }
159
+ if (segments.length !== 2)
160
+ return notFound();
161
+ const providerId = segments[0];
162
+ const action = segments[1];
163
+ if (providerId === undefined || action === undefined)
164
+ return notFound();
165
+ // GET /api/auth/sso/:provider/start?redirect=/path
166
+ if (action === "start") {
167
+ if (method !== "GET")
168
+ return notFound();
169
+ try {
170
+ const result = await startSsoLogin(context, providerId, url.searchParams.get("redirect"));
171
+ return redirect(result.redirectUrl);
172
+ }
173
+ catch (error) {
174
+ return failure(config, error);
175
+ }
176
+ }
177
+ if (action !== "callback")
178
+ return notFound();
179
+ // GET /api/auth/sso/:provider/callback?code&state (OIDC / OAuth2)
180
+ if (method === "GET") {
181
+ const parsed = callbackGetInput(url);
182
+ if (parsed.input === null)
183
+ return failure(config, parsed.error ?? new SsoError("sso_exchange_failed"));
184
+ try {
185
+ const result = await completeSsoLogin(context, providerId, parsed.input);
186
+ return await finishLogin(event, config, ctx.db, result);
187
+ }
188
+ catch (error) {
189
+ return failure(config, error);
190
+ }
191
+ }
192
+ // POST /api/auth/sso/:provider/callback (SAML ACS)
193
+ if (method === "POST") {
194
+ // Reject before buffering: an oversized public POST must not allocate its body.
195
+ const declaredLength = contentLengthOf(event);
196
+ if (declaredLength !== null && declaredLength > MAX_SAML_BODY_BYTES) {
197
+ return failure(config, new SsoError("sso_exchange_failed"));
198
+ }
199
+ const body = await readBodyText(event);
200
+ const form = body === null ? null : readSamlForm(body);
201
+ if (form === null)
202
+ return failure(config, new SsoError("sso_exchange_failed"));
203
+ try {
204
+ const result = await completeSsoLogin(context, providerId, {
205
+ method: "POST",
206
+ samlResponse: form.samlResponse,
207
+ relayState: form.relayState,
208
+ });
209
+ return await finishLogin(event, config, ctx.db, result);
210
+ }
211
+ catch (error) {
212
+ return failure(config, error);
213
+ }
214
+ }
215
+ return notFound();
216
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * POST /api/auth/token — framework-owned OAuth2 client-credentials endpoint (v3a).
3
+ *
4
+ * A machine client exchanges its id + secret for a short-lived Bearer token; the route is
5
+ * public (no session), and a disabled config answers not_found so a deployment that does not
6
+ * use API clients exposes no enumerable surface. The wrapper enforces the JSON content-type
7
+ * and validates the body; the secret is never logged.
8
+ */
9
+ declare const _default: import("@facilis.dev/core").AuthorizedHandler;
10
+ export default _default;
@@ -0,0 +1,75 @@
1
+ import { issueApiToken } from "@facilis.dev/auth";
2
+ import { defineAuthorizedHandler, fail } from "@facilis.dev/core";
3
+ import { z } from "zod";
4
+ import { getBootstrap } from "../runtime/bootstrap.js";
5
+ import { jsonResult, toResponse } from "../runtime/http.js";
6
+ import { createFixedWindowRateLimiter } from "../runtime/rate-limit.js";
7
+ // One limiter per process: the window is per client id, and a deployment runs one server.
8
+ const tokenRateLimiter = createFixedWindowRateLimiter();
9
+ const tokenRequestSchema = z.object({
10
+ grant_type: z.literal("client_credentials"),
11
+ client_id: z.string().min(1),
12
+ client_secret: z.string().min(1),
13
+ });
14
+ /**
15
+ * POST /api/auth/token — framework-owned OAuth2 client-credentials endpoint (v3a).
16
+ *
17
+ * A machine client exchanges its id + secret for a short-lived Bearer token; the route is
18
+ * public (no session), and a disabled config answers not_found so a deployment that does not
19
+ * use API clients exposes no enumerable surface. The wrapper enforces the JSON content-type
20
+ * and validates the body; the secret is never logged.
21
+ */
22
+ export default defineAuthorizedHandler({
23
+ permission: [],
24
+ // The issue path reads the client row and inserts the token; the service user is reached
25
+ // through the client's RLS policy, not by a query of this route.
26
+ dbTables: ["api_clients", "api_tokens"],
27
+ body: tokenRequestSchema,
28
+ description: "Framework-owned OAuth2 client-credentials token endpoint.",
29
+ }, async (_event, ctx) => {
30
+ const state = await getBootstrap();
31
+ const config = state.config;
32
+ if (config === null)
33
+ return fail("db_unavailable");
34
+ // v3a: a deployment with no API clients keeps the route registered but invisible.
35
+ if (config.auth.apiClients?.enabled !== true)
36
+ return fail("not_found");
37
+ // Throttle before touching the database: this is where a secret-guessing loop would
38
+ // otherwise reach a hash comparison on every attempt (D-143).
39
+ const limit = tokenRateLimiter.consume(ctx.body.client_id, config.auth.apiClients.rateLimit);
40
+ if (!limit.allowed) {
41
+ ctx.log.audit({
42
+ operation: "auth:token:issue",
43
+ outcome: "failed",
44
+ errorCode: "too_many_requests",
45
+ });
46
+ const response = fail("too_many_requests");
47
+ response.headers.set("retry-after", String(limit.retryAfterSeconds));
48
+ return response;
49
+ }
50
+ const issued = await issueApiToken(ctx.db, {
51
+ clientId: ctx.body.client_id,
52
+ clientSecret: ctx.body.client_secret,
53
+ ttlMs: config.auth.apiClients.tokenTtlMs,
54
+ });
55
+ if (issued === null) {
56
+ ctx.log.audit({
57
+ operation: "auth:token:issue",
58
+ outcome: "failed",
59
+ errorCode: "unauthorized",
60
+ });
61
+ return fail("unauthorized");
62
+ }
63
+ // Only the client id is auditable: the secret and the issued token are credentials.
64
+ ctx.log.audit({
65
+ operation: "auth:token:issue",
66
+ outcome: "succeeded",
67
+ details: { clientId: ctx.body.client_id },
68
+ });
69
+ return toResponse(jsonResult(200, {
70
+ access_token: issued.accessToken,
71
+ token_type: "Bearer",
72
+ // A response body is not a cache surface (D-119): the token must never be stored.
73
+ expires_in: Math.floor(config.auth.apiClients.tokenTtlMs / 1000),
74
+ }, { "cache-control": "no-store" }));
75
+ });
@@ -0,0 +1,21 @@
1
+ import { type FacilisConfig, type ManifestWarning } from "@facilis.dev/core";
2
+ import type { FacilisDb } from "@facilis.dev/db";
3
+ import type { JobModule } from "./jobs/contracts.js";
4
+ import type { JobsRuntime } from "./jobs/runtime.js";
5
+ import type { TasksRuntime } from "./tasks/boot.js";
6
+ import type { WorkflowModule } from "./workflows/contracts.js";
7
+ import type { WorkflowsRuntime } from "./workflows/runner.js";
8
+ /** The per-request services the context middleware attaches, all nullable on failure. */
9
+ export interface BootedRuntimes {
10
+ readonly jobs: JobsRuntime | null;
11
+ readonly tasks: TasksRuntime | null;
12
+ readonly workflows: WorkflowsRuntime | null;
13
+ }
14
+ export declare function bootRuntimes(options: {
15
+ readonly db: FacilisDb;
16
+ readonly tenantId: string;
17
+ readonly projectConfig: FacilisConfig;
18
+ readonly jobModules: readonly JobModule[];
19
+ readonly workflowModules: readonly WorkflowModule[];
20
+ readonly warnings: ManifestWarning[];
21
+ }): Promise<BootedRuntimes>;
@@ -0,0 +1,38 @@
1
+ // Boots the framework runtimes that sit behind ctx (D-107, D-135, docs/JOBS.md §8).
2
+ //
3
+ // Split out of bootstrap.ts to keep that file under the 300-line gate. Each boot is
4
+ // degradation-safe: a broken queue/task/workflow runtime is a manifest warning and a null
5
+ // service, never a failed process (contracts §8).
6
+ import { DEFAULT_JOBS_CONFIG, DEFAULT_WORKFLOWS_CONFIG, } from "@facilis.dev/core";
7
+ import { bootJobs } from "./jobs/boot.js";
8
+ import { bootTasks } from "./tasks/boot.js";
9
+ import { bootWorkflows } from "./workflows/boot.js";
10
+ export async function bootRuntimes(options) {
11
+ const { db, tenantId, projectConfig, jobModules, workflowModules, warnings } = options;
12
+ // The queue starts after the roles/views exist: its own writes run as facilis_app, while
13
+ // a job body escalates to facilis_system (D-107). A failure there is a warning, not a 500.
14
+ const jobs = await bootJobs({
15
+ db,
16
+ // isFacilisConfig deliberately does not require `jobs`, so an older virtual config can
17
+ // still hand an undefined section to a newer runtime: fall back to documented defaults.
18
+ jobsConfig: projectConfig.jobs ?? DEFAULT_JOBS_CONFIG,
19
+ modules: jobModules,
20
+ tenantId,
21
+ warnings,
22
+ });
23
+ // Manual tasks are durable rows, not a process queue (D-135): booting them is just the
24
+ // store and its table probe; the workflow runner (below) is the only tick.
25
+ const tasks = await bootTasks({ db, tenantId, warnings });
26
+ // Workflows chain step jobs and approval tasks (D-135, WORKFLOWS.md §8): the runner needs
27
+ // both runtimes, and a missing one disables the API with a warning instead of failing boot.
28
+ const workflows = await bootWorkflows({
29
+ db,
30
+ tenantId,
31
+ modules: workflowModules,
32
+ jobs,
33
+ jobsConfig: projectConfig.jobs ?? DEFAULT_JOBS_CONFIG,
34
+ workflowsConfig: projectConfig.workflows ?? DEFAULT_WORKFLOWS_CONFIG,
35
+ warnings,
36
+ });
37
+ return { jobs, tasks, workflows };
38
+ }
@@ -0,0 +1,47 @@
1
+ import { type FacilisDb } from "@facilis.dev/db";
2
+ import { type SessionEvent } from "@facilis.dev/auth";
3
+ import { type FacilisConfig, type FacilisLoggingApi, type FacilisLoggingConfig, type ManifestWarning, type StorageApi } from "@facilis.dev/core";
4
+ import type { JobsRuntime } from "./jobs/runtime.js";
5
+ import type { TasksRuntime } from "./tasks/boot.js";
6
+ import type { WorkflowsRuntime } from "./workflows/runner.js";
7
+ export interface BootstrapState {
8
+ readonly db: FacilisDb | null;
9
+ readonly config: FacilisConfig | null;
10
+ readonly warnings: readonly ManifestWarning[];
11
+ readonly startedAt: string;
12
+ /**
13
+ * Background-job runtime (D-107); null when the db or the job boot failed. The context
14
+ * middleware carries `jobs.api` on `event.context.facilis`.
15
+ */
16
+ readonly jobs: JobsRuntime | null;
17
+ /**
18
+ * Manual-task runtime (D-135); null when facilis_tasks is missing or the task boot failed.
19
+ * The context middleware carries tasks.api on event.context.facilis.
20
+ */
21
+ readonly tasks: TasksRuntime | null;
22
+ /**
23
+ * Workflow runtime (D-135); null when the tables or the job queue are unavailable. The
24
+ * context middleware carries workflows.api on event.context.facilis.
25
+ */
26
+ readonly workflows: WorkflowsRuntime | null;
27
+ /** Binary-storage runtime (D-053); null when the boot refused its configuration. */
28
+ readonly storage: StorageApi | null;
29
+ /**
30
+ * Operator logging runtime (D-119). Always present: built from the documented defaults when
31
+ * the project config failed, so the request context never lacks a logger.
32
+ */
33
+ readonly logging: FacilisLoggingApi;
34
+ /** Effective logging config (project defaults + env level override) for the middleware. */
35
+ readonly loggingConfig: FacilisLoggingConfig;
36
+ /** Cached session handler; rebuilt lazily because it closes over the db client. */
37
+ sessionHandler?: (event: SessionEvent) => Promise<void>;
38
+ }
39
+ /**
40
+ * Boot the framework runtime once per process (lazily, on the first request).
41
+ *
42
+ * Contract (docs/archive/PHASE1-CONTRACTS.md §8): never crash the request. Each failure is
43
+ * recorded as a manifest warning and the remaining steps still run, so a broken
44
+ * migration yields a 200 partial manifest instead of a 500.
45
+ */
46
+ export declare function getBootstrap(): Promise<BootstrapState>;
47
+ export declare function getSessionHandler(state: BootstrapState): ((event: SessionEvent) => Promise<void>) | null;