@werunfoundry/api 0.0.0-stage → 0.1.0-main.gcd7ba83
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 +201 -0
- package/dist/bin/serve.d.ts +10 -0
- package/dist/bin/serve.js +52 -0
- package/dist/bin/serve.js.map +1 -0
- package/dist/server.d.ts +43 -0
- package/dist/server.js +190 -0
- package/dist/server.js.map +1 -0
- package/openapi.json +156 -0
- package/package.json +37 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* kernel-api — serve the kernel's HTTP API (decision 0040), from an
|
|
4
|
+
* instance's root.
|
|
5
|
+
*
|
|
6
|
+
* Needs `KERNEL_API_TOKEN` (at least 32 characters) and `KERNEL_API_PORT`.
|
|
7
|
+
* Listens on `KERNEL_API_HOST`, or on the loopback address when none is
|
|
8
|
+
* given: exposing it beyond the machine is the instance's decision to make.
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* kernel-api — serve the kernel's HTTP API (decision 0040), from an
|
|
4
|
+
* instance's root.
|
|
5
|
+
*
|
|
6
|
+
* Needs `KERNEL_API_TOKEN` (at least 32 characters) and `KERNEL_API_PORT`.
|
|
7
|
+
* Listens on `KERNEL_API_HOST`, or on the loopback address when none is
|
|
8
|
+
* given: exposing it beyond the machine is the instance's decision to make.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { createServer } from "node:http";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { boot } from "@werunfoundry/core/runtime/boot";
|
|
14
|
+
import { connect } from "@werunfoundry/core/runtime/connect";
|
|
15
|
+
import { createApi, MIN_TOKEN } from "../server.js";
|
|
16
|
+
async function main() {
|
|
17
|
+
const root = process.cwd();
|
|
18
|
+
const envFile = join(root, ".env");
|
|
19
|
+
if (existsSync(envFile))
|
|
20
|
+
process.loadEnvFile(envFile);
|
|
21
|
+
const token = process.env.KERNEL_API_TOKEN ?? "";
|
|
22
|
+
const port = Number(process.env.KERNEL_API_PORT);
|
|
23
|
+
if (token.length < MIN_TOKEN) {
|
|
24
|
+
console.log(`api: KERNEL_API_TOKEN is required, at least ${MIN_TOKEN} characters. Nothing was started.`);
|
|
25
|
+
return 1;
|
|
26
|
+
}
|
|
27
|
+
if (!Number.isInteger(port) || port < 1) {
|
|
28
|
+
console.log("api: KERNEL_API_PORT is required. Nothing was started.");
|
|
29
|
+
return 1;
|
|
30
|
+
}
|
|
31
|
+
const booted = await boot({ root, env: process.env });
|
|
32
|
+
if (!booted.ok) {
|
|
33
|
+
for (const i of booted.issues)
|
|
34
|
+
console.log(` ✖ ${i.at.replace(`${root}/`, "")}\n ${i.message}`);
|
|
35
|
+
return 1;
|
|
36
|
+
}
|
|
37
|
+
const url = process.env.DATABASE_URL;
|
|
38
|
+
if (!url) {
|
|
39
|
+
console.log("api: DATABASE_URL is not set.");
|
|
40
|
+
return 1;
|
|
41
|
+
}
|
|
42
|
+
const connection = await connect(url, root, "api");
|
|
43
|
+
const host = process.env.KERNEL_API_HOST ?? "127.0.0.1";
|
|
44
|
+
const server = createServer(createApi({ db: connection.db, fingerprints: booted.fingerprints, domains: booted.domains, token }));
|
|
45
|
+
server.listen(port, host, () => console.log(`api: listening on ${host}:${port}`));
|
|
46
|
+
const stop = () => server.close(() => void connection.end().finally(() => process.exit(0)));
|
|
47
|
+
process.on("SIGINT", stop);
|
|
48
|
+
process.on("SIGTERM", stop);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
process.exitCode = await main();
|
|
52
|
+
//# sourceMappingURL=serve.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serve.js","sourceRoot":"","sources":["../../bin/serve.ts"],"names":[],"mappings":";AACA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,oCAAoC,CAAC;AAE7D,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEpD,KAAK,UAAU,IAAI;IACjB,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAC3B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnC,IAAI,UAAU,CAAC,OAAO,CAAC;QAAE,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC;IACjD,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IACjD,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;QAC7B,OAAO,CAAC,GAAG,CAAC,+CAA+C,SAAS,mCAAmC,CAAC,CAAC;QACzG,OAAO,CAAC,CAAC;IACX,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG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,GAAG,EAAE,CAAC,KAAK,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5F,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC3B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC5B,OAAO,CAAC,CAAC;AACX,CAAC;AAED,OAAO,CAAC,QAAQ,GAAG,MAAM,IAAI,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * kernel-api — serve the kernel's HTTP API (decision 0040), from an\n * instance's root.\n *\n * Needs `KERNEL_API_TOKEN` (at least 32 characters) and `KERNEL_API_PORT`.\n * Listens on `KERNEL_API_HOST`, or on the loopback address when none is\n * given: exposing it beyond the machine is the instance's decision to make.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { createServer } from \"node:http\";\nimport { join } from \"node:path\";\n\nimport { boot } from \"@werunfoundry/core/runtime/boot\";\nimport { connect } from \"@werunfoundry/core/runtime/connect\";\n\nimport { createApi, MIN_TOKEN } from \"../server.js\";\n\nasync function main(): Promise<number> {\n const root = process.cwd();\n const envFile = join(root, \".env\");\n if (existsSync(envFile)) process.loadEnvFile(envFile);\n const token = process.env.KERNEL_API_TOKEN ?? \"\";\n const port = Number(process.env.KERNEL_API_PORT);\n if (token.length < MIN_TOKEN) {\n console.log(`api: KERNEL_API_TOKEN is required, at least ${MIN_TOKEN} characters. Nothing was started.`);\n return 1;\n }\n if (!Number.isInteger(port) || port < 1) {\n console.log(\"api: KERNEL_API_PORT is required. Nothing was started.\");\n return 1;\n }\n const booted = await boot({ root, env: process.env });\n if (!booted.ok) {\n for (const i of booted.issues) console.log(` ✖ ${i.at.replace(`${root}/`, \"\")}\\n ${i.message}`);\n return 1;\n }\n const url = process.env.DATABASE_URL;\n if (!url) {\n console.log(\"api: DATABASE_URL is not set.\");\n return 1;\n }\n const connection = await connect(url, root, \"api\");\n const host = process.env.KERNEL_API_HOST ?? \"127.0.0.1\";\n const server = createServer(createApi({ db: connection.db, fingerprints: booted.fingerprints, domains: booted.domains, token }));\n server.listen(port, host, () => console.log(`api: listening on ${host}:${port}`));\n const stop = () => server.close(() => void connection.end().finally(() => process.exit(0)));\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n return 0;\n}\n\nprocess.exitCode = await main();\n"]}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* api — the kernel over HTTP (decision 0040), on Node's own `http`.
|
|
3
|
+
*
|
|
4
|
+
* `openapi.json` is the contract; `routes` below is what serves it, and a
|
|
5
|
+
* test holds the two equal. Three rules, before any route runs:
|
|
6
|
+
*
|
|
7
|
+
* - **The instance's token, or nothing.** A bearer token compared in constant
|
|
8
|
+
* time. It says the caller holds it — not who acts.
|
|
9
|
+
* - **No person over a token.** An actor is attribution, declared by the
|
|
10
|
+
* caller (doctrine 5); any caller can declare any actor, so a request
|
|
11
|
+
* naming `human` is refused, and what only a person may do is not here.
|
|
12
|
+
* - **No event in.** Inbound is pulled (0017); nothing here receives a push.
|
|
13
|
+
*/
|
|
14
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
15
|
+
import type { DomainManifest } from "@werunfoundry/core/manifest/types";
|
|
16
|
+
import type { Fingerprinter } from "@werunfoundry/core/runtime/fingerprint";
|
|
17
|
+
import type { Database } from "@werunfoundry/core/runtime/run";
|
|
18
|
+
export interface ApiDeps {
|
|
19
|
+
db: Database;
|
|
20
|
+
/** What the one reader recognises the register's entries with (0055): boot's. */
|
|
21
|
+
fingerprints: Fingerprinter;
|
|
22
|
+
/** The enabled domains, for what they declare — erasure, today. */
|
|
23
|
+
domains: readonly DomainManifest[];
|
|
24
|
+
token: string;
|
|
25
|
+
}
|
|
26
|
+
type Reply = {
|
|
27
|
+
status: number;
|
|
28
|
+
body: unknown;
|
|
29
|
+
};
|
|
30
|
+
type Handler = (deps: ApiDeps, req: {
|
|
31
|
+
params: Record<string, string>;
|
|
32
|
+
query: URLSearchParams;
|
|
33
|
+
body: unknown;
|
|
34
|
+
}) => Promise<Reply>;
|
|
35
|
+
export declare const MIN_TOKEN = 32;
|
|
36
|
+
export declare const routes: {
|
|
37
|
+
method: string;
|
|
38
|
+
path: string;
|
|
39
|
+
handler: Handler;
|
|
40
|
+
}[];
|
|
41
|
+
/** The request handler. Refuses to exist without a token long enough to be one. */
|
|
42
|
+
export declare function createApi(deps: ApiDeps): (req: IncomingMessage, res: ServerResponse) => void;
|
|
43
|
+
export {};
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* api — the kernel over HTTP (decision 0040), on Node's own `http`.
|
|
3
|
+
*
|
|
4
|
+
* `openapi.json` is the contract; `routes` below is what serves it, and a
|
|
5
|
+
* test holds the two equal. Three rules, before any route runs:
|
|
6
|
+
*
|
|
7
|
+
* - **The instance's token, or nothing.** A bearer token compared in constant
|
|
8
|
+
* time. It says the caller holds it — not who acts.
|
|
9
|
+
* - **No person over a token.** An actor is attribution, declared by the
|
|
10
|
+
* caller (doctrine 5); any caller can declare any actor, so a request
|
|
11
|
+
* naming `human` is refused, and what only a person may do is not here.
|
|
12
|
+
* - **No event in.** Inbound is pulled (0017); nothing here receives a push.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
15
|
+
import { and, asc, eq } from "drizzle-orm";
|
|
16
|
+
import { run } from "@werunfoundry/core/db/schema";
|
|
17
|
+
import { NOT_REACHED, planErasure } from "@werunfoundry/core/runtime/erase";
|
|
18
|
+
import { draft, draftState } from "@werunfoundry/acquisition/db/schema";
|
|
19
|
+
import { propose } from "@werunfoundry/acquisition/runtime/draft";
|
|
20
|
+
import { OPT_OUT_AFTER_ERASURE } from "@werunfoundry/relations/runtime/record";
|
|
21
|
+
export const MIN_TOKEN = 32;
|
|
22
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
23
|
+
const MAX_BODY = 1_000_000;
|
|
24
|
+
class BadRequest extends Error {
|
|
25
|
+
}
|
|
26
|
+
const object = (body) => {
|
|
27
|
+
if (typeof body !== "object" || body === null || Array.isArray(body))
|
|
28
|
+
throw new BadRequest("the body is a JSON object");
|
|
29
|
+
return body;
|
|
30
|
+
};
|
|
31
|
+
const uuid = (v, what) => {
|
|
32
|
+
if (typeof v !== "string" || !UUID.test(v))
|
|
33
|
+
throw new BadRequest(`${what} is a uuid`);
|
|
34
|
+
return v;
|
|
35
|
+
};
|
|
36
|
+
const text = (v, what) => {
|
|
37
|
+
if (typeof v !== "string")
|
|
38
|
+
throw new BadRequest(`${what} is a string`);
|
|
39
|
+
return v;
|
|
40
|
+
};
|
|
41
|
+
const integer = (v, what, min) => {
|
|
42
|
+
if (!Number.isInteger(v) || v < min)
|
|
43
|
+
throw new BadRequest(`${what} is an integer, at least ${min}`);
|
|
44
|
+
return v;
|
|
45
|
+
};
|
|
46
|
+
/** The actor as declared; a person is refused, because a token cannot say one acts. */
|
|
47
|
+
function actorOf(v) {
|
|
48
|
+
const a = object(v);
|
|
49
|
+
if (a.type === "human")
|
|
50
|
+
return { status: 403, body: { refused: "a person cannot act through this API: its token says who holds it, not who acts (decision 0040)" } };
|
|
51
|
+
if (a.type !== "agent" && a.type !== "system")
|
|
52
|
+
throw new BadRequest("actor.type is agent or system");
|
|
53
|
+
if (a.id !== undefined && typeof a.id !== "string")
|
|
54
|
+
throw new BadRequest("actor.id is a string");
|
|
55
|
+
return { type: a.type, ...(typeof a.id === "string" ? { id: a.id } : {}) };
|
|
56
|
+
}
|
|
57
|
+
const draftView = (d) => ({
|
|
58
|
+
id: d.id,
|
|
59
|
+
experimentId: d.experimentId,
|
|
60
|
+
personId: d.personId,
|
|
61
|
+
step: d.step,
|
|
62
|
+
state: d.state,
|
|
63
|
+
renderedSubject: d.renderedSubject,
|
|
64
|
+
renderedBody: d.renderedBody,
|
|
65
|
+
decidedBy: d.decidedBy,
|
|
66
|
+
});
|
|
67
|
+
export const routes = [
|
|
68
|
+
{ method: "get", path: "/v1/health", handler: async () => ({ status: 200, body: { ok: true } }) },
|
|
69
|
+
{
|
|
70
|
+
method: "get",
|
|
71
|
+
path: "/v1/runs/{id}",
|
|
72
|
+
handler: async ({ db }, { params }) => {
|
|
73
|
+
const [r] = await db.select().from(run).where(eq(run.id, uuid(params.id, "the run id")));
|
|
74
|
+
if (!r)
|
|
75
|
+
return { status: 404, body: { refused: "no such run" } };
|
|
76
|
+
const { id, processKey, status, actorType, actorId, dryRun, startedAt, finishedAt, error } = r;
|
|
77
|
+
return { status: 200, body: { id, processKey, status, actorType, actorId, dryRun, startedAt, finishedAt, error } };
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
method: "get",
|
|
82
|
+
path: "/v1/drafts",
|
|
83
|
+
handler: async ({ db }, { query }) => {
|
|
84
|
+
const state = query.get("state");
|
|
85
|
+
if (!state || !draftState.enumValues.includes(state))
|
|
86
|
+
throw new BadRequest(`state is one of ${draftState.enumValues.join(", ")}`);
|
|
87
|
+
const rows = await db
|
|
88
|
+
.select()
|
|
89
|
+
.from(draft)
|
|
90
|
+
.where(and(eq(draft.state, state)))
|
|
91
|
+
.orderBy(asc(draft.createdAt))
|
|
92
|
+
.limit(100);
|
|
93
|
+
return { status: 200, body: { drafts: rows.map(draftView) } };
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
method: "post",
|
|
98
|
+
path: "/v1/drafts",
|
|
99
|
+
handler: async ({ db, fingerprints }, { body }) => {
|
|
100
|
+
const b = object(body);
|
|
101
|
+
const allowed = new Set(["experimentId", "personId", "step", "templateId", "renderedSubject", "renderedBody", "sender", "autonomyAfter", "reactiveWithinMinutes", "actor", "runId"]);
|
|
102
|
+
for (const k of Object.keys(b))
|
|
103
|
+
if (!allowed.has(k))
|
|
104
|
+
throw new BadRequest(`${k} is not a field of this operation`);
|
|
105
|
+
const actor = actorOf(b.actor);
|
|
106
|
+
if ("status" in actor)
|
|
107
|
+
return actor;
|
|
108
|
+
const proposed = await propose(db, fingerprints, {
|
|
109
|
+
experimentId: uuid(b.experimentId, "experimentId"),
|
|
110
|
+
personId: uuid(b.personId, "personId"),
|
|
111
|
+
step: integer(b.step, "step", 0),
|
|
112
|
+
...(b.templateId !== undefined ? { templateId: uuid(b.templateId, "templateId") } : {}),
|
|
113
|
+
renderedBody: text(b.renderedBody, "renderedBody"),
|
|
114
|
+
...(b.renderedSubject !== undefined ? { renderedSubject: text(b.renderedSubject, "renderedSubject") } : {}),
|
|
115
|
+
...(b.sender !== undefined ? { sender: text(b.sender, "sender") } : {}),
|
|
116
|
+
}, { actor, ...(b.runId !== undefined ? { runId: uuid(b.runId, "runId") } : {}) }, {
|
|
117
|
+
autonomyAfter: integer(b.autonomyAfter, "autonomyAfter", 1),
|
|
118
|
+
...(b.reactiveWithinMinutes !== undefined ? { reactiveWithinMinutes: integer(b.reactiveWithinMinutes, "reactiveWithinMinutes", 1) } : {}),
|
|
119
|
+
});
|
|
120
|
+
if (!proposed.ok)
|
|
121
|
+
return { status: 422, body: { refused: proposed.refused } };
|
|
122
|
+
return { status: 201, body: { outcome: proposed.outcome, draft: draftView(proposed.draft) } };
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
method: "get",
|
|
127
|
+
path: "/v1/people/{id}/erasure",
|
|
128
|
+
// What it does not reach goes with it: a plan silent about it would read as coverage (0049).
|
|
129
|
+
handler: async ({ db, domains }, { params }) => ({
|
|
130
|
+
status: 200,
|
|
131
|
+
body: { steps: await planErasure(db, domains, uuid(params.id, "the person id")), notReached: [...NOT_REACHED, OPT_OUT_AFTER_ERASURE] },
|
|
132
|
+
}),
|
|
133
|
+
},
|
|
134
|
+
];
|
|
135
|
+
const compiled = routes.map((r) => ({
|
|
136
|
+
...r,
|
|
137
|
+
pattern: new RegExp(`^${r.path.replace(/\{(\w+)\}/g, "(?<$1>[^/]+)")}$`),
|
|
138
|
+
}));
|
|
139
|
+
const digest = (s) => createHash("sha256").update(s).digest();
|
|
140
|
+
/** The request handler. Refuses to exist without a token long enough to be one. */
|
|
141
|
+
export function createApi(deps) {
|
|
142
|
+
if (typeof deps.token !== "string" || deps.token.length < MIN_TOKEN)
|
|
143
|
+
throw new Error(`the API needs the instance's token, at least ${MIN_TOKEN} characters`);
|
|
144
|
+
const expected = digest(deps.token);
|
|
145
|
+
const send = (res, reply) => {
|
|
146
|
+
res.writeHead(reply.status, { "content-type": "application/json" });
|
|
147
|
+
res.end(JSON.stringify(reply.body));
|
|
148
|
+
};
|
|
149
|
+
return (req, res) => {
|
|
150
|
+
void (async () => {
|
|
151
|
+
const header = req.headers.authorization ?? "";
|
|
152
|
+
const given = header.startsWith("Bearer ") ? header.slice(7) : "";
|
|
153
|
+
// Hashed first, so the comparison takes the same time whatever the length.
|
|
154
|
+
if (!timingSafeEqual(digest(given), expected))
|
|
155
|
+
return send(res, { status: 401, body: { refused: "the instance's token is required" } });
|
|
156
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
157
|
+
const method = (req.method ?? "GET").toLowerCase();
|
|
158
|
+
const route = compiled.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
159
|
+
if (!route)
|
|
160
|
+
return send(res, { status: 404, body: { refused: "no such operation" } });
|
|
161
|
+
let body;
|
|
162
|
+
if (method === "post") {
|
|
163
|
+
const chunks = [];
|
|
164
|
+
let size = 0;
|
|
165
|
+
for await (const chunk of req) {
|
|
166
|
+
size += chunk.length;
|
|
167
|
+
if (size > MAX_BODY)
|
|
168
|
+
return send(res, { status: 400, body: { refused: "the body is too large" } });
|
|
169
|
+
chunks.push(chunk);
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return send(res, { status: 400, body: { refused: "the body is not JSON" } });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
const params = (route.pattern.exec(url.pathname)?.groups ?? {});
|
|
180
|
+
send(res, await route.handler(deps, { params, query: url.searchParams, body }));
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
if (error instanceof BadRequest)
|
|
184
|
+
return send(res, { status: 400, body: { refused: error.message } });
|
|
185
|
+
send(res, { status: 500, body: { refused: "the operation failed; the run, if one was opened, says why" } });
|
|
186
|
+
}
|
|
187
|
+
})();
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG1D,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,EAAE,GAAG,EAAE,MAAM,8BAA8B,CAAC;AAEnD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAG5E,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,MAAM,yCAAyC,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAc/E,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAC5B,MAAM,IAAI,GAAG,iEAAiE,CAAC;AAC/E,MAAM,QAAQ,GAAG,SAAS,CAAC;AAE3B,MAAM,UAAW,SAAQ,KAAK;CAAG;AAEjC,MAAM,MAAM,GAAG,CAAC,IAAa,EAA2B,EAAE;IACxD,IAAI,O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,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;gBACrG,IAAI,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,4DAA4D,EAAE,EAAE,CAAC,CAAC;YAC9G,CAAC;QACH,CAAC,CAAC,EAAE,CAAC;IACP,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * api — the kernel over HTTP (decision 0040), on Node's own `http`.\n *\n * `openapi.json` is the contract; `routes` below is what serves it, and a\n * test holds the two equal. Three rules, before any route runs:\n *\n * - **The instance's token, or nothing.** A bearer token compared in constant\n * time. It says the caller holds it — not who acts.\n * - **No person over a token.** An actor is attribution, declared by the\n * caller (doctrine 5); any caller can declare any actor, so a request\n * naming `human` is refused, and what only a person may do is not here.\n * - **No event in.** Inbound is pulled (0017); nothing here receives a push.\n */\n\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { and, asc, eq } from \"drizzle-orm\";\n\nimport { run } from \"@werunfoundry/core/db/schema\";\nimport type { DomainManifest } from \"@werunfoundry/core/manifest/types\";\nimport { NOT_REACHED, planErasure } from \"@werunfoundry/core/runtime/erase\";\nimport type { Fingerprinter } from \"@werunfoundry/core/runtime/fingerprint\";\nimport type { Database } from \"@werunfoundry/core/runtime/run\";\nimport { draft, draftState } from \"@werunfoundry/acquisition/db/schema\";\nimport { propose } from \"@werunfoundry/acquisition/runtime/draft\";\nimport { OPT_OUT_AFTER_ERASURE } from \"@werunfoundry/relations/runtime/record\";\n\nexport interface ApiDeps {\n db: Database;\n /** What the one reader recognises the register's entries with (0055): boot's. */\n fingerprints: Fingerprinter;\n /** The enabled domains, for what they declare — erasure, today. */\n domains: readonly DomainManifest[];\n token: string;\n}\n\ntype Reply = { status: number; body: unknown };\ntype Handler = (deps: ApiDeps, req: { params: Record<string, string>; query: URLSearchParams; body: unknown }) => Promise<Reply>;\n\nexport const MIN_TOKEN = 32;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst MAX_BODY = 1_000_000;\n\nclass BadRequest extends Error {}\n\nconst object = (body: unknown): Record<string, unknown> => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) throw new BadRequest(\"the body is a JSON object\");\n return body as Record<string, unknown>;\n};\nconst uuid = (v: unknown, what: string) => {\n if (typeof v !== \"string\" || !UUID.test(v)) throw new BadRequest(`${what} is a uuid`);\n return v;\n};\nconst text = (v: unknown, what: string) => {\n if (typeof v !== \"string\") throw new BadRequest(`${what} is a string`);\n return v;\n};\nconst integer = (v: unknown, what: string, min: number) => {\n if (!Number.isInteger(v) || (v as number) < min) throw new BadRequest(`${what} is an integer, at least ${min}`);\n return v as number;\n};\n\n/** The actor as declared; a person is refused, because a token cannot say one acts. */\nfunction actorOf(v: unknown): { type: \"agent\" | \"system\"; id?: string } | Reply {\n const a = object(v);\n if (a.type === \"human\") return { status: 403, body: { refused: \"a person cannot act through this API: its token says who holds it, not who acts (decision 0040)\" } };\n if (a.type !== \"agent\" && a.type !== \"system\") throw new BadRequest(\"actor.type is agent or system\");\n if (a.id !== undefined && typeof a.id !== \"string\") throw new BadRequest(\"actor.id is a string\");\n return { type: a.type, ...(typeof a.id === \"string\" ? { id: a.id } : {}) };\n}\n\nconst draftView = (d: typeof draft.$inferSelect) => ({\n id: d.id,\n experimentId: d.experimentId,\n personId: d.personId,\n step: d.step,\n state: d.state,\n renderedSubject: d.renderedSubject,\n renderedBody: d.renderedBody,\n decidedBy: d.decidedBy,\n});\n\nexport const routes: { method: string; path: string; handler: Handler }[] = [\n { method: \"get\", path: \"/v1/health\", handler: async () => ({ status: 200, body: { ok: true } }) },\n {\n method: \"get\",\n path: \"/v1/runs/{id}\",\n handler: async ({ db }, { params }) => {\n const [r] = await db.select().from(run).where(eq(run.id, uuid(params.id, \"the run id\")));\n if (!r) return { status: 404, body: { refused: \"no such run\" } };\n const { id, processKey, status, actorType, actorId, dryRun, startedAt, finishedAt, error } = r;\n return { status: 200, body: { id, processKey, status, actorType, actorId, dryRun, startedAt, finishedAt, error } };\n },\n },\n {\n method: \"get\",\n path: \"/v1/drafts\",\n handler: async ({ db }, { query }) => {\n const state = query.get(\"state\");\n if (!state || !(draftState.enumValues as readonly string[]).includes(state)) throw new BadRequest(`state is one of ${draftState.enumValues.join(\", \")}`);\n const rows = await db\n .select()\n .from(draft)\n .where(and(eq(draft.state, state as (typeof draftState.enumValues)[number])))\n .orderBy(asc(draft.createdAt))\n .limit(100);\n return { status: 200, body: { drafts: rows.map(draftView) } };\n },\n },\n {\n method: \"post\",\n path: \"/v1/drafts\",\n handler: async ({ db, fingerprints }, { body }) => {\n const b = object(body);\n const allowed = new Set([\"experimentId\", \"personId\", \"step\", \"templateId\", \"renderedSubject\", \"renderedBody\", \"sender\", \"autonomyAfter\", \"reactiveWithinMinutes\", \"actor\", \"runId\"]);\n for (const k of Object.keys(b)) if (!allowed.has(k)) throw new BadRequest(`${k} is not a field of this operation`);\n const actor = actorOf(b.actor);\n if (\"status\" in actor) return actor;\n const proposed = await propose(\n db,\n fingerprints,\n {\n experimentId: uuid(b.experimentId, \"experimentId\"),\n personId: uuid(b.personId, \"personId\"),\n step: integer(b.step, \"step\", 0),\n ...(b.templateId !== undefined ? { templateId: uuid(b.templateId, \"templateId\") } : {}),\n renderedBody: text(b.renderedBody, \"renderedBody\"),\n ...(b.renderedSubject !== undefined ? { renderedSubject: text(b.renderedSubject, \"renderedSubject\") } : {}),\n ...(b.sender !== undefined ? { sender: text(b.sender, \"sender\") } : {}),\n },\n { actor, ...(b.runId !== undefined ? { runId: uuid(b.runId, \"runId\") } : {}) },\n {\n autonomyAfter: integer(b.autonomyAfter, \"autonomyAfter\", 1),\n ...(b.reactiveWithinMinutes !== undefined ? { reactiveWithinMinutes: integer(b.reactiveWithinMinutes, \"reactiveWithinMinutes\", 1) } : {}),\n },\n );\n if (!proposed.ok) return { status: 422, body: { refused: proposed.refused } };\n return { status: 201, body: { outcome: proposed.outcome, draft: draftView(proposed.draft) } };\n },\n },\n {\n method: \"get\",\n path: \"/v1/people/{id}/erasure\",\n // What it does not reach goes with it: a plan silent about it would read as coverage (0049).\n handler: async ({ db, domains }, { params }) => ({\n status: 200,\n body: { steps: await planErasure(db, domains, uuid(params.id, \"the person id\")), notReached: [...NOT_REACHED, OPT_OUT_AFTER_ERASURE] },\n }),\n },\n];\n\nconst compiled = routes.map((r) => ({\n ...r,\n pattern: new RegExp(`^${r.path.replace(/\\{(\\w+)\\}/g, \"(?<$1>[^/]+)\")}$`),\n}));\n\nconst digest = (s: string) => createHash(\"sha256\").update(s).digest();\n\n/** The request handler. Refuses to exist without a token long enough to be one. */\nexport function createApi(deps: ApiDeps): (req: IncomingMessage, res: ServerResponse) => void {\n if (typeof deps.token !== \"string\" || deps.token.length < MIN_TOKEN) throw new Error(`the API needs the instance's token, at least ${MIN_TOKEN} characters`);\n const expected = digest(deps.token);\n\n const send = (res: ServerResponse, reply: Reply) => {\n res.writeHead(reply.status, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(reply.body));\n };\n\n return (req, res) => {\n void (async () => {\n const header = req.headers.authorization ?? \"\";\n const given = header.startsWith(\"Bearer \") ? header.slice(7) : \"\";\n // Hashed first, so the comparison takes the same time whatever the length.\n if (!timingSafeEqual(digest(given), expected)) return send(res, { status: 401, body: { refused: \"the instance's token is required\" } });\n\n const url = new URL(req.url ?? \"/\", \"http://localhost\");\n const method = (req.method ?? \"GET\").toLowerCase();\n const route = compiled.find((r) => r.method === method && r.pattern.test(url.pathname));\n if (!route) return send(res, { status: 404, body: { refused: \"no such operation\" } });\n\n let body: unknown;\n if (method === \"post\") {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of req) {\n size += (chunk as Buffer).length;\n if (size > MAX_BODY) return send(res, { status: 400, body: { refused: \"the body is too large\" } });\n chunks.push(chunk as Buffer);\n }\n try {\n body = JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n return send(res, { status: 400, body: { refused: \"the body is not JSON\" } });\n }\n }\n try {\n const params = (route.pattern.exec(url.pathname)?.groups ?? {}) as Record<string, string>;\n send(res, await route.handler(deps, { params, query: url.searchParams, body }));\n } catch (error) {\n if (error instanceof BadRequest) return send(res, { status: 400, body: { refused: error.message } });\n send(res, { status: 500, body: { refused: \"the operation failed; the run, if one was opened, says why\" } });\n }\n })();\n };\n}\n"]}
|
package/openapi.json
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
{
|
|
2
|
+
"openapi": "3.1.0",
|
|
3
|
+
"info": {
|
|
4
|
+
"title": "kernel",
|
|
5
|
+
"version": "0.1.0",
|
|
6
|
+
"description": "The kernel's HTTP API (decision 0040). One bearer token per instance; it says the caller holds it, not who acts. An actor is declared, as attribution, and may not be a person: what only a person may do is not on this API."
|
|
7
|
+
},
|
|
8
|
+
"security": [{ "instanceToken": [] }],
|
|
9
|
+
"components": {
|
|
10
|
+
"securitySchemes": {
|
|
11
|
+
"instanceToken": { "type": "http", "scheme": "bearer", "description": "The instance's token, at least 32 characters." }
|
|
12
|
+
},
|
|
13
|
+
"schemas": {
|
|
14
|
+
"Actor": {
|
|
15
|
+
"type": "object",
|
|
16
|
+
"required": ["type"],
|
|
17
|
+
"properties": {
|
|
18
|
+
"type": { "type": "string", "enum": ["agent", "system"], "description": "Never `human`: a token cannot say a person acts." },
|
|
19
|
+
"id": { "type": "string" }
|
|
20
|
+
},
|
|
21
|
+
"additionalProperties": false
|
|
22
|
+
},
|
|
23
|
+
"Refused": {
|
|
24
|
+
"type": "object",
|
|
25
|
+
"required": ["refused"],
|
|
26
|
+
"properties": { "refused": { "type": "string" } }
|
|
27
|
+
},
|
|
28
|
+
"Run": {
|
|
29
|
+
"type": "object",
|
|
30
|
+
"required": ["id", "processKey", "status", "actorType", "dryRun", "startedAt"],
|
|
31
|
+
"properties": {
|
|
32
|
+
"id": { "type": "string", "format": "uuid" },
|
|
33
|
+
"processKey": { "type": "string" },
|
|
34
|
+
"status": { "type": "string", "enum": ["running", "succeeded", "partial", "failed", "cancelled"] },
|
|
35
|
+
"actorType": { "type": "string", "enum": ["human", "agent", "system"] },
|
|
36
|
+
"actorId": { "type": ["string", "null"] },
|
|
37
|
+
"dryRun": { "type": "boolean" },
|
|
38
|
+
"startedAt": { "type": "string", "format": "date-time" },
|
|
39
|
+
"finishedAt": { "type": ["string", "null"], "format": "date-time" },
|
|
40
|
+
"error": { "type": ["string", "null"] }
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"Draft": {
|
|
44
|
+
"type": "object",
|
|
45
|
+
"required": ["id", "experimentId", "personId", "step", "state"],
|
|
46
|
+
"properties": {
|
|
47
|
+
"id": { "type": "string", "format": "uuid" },
|
|
48
|
+
"experimentId": { "type": "string", "format": "uuid" },
|
|
49
|
+
"personId": { "type": "string", "format": "uuid" },
|
|
50
|
+
"step": { "type": "integer" },
|
|
51
|
+
"state": { "type": "string", "enum": ["drafting", "awaiting_review", "approved", "dropped", "queued", "sent", "failed"] },
|
|
52
|
+
"renderedSubject": { "type": ["string", "null"] },
|
|
53
|
+
"renderedBody": { "type": ["string", "null"] },
|
|
54
|
+
"decidedBy": { "type": ["string", "null"] }
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"ErasureStep": {
|
|
58
|
+
"type": "object",
|
|
59
|
+
"required": ["domain", "table", "do", "rows"],
|
|
60
|
+
"properties": {
|
|
61
|
+
"domain": { "type": "string" },
|
|
62
|
+
"table": { "type": "string" },
|
|
63
|
+
"column": { "type": "string", "description": "The column naming the person by id, when the rule reaches rows that way." },
|
|
64
|
+
"keys": { "type": "string", "description": "The column holding an identity, when the rule reaches rows by the person's keys (decision 0049)." },
|
|
65
|
+
"do": { "type": "string", "enum": ["delete", "anonymise", "keep"] },
|
|
66
|
+
"rows": { "type": "integer", "description": "Rows naming the person, by id or by keys." },
|
|
67
|
+
"byKeys": { "type": "integer", "description": "Of those, the rows reached only by keys." },
|
|
68
|
+
"basis": { "type": "string" }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
"paths": {
|
|
74
|
+
"/v1/health": {
|
|
75
|
+
"get": {
|
|
76
|
+
"operationId": "health",
|
|
77
|
+
"summary": "The API answers, and the token is the instance's.",
|
|
78
|
+
"responses": {
|
|
79
|
+
"200": { "description": "Up.", "content": { "application/json": { "schema": { "type": "object", "properties": { "ok": { "const": true } } } } } },
|
|
80
|
+
"401": { "description": "No token, or not the instance's." }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
"/v1/runs/{id}": {
|
|
85
|
+
"get": {
|
|
86
|
+
"operationId": "getRun",
|
|
87
|
+
"summary": "One run, as recorded.",
|
|
88
|
+
"parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
|
|
89
|
+
"responses": {
|
|
90
|
+
"200": { "description": "The run.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Run" } } } },
|
|
91
|
+
"401": { "description": "No token, or not the instance's." },
|
|
92
|
+
"404": { "description": "No such run." }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
"/v1/drafts": {
|
|
97
|
+
"get": {
|
|
98
|
+
"operationId": "listDrafts",
|
|
99
|
+
"summary": "Drafts in one state, oldest first, at most 100.",
|
|
100
|
+
"parameters": [{ "name": "state", "in": "query", "required": true, "schema": { "type": "string", "enum": ["drafting", "awaiting_review", "approved", "dropped", "queued", "sent", "failed"] } }],
|
|
101
|
+
"responses": {
|
|
102
|
+
"200": { "description": "The drafts.", "content": { "application/json": { "schema": { "type": "object", "properties": { "drafts": { "type": "array", "items": { "$ref": "#/components/schemas/Draft" } } } } } } },
|
|
103
|
+
"400": { "description": "No state, or not one." },
|
|
104
|
+
"401": { "description": "No token, or not the instance's." }
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
"post": {
|
|
108
|
+
"operationId": "proposeDraft",
|
|
109
|
+
"summary": "Propose a draft. It waits on its experiment's lane (decisions 0027, 0042); approving it is a person's act and is not on this API.",
|
|
110
|
+
"requestBody": {
|
|
111
|
+
"required": true,
|
|
112
|
+
"content": {
|
|
113
|
+
"application/json": {
|
|
114
|
+
"schema": {
|
|
115
|
+
"type": "object",
|
|
116
|
+
"required": ["experimentId", "personId", "step", "renderedBody", "autonomyAfter", "actor"],
|
|
117
|
+
"properties": {
|
|
118
|
+
"experimentId": { "type": "string", "format": "uuid" },
|
|
119
|
+
"personId": { "type": "string", "format": "uuid" },
|
|
120
|
+
"step": { "type": "integer", "minimum": 0 },
|
|
121
|
+
"templateId": { "type": "string", "format": "uuid", "description": "The template rendered. Its channel is the draft's: what a reactive lane checks the person's inbound touch against (decision 0042)." },
|
|
122
|
+
"renderedSubject": { "type": "string" },
|
|
123
|
+
"renderedBody": { "type": "string" },
|
|
124
|
+
"sender": { "type": "string" },
|
|
125
|
+
"autonomyAfter": { "type": "integer", "minimum": 1, "description": "No default: consecutive clean human approvals after which an autonomous lane approves." },
|
|
126
|
+
"reactiveWithinMinutes": { "type": "integer", "minimum": 1, "description": "No default: how recent the person's inbound touch must be for a reactive lane to approve on its own (decision 0042). Without it, a person approves." },
|
|
127
|
+
"actor": { "$ref": "#/components/schemas/Actor" },
|
|
128
|
+
"runId": { "type": "string", "format": "uuid" }
|
|
129
|
+
},
|
|
130
|
+
"additionalProperties": false
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
"responses": {
|
|
136
|
+
"201": { "description": "Proposed: awaiting review, approved by its lane, or kept as it was.", "content": { "application/json": { "schema": { "type": "object", "properties": { "outcome": { "type": "string" }, "draft": { "$ref": "#/components/schemas/Draft" } } } } } },
|
|
137
|
+
"400": { "description": "The body is not what this operation takes." },
|
|
138
|
+
"401": { "description": "No token, or not the instance's." },
|
|
139
|
+
"403": { "description": "A person was named as the actor.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Refused" } } } },
|
|
140
|
+
"422": { "description": "The gate refused it.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Refused" } } } }
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
"/v1/people/{id}/erasure": {
|
|
145
|
+
"get": {
|
|
146
|
+
"operationId": "planErasure",
|
|
147
|
+
"summary": "What erasing this person would do, as each domain declares it (decisions 0040, 0049), and what it does not reach. Changes nothing; erasing is a person's act, at a terminal.",
|
|
148
|
+
"parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }],
|
|
149
|
+
"responses": {
|
|
150
|
+
"200": { "description": "The plan.", "content": { "application/json": { "schema": { "type": "object", "properties": { "steps": { "type": "array", "items": { "$ref": "#/components/schemas/ErasureStep" } }, "notReached": { "type": "array", "items": { "type": "string" } } } } } } },
|
|
151
|
+
"401": { "description": "No token, or not the instance's." }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@werunfoundry/api",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-main.gcd7ba83",
|
|
4
|
+
"description": "The kernel over HTTP, described by OpenAPI.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/werunfoundry/kernel",
|
|
9
|
+
"directory": "api"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/server.d.ts",
|
|
15
|
+
"default": "./dist/server.js"
|
|
16
|
+
},
|
|
17
|
+
"./openapi.json": "./openapi.json"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"drizzle-orm": "^0.45.2",
|
|
24
|
+
"@werunfoundry/acquisition": "0.1.0-main.gcd7ba83",
|
|
25
|
+
"@werunfoundry/core": "0.1.0-main.gcd7ba83",
|
|
26
|
+
"@werunfoundry/relations": "0.1.0-main.gcd7ba83"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"openapi.json",
|
|
31
|
+
"!dist/*.tsbuildinfo"
|
|
32
|
+
],
|
|
33
|
+
"bin": {
|
|
34
|
+
"kernel-api": "./dist/bin/serve.js"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsc -b tsconfig.build.json",
|
|
38
|
+
"typecheck": "tsc --noEmit"
|
|
39
|
+
}
|
|
6
40
|
}
|
package/README.md
DELETED