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 #10481
scout/forge:scout/10413-home-devices-declare-the-lan-printer-onc → main 4 commits fork
23 files
changed +936
−3
docs/design/attention-budget.json +2 −2
| @@ -109,12 +109,12 @@ | ||
| 109 | 109 | }, |
| 110 | 110 | "settings": { |
| 111 | 111 | "390": { |
| 112 | "words": 137, | |
| 112 | "words": 138, | |
| 113 | 113 | "blocks": 32, |
| 114 | 114 | "colours": 1 |
| 115 | 115 | }, |
| 116 | 116 | "1280": { |
| 117 | "words": 137, | |
| 117 | "words": 138, | |
| 118 | 118 | "blocks": 32, |
| 119 | 119 | "colours": 1 |
| 120 | 120 | } |
docs/design/audit.md +1
| @@ -114,6 +114,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 114 | 114 | - `/settings/resilience` — `pages/domains.ts` · failure domains and their last drill · `/resilience` · none seen. |
| 115 | 115 | - `/settings/backups` — `pages/backups.ts` (621 lines) · backups and restore · `/settings/resilience`, `/releases` · none seen. |
| 116 | 116 | - `/settings/flags` — `pages/flags.ts` · the forge's switches · none · none seen. |
| 117 | - `/settings/devices` — `pages/devices.ts` · the home printer declared once, apps granted to print on it · none · none seen. | |
| 117 | 118 | - `/settings/features` — `pages/features.ts` · apps absorbed as the forge's features, and their settings · `/apps` (the same apps, as apps) · none seen. |
| 118 | 119 | - `/settings/model` — `pages/model.ts` · which model the crew runs on · `/settings/crew` · none seen. |
| 119 | 120 | - `/settings/cloud` — `pages/cloud.ts` · cloud provider connection · none · none seen. |
docs/features/devices.md added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | # Home devices | |
| 2 | ||
| 3 | A site admin declares a LAN printer once; an app granted it prints through the forge, and reaches nothing else on the LAN. | |
| 4 | ||
| 5 | - **Declare:** `/settings/devices` (Settings, This forge, Devices) or `POST /api/v1/devices {name, kind: "printer", url}`, e.g. `ipp://192.168.1.161:631/ipp/print`. The address must be a private IPv4 literal (10/8, 172.16/12, 192.168/16) that is not the forge's own cluster range; names and loopback are refused. The forge probes it with IPP Get-Printer-Attributes; the device page shows model, state and supplies on one line (the problem instead, when unreachable). `POST /api/v1/devices/:name/probe` probes again. | |
| 6 | - **Grant:** the device page, or `POST /api/v1/devices/:name/grants {repo: "owner/app", daily_cap}`. Default cap: 10 jobs a day (UTC day), 0 to 1000, set by the admin. | |
| 7 | - **Print:** `POST /api/v1/repos/:owner/:app/print?device=NAME` with the PDF as the body and a token that can write the app (`rw`). At most 10 MB and 20 pages. Answers 201 `{jobId, state, pages}`; refusals are 403 `no_grant`, 400 `invalid`, 413 `too_big`/`too_many_pages`, 429 `cap`, 502 `unreachable`/`rejected`. | |
| 8 | - **Log:** every attempt (printed, failed or refused) is a row with app, pages and outcome, shown on the device page. | |
| 9 | ||
| 10 | Left out: page counting reads the PDF's page objects, so a PDF that hides pages in compressed object streams is refused as `invalid` rather than counted; no MCP tool; no job-status polling after the first state; no other device kinds. |
scripts/unreached-allow.json −1
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | "src/flow/review_rounds.ts", |
| 16 | 16 | "src/flow/shared_red.ts", |
| 17 | 17 | "src/flow/stale_fold.ts", |
| 18 | "src/kernel/why_now.ts", | |
| 19 | 18 | "src/spawn/pod.ts", |
| 20 | 19 | "src/tui/gallery.ts", |
| 21 | 20 | "src/tui/ui/qr.ts", |
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/getApiV1DevicesId.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/{id}", | |
| 6 | summary: "One device with its grants and recent print jobs (site admin, admin scope)", | |
| 7 | auth: true, | |
| 8 | }; |
src/contract/openapi/routes/index.ts +6
| @@ -69,6 +69,8 @@ export { route as getApiV1ConversationTurns } from "./getApiV1ConversationTurns. | ||
| 69 | 69 | export { route as getApiV1Conversations } from "./getApiV1Conversations.ts"; |
| 70 | 70 | export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts"; |
| 71 | 71 | export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts"; |
| 72 | export { route as getApiV1Devices } from "./getApiV1Devices.ts"; | |
| 73 | export { route as getApiV1DevicesId } from "./getApiV1DevicesId.ts"; | |
| 72 | 74 | export { route as getApiV1Explore } from "./getApiV1Explore.ts"; |
| 73 | 75 | export { route as getApiV1Family } from "./getApiV1Family.ts"; |
| 74 | 76 | export { route as getApiV1Features } from "./getApiV1Features.ts"; |
| @@ -253,6 +255,9 @@ export { route as postApiV1ConversationMessages } from "./postApiV1ConversationM | ||
| 253 | 255 | export { route as postApiV1ConversationStop } from "./postApiV1ConversationStop.ts"; |
| 254 | 256 | export { route as postApiV1ConversationTokens } from "./postApiV1ConversationTokens.ts"; |
| 255 | 257 | export { route as postApiV1Conversations } from "./postApiV1Conversations.ts"; |
| 258 | export { route as postApiV1Devices } from "./postApiV1Devices.ts"; | |
| 259 | export { route as postApiV1DevicesIdGrants } from "./postApiV1DevicesIdGrants.ts"; | |
| 260 | export { route as postApiV1DevicesIdProbe } from "./postApiV1DevicesIdProbe.ts"; | |
| 256 | 261 | export { route as postApiV1Drills } from "./postApiV1Drills.ts"; |
| 257 | 262 | export { route as postApiV1FeedChips } from "./postApiV1FeedChips.ts"; |
| 258 | 263 | export { route as postApiV1FeedInteractions } from "./postApiV1FeedInteractions.ts"; |
| @@ -314,6 +319,7 @@ export { route as postApiV1ReposOwnerNameMilestonesNumberLimb } from "./postApiV | ||
| 314 | 319 | export { route as postApiV1ReposOwnerNameOriginHook } from "./postApiV1ReposOwnerNameOriginHook.ts"; |
| 315 | 320 | export { route as postApiV1ReposOwnerNameOriginReconnect } from "./postApiV1ReposOwnerNameOriginReconnect.ts"; |
| 316 | 321 | export { route as postApiV1ReposOwnerNamePlan } from "./postApiV1ReposOwnerNamePlan.ts"; |
| 322 | export { route as postApiV1ReposOwnerNamePrint } from "./postApiV1ReposOwnerNamePrint.ts"; | |
| 317 | 323 | export { route as postApiV1ReposOwnerNamePrompts } from "./postApiV1ReposOwnerNamePrompts.ts"; |
| 318 | 324 | export { route as postApiV1ReposOwnerNamePromptsIdRun } from "./postApiV1ReposOwnerNamePromptsIdRun.ts"; |
| 319 | 325 | export { route as postApiV1ReposOwnerNameProposalTokens } from "./postApiV1ReposOwnerNameProposalTokens.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 LAN printer (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 address is not acceptable (422)" }, | |
| 11 | }; |
src/contract/openapi/routes/postApiV1DevicesIdGrants.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/{id}/grants", | |
| 6 | summary: "Grant the device to an app with a daily job cap, default 10 (site admin, admin scope); answers 201", | |
| 7 | auth: true, | |
| 8 | status: 201, | |
| 9 | body: { repo: "string", daily_cap: "integer" }, | |
| 10 | refusals: { invalid: "the repository or cap is not acceptable (422)" }, | |
| 11 | }; |
src/contract/openapi/routes/postApiV1DevicesIdProbe.ts added +8
| @@ -0,0 +1,8 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/devices/{id}/probe", | |
| 6 | summary: "Ask the printer for its model, state and supplies (site admin, admin scope)", | |
| 7 | auth: true, | |
| 8 | }; |
src/contract/openapi/routes/postApiV1ReposOwnerNamePrint.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | import { REPO, type Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: `${REPO}/print`, | |
| 6 | summary: "Print a PDF body (at most 10 MB, 20 pages) on a device the app is granted, named by the device query; answers 201 with { jobId, state, pages }", | |
| 7 | auth: true, | |
| 8 | status: 201, | |
| 9 | query: { device: "string" }, | |
| 10 | refusals: { no_grant: "the app has no grant for the device (403)", cap: "the daily cap is used (429)", too_many_pages: "over 20 pages (413)" }, | |
| 11 | }; |
src/core/devices.ts added +291
| @@ -0,0 +1,291 @@ | ||
| 1 | /** | |
| 2 | * Home devices (#10413): a printer on the owner's LAN, declared once by a | |
| 3 | * site admin and granted to apps one by one. The relay is the only path: it | |
| 4 | * reaches a declared device's address and no other, so an app gains no LAN | |
| 5 | * reach. Pages and bytes are checked before anything leaves the machine. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { isIP } from "node:net"; | |
| 10 | import { inCidrs, parseCidrs } from "../kernel/cidr.ts"; | |
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | import { neverGrantable } from "./egress_grants.ts"; | |
| 13 | import { decodeResponse, encodeRequest, OP_GET_PRINTER_ATTRIBUTES, OP_PRINT_JOB, type IppValue } from "./ipp.ts"; | |
| 14 | ||
| 15 | export const MAX_PDF_BYTES = 10 * 1024 * 1024; | |
| 16 | export const MAX_PDF_PAGES = 20; | |
| 17 | export const DEFAULT_DAILY_CAP = 10; | |
| 18 | ||
| 19 | const PRIVATE = (() => { | |
| 20 | const parsed = parseCidrs("10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"); | |
| 21 | return parsed.ok ? parsed.value : []; | |
| 22 | })(); | |
| 23 | ||
| 24 | export interface Device { | |
| 25 | readonly id: string; | |
| 26 | readonly name: string; | |
| 27 | readonly kind: "printer"; | |
| 28 | readonly url: string; | |
| 29 | readonly model: string | null; | |
| 30 | readonly state: string | null; | |
| 31 | readonly supplies: string[]; | |
| 32 | readonly probedAt: string | null; | |
| 33 | readonly probeError: string | null; | |
| 34 | } | |
| 35 | ||
| 36 | /** Options only a test sets: the fake IPP server listens on loopback. */ | |
| 37 | export interface DeviceOpts { | |
| 38 | readonly allowLoopback?: boolean; | |
| 39 | readonly now?: () => Date; | |
| 40 | } | |
| 41 | ||
| 42 | interface Target { | |
| 43 | readonly host: string; | |
| 44 | readonly port: number; | |
| 45 | readonly path: string; | |
| 46 | } | |
| 47 | ||
| 48 | /** A device URL as host, port and path; only a private IPv4 literal passes. */ | |
| 49 | export function parseDeviceUrl(text: string, opts: DeviceOpts = {}): Result<Target, string> { | |
| 50 | const url = URL.parse(text); | |
| 51 | if (!url || (url.protocol !== "ipp:" && url.protocol !== "http:")) | |
| 52 | return err("a printer's address is an ipp:// or http:// URL, like ipp://192.168.1.161:631/ipp/print"); | |
| 53 | if (url.username !== "" || url.password !== "") return err("the address carries no credentials"); | |
| 54 | const host = url.hostname; | |
| 55 | if (isIP(host) !== 4) return err("the address names an IPv4 address on the LAN, not a host name"); | |
| 56 | const loop = opts.allowLoopback === true && host.startsWith("127."); | |
| 57 | if (!loop && (neverGrantable(host) || !inCidrs(host, PRIVATE))) | |
| 58 | return err(`${host} is not an address on a home LAN; the relay reaches only private addresses`); | |
| 59 | const port = url.port === "" ? 631 : Number(url.port); | |
| 60 | const path = url.pathname + url.search; | |
| 61 | if (path.length > 200 || /[\u0000-\u001f\s]/.test(path)) return err("the address path is not valid"); | |
| 62 | return ok({ host, port, path }); | |
| 63 | } | |
| 64 | ||
| 65 | async function send(target: Target, body: Uint8Array): Promise<Result<Uint8Array, string>> { | |
| 66 | try { | |
| 67 | const res = await fetch(`http://${target.host}:${target.port}${target.path}`, { | |
| 68 | method: "POST", | |
| 69 | headers: { "content-type": "application/ipp" }, | |
| 70 | body, | |
| 71 | redirect: "manual", | |
| 72 | signal: AbortSignal.timeout(20_000), | |
| 73 | }); | |
| 74 | if (!res.ok) return err(`the printer answered HTTP ${res.status}`); | |
| 75 | return ok(new Uint8Array(await res.arrayBuffer())); | |
| 76 | } catch { | |
| 77 | return err("the printer did not answer"); | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | const PRINTER_STATE: Record<number, string> = { 3: "idle", 4: "printing", 5: "stopped" }; | |
| 82 | const JOB_STATE: Record<number, string> = { | |
| 83 | 3: "pending", 4: "held", 5: "processing", 6: "stopped", 7: "canceled", 8: "aborted", 9: "completed", | |
| 84 | }; | |
| 85 | const one = (v: IppValue[] | undefined): IppValue | undefined => v?.[0]; | |
| 86 | ||
| 87 | function rowToDevice(r: Record<string, string | null>): Device { | |
| 88 | let supplies: string[] = []; | |
| 89 | try { | |
| 90 | const parsed: unknown = JSON.parse(r["supplies"] ?? "[]"); | |
| 91 | if (Array.isArray(parsed)) supplies = parsed.filter((s): s is string => typeof s === "string"); | |
| 92 | } catch { | |
| 93 | // an unreadable cache shows no supplies until the next probe | |
| 94 | } | |
| 95 | return { | |
| 96 | id: r["id"]!, name: r["name"]!, kind: "printer", url: r["url"]!, model: r["model"] ?? null, | |
| 97 | state: r["state"] ?? null, supplies, probedAt: r["probed_at"] ?? null, probeError: r["probe_error"] ?? null, | |
| 98 | }; | |
| 99 | } | |
| 100 | ||
| 101 | export function listDevices(db: Database): Device[] { | |
| 102 | return db.query<Record<string, string | null>, []>("SELECT * FROM device ORDER BY name").all().map(rowToDevice); | |
| 103 | } | |
| 104 | ||
| 105 | export function getDevice(db: Database, key: string): Device | undefined { | |
| 106 | const r = db.query<Record<string, string | null>, [string]>("SELECT * FROM device WHERE id = ?1 OR name = ?1").get(key); | |
| 107 | return r ? rowToDevice(r) : undefined; | |
| 108 | } | |
| 109 | ||
| 110 | const NAME_RE = /^[a-z0-9][a-z0-9-]{0,39}$/; | |
| 111 | ||
| 112 | export function declareDevice( | |
| 113 | db: Database, | |
| 114 | admin: { id: string; isAdmin: boolean }, | |
| 115 | input: { name: string; kind: string; url: string }, | |
| 116 | opts: DeviceOpts = {}, | |
| 117 | ): Result<Device, string> { | |
| 118 | if (!admin.isAdmin) return err("only a site admin declares a device"); | |
| 119 | if (input.kind !== "printer") return err("the only kind of device is a printer"); | |
| 120 | if (!NAME_RE.test(input.name)) return err("a device name is lowercase letters, digits and dashes, up to 40"); | |
| 121 | const target = parseDeviceUrl(input.url, opts); | |
| 122 | if (!target.ok) return target; | |
| 123 | if (db.query("SELECT 1 FROM device WHERE name = ?1").get(input.name)) return err("a device with that name exists"); | |
| 124 | const id = crypto.randomUUID(); | |
| 125 | db.query("INSERT INTO device (id, name, kind, url, created_by) VALUES (?1, ?2, 'printer', ?3, ?4)").run( | |
| 126 | id, input.name, input.url, admin.id, | |
| 127 | ); | |
| 128 | return ok(getDevice(db, id)!); | |
| 129 | } | |
| 130 | ||
| 131 | export function grantDevice( | |
| 132 | db: Database, | |
| 133 | admin: { isAdmin: boolean }, | |
| 134 | deviceKey: string, | |
| 135 | repoId: string, | |
| 136 | dailyCap: number = DEFAULT_DAILY_CAP, | |
| 137 | ): Result<{ deviceId: string; repoId: string; dailyCap: number }, string> { | |
| 138 | if (!admin.isAdmin) return err("only a site admin grants a device"); | |
| 139 | const device = getDevice(db, deviceKey); | |
| 140 | if (!device) return err("no such device"); | |
| 141 | if (!db.query("SELECT 1 FROM repo WHERE id = ?1").get(repoId)) return err("no such repository"); | |
| 142 | if (!Number.isInteger(dailyCap) || dailyCap < 0 || dailyCap > 1000) return err("the daily cap is a whole number from 0 to 1000"); | |
| 143 | db.query( | |
| 144 | `INSERT INTO device_grant (device_id, repo_id, daily_cap) VALUES (?1, ?2, ?3) | |
| 145 | ON CONFLICT(device_id, repo_id) DO UPDATE SET daily_cap = excluded.daily_cap`, | |
| 146 | ).run(device.id, repoId, dailyCap); | |
| 147 | return ok({ deviceId: device.id, repoId, dailyCap }); | |
| 148 | } | |
| 149 | ||
| 150 | /** Ask the printer what it is and store the answer (model, state, supplies). */ | |
| 151 | export async function probeDevice(db: Database, key: string, opts: DeviceOpts = {}): Promise<Result<Device, string>> { | |
| 152 | const device = getDevice(db, key); | |
| 153 | if (!device) return err("no such device"); | |
| 154 | const target = parseDeviceUrl(device.url, opts); | |
| 155 | if (!target.ok) return target; | |
| 156 | const keywords = ["printer-make-and-model", "printer-state", "printer-state-reasons", "marker-names", "marker-levels"]; | |
| 157 | const body = encodeRequest( | |
| 158 | OP_GET_PRINTER_ATTRIBUTES, ippUri(target.value), | |
| 159 | [["name", "requesting-user-name", "forge"], ...keywords.map((k, i) => ["keyword", i === 0 ? "requested-attributes" : "", k] as const)], | |
| 160 | ); | |
| 161 | const answer = await send(target.value, body); | |
| 162 | const decoded = answer.ok ? decodeResponse(answer.value) : undefined; | |
| 163 | const now = (opts.now?.() ?? new Date()).toISOString(); | |
| 164 | if (!decoded || decoded.status >= 0x100) { | |
| 165 | const why = !answer.ok ? answer.error : "the printer's answer was not IPP"; | |
| 166 | db.query("UPDATE device SET probe_error = ?2, probed_at = ?3 WHERE id = ?1").run(device.id, why, now); | |
| 167 | return ok(getDevice(db, device.id)!); | |
| 168 | } | |
| 169 | const names = decoded.attrs.get("marker-names") ?? []; | |
| 170 | const levels = decoded.attrs.get("marker-levels") ?? []; | |
| 171 | const supplies = names.map((n, i) => `${String(n)} ${typeof levels[i] === "number" && (levels[i] as number) >= 0 ? `${levels[i]}%` : "?"}`); | |
| 172 | const state = one(decoded.attrs.get("printer-state")); | |
| 173 | const reasons = (decoded.attrs.get("printer-state-reasons") ?? []).map(String).filter((r) => r !== "none"); | |
| 174 | db.query("UPDATE device SET model = ?2, state = ?3, supplies = ?4, probed_at = ?5, probe_error = NULL WHERE id = ?1").run( | |
| 175 | device.id, | |
| 176 | String(one(decoded.attrs.get("printer-make-and-model")) ?? "unknown model"), | |
| 177 | (typeof state === "number" ? (PRINTER_STATE[state] ?? "unknown") : "unknown") + (reasons.length ? ` (${reasons.join(", ")})` : ""), | |
| 178 | JSON.stringify(supplies), | |
| 179 | now, | |
| 180 | ); | |
| 181 | return ok(getDevice(db, device.id)!); | |
| 182 | } | |
| 183 | ||
| 184 | const ippUri = (t: Target) => `ipp://${t.host}:${t.port}${t.path}`; | |
| 185 | ||
| 186 | /** Pages in a PDF by its page objects; 0 when it is not a PDF or none are found. */ | |
| 187 | export function countPdfPages(pdf: Uint8Array): number { | |
| 188 | const head = Buffer.from(pdf.subarray(0, 8)).toString("latin1"); | |
| 189 | if (!head.startsWith("%PDF-")) return 0; | |
| 190 | const text = Buffer.from(pdf).toString("latin1"); | |
| 191 | return [...text.matchAll(/\/Type\s*\/Page(?![A-Za-z])/g)].length; | |
| 192 | } | |
| 193 | ||
| 194 | export interface PrintOk { | |
| 195 | readonly jobId: number | null; | |
| 196 | readonly state: string; | |
| 197 | readonly pages: number; | |
| 198 | } | |
| 199 | export type PrintRefusal = "no_grant" | "invalid" | "too_big" | "too_many_pages" | "cap" | "unreachable" | "rejected"; | |
| 200 | export interface PrintError { | |
| 201 | readonly code: PrintRefusal; | |
| 202 | readonly message: string; | |
| 203 | } | |
| 204 | ||
| 205 | function log(db: Database, deviceId: string | null, repoId: string, day: string, pages: number, outcome: string, detail = ""): void { | |
| 206 | db.query("INSERT INTO device_job (device_id, repo_id, day, pages, outcome, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)").run( | |
| 207 | deviceId, repoId, day, pages, outcome, detail.slice(0, 200), | |
| 208 | ); | |
| 209 | } | |
| 210 | ||
| 211 | /** Relay one PDF as a Print-Job for an app that holds the grant. */ | |
| 212 | export async function printPdf( | |
| 213 | db: Database, | |
| 214 | repoId: string, | |
| 215 | deviceKey: string, | |
| 216 | pdf: Uint8Array, | |
| 217 | opts: DeviceOpts = {}, | |
| 218 | ): Promise<Result<PrintOk, PrintError>> { | |
| 219 | const day = (opts.now?.() ?? new Date()).toISOString().slice(0, 10); | |
| 220 | const device = getDevice(db, deviceKey); | |
| 221 | const grant = device | |
| 222 | ? db.query<{ daily_cap: number }, [string, string]>("SELECT daily_cap FROM device_grant WHERE device_id = ?1 AND repo_id = ?2").get(device.id, repoId) | |
| 223 | : null; | |
| 224 | if (!device || !grant) { | |
| 225 | log(db, device?.id ?? null, repoId, day, 0, "refused", "no grant"); | |
| 226 | // One answer for an unknown device and an ungranted one: the list of devices is not an app's to learn. | |
| 227 | return err({ code: "no_grant", message: "this app has no grant for that device" }); | |
| 228 | } | |
| 229 | const refuse = (code: PrintRefusal, message: string, pages = 0): Result<PrintOk, PrintError> => { | |
| 230 | log(db, device.id, repoId, day, pages, "refused", message); | |
| 231 | return err({ code, message }); | |
| 232 | }; | |
| 233 | if (pdf.length > MAX_PDF_BYTES) return refuse("too_big", "a document is at most 10 MB"); | |
| 234 | const pages = countPdfPages(pdf); | |
| 235 | if (pages === 0) return refuse("invalid", "the body is not a PDF with pages"); | |
| 236 | if (pages > MAX_PDF_PAGES) return refuse("too_many_pages", `a document is at most ${MAX_PDF_PAGES} pages`, pages); | |
| 237 | const used = db | |
| 238 | .query<{ n: number }, [string, string, string]>( | |
| 239 | "SELECT COUNT(*) AS n FROM device_job WHERE device_id = ?1 AND repo_id = ?2 AND day = ?3 AND outcome != 'refused'", | |
| 240 | ) | |
| 241 | .get(device.id, repoId, day)!.n; | |
| 242 | if (used >= grant.daily_cap) return refuse("cap", `the daily cap of ${grant.daily_cap} jobs is used`, pages); | |
| 243 | const target = parseDeviceUrl(device.url, opts); | |
| 244 | if (!target.ok) return refuse("unreachable", target.error, pages); | |
| 245 | const request = encodeRequest( | |
| 246 | OP_PRINT_JOB, ippUri(target.value), | |
| 247 | [["name", "requesting-user-name", "forge"], ["name", "job-name", "forge-app-print"], ["mime", "document-format", "application/pdf"]], | |
| 248 | pdf, | |
| 249 | ); | |
| 250 | const answer = await send(target.value, request); | |
| 251 | const decoded = answer.ok ? decodeResponse(answer.value) : undefined; | |
| 252 | if (!decoded || decoded.status >= 0x100) { | |
| 253 | const why = !answer.ok ? answer.error : decoded ? `the printer refused the job (0x${decoded.status.toString(16)})` : "the printer's answer was not IPP"; | |
| 254 | log(db, device.id, repoId, day, pages, "failed", why); | |
| 255 | return err({ code: answer.ok ? "rejected" : "unreachable", message: why }); | |
| 256 | } | |
| 257 | const jobId = one(decoded.attrs.get("job-id")); | |
| 258 | const stateNum = one(decoded.attrs.get("job-state")); | |
| 259 | const state = typeof stateNum === "number" ? (JOB_STATE[stateNum] ?? "unknown") : "accepted"; | |
| 260 | log(db, device.id, repoId, day, pages, "printed", state); | |
| 261 | return ok({ jobId: typeof jobId === "number" ? jobId : null, state, pages }); | |
| 262 | } | |
| 263 | ||
| 264 | export interface JobRow { | |
| 265 | readonly at: string; | |
| 266 | readonly app: string; | |
| 267 | readonly pages: number; | |
| 268 | readonly outcome: string; | |
| 269 | readonly detail: string; | |
| 270 | } | |
| 271 | ||
| 272 | /** The latest jobs on a device, newest first. */ | |
| 273 | export function recentJobs(db: Database, deviceId: string, limit = 20): JobRow[] { | |
| 274 | return db | |
| 275 | .query<JobRow, [string, number]>( | |
| 276 | `SELECT j.at, u.username || '/' || r.name AS app, j.pages, j.outcome, j.detail | |
| 277 | FROM device_job j JOIN repo r ON r.id = j.repo_id JOIN user u ON u.id = r.owner_id | |
| 278 | WHERE j.device_id = ?1 ORDER BY j.id DESC LIMIT ?2`, | |
| 279 | ) | |
| 280 | .all(deviceId, limit); | |
| 281 | } | |
| 282 | ||
| 283 | export interface GrantRow { readonly repoId: string; readonly app: string; readonly dailyCap: number } | |
| 284 | export function listGrants(db: Database, deviceId: string): GrantRow[] { | |
| 285 | return db | |
| 286 | .query<{ repoId: string; app: string; dailyCap: number }, [string]>( | |
| 287 | `SELECT g.repo_id AS repoId, u.username || '/' || r.name AS app, g.daily_cap AS dailyCap | |
| 288 | FROM device_grant g JOIN repo r ON r.id = g.repo_id JOIN user u ON u.id = r.owner_id WHERE g.device_id = ?1 ORDER BY app`, | |
| 289 | ) | |
| 290 | .all(deviceId); | |
| 291 | } |
src/core/ipp.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * IPP/1.1 on the wire (RFC 8010), only what the relay needs: a request with | |
| 3 | * operation attributes and optional document bytes, and a response read back | |
| 4 | * into plain `name -> values`. No other operation is encodable. | |
| 5 | */ | |
| 6 | ||
| 7 | export const OP_PRINT_JOB = 0x0002; | |
| 8 | export const OP_GET_PRINTER_ATTRIBUTES = 0x000b; | |
| 9 | ||
| 10 | const TAG = { op: 0x01, end: 0x03, name: 0x42, keyword: 0x44, uri: 0x45, charset: 0x47, lang: 0x48, mime: 0x49 } as const; | |
| 11 | ||
| 12 | export type IppValue = string | number | boolean; | |
| 13 | export interface IppResponse { | |
| 14 | readonly status: number; | |
| 15 | readonly attrs: ReadonlyMap<string, IppValue[]>; | |
| 16 | } | |
| 17 | ||
| 18 | const enc = new TextEncoder(); | |
| 19 | ||
| 20 | function attr(tag: number, name: string, value: string): Uint8Array { | |
| 21 | const n = enc.encode(name); | |
| 22 | const v = enc.encode(value); | |
| 23 | const out = new Uint8Array(5 + n.length + v.length); | |
| 24 | const view = new DataView(out.buffer); | |
| 25 | out[0] = tag; | |
| 26 | view.setUint16(1, n.length); | |
| 27 | out.set(n, 3); | |
| 28 | view.setUint16(3 + n.length, v.length); | |
| 29 | out.set(v, 5 + n.length); | |
| 30 | return out; | |
| 31 | } | |
| 32 | ||
| 33 | /** The request bytes: version 1.1, the operation, then document bytes if any. */ | |
| 34 | export function encodeRequest( | |
| 35 | op: number, | |
| 36 | printerUri: string, | |
| 37 | extra: readonly (readonly [tag: keyof typeof TAG, name: string, value: string])[], | |
| 38 | document?: Uint8Array, | |
| 39 | ): Uint8Array { | |
| 40 | const parts: Uint8Array[] = []; | |
| 41 | const head = new Uint8Array(9); | |
| 42 | const view = new DataView(head.buffer); | |
| 43 | view.setUint16(0, 0x0101); | |
| 44 | view.setUint16(2, op); | |
| 45 | view.setUint32(4, 1); | |
| 46 | head[8] = TAG.op; | |
| 47 | parts.push(head, attr(TAG.charset, "attributes-charset", "utf-8"), attr(TAG.lang, "attributes-natural-language", "en"), attr(TAG.uri, "printer-uri", printerUri)); | |
| 48 | for (const [tag, name, value] of extra) parts.push(attr(TAG[tag], name, value)); | |
| 49 | parts.push(Uint8Array.of(TAG.end)); | |
| 50 | if (document) parts.push(document); | |
| 51 | const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); | |
| 52 | let at = 0; | |
| 53 | for (const p of parts) { | |
| 54 | out.set(p, at); | |
| 55 | at += p.length; | |
| 56 | } | |
| 57 | return out; | |
| 58 | } | |
| 59 | ||
| 60 | /** A response read into attributes; undefined when the bytes are not IPP. */ | |
| 61 | export function decodeResponse(bytes: Uint8Array): IppResponse | undefined { | |
| 62 | if (bytes.length < 9) return undefined; | |
| 63 | const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); | |
| 64 | const status = view.getUint16(2); | |
| 65 | const attrs = new Map<string, IppValue[]>(); | |
| 66 | const text = new TextDecoder(); | |
| 67 | let at = 8; | |
| 68 | let last = ""; | |
| 69 | while (at < bytes.length) { | |
| 70 | const tag = bytes[at]!; | |
| 71 | at++; | |
| 72 | if (tag === TAG.end) return { status, attrs }; | |
| 73 | if (tag < 0x10) continue; // a group marker | |
| 74 | if (at + 2 > bytes.length) return undefined; | |
| 75 | const nameLen = view.getUint16(at); | |
| 76 | const name = text.decode(bytes.subarray(at + 2, at + 2 + nameLen)); | |
| 77 | at += 2 + nameLen; | |
| 78 | if (at + 2 > bytes.length) return undefined; | |
| 79 | const valueLen = view.getUint16(at); | |
| 80 | const raw = bytes.subarray(at + 2, at + 2 + valueLen); | |
| 81 | if (raw.length !== valueLen) return undefined; | |
| 82 | at += 2 + valueLen; | |
| 83 | let value: IppValue; | |
| 84 | if ((tag === 0x21 || tag === 0x23) && valueLen === 4) value = new DataView(raw.buffer, raw.byteOffset, 4).getInt32(0); | |
| 85 | else if (tag === 0x22) value = raw[0] === 1; | |
| 86 | else value = text.decode(raw); | |
| 87 | if (nameLen > 0) last = name; | |
| 88 | const list = attrs.get(last) ?? []; | |
| 89 | list.push(value); | |
| 90 | attrs.set(last, list); | |
| 91 | } | |
| 92 | return undefined; | |
| 93 | } |
src/core/migration-pins/20261110090000-devices.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 378fb5a824316b6550c99833321dba22e14ac6c9461f4315940e78eac6722712 |
src/core/migrations/20261110090000-devices.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | // Home devices (#10413): a LAN printer the owner declares once, the grant of | |
| 2 | // it to one app (with that app's daily cap), and a log of every print job. | |
| 3 | export default ` | |
| 4 | CREATE TABLE device ( | |
| 5 | id TEXT PRIMARY KEY, | |
| 6 | name TEXT NOT NULL UNIQUE, | |
| 7 | kind TEXT NOT NULL CHECK (kind IN ('printer')), | |
| 8 | url TEXT NOT NULL, | |
| 9 | created_by TEXT NOT NULL REFERENCES user(id), | |
| 10 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 11 | model TEXT, | |
| 12 | state TEXT, | |
| 13 | supplies TEXT, | |
| 14 | probed_at TEXT, | |
| 15 | probe_error TEXT | |
| 16 | ); | |
| 17 | CREATE TABLE device_grant ( | |
| 18 | device_id TEXT NOT NULL REFERENCES device(id) ON DELETE CASCADE, | |
| 19 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 20 | daily_cap INTEGER NOT NULL DEFAULT 10 CHECK (daily_cap BETWEEN 0 AND 1000), | |
| 21 | PRIMARY KEY (device_id, repo_id) | |
| 22 | ); | |
| 23 | CREATE TABLE device_job ( | |
| 24 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 25 | device_id TEXT REFERENCES device(id) ON DELETE SET NULL, | |
| 26 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 27 | day TEXT NOT NULL, | |
| 28 | at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 29 | pages INTEGER NOT NULL, | |
| 30 | outcome TEXT NOT NULL, | |
| 31 | detail TEXT NOT NULL DEFAULT '' | |
| 32 | ); | |
| 33 | CREATE INDEX device_job_day ON device_job (device_id, repo_id, day); | |
| 34 | `; |
src/http/api.ts +2
| @@ -340,6 +340,7 @@ import { frontInput, frontJson, setFront } from "../actions/front.ts"; | ||
| 340 | 340 | import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts"; |
| 341 | 341 | import { passportRoutes } from "./passport_edge.ts"; |
| 342 | 342 | import { egressGrantRoutes } from "./api/egress_grants.ts"; |
| 343 | import { deviceRoutes } from "./api/devices.ts"; | |
| 343 | 344 | import { forgeRoutes } from "./api/forges.ts"; |
| 344 | 345 | import { forgeViewRoutes } from "./api/forge_view.ts"; |
| 345 | 346 | import { economicsRoutes } from "./api/economics.ts"; |
| @@ -3750,6 +3751,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 3750 | 3751 | iterationRoutes(router); |
| 3751 | 3752 | |
| 3752 | 3753 | egressGrantRoutes(router); |
| 3754 | deviceRoutes(router); | |
| 3753 | 3755 | |
| 3754 | 3756 | promptRoutes(router); |
| 3755 | 3757 |
src/http/api/devices.ts added +81
| @@ -0,0 +1,81 @@ | ||
| 1 | /** | |
| 2 | * Home devices over the API (#10413): a site admin declares a printer, probes | |
| 3 | * it and grants it to an app; an app with the grant prints a PDF through | |
| 4 | * `POST /api/v1/repos/:owner/:name/print?device=NAME`. Rules: `core/devices.ts`. | |
| 5 | */ | |
| 6 | ||
| 7 | import { | |
| 8 | declareDevice, getDevice, grantDevice, listDevices, listGrants, MAX_PDF_BYTES, printPdf, probeDevice, recentJobs, | |
| 9 | } from "../../core/devices.ts"; | |
| 10 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 11 | import { canWrite, getRepo } from "../../core/repos.ts"; | |
| 12 | import type { Handler } from "../context.ts"; | |
| 13 | import { readBounded } from "../limits.ts"; | |
| 14 | import { body, forbidden, json, notFound, requireScope, str } from "../respond.ts"; | |
| 15 | import type { Router } from "../router.ts"; | |
| 16 | ||
| 17 | const STATUS = { no_grant: 403, invalid: 400, too_big: 413, too_many_pages: 413, cap: 429, unreachable: 502, rejected: 502 } as const; | |
| 18 | ||
| 19 | export function deviceRoutes(router: Router<Handler>): void { | |
| 20 | const gate = (ctx: Parameters<Handler>[0]): Response | undefined => { | |
| 21 | const denied = requireScope(ctx, "admin"); | |
| 22 | if (denied) return denied; | |
| 23 | const user = ctx.auth.user!; | |
| 24 | return user.isAdmin && user.kind !== "agent" ? undefined : forbidden(); | |
| 25 | }; | |
| 26 | ||
| 27 | router.add("GET", "/api/v1/devices", (ctx) => { | |
| 28 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 29 | const denied = gate(ctx); | |
| 30 | if (denied) return denied; | |
| 31 | return json({ items: listDevices(ctx.app.db), next_cursor: null }); | |
| 32 | }); | |
| 33 | ||
| 34 | router.add("POST", "/api/v1/devices", async (ctx) => { | |
| 35 | const denied = gate(ctx); | |
| 36 | if (denied) return denied; | |
| 37 | const input = await body(ctx.request); | |
| 38 | const made = declareDevice(ctx.app.db, ctx.auth.user!, { name: str(input.name), kind: str(input.kind), url: str(input.url) }); | |
| 39 | return made.ok ? json(made.value, 201) : json({ error: "invalid", message: made.error }, 422); | |
| 40 | }); | |
| 41 | ||
| 42 | router.add("GET", "/api/v1/devices/:id", (ctx) => { | |
| 43 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 44 | const denied = gate(ctx); | |
| 45 | if (denied) return denied; | |
| 46 | const device = getDevice(ctx.app.db, ctx.params.id!); | |
| 47 | if (!device) return notFound(); | |
| 48 | return json({ ...device, grants: listGrants(ctx.app.db, device.id), jobs: recentJobs(ctx.app.db, device.id) }); | |
| 49 | }); | |
| 50 | ||
| 51 | router.add("POST", "/api/v1/devices/:id/probe", async (ctx) => { | |
| 52 | const denied = gate(ctx); | |
| 53 | if (denied) return denied; | |
| 54 | const probed = await probeDevice(ctx.app.db, ctx.params.id!); | |
| 55 | return probed.ok ? json(probed.value) : notFound(); | |
| 56 | }); | |
| 57 | ||
| 58 | router.add("POST", "/api/v1/devices/:id/grants", async (ctx) => { | |
| 59 | const denied = gate(ctx); | |
| 60 | if (denied) return denied; | |
| 61 | const input = await body(ctx.request); | |
| 62 | const [owner = "", name = ""] = str(input.repo).split("/"); | |
| 63 | const repo = getRepo(ctx.app.db, owner, name); | |
| 64 | if (!repo) return json({ error: "invalid", message: "no such repository (owner/name)" }, 422); | |
| 65 | const cap = input.daily_cap === undefined ? undefined : Number(input.daily_cap); | |
| 66 | const granted = grantDevice(ctx.app.db, ctx.auth.user!, ctx.params.id!, repo.id, cap); | |
| 67 | return granted.ok ? json(granted.value, 201) : json({ error: "invalid", message: granted.error }, 422); | |
| 68 | }); | |
| 69 | ||
| 70 | router.add("POST", "/api/v1/repos/:owner/:name/print", async (ctx) => { | |
| 71 | const denied = requireScope(ctx, "rw"); | |
| 72 | if (denied) return denied; | |
| 73 | const repo = getRepo(ctx.app.db, ctx.params.owner!, ctx.params.name!); | |
| 74 | if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return notFound(); | |
| 75 | const pdf = await readBounded(ctx.request, MAX_PDF_BYTES); | |
| 76 | if (pdf === "too_large") return json({ error: "too_big", message: "a document is at most 10 MB" }, 413); | |
| 77 | const printed = await printPdf(ctx.app.db, repo.id, ctx.url.searchParams.get("device") ?? "", pdf); | |
| 78 | if (!printed.ok) return json({ error: printed.error.code, message: printed.error.message }, STATUS[printed.error.code]); | |
| 79 | return json(printed.value, 201); | |
| 80 | }); | |
| 81 | } |
src/http/settings_routes.ts +6
| @@ -15,6 +15,7 @@ import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; | ||
| 15 | 15 | import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts"; |
| 16 | 16 | import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts"; |
| 17 | 17 | import { flagsPage, flagsSet } from "../web/pages/flags.ts"; |
| 18 | import { deviceDeclare, deviceGrant, devicePage, deviceProbe, devicesPage } from "../web/pages/devices.ts"; | |
| 18 | 19 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 19 | 20 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 20 | 21 | import { usagePage } from "../web/pages/usage.ts"; |
| @@ -184,6 +185,11 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 184 | 185 | router.add("GET", "/settings/economics", economicsPage); |
| 185 | 186 | router.add("POST", "/settings/economics", economicsSet); |
| 186 | 187 | router.add("GET", "/settings/flags", flagsPage); |
| 188 | router.add("GET", "/settings/devices", devicesPage); | |
| 189 | router.add("POST", "/settings/devices", deviceDeclare); | |
| 190 | router.add("GET", "/settings/devices/:name", devicePage); | |
| 191 | router.add("POST", "/settings/devices/:name/probe", deviceProbe); | |
| 192 | router.add("POST", "/settings/devices/:name/grant", deviceGrant); | |
| 187 | 193 | // Apps absorbed as the forge's own features, and their settings. |
| 188 | 194 | router.add("GET", "/settings/features", featuresPage); |
| 189 | 195 | router.add("GET", "/settings/features/:slug", featurePage); |
src/web/pages/devices.ts added +144
| @@ -0,0 +1,144 @@ | ||
| 1 | /** | |
| 2 | * Home devices, for a site admin (#10413): `/settings/devices` declares a LAN | |
| 3 | * printer and lists them, one line each when fine; `/settings/devices/:name` | |
| 4 | * probes it, grants it to an app with a daily cap and shows its print log. | |
| 5 | * The rules are `core/devices.ts`; the same actions are in the API. | |
| 6 | */ | |
| 7 | ||
| 8 | import { declareDevice, getDevice, grantDevice, listDevices, listGrants, probeDevice, recentJobs, type Device } from "../../core/devices.ts"; | |
| 9 | import { getRepo } from "../../core/repos.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 12 | import { settingsLayout, signInFirst } from "../chrome.ts"; | |
| 13 | import { field, readForm } from "../form.ts"; | |
| 14 | import { html } from "../html.ts"; | |
| 15 | import { flashTo, page } from "../layout.ts"; | |
| 16 | import { btn, empty, icon, row } from "../ui.ts"; | |
| 17 | import { accountSections } from "./origins.ts"; | |
| 18 | ||
| 19 | function denied(ctx: Ctx): Response | undefined { | |
| 20 | const user = ctx.auth.user; | |
| 21 | if (!user) return signInFirst(ctx); | |
| 22 | if (user.isAdmin && user.kind !== "agent") return undefined; | |
| 23 | return page( | |
| 24 | { ctx, title: "Forbidden", body: html`<div class="page-head"><h1>403</h1></div>${empty({ icon: "lock", title: "Admins only", note: "Only a site admin declares home devices.", action: btn("Go home", { href: "/", variant: "primary" }) })}` }, | |
| 25 | 403, | |
| 26 | ); | |
| 27 | } | |
| 28 | ||
| 29 | /** One line when fine: model, state, supplies; the problem when not. */ | |
| 30 | function line(d: Device): string { | |
| 31 | if (d.probeError !== null) return `Unreachable: ${d.probeError}`; | |
| 32 | if (d.probedAt === null) return "Not probed yet"; | |
| 33 | return [d.model, d.state, ...d.supplies].filter((s) => s !== null && s !== "").join(" · "); | |
| 34 | } | |
| 35 | ||
| 36 | const shell = (ctx: Ctx, title: string, body: ReturnType<typeof html>, status = 200): Response => | |
| 37 | page( | |
| 38 | { ctx, title, body: html`<div class="page-head"><h1>${title}</h1></div>${settingsLayout(accountSections("devices", { admin: true }), body, "Account settings")}` }, | |
| 39 | status, | |
| 40 | ); | |
| 41 | ||
| 42 | // GET /settings/devices | |
| 43 | export function devicesPage(ctx: Ctx): Response { | |
| 44 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 45 | const no = denied(ctx); | |
| 46 | if (no) return no; | |
| 47 | const devices = listDevices(ctx.app.db); | |
| 48 | const rendering = performance.now(); | |
| 49 | const response = shell( | |
| 50 | ctx, | |
| 51 | "Devices", | |
| 52 | html`<section class="settings-block"> | |
| 53 | <h2>Home devices</h2> | |
| 54 | ${devices.length === 0 | |
| 55 | ? html`<p class="muted">No device is declared yet.</p>` | |
| 56 | : html`<ul class="list setting-list">${devices.map((d) => row({ nav: true, href: `/settings/devices/${d.name}`, lead: icon("activity"), title: d.name, meta: html`${line(d)}` }))}</ul>`} | |
| 57 | <form class="row-fields" method="post" action="/settings/devices"> | |
| 58 | <input class="input mono" name="name" placeholder="name" aria-label="Device name" required /> | |
| 59 | <input class="input mono" name="url" placeholder="ipp://192.168.1.161:631/ipp/print" size="36" aria-label="IPP address" required /> | |
| 60 | <input type="hidden" name="kind" value="printer" /> | |
| 61 | ${btn("Declare printer", { variant: "primary", label: "Declare printer" })} | |
| 62 | </form> | |
| 63 | </section>`, | |
| 64 | ); | |
| 65 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 66 | return response; | |
| 67 | } | |
| 68 | ||
| 69 | // POST /settings/devices | |
| 70 | export async function deviceDeclare(ctx: Ctx): Promise<Response> { | |
| 71 | const no = denied(ctx); | |
| 72 | if (no) return no; | |
| 73 | const form = await readForm(ctx, "admin"); | |
| 74 | if (form instanceof Response) return form; | |
| 75 | const made = declareDevice(ctx.app.db, ctx.auth.user!, { name: field(form, "name"), kind: field(form, "kind"), url: field(form, "url") }); | |
| 76 | if (!made.ok) return flashTo(ctx, "/settings/devices", { tone: "danger", message: made.error }); | |
| 77 | await probeDevice(ctx.app.db, made.value.id); | |
| 78 | return flashTo(ctx, `/settings/devices/${made.value.name}`, { message: "Device declared." }); | |
| 79 | } | |
| 80 | ||
| 81 | // GET /settings/devices/:name | |
| 82 | export function devicePage(ctx: Ctx): Response { | |
| 83 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 84 | const no = denied(ctx); | |
| 85 | if (no) return no; | |
| 86 | const d = getDevice(ctx.app.db, ctx.params.name!); | |
| 87 | const rendering = performance.now(); | |
| 88 | if (!d) { | |
| 89 | const missing = shell(ctx, "No such device", html`<p class="muted">There is no device by that name.</p>`, 404); | |
| 90 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 91 | return missing; | |
| 92 | } | |
| 93 | const here = `/settings/devices/${d.name}`; | |
| 94 | const grants = listGrants(ctx.app.db, d.id); | |
| 95 | const jobs = recentJobs(ctx.app.db, d.id); | |
| 96 | const response = shell( | |
| 97 | ctx, | |
| 98 | d.name, | |
| 99 | html`<section class="settings-block"> | |
| 100 | <p>${line(d)}</p> | |
| 101 | <form method="post" action="${here}/probe">${btn("Probe now", { size: "sm", label: "Probe now" })}</form> | |
| 102 | <h2>Apps with a grant</h2> | |
| 103 | ${grants.length === 0 | |
| 104 | ? html`<p class="muted">No app may print here.</p>` | |
| 105 | : html`<ul class="list setting-list">${grants.map((g) => row({ lead: icon("check"), title: g.app, meta: html`${g.dailyCap} jobs a day` }))}</ul>`} | |
| 106 | <form class="row-fields" method="post" action="${here}/grant"> | |
| 107 | <input class="input mono" name="repo" placeholder="owner/app" aria-label="App" required /> | |
| 108 | <input class="input mono" name="cap" placeholder="10" size="3" aria-label="Jobs a day" /> | |
| 109 | ${btn("Grant", { variant: "primary", label: "Grant to app" })} | |
| 110 | </form> | |
| 111 | <h2>Print log</h2> | |
| 112 | ${jobs.length === 0 | |
| 113 | ? html`<p class="muted">Nothing printed yet.</p>` | |
| 114 | : html`<ul class="list setting-list">${jobs.map((j) => row({ lead: icon("activity"), title: `${j.app} · ${j.pages} page${j.pages === 1 ? "" : "s"} · ${j.outcome}`, meta: html`${j.at}${j.detail === "" ? "" : ` · ${j.detail}`}` }))}</ul>`} | |
| 115 | </section>`, | |
| 116 | ); | |
| 117 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 118 | return response; | |
| 119 | } | |
| 120 | ||
| 121 | // POST /settings/devices/:name/probe | |
| 122 | export async function deviceProbe(ctx: Ctx): Promise<Response> { | |
| 123 | const no = denied(ctx); | |
| 124 | if (no) return no; | |
| 125 | const form = await readForm(ctx, "admin"); | |
| 126 | if (form instanceof Response) return form; | |
| 127 | const probed = await probeDevice(ctx.app.db, ctx.params.name!); | |
| 128 | return flashTo(ctx, `/settings/devices/${ctx.params.name!}`, probed.ok ? { message: "Probed." } : { tone: "danger", message: probed.error }); | |
| 129 | } | |
| 130 | ||
| 131 | // POST /settings/devices/:name/grant | |
| 132 | export async function deviceGrant(ctx: Ctx): Promise<Response> { | |
| 133 | const no = denied(ctx); | |
| 134 | if (no) return no; | |
| 135 | const form = await readForm(ctx, "admin"); | |
| 136 | if (form instanceof Response) return form; | |
| 137 | const [owner = "", name = ""] = field(form, "repo").trim().split("/"); | |
| 138 | const repo = getRepo(ctx.app.db, owner, name); | |
| 139 | const cap = field(form, "cap").trim(); | |
| 140 | const granted = repo | |
| 141 | ? grantDevice(ctx.app.db, ctx.auth.user!, ctx.params.name!, repo.id, cap === "" ? undefined : Number(cap)) | |
| 142 | : ({ ok: false, error: "no such repository (owner/name)" } as const); | |
| 143 | return flashTo(ctx, `/settings/devices/${ctx.params.name!}`, granted.ok ? { message: "Granted." } : { tone: "danger", message: granted.error }); | |
| 144 | } |
src/web/pages/origins.ts +2
| @@ -87,6 +87,7 @@ import { | ||
| 87 | 87 | } from "../ui.ts"; |
| 88 | 88 | |
| 89 | 89 | export type AccountSection = |
| 90 | | "devices" | |
| 90 | 91 | | "adminflows" |
| 91 | 92 | | "security" |
| 92 | 93 | | "profile" |
| @@ -159,6 +160,7 @@ const SECTION_ROWS: readonly (readonly [ | ||
| 159 | 160 | ["This forge", "Limits", "/admin/limits", "activity", (c) => c === "limits", true], |
| 160 | 161 | ["This forge", "Economics", "/settings/economics", "activity", (c) => c === "economics", true], |
| 161 | 162 | ["This forge", "Flows", "/admin/flows", "activity", (c) => c === "adminflows", true], |
| 163 | ["This forge", "Devices", "/settings/devices", "activity", (c) => c === "devices", true], | |
| 162 | 164 | ["This forge", "Flags", "/settings/flags", "activity", (c) => c === "flags", true], |
| 163 | 165 | ["This forge", "Features", "/settings/features", "rocket", (c) => c === "features", true], |
| 164 | 166 | ["This forge", "Backups", "/settings/backups", "download", (c) => c === "backups", true], |
test/data-browser.test.ts +1
| @@ -26,6 +26,7 @@ const AUDITED_CLEAR: string[] = [ | ||
| 26 | 26 | "app_feature_setting.value", |
| 27 | 27 | "comment.body", |
| 28 | 28 | "degraded_span.sentence", |
| 29 | "device_job.detail", | |
| 29 | 30 | "feed_chip.value", |
| 30 | 31 | "fleet_operation.value", |
| 31 | 32 | "issue.body", |
test/devices.test.ts added +204
| @@ -0,0 +1,204 @@ | ||
| 1 | /** | |
| 2 | * Home devices (#10413): the relay against a fake IPP printer — the probe, | |
| 3 | * the grant check, the daily cap, the PDF limits, and the refusal of any | |
| 4 | * address that is not a declared device on a home LAN. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { declareDevice, getDevice, grantDevice, listDevices, printPdf, probeDevice, recentJobs } from "../src/core/devices.ts"; | |
| 13 | import { decodeResponse } from "../src/core/ipp.ts"; | |
| 14 | import type { Repo } from "../src/core/repos.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { createUser, type User } from "../src/core/users.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | import { promote } from "./helpers/members.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const enc = new TextEncoder(); | |
| 24 | const attr = (tag: number, name: string, value: string | number) => { | |
| 25 | const n = enc.encode(name); | |
| 26 | const v = typeof value === "number" ? new Uint8Array([value >>> 24, (value >>> 16) & 255, (value >>> 8) & 255, value & 255]) : enc.encode(value); | |
| 27 | return [tag, n.length >> 8, n.length & 255, ...n, v.length >> 8, v.length & 255, ...v]; | |
| 28 | }; | |
| 29 | const ippReply = (status: number, groupTag: number, attrs: number[]) => new Uint8Array([1, 1, status >> 8, status & 255, 0, 0, 0, 1, groupTag, ...attrs, 3]); | |
| 30 | ||
| 31 | const pdf = (pages: number) => enc.encode(`%PDF-1.4\n${Array.from({ length: pages }, (_, i) => `${i + 1} 0 obj << /Type /Page >> endobj\n`).join("")}<< /Type /Pages /Count ${pages} >>\n%%EOF`); | |
| 32 | ||
| 33 | describe("home devices", () => { | |
| 34 | let app: App; | |
| 35 | let servers: Servers; | |
| 36 | let admin: User; | |
| 37 | let owner: User; | |
| 38 | let repo: Repo; | |
| 39 | let other: Repo; | |
| 40 | let printer: ReturnType<typeof Bun.serve>; | |
| 41 | let hits: { op: number; bytes: number }[] = []; | |
| 42 | let adminToken = ""; | |
| 43 | let ownerToken = ""; | |
| 44 | const opts = { allowLoopback: true }; | |
| 45 | ||
| 46 | beforeAll(async () => { | |
| 47 | printer = Bun.serve({ | |
| 48 | port: 0, | |
| 49 | hostname: "127.0.0.1", | |
| 50 | async fetch(req) { | |
| 51 | const body = new Uint8Array(await req.arrayBuffer()); | |
| 52 | const op = (body[2]! << 8) | body[3]!; | |
| 53 | hits.push({ op, bytes: body.length }); | |
| 54 | if (op === 0x000b) | |
| 55 | return new Response(ippReply(0, 0x04, [...attr(0x41, "printer-make-and-model", "Brother HL-L2350DW"), ...attr(0x23, "printer-state", 3), ...attr(0x44, "marker-names", "Black Toner"), ...attr(0x21, "marker-levels", 80)])); | |
| 56 | return new Response(ippReply(0, 0x05, [...attr(0x21, "job-id", 42), ...attr(0x23, "job-state", 9)])); | |
| 57 | }, | |
| 58 | }); | |
| 59 | const dataDir = await mkdtemp(join(tmpdir(), "forge-devices-")); | |
| 60 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 61 | servers = await serve(app); | |
| 62 | const make = async (username: string, adminIfFirst = false) => { | |
| 63 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst }); | |
| 64 | if (!made.ok) throw new Error(made.error); | |
| 65 | return made.value; | |
| 66 | }; | |
| 67 | admin = await make("ada", true); | |
| 68 | owner = await make("cy"); | |
| 69 | promote(app.db, owner); | |
| 70 | for (const name of ["paper", "snoop"]) { | |
| 71 | const made = await createRepo(app, owner, { name, visibility: "private", description: "" }); | |
| 72 | if (!made.ok) throw new Error(String(made.error)); | |
| 73 | if (name === "paper") repo = made.value; | |
| 74 | else other = made.value; | |
| 75 | } | |
| 76 | adminToken = createToken(app.db, admin.id, "admin", "admin").token; | |
| 77 | ownerToken = createToken(app.db, owner.id, "rw", "rw").token; | |
| 78 | }, 60_000); | |
| 79 | ||
| 80 | afterAll(async () => { | |
| 81 | await servers.stop(); | |
| 82 | printer.stop(true); | |
| 83 | }); | |
| 84 | ||
| 85 | const url = () => `ipp://127.0.0.1:${printer.port}/ipp/print`; | |
| 86 | ||
| 87 | test("declare, probe and show model, state and supplies", async () => { | |
| 88 | expect(declareDevice(app.db, owner, { name: "x", kind: "printer", url: url() }, opts).ok).toBe(false); | |
| 89 | const made = declareDevice(app.db, admin, { name: "kitchen", kind: "printer", url: url() }, opts); | |
| 90 | expect(made.ok).toBe(true); | |
| 91 | const probed = await probeDevice(app.db, "kitchen", opts); | |
| 92 | expect(probed.ok && probed.value.model).toBe("Brother HL-L2350DW"); | |
| 93 | expect(probed.ok && probed.value.state).toBe("idle"); | |
| 94 | expect(probed.ok && probed.value.supplies).toEqual(["Black Toner 80%"]); | |
| 95 | expect(hits.at(-1)!.op).toBe(0x000b); | |
| 96 | }); | |
| 97 | ||
| 98 | test("no grant, no print; the refusal is logged and nothing reaches the printer", async () => { | |
| 99 | hits = []; | |
| 100 | const refused = await printPdf(app.db, repo.id, "kitchen", pdf(1), opts); | |
| 101 | expect(!refused.ok && refused.error.code).toBe("no_grant"); | |
| 102 | expect(hits).toEqual([]); | |
| 103 | expect(recentJobs(app.db, getDevice(app.db, "kitchen")!.id)[0]?.outcome).toBe("refused"); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a grant prints a PDF as a Print-Job and returns the job state", async () => { | |
| 107 | expect(grantDevice(app.db, owner, "kitchen", repo.id).ok).toBe(false); | |
| 108 | const g = grantDevice(app.db, admin, "kitchen", repo.id); | |
| 109 | expect(g.ok && g.value.dailyCap).toBe(10); | |
| 110 | hits = []; | |
| 111 | const printed = await printPdf(app.db, repo.id, "kitchen", pdf(3), opts); | |
| 112 | expect(printed.ok && printed.value).toEqual({ jobId: 42, state: "completed", pages: 3 }); | |
| 113 | expect(hits).toHaveLength(1); | |
| 114 | expect(hits[0]!.op).toBe(0x0002); | |
| 115 | expect(recentJobs(app.db, getDevice(app.db, "kitchen")!.id)[0]).toMatchObject({ app: "cy/paper", pages: 3, outcome: "printed" }); | |
| 116 | // another app has no grant on the same device | |
| 117 | const other_ = await printPdf(app.db, other.id, "kitchen", pdf(1), opts); | |
| 118 | expect(!other_.ok && other_.error.code).toBe("no_grant"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("limits: 20 pages, 10 MB, only a PDF", async () => { | |
| 122 | hits = []; | |
| 123 | const many = await printPdf(app.db, repo.id, "kitchen", pdf(21), opts); | |
| 124 | expect(!many.ok && many.error.code).toBe("too_many_pages"); | |
| 125 | const big = await printPdf(app.db, repo.id, "kitchen", new Uint8Array(10 * 1024 * 1024 + 1), opts); | |
| 126 | expect(!big.ok && big.error.code).toBe("too_big"); | |
| 127 | const text = await printPdf(app.db, repo.id, "kitchen", enc.encode("hello"), opts); | |
| 128 | expect(!text.ok && text.error.code).toBe("invalid"); | |
| 129 | expect(hits).toEqual([]); | |
| 130 | }); | |
| 131 | ||
| 132 | test("the daily cap counts jobs and resets the next day", async () => { | |
| 133 | expect(grantDevice(app.db, admin, "kitchen", repo.id, 2).ok).toBe(true); | |
| 134 | const day = { ...opts, now: () => new Date("2031-01-02T08:00:00Z") }; | |
| 135 | expect((await printPdf(app.db, repo.id, "kitchen", pdf(1), day)).ok).toBe(true); | |
| 136 | expect((await printPdf(app.db, repo.id, "kitchen", pdf(1), day)).ok).toBe(true); | |
| 137 | hits = []; | |
| 138 | const third = await printPdf(app.db, repo.id, "kitchen", pdf(1), day); | |
| 139 | expect(!third.ok && third.error.code).toBe("cap"); | |
| 140 | expect(hits).toEqual([]); | |
| 141 | const next = { ...opts, now: () => new Date("2031-01-03T08:00:00Z") }; | |
| 142 | expect((await printPdf(app.db, repo.id, "kitchen", pdf(1), next)).ok).toBe(true); | |
| 143 | expect(grantDevice(app.db, admin, "kitchen", repo.id, -1).ok).toBe(false); | |
| 144 | }); | |
| 145 | ||
| 146 | test("an app cannot reach any other address: declaring refuses them, and printing re-checks", async () => { | |
| 147 | for (const bad of [ | |
| 148 | "ipp://127.0.0.1/ipp/print", | |
| 149 | "ipp://169.254.169.254/latest", | |
| 150 | "ipp://10.43.0.1:631/", | |
| 151 | "ipp://8.8.8.8:631/", | |
| 152 | "ipp://printer.local/ipp/print", | |
| 153 | "ipp://[::1]/ipp/print", | |
| 154 | "http://u:[email protected]/", | |
| 155 | "file:///etc/passwd", | |
| 156 | ]) | |
| 157 | expect(declareDevice(app.db, admin, { name: "bad", kind: "printer", url: bad }).ok).toBe(false); | |
| 158 | expect(declareDevice(app.db, admin, { name: "bad", kind: "scanner", url: "ipp://192.168.1.161/ipp/print" }).ok).toBe(false); | |
| 159 | expect(declareDevice(app.db, admin, { name: "Bad Name", kind: "printer", url: "ipp://192.168.1.161/ipp/print" }).ok).toBe(false); | |
| 160 | expect(declareDevice(app.db, admin, { name: "brother", kind: "printer", url: "ipp://192.168.1.161:631/ipp/print" }).ok).toBe(true); | |
| 161 | // a row planted with a forbidden address is still refused at print time | |
| 162 | app.db.query("UPDATE device SET url = 'ipp://169.254.169.254/' WHERE name = 'brother'").run(); | |
| 163 | grantDevice(app.db, admin, "brother", repo.id); | |
| 164 | hits = []; | |
| 165 | const refused = await printPdf(app.db, repo.id, "brother", pdf(1), opts); | |
| 166 | expect(!refused.ok && refused.error.code).toBe("unreachable"); | |
| 167 | expect(hits).toEqual([]); | |
| 168 | expect(listDevices(app.db).map((d) => d.name)).toEqual(["brother", "kitchen"]); | |
| 169 | }); | |
| 170 | ||
| 171 | test("the print endpoint: a granted app with a write token prints; others are refused", async () => { | |
| 172 | const headers = { authorization: `Bearer ${ownerToken}`, "content-type": "application/pdf" }; | |
| 173 | const post = (q: string, h: Record<string, string> = headers) => fetch(`${servers.url}/api/v1/repos/cy/paper/print?device=${q}`, { method: "POST", headers: h, body: pdf(1) }); | |
| 174 | expect((await post("brother", { "content-type": "application/pdf" })).status).toBe(401); | |
| 175 | expect((await post("kitchen")).status).toBe(502); // granted, but a loopback address is refused at the door | |
| 176 | const nogrant = await fetch(`${servers.url}/api/v1/repos/cy/snoop/print?device=kitchen`, { method: "POST", headers, body: pdf(1) }); | |
| 177 | expect(nogrant.status).toBe(403); | |
| 178 | expect(((await nogrant.json()) as { error: string }).error).toBe("no_grant"); | |
| 179 | grantDevice(app.db, admin, "kitchen", other.id, 0); | |
| 180 | const capped = await fetch(`${servers.url}/api/v1/repos/cy/snoop/print?device=kitchen`, { method: "POST", headers, body: pdf(1) }); | |
| 181 | expect(capped.status).toBe(429); | |
| 182 | }); | |
| 183 | ||
| 184 | test("the admin API declares, lists and grants; an app token cannot", async () => { | |
| 185 | const as = (token: string, init: RequestInit = {}) => ({ ...init, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" } }); | |
| 186 | expect((await fetch(`${servers.url}/api/v1/devices`, as(ownerToken))).status).toBe(403); | |
| 187 | const refused = await fetch(`${servers.url}/api/v1/devices`, as(adminToken, { method: "POST", body: JSON.stringify({ name: "evil", kind: "printer", url: "ipp://127.0.0.1/" }) })); | |
| 188 | expect(refused.status).toBe(422); | |
| 189 | const made = await fetch(`${servers.url}/api/v1/devices`, as(adminToken, { method: "POST", body: JSON.stringify({ name: "hall", kind: "printer", url: "ipp://192.168.1.161/ipp/print" }) })); | |
| 190 | expect(made.status).toBe(201); | |
| 191 | const granted = await fetch(`${servers.url}/api/v1/devices/hall/grants`, as(adminToken, { method: "POST", body: JSON.stringify({ repo: "cy/paper", daily_cap: 3 }) })); | |
| 192 | expect(granted.status).toBe(201); | |
| 193 | const view = (await (await fetch(`${servers.url}/api/v1/devices/hall`, as(adminToken))).json()) as { grants: { repoId: string; app: string; dailyCap: number }[] }; | |
| 194 | expect(view.grants).toEqual([{ repoId: repo.id, app: "cy/paper", dailyCap: 3 }]); | |
| 195 | const page = await fetch(`${servers.url}/settings/devices/hall`, { headers: { authorization: `Bearer ${adminToken}` } }); | |
| 196 | expect(page.status).toBe(200); | |
| 197 | expect(await page.text()).toContain("cy/paper"); | |
| 198 | }); | |
| 199 | ||
| 200 | test("the IPP codec rejects bytes that are not IPP", () => { | |
| 201 | expect(decodeResponse(new Uint8Array([1, 2, 3]))).toBeUndefined(); | |
| 202 | expect(decodeResponse(new Uint8Array([1, 1, 0, 0, 0, 0, 0, 1, 4, 0x41, 0xff, 0xff]))).toBeUndefined(); | |
| 203 | }); | |
| 204 | }); |
test/security-floor-routes.test.ts +1
| @@ -61,6 +61,7 @@ const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers | ||
| 61 | 61 | const UNSEEDED: Record<string, string> = { |
| 62 | 62 | "/:owner/-/teams/:team": ORG, |
| 63 | 63 | "/talk/:id": TALK, |
| 64 | "/api/v1/devices/:id": "needs a declared device; the seed declares none (test/devices.test.ts covers it)", | |
| 64 | 65 | "/bring/:id/:job": "needs a bring job of the signed-in person; the seed brings nothing", |
| 65 | 66 | "/fleet/ops/:id": FLEET, |
| 66 | 67 | "/:owner/:name/bets/:id": BET, |
new above
offline