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

A granted app's two-page print comes out as one sheet, printed on both sides #18194

opened this

Merged 14h 13m ago, live in production

mason/forge:mason/18190-a-granted-app-s-two-page-print-comes-out → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/18190-a-granted-app-s-two-page-print-comes-out was merged into main as e2e7eb4.

Review

Sign in to review this change.
13 files changed +249 −40
docs/features/devices.md +2 −1
@@ -20,6 +20,7 @@ row: Devices
2020 - Checked before anything leaves for the LAN: at most 10 MB and 20 pages, `%PDF-` header and `%%EOF` trailer, otherwise 422. Pages are counted from the plain page tree; a PDF whose tree is in a compressed object stream answers 422 `pages_unknown`. Not granted, or not a declared device: 403. Printer silent or refusing: 502.
2121 - The route takes a device number only; the job goes to the declared address, so an app reaches no other LAN host through it. Its cell's own egress is unchanged (`src/apps/egress.ts` still opens only granted `host:port`s).
2222 - An app reads how a job it sent ended with `GET $FORGE_API_URL/devices/<id>/print/<job>?within=<seconds>` (the same token and grant; `<job>` is the `job.id` the print answered with, which the forge keeps on the `print_job` row). The forge asks the printer (IPP Get-Job-Attributes) about every half second for up to `within` seconds (default 10, at most 30) and answers `{"job":{"id","state","printer","reasons"}}` with `state` one of `completed`, `failed` (the printer reports canceled, aborted or stopped) or `timed_out` (still pending, held or processing when the time ran out; `printer` says which). Only `completed` means the page came out: an app should say "sent, not confirmed" for anything else. A job this app did not send is 404 `job_unknown`; a printer that never answers is 502; an app may read 60 times a minute and hold 2 reads open at once; past either, 429 `rate_limited`. The terminal door is the Devices screen, which lists each print (`src/tui/screens/devices.ts`).
23 - `?sides=` is `one-sided` (the default; no IPP `sides` attribute is sent) or `two-sided-long-edge`; anything else is 400 `invalid_sides`, answered before the body is read. Two-sided is sent only when the printer's `sides-supported` (Get-Printer-Attributes) lists it; otherwise 422 `sides_unsupported` and nothing is printed. A printer that ignores `sides` is not detectable: the cap counts what was asked.
2324 - Each print appends `device.printed` (device, app, pages).
2425 - The app and grant are checked before the body is read, so a caller without a grant costs a lookup, not 10 MB. An app may start 10 prints a minute and have 2 in flight; past that, 429 `rate_limited`.
2526 - A PDF containing an object stream (`/ObjStm`) answers 422 `pages_unknown`: the page tree could hide there behind a plain decoy.
@@ -27,6 +28,6 @@ row: Devices
2728
2829 ## Daily limit and the print log
2930
30 - Each grant has a daily cap on jobs, default 10, set by the owner from 0 (no prints) to 1000. Jobs that reached the printer (printed or failed there) count, per UTC day; a refusal never uses up the day. Past the cap the app gets 429 `daily_cap` and can print again after midnight UTC. In-flight jobs count, and a place is reserved before the body is read, so parallel requests cannot slip past the last one.
31 - Each grant has a daily cap on sheets of paper, default 10, set by the owner from 0 (no prints) to 1000. Jobs that reached the printer (printed or failed there) count their sheets, per UTC day: a page each one-sided, a page for two when `?sides=two-sided-long-edge`, so a two-page two-sided job is one sheet and a two-page one-sided job is two. A job whose sheets do not fit what is left is 429 `daily_cap` before anything is sent; a refusal never uses up the day. Past the cap the app gets 429 `daily_cap` and can print again after midnight UTC. In-flight jobs count their reserved sheets, and a place is reserved before the body is read, so parallel requests cannot slip past the last one.
3132 - Every job is a row in `print_job` (app, device, pages, outcome, time). A cap refusal is written once per app, device and day; refusals are pruned to the last 100 per device and counted rows are dropped after 30 days, so a caller cannot grow the log.
3233 - The device page shows "n of cap printed today" per app, a "Daily limit" row to set it and a "Recent prints" row (last 10). In the terminal's Devices screen `l` sets the limit (slug, then number) and each row lists the last 5 prints; both doors use `setCap`, admin only, and append `device.cap_set` (device, app, cap).
src/actions/devices.ts +1 −1
@@ -84,7 +84,7 @@ export function revoke(app: App, actor: User | undefined, id: number, slug: stri
8484 return ok(gone.value.slug);
8585 }
8686
87 /** The owner sets how many jobs one app may print on one device each day. */
87 /** The owner sets how many sheets one app may print on one device each day. */
8888 export function setCap(app: App, actor: User | undefined, id: number, slug: string, cap: number): Result<string, DeviceActionError> {
8989 if (!mayManageDevices(actor)) return err("forbidden");
9090 const device = Number.isSafeInteger(id) ? getDevice(app.db, id) : undefined;
src/contract/openapi/routes/postApiV1DevicesIdPrint.ts +4 −1
@@ -4,10 +4,13 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/devices/{id}/print",
66 summary: "Print the PDF or PWG raster in the request body on a device the app was granted",
7 detail: "Print the PDF (application/pdf) or PWG raster (image/pwg-raster, up to 80 MB, 20 pages) in the request body on a device the app was granted (the app's own token); answers 200 with the job",
7 detail: "Print the PDF (application/pdf) or PWG raster (image/pwg-raster, up to 80 MB, 20 pages) in the request body on a device the app was granted (the app's own token); answers 200 with the job. Optional ?sides=: one-sided (the default) or two-sided-long-edge, which puts a second page on the back of the sheet and counts one sheet for two pages against the daily limit",
88 auth: true,
99 role: "member",
1010 refusals: {
11 invalid_sides: "400: sides must be one-sided (the default) or two-sided-long-edge.",
12 sides_unsupported: "422: This printer does not say it prints on both sides; ask for one-sided.",
13 daily_cap: "429: This app has used its sheets for today on this printer; it can print again tomorrow.",
1114 forbidden: "403: the app holds no grant on this device",

This daily_cap sentence differs from PRINT_WORDS.daily_cap ("This app has used its sheets for today on this printer; it can print again tomorrow."). A person and an agent should get the same words. Use the route's sentence here, and extend the words test to cover daily_cap.

1215 rate_limited: "429: the app started more than 10 prints in a minute, or has 2 in flight",
1316 too_large: "422: the PDF is over the size bound",
src/core/migration-pins/20261204110000-print-job-sheets.pin added +1
@@ -0,0 +1,1 @@
1 22288d79fe541941a587335fe1e82812e783f525fd8c065e21c21ea495c79b66
src/core/migrations/20261204110000-print-job-sheets.ts added +6
@@ -0,0 +1,6 @@
1 // Sheets of paper on each print_job row (#18190): the daily cap counts sheets, so a
2 // two-page two-sided job is one and a two-page one-sided job is two. Rows older than
3 // this were counted as one job each and stay one. Additive.
4 export default `
5 ALTER TABLE print_job ADD COLUMN sheets INTEGER NOT NULL DEFAULT 1;
6 `;
src/core/print_log.ts +8 −7
@@ -1,8 +1,8 @@
11 /**
22 * The print log and the daily cap. One row per job an app starts on a device;
3 * the cap counts the jobs of the UTC day that reached the printer (printed or
4 * failed there), so a refusal never uses up the day. The cap is a number on
5 * the owner's grant, default 10.
3 * the cap counts the sheets of the UTC day that reached the printer (printed or
4 * failed there; a job with no `sheets` is one), so a refusal never uses up the day. The cap is a
5 * number on the owner's grant, default 10 sheets.
66 */
77
88 import type { Database } from "bun:sqlite";
@@ -33,7 +33,7 @@ export function dailyCap(db: Database, deviceId: number, appId: string): number
3333 export function printedToday(db: Database, deviceId: number, appId: string, now = new Date()): number {
3434 return db
3535 .query<{ n: number }, [number, string, string]>(
36 "SELECT COUNT(*) AS n FROM print_job WHERE device_id = ?1 AND app_id = ?2 AND day = ?3 AND outcome IN ('printed','failed')",
36 "SELECT COALESCE(SUM(sheets), 0) AS n FROM print_job WHERE device_id = ?1 AND app_id = ?2 AND day = ?3 AND outcome IN ('printed','failed')",
3737 )
3838 .get(deviceId, appId, dayOf(now))!.n;
3939 }
@@ -60,7 +60,7 @@ export const OUTCOME_WORDS: Record<Outcome, string> = {
6060 */
6161 export function logJob(
6262 db: Database,
63 job: { deviceId: number; appId: string; pages: number; outcome: Outcome; jobId?: number | null },
63 job: { deviceId: number; appId: string; pages: number; outcome: Outcome; jobId?: number | null; sheets?: number },
6464 now = new Date(),
6565 ): void {
6666 if (
@@ -70,7 +70,7 @@ export function logJob(
7070 .get(job.deviceId, job.appId, dayOf(now))
7171 )
7272 return;
73 db.query("INSERT INTO print_job (device_id, app_id, pages, outcome, day, at, job_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)").run(
73 db.query("INSERT INTO print_job (device_id, app_id, pages, outcome, day, at, job_id, sheets) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)").run(
7474 job.deviceId,
7575 job.appId,
7676 job.pages,
@@ -78,6 +78,7 @@ export function logJob(
7878 dayOf(now),
7979 now.toISOString(),
8080 job.jobId ?? null,
81 job.sheets ?? 1,
8182 );
8283 if (job.outcome === "printed" || job.outcome === "failed") {
8384 db.query("DELETE FROM print_job WHERE day < ?1").run(dayOf(new Date(now.getTime() - KEEP_DAYS * 86_400_000)));
@@ -100,7 +101,7 @@ export function grantLimits(db: Database, deviceId: number, now = new Date()): G
100101 return db
101102 .query<GrantLimit, [number, string]>(
102103 `SELECT a.slug AS slug, g.daily_cap AS cap,
103 (SELECT COUNT(*) FROM print_job j WHERE j.device_id = g.device_id AND j.app_id = g.app_id AND j.day = ?2
104 (SELECT COALESCE(SUM(j.sheets), 0) FROM print_job j WHERE j.device_id = g.device_id AND j.app_id = g.app_id AND j.day = ?2
104105 AND j.outcome IN ('printed','failed')) AS today
105106 FROM device_grant g JOIN app a ON a.id = g.app_id WHERE g.device_id = ?1 ORDER BY a.slug`,
106107 )
src/devices/ipp.ts +12 −5
@@ -10,6 +10,7 @@ const OP_GET_JOB_ATTRIBUTES = 0x0009; // RFC 8011 §4.3.4
1010 const OP_GET_PRINTER_ATTRIBUTES = 0x000b; // RFC 8011 §5.2 operation-id registry
1111 const TAG = {
1212 operation: 0x01,
13 job: 0x02,
1314 end: 0x03,
1415 integer: 0x21,
1516 boolean: 0x22,
@@ -31,6 +32,7 @@ const WANTED = [
3132 "marker-levels",
3233 "marker-types",
3334 "marker-colors",
35 "sides-supported",
3436 ];
3537
3638 const RASTER_WANTED = ["pwg-raster-document-resolution-supported", "pwg-raster-document-type-supported"];
@@ -122,6 +124,8 @@ export interface PrinterReport {
122124 readonly reasons: readonly string[];
123125 readonly message: string;
124126 readonly supplies: readonly Supply[];
127 /** `sides-supported` keywords (RFC 8011 §5.2.8); empty when the printer lists none. */
128 readonly sides: readonly string[];
125129 }
126130
127131 const str = (a: IppAttributes, k: string): string[] =>
@@ -142,6 +146,7 @@ export function reportOf(attributes: IppAttributes): PrinterReport {
142146 state: stateOf(attributes.get("printer-state")?.[0]),
143147 reasons: str(attributes, "printer-state-reasons").filter((r) => r !== "none"),
144148 message: str(attributes, "printer-state-message")[0] ?? "",
149 sides: str(attributes, "sides-supported"),
145150 supplies: names.map((name, i) => {
146151 const level = levels[i];
147152 return {
@@ -229,7 +234,7 @@ async function exchange(url: string, body: Uint8Array, timeoutMs: number): Promi
229234 }
230235
231236 /** The request body for Print-Job: the document follows the attributes. */
232 export function encodePrintJob(printerUri: string, pdf: Uint8Array, jobName: string, requestId = 1, format = "application/pdf"): Uint8Array {
237 export function encodePrintJob(printerUri: string, pdf: Uint8Array, jobName: string, requestId = 1, format = "application/pdf", sides?: string): Uint8Array {
233238 const head: number[] = [
234239 1, 1,
235240 OP_PRINT_JOB >> 8, OP_PRINT_JOB & 255,
@@ -241,6 +246,8 @@ export function encodePrintJob(printerUri: string, pdf: Uint8Array, jobName: str
241246 ...attr(TAG.nameWithoutLanguage, "requesting-user-name", "forge"),
242247 ...attr(TAG.nameWithoutLanguage, "job-name", jobName),
243248 ...attr(TAG.mimeType, "document-format", format),
249 // The job attribute group is sent only when the caller asked for sides: no `sides`, no group.
250 ...(sides === undefined ? [] : [TAG.job, ...attr(TAG.keyword, "sides", sides)]),
244251 TAG.end,
245252 ];
246253 const out = new Uint8Array(head.length + pdf.length);
@@ -271,13 +278,13 @@ export type PrintResult =
271278 * IPP Print-Job and return the job state the printer reports. A printer that
272279 * takes a long document needs longer than a probe does.
273280 */
274 export async function printPdf(url: string, pdf: Uint8Array, jobName: string, timeoutMs = 30_000): Promise<PrintResult> {
275 return printDocument(url, pdf, jobName, "application/pdf", timeoutMs);
281 export async function printPdf(url: string, pdf: Uint8Array, jobName: string, timeoutMs = 30_000, sides?: string): Promise<PrintResult> {
282 return printDocument(url, pdf, jobName, "application/pdf", timeoutMs, sides);
276283 }
277284
278285 /** The same Print-Job with another document-format (PWG raster is `image/pwg-raster`). */
279 export async function printDocument(url: string, doc: Uint8Array, jobName: string, format: string, timeoutMs = 30_000): Promise<PrintResult> {
280 const answer = await exchange(url, encodePrintJob(url, doc, jobName, 1, format), timeoutMs);
286 export async function printDocument(url: string, doc: Uint8Array, jobName: string, format: string, timeoutMs = 30_000, sides?: string): Promise<PrintResult> {
287 const answer = await exchange(url, encodePrintJob(url, doc, jobName, 1, format, sides), timeoutMs);
281288 if (!answer.ok) return answer;
282289 const a = answer.response.attributes;
283290 const id = a.get("job-id")?.[0];
src/devices/print.ts +64 −16
@@ -11,7 +11,7 @@ import { getDevice, type Device } from "../core/devices.ts";
1111 import { dailyCap, logJob, printedToday, sentJob, type Outcome } from "../core/print_log.ts";
1212 import { RateLimiter } from "../core/ratelimit.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
14 import { printDocument, printPdf, probeRasterSupport, readJob, type PrintJob } from "./ipp.ts";
14 import { printDocument, printPdf, probePrinter, probeRasterSupport, readJob, type PrintJob } from "./ipp.ts";
1515 import { PWG_MAX_BYTES, readPwg, unsupportedBy, type PwgError } from "./pwg.ts";
1616 import { BODY_CAPS } from "../kernel/body_caps.ts";
1717
@@ -22,12 +22,29 @@ export const PDF_MAX_PAGES = 20;
2222 export const PRINTS_PER_MINUTE = 10;
2323 export const PRINTS_AT_ONCE = 2;
2424
25 export type PrintError = "forbidden" | "rate_limited" | "daily_cap" | "not_pdf" | "too_large" | "too_many_pages" | "pages_unknown" | "printer_unreachable" | "printer_refused" | PwgError | "raster_resolution_refused" | "raster_type_refused" | "job_unknown";
25 /** The `sides` an app may ask for: one-sided is today's behaviour and the default. */
26 export const PRINT_SIDES = ["one-sided", "two-sided-long-edge"] as const;
27 export type PrintSides = (typeof PRINT_SIDES)[number];
28
29 /**
30 * `?sides=` as asked: absent is one-sided, one of PRINT_SIDES is itself, anything else is
31 * undefined.
32 */
33 export function sidesOf(raw: string | null): PrintSides | undefined {
34 return raw === null ? "one-sided" : PRINT_SIDES.find((s) => s === raw);
35 }
36
37 /** Sheets of paper a job of `pages` uses: both sides of a sheet hold two pages. */
38 export const sheetsOf = (pages: number, sides: PrintSides): number => (sides === "one-sided" ? pages : Math.ceil(pages / 2));
39
40 export type PrintError = "invalid_sides" | "sides_unsupported" | "forbidden" | "rate_limited" | "daily_cap" | "not_pdf" | "too_large" | "too_many_pages" | "pages_unknown" | "printer_unreachable" | "printer_refused" | PwgError | "raster_resolution_refused" | "raster_type_refused" | "job_unknown";
2641
2742 export const PRINT_WORDS: Record<PrintError, string> = {
43 invalid_sides: "sides must be one-sided (the default) or two-sided-long-edge.",
44 sides_unsupported: "This printer does not say it prints on both sides; ask for one-sided.",
2845 forbidden: "This app is not granted that printer.",
2946 rate_limited: "This app is printing too fast; wait a little.",
30 daily_cap: "This app has used its prints for today on this printer; it can print again tomorrow.",
47 daily_cap: "This app has used its sheets for today on this printer; it can print again tomorrow.",
3148 not_pdf: "The body must be a PDF (application/pdf).",
3249 too_large: "The document is over its size limit (10 MB for a PDF, 80 MB for PWG raster).",
3350 too_many_pages: "The document is over 20 pages.",
@@ -84,12 +101,15 @@ export function checkRaster(raster: Uint8Array): Result<number, PrintError> {
84101 }
85102
86103 const perMinute = new RateLimiter({ perMinute: PRINTS_PER_MINUTE, adminPerMinute: PRINTS_PER_MINUTE, enabled: true });
87 const inFlight = new Map<string, number>();
104 /** Per app: jobs in flight, and the sheets they reserved against the daily cap. */
105 const inFlight = new Map<string, { jobs: number; sheets: number }>();
88106
89107 /** Who is printing and where, decided from the token and the grant alone. */
90108 export interface Permit {
91109 readonly caller: AppRef;
92110 readonly device: Device;
111 /** Sheets reserved against the daily cap: one until the document is read, then its own. */
112 sheets: number;
93113 /** Set once the reserved place is given back. */
94114 released: boolean;
95115 }
@@ -98,8 +118,9 @@ export interface Permit {
98118 export function releasePermit(permit: Permit): void {
99119 if (permit.released) return;
100120 permit.released = true;
101 const left = (inFlight.get(permit.caller.id) ?? 1) - 1;
102 if (left <= 0) inFlight.delete(permit.caller.id);
121 const held = inFlight.get(permit.caller.id) ?? { jobs: 1, sheets: permit.sheets };
122 const left = { jobs: held.jobs - 1, sheets: held.sheets - permit.sheets };
123 if (left.jobs <= 0) inFlight.delete(permit.caller.id);
103124 else inFlight.set(permit.caller.id, left);
104125 }
105126
@@ -117,28 +138,53 @@ export function permitPrint(app: App, secret: string, deviceId: number): Result<
117138 if (!caller || !Number.isSafeInteger(deviceId)) return err("forbidden");
118139 const device = getDevice(app.db, deviceId);
119140 if (!device || device.kind !== "printer" || !isGranted(app.db, device.id, caller.id)) return err("forbidden");
120 const held = inFlight.get(caller.id) ?? 0;
141 const { jobs: held, sheets: reserved } = inFlight.get(caller.id) ?? { jobs: 0, sheets: 0 };
121142 if (held >= PRINTS_AT_ONCE || !perMinute.take(caller.id, "ro").allowed) return err("rate_limited");
122 // Jobs still in flight count, so parallel requests cannot slip past the last place.
123 if (printedToday(app.db, device.id, caller.id) + held >= dailyCap(app.db, device.id, caller.id)) {
143 // Sheets reserved by jobs still in flight count, so parallel requests cannot slip past the last
144 // place.
145 if (printedToday(app.db, device.id, caller.id) + reserved >= dailyCap(app.db, device.id, caller.id)) {
124146 logJob(app.db, { deviceId: device.id, appId: caller.id, pages: 0, outcome: "refused_cap" });
125147 return err("daily_cap");
126148 }
127 inFlight.set(caller.id, held + 1);
128 return ok({ caller, device, released: false });
149 inFlight.set(caller.id, { jobs: held + 1, sheets: reserved + 1 });
150 return ok({ caller, device, sheets: 1, released: false });
129151 }
130152
131153 /** Print `pdf` for a permitted app; the document is checked before any byte leaves for the LAN. */
132 export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind: "pdf" | "raster" = "pdf"): Promise<Result<PrintJob, PrintError>> {
154 export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind: "pdf" | "raster" = "pdf", sides: PrintSides = "one-sided"): Promise<Result<PrintJob, PrintError>> {
133155 try {
134156 const { caller, device } = permit;
135157 const checked = kind === "raster" ? checkRaster(pdf) : checkPdf(pdf);
136 const log = (pages: number, outcome: Outcome, jobId: number | null = null): void =>
137 logJob(app.db, { deviceId: device.id, appId: caller.id, pages, outcome, jobId });
158 const log = (pages: number, outcome: Outcome, jobId: number | null = null, sheets = 1): void =>
159 logJob(app.db, { deviceId: device.id, appId: caller.id, pages, outcome, jobId, sheets });
138160 if (!checked.ok) {
139161 log(0, "refused_document");
140162 return checked;
141163 }
164 // The sheets this document needs must fit the day beside what was printed and what other jobs
165 // reserved: checked and reserved with no await between, so parallel jobs cannot pass together.
166 const sheets = sheetsOf(checked.value, sides);
167 const held = inFlight.get(caller.id) ?? { jobs: 0, sheets: 0 };
168 const others = held.sheets - permit.sheets;
169 if (printedToday(app.db, device.id, caller.id) + others + sheets > dailyCap(app.db, device.id, caller.id)) {
170 logJob(app.db, { deviceId: device.id, appId: caller.id, pages: 0, outcome: "refused_cap" });
171 return err("daily_cap");
172 }
173 inFlight.set(caller.id, { jobs: held.jobs, sheets: others + sheets });
174 permit.sheets = sheets;
175 if (sides !== "one-sided") {
176 // Two-sided only when the printer says it can: otherwise nothing reaches it.
177 const asked = await probePrinter(device.url);
178 if (!asked.ok) {
179 // Nothing was sent to print, so no sheet of the day is used.
outdated

A failed sides probe is logged failed with the default sheets = 1. failed rows count against the daily cap, but nothing was sent to the printer, so the app loses a sheet for a refusal. Log it as refused_document, or pass sheets as 0 here, and add a test where the probe fails.

180 log(0, "failed", null, 0);
181 return err(asked.error === "unreachable" ? "printer_unreachable" : "printer_refused");
182 }
183 if (!asked.report.sides.includes(sides)) {
184 log(0, "refused_document");
185 return err("sides_unsupported");
186 }
187 }
142188 if (kind === "raster") {
143189 // Only now does anything touch the LAN: ask what the printer takes of what the pages need.
144190 const asked = await probeRasterSupport(device.url);
@@ -156,8 +202,10 @@ export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind:
156202 }
157203 }
158204 const jobName = `${caller.slug} (forge)`;
159 const sent = kind === "raster" ? await printDocument(device.url, pdf, jobName, "image/pwg-raster") : await printPdf(device.url, pdf, jobName);
160 log(checked.value, sent.ok ? "printed" : "failed", sent.ok ? sent.job.id : null);
205 // The IPP attribute is sent only when asked: one-sided is the printer's own default.
206 const askedSides = sides === "one-sided" ? undefined : sides;
207 const sent = kind === "raster" ? await printDocument(device.url, pdf, jobName, "image/pwg-raster", undefined, askedSides) : await printPdf(device.url, pdf, jobName, undefined, askedSides);
208 log(checked.value, sent.ok ? "printed" : "failed", sent.ok ? sent.job.id : null, sheets);
161209 releasePermit(permit);
162210 if (sent.ok) {
163211 app.bus.append({ kind: "device.printed", payload: { device: device.name, app: caller.slug, pages: checked.value } });
src/http/api/print.ts +9 −2
@@ -4,7 +4,7 @@
44 * PDF, or PWG raster when the content-type says `image/pwg-raster`. The route takes a device number and nothing that names an address.
55 */
66
7 import { PRINT_WORDS, PDF_MAX_BYTES, jobOutcome, permitPrint, printFor, releasePermit, withinOf, type PrintError } from "../../devices/print.ts";
7 import { PRINT_WORDS, PDF_MAX_BYTES, jobOutcome, permitPrint, printFor, releasePermit, sidesOf, withinOf, type PrintError } from "../../devices/print.ts";
88 import { PWG_MAX_BYTES } from "../../devices/pwg.ts";
99 import type { Handler } from "../context.ts";
1010 import { readBounded } from "../limits.ts";
@@ -13,6 +13,8 @@ import type { Router } from "../router.ts";
1313 import { tokenSecret } from "../token_header.ts";
1414
1515 const STATUS: Record<PrintError, number> = {
16 invalid_sides: 400,
17 sides_unsupported: 422,
1618 forbidden: 403,
1719 rate_limited: 429,
1820 daily_cap: 429,
@@ -46,6 +48,11 @@ export function printRoutes(router: Router<Handler>): void {
4648 const permit = permitPrint(ctx.app, secret, id);
4749 if (!permit.ok) return printRefusal(permit.error);
4850 // The permit holds a place until printFor, or here when the body never gets that far.
51 const sides = sidesOf(new URL(ctx.request.url).searchParams.get("sides"));
52 if (sides === undefined) {
53 releasePermit(permit.value);
54 return printRefusal("invalid_sides");
55 }
4956 const raster = (ctx.request.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase() === "image/pwg-raster";
5057 const cap = raster ? PWG_MAX_BYTES : PDF_MAX_BYTES;
5158 let pdf: Awaited<ReturnType<typeof readBounded>>;
@@ -59,7 +66,7 @@ export function printRoutes(router: Router<Handler>): void {
5966 releasePermit(permit.value);
6067 return apiError("too_large", 422, PRINT_WORDS.too_large);
6168 }
62 const done = await printFor(ctx.app, permit.value, pdf, raster ? "raster" : "pdf");
69 const done = await printFor(ctx.app, permit.value, pdf, raster ? "raster" : "pdf", sides);
6370 if (!done.ok) return printRefusal(done.error);
6471 return json({ job: { id: done.value.id, state: done.value.state, reasons: done.value.reasons } });
6572 });
src/tui/screens/devices.ts +2 −2
@@ -106,14 +106,14 @@ export function devicesScreen(f: Session, ctx: Ctx): Screen {
106106 const setLimit = (d: Device) => (line: string): string | undefined => {
107107 const [slug = "", raw = "", extra] = line.trim().split(/\s+/);
108108 const made = setCap(f.app, f.user, d.id, slug, /^\d{1,4}$/.test(raw) && extra === undefined ? Number(raw) : Number.NaN);
109 note = made.ok ? `${made.value} may print ${raw} a day on ${d.name}.` : DEVICE_ERRORS[made.error];
109 note = made.ok ? `${made.value} may print ${raw} sheets a day on ${d.name}.` : DEVICE_ERRORS[made.error];
110110 if (made.ok) reload();
111111 return made.ok ? undefined : note;
112112 };
113113 const askLimit = (d: Device): Screen =>
114114 promptScreen(ctx, screen, {
115115 title: "Daily print limit",
116 label: `App slug, then prints a day (0 to ${CAP_MAX}) on ${d.name}`,
116 label: `App slug, then sheets a day (0 to ${CAP_MAX}) on ${d.name}`,
117117 placeholder: grantLimits(f.db, d.id).map((l) => l.slug).join(" ") || "grant an app first",
118118 onSubmit: setLimit(d),
119119 });
src/web/settings/devices.ts +2 −2
@@ -56,7 +56,7 @@ function access(ctx: Ctx, d: Device): Html {
5656 <ul class="list">${limits.map(
5757 (l) => html`<li>${row({
5858 title: html`<span class="mono">${l.slug}</span>`,
59 meta: html`<span class="small muted">${String(l.today)} of ${String(l.cap)} printed today</span>`,
59 meta: html`<span class="small muted">${String(l.today)} of ${String(l.cap)} sheets printed today</span>`,
6060 trail: html`<form class="row-actions" method="post" action="/settings/devices/revoke">
6161 <input type="hidden" name="id" value="${String(d.id)}" />
6262 <input type="hidden" name="app" value="${l.slug}" />
@@ -78,7 +78,7 @@ function access(ctx: Ctx, d: Device): Html {
7878 <select class="input" name="app" aria-label="App to limit on ${d.name}">
7979 ${limits.map((l) => html`<option value="${l.slug}">${l.slug} (${String(l.cap)})</option>`)}
8080 </select>
81 <input class="input mono" type="number" name="cap" min="0" max="${String(CAP_MAX)}" value="${String(limits[0]!.cap)}" aria-label="Prints a day" />
81 <input class="input mono" type="number" name="cap" min="0" max="${String(CAP_MAX)}" value="${String(limits[0]!.cap)}" aria-label="Sheets a day" />
8282 ${btn("Set limit", { size: "sm", label: `Set the daily limit on ${d.name}` })}
8383 </form>
8484 </dd></div>`)}
test/print.test.ts +135 −3
@@ -7,7 +7,7 @@ import { createApp, type App } from "../src/app.ts";
77 import { mintAppToken, revokeAppToken } from "../src/apps/token.ts";
88 import { grantDevice, isGranted } from "../src/core/device_grants.ts";
99 import { declareDevice } from "../src/core/devices.ts";
10 import { logJob } from "../src/core/print_log.ts";
10 import { logJob, setDailyCap } from "../src/core/print_log.ts";
1111 import { createToken } from "../src/core/tokens.ts";
1212 import { createSession } from "../src/core/sessions.ts";
1313 import { getUserByName } from "../src/core/users.ts";
@@ -33,11 +33,23 @@ const pdf = (pages: number): Uint8Array =>
3333 let received: Uint8Array[] = [];
3434 let reads: Uint8Array[] = [];
3535 let jobState = 9;
36 let sidesListed: string[] = [];
3637 const printer = Bun.serve({
3738 port: 0,
3839 hostname: "127.0.0.1",
3940 async fetch(req) {
4041 const body = new Uint8Array(await req.arrayBuffer());
42 if (body[3] === 0x0b) {
43 return new Response(
44 Uint8Array.from([
45 1, 1, 0, 0, 0, 0, 0, 1,
46 0x01, ...attr(0x47, "attributes-charset", "utf-8"),
47 0x04, ...sidesListed.flatMap((v, i) => attr(0x44, i === 0 ? "sides-supported" : "", v)),
48 0x03,
49 ]),
50 { headers: { "content-type": "application/ipp" } },
51 );
52 }
4153 if (body[3] === 9) {
4254 reads.push(body);
4355 return new Response(
@@ -146,6 +158,8 @@ test("a stopped app's token no longer prints", async () => {
146158 test("a non-PDF, an oversize or a long document is 422 and is not sent", async () => {
147159 received = [];
148160 const path = `/api/v1/devices/${deviceId}/print`;
161 // The cap counts sheets now: a 20-page one-sided job needs room for 20.
162 setDailyCap(app.db, deviceId, "labels", 100);
149163 expect((await print(path, granted, "just text")).status).toBe(422);
150164 expect((await print(path, granted, enc.encode("%PDF-1.4 truncated, no end"))).status).toBe(422);
151165 expect((await print(path, granted, pdf(21))).status).toBe(422);
@@ -256,7 +270,7 @@ test("the daily cap refuses past the limit, says why, and resets the next day",
256270 const t = mintAppToken(app.db, owner.id, "capped", "production").token;
257271 const path = `/api/v1/devices/${otherId}/print`;
258272 expect((await print(path, t, pdf(1))).status).toBe(200);
259 expect((await print(path, t, pdf(3))).status).toBe(200);
273 expect((await print(path, t, pdf(1))).status).toBe(200);
260274 const res = await print(path, t, pdf(1));
261275 expect(res.status).toBe(429);
262276 expect(((await res.json()) as { error: string }).error).toBe("daily_cap");
@@ -270,7 +284,7 @@ test("the daily cap refuses past the limit, says why, and resets the next day",
270284 }
271285 // One row per job: two printed, one refused by the cap.
272286 const rows = app.db.query<{ pages: number; outcome: string }, []>("SELECT pages, outcome FROM print_job WHERE app_id = 'a4' ORDER BY id").all();
273 expect(rows).toEqual([{ pages: 1, outcome: "printed" }, { pages: 3, outcome: "printed" }, { pages: 0, outcome: "refused_cap" }, { pages: 1, outcome: "printed" }]);
287 expect(rows).toEqual([{ pages: 1, outcome: "printed" }, { pages: 1, outcome: "printed" }, { pages: 0, outcome: "refused_cap" }, { pages: 1, outcome: "printed" }]);
274288 });
275289
276290 test("the owner sets the limit on the device page, which lists the last jobs", async () => {
@@ -479,3 +493,121 @@ test("a printer that never answers is 502 printer_unreachable; one that refuses
479493 refusing.stop(true);
480494 }
481495 });
496
497 // --- sides (#18190) ---
498
499 test("encodePrintJob sends the sides attribute only when asked", async () => {
500 const { encodePrintJob } = await import("../src/devices/ipp.ts");
501 const doc = pdf(1);
502 const text = (b: Uint8Array) => Buffer.from(b).toString("latin1");
503 const two = encodePrintJob("ipp://x/ipp/print", doc, "job", 1, "application/pdf", "two-sided-long-edge");
504 expect(text(two)).toContain("sides");
505 expect(text(two)).toContain("two-sided-long-edge");
506 // job attribute group (0x02) holds a keyword (0x44) named sides, before the end tag
507 const head = Buffer.from(two.subarray(0, two.length - doc.length));
508 const at = head.indexOf(Buffer.from("sides"));
509 expect(head[at - 3]).toBe(0x44);
510 expect(head.lastIndexOf(0x02, at)).toBeGreaterThan(head.indexOf(Buffer.from("document-format")));
511 expect(head[head.length - 1]).toBe(0x03);
512 const none = encodePrintJob("ipp://x/ipp/print", doc, "job");
513 expect(text(none)).not.toContain("two-sided");
514 expect(Buffer.from(none.subarray(0, none.length - doc.length)).includes(Buffer.from("sides"))).toBe(false);
515 });
516
517 test("reportOf reads sides-supported", async () => {
518 const { reportOf } = await import("../src/devices/ipp.ts");
519 expect(reportOf(new Map([["sides-supported", ["one-sided", "two-sided-long-edge"]]])).sides).toEqual(["one-sided", "two-sided-long-edge"]);
520 expect(reportOf(new Map()).sides).toEqual([]);
521 });
522
523 test("sheetsOf: two pages are one sheet two-sided and two sheets one-sided", async () => {
524 const { sheetsOf, sidesOf } = await import("../src/devices/print.ts");
525 expect(sheetsOf(2, "two-sided-long-edge")).toBe(1);
526 expect(sheetsOf(3, "two-sided-long-edge")).toBe(2);
527 expect(sheetsOf(2, "one-sided")).toBe(2);
528 expect(sidesOf(null)).toBe("one-sided");
529 expect(sidesOf("two-sided-short-edge")).toBeUndefined();
530 });
531
532 test("a bad sides is 400 naming the allowed values, before the body is read", async () => {
533 received = [];
534 const res = await print(`/api/v1/devices/${deviceId}/print?sides=duplex`, granted, pdf(2));
535 expect(res.status).toBe(400);
536 const body = (await res.json()) as { error: string; message?: string };
537 expect(body.error).toBe("invalid_sides");
538 expect(JSON.stringify(body)).toContain("one-sided");
539 expect(JSON.stringify(body)).toContain("two-sided-long-edge");
540 expect(received.length).toBe(0);
541 });
542
543 test("two-sided is refused when the printer does not list it, and nothing is printed", async () => {
544 received = [];
545 sidesListed = [];
546 const res = await print(`/api/v1/devices/${deviceId}/print?sides=two-sided-long-edge`, granted, pdf(2));
547 expect(res.status).toBe(422);
548 expect(((await res.json()) as { error: string }).error).toBe("sides_unsupported");
549 expect(received.filter((b) => b[3] === 2).length).toBe(0);
550 });
551
552 test("two-sided is sent when the printer lists it, and one-sided sends no sides", async () => {
553 received = [];
554 sidesListed = ["one-sided", "two-sided-long-edge"];
555 const two = await print(`/api/v1/devices/${deviceId}/print?sides=two-sided-long-edge`, granted, pdf(2));
556 expect(two.status).toBe(200);
557 const jobs = received.filter((b) => b[3] === 2);
558 expect(jobs.length).toBe(1);
559 expect(Buffer.from(jobs[0]!).toString("latin1")).toContain("two-sided-long-edge");
560 received = [];
561 const one = await print(`/api/v1/devices/${deviceId}/print`, granted, pdf(2));
562 expect(one.status).toBe(200);
563 expect(received.length).toBe(1);
564 expect(Buffer.from(received[0]!).toString("latin1")).not.toContain("sides");
565 });
566
567 test("the daily cap counts sheets: two pages two-sided are one, one-sided are two, and no job passes it", async () => {
568 const { printedToday } = await import("../src/core/print_log.ts");
569 const owner = getUserByName(app.db, "alice")!;
570 addApp("a7", "sheets");
571 grantDevice(app.db, otherId, "sheets", owner.id);
572 setDailyCap(app.db, otherId, "sheets", 3);
573 sidesListed = ["one-sided", "two-sided-long-edge"];
574 const t = mintAppToken(app.db, owner.id, "sheets", "production").token;
575 const path = `/api/v1/devices/${otherId}/print`;
576 expect((await print(`${path}?sides=two-sided-long-edge`, t, pdf(2))).status).toBe(200);
577 expect(printedToday(app.db, otherId, "a7")).toBe(1);
578 expect((await print(path, t, pdf(2))).status).toBe(200);
579 expect(printedToday(app.db, otherId, "a7")).toBe(3);
580 received = [];
581 const over = await print(`${path}?sides=two-sided-long-edge`, t, pdf(1));
582 expect(over.status).toBe(429);
583 setDailyCap(app.db, otherId, "sheets", 4);
584 // One sheet left: a three-page one-sided job needs three and is refused unsent.
585 const big = await print(path, t, pdf(3));
586 expect(big.status).toBe(429);
587 expect(((await big.json()) as { error: string }).error).toBe("daily_cap");
588 expect(received.length).toBe(0);
589 expect(printedToday(app.db, otherId, "a7")).toBe(3);
590 });
591
592 test("the OpenAPI entry and the route say the same words", async () => {
593 const { route } = await import("../src/contract/openapi/routes/postApiV1DevicesIdPrint.ts");
594 const { PRINT_WORDS } = await import("../src/devices/print.ts");
595 expect(route.refusals!["invalid_sides"]).toContain(PRINT_WORDS.invalid_sides);
596 expect(route.refusals!["sides_unsupported"]).toContain(PRINT_WORDS.sides_unsupported);
597 expect(route.refusals!["daily_cap"]).toContain(PRINT_WORDS.daily_cap);
598 });
599
600 test("a two-sided job whose sides probe fails uses no sheet of the day", async () => {
601 const { printedToday } = await import("../src/core/print_log.ts");
602 const refusing = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("no", { status: 500 }) });
603 try {
604 const r = readerOn("probefail", `ipp://127.0.0.1:${refusing.port}/ipp/print`);
605 const id = r.path.split("/")[4]!;
606 const before = printedToday(app.db, Number(id), "id-probefail");
607 const res = await print(`/api/v1/devices/${id}/print?sides=two-sided-long-edge`, r.token, pdf(2));
608 expect(res.status).toBe(502);
609 expect(printedToday(app.db, Number(id), "id-probefail")).toBe(before);
610 } finally {
611 refusing.stop(true);
612 }
613 });
test/print_raster.test.ts +3
@@ -9,6 +9,7 @@ import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
1010 import { mintAppToken } from "../src/apps/token.ts";
1111 import { grantDevice } from "../src/core/device_grants.ts";
12 import { setDailyCap } from "../src/core/print_log.ts";
1213 import { declareDevice } from "../src/core/devices.ts";
1314 import { getUserByName } from "../src/core/users.ts";
1415 import { readPwg } from "../src/devices/pwg.ts";
@@ -89,6 +90,8 @@ beforeAll(async () => {
8990 if (!d.ok) throw new Error("declare");
9091 deviceId = d.value.id;
9192 expect(grantDevice(app.db, deviceId, "paper", owner.id).ok).toBe(true);
93 // The cap counts sheets: leave room for a 20-page one-sided job.
94 setDailyCap(app.db, deviceId, "paper", 100);
9295 granted = mintAppToken(app.db, owner.id, "paper", "production").token;
9396 });
9497 afterAll(async () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs