@orthograph/logbook 0.0.0-stage → 0.1.0-next.1
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/README.md +9 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/main.d.ts +6 -0
- package/dist/main.js +19 -0
- package/dist/modules/book/internal/sql.d.ts +10 -0
- package/dist/modules/book/internal/sql.js +50 -0
- package/dist/modules/book/service.d.ts +11 -0
- package/dist/modules/book/service.js +25 -0
- package/dist/modules/book/types.d.ts +61 -0
- package/dist/modules/book/types.js +1 -0
- package/dist/modules/http/internal/body.d.ts +23 -0
- package/dist/modules/http/internal/body.js +29 -0
- package/dist/modules/http/internal/respond.d.ts +8 -0
- package/dist/modules/http/internal/respond.js +14 -0
- package/dist/modules/http/internal/routes.d.ts +13 -0
- package/dist/modules/http/internal/routes.js +36 -0
- package/dist/modules/http/internal/stores.d.ts +8 -0
- package/dist/modules/http/internal/stores.js +24 -0
- package/dist/modules/http/service.d.ts +2 -0
- package/dist/modules/http/service.js +32 -0
- package/dist/modules/http/types.d.ts +59 -0
- package/dist/modules/http/types.js +11 -0
- package/dist/modules/local/internal/wrangler.d.ts +7 -0
- package/dist/modules/local/internal/wrangler.js +34 -0
- package/dist/modules/local/service.d.ts +2 -0
- package/dist/modules/local/service.js +23 -0
- package/dist/modules/local/types.d.ts +44 -0
- package/dist/modules/local/types.js +4 -0
- package/dist/modules/tokens/internal/policy.d.ts +10 -0
- package/dist/modules/tokens/internal/policy.js +33 -0
- package/dist/modules/tokens/internal/verify.d.ts +5 -0
- package/dist/modules/tokens/internal/verify.js +16 -0
- package/dist/modules/tokens/service.d.ts +2 -0
- package/dist/modules/tokens/service.js +37 -0
- package/dist/modules/tokens/types.d.ts +56 -0
- package/dist/modules/tokens/types.js +8 -0
- package/package.json +30 -3
- package/src/main.ts +27 -0
- package/wrangler.jsonc +11 -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/README.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @orthograph/logbook
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Verdicts and the model, kept per project (D3 #3, #8; decisions #30 to #34). A worker on workerd: a Durable Object holds
|
|
4
|
+
the verdicts and releases, R2 holds each revision's model, and every write needs an OIDC token from the one issuer its
|
|
5
|
+
environment names. The routes are listed in `src/modules/http/types.ts`.
|
|
6
|
+
|
|
7
|
+
- `src/main.ts` is the worker's entry; `wrangler.jsonc` its bindings.
|
|
8
|
+
- The package's export is how to run it: `Logbook.launch`, `.ready`, `.discoverJwks`, `.start` (module `local`).
|
|
9
|
+
- Modules: `tokens` (verification and policy), `book` (the ledger), `http` (routes), `local` (running it here).
|
|
10
|
+
- Test: `nx test logbook` runs the worker under `wrangler dev` on ports 8930 to 8949 with a OIDC issuer process (@orthograph/services).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Logbook } from "#modules/local/service.js";
|
|
2
|
+
export type { Launch, LaunchOptions, LogbookApi, LogbookPolicy, Running } from "#modules/local/types.js";
|
|
3
|
+
export { LogbookFailed } from "#modules/local/types.js";
|
|
4
|
+
export type { Release, StoredVerdict, VerdictFilter, VerdictInput, VerdictValue } from "#modules/book/types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @orthograph/logbook: verdicts and the model, kept per project (D3 #3, #8). The worker itself is `main.ts`, bundled by wrangler;
|
|
2
|
+
// what other packages import is how to run it (`Logbook`) and the shapes it answers with.
|
|
3
|
+
export { Logbook } from "#modules/local/service.js";
|
|
4
|
+
export { LogbookFailed } from "#modules/local/types.js";
|
package/dist/main.d.ts
ADDED
package/dist/main.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The logbook worker's entry and composition root (wrangler.jsonc `main`). It is the one place a promise is handed to workerd.
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { Http } from "#modules/http/service.js";
|
|
4
|
+
import { Tokens } from "#modules/tokens/service.js";
|
|
5
|
+
export { Book } from "#modules/book/service.js";
|
|
6
|
+
// One verifier per policy, kept for the life of the isolate so jose keeps the issuer's keys cached between requests.
|
|
7
|
+
const verifiers = new Map();
|
|
8
|
+
const tokensFor = (env) => Tokens.fromVars(env).pipe(Effect.map(({ policy, jwksUrl }) => {
|
|
9
|
+
const key = JSON.stringify([policy, jwksUrl]);
|
|
10
|
+
const held = verifiers.get(key);
|
|
11
|
+
if (held !== undefined)
|
|
12
|
+
return held;
|
|
13
|
+
const made = Tokens.remote(policy, jwksUrl);
|
|
14
|
+
verifiers.set(key, made);
|
|
15
|
+
return made;
|
|
16
|
+
}));
|
|
17
|
+
export default {
|
|
18
|
+
fetch: (request, env) => Effect.runPromise(Http.handle(request, env, tokensFor(env))),
|
|
19
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Provenance, Release, StoredVerdict, VerdictFilter, VerdictInput } from "../types.ts";
|
|
2
|
+
export declare const schema: string[];
|
|
3
|
+
/** Expand the persisted book in place. The original create statements remain unchanged for old databases. */
|
|
4
|
+
export declare const initialize: (sql: SqlStorage) => void;
|
|
5
|
+
export declare const insertVerdict: (sql: SqlStorage, v: VerdictInput, from: Provenance) => StoredVerdict;
|
|
6
|
+
export declare const selectAll: (sql: SqlStorage, filter: VerdictFilter) => ReadonlyArray<StoredVerdict>;
|
|
7
|
+
export declare const selectLatest: (sql: SqlStorage, filter: VerdictFilter) => ReadonlyArray<StoredVerdict>;
|
|
8
|
+
export declare const findRelease: (sql: SqlStorage, version: string) => Release | null;
|
|
9
|
+
export declare const insertRelease: (sql: SqlStorage, version: string, revision: string, from: Provenance) => Release;
|
|
10
|
+
export declare const lastRelease: (sql: SqlStorage) => Release | null;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export const schema = [
|
|
2
|
+
`CREATE TABLE IF NOT EXISTS verdicts (
|
|
3
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
|
+
revision TEXT NOT NULL, environment TEXT NOT NULL, operation TEXT NOT NULL, verdict TEXT NOT NULL,
|
|
5
|
+
repository TEXT NOT NULL, ref TEXT NOT NULL, workflow TEXT NOT NULL, event_name TEXT, sha TEXT)`,
|
|
6
|
+
"CREATE INDEX IF NOT EXISTS verdicts_by_revision ON verdicts (revision, environment)",
|
|
7
|
+
`CREATE TABLE IF NOT EXISTS releases (
|
|
8
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
9
|
+
version TEXT NOT NULL UNIQUE, revision TEXT NOT NULL, ref TEXT NOT NULL, event_name TEXT)`,
|
|
10
|
+
];
|
|
11
|
+
/** Expand the persisted book in place. The original create statements remain unchanged for old databases. */
|
|
12
|
+
export const initialize = (sql) => {
|
|
13
|
+
for (const statement of schema)
|
|
14
|
+
sql.exec(statement);
|
|
15
|
+
const columns = sql.exec("PRAGMA table_info(verdicts)").toArray();
|
|
16
|
+
if (!columns.some((column) => column.name === "sha256"))
|
|
17
|
+
sql.exec("ALTER TABLE verdicts ADD COLUMN sha256 TEXT");
|
|
18
|
+
if (!columns.some((column) => column.name === "journeys"))
|
|
19
|
+
sql.exec("ALTER TABLE verdicts ADD COLUMN journeys TEXT");
|
|
20
|
+
};
|
|
21
|
+
const columns = ["revision", "environment", "operation", "ref"];
|
|
22
|
+
/** `WHERE a = ? AND b = ?` for the filters given, and their values in order. */
|
|
23
|
+
const where = (filter) => {
|
|
24
|
+
const given = columns.filter((c) => filter[c] !== undefined);
|
|
25
|
+
return { clause: given.length === 0 ? "" : ` WHERE ${given.map((c) => `${c} = ?`).join(" AND ")}`, values: given.map((c) => filter[c]) };
|
|
26
|
+
};
|
|
27
|
+
const verdictColumns = "seq, revision, environment, operation, verdict, repository, ref, workflow, event_name, sha, sha256, journeys";
|
|
28
|
+
const selectVerdicts = `SELECT ${verdictColumns} FROM verdicts`;
|
|
29
|
+
const verdictOf = (row) => {
|
|
30
|
+
const { journeys, ...stored } = row;
|
|
31
|
+
return {
|
|
32
|
+
...stored,
|
|
33
|
+
...(typeof journeys === "string" ? { journeys: JSON.parse(journeys) } : {}),
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
export const insertVerdict = (sql, v, from) => verdictOf(sql.exec(`INSERT INTO verdicts (revision, environment, operation, verdict, repository, ref, workflow, event_name, sha, sha256, journeys)
|
|
37
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
38
|
+
RETURNING ${verdictColumns}`, v.revision, v.environment, v.operation, v.verdict, from.repository, from.ref, from.workflow, from.eventName, from.sha, v.sha256 ?? null, v.journeys === undefined ? null : JSON.stringify(v.journeys)).one());
|
|
39
|
+
export const selectAll = (sql, filter) => {
|
|
40
|
+
const { clause, values } = where(filter);
|
|
41
|
+
return sql.exec(`${selectVerdicts}${clause} ORDER BY seq`, ...values).toArray().map(verdictOf);
|
|
42
|
+
};
|
|
43
|
+
export const selectLatest = (sql, filter) => {
|
|
44
|
+
const { clause, values } = where(filter);
|
|
45
|
+
return sql.exec(`${selectVerdicts} WHERE seq IN (SELECT MAX(seq) FROM verdicts${clause} GROUP BY environment, operation) ORDER BY environment, operation`, ...values).toArray().map(verdictOf);
|
|
46
|
+
};
|
|
47
|
+
const selectRelease = "SELECT seq, version, revision, ref, event_name FROM releases";
|
|
48
|
+
export const findRelease = (sql, version) => sql.exec(`${selectRelease} WHERE version = ?`, version).toArray()[0] ?? null;
|
|
49
|
+
export const insertRelease = (sql, version, revision, from) => sql.exec("INSERT INTO releases (version, revision, ref, event_name) VALUES (?, ?, ?, ?) RETURNING seq, version, revision, ref, event_name", version, revision, from.ref, from.eventName).one();
|
|
50
|
+
export const lastRelease = (sql) => sql.exec(`${selectRelease} ORDER BY seq DESC LIMIT 1`).toArray()[0] ?? null;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { DurableObject } from "cloudflare:workers";
|
|
2
|
+
import type { BookApi, Provenance, VerdictFilter, VerdictInput } from "./types.ts";
|
|
3
|
+
/** The logbook's Durable Object, bound as `BOOK` and always reached as the one named `book`. Export it from the worker's entry. */
|
|
4
|
+
export declare class Book extends DurableObject<object> implements BookApi {
|
|
5
|
+
constructor(ctx: DurableObjectState, env: object);
|
|
6
|
+
record(verdict: VerdictInput, from: Provenance): import("./types.ts").StoredVerdict;
|
|
7
|
+
verdicts(filter: VerdictFilter): readonly import("./types.ts").StoredVerdict[];
|
|
8
|
+
latest(filter: VerdictFilter): readonly import("./types.ts").StoredVerdict[];
|
|
9
|
+
release(version: string, revision: string, from: Provenance): import("./types.ts").Release | null;
|
|
10
|
+
latestRelease(): import("./types.ts").Release | null;
|
|
11
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DurableObject } from "cloudflare:workers";
|
|
2
|
+
import { findRelease, insertRelease, insertVerdict, lastRelease, initialize, selectAll, selectLatest } from "./internal/sql.js";
|
|
3
|
+
/** The logbook's Durable Object, bound as `BOOK` and always reached as the one named `book`. Export it from the worker's entry. */
|
|
4
|
+
export class Book extends DurableObject {
|
|
5
|
+
constructor(ctx, env) {
|
|
6
|
+
super(ctx, env);
|
|
7
|
+
initialize(ctx.storage.sql);
|
|
8
|
+
}
|
|
9
|
+
record(verdict, from) {
|
|
10
|
+
return insertVerdict(this.ctx.storage.sql, verdict, from);
|
|
11
|
+
}
|
|
12
|
+
verdicts(filter) {
|
|
13
|
+
return selectAll(this.ctx.storage.sql, filter);
|
|
14
|
+
}
|
|
15
|
+
latest(filter) {
|
|
16
|
+
return selectLatest(this.ctx.storage.sql, filter);
|
|
17
|
+
}
|
|
18
|
+
release(version, revision, from) {
|
|
19
|
+
const sql = this.ctx.storage.sql;
|
|
20
|
+
return findRelease(sql, version) !== null ? null : insertRelease(sql, version, revision, from);
|
|
21
|
+
}
|
|
22
|
+
latestRelease() {
|
|
23
|
+
return lastRelease(this.ctx.storage.sql);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export type VerdictValue = "pass" | "fail";
|
|
2
|
+
export interface JourneyVerdict {
|
|
3
|
+
readonly journey: string;
|
|
4
|
+
readonly modelHash: string;
|
|
5
|
+
readonly handlerHash: string | null;
|
|
6
|
+
readonly verdict: VerdictValue;
|
|
7
|
+
}
|
|
8
|
+
/** What a caller posts. `revision` is the job's own field, never the token's `sha` (D3 #8). */
|
|
9
|
+
export interface VerdictInput {
|
|
10
|
+
readonly revision: string;
|
|
11
|
+
readonly environment: string;
|
|
12
|
+
readonly operation: string;
|
|
13
|
+
readonly verdict: VerdictValue;
|
|
14
|
+
/** Bundle proved by this verdict. Absent or null on legacy rows; never inferred or backfilled. */
|
|
15
|
+
readonly sha256?: string | null;
|
|
16
|
+
readonly journeys?: ReadonlyArray<JourneyVerdict>;
|
|
17
|
+
}
|
|
18
|
+
/** Where a write came from: the verified token's claims. Stored with it so a pull request's verdict is never taken for main's. */
|
|
19
|
+
export interface Provenance {
|
|
20
|
+
readonly repository: string;
|
|
21
|
+
readonly ref: string;
|
|
22
|
+
readonly workflow: string;
|
|
23
|
+
readonly eventName: string | null;
|
|
24
|
+
readonly sha: string | null;
|
|
25
|
+
}
|
|
26
|
+
/** A verdict as stored and read back. `seq` orders the whole ledger: the larger is the later. */
|
|
27
|
+
export interface StoredVerdict extends VerdictInput {
|
|
28
|
+
readonly seq: number;
|
|
29
|
+
readonly repository: string;
|
|
30
|
+
readonly ref: string;
|
|
31
|
+
readonly workflow: string;
|
|
32
|
+
readonly event_name: string | null;
|
|
33
|
+
readonly sha: string | null;
|
|
34
|
+
}
|
|
35
|
+
/** Every filter is optional; the ones given must all match. `ref` is how a reader asks for `refs/heads/main` verdicts only. */
|
|
36
|
+
export interface VerdictFilter {
|
|
37
|
+
readonly revision?: string;
|
|
38
|
+
readonly environment?: string;
|
|
39
|
+
readonly operation?: string;
|
|
40
|
+
readonly ref?: string;
|
|
41
|
+
}
|
|
42
|
+
export interface Release {
|
|
43
|
+
readonly seq: number;
|
|
44
|
+
readonly version: string;
|
|
45
|
+
readonly revision: string;
|
|
46
|
+
readonly ref: string;
|
|
47
|
+
readonly event_name: string | null;
|
|
48
|
+
}
|
|
49
|
+
/** The Durable Object's methods, called through its stub. All plain data in and out. */
|
|
50
|
+
export interface BookApi {
|
|
51
|
+
/** Add a verdict. Every post is kept: a revision proven twice has two. */
|
|
52
|
+
readonly record: (verdict: VerdictInput, from: Provenance) => StoredVerdict;
|
|
53
|
+
/** Every verdict matching the filter, oldest first. */
|
|
54
|
+
readonly verdicts: (filter: VerdictFilter) => ReadonlyArray<StoredVerdict>;
|
|
55
|
+
/** The latest verdict of each operation in each environment among those matching the filter. */
|
|
56
|
+
readonly latest: (filter: VerdictFilter) => ReadonlyArray<StoredVerdict>;
|
|
57
|
+
/** Record a production release: the release made, or null when that version was released already. A version is released once. */
|
|
58
|
+
readonly release: (version: string, revision: string, from: Provenance) => Release | null;
|
|
59
|
+
/** The last production release, or null when there is none. */
|
|
60
|
+
readonly latestRelease: () => Release | null;
|
|
61
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import { BadRequest } from "../types.ts";
|
|
3
|
+
export declare const VerdictBody: Schema.Struct<{
|
|
4
|
+
readonly revision: Schema.String;
|
|
5
|
+
readonly environment: Schema.String;
|
|
6
|
+
readonly operation: Schema.String;
|
|
7
|
+
readonly verdict: Schema.Literals<readonly ["pass", "fail"]>;
|
|
8
|
+
readonly sha256: Schema.optionalKey<Schema.String>;
|
|
9
|
+
readonly journeys: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
10
|
+
readonly journey: Schema.String;
|
|
11
|
+
readonly modelHash: Schema.String;
|
|
12
|
+
readonly handlerHash: Schema.NullOr<Schema.String>;
|
|
13
|
+
readonly verdict: Schema.Literals<readonly ["pass", "fail"]>;
|
|
14
|
+
}>>>;
|
|
15
|
+
}>;
|
|
16
|
+
export declare const ReleaseBody: Schema.Struct<{
|
|
17
|
+
readonly version: Schema.String;
|
|
18
|
+
readonly revision: Schema.String;
|
|
19
|
+
}>;
|
|
20
|
+
export declare const isRevision: <I>(input: I) => input is I & string;
|
|
21
|
+
export declare const jsonBody: (request: Request) => Effect.Effect<unknown, BadRequest>;
|
|
22
|
+
/** The request's JSON body, checked against `schema`; a body that doesn't fit is a 400 saying which field. */
|
|
23
|
+
export declare const decoded: <S extends Schema.Decoder<unknown>>(request: Request, schema: S) => Effect.Effect<S["Type"], BadRequest>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import { BadRequest } from "../types.js";
|
|
3
|
+
/** A revision names a model object in R2, so it is a plain token: no slash, no dots-only name. */
|
|
4
|
+
const Revision = Schema.String.check(Schema.isPattern(/^[0-9A-Za-z][0-9A-Za-z._-]{0,99}$/));
|
|
5
|
+
const Name = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(200));
|
|
6
|
+
const Hash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/));
|
|
7
|
+
const Verdict = Schema.Literals(["pass", "fail"]);
|
|
8
|
+
const JourneyVerdict = Schema.Struct({
|
|
9
|
+
journey: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)),
|
|
10
|
+
modelHash: Hash,
|
|
11
|
+
handlerHash: Schema.NullOr(Hash),
|
|
12
|
+
verdict: Verdict,
|
|
13
|
+
});
|
|
14
|
+
export const VerdictBody = Schema.Struct({
|
|
15
|
+
revision: Revision,
|
|
16
|
+
environment: Name,
|
|
17
|
+
operation: Name,
|
|
18
|
+
verdict: Verdict,
|
|
19
|
+
sha256: Schema.optionalKey(Hash),
|
|
20
|
+
journeys: Schema.optionalKey(Schema.Array(JourneyVerdict)),
|
|
21
|
+
});
|
|
22
|
+
export const ReleaseBody = Schema.Struct({
|
|
23
|
+
version: Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/)),
|
|
24
|
+
revision: Revision,
|
|
25
|
+
});
|
|
26
|
+
export const isRevision = Schema.is(Revision);
|
|
27
|
+
export const jsonBody = (request) => Effect.tryPromise({ try: () => request.json(), catch: () => new BadRequest({ reason: "the body is not JSON" }) });
|
|
28
|
+
/** The request's JSON body, checked against `schema`; a body that doesn't fit is a 400 saying which field. */
|
|
29
|
+
export const decoded = (request, schema) => jsonBody(request).pipe(Effect.flatMap((body) => Schema.decodeUnknownEffect(schema)(body)), Effect.mapError((e) => (e instanceof BadRequest ? e : new BadRequest({ reason: `the body is not what ${request.method} ${new URL(request.url).pathname} takes` }))));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { TokenRefused, Misconfigured } from "#modules/tokens/types.js";
|
|
3
|
+
import type { BadRequest, Conflict, NotFound, Unavailable } from "../types.ts";
|
|
4
|
+
export declare const json: (body: unknown, status?: number) => Response;
|
|
5
|
+
export type Failure = TokenRefused | Misconfigured | BadRequest | Conflict | NotFound | Unavailable;
|
|
6
|
+
/** Every failure becomes a status and a reason; a token is never echoed, and a refusal says only which check refused. */
|
|
7
|
+
export declare const failure: (e: Failure) => Response;
|
|
8
|
+
export declare const respond: (run: Effect.Effect<Response, Failure>) => Effect.Effect<Response>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
export const json = (body, status = 200) => Response.json(body, { status });
|
|
3
|
+
/** Every failure becomes a status and a reason; a token is never echoed, and a refusal says only which check refused. */
|
|
4
|
+
export const failure = (e) => {
|
|
5
|
+
switch (e._tag) {
|
|
6
|
+
case "TokenRefused": return json({ ok: false, reason: e.reason }, 401);
|
|
7
|
+
case "Misconfigured": return json({ ok: false, reason: "not configured", missing: e.missing }, 500);
|
|
8
|
+
case "BadRequest": return json({ ok: false, reason: e.reason }, 400);
|
|
9
|
+
case "Conflict": return json({ ok: false, reason: e.reason }, 409);
|
|
10
|
+
case "NotFound": return json({ ok: false, reason: `no ${e.what}` }, 404);
|
|
11
|
+
case "Unavailable": return json({ ok: false, reason: `${e.part} unavailable` }, 500);
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
export const respond = (run) => run.pipe(Effect.catch((e) => Effect.succeed(failure(e))));
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Claims } from "#modules/tokens/types.js";
|
|
3
|
+
import type { VerdictFilter } from "#modules/book/types.js";
|
|
4
|
+
import { BadRequest, Conflict, NotFound, type LogbookEnv } from "../types.ts";
|
|
5
|
+
/** The filters a read takes, from its query string; anything else in it is ignored. */
|
|
6
|
+
export declare const filterOf: (url: URL) => VerdictFilter;
|
|
7
|
+
export declare const postVerdict: (request: Request, env: LogbookEnv, claims: Claims) => Effect.Effect<Response, BadRequest | import("../types.ts").Unavailable, never>;
|
|
8
|
+
export declare const getVerdicts: (url: URL, env: LogbookEnv, latest: boolean) => Effect.Effect<Response, import("../types.ts").Unavailable, never>;
|
|
9
|
+
export declare const getModel: (revision: string, env: LogbookEnv) => Effect.Effect<Response, NotFound | import("../types.ts").Unavailable, never>;
|
|
10
|
+
/** A revision's model is written once. The same model again is fine; a different one is a conflict. */
|
|
11
|
+
export declare const putRevisionModel: (revision: string, request: Request, env: LogbookEnv) => Effect.Effect<Response, BadRequest | Conflict | import("../types.ts").Unavailable, never>;
|
|
12
|
+
export declare const postRelease: (request: Request, env: LogbookEnv, claims: Claims) => Effect.Effect<Response, BadRequest | Conflict | import("../types.ts").Unavailable, never>;
|
|
13
|
+
export declare const getLatestRelease: (env: LogbookEnv) => Effect.Effect<Response, NotFound | import("../types.ts").Unavailable, never>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { BadRequest, Conflict, NotFound } from "../types.js";
|
|
3
|
+
import { ReleaseBody, VerdictBody, decoded, isRevision, jsonBody } from "./body.js";
|
|
4
|
+
import { json } from "./respond.js";
|
|
5
|
+
import { book, modelText, putModel } from "./stores.js";
|
|
6
|
+
const provenance = (c) => ({ repository: c.repository, ref: c.ref, workflow: c.workflow, eventName: c.eventName, sha: c.sha });
|
|
7
|
+
/** The filters a read takes, from its query string; anything else in it is ignored. */
|
|
8
|
+
export const filterOf = (url) => {
|
|
9
|
+
const q = (key) => url.searchParams.get(key) ?? undefined;
|
|
10
|
+
return { ...(q("revision") === undefined ? {} : { revision: q("revision") }), ...(q("environment") === undefined ? {} : { environment: q("environment") }),
|
|
11
|
+
...(q("operation") === undefined ? {} : { operation: q("operation") }), ...(q("ref") === undefined ? {} : { ref: q("ref") }) };
|
|
12
|
+
};
|
|
13
|
+
export const postVerdict = (request, env, claims) => decoded(request, VerdictBody).pipe(Effect.flatMap((verdict) => book(env, (b) => b.record(verdict, provenance(claims)))), Effect.map((stored) => json({ ok: true, verdict: stored })));
|
|
14
|
+
export const getVerdicts = (url, env, latest) => book(env, (b) => (latest ? b.latest(filterOf(url)) : b.verdicts(filterOf(url)))).pipe(Effect.map((rows) => json(rows)));
|
|
15
|
+
export const getModel = (revision, env) => modelText(env, revision).pipe(Effect.flatMap((text) => (text === null ? Effect.fail(new NotFound({ what: "model" })) : Effect.succeed(new Response(text, { headers: { "content-type": "application/json" } })))));
|
|
16
|
+
/** A revision's model is written once. The same model again is fine; a different one is a conflict. */
|
|
17
|
+
export const putRevisionModel = (revision, request, env) => Effect.gen(function* () {
|
|
18
|
+
if (!isRevision(revision))
|
|
19
|
+
return yield* new BadRequest({ reason: "not a revision" });
|
|
20
|
+
const model = yield* jsonBody(request);
|
|
21
|
+
if (typeof model !== "object" || model === null || Array.isArray(model))
|
|
22
|
+
return yield* new BadRequest({ reason: "a model is a JSON object" });
|
|
23
|
+
const text = JSON.stringify(model);
|
|
24
|
+
yield* putModel(env, revision, text);
|
|
25
|
+
return json({ ok: true, revision });
|
|
26
|
+
});
|
|
27
|
+
export const postRelease = (request, env, claims) => Effect.gen(function* () {
|
|
28
|
+
const { version, revision } = yield* decoded(request, ReleaseBody);
|
|
29
|
+
if ((yield* modelText(env, revision)) === null)
|
|
30
|
+
return yield* new Conflict({ reason: `revision ${revision} has no model` });
|
|
31
|
+
const made = yield* book(env, (b) => b.release(version, revision, provenance(claims)));
|
|
32
|
+
if (made === null)
|
|
33
|
+
return yield* new Conflict({ reason: `version ${version} is already released` });
|
|
34
|
+
return json({ ok: true, release: made });
|
|
35
|
+
});
|
|
36
|
+
export const getLatestRelease = (env) => book(env, (b) => b.latestRelease()).pipe(Effect.flatMap((release) => release === null ? Effect.fail(new NotFound({ what: "release" })) : Effect.succeed(json(release))));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Book } from "#modules/book/service.js";
|
|
3
|
+
import { Conflict, Unavailable, type LogbookEnv } from "../types.ts";
|
|
4
|
+
/** One Durable Object holds the whole ledger. */
|
|
5
|
+
export declare const book: <A>(env: LogbookEnv, call: (stub: DurableObjectStub<Book>) => Promise<A>) => Effect.Effect<A, Unavailable>;
|
|
6
|
+
export declare const modelText: (env: LogbookEnv, revision: string) => Effect.Effect<string | null, Unavailable>;
|
|
7
|
+
/** R2 owns admission: create atomically, then judge an identical retry against the committed winner. */
|
|
8
|
+
export declare const putModel: (env: LogbookEnv, revision: string, text: string) => Effect.Effect<void, Unavailable | Conflict>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The two stores behind the worker, each call wrapped once: the Durable Object's methods and R2's.
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { Conflict, Unavailable } from "../types.js";
|
|
4
|
+
/** One Durable Object holds the whole ledger. */
|
|
5
|
+
export const book = (env, call) => Effect.tryPromise({ try: () => call(env.BOOK.getByName("book")), catch: () => new Unavailable({ part: "book" }) });
|
|
6
|
+
const keyOf = (revision) => `models/${revision}.json`;
|
|
7
|
+
export const modelText = (env, revision) => Effect.tryPromise({
|
|
8
|
+
try: () => env.MODELS.get(keyOf(revision)).then((object) => (object === null ? null : object.text())),
|
|
9
|
+
catch: () => new Unavailable({ part: "models" }),
|
|
10
|
+
});
|
|
11
|
+
/** R2 owns admission: create atomically, then judge an identical retry against the committed winner. */
|
|
12
|
+
export const putModel = (env, revision, text) => Effect.gen(function* () {
|
|
13
|
+
const created = yield* Effect.tryPromise({
|
|
14
|
+
try: () => env.MODELS.put(keyOf(revision), text, { onlyIf: { etagDoesNotMatch: "*" }, httpMetadata: { contentType: "application/json" } }),
|
|
15
|
+
catch: () => new Unavailable({ part: "models" }),
|
|
16
|
+
});
|
|
17
|
+
if (created !== null)
|
|
18
|
+
return;
|
|
19
|
+
const held = yield* modelText(env, revision);
|
|
20
|
+
if (held === null)
|
|
21
|
+
return yield* new Unavailable({ part: "models" });
|
|
22
|
+
if (held !== text)
|
|
23
|
+
return yield* new Conflict({ reason: `revision ${revision} already has a different model` });
|
|
24
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { NotFound } from "./types.js";
|
|
3
|
+
import { getLatestRelease, getModel, getVerdicts, postRelease, postVerdict, putRevisionModel } from "./internal/routes.js";
|
|
4
|
+
import { json, respond } from "./internal/respond.js";
|
|
5
|
+
const MODEL = /^\/models\/([^/]+)$/;
|
|
6
|
+
/** A write: the token is verified first, so a request that fails it is refused before its body is even read. */
|
|
7
|
+
const signed = (request, tokens, run) => tokens.pipe(Effect.flatMap((t) => t.verify(request.headers.get("authorization"))), Effect.flatMap(run));
|
|
8
|
+
const route = (request, env, tokens) => {
|
|
9
|
+
const url = new URL(request.url);
|
|
10
|
+
const is = (method, path) => request.method === method && url.pathname === path;
|
|
11
|
+
const model = MODEL.exec(url.pathname)?.[1];
|
|
12
|
+
if (is("GET", "/health"))
|
|
13
|
+
return Effect.succeed(json({ ok: true, service: "logbook" }));
|
|
14
|
+
if (is("POST", "/verdicts"))
|
|
15
|
+
return signed(request, tokens, (claims) => postVerdict(request, env, claims));
|
|
16
|
+
if (is("GET", "/verdicts"))
|
|
17
|
+
return getVerdicts(url, env, false);
|
|
18
|
+
if (is("GET", "/verdicts/latest"))
|
|
19
|
+
return getVerdicts(url, env, true);
|
|
20
|
+
if (is("POST", "/releases"))
|
|
21
|
+
return signed(request, tokens, (claims) => postRelease(request, env, claims));
|
|
22
|
+
if (is("GET", "/releases/latest"))
|
|
23
|
+
return getLatestRelease(env);
|
|
24
|
+
if (model !== undefined && request.method === "GET")
|
|
25
|
+
return getModel(decodeURIComponent(model), env);
|
|
26
|
+
if (model !== undefined && request.method === "PUT")
|
|
27
|
+
return signed(request, tokens, () => putRevisionModel(decodeURIComponent(model), request, env));
|
|
28
|
+
return Effect.fail(new NotFound({ what: "route" }));
|
|
29
|
+
};
|
|
30
|
+
export const Http = {
|
|
31
|
+
handle: (request, env, tokens) => respond(route(request, env, tokens)),
|
|
32
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type Effect } from "effect";
|
|
2
|
+
import type { Book } from "#modules/book/service.js";
|
|
3
|
+
import type { Misconfigured, TokensApi } from "#modules/tokens/types.js";
|
|
4
|
+
/** The worker's bindings and variables (`wrangler.jsonc`; the variables are the token policy). */
|
|
5
|
+
export interface LogbookEnv {
|
|
6
|
+
readonly BOOK: DurableObjectNamespace<Book>;
|
|
7
|
+
/** R2: one object per revision, `models/<revision>.json`. */
|
|
8
|
+
readonly MODELS: R2Bucket;
|
|
9
|
+
readonly OIDC_ISSUER: string;
|
|
10
|
+
readonly OIDC_JWKS_URL: string;
|
|
11
|
+
readonly OIDC_AUDIENCE: string;
|
|
12
|
+
readonly ALLOWED_REPOSITORY: string;
|
|
13
|
+
readonly ALLOWED_REFS: string;
|
|
14
|
+
readonly ALLOWED_WORKFLOWS: string;
|
|
15
|
+
}
|
|
16
|
+
declare const BadRequest_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
17
|
+
readonly _tag: "BadRequest";
|
|
18
|
+
} & Readonly<A>;
|
|
19
|
+
export declare class BadRequest extends BadRequest_base<{
|
|
20
|
+
readonly reason: string;
|
|
21
|
+
}> {
|
|
22
|
+
}
|
|
23
|
+
declare const Conflict_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
24
|
+
readonly _tag: "Conflict";
|
|
25
|
+
} & Readonly<A>;
|
|
26
|
+
export declare class Conflict extends Conflict_base<{
|
|
27
|
+
readonly reason: string;
|
|
28
|
+
}> {
|
|
29
|
+
}
|
|
30
|
+
declare const NotFound_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
31
|
+
readonly _tag: "NotFound";
|
|
32
|
+
} & Readonly<A>;
|
|
33
|
+
export declare class NotFound extends NotFound_base<{
|
|
34
|
+
readonly what: string;
|
|
35
|
+
}> {
|
|
36
|
+
}
|
|
37
|
+
declare const Unavailable_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
38
|
+
readonly _tag: "Unavailable";
|
|
39
|
+
} & Readonly<A>;
|
|
40
|
+
/** The Durable Object or R2 didn't answer: a 500, with the failing part named but no detail. */
|
|
41
|
+
export declare class Unavailable extends Unavailable_base<{
|
|
42
|
+
readonly part: "book" | "models";
|
|
43
|
+
}> {
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Routes. Writes (`POST /verdicts`, `PUT /models/<revision>`, `POST /releases`) need a bearer token the policy accepts
|
|
47
|
+
* (401 otherwise, and nothing is stored); reads are open.
|
|
48
|
+
*
|
|
49
|
+
* - `GET /health`
|
|
50
|
+
* - `POST /verdicts` `{revision, environment, operation, verdict: "pass"|"fail"}`; `GET /verdicts?revision=&environment=&operation=&ref=`
|
|
51
|
+
* answers an array, oldest first; `GET /verdicts/latest?...` the newest verdict of each operation in each environment.
|
|
52
|
+
* - `PUT /models/<revision>` any JSON object, kept in R2 and never changed (409 for a different one); `GET /models/<revision>`.
|
|
53
|
+
* - `POST /releases` `{version, revision}` (the revision's model must be there, a version is released once);
|
|
54
|
+
* `GET /releases/latest` the last production release, 404 when there is none.
|
|
55
|
+
*/
|
|
56
|
+
export interface HttpApi {
|
|
57
|
+
readonly handle: (request: Request, env: LogbookEnv, tokens: Effect.Effect<TokensApi, Misconfigured>) => Effect.Effect<Response>;
|
|
58
|
+
}
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The logbook's HTTP surface. The worker's `fetch` calls `handle` and nothing else.
|
|
2
|
+
import { Data } from "effect";
|
|
3
|
+
export class BadRequest extends Data.TaggedError("BadRequest") {
|
|
4
|
+
}
|
|
5
|
+
export class Conflict extends Data.TaggedError("Conflict") {
|
|
6
|
+
}
|
|
7
|
+
export class NotFound extends Data.TaggedError("NotFound") {
|
|
8
|
+
}
|
|
9
|
+
/** The Durable Object or R2 didn't answer: a 500, with the failing part named but no detail. */
|
|
10
|
+
export class Unavailable extends Data.TaggedError("Unavailable") {
|
|
11
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ChildProcess } from "node:child_process";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import type { Launch, LaunchOptions } from "../types.ts";
|
|
4
|
+
export declare const launch: ({ port, state, policy }: LaunchOptions) => Launch;
|
|
5
|
+
/** The launch as a child of this process, its output appended to `log`. */
|
|
6
|
+
export declare const spawnLaunch: (run: Launch, log: string) => Effect.Effect<ChildProcess, never, never>;
|
|
7
|
+
export declare const stop: (child: ChildProcess) => Effect.Effect<void, never, never>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { openSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { Effect } from "effect";
|
|
6
|
+
const bin = join(dirname(fileURLToPath(import.meta.resolve("wrangler/package.json"))), "bin/wrangler.js");
|
|
7
|
+
const config = join(dirname(fileURLToPath(import.meta.url)), "../../../../wrangler.jsonc");
|
|
8
|
+
export const launch = ({ port, state, policy }) => {
|
|
9
|
+
const vars = {
|
|
10
|
+
OIDC_ISSUER: policy.issuer,
|
|
11
|
+
OIDC_JWKS_URL: policy.jwksUrl,
|
|
12
|
+
OIDC_AUDIENCE: policy.audience ?? "ortho-logbook",
|
|
13
|
+
ALLOWED_REPOSITORY: policy.repository,
|
|
14
|
+
ALLOWED_REFS: policy.refs.join(","),
|
|
15
|
+
ALLOWED_WORKFLOWS: policy.workflows.join(","),
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
command: process.execPath,
|
|
19
|
+
args: [bin, "dev", "--config", config, "--port", String(port), "--ip", "127.0.0.1", "--persist-to", state, "--inspector-port", "0",
|
|
20
|
+
...Object.entries(vars).flatMap(([k, v]) => ["--var", `${k}:${v}`])],
|
|
21
|
+
env: { CI: "1", WRANGLER_SEND_METRICS: "false" },
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
/** The launch as a child of this process, its output appended to `log`. */
|
|
25
|
+
export const spawnLaunch = (run, log) => Effect.sync(() => {
|
|
26
|
+
const out = openSync(log, "a");
|
|
27
|
+
return spawn(run.command, [...run.args], { stdio: ["ignore", out, out], env: { ...process.env, ...run.env } });
|
|
28
|
+
});
|
|
29
|
+
export const stop = (child) => Effect.callback((resume) => {
|
|
30
|
+
if (child.exitCode !== null)
|
|
31
|
+
return resume(Effect.void);
|
|
32
|
+
child.once("exit", () => resume(Effect.void));
|
|
33
|
+
child.kill("SIGTERM");
|
|
34
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { Effect, Schedule } from "effect";
|
|
4
|
+
import { LogbookFailed } from "./types.js";
|
|
5
|
+
import { launch, spawnLaunch, stop } from "./internal/wrangler.js";
|
|
6
|
+
const answers = (url) => Effect.tryPromise({ try: () => fetch(url).then((r) => r.ok), catch: () => false }).pipe(Effect.flatMap((ok) => (ok ? Effect.void : Effect.fail(false))));
|
|
7
|
+
const ready = (url, exited) => Effect.suspend(() => exited?.() != null ? Effect.fail("exited") : answers(`${url}/health`).pipe(Effect.mapError(() => "silent"))).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 480, while: (e) => e !== "exited" }));
|
|
8
|
+
export const Logbook = {
|
|
9
|
+
launch,
|
|
10
|
+
ready: (url) => ready(url).pipe(Effect.mapError(() => new LogbookFailed({ message: `the logbook at ${url} didn't answer within 120 s` }))),
|
|
11
|
+
discoverJwks: (issuer) => Effect.tryPromise({
|
|
12
|
+
try: () => fetch(`${issuer}/.well-known/openid-configuration`).then((r) => r.json()),
|
|
13
|
+
catch: () => new LogbookFailed({ message: `no discovery document at ${issuer}` }),
|
|
14
|
+
}).pipe(Effect.flatMap(({ jwks_uri }) => typeof jwks_uri === "string" ? Effect.succeed(jwks_uri) : Effect.fail(new LogbookFailed({ message: `${issuer} names no jwks_uri` })))),
|
|
15
|
+
start: (options) => Effect.gen(function* () {
|
|
16
|
+
mkdirSync(options.state, { recursive: true });
|
|
17
|
+
mkdirSync(dirname(options.log), { recursive: true });
|
|
18
|
+
const url = `http://127.0.0.1:${options.port}`;
|
|
19
|
+
const child = yield* Effect.acquireRelease(spawnLaunch(launch(options), options.log), stop);
|
|
20
|
+
yield* ready(url, () => child.exitCode).pipe(Effect.mapError((e) => new LogbookFailed({ message: e === "exited" ? `the logbook exited (${child.exitCode}); see ${options.log}` : `the logbook didn't answer within 120 s; see ${options.log}` })));
|
|
21
|
+
return { url, log: options.log };
|
|
22
|
+
}),
|
|
23
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Effect, type Scope } from "effect";
|
|
2
|
+
import type { TokenPolicy } from "#modules/tokens/types.js";
|
|
3
|
+
declare const LogbookFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
4
|
+
readonly _tag: "LogbookFailed";
|
|
5
|
+
} & Readonly<A>;
|
|
6
|
+
export declare class LogbookFailed extends LogbookFailed_base<{
|
|
7
|
+
readonly message: string;
|
|
8
|
+
}> {
|
|
9
|
+
}
|
|
10
|
+
/** The token policy and where the issuer's keys are. `audience` is `ortho-logbook` unless a test needs another. */
|
|
11
|
+
export interface LogbookPolicy extends Omit<TokenPolicy, "audience"> {
|
|
12
|
+
readonly jwksUrl: string;
|
|
13
|
+
readonly audience?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface LaunchOptions {
|
|
16
|
+
readonly port: number;
|
|
17
|
+
/** `wrangler dev --persist-to`: the Durable Object's SQLite and R2 live here, and survive a restart. */
|
|
18
|
+
readonly state: string;
|
|
19
|
+
readonly policy: LogbookPolicy;
|
|
20
|
+
}
|
|
21
|
+
/** A command to run, for a caller that keeps the process itself (the CLI's `env up` keeps a pidfile). */
|
|
22
|
+
export interface Launch {
|
|
23
|
+
readonly command: string;
|
|
24
|
+
readonly args: ReadonlyArray<string>;
|
|
25
|
+
/** Added to the process's own environment: `CI=1` so wrangler never asks, and no metrics. */
|
|
26
|
+
readonly env: Readonly<Record<string, string>>;
|
|
27
|
+
}
|
|
28
|
+
export interface Running {
|
|
29
|
+
readonly url: string;
|
|
30
|
+
readonly log: string;
|
|
31
|
+
}
|
|
32
|
+
export interface LogbookApi {
|
|
33
|
+
/** How to run the logbook as a long-lived process. The policy travels as `--var` arguments: none of it is a secret. */
|
|
34
|
+
readonly launch: (options: LaunchOptions) => Launch;
|
|
35
|
+
/** Wait until the logbook at `url` answers `GET /health` (about 5 s on this Mac); fails after 120 s. */
|
|
36
|
+
readonly ready: (url: string) => Effect.Effect<void, LogbookFailed>;
|
|
37
|
+
/** The JWKS URL an issuer names in its discovery document: `<issuer>/.well-known/openid-configuration`'s `jwks_uri`. */
|
|
38
|
+
readonly discoverJwks: (issuer: string) => Effect.Effect<string, LogbookFailed>;
|
|
39
|
+
/** Launch, wait for ready, and stop when the scope closes. For tests and for commands that need a logbook only briefly. */
|
|
40
|
+
readonly start: (options: LaunchOptions & {
|
|
41
|
+
readonly log: string;
|
|
42
|
+
}) => Effect.Effect<Running, LogbookFailed, Scope.Scope>;
|
|
43
|
+
}
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { JWTPayload } from "jose";
|
|
2
|
+
import type { Claims, TokenPolicy } from "../types.ts";
|
|
3
|
+
/** `*` is exactly one path segment, so a pull request's `refs/pull/<star>/merge` matches `refs/pull/7/merge` and nothing longer. */
|
|
4
|
+
export declare const matches: (pattern: string, value: string) => boolean;
|
|
5
|
+
export declare const list: (value: unknown) => ReadonlyArray<string>;
|
|
6
|
+
/**
|
|
7
|
+
* The policy after the signature: repository, ref and workflow, and `job_workflow_ref` when the token has one (two
|
|
8
|
+
* workflows can share a name; a file path cannot). Returns the claims worth keeping, or the name of the check that failed.
|
|
9
|
+
*/
|
|
10
|
+
export declare const check: (policy: TokenPolicy, payload: JWTPayload) => Claims | string;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const escape = (s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
2
|
+
/** `*` is exactly one path segment, so a pull request's `refs/pull/<star>/merge` matches `refs/pull/7/merge` and nothing longer. */
|
|
3
|
+
export const matches = (pattern, value) => new RegExp(`^${pattern.split("*").map(escape).join("[^/]+")}$`).test(value);
|
|
4
|
+
const anyMatches = (patterns, value) => patterns.some((p) => matches(p, value));
|
|
5
|
+
export const list = (value) => typeof value === "string" ? value.split(",").map((s) => s.trim()).filter((s) => s !== "") : [];
|
|
6
|
+
const text = (payload, key) => {
|
|
7
|
+
const value = payload[key];
|
|
8
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
9
|
+
};
|
|
10
|
+
/** `<repo>/.github/workflows/<file>@<ref>`, taken apart. */
|
|
11
|
+
const parseJobWorkflowRef = (value) => /^([^/]+\/[^/]+)\/(\.github\/workflows\/[^@]+)@(.+)$/.exec(value);
|
|
12
|
+
/**
|
|
13
|
+
* The policy after the signature: repository, ref and workflow, and `job_workflow_ref` when the token has one (two
|
|
14
|
+
* workflows can share a name; a file path cannot). Returns the claims worth keeping, or the name of the check that failed.
|
|
15
|
+
*/
|
|
16
|
+
export const check = (policy, payload) => {
|
|
17
|
+
const repository = text(payload, "repository");
|
|
18
|
+
const ref = text(payload, "ref");
|
|
19
|
+
const workflow = text(payload, "workflow");
|
|
20
|
+
if (repository === null || repository !== policy.repository)
|
|
21
|
+
return "repository";
|
|
22
|
+
if (ref === null || !anyMatches(policy.refs, ref))
|
|
23
|
+
return "ref";
|
|
24
|
+
const jobWorkflowRef = text(payload, "job_workflow_ref");
|
|
25
|
+
const job = jobWorkflowRef === null ? null : parseJobWorkflowRef(jobWorkflowRef);
|
|
26
|
+
if (jobWorkflowRef !== null && (job === null || job[1] !== policy.repository || !anyMatches(policy.refs, job[3])))
|
|
27
|
+
return "job_workflow_ref";
|
|
28
|
+
const named = workflow !== null && policy.workflows.some((w) => !w.includes("/") && matches(w, workflow));
|
|
29
|
+
const pinned = job !== null && policy.workflows.some((w) => w.includes("/") && matches(w, job[2]));
|
|
30
|
+
if (!named && !pinned)
|
|
31
|
+
return "workflow";
|
|
32
|
+
return { repository, ref, workflow: workflow ?? "", eventName: text(payload, "event_name"), sha: text(payload, "sha"), jobWorkflowRef };
|
|
33
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { type JWTPayload } from "jose";
|
|
3
|
+
import { type KeyLookup, TokenRefused, type TokenPolicy } from "../types.ts";
|
|
4
|
+
/** RS256 only, with the issuer, the audience and expiry checked and the claims the policy needs required. */
|
|
5
|
+
export declare const verifySignature: (token: string, keys: KeyLookup, policy: TokenPolicy) => Effect.Effect<JWTPayload, TokenRefused>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// jose's promises, wrapped once: this is the only place the logbook awaits a verification.
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { jwtVerify } from "jose";
|
|
4
|
+
import { TokenRefused } from "../types.js";
|
|
5
|
+
const code = (e) => typeof e === "object" && e !== null && "code" in e && typeof e.code === "string" ? e.code : "ERR_TOKEN";
|
|
6
|
+
/** RS256 only, with the issuer, the audience and expiry checked and the claims the policy needs required. */
|
|
7
|
+
export const verifySignature = (token, keys, policy) => Effect.tryPromise({
|
|
8
|
+
try: () => jwtVerify(token, keys, {
|
|
9
|
+
issuer: policy.issuer,
|
|
10
|
+
audience: policy.audience,
|
|
11
|
+
algorithms: ["RS256"],
|
|
12
|
+
requiredClaims: ["exp", "iat", "repository", "ref", "workflow"],
|
|
13
|
+
clockTolerance: 30,
|
|
14
|
+
}).then((verified) => verified.payload),
|
|
15
|
+
catch: (e) => new TokenRefused({ reason: code(e) }),
|
|
16
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { createRemoteJWKSet } from "jose";
|
|
3
|
+
import { Misconfigured, TokenRefused } from "./types.js";
|
|
4
|
+
import { check, list } from "./internal/policy.js";
|
|
5
|
+
import { verifySignature } from "./internal/verify.js";
|
|
6
|
+
const bearer = (authorization) => /^Bearer (\S+)$/.exec(authorization ?? "")?.[1];
|
|
7
|
+
const make = (policy, keys) => ({
|
|
8
|
+
verify: (authorization) => {
|
|
9
|
+
const token = bearer(authorization);
|
|
10
|
+
if (token === undefined)
|
|
11
|
+
return Effect.fail(new TokenRefused({ reason: "missing token" }));
|
|
12
|
+
return verifySignature(token, keys, policy).pipe(Effect.flatMap((payload) => {
|
|
13
|
+
const checked = check(policy, payload);
|
|
14
|
+
return typeof checked === "string" ? Effect.fail(new TokenRefused({ reason: checked })) : Effect.succeed(checked);
|
|
15
|
+
}));
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
const text = (vars, key) => (typeof vars[key] === "string" ? vars[key].trim() : "");
|
|
19
|
+
export const Tokens = {
|
|
20
|
+
make,
|
|
21
|
+
remote: (policy, jwksUrl) => make(policy, createRemoteJWKSet(new URL(jwksUrl), { timeoutDuration: 5000 })),
|
|
22
|
+
fromVars: (vars) => {
|
|
23
|
+
const refs = list(vars["ALLOWED_REFS"]);
|
|
24
|
+
const workflows = list(vars["ALLOWED_WORKFLOWS"]);
|
|
25
|
+
const missing = [
|
|
26
|
+
...["OIDC_ISSUER", "OIDC_JWKS_URL", "OIDC_AUDIENCE", "ALLOWED_REPOSITORY"].filter((k) => text(vars, k) === ""),
|
|
27
|
+
...(refs.length === 0 ? ["ALLOWED_REFS"] : []),
|
|
28
|
+
...(workflows.length === 0 ? ["ALLOWED_WORKFLOWS"] : []),
|
|
29
|
+
];
|
|
30
|
+
return missing.length > 0
|
|
31
|
+
? Effect.fail(new Misconfigured({ missing }))
|
|
32
|
+
: Effect.succeed({
|
|
33
|
+
jwksUrl: text(vars, "OIDC_JWKS_URL"),
|
|
34
|
+
policy: { issuer: text(vars, "OIDC_ISSUER"), audience: text(vars, "OIDC_AUDIENCE"), repository: text(vars, "ALLOWED_REPOSITORY"), refs, workflows },
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type Effect } from "effect";
|
|
2
|
+
import type { JWTVerifyGetKey } from "jose";
|
|
3
|
+
/** What the logbook trusts. Every field is an environment variable of the worker; none is a secret. */
|
|
4
|
+
export interface TokenPolicy {
|
|
5
|
+
readonly issuer: string;
|
|
6
|
+
readonly audience: string;
|
|
7
|
+
/** `<owner>/<repo>`: the only repository whose jobs may write. */
|
|
8
|
+
readonly repository: string;
|
|
9
|
+
/** Allow-list of refs. `*` stands for one path segment, never a prefix: `refs/pull/<star>/merge`, not `refs/pull/`. */
|
|
10
|
+
readonly refs: ReadonlyArray<string>;
|
|
11
|
+
/** Workflow names; an entry with a `/` is a workflow file path (`.github/workflows/ci.yml`) matched on `job_workflow_ref`. */
|
|
12
|
+
readonly workflows: ReadonlyArray<string>;
|
|
13
|
+
}
|
|
14
|
+
/** The claims of a verified token that the logbook keeps with what it stores. Never the token itself. */
|
|
15
|
+
export interface Claims {
|
|
16
|
+
readonly repository: string;
|
|
17
|
+
readonly ref: string;
|
|
18
|
+
readonly workflow: string;
|
|
19
|
+
readonly eventName: string | null;
|
|
20
|
+
readonly sha: string | null;
|
|
21
|
+
readonly jobWorkflowRef: string | null;
|
|
22
|
+
}
|
|
23
|
+
declare const TokenRefused_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
24
|
+
readonly _tag: "TokenRefused";
|
|
25
|
+
} & Readonly<A>;
|
|
26
|
+
/** A token the logbook will not take. `reason` is jose's error code or the name of the policy check; it is not the token. */
|
|
27
|
+
export declare class TokenRefused extends TokenRefused_base<{
|
|
28
|
+
readonly reason: string;
|
|
29
|
+
}> {
|
|
30
|
+
}
|
|
31
|
+
declare const Misconfigured_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
32
|
+
readonly _tag: "Misconfigured";
|
|
33
|
+
} & Readonly<A>;
|
|
34
|
+
/** The worker's variables are missing or empty: named here, so the operator can fix them. */
|
|
35
|
+
export declare class Misconfigured extends Misconfigured_base<{
|
|
36
|
+
readonly missing: ReadonlyArray<string>;
|
|
37
|
+
}> {
|
|
38
|
+
}
|
|
39
|
+
export interface TokensApi {
|
|
40
|
+
/** The `Authorization` header's value, verified: RS256 only, issuer, audience, expiry, then the policy. */
|
|
41
|
+
readonly verify: (authorization: string | null) => Effect.Effect<Claims, TokenRefused>;
|
|
42
|
+
}
|
|
43
|
+
/** Where the issuer's keys come from: jose's remote key set in the worker, a local key set in a test. */
|
|
44
|
+
export type KeyLookup = JWTVerifyGetKey;
|
|
45
|
+
export type PolicyVars = Readonly<Record<string, unknown>>;
|
|
46
|
+
export interface TokensFactory {
|
|
47
|
+
readonly make: (policy: TokenPolicy, keys: KeyLookup) => TokensApi;
|
|
48
|
+
/** Keys fetched from the issuer's JWKS URL (cached by jose, refetched on an unknown key id). */
|
|
49
|
+
readonly remote: (policy: TokenPolicy, jwksUrl: string) => TokensApi;
|
|
50
|
+
/** `OIDC_ISSUER`, `OIDC_JWKS_URL`, `OIDC_AUDIENCE`, `ALLOWED_REPOSITORY`, `ALLOWED_REFS`, `ALLOWED_WORKFLOWS`. */
|
|
51
|
+
readonly fromVars: (vars: PolicyVars) => Effect.Effect<{
|
|
52
|
+
readonly policy: TokenPolicy;
|
|
53
|
+
readonly jwksUrl: string;
|
|
54
|
+
}, Misconfigured>;
|
|
55
|
+
}
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Who may write to the logbook: an OIDC token from the one issuer this logbook names (D3 #8).
|
|
2
|
+
import { Data } from "effect";
|
|
3
|
+
/** A token the logbook will not take. `reason` is jose's error code or the name of the policy check; it is not the token. */
|
|
4
|
+
export class TokenRefused extends Data.TaggedError("TokenRefused") {
|
|
5
|
+
}
|
|
6
|
+
/** The worker's variables are missing or empty: named here, so the operator can fix them. */
|
|
7
|
+
export class Misconfigured extends Data.TaggedError("Misconfigured") {
|
|
8
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orthograph/logbook",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-next.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"imports": {
|
|
13
|
+
"#modules/*.js": "./dist/modules/*.js"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"effect": "4.1.4",
|
|
17
|
+
"jose": "6.2.15",
|
|
18
|
+
"wrangler": "4.156.1"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@cloudflare/workers-types": "5.20261101.1",
|
|
22
|
+
"@orthograph/services": "0.0.0"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"src/main.ts",
|
|
27
|
+
"wrangler.jsonc"
|
|
28
|
+
],
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"tag": "next"
|
|
32
|
+
}
|
|
6
33
|
}
|
package/src/main.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The logbook worker's entry and composition root (wrangler.jsonc `main`). It is the one place a promise is handed to workerd.
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { Http } from "#modules/http/service.js";
|
|
4
|
+
import type { LogbookEnv } from "#modules/http/types.js";
|
|
5
|
+
import { Tokens } from "#modules/tokens/service.js";
|
|
6
|
+
import type { TokensApi } from "#modules/tokens/types.js";
|
|
7
|
+
|
|
8
|
+
export { Book } from "#modules/book/service.js";
|
|
9
|
+
|
|
10
|
+
// One verifier per policy, kept for the life of the isolate so jose keeps the issuer's keys cached between requests.
|
|
11
|
+
const verifiers = new Map<string, TokensApi>();
|
|
12
|
+
|
|
13
|
+
const tokensFor = (env: LogbookEnv) =>
|
|
14
|
+
Tokens.fromVars(env as unknown as Record<string, unknown>).pipe(
|
|
15
|
+
Effect.map(({ policy, jwksUrl }) => {
|
|
16
|
+
const key = JSON.stringify([policy, jwksUrl]);
|
|
17
|
+
const held = verifiers.get(key);
|
|
18
|
+
if (held !== undefined) return held;
|
|
19
|
+
const made = Tokens.remote(policy, jwksUrl);
|
|
20
|
+
verifiers.set(key, made);
|
|
21
|
+
return made;
|
|
22
|
+
}),
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
export default {
|
|
26
|
+
fetch: (request: Request, env: LogbookEnv): Promise<Response> => Effect.runPromise(Http.handle(request, env, tokensFor(env))),
|
|
27
|
+
} satisfies ExportedHandler<LogbookEnv>;
|
package/wrangler.jsonc
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The logbook worker (D3 #3, #8): a Durable Object for verdicts and releases, R2 for each revision's model. Local workerd
|
|
2
|
+
// and a deployed environment run the same bundle. The token policy (OIDC_ISSUER, OIDC_JWKS_URL, OIDC_AUDIENCE,
|
|
3
|
+
// ALLOWED_REPOSITORY, ALLOWED_REFS, ALLOWED_WORKFLOWS) is not set here: `Logbook.launch` passes it as `--var`s.
|
|
4
|
+
{
|
|
5
|
+
"name": "ortho-logbook",
|
|
6
|
+
"main": "src/main.ts",
|
|
7
|
+
"compatibility_date": "2026-08-01",
|
|
8
|
+
"durable_objects": { "bindings": [{ "name": "BOOK", "class_name": "Book" }] },
|
|
9
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Book"] }],
|
|
10
|
+
"r2_buckets": [{ "binding": "MODELS", "bucket_name": "ortho-logbook-models" }]
|
|
11
|
+
}
|