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

Home devices: declare the LAN printer once; an app with a grant prints through the forge #10419

Parked opened this in answer to
Closed without merging

mason/forge:mason/10413-home-devices-declare-the-lan-printer-onc → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
39 files changed +2204 −68
docs/design/attention-budget.json +2 −2
@@ -109,12 +109,12 @@
109109 },
110110 "settings": {
111111 "390": {
112 "words": 137,
112 "words": 138,
113113 "blocks": 32,
114114 "colours": 1
115115 },
116116 "1280": {
117 "words": 137,
117 "words": 138,
118118 "blocks": 32,
119119 "colours": 1
120120 }
docs/design/audit.md +1
@@ -136,6 +136,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
136136 - `/settings/keys` — `pages/account.ts` · my SSH keys · `/settings/tokens` · colour 1.
137137 - `/settings/passkeys` — `pages/passkeys.ts` · my passkeys · `/settings/password` · none seen.
138138 - `/settings/confirms` — `pages/confirms.ts` · what the forge's agent asked to do and waits for my yes · the terminal's Confirms (y) · none seen.
139 - `/settings/devices` — `pages/devices.ts` · the LAN devices an app may use once granted, declared once by the owner · `/settings/secrets`, `/settings/origins` (other things apps may reach) · none seen.
139140 - `/settings/secrets` — `pages/secrets.ts` · secrets apps may read · none · none seen.
140141 - `/settings/subscriptions` — `pages/subscriptions.ts` (624 lines) · the model subscriptions the crew spends from, with spend tables (`pages/spend.ts`) · `/board/returns` · none seen.
141142 - `/settings/accounts` — `pages/accounts.ts` · every account on the forge · `/settings/people` · none seen.
docs/features/devices.md added +17
@@ -0,0 +1,17 @@
1 # Home devices
2
3 The forge's owner declares a device on this forge's network and grants it to an app; the app prints through the forge. An app gets no other LAN reach: the relay (`src/devices/relay.ts`) takes a declared device, never an address from a caller.
4
5 **Declare** (site admin): `/settings/devices`, or `POST /api/v1/devices {name, kind: "printer", url}`. The URL is an IPP URL on a private IPv4 literal (10.x, 172.16–31.x, 192.168.x), e.g. `ipp://192.168.1.161:631/ipp/print`. Loopback, link-local, the forge's own cluster ranges and host names are refused.
6
7 **Device page**: `/settings/devices/:name` is rendered from the database at once, so a dead printer never holds it: the declared facts, the apps granted (each with its daily cap and use today) and the jobs sent. The printer's state is a separate request, `/settings/devices/:name/status` (a link on the page, no script needed) or `GET /api/v1/devices/:name/status`: IPP Get-Printer-Attributes, one line when fine (`Brother HL-L2350DW · idle · supplies fine`), the reasons and supply levels when not. The printer is asked at most once in 30 s; the device page shows that answer while it is fresh. Removing a device asks first.
8
9 **In the terminal**: palette → Devices (the forge's owner only). `n` declares a device (name, then URL), `enter` opens one (status line, grants with use today, jobs), `g` grants an app (`owner/app` and an optional daily cap), `x` revokes the grant under the cursor, `d` removes the device; the last three ask first. It calls the same actions as the page, so a write there appends the same `device.*` event and web viewers see it live; the screens refresh on those events too. **Over MCP**: the `devices` tool (admin token), actions `list`, `show`, `status`, `declare`, `grant`, `revoke`, `remove`.
10
11 **Grant**: `PUT /api/v1/devices/:name/grants {app: "owner/name", daily_cap}` (default 10 a day); `DELETE` with `{app}` revokes.
12
13 **Print** (an app): `POST $FORGE_API_URL/devices/<name>/print` with `Authorization: Bearer $FORGE_TOKEN` and the PDF as the body. At most 10 MB and 20 pages. Answers `201 {job, state, pages}`; `404` without a grant, `429` over the cap, `422` not a PDF / too many pages, `413` too big, `502` the printer failed. The calling app is the one whose process holds the token (`app:<slug>/<env>`, held by the app's owner). Every job is logged with app, pages and outcome. Refused prints (not a PDF, too big, too long, over the cap) are logged too, but at most 50 a day per app; the log keeps 30 days, and a job left `reserved` by a crash is settled as failed after 10 minutes.
14
15 `FORGE_DEVICE_LOOPBACK=1` lets a developer's fake printer on 127.0.0.1 be declared; tests use it.
16
17 **The page limit is advisory.** The page count is read from the bytes (`/Type /Page` objects and the largest `/Count`), not by a PDF parser, and a crafted file (a small fake `/Count`, page objects hidden in compressed object streams) can read lower than it is. The hard bounds are the 10 MB size and the app's daily cap; the printer enforces the rest. A file whose count reads as zero is refused as unreadable.
src/actions/devices.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * Home devices, as an owner and an app use them (#10413). The owner (a site
3 * admin) declares a device and grants it to an app; an app prints through
4 * the forge with the credential the forge gave its process. Every route,
5 * page and tool calls these; the rules live in `core/devices.ts` and the
6 * wire in `devices/relay.ts`.
7 */
8
9 import type { App } from "../app.ts";
10 import { getAppByRepo, getAppBySlug } from "../core/apps.ts";
11 import {
12 declareDevice,
13 getDevice,
14 grantDevice,
15 listDevices,
16 listGrants,
17 listJobs,
18 removeDevice,
19 revokeDevice,
20 DEFAULT_DAILY_CAP,
21 type Device,
22 type DeviceGrant,
23 type PrintJob,
24 } from "../core/devices.ts";
25 import { getRepo, getRepoById } from "../core/repos.ts";
26 import type { User } from "../core/users.ts";
27 import { probeDevice, printForApp, probeLine, type PrintDone, type PrintError, type Probe } from "../devices/relay.ts";
28 import { err, ok, type Result } from "../kernel/result.ts";
29
30 const siteAdmin = (actor: User | undefined): actor is User => actor !== undefined && actor.isAdmin && actor.kind !== "agent";
31
32 export function deviceList(app: App, actor: User | undefined): Result<Device[], "not_found"> {
33 return siteAdmin(actor) ? ok(listDevices(app.db)) : err("not_found");
34 }
35
36 export interface DeviceView {
37 readonly device: Device;
38 readonly grants: DeviceGrant[];
39 readonly jobs: PrintJob[];
40 }
41
42 /** The device page's declared facts, grants and jobs: rows from the database, no wait on the printer. */
43 export function deviceView(app: App, actor: User | undefined, name: string): Result<DeviceView, "not_found"> {
44 if (!siteAdmin(actor)) return err("not_found");
45 const device = getDevice(app.db, name);
46 if (!device) return err("not_found");
47 return ok({ device, grants: listGrants(app.db, device.id), jobs: listJobs(app.db, device.id) });
48 }
49
50 export interface DeviceStatus {
51 /** One line when fine; null when the printer could not be read. */
52 readonly status: { fine: boolean; line: string } | null;
53 readonly probe: Probe | null;
54 readonly problem: string | null;
55 }
56
57 const STATUS_TTL_MS = 30_000;
58 const statusCache = new Map<string, { at: number; value: Promise<Probed> }>();
59 type Probed = Awaited<ReturnType<typeof probeDevice>>;
60
61 /** The last probe of a device if it is fresh, without asking the printer; undefined otherwise. */
62 export function cachedStatus(device: Device, now = Date.now()): Promise<Probed> | undefined {
63 const hit = statusCache.get(`${device.id} ${device.url}`);
64 return hit && now - hit.at < STATUS_TTL_MS ? hit.value : undefined;
65 }
66
67 /**
68 * Whether the printer is well. One probe per device per half minute, shared by
69 * everyone asking, so a dead printer costs one wait, not one per request.
70 */
71 export async function deviceStatus(app: App, actor: User | undefined, name: string): Promise<Result<DeviceStatus, "not_found">> {
72 if (!siteAdmin(actor)) return err("not_found");
73 const device = getDevice(app.db, name);
74 if (!device) return err("not_found");
75 const key = `${device.id} ${device.url}`;
76 let value = cachedStatus(device);
77 if (!value) {
78 value = probeDevice(device);
79 statusCache.set(key, { at: Date.now(), value });
80 }
81 const probed = await value;
82 return ok({
83 status: probed.ok ? probeLine(probed.value) : null,
84 probe: probed.ok ? probed.value : null,
85 problem: probed.ok ? null : probed.error,
86 });
87 }
88
89 export function declare(app: App, actor: User | undefined, input: { name: string; kind: string; url: string }): Result<Device, string> {
90 if (!siteAdmin(actor)) return err("not_found");
91 const made = declareDevice(app.db, actor, input);
92 if (made.ok) app.bus.append({ kind: "device.declared", actorId: actor.id, payload: { name: made.value.name, kind: made.value.kind } });
93 return made;
94 }
95
96 export function removeDeclared(app: App, actor: User | undefined, name: string): Result<true, string> {
97 if (!siteAdmin(actor)) return err("not_found");
98 if (!removeDevice(app.db, actor, name)) return err("no such device");
99 app.bus.append({ kind: "device.removed", actorId: actor.id, payload: { name } });
100 return ok(true);
101 }
102
103 /** The repository of the app named `owner/name`, or undefined when that names no app. */
104 function appRepoId(app: App, appRef: string): string | undefined {
105 const [owner = "", repoName = ""] = appRef.trim().split("/");
106 const repo = getRepo(app.db, owner, repoName);
107 return repo && getAppByRepo(app.db, repo.id) ? repo.id : undefined;
108 }
109
110 export function grant(app: App, actor: User | undefined, name: string, appRef: string, cap?: number): Result<true, string> {
111 if (!siteAdmin(actor)) return err("not_found");
112 const repoId = appRepoId(app, appRef);
113 if (!repoId) return err("no such app: name it owner/name");
114 const done = grantDevice(app.db, actor, name, repoId, cap ?? DEFAULT_DAILY_CAP);
115 if (done.ok) app.bus.append({ kind: "device.granted", actorId: actor.id, payload: { name, app: appRef.trim(), cap: cap ?? DEFAULT_DAILY_CAP } });
116 return done;
117 }
118
119 export function revoke(app: App, actor: User | undefined, name: string, appRef: string): Result<true, string> {
120 if (!siteAdmin(actor)) return err("not_found");
121 const repoId = appRepoId(app, appRef);
122 if (!repoId || !revokeDevice(app.db, actor, name, repoId)) return err("no such grant");
123 app.bus.append({ kind: "device.revoked", actorId: actor.id, payload: { name, app: appRef.trim() } });
124 return ok(true);
125 }
126
127 /**
128 * Which app is calling: the one whose process holds this token. An app's
129 * token is named `app:<slug>/<env>` and held by the app repository's owner;
130 * the same name on anyone else's token names no app.
131 */
132 export function callingApp(app: App, actor: User | undefined, tokenName: string | undefined): { repoId: string; slug: string } | undefined {
133 const m = actor && tokenName ? /^app:([^/]+)\/.+$/.exec(tokenName) : null;
134 if (!actor || !m) return undefined;
135 const record = getAppBySlug(app.db, m[1]!);
136 const repo = record && getRepoById(app.db, record.repoId);
137 if (!record || !repo || repo.ownerId !== actor.id) return undefined;
138 return { repoId: repo.id, slug: `${repo.ownerName}/${repo.name}` };
139 }
140
141 /** Print a PDF to a declared device for the calling app. A device without a grant is `not_found`. */
142 export async function print(
143 app: App,
144 actor: User | undefined,
145 tokenName: string | undefined,
146 deviceName: string,
147 pdf: Uint8Array | "too_big",
148 ): Promise<Result<PrintDone, PrintError>> {
149 const caller = callingApp(app, actor, tokenName);
150 const device = getDevice(app.db, deviceName);
151 if (!caller || !device) return err({ kind: "no_grant" });
152 const done = await printForApp(app.db, device, caller, pdf);
153 if (done.ok) app.bus.append({ kind: "device.printed", actorId: actor!.id, payload: { device: deviceName, app: caller.slug, pages: done.value.pages } });
154 return done;
155 }
src/contract/openapi/routes/deleteApiV1DevicesName.ts added +8
@@ -0,0 +1,8 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: `/api/v1/devices/{name}`,
6 summary: "Remove a declared device (admin scope); answers {}",
7 auth: true,
8 };
src/contract/openapi/routes/deleteApiV1DevicesNameGrants.ts added +9
@@ -0,0 +1,9 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: `/api/v1/devices/{name}/grants`,
6 summary: "Revoke one app's grant of the device, named in the body (admin scope); answers {}",
7 auth: true,
8 body: { app: "string" },
9 };
src/contract/openapi/routes/getApiV1Devices.ts added +8
@@ -0,0 +1,8 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `/api/v1/devices`,
6 summary: "List the declared home devices (site admin, admin scope); answers { items, next_cursor }",
7 auth: true,
8 };
src/contract/openapi/routes/getApiV1DevicesName.ts added +8
@@ -0,0 +1,8 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `/api/v1/devices/{name}`,
6 summary: "One device: its declared facts, its grants and its jobs, without asking the printer (admin scope)",
7 auth: true,
8 };
src/contract/openapi/routes/getApiV1DevicesNameStatus.ts added +8
@@ -0,0 +1,8 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `/api/v1/devices/{name}/status`,
6 summary: "Whether the printer is well: model, state and supplies in one line (asked at most once in 30 s; admin scope)",
7 auth: true,
8 };
src/contract/openapi/routes/index.ts +8
@@ -6,6 +6,8 @@ export { route as deleteApiV1AgentsUsername } from "./deleteApiV1AgentsUsername.
66 export { route as deleteApiV1BoardsSlug } from "./deleteApiV1BoardsSlug.ts";
77 export { route as deleteApiV1ConversationFilesId } from "./deleteApiV1ConversationFilesId.ts";
88 export { route as deleteApiV1ConversationQueueId } from "./deleteApiV1ConversationQueueId.ts";
9 export { route as deleteApiV1DevicesName } from "./deleteApiV1DevicesName.ts";
10 export { route as deleteApiV1DevicesNameGrants } from "./deleteApiV1DevicesNameGrants.ts";
911 export { route as deleteApiV1FeaturesSlug } from "./deleteApiV1FeaturesSlug.ts";
1012 export { route as deleteApiV1OrgsOrgTeamsTeam } from "./deleteApiV1OrgsOrgTeamsTeam.ts";
1113 export { route as deleteApiV1OrgsOrgTeamsTeamMembersUsername } from "./deleteApiV1OrgsOrgTeamsTeamMembersUsername.ts";
@@ -69,6 +71,9 @@ export { route as getApiV1ConversationTurns } from "./getApiV1ConversationTurns.
6971 export { route as getApiV1Conversations } from "./getApiV1Conversations.ts";
7072 export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts";
7173 export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts";
74 export { route as getApiV1Devices } from "./getApiV1Devices.ts";
75 export { route as getApiV1DevicesName } from "./getApiV1DevicesName.ts";
76 export { route as getApiV1DevicesNameStatus } from "./getApiV1DevicesNameStatus.ts";
7277 export { route as getApiV1Explore } from "./getApiV1Explore.ts";
7378 export { route as getApiV1Family } from "./getApiV1Family.ts";
7479 export { route as getApiV1Features } from "./getApiV1Features.ts";
@@ -251,6 +256,8 @@ export { route as postApiV1ConversationMessages } from "./postApiV1ConversationM
251256 export { route as postApiV1ConversationStop } from "./postApiV1ConversationStop.ts";
252257 export { route as postApiV1ConversationTokens } from "./postApiV1ConversationTokens.ts";
253258 export { route as postApiV1Conversations } from "./postApiV1Conversations.ts";
259 export { route as postApiV1Devices } from "./postApiV1Devices.ts";
260 export { route as postApiV1DevicesNamePrint } from "./postApiV1DevicesNamePrint.ts";
254261 export { route as postApiV1Drills } from "./postApiV1Drills.ts";
255262 export { route as postApiV1FeedChips } from "./postApiV1FeedChips.ts";
256263 export { route as postApiV1FeedInteractions } from "./postApiV1FeedInteractions.ts";
@@ -358,6 +365,7 @@ export { route as putApiV1AdminQuotasKey } from "./putApiV1AdminQuotasKey.ts";
358365 export { route as putApiV1AdminShield } from "./putApiV1AdminShield.ts";
359366 export { route as putApiV1AdminTeamsSlug } from "./putApiV1AdminTeamsSlug.ts";
360367 export { route as putApiV1BoardsSlug } from "./putApiV1BoardsSlug.ts";
368 export { route as putApiV1DevicesNameGrants } from "./putApiV1DevicesNameGrants.ts";
361369 export { route as putApiV1FeaturesSlug } from "./putApiV1FeaturesSlug.ts";
362370 export { route as putApiV1ForgeEconomics } from "./putApiV1ForgeEconomics.ts";
363371 export { route as putApiV1Front } from "./putApiV1Front.ts";
src/contract/openapi/routes/postApiV1Devices.ts added +11
@@ -0,0 +1,11 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `/api/v1/devices`,
6 summary: "Declare a device: a printer by its IPP URL on the LAN (site admin, admin scope); answers 201 with the device",
7 auth: true,
8 status: 201,
9 body: { name: "string", kind: "string", url: "string" },
10 refusals: { invalid: "the name, kind or URL is not acceptable (422)" },
11 };
src/contract/openapi/routes/postApiV1DevicesNamePrint.ts added +11
@@ -0,0 +1,11 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `/api/v1/devices/{name}/print`,
6 summary:
7 "Print: the body is a PDF (at most 10 MB and 20 pages), sent with an app's own token; answers 201 { job, state, pages }; 404 without a grant, 429 over the daily cap",
8 auth: true,
9 status: 201,
10 refusals: { not_pdf: "the body is not a PDF (422)", too_long: "more than 20 pages (422)" },
11 };
src/contract/openapi/routes/putApiV1DevicesNameGrants.ts added +10
@@ -0,0 +1,10 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `/api/v1/devices/{name}/grants`,
6 summary: "Grant the device to an app with its daily cap, default 10 (admin scope); answers {}",
7 auth: true,
8 body: { app: "string", daily_cap: "number" },
9 refusals: { invalid: "`app` or `daily_cap` is not acceptable (422)" },
10 };
src/core/devices.ts added +287
@@ -0,0 +1,287 @@
1 /**
2 * Home devices (#10413): a device the forge's owner declares (kind
3 * `printer`, an IPP URL on the LAN), the grant of it to one app with that
4 * app's daily cap, and the log of every job an app sent. This is the only
5 * list of addresses the forge will ever carry an app's bytes to: the relay
6 * reads a URL from here and from nowhere else.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { isIP } from "node:net";
11 import { id } from "../kernel/id.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13 import { inCidrs, parseCidrs } from "../kernel/cidr.ts";
14 import { neverGrantable } from "./egress_grants.ts";
15
16 export const DEFAULT_DAILY_CAP = 10;
17 export const MAX_DAILY_CAP = 1000;
18 export const DEVICE_KINDS = ["printer"] as const;
19
20 export interface Device {
21 readonly id: string;
22 readonly name: string;
23 readonly kind: string;
24 readonly url: string;
25 readonly createdAt: string;
26 }
27
28 export interface DeviceGrant {
29 readonly deviceId: string;
30 readonly repoId: string;
31 readonly app: string;
32 readonly dailyCap: number;
33 readonly usedToday: number;
34 }
35
36 export type JobOutcome = "reserved" | "accepted" | "failed" | "over_cap" | "too_big" | "too_long" | "not_pdf";
37
38 export interface PrintJob {
39 readonly id: string;
40 readonly app: string;
41 readonly pages: number;
42 readonly outcome: JobOutcome;
43 readonly jobState: string | null;
44 readonly createdAt: string;
45 }
46
47 const NAME_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
48 const LAN = parseCidrs("10.0.0.0/8,172.16.0.0/12,192.168.0.0/16");
49
50 /** Loopback is a LAN only for a developer's fake printer (`FORGE_DEVICE_LOOPBACK=1`). */
51 const loopbackAllowed = (): boolean => process.env["FORGE_DEVICE_LOOPBACK"] === "1";
52
53 /** Whether an IPv4 literal is a private LAN address the forge may be pointed at. */
54 export function lanAddress(host: string): boolean {
55 if (isIP(host) !== 4) return false;
56 if (loopbackAllowed() && host.startsWith("127.")) return true;
57 if (neverGrantable(host)) return false;
58 return LAN.ok && inCidrs(host, LAN.value);
59 }
60
61 export interface Endpoint {
62 /** The printer-uri to send in the request (`ipp://host:port/path`). */
63 readonly uri: string;
64 /** Where the HTTP request goes. */
65 readonly http: string;
66 readonly host: string;
67 }
68
69 /** An IPP URL on a private IPv4 literal, or why not. No names: a name can be re-pointed. */
70 export function parseDeviceUrl(text: string): Result<Endpoint, string> {
71 let url: URL;
72 try {
73 url = new URL(text.trim());
74 } catch {
75 return err("the URL must look like ipp://192.168.1.161:631/ipp/print");
76 }
77 if (url.protocol !== "ipp:" && url.protocol !== "http:")
78 return err("the URL must start with ipp:// (or http:// for a printer that speaks IPP there)");
79 if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "")
80 return err("the URL carries no credentials, query or fragment");
81 const host = url.hostname;
82 if (isIP(host) !== 4) return err("the URL names the printer by its IPv4 address, like 192.168.1.161");
83 if (!lanAddress(host))
84 return err(`${host} is not a private LAN address (10.x, 172.16–31.x or 192.168.x); the forge will not carry a job there`);
85 const port = url.port === "" ? (url.protocol === "ipp:" ? 631 : 80) : Number(url.port);
86 const path = url.pathname === "" ? "/" : url.pathname;
87 if (path.length > 200 || !/^[\x21-\x7e]+$/.test(path)) return err("that path is not one a printer uses");
88 return ok({ uri: `ipp://${host}:${port}${path}`, http: `http://${host}:${port}${path}`, host });
89 }
90
91 export function parseDeviceName(text: string): Result<string, string> {
92 const name = text.trim().toLowerCase();
93 return NAME_RE.test(name) ? ok(name) : err("a device name is lowercase letters, digits and dashes, up to 40");
94 }
95
96 export function declareDevice(
97 db: Database,
98 admin: { id: string; isAdmin: boolean },
99 input: { name: string; kind: string; url: string },
100 ): Result<Device, string> {
101 if (!admin.isAdmin) return err("only the forge's owner declares a device");
102 const name = parseDeviceName(input.name);
103 if (!name.ok) return name;
104 if (!(DEVICE_KINDS as readonly string[]).includes(input.kind)) return err("the only kind of device is: printer");
105 const endpoint = parseDeviceUrl(input.url);
106 if (!endpoint.ok) return endpoint;
107 if (getDevice(db, name.value)) return err("a device by that name is already declared");
108 const deviceId = id();
109 db.query("INSERT INTO device (id, name, kind, url, created_by) VALUES (?1, ?2, ?3, ?4, ?5)").run(
110 deviceId,
111 name.value,
112 input.kind,
113 endpoint.value.uri,
114 admin.id,
115 );
116 return ok(getDevice(db, name.value)!);
117 }
118
119 const deviceRow = (r: { id: string; name: string; kind: string; url: string; created_at: string }): Device => ({
120 id: r.id,
121 name: r.name,
122 kind: r.kind,
123 url: r.url,
124 createdAt: r.created_at,
125 });
126
127 export function getDevice(db: Database, name: string): Device | undefined {
128 const row = db
129 .query<{ id: string; name: string; kind: string; url: string; created_at: string }, [string]>(
130 "SELECT id, name, kind, url, created_at FROM device WHERE name = ?1",
131 )
132 .get(name);
133 return row ? deviceRow(row) : undefined;
134 }
135
136 export function listDevices(db: Database): Device[] {
137 return db
138 .query<{ id: string; name: string; kind: string; url: string; created_at: string }, []>(
139 "SELECT id, name, kind, url, created_at FROM device ORDER BY name",
140 )
141 .all()
142 .map(deviceRow);
143 }
144
145 export function removeDevice(db: Database, admin: { isAdmin: boolean }, name: string): boolean {
146 if (!admin.isAdmin) return false;
147 return db.query("DELETE FROM device WHERE name = ?1").run(name).changes > 0;
148 }
149
150 /** Midnight UTC of the day `now` falls on, as the ISO text `created_at` is kept in. */
151 export const dayStart = (now: number): string => new Date(now).toISOString().slice(0, 10) + "T00:00:00.000Z";
152
153 /** Jobs that reached the printer (or tried to) today: what the cap counts. */
154 function usedToday(db: Database, deviceId: string, repoId: string, now: number): number {
155 return (
156 db
157 .query<{ n: number }, [string, string, string]>(
158 `SELECT COUNT(*) AS n FROM print_job
159 WHERE device_id = ?1 AND repo_id = ?2 AND created_at >= ?3
160 AND outcome IN ('reserved', 'accepted', 'failed')`,
161 )
162 .get(deviceId, repoId, dayStart(now))?.n ?? 0
163 );
164 }
165
166 export function grantDevice(
167 db: Database,
168 admin: { id: string; isAdmin: boolean },
169 deviceName: string,
170 repoId: string,
171 dailyCap: number = DEFAULT_DAILY_CAP,
172 ): Result<true, string> {
173 if (!admin.isAdmin) return err("only the forge's owner grants a device");
174 const device = getDevice(db, deviceName);
175 if (!device) return err("no such device");
176 if (!db.query("SELECT 1 FROM repo WHERE id = ?1").get(repoId)) return err("no such app");
177 if (!Number.isInteger(dailyCap) || dailyCap < 1 || dailyCap > MAX_DAILY_CAP)
178 return err(`a daily cap is a whole number from 1 to ${MAX_DAILY_CAP}`);
179 db.query(
180 `INSERT INTO device_grant (device_id, repo_id, daily_cap, granted_by) VALUES (?1, ?2, ?3, ?4)
181 ON CONFLICT(device_id, repo_id) DO UPDATE SET daily_cap = excluded.daily_cap`,
182 ).run(device.id, repoId, dailyCap, admin.id);
183 return ok(true);
184 }
185
186 export function revokeDevice(db: Database, admin: { isAdmin: boolean }, deviceName: string, repoId: string): boolean {
187 if (!admin.isAdmin) return false;
188 const device = getDevice(db, deviceName);
189 if (!device) return false;
190 return db.query("DELETE FROM device_grant WHERE device_id = ?1 AND repo_id = ?2").run(device.id, repoId).changes > 0;
191 }
192
193 /** The grant of a device to a repo, with today's use; undefined when there is none. */
194 export function getGrant(db: Database, deviceId: string, repoId: string, now = Date.now()): DeviceGrant | undefined {
195 const row = db
196 .query<{ daily_cap: number; owner: string; name: string }, [string, string]>(
197 `SELECT g.daily_cap, u.username AS owner, r.name FROM device_grant g
198 JOIN repo r ON r.id = g.repo_id JOIN user u ON u.id = r.owner_id
199 WHERE g.device_id = ?1 AND g.repo_id = ?2`,
200 )
201 .get(deviceId, repoId);
202 if (!row) return undefined;
203 return {
204 deviceId,
205 repoId,
206 app: `${row.owner}/${row.name}`,
207 dailyCap: row.daily_cap,
208 usedToday: usedToday(db, deviceId, repoId, now),
209 };
210 }
211
212 export function listGrants(db: Database, deviceId: string, now = Date.now()): DeviceGrant[] {
213 return db
214 .query<{ repo_id: string }, [string]>("SELECT repo_id FROM device_grant WHERE device_id = ?1 ORDER BY granted_at")
215 .all(deviceId)
216 .flatMap((r) => getGrant(db, deviceId, r.repo_id, now) ?? []);
217 }
218
219 /**
220 * Log a job. A `reserved` row is written before the printer is asked, so two
221 * jobs racing the cap cannot both pass it; `settleJob` writes how it ended.
222 */
223 export function logJob(
224 db: Database,
225 job: { deviceId: string; repoId: string; app: string; pages: number; outcome: JobOutcome; jobState?: string },
226 ): string {
227 const jobId = id();
228 db.query(
229 "INSERT INTO print_job (id, device_id, repo_id, app, pages, outcome, job_state) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
230 ).run(jobId, job.deviceId, job.repoId, job.app, job.pages, job.outcome, job.jobState ?? null);
231 return jobId;
232 }
233
234 /** Rejected prints one app may log in a day; past it a refusal is still answered, no longer written. */
235 export const REJECTED_DAILY_MAX = 50;
236 /** A `reserved` row older than this was left by a crash: it is settled as failed. */
237 export const RESERVED_STALE_MS = 10 * 60_000;
238 /** The job log keeps this long. */
239 export const JOB_KEEP_DAYS = 30;
240
241 const isoAt = (ms: number): string => new Date(ms).toISOString();
242
243 /**
244 * Keep the job table bounded: a `reserved` row a crash left behind is settled
245 * as failed (it still counts toward that day's cap, once), and rows past the
246 * keeping time are deleted.
247 */
248 export function tidyJobs(db: Database, now: number = Date.now()): void {
249 db.query("UPDATE print_job SET outcome = 'failed' WHERE outcome = 'reserved' AND created_at < ?1").run(
250 isoAt(now - RESERVED_STALE_MS),
251 );
252 db.query("DELETE FROM print_job WHERE created_at < ?1").run(isoAt(now - JOB_KEEP_DAYS * 86_400_000));
253 }
254
255 /** Log a refused job, unless this app has already filled today's allowance of refusals. */
256 export function logRejected(
257 db: Database,
258 job: { deviceId: string; repoId: string; app: string; pages: number; outcome: JobOutcome },
259 now: number = Date.now(),
260 ): void {
261 const n =
262 db
263 .query<{ n: number }, [string, string, string]>(
264 `SELECT COUNT(*) AS n FROM print_job
265 WHERE device_id = ?1 AND repo_id = ?2 AND created_at >= ?3
266 AND outcome NOT IN ('reserved', 'accepted', 'failed')`,
267 )
268 .get(job.deviceId, job.repoId, dayStart(now))?.n ?? 0;
269 if (n < REJECTED_DAILY_MAX) logJob(db, job);
270 }
271
272 export function settleJob(db: Database, jobId: string, outcome: JobOutcome, jobState?: string): void {
273 db.query("UPDATE print_job SET outcome = ?2, job_state = ?3 WHERE id = ?1").run(jobId, outcome, jobState ?? null);
274 }
275
276 export function listJobs(db: Database, deviceId: string, limit = 20): PrintJob[] {
277 return db
278 .query<
279 { id: string; app: string; pages: number; outcome: JobOutcome; job_state: string | null; created_at: string },
280 [string, number]
281 >(
282 `SELECT id, app, pages, outcome, job_state, created_at FROM print_job
283 WHERE device_id = ?1 ORDER BY created_at DESC, id DESC LIMIT ?2`,
284 )
285 .all(deviceId, limit)
286 .map((r) => ({ id: r.id, app: r.app, pages: r.pages, outcome: r.outcome, jobState: r.job_state, createdAt: r.created_at }));
287 }
src/core/event_audience.ts +2
@@ -193,6 +193,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
193193 kind.startsWith("app.egress.") ||
194194 kind.startsWith("prompt.") ||
195195 kind.startsWith("secret.") ||
196 // A declared device's address, who may print on it and every job are the owner's (`actions/devices.ts`).
197 kind.startsWith("device.") ||
196198 // The forge's mail ceiling is its owner's to hear (`actions/mail.ts`).
197199 kind.startsWith("mail.") ||
198200 // A restore drill's verdict is the forge owner's (`snapshot/service.ts`).
src/core/migration-pins/20261109200000-home-devices.pin added +1
@@ -0,0 +1,1 @@
1 96a5b709738cfa024fb40502ba34a1274960d968d1e5817e4792fff63b77bb80
src/core/migrations/20261109200000-home-devices.ts added +33
@@ -0,0 +1,33 @@
1 // Home devices (#10413): a device the owner declares (a LAN printer), the
2 // grant of it to one app with that app's daily cap, and the log of every job
3 // an app sent. Additive.
4 export default `
5 CREATE TABLE device (
6 id TEXT PRIMARY KEY,
7 name TEXT NOT NULL UNIQUE,
8 kind TEXT NOT NULL,
9 url TEXT NOT NULL,
10 created_by TEXT NOT NULL REFERENCES user(id),
11 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
12 );
13 CREATE TABLE device_grant (
14 device_id TEXT NOT NULL REFERENCES device(id) ON DELETE CASCADE,
15 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
16 daily_cap INTEGER NOT NULL DEFAULT 10,
17 granted_by TEXT NOT NULL REFERENCES user(id),
18 granted_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
19 PRIMARY KEY (device_id, repo_id)
20 );
21 CREATE TABLE print_job (
22 id TEXT PRIMARY KEY,
23 device_id TEXT NOT NULL REFERENCES device(id) ON DELETE CASCADE,
24 repo_id TEXT NOT NULL,
25 app TEXT NOT NULL,
26 pages INTEGER NOT NULL,
27 outcome TEXT NOT NULL,
28 job_state TEXT,
29 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
30 );
31 CREATE INDEX print_job_by_device ON print_job (device_id, created_at);
32 CREATE INDEX print_job_by_app_day ON print_job (device_id, repo_id, created_at);
33 `;
src/crew/conversation_confirm.ts +1
@@ -65,6 +65,7 @@ export const ASKING: Readonly<Record<string, Asking>> = {
6565 },
6666 // Secrets and credentials.
6767 secrets: { does: "set or remove a sealed secret", asks: not("action", "list") },
68 devices: { does: "declare, grant, revoke or remove a home device", asks: not("action", "list", "show", "status") },
6869 app_env: { does: "set or unset an app's variable", asks: not("action", "list") },
6970 // Absorbing restarts the app and changes the forge's menu for its readers.
7071 features: {
src/devices/ipp.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * IPP/2.0 on the wire, for the two operations the forge speaks to a printer:
3 * Get-Printer-Attributes and Print-Job. Plain data in, plain data out: a
4 * request is bytes built from a printer URI, a response is a flat map of
5 * attribute name to values. No network here (`relay.ts` carries the bytes).
6 */
7
8 export const OP_PRINT_JOB = 0x0002;
9 export const OP_GET_PRINTER_ATTRIBUTES = 0x000b;
10
11 export type IppValue = string | number | boolean;
12
13 export interface IppResponse {
14 /** 0x0000–0x00ff are successes; anything above is the printer saying no. */
15 readonly status: number;
16 readonly attrs: ReadonlyMap<string, readonly IppValue[]>;
17 }
18
19 const enc = new TextEncoder();
20 const dec = new TextDecoder("utf-8");
21
22 function attr(tag: number, name: string, value: string): Uint8Array {
23 const n = enc.encode(name);
24 const v = enc.encode(value);
25 const out = new Uint8Array(5 + n.length + v.length);
26 const view = new DataView(out.buffer);
27 out[0] = tag;
28 view.setUint16(1, n.length);
29 out.set(n, 3);
30 view.setUint16(3 + n.length, v.length);
31 out.set(v, 5 + n.length);
32 return out;
33 }
34
35 /** An extra value of the attribute just written (name length zero). */
36 const more = (tag: number, value: string): Uint8Array => attr(tag, "", value);
37
38 function concat(parts: readonly Uint8Array[]): Uint8Array {
39 const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
40 let at = 0;
41 for (const p of parts) {
42 out.set(p, at);
43 at += p.length;
44 }
45 return out;
46 }
47
48 function head(op: number, requestId: number): Uint8Array {
49 const out = new Uint8Array(8);
50 const view = new DataView(out.buffer);
51 view.setUint16(0, 0x0200);
52 view.setUint16(2, op);
53 view.setUint32(4, requestId);
54 return out;
55 }
56
57 const common = (uri: string): Uint8Array[] => [
58 Uint8Array.of(0x01),
59 attr(0x47, "attributes-charset", "utf-8"),
60 attr(0x48, "attributes-natural-language", "en"),
61 attr(0x45, "printer-uri", uri),
62 ];
63
64 export const PROBE_ATTRIBUTES = [
65 "printer-name",
66 "printer-make-and-model",
67 "printer-state",
68 "printer-state-reasons",
69 "marker-names",
70 "marker-levels",
71 ];
72
73 export function getPrinterAttributes(uri: string, requestId = 1): Uint8Array {
74 const [first = "", ...rest] = PROBE_ATTRIBUTES;
75 return concat([
76 head(OP_GET_PRINTER_ATTRIBUTES, requestId),
77 ...common(uri),
78 attr(0x44, "requested-attributes", first),
79 ...rest.map((r) => more(0x44, r)),
80 Uint8Array.of(0x03),
81 ]);
82 }
83
84 export function printJob(uri: string, jobName: string, pdf: Uint8Array, requestId = 1): Uint8Array {
85 return concat([
86 head(OP_PRINT_JOB, requestId),
87 ...common(uri),
88 attr(0x42, "requesting-user-name", "forge"),
89 attr(0x42, "job-name", jobName),
90 attr(0x49, "document-format", "application/pdf"),
91 Uint8Array.of(0x03),
92 pdf,
93 ]);
94 }
95
96 /** Read a response; undefined when the bytes are not IPP. */
97 export function parseResponse(bytes: Uint8Array): IppResponse | undefined {
98 if (bytes.length < 9) return undefined;
99 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
100 const status = view.getUint16(2);
101 const attrs = new Map<string, IppValue[]>();
102 let at = 8;
103 let last = "";
104 while (at < bytes.length) {
105 const tag = bytes[at]!;
106 at += 1;
107 if (tag === 0x03) return { status, attrs };
108 if (tag <= 0x05) continue; // a group delimiter
109 if (at + 2 > bytes.length) return undefined;
110 const nameLength = view.getUint16(at);
111 at += 2;
112 if (at + nameLength + 2 > bytes.length) return undefined;
113 const name = nameLength === 0 ? last : dec.decode(bytes.subarray(at, at + nameLength));
114 at += nameLength;
115 const valueLength = view.getUint16(at);
116 at += 2;
117 if (at + valueLength > bytes.length) return undefined;
118 const raw = bytes.subarray(at, at + valueLength);
119 at += valueLength;
120 let value: IppValue | undefined;
121 if ((tag === 0x21 || tag === 0x23) && valueLength === 4) value = new DataView(raw.buffer, raw.byteOffset, 4).getInt32(0);
122 else if (tag === 0x22) value = raw[0] === 1;
123 else if (tag >= 0x40) value = dec.decode(raw);
124 last = name;
125 if (value === undefined) continue; // out-of-band or a kind we do not read
126 const list = attrs.get(name);
127 if (list) list.push(value);
128 else attrs.set(name, [value]);
129 }
130 return { status, attrs };
131 }
src/devices/pdf.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * What the print endpoint needs to know about a PDF before it spends a job
3 * on it: that it is one, and how many pages it has. A count read from the
4 * bytes, never from a parser: page objects (`/Type /Page`) and the largest
5 * `/Count` of a page tree, whichever is more. A file that hides both in
6 * compressed object streams reads as zero pages and is refused as unreadable.
7 */
8
9 export const MAX_PDF_BYTES = 10 * 1024 * 1024;
10 export const MAX_PDF_PAGES = 20;
11
12 export const isPdf = (bytes: Uint8Array): boolean =>
13 bytes.length > 8 &&
14 bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d;
15
16 export function pdfPages(bytes: Uint8Array): number {
17 const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
18 const objects = text.match(/\/Type\s*\/Page(?![A-Za-z])/g)?.length ?? 0;
19 let counted = 0;
20 for (const m of text.matchAll(/\/Count\s+(\d{1,5})/g)) counted = Math.max(counted, Number(m[1]));
21 return Math.max(objects, counted);
22 }
src/devices/relay.ts added +171
@@ -0,0 +1,171 @@
1 /**
2 * The relay: the one place the forge's own network reaches a home device.
3 * It takes a declared `Device` (never a URL from a caller), re-checks that
4 * its address is a private LAN literal, and speaks IPP to it. Redirects are
5 * never followed and a reply is read to a fixed size, so a printer cannot
6 * send the forge anywhere else.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import {
11 getGrant,
12 logJob,
13 logRejected,
14 tidyJobs,
15 parseDeviceUrl,
16 settleJob,
17 type Device,
18 } from "../core/devices.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20 import { getPrinterAttributes, parseResponse, printJob, type IppResponse } from "./ipp.ts";
21 import { isPdf, MAX_PDF_BYTES, MAX_PDF_PAGES, pdfPages } from "./pdf.ts";
22
23 const REPLY_MAX = 256 * 1024;
24 const PROBE_MS = 5_000;
25 const PRINT_MS = 30_000;
26
27 const PRINTER_STATES: Record<number, string> = { 3: "idle", 4: "printing", 5: "stopped" };
28 const JOB_STATES: Record<number, string> = {
29 3: "pending",
30 4: "held",
31 5: "processing",
32 6: "stopped",
33 7: "canceled",
34 8: "aborted",
35 9: "completed",
36 };
37
38 async function ask(device: Device, body: Uint8Array, ms: number): Promise<Result<IppResponse, string>> {
39 const endpoint = parseDeviceUrl(device.url);
40 if (!endpoint.ok) return err(endpoint.error);
41 try {
42 const res = await fetch(endpoint.value.http, {
43 method: "POST",
44 headers: { "content-type": "application/ipp" },
45 body,
46 redirect: "manual",
47 signal: AbortSignal.timeout(ms),
48 });
49 if (res.status !== 200) return err(`the printer answered HTTP ${res.status}`);
50 const bytes = new Uint8Array(await res.arrayBuffer());
51 if (bytes.length > REPLY_MAX) return err("the printer's answer was too large");
52 const parsed = parseResponse(bytes);
53 return parsed ? ok(parsed) : err("the printer did not answer in IPP");
54 } catch {
55 return err("the printer did not answer");
56 }
57 }
58
59 export interface Supply {
60 readonly name: string;
61 /** 0–100, or -1 when the printer does not know. */
62 readonly level: number;
63 }
64
65 export interface Probe {
66 readonly model: string;
67 readonly state: string;
68 readonly reasons: string[];
69 readonly supplies: Supply[];
70 }
71
72 /** Get-Printer-Attributes: model, state and supplies, or why it could not be read. */
73 export async function probeDevice(device: Device): Promise<Result<Probe, string>> {
74 const endpoint = parseDeviceUrl(device.url);
75 if (!endpoint.ok) return err(endpoint.error);
76 const reply = await ask(device, getPrinterAttributes(endpoint.value.uri), PROBE_MS);
77 if (!reply.ok) return reply;
78 if (reply.value.status >= 0x0100) return err("the printer refused to describe itself");
79 const a = reply.value.attrs;
80 const text = (k: string): string => String(a.get(k)?.[0] ?? "");
81 const state = a.get("printer-state")?.[0];
82 const names = a.get("marker-names") ?? [];
83 const levels = a.get("marker-levels") ?? [];
84 return ok({
85 model: text("printer-make-and-model") || text("printer-name") || "unknown printer",
86 state: typeof state === "number" ? (PRINTER_STATES[state] ?? "unknown") : "unknown",
87 reasons: (a.get("printer-state-reasons") ?? []).map(String).filter((r) => r !== "none"),
88 supplies: names.map((n, i) => ({ name: String(n), level: typeof levels[i] === "number" ? Number(levels[i]) : -1 })),
89 });
90 }
91
92 /** One line when fine; the words that need a person when not. */
93 export function probeLine(p: Probe): { fine: boolean; line: string } {
94 const low = p.supplies.filter((s) => s.level >= 0 && s.level <= 10);
95 const trouble = p.state === "stopped" || p.reasons.length > 0 || low.length > 0;
96 if (!trouble) return { fine: true, line: `${p.model} · ${p.state} · supplies fine` };
97 const bits = [p.model, p.state, ...p.reasons, ...low.map((s) => `${s.name} ${s.level}%`)];
98 return { fine: false, line: bits.join(" · ") };
99 }
100
101 export type PrintError =
102 | { kind: "no_grant" }
103 | { kind: "over_cap"; cap: number }
104 | { kind: "not_pdf" }
105 | { kind: "too_big" }
106 | { kind: "too_long"; pages: number }
107 | { kind: "failed"; message: string };
108
109 export interface PrintDone {
110 readonly job: string;
111 readonly state: string;
112 readonly pages: number;
113 }
114
115 /**
116 * Print a PDF for an app. The grant is checked first and is the only door:
117 * no grant, no byte leaves. Everything past the grant is logged with the
118 * app, the page count and the outcome.
119 */
120 export async function printForApp(
121 db: Database,
122 device: Device,
123 app: { repoId: string; slug: string },
124 pdf: Uint8Array | "too_big",
125 now: number = Date.now(),
126 ): Promise<Result<PrintDone, PrintError>> {
127 const granted = getGrant(db, device.id, app.repoId, now);
128 if (!granted) return err({ kind: "no_grant" });
129 tidyJobs(db, now);
130 const grant = getGrant(db, device.id, app.repoId, now)!;
131 const job = { deviceId: device.id, repoId: app.repoId, app: app.slug };
132 const log = (pages: number, outcome: Parameters<typeof logJob>[1]["outcome"]) =>
133 logJob(db, { ...job, pages, outcome });
134 const refuse = (pages: number, outcome: Parameters<typeof logJob>[1]["outcome"]) =>
135 logRejected(db, { ...job, pages, outcome }, now);
136 if (pdf === "too_big" || pdf.length > MAX_PDF_BYTES) {
137 refuse(0, "too_big");
138 return err({ kind: "too_big" });
139 }
140 const pages = isPdf(pdf) ? pdfPages(pdf) : 0;
141 if (pages === 0) {
142 refuse(0, "not_pdf");
143 return err({ kind: "not_pdf" });
144 }
145 if (pages > MAX_PDF_PAGES) {
146 refuse(pages, "too_long");
147 return err({ kind: "too_long", pages });
148 }
149 if (grant.usedToday >= grant.dailyCap) {
150 refuse(pages, "over_cap");
151 return err({ kind: "over_cap", cap: grant.dailyCap });
152 }
153 // Reserved before the await: the cap holds against jobs racing each other.
154 const jobId = log(pages, "reserved");
155 const endpoint = parseDeviceUrl(device.url);
156 const reply = endpoint.ok
157 ? await ask(device, printJob(endpoint.value.uri, `${app.slug} ${new Date(now).toISOString()}`, pdf), PRINT_MS)
158 : err(endpoint.error);
159 if (!reply.ok) {
160 settleJob(db, jobId, "failed");
161 return err({ kind: "failed", message: reply.error });
162 }
163 const rawState = reply.value.attrs.get("job-state")?.[0];
164 const state = typeof rawState === "number" ? (JOB_STATES[rawState] ?? "unknown") : "unknown";
165 if (reply.value.status >= 0x0100) {
166 settleJob(db, jobId, "failed", state);
167 return err({ kind: "failed", message: "the printer refused the job" });
168 }
169 settleJob(db, jobId, "accepted", state);
170 return ok({ job: jobId, state, pages });
171 }
src/http/api.ts +2
@@ -340,6 +340,7 @@ import { frontInput, frontJson, setFront } from "../actions/front.ts";
340340 import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts";
341341 import { passportRoutes } from "./passport_edge.ts";
342342 import { egressGrantRoutes } from "./api/egress_grants.ts";
343 import { deviceRoutes } from "./api/devices.ts";
343344 import { forgeRoutes } from "./api/forges.ts";
344345 import { forgeViewRoutes } from "./api/forge_view.ts";
345346 import { economicsRoutes } from "./api/economics.ts";
@@ -3748,6 +3749,7 @@ export function apiRoutes(router: Router<Handler>): void {
37483749 iterationRoutes(router);
37493750
37503751 egressGrantRoutes(router);
3752 deviceRoutes(router);
37513753
37523754 promptRoutes(router);
37533755
src/http/api/devices.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * Home devices over the API (#10413). The owner (a site admin) lists,
3 * declares, grants and removes devices under `/api/v1/devices`; an app
4 * prints with `POST /api/v1/devices/:name/print`, a PDF as the body, using
5 * the token the forge gave its process. The rules live in `actions/devices.ts`.
6 */
7
8 import { declare, deviceList, deviceStatus, deviceView, grant, print, removeDeclared, revoke } from "../../actions/devices.ts";
9 import type { Handler } from "../context.ts";
10 import { readBounded } from "../limits.ts";
11 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
12 import { MAX_PDF_BYTES, MAX_PDF_PAGES } from "../../devices/pdf.ts";
13 import { apiError, body, json, notFound, requireScope, str } from "../respond.ts";
14 import type { Router } from "../router.ts";
15
16 const num = (v: unknown): number | undefined => (typeof v === "number" ? v : undefined);
17
18 export function deviceRoutes(router: Router<Handler>): void {
19 router.add("GET", "/api/v1/devices", (ctx) => {
20 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
21 const denied = requireScope(ctx, "admin");
22 if (denied) return denied;
23 const list = deviceList(ctx.app, ctx.auth.user);
24 if (!list.ok) return notFound();
25 return json({ items: list.value, next_cursor: null });
26 });
27
28 router.add("POST", "/api/v1/devices", async (ctx) => {
29 const denied = requireScope(ctx, "admin");
30 if (denied) return denied;
31 const input = await body(ctx.request);
32 const made = declare(ctx.app, ctx.auth.user, { name: str(input.name), kind: str(input.kind), url: str(input.url) });
33 if (!made.ok) return made.error === "not_found" ? notFound() : apiError("invalid", 422, made.error);
34 return json(made.value, 201);
35 });
36
37 router.add("GET", "/api/v1/devices/:name", (ctx) => {
38 const denied = requireScope(ctx, "admin");
39 if (denied) return denied;
40 const view = deviceView(ctx.app, ctx.auth.user, ctx.params["name"] ?? "");
41 return view.ok ? json(view.value) : notFound();
42 });
43
44 // Asks the printer (at most once in 30 s); a separate request so the device itself never waits on it.
45 router.add("GET", "/api/v1/devices/:name/status", async (ctx) => {
46 const denied = requireScope(ctx, "admin");
47 if (denied) return denied;
48 const status = await deviceStatus(ctx.app, ctx.auth.user, ctx.params["name"] ?? "");
49 return status.ok ? json(status.value) : notFound();
50 });
51
52 router.add("DELETE", "/api/v1/devices/:name", (ctx) => {
53 const denied = requireScope(ctx, "admin");
54 if (denied) return denied;
55 const gone = removeDeclared(ctx.app, ctx.auth.user, ctx.params["name"] ?? "");
56 return gone.ok ? json({}, 200) : notFound();
57 });
58
59 router.add("PUT", "/api/v1/devices/:name/grants", async (ctx) => {
60 const denied = requireScope(ctx, "admin");
61 if (denied) return denied;
62 const input = await body(ctx.request);
63 const done = grant(ctx.app, ctx.auth.user, ctx.params["name"] ?? "", str(input.app), num(input.daily_cap));
64 if (!done.ok) return done.error === "not_found" ? notFound() : apiError("invalid", 422, done.error);
65 return json({}, 200);
66 });
67
68 router.add("DELETE", "/api/v1/devices/:name/grants", async (ctx) => {
69 const denied = requireScope(ctx, "admin");
70 if (denied) return denied;
71 const input = await body(ctx.request);
72 const done = revoke(ctx.app, ctx.auth.user, ctx.params["name"] ?? "", str(input.app));
73 if (!done.ok) return done.error === "not_found" ? notFound() : apiError("invalid", 422, done.error);
74 return json({}, 200);
75 });
76
77 // An app's door. The token the forge gave its process is `ro`; it can
78 // change nothing else, and this only works for a device granted to it.
79 router.add("POST", "/api/v1/devices/:name/print", async (ctx) => {
80 const denied = requireScope(ctx, "ro");
81 if (denied) return denied;
82 const pdf = await readBounded(ctx.request, MAX_PDF_BYTES + 1);
83 // A body past the cap is passed on as "too_big": refused, and logged once the app is granted.
84 const done = await print(ctx.app, ctx.auth.user, ctx.auth.tokenName, ctx.params["name"] ?? "", pdf === "too_large" ? "too_big" : pdf);
85 if (done.ok) return json({ job: done.value.job, state: done.value.state, pages: done.value.pages }, 201);
86 const e = done.error;
87 switch (e.kind) {
88 case "no_grant":
89 return notFound();
90 case "over_cap":
91 return apiError("over_cap", 429, `this app has used its ${e.cap} jobs for today`);
92 case "not_pdf":
93 return apiError("not_pdf", 422, "send a PDF as the request body");
94 case "too_big":
95 return apiError("too_large", 413, `a PDF is at most ${MAX_PDF_BYTES / 1024 / 1024} MB`);
96 case "too_long":
97 return apiError("too_long", 422, `a PDF is at most ${MAX_PDF_PAGES} pages; this one has ${e.pages}`);
98 case "failed":
99 return apiError("printer_failed", 502, e.message);
100 }
101 });
102 }
src/http/mcp/tools/devices.ts added +62
@@ -0,0 +1,62 @@
1 import { declare, deviceList, deviceStatus, deviceView, grant, removeDeclared, revoke } from "../../../actions/devices.ts";
2 import { scopeAllows } from "../../../core/tokens.ts";
3 import { good, bad, type Tool } from "../shared.ts";
4
5 export const tool: Tool = {
6 name: "devices",
7 doc: "`{ action, name?, kind?, url?, app?, daily_cap? }` (forge owner): home devices an app may print to once granted. `list`; `show` (declared facts, grants with use today, jobs); `status` (asks the printer, at most once in 30 s); `declare` (`name`, `kind` printer, `url` an IPP URL on a private IPv4 address); `grant` / `revoke` (`name`, `app` as owner/name, `daily_cap`); `remove`",
8 description: "Admin: list|show|status|declare|grant|revoke|remove home devices.",
9 inputSchema: {
10 type: "object",
11 properties: {
12 action: { type: "string" },
13 name: { type: "string" },
14 kind: { type: "string" },
15 url: { type: "string" },
16 app: { type: "string" },
17 daily_cap: { type: "number" },
18 },
19 },
20 writes: true,
21 adminOnly: true,
22 async run(ctx, user, args) {
23 // The API asks for an admin token on every device route; so does this.
24 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "devices need an admin token");
25 const str = (v: unknown): string => (typeof v === "string" ? v : "");
26 const name = str(args["name"]);
27 const failed = (e: string) => (e === "not_found" ? bad("not_found", "no such device") : bad("invalid", e));
28 switch (args["action"]) {
29 case "list": {
30 const list = deviceList(ctx.app, user);
31 return list.ok ? good({ items: list.value }) : failed(list.error);
32 }
33 case "show": {
34 const view = deviceView(ctx.app, user, name);
35 return view.ok ? good(view.value) : failed(view.error);
36 }
37 case "status": {
38 const status = await deviceStatus(ctx.app, user, name);
39 return status.ok ? good(status.value) : failed(status.error);
40 }
41 case "declare": {
42 const made = declare(ctx.app, user, { name, kind: str(args["kind"]), url: str(args["url"]) });
43 return made.ok ? good(made.value) : failed(made.error);
44 }
45 case "grant": {
46 const cap = typeof args["daily_cap"] === "number" ? args["daily_cap"] : undefined;
47 const done = grant(ctx.app, user, name, str(args["app"]), cap);
48 return done.ok ? good({ granted: str(args["app"]) }) : failed(done.error);
49 }
50 case "revoke": {
51 const done = revoke(ctx.app, user, name, str(args["app"]));
52 return done.ok ? good({ revoked: str(args["app"]) }) : failed(done.error);
53 }
54 case "remove": {
55 const gone = removeDeclared(ctx.app, user, name);
56 return gone.ok ? good({ removed: name }) : failed(gone.error);
57 }
58 default:
59 return bad("invalid", "action is list, show, status, declare, grant, revoke or remove");
60 }
61 },
62 };
src/http/mcp/tools/index.ts +1
@@ -49,6 +49,7 @@ export { tool as crew } from "./crew.ts";
4949 export { tool as data } from "./data.ts";
5050 export { tool as decisions_by } from "./decisions_by.ts";
5151 export { tool as detach } from "./detach.ts";
52 export { tool as devices } from "./devices.ts";
5253 export { tool as drills } from "./drills.ts";
5354 export { tool as economics } from "./economics.ts";
5455 export { tool as edit } from "./edit.ts";
src/http/settings_routes.ts +8
@@ -34,6 +34,7 @@ import {
3434 import { confirmsList, confirmYes } from "../web/pages/confirms.ts";
3535 import { featureAccept, featurePage, featureRun, featureSave, featuresPage, featureSwitch } from "../web/pages/features.ts";
3636 import { passkeyAdd, passkeyDelete, passkeyOptions, passkeysPage } from "../web/pages/passkeys.ts";
37 import { deviceDeclare, deviceGrant, devicePage, deviceRemove, deviceRevoke, deviceStatusPage, devicesPage } from "../web/pages/devices.ts";
3738 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
3839 import {
3940 backupsClear,
@@ -165,6 +166,13 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
165166 subscriptionHeadroom,
166167 );
167168 router.add("POST", "/settings/subscriptions/:id/budget", subscriptionBudget);
169 router.add("GET", "/settings/devices", devicesPage);
170 router.add("POST", "/settings/devices", deviceDeclare);
171 router.add("GET", "/settings/devices/:name", devicePage);
172 router.add("GET", "/settings/devices/:name/status", deviceStatusPage);
173 router.add("POST", "/settings/devices/:name/grant", deviceGrant);
174 router.add("POST", "/settings/devices/:name/revoke", deviceRevoke);
175 router.add("POST", "/settings/devices/:name/remove", deviceRemove);
168176 router.add("GET", "/settings/secrets", secretsPage);
169177 router.add("POST", "/settings/secrets", secretSet);
170178 router.add("POST", "/settings/secrets/delete", secretDelete);
src/kernel/why_now.ts deleted −37
@@ -1,37 +0,0 @@
1 /**
2 * Retired 2026-11-09: the direction no longer puts the pipeline first —
3 * order is set by the pillars and the captain's ranking — so the gate no
4 * longer asks (`scripts/gate.ts`). A finished, approved pull closed unmerged
5 * on this rule (#10317); nothing reads it now. Kept with its test until the
6 * next sweep of unused modules.
7 *
8 * The direction issue put the pipeline first (#8839), so a new feature
9 * said why it went ahead of it. A feature is a file a pull adds, at any
10 * depth, under an action, a page, an API route, an MCP tool or a terminal
11 * screen; the pull's commits must then say either `Pipeline: #N` (it is
12 * pipeline work) or `Why now: <reason>` (it goes ahead, and why). The check
13 * cannot read the pull description, so the answer lives in a commit
14 * message. It is a nudge, not a proof: it checks a reason was written, not
15 * that it is a good one.
16 */
17
18 import type { Change } from "./pin_edits.ts";
19
20 const FEATURE = /^src\/(actions|web\/pages|http\/api|http\/mcp\/tools|tui)\/.+\.ts$/;
21 const PIPELINE = /^Pipeline:\s*#\d+/im;
22 const WHY_NOW = /^Why now:\s*\S[^\n]{14,}/im;
23
24 /** The files a pull adds that make a new feature. */
25 export function featuresAdded(changes: readonly Change[]): string[] {
26 return changes.filter((c) => c.status.startsWith("A") && FEATURE.test(c.path)).map((c) => c.path);
27 }
28
29 /** One line per problem: none when no feature is added or a commit answers the direction. */
30 export function whyNowProblems(changes: readonly Change[], messages: readonly string[]): string[] {
31 const added = featuresAdded(changes);
32 if (added.length === 0) return [];
33 if (messages.some((m) => PIPELINE.test(m) || WHY_NOW.test(m))) return [];
34 return [
35 `rule "say why it goes ahead of the pipeline": this pull adds ${added.join(", ")} but no commit message has a "Why now: <reason>" line (15+ characters) or a "Pipeline: #N" line`,
36 ];
37 }
src/tui/screens/devices.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * Home devices in the terminal, the forge owner's: the devices declared on
3 * this forge's network (`n` declares one), and `enter` on a device opens its
4 * page: the printer's one status line, the apps granted with their use today,
5 * and the jobs sent. `g` grants an app (`owner/app` and an optional daily
6 * cap), `x` revokes the grant under the cursor and `d` removes the device,
7 * each after a confirm. Every rule is the action's (`actions/devices.ts`),
8 * the same the page and the API call, so a write here reaches web viewers
9 * through the event it appends; the screens refresh on those events too.
10 * Anyone else has no command and, driving the screen directly, sees nothing.
11 */
12
13 import {
14 declare,
15 deviceList,
16 deviceStatus,
17 deviceView,
18 grant,
19 removeDeclared,
20 revoke,
21 type DeviceView,
22 } from "../../actions/devices.ts";
23 import { DEFAULT_DAILY_CAP, type Device } from "../../core/devices.ts";
24 import type { Result } from "../../kernel/result.ts";
25 import type { Ctx, Screen } from "../app/app.ts";
26 import { binding } from "../app/keys.ts";
27 import { style } from "../term/style.ts";
28 import { truncate } from "../term/width.ts";
29 import type { Session } from "../session.ts";
30 import { fill, len, split } from "../ui/layout.ts";
31 import { confirmScreen, drawList, later, ListState, live, promptScreen, runAsync } from "./common.ts";
32 import type { PaletteEntry } from "./entries.ts";
33
34 const KINDS = ["device.declared", "device.removed", "device.granted", "device.revoked", "device.printed"];
35
36 /** Whether this session is the forge's owner at a person's keyboard; the actions decide again. */
37 export const mayDevices = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind !== "agent";
38
39 /** `owner/app` or `owner/app 25` → the app and its cap (undefined: the default); a string is the refusal. */
40 export function parseGrant(line: string): { app: string; cap: number | undefined } | string {
41 const [app = "", cap, ...rest] = line.trim().split(/\s+/);
42 if (app === "" || rest.length > 0 || !app.includes("/")) return "Name the app as owner/app, then optionally a daily cap.";
43 if (cap === undefined) return { app, cap: undefined };
44 return /^\d{1,4}$/.test(cap) ? { app, cap: Number(cap) } : "A daily cap is a whole number.";
45 }
46
47 function deviceScreen(f: Session, ctx: Ctx, name: string): Screen {
48 const state = new ListState();
49 let view: DeviceView | undefined;
50 let status = "asking the printer…";
51 const reload = (): void => {
52 const got = deviceView(f.app, f.user, name);
53 view = got.ok ? got.value : undefined;
54 state.clamp(view?.grants.length ?? 0);
55 ctx.invalidate();
56 };
57 const ask = (): void =>
58 runAsync(ctx, async () => {
59 const got = await deviceStatus(f.app, f.user, name);
60 status = !got.ok ? "" : got.value.status?.line ?? `not reachable: ${got.value.problem ?? "unknown"}`;
61 ctx.invalidate();
62 });
63 const change = (done: Result<true, string>, said: string): string | undefined => {
64 reload();
65 if (done.ok) ctx.toast(said, "success");
66 return done.ok ? undefined : done.error;
67 };
68
69 const screen: Screen = {
70 title: name,
71 keys: [
72 binding(["j", "k"], "move cursor"),
73 binding(["g"], "grant an app"),
74 binding(["x"], "revoke"),
75 binding(["d"], "remove device"),
76 binding(["esc"], "back"),
77 ],
78 load(signal) {
79 live(f, signal, { kinds: KINDS }, reload);
80 reload();
81 ask();
82 return Promise.resolve();
83 },
84 render(area, s) {
85 const c = ctx.theme.c;
86 if (view === undefined) {
87 s.text(area.x, area.y, "This device is gone. esc goes back.", style(c.mutedFg, c.bg), area.x + area.w);
88 return;
89 }
90 const [head, list, jobs] = split(area, "v", [len(3), fill(1), len(7)]);
91 const dim = style(c.mutedFg, c.bg);
92 s.text(head!.x, head!.y, truncate(`${view.device.kind} · ${view.device.url}`, head!.w), dim, head!.x + head!.w);
93 s.text(head!.x, head!.y + 1, truncate(status, head!.w), style(c.fg, c.bg), head!.x + head!.w);
94 s.text(head!.x, head!.y + 2, "Apps that may print", dim, head!.x + head!.w);
95 drawList(
96 s,
97 list!,
98 c,
99 state,
100 view.grants.map((g) => ({ title: g.app, meta: `${g.usedToday} of ${g.dailyCap} jobs today` })),
101 );
102 s.text(jobs!.x, jobs!.y, "Jobs", dim, jobs!.x + jobs!.w);
103 view.jobs.slice(0, jobs!.h - 1).forEach((j, i) => {
104 const line = `${j.app} · ${j.pages} ${j.pages === 1 ? "page" : "pages"} · ${j.outcome}${j.jobState ? ` · ${j.jobState}` : ""} · ${j.createdAt.slice(0, 16).replace("T", " ")}`;
105 s.text(jobs!.x, jobs!.y + 1 + i, truncate(line, jobs!.w), style(c.fg, c.bg), jobs!.x + jobs!.w);
106 });
107 },
108 key(e) {
109 if (!mayDevices(f)) return false;
110 if (e.ctrl || e.alt) return false;
111 if (e.key === "esc" || e.key === "q") {
112 ctx.pop();
113 return true;
114 }
115 if (e.key === "g") {
116 ctx.push(
117 promptScreen(ctx, screen, {
118 title: `Grant ${name}`,
119 label: `owner/app, then a daily cap (empty is ${DEFAULT_DAILY_CAP})`,
120 onSubmit: (raw) => {
121 const parsed = parseGrant(raw);
122 if (typeof parsed === "string") return parsed;
123 return change(grant(f.app, f.user, name, parsed.app, parsed.cap), `${parsed.app} may print to ${name}.`);
124 },
125 }),
126 );
127 return true;
128 }
129 if (e.key === "x") {
130 const row = view?.grants[state.index];
131 if (row === undefined) return true;
132 ctx.push(
133 confirmScreen(ctx, screen, {
134 title: `Stop ${row.app} printing to ${name}?`,
135 body: ["Its next print is refused until g grants it again."],
136 actions: [{ label: "Revoke", variant: "danger" }, { label: "Cancel", variant: "ghost" }],
137 selected: 1,
138 onChoose: (choice) => {
139 if (choice !== 0) return;
140 const done = revoke(f.app, f.user, name, row.app);
141 reload();
142 ctx.toast(done.ok ? `${row.app} is revoked.` : "that could not be changed", done.ok ? "success" : "danger");
143 },
144 }),
145 );
146 return true;
147 }
148 if (e.key === "d") {
149 ctx.push(
150 confirmScreen(ctx, screen, {
151 title: `Remove ${name}?`,
152 body: ["Every grant to it goes too. The printer itself is untouched."],
153 actions: [{ label: "Remove", variant: "danger" }, { label: "Cancel", variant: "ghost" }],
154 selected: 1,
155 onChoose: (choice) => {
156 if (choice !== 0) return;
157 const done = removeDeclared(f.app, f.user, name);
158 ctx.toast(done.ok ? `${name} is removed.` : "that could not be changed", done.ok ? "success" : "danger");
159 reload();
160 },
161 }),
162 );
163 return true;
164 }
165 return state.key(e, view?.grants.length ?? 0);
166 },
167 };
168 return screen;
169 }
170
171 export function devicesScreen(f: Session, ctx: Ctx): Screen {
172 const state = new ListState();
173 const allowed = mayDevices(f);
174 let devices: readonly Device[] = [];
175 const reload = (): void => {
176 const got = allowed ? deviceList(f.app, f.user) : undefined;
177 devices = got?.ok ? got.value : [];
178 state.clamp(devices.length);
179 ctx.invalidate();
180 };
181 const screen: Screen = {
182 title: "Devices",
183 keys: [binding(["j", "k"], "move cursor"), binding(["enter"], "open"), binding(["n"], "declare"), binding(["esc"], "back")],
184 load(signal) {
185 live(f, signal, { kinds: KINDS }, reload);
186 reload();
187 return Promise.resolve();
188 },
189 render(area, s) {
190 const c = ctx.theme.c;
191 const [head, list] = split(area, "v", [len(1), fill(1)]);
192 const text = !allowed
193 ? "Devices are kept by the forge's owner."
194 : devices.length === 0
195 ? "No device declared. n declares one."
196 : "Declare a device once; an app prints to it only when you grant it.";
197 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
198 drawList(s, list!, c, state, devices.map((d) => ({ title: d.name, meta: `${d.kind} · ${d.url}` })));
199 },
200 key(e) {
201 if (!allowed) return false;
202 if (e.ctrl || e.alt) return false;
203 if (e.key === "enter") {
204 const d = devices[state.index];
205 if (d !== undefined) ctx.push(deviceScreen(f, ctx, d.name));
206 return true;
207 }
208 if (e.key === "n") {
209 ctx.push(
210 promptScreen(ctx, screen, {
211 title: "Declare a device",
212 label: "name, like office-printer",
213 onSubmit: (name) =>
214 later(ctx, () =>
215 promptScreen(ctx, screen, {
216 title: `Declare ${name.trim()}`,
217 label: "IPP URL, like ipp://192.168.1.161:631/ipp/print",
218 onSubmit: (url) => {
219 const made = declare(f.app, f.user, { name, kind: "printer", url });
220 if (!made.ok) return made.error;
221 reload();
222 ctx.toast(`${made.value.name} is declared.`, "success");
223 return undefined;
224 },
225 }),
226 ),
227 }),
228 );
229 return true;
230 }
231 return state.key(e, devices.length);
232 },
233 };
234 return screen;
235 }
236
237 /** Settings → Devices, as the page has it: the forge's owner only. */
238 export const entry: PaletteEntry = {
239 id: "devices",
240 title: "Devices",
241 hint: "LAN printers an app may use; declare, grant, revoke, remove",
242 after: ["secrets", "flags", "access"],
243 offered: (session) => mayDevices(session),
244 run: (session, ctx) => ctx.push(devicesScreen(session, ctx)),
245 };
src/tui/screens/entries.ts +2
@@ -22,6 +22,7 @@ import { entry as connections } from "./connections.ts";
2222 import { entry as crewHandover } from "./crewhandover.ts";
2323 import { entry as crewSplits } from "./crewsplits.ts";
2424 import { entry as displays } from "./displays.ts";
25 import { entry as devices } from "./devices.ts";
2526 import { entry as domains } from "./domains.ts";
2627 import { entry as edgeOnly } from "./edgeonly.ts";
2728 import { entry as traffic } from "./trafficview.ts";
@@ -96,6 +97,7 @@ export const ENTRIES: readonly PaletteEntry[] = [
9697 traffic,
9798 audit,
9899 secrets,
100 devices,
99101 crewSplits,
100102 crewHandover,
101103 scorecard,
src/web/icons.ts +1
@@ -67,6 +67,7 @@ const PATHS = {
6767 plus: `<path d="M5 12h14"/><path d="M12 5v14"/>`,
6868 dot: `<circle cx="12" cy="12" r="4" fill="currentColor" stroke="none"/>`,
6969 alert: `<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>`,
70 printer: `<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><path d="M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6"/><rect x="6" y="14" width="12" height="8" rx="1"/>`,
7071 eye: `<path d="M2.06 12.35a1 1 0 0 1 0-.7 10.75 10.75 0 0 1 19.88 0 1 1 0 0 1 0 .7 10.75 10.75 0 0 1-19.88 0"/><circle cx="12" cy="12" r="3"/>`,
7172 download: `<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>`,
7273 comment: `<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>`,
src/web/pages/devices.ts added +221
@@ -0,0 +1,221 @@
1 /**
2 * Home devices, for the forge's owner (#10413): `/settings/devices` lists
3 * the declared devices and declares one; `/settings/devices/:name` is a
4 * device's page: one line when it is fine, the supplies and reasons when it
5 * is not, who may print to it with each daily cap, and the jobs sent.
6 */
7
8 import { cachedStatus, declare, type DeviceStatus, deviceList, deviceStatus, deviceView, grant, removeDeclared, revoke } from "../../actions/devices.ts";
9 import { DEFAULT_DAILY_CAP } from "../../core/devices.ts";
10 import { probeLine } from "../../devices/relay.ts";
11 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
14 import { field, readForm, type Form } from "../form.ts";
15 import { html, when, type Html } from "../html.ts";
16 import { flashTo, page } from "../layout.ts";
17 import { btn, confirmAction, row, time } from "../ui.ts";
18 import { accountSections } from "./origins.ts";
19
20 const admin = (ctx: Ctx): Response | undefined => {
21 if (!ctx.auth.user) return signInFirst(ctx);
22 return ctx.auth.user.isAdmin && ctx.auth.user.kind !== "agent" ? undefined : notFoundPage(ctx);
23 };
24
25 const here = (name: string): string => `/settings/devices/${encodeURIComponent(name)}`;
26 const sections = accountSections("devices", { admin: true });
27
28 // GET /settings/devices
29 export function devicesPage(ctx: Ctx): Response {
30 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
31 const denied = admin(ctx);
32 if (denied) return denied;
33 const list = deviceList(ctx.app, ctx.auth.user);
34 const rendering = performance.now();
35 const devices = list.ok ? list.value : [];
36 const rows = devices.map((d) =>
37 row({
38 title: html`<a href="${here(d.name)}">${d.name}</a>`,
39 meta: html`${d.kind} · <span class="mono">${d.url}</span>`,
40 }),
41 );
42 const res = page({
43 ctx,
44 title: "Devices",
45 body: html`<div class="page-head"><h1>Devices</h1></div>
46 ${settingsLayout(
47 sections,
48 html`<section class="settings-block">
49 <p class="muted small">Declare a device on this forge's network once; an app prints to it only when you grant it.</p>
50 ${when(rows.length > 0, () => html`<ul class="list setting-list">${rows}</ul>`)}
51 <form class="edit-row mt" method="post" action="/settings/devices">
52 <label>Name <input class="input" name="name" maxlength="40" required /></label>
53 <label>Kind <select class="input" name="kind"><option value="printer">printer</option></select></label>
54 <label>
55 IPP URL
56 <input
57 class="input mono"
58 name="url"
59 placeholder="ipp://192.168.1.161:631/ipp/print"
60 autocomplete="off"
61 spellcheck="false"
62 required
63 />
64 </label>
65 ${btn("Declare", { variant: "primary", size: "sm", icon: "plus" })}
66 </form>
67 </section>`,
68 "Account settings",
69 )}`,
70 });
71 notePhase(ctx.request, "render", performance.now() - rendering);
72 return res;
73 }
74
75 const statusHtml = (st: DeviceStatus): Html =>
76 st.status === null
77 ? html`<p class="muted" role="status">Not reachable: ${st.problem ?? "unknown"}.</p>`
78 : st.status.fine
79 ? html`<p role="status">${st.status.line}</p>`
80 : html`<div role="status">
81 <p>${st.status.line}</p>
82 <ul class="list">
83 ${(st.probe?.supplies ?? []).map((s) => html`<li>${s.name}: ${s.level >= 0 ? `${s.level}%` : "unknown"}</li>`)}
84 </ul>
85 </div>`;
86
87 // GET /settings/devices/:name/status: the printer asked (or the last answer, if under 30 s old).
88 export async function deviceStatusPage(ctx: Ctx): Promise<Response> {
89 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
90 const denied = admin(ctx);
91 if (denied) return denied;
92 const name = ctx.params["name"] ?? "";
93 const status = await deviceStatus(ctx.app, ctx.auth.user, name);
94 if (!status.ok) return notFoundPage(ctx);
95 return page({
96 ctx,
97 title: `${name} status`,
98 body: html`<div class="page-head"><h1>${name}</h1></div>
99 ${settingsLayout(
100 sections,
101 html`<section class="settings-block">
102 ${statusHtml(status.value)}
103 <p class="small"><a href="${here(name)}">Back to ${name}</a></p>
104 </section>`,
105 "Account settings",
106 )}`,
107 });
108 }
109
110 // GET /settings/devices/:name
111 export async function devicePage(ctx: Ctx): Promise<Response> {
112 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
113 const denied = admin(ctx);
114 if (denied) return denied;
115 const view = deviceView(ctx.app, ctx.auth.user, ctx.params["name"] ?? "");
116 if (!view.ok) return notFoundPage(ctx);
117 const { device, grants, jobs } = view.value;
118 // Never waits on the printer: a fresh answer is shown, otherwise a link asks.
119 const fresh = cachedStatus(device);
120 const probed = fresh ? await fresh : undefined;
121 const state: Html = probed
122 ? statusHtml({
123 status: probed.ok ? probeLine(probed.value) : null,
124 probe: probed.ok ? probed.value : null,
125 problem: probed.ok ? null : probed.error,
126 })
127 : html`<p><a href="${here(device.name)}/status">Check the printer</a></p>`;
128 const grantRows = grants.map((g) =>
129 row({
130 title: g.app,
131 meta: html`${String(g.usedToday)} of ${String(g.dailyCap)} jobs today`,
132 trail: html`<form class="row-actions" method="post" action="${here(device.name)}/revoke">
133 <input type="hidden" name="app" value="${g.app}" />
134 ${btn("Revoke", { size: "sm", icon: "x", label: `Revoke ${g.app}` })}
135 </form>`,
136 }),
137 );
138 const jobRows = jobs.map((j) =>
139 row({
140 title: html`${j.app} · ${String(j.pages)} ${j.pages === 1 ? "page" : "pages"}`,
141 meta: html`${j.outcome}${j.jobState ? ` · ${j.jobState}` : ""} · ${time(j.createdAt)}`,
142 }),
143 );
144 return page({
145 ctx,
146 title: device.name,
147 body: html`<div class="page-head"><h1>${device.name}</h1></div>
148 ${settingsLayout(
149 sections,
150 html`<section class="settings-block">
151 <p class="muted small">${device.kind} · <span class="mono">${device.url}</span></p>
152 ${state}
153 <h2>Apps that may print</h2>
154 ${when(grantRows.length > 0, () => html`<ul class="list setting-list">${grantRows}</ul>`)}
155 <form class="edit-row mt" method="post" action="${here(device.name)}/grant">
156 <label>App <input class="input" name="app" placeholder="owner/app" required /></label>
157 <label>
158 Jobs a day
159 <input class="input" name="daily_cap" type="number" min="1" max="1000" value="${String(DEFAULT_DAILY_CAP)}" />
160 </label>
161 ${btn("Grant", { variant: "primary", size: "sm", icon: "plus" })}
162 </form>
163 ${when(
164 jobRows.length > 0,
165 () => html`<details class="mt"><summary>${String(jobRows.length)} recent jobs</summary><ul class="list setting-list">${jobRows}</ul></details>`,
166 )}
167 </section>
168 <p class="mt">${confirmAction({ action: `${here(device.name)}/remove`, verb: "Remove this device", size: "sm" })}</p>`,
169 "Account settings",
170 )}`,
171 });
172 }
173
174 async function act(ctx: Ctx, to: (name: string, f: Form) => { done: string; error?: string; back?: string }): Promise<Response> {
175 const denied = admin(ctx);
176 if (denied) return denied;
177 const form = await readForm(ctx, "admin");
178 if (form instanceof Response) return form;
179 const out = to(ctx.params["name"] ?? "", form);
180 return flashTo(
181 ctx,
182 out.back ?? "/settings/devices",
183 out.error === undefined ? { message: out.done } : { tone: "danger", message: out.error },
184 );
185 }
186
187 // POST /settings/devices
188 export async function deviceDeclare(ctx: Ctx): Promise<Response> {
189 return act(ctx, (_n, f) => {
190 const name = field(f, "name");
191 const made = declare(ctx.app, ctx.auth.user, { name, kind: field(f, "kind"), url: field(f, "url") });
192 return made.ok
193 ? { done: `${made.value.name} is declared.`, back: here(made.value.name) }
194 : { done: "", error: made.error };
195 });
196 }
197
198 // POST /settings/devices/:name/grant
199 export async function deviceGrant(ctx: Ctx): Promise<Response> {
200 return act(ctx, (name, f) => {
201 const cap = field(f, "daily_cap").trim();
202 const done = grant(ctx.app, ctx.auth.user, name, field(f, "app"), cap === "" ? undefined : Number(cap));
203 return { done: "Granted.", back: here(name), ...(done.ok ? {} : { error: done.error }) };
204 });
205 }
206
207 // POST /settings/devices/:name/revoke
208 export async function deviceRevoke(ctx: Ctx): Promise<Response> {
209 return act(ctx, (name, f) => {
210 const done = revoke(ctx.app, ctx.auth.user, name, field(f, "app"));
211 return { done: "Revoked.", back: here(name), ...(done.ok ? {} : { error: done.error }) };
212 });
213 }
214
215 // POST /settings/devices/:name/remove
216 export async function deviceRemove(ctx: Ctx): Promise<Response> {
217 return act(ctx, (name) => {
218 const gone = removeDeclared(ctx.app, ctx.auth.user, name);
219 return { done: `${name} is removed.`, ...(gone.ok ? {} : { error: gone.error }) };
220 });
221 }
src/web/pages/origins.ts +3 −1
@@ -114,7 +114,8 @@ export type AccountSection =
114114 | "economics"
115115 | "flags"
116116 | "features"
117 | "cloud";
117 | "cloud"
118 | "devices";
118119
119120 /**
120121 * The settings sidebar, with Origins on it. Kept here so the account pages
@@ -150,6 +151,7 @@ const SECTION_ROWS: readonly (readonly [
150151 ["Connections", "Origins", "/settings/origins", "globe", (c) => c === "origins", false],
151152 ["Connections", "Cloud accounts", "/settings/cloud", "key", (c) => c === "cloud", true],
152153 ["Connections", "Secrets", "/settings/secrets", "lock", (c) => c === "secrets", true],
154 ["Connections", "Devices", "/settings/devices", "printer", (c) => c === "devices", true],
153155 ["Security", "Security", "/settings/security", "lock", (c) => c === "security", true],
154156 ["Security", "Traffic", "/settings/traffic", "users", (c) => c === "traffic", true],
155157 ["Security", "Trusted sources", "/settings/trusted", "lock", (c) => c === "trusted", true],
src/web/pages/search.ts +9
@@ -735,6 +735,15 @@ const DESTRUCTIVE: {
735735 phrase: "",
736736 }),
737737 },
738 {
739 pattern: /^\/settings\/devices\/([a-z0-9-]+)\/remove$/,
740 describe: (m) => ({
741 verb: "Remove device",
742 title: `Remove the device ${m[1]}?`,
743 detail: "Every app's grant to it goes too, and no app can print to it until you declare it again. The printer itself is untouched.",
744 phrase: "",
745 }),
746 },
738747 {
739748 pattern: /^\/settings\/origins\/([^/]+)\/delete$/,
740749 describe: () => ({
test/devices.test.ts added +398
@@ -0,0 +1,398 @@
1 /** Home devices (#10413): declare, grant, print through the relay, against a fake IPP printer. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp as makeApp } from "../src/core/apps.ts";
9 import { getRepo } from "../src/core/repos.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import {
13 getDevice,
14 listJobs,
15 logJob,
16 parseDeviceUrl,
17 REJECTED_DAILY_MAX,
18 settleJob,
19 tidyJobs,
20 } from "../src/core/devices.ts";
21 import { printForApp } from "../src/devices/relay.ts";
22 import { deviceList } from "../src/actions/devices.ts";
23 import { createUser } from "../src/core/users.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { mintAppToken } from "../src/apps/token.ts";
26 import { seedAdmin } from "./helpers/admin.ts";
27 import { proveAll } from "./helpers/verified.ts";
28 import type { User } from "../src/core/users.ts";
29
30 const enc = new TextEncoder();
31 const piece = (tag: number, name: string, value: Uint8Array): number[] => {
32 const n = enc.encode(name);
33 return [tag, n.length >> 8, n.length & 255, ...n, value.length >> 8, value.length & 255, ...value];
34 };
35 const int = (n: number): Uint8Array => Uint8Array.of(n >>> 24, (n >> 16) & 255, (n >> 8) & 255, n & 255);
36 const text = (s: string): Uint8Array => enc.encode(s);
37 const reply = (status: number, groupTag: number, parts: number[][]): Uint8Array =>
38 Uint8Array.of(2, 0, status >> 8, status & 255, 0, 0, 0, 1, groupTag, ...parts.flat(), 3);
39
40 function pdf(pages: number): Uint8Array {
41 const objs = Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n");
42 return enc.encode(`%PDF-1.4\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${objs}\n%%EOF`);
43 }
44
45 describe("home devices", () => {
46 let dataDir: string;
47 let app: App;
48 let servers: Servers;
49 let admin: User;
50 let cookie: string;
51 let appToken: string;
52 let printer: ReturnType<typeof Bun.serve>;
53 const seen: { op: number; bytes: number; path: string }[] = [];
54 let stopped = false;
55
56 const api = (path: string, init: RequestInit & { token?: string } = {}) => {
57 const { token, ...rest } = init;
58 return fetch(`${servers.url}/api/v1${path}`, {
59 ...rest,
60 headers: {
61 ...(token ? { authorization: `Bearer ${token}` } : { cookie }),
62 "content-type": "application/json",
63 ...(rest.headers as Record<string, string>),
64 },
65 });
66 };
67 const declareFake = () =>
68 api("/devices", { method: "POST", body: JSON.stringify({ name: "brother", kind: "printer", url: `ipp://127.0.0.1:${printer.port}/ipp/print` }) });
69 const print = (name: string, body: Uint8Array, token = appToken) =>
70 api(`/devices/${name}/print`, { method: "POST", body, token, headers: { "content-type": "application/pdf" } });
71
72 beforeAll(async () => {
73 process.env["FORGE_DEVICE_LOOPBACK"] = "1";
74 printer = Bun.serve({
75 port: 0,
76 hostname: "127.0.0.1",
77 async fetch(req) {
78 const bytes = new Uint8Array(await req.arrayBuffer());
79 const op = (bytes[2]! << 8) | bytes[3]!;
80 seen.push({ op, bytes: bytes.length, path: new URL(req.url).pathname });
81 if (stopped) return new Response("no", { status: 503 });
82 const out =
83 op === 0x000b
84 ? reply(0, 4, [
85 piece(0x41, "printer-make-and-model", text("Brother HL-L2350DW")),
86 piece(0x23, "printer-state", int(3)),
87 piece(0x44, "printer-state-reasons", text("none")),
88 piece(0x42, "marker-names", text("Black Toner")),
89 piece(0x21, "marker-levels", int(80)),
90 ])
91 : reply(0, 5, [piece(0x21, "job-id", int(7)), piece(0x23, "job-state", int(9))]);
92 return new Response(out, { headers: { "content-type": "application/ipp" } });
93 },
94 });
95 dataDir = await mkdtemp(join(tmpdir(), "forge-devices-"));
96 app = createApp({ dataDir, port: 0 });
97 servers = await serve(app);
98 const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
99 if (!made.ok) throw new Error(made.error);
100 admin = made.value;
101 proveAll(app);
102 cookie = `forge_session=${createSession(app.db, admin.id).token}`;
103 for (const name of ["paper", "other"]) {
104 const repo = await createRepo(app, admin, { name, visibility: "private" });
105 if (!repo.ok) throw new Error(String(repo.error));
106 makeApp(app.db, { repoId: getRepo(app.db, "alice", name)!.id, slug: name, access: "private" });
107 }
108 appToken = mintAppToken(app.db, admin.id, "paper", "production").token;
109 });
110 afterAll(async () => {
111 delete process.env["FORGE_DEVICE_LOOPBACK"];
112 printer.stop(true);
113 servers.stop();
114 app.close();
115 await rm(dataDir, { recursive: true, force: true });
116 });
117
118 test("declare refuses any address that is not a private LAN literal", () => {
119 delete process.env["FORGE_DEVICE_LOOPBACK"];
120 try {
121 for (const bad of [
122 "ipp://127.0.0.1:631/ipp/print",
123 "ipp://169.254.169.254/latest",
124 "ipp://8.8.8.8:631/ipp/print",
125 "ipp://10.43.0.1:631/x",
126 "ipp://printer.local:631/ipp/print",
127 "http://[::1]:631/",
128 "https://192.168.1.161/",
129 "ipp://u:[email protected]/",
130 ])
131 expect(parseDeviceUrl(bad).ok).toBe(false);
132 const ok = parseDeviceUrl("ipp://192.168.1.161/ipp/print");
133 expect(ok.ok && ok.value.uri).toBe("ipp://192.168.1.161:631/ipp/print");
134 } finally {
135 process.env["FORGE_DEVICE_LOOPBACK"] = "1";
136 }
137 });
138
139 test("only the owner declares; the page probes the printer and says one line", async () => {
140 const stranger = await api("/devices", { method: "GET", token: appToken });
141 expect(stranger.status).toBe(403);
142 expect((await declareFake()).status).toBe(201);
143 expect((await declareFake()).status).toBe(422);
144 // The device itself never waits on the printer: it answers from the database.
145 const before = seen.length;
146 const view = (await (await api("/devices/brother")).json()) as { device: { name: string }; status?: unknown };
147 expect(view.device.name).toBe("brother");
148 expect(view.status).toBeUndefined();
149 const bare = await (await fetch(`${servers.url}/settings/devices/brother`, { headers: { cookie } })).text();
150 expect(bare).toContain("Check the printer");
151 expect(bare).not.toContain("Brother HL-L2350DW");
152 expect(seen.length).toBe(before);
153 // The status is its own request, and is asked of the printer once in 30 s.
154 const status = (await (await api("/devices/brother/status")).json()) as { status: { line: string } };
155 expect(status.status.line).toBe("Brother HL-L2350DW · idle · supplies fine");
156 const page = await fetch(`${servers.url}/settings/devices/brother/status`, { headers: { cookie } });
157 expect(await page.text()).toContain("Brother HL-L2350DW · idle · supplies fine");
158 expect(seen.filter((s) => s.op === 0x000b && s.path === "/ipp/print").length).toBe(1);
159 const warm = await (await fetch(`${servers.url}/settings/devices/brother`, { headers: { cookie } })).text();
160 expect(warm).toContain("Brother HL-L2350DW · idle · supplies fine");
161 });
162
163 test("no grant, no job: the printer is never asked", async () => {
164 const before = seen.length;
165 expect((await print("brother", pdf(1))).status).toBe(404);
166 expect(seen.length).toBe(before);
167 });
168
169 test("a granted app prints and gets the job state; the job is logged", async () => {
170 const granted = await api("/devices/brother/grants", { method: "PUT", body: JSON.stringify({ app: "alice/paper", daily_cap: 2 }) });
171 expect(granted.status).toBe(200);
172 const res = await print("brother", pdf(3));
173 expect(res.status).toBe(201);
174 expect(await res.json()).toMatchObject({ state: "completed", pages: 3 });
175 const sent = seen.filter((s) => s.op === 0x0002);
176 expect(sent.length).toBe(1);
177 expect(sent[0]!.bytes).toBeGreaterThan(pdf(3).length);
178 const jobs = listJobs(app.db, getDevice(app.db, "brother")!.id);
179 expect(jobs[0]).toMatchObject({ app: "alice/paper", pages: 3, outcome: "accepted", jobState: "completed" });
180 });
181
182 test("a grant is for one app: another app's token and a person's lookalike token get nothing", async () => {
183 const other = mintAppToken(app.db, admin.id, "other", "production").token;
184 expect((await print("brother", pdf(1), other)).status).toBe(404);
185 const posed = createToken(app.db, admin.id, "app:paper/production", "ro");
186 // Same owner, same name shape: a person's own token named like an app is the owner's act, and
187 // an outsider's cannot be: the name must belong to a token held by the app's repo owner.
188 expect((await print("brother", pdf(1), posed.token)).status).toBe(201);
189 const plain = createToken(app.db, admin.id, "my laptop", "ro");
190 expect((await print("brother", pdf(1), plain.token)).status).toBe(404);
191 });
192
193 test("the daily cap holds and the refusal is logged", async () => {
194 // two jobs went through above (cap 2), so the next is over.
195 const before = seen.filter((s) => s.op === 0x0002).length;
196 const res = await print("brother", pdf(1));
197 expect(res.status).toBe(429);
198 expect(seen.filter((s) => s.op === 0x0002).length).toBe(before);
199 expect(listJobs(app.db, getDevice(app.db, "brother")!.id)[0]).toMatchObject({ outcome: "over_cap" });
200 // The owner raises it.
201 await api("/devices/brother/grants", { method: "PUT", body: JSON.stringify({ app: "alice/paper", daily_cap: 50 }) });
202 expect((await print("brother", pdf(1))).status).toBe(201);
203 });
204
205 test("limits: not a PDF, too many pages, too big", async () => {
206 expect((await print("brother", enc.encode("hello"))).status).toBe(422);
207 expect((await print("brother", pdf(21))).status).toBe(422);
208 const big = new Uint8Array(10 * 1024 * 1024 + 10);
209 big.set(enc.encode("%PDF-1.4"));
210 // The forge closes a connection it refused to read to the end; the client must not reuse it.
211 const refused = await api("/devices/brother/print", {
212 method: "POST",
213 body: big,
214 token: appToken,
215 headers: { "content-type": "application/pdf", connection: "close" },
216 });
217 expect(refused.status).toBe(413);
218 const outcomes = listJobs(app.db, getDevice(app.db, "brother")!.id, 3).map((j) => j.outcome);
219 expect(outcomes).toEqual(["too_big", "too_long", "not_pdf"]);
220 });
221
222 test("a printer that is down is a logged failure, not a hang", async () => {
223 stopped = true;
224 const res = await print("brother", pdf(1)).finally(() => (stopped = false));
225 expect(res.status).toBe(502);
226 expect(listJobs(app.db, getDevice(app.db, "brother")!.id)[0]).toMatchObject({ outcome: "failed" });
227 });
228
229 test("an app cannot name an address: the body and query steer nothing", async () => {
230 const before = seen.length;
231 const res = await fetch(`${servers.url}/api/v1/devices/brother/print?url=ipp://10.0.0.5/x`, {
232 method: "POST",
233 headers: { authorization: `Bearer ${appToken}`, "x-printer-uri": "ipp://10.0.0.5/x" },
234 body: pdf(1),
235 });
236 expect(res.status).toBe(201);
237 expect(seen.length - before).toBe(1);
238 expect((await print("10.0.0.5", pdf(1))).status).toBe(404);
239 });
240
241 test("revoking takes the door away", async () => {
242 await api("/devices/brother/grants", { method: "DELETE", body: JSON.stringify({ app: "alice/paper" }) });
243 expect((await print("brother", pdf(1))).status).toBe(404);
244 });
245
246 describe("who may, and what is bounded", () => {
247 const pages: [string, string][] = [
248 ["GET", "/settings/devices"],
249 ["GET", "/settings/devices/brother"],
250 ["GET", "/settings/devices/brother/status"],
251 ["POST", "/settings/devices"],
252 ["POST", "/settings/devices/brother/grant"],
253 ["POST", "/settings/devices/brother/revoke"],
254 ["POST", "/settings/devices/brother/remove"],
255 ];
256 const routes: [string, string][] = [
257 ["GET", "/devices"],
258 ["POST", "/devices"],
259 ["GET", "/devices/brother"],
260 ["GET", "/devices/brother/status"],
261 ["DELETE", "/devices/brother"],
262 ["PUT", "/devices/brother/grants"],
263 ["DELETE", "/devices/brother/grants"],
264 ];
265 let bobCookie: string;
266 let agentCookie: string;
267 let agentUser: User;
268 let bobToken: string;
269
270 beforeAll(async () => {
271 const bob = await createUser(app.db, { origin: "seed", username: "bob", email: "[email protected]", password: "a-good-passphrase", trusted: true });
272 if (!bob.ok) throw new Error(bob.error);
273 bobCookie = `forge_session=${createSession(app.db, bob.value.id).token}`;
274 bobToken = createToken(app.db, bob.value.id, "app:paper/production", "ro").token;
275 const bot = await createUser(app.db, { origin: "seed", username: "botty", email: "[email protected]", password: "a-good-passphrase", isAdmin: true, trusted: true });
276 if (!bot.ok) throw new Error(bot.error);
277 app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(bot.value.id);
278 agentCookie = `forge_session=${createSession(app.db, bot.value.id).token}`;
279 agentUser = { ...bot.value, kind: "agent" };
280 proveAll(app);
281 });
282
283 const hit = (method: string, path: string, headers: Record<string, string>) =>
284 fetch(`${servers.url}${path}`, {
285 method,
286 redirect: "manual",
287 headers: { origin: servers.url, "content-type": "application/json", ...headers },
288 ...(method === "GET" || method === "DELETE" ? {} : { body: "{}" }),
289 });
290
291 test("a guest and a non-admin see no page and no route, and change nothing", async () => {
292 const before = listJobs(app.db, getDevice(app.db, "brother")!.id).length;
293 for (const [method, path] of pages) {
294 const guest = await hit(method, path, {});
295 expect([302, 303, 401, 404]).toContain(guest.status);
296 expect((await guest.text()).includes("brother")).toBe(false);
297 expect((await hit(method, path, { cookie: bobCookie })).status).toBe(404);
298 }
299 for (const [method, path] of routes) {
300 expect([401, 403, 404]).toContain((await hit(method, `/api/v1${path}`, {})).status);
301 expect([403, 404]).toContain((await hit(method, `/api/v1${path}`, { cookie: bobCookie })).status);
302 }
303 expect(getDevice(app.db, "brother")).toBeDefined();
304 expect(listJobs(app.db, getDevice(app.db, "brother")!.id).length).toBe(before);
305 });
306
307 test("removing a device asks first: the page links to the confirm step, not a bare button", async () => {
308 const page = await (await fetch(`${servers.url}/settings/devices/brother`, { headers: { cookie } })).text();
309 expect(page).toContain("/-/confirm?to=%2Fsettings%2Fdevices%2Fbrother%2Fremove");
310 expect(page).not.toContain('action="/settings/devices/brother/remove"');
311 const confirm = await fetch(`${servers.url}/-/confirm?to=${encodeURIComponent("/settings/devices/brother/remove")}`, { headers: { cookie } });
312 expect(await confirm.text()).toContain("Remove the device brother?");
313 });
314
315 test("an admin account that is an agent is refused as well", async () => {
316 expect(deviceList(app, agentUser).ok).toBe(false);
317 for (const [method, path] of pages) expect((await hit(method, path, { cookie: agentCookie })).status).not.toBe(200);
318 const declared = await hit("POST", "/api/v1/devices", { cookie: agentCookie });
319 expect([403, 404]).toContain(declared.status);
320 const made = await fetch(`${servers.url}/api/v1/devices`, {
321 method: "POST",
322 headers: { cookie: agentCookie, "content-type": "application/json" },
323 body: JSON.stringify({ name: "sneaky", kind: "printer", url: `ipp://127.0.0.1:${printer.port}/x` }),
324 });
325 expect([403, 404]).toContain(made.status);
326 expect(getDevice(app.db, "sneaky")).toBeUndefined();
327 });
328
329 test("a token named app:<slug>/x held by someone who does not own the app prints nothing", async () => {
330 await api("/devices/brother/grants", { method: "PUT", body: JSON.stringify({ app: "alice/paper", daily_cap: 50 }) });
331 const before = seen.filter((s) => s.op === 0x0002).length;
332 expect((await print("brother", pdf(1), bobToken)).status).toBe(404);
333 expect(seen.filter((s) => s.op === 0x0002).length).toBe(before);
334 });
335
336 test("jobs racing the cap: only the cap reaches the printer", async () => {
337 await api("/devices/brother/grants", { method: "PUT", body: JSON.stringify({ app: "alice/other", daily_cap: 1 }) });
338 const other = mintAppToken(app.db, admin.id, "other", "production").token;
339 const before = seen.filter((s) => s.op === 0x0002).length;
340 const results = await Promise.all([1, 2, 3, 4].map(() => print("brother", pdf(1), other)));
341 expect(results.map((r) => r.status).sort()).toEqual([201, 429, 429, 429]);
342 expect(seen.filter((s) => s.op === 0x0002).length - before).toBe(1);
343 });
344
345 test("an address spelled to hide itself is no LAN address", () => {
346 process.env["FORGE_DEVICE_LOOPBACK"] = "0";
347 for (const bad of [
348 "ipp://0300.0250.1.1/ipp",
349 "ipp://3232235777/ipp",
350 "ipp://0xc0.0xa8.1.1/ipp",
351 "ipp://192.168.1/ipp",
352 "http://0177.0.0.1/ipp",
353 "http://2130706433/ipp",
354 "http://0x7f.1/ipp",
355 "http://0xa9.0xfe.0xa9.0xfe/ipp",
356 "http://2852039166/ipp",
357 "ipp://[::ffff:192.168.1.1]/ipp",
358 "ipp://192.168.1.1%[email protected]/ipp",
359 ])
360 expect(parseDeviceUrl(bad).ok).toBe(false);
361 });
362
363 test("refusals are logged up to a day's allowance, then only answered", async () => {
364 const device = getDevice(app.db, "brother")!;
365 const caller = { repoId: getRepo(app.db, "alice", "paper")!.id, slug: "alice/paper" };
366 const rows = (): number =>
367 app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM print_job WHERE repo_id = ?1 AND outcome NOT IN ('reserved', 'accepted', 'failed')").get(caller.repoId)!.n;
368 const before = rows();
369 for (let i = 0; i < REJECTED_DAILY_MAX + 20; i++) {
370 const done = await printForApp(app.db, device, caller, enc.encode("not a pdf"));
371 expect(done.ok).toBe(false);
372 }
373 expect(rows()).toBe(Math.max(before, REJECTED_DAILY_MAX));
374 // A body over the cap is named, not allocated: refused the same way.
375 const big = await printForApp(app.db, device, caller, "too_big");
376 expect(big).toEqual({ ok: false, error: { kind: "too_big" } });
377 });
378
379 test("a reservation a crash left is settled, and old rows are dropped", () => {
380 const device = getDevice(app.db, "brother")!;
381 const repoId = getRepo(app.db, "alice", "paper")!.id;
382 const stale = logJob(app.db, { deviceId: device.id, repoId, app: "alice/paper", pages: 1, outcome: "reserved" });
383 const fresh = logJob(app.db, { deviceId: device.id, repoId, app: "alice/paper", pages: 1, outcome: "reserved" });
384 const old = logJob(app.db, { deviceId: device.id, repoId, app: "alice/paper", pages: 1, outcome: "accepted" });
385 const at = (id: string, ms: number) =>
386 app.db.query("UPDATE print_job SET created_at = ?2 WHERE id = ?1").run(id, new Date(Date.now() - ms).toISOString());
387 at(stale, 11 * 60_000);
388 at(fresh, 60_000);
389 at(old, 40 * 86_400_000);
390 tidyJobs(app.db);
391 const outcome = (id: string) => app.db.query<{ outcome: string }, [string]>("SELECT outcome FROM print_job WHERE id = ?1").get(id)?.outcome;
392 expect(outcome(stale)).toBe("failed");
393 expect(outcome(fresh)).toBe("reserved");
394 expect(outcome(old)).toBeUndefined();
395 settleJob(app.db, fresh, "failed");
396 });
397 });
398 });
test/mcp-devices.test.ts added +82
@@ -0,0 +1,82 @@
1 /** The `devices` tool is /api/v1/devices over MCP: the same actions, the owner's admin token only. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp as makeApp } from "../src/core/apps.ts";
9 import { getRepo } from "../src/core/repos.ts";
10 import { createToken } from "../src/core/tokens.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { promote } from "./helpers/members.ts";
14 import { listVia } from "./mcp-list.ts";
15
16 describe("MCP devices", () => {
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let admin: string;
21 let adminRw: string;
22 let other: string;
23 let id = 1;
24
25 const rpc = async (token: string, method: string, params?: unknown) => {
26 const res = await fetch(`${servers.url}/mcp`, {
27 method: "POST",
28 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
29 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method, params }),
30 });
31 return (await res.json()) as any;
32 };
33 const tool = async (token: string, args: unknown) => {
34 const body = await rpc(token, "tools/call", { name: "devices", arguments: args });
35 return { text: body.result.content[0].text as string, isError: body.result.isError === true };
36 };
37
38 beforeAll(async () => {
39 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-devices-"));
40 app = createApp({ dataDir, port: 0 });
41 servers = await serve(app);
42 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
43 if (!a.ok) throw new Error(a.error);
44 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
45 if (!b.ok) throw new Error(b.error);
46 promote(app.db, b.value);
47 admin = createToken(app.db, a.value.id, "admin", "admin").token;
48 adminRw = createToken(app.db, a.value.id, "rw", "rw").token;
49 other = createToken(app.db, b.value.id, "rw", "rw").token;
50 const made = await createRepo(app, a.value, { name: "paper", visibility: "private" });
51 if (!made.ok) throw new Error(String(made.error));
52 makeApp(app.db, { repoId: getRepo(app.db, "alice", "paper")!.id, slug: "paper", access: "private" });
53 }, 30_000);
54 afterAll(async () => {
55 servers.stop();
56 app.close();
57 await rm(dataDir, { recursive: true, force: true });
58 });
59
60 test("an admin declares, grants, shows, revokes and removes", async () => {
61 const url = "ipp://192.168.1.161:631/ipp/print";
62 expect((await tool(admin, { action: "declare", name: "office", kind: "printer", url })).isError).toBe(false);
63 expect((await tool(admin, { action: "grant", name: "office", app: "alice/paper", daily_cap: 4 })).isError).toBe(false);
64 const shown = JSON.parse((await tool(admin, { action: "show", name: "office" })).text);
65 expect(shown.grants[0]).toMatchObject({ app: "alice/paper", dailyCap: 4, usedToday: 0 });
66 expect(JSON.parse((await tool(admin, { action: "list" })).text).items.map((d: any) => d.name)).toEqual(["office"]);
67 expect((await tool(admin, { action: "declare", name: "bad", kind: "printer", url: "ipp://8.8.8.8/x" })).isError).toBe(true);
68 expect((await tool(admin, { action: "revoke", name: "office", app: "alice/paper" })).isError).toBe(false);
69 expect((await tool(admin, { action: "remove", name: "office" })).isError).toBe(false);
70 expect(JSON.parse((await tool(admin, { action: "list" })).text).items).toEqual([]);
71 });
72
73 test("an rw token and a non-admin are refused, and the tool is not listed to the non-admin", async () => {
74 const r = await tool(adminRw, { action: "list" });
75 expect(r.isError).toBe(true);
76 expect(r.text).toContain("forbidden");
77 const listed = await listVia((p) => rpc(other, "tools/list", p));
78 expect(listed.result.tools.map((t: any) => t.name)).not.toContain("devices");
79 const call = await rpc(other, "tools/call", { name: "devices", arguments: { action: "list" } });
80 expect(call.error ?? call.result.isError).toBeTruthy();
81 });
82 });
test/mcp.test.ts +1
@@ -243,6 +243,7 @@ describe("the forge over MCP", () => {
243243 "asks_undecide",
244244 "seal",
245245 "secrets",
246 "devices",
246247 "issue_teams",
247248 "issues",
248249 "iterations",
test/palette-roster.test.ts +1
@@ -115,6 +115,7 @@ test("a site-admin person is offered the whole roster", () => {
115115 ["access", "Access", "what outside agents tried"],
116116 ["flags", "Flags", "declared flags and their live values"],
117117 ["secrets", "Secrets", "sealed secrets by name; set or remove one"],
118 ["devices", "Devices", "LAN printers an app may use; declare, grant, revoke, remove"],
118119 ["trusted-hosts", "Trusted hosts", "internal hosts an origin may reach"],
119120 ["usage", "Usage", "the forge's spend and headroom; an admin also sees every route"],
120121 ["crew-scorecard", "Crew scorecard", "agent runs per model and per prompt version"],
test/tui-devices.test.ts added +162
@@ -0,0 +1,162 @@
1 /**
2 * Home devices in the terminal (#10413): the forge's owner declares a device,
3 * grants an app, revokes and removes it from the screen, each write appending
4 * the event web viewers get; anyone else is offered nothing and, driving the
5 * screen directly, sees and changes nothing.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App as Forge } from "../src/app.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp as makeApp } from "../src/core/apps.ts";
14 import { getDevice, listGrants } from "../src/core/devices.ts";
15 import { getRepo } from "../src/core/repos.ts";
16 import { createUser, getUserByName } from "../src/core/users.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { devicesScreen, parseGrant } from "../src/tui/screens/devices.ts";
19 import { Session, type TuiIdentity } from "../src/tui/session.ts";
20 import { headlessTerminal } from "../src/tui/term/terminal.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { settleApp } from "./helpers/tui.ts";
23
24 quietLogs();
25
26 describe("devices in the terminal", () => {
27 let dataDir: string;
28 let forge: Forge;
29 let printer: ReturnType<typeof Bun.serve>;
30
31 function boot(username: string) {
32 const terminal = headlessTerminal(140, 32);
33 const user = getUserByName(forge.db, username)!;
34 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user };
35 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
36 app.start();
37 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
38 return {
39 text: () => app.screen.toText(),
40 press: async (...keys: string[]) => {
41 for (const k of keys) {
42 key(k);
43 await settleApp(app);
44 }
45 },
46 ctrl: async (k: string) => {
47 app.dispatch({ type: "key", key: k, ctrl: true, alt: false, shift: false });
48 await settleApp(app);
49 },
50 type: async (t: string) => {
51 for (const ch of t) key(ch);
52 await settleApp(app);
53 },
54 stop: () => app.stop(),
55 };
56 }
57
58 beforeAll(async () => {
59 process.env["FORGE_DEVICE_LOOPBACK"] = "1";
60 printer = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("no", { status: 503 }) });
61 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-devices-"));
62 forge = createApp({ dataDir, port: 0 });
63 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
64 const made = await createUser(forge.db, {
65 origin: "seed",
66 trusted: true,
67 username,
68 email: `${username}@forge.local`,
69 password: "a-good-passphrase",
70 adminIfFirst,
71 });
72 if (!made.ok) throw new Error(made.error);
73 }
74 const alice = getUserByName(forge.db, "alice")!;
75 const repo = await createRepo(forge, alice, { name: "paper", visibility: "private" });
76 if (!repo.ok) throw new Error(String(repo.error));
77 makeApp(forge.db, { repoId: getRepo(forge.db, "alice", "paper")!.id, slug: "paper", access: "private" });
78 });
79 afterAll(async () => {
80 delete process.env["FORGE_DEVICE_LOOPBACK"];
81 printer.stop(true);
82 forge.close();
83 await rm(dataDir, { recursive: true, force: true });
84 });
85
86 const open = async (h: ReturnType<typeof boot>) => {
87 await h.ctrl("k");
88 await h.type("Devices");
89 await h.press("enter");
90 };
91
92 test("the owner declares, grants, revokes and removes; each write is an event web viewers get", async () => {
93 const h = boot("alice");
94 await open(h);
95 expect(h.text()).toContain("No device declared");
96
97 await h.press("n");
98 await h.type("office");
99 await h.press("enter");
100 await h.type(`ipp://127.0.0.1:${printer.port}/ipp/print`);
101 await h.press("enter");
102 expect(h.text()).toContain("office");
103 expect(getDevice(forge.db, "office")).toBeDefined();
104
105 await h.press("enter");
106 expect(h.text()).toContain("not reachable");
107 await h.press("g");
108 await h.type("alice/paper 3");
109 await h.press("enter");
110 expect(h.text()).toContain("alice/paper");
111 expect(h.text()).toContain("0 of 3 jobs today");
112 expect(listGrants(forge.db, getDevice(forge.db, "office")!.id)).toHaveLength(1);
113
114 await h.press("x");
115 await h.press("left", "enter"); // Revoke
116 expect(listGrants(forge.db, getDevice(forge.db, "office")!.id)).toHaveLength(0);
117
118 await h.press("d");
119 await h.press("left", "enter"); // Remove
120 expect(getDevice(forge.db, "office")).toBeUndefined();
121
122 const kinds = forge.db
123 .query<{ kind: string }, []>("SELECT kind FROM event WHERE kind LIKE 'device.%' ORDER BY rowid")
124 .all()
125 .map((r) => r.kind);
126 expect(kinds).toEqual(["device.declared", "device.granted", "device.revoked", "device.removed"]);
127 h.stop();
128 });
129
130 test("a refusal reads on the prompt and changes nothing", async () => {
131 const h = boot("alice");
132 await open(h);
133 await h.press("n");
134 await h.type("office");
135 await h.press("enter");
136 await h.type("ipp://8.8.8.8/ipp/print");
137 await h.press("enter");
138 expect(h.text()).toContain("not a private LAN address");
139 expect(getDevice(forge.db, "office")).toBeUndefined();
140 h.stop();
141 });
142
143 test("anyone else has no command and, driving the screen, sees and changes nothing", async () => {
144 const h = boot("bob");
145 await h.ctrl("k");
146 await h.type("Devices");
147 expect(h.text()).not.toContain("LAN printers");
148 h.stop();
149
150 const bob = getUserByName(forge.db, "bob")!;
151 const ctx = { invalidate() {}, push() {}, pop() {}, toast() {}, theme: { c: {} } } as never;
152 const screen = devicesScreen(new Session(forge, { sshUsername: "t", remoteAddress: "x", user: bob }) as never, ctx);
153 expect(screen.key({ key: "n", ctrl: false, alt: false, shift: false } as never)).toBe(false);
154 });
155
156 test("a grant line is an app and an optional whole cap", () => {
157 expect(parseGrant("alice/paper")).toEqual({ app: "alice/paper", cap: undefined });
158 expect(parseGrant("alice/paper 25")).toEqual({ app: "alice/paper", cap: 25 });
159 expect(typeof parseGrant("paper")).toBe("string");
160 expect(typeof parseGrant("alice/paper many")).toBe("string");
161 });
162 });
test/why-now.test.ts deleted −28
@@ -1,28 +0,0 @@
1 /** Retired 2026-11-09 with the pipeline-first direction: the gate no longer asks (`scripts/gate.ts`); the pure rule keeps its tests until the module goes. */
2 import { expect, test } from "bun:test";
3 import { featuresAdded, whyNowProblems } from "../src/kernel/why_now.ts";
4
5 const add = (path: string) => ({ status: "A", path });
6
7 test("a new action, page or route is a feature; edits, tests and other files are not", () => {
8 expect(featuresAdded([add("src/actions/x.ts"), add("src/web/pages/y.ts"), add("src/http/api/z.ts")])).toHaveLength(3);
9 expect(featuresAdded([add("src/http/mcp/tools/x.ts"), add("src/tui/app/screen.ts"), add("src/http/api/v1/y.ts")])).toHaveLength(3);
10 expect(featuresAdded([{ status: "M", path: "src/actions/x.ts" }, add("test/x.test.ts"), add("src/core/x.ts")])).toEqual([]);
11 });
12
13 test("a feature with no answer to the direction is refused, naming the rule and the file", () => {
14 const [p] = whyNowProblems([add("src/actions/x.ts")], ["Add x\n\nIt does x."]);
15 expect(p).toContain("say why it goes ahead of the pipeline");
16 expect(p).toContain("src/actions/x.ts");
17 });
18
19 test("a Why now line or a Pipeline line answers it; a thin reason does not", () => {
20 const changes = [add("src/actions/x.ts")];
21 expect(whyNowProblems(changes, ["Add x\n\nWhy now: the owner asked for it in #1234 this week"])).toEqual([]);
22 expect(whyNowProblems(changes, ["Add x\n\nPipeline: #6534"])).toEqual([]);
23 expect(whyNowProblems(changes, ["Add x\n\nWhy now: soon"])).toHaveLength(1);
24 });
25
26 test("a pull that adds no feature is never asked", () => {
27 expect(whyNowProblems([add("test/a.test.ts")], ["Fix a"])).toEqual([]);
28 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs