@notation/factory 0.0.0-stage → 0.1.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 +21 -0
- package/contracts/channel.ts +43 -0
- package/contracts/connection.ts +15 -0
- package/contracts/hub.ts +33 -0
- package/contracts/index.ts +36 -0
- package/contracts/outpost.ts +54 -0
- package/contracts/router.ts +104 -0
- package/contracts/vault.ts +22 -0
- package/deployer/collect.ts +31 -0
- package/deployer/deploy.test.ts +50 -0
- package/deployer/index.ts +152 -0
- package/deployer/sdk.gen.ts +2 -0
- package/deployer/sdk.ts +18 -0
- package/implementations/container.ts +67 -0
- package/implementations/outpost.ts +50 -0
- package/implementations/policy.ts +26 -0
- package/implementations/trigger.ts +67 -0
- package/index.ts +3 -0
- package/lib/binding-name.ts +9 -0
- package/lib/collect.ts +21 -0
- package/lib/outpost.ts +17 -0
- package/lib/scoped-name.ts +10 -0
- package/outpost.ts +12 -0
- package/package.json +39 -3
- package/resources/outpost-config.ts +102 -0
- package/resources/random-key.ts +54 -0
- package/resources/router-sync.ts +53 -0
- package/router/channel.ts +114 -0
- package/router/handle.test.ts +419 -0
- package/router/handle.ts +442 -0
- package/router/index.ts +52 -0
- package/router/keys.ts +36 -0
- package/router/run.ts +91 -0
- package/runner/index.ts +628 -0
- package/runner/runner.test.ts +322 -0
- package/README.md +0 -3
package/router/handle.ts
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
import type { OutpostConfig } from "../contracts/outpost.ts";
|
|
2
|
+
import type { RepoPattern, RouterConfig } from "../contracts/router.ts";
|
|
3
|
+
import type {
|
|
4
|
+
AuthorCheck,
|
|
5
|
+
BuildCheck,
|
|
6
|
+
Delivery,
|
|
7
|
+
FactoryStatus,
|
|
8
|
+
RemoteChannel,
|
|
9
|
+
SourceChange,
|
|
10
|
+
SourceFiles,
|
|
11
|
+
} from "./channel.ts";
|
|
12
|
+
import {
|
|
13
|
+
type BuildReportRequest,
|
|
14
|
+
isBranchName,
|
|
15
|
+
type Relay,
|
|
16
|
+
REPLY_TTL_MS,
|
|
17
|
+
type Run,
|
|
18
|
+
signTicket,
|
|
19
|
+
signTokenTicket,
|
|
20
|
+
type TokenRequest,
|
|
21
|
+
type Tokens,
|
|
22
|
+
verifyBuildReport,
|
|
23
|
+
verifyTicket,
|
|
24
|
+
verifyTokenTicket,
|
|
25
|
+
} from "./run.ts";
|
|
26
|
+
|
|
27
|
+
/** The KV key that the deployer stores a repo's outpost config under. `repo` is `owner/name`. */
|
|
28
|
+
export const outpostKey = (repo: string) => `outposts/${repo.toLowerCase()}`;
|
|
29
|
+
|
|
30
|
+
/** Where the router reads its state, and finds each connection's channel. Each platform adapts its own storage to it. */
|
|
31
|
+
export type RouterStore = {
|
|
32
|
+
config: Partial<RouterConfig>;
|
|
33
|
+
/** The channel that the router reaches by `binding`, the name in a connection's entry. */
|
|
34
|
+
channel(binding: string): RemoteChannel | undefined;
|
|
35
|
+
outpost(repo: string): Promise<OutpostConfig | undefined>;
|
|
36
|
+
deployer?: RemoteDeployer;
|
|
37
|
+
/** The root key, which the router derives its own keys from. */
|
|
38
|
+
rootKey(): Promise<string>;
|
|
39
|
+
/** Keeps `task` running after the response, where the platform allows it. Without it, the router waits for the task. */
|
|
40
|
+
background?(task: Promise<unknown>): void;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** The deployer, as the router calls it. */
|
|
44
|
+
export type RemoteDeployer = {
|
|
45
|
+
/** Evaluates the repo's `.factory/` files and stores its outpost config. Resolves to the status to show on the repo. */
|
|
46
|
+
deploy(repo: string, source: SourceFiles): Promise<FactoryStatus>;
|
|
47
|
+
/** Removes the repo's outpost config. */
|
|
48
|
+
remove(repo: string): Promise<void>;
|
|
49
|
+
/** Calls the worktree function of the repo's trigger with `payload`, in the isolate that evaluates configs. */
|
|
50
|
+
worktree(repo: string, trigger: string, payload: unknown): Promise<string | undefined>;
|
|
51
|
+
/** Hands `run` to its container, which queues it. */
|
|
52
|
+
run(run: Run): Promise<void>;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** The name of the check that shows the build of a container's image, such as `factory/build dev`. */
|
|
56
|
+
export const buildCheckName = (container: string) => `factory/build ${container}`;
|
|
57
|
+
|
|
58
|
+
/** The directory of a repo that holds its outpost's files. */
|
|
59
|
+
export const FACTORY_DIR = ".factory";
|
|
60
|
+
|
|
61
|
+
/** A trigger that a delivery matched. `run` is the id of the run it started, if its author may start one. */
|
|
62
|
+
export type TriggerMatch = { trigger: string; author: AuthorCheck; run?: string };
|
|
63
|
+
|
|
64
|
+
/** The path that a connection's platform delivers to. `key` is the connection's key, such as `github/gh`. */
|
|
65
|
+
export const webhookPath = (key: string) => `/webhook/${key}`;
|
|
66
|
+
|
|
67
|
+
const json = (status: number, body: unknown) =>
|
|
68
|
+
new Response(JSON.stringify(body), {
|
|
69
|
+
status,
|
|
70
|
+
headers: { "content-type": "application/json" },
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
/** The connections whose channel the router can reach, by key. */
|
|
74
|
+
const channels = (store: RouterStore) =>
|
|
75
|
+
Object.entries(store.config.connections ?? {}).flatMap(([key, entry]) => {
|
|
76
|
+
const channel = entry.channel && store.channel(entry.channel);
|
|
77
|
+
return channel ? [{ key, entry, channel }] : [];
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Handles a delivery to a connection's webhook path:
|
|
82
|
+
* 1. Finds the connection's channel.
|
|
83
|
+
* 2. Has the channel verify and parse the delivery.
|
|
84
|
+
* 3. Reads the outpost of the delivery's repo, and matches the triggers on
|
|
85
|
+
* channels of the delivery's connection and scope.
|
|
86
|
+
* 4. Starts a run for each match whose author may start one.
|
|
87
|
+
*/
|
|
88
|
+
const webhook = async (request: Request, key: string, store: RouterStore) => {
|
|
89
|
+
const found = channels(store).find((c) => c.key === key);
|
|
90
|
+
if (!found) return json(404, { error: `no channel for connection ${key}` });
|
|
91
|
+
const { entry, channel } = found;
|
|
92
|
+
const name = key.slice(entry.provider.length + 1);
|
|
93
|
+
|
|
94
|
+
const received = await channel.receive(request);
|
|
95
|
+
if (received.status === "rejected") return json(401, { error: received.reason });
|
|
96
|
+
if (received.status === "ignored") return json(200, { ignored: received.reason });
|
|
97
|
+
if (received.status === "source") {
|
|
98
|
+
return source(key, received.changes, channel, store);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const { delivery } = received;
|
|
102
|
+
const summary = { delivery: delivery.id, connection: key, event: delivery.event, scope: delivery.scope };
|
|
103
|
+
const outpost = await store.outpost(delivery.repo);
|
|
104
|
+
if (!outpost) return json(202, { ...summary, ignored: "no outpost" });
|
|
105
|
+
|
|
106
|
+
const matches: TriggerMatch[] = [];
|
|
107
|
+
const runs: Promise<void>[] = [];
|
|
108
|
+
const origin = new URL(request.url).origin;
|
|
109
|
+
for (const [id, trigger] of Object.entries(outpost.triggers ?? {})) {
|
|
110
|
+
const target = outpost.channels?.[trigger.channel];
|
|
111
|
+
if (
|
|
112
|
+
trigger.event !== delivery.event ||
|
|
113
|
+
target?.provider !== entry.provider ||
|
|
114
|
+
target.connection !== name ||
|
|
115
|
+
target.scope !== delivery.scope
|
|
116
|
+
) {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const author = await channel.match(trigger.match, delivery);
|
|
120
|
+
if (!author) continue;
|
|
121
|
+
// Team checks need a call to the platform, which the router doesn't make yet.
|
|
122
|
+
if (author.result !== "allowed") {
|
|
123
|
+
matches.push({ trigger: id, author });
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const run = crypto.randomUUID();
|
|
127
|
+
matches.push({ trigger: id, author, run });
|
|
128
|
+
runs.push(
|
|
129
|
+
dispatch({ run, trigger: id, key, channel, delivery, outpost, origin }, store).catch((error) =>
|
|
130
|
+
console.error(JSON.stringify({ run, trigger: id, error: message(error) })),
|
|
131
|
+
),
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (runs.length) {
|
|
135
|
+
const task = Promise.all(runs);
|
|
136
|
+
if (store.background) store.background(task);
|
|
137
|
+
else await task;
|
|
138
|
+
}
|
|
139
|
+
const result = { ...summary, matches };
|
|
140
|
+
console.log(JSON.stringify(result));
|
|
141
|
+
return json(202, result);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
type Dispatch = {
|
|
145
|
+
run: string;
|
|
146
|
+
trigger: string;
|
|
147
|
+
/** The delivery's connection. */
|
|
148
|
+
key: string;
|
|
149
|
+
channel: RemoteChannel;
|
|
150
|
+
delivery: Delivery<unknown>;
|
|
151
|
+
outpost: OutpostConfig;
|
|
152
|
+
/** The router's origin, which the runner replies to. */
|
|
153
|
+
origin: string;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/** The channel of the code host's connection, which mints repo tokens. */
|
|
157
|
+
const codeHostChannel = (store: RouterStore) => {
|
|
158
|
+
const codeHost = store.config.codeHost;
|
|
159
|
+
if (!codeHost) return undefined;
|
|
160
|
+
const key = `${codeHost.provider}/${codeHost.connection}`;
|
|
161
|
+
return { provider: codeHost.provider, channel: channels(store).find((c) => c.key === key)?.channel };
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** Has the code host's channel mint a token for each of the container's code host policies. */
|
|
165
|
+
const mintTokens = async (store: RouterStore, outpost: OutpostConfig, repo: string, container: string) => {
|
|
166
|
+
const codeHost = codeHostChannel(store);
|
|
167
|
+
if (!codeHost?.channel) throw new Error("The hub has no code host whose channel mints tokens.");
|
|
168
|
+
const entry = outpost.containers[container];
|
|
169
|
+
if (!entry) throw new Error(`The outpost has no container ${container}.`);
|
|
170
|
+
const tokens: Tokens = [];
|
|
171
|
+
for (const policy of entry.policies) {
|
|
172
|
+
const policyEntry = outpost.policies[policy];
|
|
173
|
+
if (!policyEntry) throw new Error(`The outpost has no policy ${policy}.`);
|
|
174
|
+
// Policies of other providers aren't minted yet.
|
|
175
|
+
if (policyEntry.provider !== codeHost.provider) continue;
|
|
176
|
+
const target = typeof policyEntry.repo === "string" ? policyEntry.repo : repo;
|
|
177
|
+
const permissions = policyEntry.permissions as Record<string, "read" | "write">;
|
|
178
|
+
tokens.push({ policy, repo: target, token: await codeHost.channel.token(target, permissions) });
|
|
179
|
+
}
|
|
180
|
+
return tokens;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Starts one run of a matched trigger:
|
|
185
|
+
* 1. Has the delivery's channel name the conversation, and signs a ticket
|
|
186
|
+
* for replies to its thread.
|
|
187
|
+
* 2. Has the deployer call the trigger's worktree function, if it has one.
|
|
188
|
+
* 3. Has the code host's channel mint a read-only token for the clone, and a
|
|
189
|
+
* token for each of the container's code host policies. Signs a ticket
|
|
190
|
+
* for new tokens.
|
|
191
|
+
* 4. Hands the run to the deployer. If a step fails, the channel replies
|
|
192
|
+
* with the error.
|
|
193
|
+
*/
|
|
194
|
+
const dispatch = async (d: Dispatch, store: RouterStore) => {
|
|
195
|
+
const { delivery, outpost } = d;
|
|
196
|
+
const repo = delivery.repo;
|
|
197
|
+
const trigger = outpost.triggers[d.trigger]!;
|
|
198
|
+
const conversation = await d.channel.conversation(delivery);
|
|
199
|
+
const ticket = { connection: d.key, thread: conversation.thread, expires: Date.now() + REPLY_TTL_MS };
|
|
200
|
+
const rootKey = await store.rootKey();
|
|
201
|
+
const reply = { url: `${d.origin}/relay`, ticket, signature: await signTicket(rootKey, ticket) };
|
|
202
|
+
try {
|
|
203
|
+
const { deployer } = store;
|
|
204
|
+
if (!deployer) throw new Error("The hub has no deployer.");
|
|
205
|
+
const container = outpost.containers[trigger.container];
|
|
206
|
+
const agent = outpost.agents[trigger.agent];
|
|
207
|
+
if (!container) throw new Error(`The outpost has no container ${trigger.container}.`);
|
|
208
|
+
if (!agent) throw new Error(`The outpost has no agent ${trigger.agent}.`);
|
|
209
|
+
const codeHost = codeHostChannel(store);
|
|
210
|
+
if (!codeHost?.channel) throw new Error("The hub has no code host whose channel mints tokens.");
|
|
211
|
+
|
|
212
|
+
let worktree: Run["worktree"];
|
|
213
|
+
if (trigger.worktree) {
|
|
214
|
+
const branch = await deployer.worktree(repo, d.trigger, delivery.payload);
|
|
215
|
+
if (branch !== undefined) {
|
|
216
|
+
if (typeof branch !== "string" || !isBranchName(branch)) {
|
|
217
|
+
throw new Error(`The worktree function of ${d.trigger} returned ${JSON.stringify(branch)}, which isn't a branch name the runner can check out.`);
|
|
218
|
+
}
|
|
219
|
+
worktree = { branch, ...(trigger.worktree.base && { base: trigger.worktree.base }) };
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const tokens = await mintTokens(store, outpost, repo, trigger.container);
|
|
224
|
+
const tokenTicket = { repo, container: trigger.container, expires: Date.now() + REPLY_TTL_MS };
|
|
225
|
+
const refresh = { url: `${d.origin}/tokens`, ticket: tokenTicket, signature: await signTokenTicket(rootKey, tokenTicket) };
|
|
226
|
+
|
|
227
|
+
await deployer.run({
|
|
228
|
+
id: d.run,
|
|
229
|
+
repo,
|
|
230
|
+
trigger: d.trigger,
|
|
231
|
+
container: trigger.container,
|
|
232
|
+
runtimes: container.runtimes,
|
|
233
|
+
files: container.files ?? {},
|
|
234
|
+
agent: { id: trigger.agent, ...agent },
|
|
235
|
+
conversation: { id: conversation.id, prompt: conversation.prompt },
|
|
236
|
+
...(worktree && { worktree }),
|
|
237
|
+
cloneToken: await codeHost.channel.token(repo, { contents: "read" }),
|
|
238
|
+
tokens,
|
|
239
|
+
refresh,
|
|
240
|
+
reply,
|
|
241
|
+
});
|
|
242
|
+
console.log(JSON.stringify({ run: d.run, repo, trigger: d.trigger, container: trigger.container, worktree }));
|
|
243
|
+
} catch (error) {
|
|
244
|
+
await d.channel.reply(conversation.thread, `Couldn't start the run of trigger \`${d.trigger}\`: ${message(error)}`);
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
/** Posts a container's reply, if the router signed its ticket, through the channel of the ticket's connection. */
|
|
250
|
+
const relay = async (request: Request, store: RouterStore) => {
|
|
251
|
+
let body: Relay;
|
|
252
|
+
try {
|
|
253
|
+
body = (await request.json()) as Relay;
|
|
254
|
+
} catch {
|
|
255
|
+
return json(400, { error: "the body isn't JSON" });
|
|
256
|
+
}
|
|
257
|
+
const { ticket, signature, text } = body ?? {};
|
|
258
|
+
if (!ticket || typeof signature !== "string" || typeof text !== "string") {
|
|
259
|
+
return json(400, { error: "the body needs ticket, signature and text" });
|
|
260
|
+
}
|
|
261
|
+
if (!(await verifyTicket(await store.rootKey(), ticket, signature))) {
|
|
262
|
+
return json(401, { error: "bad or expired ticket" });
|
|
263
|
+
}
|
|
264
|
+
const found = channels(store).find((c) => c.key === ticket.connection);
|
|
265
|
+
if (!found) return json(404, { error: `no channel for connection ${ticket.connection}` });
|
|
266
|
+
await found.channel.reply(ticket.thread, text);
|
|
267
|
+
return json(200, { ok: true });
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Mints a container's policy tokens again, if the router signed the
|
|
272
|
+
* ticket. The tokens follow the outpost config that the repo has now.
|
|
273
|
+
*/
|
|
274
|
+
const tokens = async (request: Request, store: RouterStore) => {
|
|
275
|
+
let body: TokenRequest;
|
|
276
|
+
try {
|
|
277
|
+
body = (await request.json()) as TokenRequest;
|
|
278
|
+
} catch {
|
|
279
|
+
return json(400, { error: "the body isn't JSON" });
|
|
280
|
+
}
|
|
281
|
+
const { ticket, signature } = body ?? {};
|
|
282
|
+
if (!ticket || typeof signature !== "string") return json(400, { error: "the body needs ticket and signature" });
|
|
283
|
+
if (!(await verifyTokenTicket(await store.rootKey(), ticket, signature))) {
|
|
284
|
+
return json(401, { error: "bad or expired ticket" });
|
|
285
|
+
}
|
|
286
|
+
const outpost = await store.outpost(ticket.repo);
|
|
287
|
+
if (!outpost) return json(404, { error: `${ticket.repo} has no outpost` });
|
|
288
|
+
if (!outpost.containers[ticket.container]) return json(404, { error: `the outpost has no container ${ticket.container}` });
|
|
289
|
+
try {
|
|
290
|
+
return json(200, await mintTokens(store, outpost, ticket.repo, ticket.container));
|
|
291
|
+
} catch (error) {
|
|
292
|
+
return json(502, { error: message(error) });
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
/** Shows a container image's build on the commit it was built from, through the code host's channel. */
|
|
297
|
+
const builds = async (request: Request, store: RouterStore) => {
|
|
298
|
+
let body: BuildReportRequest;
|
|
299
|
+
try {
|
|
300
|
+
body = (await request.json()) as BuildReportRequest;
|
|
301
|
+
} catch {
|
|
302
|
+
return json(400, { error: "the body isn't JSON" });
|
|
303
|
+
}
|
|
304
|
+
const { report, signature } = body ?? {};
|
|
305
|
+
if (!report || typeof signature !== "string") return json(400, { error: "the body needs report and signature" });
|
|
306
|
+
if (!(await verifyBuildReport(await store.rootKey(), report, signature))) {
|
|
307
|
+
return json(401, { error: "bad or expired signature" });
|
|
308
|
+
}
|
|
309
|
+
const channel = codeHostChannel(store)?.channel;
|
|
310
|
+
if (!channel) return json(404, { error: "the hub has no code host" });
|
|
311
|
+
const { repo, ref, container, state, url, summary } = report;
|
|
312
|
+
try {
|
|
313
|
+
await channel.writeCheck(repo, ref, { name: buildCheckName(container), state, ...(url && { url }), ...(summary && { summary }) });
|
|
314
|
+
} catch (error) {
|
|
315
|
+
return json(502, { error: message(error) });
|
|
316
|
+
}
|
|
317
|
+
return json(200, { ok: true });
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
/** Writes a check, and logs a failure instead of throwing it. The App may not have the checks permission yet. */
|
|
321
|
+
const writeCheck = async (channel: RemoteChannel, repo: string, ref: string, check: BuildCheck) => {
|
|
322
|
+
try {
|
|
323
|
+
await channel.writeCheck(repo, ref, check);
|
|
324
|
+
} catch (error) {
|
|
325
|
+
console.error(JSON.stringify({ repo, ref, check: check.name, error: message(error) }));
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const allows = (allow: RepoPattern[], repo: string) => {
|
|
330
|
+
const [owner, name] = repo.toLowerCase().split("/");
|
|
331
|
+
return allow.some(
|
|
332
|
+
(p) => p.owner.toLowerCase() === owner && (!p.repo || p.repo.toLowerCase() === name),
|
|
333
|
+
);
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Deploys one repo's outpost again:
|
|
340
|
+
* 1. A repo that the hub can no longer read, or that the code host doesn't
|
|
341
|
+
* allow, loses its outpost.
|
|
342
|
+
* 2. Otherwise the channel reads `.factory/`, and the deployer evaluates and
|
|
343
|
+
* stores it.
|
|
344
|
+
* 3. The channel shows the outcome on the repo, and a queued check on the
|
|
345
|
+
* commit for each container whose image started building. The deployer
|
|
346
|
+
* reports each build's progress to `/builds`.
|
|
347
|
+
*/
|
|
348
|
+
const redeploy = async (
|
|
349
|
+
change: SourceChange,
|
|
350
|
+
allow: RepoPattern[],
|
|
351
|
+
channel: RemoteChannel,
|
|
352
|
+
deployer: RemoteDeployer,
|
|
353
|
+
) => {
|
|
354
|
+
const { repo, ref } = change;
|
|
355
|
+
if (change.removed) return deployer.remove(repo);
|
|
356
|
+
const at = () => new Date().toISOString();
|
|
357
|
+
let status: FactoryStatus;
|
|
358
|
+
if (!allows(allow, repo)) {
|
|
359
|
+
await deployer.remove(repo);
|
|
360
|
+
status = { state: "failed", error: `The hub doesn't serve ${repo}: the code host's allow list doesn't include it.`, at: at() };
|
|
361
|
+
} else {
|
|
362
|
+
try {
|
|
363
|
+
status = await deployer.deploy(repo, await channel.read(repo, FACTORY_DIR, ref));
|
|
364
|
+
} catch (error) {
|
|
365
|
+
status = { state: "failed", ref, error: message(error), at: at() };
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
await channel.writeStatus(repo, status);
|
|
369
|
+
for (const container of status.building ?? []) {
|
|
370
|
+
if (status.ref) await writeCheck(channel, repo, status.ref, { name: buildCheckName(container), state: "queued" });
|
|
371
|
+
}
|
|
372
|
+
console.log(JSON.stringify({ repo, ...status }));
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
/** Deploys the outposts of the repos a delivery changed. Only the code host's connection reads repos. */
|
|
376
|
+
const source = async (
|
|
377
|
+
key: string,
|
|
378
|
+
changes: SourceChange[],
|
|
379
|
+
channel: RemoteChannel,
|
|
380
|
+
store: RouterStore,
|
|
381
|
+
) => {
|
|
382
|
+
const codeHost = store.config.codeHost;
|
|
383
|
+
if (!codeHost || `${codeHost.provider}/${codeHost.connection}` !== key) {
|
|
384
|
+
return json(200, { ignored: "not the code host's connection" });
|
|
385
|
+
}
|
|
386
|
+
const { deployer } = store;
|
|
387
|
+
if (!deployer) return json(200, { ignored: "no deployer" });
|
|
388
|
+
const task = (async () => {
|
|
389
|
+
for (const change of changes) {
|
|
390
|
+
try {
|
|
391
|
+
await redeploy(change, codeHost.allow ?? [], channel, deployer);
|
|
392
|
+
} catch (error) {
|
|
393
|
+
console.error(JSON.stringify({ repo: change.repo, error: message(error) }));
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
})();
|
|
397
|
+
if (store.background) store.background(task);
|
|
398
|
+
else await task;
|
|
399
|
+
return json(202, { connection: key, deploying: changes.map((c) => c.repo) });
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
/** Has each connection's channel set up its platform side, pointing it at this router. */
|
|
403
|
+
const sync = async (request: Request, store: RouterStore) => {
|
|
404
|
+
const { origin } = new URL(request.url);
|
|
405
|
+
const results: Record<string, string> = {};
|
|
406
|
+
for (const { key, channel } of channels(store)) {
|
|
407
|
+
try {
|
|
408
|
+
await channel.sync(`${origin}${webhookPath(key)}`);
|
|
409
|
+
results[key] = "ok";
|
|
410
|
+
} catch (error) {
|
|
411
|
+
results[key] = error instanceof Error ? error.message : String(error);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const failed = Object.values(results).some((r) => r !== "ok");
|
|
415
|
+
return json(failed ? 502 : 200, { connections: results });
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* The router's routes. `POST /sync` needs no auth, because a channel's sync
|
|
420
|
+
* only sets the values the router derives. `POST /relay` and `POST /tokens`
|
|
421
|
+
* take tickets that the router signed when it started a run. `POST /builds`
|
|
422
|
+
* takes reports that the deployer signed.
|
|
423
|
+
*/
|
|
424
|
+
export const handle = (request: Request, store: RouterStore) => {
|
|
425
|
+
const { pathname } = new URL(request.url);
|
|
426
|
+
if (request.method === "POST" && pathname.startsWith("/webhook/")) {
|
|
427
|
+
return webhook(request, pathname.slice("/webhook/".length), store);
|
|
428
|
+
}
|
|
429
|
+
if (request.method === "POST" && pathname === "/relay") {
|
|
430
|
+
return relay(request, store);
|
|
431
|
+
}
|
|
432
|
+
if (request.method === "POST" && pathname === "/tokens") {
|
|
433
|
+
return tokens(request, store);
|
|
434
|
+
}
|
|
435
|
+
if (request.method === "POST" && pathname === "/builds") {
|
|
436
|
+
return builds(request, store);
|
|
437
|
+
}
|
|
438
|
+
if (request.method === "POST" && pathname === "/sync") {
|
|
439
|
+
return sync(request, store);
|
|
440
|
+
}
|
|
441
|
+
return Promise.resolve(json(404, { error: "not found" }));
|
|
442
|
+
};
|
package/router/index.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export type {
|
|
2
|
+
AgentEntry,
|
|
3
|
+
ChannelEntry,
|
|
4
|
+
ContainerEntry,
|
|
5
|
+
ConnectionEntry,
|
|
6
|
+
OutpostConfig,
|
|
7
|
+
RouterConfig,
|
|
8
|
+
TriggerEntry,
|
|
9
|
+
} from "../contracts/index.ts";
|
|
10
|
+
export type {
|
|
11
|
+
AuthorCheck,
|
|
12
|
+
BuildCheck,
|
|
13
|
+
Channel,
|
|
14
|
+
ChannelContext,
|
|
15
|
+
ChannelModule,
|
|
16
|
+
Conversation,
|
|
17
|
+
Delivery,
|
|
18
|
+
FactoryStatus,
|
|
19
|
+
Received,
|
|
20
|
+
RemoteChannel,
|
|
21
|
+
SourceChange,
|
|
22
|
+
SourceFiles,
|
|
23
|
+
} from "./channel.ts";
|
|
24
|
+
export {
|
|
25
|
+
buildCheckName,
|
|
26
|
+
FACTORY_DIR,
|
|
27
|
+
handle,
|
|
28
|
+
outpostKey,
|
|
29
|
+
type RemoteDeployer,
|
|
30
|
+
type RouterStore,
|
|
31
|
+
type TriggerMatch,
|
|
32
|
+
webhookPath,
|
|
33
|
+
} from "./handle.ts";
|
|
34
|
+
export { deriveKey, hmacHex, timingSafeEqual } from "./keys.ts";
|
|
35
|
+
export {
|
|
36
|
+
type BuildReport,
|
|
37
|
+
type BuildReportRequest,
|
|
38
|
+
isBranchName,
|
|
39
|
+
type Relay,
|
|
40
|
+
REPLY_TTL_MS,
|
|
41
|
+
type ReplyTicket,
|
|
42
|
+
type Run,
|
|
43
|
+
signBuildReport,
|
|
44
|
+
signTicket,
|
|
45
|
+
signTokenTicket,
|
|
46
|
+
type TokenRequest,
|
|
47
|
+
type Tokens,
|
|
48
|
+
type TokenTicket,
|
|
49
|
+
verifyBuildReport,
|
|
50
|
+
verifyTicket,
|
|
51
|
+
verifyTokenTicket,
|
|
52
|
+
} from "./run.ts";
|
package/router/keys.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
|
|
3
|
+
const hex = (bytes: ArrayBuffer) =>
|
|
4
|
+
Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join(
|
|
5
|
+
"",
|
|
6
|
+
);
|
|
7
|
+
|
|
8
|
+
/** HMAC-SHA256 of `message` with `key`, as lower-case hex. */
|
|
9
|
+
export const hmacHex = async (key: string, message: string | Uint8Array<ArrayBuffer>) => {
|
|
10
|
+
const cryptoKey = await crypto.subtle.importKey(
|
|
11
|
+
"raw",
|
|
12
|
+
encoder.encode(key),
|
|
13
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
14
|
+
false,
|
|
15
|
+
["sign"],
|
|
16
|
+
);
|
|
17
|
+
const data = typeof message === "string" ? encoder.encode(message) : message;
|
|
18
|
+
return hex(await crypto.subtle.sign("HMAC", cryptoKey, data));
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Derives a key from the root key. `purpose` names what the key is for, such
|
|
23
|
+
* as `github:webhook:<App id>`, so that no two purposes share a key.
|
|
24
|
+
*/
|
|
25
|
+
export const deriveKey = (rootKey: string, purpose: string) =>
|
|
26
|
+
hmacHex(rootKey, purpose);
|
|
27
|
+
|
|
28
|
+
/** Compares two strings in time that depends only on their lengths. */
|
|
29
|
+
export const timingSafeEqual = (a: string, b: string) => {
|
|
30
|
+
const x = encoder.encode(a);
|
|
31
|
+
const y = encoder.encode(b);
|
|
32
|
+
if (x.length !== y.length) return false;
|
|
33
|
+
let diff = 0;
|
|
34
|
+
for (let i = 0; i < x.length; i++) diff |= x[i]! ^ y[i]!;
|
|
35
|
+
return diff === 0;
|
|
36
|
+
};
|
package/router/run.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { AgentEntry, ContainerEntry } from "../contracts/outpost.ts";
|
|
2
|
+
import { deriveKey, hmacHex, timingSafeEqual } from "./keys.ts";
|
|
3
|
+
|
|
4
|
+
/** Where a run's reply goes: the connection whose channel posts it, and the channel's thread. `expires` is in ms since the epoch. */
|
|
5
|
+
export type ReplyTicket = { connection: string; thread: unknown; expires: number };
|
|
6
|
+
|
|
7
|
+
/** What the runner posts to a run's `reply.url`. */
|
|
8
|
+
export type Relay = { ticket: ReplyTicket; signature: string; text: string };
|
|
9
|
+
|
|
10
|
+
/** Which container's policy tokens the router mints again: a container of the repo's outpost. `expires` is in ms since the epoch. */
|
|
11
|
+
export type TokenTicket = { repo: string; container: string; expires: number };
|
|
12
|
+
|
|
13
|
+
/** What the runner posts to a run's `refresh.url`. The router answers with `Tokens`. */
|
|
14
|
+
export type TokenRequest = { ticket: TokenTicket; signature: string };
|
|
15
|
+
|
|
16
|
+
/** A token for each of a container's code host policies. */
|
|
17
|
+
export type Tokens = { policy: string; repo: string; token: string }[];
|
|
18
|
+
|
|
19
|
+
/** A container image's build, as the deployer reports it. `ref` is the code host's commit that the build's source was read at. `expires` is in ms since the epoch. */
|
|
20
|
+
export type BuildReport = {
|
|
21
|
+
repo: string;
|
|
22
|
+
ref: string;
|
|
23
|
+
container: string;
|
|
24
|
+
state: "in_progress" | "success" | "failure" | "cancelled";
|
|
25
|
+
url?: string;
|
|
26
|
+
summary?: string;
|
|
27
|
+
expires: number;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** What the deployer posts to the router's `/builds` route. */
|
|
31
|
+
export type BuildReportRequest = { report: BuildReport; signature: string };
|
|
32
|
+
|
|
33
|
+
/** What a container's runner needs for one trigger match. */
|
|
34
|
+
export type Run = {
|
|
35
|
+
id: string;
|
|
36
|
+
repo: string;
|
|
37
|
+
trigger: string;
|
|
38
|
+
container: string;
|
|
39
|
+
/** The container's runtimes. The provider gives the container their accounts' credentials. */
|
|
40
|
+
runtimes: string[];
|
|
41
|
+
/** The container's startup files, read from `.factory/` in the checkout. */
|
|
42
|
+
files: ContainerEntry["files"];
|
|
43
|
+
agent: { id: string } & AgentEntry;
|
|
44
|
+
conversation: { id: string; prompt: string };
|
|
45
|
+
/** The branch to run on, cut from `base` if it doesn't exist. Without it, the run gets a scratch checkout of the default branch. */
|
|
46
|
+
worktree?: { branch: string; base?: string };
|
|
47
|
+
/** A read-only token for cloning the repo. */
|
|
48
|
+
cloneToken: string;
|
|
49
|
+
/** A token for each of the container's code host policies. */
|
|
50
|
+
tokens: Tokens;
|
|
51
|
+
/** The runner posts a `TokenRequest` with this ticket and signature to `url` for new tokens, before the old ones expire. */
|
|
52
|
+
refresh: { url: string; ticket: TokenTicket; signature: string };
|
|
53
|
+
/** The runner posts a `Relay` with this ticket and signature to `url`. */
|
|
54
|
+
reply: { url: string; ticket: ReplyTicket; signature: string };
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** How long a container may reply to a run, or ask for its tokens again. A run may wait in the queue behind others before it starts. */
|
|
58
|
+
export const REPLY_TTL_MS = 24 * 60 * 60 * 1000;
|
|
59
|
+
|
|
60
|
+
const sign = async (rootKey: string, purpose: string, ticket: { expires: number }) =>
|
|
61
|
+
hmacHex(await deriveKey(rootKey, purpose), JSON.stringify(ticket));
|
|
62
|
+
|
|
63
|
+
const verify = async (rootKey: string, purpose: string, ticket: { expires: number }, signature: string) =>
|
|
64
|
+
ticket.expires > Date.now() && timingSafeEqual(signature, await sign(rootKey, purpose, ticket));
|
|
65
|
+
|
|
66
|
+
export const signTicket = (rootKey: string, ticket: ReplyTicket) => sign(rootKey, "router:relay", ticket);
|
|
67
|
+
|
|
68
|
+
/** Whether the router signed `ticket`, and it hasn't expired. */
|
|
69
|
+
export const verifyTicket = (rootKey: string, ticket: ReplyTicket, signature: string) =>
|
|
70
|
+
verify(rootKey, "router:relay", ticket, signature);
|
|
71
|
+
|
|
72
|
+
export const signTokenTicket = (rootKey: string, ticket: TokenTicket) => sign(rootKey, "router:tokens", ticket);
|
|
73
|
+
|
|
74
|
+
/** Whether the router signed `ticket`, and it hasn't expired. */
|
|
75
|
+
export const verifyTokenTicket = (rootKey: string, ticket: TokenTicket, signature: string) =>
|
|
76
|
+
verify(rootKey, "router:tokens", ticket, signature);
|
|
77
|
+
|
|
78
|
+
export const signBuildReport = (rootKey: string, report: BuildReport) => sign(rootKey, "router:builds", report);
|
|
79
|
+
|
|
80
|
+
/** Whether the deployer signed `report`, and it hasn't expired. */
|
|
81
|
+
export const verifyBuildReport = (rootKey: string, report: BuildReport, signature: string) =>
|
|
82
|
+
verify(rootKey, "router:builds", report, signature);
|
|
83
|
+
|
|
84
|
+
/** A git branch name the runner can check out: no `..`, no leading `-` or `/`, and only letters, digits and `._/-`. */
|
|
85
|
+
export const isBranchName = (name: string) =>
|
|
86
|
+
/^[A-Za-z0-9._][A-Za-z0-9._/-]*$/.test(name) &&
|
|
87
|
+
!name.includes("..") &&
|
|
88
|
+
!name.includes("//") &&
|
|
89
|
+
!name.endsWith("/") &&
|
|
90
|
+
!name.endsWith(".lock") &&
|
|
91
|
+
name.length <= 200;
|