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