Public: anyone can read this; the crew can change it.

SSH is a feature that is off unless switched on: no host key, no ssh clone line, no SSH keys page anywhere while it is off #13669

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/13640-ssh-is-a-feature-that-is-off-unless-swit → main 28 commits fork 1 thread · 1 unresolved

  • Merged. torque/13640-ssh-is-a-feature-that-is-off-unless-swit was merged into main as 7be3817.

Review

Sign in to review this change.
95 files changed +880 −141
docs/features/README.md +2
@@ -165,7 +165,9 @@ Read with the guide page [Tell the crew](../guide-tell-the-crew.md).
165165 - [The crew's runs on the desk](desk-runs.md)
166166 - [The crew's week](crew-week-card.md)
167167 - [The crew's week shows which pulls came back](crew-week-returned.md)
168 <!-- ssh -->
168169 - [The first ask by ssh makes an app](ssh-first-ask.md)
170 <!-- /ssh -->
169171 - [The governor's line](governor-line.md)
170172 - [The map, lightly](map.md)
171173 - [The pulls a crew team's review holds](team-waiting.md)
docs/features/absorb.md +47
@@ -132,3 +132,50 @@ Beside each app on Settings › Features, on its own page, and in the terminal's
132132 - **Last changed by**: the author and date of the latest commit on the default branch that touched `forge.json`. The author is the name the commit carries, not a verified identity: anyone who can push can write any name.
133133
134134 Nothing shows when there is nothing to say. The last change is read from git once per tip and kept.
135
136 <!-- ssh -->
137 ## SSH, the forge's own switch
138
139 Git over SSH and the forge's terminal are a feature an admin turns on. Off, no
140 page, API answer, MCP tool, terminal screen, doc page or llms.txt line says
141 ssh, a host key, an SSH key, or a `git@` / `ssh://` address, and the listener
142 does not start.
143
144 ### Turn it on
145
146 1. Sign in as an admin who is a person (not an agent) and open `/settings/features`.
147 2. Press Turn on on the SSH row. The same switch is the `features` MCP tool with
148 slug `ssh` (`absorb: true`, an admin-scope token, `dryRun: false`) and the last
149 row of Features in the terminal (`a`).
150 3. The change is kept in `forge_setting_change` with who made it. The
151 repository clone box gains an ssh line, and Settings gains Computer keys
152 (`/settings/keys`), where you add the public key of the computer you push from.
153
154 Switch it off the same way: the ssh words disappear again and the listener
155 stops taking connections.
156
157 If the listener could not start (the port is taken, or the forge has no port),
158 the answer says so after "SSH is on": the page flashes it, the MCP answer has
159 `warning` and `listening: false`, and the terminal toast says it.
160
161 ### What it needs
162
163 A port. The forge listens on `FORGE_SSH_PORT` (2222 unless set; `0`, or a forge
164 hosted as an app of another, means no port). Nothing outside the machine reaches
165 it unless the port is published. The boot works this out once and keeps it as
166 `sshReachable` on the app's config.
167
168 ### A forge that already had SSH
169
170 Before the switch, a forge with a port served ssh and wrote its host key to
171 `<data dir>/ssh/host_ed25519`. At boot, a forge with that key and no stored
172 setting starts with the switch on, so an update does not take ssh away. A fresh
173 forge has no key and starts off. Turning it off is remembered and not undone.
174
175 ### Where it lives
176
177 - `src/settings/ssh.ts`: the stored switch (`sshOn`) and the boot migration.
178 - `src/ssh/switch.ts`: how `main.ts` starts and stops the listener, and says if it is up.
179 - `src/actions/ssh_switch.ts`: the admin action behind the page, the MCP tool and the terminal.
180 - `src/ssh/command.ts`: every builder of ssh words answers undefined while off.
181 <!-- /ssh -->
docs/guide-agents.md +4 −1
@@ -22,7 +22,10 @@ forge pulls
2222 forge tell "words"
2323 ```
2424
25 `forge ui` opens a full-screen terminal. The forge may also offer an SSH terminal: its exact address is on the forge's own pages; use it as written.
25 `forge ui` opens a full-screen terminal.
26 <!-- ssh -->
27 The forge may also offer an SSH terminal: its exact address is on the forge's own pages; use it as written.
28 <!-- /ssh -->
2629
2730 ## What an agent should read first
2831
src/actions/ssh_switch.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * The SSH switch (`settings/ssh.ts`) as one row beside the absorbed features, for the page, the
3 * MCP `features` tool and the terminal alike. Reading it is for any admin; turning it is for an
4 * admin who is a person. Everyone else is told `not_found`.
5 */
6
7 import type { App } from "../app.ts";
8 import type { User } from "../core/users.ts";
9 import { err, ok, type Result } from "../kernel/result.ts";
10 import { SSH_GIVES, setSsh, sshOn } from "../settings/ssh.ts";
11 import { applySsh, sshListening } from "../ssh/switch.ts";
12
13 export interface SshRow {
14 readonly slug: "ssh";
15 readonly name: "SSH";
16 readonly on: boolean;
17 readonly gives: string;
18 /** Whether this forge has a terminal to give at all (worked out once at boot). */
19 readonly reachable: boolean;
20 /** Whether the listener is up now; undefined where nothing here starts one (a test, the CLI). */
21 readonly listening?: boolean;
22 }
23
24 /** What turning it did: the row, and when the switch is on but the listener is not, why. */
outdated

This re-derives the boot's port rules from process.env in a second place. Compute it once at boot and store it on app.config (finding 6).

25 export interface SshSwitched extends SshRow {
26 readonly warning?: string;
27 }
28
29 export function sshRow(app: App, actor: User | undefined): Result<SshRow, "not_found"> {
30 if (actor?.isAdmin !== true || actor.kind === "agent") return err("not_found");
31 const on = sshOn(app.db);
32 const listening = sshListening(app);
33 return ok({
34 slug: "ssh",
35 name: "SSH",
36 on,
37 gives: SSH_GIVES,
38 reachable: app.config.sshReachable === true,
39 ...(listening === undefined ? {} : { listening }),
40 });
41 }
42
43 /**
44 * Turn the switch on or off, and start or stop the listener to match; say when it did not start.
45 */
46 export async function switchSsh(app: App, actor: User | undefined, on: boolean): Promise<Result<SshSwitched, "not_found">> {
47 const seen = sshRow(app, actor);
48 if (!seen.ok) return seen;
49 setSsh(app.db, on, actor!.id);
50 const failed = await applySsh(app, on);
51 const listening = sshListening(app);
52 return ok({
53 ...seen.value,
54 on,
55 ...(listening === undefined ? {} : { listening }),
56 ...(on && failed !== undefined ? { warning: failed } : {}),
57 });
58 }
src/app.ts +6
@@ -193,6 +193,12 @@ export interface ForgeConfig {
193193 * child). Printed verbatim wherever the forge says how to connect.
194194 */
195195 appSsh?: string;
196 /**
197 * Whether this forge has a terminal to give at all: a port for its own listener
198 * (`FORGE_SSH_PORT` above 0) or a command its host gave it. Worked out once at boot;
199 * the SSH switch (`settings/ssh.ts`) reads it, and does not re-derive it.
200 */
201 sshReachable?: boolean;
196202 /**
197203 * The rolling intent doc a person's build note is copied into, once,
198204 * under "## Iterator notes" (`core/intent_notes.ts`). Unset copies none.
src/core/mcp_card.ts +12 −10
@@ -181,6 +181,8 @@ export function cardsLine(): string {
181181 * cards so neither can name a tool the other lacks.
182182 */
183183 let cardTools: readonly { name: string; description: string }[] = [];
184 /** The tools a card names: one that waits on the SSH switch only while it is on. */
185 const shownTools = (ssh: boolean): typeof cardTools => cardTools.filter((t) => t.name !== "ssh_keys" || ssh);
184186 export function setCardTools(tools: readonly { name: string; description: string; doc?: string }[]): void {
185187 const seen = new Set<string>();
186188 cardTools = tools
@@ -192,7 +194,7 @@ export function setCardTools(tools: readonly { name: string; description: string
192194 }
193195
194196 /** What the cards name as tools, as one string: a cached body is made again when it changes. */
195 export const toolsKey = (): string => cardTools.map((t) => t.name).join(",");
197 export const toolsKey = (ssh: boolean): string => shownTools(ssh).map((t) => t.name).join(",");
196198
197199 /**
198200 * The agent card (A2A, protocol 0.3.0, the stable subset: name, description,
@@ -200,7 +202,7 @@ export const toolsKey = (): string => cardTools.map((t) => t.name).join(",");
200202 * sign-in is named by `securitySchemes`). With a token, one skill per MCP tool,
201203 * from the same list `mcpCard` names under `tools`; without, see `agentSkills`.
202204 */
203 export function agentCard(origin: string, now: Running = running(), signedIn = true) {
205 export function agentCard(origin: string, ssh: boolean, now: Running = running(), signedIn = true) {
204206 const { url, oauth } = mcpPointers(origin);
205207 return {
206208 protocolVersion: "0.3.0",
@@ -219,7 +221,7 @@ export function agentCard(origin: string, now: Running = running(), signedIn = t
219221 // Which list `skills` is: "full" is every tool;
220222 // "open" is the token-free ones and a count of the rest.
221223 skillsScope: signedIn ? "full" : "open",
222 skills: agentSkills(origin, signedIn),
224 skills: agentSkills(origin, signedIn, ssh),
223225 };
224226 }
225227
@@ -227,22 +229,22 @@ export function agentCard(origin: string, now: Running = running(), signedIn = t
227229 * How many tools an account opens beyond the token-free ones:
228230 * the number /llms.txt prints for a stranger.
229231 */
230 export const moreAfterSignIn = (): number => cardTools.filter((t) => !TOKEN_FREE_TOOLS.includes(t.name)).length;
232 export const moreAfterSignIn = (ssh: boolean): number => shownTools(ssh).filter((t) => !TOKEN_FREE_TOOLS.includes(t.name)).length;
231233
232234 /**
233235 * A reader with a token gets one skill per tool; a stranger gets the
234236 * token-free tools and one entry counting the rest (the card is the first
235237 * thing an agent reads, so it stays small).
236238 */
237 function agentSkills(origin: string, signedIn: boolean) {
239 function agentSkills(origin: string, signedIn: boolean, ssh: boolean) {
238240 const skill = (t: { name: string; description: string }) => ({ id: t.name, name: t.name, description: t.description, tags: ["mcp"] });
239 if (signedIn) return cardTools.map(skill);
241 if (signedIn) return shownTools(ssh).map(skill);
240242 return [
241 ...cardTools.filter((t) => TOKEN_FREE_TOOLS.includes(t.name)).map(skill),
243 ...shownTools(ssh).filter((t) => TOKEN_FREE_TOOLS.includes(t.name)).map(skill),
242244 {
243245 id: "more-after-sign-in",
244246 name: "more-after-sign-in",
245 description: `${moreAfterSignIn()} more tools with an account: call tools/list on ${origin}/mcp once signed in.`,
247 description: `${moreAfterSignIn(ssh)} more tools with an account: call tools/list on ${origin}/mcp once signed in.`,
246248 tags: ["mcp", "sign-in"],
247249 },
248250 ];
@@ -253,7 +255,7 @@ function agentSkills(origin: string, signedIn: boolean) {
253255 * true is named: who answers, where, over what transport, how to sign in,
254256 * and the one tool that needs no token.
255257 */
256 export function mcpCard(origin: string, repo: string | undefined, now: Running = running()) {
258 export function mcpCard(origin: string, repo: string | undefined, ssh: boolean, now: Running = running()) {
257259 const { url, oauth } = mcpPointers(origin);
258260 return {
259261 name: "forge",
@@ -265,7 +267,7 @@ export function mcpCard(origin: string, repo: string | undefined, now: Running =
265267 documentation: `${origin}${DISCOVERY.docs}`,
266268 openapi: `${origin}${DISCOVERY.openapi}`,
267269 tokenFreeTools: [...TOKEN_FREE_TOOLS],
268 tools: cardTools.map((t) => t.name),
270 tools: shownTools(ssh).map((t) => t.name),
269271 cards: cardList(),
270272 plugins: offeredPlugins(repo).map((p) => ({
271273 harness: p.harness,
src/engine/crossing.ts +1
@@ -43,6 +43,7 @@ export const CROSSES = [
4343 "turnstileSecret",
4444 "turnstileSiteKey",
4545 "appSsh",
46 "sshReachable",
4647 "notesIntent",
4748 "forgeRepo",
4849 "parentUrl",
src/http/api/user.ts +21 −6
@@ -5,6 +5,7 @@
55 * is assigned to the caller. Moved out of `api.ts` (#7444), unchanged.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import { contribute, forkOrigin } from "../../actions/contribute.ts";
910 import { CAPPED_WORDS } from "../../actions/mail.ts";
1011 import { ORIGIN_UNREACHABLE } from "../../actions/origin_app_words.ts";
@@ -38,7 +39,13 @@ import { noMailBlocked } from "../../actions/blocked_words.ts";
3839 import { blockedFields } from "../../kernel/blocked.ts";
3940 import { gatedHost } from "../../origins/discover.ts";
4041
41 /** 422 `unreachable`, with what stands in the way as `says` and the call that asks the host as `ask`. */
42 /** The keys routes while the switch is off: a feature that is off, said as such. */
43 const keysOff = (): Response => apiError("feature_off", 404, "computer keys are a feature that is off on this forge");
44
45 /**
46 * 422 `unreachable`, with what stands in the way as `says` and the call that asks the host as
47 * `ask`.
48 */
4249 async function gateRefusal(ctx: Ctx, host: string): Promise<Response> {
4350 const blocked = gateBlocked(host, await hostOf(ctx.app));
4451 return json({ error: "unreachable", message: blocked.says, ...blockedFields(blocked) }, 422);
@@ -101,7 +108,9 @@ function sourceFailure(error: SourceError): Response {
101108 }
102109 }
103110
104 /** No mailer is set: an operator must configure one, no clock ends it; ask again in five minutes. */
111 /**
112 * No mailer is set: an operator must configure one, no clock ends it; ask again in five minutes.
113 */
105114 const NO_MAIL_RETRY = 300;
106115
107116 export function userRoutes(router: Router<Handler>): void {
@@ -123,7 +132,8 @@ export function userRoutes(router: Router<Handler>): void {
123132 if (sent.error === "too_soon")
124133 return tryAgain("too_soon", 429, VERIFY_WORDS.too_soon, RESEND_AFTER_MS / 1000);
125134 if (sent.error === "no_mail") {
126 // The same refusal, with what stands in the way and the next step as data for an agent (`kernel/blocked.ts`).
135 // The same refusal, with what stands in the way and the next step as data for an agent
136 // (`kernel/blocked.ts`).
127137 const refused = tryAgain("no_mail", 503, VERIFY_WORDS.no_mail, NO_MAIL_RETRY);
128138 const said = (await refused.json()) as Record<string, unknown>;
129139 return json({ ...said, ...blockedFields(noMailBlocked(ctx.app, ctx.auth.user!)) }, 503, Object.fromEntries(refused.headers));
@@ -195,6 +205,7 @@ export function userRoutes(router: Router<Handler>): void {
195205 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
196206 const user = ctx.auth.user;
197207 if (!user) return unauthorized();
208 if (!sshOn(ctx.app.db)) return keysOff();
198209 const window = keyedWindow(ctx);
199210 if (window instanceof Response) return window;
200211 const keys = timePhase(ctx.request, "keys", () => listKeys(ctx.app.db, user.id));
@@ -211,6 +222,7 @@ export function userRoutes(router: Router<Handler>): void {
211222 router.add("POST", "/api/v1/user/keys", async (ctx) => {
212223 const denied = requireScope(ctx, "rw");
213224 if (denied) return denied;
225 if (!sshOn(ctx.app.db)) return keysOff();
214226 const input = await body(ctx.request);
215227 const added = addSshKey(ctx.app, ctx.auth.user, {
216228 name: str(input.name),
@@ -222,6 +234,7 @@ export function userRoutes(router: Router<Handler>): void {
222234 router.add("DELETE", "/api/v1/user/keys/:id", (ctx) => {
223235 const denied = requireScope(ctx, "rw");
224236 if (denied) return denied;
237 if (!sshOn(ctx.app.db)) return keysOff();
225238 const removed = deleteSshKey(ctx.app, ctx.auth.user, ctx.params.id!);
226239 if (!removed.ok) return respondAccess(removed.error, 422);
227240 return new Response(null, { status: 204 });
@@ -290,7 +303,8 @@ export function userRoutes(router: Router<Handler>): void {
290303 const refused = connectRefusal(connected.error);
291304 if (refused.code === "rate_limited")
292305 return tryAgain("rate_limited", 429, refused.message ?? connectMessage(refused.code), CONNECT_LIMITS.windowMs! / 1000);
293 // The host's gate refused the name: the answer carries the call that asks the host (`kernel/blocked.ts`).
306 // The host's gate refused the name: the answer carries the call that asks the host
307 // (`kernel/blocked.ts`).
294308 const gate = gatedHost(connected.error);
295309 if (gate !== undefined) return gateRefusal(ctx, gate);
296310 return apiError(
@@ -760,8 +774,9 @@ export function userRoutes(router: Router<Handler>): void {
760774 name: repo.name,
761775 defaultBranch: repo.defaultBranch,
762776 cloneUrl: `${ctx.url.origin}/${path}.git`,
763 sshUrl:
764 sshCloneUrl(ctx.app, repo.ownerName, repo.name) ?? null,
777 ...(sshOn(ctx.app.db)
778 ? { sshUrl: sshCloneUrl(ctx.app, repo.ownerName, repo.name) ?? null }
779 : {}),
765780 origin: originFacts(repo),
766781 pinnedAt: pin.createdAt,
767782 },
src/http/mcp/shared.ts +4
@@ -1,3 +1,4 @@
1 import { sshOn } from "../../settings/ssh.ts";
12 import { SIGN_IN_AS_ADMIN } from "../../core/roles.ts";
23 import { blockedFields, blockedText, type Blocked } from "../../kernel/blocked.ts";
34 import { mayView } from "../../core/sealed.ts";
@@ -81,6 +82,8 @@ export interface Tool {
8182 readonly writes: boolean;
8283 /** Listed, and callable, for a forge admin only. */
8384 readonly adminOnly?: true;
85 /** Listed, and callable, only while this switch is on (`settings/ssh.ts`). */
86 readonly needsSwitch?: "ssh";
8487 /** Listed, and callable, only with a token of this scope. */
8588 readonly needsAdminScope?: true;
8689 /** With this argument (or all of these) absent the tool only reads, whatever the token. */
@@ -103,6 +106,7 @@ export const notAdminTool = (name: string, why: string = SIGN_IN_AS_ADMIN): stri
103106 */
104107 export const visible = (tool: Tool, ctx: Ctx, user: User): boolean =>
105108 (tool.adminOnly !== true || user.isAdmin) &&
109 (tool.needsSwitch === undefined || sshOn(ctx.app.db)) &&
106110 (tool.needsAdminScope !== true || scopeAllows(ctx.auth.scope ?? "ro", "admin"));
107111
108112 /** Whether this call only plans or reads, so a read-only token may make it. */
src/http/mcp/tools/features.ts +15 −2
@@ -1,11 +1,12 @@
11 import { absorbApp, changeFeatureSettings, feedOf, getFeature, listFeatures, unabsorbApp } from "../../../actions/features.ts";
2 import { sshRow, switchSsh } from "../../../actions/ssh_switch.ts";
23 import { callFeatureTool } from "../../../actions/feature_tools.ts";
34 import { scopeAllows } from "../../../core/tokens.ts";
45 import { good, bad, type Tool } from "../shared.ts";
56
67 export const tool: Tool = {
78 name: "features",
8 doc: "`{ slug?, feed?, absorb?, settings?, tool?, args?, dryRun? }`: apps absorbed as the forge's own features. With nothing, every app whose forge.json declares a `feature`, absorbed or not (forge admin); with `slug`, that one and its typed settings (its readers), or with `feed: true` its feed items; `absorb: true|false` absorbs or un-absorbs it, `settings: { name: value }` changes an absorbed one's settings (each checked against its declaration, the app restarts with them as `FORGE_SETTING_*`); `tool` calls one of the absorbed app's declared tools (listed as `tools` with `slug`) with `args`: a read tool answers at once, one that writes is for a repo writer and planned first; absorbing and settings changes are planned first (`dryRun` is true unless `false`) and need an admin-scope token",
9 doc: "`{ slug?, feed?, absorb?, settings?, tool?, args?, dryRun? }`: apps absorbed as the forge's own features, and the forge's own switches, listed first and named by `slug` (`absorb: true|false` turns one on or off). With nothing, every app whose forge.json declares a `feature`, absorbed or not (forge admin); with `slug`, that one and its typed settings (its readers), or with `feed: true` its feed items; `absorb: true|false` absorbs or un-absorbs it, `settings: { name: value }` changes an absorbed one's settings (each checked against its declaration, the app restarts with them as `FORGE_SETTING_*`); `tool` calls one of the absorbed app's declared tools (listed as `tools` with `slug`) with `args`: a read tool answers at once, one that writes is for a repo writer and planned first; absorbing and settings changes are planned first (`dryRun` is true unless `false`) and need an admin-scope token",
910 description: "Apps absorbed as forge features: list, read, absorb or un-absorb, change typed settings.",
1011 inputSchema: {
1112 type: "object",
@@ -23,9 +24,21 @@ export const tool: Tool = {
2324 dryByDefault: true,
2425 async run(ctx, user, args) {
2526 const slug = typeof args["slug"] === "string" ? args["slug"] : undefined;
27 // The forge's own switch, SSH, is listed first and named by slug `ssh`: `absorb` is on or off.
2628 if (slug === undefined) {
2729 const listed = await listFeatures(ctx.app, user);
28 return listed.ok ? good({ items: listed.value }) : bad("not_found", "no such tool here");
30 const ssh = sshRow(ctx.app, user);
31 return listed.ok ? good({ items: ssh.ok ? [ssh.value, ...listed.value] : listed.value }) : bad("not_found", "no such tool here");
32 }
33 if (slug === "ssh") {
34 const ssh = sshRow(ctx.app, user);
35 if (!ssh.ok) return bad("not_found", "no such app");
36 const on = typeof args["absorb"] === "boolean" ? args["absorb"] : undefined;
37 if (on === undefined) return good(ssh.value);
38 if (args["dryRun"] !== false) return good({ says: `Would turn SSH ${on ? "on" : "off"}. Send dryRun: false to do it.` });
39 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "turning SSH on or off needs an admin-scope token");
40 const done = await switchSsh(ctx.app, user, on);
41 return done.ok ? good(done.value) : bad("not_found", "no such app");
2942 }
3043 const found = await getFeature(ctx.app, user, slug);
3144 if (!found.ok) return bad(found.error, found.error === "not_a_feature" ? "that app declares no feature" : "no such app");
src/http/mcp/tools/ssh_keys.ts +1
@@ -15,6 +15,7 @@ export const tool: Tool = {
1515 id: { type: "string" },
1616 },
1717 },
18 needsSwitch: "ssh",
1819 writes: true,
1920 readsWhen: (args) => (args["action"] ?? "list") === "list",
2021 run(ctx, user, args) {
src/main.ts +44 −25
@@ -124,6 +124,8 @@ import { sweepLeftoverProbes } from "./release/leftover_sweep.ts";
124124 import { forgesMemory, memoryOverLine } from "./spawn/memory_fit.ts";
125125 import { keepFloor } from "./apps/cgroup.ts";
126126 import { limitValue } from "./settings/limits.ts";
127 import { migrateSsh, sshOn } from "./settings/ssh.ts";
128 import { followSsh } from "./ssh/switch.ts";
127129 import { capacityDefault, egressEnvIgnored } from "./core/capacity.ts";
128130 import { bootCounts, recordBoot, recordCleanExit } from "./kernel/boots.ts";
129131 import { census, censusWords, processRows } from "./kernel/census.ts";
@@ -212,8 +214,8 @@ const hosted = hostedAt !== "";
212214 // A full disk is survivable (#12144): boot, deploy and timer paths included.
213215 survivesFull(dataDirOf(process.env));
214216
215 // SSH is on by default: the terminal UI is a first-class surface, not an
216 // add-on. `FORGE_SSH_PORT=0` turns the listener off entirely.
217 // SSH is off until the admin's switch says on (settings/ssh.ts); FORGE_SSH_PORT is where it
218 // listens, and `0` means there is no port to give.
217219 // A read-only standby (FORGE_READ_ONLY=1, #9657) serves reads from a restored
218220 // directory: no terminal, no apps, no crew, no jobs.
219221 const readOnly = readOnlyFrom(process.env);
@@ -313,6 +315,8 @@ const app = createApp({
313315 ...(hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== ""
314316 ? { appSsh: (process.env.FORGE_APP_SSH ?? "").trim() }
315317 : {}),
318 // Whether there is a terminal to switch on: a port to listen on, or the host's command.
319 sshReachable: sshPort > 0 || (hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== ""),
316320 // The repository holding this forge's own code: a landing there is
317321 // checked out under releases/ and preflighted (#1662).
318322 ...releaseEnv(process.env),
@@ -465,22 +469,44 @@ keepForgePages(app);
465469 startKeeping(app.db);
466470 // The terminal is optional: its modules load only when a port is set, so a forge with
467471 // FORGE_SSH_PORT=0 never loads them (test/boot-lazy.test.ts).
468 const sshStarted =
469 sshPort > 0
470 ? await import("./tui/ssh.ts")
471 .then((m) => m.startForgeSsh(app, { port: sshPort }))
472 .catch((error) => {
473 app.log.warn("ssh is off: the terminal failed to load", { error: String(error) });
474 return undefined;
475 })
476 : undefined;
477 if (sshStarted && !sshStarted.ok)
478 app.log.warn("ssh is off: the terminal could not start", {
479 port: sshPort,
480 reason: sshStarted.error.message,
481 code: (sshStarted.error as { code?: string }).code,
482 });
483 const ssh = sshStarted?.ok ? sshStarted.value : undefined;
472 // SSH is one switch (`settings/ssh.ts`), off unless an admin turns it on; FORGE_SSH_PORT is only
473 // where it listens, so the listener starts when both say so and follows the switch afterwards.
474 type StartedSsh = Extract<Awaited<ReturnType<typeof import("./tui/ssh.ts").startForgeSsh>>, { ok: true }>["value"];
475 let ssh: StartedSsh | undefined;
476 /** Start the listener; resolves with why it did not start, or undefined when it is up. */
477 async function startSsh(): Promise<string | undefined> {
478 if (ssh !== undefined) return undefined;
479 if (sshPort <= 0) return "this forge has no port for it: FORGE_SSH_PORT is 0, or it runs as an app of another forge";
480 const started = await import("./tui/ssh.ts")
481 .then((m) => m.startForgeSsh(app, { port: sshPort }))
482 .catch((error) => {
483 app.log.warn("ssh is off: the terminal failed to load", { error: String(error) });
484 return undefined;
485 });
486 if (started === undefined) return "the terminal module failed to load; the log says why";
487 if (!started.ok) {
488 app.log.warn("ssh is off: the terminal could not start", {
489 port: sshPort,
490 reason: started.error.message,
491 code: (started.error as { code?: string }).code,
492 });
493 return `port ${sshPort} could not be opened: ${started.error.message}`;
494 }
495 ssh = started.value;
496 app.log.info("ssh is up", { port: ssh.port, hostKey: ssh.hostKey.fingerprint });
497 return undefined;
498 }
499 function stopSsh(): void {
500 if (ssh === undefined) return;
501 ssh.stop();
502 ssh = undefined;
503 delete app.config.sshPort;
504 delete app.config.sshHostKey;
505 }
506 // A forge that already had a host key keeps serving ssh: its switch starts on (settings/ssh.ts).
507 if (!readOnly && migrateSsh(app.db, app.config.dataDir)) app.log.info("ssh stays on: this forge already had a host key");
508 if (sshOn(app.db)) await startSsh();
509 followSsh(app, { follow: async (on) => (on ? startSsh() : void stopSsh()), listening: () => ssh !== undefined });
484510
485511 // Apps and the crew (docs/APPS.md). Both are on unless FORGE_APPS=0: an app
486512 // is served by Host on the same port, and the crew runs agents as child
@@ -1007,13 +1033,6 @@ if (crew)
10071033 app.log.info(crew.ready ? "crew is ready" : "crew is not ready", {
10081034 detail: crew.detail,
10091035 });
1010 if (ssh)
1011 // The host key fingerprint on boot is what an operator compares against the
1012 // one their client prints on first connect.
1013 app.log.info("ssh is up", {
1014 port: ssh.port,
1015 hostKey: ssh.hostKey.fingerprint,
1016 });
10171036
10181037 // A run whose forge died is noticed by whichever forge is up, on boot and
10191038 // on the way: an old process finishing beside a new one keeps its runs alive
src/settings/ssh.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * SSH, one switch: off unless an admin turns it on. Stored in `forge_setting`
3 * under `ssh` (`on` or `off`; absent is off, unless the forge already had a host key:
4 * `migrateSsh`), every change kept in `forge_setting_change`.
5 *
6 * Off, the listener does not start (`main.ts` asks `sshOn`) and no page, API or
7 * MCP answer, terminal screen, doc page or llms.txt line says ssh, a host key,
8 * an SSH key or a `git@`/`ssh://` address: every builder of those words
9 * (`ssh/command.ts`) answers undefined, and the keys page says the feature is
10 * off. On, everything is as it was.
11 *
12 * `FORGE_SSH_PORT` is only where the listener binds (`0`, or a forge hosted
13 * as an app of another, means there is no port, so the switch cannot give
14 * anything): the switch decides whether it is used. Both must hold.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import { existsSync } from "node:fs";
19 import { join } from "node:path";
20 import { writeSetting } from "./limits.ts";
21
22 const KEY = "ssh";
23
24 /** What the switch is for, in one sentence, on the page and in the MCP. */
25 export const SSH_GIVES = "Lets people clone and push over SSH and open the forge's terminal, with the SSH keys they add under Settings.";
26
27 const known = new WeakMap<Database, boolean>();
28
29 /** Whether the switch is on. One read per database, kept until `setSsh` changes it. */
30 export function sshOn(db: Database): boolean {
31 let on = known.get(db);
32 if (on === undefined) {
33 const row = db
34 .query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1")
35 .get(KEY);
36 on = row?.value === "on";
37 known.set(db, on);
38 }
39 return on;
40 }
41
42 /** Set the switch and keep the change; the same value again keeps nothing. */
43 export function setSsh(db: Database, on: boolean, actorId: string): void {
44 if (sshOn(db) === on) return;
45 writeSetting(db, KEY, on ? "on" : "off", on ? "off" : "on", on ? "on" : "off", actorId);
46 known.delete(db);
47 }
48
49 /**
50 * A forge that already served ssh keeps serving it: before there was a switch the listener
51 * wrote its host key under `<dataDir>/ssh`, so a key there with no setting stored means the
52 * switch starts on. A fresh forge has no key and stays off. Run once at boot, before `sshOn`.
53 */
54 export function migrateSsh(db: Database, dataDir: string): boolean {
55 const stored = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(KEY);
56 if (stored !== null || !existsSync(join(dataDir, "ssh", "host_ed25519"))) return false;
57 writeSetting(db, KEY, "on", "off", "on", "system");
58 known.delete(db);
59 return true;
60 }
src/ssh/command.ts +5 −1
@@ -2,12 +2,16 @@
22 * The exact `ssh …` that opens this forge's terminal — or an app's, when a
33 * login is given (its slug; `slug--12` for the preview of pull 12). One
44 * builder for every surface that shows the command, so they never disagree
5 * about the host or the port. Undefined when SSH is off.
5 * about the host or the port. Undefined when SSH is off: the switch
6 * (`settings/ssh.ts`) or no port.
67 */
78
89 import type { App } from "../app.ts";
10 import { sshOn } from "../settings/ssh.ts";
911
1012 export function sshCommand(app: App, login?: string): string | undefined {
13 // The switch (`settings/ssh.ts`): off, there is no command anywhere.
14 if (!sshOn(app.db)) return undefined;
1115 // Hosted by another forge, this forge's own terminal is reached the way
1216 // its host said, word for word; it has no listener of its own.
1317 if (login === undefined && app.config.appSsh !== undefined) return app.config.appSsh;
src/ssh/switch.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * The listener follows the switch (`settings/ssh.ts`): `main.ts` registers how to start and stop
3 * it, and whoever turns the switch calls `applySsh`. A forge with no registered listener (a test,
4 * the CLI, a forge with no port) has nothing to start, and the switch alone decides what is shown.
5 */
6
7 import type { App } from "../app.ts";
8
9 /** Starts or stops the listener; when it could not start, says why in a sentence. */
10 interface Follower {
11 readonly follow: (on: boolean) => Promise<string | undefined>;
12 readonly listening: () => boolean;
13 }
14 const followers = new WeakMap<App, Follower>();
15
16 export function followSsh(app: App, follower: Follower): void {
17 followers.set(app, follower);
18 }
19
20 /** Start or stop the listener to match the switch; resolves with why it did not start, if so. */
21 export async function applySsh(app: App, on: boolean): Promise<string | undefined> {
22 return followers.get(app)?.follow(on);
23 }
24
25 /** Whether the listener is up now; undefined when this forge registered none. */
26 export function sshListening(app: App): boolean | undefined {
27 return followers.get(app)?.listening();
28 }
src/tui/forge.ts +4 −2
@@ -76,6 +76,7 @@ import { modelScreen } from "./screens/model.ts";
7676 import { notifyScreen } from "./screens/notify.ts";
7777 import { talkBuildScreen } from "./screens/talk_build.ts";
7878 import { talkChatsScreen } from "./screens/talk_chats.ts";
79 import { sshOn } from "../settings/ssh.ts";
7980 import { sshKeysScreen } from "./screens/sshkeys.ts";
8081 import { passkeysScreen } from "./screens/passkeys.ts";
8182 import { confirmsScreen } from "./screens/confirms.ts";
@@ -481,7 +482,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
481482 hint: "say what to build; versions, diff, restore and publish. n starts one",
482483 run: () => ctx.push(talkBuildScreen(session, ctx)),
483484 });
484 if (session.signedIn)
485 // Only while the SSH switch is on (`settings/ssh.ts`); off, the keys are not a thing here.
486 if (session.signedIn && sshOn(session.app.db))
485487 commands.push({
486488 id: "ssh-keys",
487489 title: "Computer keys",
@@ -590,7 +592,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
590592 id: "docs",
591593 title: "Docs",
592594 hint: "the forge's documentation; Enter reads one",
593 run: () => ctx.push(docsScreen(ctx)),
595 run: () => ctx.push(docsScreen(ctx, sshOn(session.app.db))),
594596 });
595597 // The last releases with their pulls, as /changelog shows them: for anyone.
596598 commands.push({
src/tui/screens/docs.ts +8 −7
@@ -15,10 +15,10 @@ export function docRows(entries: readonly DocEntry[]): ListRow[] {
1515 return entries.map((e) => ({ title: e.title }));
1616 }
1717
18 function docScreen(ctx: Ctx, entry: DocEntry): Screen {
18 function docScreen(ctx: Ctx, entry: DocEntry, ssh: boolean): Screen {
1919 const scroll = new Scroll();
2020 let cache: { w: number; lines: ReturnType<typeof renderMarkdown> } | undefined;
21 const text = docText(entry);
21 const text = docText(entry, ssh);
2222 return {
2323 title: entry.title,
2424 keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")],
@@ -46,7 +46,7 @@ export function docList(): { rows: ListRow[]; entries: (DocEntry | undefined)[]
4646 }
4747
4848 /** The hits of a query as a list of their own; Enter reads one. */
49 function resultsScreen(ctx: Ctx, query: string): Screen {
49 function resultsScreen(ctx: Ctx, query: string, ssh: boolean): Screen {
5050 const state = new ListState();
5151 const hits = searchDocs(query);
5252 return {
@@ -60,14 +60,15 @@ function resultsScreen(ctx: Ctx, query: string): Screen {
6060 if (e.key === "esc" || e.key === "q") ctx.pop();
6161 else if (e.key === "enter") {
6262 const hit = hits[state.index];
63 if (hit !== undefined) ctx.push(docScreen(ctx, hit));
63 if (hit !== undefined) ctx.push(docScreen(ctx, hit, ssh));
6464 } else state.key(e, hits.length);
6565 return true;
6666 },
6767 };
6868 }
6969
70 export function docsScreen(ctx: Ctx): Screen {
70 /** `ssh`: whether the SSH switch is on, which passages of the docs are shown (`view/docs.ts`). */
71 export function docsScreen(ctx: Ctx, ssh = false): Screen {
7172 const state = new ListState();
7273 const { rows, entries } = docList();
7374 const self: Screen = {
@@ -84,7 +85,7 @@ export function docsScreen(ctx: Ctx): Screen {
8485 label: "Words to find",
8586 onSubmit: (q) => {
8687 if (q === "") return "Type a word to look for.";
87 return later(ctx, () => resultsScreen(ctx, q.slice(0, 80)));
88 return later(ctx, () => resultsScreen(ctx, q.slice(0, 80), ssh));
8889 },
8990 }),
9091 );
@@ -93,7 +94,7 @@ export function docsScreen(ctx: Ctx): Screen {
9394 else if (e.key === "enter") {
9495 const entry = entries[state.index];
9596 if (entry === undefined) search();
96 else ctx.push(docScreen(ctx, entry));
97 else ctx.push(docScreen(ctx, entry, ssh));
9798 } else state.key(e, rows.length);
9899 return true;
99100 },
src/tui/screens/featureswitch.ts +25 −3
@@ -15,6 +15,7 @@ import {
1515 type FeatureView,
1616 type SettingView,
1717 } from "../../actions/features.ts";
18 import { sshRow, switchSsh, type SshRow } from "../../actions/ssh_switch.ts";
1819 import type { Ctx, Screen } from "../app/app.ts";
1920 import { binding } from "../app/keys.ts";
2021 import type { Session } from "../session.ts";
@@ -96,23 +97,44 @@ function settingsScreen(f: Session, ctx: Ctx, slug: string): Screen {
9697 return screen;
9798 }
9899
100 /** The forge's own SSH switch, the last row. */
101 function sshListRow(r: SshRow): ListRow {
102 return { title: "SSH the forge's own switch", meta: r.on ? "on" : "off", note: r.gives };
103 }
104
99105 export function featureSwitchScreen(f: Session, ctx: Ctx): Screen {
100106 const state = new ListState();
101107 let features: readonly FeatureView[] = [];
108 let ssh: SshRow | undefined;
102109 const reload = async (): Promise<void> => {
103110 const listed = mayFeatures(f) ? await listFeatures(f.app, f.user) : undefined;
104111 features = listed?.ok ? listed.value : [];
112 const row = mayFeatures(f) ? sshRow(f.app, f.user) : undefined;
113 ssh = row?.ok ? row.value : undefined;
105114 ctx.invalidate();
106115 };
116 const at = (): FeatureView | undefined => features[state.index];
107117 const screen: Screen = {
108118 title: "Features",
109119 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "absorb / un-absorb"), binding(["enter"], "settings")],
110120 load: reload,
111121 render(area, s) {
112 drawList(s, area, ctx.theme.c, state, features.map(featureRow));
122 drawList(s, area, ctx.theme.c, state, [...features.map(featureRow), ...(ssh === undefined ? [] : [sshListRow(ssh)])]);
113123 },
114124 key(e) {
115 const here = features[state.index];
125 const here = at();
126 if (e.key === "a" && ssh !== undefined && state.index === features.length) {
127 const on = !ssh.on;
128 runAsync(ctx, async () => {
129 const done = await switchSsh(f.app, f.user, on);
130 ctx.toast(
131 !done.ok ? "only a site admin does that" : !on ? "SSH is off." : done.value.warning === undefined ? "SSH is on." : `SSH is on, but it did not start: ${done.value.warning}`,
132 done.ok && done.value.warning === undefined ? undefined : "attn",
133 );
134 await reload();
135 });
136 return true;
137 }
116138 if (e.key === "a" && here !== undefined) {
117139 runAsync(ctx, async () => {
118140 const done = here.absorbed ? await unabsorbApp(f.app, f.user, here.slug) : await absorbApp(f.app, f.user, here.slug);
@@ -128,7 +150,7 @@ export function featureSwitchScreen(f: Session, ctx: Ctx): Screen {
128150 ctx.push(settingsScreen(f, ctx, here.slug));
129151 return true;
130152 }
131 return state.key(e, features.length);
153 return state.key(e, features.length + (ssh === undefined ? 0 : 1));
132154 },
133155 };
134156 return screen;
src/view/docs.ts +10 −2
@@ -44,8 +44,16 @@ export function docEntry(name: string): DocEntry | undefined {
4444 }
4545
4646 /** The text of an entry from either folder (`features/NAME.md` too). */
47 export function docText(entry: DocEntry): string {
48 return readFileSync(join(DOCS, entry.name), "utf8");
47 export function docText(entry: DocEntry, ssh = false): string {
48 return withSsh(readFileSync(join(DOCS, entry.name), "utf8"), ssh);
49 }
50
51 /**
52 * A passage that speaks of ssh sits between `<!-- ssh -->` and `<!-- /ssh -->`: kept (the markers
53 * dropped) while the switch is on (`settings/ssh.ts`), gone while it is off.
54 */
55 export function withSsh(text: string, on: boolean): string {
56 return text.replace(/<!-- ssh -->\n?([\s\S]*?)<!-- \/ssh -->\n?/g, (_, inner: string) => (on ? inner : ""));
4957 }
5058
5159 const FEATURES = join(DOCS, "features");
src/web/layout.ts +3 −1
@@ -7,6 +7,7 @@
77 * `/search`), and every dialog (a link to a real page).
88 */
99
10 import { sshOn } from "../settings/ssh.ts";
1011 import { returnTo, withReturn } from "./return_to.ts";
1112 import { waitingCount } from "../actions/conversation_confirms.ts";
1213 import { goLevel, goPaletteRows } from "./go_pages.ts";
@@ -414,7 +415,7 @@ const STATIC_PALETTE: PaletteItem[] = [
414415 { t: "Account settings", h: "/settings", c: "Settings" },
415416 { t: "Access codes", h: "/settings/tokens", c: "Settings" },
416417 { t: "Connected agents", h: "/settings/grants", c: "Settings" },
417 { t: "Computer keys", h: "/settings/keys", c: "Settings" },
418 { t: "Computer keys", h: "/settings/keys", c: "Settings" }, // only while the SSH switch is on
418419 { t: "Connected accounts", h: "/settings/origins", c: "Settings" },
419420 { t: "Your shells", h: "/settings/shells", c: "Settings" },
420421 ];
@@ -544,6 +545,7 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html {
544545 // at a 403 or a 404).
545546 ...(ctx.auth.user
546547 ? STATIC_PALETTE.filter((p) => {
548 if (p.h === "/settings/keys" && !sshOn(ctx.app.db)) return false;
547549 const row = GO_ROWS.find((r) => r.t === p.t && r.h === p.h);
548550 return row === undefined || row.who !== "admin" || ctx.auth.user?.isAdmin === true;
549551 })
src/web/llms_tools.ts +6 −5
@@ -11,7 +11,7 @@ import { TOKEN_FREE_TOOLS } from "../core/mcp_card.ts";
1111 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
1212
1313 /** What a line reads: `report` is not a `Tool`, having no `run`, but is listed. */
14 export type Listed = Pick<Tool, "name" | "description" | "doc" | "writes" | "adminOnly" | "needsAdminScope" | "dryByDefault" | "readsWithout" | "readsWhen">;
14 export type Listed = Pick<Tool, "name" | "description" | "doc" | "writes" | "adminOnly" | "needsSwitch" | "needsAdminScope" | "dryByDefault" | "readsWithout" | "readsWhen">;
1515
1616 const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim();
1717
@@ -80,13 +80,14 @@ export const setMcpTools = (all: readonly Listed[], tokenFree: readonly Listed[]
8080 };
8181
8282 /** The kept-body key for a reader: tools differ by scope and by admin, nothing else. */
83 export const readerKey = (r: Reader | undefined): string => (r === undefined ? "anon" : `${r.scope}${r.isAdmin ? "+admin" : ""}`);
83 export const readerKey = (r: Reader | undefined, ssh: boolean): string =>
84 r === undefined ? "anon" : `${r.scope}${r.isAdmin ? "+admin" : ""}${ssh ? "+ssh" : ""}`;
8485
8586 /** A signed-in reader's section is the tools they may call; a stranger's is folded. */
86 export function mcpToolsSection(origin: string, reader: Reader | undefined): readonly string[] {
87 export function mcpToolsSection(origin: string, reader: Reader | undefined, ssh: boolean): readonly string[] {
8788 if (reader === undefined) return anonymousToolsSection(open, toolCount, origin);
88 const k = readerKey(reader);
89 const k = readerKey(reader, ssh);
8990 let s = sections.get(k);
90 if (s === undefined) sections.set(k, (s = toolsSection(every.filter((t) => callableBy(t, reader)))));
91 if (s === undefined) sections.set(k, (s = toolsSection(every.filter((t) => (t.needsSwitch === undefined || ssh) && callableBy(t, reader)))));
9192 return s;
9293 }
src/web/pages/access.ts +2 −1
@@ -5,6 +5,7 @@
55 * never an address — stands for the caller.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import { listAccess } from "../../actions/access_log.ts";
910 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1011 import type { Ctx } from "../../http/context.ts";
@@ -81,7 +82,7 @@ export function accessPage(ctx: Ctx): Response {
8182 title: "Access",
8283 body: html`<div class="page-head"><h1>Access</h1></div>
8384 ${settingsLayout(
84 accountSections("access", { admin: true }),
85 accountSections("access", { admin: true, ssh: sshOn(ctx.app.db) }),
8586 body,
8687 "Account settings",
8788 )}`,
src/web/pages/account.ts +18 −1
@@ -51,6 +51,7 @@ import { cookieValue, isAccountItself, type Ctx } from "../../http/context.ts";
5151 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
5252 import { offeredPluginRepo } from "../../core/mcp_card.ts";
5353 import { publicOrigin } from "../../core/public_origin.ts";
54 import { sshOn } from "../../settings/ssh.ts";
5455 import { sshCommand } from "../../ssh/command.ts";
5556 import {
5657 settingsLayout,
@@ -114,7 +115,7 @@ type Section = "profile" | "appearance" | "password" | "tokens" | "grants" | "ke
114115 // The section list lives beside the newest page that joins it, so adding one
115116 // cannot leave the others pointing at a nav that has forgotten it.
116117 const sections = (ctx: Ctx, current: Section): SettingsSection[] =>
117 accountSections(current, { admin: ctx.auth.user?.isAdmin === true });
118 accountSections(current, { admin: ctx.auth.user?.isAdmin === true, ssh: sshOn(ctx.app.db) });
118119
119120 /** One account page: the shared shell, the section nav, and this section. */
120121 export function accountShell(
@@ -1029,9 +1030,23 @@ function keysView(
10291030 )}`;
10301031 }
10311032
1033 /**
1034 * The keys routes while the switch is off (`settings/ssh.ts`): the page says the feature is off,
1035 * and a forge admin gets the link that turns it on; no one else is offered a way.
1036 */
1037 function keysOff(ctx: Ctx): Response {
1038 const admin = ctx.auth.user?.isAdmin === true && ctx.auth.user.kind !== "agent";
1039 const body = html`<p class="muted" id="keys-off">Computer keys are a feature that is off on this forge.</p>
1040 ${admin
1041 ? html`<p><a href="/settings/features">Switch it on in Settings › Features</a></p>`
1042 : html`<p class="muted small">A forge admin can switch it on.</p>`}`;
1043 return accountShell(ctx, "profile", "Computer keys", body, 404);
1044 }
1045
10321046 // GET /settings/keys
10331047 export function keysPage(ctx: Ctx): Response {
10341048 if (!ctx.auth.user) return signInFirst(ctx);
1049 if (!sshOn(ctx.app.db)) return keysOff(ctx);
10351050 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
10361051 const body = keysView(ctx, { name: "", key: "" });
10371052 return timePhase(ctx.request, "render", () => accountShell(ctx, "keys", "Computer keys", body));
@@ -1040,6 +1055,7 @@ export function keysPage(ctx: Ctx): Response {
10401055 // POST /settings/keys
10411056 export async function keyCreate(ctx: Ctx): Promise<Response> {
10421057 if (!ctx.auth.user) return signInFirst(ctx);
1058 if (!sshOn(ctx.app.db)) return keysOff(ctx);
10431059 const form = await readForm(ctx, "rw");
10441060 if (form instanceof Response) return form;
10451061 const name = field(form, "name");
@@ -1070,6 +1086,7 @@ export async function keyCreate(ctx: Ctx): Promise<Response> {
10701086 // POST /settings/keys/:id/delete
10711087 export async function keyDelete(ctx: Ctx): Promise<Response> {
10721088 if (!ctx.auth.user) return signInFirst(ctx);
1089 if (!sshOn(ctx.app.db)) return keysOff(ctx);
10731090 const form = await readForm(ctx, "rw");
10741091 if (form instanceof Response) return form;
10751092 const removed = deleteSshKey(ctx.app, ctx.auth.user, ctx.params.id ?? "");
src/web/pages/accounts.ts +2 −1
@@ -5,6 +5,7 @@
55 * only; anyone else gets the forge's one 404.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import {
910 listAccounts,
1011 removeAccount,
@@ -59,7 +60,7 @@ function shell(ctx: Ctx, body: Html, status = 200): Response {
5960 title: "Accounts",
6061 body: html`<div class="page-head"><h1>Accounts</h1></div>
6162 ${settingsLayout(
62 accountSections("accounts", { admin: true }),
63 accountSections("accounts", { admin: true, ssh: sshOn(ctx.app.db) }),
6364 body,
6465 "Account settings",
6566 )}`,
src/web/pages/admin-limits.ts +2 −1
@@ -5,6 +5,7 @@
55 * who, when, from what to what. Anyone else gets the not-found page.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import { usdWords } from "../../spawn/credit.ts";
910 import { worstCaseOf } from "../../spawn/included_credit.ts";
1011 import { QUOTA_INVALID } from "../../actions/admin_limits_words.ts";
@@ -239,7 +240,7 @@ export function limitsPage(ctx: Ctx): Response {
239240 title: "Limits",
240241 body: html`<div class="page-head"><h1>Limits</h1></div>
241242 ${settingsLayout(
242 accountSections("limits", { admin: true }),
243 accountSections("limits", { admin: true, ssh: sshOn(ctx.app.db) }),
243244 body,
244245 "Account settings",
245246 )}`,
src/web/pages/app_templates.ts +2 −1
@@ -3,6 +3,7 @@
33 * form to mark another or unmark one. Anyone else is told 403.
44 */
55
6 import { sshOn } from "../../settings/ssh.ts";
67 import { MARK_TEMPLATE_ERRORS, markTemplate } from "../../actions/app_templates.ts";
78 import { DEFAULT_TEMPLATE, markedTemplates } from "../../core/app_templates.ts";
89 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -69,7 +70,7 @@ export function appTemplatesPage(ctx: Ctx): Response {
6970 ctx,
7071 title: "App templates",
7172 body: html`<div class="page-head"><h1>App templates</h1></div>
72 ${settingsLayout(accountSections("templates", { admin: true }), body, "Account settings")}`,
73 ${settingsLayout(accountSections("templates", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
7374 });
7475 notePhase(ctx.request, "render", performance.now() - rendering);
7576 return response;
src/web/pages/apps.ts +2 −1
@@ -13,6 +13,7 @@
1313 */
1414
1515 import { USERNAME_PATTERN } from "../username_pattern.ts";
16 import { sshOn } from "../../settings/ssh.ts";
1617 import { runnerSettings } from "../../crew/runner_env.ts";
1718 import { clearCache } from "../../actions/build_cache.ts";
1819 import { returnTo, withReturn } from "../return_to.ts";
@@ -779,7 +780,7 @@ export function previewBlock(ctx: Ctx, repo: Repo, pull: Pull): Html {
779780 return previewSection(
780781 html`${envFacts(base, env)}
781782 ${dataNote === null ? null : html`<p class="muted small">${dataNote}</p>`}
782 ${when(writer, () =>
783 ${when(writer && sshOn(ctx.app.db), () =>
783784 terminalLine(
784785 terminalFor(ctx.app, view.value.app, env.env, env),
785786 ctx.app.config.sshHostKey,
src/web/pages/backups.ts +2 −1
@@ -13,6 +13,7 @@
1313 * was /settings/resilience, which now sends here.
1414 */
1515
16 import { sshOn } from "../../settings/ssh.ts";
1617 import {
1718 forgetDestination,
1819 saveDestination,
@@ -60,7 +61,7 @@ function shell(ctx: Ctx, body: Html): Response {
6061 scriptJs: liveRegionsJs,
6162 body: html`<div class="page-head"><h1>Backups</h1></div>
6263 ${settingsLayout(
63 accountSections("backups", { admin: true }),
64 accountSections("backups", { admin: true, ssh: sshOn(ctx.app.db) }),
6465 body,
6566 "Account settings",
6667 )}`,
src/web/pages/billing.ts +2 −1
@@ -5,6 +5,7 @@
55 * Anyone else gets the not-found page.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import { ledBlock } from "./visitors.ts";
910 import { BILLING_WORDS, STRIPE_WORDS, connectStripe, disconnectStripe, grantPlan, planGrant, readBilling, saveSigningSecret, type BillingError, type StripeWords } from "../../actions/billing.ts";
1011 import { retryOrder } from "../../actions/order.ts";
@@ -260,7 +261,7 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
260261 ctx,
261262 title: "Billing",
262263 body: html`<div class="page-head"><h1>Billing</h1></div>
263 ${settingsLayout(accountSections("billing", { admin: true }), body, "Account settings")}`,
264 ${settingsLayout(accountSections("billing", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
264265 }, status);
265266 notePhase(ctx.request, "render", performance.now() - rendering);
266267 // A code just made is in this body only: never kept by a cache.
src/web/pages/captain.ts +2 −1
@@ -6,6 +6,7 @@
66 * browser's own, same-origin, admin only.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { addMemory, editMemory, MEMORY_TEXT_MAX, MEMORY_WORDS, removeMemory, rulesOf } from "../../core/talk_memory.ts";
1011 import { EVERY_MAX, EVERY_MIN, listRoutines, ROUTINE_KINDS, ROUTINE_NAMES, setRoutine } from "../../core/talk_routines.ts";
1112 import { runRoutine } from "../../crew/routines.ts";
@@ -66,7 +67,7 @@ function view(ctx: Ctx, error?: string, status = 200): Response {
6667 {
6768 ctx,
6869 title: "Captain",
69 body: html`${pageHead("Captain", { sub: "What Talk remembers about how you want the forge run, and the check-ins it posts for you." })}${settingsLayout(accountSections("captain", { admin: true }), body, "Account settings")}`,
70 body: html`${pageHead("Captain", { sub: "What Talk remembers about how you want the forge run, and the check-ins it posts for you." })}${settingsLayout(accountSections("captain", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
7071 },
7172 status,
7273 );
src/web/pages/cloud.ts +3 −2
@@ -6,6 +6,7 @@
66 * event. "Write allowed" is off until someone turns it on here.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import {
1011 addAccount,
1112 allowWrite,
@@ -151,7 +152,7 @@ export async function cloudPage(ctx: Ctx): Promise<Response> {
151152 title: "Cloud accounts",
152153 body: html`<div class="page-head"><h1>Cloud accounts</h1></div>
153154 ${settingsLayout(
154 accountSections("cloud", { admin: true }),
155 accountSections("cloud", { admin: true, ssh: sshOn(ctx.app.db) }),
155156 html`${accountsCard(accounts, reads, uses)}${readsCard(reads)}
156157 <p class="muted small"><a href="/settings/cloud/audit">Every vendor call today</a> · <a href="/pinned">Pinned forges</a> · <a href="/deploy-to">Deploy a pinned forge</a></p>`,
157158 "Account settings",
@@ -222,7 +223,7 @@ export function cloudAuditPage(ctx: Ctx): Response {
222223 title: "Cloud audit",
223224 body: html`<div class="page-head"><h1>Cloud audit</h1></div>
224225 ${settingsLayout(
225 accountSections("cloud", { admin: true }),
226 accountSections("cloud", { admin: true, ssh: sshOn(ctx.app.db) }),
226227 html`<section class="settings-block">
227228 <h2>Today's vendor calls</h2>
228229 ${rows.length === 0
src/web/pages/confirms.ts +2 −1
@@ -7,6 +7,7 @@
77 * answer itself, never put in a flash cookie or the conversation.
88 */
99
10 import { sshOn } from "../../settings/ssh.ts";
1011 import { REFUSED, sayYes, waitingConfirms } from "../../actions/conversation_confirms.ts";
1112 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1213 import { ASKING } from "../../crew/conversation_confirm.ts";
@@ -53,7 +54,7 @@ function confirmsPage(ctx: Ctx, shown?: Html): Response {
5354 ctx,
5455 title: "Confirms",
5556 body: html`<div class="page-head"><h1>Confirms</h1></div>
56 ${settingsLayout(accountSections("confirms", { admin: user.isAdmin }), body, "Account settings")}`,
57 ${settingsLayout(accountSections("confirms", { admin: user.isAdmin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
5758 });
5859 }
5960
src/web/pages/crew.ts +2 −1
@@ -6,6 +6,7 @@
66 * the crew is actually there, in words, before anyone assigns anything.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { USERNAME_PATTERN } from "../username_pattern.ts";
1011 import { budgetsCard } from "../studio/crew_budgets.ts";
1112 import { crewKeyField } from "../studio/crew_key.ts";
@@ -99,7 +100,7 @@ function shell(ctx: Ctx, title: string, body: Html, status = 200): Response {
99100 title,
100101 body: html`<div class="page-head"><h1>${title}</h1></div>
101102 ${settingsLayout(
102 accountSections("crew", { admin: true }),
103 accountSections("crew", { admin: true, ssh: sshOn(ctx.app.db) }),
103104 body,
104105 "Account settings",
105106 )}`,
src/web/pages/economics.ts +2 −1
@@ -13,6 +13,7 @@
1313 * Anyone else gets the not-found page.
1414 */
1515
16 import { sshOn } from "../../settings/ssh.ts";
1617 import { ECONOMICS_WORDS, changeEconomics, readEconomics } from "../../actions/economics.ts";
1718 import { MARGIN_MAX, POSITION_MAX, POSITION_MIN, PRICE_MAX_CENTS, SLOTS_MAX, usdOfCents } from "../../core/slider.ts";
1819 import { OWNED_NODE_LABEL_DEFAULT } from "../../core/placement_policy.ts";
@@ -159,7 +160,7 @@ export function economicsPage(ctx: Ctx): Response {
159160 ctx,
160161 title: "Economics",
161162 body: html`<div class="page-head"><h1>Economics</h1></div>
162 ${settingsLayout(accountSections("economics", { admin: true }), body, "Account settings")}`,
163 ${settingsLayout(accountSections("economics", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
163164 });
164165 notePhase(ctx.request, "render", performance.now() - rendering);
165166 return response;
src/web/pages/features.ts +33 −1
@@ -6,6 +6,7 @@
66 * Anyone else is told the forge's 404, as every admin page does.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { upstreamBlob } from "../../core/upstream.ts";
1011 import {
1112 absorbApp,
@@ -19,6 +20,7 @@ import {
1920 type SettingView,
2021 provenanceFacts,
2122 } from "../../actions/features.ts";
23 import { sshRow, switchSsh, type SshRow } from "../../actions/ssh_switch.ts";
2224 import { runNow } from "../../apps/feature_run.ts";
2325 import { scheduleMeta, scheduleWhen } from "../../apps/feature_schedule.ts";
2426 import type { Run } from "../../core/feature_fires.ts";
@@ -50,7 +52,7 @@ function shell(ctx: Ctx, title: string, body: ReturnType<typeof html>): Response
5052 ctx,
5153 title,
5254 body: html`<div class="page-head"><h1>${title}</h1></div>
53 ${settingsLayout(accountSections("features", { admin: true }), body, "Account settings")}`,
55 ${settingsLayout(accountSections("features", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
5456 });
5557 }
5658
@@ -103,6 +105,24 @@ function featureRow(f: FeatureView) {
103105 });
104106 }
105107
108 /** The one built-in switch, above the absorbed apps: what it is for, and the button. */
109 function sshSwitchRow(r: SshRow) {
110 return row({
111 title: html`${r.name} ${r.on ? badge("on", { tone: "success" }) : badge("off")}`,
112 meta: html`<span id="sw-ssh">${r.gives}${sshState(r)}</span>`,
113 after: html`<form class="row-fields" method="post" action="/settings/features/${r.slug}/${r.on ? "unabsorb" : "absorb"}" aria-describedby="sw-ssh">
114 ${btn(r.on ? "Turn off" : "Turn on", { size: "sm", variant: r.on ? "secondary" : "primary", label: `Turn SSH ${r.on ? "off" : "on"}` })}
115 </form>`,
116 });
117 }
118
119 /** What the switch cannot give right now, said plainly; nothing when it is as it should be. */
120 function sshState(r: SshRow): string {
121 if (!r.reachable) return " This forge has no port to offer it on.";
122 if (r.on && r.listening === false) return " It is on, but nothing is listening yet.";
123 return "";
124 }
125
106126 // GET /settings/features
107127 export async function featuresPage(ctx: Ctx): Promise<Response> {
108128 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -111,9 +131,12 @@ export async function featuresPage(ctx: Ctx): Promise<Response> {
111131 const listed = await timePhase(ctx.request, "features", () => listFeatures(ctx.app, ctx.auth.user));
112132 if (!listed.ok) return notFoundPage(ctx);
113133 const rendering = performance.now();
134 const ssh = sshRow(ctx.app, ctx.auth.user);
135 const sshSwitch = ssh.ok ? html`<ul class="list setting-list">${sshSwitchRow(ssh.value)}</ul>` : null;
114136 const body = html`<section class="settings-block">
115137 <h2>Features</h2>
116138 <p class="muted">An absorbed app is a menu link with its settings kept here.</p>
139 ${sshSwitch}
117140 ${listed.value.length === 0
118141 ? empty({
119142 icon: "rocket",
@@ -328,6 +351,15 @@ export function featureSwitch(absorbing: boolean) {
328351 const form = await readForm(ctx, "admin");
329352 if (form instanceof Response) return form;
330353 const slug = ctx.params["slug"] ?? "";
354 // The forge's own switch, SSH, is named by its slug and turned by the same two routes.
355 if (slug === "ssh") {
356 const set = await switchSsh(ctx.app, ctx.auth.user, absorbing);
357 if (!set.ok) return notFoundPage(ctx);
358 return flashTo(ctx, "/settings/features", {
359 message: !absorbing ? "SSH is off." : set.value.warning === undefined ? "SSH is on." : `SSH is on, but it did not start: ${set.value.warning}`,
360 ...(absorbing && set.value.warning !== undefined ? { tone: "attn" as const } : {}),
361 });
362 }
331363 const done = absorbing ? await absorbApp(ctx.app, ctx.auth.user, slug) : await unabsorbApp(ctx.app, ctx.auth.user, slug);
332364 if (!done.ok && done.error === "not_found") return notFoundPage(ctx);
333365 return flashTo(
src/web/pages/flags.ts +2 −1
@@ -6,6 +6,7 @@
66 * Anyone else is told 403, and an agent is never an admin here.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { readFlags } from "../../actions/flags_view.ts";
1011 import { checkInput, FLAGS_ADMIN_ONLY, flagRegistry, usesLine, winnerOffer, mayManageFlags, useFlagRegistry, type FlagValue } from "../../core/flags.ts";
1112 import { makeWinnerDefault } from "../../actions/flag_winner.ts";
@@ -118,7 +119,7 @@ export function flagsPage(ctx: Ctx): Response {
118119 ctx,
119120 title: "Flags",
120121 body: html`<div class="page-head"><h1>Flags</h1></div>
121 ${settingsLayout(accountSections("flags", { admin: true }), body, "Account settings")}`,
122 ${settingsLayout(accountSections("flags", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
122123 });
123124 notePhase(ctx.request, "uses", usesMs);
124125 notePhase(ctx.request, "render", Math.max(performance.now() - rendering - usesMs, 0));
src/web/pages/flows-all.ts +2 −1
@@ -4,6 +4,7 @@
44 * admins only; anyone else gets the not-found page. Reads stored state only.
55 */
66
7 import { sshOn } from "../../settings/ssh.ts";
78 import { ALL_KINDS, parseKind, readAllFlows } from "../../flows/all.ts";
89 import type { Health } from "../../flows/view.ts";
910 import type { Ctx } from "../../http/context.ts";
@@ -47,7 +48,7 @@ export function allFlowsPage(ctx: Ctx): Response {
4748 const body = html`${pageHead("Flows across the forge", { sub: `${lines.length} ${lines.length === 1 ? "line" : "lines"}${lines.length > SHOWN ? `, the newest ${SHOWN} shown` : ""}.` })}
4849 ${filters}
4950 ${rows.length === 0 ? html`<p class="muted">No flow lines match.</p>` : listCard(rows)}`;
50 const response = page({ ctx, title: "Flows · admin", body: settingsLayout(accountSections("adminflows", { admin: true }), body, "Account settings") });
51 const response = page({ ctx, title: "Flows · admin", body: settingsLayout(accountSections("adminflows", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings") });
5152 notePhase(ctx.request, "render", performance.now() - rendering);
5253 return response;
5354 }
src/web/pages/hosted-forges.ts +2 −1
@@ -11,6 +11,7 @@
1111 * `REACH_SETTINGS`, the section's own anchor.
1212 */
1313
14 import { sshOn } from "../../settings/ssh.ts";
1415 import {
1516 allowReach,
1617 putAsideReach,
@@ -239,7 +240,7 @@ export async function hostedForgesPage(ctx: Ctx): Promise<Response> {
239240 title: "Hosted forges",
240241 body: html`<div class="page-head"><h1>Hosted forges</h1></div>
241242 ${settingsLayout(
242 accountSections("hosted", { admin: true }),
243 accountSections("hosted", { admin: true, ssh: sshOn(ctx.app.db) }),
243244 body,
244245 "Account settings",
245246 )}`,
src/web/pages/model.ts +2 −1
@@ -6,6 +6,7 @@
66 * card). A token is typed once and never shown again.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { blockedWay } from "../blocked.ts";
1011 import { noBudgetBlocked } from "../../actions/blocked_words.ts";
1112 import { ADD_MESSAGES, addOwnModel, setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
@@ -67,7 +68,7 @@ export function modelPage(ctx: Ctx): Response {
6768 title: "Connect your AI",
6869 body: html`<div class="page-head"><h1>Connect your AI</h1></div>
6970 ${settingsLayout(
70 accountSections("model", { admin: user.isAdmin }),
71 accountSections("model", { admin: user.isAdmin, ssh: sshOn(ctx.app.db) }),
7172 html`<section class="settings-block">
7273 <h2>Your model budget</h2>
7374 ${grant === undefined || own || user.isAdmin
src/web/pages/origins.ts +4 −4
@@ -17,6 +17,7 @@
1717 * where it was — that page and its poll live in `origin-flow.ts`.
1818 */
1919
20 import { sshOn } from "../../settings/ssh.ts";
2021 import type { Database } from "bun:sqlite";
2122 import { upstreamBlob } from "../../core/upstream.ts";
2223 import { FORGE_NOT_CARRIED } from "../../origins/words.ts";
@@ -192,9 +193,9 @@ const SECTION_ROWS: readonly (readonly [
192193
193194 export function accountSections(
194195 current: AccountSection,
195 o: { admin?: boolean } = {},
196 o: { admin?: boolean; ssh?: boolean } = {},
196197 ): SettingsSection[] {
197 return SECTION_ROWS.filter((r) => o.admin === true || !r[5]).map(
198 return SECTION_ROWS.filter((r) => (o.admin === true || !r[5]) && (r[2] !== "/settings/keys" || o.ssh === true)).map(
198199 ([group, label, href, icon, is]) => ({ group, label, href, icon, current: is(current) }),
199200 );
200201 }
@@ -992,8 +993,7 @@ export function shell(
992993 body: html`<div class="page-head"><h1>Connected accounts</h1></div>
993994 ${settingsLayout(
994995 accountSections("origins", {
995 admin: ctx.auth.user?.isAdmin === true,
996 }),
996 admin: ctx.auth.user?.isAdmin === true, ssh: sshOn(ctx.app.db) }),
997997 body,
998998 "Account settings",
999999 )}`,
src/web/pages/packs-settings.ts +2 −1
@@ -6,6 +6,7 @@
66 * the change is on /packs at once.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1011 import { refreshCatalogQuietly } from "../../packs/catalog.ts";
1112 import { setPackRepos } from "../../packs/set.ts";
@@ -48,7 +49,7 @@ function view(ctx: Ctx, problems: readonly string[], text: string, error?: strin
4849 {
4950 ctx,
5051 title: "Packs settings",
51 body: html`${pageHead("Packs", { sub: "/packs lists the public repositories named here, each with a pack.json at its root, and no others." })}${settingsLayout(accountSections("packs", { admin: true }), body, "Account settings")}`,
52 body: html`${pageHead("Packs", { sub: "/packs lists the public repositories named here, each with a pack.json at its root, and no others." })}${settingsLayout(accountSections("packs", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
5253 },
5354 status,
5455 );
src/web/pages/people.ts +2 −1
@@ -10,6 +10,7 @@
1010 * username wraps anywhere, so the page never scrolls sideways (#9374).
1111 */
1212
13 import { sshOn } from "../../settings/ssh.ts";
1314 import { setRole } from "../../actions/roles.ts";
1415 import { GRANT_MAX_USD } from "../../core/model_grant.ts";
1516 import { peopleByActivity, wordFilter, type PersonRow } from "../../core/people_rows.ts";
@@ -97,7 +98,7 @@ export function peoplePage(ctx: Ctx): Response {
9798 title: "People",
9899 body: html`<div class="page-head"><h1>People</h1></div>
99100 ${settingsLayout(
100 accountSections("people", { admin: true }),
101 accountSections("people", { admin: true, ssh: sshOn(ctx.app.db) }),
101102 html`<section class="settings-block">
102103 <p>Most recently seen first.</p>
103104 ${filters}
src/web/pages/scrapes.ts +6 −2
@@ -6,6 +6,7 @@
66 * of identity stops at a network or a group, and says so.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1011 import type { Ctx } from "../../http/context.ts";
1112 import { repoDir } from "../../git/repos.ts";
@@ -207,7 +208,7 @@ export async function scrapesPage(ctx: Ctx): Promise<Response> {
207208 ctx,
208209 title: "Scrapes",
209210 body: html`<div class="page-head"><h1>Scrapes</h1></div>
210 ${settingsLayout(accountSections("traffic", { admin: true }), body, "Account settings")}`,
211 ${settingsLayout(accountSections("traffic", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
211212 });
212213 }
213214
@@ -252,7 +253,10 @@ export async function networksImport(ctx: Ctx): Promise<Response> {
252253 });
253254 }
254255
255 /** A plain-text report for one group: what was seen, the networks and their abuse contacts, and what it cannot show. */
256 /**
257 * A plain-text report for one group: what was seen, the networks and their abuse contacts, and what
258 * it cannot show.
259 */
256260 export function reportOf(g: Group, net: NetworkTable, capture: { id: string; startedAt: number }): string {
257261 const nets = new Map<string, Network | null>(g.prefixes.map((p) => [p, net.find(p)]));
258262 const first = Math.min(...g.requests.map((r) => r.at));
src/web/pages/secrets.ts +2 −1
@@ -7,6 +7,7 @@
77 * when something last opened it.
88 */
99
10 import { sshOn } from "../../settings/ssh.ts";
1011 import type { SecretUse } from "../../core/app_secrets.ts";
1112 import { listSecrets, putSecret, removeSecret, secretUses } from "../../actions/secrets.ts";
1213 import type { Ctx } from "../../http/context.ts";
@@ -173,7 +174,7 @@ export function secretsPage(ctx: Ctx): Response {
173174 title: "Secrets",
174175 body: html`<div class="page-head"><h1>Secrets</h1></div>
175176 ${settingsLayout(
176 accountSections("secrets", { admin: true }),
177 accountSections("secrets", { admin: true, ssh: sshOn(ctx.app.db) }),
177178 html`${card}
178179 <p class="muted small">${humanCheckLine(ctx)}</p>`,
179180 "Account settings",
src/web/pages/security.ts +2 −1
@@ -6,6 +6,7 @@
66 * names, never the value of a token or key.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import { upstreamBlob } from "../../core/upstream.ts";
1011 import { existsSync, readFileSync, statSync } from "node:fs";
1112 import { join } from "node:path";
@@ -360,7 +361,7 @@ export function securityPage(ctx: Ctx): Response {
360361 ctx,
361362 title: "Security settings",
362363 body: html`<div class="page-head"><h1>Security</h1></div>
363 ${settingsLayout(accountSections("security", { admin: true }), body, "Account settings")}`,
364 ${settingsLayout(accountSections("security", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
364365 });
365366 }
366367
src/web/pages/security_controls.ts +6 −2
@@ -1,5 +1,9 @@
1 /** GET /settings/security/controls: each safeguard, and when it was last tested (`checks/controls.ts`). */
1 /**
2 * GET /settings/security/controls: each safeguard, and when it was last tested
3 * (`checks/controls.ts`).
4 */
25
6 import { sshOn } from "../../settings/ssh.ts";
37 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
48 import { controlStandings, type Standing } from "../../checks/controls.ts";
59 import type { Ctx } from "../../http/context.ts";
@@ -47,6 +51,6 @@ export function securityControlsPage(ctx: Ctx): Response {
4751 ctx,
4852 title: "Security controls",
4953 body: html`<div class="page-head"><h1>Security controls</h1></div>
50 ${settingsLayout(accountSections("security", { admin: true }), body, "Account settings")}`,
54 ${settingsLayout(accountSections("security", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
5155 });
5256 }
src/web/pages/sources.ts +2 −1
@@ -9,6 +9,7 @@
99 * stored views (`perf/views_store.ts`) in one indexed read.
1010 */
1111
12 import { sshOn } from "../../settings/ssh.ts";
1213 import { getAppById } from "../../core/apps.ts";
1314 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1415 import type { Ctx } from "../../http/context.ts";
@@ -280,7 +281,7 @@ export function sourcesPage(ctx: Ctx): Response {
280281 ctx,
281282 title: "Sources",
282283 body: html`<div class="page-head"><h1>Where people come from</h1></div>
283 ${settingsLayout(accountSections("traffic", { admin: true }), sourcesBody(ctx, q, label), "Account settings")}`,
284 ${settingsLayout(accountSections("traffic", { admin: true, ssh: sshOn(ctx.app.db) }), sourcesBody(ctx, q, label), "Account settings")}`,
284285 });
285286 notePhase(ctx.request, "render", performance.now() - rendering);
286287 return response;
src/web/pages/subscriptions.ts +2 −1
@@ -5,6 +5,7 @@
55 * for. A token is typed once and never shown again.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import { listAgents, type Agent } from "../../core/agents.ts";
910 import {
1011 addSubscription,
@@ -97,7 +98,7 @@ function shell(ctx: Ctx, body: Html): Response {
9798 title: "Subscriptions",
9899 body: html`<div class="page-head"><h1>Subscriptions</h1></div>
99100 ${settingsLayout(
100 accountSections("subscriptions", { admin: true }),
101 accountSections("subscriptions", { admin: true, ssh: sshOn(ctx.app.db) }),
101102 body,
102103 "Account settings",
103104 )}`,
src/web/pages/teams.ts +3 −2
@@ -5,6 +5,7 @@
55 * not-found page, before a body is read.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import { changeTeam, readTeamQueue, readTeams, teamChanges, TEAM_SAYS } from "../../actions/teams.ts";
910 import type { Agent } from "../../core/agents.ts";
1011 import { CHARTER_MAX, DIAL_MAX, shareSays, type Team } from "../../core/teams.ts";
@@ -118,7 +119,7 @@ export function teamPage(ctx: Ctx): Response {
118119 title: team.name,
119120 body: html`<div class="page-head"><h1>${team.name}</h1></div>
120121 ${settingsLayout(
121 accountSections("crew", { admin: true }),
122 accountSections("crew", { admin: true, ssh: sshOn(ctx.app.db) }),
122123 html`<p class="muted small">${btn("All teams", { href: "/settings/teams", variant: "ghost" })}</p>
123124 ${teamBody(team, read.value.agents, queue.ok ? queue.value : [])}`,
124125 "Account settings",
@@ -183,7 +184,7 @@ export function teamsPage(ctx: Ctx): Response {
183184 scriptJs: teamsLiveJs,
184185 body: html`<div class="page-head"><h1>Teams</h1></div>
185186 ${settingsLayout(
186 accountSections("crew", { admin: true }),
187 accountSections("crew", { admin: true, ssh: sshOn(ctx.app.db) }),
187188 html`<p class="muted small">
188189 A team is a named group of agents with a charter and a dial: its
189190 share of builder slots and budget. The dials together may not pass
src/web/pages/traffic.ts +2 −1
@@ -6,6 +6,7 @@
66 * but an admin.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import type { Ctx } from "../../http/context.ts";
1011 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1112 import {
@@ -183,7 +184,7 @@ export function trafficPage(ctx: Ctx): Response {
183184 body: html`<div class="page-head"><h1>Traffic</h1></div>
184185 <p class="muted">Who is using the forge's answering time, and from where.</p>
185186 ${settingsLayout(
186 accountSections("traffic", { admin: true }),
187 accountSections("traffic", { admin: true, ssh: sshOn(ctx.app.db) }),
187188 html`<div>
188189 ${seg(
189190 Object.entries(TRAFFIC_WINDOWS).map(([key, w]) => ({
src/web/pages/trusted.ts +2 −1
@@ -3,6 +3,7 @@
33 * a person's review, until when; a one-click remove; the kill switch that
44 * stops all folding in; and the revert of one source's landings.
55 */
6 import { sshOn } from "../../settings/ssh.ts";
67 import { addTrust, removeTrust, revertBySource, setFoldInStopped } from "../../actions/trusted_sources.ts";
78 import {
89 endsSoon,
@@ -108,7 +109,7 @@ export function trustedPage(ctx: Ctx): Response {
108109 ctx,
109110 title: "Trusted sources",
110111 body: html`<div class="page-head"><h1>Trusted sources</h1></div>
111 ${settingsLayout(accountSections("trusted", { admin: true }), body, "Account settings")}`,
112 ${settingsLayout(accountSections("trusted", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
112113 });
113114 }
114115
src/web/pages/usage-tabs.ts +2 −1
@@ -5,6 +5,7 @@
55 * frame they share.
66 */
77
8 import { sshOn } from "../../settings/ssh.ts";
89 import type { Html } from "../html.ts";
910 import { settingsLayout } from "../chrome.ts";
1011 import { html } from "../html.ts";
@@ -32,7 +33,7 @@ export function usageShell(ctx: Ctx, current: UsageTab, body: Html, status?: num
3233 scriptJs: liveRegionsJs,
3334 body: html`<div class="page-head"><h1>Usage</h1></div>
3435 ${settingsLayout(
35 accountSections("usage", { admin: true }),
36 accountSections("usage", { admin: true, ssh: sshOn(ctx.app.db) }),
3637 html`${tabs(
3738 TABS.map((t) => ({ label: t.label, href: t.href, current: t.id === current })),
3839 "Usage",
src/web/settings/devices.ts +6 −2
@@ -6,6 +6,7 @@
66 * the probe (`devices/ipp.ts`) is bounded and its answer is kept 30 s.
77 */
88
9 import { sshOn } from "../../settings/ssh.ts";
910 import type { Ctx } from "../../http/context.ts";
1011 import { DEVICE_ERRORS, declare, setCap, grant, revoke, devicesWithStatus, remove, statusLine } from "../../actions/devices.ts";
1112 import { allAppSlugs } from "../../core/device_grants.ts";
@@ -39,7 +40,10 @@ function supplies(report: PrinterReport): Html | null {
3940 </details>`;
4041 }
4142
42 /** Who may print here, as facts: the granted apps (revoke), one picker to grant more, the daily limit, the last prints. */
43 /**
44 * Who may print here, as facts: the granted apps (revoke), one picker to grant more, the daily
45 * limit, the last prints.
46 */
4347 function access(ctx: Ctx, d: Device): Html {
4448 const limits = grantLimits(ctx.app.db, d.id);
4549 const granted = limits.map((l) => l.slug);
@@ -112,7 +116,7 @@ export async function devicesPage(ctx: Ctx): Promise<Response> {
112116 title: "Devices",
113117 body: html`<div class="page-head"><h1>Devices</h1></div>
114118 ${settingsLayout(
115 accountSections("devices", { admin: true }),
119 accountSections("devices", { admin: true, ssh: sshOn(ctx.app.db) }),
116120 html`<section class="settings-block">
117121 <p class="muted">Printers on your network, as the forge sees them; only addresses like 192.168.1.161 are accepted.</p>
118122 ${when(devices.length === 0, () => html`<p class="muted">No devices declared.</p>`)}
src/web/standards.ts +8 −4
@@ -28,6 +28,7 @@
2828 * FORGE_SECURITY_CONTACT.
2929 */
3030
31 import { sshOn } from "../settings/ssh.ts";
3132 import { UPSTREAM_REPO } from "../core/upstream.ts";
3233 import { CRAWL_DELAY_S, DEEP_SEGMENTS } from "../http/crawl.ts";
3334 import { markPng, type MarkShape } from "../design/mark.ts";
@@ -168,7 +169,8 @@ export async function mcpJson(ctx: Ctx): Promise<Response> {
168169 await loadMcp();
169170 const repo = offeredPluginRepo(ctx.app.db, ctx.app.config.forgeRepo, UPSTREAM_REPO);
170171 const now = running();
171 return discovery(ctx, "mcp", JSON.stringify([repo, now.version, now.commit, toolsKey()]), () => mcpCard(ctx.url.origin, repo, now), "application/json", "public, max-age=3600", true);
172 const ssh = sshOn(ctx.app.db);
173 return discovery(ctx, "mcp", JSON.stringify([repo, now.version, now.commit, toolsKey(ssh)]), () => mcpCard(ctx.url.origin, repo, ssh, now), "application/json", "public, max-age=3600", true);
172174 }
173175
174176 /** GET /.well-known/mcp/server-card.json — the small server card (a draft; see `serverCard`).
@@ -187,7 +189,8 @@ export async function agentCardJson(ctx: Ctx): Promise<Response> {
187189 const now = running();
188190 // The same reader test /llms.txt uses, so the two agree on who sees the full list.
189191 const signedIn = ctx.auth.user !== undefined;
190 return discovery(ctx, `agent-card ${signedIn}`, JSON.stringify([now.version, toolsKey()]), () => agentCard(ctx.url.origin, now, signedIn), "application/json", signedIn ? "private, max-age=3600" : "public, max-age=3600", true, "Cookie, Authorization");
192 const ssh = sshOn(ctx.app.db);
193 return discovery(ctx, `agent-card ${signedIn}`, JSON.stringify([now.version, toolsKey(ssh)]), () => agentCard(ctx.url.origin, ssh, now, signedIn), "application/json", signedIn ? "private, max-age=3600" : "public, max-age=3600", true, "Cookie, Authorization");
191194 }
192195
193196 /**
@@ -491,7 +494,8 @@ export function llmsBody(ctx: Ctx): { body: string; etag: string } {
491494 // The tools section depends on who asks (scope and admin): each reader kind keeps its body.
492495 // A session acts with full authority; a token with its stored scope.
493496 const reader: Reader | undefined = ctx.auth.user === undefined ? undefined : { scope: ctx.auth.scope ?? "admin", isAdmin: ctx.auth.user.isAdmin };
494 const key = `${o} ${readerKey(reader)}`;
497 const ssh = sshOn(ctx.app.db);
498 const key = `${o} ${readerKey(reader, ssh)}`;
495499 const plans = JSON.stringify(getPlans(ctx.app.db));
496500 const tools = mcpToolsVersion();
497501 let kept = llmsBodies.get(key);
@@ -592,7 +596,7 @@ function renderLlmsTxt(ctx: Ctx, o: string, tell: string | undefined, running: s
592596 `- API catalog (RFC 9727, one linkset of the above): ${o}${DISCOVERY.catalog}`,
593597 `- OpenAPI: GET ${o}${DISCOVERY.openapi}, or one slice with ?tag= (${TAGS.join(", ")})`,
594598 "",
595 ...mcpToolsSection(o, reader),
599 ...mcpToolsSection(o, reader, sshOn(ctx.app.db)),
596600 cardsLine(),
597601 "",
598602 "## Public repositories",
src/web/studio/previews.ts +2 −1
@@ -7,6 +7,7 @@
77 * deploy event refreshes (`appStateFragment`) share.
88 */
99
10 import { sshOn } from "../../settings/ssh.ts";
1011 import { appCacheSize } from "../../apps/build_cache.ts";
1112 import { HELP_BUILD } from "../../core/contribute.ts";
1213 import { lacks } from "../../core/roles.ts";
@@ -354,7 +355,7 @@ export function appPanels(
354355 html`${onboarding === undefined
355356 ? when(production, (env) => envFacts(base, env))
356357 : onboardingRow(onboarding)}
357 ${when(writer && !fresh, () =>
358 ${when(writer && !fresh && sshOn(ctx.app.db), () =>
358359 terminalLine(
359360 terminalFor(ctx.app, record, "production", production),
360361 ctx.app.config.sshHostKey,
test/account-menu-names.test.ts +6 −1
@@ -1,9 +1,13 @@
1 /** A person who taps an account-menu label meets the same words on the page it opens: label, title, heading, empty line, palette. */
1 /**
2 * A person who taps an account-menu label meets the same words on the page it opens: label, title,
3 * heading, empty line, palette.
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
58 import { join } from "node:path";
69 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
711 import { serve, type Servers } from "../src/http/server.ts";
812 import { getUserByName } from "../src/core/users.ts";
913 import { createForgeApp } from "../src/tui/forge.ts";
@@ -20,6 +24,7 @@ let app: App, servers: Servers, base = "", cookie = "";
2024 beforeAll(async () => {
2125 dir = await mkdtemp(join(tmpdir(), "forge-menunames-"));
2226 app = createApp({ dataDir: dir, port: 0 });
27 setSsh(app.db, true, "test");
2328 servers = await serve(app);
2429 base = servers.url;
2530 const signup = await fetch(`${base}/signup`, {
test/account-menu.test.ts +10 −2
@@ -1,9 +1,13 @@
1 /** The account menu, by who opens it: three groups a person reads in two seconds, and one row for appearance. */
1 /**
2 * The account menu, by who opens it: three groups a person reads in two seconds, and one row for
3 * appearance.
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
58 import { join } from "node:path";
69 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
711 import { serve, type Servers } from "../src/http/server.ts";
812 import { adminCookie } from "./helpers/admin.ts";
913 import { quietLogs } from "./helpers/globals.ts";
@@ -16,6 +20,7 @@ let app: App, servers: Servers, base = "", admin = "", member = "";
1620 beforeAll(async () => {
1721 dir = await mkdtemp(join(tmpdir(), "forge-menu-"));
1822 app = createApp({ dataDir: dir, port: 0 });
23 setSsh(app.db, true, "test");
1924 servers = await serve(app);
2025 base = servers.url;
2126 admin = await adminCookie(app, { username: "grace", email: "[email protected]" });
@@ -33,7 +38,10 @@ afterAll(async () => {
3338 await rm(dir, { recursive: true, force: true });
3439 });
3540
36 /** The last menu of the bar, as its rows in order: a label, "---" for a rule, "[Theme]" for the appearance row. */
41 /**
42 * The last menu of the bar, as its rows in order: a label, "---" for a rule, "[Theme]" for the
43 * appearance row.
44 */
3745 async function menuRows(path: string, cookie: string): Promise<{ rows: string[]; html: string }> {
3846 const page = await (await fetch(`${base}${path}`, { headers: { cookie } })).text();
3947 const bar = page.slice(page.indexOf('<header class="topbar"'), page.indexOf("</header>"));
test/account-nojs.test.ts +8 −2
@@ -7,6 +7,7 @@ import { mkdtempSync, rmSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
1011 import { createSession } from "../src/core/sessions.ts";
1112 import { createUser } from "../src/core/users.ts";
1213 import { serve, type Servers } from "../src/http/server.ts";
@@ -18,7 +19,10 @@ quietLogs();
1819
1920 const EDGE_TOKEN = "edge-secret-for-the-test";
2021 const PARENT = "https://parent.test";
21 /** Measured: a warm /settings costs STATEMENTS_MEASURED statements; the ceiling sits just above it, so an N+1 fails. */
22 /**
23 * Measured: a warm /settings costs STATEMENTS_MEASURED statements; the ceiling sits just above it,
24 * so an N+1 fails.
25 */
2226 const TOKEN_STATUS = 303, KEY_STATUS = 303, PARENT_STATUS = 502, EDGE_STATUS = 303;
2327 const STATEMENTS_MEASURED = 19;
2428 const STATEMENT_CEILING = STATEMENTS_MEASURED + 2;
@@ -47,6 +51,7 @@ const post = (path: string, body: Record<string, string>, origin: string) =>
4751 beforeAll(async () => {
4852 root = mkdtempSync(join(tmpdir(), "forge-account-nojs-"));
4953 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge", edgeToken: EDGE_TOKEN, parentUrl: PARENT });
54 setSsh(app.db, true, "test");
5055 const u = await createUser(app.db, {
5156 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
5257 password: "a-good-passphrase", adminIfFirst: true,
@@ -149,7 +154,8 @@ test("a same-origin post lands: token and key rows appear, the status is pinned"
149154 });
150155
151156 test("the sign-in link forms: cross-origin refused, same-origin gets past the origin gate", async () => {
152 // The parent round trip cannot reach parent.test from here: past the gate it answers 502, not 403.
157 // The parent round trip cannot reach parent.test from here: past the gate it answers 502,
158 // not 403.
153159 const parent = await post("/settings/parent/link", {}, servers.url);
154160 expect(parent.status).toBe(PARENT_STATUS);
155161 const linked = await post("/settings/edge/link", {}, servers.url);
test/account-refusals.test.ts +2
@@ -8,6 +8,7 @@ import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
11 import { setSsh } from "../src/settings/ssh.ts";
1112 import { createUser } from "../src/core/users.ts";
1213 import { serve, type Servers } from "../src/http/server.ts";
1314
@@ -20,6 +21,7 @@ describe("account refusals", () => {
2021 beforeAll(async () => {
2122 dataDir = await mkdtemp(join(tmpdir(), "forge-account-refusals-"));
2223 app = createApp({ dataDir, port: 0 });
24 setSsh(app.db, true, "test");
2325 servers = await serve(app);
2426 const made = await createUser(app.db, {
2527 origin: "seed",
test/account-rows.test.ts +5 −1
@@ -1,9 +1,12 @@
1 /** Settings › Account is rows under headings, not cards, and its tokens and keys are lists (#9706). */
1 /**
2 * Settings › Account is rows under headings, not cards, and its tokens and keys are lists (#9706).
3 */
24 import { afterAll, beforeAll, expect, test } from "bun:test";
35 import { mkdtemp, rm } from "node:fs/promises";
46 import { tmpdir } from "node:os";
57 import { join } from "node:path";
68 import { createApp, type App } from "../src/app.ts";
9 import { setSsh } from "../src/settings/ssh.ts";
710 import { serve, type Servers } from "../src/http/server.ts";
811 import { getUserByName } from "../src/core/users.ts";
912 import { createToken } from "../src/core/tokens.ts";
@@ -20,6 +23,7 @@ const KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9o
2023 beforeAll(async () => {
2124 dir = await mkdtemp(join(tmpdir(), "forge-acctrows-"));
2225 app = createApp({ dataDir: dir, port: 0 });
26 setSsh(app.db, true, "test");
2327 servers = await serve(app);
2428 base = servers.url;
2529 const signup = await fetch(`${base}/signup`, {
test/agent-card.test.ts +3 −1
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { moreAfterSignIn, TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
77 import { createApp } from "../src/app.ts";
8 import { setSsh } from "../src/settings/ssh.ts";
89 import { TOOLS } from "../src/http/mcp/tools.ts";
910 import { OFFER_TOOL, REPORT_TOOL, START_TOOL } from "../src/http/mcp.ts";
1011 import { createUser } from "../src/core/users.ts";
@@ -20,6 +21,7 @@ describe("the agent card", () => {
2021 beforeAll(async () => {
2122 dataDir = await mkdtemp(join(tmpdir(), "forge-agent-card-"));
2223 app = createApp({ dataDir, port: 0 });
24 setSsh(app.db, true, "test");
2325 servers = await serve(app);
2426 base = servers.url;
2527 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "cardreader", email: "[email protected]", password: "correct horse battery 1", isAdmin: false });
@@ -104,6 +106,6 @@ describe("the agent card", () => {
104106 const more = card.skills.at(-1).description.match(/^(\d+) more tools/)[1];
105107 const llms = await (await fetch(`${base}/llms.txt`)).text();
106108 expect(llms).toContain(`- ${more} more tools with an account`);
107 expect(Number(more)).toBe(moreAfterSignIn());
109 expect(Number(more)).toBe(moreAfterSignIn(true));
108110 });
109111 });
test/api-keys-timing.test.ts +2
@@ -4,6 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
7 import { setSsh } from "../src/settings/ssh.ts";
78 import { createSession } from "../src/core/sessions.ts";
89 import { createUser } from "../src/core/users.ts";
910 import { serve, type Servers } from "../src/http/server.ts";
@@ -23,6 +24,7 @@ beforeAll(async () => {
2324 process.env["FORGE_CELLS"] = "off";
2425 dataDir = await mkdtemp(join(tmpdir(), "forge-api-keys-timing-"));
2526 app = createApp({ dataDir, port: 0 });
27 setSsh(app.db, true, "test");
2628 servers = await serve(app);
2729 const made = await createUser(app.db, {
2830 origin: "seed",
test/apps-door.test.ts +2
@@ -5,6 +5,7 @@ import { mkdtemp, rm } from "node:fs/promises";
55 import { tmpdir } from "node:os";
66 import { join } from "node:path";
77 import { createApp, type App } from "../src/app.ts";
8 import { setSsh } from "../src/settings/ssh.ts";
89 import { newApp } from "../src/actions/apps.ts";
910 import { doorPage } from "../src/apps/door.ts";
1011 import type { PillWhere } from "../src/apps/toolbar.ts";
@@ -32,6 +33,7 @@ let pull: number;
3233 beforeAll(async () => {
3334 dataDir = await mkdtemp(join(tmpdir(), "forge-door-"));
3435 app = createApp({ dataDir, port: 0, host: "forge.test" });
36 setSsh(app.db, true, "test");
3537 servers = await serve(app);
3638 runtime = new AppsRuntime(app, {
3739 domain: DOMAIN,
test/capacity.test.ts +7
@@ -13,6 +13,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1313 import { tmpdir } from "node:os";
1414 import { join } from "node:path";
1515 import { createApp, type App } from "../src/app.ts";
16 import { setSsh } from "../src/settings/ssh.ts";
1617 import { changeCapacity, listCapacity } from "../src/actions/capacity.ts";
1718 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1819 import { assignIssue, openIssue } from "../src/actions/issues.ts";
@@ -107,6 +108,7 @@ describe("capacity: only a forge admin reads or changes it", () => {
107108 beforeAll(async () => {
108109 dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-"));
109110 app = createApp({ dataDir, port: 0 });
111 setSsh(app.db, true, "test");
110112 servers = await serve(app);
111113 const a = await createUser(app.db, {
112114 origin: "seed",
@@ -379,6 +381,7 @@ describe("report mode is loud to admins, and to nobody else", () => {
379381 beforeAll(async () => {
380382 dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-loud-"));
381383 app = createApp({ dataDir, port: 0 });
384 setSsh(app.db, true, "test");
382385 servers = await serve(app);
383386 const a = await createUser(app.db, {
384387 origin: "seed",
@@ -539,6 +542,7 @@ describe("the default shown, and gone back to, is the one the service booted wit
539542 test("a crew booted at one shows one, and a reset returns it there", async () => {
540543 const dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-boot-"));
541544 const app = createApp({ dataDir, port: 0 });
545 setSsh(app.db, true, "test");
542546 try {
543547 const a = await createUser(app.db, {
544548 origin: "seed",
@@ -615,6 +619,7 @@ describe("the next check honours a concurrency the admin lowered, and gets the s
615619 beforeAll(async () => {
616620 dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-checks-"));
617621 app = createApp({ dataDir, port: 0 });
622 setSsh(app.db, true, "test");
618623 servers = await serve(app);
619624 // Booted at three at once.
620625 checks = startChecks(app, { forgeUrl: servers.url, concurrency: 3 });
@@ -706,6 +711,7 @@ describe("the crew's concurrency and shard count reach the next pick", () => {
706711 beforeAll(async () => {
707712 dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-crew-"));
708713 app = createApp({ dataDir, port: 0 });
714 setSsh(app.db, true, "test");
709715 servers = await serve(app);
710716 const fake = join(dataDir, "fake-claude");
711717 writeFileSync(
@@ -820,6 +826,7 @@ describe("the egress mode is the emergency lever: the next cell starts with what
820826 test("report → enforce reaches the next start's cell without a restart", async () => {
821827 const dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-egress-"));
822828 const app = createApp({ dataDir, port: 0 });
829 setSsh(app.db, true, "test");
823830 const runtime = new AppsRuntime(app, {
824831 domain: "cap.test",
825832 scheme: "http",
test/engine-crossing.test.ts +1
@@ -233,6 +233,7 @@ const whole = (dataDir: string): Required<ForgeConfig> => ({
233233 turnstileSiteKey: "not-a-site-key",
234234 verifyHuman: async () => true,
235235 appSsh: "ssh -p 2222 forge.test",
236 sshReachable: true,
236237 notesIntent: "docs/intent.md",
237238 forgeRepo: "trevato/forge",
238239 parentUrl: "https://parent.test",
test/features-tui.test.ts +16
@@ -4,6 +4,7 @@
44 * and un-absorbs, and a setting is saved or refused as on the page; anyone
55 * else is not offered it.
66 */
7 import { sshOn } from "../src/settings/ssh.ts";
78 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
89 import { mkdtemp, rm } from "node:fs/promises";
910 import { tmpdir } from "node:os";
@@ -86,6 +87,21 @@ describe("features in the terminal", () => {
8687 await rm(dir, { recursive: true, force: true });
8788 });
8889
90 test("the SSH switch is the last row: a turns it on and off, and the toast says which", async () => {
91 const t = boot(ada);
92 await t.palette();
93 await t.press("enter");
94 expect(t.text()).toContain("SSH the forge's own switch");
95 await t.press("j");
96 await t.press("a");
97 await t.until("SSH is on");
98 expect(sshOn(forge.db)).toBe(true);
99 await t.press("a");
100 await t.until("SSH is off");
101 expect(sshOn(forge.db)).toBe(false);
102 t.stop();
103 });
104
89105 test("only a site admin is offered the entry", async () => {
90106 const other = boot(eve);
91107 await other.palette();
test/helpers/apps-forge.ts +2
@@ -9,6 +9,7 @@ import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { createApp, type App } from "../../src/app.ts";
12 import { setSsh } from "../../src/settings/ssh.ts";
1213 import { newApp } from "../../src/actions/apps.ts";
1314 import { AppsRuntime } from "../../src/apps/runtime.ts";
1415 import type { AppRecord } from "../../src/core/apps.ts";
@@ -49,6 +50,7 @@ export async function startAppsForge(
4950 const dataDir = await mkdtemp(join(tmpdir(), "forge-apps-"));
5051 const work = await mkdtemp(join(tmpdir(), "forge-apps-work-"));
5152 const app = createApp({ dataDir, port: 0 });
53 setSsh(app.db, true, "test");
5254 const servers = await serve(app);
5355 // Every app the runtime boots is handed this key; the tests sign as
5456 // the forge would.
test/home-terminal-block.test.ts +2
@@ -4,6 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
7 import { setSsh } from "../src/settings/ssh.ts";
78 import { serve, type Servers } from "../src/http/server.ts";
89 import { sshCommand } from "../src/ssh/command.ts";
910 import { adminCookie } from "./helpers/admin.ts";
@@ -13,6 +14,7 @@ async function boot(sshPort?: number) {
1314 const dataDir = await mkdtemp(join(tmpdir(), "forge-home-term-"));
1415 dirs.push(dataDir);
1516 const app: App = createApp({ dataDir, port: 0, host: "forge.example" });
17 setSsh(app.db, true, "test");
1618 if (sshPort !== undefined) app.config.sshPort = sshPort;
1719 const servers: Servers = await serve(app);
1820 const cookie = await adminCookie(app, { username: "ada", email: "[email protected]", password: "analytical-engine" });
test/llms-anonymous.test.ts +2
@@ -4,6 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp } from "../src/app.ts";
7 import { setSsh } from "../src/settings/ssh.ts";
78 import { serve, type Servers } from "../src/http/server.ts";
89 import { createToken } from "../src/core/tokens.ts";
910 import { createUser } from "../src/core/users.ts";
@@ -17,6 +18,7 @@ let token: string;
1718 beforeAll(async () => {
1819 dataDir = await mkdtemp(join(tmpdir(), "forge-llms-anon-"));
1920 app = createApp({ dataDir, port: 0 });
21 setSsh(app.db, true, "test");
2022 servers = await serve(app);
2123 const made = await createUser(app.db, {
2224 origin: "seed",
test/llms-tools.test.ts +6 −1
@@ -1,10 +1,14 @@
1 /** /llms.txt's `## MCP tools` section is the generated tool index and `report`, line for line, each by its `doc`. */
1 /**
2 * /llms.txt's `## MCP tools` section is the generated tool index and `report`, line for line, each
3 * by its `doc`.
4 */
25 import { TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
36 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
47 import { mkdtemp, rm } from "node:fs/promises";
58 import { tmpdir } from "node:os";
69 import { join } from "node:path";
710 import { createApp } from "../src/app.ts";
11 import { setSsh } from "../src/settings/ssh.ts";
812 import { serve, type Servers } from "../src/http/server.ts";
913 import { OFFER_TOOL, REPORT_TOOL, START_TOOL } from "../src/http/mcp.ts";
1014 import { TOOLS } from "../src/http/mcp/tools.ts";
@@ -20,6 +24,7 @@ describe("/llms.txt MCP tools", () => {
2024 beforeAll(async () => {
2125 dataDir = await mkdtemp(join(tmpdir(), "forge-llms-tools-"));
2226 const app = createApp({ dataDir, port: 0 });
27 setSsh(app.db, true, "test");
2328 servers = await serve(app);
2429 const made = await createUser(app.db, {
2530 origin: "seed",
test/mcp-card-plugins.test.ts +1 −1
@@ -116,6 +116,6 @@ test("the upstream stands in while the own repository is private or unset, and w
116116 expect(offeredPluginRepo(bare.db, undefined, undefined)).toBeUndefined();
117117 expect(offeredPluginRepo(app.db, "trevato/forge", undefined)).toBeUndefined();
118118 const { mcpCard } = await import("../src/core/mcp_card.ts");
119 expect(mcpCard("http://x.test", undefined).plugins.map((p: any) => p.harness)).toEqual(["opencode"]);
119 expect(mcpCard("http://x.test", undefined, false).plugins.map((p: any) => p.harness)).toEqual(["opencode"]);
120120 bare.close();
121121 });
test/mcp-card.test.ts +3 −3
@@ -75,8 +75,8 @@ describe("the MCP server card", () => {
7575
7676 test("carries the commit it runs, or null when nothing says", () => {
7777 const sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
78 expect(mcpCard("https://x", "trevato/forge", running({ FORGE_APP_COMMIT: sha })).commit).toBe(sha);
79 expect(mcpCard("https://x", "trevato/forge", running({})).commit).toBeNull();
78 expect(mcpCard("https://x", "trevato/forge", false, running({ FORGE_APP_COMMIT: sha })).commit).toBe(sha);
79 expect(mcpCard("https://x", "trevato/forge", false, running({})).commit).toBeNull();
8080 });
8181
8282 test("the live card's commit is what running() says", async () => {
@@ -99,7 +99,7 @@ describe("the MCP server card", () => {
9999 describe("the cards the server card names", () => {
100100 test("every tool in CARD_OF_TOOL is listed under its card's resource", async () => {
101101 const { CARD_OF_TOOL, CARD_URI } = await import("../src/web/studio/cards.ts");
102 const card = mcpCard("https://x", undefined, running({}));
102 const card = mcpCard("https://x", undefined, false, running({}));
103103 for (const [tool, kind] of Object.entries(CARD_OF_TOOL)) {
104104 const entry = card.cards.find((c) => c.resource === CARD_URI(kind));
105105 expect(entry?.tools).toContain(tool);
test/mcp-ssh-keys.test.ts +2
@@ -7,6 +7,7 @@ import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
1011 import { listKeys } from "../src/core/keys.ts";
1112 import { createToken } from "../src/core/tokens.ts";
1213 import { createUser, getUserByName } from "../src/core/users.ts";
@@ -51,6 +52,7 @@ describe("MCP ssh_keys", () => {
5152 beforeAll(async () => {
5253 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-keys-"));
5354 app = createApp({ dataDir, port: 0 });
55 setSsh(app.db, true, "test");
5456 servers = await serve(app);
5557 const mk = async (username: string) => {
5658 const u = await createUser(app.db, {
test/mcp-table.test.ts +2
@@ -5,6 +5,7 @@ import { mkdtemp, rm } from "node:fs/promises";
55 import { tmpdir } from "node:os";
66 import { join } from "node:path";
77 import { createApp } from "../src/app.ts";
8 import { setSsh } from "../src/settings/ssh.ts";
89 import { createToken } from "../src/core/tokens.ts";
910 import { createUser } from "../src/core/users.ts";
1011 import { serve } from "../src/http/server.ts";
@@ -60,6 +61,7 @@ test("withTable round-trips and refuses a doc with a missing or misordered marke
6061 test("the bytes are those of an admin's real tools/list response", async () => {
6162 const dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-table-"));
6263 const app = createApp({ dataDir, port: 0 });
64 setSsh(app.db, true, "test");
6365 const servers = await serve(app);
6466 try {
6567 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-table-passphrase", isAdmin: true });
test/mcp-write-scope.test.ts +2
@@ -10,6 +10,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1010 import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
13 import { setSsh } from "../src/settings/ssh.ts";
1314 import { createToken } from "../src/core/tokens.ts";
1415 import { createRepo } from "../src/actions/repos.ts";
1516 import { createUser } from "../src/core/users.ts";
@@ -70,6 +71,7 @@ describe("a token that may only read cannot write through any tool", () => {
7071 beforeAll(async () => {
7172 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-scope-"));
7273 app = createApp({ dataDir, port: 0 });
74 setSsh(app.db, true, "test");
7375 servers = await serve(app);
7476 const made = await createUser(app.db, {
7577 origin: "seed",
test/mcp.test.ts +2
@@ -12,6 +12,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1212 import { tmpdir } from "node:os";
1313 import { join } from "node:path";
1414 import { createApp, type App } from "../src/app.ts";
15 import { setSsh } from "../src/settings/ssh.ts";
1516 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1617 import { pullDir } from "../src/core/pulls.ts";
1718 import { resolveOid } from "../src/git/merge.ts";
@@ -96,6 +97,7 @@ describe("the forge over MCP", () => {
9697 beforeAll(async () => {
9798 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-"));
9899 app = createApp({ dataDir, port: 0 });
100 setSsh(app.db, true, "test");
99101 servers = await serve(app);
100102 base = servers.url;
101103 const a = await createUser(app.db, { origin: "seed", trusted: true,
test/palette-repos.test.ts +3
@@ -7,6 +7,7 @@ import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
1011 import { createRepo } from "../src/actions/repos.ts";
1112 import { search } from "../src/actions/search.ts";
1213 import { createApp as createAppRecord } from "../src/core/apps.ts";
@@ -26,6 +27,7 @@ let cookie = "";
2627 beforeAll(async () => {
2728 dataDir = await mkdtemp(join(tmpdir(), "forge-palette-repos-"));
2829 app = createApp({ dataDir, port: 0 });
30 setSsh(app.db, true, "test");
2931 servers = await serve(app);
3032 const pw = "a-long-palette-passphrase";
3133 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "trevato", email: "[email protected]", password: pw, adminIfFirst: true });
@@ -124,6 +126,7 @@ test("a visitor's palette holds places to go and Sign in; a signed-in one holds
124126 test("the palette's Sign in leads where the topbar's button does, on an edge-login forge too", async () => {
125127 const edgeDir = await mkdtemp(join(tmpdir(), "forge-palette-edge-"));
126128 const edgeApp = createApp({ dataDir: edgeDir, port: 0, edgeToken: "edge-secret-for-palette" });
129 setSsh(edgeApp.db, true, "test");
127130 const edgeServers = await serve(edgeApp);
128131 try {
129132 const items = async (headers: Record<string, string> = {}) => {
test/palette-roster.test.ts +3
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { setSsh } from "../src/settings/ssh.ts";
67 import { createUser, type User } from "../src/core/users.ts";
78 import { forgeCommands, Session } from "../src/tui/forge.ts";
89 import { quietLogs } from "./helpers/globals.ts";
@@ -26,6 +27,7 @@ const roster = (user?: User) =>
2627 beforeAll(async () => {
2728 dir = await mkdtemp(join(tmpdir(), "forge-palette-roster-"));
2829 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
30 setSsh(app.db, true, "test");
2931 const mk = async (username: string, isAdmin: boolean) => {
3032 const r = await createUser(app.db, {
3133 origin: "seed",
@@ -512,6 +514,7 @@ describe("on a pull's Files step the palette lists what the page offers this rea
512514 beforeAll(async () => {
513515 pdir = await mkdtemp(join(tmpdir(), "forge-palette-pull-"));
514516 papp = createApp({ dataDir: pdir, port: 0, host: "forge.test" });
517 setSsh(papp.db, true, "test");
515518 servers = await serve(papp);
516519 const mk = async (username: string, adminIfFirst: boolean) => {
517520 const r = await createUser(papp.db, {
test/plugin-routes.test.ts +1 −1
@@ -79,7 +79,7 @@ test("llms.txt and the card print opencodeInstall, never the code host", async (
7979 expect(llms).toContain(cmd);
8080 expect(llms).not.toMatch(/OpenCode[^\n]*forge\.open-platform\.sh/);
8181 expect(llms).not.toMatch(/raw\/main\/plugins\/opencode/);
82 const card = mcpCard(servers.url, "trevato/forge");
82 const card = mcpCard(servers.url, "trevato/forge", false);
8383 expect(card.plugins.find((p: any) => p.harness === "opencode")?.install).toBe(cmd);
8484 });
8585
test/repo-about-card.test.ts +2
@@ -8,6 +8,7 @@ import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createRepo } from "../src/actions/repos.ts";
1010 import { createApp, type App } from "../src/app.ts";
11 import { setSsh } from "../src/settings/ssh.ts";
1112 import { createUser } from "../src/core/users.ts";
1213 import { repoDir } from "../src/git/repos.ts";
1314 import { commitFiles } from "../src/git/write.ts";
@@ -23,6 +24,7 @@ let servers: Servers;
2324 beforeAll(async () => {
2425 dataDir = await mkdtemp(join(tmpdir(), "forge-about-card-"));
2526 app = createApp({ dataDir, port: 0, host: "forge.test" });
27 setSsh(app.db, true, "test");
2628 servers = await serve(app);
2729 const made = await createUser(app.db, {
2830 origin: "seed",
test/repo-head-quiet.test.ts +14 −6
@@ -1,8 +1,12 @@
1 /** The repository head at rest (#8774): few tabs, the rest in "More", nothing lost, and every step in the palette. */
1 /**
2 * The repository head at rest (#8774): few tabs, the rest in "More", nothing lost, and every step
3 * in the palette.
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { forkRepo } from "../src/actions/repos.ts";
47 import { rememberSpec } from "../src/apps/api_spec.ts";
58 import { createApp } from "../src/core/apps.ts";
9 import { setSsh } from "../src/settings/ssh.ts";
610 import { snappyFixture, type SnappyFixture } from "../bench/snappy.ts";
711
812 let f: SnappyFixture;
@@ -13,10 +17,12 @@ afterAll(async () => {
1317 await f.close();
1418 });
1519
16 // Bytes of the repository head on the snappy fixture as the owner: [before it folded its rare steps away (#8802), measured now plus room].
17 // Only the head is weighed: it is what this test is about, and it holds no port, clock or host, so the verdict is the head's code
18 // and nothing else. Weighing the whole page tripped every pull that added a few bytes to the top bar, the palette or a list (#8991).
19 // The head now weighs 2,700 bytes on each page, the shortcut keys beside its tabs (#8895) included; the budget leaves ~100 bytes for one more.
20 // Bytes of the repository head on the snappy fixture as the owner: [before it folded its rare steps
21 // away (#8802), measured now plus room]. Only the head is weighed: it is what this test is about,
22 // and it holds no port, clock or host, so the verdict is the head's code and nothing else. Weighing
23 // the whole page tripped every pull that added a few bytes to the top bar, the palette or a list
24 // (#8991). The head now weighs 2,700 bytes on each page, the shortcut keys beside its tabs (#8895)
25 // included; the budget leaves ~100 bytes for one more.
2026 const HEAD_BYTES = { before: 3_808, budget: 2_800 };
2127 const PATHS = ["", "/issues", "/pulls"];
2228
@@ -73,6 +79,7 @@ test("the palette holds the head's links and no others, for the owner, a reader
7379 if (!made.ok) throw new Error(made.error);
7480 rememberSpec(made.value.id, { openapi: "3.0.0", paths: {} });
7581 (f.app.config as { appSsh?: string }).appSsh = "ssh -p 2222 three@localhost";
82 setSsh(f.app.db, true, "test");
7683
7784 const plainBase = `/${plain.ownerName}/${plain.name}`;
7885 const appBase = `/${appRepo.ownerName}/${appRepo.name}`;
@@ -83,7 +90,8 @@ test("the palette holds the head's links and no others, for the owner, a reader
8390 const page = await asViewer(who, `${base}${path}`);
8491 const links = headLinks(page);
8592 expect(links.length).toBeGreaterThan(3);
86 // Nothing the head offers is missing from the palette, nothing the head hides leaks into it.
93 // Nothing the head offers is missing from the palette, nothing the head hides leaks into
94 // it.
8795 expect([`${who} ${base}${path}`, ...stepRows(page)]).toEqual([`${who} ${base}${path}`, ...links]);
8896 if (path === "") seen.set(`${who} ${base}`, links);
8997 }
test/server-timing-sweep.test.ts +2
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createRepo } from "../src/actions/repos.ts";
1414 import { createApp, type App } from "../src/app.ts";
15 import { setSsh } from "../src/settings/ssh.ts";
1516 import { createUser } from "../src/core/users.ts";
1617 import { buildApiRouter, buildRouter, serve, type Servers } from "../src/http/server.ts";
1718 import { proveAll } from "./helpers/verified.ts";
@@ -86,6 +87,7 @@ let servers: Servers;
8687 beforeAll(async () => {
8788 root = mkdtempSync(join(tmpdir(), "forge-timing-sweep-"));
8889 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
90 setSsh(app.db, true, "test");
8991 const u = await createUser(app.db, {
9092 origin: "seed",
9193 trusted: true,
test/settings-timing.test.ts +6 −1
@@ -1,10 +1,14 @@
1 /** `/settings/keys`, `/settings/tokens` and `/settings/password` name their phases signed in and cost a bounded number of statements (#4316). */
1 /**
2 * `/settings/keys`, `/settings/tokens` and `/settings/password` name their phases signed in and
3 * cost a bounded number of statements (#4316).
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { expectWork, requestStatements } from "./helpers/work.ts";
47 import { mkdtempSync, rmSync } from "node:fs";
58 import { tmpdir } from "node:os";
69 import { join } from "node:path";
710 import { createApp, type App } from "../src/app.ts";
11 import { setSsh } from "../src/settings/ssh.ts";
812 import { createUser } from "../src/core/users.ts";
913 import { serve, type Servers } from "../src/http/server.ts";
1014 import { proveAll } from "./helpers/verified.ts";
@@ -21,6 +25,7 @@ let cookie = "";
2125 beforeAll(async () => {
2226 root = mkdtempSync(join(tmpdir(), "forge-settings-timing-"));
2327 app = createApp({ dataDir: root, port: 0 });
28 setSsh(app.db, true, "test");
2429 const u = await createUser(app.db, {
2530 origin: "seed",
2631 trusted: true,
test/spawn-keys.test.ts +7
@@ -16,6 +16,7 @@ import { join, relative } from "node:path";
1616 import { createRepo } from "../src/actions/repos.ts";
1717 import { childDirOf, STARTER_KEY } from "../src/actions/spawn.ts";
1818 import { createApp, type App } from "../src/app.ts";
19 import { setSsh } from "../src/settings/ssh.ts";
1920 import { getRepo } from "../src/core/repos.ts";
2021 import { createRun } from "../src/core/runs.ts";
2122 import {
@@ -84,6 +85,7 @@ describe("a spawned child's own keys and domain", () => {
8485 beforeAll(async () => {
8586 dir = await mkdtemp(join(tmpdir(), "forge-child-keys-"));
8687 parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
88 setSsh(parent.db, true, "test");
8789 // The parent's own keys, so there is something not to copy.
8890 loadKey(dir);
8991 loadOrCreateHostKey(join(dir, "ssh"));
@@ -222,6 +224,7 @@ describe("a spawned child's own keys and domain", () => {
222224 expect(res.status).toBe(201);
223225 const dir1 = childDirOf(parent, ((await res.json()) as { bodyId: string }).bodyId);
224226 const child = createApp({ dataDir: dir1, port: 0 });
227 setSsh(child.db, true, "test");
225228 try {
226229 expect(getSubscriptionByName(child.db, STARTER_KEY)!.apiBase).toBe("https://x/api");
227230 } finally {
@@ -321,6 +324,7 @@ describe("a spawned child's own keys and domain", () => {
321324
322325 test("the key is sealed with the child's key, opens only there, and is offered to its organisation", () => {
323326 const child = createApp({ dataDir: childDir, port: 0 });
327 setSsh(child.db, true, "test");
324328 try {
325329 const sub = getSubscriptionByName(child.db, STARTER_KEY)!;
326330 expect(sub.kind).toBe("api_key");
@@ -359,6 +363,7 @@ describe("a spawned child's own keys and domain", () => {
359363
360364 test("once the starter budget is spent, a run in the child gets no account: an assigned one, on any repository of its org", async () => {
361365 const child = createApp({ dataDir: childDir, port: 0 });
366 setSsh(child.db, true, "test");
362367 try {
363368 const sub = getSubscriptionByName(child.db, STARTER_KEY)!;
364369 const org = getOrg(child.db, "maria")!;
@@ -387,6 +392,7 @@ describe("a spawned child's own keys and domain", () => {
387392
388393 test("nothing in the child's config points into the parent", async () => {
389394 const child = createApp({ dataDir: childDir, port: 0 });
395 setSsh(child.db, true, "test");
390396 try {
391397 for (const value of [child.config.dataDir, child.reposRoot])
392398 expect(relative(childDir, value).startsWith("..")).toBe(false);
@@ -420,6 +426,7 @@ describe("a spawned child's own keys and domain", () => {
420426 ) as { url: string };
421427 expect(record.url).toBe("https://maria--forge.test");
422428 const child = createApp({ dataDir: childDir, port: 0 });
429 setSsh(child.db, true, "test");
423430 await firstBoot(child);
424431 const childServers = await serve(child);
425432 try {
test/ssh-clone.test.ts +3
@@ -11,6 +11,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createApp, type App } from "../src/app.ts";
14 import { setSsh } from "../src/settings/ssh.ts";
1415 import { serve, type Servers } from "../src/http/server.ts";
1516 import { createRepo } from "../src/actions/repos.ts";
1617 import type { Repo } from "../src/core/repos.ts";
@@ -33,6 +34,7 @@ describe("sshCloneUrl", () => {
3334 beforeAll(async () => {
3435 dataDir = await mkdtemp(join(tmpdir(), "forge-sshclone-"));
3536 app = createApp({ dataDir, port: 0, host: "forge.example" });
37 setSsh(app.db, true, "test");
3638 });
3739
3840 afterAll(async () => {
@@ -84,6 +86,7 @@ describe("the clone address on the repository page, in the terminal and in the p
8486 host: "forge.example",
8587 url: "https://forge.example",
8688 });
89 setSsh(app.db, true, "test");
8790 servers = await serve(app);
8891 const ada = await seedAdmin(app, { username: "ada", email: "[email protected]" });
8992 if (!ada.ok) throw new Error(ada.error);
test/ssh-site.test.ts +5
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { setSsh } from "../src/settings/ssh.ts";
67 import { serve, type Servers } from "../src/http/server.ts";
78 import { sshCommand } from "../src/ssh/command.ts";
89 import { adminCookie } from "./helpers/admin.ts";
@@ -11,6 +12,7 @@ describe("sshCommand", () => {
1112 test("is undefined without a listener, and names host and port with one", async () => {
1213 const dataDir = await mkdtemp(join(tmpdir(), "forge-sshcmd-"));
1314 const app = createApp({ dataDir, port: 0, host: "forge.example" });
15 setSsh(app.db, true, "test");
1416 try {
1517 expect(sshCommand(app)).toBeUndefined();
1618 app.config.sshPort = 2222;
@@ -27,6 +29,7 @@ describe("sshCommand", () => {
2729 test("falls back to the public URL's host when no host is configured", async () => {
2830 const dataDir = await mkdtemp(join(tmpdir(), "forge-sshcmd-"));
2931 const app = createApp({ dataDir, port: 0, url: "https://forge.example" });
32 setSsh(app.db, true, "test");
3033 try {
3134 app.config.sshPort = 2222;
3235 expect(sshCommand(app)).toBe("ssh -p 2222 forge.example");
@@ -47,6 +50,7 @@ describe("the terminal on the website", () => {
4750 beforeAll(async () => {
4851 dataDir = await mkdtemp(join(tmpdir(), "forge-ssh-site-"));
4952 app = createApp({ dataDir, port: 0, host: "forge.example" });
53 setSsh(app.db, true, "test");
5054 app.config.sshPort = 2222;
5155 app.config.sshHostKey =
5256 "SHA256:abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
@@ -116,6 +120,7 @@ describe("the front page without a terminal", () => {
116120 test("prints nothing about it and carries no hero classes", async () => {
117121 const dataDir = await mkdtemp(join(tmpdir(), "forge-ssh-off-"));
118122 const app = createApp({ dataDir, port: 0, host: "forge.example" });
123 setSsh(app.db, true, "test");
119124 const servers = await serve(app);
120125 try {
121126 const page = await fetch(`${servers.url}/`).then((r) => r.text());
test/ssh-switch-page.test.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * Settings › Features: the SSH row says what it is for in one sentence, and turning it says what
3 * happened.
4 */
5
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { sshOn, SSH_GIVES } from "../src/settings/ssh.ts";
14 import { followSsh } from "../src/ssh/switch.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dataDir = "";
20 let app: App;
21 let servers: Servers;
22 let cookie = "";
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-ssh-page-"));
26 app = createApp({ dataDir, port: 0, host: "forge.test" });
27 servers = await serve(app);
28 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
29 if (!made.ok) throw new Error(made.error);
30 const signed = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "ada", password: "a-good-passphrase" }), redirect: "manual" });
31 cookie = `${(signed.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=dev`;
32 }, 60_000);
33
34 afterAll(async () => {
35 servers?.stop();
36 app?.close();
37 if (dataDir) await rm(dataDir, { recursive: true, force: true });
38 });
39
40 const turn = (to: "absorb" | "unabsorb") =>
41 fetch(`${servers.url}/settings/features/ssh/${to}`, { method: "POST", headers: { cookie, origin: servers.url }, redirect: "manual" });
42 const flashOf = (r: Response): string => decodeURIComponent((r.headers.get("location") ?? "") + (r.headers.get("set-cookie") ?? "")).replace(/\+/g, " ");
43
44 test("the row says what SSH is for, in plain words and no port detail", async () => {
45 const page = await (await fetch(`${servers.url}/settings/features`, { headers: { cookie } })).text();
46 expect(page).toContain(SSH_GIVES.replace("'", "&#39;"));
47 expect(page).not.toContain("FORGE_SSH_PORT");
48 });
49
50 test("turning it on and off says so; a listener that did not start is said too", async () => {
51 expect(flashOf(await turn("absorb"))).toContain("SSH is on");
52 expect(sshOn(app.db)).toBe(true);
53 expect(flashOf(await turn("unabsorb"))).toContain("SSH is off");
54 expect(flashOf(await turn("unabsorb"))).not.toContain("any more");
55 followSsh(app, { follow: async (on) => (on ? "port 2222 could not be opened: in use" : undefined), listening: () => false });
56 const failed = flashOf(await turn("absorb"));
57 expect(failed).toContain("it did not start");
58 expect(failed).toContain("port 2222 could not be opened");
59 expect(sshOn(app.db)).toBe(true);
60 });
61
62 test("a person who is not an admin is told there is no such page", async () => {
63 const r = await fetch(`${servers.url}/settings/features/ssh/absorb`, { method: "POST", headers: { origin: servers.url }, redirect: "manual" });
64 expect(r.status).not.toBe(302);
65 });
test/ssh-switch.test.ts added +113
@@ -0,0 +1,113 @@
1 /**
2 * The SSH switch (#13640): off by default, nothing says ssh; on, the clone box and keys page
3 * return.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { sshRow, switchSsh } from "../src/actions/ssh_switch.ts";
11 import { seedAdmin } from "./helpers/admin.ts";
12 import { migrateSsh, setSsh, sshOn } from "../src/settings/ssh.ts";
13 import { followSsh } from "../src/ssh/switch.ts";
14 import { accountSections } from "../src/web/pages/origins.ts";
15 import { sshCloneUrl, sshCommand } from "../src/ssh/command.ts";
16
17 let dir = "";
18 let app: App;
19 beforeAll(async () => {
20 dir = await mkdtemp(join(tmpdir(), "forge-sshsw-"));
21 app = createApp({ dataDir: dir, port: 0, host: "forge.example" });
22 app.config.sshPort = 2222;
23 app.config.sshHostKey = "SHA256:abc";
24 });
25 afterAll(async () => {
26 app.close();
27 await rm(dir, { recursive: true, force: true });
28 });
29
30 test("off by default: no command, no clone address; on: both; off again: both gone", async () => {
31 expect(sshOn(app.db)).toBe(false);
32 expect(sshCommand(app)).toBeUndefined();
33 expect(sshCloneUrl(app, "ada", "notes")).toBeUndefined();
34 const ada = await seedAdmin(app, { username: "ada", email: "[email protected]" });
35 if (!ada.ok) throw new Error(ada.error);
36 expect(sshRow(app, undefined).ok).toBe(false);
37 const on = await switchSsh(app, ada.value, true);
38 expect(on.ok && on.value.on).toBe(true);
39 expect(sshCommand(app)).toBe("ssh -p 2222 forge.example");
40 expect(sshCloneUrl(app, "ada", "notes")).toContain("ssh://");
41 await switchSsh(app, ada.value, false);
42 expect(sshCommand(app)).toBeUndefined();
43 expect(sshCloneUrl(app, "ada", "notes")).toBeUndefined();
44 });
45
46 test("turning it on says when the listener did not start, and reports what is listening", async () => {
47 const other = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-sshsw2-")), port: 0, host: "forge.example" });
48 const ada = await seedAdmin(other, { username: "ada", email: "[email protected]" });
49 if (!ada.ok) throw new Error(ada.error);
50 let up = false;
51 followSsh(other, { follow: async (on) => (on ? "port 2222 could not be opened: in use" : void (up = false)), listening: () => up });
52 const on = await switchSsh(other, ada.value, true);
53 expect(on.ok && on.value.on).toBe(true);
54 expect(on.ok && on.value.listening).toBe(false);
55 expect(on.ok && on.value.warning).toBe("port 2222 could not be opened: in use");
56 followSsh(other, { follow: async (on) => void (up = on), listening: () => up });
57 const again = await switchSsh(other, ada.value, true);
58 expect(again.ok && again.value.warning).toBeUndefined();
59 expect(again.ok && again.value.listening).toBe(true);
60 const off = await switchSsh(other, ada.value, false);
61 expect(off.ok && off.value.listening).toBe(false);
62 other.close();
63 });
64
65 test("one forge's switch is not another's in the same process", async () => {
66 const a = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-sshsw3-")), port: 0, host: "a.example" });
67 const b = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-sshsw4-")), port: 0, host: "b.example" });
68 const ada = await seedAdmin(a, { username: "ada", email: "[email protected]" });
69 if (!ada.ok) throw new Error(ada.error);
70 await switchSsh(a, ada.value, true);
71 expect(sshOn(a.db)).toBe(true);
72 expect(sshOn(b.db)).toBe(false);
73 expect(accountSections("keys", { admin: true, ssh: sshOn(a.db) }).some((s) => s.href === "/settings/keys")).toBe(true);
74 expect(accountSections("keys", { admin: true, ssh: sshOn(b.db) }).some((s) => s.href === "/settings/keys")).toBe(false);
75 a.close();
76 b.close();
77 });
78
79 test("a forge that already has a host key starts with the switch on; a fresh one stays off", async () => {
80 const old = await mkdtemp(join(tmpdir(), "forge-sshsw5-"));
81 await mkdir(join(old, "ssh"));
82 await writeFile(join(old, "ssh", "host_ed25519"), "x", { mode: 0o600 });
83 const had = createApp({ dataDir: old, port: 0, host: "forge.example" });
84 expect(migrateSsh(had.db, old)).toBe(true);
85 expect(sshOn(had.db)).toBe(true);
86 expect(migrateSsh(had.db, old)).toBe(false);
87 had.close();
88 const fresh = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-sshsw6-")), port: 0, host: "forge.example" });
89 expect(migrateSsh(fresh.db, fresh.config.dataDir)).toBe(false);
90 expect(sshOn(fresh.db)).toBe(false);
91 fresh.close();
92 });
93
94 test("an explicit off survives the migration", async () => {
95 const old = await mkdtemp(join(tmpdir(), "forge-sshsw7-"));
96 await mkdir(join(old, "ssh"));
97 await writeFile(join(old, "ssh", "host_ed25519"), "x", { mode: 0o600 });
98 const had = createApp({ dataDir: old, port: 0, host: "forge.example" });
99 setSsh(had.db, true, "u");
100 setSsh(had.db, false, "u");
101 expect(migrateSsh(had.db, old)).toBe(false);
102 expect(sshOn(had.db)).toBe(false);
103 had.close();
104 });
105
106 test("the how-to's ssh section is in the doc while the switch is on and gone while it is off", async () => {
107 const { readFileSync } = await import("node:fs");
108 const { withSsh } = await import("../src/view/docs.ts");
109 const text = readFileSync("docs/features/absorb.md", "utf8");
110 expect(withSsh(text, true)).toContain("SSH, the forge's own switch");
111 expect(withSsh(text, false)).not.toContain("SSH, the forge's own switch");
112 expect(withSsh(text, true)).not.toContain("<!-- ssh -->");
113 });
test/ssh-tell-discovery.test.ts +6 −1
@@ -1,9 +1,13 @@
1 /** /llms.txt and /api/v1/here name `ssh <forge> tell` when SSH is on, and are silent when off (#6111). */
1 /**
2 * /llms.txt and /api/v1/here name `ssh <forge> tell` when SSH is on, and are silent when off
3 * (#6111).
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
58 import { join } from "node:path";
69 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
711 import { createToken } from "../src/core/tokens.ts";
812 import { createUser } from "../src/core/users.ts";
913 import { createRepo } from "../src/actions/repos.ts";
@@ -18,6 +22,7 @@ let roToken: string;
1822 beforeAll(async () => {
1923 dir = await mkdtemp(join(tmpdir(), "forge-tell-disc-"));
2024 app = createApp({ dataDir: dir, port: 0 });
25 setSsh(app.db, true, "test");
2126 servers = await serve(app);
2227 const made = await createUser(app.db, {
2328 origin: "seed",
test/studio-door.test.ts +2
@@ -22,6 +22,7 @@ import { mkdtemp, rm } from "node:fs/promises";
2222 import { tmpdir } from "node:os";
2323 import { join } from "node:path";
2424 import { createApp, type App } from "../src/app.ts";
25 import { setSsh } from "../src/settings/ssh.ts";
2526 import { enableApp } from "../src/actions/apps.ts";
2627 import { previewEnv, type EnvName } from "../src/apps/data.ts";
2728 import { AppsRuntime } from "../src/apps/runtime.ts";
@@ -63,6 +64,7 @@ beforeAll(async () => {
6364 dataDir = await mkdtemp(join(tmpdir(), "forge-studio-door-"));
6465 // The terminal's block reads its command off this host.
6566 app = createApp({ dataDir, port: 0, host: "forge.example" });
67 setSsh(app.db, true, "test");
6668 servers = await serve(app);
6769 base = servers.url;
6870 runtime = new AppsRuntime(app, {
test/support/deadends-crawl.ts +41 −5
@@ -26,7 +26,7 @@ export interface Edge {
2626 }
2727
2828 export interface Finding {
29 readonly kind: "dead" | "wall" | "anchor" | "no-route" | "error";
29 readonly kind: "dead" | "wall" | "anchor" | "no-route" | "error" | "words";
3030 readonly viewer: ViewerName;
3131 readonly from: string;
3232 readonly edge: EdgeKind;
@@ -59,7 +59,10 @@ export function patternOf(path: string, method = "GET"): string | undefined {
5959 return (api ? apiRouter : pageRouter).match(method, pathname)?.pattern;
6060 }
6161
62 /** A path with its ids folded, for grouping findings: `/alice/forge/issues/3` is `/:owner/:name/issues/:number`. */
62 /**
63 * A path with its ids folded, for grouping findings: `/alice/forge/issues/3` is
64 * `/:owner/:name/issues/:number`.
65 */
6366 export const group = (path: string): string =>
6467 patternOf(path) ?? path.split("?")[0]!.replace(/\d+/g, "N");
6568
@@ -130,7 +133,8 @@ export function formsOf(html: string): Form[] {
130133 required: f.required !== undefined,
131134 });
132135 }
133 // The submit button that carries a name is part of what a click sends (`<button name="by" value="1">`).
136 // The submit button that carries a name is part of what a click sends
137 // (`<button name="by" value="1">`).
134138 for (const b of m[1]!.matchAll(/<button\b[^>]*>/gi)) {
135139 const f = attrs(b[0]);
136140 if (f.name !== undefined && f.disabled === undefined && (f.type ?? "submit") === "submit") {
@@ -269,7 +273,10 @@ export function edgesOf(base: string, html: string, origin: string): Edge[] {
269273
270274 const URL_KEYS = /^(?:page|url|next|href|link|[a-z_]*_url|[a-z_]*_href)$/;
271275
272 /** URL strings in a JSON answer: under keys that name one, and every string of a `links` array or object. */
276 /**
277 * URL strings in a JSON answer: under keys that name one, and every string of a `links` array or
278 * object.
279 */
273280 export function jsonEdges(base: string, text: string, origin: string): Edge[] {
274281 let value: unknown;
275282 try {
@@ -330,7 +337,24 @@ export interface Crawl {
330337 readonly patterns: Set<string>;
331338 }
332339
340 /**
341 * The words the forge says nothing of while its SSH switch is off (`settings/ssh.ts`, #13640): ssh,
342 * a host key, an SSH key, a `git@` or `ssh://` address.
343 */
344 export const SSH_WORDS = /\bssh\b|ssh:\/\/|git@|host key|SSH keys?\b/i;
345
346 /**
347 * Where the words may stay: the switch's own row, the API's contract (every route is listed, and
348 * the keys routes answer "off"), the operator's two pages about the machines and the backups, and
349 * the feature how-tos' index (a list of documents, one of which is about ssh).
350 */
351 const SSH_SWITCH_PAGE = /^\/(?:settings\/features|api|contract|system|resilience|docs\/features)(?:\/|\?|\.|$)/;
352
333353 export const ENTRIES = [
354 "/llms.txt",
355 "/docs/guide-agents.md",
356 "/alice/forge/issues",
357 "/alice/forge/pulls",
334358 "/",
335359 "/signin",
336360 "/signup",
@@ -588,6 +612,15 @@ function judge(
588612 to: path,
589613 text: src?.text ?? "",
590614 };
615 if (a.status < 500 && !SSH_SWITCH_PAGE.test(path) && /html|json|text/.test(a.type)) {
616 const said = SSH_WORDS.exec(a.body);
617 if (said !== null)
618 record({
619 ...base,
620 kind: "words",
621 why: `says "${a.body.slice(Math.max(0, said.index - 30), said.index + 40).replace(/\s+/g, " ")}" while the switch is off`,
622 });
623 }
591624 if (a.status === 599)
592625 return void record({
593626 ...base,
@@ -617,7 +650,10 @@ function judge(
617650 });
618651 }
619652
620 /** The GET page patterns the router holds that no path of this crawl matched: where a crawl is blind. */
653 /**
654 * The GET page patterns the router holds that no path of this crawl matched: where a crawl is
655 * blind.
656 */
621657 export function unreached(c: Crawl): string[] {
622658 const seen = c.patterns;
623659 return [...new Set([...pageRouter.routes(), ...apiRouter.routes()].filter((r) => r.method === "GET").map((r) => r.pattern))].filter((p) => !seen.has(p) && !SKIP.test(p));
test/tui-sshkeys.test.ts +2
@@ -7,6 +7,7 @@ import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
1011 import { addKey, listKeys, parseAuthorizedKey } from "../src/core/keys.ts";
1112 import { createUser, getUserByName } from "../src/core/users.ts";
1213 import { createForgeApp } from "../src/tui/forge.ts";
@@ -74,6 +75,7 @@ describe("Computer keys in the terminal", () => {
7475 beforeAll(async () => {
7576 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-sshkeys-"));
7677 app = createApp({ dataDir, port: 0, host: "forge.test" });
78 setSsh(app.db, true, "test");
7779 for (const [username, first] of [["alice", true], ["bob", false]] as const) {
7880 const made = await createUser(app.db, {
7981 origin: "seed",
test/user-keys-etag.test.ts +6 −1
@@ -1,9 +1,13 @@
1 /** GET /api/v1/user/keys is tagged and answers a repeat 304 until one of the viewer's SSH keys changes (#9243). */
1 /**
2 * GET /api/v1/user/keys is tagged and answers a repeat 304 until one of the viewer's SSH keys
3 * changes (#9243).
4 */
25 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
58 import { join } from "node:path";
69 import { createApp, type App } from "../src/app.ts";
10 import { setSsh } from "../src/settings/ssh.ts";
711 import { addSshKey } from "../src/actions/users.ts";
812 import { deleteKey, touchKey } from "../src/core/keys.ts";
913 import { createToken } from "../src/core/tokens.ts";
@@ -55,6 +59,7 @@ const tagOf = async (who: string) => {
5559 beforeAll(async () => {
5660 dataDir = await mkdtemp(join(tmpdir(), "forge-keys-etag-"));
5761 app = createApp({ dataDir, port: 0 });
62 setSsh(app.db, true, "test");
5863 servers = await serve(app);
5964 const mk = async (username: string, first = false) => {
6065 const r = await createUser(app.db, {
test/user-lists-page.test.ts +6 −1
@@ -1,4 +1,7 @@
1 /** The caller's SSH keys, pins and orgs answer `{ items, next_cursor }` with a bounded limit and a cursor. */
1 /**
2 * The caller's SSH keys, pins and orgs answer `{ items, next_cursor }` with a bounded limit and a
3 * cursor.
4 */
25
36 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
47 import { mkdtemp, rm } from "node:fs/promises";
@@ -9,6 +12,7 @@ import { pinRepo } from "../src/actions/origins.ts";
912 import { createRepo } from "../src/actions/repos.ts";
1013 import { addSshKey, deleteSshKey } from "../src/actions/users.ts";
1114 import { createApp, type App } from "../src/app.ts";
15 import { setSsh } from "../src/settings/ssh.ts";
1216 import { serve, type Servers } from "../src/http/server.ts";
1317 import { seedAdmin } from "./helpers/admin.ts";
1418 import { proveAll } from "./helpers/verified.ts";
@@ -60,6 +64,7 @@ describe("the caller's lists are pages", () => {
6064 beforeAll(async () => {
6165 dir = await mkdtemp(join(tmpdir(), "forge-user-lists-"));
6266 app = createApp({ dataDir: dir, port: 0 });
67 setSsh(app.db, true, "test");
6368 servers = await serve(app);
6469 const a = await seedAdmin(app, {
6570 username: "alice",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs