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

A link or an image shared to the forge from a phone becomes a tell that names it #16675

Merged opened this

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

Merged

scout/forge:scout/16311-a-link-or-an-image-shared-to-the-forge-f → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/16311-a-link-or-an-image-shared-to-the-forge-f was merged into main as 3356be2.

Review

Sign in to review this change.
12 files changed +304 −33
docs/design/areas/feed.md +2
@@ -21,3 +21,5 @@ The tell box takes the cursor from a small script in `feedJs` only when the feed
2121 ## Kept words
2222
2323 `.kept-words` is the words of a tell on its receipt (`shareReceipt` in `src/web/studio/share_receive.ts`): a `dd` of the §5 `.status-row` that keeps the sender's line breaks (`pre-wrap`) and wraps anywhere, so a long link never scrolls the page at 360px.
24
25 `.share-image` is the picture a phone shared, on the held form (`shareHeld` in `src/web/studio/share_receive.ts`): a 160px box that never shifts the page, `object-fit: contain` so a non-square photo is never stretched; no frame or fill, the picture is the content.
docs/features/share-receive.md +9 −1
@@ -11,10 +11,18 @@ row: Share to the forge from a phone's share sheet
1111 HttpOnly cookie and `/tell/share` shows them in a form; nothing is filed until you tap Send.
1212 Signed out, you sign in first and come back to that form. Send files the tell as typed and
1313 lands on its receipt (`/tell/share/:id`), which only you can open.
14 - A share may also carry one picture (PNG, JPEG, GIF or WebP by its bytes, up to 5 MB). It is kept
15 as your own unsent attachment (owner-only, swept after an hour), shown on the held form beside a
16 line saying where the share came from; a tell carries words only, so the picture waits in Talk: the
17 page shows your unsent files as chips, attached to your next message there. A refused picture says why and keeps your words. Signed out, the words are
18 held and the picture is not, and the form says so (#16311).
1419 - Nothing shared, a link that is not http(s), or more than 4,000 characters is refused with a
1520 sentence; nothing is cut or held. A signed-out address may hold 10 shares a minute.
1621
17 **Terminal.** `ssh` in, open the palette (`:`) and pick "Shared from my phone": your own
22 **Terminal.** Sharing is phone-only by nature: a share sheet exists on a phone, not over `ssh`, so
23 the held form and its picture have no terminal screen.
24
25 The terminal lists what a share filed: `ssh` in, open the palette (`:`) and pick "Shared from my phone": your own
1826 share-filed tells, newest first (50 at most; `/` filters, Enter shows one's words whole, `esc`
1927 back). Nothing to list says so.
2028
src/core/conversation_files.ts +19
@@ -166,6 +166,25 @@ export function removePending(db: Database, dataDir: string, userId: string, fil
166166 return true;
167167 }
168168
169 /**
170 * One read for a Talk page: the files sent with `turnIds`, by turn, and the person's unsent files
171 * (at most FILES_PER_MESSAGE, as upload allows no more), oldest first, so a reload or a shared
172 * picture keeps them attached.
173 */
174 export function filesOfTalk(db: Database, userId: string, turnIds: readonly string[]): { sent: Map<string, ConversationFile[]>; unsent: ConversationFile[] } {
175 const sent = new Map<string, ConversationFile[]>();
176 const unsent: ConversationFile[] = [];
177 const among = turnIds.length === 0 ? "" : ` OR turn_id IN (${turnIds.map((_, i) => `?${i + 2}`).join(",")})`;
178 const rows = db
179 .query<FileRow, string[]>(`SELECT id, turn_id, name, type, size FROM conversation_file WHERE user_id = ?1 AND (turn_id IS NULL${among}) ORDER BY rowid`)
180 .all(userId, ...turnIds);
181 for (const r of rows) {
182 if (r.turn_id === null) { if (unsent.length < FILES_PER_MESSAGE) unsent.push(fileOf(r)); }
183 else sent.set(r.turn_id, [...(sent.get(r.turn_id) ?? []), fileOf(r)]);
184 }
185 return { sent, unsent };
186 }
187
169188 /** The person's own unsent files among `ids`, in order; any other id makes the whole list `not_found`. */
170189 export function pendingAmong(db: Database, userId: string, ids: readonly string[]): Result<ConversationFile[], FileRefusal> {
171190 if (new Set(ids).size !== ids.length || ids.length > FILES_PER_MESSAGE) return err("not_found");
src/web/pages/talk.ts +3 −3
@@ -20,7 +20,7 @@ import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
2020 import type { Database } from "bun:sqlite";
2121 import { cancelTalk, queuedTalk, STARTER_PROMPTS, TALK_WORDS, talk, talkAgain } from "../../actions/talk.ts";
2222 import { REFUSED, sayNo, sayYes, UNDO_REFUSED, undoReceipt, waitingConfirms, type Waiting } from "../../actions/conversation_confirms.ts";
23 import { filesOfTurns, type ConversationFile } from "../../core/conversation_files.ts";
23 import { filesOfTalk, filesOfTurns, type ConversationFile } from "../../core/conversation_files.ts";
2424 import {
2525 archiveConversation,
2626 conversationActivity,
@@ -564,7 +564,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
564564 const pendingConfirms = confirmsOf(turns, waitingList);
565565 const expired = ranOutOf(ctx, user.id, turns);
566566 const undone = undoneIn(turns);
567 const sent = filesOfTurns(ctx.app.db, user.id, turns.filter((t) => t.role === "person").map((t) => t.id));
567 const { sent, unsent } = filesOfTalk(ctx.app.db, user.id, turns.filter((t) => t.role === "person").map((t) => t.id));
568568 const running = clock.running(ctx.app, user.id, conversation.id);
569569 const costs = turnSpend(ctx.app.db, conversation.id);
570570 const context = contextOf(ctx.app.db, conversation.id);
@@ -666,7 +666,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
666666 ${confirmsDock(pendingConfirms)}
667667 <p class="sr-only" role="status" data-confirms-said></p>
668668 <div class="talk-box">
669 <div class="talk-chips" data-chips role="group" aria-label="Attached files"></div>
669 <div class="talk-chips" data-chips role="group" aria-label="Attached files">${buildMode ? null : unsent.map((f) => html`<span class="badge" data-pending-file="${f.id}">${f.name}</span>`)}</div>
outdated

Chips only appear with ?shared=1, so a plain /talk does not attach the picture and it is swept after an hour. Make the pickup not depend on a query flag (and not run an extra query for everyone), or the picture cannot be finished.

670670 <p class="talk-to small" data-to-line hidden><span></span> <button type="button" class="btn btn-icon" data-variant="ghost" data-to-off aria-label="Talk to the forge instead" title="Talk to the forge instead">${icon("x")}</button></p>
671671 <div class="talk-tools">
672672 ${buildMode ? null : html`<button type="button" class="btn btn-icon" data-variant="ghost" data-attach hidden aria-label="Attach files" title="Attach files">${icon("paperclip")}</button><input type="file" multiple hidden data-files />`}
src/web/pages/talk_client.ts +2
@@ -880,6 +880,8 @@ if (root) {
880880 li.appendChild(x);
881881 chips.appendChild(li);
882882 };
883 // The person's unsent files, rendered by the server (kept over a reload, or a picture shared from a phone), go with the next message.
884 for (const el of [...chips.querySelectorAll("[data-pending-file]")]) { el.remove(); const f = { id: el.dataset.pendingFile, name: el.textContent }; attached.push(f); drawChip(f); }

This adopts every unsent file, not only the shared one, and only when the server rendered chips; on a plain /talk the picture is never attached.

883885 const upload = async (file) => {
884886 say("Attaching " + file.name + "…");
885887 try {
src/web/share_target.ts +40 −4
@@ -9,17 +9,25 @@
99 * Links made before this (`GET /?title=…`, `GET /tell?…`) still open the composer.
1010 */
1111 import { TELL_TEXT_MAX } from "../actions/tell_from.ts";
12 import { checkFile, cleanName, FILE_WORDS, IMAGE_MAX } from "../core/conversation_files.ts";
1213 import type { URLSearchParams as Params } from "node:url";
1314
1415 /** The query parameters a share carries, in the order they are joined. */
1516 export const SHARE_PARAMS = { title: "title", text: "text", url: "url" } as const;
1617
17 /** What the manifest declares. */
18 /** The one file field a share may carry: a picture. */
19 export const SHARE_IMAGE_FIELD = "image";
20
21 /** The image types the sheet may offer; the bytes are checked again at the boundary. */
22 export const SHARE_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"] as const;
23
24 /** What the manifest declares. Multipart, because a share may carry one image. */
1825 export const SHARE_TARGET = {
1926 action: "/tell/share",
2027 method: "POST",
21 enctype: "application/x-www-form-urlencoded",
28 enctype: "multipart/form-data",
2229 params: SHARE_PARAMS,
30 files: [{ name: SHARE_IMAGE_FIELD, accept: [...SHARE_IMAGE_TYPES] }],
2331 } as const;
2432
2533 /** The longest tell the composer takes (its textarea's `maxlength`). */
@@ -43,10 +51,10 @@ const NOT_WEB = "That share's link is not a web address (http or https), so it w
4351 * Why a share cannot be a tell, in a sentence, or undefined when it can: nothing
4452 * shared, too long, or a link that is not http(s). Whitespace-only counts as nothing.
4553 */
46 export function refuseShare(params: URLSearchParams | Params): string | undefined {
54 export function refuseShare(params: URLSearchParams | Params, hasImage = false): string | undefined {
4755 const get = (k: string) => (params.get(k) ?? "").trim();
4856 const title = get(SHARE_PARAMS.title), text = get(SHARE_PARAMS.text), url = get(SHARE_PARAMS.url);
49 if (title === "" && text === "" && url === "") return refuseTell("");
57 if (title === "" && text === "" && url === "") return hasImage ? undefined : refuseTell("");
5058 if (url !== "" && !URL.canParse(url)) return NOT_WEB;
5159 if (url !== "") {
5260 const protocol = new URL(url).protocol;
@@ -57,6 +65,34 @@ export function refuseShare(params: URLSearchParams | Params): string | undefine
5765 return undefined;
5866 }
5967
68 /**
69 * Why a shared file cannot be kept, or undefined when it is a picture we hold: PNG, JPEG, GIF or
70 * WebP by its first bytes (never by the name or type it was sent with), not empty, at most 5 MB.
71 * The words begin "The image was not kept" and name the limit; the text shared with it is kept.
72 */
73 export function refuseImage(name: string, bytes: Uint8Array): string | undefined {
74 const checked = checkFile(cleanName(name), bytes);
75 if (checked.ok && checked.value.startsWith("image/")) return undefined;
76 const why = checked.ok ? FILE_WORDS.bad_type[1] : FILE_WORDS[checked.error][1];
77 const limit = `${IMAGE_MAX / 1024 / 1024} MB`;
78 return `The image was not kept: ${checked.ok || checked.error === "bad_type" ? `only a PNG, JPEG, GIF or WebP picture up to ${limit} is taken` : why}. Your words were kept.`;
79 }
80
81 /**
82 * The line saying where a share came from, never sent: "Shared from your phone: a link to
83 * example.com, some text and an image (name)." Plain words; the caller escapes them.
84 */
85 export function shareOrigin(params: URLSearchParams | Params, image?: string): string {
86 const get = (k: string) => (params.get(k) ?? "").trim();
87 const parts: string[] = [];
88 const url = get(SHARE_PARAMS.url);
89 if (url !== "" && URL.canParse(url)) parts.push(`a link to ${new URL(url).host}`);
90 if (get(SHARE_PARAMS.text) !== "" || get(SHARE_PARAMS.title) !== "") parts.push("some text");
91 if (image !== undefined) parts.push(`an image (${image})`);
92 const list = parts.length < 2 ? parts.join("") : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
93 return `Shared from your phone${list === "" ? "" : `: ${list}`}.`;
94 }
95
6096 /** The composer form's field names. */
6197 export const COMPOSER_FIELDS = { text: "text", app: "app", back: "back", once: "once" } as const;
6298
src/web/studio/share_receive.ts +62 −21
@@ -11,6 +11,7 @@
1111 * `html`.
1212 */
1313 import { keepThought } from "../../actions/thought.ts";
14 import { FILE_WORDS, storeFile } from "../../core/conversation_files.ts";
1415 import { emptyNote } from "../empty_words.ts";
1516 import { expireCookie, setCookie } from "../../auth/cookies.ts";
1617 import type { Ctx } from "../../http/context.ts";
@@ -23,7 +24,7 @@ import { notFoundPage, signInHref } from "../chrome.ts";
2324 import { field, readForm } from "../form.ts";
2425 import { html } from "../html.ts";
2526 import { page, redirect } from "../layout.ts";
26 import { COMPOSER_FIELDS, SHARE_PARAMS, refuseShare, refuseTell, sharedDraft } from "../share_target.ts";
27 import { COMPOSER_FIELDS, SHARE_IMAGE_FIELD, SHARE_PARAMS, refuseImage, refuseShare, refuseTell, shareOrigin, sharedDraft } from "../share_target.ts";
2728 import { btn, empty } from "../ui.ts";
2829 import { tellForm } from "./tell_form.ts";
2930
@@ -50,34 +51,59 @@ const tooMany = (ctx: Ctx): Response =>
5051 page({ ctx, title: "Share not sent", body: html`<h1>Too many shares</h1>${empty({ icon: "lock", title: "Too many shares from this address; try again in a minute.", action: btn("Back to the forge", { href: "/", variant: "primary" }) })}` }, 429);
5152
5253 /** Hold the words and give the cookie that names them. */
53 const hold = (ctx: Ctx, draft: string): string =>
54 setCookie(STASH_COOKIE, stashShare(ctx.app, draft), { maxAge: STASH_SECONDS, secure: secure(ctx) });
54 const hold = (ctx: Ctx, draft: string, extra: Omit<Held, "draft" | "at"> = {}): string =>
55 setCookie(STASH_COOKIE, stashShare(ctx.app, draft, Date.now(), extra), { maxAge: STASH_SECONDS, secure: secure(ctx) });
5556
5657 /** POST /tell/share */
5758 export async function shareReceive(ctx: Ctx): Promise<Response> {
5859 const form = await readForm(ctx, ctx.auth.user === undefined ? undefined : "rw");
59 if (form instanceof Response) return form;
60 if (form instanceof Response) {
61 // A picture is more than a signed-out caller may send before signing in: say so, not "payload
62 // too large".
63 if (form.status === 413 && ctx.auth.user === undefined) return refused(ctx, "That share is too big to take before you sign in. Sign in, then share it again; nothing was kept.", 413);
64 return form;
65 }
6066 const params = new URLSearchParams();
6167 for (const key of [...Object.values(SHARE_PARAMS), COMPOSER_FIELDS.text]) params.set(key, field(form, key));
6268 const draft = sharedDraft(params);
63 const words = refuseShare(params);
6469 const user = ctx.auth.user;
70 // At most one picture, read as bytes; an empty file field (a browser's "no file") is no picture.
71 const file = form.get(SHARE_IMAGE_FIELD);
72 const image = file instanceof File && file.size > 0 ? { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) } : undefined;
73 const words = refuseShare(params, image !== undefined);
6574 if (user === undefined) {
6675 // Nothing valid to keep: say so rather than hold it through a sign-in.
6776 if (words !== undefined) return refused(ctx, words, refuseTell(draft) === words ? 422 : 400, draft);
6877 if (!mayHold(ctx.app, clientAddress(ctx.request))) {
6978 return tooMany(ctx);
7079 }
71 return redirect(signInHref(ctx, "/tell/share"), { cookie: hold(ctx, draft) });
80 // The words wait through the sign-in; a picture does not (it has no owner yet), and that is
81 // said.
82 return redirect(signInHref(ctx, "/tell/share"), {
83 cookie: hold(ctx, draft, { params, ...(image === undefined ? {} : { note: "The image was not kept because you were signed out. Share it again." }) }),
84 });
7285 }
7386 if (words !== undefined) return refused(ctx, words, refuseTell(draft) === words ? 422 : 400, draft);
87 if (image !== undefined && field(form, CONFIRM_FIELD) !== "1") {
88 const bad = refuseImage(image.name, image.bytes);
89 // Refused: the words stay in the box, and the sentence says the picture did not.
90 if (bad !== undefined) return refused(ctx, bad, 422, draft);
91 }
7492 // A share arriving from the share sheet never files: it is held and shown, prefilled, for the
7593 // person's own Send (the form below carries CONFIRM_FIELD; the share sheet never does).
7694 if (field(form, CONFIRM_FIELD) !== "1") {
7795 if (!mayHold(ctx.app, clientAddress(ctx.request))) {
7896 return tooMany(ctx);
7997 }
80 return redirect("/tell/share", { cookie: hold(ctx, draft) });
98 // The picture is kept as the person's own unsent attachment (owner-only, swept after an hour):
99 // a draft, like the words.
100 let kept: { id: string; name: string } | undefined;
101 if (image !== undefined) {
102 const stored = storeFile(ctx.app.db, ctx.app.config.dataDir, user.id, image.name, image.bytes);
103 if (!stored.ok) return refused(ctx, `The image was not kept: ${FILE_WORDS[stored.error][1]}. Your words were kept.`, 422, draft);
104 kept = { id: stored.value.id, name: stored.value.name };
105 }
106 return redirect("/tell/share", { cookie: hold(ctx, draft, { params, ...(kept === undefined ? {} : { image: kept }) }) });
81107 }
82108 const kept = keepThought(ctx.app, user, draft, "share");
83109 if (!kept.ok) return refused(ctx, "That could not be kept.", 400);
@@ -89,7 +115,8 @@ export function shareHeld(ctx: Ctx): Response {
89115 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
90116 const rendering = performance.now();
91117 if (ctx.auth.user === undefined) return redirect(signInHref(ctx, "/tell/share"));
92 const draft = takeShare(ctx.app, cookieValue(ctx.request, STASH_COOKIE));
118 const held = takeHeld(ctx.app, cookieValue(ctx.request, STASH_COOKIE));
119 const draft = held?.draft;
93120 const clear = expireCookie(STASH_COOKIE, { secure: secure(ctx) });
94121 const response = page({
95122 ctx,
@@ -97,7 +124,9 @@ export function shareHeld(ctx: Ctx): Response {
97124 body: html`<h1>Tell the crew</h1>
98125 ${draft === undefined
99126 ? emptyNote("nothingIsWaitingToBeSent")
100 : html`<p class="muted small">Nothing is sent until you tap Send.</p>
127 : html`<p class="muted small" data-share-origin>${shareOrigin(held?.params ?? new URLSearchParams(), held?.image?.name)} Nothing is sent until you tap Send${held?.image === undefined ? "." : html`; the picture waits in <a href="/talk">Talk</a> for your next message there.`}</p>
128 ${held?.note === undefined ? html`` : html`<p role="alert" data-share-note>${held.note}</p>`}
129 ${held?.image === undefined ? html`` : html`<p><img src="/api/v1/conversation/files/${held.image.id}" alt="${held.image.name}" width="160" height="160" class="share-image" data-share-image></p>`}
outdated

Principle 1 and 2: this one paragraph promises the picture is kept 'for your next message in Talk', but Talk shows no pending file, so the promise cannot be kept. Fix first. Also the fixed width/height 160 distorts non-square photos: size by a .share-image rule with object-fit, not by attributes alone. The paragraph explains itself twice (the origin line already says an image came).

101130 <form class="stack" method="post" action="/tell/share">
102131 <input type="hidden" name="${CONFIRM_FIELD}" value="1">
103132 <textarea class="input" name="${COMPOSER_FIELDS.text}" rows="6" required aria-label="Tell the crew">${draft}</textarea>
@@ -135,14 +164,26 @@ export function shareReceipt(ctx: Ctx): Response {
135164 // Held words: a share that arrived signed out, kept on the server while its sender signs in. They
136165 // never ride in a URL (logs, history, Referer keep those); the browser holds only a random
137166 // HttpOnly cookie naming them. In memory on purpose: a few minutes of hand-off.
138 type Held = Map<string, { draft: string; at: number }>;
167 interface Held {
168 draft: string;
169 at: number;
170 /** The share's own fields, for the line saying where it came from. */
171 params?: URLSearchParams;
172 /** The picture, already kept as the person's unsent attachment. */
173 image?: { id: string; name: string };
174 /** A sentence to show with the held words. */
175 note?: string;
176 }
177 type HeldMap = Map<string, Held>;
139178 /** Per forge, not per process: two forges in one process never see each other's shares. */

Needless rewrite of heldShares with a ! assertion; the old version was clear. Keep the original and only change the type.

140 const HELD = new WeakMap<object, Held>();
141 const heldShares = (app: object): Held => {
142 let m = HELD.get(app);
143 if (m === undefined) HELD.set(app, (m = new Map()));
144 return m;
145 };
179 const HELD = new WeakMap<object, HeldMap>();
180 function heldShares(app: object): HeldMap {
181 const kept = HELD.get(app);
182 if (kept !== undefined) return kept;
183 const made: HeldMap = new Map();
184 HELD.set(app, made);
185 return made;
186 }
146187 const HELD_FOR_MS = 15 * 60 * 1000;
147188 const HELD_KEEP = 200;
148189
@@ -170,19 +211,19 @@ export function mayHold(app: object, address: string): boolean {
170211 }
171212
172213 /** Hold a draft; the key to put in the cookie. */
173 export function stashShare(app: object, draft: string, now = Date.now()): string {
214 export function stashShare(app: object, draft: string, now = Date.now(), extra: Omit<Held, "draft" | "at"> = {}): string {
174215 const held = heldShares(app);
175216 for (const [k, v] of held) if (now - v.at >= HELD_FOR_MS || held.size >= HELD_KEEP) held.delete(k);
176217 const key = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
177 held.set(key, { draft, at: now });
218 held.set(key, { draft, at: now, ...extra });
178219 return key;
179220 }
180221
181 /** The draft a key names, given up once (a second ask gets nothing), or undefined. */
182 export function takeShare(app: object, key: string | undefined, now = Date.now()): string | undefined {
222 /** The whole held share (words, fields, picture, note) a key names, given up once, or undefined. */
223 export function takeHeld(app: object, key: string | undefined, now = Date.now()): Held | undefined {
183224 if (key === undefined || !KEY.test(key)) return undefined;
184225 const map = heldShares(app);
185226 const held = map.get(key);
186227 map.delete(key);
187 return held !== undefined && now - held.at < HELD_FOR_MS ? held.draft : undefined;
228 return held !== undefined && now - held.at < HELD_FOR_MS ? held : undefined;
188229 }
src/web/style/components.ts +1
@@ -1253,6 +1253,7 @@ html[data-overlay] { overflow: hidden; }
12531253 .status-row > dt { font-weight: 550; }
12541254 .status-row > dd { margin: 0; min-width: 0; }
12551255 .status-row > dd.kept-words { white-space: pre-wrap; overflow-wrap: anywhere; }
1256 .share-image { display: block; width: 160px; height: 160px; max-width: 100%; object-fit: contain; }
outdated

Principle 6: a border and a --muted fill box the picture. Remove background and border; keep the fixed size and object-fit: contain. Update the line in docs/design/areas/feed.md.

12561257 .status-act { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
12571258 .status-act:empty { display: none; }
12581259 .status-days { display: grid; grid-template-columns: repeat(30, minmax(0, 1fr)); gap: 2px; width: min(100%, 240px); height: 16px; margin: 0; padding: 0; }
test/home-feed.test.ts +3 −2
@@ -231,12 +231,13 @@ describe("home is the feed", () => {
231231 test("a phone's share sheet opens the composer with the shared words, escaped, and sends nothing", async () => {
232232 const manifest = (await fetch(`${servers.url}/manifest.webmanifest`).then((r) =>
233233 r.json(),
234 )) as { share_target: { action: string; method: string; enctype: string; params: Record<string, string> } };
234 )) as { share_target: { action: string; method: string; enctype: string; params: Record<string, string>; files: unknown } };
235235 expect(manifest.share_target).toEqual({
236236 action: "/tell/share",
237237 method: "POST",
238 enctype: "application/x-www-form-urlencoded",
238 enctype: "multipart/form-data",
239239 params: { title: "title", text: "text", url: "url" },
240 files: [{ name: "image", accept: ["image/png", "image/jpeg", "image/gif", "image/webp"] }],
240241 });
241242 const before = listIssues(app.db, garden.id, { state: "open" }).length;
242243 const q = new URLSearchParams({
test/pages-budget.test.ts +1
@@ -61,6 +61,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
6161 "/next": { statements: 90 }, // a new page: measured 90 warm over the fixture's repositories, one ranking per administered repository, at most GROUPS_MAX = 5 (#15870)
6262 "/:owner/:name/next": { statements: 63 }, // -3 (#15913): the waiting offers and outsider reports ride the page's own writer check, the open-pull ceiling and count are one statement; -6 (#15940): the page's repository read once per request, the palette lists skip counts, the runs tab reuses the app read; +2: the waiting offers and the decision check beside the reports (#15887); +1: the size limits of held issues, one read of both (#15845); +2: the waiting outsider reports, the decider check and the list (#15840); +1: whether the repository is archived (#14305); +1: the wallet row, one read of the monthly cap (#13529); +1: the growth line, one read for the week, the open counts and the planner pause (#12290, #12867)
6363 "/:owner/:name/pulls/:number": { statements: 115 }, // +1: what a green pull waits for (#15812), and the head's check is read once for it, the next actor and the step (#15913); +1: whether the reports door is closed, one primary-key read per request, never from memory (#15053); +1: whether the repository is archived (#14305); +1: the desk hold on the pull, one read of the notes that link it (#12536); +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
64 "/talk": { statements: 61 }, // +1 on a conversation with no message yet, as the fixture's is: the person's unsent files (a picture shared from a phone, #16311) ride the read of the sent ones, so a conversation with messages pays nothing more
6465 "/api/v1/asks": { statements: 61 }, // +1: the stopped apps someone asked for, one read of the viewer's archived repositories (#12277)
6566 "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps
6667 "/settings/capacity": { statements: 70 },
test/share-target-image.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * The share sheet's three shapes: a link, some text, one picture (#16311). Each lands in a draft;
3 * none files.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { refuseImage, shareOrigin } from "../src/web/share_target.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let cookie = "";
21
22 beforeAll(async () => {
23 dataDir = await mkdtemp(join(tmpdir(), "forge-share-image-"));
24 app = createApp({ dataDir, port: 0, host: "forge.test" });
25 servers = await serve(app);
26 const made = await createUser(app.db, {
27 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
28 password: "a-good-passphrase", adminIfFirst: true,
29 });
30 if (!made.ok) throw new Error(made.error);
31 const res = await fetch(`${servers.url}/signin`, {
32 method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual",
33 });
34 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
35 }, 120_000);
36
37 afterAll(async () => {
38 servers.stop();
39 app.close();
40 await rm(dataDir, { recursive: true, force: true });
41 });
42
43 const thoughts = () => app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM thought").get()!.n;
44 const files = () => app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM conversation_file").get()!.n;
45 const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]);
46
47 /** What a phone posts: multipart, from the share sheet. */
48 async function share(fields: Record<string, string>, image?: { name: string; bytes: Uint8Array; type?: string }, headers: Record<string, string> = { cookie }) {
49 const form = new FormData();
50 for (const [k, v] of Object.entries(fields)) form.set(k, v);
51 if (image) form.set("image", new File([image.bytes], image.name, { type: image.type ?? "image/png" }));
52 return fetch(`${servers.url}/tell/share`, { method: "POST", headers: { ...headers, origin: servers.url }, body: form, redirect: "manual" });
53 }
54 const held = (res: Response) => fetch(`${servers.url}/tell/share`, { headers: { cookie: `${cookie}; ${res.headers.get("set-cookie")!.split(";")[0]}` } }).then((r) => r.text());
55
56 test("a shared link opens the box prefilled with the link and where it came from; nothing is sent", async () => {
57 const before = thoughts();
58 const res = await share({ title: "Rain <b>gauges</b>", url: "https://example.com/gauge" });
59 expect(res.status).toBe(303);
60 const out = await held(res);
61 expect(out).toContain("Rain &lt;b&gt;gauges&lt;/b&gt;\nhttps://example.com/gauge");
62 expect(out).toContain("Shared from your phone: a link to example.com and some text.");
63 expect(out).not.toContain("<b>gauges</b>");
64 expect(thoughts()).toBe(before);
65 });
66
67 test("shared text opens the box with the text, and says it is text", async () => {
68 const before = thoughts();
69 const out = await held(await share({ text: "remember the milk" }));
70 expect(out).toContain("remember the milk");
71 expect(out).toContain("Shared from your phone: some text.");
72 expect(thoughts()).toBe(before);
73 });
74
75 test("one shared picture is checked, kept as an unsent attachment and shown; no tell is made", async () => {
76 const before = thoughts(), filesBefore = files();
77 const res = await share({ text: "this one" }, { name: "photo<1>.png", bytes: PNG });
78 expect(res.status).toBe(303);
79 const out = await held(res);
80 expect(out).toContain("an image (photo1.png)");
81 expect(out).toMatch(/<img src="\/api\/v1\/conversation\/files\/[^"]+"/);
82 expect(files()).toBe(filesBefore + 1);
83 expect(thoughts()).toBe(before);
84 });
85
86 test("a picture alone is a share too", async () => {
87 const res = await share({}, { name: "a.png", bytes: PNG });
88 expect(res.status).toBe(303);
89 expect(await held(res)).toContain("Shared from your phone: an image (a.png).");
90 });
91
92 test("a refused picture says why and keeps the words, and keeps nothing else", async () => {
93 const filesBefore = files(), before = thoughts();
94 // Named .png and typed image/png, but its bytes are not a picture.
95 const res = await share({ text: "keep me" }, { name: "x.png", bytes: new TextEncoder().encode("not a picture") });
96 expect(res.status).toBe(422);
97 const out = await res.text();
98 expect(out).toContain("The image was not kept");
99 expect(out).toContain("PNG, JPEG, GIF or WebP");
100 expect(out).toContain("keep me");
101 expect(files()).toBe(filesBefore);
102 expect(thoughts()).toBe(before);

The 5 MB limit is only tested on refuseImage. Post an over-limit picture to /tell/share and expect the 422 with the limit and the words kept. Also add a signed-out post over 64 KiB and expect the 'too big to take before you sign in' sentence.

103 });
104
105 test("a picture over 5 MB is refused with the limit", () => {
106 const big = new Uint8Array(5 * 1024 * 1024 + 1);
107 big.set(PNG);
108 expect(refuseImage("big.png", big)).toContain("5 MB");
109 expect(refuseImage("ok.png", PNG)).toBeUndefined();
110 expect(refuseImage("empty.png", new Uint8Array())).toContain("not kept");
111 });
112
113 test("a picture over 5 MB posted to the endpoint is refused 422 with the limit, the words kept, nothing stored", async () => {
114 const filesBefore = files();
115 const big = new Uint8Array(5 * 1024 * 1024 + 1);
116 big.set(PNG);
117 const res = await share({ text: "keep these words" }, { name: "big.png", bytes: big });
118 expect(res.status).toBe(422);
119 const out = await res.text();
120 expect(out).toContain("5 MB");
121 expect(out).toContain("keep these words");
122 expect(files()).toBe(filesBefore);
123 });
124
125 test("a signed-out post over the sign-in cap says it is too big to take before you sign in", async () => {
126 const big = new Uint8Array(70 * 1024);
127 big.set(PNG);
128 const res = await share({ text: "hi" }, { name: "big.png", bytes: big }, {});
129 expect(res.status).toBe(413);
130 expect(await res.text()).toContain("too big to take before you sign in");
131 });
132
133 test("the shared picture waits on a plain /talk as an attached chip, one sentence says so, and a removed one is gone", async () => {
134 const res = await share({ text: "x" }, { name: "wait.png", bytes: PNG });
135 expect(res.status).toBe(303);
136 const form = await held(res);
137 expect(form).toContain('Nothing is sent until you tap Send; the picture waits in <a href="/talk">Talk</a> for your next message there.');
138 expect(form).not.toContain("It waits in");
139 const talk = await fetch(`${servers.url}/talk`, { headers: { cookie } }).then((r) => r.text());
140 const id = /data-pending-file="([^"]+)">wait\.png</.exec(talk)?.[1];
141 expect(id).toBeDefined();
142 const gone = await fetch(`${servers.url}/api/v1/conversation/files/${id}`, { method: "DELETE", headers: { cookie, origin: servers.url } });
143 expect(gone.ok).toBe(true);
144 const after = await fetch(`${servers.url}/talk`, { headers: { cookie } }).then((r) => r.text());
145 expect(after).not.toContain(`data-pending-file="${id}"`);
146 });
147
148 test("a signed-out picture is not held, and the held words say so", async () => {
149 const res = await share({ text: "hello" }, { name: "a.png", bytes: PNG }, {});
150 expect(res.status).toBe(303);
151 expect(res.headers.get("location")).toContain("/signin");
152 const out = await held(res);
153 expect(out).toContain("hello");
154 expect(out).toContain("The image was not kept because you were signed out");
155 });
156
157 test("the origin line names only what was shared", () => {
158 expect(shareOrigin(new URLSearchParams({ url: "https://example.com/a" }))).toBe("Shared from your phone: a link to example.com.");
159 expect(shareOrigin(new URLSearchParams())).toBe("Shared from your phone.");
160 });
test/share-target.test.ts +2 −2
@@ -43,8 +43,8 @@ const shareQuery = (o: Record<string, string>) => new URLSearchParams(o).toStrin
4343 const thoughts = () => app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM thought").get()!.n;
4444
4545 test("the manifest declares the same names the composer uses", async () => {
46 const m = (await (await fetch(`${servers.url}/manifest.webmanifest`)).json()) as { share_target: { action: string; method: string; enctype: string; params: Record<string, string> } };
47 expect(m.share_target).toEqual({ action: "/tell/share", method: "POST", enctype: "application/x-www-form-urlencoded", params: { ...SHARE_PARAMS } });
46 const m = (await (await fetch(`${servers.url}/manifest.webmanifest`)).json()) as { share_target: { action: string; method: string; enctype: string; params: Record<string, string>; files: unknown } };
47 expect(m.share_target).toEqual({ action: "/tell/share", method: "POST", enctype: "multipart/form-data", params: { ...SHARE_PARAMS }, files: [{ name: "image", accept: ["image/png", "image/jpeg", "image/gif", "image/webp"] }] });
4848 });
4949
5050 test("a share opens the composer with title, text and url joined, escaped", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs