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

A person shares one imported session by a link that hides what the forge redacts #18391

opened this

Merged 3h 21m ago, live in production

mason/forge:mason/18377-a-person-shares-one-imported-session-by → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/18377-a-person-shares-one-imported-session-by was merged into main as 080d52c.

Review

Sign in to review this change.
11 files changed +411 −19
docs/features/traces.md +4
@@ -76,3 +76,7 @@ A search you repeat (a repository, a model, a failed outcome, a tool) is kept un
7676 - **MCP:** the `trace` tool's `action: "saved"` lists, with `name` and `query` keeps, with `remove` (an id) ends one.
7777 - **Terminal:** in Traces, `b` types the start of a saved name and Enter opens it, `w` names the filters on screen and keeps them, `x` removes the search last opened.
7878 - **Opening re-reads the query** through the list's own validator: a facet that no longer exists (an outcome the forge dropped) is left out and the page, the API (`dropped`) and the terminal say which. Names are escaped everywhere. Code: `src/trace/saved.ts`, `src/web/pages/traces_saved.ts`.
79
80 ## Share an imported session (#18377)
81
82 On `/traces/<id>` of an imported session its importer sees **Make a share link** (`POST /traces/<id>/share`, same-origin) and, while one is live, **Stop sharing** (`/unshare`). It is the run's link (`src/trace/share.ts`, gate `shareImported` and `unshareImported` in `src/actions/trace_share.ts`, reader `src/trace/shared.ts`, the same `/traces/shared/<secret>` page): shown once, only its hash kept, one live link, off until made. Anyone else, signed in or not, gets the not-found, as for the session's own page. The shared page passes every step line and raw line through `redactHeld` (credential shapes and granted values become `[redacted]`) and drops who and where from the raw records (`src/trace/who.ts`: the keys `cwd`, `gitBranch`, `email`, `user`, `host`, `git` and the like, read only at a record's top level, in `payload` and in `message.metadata`; a tool's input is kept whole, even one with a `user` key), so no person and no path of the importer's machine shows; it says the forge cannot know every secret, and the form on the session says to share only what you have read. A stopped link, a deleted session or a link never made is the plain not-found, and one address opens 60 shared pages a minute. Terminal: in the Traces list (`src/tui/screens/traces.ts`) `s` on an imported row makes the link (shown to copy; a second press confirms when one is live) and `z` ends it.
src/actions/trace_share.ts +30
@@ -9,6 +9,8 @@ import { ownsRepo, type Repo } from "../core/repos.ts";
99 import type { User } from "../core/users.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { isShared, makeShare, revokeShare } from "../trace/share.ts";
12 import type { TraceRow } from "../trace/index_table.ts";
13 import { seenTraceRow } from "../trace/tree.ts";
1214 import { getRepoRun } from "./runs.ts";
1315
1416 export type ShareError = "unauthorized" | "forbidden" | "not_found";
@@ -39,3 +41,31 @@ export function unshareRun(app: App, actor: User | undefined, repo: Repo, runId:
3941 export function sharedNow(app: App, actor: User | undefined, repo: Repo, runId: string): boolean | undefined {
4042 return mayShare(app, actor, repo, runId).ok ? isShared(app.db, runId) : undefined;
4143 }
44
45 /**
46 * An imported session's link (#18377): the importer alone, through the same gate as the page that
47 * reads it (`seenTraceRow`); another person, a run's id or an unknown one is `not_found`.
48 */
49 function mayShareImported(app: App, actor: User | undefined, id: string): Result<{ actor: User; row: TraceRow }, ShareError> {
50 if (actor === undefined) return err("unauthorized");
51 const row = seenTraceRow(app, actor, id);
52 return row?.kind === "imported" ? ok({ actor, row }) : err("not_found");
53 }
54
55 /** Make the session's link (an older one ends); its secret is told once. */
56 export function shareImported(app: App, actor: User | undefined, id: string, now = Date.now()): Result<{ token: string }, ShareError> {
57 const who = mayShareImported(app, actor, id);
58 return who.ok ? ok({ token: makeShare(app.db, who.value.row.id, who.value.actor.id, now) }) : who;
59 }
60
61 /** End the session's link; whether one was live. */
62 export function unshareImported(app: App, actor: User | undefined, id: string, now = Date.now()): Result<{ was: boolean }, ShareError> {
63 const who = mayShareImported(app, actor, id);
64 return who.ok ? ok({ was: revokeShare(app.db, who.value.row.id, now) }) : who;
65 }
66
67 /** Whether the session is shared now: said only to its importer. */
68 export function importedSharedNow(app: App, actor: User | undefined, id: string): boolean | undefined {
69 const who = mayShareImported(app, actor, id);
70 return who.ok ? isShared(app.db, who.value.row.id) : undefined;
71 }
src/trace/imported_read.ts +25
@@ -90,3 +90,28 @@ export function rawLinesOf(lines: Iterable<string>, step: Pick<Step, "id">): str
9090 }
9191 return out;
9292 }
93
94 /**
95 * The lines of the file that name each step's id, found in one pass: a quoted string of a line is
96 * looked up among the ids, so a long session is read once, not once a step. `keep` is applied to
97 * a line before it is cut (the shared page redacts there), at most `RAW_LINES` a step.
98 */
99 export function rawLinesByStep(lines: Iterable<string>, steps: readonly Pick<Step, "id">[], keep: (line: string) => string = (l) => l): string[][] {
100 const at = new Map<string, number>();
101 steps.forEach((s, i) => {
102 if (!at.has(s.id)) at.set(s.id, i);
103 });
104 const out: string[][] = steps.map(() => []);
105 for (const line of lines) {
106 const hit = new Set<number>();
107 for (const m of line.matchAll(/"([^"\\]{1,200})"/g)) {
108 const i = at.get(m[1]!);
109 if (i !== undefined && out[i]!.length < RAW_LINES) hit.add(i);
110 }
111 if (hit.size === 0) continue;
112 const kept = keep(line);
113 const cut = kept.length > RAW_CHARS ? `${kept.slice(0, RAW_CHARS)}…` : kept;
114 for (const i of hit) out[i]!.push(cut);
115 }
116 return out;
117 }
src/trace/shared.ts +28 −1
@@ -16,6 +16,10 @@ import { restoreRunLog } from "../runs/archive.ts";
1616 import { stepsOf } from "./model.ts";
1717 import { parseRunLog } from "./run_log.ts";
1818 import { sharedRunId } from "./share.ts";
19 import { importedLines } from "./import.ts";
20 import { withoutWho } from "./who.ts";
21 import { parseImported, rawLinesByStep } from "./imported_read.ts";
22 import { getTraceRow } from "./index_table.ts";
1923
2024 /** The most steps and raw lines a step the shared page carries; a longer trace says so. */
2125 export const SHARED_STEPS_MAX = 2_000;
@@ -71,7 +75,8 @@ export function sharedTurn(app: App, address: string): { allowed: true } | { all
7175 */
7276 export async function readShared(app: App, token: string): Promise<SharedTrace | undefined> {
7377 const runId = sharedRunId(app.db, token);
74 if (runId === undefined) return undefined;
78 // A session or run that is gone ends its link at once, whatever is kept.
79 if (runId === undefined || (getTraceRow(app.db, runId) === undefined && getRun(app.db, runId) === undefined)) return undefined;
7580 let held = kept.get(app);
7681 if (held === undefined) {
7782 held = new Map();
@@ -89,6 +94,8 @@ export async function readShared(app: App, token: string): Promise<SharedTrace |
8994 }
9095
9196 async function buildShared(app: App, runId: string): Promise<SharedTrace | undefined> {
97 const row = getTraceRow(app.db, runId);
98 if (row?.kind === "imported") return buildImported(app, row.id, row.title);
9299 const run = getRun(app.db, runId);
93100 if (run === undefined) return undefined;
94101 await restoreRunLog(app.db, app.config.dataDir, run.id);
@@ -113,3 +120,23 @@ async function buildShared(app: App, runId: string): Promise<SharedTrace | undef
113120 });
114121 return { title, state: run.state, timed, steps, cut };
115122 }
123
124 /**
125 * An imported session as the link serves it: a deleted session or file is nothing. Its lines are
126 * redacted before they are cut, so a credential split by the cut is not left as a prefix; nothing
127 * of the importer (the account, the stored path) is read here.
128 */
129 function buildImported(app: App, id: string, rowTitle: string): SharedTrace | undefined {
130 const read = parseImported(app, { id });
131 if (read === undefined) return undefined;
132 const all = stepsOf(read.trace);
133 const shown = all.slice(0, SHARED_STEPS_MAX);
134 const raws = rawLinesByStep(importedLines(app.config.dataDir, id), shown, (l) => redactHeld(withoutWho(l)));
135 let cut = read.truncated || all.length > SHARED_STEPS_MAX;
136 const steps = shown.map((s, i): SharedStep => {
137 const raw = raws[i]!;
138 if (raw.length > SHARED_RAW_MAX) cut = true;
139 return { n: i + 1, failed: s.outcome === "error", kind: s.kind, line: redactHeld(s.line), took: read.timed ? { startMs: s.startMs, endMs: s.endMs } : undefined, raw: raw.slice(0, SHARED_RAW_MAX) };
140 });
141 return { title: redactHeld(rowTitle), state: "imported", timed: read.timed, steps, cut };
142 }
src/trace/who.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * What a shared session leaves out of each raw record (#18377): who made it and where, never what
3 * it did. Only the record's own level is read (its top level, `payload` as a Codex record keeps its
4 * session header there, and `message.metadata`), so a tool's input that happens to hold a `user`,
5 * `host` or `git` key is kept whole. Plain data in, plain data out.
6 */
7
8 /** Keys that say who or where the session was made. */
9 const WHO_KEYS = new Set(["cwd", "workdir", "working_directory", "gitBranch", "userEmail", "email", "user", "username", "hostname", "host", "originator", "git"]);
10
11 type Obj = { [k: string]: unknown };
12 const isObj = (v: unknown): v is Obj => v !== null && typeof v === "object" && !Array.isArray(v);
13
14 /** `o` without its who-keys; any of `into` that is an object is cleaned the same way. */
15 function cleaned(o: Obj, into: readonly string[]): Obj {
16 const out: Obj = {};
17 for (const [k, v] of Object.entries(o)) {
18 if (WHO_KEYS.has(k)) continue;
19 out[k] = into.includes(k) && isObj(v) ? cleaned(v, k === "message" ? ["metadata"] : []) : v;
20 }
21 return out;
22 }
23
24 /**
25 * A record without the person and the machine around it; a line that is not JSON is kept as it is.
26 */
27 export function withoutWho(line: string): string {
28 let rec: unknown;
29 try {
30 rec = JSON.parse(line);
31 } catch {
32 return line;
33 }
34 return isObj(rec) ? JSON.stringify(cleaned(rec, ["payload", "message"])) : line;
35 }
src/tui/screens/traces.ts +22 −3
@@ -10,7 +10,9 @@
1010 * page's own `readFilter`. `b` types the name of a saved search (the page's links) and opens the
1111 * first that starts with it, `w` names the filters on screen and keeps them, `x` removes the saved
1212 * search last opened (the search only: no trace is touched); a facet a saved search holds that no
13 * longer exists is dropped and said. Esc closes. The lines are `traceLine`, the page's own row.
13 * longer exists is dropped and said. On an imported session `s` makes its share link (shown once;
14 * a second press confirms when one is live, as it ends the old) and `z` ends it (#18377). Esc
15 * closes. The lines are `traceLine`, the page's own row.
1416 */
1517 import { binding } from "../app/keys.ts";
1618 import type { Ctx, Screen } from "../app/app.ts";
@@ -20,6 +22,7 @@ import { getRun } from "../../core/runs.ts";
2022 import { openedSaved, removeSaved, SAVE_WORDS, saveSearch, savedWords, NAME_MAX, type OpenedSearch } from "../../trace/saved.ts";
2123 import { sameIssue } from "../../trace/compare.ts";
2224 import { traceScreen } from "./trace.ts";
25 import { importedSharedNow, sharedHref, shareImported, unshareImported } from "../../actions/trace_share.ts";
2326 import { Scroll, openOnWeb } from "./common.ts";
2427 import { style } from "../term/style.ts";
2528 import { truncate } from "../term/width.ts";
@@ -58,6 +61,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
5861 const made = saveSearch(f.app.db, f.user!.id, name, q.toString());
5962 ctx.toast(made.ok ? `saved “${made.value.name}”` : SAVE_WORDS[made.error], made.ok ? undefined : "attn");
6063 };
64 let confirmShare: string | undefined;
6165 let typing: "q" | "tool" | "file" | "from" | "to" | undefined;
6266 const read = (): void => {
6367 list = listTraces(f.app, f.user, filter());
@@ -81,7 +85,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
8185 };
8286 return {
8387 title: "Traces",
84 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["u", "e"], "tool used, file touched"), binding(["f", "t"], "from, to day"), binding(["b", "w", "x"], "open, save, remove a saved search"), binding(["y"], "import a session on the web"), binding(["c"], "clear filters"), binding(["esc"], "close")],
88 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["u", "e"], "tool used, file touched"), binding(["f", "t"], "from, to day"), binding(["b", "w", "x"], "open, save, remove a saved search"), binding(["y"], "import a session on the web"), binding(["s", "z"], "share an imported session, stop sharing"), binding(["c"], "clear filters"), binding(["esc"], "close")],
8589 render(area, s) {
8690 const c = ctx.theme.c;
8791 s.text(area.x, area.y, truncate(`${typing === undefined ? "/ to search" : typing === "q" ? "Search" : typing === "from" ? "From (YYYY-MM-DD)" : typing === "to" ? "To (YYYY-MM-DD)" : typing === "tool" ? "Tool (Edit, Bash…)" : "File (path)"}: ${typing === undefined || typing === "q" ? (facet.q ?? "") : (facet[typing] ?? "")}${typing === undefined ? "" : "_"}${summary()}`, area.w), style(c.fg, c.bg), area.x + area.w);
@@ -157,7 +161,22 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
157161 else ctx.push(traceScreen(f, ctx, repo, ra.id, rb.id));
158162 }
159163 } else if (e.key === "y") openOnWeb(f, ctx, "/traces#traces-import", "the import form (a file input)");
160 else if (e.key === "c") {
164 else if (e.key === "s" || e.key === "z") {
165 const r = list.rows[at];
166 const live = r?.kind === "imported" ? importedSharedNow(f.app, f.user, r.id) : undefined;
167 if (r === undefined || live === undefined) ctx.toast("share is for an imported session of yours: move to one", "attn");
168 else if (e.key === "s" && live && confirmShare !== r.id) {
169 confirmShare = r.id;
170 ctx.toast("a share link is live: press s again to replace it, and end the old one", "attn");
171 } else {
172 confirmShare = undefined;
173 const done = e.key === "s" ? shareImported(f.app, f.user, r.id) : unshareImported(f.app, f.user, r.id);
174 if (!done.ok) ctx.toast("that could not be done", "danger");
175 else if ("token" in done.value) openOnWeb(f, ctx, sharedHref(done.value.token), "the share link (shown once)");
176 else ctx.toast(done.value.was ? "sharing stopped: the link no longer works" : "this session was not shared", "success");
177 }
178 if (e.key === "z") confirmShare = undefined;
179 } else if (e.key === "c") {
161180 for (const k of Object.keys(facet)) delete facet[k as keyof typeof facet];
162181 before = undefined;
163182 read();
src/web/pages/trace_imported.ts +6
@@ -4,6 +4,7 @@
44 * not-found an unknown id gets, `seenTraceRow`). The file holds no cost and often no tokens; the
55 * page says so rather than showing zero. Raw lines load per step, as on a run's page.
66 */
7 import { importedSharedNow } from "../../actions/trace_share.ts";
78 import type { Ctx } from "../../http/context.ts";
89 import { securityFloor } from "../../http/respond.ts";
910 import { importedLines } from "../../trace/import.ts";
@@ -35,6 +36,7 @@ export function importedTracePage(ctx: Ctx, row: TraceRow): Response {
3536 const base = `/traces/${row.id}`;
3637 const timed = read.timed;
3738 const failed = steps.filter((s) => s.outcome === "error").length;
39 const shared = importedSharedNow(ctx.app, ctx.auth.user, row.id);
3840 const tokens = row.tokensIn + row.tokensCached + row.tokensOut;
3941 const content = html`${pageHead(html`Trace: ${row.title}`, { sub: `An imported ${read.trace.source} session, step by step. Only you can read it.` })}
4042 <dl class="row-facts" id="trace-total">
@@ -45,6 +47,10 @@ export function importedTracePage(ctx: Ctx, row: TraceRow): Response {
4547 <div><dt>Cost</dt><dd id="trace-cost">${row.costUsd > 0 ? `$${row.costUsd.toFixed(2)}` : "not recorded in this file"}</dd></div>
4648 </dl>
4749 <nav class="bar small" id="trace-links" aria-label="Where this trace is"><a href="/traces">All traces</a></nav>
50 ${shared === undefined ? null : html`<form method="post" class="bar small" id="trace-share" action="${base}/${shared ? "unshare" : "share"}">
51 <span class="muted">${shared ? "A share link is live: anyone holding it reads this session, secrets redacted." : "Not shared. A link lets anyone who holds it read this session. The forge hides the credentials it knows, but a file can hold others, so share only what you have read."}</span>
52 <button type="submit">${shared ? "Stop sharing" : "Make a share link"}</button>
53 </form>`}
4854 ${read.truncated ? html`<p class="small muted" id="trace-cut">The session is longer than the page reads; only its first steps are shown.</p>` : null}
4955 ${total === 0 ? html`<p class="muted" id="trace-empty">This session holds no steps.</p>` : html`${strip(steps, timed)}
5056 <div class="trace-tree" id="trace-tree" data-base="${base}" role="group" aria-label="Steps">${treeRows(steps, base, timed)}</div>
src/web/pages/trace_share.ts +37 −15
@@ -5,7 +5,7 @@
55 * (`readShared`), as plain server-rendered steps with no script; a revoked or unknown link is the
66 * not-found a missing page gets. The terminal does the same (`src/tui/screens/trace.ts`).
77 */
8 import { sharedHref, shareRun, unshareRun } from "../../actions/trace_share.ts";
8 import { sharedHref, shareImported, shareRun, unshareImported, unshareRun } from "../../actions/trace_share.ts";
99 import type { Ctx } from "../../http/context.ts";
1010 import { spanWords, traceHref } from "../../trace/read.ts";
1111 import { readShared, sharedTurn } from "../../trace/shared.ts";
@@ -17,31 +17,53 @@ import { field } from "../ui.ts";
1717 import { clientAddress } from "../../http/peer.ts";
1818 import { tryAgain } from "../../http/respond.ts";
1919 import { repoOfRun } from "./trace.ts";
20 import { importedRowOf } from "./trace_imported.ts";
2021
2122 const noStore = (r: Response): Response => {
2223 r.headers.set("cache-control", "private, no-store");
2324 return r;
2425 };
2526
27 /**
28 * The link's page: its secret once, with the way back. `crumbs` only where a repository has them.
29 */
30 function linkPage(ctx: Ctx, token: string, what: string, back: string, crumbs?: ReturnType<typeof crumbsFor>): Response {
31 const url = `${ctx.app.config.url?.replace(/\/+$/, "") ?? ctx.url.origin}${sharedHref(token)}`;
32 return noStore(
33 page({
34 ctx,
35 title: "Share link",
36 ...(crumbs === undefined ? {} : { crumbs }),
37 body: html`${pageHead("Share link made", { sub: `Anyone holding it reads this ${what} with secrets redacted. It is shown once; making another ends this one.` })}
38 ${field({ name: "share-url", id: "share-url", label: "Share link", labelHidden: true, value: url, readonly: true, mono: true })}
39 <p><a href="${back}">Back to the ${what}</a>, where you can stop sharing.</p>`,
40 }),
41 );
42 }
43
44 /** An imported session's link: its importer's alone; anyone else is the not-found. */
45 function importedShare(ctx: Ctx): Response {
46 const row = importedRowOf(ctx);
47 const made = row === undefined ? undefined : shareImported(ctx.app, ctx.auth.user, row.id);
48 return row === undefined || made === undefined || !made.ok ? notFoundPage(ctx) : linkPage(ctx, made.value.token, "session", traceHref(row.id));
49 }
50
51 function importedUnshare(ctx: Ctx): Response {
52 const row = importedRowOf(ctx);
53 const ended = row === undefined ? undefined : unshareImported(ctx.app, ctx.auth.user, row.id);
54 if (row === undefined || ended === undefined || !ended.ok) return notFoundPage(ctx);
55 return flashTo(ctx, traceHref(row.id), { message: ended.value.was ? "Sharing stopped: the link no longer works." : "This session was not shared." });
56 }
57
2658 // POST /traces/:id/share
2759 export async function traceShare(ctx: Ctx): Promise<Response> {
2860 const form = await readForm(ctx, "rw");
2961 if (form instanceof Response) return form;
3062 const found = repoOfRun(ctx);
31 if (found === undefined) return notFoundPage(ctx);
63 if (found === undefined) return importedShare(ctx);
3264 const made = shareRun(ctx.app, ctx.auth.user, found.repo, found.id);
3365 if (!made.ok) return made.error === "forbidden" || made.error === "unauthorized" ? forbiddenPage(ctx, "Only the repository's owner makes a share link.") : notFoundPage(ctx);
34 const url = `${ctx.app.config.url?.replace(/\/+$/, "") ?? ctx.url.origin}${sharedHref(made.value.token)}`;
35 return noStore(
36 page({
37 ctx,
38 title: "Share link",
39 crumbs: crumbsFor(found.repo),
40 body: html`${pageHead("Share link made", { sub: "Anyone holding it reads this trace with secrets redacted. It is shown once; making another ends this one." })}
41 ${field({ name: "share-url", id: "share-url", label: "Share link", labelHidden: true, value: url, readonly: true, mono: true })}
42 <p><a href="${traceHref(found.id)}">Back to the trace</a>, where you can stop sharing.</p>`,
43 }),
44 );
66 return linkPage(ctx, made.value.token, "trace", traceHref(found.id), crumbsFor(found.repo));
4567 }
4668
4769 // POST /traces/:id/unshare
@@ -49,7 +71,7 @@ export async function traceUnshare(ctx: Ctx): Promise<Response> {
4971 const form = await readForm(ctx, "rw");
5072 if (form instanceof Response) return form;
5173 const found = repoOfRun(ctx);
52 if (found === undefined) return notFoundPage(ctx);
74 if (found === undefined) return importedUnshare(ctx);
5375 const ended = unshareRun(ctx.app, ctx.auth.user, found.repo, found.id);
5476 if (!ended.ok) return ended.error === "not_found" ? notFoundPage(ctx) : forbiddenPage(ctx, "Only the repository's owner ends a share link.");
5577 return flashTo(ctx, traceHref(found.id), { message: ended.value.was ? "Sharing stopped: the link no longer works." : "This trace was not shared." });
@@ -66,7 +88,7 @@ export async function traceShared(ctx: Ctx): Promise<Response> {
6688 page({
6789 ctx,
6890 title: `Trace · ${view.title}`,
69 body: html`${pageHead(html`Trace: ${view.title}`, { sub: "Shared read-only. Secrets are redacted." })}
91 body: html`${pageHead(html`Trace: ${view.title}`, { sub: view.state === "imported" ? "Shared read-only. The forge redacted the credentials it knows (shown as [redacted]); it cannot know every secret." : "Shared read-only. Secrets are redacted." })}
7092 <dl class="row-facts" id="shared-total">
7193 <div><dt>Steps</dt><dd>${String(view.steps.length)}</dd></div>
7294 <div><dt>Failed</dt><dd>${String(view.steps.filter((s) => s.failed).length)}</dd></div>
test/trace-imported-share.test.ts added +117
@@ -0,0 +1,117 @@
1 /** An imported session shared by a secret link that redacts, and ends (#18377). */

Add tests for the terminal s/z keys, for withoutWho on nested keys and non-JSON lines, and one request-level check of the 60-a-minute limit.

2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { sharedHref, shareImported } from "../src/actions/trace_share.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { createUser, type User } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { sharedTurn } from "../src/trace/shared.ts";
12 import { seedAdmin } from "./helpers/admin.ts";
13
14 const PLANTED = "ghp_0123456789abcdefghijABCDEFGHIJ0123";
15 const rec = (o: object): string => JSON.stringify({ sessionId: "sess-s", cwd: "/home/alice/private", ...o });
16 const SESSION = [
17 rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "deploy it" } }),
18 rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: `curl -H "Authorization: token ${PLANTED}" https://example.com` } }] } }),
19 rec({ type: "user", timestamp: "2026-12-01T09:00:04Z", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] } }),
20 ].join("\n");
21
22 let dir = "";
23 let app: App, servers: Servers;
24 let alice = "", bob = "", id = "";
25 let bobUser: User;
26
27 const call = (path: string, token: string | undefined, method = "GET") =>
28 fetch(`${servers.url}${path}`, { method, redirect: "manual", headers: token === undefined ? {} : { authorization: `Bearer ${token}` } });
29 const linkOf = async (res: Response): Promise<string> => /\/traces\/shared\/[A-Za-z0-9_-]{43}/.exec(await res.text())![0];
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-trace-imported-share-"));
33 app = createApp({ dataDir: dir, port: 0 });
34 servers = await serve(app);
35 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
36 if (!a.ok) throw new Error(a.error);
37 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
38 if (!b.ok) throw new Error(b.error);
39 bobUser = b.value;
40 alice = createToken(app.db, a.value.id, "t", "rw").token;
41 bob = createToken(app.db, b.value.id, "t", "rw").token;
42 const sent = await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${alice}` }, body: SESSION });
43 id = ((await sent.json()) as { id: string }).id;
44 }, 30_000);
45
46 afterAll(async () => {
47 servers.stop();
48 app.close();
49 await rm(dir, { recursive: true, force: true });
50 });
51
52 test("the importer makes a link; a secret in a line is [redacted] on the shared page and no person or path shows", async () => {
53 const page = await (await call(`/traces/${id}`, alice)).text();
54 expect(page).toContain("Make a share link");
55 const made = await call(`/traces/${id}/share`, alice, "POST");
56 expect(made.status).toBe(200);
57 const link = await linkOf(made);
58 const open = await call(link, undefined);
59 expect(open.status).toBe(200);
60 const text = await open.text();
61 expect(text).toContain("deploy it");
62 expect(text).toContain("[redacted]");
63 expect(text).not.toContain(PLANTED);
64 expect(text).not.toContain("alice");
65 expect(text).not.toContain("/home/");
66 expect(open.headers.get("cache-control")).toBe("private, no-store");
67 // Only the hash is kept.
68 const rows = app.db.query<{ token_hash: string }, [string]>("SELECT token_hash FROM trace_share WHERE run_id = ?1").all(id);
69 expect(rows).toHaveLength(1);
70 expect(link).not.toContain(rows[0]!.token_hash);
71 expect(await (await call(`/traces/${id}`, alice)).text()).toContain("Stop sharing");
72 });
73
74 test("another person cannot make or end the link, and a signed-out post is refused", async () => {
75 expect((await call(`/traces/${id}/share`, bob, "POST")).status).toBe(404);
76 expect((await call(`/traces/${id}/unshare`, bob, "POST")).status).toBe(404);
77 expect((await call(`/traces/${id}/share`, undefined, "POST")).status).not.toBe(200);
78 expect(shareImported(app, undefined, id).ok).toBe(false);
79 expect(shareImported(app, bobUser, id).ok).toBe(false);
80 });
81
82 test("a cross-site post cannot make the link", async () => {
83 const res = await fetch(`${servers.url}/traces/${id}/share`, { method: "POST", redirect: "manual", headers: { authorization: `Bearer ${alice}`, origin: "https://evil.example" } });
84 expect(res.status).toBe(403);
85 });
86
87 test("a new link ends the old one; stopping ends the link at the next request", async () => {
88 const first = await linkOf(await call(`/traces/${id}/share`, alice, "POST"));
89 const second = await linkOf(await call(`/traces/${id}/share`, alice, "POST"));
90 expect((await call(first, undefined)).status).toBe(404);
91 expect((await call(second, undefined)).status).toBe(200);
92 const stopped = await call(`/traces/${id}/unshare`, alice, "POST");
93 expect(stopped.status).toBeLessThan(400);
94 expect((await call(second, undefined)).status).toBe(404);
95 });
96
97 test("a deleted session's link is the not-found, and a link never made is too", async () => {
98 const link = await linkOf(await call(`/traces/${id}/share`, alice, "POST"));
99 expect((await call(link, undefined)).status).toBe(200);
100 app.db.query("DELETE FROM trace_index WHERE id = ?1").run(id);
101 expect((await call(link, undefined)).status).toBe(404);
102 expect((await call(sharedHref("a".repeat(43)), undefined)).status).toBe(404);
103 });
104
105 test("one address opens at most 60 shared pages a minute", () => {
106 let refused = 0;
107 for (let i = 0; i < 70; i++) if (!sharedTurn(app, "203.0.113.77").allowed) refused++;
108 expect(refused).toBe(10);
109 });
110
111 test("the 61st open of shared pages from one address is a 429 through the route", async () => {
112 const link = sharedHref("b".repeat(43));
113 const statuses: number[] = [];
114 for (let i = 0; i < 62; i++) statuses.push((await fetch(`${servers.url}${link}`)).status);
115 expect(statuses.filter((s) => s === 429).length).toBeGreaterThan(0);
116 expect(statuses.indexOf(429)).toBeLessThanOrEqual(60);
117 });
test/trace-who.test.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * What a shared session drops of who and where (#18377): the record's own level, nothing of a
3 * tool's input.
4 */
5 import { expect, test } from "bun:test";
6 import { withoutWho } from "../src/trace/who.ts";
7
8 const back = (o: object): unknown => JSON.parse(withoutWho(JSON.stringify(o)));
9
10 test("top-level, payload and message.metadata who-keys go; the rest stays", () => {
11 expect(back({ type: "x", cwd: "/home/a", gitBranch: "m", userEmail: "[email protected]", n: 1 })).toEqual({ type: "x", n: 1 });
12 expect(back({ type: "session_meta", payload: { id: "s", cwd: "/home/a", git: { repository_url: "https://h/r" }, originator: "cli", keep: [1] } })).toEqual({ type: "session_meta", payload: { id: "s", keep: [1] } });
13 expect(back({ message: { role: "user", metadata: { email: "[email protected]", user: "al", model: "m" }, content: "hi" } })).toEqual({ message: { role: "user", metadata: { model: "m" }, content: "hi" } });
14 });
15
16 test("a tool's input keeps its own user, host and git keys", () => {
17 const rec = { cwd: "/w", message: { content: [{ type: "tool_use", input: { user: "deploy", host: "db1", git: "status", list: [{ email: "[email protected]" }] } }] } };
18 expect(back(rec)).toEqual({ message: rec.message });
19 });
20
21 test("a line that is not a JSON object is kept as it is", () => {
22 expect(withoutWho("not json cwd")).toBe("not json cwd");
23 expect(withoutWho("[1,2]")).toBe("[1,2]");
24 expect(withoutWho("\"cwd\"")).toBe("\"cwd\"");
25 });
test/traces-share-tui.test.ts added +82
@@ -0,0 +1,82 @@
1 /** `s` and `z` in the Traces screen share and unshare an imported session (#18377). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createUser, type User } from "../src/core/users.ts";
8 import { isShared } from "../src/trace/share.ts";
9 import { importSession } from "../src/trace/import.ts";
10 import { createForgeApp } from "../src/tui/forge.ts";
11 import { headlessTerminal } from "../src/tui/term/terminal.ts";
12 import { entry } from "../src/tui/screens/traces.ts";
13 import { seedAdmin } from "./helpers/admin.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15 import { settleApp } from "./helpers/tui.ts";
16
17 quietLogs();
18
19 const rec = (o: object): string => JSON.stringify({ sessionId: "sess-t", cwd: "/w", ...o });
20 const SESSION = [
21 rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "ship it" } }),
22 rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Done" }] } }),
23 ].join("\n");
24
25 let dir = "";
26 let app: App;
27 let alice: User, bob: User;
28 let id = "";
29
30 async function screenOf(user: User) {
31 const { app: tui, session } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", user }, { terminal: headlessTerminal(140, 30), exitHooks: false });
32 tui.start();
33 await settleApp(tui);
34 entry.run(session, tui.ctx);
35 await settleApp(tui);
36 return async (key: string): Promise<string> => {
37 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
38 await settleApp(tui);
39 return tui.screen.toText();
40 };
41 }
42
43 beforeAll(async () => {
44 dir = await mkdtemp(join(tmpdir(), "forge-traces-share-tui-"));
45 app = createApp({ dataDir: dir, port: 0 });
46 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
47 if (!a.ok) throw new Error(a.error);
48 alice = a.value;
49 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
50 if (!b.ok) throw new Error("bob");
51 bob = b.value;
52 const made = await importSession(app.db, dir, alice.id, new TextEncoder().encode(SESSION));
53 if (!made.ok) throw new Error(made.reason);
54 id = made.row.id;
55 }, 30_000);
56
57 afterAll(async () => {
58 app.close();
59 await rm(dir, { recursive: true, force: true });
60 });
61
62 test("s makes the link, a second s confirms before replacing it, z ends it", async () => {
63 const press = await screenOf(alice);
64 const first = await press("s");
65 expect(first).toMatch(/\/traces\/shared\/[A-Za-z0-9_-]{43}/);
66 expect(isShared(app.db, id)).toBe(true);
67 const old = app.db.query<{ token_hash: string }, [string]>("SELECT token_hash FROM trace_share WHERE run_id = ?1 AND revoked_at IS NULL").get(id)!.token_hash;
68 expect(await press("s")).toContain("press s again");
69 expect(app.db.query<{ token_hash: string }, [string]>("SELECT token_hash FROM trace_share WHERE run_id = ?1 AND revoked_at IS NULL").get(id)!.token_hash).toBe(old);
70 await press("s");
71 expect(app.db.query<{ token_hash: string }, [string]>("SELECT token_hash FROM trace_share WHERE run_id = ?1 AND revoked_at IS NULL").get(id)!.token_hash).not.toBe(old);
72 expect(await press("z")).toContain("sharing stopped");
73 expect(isShared(app.db, id)).toBe(false);
74 expect(await press("z")).toContain("this session was not shared");
75 });
76
77 test("someone who did not import the session is told it is not theirs to share", async () => {
78 const press = await screenOf(bob);
79 expect(await press("s")).toContain("share is for an imported session of yours");
80 expect(await press("z")).toContain("share is for an imported session of yours");
81 expect(isShared(app.db, id)).toBe(false);
82 });

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

Keyboard shortcuts

Docs