@formancy/server 0.1.0 → 0.2.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/dist/file-collector-WWc-eo8h.mjs +1464 -0
- package/dist/file-collector-WWc-eo8h.mjs.map +1 -0
- package/dist/index.d.mts +138 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/main.mjs +458 -4
- package/dist/main.mjs.map +1 -1
- package/package.json +10 -6
- package/dist/postgres-storage-UMh8A-4C.mjs +0 -599
- package/dist/postgres-storage-UMh8A-4C.mjs.map +0 -1
|
@@ -1,599 +0,0 @@
|
|
|
1
|
-
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
-
import Fastify from "fastify";
|
|
3
|
-
import { authenticateApiKey, authenticateLocal, can, createApiKey, createLocalUser, createSubmission, exportCsv, listForms, listSubmissions, listVersions, publishForm, resolveForm, resumeDraft, saveDraft } from "@formancy/server-core";
|
|
4
|
-
import { hash, verify } from "@node-rs/argon2";
|
|
5
|
-
import { SignJWT, jwtVerify } from "jose";
|
|
6
|
-
import { and, desc, eq, max } from "drizzle-orm";
|
|
7
|
-
import { drizzle } from "drizzle-orm/postgres-js";
|
|
8
|
-
import { integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
|
9
|
-
//#region src/auth-runtime.ts
|
|
10
|
-
/**
|
|
11
|
-
* The real cryptography, confined to the composition root: argon2id for
|
|
12
|
-
* secrets at rest, an HMAC-signed short-lived access token for sessions, and
|
|
13
|
-
* a CSPRNG for API keys. server-core never sees any of this — it is handed
|
|
14
|
-
* hash/verify/random functions and stays deterministic under test.
|
|
15
|
-
*
|
|
16
|
-
* HS256 rather than EdDSA for the session token, deliberately for this phase:
|
|
17
|
-
* one secret in one env var is the self-hosting story a single-container
|
|
18
|
-
* deployment can operate, and the signing scheme is an implementation detail
|
|
19
|
-
* of a token that lives fifteen minutes. Revisit with key rotation.
|
|
20
|
-
*/
|
|
21
|
-
function realSecretHashing() {
|
|
22
|
-
return {
|
|
23
|
-
hashSecret: (secret) => hash(secret),
|
|
24
|
-
verifySecret: async (secret, digest) => {
|
|
25
|
-
try {
|
|
26
|
-
return await verify(digest, secret);
|
|
27
|
-
} catch {
|
|
28
|
-
return false;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
function realRandomToken() {
|
|
34
|
-
return randomBytes(30).toString("base64url");
|
|
35
|
-
}
|
|
36
|
-
const TOKEN_LIFETIME = "15m";
|
|
37
|
-
function createSessionTokens(secret) {
|
|
38
|
-
if (secret.length < 32) throw new Error("FORMANCY_AUTH_SECRET must be at least 32 characters. Generate one: openssl rand -base64 33");
|
|
39
|
-
const key = new TextEncoder().encode(secret);
|
|
40
|
-
return {
|
|
41
|
-
async issue(actor) {
|
|
42
|
-
return new SignJWT({
|
|
43
|
-
role: actor.role,
|
|
44
|
-
kind: actor.kind
|
|
45
|
-
}).setProtectedHeader({ alg: "HS256" }).setSubject(actor.id).setIssuedAt().setExpirationTime(TOKEN_LIFETIME).sign(key);
|
|
46
|
-
},
|
|
47
|
-
async verify(token) {
|
|
48
|
-
try {
|
|
49
|
-
const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"] });
|
|
50
|
-
const role = payload["role"];
|
|
51
|
-
const kind = payload["kind"];
|
|
52
|
-
if (typeof payload.sub !== "string" || role !== "admin" && role !== "editor" && role !== "viewer" || kind !== "user" && kind !== "apiKey") return;
|
|
53
|
-
return {
|
|
54
|
-
id: payload.sub,
|
|
55
|
-
role,
|
|
56
|
-
kind
|
|
57
|
-
};
|
|
58
|
-
} catch {
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
//#endregion
|
|
65
|
-
//#region src/app.ts
|
|
66
|
-
const SCHEMA_HASH_HEADER = "x-formancy-schema-hash";
|
|
67
|
-
const API_KEY_HEADER = "x-formancy-api-key";
|
|
68
|
-
/**
|
|
69
|
-
* The HTTP surface, split into two planes.
|
|
70
|
-
*
|
|
71
|
-
* PUBLIC — what a person filling a form needs: resolve, submit, drafts. These
|
|
72
|
-
* stay unauthenticated by design; anonymous-submission hardening is its own
|
|
73
|
-
* upcoming step and is opt-in per form.
|
|
74
|
-
*
|
|
75
|
-
* MANAGEMENT — everything an operator does: publish, catalog, submissions,
|
|
76
|
-
* export, users, keys. Authenticated via a session token (login) or an API
|
|
77
|
-
* key header, authorized through server-core's one-table can().
|
|
78
|
-
*
|
|
79
|
-
* This file is the composition root, so THIS is where ambient reality enters:
|
|
80
|
-
* randomUUID, the real clock, argon2 and the CSPRNG. Everything below stays
|
|
81
|
-
* injected and replayable.
|
|
82
|
-
*/
|
|
83
|
-
async function createApp(storage, options) {
|
|
84
|
-
const app = Fastify({ logger: false });
|
|
85
|
-
const deps = {
|
|
86
|
-
storage,
|
|
87
|
-
newId: () => randomUUID(),
|
|
88
|
-
nowIso: () => (/* @__PURE__ */ new Date()).toISOString(),
|
|
89
|
-
capabilities: {
|
|
90
|
-
now: () => Date.now(),
|
|
91
|
-
today: () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
|
|
92
|
-
random: () => Math.random()
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
const authDeps = {
|
|
96
|
-
storage,
|
|
97
|
-
newId: deps.newId,
|
|
98
|
-
nowIso: deps.nowIso,
|
|
99
|
-
randomToken: realRandomToken,
|
|
100
|
-
...realSecretHashing()
|
|
101
|
-
};
|
|
102
|
-
const sessions = createSessionTokens(options.authSecret);
|
|
103
|
-
if (options.bootstrapAdmin !== void 0) {
|
|
104
|
-
if (await storage.getUserByEmail(options.bootstrapAdmin.email) === void 0) {
|
|
105
|
-
const outcome = await createLocalUser(authDeps, {
|
|
106
|
-
...options.bootstrapAdmin,
|
|
107
|
-
role: "admin"
|
|
108
|
-
});
|
|
109
|
-
if (!outcome.ok) throw new Error(`Bootstrap admin rejected: ${outcome.message}`);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
async function actorOf(request) {
|
|
113
|
-
const bearer = request.headers.authorization;
|
|
114
|
-
if (typeof bearer === "string" && bearer.startsWith("Bearer ")) return sessions.verify(bearer.slice(7));
|
|
115
|
-
const apiKey = request.headers[API_KEY_HEADER];
|
|
116
|
-
if (typeof apiKey === "string" && apiKey !== "") {
|
|
117
|
-
const outcome = await authenticateApiKey(authDeps, apiKey);
|
|
118
|
-
return outcome.ok ? outcome.actor : void 0;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
/** 401 without an identity, 403 with one that lacks the permission — the
|
|
122
|
-
* difference tells a client whether to log in or to give up. */
|
|
123
|
-
function requires(action) {
|
|
124
|
-
return async (request, reply) => {
|
|
125
|
-
const actor = await actorOf(request);
|
|
126
|
-
if (actor === void 0) return reply.code(401).send({ error: "unauthenticated" });
|
|
127
|
-
if (!can(actor, action)) return reply.code(403).send({
|
|
128
|
-
error: "forbidden",
|
|
129
|
-
action
|
|
130
|
-
});
|
|
131
|
-
request.actor = actor;
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
app.post("/auth/login", async (request, reply) => {
|
|
135
|
-
const body = request.body;
|
|
136
|
-
if (body === null || typeof body.email !== "string" || typeof body.password !== "string") return reply.code(400).send({
|
|
137
|
-
error: "bad_request",
|
|
138
|
-
message: "Body needs { email, password }."
|
|
139
|
-
});
|
|
140
|
-
const outcome = await authenticateLocal(authDeps, {
|
|
141
|
-
email: body.email,
|
|
142
|
-
password: body.password
|
|
143
|
-
});
|
|
144
|
-
if (!outcome.ok) return reply.code(401).send({ error: "invalid_credentials" });
|
|
145
|
-
return reply.send({
|
|
146
|
-
token: await sessions.issue(outcome.actor),
|
|
147
|
-
role: outcome.actor.role
|
|
148
|
-
});
|
|
149
|
-
});
|
|
150
|
-
app.post("/users", { preHandler: requires("user.create") }, async (request, reply) => {
|
|
151
|
-
const body = request.body;
|
|
152
|
-
if (body === null || typeof body.email !== "string" || typeof body.password !== "string" || body.role !== "admin" && body.role !== "editor" && body.role !== "viewer") return reply.code(400).send({
|
|
153
|
-
error: "bad_request",
|
|
154
|
-
message: "Body needs { email, password, role }."
|
|
155
|
-
});
|
|
156
|
-
const outcome = await createLocalUser(authDeps, {
|
|
157
|
-
email: body.email,
|
|
158
|
-
password: body.password,
|
|
159
|
-
role: body.role
|
|
160
|
-
});
|
|
161
|
-
if (!outcome.ok) return reply.code(422).send({
|
|
162
|
-
error: "rejected",
|
|
163
|
-
message: outcome.message
|
|
164
|
-
});
|
|
165
|
-
return reply.code(201).send({ id: outcome.id });
|
|
166
|
-
});
|
|
167
|
-
app.post("/api-keys", { preHandler: requires("apiKey.create") }, async (request, reply) => {
|
|
168
|
-
const body = request.body;
|
|
169
|
-
if (body === null || typeof body.name !== "string" || body.role !== "admin" && body.role !== "editor" && body.role !== "viewer") return reply.code(400).send({
|
|
170
|
-
error: "bad_request",
|
|
171
|
-
message: "Body needs { name, role }."
|
|
172
|
-
});
|
|
173
|
-
const outcome = await createApiKey(authDeps, {
|
|
174
|
-
name: body.name,
|
|
175
|
-
role: body.role
|
|
176
|
-
});
|
|
177
|
-
if (!outcome.ok) return reply.code(422).send({
|
|
178
|
-
error: "rejected",
|
|
179
|
-
message: outcome.message
|
|
180
|
-
});
|
|
181
|
-
return reply.code(201).send({
|
|
182
|
-
id: outcome.id,
|
|
183
|
-
secret: outcome.secret
|
|
184
|
-
});
|
|
185
|
-
});
|
|
186
|
-
app.post("/forms", { preHandler: requires("form.publish") }, async (request, reply) => {
|
|
187
|
-
const body = request.body;
|
|
188
|
-
if (body === null || typeof body.path !== "string" || body.path === "" || body.schema === void 0) return reply.code(400).send({
|
|
189
|
-
error: "bad_request",
|
|
190
|
-
message: "Body needs { path, schema }."
|
|
191
|
-
});
|
|
192
|
-
const outcome = await publishForm(deps, {
|
|
193
|
-
path: body.path,
|
|
194
|
-
schema: body.schema
|
|
195
|
-
});
|
|
196
|
-
if (!outcome.ok) return reply.code(422).send({
|
|
197
|
-
error: outcome.kind,
|
|
198
|
-
...outcome.kind === "invalid_schema" ? { errors: outcome.errors } : { message: outcome.message }
|
|
199
|
-
});
|
|
200
|
-
return reply.code(201).send({
|
|
201
|
-
version: outcome.version,
|
|
202
|
-
schemaHash: outcome.schemaHash
|
|
203
|
-
});
|
|
204
|
-
});
|
|
205
|
-
app.get("/forms", { preHandler: requires("form.read") }, async (_request, reply) => {
|
|
206
|
-
return reply.send({ forms: await listForms(deps) });
|
|
207
|
-
});
|
|
208
|
-
app.get("/f/:path/versions", { preHandler: requires("form.read") }, async (request, reply) => {
|
|
209
|
-
const { path } = request.params;
|
|
210
|
-
const versions = await listVersions(deps, path);
|
|
211
|
-
if (versions === void 0) return reply.code(404).send({ error: "unknown_form" });
|
|
212
|
-
return reply.send({ versions });
|
|
213
|
-
});
|
|
214
|
-
app.get("/f/:path/submissions", { preHandler: requires("submission.read") }, async (request, reply) => {
|
|
215
|
-
const { path } = request.params;
|
|
216
|
-
const listed = await listSubmissions(deps, path);
|
|
217
|
-
if (listed === void 0) return reply.code(404).send({ error: "unknown_form" });
|
|
218
|
-
return reply.send({ submissions: listed });
|
|
219
|
-
});
|
|
220
|
-
app.get("/f/:path/submissions/export.csv", { preHandler: requires("submission.export") }, async (request, reply) => {
|
|
221
|
-
const { path } = request.params;
|
|
222
|
-
const csv = await exportCsv(deps, path);
|
|
223
|
-
if (csv === void 0) return reply.code(404).send({ error: "unknown_form" });
|
|
224
|
-
return reply.header("content-type", "text/csv; charset=utf-8").header("content-disposition", `attachment; filename="${path}-submissions.csv"`).send(csv);
|
|
225
|
-
});
|
|
226
|
-
app.get("/f/:path", async (request, reply) => {
|
|
227
|
-
const { path } = request.params;
|
|
228
|
-
const resolved = await resolveForm(deps, path);
|
|
229
|
-
if (resolved === void 0) return reply.code(404).send({ error: "unknown_form" });
|
|
230
|
-
return reply.send({
|
|
231
|
-
version: resolved.version,
|
|
232
|
-
schemaHash: resolved.schemaHash,
|
|
233
|
-
schema: resolved.schema
|
|
234
|
-
});
|
|
235
|
-
});
|
|
236
|
-
app.put("/f/:path/drafts/:draftId", async (request, reply) => {
|
|
237
|
-
const { path, draftId } = request.params;
|
|
238
|
-
const saved = await saveDraft(deps, {
|
|
239
|
-
path,
|
|
240
|
-
draftId,
|
|
241
|
-
data: request.body ?? {}
|
|
242
|
-
});
|
|
243
|
-
if (saved === void 0) return reply.code(404).send({ error: "unknown_form" });
|
|
244
|
-
return reply.send(saved);
|
|
245
|
-
});
|
|
246
|
-
app.get("/f/:path/drafts/:draftId", async (request, reply) => {
|
|
247
|
-
const { path, draftId } = request.params;
|
|
248
|
-
const resumed = await resumeDraft(deps, {
|
|
249
|
-
path,
|
|
250
|
-
draftId
|
|
251
|
-
});
|
|
252
|
-
if (resumed === void 0) return reply.code(404).send({ error: "unknown_draft" });
|
|
253
|
-
return reply.send(resumed);
|
|
254
|
-
});
|
|
255
|
-
app.post("/f/:path/submissions", async (request, reply) => {
|
|
256
|
-
const { path } = request.params;
|
|
257
|
-
const declaredSchemaHash = request.headers[SCHEMA_HASH_HEADER];
|
|
258
|
-
if (typeof declaredSchemaHash !== "string" || declaredSchemaHash === "") return reply.code(400).send({
|
|
259
|
-
error: "missing_schema_hash",
|
|
260
|
-
message: `Send the schema hash you rendered in the ${SCHEMA_HASH_HEADER} header.`
|
|
261
|
-
});
|
|
262
|
-
const outcome = await createSubmission(deps, {
|
|
263
|
-
path,
|
|
264
|
-
declaredSchemaHash,
|
|
265
|
-
data: request.body ?? {}
|
|
266
|
-
});
|
|
267
|
-
if (outcome.ok) return reply.code(201).send({
|
|
268
|
-
id: outcome.id,
|
|
269
|
-
data: outcome.canonicalData
|
|
270
|
-
});
|
|
271
|
-
switch (outcome.kind) {
|
|
272
|
-
case "unknown_form": return reply.code(404).send({ error: "unknown_form" });
|
|
273
|
-
case "version_changed": return reply.code(409).send({
|
|
274
|
-
error: "FORM_VERSION_CHANGED",
|
|
275
|
-
current: outcome.current === void 0 ? void 0 : {
|
|
276
|
-
version: outcome.current.version,
|
|
277
|
-
schemaHash: outcome.current.schemaHash,
|
|
278
|
-
schema: outcome.current.schema
|
|
279
|
-
}
|
|
280
|
-
});
|
|
281
|
-
case "invalid": return reply.code(422).send({
|
|
282
|
-
error: "invalid",
|
|
283
|
-
errors: outcome.errors
|
|
284
|
-
});
|
|
285
|
-
}
|
|
286
|
-
});
|
|
287
|
-
return app;
|
|
288
|
-
}
|
|
289
|
-
//#endregion
|
|
290
|
-
//#region src/db.ts
|
|
291
|
-
/**
|
|
292
|
-
* The thin slice's tables. Three rules from the design spec are enforced HERE,
|
|
293
|
-
* in the database, because application code can be bypassed and these must not
|
|
294
|
-
* be:
|
|
295
|
-
*
|
|
296
|
-
* - published versions are immutable (a trigger refuses UPDATE),
|
|
297
|
-
* - a submission binds to its exact version by real foreign key,
|
|
298
|
-
* - that key is ON DELETE RESTRICT, so orphaning a submission from the schema
|
|
299
|
-
* that produced it is structurally impossible.
|
|
300
|
-
*/
|
|
301
|
-
const forms = pgTable("forms", {
|
|
302
|
-
id: uuid("id").primaryKey(),
|
|
303
|
-
path: text("path").notNull().unique(),
|
|
304
|
-
currentVersionId: uuid("current_version_id"),
|
|
305
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
306
|
-
});
|
|
307
|
-
const formVersions = pgTable("form_versions", {
|
|
308
|
-
id: uuid("id").primaryKey(),
|
|
309
|
-
formId: uuid("form_id").notNull().references(() => forms.id),
|
|
310
|
-
version: integer("version").notNull(),
|
|
311
|
-
schema: jsonb("schema").notNull(),
|
|
312
|
-
schemaHash: text("schema_hash").notNull(),
|
|
313
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
314
|
-
});
|
|
315
|
-
const users = pgTable("users", {
|
|
316
|
-
id: uuid("id").primaryKey(),
|
|
317
|
-
email: text("email").notNull().unique(),
|
|
318
|
-
passwordHash: text("password_hash").notNull(),
|
|
319
|
-
role: text("role").notNull(),
|
|
320
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull()
|
|
321
|
-
});
|
|
322
|
-
const apiKeys = pgTable("api_keys", {
|
|
323
|
-
id: uuid("id").primaryKey(),
|
|
324
|
-
name: text("name").notNull(),
|
|
325
|
-
prefix: text("prefix").notNull(),
|
|
326
|
-
secretHash: text("secret_hash").notNull(),
|
|
327
|
-
role: text("role").notNull(),
|
|
328
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
329
|
-
revokedAt: timestamp("revoked_at", { withTimezone: true })
|
|
330
|
-
});
|
|
331
|
-
const drafts = pgTable("drafts", {
|
|
332
|
-
id: text("id").notNull(),
|
|
333
|
-
formId: uuid("form_id").notNull().references(() => forms.id),
|
|
334
|
-
formVersionId: uuid("form_version_id").notNull().references(() => formVersions.id),
|
|
335
|
-
data: jsonb("data").notNull(),
|
|
336
|
-
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull()
|
|
337
|
-
});
|
|
338
|
-
const submissions = pgTable("submissions", {
|
|
339
|
-
id: uuid("id").primaryKey(),
|
|
340
|
-
formId: uuid("form_id").notNull().references(() => forms.id),
|
|
341
|
-
formVersionId: uuid("form_version_id").notNull().references(() => formVersions.id, { onDelete: "restrict" }),
|
|
342
|
-
data: jsonb("data").notNull(),
|
|
343
|
-
submittedAt: timestamp("submitted_at", { withTimezone: true }).notNull()
|
|
344
|
-
});
|
|
345
|
-
/**
|
|
346
|
-
* Bootstrap DDL for the thin slice — drizzle-kit migrations arrive with the
|
|
347
|
-
* lifecycle work; a self-hosted skeleton that creates its own tables on first
|
|
348
|
-
* start is worth more right now than a migration pipeline.
|
|
349
|
-
*/
|
|
350
|
-
async function bootstrapSchema(sql) {
|
|
351
|
-
await sql`
|
|
352
|
-
CREATE TABLE IF NOT EXISTS forms (
|
|
353
|
-
id uuid PRIMARY KEY,
|
|
354
|
-
path text NOT NULL UNIQUE,
|
|
355
|
-
current_version_id uuid,
|
|
356
|
-
created_at timestamptz NOT NULL DEFAULT now()
|
|
357
|
-
)`;
|
|
358
|
-
await sql`
|
|
359
|
-
CREATE TABLE IF NOT EXISTS form_versions (
|
|
360
|
-
id uuid PRIMARY KEY,
|
|
361
|
-
form_id uuid NOT NULL REFERENCES forms(id),
|
|
362
|
-
version integer NOT NULL,
|
|
363
|
-
schema jsonb NOT NULL,
|
|
364
|
-
schema_hash text NOT NULL,
|
|
365
|
-
created_at timestamptz NOT NULL DEFAULT now(),
|
|
366
|
-
UNIQUE (form_id, version),
|
|
367
|
-
UNIQUE (form_id, schema_hash)
|
|
368
|
-
)`;
|
|
369
|
-
await sql`
|
|
370
|
-
CREATE TABLE IF NOT EXISTS submissions (
|
|
371
|
-
id uuid PRIMARY KEY,
|
|
372
|
-
form_id uuid NOT NULL REFERENCES forms(id),
|
|
373
|
-
form_version_id uuid NOT NULL REFERENCES form_versions(id) ON DELETE RESTRICT,
|
|
374
|
-
data jsonb NOT NULL,
|
|
375
|
-
submitted_at timestamptz NOT NULL
|
|
376
|
-
)`;
|
|
377
|
-
await sql`
|
|
378
|
-
CREATE TABLE IF NOT EXISTS users (
|
|
379
|
-
id uuid PRIMARY KEY,
|
|
380
|
-
email text NOT NULL UNIQUE,
|
|
381
|
-
password_hash text NOT NULL,
|
|
382
|
-
role text NOT NULL,
|
|
383
|
-
created_at timestamptz NOT NULL
|
|
384
|
-
)`;
|
|
385
|
-
await sql`
|
|
386
|
-
CREATE TABLE IF NOT EXISTS api_keys (
|
|
387
|
-
id uuid PRIMARY KEY,
|
|
388
|
-
name text NOT NULL,
|
|
389
|
-
prefix text NOT NULL,
|
|
390
|
-
secret_hash text NOT NULL,
|
|
391
|
-
role text NOT NULL,
|
|
392
|
-
created_at timestamptz NOT NULL,
|
|
393
|
-
revoked_at timestamptz
|
|
394
|
-
)`;
|
|
395
|
-
await sql`CREATE INDEX IF NOT EXISTS api_keys_prefix ON api_keys (prefix)`;
|
|
396
|
-
await sql`
|
|
397
|
-
CREATE TABLE IF NOT EXISTS drafts (
|
|
398
|
-
id text NOT NULL,
|
|
399
|
-
form_id uuid NOT NULL REFERENCES forms(id),
|
|
400
|
-
form_version_id uuid NOT NULL REFERENCES form_versions(id),
|
|
401
|
-
data jsonb NOT NULL,
|
|
402
|
-
updated_at timestamptz NOT NULL,
|
|
403
|
-
PRIMARY KEY (form_id, id)
|
|
404
|
-
)`;
|
|
405
|
-
await sql`
|
|
406
|
-
CREATE OR REPLACE FUNCTION refuse_version_update() RETURNS trigger AS $$
|
|
407
|
-
BEGIN
|
|
408
|
-
RAISE EXCEPTION 'form_versions rows are immutable; publish a new version instead';
|
|
409
|
-
END
|
|
410
|
-
$$ LANGUAGE plpgsql`;
|
|
411
|
-
await sql`DROP TRIGGER IF EXISTS form_versions_immutable ON form_versions`;
|
|
412
|
-
await sql`
|
|
413
|
-
CREATE TRIGGER form_versions_immutable
|
|
414
|
-
BEFORE UPDATE ON form_versions
|
|
415
|
-
FOR EACH ROW EXECUTE FUNCTION refuse_version_update()`;
|
|
416
|
-
}
|
|
417
|
-
//#endregion
|
|
418
|
-
//#region src/postgres-storage.ts
|
|
419
|
-
/** The Storage port over Postgres — the mirror of server-core's in-memory one. */
|
|
420
|
-
function createPostgresStorage(sql) {
|
|
421
|
-
const db = drizzle(sql);
|
|
422
|
-
return {
|
|
423
|
-
async getFormByPath(path) {
|
|
424
|
-
const row = (await db.select().from(forms).where(eq(forms.path, path)).limit(1))[0];
|
|
425
|
-
if (row === void 0) return void 0;
|
|
426
|
-
return {
|
|
427
|
-
id: row.id,
|
|
428
|
-
path: row.path,
|
|
429
|
-
currentVersionId: row.currentVersionId
|
|
430
|
-
};
|
|
431
|
-
},
|
|
432
|
-
async listForms() {
|
|
433
|
-
return (await db.select().from(forms)).map((row) => ({
|
|
434
|
-
id: row.id,
|
|
435
|
-
path: row.path,
|
|
436
|
-
currentVersionId: row.currentVersionId
|
|
437
|
-
}));
|
|
438
|
-
},
|
|
439
|
-
async createForm(record) {
|
|
440
|
-
await db.insert(forms).values({
|
|
441
|
-
id: record.id,
|
|
442
|
-
path: record.path,
|
|
443
|
-
currentVersionId: record.currentVersionId
|
|
444
|
-
});
|
|
445
|
-
},
|
|
446
|
-
async setCurrentVersion(formId, versionId) {
|
|
447
|
-
await db.update(forms).set({ currentVersionId: versionId }).where(eq(forms.id, formId));
|
|
448
|
-
},
|
|
449
|
-
async insertVersion(record) {
|
|
450
|
-
await db.insert(formVersions).values({
|
|
451
|
-
id: record.id,
|
|
452
|
-
formId: record.formId,
|
|
453
|
-
version: record.version,
|
|
454
|
-
schema: record.schema,
|
|
455
|
-
schemaHash: record.schemaHash
|
|
456
|
-
});
|
|
457
|
-
},
|
|
458
|
-
async getVersionById(id) {
|
|
459
|
-
const row = (await db.select().from(formVersions).where(eq(formVersions.id, id)).limit(1))[0];
|
|
460
|
-
if (row === void 0) return void 0;
|
|
461
|
-
return {
|
|
462
|
-
id: row.id,
|
|
463
|
-
formId: row.formId,
|
|
464
|
-
version: row.version,
|
|
465
|
-
schema: row.schema,
|
|
466
|
-
schemaHash: row.schemaHash
|
|
467
|
-
};
|
|
468
|
-
},
|
|
469
|
-
async findVersionByHash(formId, schemaHash) {
|
|
470
|
-
const row = (await db.select().from(formVersions).where(eq(formVersions.formId, formId))).find((candidate) => candidate.schemaHash === schemaHash);
|
|
471
|
-
if (row === void 0) return void 0;
|
|
472
|
-
return {
|
|
473
|
-
id: row.id,
|
|
474
|
-
formId: row.formId,
|
|
475
|
-
version: row.version,
|
|
476
|
-
schema: row.schema,
|
|
477
|
-
schemaHash: row.schemaHash
|
|
478
|
-
};
|
|
479
|
-
},
|
|
480
|
-
async latestVersionNumber(formId) {
|
|
481
|
-
return (await db.select({ latest: max(formVersions.version) }).from(formVersions).where(eq(formVersions.formId, formId)))[0]?.latest ?? 0;
|
|
482
|
-
},
|
|
483
|
-
async insertSubmission(record) {
|
|
484
|
-
await db.insert(submissions).values({
|
|
485
|
-
id: record.id,
|
|
486
|
-
formId: record.formId,
|
|
487
|
-
formVersionId: record.formVersionId,
|
|
488
|
-
data: record.data,
|
|
489
|
-
submittedAt: new Date(record.submittedAt)
|
|
490
|
-
});
|
|
491
|
-
},
|
|
492
|
-
async listSubmissions() {
|
|
493
|
-
return (await db.select().from(submissions)).map(toSubmissionRecord);
|
|
494
|
-
},
|
|
495
|
-
async listSubmissionsByForm(formId) {
|
|
496
|
-
return (await db.select().from(submissions).where(eq(submissions.formId, formId)).orderBy(desc(submissions.submittedAt), desc(submissions.id))).map(toSubmissionRecord);
|
|
497
|
-
},
|
|
498
|
-
async listVersionsByForm(formId) {
|
|
499
|
-
return (await db.select().from(formVersions).where(eq(formVersions.formId, formId)).orderBy(desc(formVersions.version))).map((row) => ({
|
|
500
|
-
id: row.id,
|
|
501
|
-
formId: row.formId,
|
|
502
|
-
version: row.version,
|
|
503
|
-
schema: row.schema,
|
|
504
|
-
schemaHash: row.schemaHash
|
|
505
|
-
}));
|
|
506
|
-
},
|
|
507
|
-
async upsertDraft(record) {
|
|
508
|
-
await db.insert(drafts).values({
|
|
509
|
-
id: record.id,
|
|
510
|
-
formId: record.formId,
|
|
511
|
-
formVersionId: record.formVersionId,
|
|
512
|
-
data: record.data,
|
|
513
|
-
updatedAt: new Date(record.updatedAt)
|
|
514
|
-
}).onConflictDoUpdate({
|
|
515
|
-
target: [drafts.formId, drafts.id],
|
|
516
|
-
set: {
|
|
517
|
-
formVersionId: record.formVersionId,
|
|
518
|
-
data: record.data,
|
|
519
|
-
updatedAt: new Date(record.updatedAt)
|
|
520
|
-
}
|
|
521
|
-
});
|
|
522
|
-
},
|
|
523
|
-
async getDraft(formId, draftId) {
|
|
524
|
-
const row = (await db.select().from(drafts).where(and(eq(drafts.formId, formId), eq(drafts.id, draftId))).limit(1))[0];
|
|
525
|
-
if (row === void 0) return void 0;
|
|
526
|
-
return {
|
|
527
|
-
id: row.id,
|
|
528
|
-
formId: row.formId,
|
|
529
|
-
formVersionId: row.formVersionId,
|
|
530
|
-
data: row.data,
|
|
531
|
-
updatedAt: row.updatedAt.toISOString()
|
|
532
|
-
};
|
|
533
|
-
},
|
|
534
|
-
async insertUser(record) {
|
|
535
|
-
await db.insert(users).values({
|
|
536
|
-
id: record.id,
|
|
537
|
-
email: record.email,
|
|
538
|
-
passwordHash: record.passwordHash,
|
|
539
|
-
role: record.role,
|
|
540
|
-
createdAt: new Date(record.createdAt)
|
|
541
|
-
});
|
|
542
|
-
},
|
|
543
|
-
async getUserByEmail(email) {
|
|
544
|
-
const row = (await db.select().from(users).where(eq(users.email, email)).limit(1))[0];
|
|
545
|
-
if (row === void 0) return void 0;
|
|
546
|
-
return {
|
|
547
|
-
id: row.id,
|
|
548
|
-
email: row.email,
|
|
549
|
-
passwordHash: row.passwordHash,
|
|
550
|
-
role: row.role,
|
|
551
|
-
createdAt: row.createdAt.toISOString()
|
|
552
|
-
};
|
|
553
|
-
},
|
|
554
|
-
async insertApiKey(record) {
|
|
555
|
-
await db.insert(apiKeys).values({
|
|
556
|
-
id: record.id,
|
|
557
|
-
name: record.name,
|
|
558
|
-
prefix: record.prefix,
|
|
559
|
-
secretHash: record.secretHash,
|
|
560
|
-
role: record.role,
|
|
561
|
-
createdAt: new Date(record.createdAt),
|
|
562
|
-
revokedAt: record.revokedAt === null ? null : new Date(record.revokedAt)
|
|
563
|
-
});
|
|
564
|
-
},
|
|
565
|
-
async listApiKeys() {
|
|
566
|
-
return (await db.select().from(apiKeys)).map(toApiKeyRecord);
|
|
567
|
-
},
|
|
568
|
-
async findApiKeysByPrefix(prefix) {
|
|
569
|
-
return (await db.select().from(apiKeys).where(eq(apiKeys.prefix, prefix))).map(toApiKeyRecord);
|
|
570
|
-
},
|
|
571
|
-
async revokeApiKey(id, atIso) {
|
|
572
|
-
await db.update(apiKeys).set({ revokedAt: new Date(atIso) }).where(eq(apiKeys.id, id));
|
|
573
|
-
}
|
|
574
|
-
};
|
|
575
|
-
}
|
|
576
|
-
function toApiKeyRecord(row) {
|
|
577
|
-
return {
|
|
578
|
-
id: row.id,
|
|
579
|
-
name: row.name,
|
|
580
|
-
prefix: row.prefix,
|
|
581
|
-
secretHash: row.secretHash,
|
|
582
|
-
role: row.role,
|
|
583
|
-
createdAt: row.createdAt.toISOString(),
|
|
584
|
-
revokedAt: row.revokedAt === null ? null : row.revokedAt.toISOString()
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
function toSubmissionRecord(row) {
|
|
588
|
-
return {
|
|
589
|
-
id: row.id,
|
|
590
|
-
formId: row.formId,
|
|
591
|
-
formVersionId: row.formVersionId,
|
|
592
|
-
data: row.data,
|
|
593
|
-
submittedAt: row.submittedAt.toISOString()
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
//#endregion
|
|
597
|
-
export { createApp as i, bootstrapSchema as n, SCHEMA_HASH_HEADER as r, createPostgresStorage as t };
|
|
598
|
-
|
|
599
|
-
//# sourceMappingURL=postgres-storage-UMh8A-4C.mjs.map
|