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 #16766

Merged opened this

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

Merged

scout/forge:scout/11925-a-subscriber-gives-a-friend-a-forge-in-o → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/11925-a-subscriber-gives-a-friend-a-forge-in-o was merged into main as 94c2cbe.

Review

Sign in to review this change.
12 files changed +404 −17
docs/features/gifts.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Gifts
4 ---
5 # Gifts
6
7 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>`.
8
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.
11 - **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.
12 - **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.
13 - **Audit:** a `billing.gift.give` event per gift.
src/actions/gifts.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * A subscriber's gift (#11925): a person on a paid plan gives a friend a forge with one link. The
3 * link is a one-use gift code (`billing/codes.ts`) whose `giver` is the subscriber, so the friend
4 * claims it through the same door as an admin's code (`spawn/door.ts`) and the forge is made on
5 * the gift plan with source `code:<id>`. Never an agent; anyone who is not a subscriber is told
6 * `not_subscriber`. The plain code is in the answer that makes it and nowhere else. Each gift is a
7 * `billing.gift.give` event.
8 */
9
10 import type { App } from "../app.ts";
11 import { giftCount, giftsBy, insertCode, type Listed } from "../billing/codes.ts";
12 import { getStored } from "../billing/store.ts";
13 import type { User } from "../core/users.ts";
14 import { err, ok, type Result } from "../kernel/result.ts";
15 import { limitValue } from "../settings/limits.ts";
16 import { FREE, getPlans, type Plan } from "../settings/plans.ts";
17 import { linkFor } from "./codes.ts";
18 import { listChildrenNow } from "./spawn.ts";
19
20 export type GiftError = "not_found" | "not_subscriber" | "gifts_off" | "none_left" | "no_plan";
21
22 export const GIFT_WORDS: Record<Exclude<GiftError, "not_found">, string> = {
23 not_subscriber: "Gifts are for people with a forge on a paid plan",
24 gifts_off: "This forge is not giving gifts now",
25 none_left: "You have given every gift you have",
26 no_plan: "This forge has no paid plan to give",
27 };
28
29 const DAY = 86_400_000;
30
31 /** The plan a gift gives: the cheapest paid plan. */
32 export const giftPlan = (app: App): Plan | undefined =>
33 getPlans(app.db).filter((p) => p.key !== FREE && p.priceUsd > 0).sort((a, b) => a.priceUsd - b.priceUsd)[0];
34
35 /**
36 * Whether `actor` has a forge of their own on a paid plan: bought or granted, never itself a gift.
37 */
38 export function isSubscriber(app: App, actor: User | undefined): boolean {
39 if (actor === undefined || actor.kind === "agent") return false;
40 return listChildrenNow(app).some((c) => {
41 if (c.ownerId !== actor.id) return false;
42 const e = getStored(app.db, c.name);
43 return e !== undefined && e.plan !== FREE && e.status === "active" && !e.source.startsWith("code:");
44 });
45 }
46
47 export interface GiftView {
48 readonly left: number;
49 readonly plan: string;
50 readonly gifts: readonly Listed[];
51 }
52
53 export function readGifts(app: App, actor: User | undefined): Result<GiftView, "not_found" | "not_subscriber"> {
54 if (actor === undefined || actor.kind === "agent") return err("not_found");
55 if (!isSubscriber(app, actor)) return err("not_subscriber");
56 const left = Math.max(0, limitValue(app.db, "gifts.per_subscriber") - giftCount(app.db, actor.id));
57 return ok({ left, plan: giftPlan(app)?.key ?? "", gifts: giftsBy(app.db, actor.id) });
58 }
59
60 /** A subscriber makes a gift link. */
61 export function giveGift(app: App, actor: User | undefined, origin: string, now = new Date()): Result<{ code: string; link: string; left: number }, GiftError> {
62 if (actor === undefined || actor.kind === "agent") return err("not_found");
63 if (!isSubscriber(app, actor)) return err("not_subscriber");
64 const cap = limitValue(app.db, "gifts.per_subscriber");
65 if (cap === 0) return err("gifts_off");
66 const made = giftCount(app.db, actor.id);
67 if (made >= cap) return err("none_left");
68 const plan = giftPlan(app);
69 if (plan === undefined) return err("no_plan");
70 const expiresAt = new Date(now.getTime() + limitValue(app.db, "gifts.link_days") * DAY).toISOString();
71 const { code, row } = insertCode(app.db, { plan: plan.key, note: "", uses: 1, expiresAt, madeBy: actor.id, giver: actor.id }, now);
72 app.bus.append({ kind: "billing.gift.give", actorId: actor.id, payload: { id: row.id, plan: plan.key } });
73 return ok({ code, link: linkFor(origin, code), left: cap - made - 1 });
74 }
src/billing/codes.ts +25 −10
@@ -41,6 +41,8 @@ export interface Code {
4141 readonly revokedAt?: string;
4242 readonly madeBy: string;
4343 readonly madeAt: string;
44 /** The subscriber who gave it as a gift (#11925); absent for an admin's code. */
45 readonly giver?: string;
4446 }
4547
4648 export interface Redeemed {
@@ -50,7 +52,7 @@ export interface Redeemed {
5052
5153 interface Row {
5254 id: string; plan: string; kind: CodeKind; note: string; uses: number; used: number; expires_at: string | null;
53 revoked_at: string | null; made_by: string; made_at: string;
55 revoked_at: string | null; made_by: string; made_at: string; giver_id: string | null;
5456 }
5557
5658 const fromRow = (r: Row): Code => ({
@@ -58,6 +60,7 @@ const fromRow = (r: Row): Code => ({
5860 ...(r.expires_at === null ? {} : { expiresAt: r.expires_at }),
5961 ...(r.revoked_at === null ? {} : { revokedAt: r.revoked_at }),
6062 madeBy: r.made_by, madeAt: r.made_at,
63 ...(r.giver_id === null ? {} : { giver: r.giver_id }),
6164 });
6265
6366 /** What a person typed, as the code it means: trimmed, lowercased, and of the code's shape, else undefined. */
@@ -81,6 +84,7 @@ export interface NewCode {
8184 uses: number;
8285 expiresAt?: string;
8386 madeBy: string;
87 giver?: string;
8488 }
8589
8690 /** Make a code: its row (hashed) and the plain code, which exists nowhere else. */
@@ -89,8 +93,8 @@ export function insertCode(db: Database, n: NewCode, now = new Date()): { code:
8993 const id = crypto.randomUUID().slice(0, 8);
9094 const at = now.toISOString();
9195 db.query(
92 "INSERT INTO gift_code (id, hash, plan, note, uses, expires_at, made_by, made_at, kind) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
93 ).run(id, hashCode(code), n.plan, n.note, n.uses, n.expiresAt ?? null, n.madeBy, at, n.kind ?? "plan");
96 "INSERT INTO gift_code (id, hash, plan, note, uses, expires_at, made_by, made_at, kind, giver_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
97 ).run(id, hashCode(code), n.plan, n.note, n.uses, n.expiresAt ?? null, n.madeBy, at, n.kind ?? "plan", n.giver ?? null);
9498 return { code, row: getCode(db, id)! };
9599 }
96100
@@ -168,13 +172,10 @@ export interface Listed extends Code {
168172 readonly redeemed: readonly Redeemed[];
169173 }
170174
171 /** Newest first, with who redeemed each. */
172 export function listCodes(db: Database, limit = 200): Listed[] {
173 const rows = db
174 .query<Row & { name: string | null }, [number]>(
175 "SELECT g.*, u.username AS name FROM gift_code g LEFT JOIN user u ON u.id = g.made_by ORDER BY g.made_at DESC, g.rowid DESC LIMIT ?1",
176 )
177 .all(limit);
175 const LISTED = "SELECT g.*, u.username AS name FROM gift_code g LEFT JOIN user u ON u.id = g.made_by";
176
177 /** The rows as `Listed`, each with who redeemed it. */
178 function listed(db: Database, rows: readonly (Row & { name: string | null })[]): Listed[] {
178179 const redeemed = db.query<{ code_id: string; forge: string; at: string }, []>("SELECT code_id, forge, at FROM gift_redeem ORDER BY id").all();
179180 return rows.map((r) => ({
180181 ...fromRow(r),
@@ -183,6 +184,11 @@ export function listCodes(db: Database, limit = 200): Listed[] {
183184 }));
184185 }
185186
187 /** Newest first, with who redeemed each. */
188 export function listCodes(db: Database, limit = 200): Listed[] {
189 return listed(db, db.query<Row & { name: string | null }, [number]>(`${LISTED} ORDER BY g.made_at DESC, g.rowid DESC LIMIT ?1`).all(limit));
190 }
191
186192 const WINDOW_MS = 10 * 60_000;
187193 /** Attempts one client may make in the window, redemption or look alike. */
188194 export const TRIES_PER_WINDOW = 10;
@@ -195,3 +201,12 @@ export function takeTry(db: Database, bucket: string, now = Date.now()): boolean
195201 db.query("INSERT INTO gift_try (bucket, at) VALUES (?1, ?2)").run(bucket, now);
196202 return true;
197203 }
204
205 /** The gifts a subscriber made, newest first, with the forges that took each. */
outdated

This filters the newest 1000 codes of everyone in memory, so a subscriber's gifts vanish from their list once admin codes push them out. Query by giver_id in SQL (the new index covers it) and add a test with over 1000 codes.

206 export function giftsBy(db: Database, giver: string): Listed[] {
207 return listed(db, db.query<Row & { name: string | null }, [string]>(`${LISTED} WHERE g.giver_id = ?1 ORDER BY g.made_at DESC, g.rowid DESC`).all(giver));
208 }
209
210 /** How many gifts a subscriber has made, spent or not (a revoked one still counts). */
211 export const giftCount = (db: Database, giver: string): number =>
212 db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM gift_code WHERE giver_id = ?1").get(giver)?.n ?? 0;
src/core/migration-pins/20261130110000-gift-giver.pin added +1
@@ -0,0 +1,1 @@
1 9e35481b921ff73d441d2e1f7d481592836626aca4302807a9273b58ac392547
src/core/migrations/20261130110000-gift-giver.ts added +6
@@ -0,0 +1,6 @@
1 // A subscriber's gift (#11925): a gift code made by a person on a paid plan, not by an admin.
2 // `giver` is that person; null for an admin's code. Additive.
3 export default `
4 ALTER TABLE gift_code ADD COLUMN giver_id TEXT REFERENCES user (id) ON DELETE SET NULL;
5 CREATE INDEX gift_code_giver ON gift_code (giver_id, made_at);
6 `;
src/http/mcp/tools/profile.ts +18 −4
@@ -1,5 +1,7 @@
11 import { scopeAllows } from "../../../core/tokens.ts";
22 import { emailVerified } from "../../../core/verify.ts";
3 import { GIFT_WORDS, giveGift, readGifts } from "../../../actions/gifts.ts";
4 import { publicOrigin } from "../../../core/public_origin.ts";
35 import { updateProfile } from "../../../actions/users.ts";
46 import { publicUser } from "../../respond.ts";
57 import { exportAnswer } from "../export_answer.ts";
@@ -7,7 +9,7 @@ import { good, bad, type Tool } from "../shared.ts";
79
810 export const tool: Tool = {
911 name: "profile",
10 doc: "`{ displayName?, email?, commitEmail?, action? }`: your own profile (`publicUser` and `emailVerified`, never the address); with an argument it changes it by the rules of `PATCH /api/v1/user`, and needs admin scope: only a site admin can mint such a token, so most people sign in to `/mcp` with their password. `action: \"export\"` answers the document of `GET /api/v1/user/export` (a size summary and the link past 16,000 bytes, a bound this tool sets for itself: the MCP layer has none), for a person's account with an admin-scope token",
12 doc: "`{ displayName?, email?, commitEmail?, action? }`: your own profile (`publicUser` and `emailVerified`, never the address); with an argument it changes it by the rules of `PATCH /api/v1/user`, and needs admin scope: only a site admin can mint such a token, so most people sign in to `/mcp` with their password. `action: \"export\"` answers the document of `GET /api/v1/user/export` (a size summary and the link past 16,000 bytes, a bound this tool sets for itself: the MCP layer has none), for a person's account with an admin-scope token. `action: \"gift\"` (#11925), for a person on a paid plan, reads the gifts left and who took each; with `dryRun: false` and an admin-scope token it makes a one-use link to give a friend a forge, shown once",
1113 description: "Read or change your profile.",
1214 inputSchema: {
1315 type: "object",
@@ -15,14 +17,26 @@ export const tool: Tool = {
1517 displayName: { type: "string" },
1618 email: { type: "string" },
1719 commitEmail: { type: "string" },
18 action: { enum: ["export"] },
20 action: { enum: ["export", "gift"] },
21 dryRun: { type: "boolean" },
1922 },
2023 },
2124 writes: true,
2225 readsWithout: ["displayName", "email", "commitEmail"],
23 readsWhen: (args) => args["action"] === "export",
26 readsWhen: (args) => args["action"] === "export" || (args["action"] === "gift" && args["dryRun"] !== false),
2427 run(ctx, user, args) {
25 if (args["action"] !== undefined && args["action"] !== "export") return bad("invalid", "action is export");
28 if (args["action"] !== undefined && args["action"] !== "export" && args["action"] !== "gift") return bad("invalid", "action is export or gift");
29 if (args["action"] === "gift") {
30 const refuse = (e: string) => (e === "not_found" ? bad("not_found", "Not found.") : bad("invalid", GIFT_WORDS[e as keyof typeof GIFT_WORDS] ?? e));
31 if (args["dryRun"] !== false) {
32 const read = readGifts(ctx.app, user);
33 if (!read.ok) return refuse(read.error);
34 return good({ ...read.value, says: "Send dryRun: false to make a gift link; nothing was made." });
35 }
36 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "giving a gift needs an admin-scope token");
37 const made = giveGift(ctx.app, user, publicOrigin(ctx.app.config.url, ctx.url.origin));
38 return made.ok ? good({ ...made.value, says: "Shown once: the plain code is not kept." }) : refuse(made.error);
39 }
2640 if (args["action"] === "export") return exportAnswer(ctx, user);
2741 const { displayName, email, commitEmail } = args;
2842 if (displayName === undefined && email === undefined && commitEmail === undefined)
src/settings/limits.ts +18
@@ -49,6 +49,8 @@ export type LimitKey =
4949 | "guest.forks_forge_per_day"
5050 | "guest.pulls_per_day"
5151 | "forges.per_person"
52 | "gifts.per_subscriber"
53 | "gifts.link_days"
5254 | "forges.wakes_per_person_hour"
5355 | "forges.storage_mb"
5456 | "spawn.anon_per_day"
@@ -307,6 +309,22 @@ export const LIMITS: Record<LimitKey, LimitDef> = {
307309 max: 10_000,
308310 reason: "A stranger's visits can wake a sleeping forge again and again; one forge is woken this often at most. FORGE_CHILD_WAKES_PER_HOUR is read only while this is not set.",
309311 },
312 "gifts.per_subscriber": {
313 label: "Gifts a subscriber may give",
314 unit: "gifts",
315 default: 3,
316 min: 0,
317 max: 100,
318 reason: "A person on a paid plan can give a friend a forge on the gift plan with one link; each link works once. 0 turns gifts off.",
319 },
320 "gifts.link_days": {
321 label: "Days a gift link stays good",
322 unit: "days",
323 default: 30,
324 min: 1,
325 max: 365,
326 reason: "A gift link that no one opens stops working after this many days, so an old link in a chat cannot be used by a stranger later.",
327 },
310328 "forges.per_person": {
311329 label: "Hosted forges one person may own",
312330 unit: "forges",
src/tui/screens/gifts.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * A subscriber's gifts in the terminal (#11925): the same `readGifts` and `giveGift` the MCP tool
3 * uses. `n` makes a one-use link and shows the plain code once; the list says who took each gift.
4 * Offered to a person with a paid forge of their own.
5 */
6
7 import { giveGift, GIFT_WORDS, isSubscriber, readGifts } from "../../actions/gifts.ts";
8 import { publicOrigin } from "../../core/public_origin.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import { binding } from "../app/keys.ts";
11 import { fill, len, split } from "../ui/layout.ts";
12 import { style } from "../term/style.ts";
13 import { truncate } from "../term/width.ts";
14 import type { Session } from "../session.ts";
15 import { ListState, drawList, type ListRow } from "./common.ts";
16 import type { PaletteEntry } from "./entries.ts";
17
18 export function giftRows(f: Session): { rows: ListRow[]; left: number } {
19 const read = readGifts(f.app, f.user);
20 if (!read.ok) return { rows: [], left: 0 };
21 const rows = read.value.gifts.map((g) => ({
22 title: `${g.plan} · made ${g.madeAt.slice(0, 10)}`,
23 secondary: g.revokedAt !== undefined ? "revoked" : g.used >= g.uses ? "taken" : "waiting",
24 meta: g.redeemed.map((r) => r.forge).join(", "),
25 }));
26 return { rows, left: read.value.left };
27 }
28
29 export function giftsScreen(f: Session, ctx: Ctx): Screen {
30 const state = new ListState();
31 let note = "";
32 return {
33 title: "Gifts",
34 keys: [binding(["j", "k"], "move cursor"), binding(["n"], "make a gift link"), binding(["esc"], "back")],
35 render(area, s) {
36 const c = ctx.theme.c;
37 const { rows, left } = giftRows(f);
38 state.clamp(rows.length);
39 const [head, body] = split(area, "v", [len(2), fill(1)]);
40 s.text(head!.x, head!.y, truncate(note !== "" ? note : `${left} gifts left: n makes a one-use link for a friend's forge`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
41 if (rows.length === 0) s.text(body!.x, body!.y, truncate("No gift yet.", body!.w), style(c.mutedFg, c.bg), body!.x + body!.w);
42 else drawList(s, body!, c, state, rows);
43 },
44 key(e) {
45 if (e.key === "n") {
46 const made = giveGift(f.app, f.user, publicOrigin(f.app.config.url, `http://localhost:${f.app.config.port}`));
47 note = made.ok ? `Shown once: ${made.value.code} ${made.value.link}` : made.error === "not_found" ? "Not found." : `${GIFT_WORDS[made.error]}.`;
48 ctx.invalidate();
49 return true;
50 }
51 return state.key(e, giftRows(f).rows.length);
52 },
53 };
54 }
55
56 /** Give a friend a forge, and see who came. */
57 export const entry: PaletteEntry = {
58 rank: 595,
59 id: "gifts",
60 title: "Gifts",
61 hint: "give a friend a forge with one link, and see who came",
62 offered: (f) => f.user !== undefined && isSubscriber(f.app, f.user),
63 run: (session, ctx) => ctx.push(giftsScreen(session, ctx)),
64 };
test/gifts-tui.test.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * A subscriber's gifts in the terminal (#11925): offered to a subscriber only; `n` makes a link
3 * shown once.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, mkdir, rm, writeFile } 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 { putEntitlement } from "../src/billing/store.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { entry, giftsScreen } from "../src/tui/screens/gifts.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let sub: User;
23 let plain: User;
24
25 beforeAll(async () => {
26 dir = await mkdtemp(join(tmpdir(), "forge-gifts-tui-"));
27 app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge-code" });
28 await mkdir(join(dir, "spawn"), { recursive: true });
29 const mk = async (username: string): Promise<User> => {
30 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase" });
31 if (!u.ok) throw new Error("user");
32 return u.value;
33 };
34 sub = await mk("sub");
35 plain = await mk("plain");
36 await writeFile(join(dir, "spawn", "subforge.json"), JSON.stringify({ name: "subforge", bodyId: "b", done: true, ownerId: sub.id, createdAt: new Date().toISOString() }));
37 putEntitlement(app.db, { forge: "subforge", plan: "small", status: "active", source: "stripe", provider: "stripe" }, "small", "");
38 });
39 afterAll(async () => {
40 app.close();
41 await rm(dir, { recursive: true, force: true });
42 });
43
44 const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false });
45 function open(user: User) {
46 const { app: tui, session } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, { terminal: headlessTerminal(140, 40), exitHooks: false });
47 tui.start();
48 return { tui, session };
49 }
50
51 test("the entry is offered to a subscriber only", () => {
52 expect(entry.offered(open(sub).session)).toBe(true);
53 expect(entry.offered(open(plain).session)).toBe(false);
54 });
55
56 test("a subscriber makes a gift link and sees it listed as waiting", async () => {
57 const { tui, session } = open(sub);
58 tui.ctx.push(giftsScreen(session, tui.ctx));
59 await settleApp(tui);
60 expect(tui.screen.toText()).toContain("No gift yet.");
61 tui.dispatch(key("n"));
62 await settleApp(tui);
63 expect(tui.screen.toText()).toMatch(/forge-[a-z0-9]{4}-[a-z0-9]{4}/);
64 expect(tui.screen.toText()).toContain("waiting");
65 tui.stop?.();
66 });
test/gifts.test.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * A subscriber's gift (#11925): only a person with a paid forge makes one, up to the setting; the
3 * link is claimed once through the same code door; the giver sees who took it.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, mkdir, rm, writeFile } 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 { giveGift, isSubscriber, readGifts } from "../src/actions/gifts.ts";
11 import { claimCode, noteRedeemed } from "../src/billing/codes.ts";
12 import { putEntitlement } from "../src/billing/store.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { setLimit } from "../src/settings/limits.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 describe("a subscriber's gift", () => {
20 let dataDir: string;
21 let app: App;
22 let sub: User;
23 let free: User;
24 const ORIGIN = "https://forge.test";
25
26 const ledger = (name: string, ownerId: string) =>
27 writeFile(join(dataDir, "spawn", `${name}.json`), JSON.stringify({ name, bodyId: `b-${name}`, done: true, ownerId, createdAt: new Date().toISOString() }));
28
29 beforeAll(async () => {
30 dataDir = await mkdtemp(join(tmpdir(), "gifts-"));
31 app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge-code" });
32 await mkdir(join(dataDir, "spawn"), { recursive: true });
33 const person = async (username: string): Promise<User> => {
34 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase" });
35 if (!u.ok) throw new Error("user");
36 return u.value;
37 };
38 sub = await person("sub");
39 free = await person("plain");
40 await ledger("subforge", sub.id);
41 await ledger("plainforge", free.id);
42 putEntitlement(app.db, { forge: "subforge", plan: "small", status: "active", source: "stripe", provider: "stripe" }, "small", "");
43 });
44 afterAll(async () => {
45 app.close();
46 await rm(dataDir, { recursive: true, force: true });
47 });
48
49 test("a person without a paid forge is refused; an agent is not found", () => {
50 expect(isSubscriber(app, free)).toBe(false);
51 const r = giveGift(app, free, ORIGIN);
52 expect(r.ok ? "" : r.error).toBe("not_subscriber");
53 const a = giveGift(app, { ...sub, kind: "agent" } as User, ORIGIN);
54 expect(a.ok ? "" : a.error).toBe("not_found");
55 expect(giveGift(app, undefined, ORIGIN).ok).toBe(false);
56 });
57
58 test("a subscriber makes a one-use link, claimed once, and sees who came", () => {
59 expect(isSubscriber(app, sub)).toBe(true);
60 const made = giveGift(app, sub, ORIGIN);
61 if (!made.ok) throw new Error(made.error);
62 expect(made.value.link.startsWith(`${ORIGIN}/?code=forge-`)).toBe(true);
63 expect(made.value.left).toBe(2);
64 const claimed = claimCode(app.db, made.value.code);
65 expect(claimed.ok).toBe(true);
66 if (claimed.ok) noteRedeemed(app.db, claimed.value.id, "friendforge");
67 const second = claimCode(app.db, made.value.code);
68 expect(second.ok ? "" : second.error).toBe("used_up");
69 const view = readGifts(app, sub);
70 if (!view.ok) throw new Error(view.error);
71 expect(view.value.gifts.length).toBe(1);
72 expect(view.value.gifts[0]!.redeemed.map((r) => r.forge)).toEqual(["friendforge"]);
73 expect(view.value.left).toBe(2);
74 });
75
76 test("a gift forge cannot give gifts; the setting caps them; 0 turns them off", () => {
77 putEntitlement(app.db, { forge: "plainforge", plan: "small", status: "active", source: "code:abc", provider: "none" }, "small", "");
78 expect(isSubscriber(app, free)).toBe(false);
79 expect(giveGift(app, sub, ORIGIN).ok).toBe(true);
80 expect(giveGift(app, sub, ORIGIN).ok).toBe(true);
81 const out = giveGift(app, sub, ORIGIN);
82 expect(out.ok ? "" : out.error).toBe("none_left");
83 setLimit(app.db, "gifts.per_subscriber", 0, sub.id);
84 const off = giveGift(app, sub, ORIGIN);
85 expect(off.ok ? "" : off.error).toBe("gifts_off");
86 });
87
88 test("a link stops working after its days", () => {
89 setLimit(app.db, "gifts.per_subscriber", 10, sub.id);
90 const made = giveGift(app, sub, ORIGIN, new Date(Date.now() - 40 * 86_400_000));
91 if (!made.ok) throw new Error(made.error);
92 const r = claimCode(app.db, made.value.code);
93 expect(r.ok ? "" : r.error).toBe("expired");
94 });
95 });
96
97 describe("the giver's list", () => {
98 test("a gift stays listed behind more than a thousand admin codes", async () => {
99 const dataDir = await mkdtemp(join(tmpdir(), "gifts-many-"));
100 const app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge-code" });
101 await mkdir(join(dataDir, "spawn"), { recursive: true });
102 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "giver", email: "[email protected]", password: "a-good-passphrase" });
103 if (!u.ok) throw new Error("user");
104 await writeFile(join(dataDir, "spawn", "gforge.json"), JSON.stringify({ name: "gforge", bodyId: "b", done: true, ownerId: u.value.id, createdAt: new Date().toISOString() }));
105 putEntitlement(app.db, { forge: "gforge", plan: "small", status: "active", source: "stripe", provider: "stripe" }, "small", "");
106 const made = giveGift(app, u.value, "https://forge.test", new Date(Date.now() - 86_400_000));
107 if (!made.ok) throw new Error(made.error);
108 app.db
109 .query("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1100) INSERT INTO gift_code (id, hash, plan, uses, made_by, made_at) SELECT 'x' || i, 'h' || i, 'small', 1, ?1, ?2 FROM n")
110 .run(u.value.id, new Date().toISOString());
111 const view = readGifts(app, u.value);
112 if (!view.ok) throw new Error(view.error);
113 expect(view.value.gifts.length).toBe(1);
114 app.close();
115 await rm(dataDir, { recursive: true, force: true });
116 });
117 });
test/llms-budget.test.ts +2 −2
@@ -59,9 +59,9 @@ const get = async (token?: string): Promise<string> =>
5959 * add about 40 to 330 bytes to it. Only an agent with an admin token reads this text, and few do,
6060 * so the cost of the room is small. Raised to 98,500 for cut_wave (admin 98,345), then to 98,700
6161 * for the allocation tool (#8718; admin 98,516), then to 99,200 for the app_flags tool (#1830;
62 * admin 98,939).
62 * admin 98,939). Raised to 100,700 for the profile tool's `gift` action (admin 99,756).
6363 */
64 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 99_200 } as const;
64 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 100_700 } as const;
6565
6666 test("/llms.txt stays under its byte budget for each role", async () => {
6767 const sizes = {
test/refusals-lead-somewhere.test.ts −1
@@ -36,7 +36,6 @@ const TERMINAL: Readonly<Record<string, string>> = {
3636 "src/web/pages/origin-reach.ts\tAsk the host again to allow ${a.host}": "The label of the ask itself, on the button the helper draws.",
3737 "src/web/pages/passkeys.ts\tThis link has been used or has expired.": "The reader is signed out and locked out: the link came from an admin outside the forge, and there is no account to ask as.",
3838 "src/actions/account_access.ts\tThat link has been used or has expired.": "The same link, for the API and the terminal: no account to ask as.",
39 "src/http/mcp/tools/profile.ts\t`{ displayName?, email?, commitEmail?, action? }`: your own": "A tool's description of what its scope is, not a refusal.",
4039 "src/http/api.ts\tthe origin refused: this connection cannot write": "The owner is of a repository on another host; the way through it names is the reader's own (connect again with a token that can write).",
4140 "src/http/respond.ts\tUse a token or account with the scope or role": "The hint on every 403, which does not know what was refused; a refusal with something to ask for carries `ask` itself.",
4241 "src/http/respond.ts\tYour token's scope or your role on this resource": "The same hint, by code.",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs