@formancy/server 0.1.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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +40 -0
- package/dist/index.d.mts +48 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/main.d.mts +1 -0
- package/dist/main.mjs +46 -0
- package/dist/main.mjs.map +1 -0
- package/dist/postgres-storage-UMh8A-4C.mjs +599 -0
- package/dist/postgres-storage-UMh8A-4C.mjs.map +1 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
<!-- Part of formancy: https://github.com/sharkysan/formancy.ai -->
|
|
2
|
+
|
|
3
|
+
# @formancy/server
|
|
4
|
+
|
|
5
|
+
The self-hostable formancy backend: Fastify routes and Postgres storage over
|
|
6
|
+
`@formancy/server-core`.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
docker compose up -d # Postgres on :5439
|
|
10
|
+
DATABASE_URL=… FORMANCY_AUTH_SECRET=… pnpm --filter @formancy/server dev
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Two load-bearing decisions
|
|
14
|
+
|
|
15
|
+
**Invariants live in the database, because application code can be bypassed.**
|
|
16
|
+
A published `form_versions` row can never be updated — a trigger raises instead
|
|
17
|
+
— and a submission's foreign key to its version is `ON DELETE RESTRICT`, so
|
|
18
|
+
orphaning a submission from the schema that produced it is structurally
|
|
19
|
+
impossible. Both are proven by integration tests that try to break them against
|
|
20
|
+
a real Postgres.
|
|
21
|
+
|
|
22
|
+
**Two planes, split on purpose.** The public plane (resolve, submit, drafts)
|
|
23
|
+
needs no identity, because that is what a person filling in a form needs. The
|
|
24
|
+
management plane (publish, catalog, submissions, export, users, keys) requires a
|
|
25
|
+
session token or an API key. `401` means you have no identity; `403` means you
|
|
26
|
+
have one that lacks the permission.
|
|
27
|
+
|
|
28
|
+
## Tests
|
|
29
|
+
|
|
30
|
+
Integration tests run against a disposable Postgres via Testcontainers rather
|
|
31
|
+
than mocks — versioning and submission bugs only manifest under real SQL
|
|
32
|
+
semantics. Docker must be running.
|
|
33
|
+
|
|
34
|
+
## Status
|
|
35
|
+
|
|
36
|
+
Pre-alpha. Has authentication and role-based authorization; does **not** yet
|
|
37
|
+
have rate limiting, anonymous-submission hardening, audit logging or file
|
|
38
|
+
uploads. Evaluate it; do not expose it publicly.
|
|
39
|
+
|
|
40
|
+
Docs: `apps/docs` (Quickstart: self-hosting) for the full endpoint walk-through.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { FastifyInstance } from "fastify";
|
|
2
|
+
import { Storage } from "@formancy/server-core";
|
|
3
|
+
import postgres from "postgres";
|
|
4
|
+
//#region src/app.d.ts
|
|
5
|
+
export declare const SCHEMA_HASH_HEADER = "x-formancy-schema-hash";
|
|
6
|
+
interface AppOptions {
|
|
7
|
+
/** Signs the short-lived session tokens. At least 32 characters. */
|
|
8
|
+
authSecret: string;
|
|
9
|
+
/**
|
|
10
|
+
* Created at startup IF no user exists yet — the docker-compose path to a
|
|
11
|
+
* first login. Ignored once any user exists, so it cannot re-seed an admin
|
|
12
|
+
* into a running installation.
|
|
13
|
+
*/
|
|
14
|
+
bootstrapAdmin?: {
|
|
15
|
+
email: string;
|
|
16
|
+
password: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The HTTP surface, split into two planes.
|
|
21
|
+
*
|
|
22
|
+
* PUBLIC — what a person filling a form needs: resolve, submit, drafts. These
|
|
23
|
+
* stay unauthenticated by design; anonymous-submission hardening is its own
|
|
24
|
+
* upcoming step and is opt-in per form.
|
|
25
|
+
*
|
|
26
|
+
* MANAGEMENT — everything an operator does: publish, catalog, submissions,
|
|
27
|
+
* export, users, keys. Authenticated via a session token (login) or an API
|
|
28
|
+
* key header, authorized through server-core's one-table can().
|
|
29
|
+
*
|
|
30
|
+
* This file is the composition root, so THIS is where ambient reality enters:
|
|
31
|
+
* randomUUID, the real clock, argon2 and the CSPRNG. Everything below stays
|
|
32
|
+
* injected and replayable.
|
|
33
|
+
*/
|
|
34
|
+
export declare function createApp(storage: Storage, options: AppOptions): Promise<FastifyInstance>;
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/postgres-storage.d.ts
|
|
37
|
+
/** The Storage port over Postgres — the mirror of server-core's in-memory one. */
|
|
38
|
+
export declare function createPostgresStorage(sql: postgres.Sql): Storage;
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/db.d.ts
|
|
41
|
+
/**
|
|
42
|
+
* Bootstrap DDL for the thin slice — drizzle-kit migrations arrive with the
|
|
43
|
+
* lifecycle work; a self-hosted skeleton that creates its own tables on first
|
|
44
|
+
* start is worth more right now than a migration pipeline.
|
|
45
|
+
*/
|
|
46
|
+
export declare function bootstrapSchema(sql: postgres.Sql): Promise<void>;
|
|
47
|
+
//#endregion
|
|
48
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/app.ts","../src/postgres-storage.ts","../src/db.ts"],"mappings":";;;;qBAsBa;UAGI;;EAEf;;;;;;EAMA;IAAmB;IAAe;;;;;;;;;;;;;;;;;;wBAkBd,UAAU,SAAS,SAAS,SAAS,aAAa,QAAQ;;;;wBC1ChE,sBAAsB,KAAK,SAAS,MAAM;;;;;;;;wBCqEpC,gBAAgB,KAAK,SAAS,MAAM"}
|
package/dist/index.mjs
ADDED
package/dist/main.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/main.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { i as createApp, n as bootstrapSchema, t as createPostgresStorage } from "./postgres-storage-UMh8A-4C.mjs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import postgres from "postgres";
|
|
4
|
+
//#region src/main.ts
|
|
5
|
+
/**
|
|
6
|
+
* The runnable server: `node dist/main.mjs` with DATABASE_URL set, or
|
|
7
|
+
* `docker compose up` from the repo root, which supplies both.
|
|
8
|
+
*
|
|
9
|
+
* Bootstraps its own tables on start — a self-hosted skeleton that works five
|
|
10
|
+
* minutes after `git clone` is the adoption funnel; migrations arrive with the
|
|
11
|
+
* lifecycle work.
|
|
12
|
+
*/
|
|
13
|
+
const databaseUrl = process.env["DATABASE_URL"];
|
|
14
|
+
if (databaseUrl === void 0 || databaseUrl === "") {
|
|
15
|
+
console.error("DATABASE_URL is required, e.g. postgres://formancy:formancy@localhost:5432/formancy");
|
|
16
|
+
process.exit(1);
|
|
17
|
+
}
|
|
18
|
+
const port = Number(process.env["PORT"] ?? 4380);
|
|
19
|
+
const sql = postgres(databaseUrl);
|
|
20
|
+
let authSecret = process.env["FORMANCY_AUTH_SECRET"];
|
|
21
|
+
if (authSecret === void 0 || authSecret === "") {
|
|
22
|
+
authSecret = randomBytes(33).toString("base64url");
|
|
23
|
+
console.warn("FORMANCY_AUTH_SECRET is not set: generated an ephemeral one, sessions will not survive a restart.");
|
|
24
|
+
}
|
|
25
|
+
const adminEmail = process.env["FORMANCY_ADMIN_EMAIL"];
|
|
26
|
+
const adminPassword = process.env["FORMANCY_ADMIN_PASSWORD"];
|
|
27
|
+
await bootstrapSchema(sql);
|
|
28
|
+
const app = await createApp(createPostgresStorage(sql), {
|
|
29
|
+
authSecret,
|
|
30
|
+
...adminEmail !== void 0 && adminPassword !== void 0 ? { bootstrapAdmin: {
|
|
31
|
+
email: adminEmail,
|
|
32
|
+
password: adminPassword
|
|
33
|
+
} } : {}
|
|
34
|
+
});
|
|
35
|
+
await app.listen({
|
|
36
|
+
port,
|
|
37
|
+
host: process.env["HOST"] ?? "0.0.0.0"
|
|
38
|
+
});
|
|
39
|
+
console.log(`formancy server listening on :${port}`);
|
|
40
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => {
|
|
41
|
+
app.close().then(() => sql.end()).then(() => process.exit(0));
|
|
42
|
+
});
|
|
43
|
+
//#endregion
|
|
44
|
+
export {};
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=main.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"main.mjs","names":[],"sources":["../src/main.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport postgres from 'postgres'\nimport { createApp } from './app.js'\nimport { bootstrapSchema } from './db.js'\nimport { createPostgresStorage } from './postgres-storage.js'\n\n/**\n * The runnable server: `node dist/main.mjs` with DATABASE_URL set, or\n * `docker compose up` from the repo root, which supplies both.\n *\n * Bootstraps its own tables on start — a self-hosted skeleton that works five\n * minutes after `git clone` is the adoption funnel; migrations arrive with the\n * lifecycle work.\n */\nconst databaseUrl = process.env['DATABASE_URL']\nif (databaseUrl === undefined || databaseUrl === '') {\n console.error('DATABASE_URL is required, e.g. postgres://formancy:formancy@localhost:5432/formancy')\n process.exit(1)\n}\n\nconst port = Number(process.env['PORT'] ?? 4380)\nconst sql = postgres(databaseUrl)\n\nlet authSecret = process.env['FORMANCY_AUTH_SECRET']\nif (authSecret === undefined || authSecret === '') {\n // A generated secret keeps `docker compose up` working, at the cost of every\n // session dying on restart. Say so loudly rather than failing dev cold.\n authSecret = randomBytes(33).toString('base64url')\n console.warn(\n 'FORMANCY_AUTH_SECRET is not set: generated an ephemeral one, sessions will not survive a restart.',\n )\n}\n\nconst adminEmail = process.env['FORMANCY_ADMIN_EMAIL']\nconst adminPassword = process.env['FORMANCY_ADMIN_PASSWORD']\n\nawait bootstrapSchema(sql)\nconst app = await createApp(createPostgresStorage(sql), {\n authSecret,\n ...(adminEmail !== undefined && adminPassword !== undefined\n ? { bootstrapAdmin: { email: adminEmail, password: adminPassword } }\n : {}),\n})\n\nawait app.listen({ port, host: process.env['HOST'] ?? '0.0.0.0' })\nconsole.log(`formancy server listening on :${port}`)\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, () => {\n void app\n .close()\n .then(() => sql.end())\n .then(() => process.exit(0))\n })\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,cAAc,QAAQ,IAAI;AAChC,IAAI,gBAAgB,KAAA,KAAa,gBAAgB,IAAI;CACnD,QAAQ,MAAM,qFAAqF;CACnG,QAAQ,KAAK,CAAC;AAChB;AAEA,MAAM,OAAO,OAAO,QAAQ,IAAI,WAAW,IAAI;AAC/C,MAAM,MAAM,SAAS,WAAW;AAEhC,IAAI,aAAa,QAAQ,IAAI;AAC7B,IAAI,eAAe,KAAA,KAAa,eAAe,IAAI;CAGjD,aAAa,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;CACjD,QAAQ,KACN,mGACF;AACF;AAEA,MAAM,aAAa,QAAQ,IAAI;AAC/B,MAAM,gBAAgB,QAAQ,IAAI;AAElC,MAAM,gBAAgB,GAAG;AACzB,MAAM,MAAM,MAAM,UAAU,sBAAsB,GAAG,GAAG;CACtD;CACA,GAAI,eAAe,KAAA,KAAa,kBAAkB,KAAA,IAC9C,EAAE,gBAAgB;EAAE,OAAO;EAAY,UAAU;CAAc,EAAE,IACjE,CAAC;AACP,CAAC;AAED,MAAM,IAAI,OAAO;CAAE;CAAM,MAAM,QAAQ,IAAI,WAAW;AAAU,CAAC;AACjE,QAAQ,IAAI,iCAAiC,MAAM;AAEnD,KAAK,MAAM,UAAU,CAAC,UAAU,SAAS,GACvC,QAAQ,GAAG,cAAc;CACvB,IACG,MAAM,CAAC,CACP,WAAW,IAAI,IAAI,CAAC,CAAC,CACrB,WAAW,QAAQ,KAAK,CAAC,CAAC;AAC/B,CAAC"}
|
|
@@ -0,0 +1,599 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-storage-UMh8A-4C.mjs","names":["argon2Hash","argon2Verify"],"sources":["../src/auth-runtime.ts","../src/app.ts","../src/db.ts","../src/postgres-storage.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { hash as argon2Hash, verify as argon2Verify } from '@node-rs/argon2'\nimport { SignJWT, jwtVerify } from 'jose'\nimport type { Actor, Role } from '@formancy/server-core'\n\n/**\n * The real cryptography, confined to the composition root: argon2id for\n * secrets at rest, an HMAC-signed short-lived access token for sessions, and\n * a CSPRNG for API keys. server-core never sees any of this — it is handed\n * hash/verify/random functions and stays deterministic under test.\n *\n * HS256 rather than EdDSA for the session token, deliberately for this phase:\n * one secret in one env var is the self-hosting story a single-container\n * deployment can operate, and the signing scheme is an implementation detail\n * of a token that lives fifteen minutes. Revisit with key rotation.\n */\nexport function realSecretHashing(): {\n hashSecret(secret: string): Promise<string>\n verifySecret(secret: string, hash: string): Promise<boolean>\n} {\n return {\n hashSecret: (secret) => argon2Hash(secret),\n verifySecret: async (secret, digest) => {\n try {\n return await argon2Verify(digest, secret)\n } catch {\n // A malformed digest is a failed verification, not a crash: this runs\n // on the login path with attacker-influenced timing.\n return false\n }\n },\n }\n}\n\nexport function realRandomToken(): string {\n return randomBytes(30).toString('base64url')\n}\n\nconst TOKEN_LIFETIME = '15m'\n\nexport interface SessionTokens {\n issue(actor: Actor): Promise<string>\n verify(token: string): Promise<Actor | undefined>\n}\n\nexport function createSessionTokens(secret: string): SessionTokens {\n if (secret.length < 32) {\n throw new Error(\n 'FORMANCY_AUTH_SECRET must be at least 32 characters. Generate one: openssl rand -base64 33',\n )\n }\n const key = new TextEncoder().encode(secret)\n\n return {\n async issue(actor) {\n return new SignJWT({ role: actor.role, kind: actor.kind })\n .setProtectedHeader({ alg: 'HS256' })\n .setSubject(actor.id)\n .setIssuedAt()\n .setExpirationTime(TOKEN_LIFETIME)\n .sign(key)\n },\n\n async verify(token) {\n try {\n const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] })\n const role = payload['role']\n const kind = payload['kind']\n if (\n typeof payload.sub !== 'string' ||\n (role !== 'admin' && role !== 'editor' && role !== 'viewer') ||\n (kind !== 'user' && kind !== 'apiKey')\n ) {\n return undefined\n }\n return { id: payload.sub, role: role as Role, kind }\n } catch {\n return undefined\n }\n },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport Fastify from 'fastify'\nimport type { FastifyInstance, FastifyRequest, preHandlerHookHandler } from 'fastify'\nimport {\n authenticateApiKey,\n authenticateLocal,\n can,\n createApiKey,\n createLocalUser,\n createSubmission,\n exportCsv,\n listForms,\n listSubmissions,\n listVersions,\n publishForm,\n resolveForm,\n resumeDraft,\n saveDraft,\n} from '@formancy/server-core'\nimport type { Action, Actor, AuthDeps, Role, ServerDeps, Storage } from '@formancy/server-core'\nimport { createSessionTokens, realRandomToken, realSecretHashing } from './auth-runtime.js'\n\nexport const SCHEMA_HASH_HEADER = 'x-formancy-schema-hash'\nexport const API_KEY_HEADER = 'x-formancy-api-key'\n\nexport interface AppOptions {\n /** Signs the short-lived session tokens. At least 32 characters. */\n authSecret: string\n /**\n * Created at startup IF no user exists yet — the docker-compose path to a\n * first login. Ignored once any user exists, so it cannot re-seed an admin\n * into a running installation.\n */\n bootstrapAdmin?: { email: string; password: string }\n}\n\n/**\n * The HTTP surface, split into two planes.\n *\n * PUBLIC — what a person filling a form needs: resolve, submit, drafts. These\n * stay unauthenticated by design; anonymous-submission hardening is its own\n * upcoming step and is opt-in per form.\n *\n * MANAGEMENT — everything an operator does: publish, catalog, submissions,\n * export, users, keys. Authenticated via a session token (login) or an API\n * key header, authorized through server-core's one-table can().\n *\n * This file is the composition root, so THIS is where ambient reality enters:\n * randomUUID, the real clock, argon2 and the CSPRNG. Everything below stays\n * injected and replayable.\n */\nexport async function createApp(storage: Storage, options: AppOptions): Promise<FastifyInstance> {\n const app = Fastify({ logger: false })\n\n const deps: ServerDeps = {\n storage,\n newId: () => randomUUID(),\n nowIso: () => new Date().toISOString(),\n capabilities: {\n now: () => Date.now(),\n today: () => new Date().toISOString().slice(0, 10),\n random: () => Math.random(),\n },\n }\n\n const authDeps: AuthDeps = {\n storage,\n newId: deps.newId,\n nowIso: deps.nowIso,\n randomToken: realRandomToken,\n ...realSecretHashing(),\n }\n\n const sessions = createSessionTokens(options.authSecret)\n\n if (options.bootstrapAdmin !== undefined) {\n const alreadyThere = await storage.getUserByEmail(options.bootstrapAdmin.email)\n if (alreadyThere === undefined) {\n const outcome = await createLocalUser(authDeps, { ...options.bootstrapAdmin, role: 'admin' })\n if (!outcome.ok) throw new Error(`Bootstrap admin rejected: ${outcome.message}`)\n }\n }\n\n async function actorOf(request: FastifyRequest): Promise<Actor | undefined> {\n const bearer = request.headers.authorization\n if (typeof bearer === 'string' && bearer.startsWith('Bearer ')) {\n return sessions.verify(bearer.slice('Bearer '.length))\n }\n const apiKey = request.headers[API_KEY_HEADER]\n if (typeof apiKey === 'string' && apiKey !== '') {\n const outcome = await authenticateApiKey(authDeps, apiKey)\n return outcome.ok ? outcome.actor : undefined\n }\n return undefined\n }\n\n /** 401 without an identity, 403 with one that lacks the permission — the\n * difference tells a client whether to log in or to give up. */\n function requires(action: Action): preHandlerHookHandler {\n return async (request, reply) => {\n const actor = await actorOf(request)\n if (actor === undefined) {\n return reply.code(401).send({ error: 'unauthenticated' })\n }\n if (!can(actor, action)) {\n return reply.code(403).send({ error: 'forbidden', action })\n }\n ;(request as FastifyRequest & { actor: Actor }).actor = actor\n }\n }\n\n // -------------------------------------------------------------------- auth\n\n app.post('/auth/login', async (request, reply) => {\n const body = request.body as { email?: unknown; password?: unknown } | null\n if (body === null || typeof body.email !== 'string' || typeof body.password !== 'string') {\n return reply.code(400).send({ error: 'bad_request', message: 'Body needs { email, password }.' })\n }\n const outcome = await authenticateLocal(authDeps, { email: body.email, password: body.password })\n if (!outcome.ok) return reply.code(401).send({ error: 'invalid_credentials' })\n return reply.send({ token: await sessions.issue(outcome.actor), role: outcome.actor.role })\n })\n\n app.post('/users', { preHandler: requires('user.create') }, async (request, reply) => {\n const body = request.body as { email?: unknown; password?: unknown; role?: unknown } | null\n if (\n body === null ||\n typeof body.email !== 'string' ||\n typeof body.password !== 'string' ||\n (body.role !== 'admin' && body.role !== 'editor' && body.role !== 'viewer')\n ) {\n return reply\n .code(400)\n .send({ error: 'bad_request', message: 'Body needs { email, password, role }.' })\n }\n const outcome = await createLocalUser(authDeps, {\n email: body.email,\n password: body.password,\n role: body.role as Role,\n })\n if (!outcome.ok) return reply.code(422).send({ error: 'rejected', message: outcome.message })\n return reply.code(201).send({ id: outcome.id })\n })\n\n app.post('/api-keys', { preHandler: requires('apiKey.create') }, async (request, reply) => {\n const body = request.body as { name?: unknown; role?: unknown } | null\n if (\n body === null ||\n typeof body.name !== 'string' ||\n (body.role !== 'admin' && body.role !== 'editor' && body.role !== 'viewer')\n ) {\n return reply.code(400).send({ error: 'bad_request', message: 'Body needs { name, role }.' })\n }\n const outcome = await createApiKey(authDeps, { name: body.name, role: body.role as Role })\n if (!outcome.ok) return reply.code(422).send({ error: 'rejected', message: outcome.message })\n // The one and only time the secret exists in full outside a hash.\n return reply.code(201).send({ id: outcome.id, secret: outcome.secret })\n })\n\n // -------------------------------------------------------------- management\n\n app.post('/forms', { preHandler: requires('form.publish') }, async (request, reply) => {\n const body = request.body as { path?: unknown; schema?: unknown } | null\n if (body === null || typeof body.path !== 'string' || body.path === '' || body.schema === undefined) {\n return reply.code(400).send({ error: 'bad_request', message: 'Body needs { path, schema }.' })\n }\n\n const outcome = await publishForm(deps, { path: body.path, schema: body.schema })\n if (!outcome.ok) {\n return reply.code(422).send({\n error: outcome.kind,\n ...(outcome.kind === 'invalid_schema' ? { errors: outcome.errors } : { message: outcome.message }),\n })\n }\n return reply.code(201).send({ version: outcome.version, schemaHash: outcome.schemaHash })\n })\n\n app.get('/forms', { preHandler: requires('form.read') }, async (_request, reply) => {\n return reply.send({ forms: await listForms(deps) })\n })\n\n app.get('/f/:path/versions', { preHandler: requires('form.read') }, async (request, reply) => {\n const { path } = request.params as { path: string }\n const versions = await listVersions(deps, path)\n if (versions === undefined) return reply.code(404).send({ error: 'unknown_form' })\n return reply.send({ versions })\n })\n\n app.get(\n '/f/:path/submissions',\n { preHandler: requires('submission.read') },\n async (request, reply) => {\n const { path } = request.params as { path: string }\n const listed = await listSubmissions(deps, path)\n if (listed === undefined) return reply.code(404).send({ error: 'unknown_form' })\n return reply.send({ submissions: listed })\n },\n )\n\n app.get(\n '/f/:path/submissions/export.csv',\n { preHandler: requires('submission.export') },\n async (request, reply) => {\n const { path } = request.params as { path: string }\n const csv = await exportCsv(deps, path)\n if (csv === undefined) return reply.code(404).send({ error: 'unknown_form' })\n return reply\n .header('content-type', 'text/csv; charset=utf-8')\n .header('content-disposition', `attachment; filename=\"${path}-submissions.csv\"`)\n .send(csv)\n },\n )\n\n // ------------------------------------------------------------------ public\n\n app.get('/f/:path', async (request, reply) => {\n const { path } = request.params as { path: string }\n const resolved = await resolveForm(deps, path)\n if (resolved === undefined) return reply.code(404).send({ error: 'unknown_form' })\n return reply.send({\n version: resolved.version,\n schemaHash: resolved.schemaHash,\n schema: resolved.schema,\n })\n })\n\n app.put('/f/:path/drafts/:draftId', async (request, reply) => {\n const { path, draftId } = request.params as { path: string; draftId: string }\n const saved = await saveDraft(deps, { path, draftId, data: request.body ?? {} })\n if (saved === undefined) return reply.code(404).send({ error: 'unknown_form' })\n return reply.send(saved)\n })\n\n app.get('/f/:path/drafts/:draftId', async (request, reply) => {\n const { path, draftId } = request.params as { path: string; draftId: string }\n const resumed = await resumeDraft(deps, { path, draftId })\n if (resumed === undefined) return reply.code(404).send({ error: 'unknown_draft' })\n return reply.send(resumed)\n })\n\n app.post('/f/:path/submissions', async (request, reply) => {\n const { path } = request.params as { path: string }\n const declaredSchemaHash = request.headers[SCHEMA_HASH_HEADER]\n if (typeof declaredSchemaHash !== 'string' || declaredSchemaHash === '') {\n return reply.code(400).send({\n error: 'missing_schema_hash',\n message: `Send the schema hash you rendered in the ${SCHEMA_HASH_HEADER} header.`,\n })\n }\n\n const outcome = await createSubmission(deps, {\n path,\n declaredSchemaHash,\n data: request.body ?? {},\n })\n\n if (outcome.ok) return reply.code(201).send({ id: outcome.id, data: outcome.canonicalData })\n\n switch (outcome.kind) {\n case 'unknown_form':\n return reply.code(404).send({ error: 'unknown_form' })\n case 'version_changed':\n // 409 carries the CURRENT schema so the client can re-render and\n // preserve what it can, instead of guessing why it was refused.\n return reply.code(409).send({\n error: 'FORM_VERSION_CHANGED',\n current:\n outcome.current === undefined\n ? undefined\n : {\n version: outcome.current.version,\n schemaHash: outcome.current.schemaHash,\n schema: outcome.current.schema,\n },\n })\n case 'invalid':\n // The identical error shape the client's engine produces, so server\n // errors render through the same code path as local ones.\n return reply.code(422).send({ error: 'invalid', errors: outcome.errors })\n }\n })\n\n return app\n}\n","import { jsonb, integer, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'\nimport type postgres from 'postgres'\n\n/**\n * The thin slice's tables. Three rules from the design spec are enforced HERE,\n * in the database, because application code can be bypassed and these must not\n * be:\n *\n * - published versions are immutable (a trigger refuses UPDATE),\n * - a submission binds to its exact version by real foreign key,\n * - that key is ON DELETE RESTRICT, so orphaning a submission from the schema\n * that produced it is structurally impossible.\n */\nexport const forms = pgTable('forms', {\n id: uuid('id').primaryKey(),\n path: text('path').notNull().unique(),\n currentVersionId: uuid('current_version_id'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n})\n\nexport const formVersions = pgTable('form_versions', {\n id: uuid('id').primaryKey(),\n formId: uuid('form_id')\n .notNull()\n .references(() => forms.id),\n version: integer('version').notNull(),\n schema: jsonb('schema').notNull(),\n schemaHash: text('schema_hash').notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n})\n\nexport const users = pgTable('users', {\n id: uuid('id').primaryKey(),\n email: text('email').notNull().unique(),\n passwordHash: text('password_hash').notNull(),\n role: text('role').notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull(),\n})\n\nexport const apiKeys = pgTable('api_keys', {\n id: uuid('id').primaryKey(),\n name: text('name').notNull(),\n prefix: text('prefix').notNull(),\n secretHash: text('secret_hash').notNull(),\n role: text('role').notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull(),\n revokedAt: timestamp('revoked_at', { withTimezone: true }),\n})\n\nexport const drafts = pgTable('drafts', {\n id: text('id').notNull(),\n formId: uuid('form_id')\n .notNull()\n .references(() => forms.id),\n formVersionId: uuid('form_version_id')\n .notNull()\n .references(() => formVersions.id),\n data: jsonb('data').notNull(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull(),\n})\n\nexport const submissions = pgTable('submissions', {\n id: uuid('id').primaryKey(),\n formId: uuid('form_id')\n .notNull()\n .references(() => forms.id),\n formVersionId: uuid('form_version_id')\n .notNull()\n .references(() => formVersions.id, { onDelete: 'restrict' }),\n data: jsonb('data').notNull(),\n submittedAt: timestamp('submitted_at', { withTimezone: true }).notNull(),\n})\n\n/**\n * Bootstrap DDL for the thin slice — drizzle-kit migrations arrive with the\n * lifecycle work; a self-hosted skeleton that creates its own tables on first\n * start is worth more right now than a migration pipeline.\n */\nexport async function bootstrapSchema(sql: postgres.Sql): Promise<void> {\n await sql`\n CREATE TABLE IF NOT EXISTS forms (\n id uuid PRIMARY KEY,\n path text NOT NULL UNIQUE,\n current_version_id uuid,\n created_at timestamptz NOT NULL DEFAULT now()\n )`\n await sql`\n CREATE TABLE IF NOT EXISTS form_versions (\n id uuid PRIMARY KEY,\n form_id uuid NOT NULL REFERENCES forms(id),\n version integer NOT NULL,\n schema jsonb NOT NULL,\n schema_hash text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (form_id, version),\n UNIQUE (form_id, schema_hash)\n )`\n await sql`\n CREATE TABLE IF NOT EXISTS submissions (\n id uuid PRIMARY KEY,\n form_id uuid NOT NULL REFERENCES forms(id),\n form_version_id uuid NOT NULL REFERENCES form_versions(id) ON DELETE RESTRICT,\n data jsonb NOT NULL,\n submitted_at timestamptz NOT NULL\n )`\n await sql`\n CREATE TABLE IF NOT EXISTS users (\n id uuid PRIMARY KEY,\n email text NOT NULL UNIQUE,\n password_hash text NOT NULL,\n role text NOT NULL,\n created_at timestamptz NOT NULL\n )`\n await sql`\n CREATE TABLE IF NOT EXISTS api_keys (\n id uuid PRIMARY KEY,\n name text NOT NULL,\n prefix text NOT NULL,\n secret_hash text NOT NULL,\n role text NOT NULL,\n created_at timestamptz NOT NULL,\n revoked_at timestamptz\n )`\n await sql`CREATE INDEX IF NOT EXISTS api_keys_prefix ON api_keys (prefix)`\n await sql`\n CREATE TABLE IF NOT EXISTS drafts (\n id text NOT NULL,\n form_id uuid NOT NULL REFERENCES forms(id),\n form_version_id uuid NOT NULL REFERENCES form_versions(id),\n data jsonb NOT NULL,\n updated_at timestamptz NOT NULL,\n PRIMARY KEY (form_id, id)\n )`\n // Immutability lives in the database, not in application discipline: a\n // published version row can never change, because every submission's audit\n // story depends on it staying exactly what the user saw.\n await sql`\n CREATE OR REPLACE FUNCTION refuse_version_update() RETURNS trigger AS $$\n BEGIN\n RAISE EXCEPTION 'form_versions rows are immutable; publish a new version instead';\n END\n $$ LANGUAGE plpgsql`\n await sql`DROP TRIGGER IF EXISTS form_versions_immutable ON form_versions`\n await sql`\n CREATE TRIGGER form_versions_immutable\n BEFORE UPDATE ON form_versions\n FOR EACH ROW EXECUTE FUNCTION refuse_version_update()`\n}\n","import { and, desc, eq, max } from 'drizzle-orm'\nimport { drizzle } from 'drizzle-orm/postgres-js'\nimport type postgres from 'postgres'\nimport type { FormSchema } from '@formancy/spec'\nimport type { Role, Storage } from '@formancy/server-core'\nimport { apiKeys, drafts, forms, formVersions, submissions } from './db.js'\nimport { users } from './db.js'\n\n/** The Storage port over Postgres — the mirror of server-core's in-memory one. */\nexport function createPostgresStorage(sql: postgres.Sql): Storage {\n const db = drizzle(sql)\n\n return {\n async getFormByPath(path) {\n const rows = await db.select().from(forms).where(eq(forms.path, path)).limit(1)\n const row = rows[0]\n if (row === undefined) return undefined\n return { id: row.id, path: row.path, currentVersionId: row.currentVersionId }\n },\n\n async listForms() {\n const rows = await db.select().from(forms)\n return rows.map((row) => ({\n id: row.id,\n path: row.path,\n currentVersionId: row.currentVersionId,\n }))\n },\n\n async createForm(record) {\n await db.insert(forms).values({\n id: record.id,\n path: record.path,\n currentVersionId: record.currentVersionId,\n })\n },\n\n async setCurrentVersion(formId, versionId) {\n await db.update(forms).set({ currentVersionId: versionId }).where(eq(forms.id, formId))\n },\n\n async insertVersion(record) {\n await db.insert(formVersions).values({\n id: record.id,\n formId: record.formId,\n version: record.version,\n schema: record.schema,\n schemaHash: record.schemaHash,\n })\n },\n\n async getVersionById(id) {\n const rows = await db.select().from(formVersions).where(eq(formVersions.id, id)).limit(1)\n const row = rows[0]\n if (row === undefined) return undefined\n return {\n id: row.id,\n formId: row.formId,\n version: row.version,\n schema: row.schema as FormSchema,\n schemaHash: row.schemaHash,\n }\n },\n\n async findVersionByHash(formId, schemaHash) {\n const rows = await db\n .select()\n .from(formVersions)\n .where(eq(formVersions.formId, formId))\n const row = rows.find((candidate) => candidate.schemaHash === schemaHash)\n if (row === undefined) return undefined\n return {\n id: row.id,\n formId: row.formId,\n version: row.version,\n schema: row.schema as FormSchema,\n schemaHash: row.schemaHash,\n }\n },\n\n async latestVersionNumber(formId) {\n const rows = await db\n .select({ latest: max(formVersions.version) })\n .from(formVersions)\n .where(eq(formVersions.formId, formId))\n return rows[0]?.latest ?? 0\n },\n\n async insertSubmission(record) {\n await db.insert(submissions).values({\n id: record.id,\n formId: record.formId,\n formVersionId: record.formVersionId,\n data: record.data,\n submittedAt: new Date(record.submittedAt),\n })\n },\n\n async listSubmissions() {\n const rows = await db.select().from(submissions)\n return rows.map(toSubmissionRecord)\n },\n\n async listSubmissionsByForm(formId) {\n const rows = await db\n .select()\n .from(submissions)\n .where(eq(submissions.formId, formId))\n .orderBy(desc(submissions.submittedAt), desc(submissions.id))\n return rows.map(toSubmissionRecord)\n },\n\n async listVersionsByForm(formId) {\n const rows = await db\n .select()\n .from(formVersions)\n .where(eq(formVersions.formId, formId))\n .orderBy(desc(formVersions.version))\n return rows.map((row) => ({\n id: row.id,\n formId: row.formId,\n version: row.version,\n schema: row.schema as FormSchema,\n schemaHash: row.schemaHash,\n }))\n },\n\n async upsertDraft(record) {\n await db\n .insert(drafts)\n .values({\n id: record.id,\n formId: record.formId,\n formVersionId: record.formVersionId,\n data: record.data,\n updatedAt: new Date(record.updatedAt),\n })\n .onConflictDoUpdate({\n target: [drafts.formId, drafts.id],\n set: {\n formVersionId: record.formVersionId,\n data: record.data,\n updatedAt: new Date(record.updatedAt),\n },\n })\n },\n\n async getDraft(formId, draftId) {\n const rows = await db\n .select()\n .from(drafts)\n .where(and(eq(drafts.formId, formId), eq(drafts.id, draftId)))\n .limit(1)\n const row = rows[0]\n if (row === undefined) return undefined\n return {\n id: row.id,\n formId: row.formId,\n formVersionId: row.formVersionId,\n data: row.data,\n updatedAt: row.updatedAt.toISOString(),\n }\n },\n\n async insertUser(record) {\n await db.insert(users).values({\n id: record.id,\n email: record.email,\n passwordHash: record.passwordHash,\n role: record.role,\n createdAt: new Date(record.createdAt),\n })\n },\n\n async getUserByEmail(email) {\n const rows = await db.select().from(users).where(eq(users.email, email)).limit(1)\n const row = rows[0]\n if (row === undefined) return undefined\n return {\n id: row.id,\n email: row.email,\n passwordHash: row.passwordHash,\n role: row.role as Role,\n createdAt: row.createdAt.toISOString(),\n }\n },\n\n async insertApiKey(record) {\n await db.insert(apiKeys).values({\n id: record.id,\n name: record.name,\n prefix: record.prefix,\n secretHash: record.secretHash,\n role: record.role,\n createdAt: new Date(record.createdAt),\n revokedAt: record.revokedAt === null ? null : new Date(record.revokedAt),\n })\n },\n\n async listApiKeys() {\n const rows = await db.select().from(apiKeys)\n return rows.map(toApiKeyRecord)\n },\n\n async findApiKeysByPrefix(prefix) {\n const rows = await db.select().from(apiKeys).where(eq(apiKeys.prefix, prefix))\n return rows.map(toApiKeyRecord)\n },\n\n async revokeApiKey(id, atIso) {\n await db.update(apiKeys).set({ revokedAt: new Date(atIso) }).where(eq(apiKeys.id, id))\n },\n }\n}\n\nfunction toApiKeyRecord(row: {\n id: string\n name: string\n prefix: string\n secretHash: string\n role: string\n createdAt: Date\n revokedAt: Date | null\n}) {\n return {\n id: row.id,\n name: row.name,\n prefix: row.prefix,\n secretHash: row.secretHash,\n role: row.role as Role,\n createdAt: row.createdAt.toISOString(),\n revokedAt: row.revokedAt === null ? null : row.revokedAt.toISOString(),\n }\n}\n\nfunction toSubmissionRecord(row: {\n id: string\n formId: string\n formVersionId: string\n data: unknown\n submittedAt: Date\n}) {\n return {\n id: row.id,\n formId: row.formId,\n formVersionId: row.formVersionId,\n data: row.data,\n submittedAt: row.submittedAt.toISOString(),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,oBAGd;CACA,OAAO;EACL,aAAa,WAAWA,KAAW,MAAM;EACzC,cAAc,OAAO,QAAQ,WAAW;GACtC,IAAI;IACF,OAAO,MAAMC,OAAa,QAAQ,MAAM;GAC1C,QAAQ;IAGN,OAAO;GACT;EACF;CACF;AACF;AAEA,SAAgB,kBAA0B;CACxC,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;AAEA,MAAM,iBAAiB;AAOvB,SAAgB,oBAAoB,QAA+B;CACjE,IAAI,OAAO,SAAS,IAClB,MAA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,YAAY,IAAI;EAChB,MAAM,IAAI;EACV,WAAW,IAAI,UAAU,YAAY;EACrC,WAAW,IAAI,cAAc,OAAO,OAAO,IAAI,UAAU,YAAY;CACvE;AACF;AAEA,SAAS,mBAAmB,KAMzB;CACD,OAAO;EACL,IAAI,IAAI;EACR,QAAQ,IAAI;EACZ,eAAe,IAAI;EACnB,MAAM,IAAI;EACV,aAAa,IAAI,YAAY,YAAY;CAC3C;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@formancy/server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The self-hostable formancy backend: Fastify routes and Postgres storage over @formancy/server-core.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.mts",
|
|
10
|
+
"default": "./dist/index.mjs"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist",
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"NOTICE"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@formancy/server-core": "0.1.0",
|
|
20
|
+
"@formancy/spec": "0.1.0",
|
|
21
|
+
"drizzle-orm": "^0.45.2",
|
|
22
|
+
"fastify": "^5.12.5",
|
|
23
|
+
"postgres": "^3.4.9",
|
|
24
|
+
"@fastify/rate-limit": "^11.2.0",
|
|
25
|
+
"jose": "^6.2.12",
|
|
26
|
+
"@node-rs/argon2": "^2.2.1"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
30
|
+
"@testcontainers/postgresql": "^12.1.0",
|
|
31
|
+
"@types/node": "^22.10.0",
|
|
32
|
+
"publint": "^0.3.24",
|
|
33
|
+
"tsdown": "^0.23.0",
|
|
34
|
+
"typescript": "~6.0.3",
|
|
35
|
+
"unrun": "^0.3.1",
|
|
36
|
+
"vitest": "^5.0.1"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "git+https://github.com/sharkysan/formancy.ai.git",
|
|
44
|
+
"directory": "packages/server"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/sharkysan/formancy.ai",
|
|
47
|
+
"bugs": "https://github.com/sharkysan/formancy.ai/issues",
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"test": "vitest run",
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"check:pkg": "publint && attw --pack . --profile esm-only",
|
|
53
|
+
"dev": "tsdown && node dist/main.mjs"
|
|
54
|
+
}
|
|
55
|
+
}
|