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

A subscriber gives a friend a forge in one tap, and sees who came — restarted from the parked branch, in two small pulls #16812

Merged opened this

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

Merged

mason/forge:mason/11925-a-subscriber-gives-a-friend-a-forge-in-o → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/11925-a-subscriber-gives-a-friend-a-forge-in-o was merged into main as 8418b63.

Review

Sign in to review this change.
6 files changed +168 −3
docs/features/gifts.md +2 −2
@@ -6,8 +6,8 @@ row: Gifts
66
77 A person with a forge of their own on a paid plan gives a friend a forge with one link (#11925; `src/actions/gifts.ts`). The link is a one-use gift code whose giver is the subscriber, claimed through the same door as an admin's code (`docs/features/billing.md`, Gift codes): the friend's forge is made on the cheapest paid plan, source `code:<id>`.
88
9 - **Make:** the terminal's *Gifts* screen (`src/tui/screens/gifts.ts`; `n` makes a link, shown once with its code, since only a hash is kept), or the MCP `profile` tool's `gift` action. The web page waits for the second pull.
10 - **See who came:** the same list says each gift is waiting, taken or revoked, and names the forge that took it.
9 - **Make:** the terminal's *Gifts* screen (`src/tui/screens/gifts.ts`; `n` makes a link, shown once with its code, since only a hash is kept), the MCP `profile` tool's `gift` action, or the web: on Settings (`/settings`) a person with a paid forge sees *Give a friend a forge*, whose *Make a gift link* button posts `/settings/gifts` and answers with the link, shown once (`src/web/pages/gifts.ts`).
10 - **See who came:** the list under the button (and the terminal's and MCP's) says each gift is waiting, taken or revoked, and names the forge that took it.
1111 - **Limits:** the `gifts.per_subscriber` setting caps gifts per person (0 turns them off), `gifts.link_days` says how long a link works. A revoked gift still counts against the cap. A forge that is itself a gift cannot give gifts; agents never can.
1212 - **When the giver's account is removed:** the gift codes stay and still work, but no longer name a giver, so their count and list are gone with the account.
1313 - **Audit:** a `billing.gift.give` event per gift.
src/http/marks/settings.json +1
@@ -39,6 +39,7 @@
3939 "/settings/grants/:id/revoke": "open",
4040 "/settings/sessions/end-others": "open",
4141 "/settings/sessions/:id/delete": "open",
42 "/settings/gifts": "open",
4243 "/settings/confirms": "open",
4344 "/settings/confirms/:id": "open",
4445 "/settings/passkeys": "open",
src/http/settings_routes.ts +2
@@ -43,6 +43,7 @@ import {
4343 personSignInsPage,
4444 signInAct,
4545 } from "../web/pages/accounts.ts";
46 import { giftMake } from "../web/pages/gifts.ts";
4647 import { confirmsList, confirmYes } from "../web/pages/confirms.ts";
4748 import { captainAct, captainPage } from "../web/pages/captain.ts";
4849 import { packsSettingsPage, packsSettingsSave } from "../web/pages/packs-settings.ts";
@@ -206,6 +207,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
206207 router.add("POST", "/settings/grants/:id/revoke", grantRevoke);
207208 router.add("POST", "/settings/sessions/end-others", sessionsOthersDelete);
208209 router.add("POST", "/settings/sessions/:id/delete", sessionDelete);
210 router.add("POST", "/settings/gifts", giftMake);
209211 router.add("GET", "/settings/confirms", confirmsList);
210212 router.add("POST", "/settings/confirms/:id", confirmYes);
211213 router.add("GET", "/settings/passkeys", passkeysPage);
src/web/pages/account.ts +2 −1
@@ -109,6 +109,7 @@ import {
109109 import { STOPPED_ONE, myShells, stopIdleShells, stopShell, stoppedIdleSays } from "../../machines/shell.ts";
110110 import { DOTFILES_ERRORS, dotfilesRepoOf, setDotfilesRepo } from "../../machines/dotfiles.ts";
111111 import { billsBlock } from "./bills.ts";
112 import { giftsBlock } from "./gifts.ts";
112113 import { everydayLine } from "./everyday.ts";
113114 import { madeFromOf } from "../../spawn/template_record.ts";
114115 import { madeFromHtml } from "../started_from.ts";
@@ -652,7 +653,7 @@ export function accountPage(ctx: Ctx): Response {
652653 ctx,
653654 "profile",
654655 "Settings",
655 html`${plan}${pair}${profile}${edge}${parent}${notify}${billsBlock(ctx.app, user)}${closingNotice(ctx)}`,
656 html`${plan}${pair}${profile}${edge}${parent}${notify}${giftsBlock(ctx)}${billsBlock(ctx.app, user)}${closingNotice(ctx)}`,
656657 200,
657658 // The everyday form makes its account with a passkey (#1890).
658659 pair ? passkeyJs : undefined,
src/web/pages/gifts.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * A subscriber's gifts on their own settings (#11925): one button makes a one-use link for a
3 * friend, shown once; under it one line per gift, a dot and its word (waiting, taken, revoked) and
4 * the forge that took it. The same `readGifts` and `giveGift` as the MCP and the terminal. Anyone
5 * who is not a subscriber sees no block, and the POST answers not found.
6 */
7
8 import { GIFT_WORDS, giveGift, readGifts } from "../../actions/gifts.ts";
9 import { publicOrigin } from "../../core/public_origin.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { notFoundPage, signInFirst } from "../chrome.ts";
12 import { readForm } from "../form.ts";
13 import { html, type Html } from "../html.ts";
14 import { btn, copyField, dot } from "../ui.ts";
15 import { accountShell } from "./account.ts";
16
17 /** A link just made: the plain code and link, shown once and never kept. */
18 interface Shown {
19 readonly code: string;
20 readonly link: string;
21 }
22
23 const day = (iso: string): string => iso.slice(0, 10);
24
25 /** The Gifts block of Settings: null for anyone who cannot give one. */
26 export function giftsBlock(ctx: Ctx, shown?: Shown, refusal?: string): Html | null {
27 const read = readGifts(ctx.app, ctx.auth.user);
28 if (!read.ok) return null;
29 const { left, gifts } = read.value;
30 const lines = gifts.map((g) => {
31 const state = g.revokedAt !== undefined ? "revoked" : g.used >= g.uses ? "taken" : "waiting";
32 const tone = state === "taken" ? "success" : state === "revoked" ? "danger" : "attn";
33 const who = g.redeemed.map((r) => r.forge).join(", ");
34 return html`<div class="status-row" data-gift="${g.id}"><dt>${dot(tone)} ${state}</dt><dd>${g.plan} · made ${day(g.madeAt)}${who === "" ? "" : html` · <span class="mono">${who}</span>`}</dd></div>`;
35 });
36 return html`<section class="settings-block" id="gifts" data-gifts>
37 <h2>Give a friend a forge</h2>
38 <p class="muted small">One link, one forge on the ${read.value.plan} plan, free for the friend. ${left} left to give.</p>
39 ${refusal === undefined ? null : html`<p class="notice danger" role="alert">${refusal}.</p>`}
40 ${shown === undefined
41 ? null
42 : html`<div class="stack stack-tight" id="new-gift" role="status">
43 <p class="small">Shown once. It is kept only as a hash; send the link. Do not reload this page: that would make another link.</p>
44 ${copyField("gift-link", shown.link, "The link to send", "Copy the link")}
45 </div>`}
46 <form method="post" action="/settings/gifts">${btn("Make a gift link", { variant: "primary" })}</form>
47 ${lines.length === 0 ? html`<p class="muted small">No gift yet.</p>` : html`<dl class="status-rows">${lines}</dl>`}
48 </section>`;
49 }
50
51 // POST /settings/gifts
52 export async function giftMake(ctx: Ctx): Promise<Response> {
53 if (!ctx.auth.user) return signInFirst(ctx);
54 const form = await readForm(ctx);
55 if (form instanceof Response) return form;
56 const made = giveGift(ctx.app, ctx.auth.user, publicOrigin(ctx.app.config.url, ctx.url.origin));
57 if (!made.ok && made.error === "not_found") return notFoundPage(ctx);
58 const refusal = made.ok || made.error === "not_found" ? undefined : GIFT_WORDS[made.error];
59 const body = giftsBlock(ctx, made.ok ? { code: made.value.code, link: made.value.link } : undefined, refusal);
outdated

Medium: a 200 page from a POST means reload re-posts and makes another link, burning the cap. Redirect after post, or guard against the repeat. Also drop the as Exclude cast by narrowing made.error.

60 if (body === null) return notFoundPage(ctx);
61 const response = accountShell(ctx, "profile", "Settings", body, made.ok ? 200 : 422);
62 // A link just made is in this body only: never kept by a cache.
63 response.headers.set("cache-control", "no-store");
64 return response;
65 }
test/gifts-page.test.ts added +96
@@ -0,0 +1,96 @@
1 /**
2 * A subscriber's gifts on Settings (#11925): the block shows only to a person with a paid forge,
3 * one tap makes a link shown once, and the list says who came.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { putEntitlement } from "../src/billing/store.ts";
11 import { insertCode, noteRedeemed, revokeCode } from "../src/billing/codes.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let root = "";
20 let app: App;
21 let servers: Servers;
22 let sub = "";
23 let subId = "";
24 let plain = "";
25
26 beforeAll(async () => {
27 root = mkdtempSync(join(tmpdir(), "forge-gifts-page-"));
28 app = createApp({ dataDir: root, port: 0 });
29 mkdirSync(join(root, "spawn"), { recursive: true });
30 const first = await createUser(app.db, { origin: "seed", username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
31 if (!first.ok) throw new Error(first.error);
32 const person = async (username: string) => {
33 const u = await createUser(app.db, { origin: "seed", username, email: `${username}@x.local`, password: "a-good-passphrase" });
34 if (!u.ok) throw new Error(u.error);
35 return `forge_session=${createSession(app.db, u.value.id).token}`;
36 };
37 const s = await createUser(app.db, { origin: "seed", username: "sub", email: "[email protected]", password: "a-good-passphrase" });
38 if (!s.ok) throw new Error(s.error);
39 subId = s.value.id;
40 sub = `forge_session=${createSession(app.db, s.value.id).token}`;
41 writeFileSync(join(root, "spawn", "subforge.json"), JSON.stringify({ name: "subforge", bodyId: "b-sub", done: true, ownerId: s.value.id, createdAt: new Date().toISOString() }));
42 putEntitlement(app.db, { forge: "subforge", plan: "small", status: "active", source: "stripe", provider: "stripe" }, "small", "");
43 plain = await person("plain");
44 servers = await serve(app);
45 });
46 afterAll(() => {
47 servers.stop();
48 app.close();
49 rmSync(root, { recursive: true, force: true });
50 });
51
52 const get = (cookie: string) => fetch(`${servers.url}/settings`, { headers: { cookie } }).then((r) => r.text());
53 const make = (cookie: string, origin = servers.url) => fetch(`${servers.url}/settings/gifts`, { method: "POST", headers: { cookie, origin }, body: new URLSearchParams() });
54
55 test("a person without a paid forge sees no block and cannot make a link", async () => {
56 expect(await get(plain)).not.toContain("data-gifts");
57 expect((await make(plain)).status).toBe(404);
58 });
59
60 test("one tap makes a link shown once; the settings then list it as waiting", async () => {
61 expect(await get(sub)).toContain("Make a gift link");
62 const res = await make(sub);
63 expect(res.status).toBe(200);
64 expect(res.headers.get("cache-control")).toBe("no-store");
65 const body = await res.text();
outdated

This regex matches 'gift' anywhere, so it passes without a link. Assert the link's real shape, and add tests for a taken gift (forge name listed) and a revoked one: 'who came' is the feature and has no test.

66 expect(body).toContain("new-gift");
67 expect(body).toContain("Do not reload this page");
68 expect(body).toMatch(/value="[^"]*\/\?code=[A-Za-z0-9_-]+/);
69 const after = await get(sub);
70 expect(after).not.toContain("new-gift");
71 expect(after).toContain('data-gift="');
72 expect(after).toContain("waiting");
73 });
74
75 test("a cross-site post makes nothing", async () => {
76 const before = await get(sub);
77 const res = await make(sub, "https://evil.example");
78 expect(res.status).toBe(403);
79 expect((await get(sub)).match(/data-gift="/g)?.length).toBe(before.match(/data-gift="/g)?.length);
80 });
81
82 test("the list says who came: a taken gift names the forge, a revoked one says so", async () => {
83 const taken = insertCode(app.db, { plan: "small", note: "", uses: 1, madeBy: subId, giver: subId });
84 app.db.query("UPDATE gift_code SET used = 1 WHERE id = ?1").run(taken.row.id);
85 noteRedeemed(app.db, taken.row.id, "friendforge");
86 const gone = insertCode(app.db, { plan: "small", note: "", uses: 1, madeBy: subId, giver: subId });
87 revokeCode(app.db, gone.row.id);
88 const page = await get(sub);
89 const row = (id: string) => page.match(new RegExp(`data-gift="${id}"[\\s\\S]*?</div>`))?.[0] ?? "";
90 expect(row(taken.row.id)).toContain("taken");
91 expect(row(taken.row.id)).toContain("friendforge");
92 expect(row(taken.row.id)).toContain("success");
93 expect(row(gone.row.id)).toContain("revoked");
94 expect(row(gone.row.id)).toContain("danger");
95 expect(row(gone.row.id)).not.toContain("friendforge");
96 });

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

Keyboard shortcuts

Docs