@nathanstephenson/flow 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +641 -0
- package/build/workflow-runtime.cjs +213964 -0
- package/dist/backend/claude/async-queue.js +44 -0
- package/dist/backend/claude/auto-compaction.js +10 -0
- package/dist/backend/claude/background-calls.js +116 -0
- package/dist/backend/claude/enquiries.js +162 -0
- package/dist/backend/claude/index.js +1138 -0
- package/dist/backend/claude/mcp.js +55 -0
- package/dist/backend/claude/permissions.js +106 -0
- package/dist/backend/claude/streamed-message.js +120 -0
- package/dist/backend/claude/subagents.js +128 -0
- package/dist/backend/claude/workflow-parent.js +12 -0
- package/dist/backend/claude/workflow-processes.js +95 -0
- package/dist/backend/claude/workflow-subagent.js +234 -0
- package/dist/backend/effort.js +30 -0
- package/dist/backend/fake/index.js +570 -0
- package/dist/backend/mcp.js +190 -0
- package/dist/backend/pi/auto-compaction.js +16 -0
- package/dist/backend/pi/background-calls.js +56 -0
- package/dist/backend/pi/enquiries.js +63 -0
- package/dist/backend/pi/index.js +597 -0
- package/dist/backend/pi/mcp.js +35 -0
- package/dist/backend/pi/subagents.js +23 -0
- package/dist/backend/pi/work.js +104 -0
- package/dist/backend/pi/workflow-parent.js +21 -0
- package/dist/backend/pi/workflow-subagent.js +199 -0
- package/dist/backend/registry.js +34 -0
- package/dist/backend/types.js +1 -0
- package/dist/backend/workflow-tools.js +25 -0
- package/dist/build-id +1 -0
- package/dist/cli/application.js +397 -0
- package/dist/cli/bootstrap.js +535 -0
- package/dist/cli/host-control.js +100 -0
- package/dist/cli/install-guard.js +270 -0
- package/dist/cli/install-process.js +52 -0
- package/dist/cli/main.js +12 -0
- package/dist/cli/update.js +128 -0
- package/dist/client/connection.js +183 -0
- package/dist/client/context-usage.js +66 -0
- package/dist/client/diff.js +36 -0
- package/dist/client/enquiry.js +105 -0
- package/dist/client/markdown.js +192 -0
- package/dist/client/model-choices.js +32 -0
- package/dist/client/permission.js +60 -0
- package/dist/client/project-name.js +19 -0
- package/dist/client/reduce.js +463 -0
- package/dist/client/relative-time.js +30 -0
- package/dist/client/scope-kind.js +28 -0
- package/dist/client/search.js +136 -0
- package/dist/client/session-label.js +9 -0
- package/dist/client/status.js +84 -0
- package/dist/client/tool-chains.js +52 -0
- package/dist/client/tool-summary.js +98 -0
- package/dist/daemon/auth.js +590 -0
- package/dist/daemon/config-store.js +183 -0
- package/dist/daemon/config.js +687 -0
- package/dist/daemon/credential-redaction.js +9 -0
- package/dist/daemon/git.js +312 -0
- package/dist/daemon/host-control-routes.js +29 -0
- package/dist/daemon/host.js +2343 -0
- package/dist/daemon/http.js +19 -0
- package/dist/daemon/log.js +44 -0
- package/dist/daemon/mcp-auth.js +164 -0
- package/dist/daemon/models.js +85 -0
- package/dist/daemon/ownership.js +104 -0
- package/dist/daemon/projects.js +317 -0
- package/dist/daemon/publish.js +289 -0
- package/dist/daemon/pull-request.js +198 -0
- package/dist/daemon/runtime.js +100 -0
- package/dist/daemon/secret-store.js +65 -0
- package/dist/daemon/server.js +827 -0
- package/dist/daemon/shell.js +220 -0
- package/dist/daemon/skills.js +104 -0
- package/dist/daemon/stack-metadata.js +24 -0
- package/dist/daemon/stack.js +743 -0
- package/dist/daemon/store.js +130 -0
- package/dist/daemon/summariser.js +476 -0
- package/dist/daemon/workflow-execution-routes.js +105 -0
- package/dist/daemon/workflow-executions.js +1018 -0
- package/dist/daemon/workflow-mcp.js +20 -0
- package/dist/daemon/workflow-routes.js +102 -0
- package/dist/protocol/attachments.js +59 -0
- package/dist/protocol/commands.js +1 -0
- package/dist/protocol/events.js +20 -0
- package/dist/protocol/fonts.js +26 -0
- package/dist/protocol/git.js +12 -0
- package/dist/protocol/mcp.js +51 -0
- package/dist/protocol/projects.js +21 -0
- package/dist/protocol/publish.js +1 -0
- package/dist/protocol/pull-request.js +1 -0
- package/dist/protocol/secrets.js +4 -0
- package/dist/protocol/settings.js +63 -0
- package/dist/protocol/shells.js +8 -0
- package/dist/protocol/skills.js +16 -0
- package/dist/protocol/stack.js +41 -0
- package/dist/protocol/workflow-executions.js +1 -0
- package/dist/protocol/workflows.js +1 -0
- package/dist/tui/app.js +518 -0
- package/dist/tui/keys.js +54 -0
- package/dist/tui/render.js +366 -0
- package/dist/web/assets.js +10 -0
- package/dist/web/embedded.js +12 -0
- package/dist/web/manifest.js +70 -0
- package/dist/workflows/decisions.js +65 -0
- package/dist/workflows/executors.js +132 -0
- package/dist/workflows/graph.js +276 -0
- package/dist/workflows/json-schema.js +49 -0
- package/dist/workflows/loops.js +102 -0
- package/dist/workflows/mcp.js +18 -0
- package/dist/workflows/records.js +111 -0
- package/dist/workflows/recovery.js +25 -0
- package/dist/workflows/runtime-asset.js +17 -0
- package/dist/workflows/runtime-libs.js +1 -0
- package/dist/workflows/runtime-settings.js +23 -0
- package/dist/workflows/runtime.js +343 -0
- package/dist/workflows/scheduler.js +573 -0
- package/dist/workflows/schema.js +161 -0
- package/dist/workflows/store.js +93 -0
- package/package.json +87 -0
- package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/web/dist/assets/index-BC0gLS53.js +106 -0
- package/web/dist/assets/index-CCeZYKES.css +2 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
- package/web/dist/assets/select-6i3wxovH.js +1 -0
- package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
- package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
- package/web/dist/assets/switch-ftZleVB8.js +6 -0
- package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
- package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
- package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
- package/web/dist/index.html +31 -0
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { mediaTypeOf } from "../protocol/attachments.js";
|
|
3
|
+
import { ConfigError } from "./config.js";
|
|
4
|
+
import { workflowRoutes } from "./workflow-routes.js";
|
|
5
|
+
import { hostControlRoute } from "./host-control-routes.js";
|
|
6
|
+
import { readBody, send } from "./http.js";
|
|
7
|
+
import { workflowExecutionRoutes } from "./workflow-execution-routes.js";
|
|
8
|
+
import { discoverProjects, includedProjects, searchDirectories } from "./projects.js";
|
|
9
|
+
import { gitAvailable, head, isRepository, localBranches, MAX_BRANCHES } from "./git.js";
|
|
10
|
+
import { tokenMatches } from "./auth.js";
|
|
11
|
+
import { CommandRefused } from "./host.js";
|
|
12
|
+
export async function serve(options) {
|
|
13
|
+
const address = options.address ?? "127.0.0.1";
|
|
14
|
+
let stopping = false;
|
|
15
|
+
const pending = new Set();
|
|
16
|
+
const sockets = new Set();
|
|
17
|
+
const track = (work) => { pending.add(work); void work.finally(() => pending.delete(work)); };
|
|
18
|
+
const server = createServer((request, response) => {
|
|
19
|
+
let path;
|
|
20
|
+
try {
|
|
21
|
+
path = new URL(request.url ?? '/', 'http://localhost').pathname;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
send(response, 400, { error: 'Invalid request URL' });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (options.control && (path === '/api/host' || path === '/api/host/stop')) {
|
|
28
|
+
if (!originAllowed(request, options.oidc?.config.publicAppUrl)) {
|
|
29
|
+
send(response, 403, {});
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (!tokenMatches(options.token, presentedBearer(request))) {
|
|
33
|
+
unauthorized(response);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
void hostControlRoute(request, response, path, options.control, {
|
|
37
|
+
isStopping: () => stopping, hasPending: () => pending.size > 0, stop: () => { stopping = true; },
|
|
38
|
+
});
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (stopping) {
|
|
42
|
+
send(response, 503, { error: 'Session Host is stopping' });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const work = handle(request, response, options).catch((error) => {
|
|
46
|
+
send(response, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
47
|
+
});
|
|
48
|
+
track(work);
|
|
49
|
+
});
|
|
50
|
+
server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
|
|
51
|
+
const shells = options.shells;
|
|
52
|
+
if (shells) {
|
|
53
|
+
server.on("upgrade", (request, socket, head) => {
|
|
54
|
+
if (stopping) {
|
|
55
|
+
refuse(socket, 503);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
track(handleUpgrade(request, socket, head, options, shells).catch(() => refuse(socket, 500)));
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
await new Promise((resolve, reject) => {
|
|
62
|
+
server.once('error', reject);
|
|
63
|
+
server.listen(options.port ?? 0, address, () => { server.off('error', reject); resolve(); });
|
|
64
|
+
});
|
|
65
|
+
const port = server.address().port;
|
|
66
|
+
return {
|
|
67
|
+
server,
|
|
68
|
+
url: `http://${address}:${port}`,
|
|
69
|
+
...(options.oidc === undefined ? {} : { oidc: options.oidc }),
|
|
70
|
+
stopAdmission: async (interrupt, timeoutMs = 10000) => {
|
|
71
|
+
stopping = true;
|
|
72
|
+
for (const socket of sockets)
|
|
73
|
+
socket.destroy();
|
|
74
|
+
let timer;
|
|
75
|
+
try {
|
|
76
|
+
await Promise.race([
|
|
77
|
+
Promise.all([...pending, interrupt?.()]),
|
|
78
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Session Host drain timed out; ownership retained')), timeoutMs); }),
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
close: () => {
|
|
86
|
+
for (const socket of sockets)
|
|
87
|
+
socket.destroy();
|
|
88
|
+
options.mcpAuth?.dispose();
|
|
89
|
+
options.oidc?.dispose();
|
|
90
|
+
return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
async function handle(request, response, options) {
|
|
95
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
96
|
+
if (request.method === "GET" && url.pathname === "/api/mcp/callback") {
|
|
97
|
+
try {
|
|
98
|
+
if (!options.mcpAuth)
|
|
99
|
+
throw new Error("MCP auth unavailable");
|
|
100
|
+
const location = await options.mcpAuth.callback(url);
|
|
101
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer" });
|
|
102
|
+
response.end(`<!doctype html><title>Return to Flow</title><script>window.location.replace(${JSON.stringify(location).replace(/</g, "\\u003c")})</script>`);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
send(response, 400, { error: "Invalid or expired MCP sign-in. Return to Flow and try again." });
|
|
106
|
+
}
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
/*
|
|
110
|
+
* OIDC protocol endpoints are outside the app-session gate by definition. The back-channel route
|
|
111
|
+
* is issuer-to-daemon and has neither a browser Origin nor a Flow credential; its signed logout
|
|
112
|
+
* token is the credential. The MCP callback remains above all of these and independently secured.
|
|
113
|
+
*/
|
|
114
|
+
if (options.oidc && request.method === "POST" && url.pathname === "/oauth/backchannel") {
|
|
115
|
+
try {
|
|
116
|
+
const body = new URLSearchParams(await readBody(request, 16 * 1024));
|
|
117
|
+
const logoutToken = body.get("logout_token");
|
|
118
|
+
if (!logoutToken)
|
|
119
|
+
throw new Error("missing logout token");
|
|
120
|
+
await options.oidc.backchannelLogout(logoutToken);
|
|
121
|
+
response.writeHead(200, { "cache-control": "no-store" });
|
|
122
|
+
response.end();
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
send(response, 400, { error: "Invalid logout notification" });
|
|
126
|
+
}
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (options.oidc && request.method === "GET" && url.pathname === "/oauth/login") {
|
|
130
|
+
response.writeHead(302, {
|
|
131
|
+
location: await options.oidc.beginLogin(url.searchParams.get("return_to") ?? undefined),
|
|
132
|
+
"cache-control": "no-store",
|
|
133
|
+
"referrer-policy": "no-referrer",
|
|
134
|
+
});
|
|
135
|
+
response.end();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (options.oidc && request.method === "GET" && url.pathname === "/oauth/callback") {
|
|
139
|
+
try {
|
|
140
|
+
const completed = await options.oidc.completeLogin(url);
|
|
141
|
+
response.writeHead(302, {
|
|
142
|
+
location: completed.location,
|
|
143
|
+
"set-cookie": completed.cookie,
|
|
144
|
+
"cache-control": "no-store",
|
|
145
|
+
"referrer-policy": "no-referrer",
|
|
146
|
+
});
|
|
147
|
+
response.end();
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
sendAuthPage(response, 400, "Sign-in could not be completed", "The response was invalid or the sign-in request expired. No credentials were saved.", { href: "/oauth/login", label: "Try signing in again" });
|
|
151
|
+
}
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (options.oidc && request.method === "GET" && url.pathname === "/oauth/signed-out") {
|
|
155
|
+
sendAuthPage(response, 200, "You’re signed out", "This browser no longer has access to Flow. Agent Sessions keep running in the background.", { href: "/oauth/login", label: "Sign in again" });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
// A page on any origin can reach loopback; only the configured public origin may command an OIDC
|
|
159
|
+
// deployment. No Forwarded/X-Forwarded header participates in this decision.
|
|
160
|
+
if (!originAllowed(request, options.oidc?.config.publicAppUrl)) {
|
|
161
|
+
send(response, 403, { error: "Origin not allowed" });
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// The local-mode handoff is disabled, not merely unused, when OIDC owns browser authentication.
|
|
165
|
+
// This also ensures an old `flow=` cookie cannot bypass the external issuer.
|
|
166
|
+
if (url.pathname === "/auth") {
|
|
167
|
+
if (options.oidc) {
|
|
168
|
+
send(response, 404, { error: "Not found" });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const presented = url.searchParams.get("token") ?? undefined;
|
|
172
|
+
if (!tokenMatches(options.token, presented)) {
|
|
173
|
+
unauthorized(response);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
response.writeHead(302, {
|
|
177
|
+
"set-cookie": `flow=${presented}; HttpOnly; SameSite=Strict; Path=/`,
|
|
178
|
+
// Relative on purpose, and load-bearing when the handoff is taken through the Vite dev
|
|
179
|
+
// server's proxy: an absolute Location would bounce the browser back to the Session Host's own
|
|
180
|
+
// origin, stranding the cookie there while the app it has to authenticate sits on the other.
|
|
181
|
+
location: "/",
|
|
182
|
+
});
|
|
183
|
+
response.end();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const authentication = await authenticateRequest(request, options);
|
|
187
|
+
if (!authentication) {
|
|
188
|
+
if (options.oidc && documentNavigation(request, url.pathname)) {
|
|
189
|
+
sendLoginRedirectPage(response);
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
unauthorized(response, options.oidc ? "/oauth/login" : undefined);
|
|
193
|
+
}
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (options.oidc && request.method === "POST" && url.pathname === "/oauth/logout") {
|
|
197
|
+
options.oidc.logout(request.headers.cookie);
|
|
198
|
+
response.writeHead(303, {
|
|
199
|
+
location: "/oauth/signed-out",
|
|
200
|
+
"set-cookie": options.oidc.clearCookie(),
|
|
201
|
+
"cache-control": "no-store",
|
|
202
|
+
});
|
|
203
|
+
response.end();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (await workflowExecutionRoutes(request, response, url.pathname, options.workflowExecutions, options.workflows))
|
|
207
|
+
return;
|
|
208
|
+
if (await workflowRoutes(request, response, url.pathname, options.workflows, options.secrets, options.workflowExecutions))
|
|
209
|
+
return;
|
|
210
|
+
const mcpRoute = /^\/api\/sessions\/([^/]+)\/mcp(?:\/([^/]+)\/retry)?$/.exec(url.pathname);
|
|
211
|
+
if (mcpRoute) {
|
|
212
|
+
try {
|
|
213
|
+
if (request.method === "POST" && mcpRoute[2]) {
|
|
214
|
+
await options.host.retryMcp(mcpRoute[1], mcpRoute[2]);
|
|
215
|
+
send(response, 200, options.host.mcpStatus(mcpRoute[1]));
|
|
216
|
+
}
|
|
217
|
+
else if (request.method === "GET" && !mcpRoute[2])
|
|
218
|
+
send(response, 200, options.host.mcpStatus(mcpRoute[1]));
|
|
219
|
+
else
|
|
220
|
+
send(response, 405, { error: "Method not allowed" });
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
send(response, 400, { error: "MCP operation failed. Retry requires an Idle Agent Session without background work." });
|
|
224
|
+
}
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const mcpLogin = /^\/api\/mcp\/([^/]+)\/login$/.exec(url.pathname);
|
|
228
|
+
if (request.method === "POST" && mcpLogin) {
|
|
229
|
+
const connection = options.config?.mcpConnections().find((entry) => entry.id === mcpLogin[1]);
|
|
230
|
+
try {
|
|
231
|
+
if (!connection || !options.mcpAuth)
|
|
232
|
+
throw new Error("Unknown connection");
|
|
233
|
+
const body = JSON.parse(await readBody(request));
|
|
234
|
+
const returnUrl = new URL(body.returnUrl);
|
|
235
|
+
if (returnUrl.host !== request.headers.host ||
|
|
236
|
+
(request.headers.origin && returnUrl.origin !== request.headers.origin))
|
|
237
|
+
throw new Error("Invalid return origin");
|
|
238
|
+
send(response, 200, { url: await options.mcpAuth.login(connection, returnUrl.href) });
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
send(response, 400, { error: "MCP sign-in failed or is already in progress" });
|
|
242
|
+
}
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (request.method === "GET" && url.pathname === "/api/sessions") {
|
|
246
|
+
send(response, 200, options.host.list());
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (request.method === "GET" && url.pathname === "/api/config") {
|
|
250
|
+
send(response, 200, {
|
|
251
|
+
// The Project Root first: it is the directory this deployment is anchored to, and a client
|
|
252
|
+
// with no working directory of its own has nothing better to say it is open on. Resolved here
|
|
253
|
+
// rather than in main.ts on purpose — computing it at startup is the exact bug ADR 0009
|
|
254
|
+
// exists to prevent, where editing the root in a browser only reaches the *next* daemon.
|
|
255
|
+
scope: options.config?.projectRoot() ?? options.scope ?? process.cwd(),
|
|
256
|
+
backends: options.host.backendNames(),
|
|
257
|
+
// Whether this build can open a Shell at all. The web client hides the control when it cannot
|
|
258
|
+
// rather than offering one that fails on click — the rule Capabilities already sets for
|
|
259
|
+
// backends, applied to a host-wide facility.
|
|
260
|
+
shell: (await options.shells?.available()) ?? false,
|
|
261
|
+
// Whether this build can run git at all — exactly the question `shell` above asks, and the
|
|
262
|
+
// same answer: hide the control rather than offer one that fails on click. git is a
|
|
263
|
+
// documented prerequisite rather than a dependency, so a single-executable build or a bare
|
|
264
|
+
// container has none, and without this a Scope's `.git` would promise a control that then
|
|
265
|
+
// fails with ENOENT.
|
|
266
|
+
git: await gitAvailable(),
|
|
267
|
+
// Lets the browser offer reauthentication and logout without exposing provider details.
|
|
268
|
+
authentication: options.oidc ? "oidc" : "token",
|
|
269
|
+
// The two Project lists, disjoint, both derived and both asked fresh on each request.
|
|
270
|
+
//
|
|
271
|
+
// `projectList` is what a client offers: the opted-in Projects, resolved from
|
|
272
|
+
// `projects.include`. `projectCandidates` is what the Settings page offers to opt *into*:
|
|
273
|
+
// repositories found beneath the Project Root that are not already in the list. Separating
|
|
274
|
+
// them here rather than sending one annotated list means neither consumer has to filter, and
|
|
275
|
+
// the dropdown cannot accidentally show a candidate.
|
|
276
|
+
//
|
|
277
|
+
// Beside the Settings rather than inside them: both are *derived* state, and folding them in
|
|
278
|
+
// would break the invariant that `settingsOf()` is one function serving both the file and the
|
|
279
|
+
// wire, so that GET cannot report something config.json does not hold (ADR 0009). Uncached
|
|
280
|
+
// for a plainer reason — cloning a repository changes the answer without changing the file, so
|
|
281
|
+
// a cache would need a filesystem watcher to make it more often wrong.
|
|
282
|
+
...projectLists(options.config),
|
|
283
|
+
// Reported rather than decided by the client: the daemon owns config.json, and a font is the
|
|
284
|
+
// one piece of presentation whose right answer depends on the machine (src/daemon/config.ts).
|
|
285
|
+
// Spread rather than nested so `fonts` stays where it was on the wire.
|
|
286
|
+
...(options.config?.view() ?? {}),
|
|
287
|
+
});
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (request.method === "PUT" && url.pathname === "/api/config") {
|
|
291
|
+
await handleSettingsUpdate(request, response, options.config);
|
|
292
|
+
options.workflowExecutions?.refresh();
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
/*
|
|
296
|
+
* `GET /api/directories?q=…` — directories to opt in as Projects.
|
|
297
|
+
*
|
|
298
|
+
* Its own endpoint rather than more of /api/config, because it answers a *query* rather than
|
|
299
|
+
* reporting state: it changes with every keystroke and none of its answers are worth folding into
|
|
300
|
+
* the document every other client polls.
|
|
301
|
+
*
|
|
302
|
+
* This enumerates the filesystem to whoever holds the token. That is not a new privilege — ADR
|
|
303
|
+
* 0004 has it that anything able to reach this daemon can already run commands as this user — but
|
|
304
|
+
* it is the first endpoint whose whole job is to read outside the state root, so it is worth being
|
|
305
|
+
* deliberate: it returns directory *names* only, never file contents, and never follows a symlink.
|
|
306
|
+
*/
|
|
307
|
+
if (request.method === "GET" && url.pathname === "/api/directories") {
|
|
308
|
+
send(response, 200, searchDirectories(options.config?.rawProjectRoot(), url.searchParams.get("q") ?? ""));
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
/*
|
|
312
|
+
* `GET /api/branches?scope=…` — the branches a Scope could be switched to.
|
|
313
|
+
*
|
|
314
|
+
* Its own endpoint rather than more of `/api/config`, and a query rather than state, for the
|
|
315
|
+
* reason `/api/directories` is (ADR 0011): the answer changes outside Flow — a `git
|
|
316
|
+
* branch` in a terminal, a `git fetch` — so there is nothing worth folding into the document
|
|
317
|
+
* every client polls, and a cache would need a filesystem watcher in order to be more often
|
|
318
|
+
* wrong.
|
|
319
|
+
*
|
|
320
|
+
* Answers for a *Scope* rather than for an Agent Session, because the New Agent Session view
|
|
321
|
+
* has to ask before there is a session to ask about: picking the branch to cut a worktree from
|
|
322
|
+
* happens first. `head` is reported here as well as on `SessionSummary`, and the two cannot
|
|
323
|
+
* disagree, because both are `head()` in `src/daemon/git.ts`.
|
|
324
|
+
*
|
|
325
|
+
* A Scope that is not a repository is a 200 carrying `repository: false`, not a 404: the
|
|
326
|
+
* directory exists, and reporting the state distinguishes "not a repository" from a typo better
|
|
327
|
+
* than a status code would.
|
|
328
|
+
*/
|
|
329
|
+
if (request.method === "GET" && url.pathname === "/api/branches") {
|
|
330
|
+
const scope = url.searchParams.get("scope");
|
|
331
|
+
if (!scope) {
|
|
332
|
+
send(response, 400, { error: "scope is required" });
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
send(response, 200, await branchList(scope));
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
/*
|
|
339
|
+
* `GET /api/models` — what each Backend Adapter can reach, for the Providers section to offer.
|
|
340
|
+
*
|
|
341
|
+
* Its own endpoint rather than more of `/api/config`, and a query rather than state, for the
|
|
342
|
+
* reason `/api/directories` and `/api/branches` are: a client polling the config document every
|
|
343
|
+
* few seconds must not be made to spawn a process per backend to get it.
|
|
344
|
+
*
|
|
345
|
+
* A backend that cannot answer is a **200 carrying a `problem`**, never a 404 — the choice
|
|
346
|
+
* `/api/branches` makes for a Scope that is not a repository, and for the same reason: naming the
|
|
347
|
+
* state tells the reader more than a status code, and here it is what turns a picker into a text
|
|
348
|
+
* field rather than into an empty list nobody can explain.
|
|
349
|
+
*
|
|
350
|
+
* Unlike its two neighbours, the answer is cached — see `SessionHost.models` for why, and
|
|
351
|
+
* `?refresh=1` for the way out.
|
|
352
|
+
*/
|
|
353
|
+
if (request.method === "GET" && url.pathname === "/api/models") {
|
|
354
|
+
const scope = options.config?.projectRoot() ?? options.scope ?? process.cwd();
|
|
355
|
+
send(response, 200, await options.host.models(scope, url.searchParams.get("refresh") === "1"));
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
/*
|
|
359
|
+
* `GET /api/skills?scope=…&backend=…` — the Skills a Scope offers, before it has an Agent Session.
|
|
360
|
+
*
|
|
361
|
+
* The `list_skills` Command already answers this for a session that exists, and cannot answer it
|
|
362
|
+
* for one that does not: it reads a live Backend Session. The New Agent Session view needs the
|
|
363
|
+
* menu before there is anything to read, so this opens a throwaway session the way
|
|
364
|
+
* `/api/models` does (ADR 0020) and disposes of it.
|
|
365
|
+
*
|
|
366
|
+
* **Both parameters are required.** `scope` because the view asks about a Scope it has picked,
|
|
367
|
+
* which is why `/api/models`' shortcut of using the Project Root would be wrong here — this is the
|
|
368
|
+
* `/api/branches` shape, not the `/api/models` one. `backend` because the two adapters genuinely
|
|
369
|
+
* disagree about what a Skill is (pi folds its PromptTemplates in), so defaulting to the first
|
|
370
|
+
* registered one would quietly answer with a different adapter's menu than the session is about to
|
|
371
|
+
* be created on. The client already knows the names: `/api/config` hands it the same list it picks
|
|
372
|
+
* the backend from.
|
|
373
|
+
*
|
|
374
|
+
* A backend that cannot answer is a **200 carrying a `problem`**, the choice both neighbours make.
|
|
375
|
+
* It matters more here than for either of them: `CommandRefused` → 409 is wired only for
|
|
376
|
+
* `POST /api/command`, so anything thrown in this handler would reach the reader as a bare 500.
|
|
377
|
+
* `SessionHost.skillsFor` therefore never throws, including for a backend name it does not know.
|
|
378
|
+
*
|
|
379
|
+
* No `?refresh=1`, because nothing is cached to refresh — see `SessionHost.skillsFor`.
|
|
380
|
+
*/
|
|
381
|
+
if (request.method === "GET" && url.pathname === "/api/skills") {
|
|
382
|
+
const scope = url.searchParams.get("scope");
|
|
383
|
+
const backend = url.searchParams.get("backend");
|
|
384
|
+
if (!scope || !backend) {
|
|
385
|
+
send(response, 400, { error: "scope and backend are required" });
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
send(response, 200, await options.host.skillsFor(scope, backend));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (options.shells && url.pathname === "/api/shells") {
|
|
392
|
+
await handleShellCollection(request, response, url, options.host, options.shells);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
const shellMatch = /^\/api\/shells\/([^/]+)$/.exec(url.pathname);
|
|
396
|
+
const shellId = shellMatch?.[1];
|
|
397
|
+
if (options.shells && request.method === "DELETE" && shellId) {
|
|
398
|
+
if (!options.shells.get(shellId)) {
|
|
399
|
+
send(response, 404, { error: `No Shell ${shellId}` });
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
options.shells.kill(shellId);
|
|
403
|
+
send(response, 200, { ok: true });
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
// Assets are served from the embedded manifest rather than disk, so a single-executable build has
|
|
407
|
+
// nothing to find at runtime. The manifest is keyed by the path Vite emitted each file at, so `/`
|
|
408
|
+
// has to be spelled out as the Entry Document.
|
|
409
|
+
const asset = options.assets[url.pathname === "/" ? "/index.html" : url.pathname];
|
|
410
|
+
if (request.method === "GET" && asset) {
|
|
411
|
+
sendAsset(response, asset);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
const eventsMatch = /^\/api\/sessions\/([^/]+)\/events$/.exec(url.pathname);
|
|
415
|
+
const sessionId = eventsMatch?.[1];
|
|
416
|
+
if (request.method === "GET" && sessionId) {
|
|
417
|
+
streamEvents(response, options.host, sessionId, Number(url.searchParams.get("since") ?? 0), authentication.kind === "browser" ? options.oidc : undefined, authentication.kind === "browser" ? authentication.sessionId : undefined);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* `GET /api/sessions/:id/attachments/:attachmentId` — the bytes behind an id in a transcript.
|
|
422
|
+
*
|
|
423
|
+
* Under the Agent Session rather than in a store of its own, because that is where the bytes live
|
|
424
|
+
* and an Attachment has no life apart from the transcript naming it. Behind the same bearer check
|
|
425
|
+
* as everything else, which is what lets the web client render one with a plain `<img src>`: the
|
|
426
|
+
* token is in an HttpOnly cookie (ADR 0004) and the client is same-origin, so the browser presents
|
|
427
|
+
* it without the page having to.
|
|
428
|
+
*/
|
|
429
|
+
const attachmentMatch = /^\/api\/sessions\/([^/]+)\/attachments\/([^/]+)$/.exec(url.pathname);
|
|
430
|
+
if (request.method === "GET" && attachmentMatch) {
|
|
431
|
+
sendAttachment(response, options.store, attachmentMatch[1] ?? "", attachmentMatch[2] ?? "");
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
if (request.method === "POST" && url.pathname === "/api/command") {
|
|
435
|
+
const command = JSON.parse(await readBody(request));
|
|
436
|
+
try {
|
|
437
|
+
send(response, 200, { result: (await options.host.execute(command)) ?? null });
|
|
438
|
+
}
|
|
439
|
+
catch (error) {
|
|
440
|
+
// A refusal is the caller asking for something this Agent Session cannot do in the state it
|
|
441
|
+
// is in — a turn in flight, a checkout git itself declined — and its message is the whole of
|
|
442
|
+
// what is worth showing. Anything else is ours, and `serve`'s catch turns it into a 500. The
|
|
443
|
+
// same asymmetry as `ConfigError` → 400, at the status `/api/shells` already answers when an
|
|
444
|
+
// Agent Session's state forbids the request.
|
|
445
|
+
if (!(error instanceof CommandRefused))
|
|
446
|
+
throw error;
|
|
447
|
+
send(response, 409, { error: error.message });
|
|
448
|
+
}
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
// An Agent Session is deep-linkable, so an unknown path is the client router's business — except
|
|
452
|
+
// under /api, where a 404 must stay JSON, and under /assets, where a missing hashed file is a bug
|
|
453
|
+
// and must not be answered with HTML the browser will try to execute.
|
|
454
|
+
const entryDocument = options.assets["/index.html"];
|
|
455
|
+
if (request.method === "GET" &&
|
|
456
|
+
entryDocument &&
|
|
457
|
+
!url.pathname.startsWith("/api/") &&
|
|
458
|
+
!url.pathname.startsWith("/assets/")) {
|
|
459
|
+
sendAsset(response, entryDocument);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
send(response, 404, { error: "Not found" });
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* The opted-in Projects, and the candidates not yet among them.
|
|
466
|
+
*
|
|
467
|
+
* Candidates are the discovered repositories minus whatever is already opted in, compared on the
|
|
468
|
+
* resolved absolute path so that `work/api` and `/home/me/workspace/work/api` are recognised as the
|
|
469
|
+
* same directory — which they are, and a candidate list that offered a Project you already have
|
|
470
|
+
* would be a list that never emptied.
|
|
471
|
+
*/
|
|
472
|
+
/**
|
|
473
|
+
* What `/api/branches` answers.
|
|
474
|
+
*
|
|
475
|
+
* The `isRepository` gate comes first so a Scope that is not a repository costs one `statSync` and
|
|
476
|
+
* spawns nothing — which is most of the calls, since the New Agent Session view asks on every
|
|
477
|
+
* settled keystroke of a free-text Scope field.
|
|
478
|
+
*
|
|
479
|
+
* A repository git cannot list is reported as a repository with no branches rather than as no
|
|
480
|
+
* repository, because those are different things to a reader: the first is a state to explain, and
|
|
481
|
+
* lying about the second would hide a broken checkout behind a missing control.
|
|
482
|
+
*/
|
|
483
|
+
async function branchList(scope) {
|
|
484
|
+
if (!isRepository(scope) || !(await gitAvailable())) {
|
|
485
|
+
return { scope, repository: false, branches: [] };
|
|
486
|
+
}
|
|
487
|
+
const listed = await localBranches(scope);
|
|
488
|
+
const found = await head(scope);
|
|
489
|
+
const branches = listed.ok ? listed.value : [];
|
|
490
|
+
return {
|
|
491
|
+
scope,
|
|
492
|
+
repository: true,
|
|
493
|
+
branches: branches.slice(0, MAX_BRANCHES),
|
|
494
|
+
...(branches.length > MAX_BRANCHES ? { truncated: true } : {}),
|
|
495
|
+
...(found.ok ? { head: found.value } : {}),
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function projectLists(config) {
|
|
499
|
+
if (!config)
|
|
500
|
+
return { projectList: [], projectCandidates: [] };
|
|
501
|
+
const projectList = includedProjects(config.rawProjectRoot(), config.projectInclude());
|
|
502
|
+
const included = new Set(projectList.map((project) => project.path));
|
|
503
|
+
return {
|
|
504
|
+
projectList,
|
|
505
|
+
projectCandidates: discoverProjects(config.projectRoot()).filter((candidate) => !included.has(candidate.path)),
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* `PUT /api/config` — merge a patch into the Settings.
|
|
510
|
+
*
|
|
511
|
+
* Refuses rather than warns, which is the opposite of how the same values are read off disk. A file
|
|
512
|
+
* is parsed leniently so a typo cannot stop the daemon starting; a person watching a form has to be
|
|
513
|
+
* told their value was rejected, because a settings page that reports success and keeps the old
|
|
514
|
+
* value is worse than one that has no save button at all.
|
|
515
|
+
*
|
|
516
|
+
* Retention is not swept here. The next hourly sweep applies it, which is what the UI says, so
|
|
517
|
+
* saving a shorter window is never itself the thing that deletes a Presentation Transcript.
|
|
518
|
+
*/
|
|
519
|
+
async function handleSettingsUpdate(request, response, config) {
|
|
520
|
+
if (!config) {
|
|
521
|
+
send(response, 404, { error: "This Session Host serves no Settings" });
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
let patch;
|
|
525
|
+
try {
|
|
526
|
+
patch = JSON.parse(await readBody(request));
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
send(response, 400, { error: "expected a JSON object" });
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
try {
|
|
533
|
+
send(response, 200, config.update(patch));
|
|
534
|
+
}
|
|
535
|
+
catch (error) {
|
|
536
|
+
// A rejected value is the client's fault and its message names the field, so it is safe and
|
|
537
|
+
// useful to pass back. Anything else is ours, and `handle`'s caller turns it into a 500.
|
|
538
|
+
if (!(error instanceof ConfigError))
|
|
539
|
+
throw error;
|
|
540
|
+
send(response, 400, { error: error.message });
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* `/api/shells` — list the Shells beside one Agent Session, or open another.
|
|
545
|
+
*
|
|
546
|
+
* Addressed as a collection rather than as `/api/sessions/:id/shell`, because an Agent Session may
|
|
547
|
+
* own several Shells and a singular path would have to be broken to admit the second one.
|
|
548
|
+
*/
|
|
549
|
+
async function handleShellCollection(request, response, url, host, shells) {
|
|
550
|
+
if (request.method === "GET") {
|
|
551
|
+
const sessionId = url.searchParams.get("sessionId");
|
|
552
|
+
if (!sessionId) {
|
|
553
|
+
send(response, 400, { error: "sessionId is required" });
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
send(response, 200, shells.listFor(sessionId));
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
if (request.method !== "POST") {
|
|
560
|
+
send(response, 405, { error: "Method not allowed" });
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
const body = JSON.parse(await readBody(request));
|
|
564
|
+
if (!body.sessionId) {
|
|
565
|
+
send(response, 400, { error: "sessionId is required" });
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
// The Scope is read from the Agent Session rather than taken from the request: a client that
|
|
569
|
+
// could name its own working directory would make the Agent Session's Scope decorative.
|
|
570
|
+
const summary = host.list().find((candidate) => candidate.id === body.sessionId);
|
|
571
|
+
if (!summary) {
|
|
572
|
+
send(response, 404, { error: `No Agent Session ${body.sessionId}` });
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
if (summary.status === "settled" || summary.status === "ended") {
|
|
576
|
+
// Refused rather than opened-and-immediately-killed: the same rule that exits a Shell on Settle
|
|
577
|
+
// has to also stop one being opened afterwards, or the two disagree.
|
|
578
|
+
send(response, 409, { error: `Agent Session ${summary.id} is ${summary.status}` });
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
try {
|
|
582
|
+
send(response, 200, await shells.create({
|
|
583
|
+
sessionId: summary.id,
|
|
584
|
+
cwd: summary.scope,
|
|
585
|
+
...(body.cols === undefined ? {} : { cols: body.cols }),
|
|
586
|
+
...(body.rows === undefined ? {} : { rows: body.rows }),
|
|
587
|
+
}));
|
|
588
|
+
}
|
|
589
|
+
catch (error) {
|
|
590
|
+
send(response, 503, { error: error instanceof Error ? error.message : String(error) });
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* The Shell socket: `GET /api/shells/:id/stream`, upgraded.
|
|
595
|
+
*
|
|
596
|
+
* Binary frames are bytes in both directions — keystrokes up, output down — and text frames carry
|
|
597
|
+
* the out-of-band messages. Splitting them by frame type rather than by envelope means the hot path
|
|
598
|
+
* does no parsing and no base64.
|
|
599
|
+
*/
|
|
600
|
+
async function handleUpgrade(request, socket, head, options, shells) {
|
|
601
|
+
if (!originAllowed(request, options.oidc?.config.publicAppUrl))
|
|
602
|
+
return refuse(socket, 403);
|
|
603
|
+
const authentication = await authenticateRequest(request, options);
|
|
604
|
+
if (!authentication)
|
|
605
|
+
return refuse(socket, 401);
|
|
606
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
607
|
+
const shellId = /^\/api\/shells\/([^/]+)\/stream$/.exec(url.pathname)?.[1];
|
|
608
|
+
if (!shellId)
|
|
609
|
+
return refuse(socket, 404);
|
|
610
|
+
const summary = shells.get(shellId);
|
|
611
|
+
if (!summary)
|
|
612
|
+
return refuse(socket, 404);
|
|
613
|
+
// Imported here rather than at module scope so that `ws` is only loaded by a host that was given
|
|
614
|
+
// a ShellRegistry, and so the module graph of a Shell-less deployment stays as it was.
|
|
615
|
+
const { WebSocketServer } = await import("ws");
|
|
616
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
617
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
618
|
+
const detachAuth = authentication.kind === "browser"
|
|
619
|
+
? options.oidc?.registerConnection(authentication.sessionId, () => ws.close(4001, "Authentication ended"))
|
|
620
|
+
: undefined;
|
|
621
|
+
if (ws.readyState !== ws.OPEN) {
|
|
622
|
+
detachAuth?.();
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
const tell = (frame) => ws.send(JSON.stringify(frame));
|
|
626
|
+
tell({ type: "ready", shell: summary });
|
|
627
|
+
const detach = shells.attach(shellId, {
|
|
628
|
+
output: (chunk) => ws.send(chunk, { binary: true }),
|
|
629
|
+
exit: (code, signal) => {
|
|
630
|
+
tell({ type: "exit", code, signal });
|
|
631
|
+
ws.close();
|
|
632
|
+
},
|
|
633
|
+
});
|
|
634
|
+
ws.on("message", (data, isBinary) => {
|
|
635
|
+
if (isBinary) {
|
|
636
|
+
shells.write(shellId, data);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
// A malformed control frame is dropped rather than allowed to tear down a live Shell.
|
|
640
|
+
let frame;
|
|
641
|
+
try {
|
|
642
|
+
frame = JSON.parse(data.toString("utf8"));
|
|
643
|
+
}
|
|
644
|
+
catch {
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (frame.type === "resize")
|
|
648
|
+
shells.resize(shellId, frame.cols, frame.rows);
|
|
649
|
+
});
|
|
650
|
+
// Detach only. Closing the pane, closing the tab and losing the network all arrive here
|
|
651
|
+
// identically, and none of them is a reason to kill a Shell someone left `npm run dev` in.
|
|
652
|
+
const detachAll = () => {
|
|
653
|
+
detach();
|
|
654
|
+
detachAuth?.();
|
|
655
|
+
};
|
|
656
|
+
ws.on("close", detachAll);
|
|
657
|
+
ws.on("error", detachAll);
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
/** An upgrade cannot be answered with a JSON body, so a refusal is a bare status line. */
|
|
661
|
+
function refuse(socket, status) {
|
|
662
|
+
const text = { 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 500: "Internal Server Error" }[status] ??
|
|
663
|
+
"Error";
|
|
664
|
+
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\n\r\n`);
|
|
665
|
+
socket.destroy();
|
|
666
|
+
}
|
|
667
|
+
function sendAsset(response, asset) {
|
|
668
|
+
const body = Buffer.from(asset.body, asset.encoding);
|
|
669
|
+
response.writeHead(200, {
|
|
670
|
+
"content-type": asset.type,
|
|
671
|
+
"content-length": body.byteLength,
|
|
672
|
+
// Caching an immutable asset forever is safe for a sharper reason than usual: its URL carries
|
|
673
|
+
// the bundler's content hash, so different content is a different URL by construction and there
|
|
674
|
+
// is no revalidation path to get wrong. The corollary is that no-store on the shell is doing
|
|
675
|
+
// real work — a cached shell would pin its reader to an asset hash that no longer exists.
|
|
676
|
+
"cache-control": asset.immutable ? "public, max-age=31536000, immutable" : "no-store",
|
|
677
|
+
});
|
|
678
|
+
response.end(body);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* One Attachment's bytes.
|
|
682
|
+
*
|
|
683
|
+
* `mediaTypeOf` is the only check on the id, and that is deliberate: it accepts a uuid and one of
|
|
684
|
+
* four extensions and nothing else, so it is simultaneously the content-type lookup and the reason
|
|
685
|
+
* `../../token` cannot reach `readAttachment`. A second traversal guard would be a second rule able
|
|
686
|
+
* to drift from this one.
|
|
687
|
+
*
|
|
688
|
+
* Cached forever, on the same reasoning as a hashed asset: the bytes at an id never change, because
|
|
689
|
+
* an id is minted per write and a Presentation Transcript is never rewritten (ADR 0001).
|
|
690
|
+
*/
|
|
691
|
+
function sendAttachment(response, store, sessionId, attachmentId) {
|
|
692
|
+
const mediaType = mediaTypeOf(attachmentId);
|
|
693
|
+
const bytes = mediaType && store ? store.readAttachment(sessionId, attachmentId) : undefined;
|
|
694
|
+
if (!mediaType || !bytes) {
|
|
695
|
+
send(response, 404, { error: "Not found" });
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
response.writeHead(200, {
|
|
699
|
+
"content-type": mediaType,
|
|
700
|
+
"content-length": bytes.byteLength,
|
|
701
|
+
"cache-control": "private, max-age=31536000, immutable",
|
|
702
|
+
});
|
|
703
|
+
response.end(bytes);
|
|
704
|
+
}
|
|
705
|
+
function streamEvents(response, host, sessionId, since, oidc, browserSessionId) {
|
|
706
|
+
let log;
|
|
707
|
+
try {
|
|
708
|
+
log = host.logFor(sessionId);
|
|
709
|
+
}
|
|
710
|
+
catch (error) {
|
|
711
|
+
send(response, 404, { error: error instanceof Error ? error.message : String(error) });
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
response.writeHead(200, {
|
|
715
|
+
"content-type": "text/event-stream",
|
|
716
|
+
"cache-control": "no-cache",
|
|
717
|
+
connection: "keep-alive",
|
|
718
|
+
});
|
|
719
|
+
// writeHead only buffers; Node sends the headers with the first body write. A client resuming at
|
|
720
|
+
// `since: lastSeq` has nothing to replay, so without this its fetch() would not resolve until the
|
|
721
|
+
// Agent Session next said something — which for an idle one is never.
|
|
722
|
+
response.flushHeaders();
|
|
723
|
+
const write = (entry) => {
|
|
724
|
+
response.write(`id: ${entry.seq}\ndata: ${JSON.stringify(entry)}\n\n`);
|
|
725
|
+
};
|
|
726
|
+
for (const entry of log.since(since))
|
|
727
|
+
write(entry);
|
|
728
|
+
const unsubscribe = log.subscribe(write);
|
|
729
|
+
const detachAuth = oidc && browserSessionId
|
|
730
|
+
? oidc.registerConnection(browserSessionId, () => response.end())
|
|
731
|
+
: undefined;
|
|
732
|
+
response.on("close", () => {
|
|
733
|
+
unsubscribe();
|
|
734
|
+
detachAuth?.();
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
/** Bearer access is deliberately independent of OIDC so remote CLI/TUI clients keep working. */
|
|
738
|
+
async function authenticateRequest(request, options) {
|
|
739
|
+
if (tokenMatches(options.token, presentedBearer(request)))
|
|
740
|
+
return { kind: "bearer" };
|
|
741
|
+
if (options.oidc) {
|
|
742
|
+
const sessionId = await options.oidc.authenticate(request.headers.cookie);
|
|
743
|
+
return sessionId ? { kind: "browser", sessionId } : undefined;
|
|
744
|
+
}
|
|
745
|
+
return tokenMatches(options.token, presentedToken(request)) ? { kind: "browser", sessionId: "local" } : undefined;
|
|
746
|
+
}
|
|
747
|
+
function documentNavigation(request, pathname) {
|
|
748
|
+
if (request.method !== "GET" || pathname.startsWith("/api/") || pathname.startsWith("/assets/"))
|
|
749
|
+
return false;
|
|
750
|
+
const destination = request.headers["sec-fetch-dest"];
|
|
751
|
+
const accept = request.headers.accept;
|
|
752
|
+
return destination === "document" || accept?.includes("text/html") === true || pathname === "/";
|
|
753
|
+
}
|
|
754
|
+
function sendLoginRedirectPage(response) {
|
|
755
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><title>Signing in · Flow</title></head>
|
|
756
|
+
<body><script>location.replace("/oauth/login?return_to="+encodeURIComponent(location.pathname+location.search+location.hash))</script>
|
|
757
|
+
<noscript><a href="/oauth/login">Sign in</a></noscript></body></html>`;
|
|
758
|
+
response.writeHead(200, {
|
|
759
|
+
"content-type": "text/html; charset=utf-8",
|
|
760
|
+
"content-length": Buffer.byteLength(html),
|
|
761
|
+
"cache-control": "no-store",
|
|
762
|
+
"referrer-policy": "no-referrer",
|
|
763
|
+
"content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
764
|
+
});
|
|
765
|
+
response.end(html);
|
|
766
|
+
}
|
|
767
|
+
function unauthorized(response, login) {
|
|
768
|
+
const body = JSON.stringify({ error: "Unauthorized" });
|
|
769
|
+
response.writeHead(401, {
|
|
770
|
+
"content-type": "application/json",
|
|
771
|
+
"content-length": Buffer.byteLength(body),
|
|
772
|
+
"cache-control": "no-store",
|
|
773
|
+
...(login ? { "x-flow-login": login } : {}),
|
|
774
|
+
});
|
|
775
|
+
response.end(body);
|
|
776
|
+
}
|
|
777
|
+
/** A self-contained page: auth failures must not request protected CSS or leak callback parameters. */
|
|
778
|
+
function sendAuthPage(response, status, title, detail, action) {
|
|
779
|
+
const html = `<!doctype html>
|
|
780
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
781
|
+
<title>${title} · Flow</title><style>
|
|
782
|
+
:root{color-scheme:light dark;font-family:Inter,ui-sans-serif,system-ui,sans-serif;background:#f6f6f4;color:#181817}
|
|
783
|
+
*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;background:radial-gradient(circle at 50% 0,#fff 0,#f6f6f4 52%)}
|
|
784
|
+
main{width:min(100%,430px);border:1px solid #deded9;border-radius:18px;background:rgba(255,255,255,.9);padding:30px;box-shadow:0 18px 55px rgba(28,28,24,.08)}
|
|
785
|
+
h1{font-size:24px;line-height:1.2;margin:0 0 12px;letter-spacing:-.025em}p{font-size:14px;line-height:1.6;color:#65655e;margin:0 0 26px}
|
|
786
|
+
a{display:inline-flex;align-items:center;justify-content:center;width:100%;height:42px;border-radius:10px;background:#1d1d1b;color:#fff;text-decoration:none;font-size:14px;font-weight:600}a:focus-visible{outline:3px solid #8bb9f5;outline-offset:2px}
|
|
787
|
+
@media(prefers-color-scheme:dark){:root{background:#171716;color:#f5f5f2}body{background:radial-gradient(circle at 50% 0,#292927 0,#171716 55%)}main{background:rgba(31,31,29,.95);border-color:#3b3b37;box-shadow:0 18px 55px rgba(0,0,0,.3)}a{background:#f0f0ec;color:#1b1b19}p{color:#aaa9a1}}
|
|
788
|
+
</style></head><body><main><h1>${title}</h1><p>${detail}</p><a href="${action.href}">${action.label}</a></main></body></html>`;
|
|
789
|
+
response.writeHead(status, {
|
|
790
|
+
"content-type": "text/html; charset=utf-8",
|
|
791
|
+
"content-length": Buffer.byteLength(html),
|
|
792
|
+
"cache-control": "no-store",
|
|
793
|
+
"referrer-policy": "no-referrer",
|
|
794
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
795
|
+
});
|
|
796
|
+
response.end(html);
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Same-origin only. A request with no Origin header is a non-browser client (the TUI, curl), which
|
|
800
|
+
* a hostile page cannot forge on the user's behalf, so it is not what this check defends against.
|
|
801
|
+
*/
|
|
802
|
+
function originAllowed(request, publicAppUrl) {
|
|
803
|
+
const origin = request.headers.origin;
|
|
804
|
+
if (!origin)
|
|
805
|
+
return true;
|
|
806
|
+
try {
|
|
807
|
+
if (publicAppUrl)
|
|
808
|
+
return new URL(origin).origin === new URL(publicAppUrl).origin;
|
|
809
|
+
const { hostname, host } = new URL(origin);
|
|
810
|
+
return host === request.headers.host || hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]";
|
|
811
|
+
}
|
|
812
|
+
catch {
|
|
813
|
+
return false;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function presentedBearer(request) {
|
|
817
|
+
const header = request.headers.authorization;
|
|
818
|
+
return header?.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : undefined;
|
|
819
|
+
}
|
|
820
|
+
function presentedToken(request) {
|
|
821
|
+
const bearer = presentedBearer(request);
|
|
822
|
+
if (bearer)
|
|
823
|
+
return bearer;
|
|
824
|
+
const cookie = request.headers.cookie;
|
|
825
|
+
const match = cookie ? /(?:^|;\s*)flow=([^;]+)/.exec(cookie) : null;
|
|
826
|
+
return match?.[1];
|
|
827
|
+
}
|