@pgfsm/api 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/_dnt.polyfills.d.ts +17 -0
- package/esm/_dnt.polyfills.js +15 -0
- package/esm/_dnt.shims.d.ts +5 -0
- package/esm/_dnt.shims.js +61 -0
- package/esm/database-src/generated/database.types.d.ts +2131 -0
- package/esm/database-src/generated/database.types.js +21 -0
- package/esm/deps/jsr.io/@std/cli/1.0.31/parse_args.d.ts +342 -0
- package/esm/deps/jsr.io/@std/cli/1.0.31/parse_args.js +372 -0
- package/esm/fsm-api-ts/env.d.ts +143 -0
- package/esm/fsm-api-ts/env.js +72 -0
- package/esm/fsm-api-ts/lib/configure-open-api.d.ts +3 -0
- package/esm/fsm-api-ts/lib/configure-open-api.js +25 -0
- package/esm/fsm-api-ts/lib/constants.d.ts +15 -0
- package/esm/fsm-api-ts/lib/constants.js +11 -0
- package/esm/fsm-api-ts/lib/create-app.d.ts +19 -0
- package/esm/fsm-api-ts/lib/create-app.js +137 -0
- package/esm/fsm-api-ts/lib/create-router.d.ts +3 -0
- package/esm/fsm-api-ts/lib/create-router.js +10 -0
- package/esm/fsm-api-ts/lib/license.d.ts +13 -0
- package/esm/fsm-api-ts/lib/license.js +15 -0
- package/esm/fsm-api-ts/lib/types.d.ts +19 -0
- package/esm/fsm-api-ts/lib/types.js +1 -0
- package/esm/fsm-api-ts/logger.d.ts +3 -0
- package/esm/fsm-api-ts/logger.js +20 -0
- package/esm/fsm-api-ts/middlewares/api-key-auth.d.ts +34 -0
- package/esm/fsm-api-ts/middlewares/api-key-auth.js +70 -0
- package/esm/fsm-api-ts/middlewares/logtape-logger.d.ts +2 -0
- package/esm/fsm-api-ts/middlewares/logtape-logger.js +33 -0
- package/esm/fsm-api-ts/middlewares/otel-trace.d.ts +2 -0
- package/esm/fsm-api-ts/middlewares/otel-trace.js +29 -0
- package/esm/fsm-api-ts/middlewares/supabase.d.ts +10 -0
- package/esm/fsm-api-ts/middlewares/supabase.js +34 -0
- package/esm/fsm-api-ts/mod.d.ts +2 -0
- package/esm/fsm-api-ts/mod.js +6 -0
- package/esm/fsm-api-ts/routes/admin/admin.handlers.d.ts +8 -0
- package/esm/fsm-api-ts/routes/admin/admin.handlers.js +98 -0
- package/esm/fsm-api-ts/routes/admin/admin.index.d.ts +189 -0
- package/esm/fsm-api-ts/routes/admin/admin.index.js +11 -0
- package/esm/fsm-api-ts/routes/admin/admin.routes.d.ts +473 -0
- package/esm/fsm-api-ts/routes/admin/admin.routes.js +130 -0
- package/esm/fsm-api-ts/routes/definitions/definitions.handlers.d.ts +5 -0
- package/esm/fsm-api-ts/routes/definitions/definitions.handlers.js +29 -0
- package/esm/fsm-api-ts/routes/definitions/definitions.index.d.ts +86 -0
- package/esm/fsm-api-ts/routes/definitions/definitions.index.js +8 -0
- package/esm/fsm-api-ts/routes/definitions/definitions.routes.d.ts +204 -0
- package/esm/fsm-api-ts/routes/definitions/definitions.routes.js +56 -0
- package/esm/fsm-api-ts/routes/index.route.d.ts +19 -0
- package/esm/fsm-api-ts/routes/index.route.js +31 -0
- package/esm/fsm-api-ts/routes/instances/instances.handlers.d.ts +8 -0
- package/esm/fsm-api-ts/routes/instances/instances.handlers.js +108 -0
- package/esm/fsm-api-ts/routes/instances/instances.index.d.ts +237 -0
- package/esm/fsm-api-ts/routes/instances/instances.index.js +11 -0
- package/esm/fsm-api-ts/routes/instances/instances.routes.d.ts +411 -0
- package/esm/fsm-api-ts/routes/instances/instances.routes.js +104 -0
- package/esm/fsm-api-ts/src/cli/index.d.ts +2 -0
- package/esm/fsm-api-ts/src/cli/index.js +197 -0
- package/esm/fsm-api-ts/src/cli/invocation.node.d.ts +1 -0
- package/esm/fsm-api-ts/src/cli/invocation.node.js +4 -0
- package/esm/fsm-api-ts/src/cli/key-bootstrap.d.ts +14 -0
- package/esm/fsm-api-ts/src/cli/key-bootstrap.js +35 -0
- package/esm/fsm-api-ts/src/cli/serve.node.d.ts +6 -0
- package/esm/fsm-api-ts/src/cli/serve.node.js +20 -0
- package/esm/fsm-api-ts/src/cli/version.node.d.ts +1 -0
- package/esm/fsm-api-ts/src/cli/version.node.js +2 -0
- package/esm/fsm-api-ts/stoker-src/http-status-codes.d.ts +354 -0
- package/esm/fsm-api-ts/stoker-src/http-status-codes.js +356 -0
- package/esm/fsm-api-ts/stoker-src/http-status-phrases.d.ts +354 -0
- package/esm/fsm-api-ts/stoker-src/http-status-phrases.js +356 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/index.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/index.js +3 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/not-found.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/not-found.js +8 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/on-error.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/on-error.js +19 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/serve-emoji-favicon.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/middlewares/serve-emoji-favicon.js +10 -0
- package/esm/fsm-api-ts/stoker-src/openapi/default-hook.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/openapi/default-hook.js +11 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/index.d.ts +4 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/index.js +4 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/json-content-one-of.d.ts +12 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/json-content-one-of.js +14 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/json-content-required.d.ts +11 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/json-content-required.js +8 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/json-content.d.ts +10 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/json-content.js +11 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/one-of.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/one-of.js +13 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/types.d.ts +2 -0
- package/esm/fsm-api-ts/stoker-src/openapi/helpers/types.js +1 -0
- package/esm/fsm-api-ts/stoker-src/openapi/index.d.ts +3 -0
- package/esm/fsm-api-ts/stoker-src/openapi/index.js +3 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/create-error-schema.d.ts +56 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/create-error-schema.js +25 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/create-message-object.d.ts +9 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/create-message-object.js +11 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/id-params.d.ts +9 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/id-params.js +13 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/id-uuid-params.d.ts +9 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/id-uuid-params.js +13 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/index.d.ts +5 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/index.js +5 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/slug-params.d.ts +9 -0
- package/esm/fsm-api-ts/stoker-src/openapi/schemas/slug-params.js +18 -0
- package/esm/fsm-core-db-ts/src/database.types.d.ts +4 -0
- package/esm/fsm-core-db-ts/src/database.types.js +17 -0
- package/esm/package.json +3 -0
- package/package.json +45 -3
- package/script/_dnt.polyfills.d.ts +17 -0
- package/script/_dnt.polyfills.js +16 -0
- package/script/_dnt.shims.d.ts +5 -0
- package/script/_dnt.shims.js +65 -0
- package/script/fsm-api-ts/mod.d.ts +2 -0
- package/script/fsm-api-ts/mod.js +10 -0
- package/script/fsm-api-ts/src/cli/version.node.d.ts +1 -0
- package/script/fsm-api-ts/src/cli/version.node.js +5 -0
- package/script/package.json +3 -0
- package/README.md +0 -3
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { cors } from "hono/cors";
|
|
2
|
+
import { getLogger } from "@logtape/logtape";
|
|
3
|
+
// @ts-types="@types/pg"
|
|
4
|
+
import { Pool } from "pg";
|
|
5
|
+
import { requestId } from "hono/request-id";
|
|
6
|
+
import { notFound, onError, serveEmojiFavicon, } from "../stoker-src/middlewares/index.js";
|
|
7
|
+
import configureOpenAPI from "./configure-open-api.js";
|
|
8
|
+
import { licenseNotice } from "./license.js";
|
|
9
|
+
import { createRouter } from "./create-router.js";
|
|
10
|
+
// import { pinoLogger } from "./../middlewares/pino-logger.ts";
|
|
11
|
+
import { logtapeLogger } from "../middlewares/logtape-logger.js";
|
|
12
|
+
import { otelTrace } from "../middlewares/otel-trace.js";
|
|
13
|
+
import { apiKeyAuth } from "../middlewares/api-key-auth.js";
|
|
14
|
+
import { supabaseMiddleware } from "../middlewares/supabase.js";
|
|
15
|
+
import env from "../env.js";
|
|
16
|
+
import { createIndexRouter } from "../routes/index.route.js";
|
|
17
|
+
import instances from "../routes/instances/instances.index.js";
|
|
18
|
+
import admin from "../routes/admin/admin.index.js";
|
|
19
|
+
import definitions from "../routes/definitions/definitions.index.js";
|
|
20
|
+
export { createRouter };
|
|
21
|
+
const logger = getLogger(["@pgfsm/api", "app"]);
|
|
22
|
+
/**
|
|
23
|
+
* The REST API. It only serves HTTP: fsmlets run as separate worker
|
|
24
|
+
* processes (root CLAUDE.md #3; the API used to embed one, which stopped
|
|
25
|
+
* compiling once the fsmlet moved to compiled registries in #341).
|
|
26
|
+
*/
|
|
27
|
+
export default async function createApp(basePath = "", options = {}) {
|
|
28
|
+
const auth = options.auth ?? !env.PGFSM_NO_AUTH;
|
|
29
|
+
const adminApi = options.adminApi ?? env.PGFSM_ENABLE_ADMIN_API;
|
|
30
|
+
const authCacheTtlMs = options.authCacheTtlMs ??
|
|
31
|
+
env.PGFSM_AUTH_CACHE_TTL_MS;
|
|
32
|
+
if (!auth && env.NODE_ENV === "production") {
|
|
33
|
+
throw new Error("createApp: --no-auth / PGFSM_NO_AUTH is for local development and refused when NODE_ENV=production");
|
|
34
|
+
}
|
|
35
|
+
if (auth && env.DB_TYPE !== "postgres") {
|
|
36
|
+
throw new Error(`createApp: API-key auth needs DB_TYPE=postgres (got ${env.DB_TYPE}); the Supabase client path doesn't run requests under the key's role yet`);
|
|
37
|
+
}
|
|
38
|
+
const pool = options.pool ??
|
|
39
|
+
new Pool({ connectionString: env.DATABASE_URL });
|
|
40
|
+
pool.on("connect", () => {
|
|
41
|
+
logger.debug("Database pool: new connection established");
|
|
42
|
+
});
|
|
43
|
+
pool.on("error", (err) => {
|
|
44
|
+
logger.error("Database pool error: {error}", { error: err });
|
|
45
|
+
});
|
|
46
|
+
await checkPoolLogin(pool, { auth, adminApi });
|
|
47
|
+
const app = createRouter();
|
|
48
|
+
const otelEnabled = env.OTEL_DENO === "true" &&
|
|
49
|
+
!!env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
50
|
+
// app.use(requestId()).use(serveEmojiFavicon("📝")).use(pinoLogger());
|
|
51
|
+
app.use(requestId()).use(serveEmojiFavicon("📝")).use(logtapeLogger());
|
|
52
|
+
if (otelEnabled)
|
|
53
|
+
app.use(otelTrace());
|
|
54
|
+
app.use("*", (c, next) => {
|
|
55
|
+
const corsMiddlewareHandler = cors({
|
|
56
|
+
origin: env.CORS_ORIGIN,
|
|
57
|
+
});
|
|
58
|
+
return corsMiddlewareHandler(c, next);
|
|
59
|
+
});
|
|
60
|
+
if (auth) {
|
|
61
|
+
// Each request runs in withRole(key's role); the middleware sets `db` to
|
|
62
|
+
// that transaction. Routes outside these paths (index, docs) get no db.
|
|
63
|
+
const operator = apiKeyAuth({
|
|
64
|
+
pool,
|
|
65
|
+
requiredRole: "fsm_operator",
|
|
66
|
+
cacheTtlMs: authCacheTtlMs,
|
|
67
|
+
});
|
|
68
|
+
app.use("/instances", operator);
|
|
69
|
+
app.use("/instances/*", operator);
|
|
70
|
+
app.use("/definitions", operator);
|
|
71
|
+
app.use("/definitions/*", operator);
|
|
72
|
+
if (adminApi) {
|
|
73
|
+
app.use("/admin/*", apiKeyAuth({
|
|
74
|
+
pool,
|
|
75
|
+
requiredRole: "fsm_admin",
|
|
76
|
+
cacheTtlMs: authCacheTtlMs,
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
logger.warn("API-key auth is OFF (--no-auth): every request runs as the pool's login role. Local development only.");
|
|
82
|
+
if (env.DB_TYPE === "supabase") {
|
|
83
|
+
app.use("*", supabaseMiddleware());
|
|
84
|
+
}
|
|
85
|
+
else if (env.DB_TYPE === "postgres") {
|
|
86
|
+
app.use("*", (c, next) => {
|
|
87
|
+
c.set("db", pool);
|
|
88
|
+
return next();
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
else if (env.DB_TYPE === "supabase_and_postgres") {
|
|
92
|
+
app.use("*", supabaseMiddleware());
|
|
93
|
+
app.use("*", (c, next) => {
|
|
94
|
+
c.set("db", pool);
|
|
95
|
+
return next();
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
app.notFound(notFound);
|
|
100
|
+
app.onError(onError);
|
|
101
|
+
const notice = licenseNotice(env.PGFSM_SOURCE_URL);
|
|
102
|
+
const index = createIndexRouter(notice);
|
|
103
|
+
const routes = adminApi
|
|
104
|
+
? [index, instances, definitions, admin]
|
|
105
|
+
: [index, instances, definitions];
|
|
106
|
+
routes.forEach((route) => {
|
|
107
|
+
app.route("/", route);
|
|
108
|
+
});
|
|
109
|
+
configureOpenAPI(app, basePath, notice);
|
|
110
|
+
logger.info("API ready: auth {auth}, admin API {admin}; licence {license}, source {source}", {
|
|
111
|
+
auth: auth ? "on" : "OFF",
|
|
112
|
+
admin: adminApi ? "on" : "off",
|
|
113
|
+
license: notice.license,
|
|
114
|
+
source: notice.source,
|
|
115
|
+
});
|
|
116
|
+
return app;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Startup checks on the pool's login (SPEC-009 §3): with the admin API on it
|
|
120
|
+
* must be able to become fsm_admin, or every admin request would fail at its
|
|
121
|
+
* first query; with auth on, a login that inherits privileges (rather than an
|
|
122
|
+
* fsm_authenticator-style NOINHERIT one) works but holds rights of its own.
|
|
123
|
+
*/
|
|
124
|
+
async function checkPoolLogin(pool, { auth, adminApi }) {
|
|
125
|
+
if (!auth)
|
|
126
|
+
return;
|
|
127
|
+
const { rows: [login] } = await pool.query(`SELECT session_user AS login,
|
|
128
|
+
r.rolinherit AS inherits,
|
|
129
|
+
pg_has_role(session_user, 'fsm_admin', 'MEMBER') AS can_admin
|
|
130
|
+
FROM pg_roles r WHERE r.rolname = session_user`);
|
|
131
|
+
if (adminApi && !login.can_admin) {
|
|
132
|
+
throw new Error(`createApp: the admin API is on but the API's database login ${login.login} can't act as fsm_admin. Run: GRANT fsm_admin TO ${login.login};`);
|
|
133
|
+
}
|
|
134
|
+
if (login.inherits) {
|
|
135
|
+
logger.warn("The API's database login {login} inherits privileges. Requests still run under the API key's role, but in production log in as fsm_authenticator (NOINHERIT), so the process holds no rights of its own.", { login: login.login });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import { defaultHook } from "../stoker-src/openapi/index.js";
|
|
3
|
+
// Kept apart from create-app.ts (which reads env.ts at import time) so route
|
|
4
|
+
// modules can be imported, and tested, without the API's environment.
|
|
5
|
+
export function createRouter() {
|
|
6
|
+
return new OpenAPIHono({
|
|
7
|
+
strict: false,
|
|
8
|
+
defaultHook,
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The SPDX identifier of @pgfsm/api's licence. */
|
|
2
|
+
export declare const LICENSE_SPDX = "AGPL-3.0-only";
|
|
3
|
+
/** The licence text. */
|
|
4
|
+
export declare const LICENSE_URL = "https://www.gnu.org/licenses/agpl-3.0.html";
|
|
5
|
+
/** The unmodified API's source; PGFSM_SOURCE_URL overrides it. */
|
|
6
|
+
export declare const DEFAULT_SOURCE_URL = "https://github.com/pgfsm/fsm";
|
|
7
|
+
export interface LicenseNotice {
|
|
8
|
+
/** SPDX identifier, e.g. AGPL-3.0-only. */
|
|
9
|
+
license: string;
|
|
10
|
+
/** Where the source of the running API can be obtained. */
|
|
11
|
+
source: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function licenseNotice(source?: string): LicenseNotice;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The API's licence notice (SPEC-017). @pgfsm/api is AGPL-3.0-only, and
|
|
2
|
+
// AGPL-3.0 §13 obliges whoever runs a modified version to offer its source to
|
|
3
|
+
// the users who interact with it over a network. GET / and the OpenAPI
|
|
4
|
+
// document report the licence and where the source is; PGFSM_SOURCE_URL
|
|
5
|
+
// points that at a modified version's own source. Kept free of env.ts so route
|
|
6
|
+
// modules stay importable (and testable) without the API's environment.
|
|
7
|
+
/** The SPDX identifier of @pgfsm/api's licence. */
|
|
8
|
+
export const LICENSE_SPDX = "AGPL-3.0-only";
|
|
9
|
+
/** The licence text. */
|
|
10
|
+
export const LICENSE_URL = "https://www.gnu.org/licenses/agpl-3.0.html";
|
|
11
|
+
/** The unmodified API's source; PGFSM_SOURCE_URL overrides it. */
|
|
12
|
+
export const DEFAULT_SOURCE_URL = "https://github.com/pgfsm/fsm";
|
|
13
|
+
export function licenseNotice(source = DEFAULT_SOURCE_URL) {
|
|
14
|
+
return { license: LICENSE_SPDX, source };
|
|
15
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { OpenAPIHono, RouteConfig, RouteHandler } from "@hono/zod-openapi";
|
|
2
|
+
import type { Schema } from "hono";
|
|
3
|
+
import type { Pool } from "pg";
|
|
4
|
+
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
5
|
+
import type { Database } from "../../fsm-core-db-ts/src/database.types.js";
|
|
6
|
+
import type { ApiKeyRole } from "@pgfsm/db";
|
|
7
|
+
export interface AppBindings {
|
|
8
|
+
Bindings: {
|
|
9
|
+
MY_DB: unknown;
|
|
10
|
+
};
|
|
11
|
+
Variables: {
|
|
12
|
+
db: Pool;
|
|
13
|
+
supabase: SupabaseClient<Database>;
|
|
14
|
+
/** The API key's role; unset when auth is off (--no-auth). */
|
|
15
|
+
role: ApiKeyRole | undefined;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export type AppOpenAPI<S extends Schema = Record<PropertyKey, never>> = OpenAPIHono<AppBindings, S>;
|
|
19
|
+
export type AppRouteHandler<R extends RouteConfig> = RouteHandler<R, AppBindings>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CATEGORY, configureLogging } from "@pgfsm/logging";
|
|
2
|
+
import env from "./env.js";
|
|
3
|
+
// Composition root for the API process: resolves levels from the validated env
|
|
4
|
+
// (per-category overrides falling back to LOG_LEVEL) and configures LogTape
|
|
5
|
+
// once. The API process also hosts db/worker/compiler code, so it surfaces
|
|
6
|
+
// those categories too.
|
|
7
|
+
export async function configureApiLogger() {
|
|
8
|
+
const defaultLevel = env.LOG_LEVEL;
|
|
9
|
+
const otelEnabled = env.OTEL_DENO === "true" &&
|
|
10
|
+
!!env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
11
|
+
await configureLogging({
|
|
12
|
+
levels: {
|
|
13
|
+
[CATEGORY.api]: (env.LOG_LEVEL_API ?? defaultLevel),
|
|
14
|
+
[CATEGORY.worker]: (env.LOG_LEVEL_WORKER ?? defaultLevel),
|
|
15
|
+
[CATEGORY.compiler]: (env.LOG_LEVEL_COMPILER ?? defaultLevel),
|
|
16
|
+
[CATEGORY.db]: (env.LOG_LEVEL_DB ?? defaultLevel),
|
|
17
|
+
},
|
|
18
|
+
otel: otelEnabled,
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import type { Pool } from "pg";
|
|
3
|
+
import { type ApiKeyRole } from "@pgfsm/db";
|
|
4
|
+
export type ApiKeyAuthOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Pool that verifies keys and runs the request. Its login needs EXECUTE on
|
|
7
|
+
* fsm_core.verify_api_key and membership in each role it serves:
|
|
8
|
+
* fsm_authenticator (+ fsm_admin where the admin API is on), or the schema
|
|
9
|
+
* owner in development (SPEC-009 §1).
|
|
10
|
+
*/
|
|
11
|
+
pool: Pool;
|
|
12
|
+
/**
|
|
13
|
+
* Lowest role the route accepts. "fsm_operator" also accepts admin keys
|
|
14
|
+
* (fsm_admin is a member of fsm_operator); "fsm_admin" accepts only them.
|
|
15
|
+
*/
|
|
16
|
+
requiredRole: ApiKeyRole;
|
|
17
|
+
/**
|
|
18
|
+
* How long a verification result is reused, in ms. It's also the upper
|
|
19
|
+
* bound on how long a revoked key keeps working. 0 disables the cache.
|
|
20
|
+
*/
|
|
21
|
+
cacheTtlMs: number;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* SPEC-009 §3. Reads `Authorization: Bearer <key>`, verifies the key's SHA-256
|
|
25
|
+
* with fsm_core.verify_api_key, then runs the rest of the request inside
|
|
26
|
+
* withRole(key's role): one transaction under SET LOCAL ROLE, with `db` set to
|
|
27
|
+
* that transaction, so Postgres grants decide what the handler can do.
|
|
28
|
+
*
|
|
29
|
+
* - Missing or malformed header, unknown or revoked key → 401.
|
|
30
|
+
* - An operator key on an admin route → 403.
|
|
31
|
+
* - The transaction rolls back when the handler throws or answers 5xx, and
|
|
32
|
+
* commits otherwise.
|
|
33
|
+
*/
|
|
34
|
+
export declare function apiKeyAuth(options: ApiKeyAuthOptions): MiddlewareHandler;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { getLogger } from "@logtape/logtape";
|
|
2
|
+
import { hashApiKey, verifyApiKey, withRole } from "@pgfsm/db";
|
|
3
|
+
import { FORBIDDEN, UNAUTHORIZED } from "../stoker-src/http-status-codes.js";
|
|
4
|
+
const logger = getLogger(["@pgfsm/api", "auth"]);
|
|
5
|
+
/** Thrown inside withRole to roll back without changing the response. */
|
|
6
|
+
class RollbackRequest extends Error {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* SPEC-009 §3. Reads `Authorization: Bearer <key>`, verifies the key's SHA-256
|
|
10
|
+
* with fsm_core.verify_api_key, then runs the rest of the request inside
|
|
11
|
+
* withRole(key's role): one transaction under SET LOCAL ROLE, with `db` set to
|
|
12
|
+
* that transaction, so Postgres grants decide what the handler can do.
|
|
13
|
+
*
|
|
14
|
+
* - Missing or malformed header, unknown or revoked key → 401.
|
|
15
|
+
* - An operator key on an admin route → 403.
|
|
16
|
+
* - The transaction rolls back when the handler throws or answers 5xx, and
|
|
17
|
+
* commits otherwise.
|
|
18
|
+
*/
|
|
19
|
+
export function apiKeyAuth(options) {
|
|
20
|
+
const { pool, requiredRole, cacheTtlMs } = options;
|
|
21
|
+
const cache = new Map();
|
|
22
|
+
const verify = async (keyHash) => {
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
const hit = cache.get(keyHash);
|
|
25
|
+
if (hit && hit.expiresAt > now)
|
|
26
|
+
return hit.role;
|
|
27
|
+
const role = await verifyApiKey({ db: pool, useSupabase: false }, keyHash);
|
|
28
|
+
if (cacheTtlMs > 0) {
|
|
29
|
+
cache.set(keyHash, { role, expiresAt: now + cacheTtlMs });
|
|
30
|
+
// Keep the map bounded: drop expired entries now and then.
|
|
31
|
+
if (cache.size > 1000) {
|
|
32
|
+
for (const [k, v] of cache)
|
|
33
|
+
if (v.expiresAt <= now)
|
|
34
|
+
cache.delete(k);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return role;
|
|
38
|
+
};
|
|
39
|
+
return async (c, next) => {
|
|
40
|
+
const header = c.req.header("Authorization") ?? "";
|
|
41
|
+
const match = /^Bearer\s+(\S+)\s*$/i.exec(header);
|
|
42
|
+
if (!match) {
|
|
43
|
+
return c.json({ message: "Missing API key: send Authorization: Bearer <key>" }, UNAUTHORIZED);
|
|
44
|
+
}
|
|
45
|
+
const role = await verify(await hashApiKey(match[1]));
|
|
46
|
+
if (!role) {
|
|
47
|
+
return c.json({ message: "Invalid or revoked API key" }, UNAUTHORIZED);
|
|
48
|
+
}
|
|
49
|
+
if (requiredRole === "fsm_admin" && role !== "fsm_admin") {
|
|
50
|
+
return c.json({ message: "This route needs an admin key" }, FORBIDDEN);
|
|
51
|
+
}
|
|
52
|
+
c.set("role", role);
|
|
53
|
+
try {
|
|
54
|
+
await withRole({ db: pool, useSupabase: false }, role, async (deps) => {
|
|
55
|
+
c.set("db", deps.db);
|
|
56
|
+
await next();
|
|
57
|
+
// Hono turns a handler's throw into c.error + an onError response
|
|
58
|
+
// without rejecting next(), so check both before committing.
|
|
59
|
+
if (c.error || c.res.status >= 500)
|
|
60
|
+
throw new RollbackRequest();
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof RollbackRequest)
|
|
65
|
+
return; // response already set
|
|
66
|
+
logger.error("Request transaction failed: {error}", { error });
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { honoLogger } from "@logtape/hono";
|
|
2
|
+
// @logtape/hono provides an official Hono middleware that:
|
|
3
|
+
// - Logs HTTP access records (method, path, status, responseTime) via LogTape
|
|
4
|
+
// - `context.requestId` reads x-request-id from incoming headers (or generates
|
|
5
|
+
// a UUID), writes it back in the response header, and calls LogTape's
|
|
6
|
+
// withContext() so every log record emitted anywhere during the request
|
|
7
|
+
// automatically carries requestId without explicit propagation.
|
|
8
|
+
export function logtapeLogger() {
|
|
9
|
+
return honoLogger({
|
|
10
|
+
// Route all HTTP access logs under @pgfsm/api so they share the same
|
|
11
|
+
// configured sink as the rest of the app.
|
|
12
|
+
category: ["@pgfsm/api", "http"],
|
|
13
|
+
// Structured object per request — logged as:
|
|
14
|
+
// "{method} {url} {status} - {responseTime} ms"
|
|
15
|
+
// with method, path, status, responseTime, contentLength, userAgent,
|
|
16
|
+
// referrer also available as structured properties on the log record.
|
|
17
|
+
format: "structured-combined",
|
|
18
|
+
// Per-request implicit context via withContext(): reads / generates
|
|
19
|
+
// x-request-id and makes it available on every LogTape record emitted
|
|
20
|
+
// during the request — including deep library and DB calls.
|
|
21
|
+
context: {
|
|
22
|
+
requestId: {
|
|
23
|
+
headerNames: ["x-request-id"],
|
|
24
|
+
responseHeader: "x-request-id",
|
|
25
|
+
},
|
|
26
|
+
include: ["requestId", "method", "path"],
|
|
27
|
+
},
|
|
28
|
+
skip: (c) => c.req.path === "/favicon.ico",
|
|
29
|
+
// @logtape/hono resolves Hono from jsr (@hono/hono) while this app uses the
|
|
30
|
+
// npm `hono` build; the MiddlewareHandler types are structurally identical
|
|
31
|
+
// but nominally distinct across registries, so bridge them here.
|
|
32
|
+
});
|
|
33
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { SpanStatusCode, trace } from "@opentelemetry/api";
|
|
2
|
+
const tracer = trace.getTracer("pgfsm-api");
|
|
3
|
+
export function otelTrace() {
|
|
4
|
+
return async (c, next) => {
|
|
5
|
+
const method = c.req.method;
|
|
6
|
+
const path = c.req.path;
|
|
7
|
+
await tracer.startActiveSpan(`${method} ${path}`, async (span) => {
|
|
8
|
+
span.setAttributes({
|
|
9
|
+
"http.request.method": method,
|
|
10
|
+
"url.path": path,
|
|
11
|
+
});
|
|
12
|
+
try {
|
|
13
|
+
await next();
|
|
14
|
+
const route = c.req.routePath ?? path;
|
|
15
|
+
span.updateName(`${method} ${route}`);
|
|
16
|
+
span.setAttribute("http.route", route);
|
|
17
|
+
span.setAttribute("http.response.status_code", c.res.status);
|
|
18
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: String(e) });
|
|
22
|
+
throw e;
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
span.end();
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
3
|
+
import type { Database } from "../../fsm-core-db-ts/src/database.types.js";
|
|
4
|
+
declare module "hono" {
|
|
5
|
+
interface ContextVariableMap {
|
|
6
|
+
supabase: SupabaseClient;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export declare const supabaseMiddleware: () => MiddlewareHandler;
|
|
10
|
+
export declare const getSupabase: (c: Context) => SupabaseClient<Database>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createServerClient, parseCookieHeader } from "@supabase/ssr";
|
|
2
|
+
import { env } from "hono/adapter";
|
|
3
|
+
import { setCookie } from "hono/cookie";
|
|
4
|
+
export const supabaseMiddleware = () => {
|
|
5
|
+
return async (c, next) => {
|
|
6
|
+
const supabaseEnv = env(c);
|
|
7
|
+
const supabaseUrl = supabaseEnv.SUPABASE_URL;
|
|
8
|
+
const supabaseAnonKey = supabaseEnv.SUPABASE_ANON_KEY;
|
|
9
|
+
if (!supabaseUrl) {
|
|
10
|
+
throw new Error("SUPABASE_URL missing!");
|
|
11
|
+
}
|
|
12
|
+
if (!supabaseAnonKey) {
|
|
13
|
+
throw new Error("SUPABASE_ANON_KEY missing!");
|
|
14
|
+
}
|
|
15
|
+
const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
|
|
16
|
+
db: {
|
|
17
|
+
schema: "fsm_core", // Specify your custom schema name here
|
|
18
|
+
},
|
|
19
|
+
cookies: {
|
|
20
|
+
getAll() {
|
|
21
|
+
return parseCookieHeader(c.req.header("Cookie") ?? "");
|
|
22
|
+
},
|
|
23
|
+
setAll(cookiesToSet) {
|
|
24
|
+
cookiesToSet.forEach(({ name, value, options }) => setCookie(c, name, value, options));
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
c.set("supabase", supabase);
|
|
29
|
+
await next();
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
export const getSupabase = (c) => {
|
|
33
|
+
return c.get("supabase");
|
|
34
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// @pgfsm/api's library export (SPEC-016, #689): the package is mainly the
|
|
2
|
+
// `pgfsm-api` bin (src/cli/index.ts). This exports its version only;
|
|
3
|
+
// createApp() reads the process environment at import (env.ts), so it isn't
|
|
4
|
+
// a library entry point.
|
|
5
|
+
import "../_dnt.polyfills.js";
|
|
6
|
+
export { PACKAGE_VERSION } from "./src/cli/version.node.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AppRouteHandler } from "../../lib/types.js";
|
|
2
|
+
import type { CreateKeyRoute, GetSchedulerRoute, ListKeysRoute, LoadDefinitionsRoute, RegisterSchedulerRoute, RevokeKeyRoute } from "./admin.routes.js";
|
|
3
|
+
export declare const loadDefinitions: AppRouteHandler<LoadDefinitionsRoute>;
|
|
4
|
+
export declare const listKeys: AppRouteHandler<ListKeysRoute>;
|
|
5
|
+
export declare const createKey: AppRouteHandler<CreateKeyRoute>;
|
|
6
|
+
export declare const revokeKey: AppRouteHandler<RevokeKeyRoute>;
|
|
7
|
+
export declare const getScheduler: AppRouteHandler<GetSchedulerRoute>;
|
|
8
|
+
export declare const registerScheduler: AppRouteHandler<RegisterSchedulerRoute>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import * as HttpStatusCodes from "../../stoker-src/http-status-codes.js";
|
|
2
|
+
import { getLogger } from "@logtape/logtape";
|
|
3
|
+
import { createApiKey, FsmDefinitionLoadError, listApiKeys, loadFsmDefinitions, registerSchedulerJob, revokeApiKey, schedulerJobStatus, } from "@pgfsm/db";
|
|
4
|
+
const logger = getLogger(["@pgfsm/api", "admin"]);
|
|
5
|
+
/** The Postgres SQLSTATE of an error (or its cause), if any. */
|
|
6
|
+
const sqlState = (err) => {
|
|
7
|
+
for (let e = err; e && typeof e === "object"; e = e.cause) {
|
|
8
|
+
const code = e.code;
|
|
9
|
+
if (typeof code === "string")
|
|
10
|
+
return code;
|
|
11
|
+
}
|
|
12
|
+
return undefined;
|
|
13
|
+
};
|
|
14
|
+
// Handlers run inside the auth middleware's withRole(fsm_admin) transaction:
|
|
15
|
+
// c.get("db") is that transaction, so Postgres grants are what's enforced.
|
|
16
|
+
export const loadDefinitions = async (c) => {
|
|
17
|
+
const deps = { db: c.get("db"), useSupabase: false };
|
|
18
|
+
const { definitions } = c.req.valid("json");
|
|
19
|
+
try {
|
|
20
|
+
const data = await loadFsmDefinitions(deps, definitions.map((d) => ({ ...d, fsmJson: d.fsmJson })));
|
|
21
|
+
logger.info("Loaded {count} FSM definition(s)", { count: data.length });
|
|
22
|
+
return c.json({ data }, HttpStatusCodes.OK);
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
if (!(err instanceof FsmDefinitionLoadError))
|
|
26
|
+
throw err;
|
|
27
|
+
if (sqlState(err) === "42501") {
|
|
28
|
+
return c.json({ message: "Permission denied", problems: err.problems }, HttpStatusCodes.FORBIDDEN);
|
|
29
|
+
}
|
|
30
|
+
return c.json({ message: "FSM definitions not loaded", problems: err.problems }, HttpStatusCodes.UNPROCESSABLE_ENTITY);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
export const listKeys = async (c) => {
|
|
34
|
+
const rows = await listApiKeys({ db: c.get("db"), useSupabase: false });
|
|
35
|
+
const iso = (d) => d?.toISOString() ?? null;
|
|
36
|
+
return c.json({
|
|
37
|
+
data: rows.map((r) => ({
|
|
38
|
+
...r,
|
|
39
|
+
created_at: r.created_at.toISOString(),
|
|
40
|
+
last_used_at: iso(r.last_used_at),
|
|
41
|
+
revoked_at: iso(r.revoked_at),
|
|
42
|
+
})),
|
|
43
|
+
}, HttpStatusCodes.OK);
|
|
44
|
+
};
|
|
45
|
+
export const createKey = async (c) => {
|
|
46
|
+
const { name, role } = c.req.valid("json");
|
|
47
|
+
try {
|
|
48
|
+
const data = await createApiKey({ db: c.get("db"), useSupabase: false }, name, role);
|
|
49
|
+
logger.info("Created {role} API key {name} ({prefix})", {
|
|
50
|
+
role,
|
|
51
|
+
name,
|
|
52
|
+
prefix: data.prefix,
|
|
53
|
+
});
|
|
54
|
+
return c.json({ data }, HttpStatusCodes.CREATED);
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
if (sqlState(err) === "23505") {
|
|
58
|
+
return c.json({ message: `An API key named ${JSON.stringify(name)} exists` }, HttpStatusCodes.CONFLICT);
|
|
59
|
+
}
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
export const revokeKey = async (c) => {
|
|
64
|
+
const { idOrName } = c.req.valid("param");
|
|
65
|
+
const revoked = await revokeApiKey({ db: c.get("db"), useSupabase: false }, idOrName);
|
|
66
|
+
if (!revoked) {
|
|
67
|
+
return c.json({ message: "No live API key with that id or name" }, HttpStatusCodes.NOT_FOUND);
|
|
68
|
+
}
|
|
69
|
+
logger.info("Revoked API key {idOrName}", { idOrName });
|
|
70
|
+
return c.json({ data: { revoked: true } }, HttpStatusCodes.OK);
|
|
71
|
+
};
|
|
72
|
+
export const getScheduler = async (c) => {
|
|
73
|
+
const data = await schedulerJobStatus({
|
|
74
|
+
db: c.get("db"),
|
|
75
|
+
useSupabase: false,
|
|
76
|
+
});
|
|
77
|
+
return c.json({ data }, HttpStatusCodes.OK);
|
|
78
|
+
};
|
|
79
|
+
export const registerScheduler = async (c) => {
|
|
80
|
+
// The body is optional: an empty POST registers the default schedule.
|
|
81
|
+
const body = await c.req.json().catch(() => ({}));
|
|
82
|
+
if (body.schedule !== undefined &&
|
|
83
|
+
(typeof body.schedule !== "string" || body.schedule === "")) {
|
|
84
|
+
return c.json({ message: "schedule must be a non-empty string" }, HttpStatusCodes.UNPROCESSABLE_ENTITY);
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
const data = await registerSchedulerJob({ db: c.get("db"), useSupabase: false }, body.schedule);
|
|
88
|
+
return c.json({ data }, HttpStatusCodes.OK);
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
// pg_cron raises a plain error for a schedule it can't parse.
|
|
92
|
+
const message = err.message ?? "";
|
|
93
|
+
if (/schedule/i.test(message) && sqlState(err) !== "42501") {
|
|
94
|
+
return c.json({ message }, HttpStatusCodes.UNPROCESSABLE_ENTITY);
|
|
95
|
+
}
|
|
96
|
+
throw err;
|
|
97
|
+
}
|
|
98
|
+
};
|