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

The phone's share sheet can tell the crew: a web share target that files a tell #15704

Merged opened this

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

Merged

torque/forge:torque/15684-the-phone-s-share-sheet-can-tell-the-cre → main 0 commits fork 5 threads · 5 unresolved

  • Merged. torque/15684-the-phone-s-share-sheet-can-tell-the-cre was merged into main as bc83af5.

Review

Sign in to review this change.
20 files changed +434 −26
docs/design/areas/feed.md +4
@@ -17,3 +17,7 @@ The tell box takes the cursor from a small script in `feedJs` only when the feed
1717 ## Run age
1818
1919 `.age` sits on the `<time>` of a run post and holds `min-width: 10ch`, the width of its longest words (`59 min ago`), so the age never changes width as it grows older, a phone's 360 px byline included. It says elapsed time only (`4 min ago`, `1 d ago`); the headline says whether the run finished or failed.
20
21 ## Kept words
22
23 `.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.
docs/design/audit.md +1
@@ -71,6 +71,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
7171 - `/flow` — `pages/flow.ts` · the pipeline from ready issue to live deploy, and the bottleneck · `/system`, `/board`, `/` · none seen. A topbar button points here.
7272 - `/talk` — `pages/talk.ts` · the person's one conversation with the forge: history, composer, Do it and Not now; replies stream in over `/talk/stream` · `/settings/confirms` (the same yes, as a list), the home tell box (one line to an app's crew) · none seen; styles in `docs/design/areas/talk.md`.
7373 - `/tell` — `studio/share_tell.ts` · where a phone's share sheet lands: the shared words in a form, the last repository chosen, nothing filed until Send · the phone's share sheet (manifest `share_target`) · none seen.
74 - `/tell/share` — `studio/share_receive.ts` · the words a phone shared while signed out, held on the server through sign-in, in a form filed only on Send · the sign-in redirect after a share · none seen.
7475 - `/notes` — `pages/notes.ts` · what the person wrote, newest first, with the planner's verdict and live state in one line, and one tap to overrule it · the home tell box (Notes button), the user menu, the palette · none seen; styles in `docs/design/areas/notes.md`.
7576 - `/pipeline` — `pages/pipeline.ts` · the four steps a change follows (check, review, land, live), for a newcomer · a pull page's step line, `/flow` · none seen.
7677 - `/packs` — `pages/packs.ts` · the premade forges this forge ships, what each brings, how to deploy it and how a stranger helps build its apps · the user menu, the signed-out menu, the palette · none seen; uses the shared card, list and button components.
docs/features/share-receive.md added +23
@@ -0,0 +1,23 @@
1 ---
2 topic: Tell the crew
3 row: Share to the forge from a phone's share sheet
4 ---
5 # Share to the forge from a phone's share sheet (#15684)
6
7 **Phone.** With the forge installed as an app, share text or a link to it. The sheet POSTs
8 `title`, `text` and `url` to `/tell/share`, so the words are never in a logged URL.
9
10 - Signed in: one tell is filed as typed and you land on its receipt (`/tell/share/:id`), which
11 only you can open.
12 - Signed out: the words are held on the server for 15 minutes behind an HttpOnly cookie, you
13 sign in, and `/tell/share` shows them in a form; nothing is filed until you tap Send.
14 - Nothing shared, a link that is not http(s), or more than 4,000 characters is refused with a
15 sentence; nothing is cut or held. A signed-out address may hold 10 shares a minute.
16
17 **Terminal.** `ssh` in, open the palette (`:`) and pick "Shared from my phone": your own
outdated

Both doors: this how-to names only the phone and the web receipt. The terminal has no screen for share-filed tells, so what a person can do on the page they cannot do in the terminal. Restore a src/tui/ screen and say here how to open it.

18 share-filed tells, newest first (50 at most; `/` filters, Enter shows one's words whole, `esc`
19 back). Nothing to list says so.
20
21 Code: `src/web/studio/share_receive.ts` (routes, held words, the per-address limit),
22 `shareReceiptsCommand` in `src/tui/screens/share_tell.ts` (terminal). Pinned by
23 `test/share-target.test.ts` and `test/share-tell-tui.test.ts`.
src/core/thoughts.ts +8 −5
@@ -13,16 +13,19 @@ export interface Thought {
1313 receivedAt: string;
1414 }
1515
16 /** The author's newest thoughts received at or after `since` (ISO), newest first; the text exactly as kept. */
17 export function recentThoughts(db: Database, authorId: string, limit: number, since = ""): Thought[] {
16 /**
17 * The author's newest thoughts received at or after `since` (ISO), newest first; the text exactly
18 * as kept. Given `source`, only the thoughts that door kept (`share`: the phone's share sheet).
19 */
20 export function recentThoughts(db: Database, authorId: string, limit: number, since = "", source: string | null = null): Thought[] {
1821 return db
1922 .query<
2023 { id: string; text: string; source: string; received_at: string },
21 [string, string, number]
24 [string, string, number, string | null]
2225 >(
23 "SELECT id, text, source, received_at FROM thought WHERE author = ?1 AND received_at >= ?2 ORDER BY received_at DESC, id DESC LIMIT ?3",
26 "SELECT id, text, source, received_at FROM thought WHERE author = ?1 AND received_at >= ?2 AND (?4 IS NULL OR source = ?4) ORDER BY received_at DESC, id DESC LIMIT ?3",
2427 )
25 .all(authorId, since, limit)
28 .all(authorId, since, limit, source)
2629 .map((r) => ({ id: r.id, text: r.text, source: r.source, receivedAt: r.received_at }));
2730 }
2831
src/http/server.ts +4
@@ -331,6 +331,7 @@ import {
331331 tellUndoSubmit,
332332 } from "../web/studio/actions.ts";
333333 import { shareTellPage } from "../web/studio/share_tell.ts";
334 import { shareHeld, shareReceipt, shareReceive } from "../web/studio/share_receive.ts";
334335 import { forgeReady } from "../web/pages/forge-ready.ts";
335336 import { forgeName } from "../web/pages/forge-name.ts";
336337 import { claimFragmentPage, claimOptions, claimRenew, claimSubmit, welcomePage, welcomeSubmit } from "../web/pages/claim.ts";
@@ -1477,6 +1478,9 @@ export function buildRouter(): Router<Handler> {
14771478 router.add("POST", "/tell", composerSubmit);
14781479 // Where the phone share sheet lands: the shared words in a form, filed only on Send.
14791480 router.add("GET", "/tell", shareTellPage);
1481 router.add("POST", "/tell/share", shareReceive);
1482 router.add("GET", "/tell/share", shareHeld);
1483 router.add("GET", "/tell/share/:id", shareReceipt);
14801484 // A like from a card without a script (#7751): the feed's `liked`, then back to the feed.
14811485 router.add("POST", "/feed/like", likeSubmit);
14821486 router.add("POST", "/feed/back", filterBackSubmit);
src/tui/forge.ts +3 −1
@@ -26,7 +26,7 @@ import { statusCommand } from "./screens/status.ts";
2626 import { templatesCommand } from "./screens/templates.ts";
2727 import { needsCommands } from "./screens/needs.ts";
2828 import { asksAdminCommands } from "./screens/asks_admin.ts";
29 import { shareTellCommand } from "./screens/share_tell.ts";
29 import { shareReceiptsCommand, shareTellCommand } from "./screens/share_tell.ts";
3030 import { sendChangeCommand } from "./screens/send_change.ts";
3131 import { interruptedOutCommand } from "./screens/interrupted_out.ts";
3232 import { getForgeCommand } from "./screens/getforge.ts";
@@ -361,6 +361,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
361361 );
362362 // The owner's read-only mirrors, as the profile's "work (read-only)" draws them.
363363 if (session.user !== undefined && session.user.kind !== "agent") commands.push(workCommand(session, ctx));
364 // What this person's phone share sheet filed, as each receipt at /tell/share/:id shows it.
365 if (session.user !== undefined && session.user.kind !== "agent") commands.push(shareReceiptsCommand(session, ctx));
364366 // An app from a sentence, as /apps/new makes it: a person's, never an agent's.
365367 if (session.user !== undefined && session.user.kind !== "agent")
366368 commands.push({
src/tui/screens/share_tell.ts +51
@@ -4,11 +4,16 @@
44 * a confirm; nothing is filed until the person says yes. The same refusal
55 * (`refuseShare`), draft (`sharedDraft`), last-told rule (`lastTold`) and
66 * filing (`tell`, `keepThought`) as the page.
7 *
8 * Also the terminal's door to the share sheet's receipts (`POST /tell/share`, receipt at
9 * `/tell/share/:id`): "Shared from my phone" lists the person's own share-filed tells, newest
10 * first, and Enter shows one's words whole. Read-only; a tell is its author's alone.
711 */
812 import { appsFirst } from "../../actions/first_ask.ts";
913 import { keepThought } from "../../actions/thought.ts";
1014 import { tell } from "../../actions/tell.ts";
1115 import { lastTold, TOLD_FORGE } from "../../core/last_told.ts";
16 import { recentThoughts, type Thought } from "../../core/thoughts.ts";
1217 import { listReposWritableTo } from "../../core/repos.ts";
1318 import { refuseShare, sharedDraft } from "../../web/share_target.ts";
1419 import { tellAnswer } from "../../actions/tell_answer.ts";
@@ -114,3 +119,49 @@ export async function fileShare(
114119 if (repo === undefined) return { tone: "danger", text: "That app is not one you can tell." };
115120 return tellAnswer(await tell(f.app, user, repo, draft), draft.trim());
116121 }
122
123 /** Receipts shown at most: the newest. */
124 export const RECEIPTS_SHOWN = 50;
125
126 /** The person's own tells their phone's share sheet filed, newest first. */
127 export function shareReceipts(f: Pick<Session, "db">, user: User): Thought[] {
128 return recentThoughts(f.db, user.id, RECEIPTS_SHOWN, "", "share");
129 }
130
131 /** One picker row per receipt: the words on one line, when as the hint. */
132 export function receiptItems(rows: readonly Thought[]): PickItem[] {
133 return rows.map((r) => ({ id: r.id, label: r.text.replace(/\s+/g, " ").trim(), hint: r.receivedAt }));
134 }
135
136 export function shareReceiptsCommand(f: Session, ctx: Ctx) {
137 return {
138 id: "share-receipts",
139 title: "Shared from my phone",
140 hint: "the tells your phone's share sheet filed",
141 run: () => {
142 const user = f.user;
143 if (user === undefined) return ctx.toast("Sign in to read what you shared.", "danger");
144 const rows = shareReceipts(f, user);
145 if (rows.length === 0) return ctx.toast("Nothing has been shared from your phone.");
146 const parent = blank("Shared from my phone");
147 ctx.push(
148 pickerScreen(ctx, parent, {
149 title: "Shared from my phone",
150 items: receiptItems(rows),
151 onPick: ([id]) => {
152 const row = rows.find((r) => r.id === id);
153 if (row === undefined) return;
154 ctx.push(
155 confirmScreen(ctx, parent, {
156 title: `Received ${row.receivedAt}`,
157 body: wrap(row.text, 60),
158 actions: [{ label: "Close" }],
159 onChoose: () => {},
160 }),
161 );
162 },
163 }),
164 );
165 },
166 };
167 }
src/web/chrome.ts +2 −3
@@ -173,9 +173,8 @@ export function signInFirst(ctx: Ctx): Response {
173173 return redirect(signInHref(ctx));
174174 }
175175
176 /** Where signing in starts, coming back to this page after. */
177 export function signInHref(ctx: Ctx): string {
178 const next = hereAddress(ctx);
176 /** Where signing in starts, coming back to this page after (or to `next`, a path on this forge). */
177 export function signInHref(ctx: Ctx, next: string = hereAddress(ctx)): string {
179178 // Behind a platform edge the edge is how people sign in; an account it
180179 // made has no password here, so the password form would only refuse them.
181180 if (edgeStrangerLogin(ctx.request, activeEdgeToken(ctx.app), ctx.auth.user) !== undefined)
src/web/share_target.ts +9 −3
@@ -4,8 +4,9 @@
44 * (studio/feed.ts, studio/actions.ts) both import these names, so they
55 * cannot drift apart.
66 *
7 * A share arrives as `GET /?title=…&text=…&url=…`; the composer opens with
8 * those words as a draft; Post is `POST /tell` with the fields below.
7 * A share arrives as `POST /tell/share` (title, text, url in the body, never in a
8 * logged URL); signed in it files one tell and shows a receipt (studio/share_receive.ts).
9 * Links made before this (`GET /?title=…`, `GET /tell?…`) still open the composer.
910 */
1011 import { TELL_TEXT_MAX } from "../actions/tell_from.ts";
1112 import type { URLSearchParams as Params } from "node:url";
@@ -14,7 +15,12 @@ import type { URLSearchParams as Params } from "node:url";
1415 export const SHARE_PARAMS = { title: "title", text: "text", url: "url" } as const;
1516
1617 /** What the manifest declares. */
17 export const SHARE_TARGET = { action: "/tell", method: "GET", params: SHARE_PARAMS } as const;
18 export const SHARE_TARGET = {
19 action: "/tell/share",
20 method: "POST",
21 enctype: "application/x-www-form-urlencoded",
22 params: SHARE_PARAMS,
23 } as const;
1824
1925 /** The longest tell the composer takes (its textarea's `maxlength`). */
2026 export const TELL_MAX = TELL_TEXT_MAX;
src/web/studio/share_receive.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * The phone share sheet's POST target (manifest `share_target`, share_target.ts).
3 * POST /tell/share signed in: files one tell (a thought kept as typed) and redirects to
4 * its receipt; signed out: holds the words server-side (at most
5 * SHARES_PER_MINUTE per socket address) and sends the person to sign in.
6 * GET /tell/share after sign-in: the held words in a form that posts back here, filed
7 * on Send.
8 * GET /tell/share/:id the receipt: what was sent, to the person who sent it only.
9 * Same-origin is checked by readForm; length by refuseShare/refuseTell; output is escaped by
10 * `html`.
11 */
12 import { keepThought } from "../../actions/thought.ts";
13 import { expireCookie, setCookie } from "../../auth/cookies.ts";
14 import type { Ctx } from "../../http/context.ts";
15 import { cookieValue } from "../../http/context.ts";
16 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
17 import { secureFor } from "../../http/cookie_secure.ts";
18 import { bucketOf, clientAddress } from "../../http/peer.ts";
19 import { RateLimiter } from "../../core/ratelimit.ts";
20 import { notFoundPage, signInHref } from "../chrome.ts";
21 import { field, readForm } from "../form.ts";
22 import { html } from "../html.ts";
23 import { page, redirect } from "../layout.ts";
24 import { COMPOSER_FIELDS, SHARE_PARAMS, refuseShare, refuseTell, sharedDraft } from "../share_target.ts";
25 import { btn, empty } from "../ui.ts";
26 import { tellForm } from "./tell_form.ts";
27
28 const secure = (ctx: Ctx) => secureFor(ctx.url, ctx.app.config.url);
29
30 function refused(ctx: Ctx, words: string, status: number, text = ""): Response {
31 return page(
32 {
33 ctx,
34 title: "Share not sent",
35 body: status === 422
36 ? html`<h1>Tell not sent</h1>${tellForm({ text, refusal: words, hidden: html`` })}`
outdated

Principle 7/8: the refusal page is hand-rolled markup with a bare alert paragraph; use the named components and one plain sentence.

37 : html`<h1>That share was not kept</h1>${empty({ icon: "lock", title: words, action: btn("Back to the forge", { href: "/", variant: "primary" }) })}`,
38 },
39 status,
40 );
41 }
42
43 /** POST /tell/share */
44 export async function shareReceive(ctx: Ctx): Promise<Response> {
45 const form = await readForm(ctx, ctx.auth.user === undefined ? undefined : "rw");
46 if (form instanceof Response) return form;
47 const params = new URLSearchParams();
48 for (const key of [...Object.values(SHARE_PARAMS), COMPOSER_FIELDS.text]) params.set(key, field(form, key));
49 const draft = sharedDraft(params);
50 const words = refuseShare(params);
51 const user = ctx.auth.user;
52 if (user === undefined) {
53 // Nothing valid to keep: say so rather than hold it through a sign-in.
54 if (words !== undefined) return refused(ctx, words, refuseTell(draft) === words ? 422 : 400, draft);
55 if (!mayHold(ctx.app, clientAddress(ctx.request))) {
56 return 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);
57 }
58 const key = stashShare(ctx.app, draft);
59 const cookie = setCookie(STASH_COOKIE, key, { maxAge: STASH_SECONDS, secure: secure(ctx) });
60 const next = signInHref(ctx, "/tell/share");
61 return redirect(next, { cookie });
62 }
63 if (words !== undefined) return refused(ctx, words, refuseTell(draft) === words ? 422 : 400, draft);
64 const kept = keepThought(ctx.app, user, draft, "share");
65 if (!kept.ok) return refused(ctx, "That could not be kept.", 400);
66 return redirect(`/tell/share/${kept.value.id}`);
67 }
68
69 /** GET /tell/share */
70 export function shareHeld(ctx: Ctx): Response {
71 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
72 const rendering = performance.now();
73 if (ctx.auth.user === undefined) return redirect(signInHref(ctx, "/tell/share"));
74 const draft = takeShare(ctx.app, cookieValue(ctx.request, STASH_COOKIE));
75 const clear = expireCookie(STASH_COOKIE, { secure: secure(ctx) });
76 const response = page({
77 ctx,
78 title: "Shared words · held",
79 body: html`<h1>Tell the crew</h1>
80 ${draft === undefined
81 ? html`<p class="muted">Nothing is waiting to be sent.</p>`
82 : html`<p class="muted small">Nothing is sent until you tap Send.</p>
83 <form class="stack" method="post" action="/tell/share">
84 <textarea class="input" name="${COMPOSER_FIELDS.text}" rows="6" required aria-label="Tell the crew">${draft}</textarea>
85 <div class="bar"><span class="spacer"></span>${btn("Send", { variant: "primary" })}</div>
86 </form>`}`,
87 });
88 response.headers.append("set-cookie", clear);
89 notePhase(ctx.request, "render", performance.now() - rendering);
90 return response;
91 }
92
93 /** GET /tell/share/:id */
94 export function shareReceipt(ctx: Ctx): Response {
95 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
96 const user = ctx.auth.user;
97 if (user === undefined) return redirect(signInHref(ctx));
98 const row = ctx.app.db
99 .query<{ text: string; received_at: string }, [string, string]>(
100 "SELECT text, received_at FROM thought WHERE id = ?1 AND author = ?2 AND source = 'share'",
101 )
102 .get(ctx.params.id ?? "", user.id);
103 if (row === null) return notFoundPage(ctx);
104 return page({
105 ctx,
outdated

Principle 7: what was sent is a fact, show it as a dl row (text, link) rather than a blockquote around a pre.

106 title: "Tell sent",
outdated

Principle 1: the receipt already said what was sent; this paragraph explains it a second time. One sentence, or nothing.

107 body: html`<h1>Sent to the crew</h1>
108 <dl class="status-rows" data-receipt>
109 <div class="status-row"><dt>Received</dt><dd>${row.received_at}</dd></div>
110 <div class="status-row"><dt>Text</dt><dd class="kept-words">${row.text}</dd></div>
111 </dl>
112 <p>${btn("Back to the feed", { href: "/feed", variant: "primary" })}</p>`,
113 });
114 }
115
116 // Held words: a share that arrived signed out, kept on the server while its sender signs in. They
117 // never ride in a URL (logs, history, Referer keep those); the browser holds only a random
118 // HttpOnly cookie naming them. In memory on purpose: a few minutes of hand-off.
119 type Held = Map<string, { draft: string; at: number }>;
120 /** Per forge, not per process: two forges in one process never see each other's shares. */
121 const HELD = new WeakMap<object, Held>();
122 const heldShares = (app: object): Held => {
123 let m = HELD.get(app);
124 if (m === undefined) HELD.set(app, (m = new Map()));
125 return m;
126 };
127 const HELD_FOR_MS = 15 * 60 * 1000;
128 const HELD_KEEP = 200;
129
130 /** The cookie that names a held share. */
131 export const STASH_COOKIE = "forge_share";
132 export const STASH_SECONDS = HELD_FOR_MS / 1000;
133 const KEY = /^[0-9a-f]{32}$/;
134
135 /** Signed-out holds one socket address may start in a minute; past it the forge says to wait. */
136 export const SHARES_PER_MINUTE = 10;
137 const LIMITERS = new WeakMap<object, RateLimiter>();
138
139 /**
140 * Whether this address may hold another share. `address` is what the listener resolved from the
141 * socket (`clientAddress`), never a header a caller wrote; counted per address so one flood cannot
142 * evict other people's held shares.
143 */
144 export function mayHold(app: object, address: string): boolean {
145 let limiter = LIMITERS.get(app);
146 if (limiter === undefined) {
147 limiter = new RateLimiter({ perMinute: SHARES_PER_MINUTE, adminPerMinute: SHARES_PER_MINUTE, enabled: true, maxKeys: 1_000 });
148 LIMITERS.set(app, limiter);
149 }
150 return limiter.take(`share:${bucketOf(address)}`, "ro").allowed;
151 }
152
153 /** Hold a draft; the key to put in the cookie. */
154 export function stashShare(app: object, draft: string, now = Date.now()): string {
155 const held = heldShares(app);
156 for (const [k, v] of held) if (now - v.at >= HELD_FOR_MS || held.size >= HELD_KEEP) held.delete(k);
157 const key = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
158 held.set(key, { draft, at: now });
159 return key;
160 }
161
162 /** The draft a key names, given up once (a second ask gets nothing), or undefined. */
163 export function takeShare(app: object, key: string | undefined, now = Date.now()): string | undefined {
164 if (key === undefined || !KEY.test(key)) return undefined;
165 const map = heldShares(app);
166 const held = map.get(key);
167 map.delete(key);
168 return held !== undefined && now - held.at < HELD_FOR_MS ? held.draft : undefined;
169 }
src/web/style/components.ts +1
@@ -1242,6 +1242,7 @@ html[data-overlay] { overflow: hidden; }
12421242 }
12431243 .status-row > dt { font-weight: 550; }
12441244 .status-row > dd { margin: 0; min-width: 0; }
1245 .status-row > dd.kept-words { white-space: pre-wrap; overflow-wrap: anywhere; }
12451246 .status-act { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
12461247 .status-act:empty { display: none; }
12471248 .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 +4 −3
@@ -231,10 +231,11 @@ 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; params: Record<string, string> } };
234 )) as { share_target: { action: string; method: string; enctype: string; params: Record<string, string> } };
235235 expect(manifest.share_target).toEqual({
236 action: "/tell",
237 method: "GET",
236 action: "/tell/share",
237 method: "POST",
238 enctype: "application/x-www-form-urlencoded",
238239 params: { title: "title", text: "text", url: "url" },
239240 });
240241 const before = listIssues(app.db, garden.id, { state: "open" }).length;
test/no-polling.test.ts +1
@@ -330,6 +330,7 @@ const NOT_WALKED: Record<string, string> = {
330330 "/resilience/nightly/:job": "needs a nightly job name",
331331 "/runs/:id": "the seed creates no run",
332332 "/signin/access/:token": "needs a one-time access link an admin minted",
333 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
333334 "/settings/features/:slug": "needs a feature slug",
334335 "/:owner/:name/pulls/:number/review/:step": "needs a pull carrying review steps, which the seed has none of",
335336 "/settings/origins/:id/archived": ORIGIN,
test/pages-budget.test.ts +1 −1
@@ -64,7 +64,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
6464 };
6565
6666 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
67 const MAX_UNFIXTURED = 151; // +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645)
67 const MAX_UNFIXTURED = 152; // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645)
6868
6969 /** Streams and live fragments: no page. */
7070 const NOT_PAGES = new Set([
test/palette-roster.test.ts +2
@@ -91,6 +91,7 @@ test("a site-admin person is offered the whole roster", () => {
9191 ["settings", "Repository settings", "owner/name"],
9292 ["new-repo", "New repository", undefined],
9393 ["work", "work (read-only)", "repositories mirrored from read-only origins, last fetch and why one failed"],
94 ["share-receipts", "Shared from my phone", "the tells your phone's share sheet filed"],
9495 ["new-app", "New app", "say what it does in a sentence; the crew starts on it"],
9596 ["new-app-template", "New app from a template", "copy a repository you can read, as the starting files"],
9697 ["bring-app", "Bring an app", "paste a link from another forge; it runs here"],
@@ -389,6 +390,7 @@ test("a member person is offered the signed-in roster without the admin entries"
389390 ["settings", "Repository settings", "owner/name"],
390391 ["new-repo", "New repository", undefined],
391392 ["work", "work (read-only)", "repositories mirrored from read-only origins, last fetch and why one failed"],
393 ["share-receipts", "Shared from my phone", "the tells your phone's share sheet filed"],
392394 ["new-app", "New app", "say what it does in a sentence; the crew starts on it"],
393395 ["new-app-template", "New app from a template", "copy a repository you can read, as the starting files"],
394396 ["bring-app", "Bring an app", "paste a link from another forge; it runs here"],
test/security-floor-routes.test.ts +1
@@ -74,6 +74,7 @@ const UNSEEDED: Record<string, string> = {
7474 "/api/v1/runner/jobs/:id/git/info/refs": "a job a runner holds, read with that job's own token; the seed offers none (test/checks-runner-placement.test.ts covers it)",
7575 "/claim/start/:token": "needs a one-time start claim token, which the seed does not mint (test/start.test.ts covers it)",
7676 "/signin/access/:token": "needs a one-time access link an admin minted",
77 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
7778 "/talk/:id": TALK,
7879 "/talk/:id/download": TALK,
7980 "/docs/:file": "a file name of the documentation folder; the seed supplies no :file",
test/share-target-tell.test.ts +7 −7
@@ -9,6 +9,7 @@ import { createRepo } from "../src/actions/repos.ts";
99 import { createApp as insertApp } from "../src/core/apps.ts";
1010 import { createUser } from "../src/core/users.ts";
1111 import { serve, type Servers } from "../src/http/server.ts";
12 import { SHARE_PARAMS } from "../src/web/share_target.ts";
1213 import { quietLogs } from "./helpers/globals.ts";
1314
1415 quietLogs();
@@ -43,15 +44,14 @@ afterAll(async () => {
4344
4445 const thoughts = () => app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM thought").get()!.n;
4546
46 /** The share exactly as the manifest declares it: its action, its method, its parameter names. */
47 /**
48 * An older share link, as phones that installed before /share still send it: GET /tell with the
49 * names.
50 */
4751 async function share(fields: Record<string, string>, headers: Record<string, string> = { cookie }) {
48 const m = (await (await fetch(`${servers.url}/manifest.webmanifest`)).json()) as {
49 share_target: { action: string; method: string; params: Record<string, string> };
50 };
5152 const q = new URLSearchParams();
52 for (const [k, v] of Object.entries(fields)) q.set(m.share_target.params[k]!, v);
53 expect(m.share_target.method).toBe("GET");
54 return fetch(`${servers.url}${m.share_target.action}?${q}`, { headers, redirect: "manual" });
53 for (const [k, v] of Object.entries(fields)) q.set(SHARE_PARAMS[k as keyof typeof SHARE_PARAMS], v);
54 return fetch(`${servers.url}/tell?${q}`, { headers, redirect: "manual" });
5555 }
5656
5757 test("a shared link opens a prefilled composer and files nothing", async () => {
test/share-target.test.ts +101 −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; params: Record<string, string> } };
47 expect(m.share_target).toEqual({ action: "/tell", method: "GET", 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> } };
47 expect(m.share_target).toEqual({ action: "/tell/share", method: "POST", enctype: "application/x-www-form-urlencoded", params: { ...SHARE_PARAMS } });
4848 });
4949
5050 test("a share opens the composer with title, text and url joined, escaped", async () => {
@@ -149,3 +149,102 @@ test("claimShare evicts only the oldest when full, and release gives a token bac
149149 expect(claimShare("u", hex(1999), 4004)).toBe("fresh");
150150 forgetShares();
151151 });
152
153 const share = (fields: Record<string, string>, headers: Record<string, string> = {}) =>
154 fetch(`${servers.url}/tell/share`, { method: "POST", headers, body: new URLSearchParams(fields), redirect: "manual" });
155 const SHARED = { title: "A <b>page</b>", text: "look", url: "https://example.com/x?y=1" };
156
157 test("POST /tell/share signed in files one tell and redirects to an escaped receipt", async () => {
158 const before = thoughts();
159 const res = await share(SHARED, { cookie, origin: servers.url });
160 expect(res.status).toBe(303);
161 expect(thoughts()).toBe(before + 1);
162 const at = res.headers.get("location")!;
163 expect(at).toMatch(/^\/tell\/share\/[0-9a-z]+$/);
164 const out = await (await fetch(`${servers.url}${at}`, { headers: { cookie } })).text();
165 expect(out).toContain("A &lt;b&gt;page&lt;/b&gt;");
166 expect(out).not.toContain("<b>page</b>");
167 expect(out).toContain("https://example.com/x?y=1");
168 // Nobody else's receipt.
169 expect((await fetch(`${servers.url}${at}`, { redirect: "manual" })).status).toBe(303);
170 });
171
172 test("POST /tell/share from another origin is refused and files nothing", async () => {
173 const before = thoughts();
174 const res = await share(SHARED, { cookie, origin: "https://evil.example" });
175 expect(res.status).toBe(403);
176 expect(thoughts()).toBe(before);
177 });
178
179 test("POST /tell/share over the limit is 422 and files nothing", async () => {
180 const before = thoughts();
181 const res = await share({ text: "x".repeat(4_001) }, { cookie, origin: servers.url });
182 expect(res.status).toBe(422);
183 expect(thoughts()).toBe(before);
184 expect((await share({ text: " " }, { cookie, origin: servers.url })).status).toBe(422);
185 expect((await share({ url: "javascript:alert(1)" }, { cookie, origin: servers.url })).status).toBe(400);
186 expect(thoughts()).toBe(before);
187 });
188
189 test("POST /tell/share signed out files nothing, keeps the words out of any URL, and returns them after sign-in", async () => {
190 const before = thoughts();
191 const res = await share({ text: "secret plan", url: "https://example.com/s" }, { origin: servers.url });
192 expect(res.status).toBe(303);
193 const to = res.headers.get("location")!;
194 expect(to).toBe(`/signin?next=${encodeURIComponent("/tell/share")}`);
195 expect(to).not.toContain("secret");
196 const set = res.headers.get("set-cookie")!;
197 expect(set).toContain("HttpOnly");
198 expect(set).not.toContain("secret");
199 expect(thoughts()).toBe(before);
200 const held = set.split(";")[0]!;
201 const out = await (await fetch(`${servers.url}/tell/share`, { headers: { cookie: `${cookie}; ${held}` } })).text();
202 expect(out).toContain("secret plan\nhttps://example.com/s");
203 // Held once: a second visit has nothing.
204 const again = await (await fetch(`${servers.url}/tell/share`, { headers: { cookie: `${cookie}; ${held}` } })).text();
205 expect(again).not.toContain("secret plan");
206 expect(thoughts()).toBe(before);
207 });
208
209 test("POST /tell/share signed out and over-long is 422 and holds nothing", async () => {
210 const before = thoughts();
211 const res = await share({ text: "x".repeat(4_001) }, { origin: servers.url });
212 expect(res.status).toBe(422);
213 expect(res.headers.get("set-cookie")).toBeNull();
214 expect(thoughts()).toBe(before);
215 });
216
217 test("another signed-in person gets 404 on a receipt that is not theirs", async () => {
218 const made = await createUser(app.db, {
219 origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase",
220 });
221 if (!made.ok) throw new Error(made.error);
222 const signed = await fetch(`${servers.url}/signin`, {
223 method: "POST", body: new URLSearchParams({ username: "bob", password: "a-good-passphrase" }), redirect: "manual",
224 });
225 const bobCookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
226 const at = (await share(SHARED, { cookie, origin: servers.url })).headers.get("location")!;
227 expect((await fetch(`${servers.url}${at}`, { headers: { cookie } })).status).toBe(200);
228 expect((await fetch(`${servers.url}${at}`, { headers: { cookie: bobCookie } })).status).toBe(404);
229 });
230
231 test("a double POST signed in files two tells: a share is not deduplicated, each has its own receipt", async () => {
232 const before = thoughts();
233 const one = await share(SHARED, { cookie, origin: servers.url });
234 const two = await share(SHARED, { cookie, origin: servers.url });
235 expect(thoughts()).toBe(before + 2);
236 expect(one.headers.get("location")).not.toBe(two.headers.get("location"));
237 });
238
239 test("a signed-out address is limited, by socket address, before anything is held", async () => {
240 const { mayHold: mayStash, SHARES_PER_MINUTE } = await import("../src/web/studio/share_receive.ts");
241 const other = {};
242 for (let i = 0; i < SHARES_PER_MINUTE; i++) expect(mayStash(other, "203.0.113.9")).toBe(true);
243 expect(mayStash(other, "203.0.113.9")).toBe(false);
244 expect(mayStash(other, "203.0.113.10")).toBe(true);
245 // Over HTTP: the 11th signed-out POST from this one address is 429 and sets no cookie.
246 let last: Response | undefined;
247 for (let i = 0; i <= SHARES_PER_MINUTE; i++) last = await share({ text: `hold ${String(i)}` }, { origin: servers.url });
248 expect(last!.status).toBe(429);
249 expect(last!.headers.get("set-cookie")).toBeNull();
250 });
test/share-tell-tui.test.ts +40 −1
@@ -7,9 +7,12 @@ import { createRepo } from "../src/actions/repos.ts";
77 import { setRole } from "../src/actions/roles.ts";
88 import { createApp as insertApp } from "../src/core/apps.ts";
99 import { createUser, type User } from "../src/core/users.ts";
10 import { fileShare, parseShare, shareTargets } from "../src/tui/screens/share_tell.ts";
10 import { fileShare, parseShare, receiptItems, shareReceipts, shareReceiptsCommand, shareTargets } from "../src/tui/screens/share_tell.ts";
1111 import { refuseShare } from "../src/web/share_target.ts";
1212 import { quietLogs } from "./helpers/globals.ts";
13 import { settleApp } from "./helpers/tui.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1316
1417 quietLogs();
1518
@@ -108,3 +111,39 @@ test("the picker offers only writable apps and the forge, the one told last firs
108111 ids = shareTargets(f(), alice).map((x) => x.id);
109112 expect(ids[0]).toBe("forge");
110113 });
114
115 test("Shared from my phone lists only the person's own share-filed tells, newest first", async () => {
116 const bob = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get()!;
117 app.db.run("INSERT INTO thought (id, author, text, source, received_at) VALUES ('sh1', ?, 'first\nshare', 'share', '2026-01-01T00:00:00Z')", [alice.id]);
118 app.db.run("INSERT INTO thought (id, author, text, source, received_at) VALUES ('sh2', ?, 'second share', 'share', '2026-01-02T00:00:00Z')", [alice.id]);
119 app.db.run("INSERT INTO thought (id, author, text, source, received_at) VALUES ('shb', ?, 'bob shared', 'share', '2026-01-03T00:00:00Z')", [bob.id]);
120 const rows = shareReceipts(f(), alice);
121 // Composer thoughts (filed above) and bob's share are not hers from the share sheet.
122 expect(rows.map((r) => r.id)).toEqual(["sh2", "sh1"]);
123 expect(receiptItems(rows)).toEqual([
124 { id: "sh2", label: "second share", hint: "2026-01-02T00:00:00Z" },
125 { id: "sh1", label: "first share", hint: "2026-01-01T00:00:00Z" },
126 ]);
127 });
128
129 test("the receipts command draws the list signed in and refuses signed out", async () => {
130 const open = (user: User | undefined) => {
131 const { app: tui, session } = createForgeApp(
132 app,
133 { sshUsername: user?.username ?? "guest", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", ...(user ? { user } : {}) },
134 { terminal: headlessTerminal(120, 40), exitHooks: false },
135 );
136 tui.start();
137 shareReceiptsCommand(session, tui.ctx).run();
138 return tui;
139 };
140 const signedIn = open(alice);
141 await settleApp(signedIn);
142 const seen = signedIn.screen.toText();
143 expect(seen).toContain("Shared from my phone");
144 expect(seen).toContain("second share");
145 expect(seen).not.toContain("bob shared");
146 const out = open(undefined);
147 await settleApp(out);
148 expect(out.screen.toText()).toContain("Sign in to read what you shared.");
149 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs