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

A subscriber gives a friend a forge in one tap, and sees who came #11791

opened this in answer to

Parked 21d 6h ago

mason/forge:mason/11655-a-subscriber-gives-a-friend-a-forge-in-o → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
21 files changed +942 −15
docs/features/gifts.md added +13
@@ -0,0 +1,13 @@
1 # Gifts (#11655)
2
3 A person who holds a forge on a paid plan gives a friend a forge in one tap, and sees who came.
4
5 - **Who may give.** The payer (by email) or the "for" name of a forge with an active paid entitlement that did not itself come from a code. Each such forge brings `gifts.per_forge` gifts (default 3, `/admin/limits`).
6 - **Give.** The home shows one quiet line, "Give a friend a forge" (`POST /gifts/make`), which answers with a link to copy and a message already written (the giver may change it, up to 280 characters). The giver may pick an app of theirs to open the gift with. `/gifts` lists every gift and who took it.
7 - **The friend's page.** `/gift/<code>` moves the code into an HttpOnly cookie and shows "A forge from <name>", the message, and the same one step as the home form (a forge name). With a shared app the button reads "Start with <app>": the new forge starts with a copy of it, even if the app is private. The friend may tick "Let <name> see what I build", which lets the giver's list show the apps in that forge.
8 - **What a gift is.** A gift code (#11157) with one use: the cheapest paid plan for `gifts.days` days (default 30). A second use is refused: "This gift has already been taken."
9 - **Thank-you.** When a gifted forge becomes a paying one at a provider, its giver is credited `gifts.thanks_days` days (default 30; 0 turns the credit off). It is recorded once per gift (`gift_thanks`), shown on `/gifts` and audited (`billing.gift.thanks`); it is not yet applied to the provider's invoice.
10 - **Send this app.** From an app's toolbar page, a writer's "Send this app" (`POST /gifts/send`) makes a link whose receiver gets their own copy on a free forge. Capped at 10 a day per person; it does not use up gifts.
11 - **Never public.** The forge posts no gift anywhere. The code is kept only as a hash.
12 - **Billing.** The funnel counts gifts given (not cancelled), taken, and converted, on Settings → Billing, in the terminal's "From visit to paid" screen and in the funnel API.
13 - **MCP.** The `gift` tool does the same as the page.
src/actions/codes.ts +7 −3
@@ -14,6 +14,7 @@ import {
1414 CODE_WORDS, MAX_NOTE, MAX_USES, insertCode, listCodes, lookupCode, noteRedeemed,
1515 releaseCode, revokeCode, takeTry, type Code, type CodeRefusal, type Listed,
1616 } from "../billing/codes.ts";
17 import { allowShowing } from "../billing/gifts.ts";
1718 import { putEntitlement } from "../billing/store.ts";
1819 import type { User } from "../core/users.ts";
1920 import { clientBucket } from "../http/peer.ts";
@@ -109,10 +110,13 @@ export function giftOf(app: App, request: Request, input: unknown): Result<{ id:
109110 export const unclaimGift = (app: App, code: Code): void => releaseCode(app.db, code.id);
110111
111112 /** The forge was made: record who redeemed it, give it the plan with source `code:<id>`, and audit it. */
112 export function settleGift(app: App, code: Code, forge: string): void {
113 export function settleGift(app: App, code: Code, forge: string, opts: { readonly showBuilt?: boolean } = {}): void {
114 if (opts.showBuilt === true && code.giver !== undefined) allowShowing(app.db, code.id);
113115 const size = getPlan(app.db, code.plan)?.size ?? "small";
114116 noteRedeemed(app.db, code.id, forge);
115 putEntitlement(app.db, { forge, plan: code.plan, status: "active", source: `code:${code.id}`, provider: "none" }, size, "");
117 // A subscriber's gift is free for its days, and the forge is told when they end.
118 const periodEnd = code.days > 0 ? Math.floor(Date.now() / 1000) + code.days * 86_400 : undefined;
119 putEntitlement(app.db, { forge, plan: code.plan, status: "active", source: `code:${code.id}`, provider: "none", ...(periodEnd === undefined ? {} : { periodEnd }) }, size, "");
116120 tellPlan(app, forge);
117 app.bus.append({ kind: "billing.code.redeem", payload: { id: code.id, forge, plan: code.plan } });
121 app.bus.append({ kind: "billing.code.redeem", payload: { id: code.id, forge, plan: code.plan, ...(code.giver === undefined ? {} : { giver: code.giver, kind: code.kind }) } });
118122 }
src/actions/gifts.ts added +180
@@ -0,0 +1,180 @@
1 /**
2 * Gifts as they are reached (#11655). A person who holds a forge on a paid
3 * plan gives a friend a forge in one tap (`giveGift`); anyone signed in may
4 * send an app they can write to as a gift (`sendApp`), which gives the
5 * receiver a copy on a free forge of their own. Both make a one-use code
6 * (`billing/gifts.ts`) whose link the giver copies or shares themselves:
7 * the forge posts nothing, anywhere. The friend reads what the link says
8 * (`friendLook`) without spending anything, and the forge itself is made at
9 * the same door as every start (`spawn/door.ts`). A giver sees who took each
10 * gift, and what the friend built only if the friend allowed it when taking it. A code made here is
11 * `gift` or `send` and never shows in the operator's list of codes.
12 */
13
14 import type { App } from "../app.ts";
15 import { lookupCode, normalizeCode, revokeCode, takeTry, CODE_WORDS, type CodeRefusal } from "../billing/codes.ts";
16 import {
17 MAX_MESSAGE, SENDS_PER_DAY, giftPlan, giftsHeld, givenBy, insertGift, paidForgesOf, sendsToday, thanksEarned, type Given,
18 } from "../billing/gifts.ts";
19 import { listChildrenNow } from "./spawn.ts";
20 import { canWrite, getRepo } from "../core/repos.ts";
21 import { getUserById, type User } from "../core/users.ts";
22 import { clientBucket } from "../http/peer.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import { limitValue } from "../settings/limits.ts";
25 import { FREE, getPlan } from "../settings/plans.ts";
26
27 export type GiftError = "not_found" | "not_paid" | "none_left" | "bad_message" | "bad_app" | "too_many_sends" | "no_such_gift";
28
29 export const GIFT_WORDS: Record<Exclude<GiftError, "not_found">, string> = {
30 not_paid: "Gifts come with a forge on a paid plan",
31 none_left: "Every gift you have is made; cancel one that has not been taken, or ask for more",
32 bad_message: `A message is at most ${MAX_MESSAGE} characters`,
33 bad_app: "That is not an app you can share: name one of your own apps as owner/name",
34 too_many_sends: `You have sent ${SENDS_PER_DAY} apps today; the next can go tomorrow`,
35 no_such_gift: "No gift of yours by that id",
36 };
37
38 /** The link a friend opens. */
39 export const giftLink = (origin: string, code: string): string => `${origin}/gift/${code}`;
40
41 /** The words that go with a link, as the giver would say them; the giver may change them. */
42 export function defaultMessage(app: App, user: User, shared: string): string {
43 const days = limitValue(app.db, "gifts.days");
44 return shared === ""
45 ? `I thought of you: here is a forge of your own for ${days} days, on me. Open it and tell the crew what you need.`
46 : `I built something I wanted you to have: ${shared}. Here is a forge of your own for ${days} days, on me, with it already running.`;
47 }
48
49 export interface GiftsView {
50 /** Gifts this person may make in all: the setting times their paid forges. */
51 readonly allowed: number;
52 readonly held: number;
53 readonly left: number;
54 readonly days: number;
55 readonly given: readonly Given[];
56 /** Days of thanks earned from friends who subscribed. */
57 readonly thanksDays: number;
58 }
59
60 const forNames = (app: App): Map<string, string | null> => new Map(listChildrenNow(app).map((c) => [c.name, c.for]));
61
62 /** What a person's home says about gifts; null when they hold no paid forge and have given none, so the home stays quiet. */
63 export function readGifts(app: App, actor: User | undefined): GiftsView | null {
64 if (actor === undefined || actor.kind !== "user") return null;
65 const paid = paidForgesOf(app.db, actor.email, actor.username, () => forNames(app));
66 const raw = givenBy(app.db, actor.id);
67 const taken = raw.some((g) => g.showBuilt && g.takenBy !== undefined) ? listChildrenNow(app) : [];
68 const given = raw.map((g) => (g.showBuilt && g.takenBy !== undefined ? { ...g, built: taken.find((c) => c.name === g.takenBy)?.apps ?? [] } : g));
69 if (paid.length === 0 && given.length === 0) return null;
70 const allowed = paid.length * limitValue(app.db, "gifts.per_forge");
71 const held = giftsHeld(app.db, actor.id);
72 return {
73 allowed, held, left: Math.max(0, allowed - held), days: limitValue(app.db, "gifts.days"), given,
74 thanksDays: thanksEarned(app.db, actor.id),
75 };
76 }
77
78 /** A shared app as the giver may give it: theirs to write to. Returns `owner/name` as stored, or "" when none named. */
79 function shareable(app: App, actor: User, raw: unknown): Result<string, "bad_app"> {
80 if (raw === undefined || raw === null || raw === "") return ok("");
81 if (typeof raw !== "string") return err("bad_app");
82 const [o, n, ...rest] = raw.trim().split("/");
83 const repo = o && n && rest.length === 0 ? getRepo(app.db, o, n) : undefined;
84 if (repo === undefined || !canWrite(app.db, repo, actor)) return err("bad_app");
85 return ok(`${o}/${n}`);
86 }
87
88 function messageOf(raw: unknown): Result<string, "bad_message"> {
89 if (raw === undefined || raw === null) return ok("");
90 // eslint-disable-next-line no-control-regex
91 if (typeof raw !== "string" || raw.trim().length > MAX_MESSAGE || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(raw)) return err("bad_message");
92 return ok(raw.trim());
93 }
94
95 export interface Made {
96 readonly code: string;
97 readonly link: string;
98 readonly message: string;
99 }
100
101 /** A person with a paid forge makes a gift: one link, one use. The plain code is in this answer and nowhere else. */
102 export function giveGift(app: App, actor: User | undefined, input: Record<string, unknown>, origin: string): Result<Made, GiftError> {
103 const view = readGifts(app, actor);
104 if (actor === undefined || view === null) return err("not_found");
105 const plan = giftPlan(app.db);
106 if (view.allowed === 0 || plan === undefined) return err("not_paid");
107 if (view.left === 0) return err("none_left");
108 const shared = shareable(app, actor, input["app"]);
109 if (!shared.ok) return shared;
110 const said = messageOf(input["message"]);
111 if (!said.ok) return said;
112 const message = said.value === "" ? defaultMessage(app, actor, shared.value) : said.value;
113 const { code, row } = insertGift(app.db, {
114 kind: "gift", giver: actor.id, plan, days: limitValue(app.db, "gifts.days"), app: shared.value, message,
115 showBuilt: false,
116 });
117 app.bus.append({ kind: "billing.gift.make", actorId: actor.id, payload: { id: row.id, plan, app: shared.value } });
118 return ok({ code, link: giftLink(origin, code), message });
119 }
120
121 /** Anyone signed in sends an app they can write to: the receiver gets their own copy on a free forge. */
122 export function sendApp(app: App, actor: User | undefined, input: Record<string, unknown>, origin: string): Result<Made, GiftError> {
123 if (actor === undefined || actor.kind !== "user") return err("not_found");
124 const shared = shareable(app, actor, input["app"]);
125 if (!shared.ok) return shared;
126 if (shared.value === "") return err("bad_app");
127 const said = messageOf(input["message"]);
128 if (!said.ok) return said;
129 if (sendsToday(app.db, actor.id) >= SENDS_PER_DAY) return err("too_many_sends");
130 const message = said.value === "" ? `I made ${shared.value} and want you to have your own copy: it opens running on a forge of your own, free.` : said.value;
131 const { code, row } = insertGift(app.db, {
132 kind: "send", giver: actor.id, plan: FREE, days: 0, app: shared.value, message, showBuilt: false,
133 });
134 app.bus.append({ kind: "billing.gift.send", actorId: actor.id, payload: { id: row.id, app: shared.value } });
135 return ok({ code, link: giftLink(origin, code), message });
136 }
137
138 /** A giver takes back a gift nobody has taken: the gift is theirs again to make. */
139 export function cancelGift(app: App, actor: User | undefined, id: unknown): Result<{ id: string }, GiftError> {
140 if (actor === undefined || actor.kind !== "user") return err("not_found");
141 const mine = typeof id === "string" ? givenBy(app.db, actor.id).find((g) => g.id === id && g.takenBy === undefined && !g.revoked) : undefined;
142 if (mine === undefined || !revokeCode(app.db, mine.id)) return err("no_such_gift");
143 app.bus.append({ kind: "billing.gift.cancel", actorId: actor.id, payload: { id: mine.id } });
144 return ok({ id: mine.id });
145 }
146
147 export interface FriendLook {
148 readonly id: string;
149 readonly kind: string;
150 readonly from: string;
151 readonly message: string;
152 /** The app the friend starts with, as owner/name; "" for none. */
153 readonly app: string;
154 readonly planName: string;
155 readonly days: number;
156 }
157
158 export type FriendRefusal = CodeRefusal | "slow_down";
159
160 export const FRIEND_WORDS: Record<FriendRefusal, string> = {
161 ...CODE_WORDS,
162 unknown: "This gift link is not one this forge knows. Ask whoever sent it for another",
163 used_up: "This gift has already been taken. A gift link works once; ask whoever sent it for another",
164 slow_down: "Too many links tried from here; try again in a few minutes",
165 };
166
167 /** What a friend sees before taking a gift: who it is from, what it holds. Spends nothing; counts one try for the client. */
168 export function friendLook(app: App, request: Request, raw: unknown): Result<FriendLook, FriendRefusal> {
169 if (normalizeCode(raw) === undefined) return err("unknown");
170 if (!takeTry(app.db, clientBucket(request))) return err("slow_down");
171 const seen = lookupCode(app.db, raw);
172 if (!seen.ok) return seen;
173 const c = seen.value;
174 if ((c.kind !== "gift" && c.kind !== "send") || c.giver === undefined) return err("unknown");
175 const giver = getUserById(app.db, c.giver);
176 return ok({
177 id: c.id, kind: c.kind, from: giver?.username ?? "a friend", message: c.message, app: c.shareApp,
178 planName: getPlan(app.db, c.plan)?.name ?? c.plan, days: c.days,
179 });
180 }
src/actions/spawn.ts +3 −1
@@ -102,6 +102,8 @@ export interface SpawnDeps {
102102 readonly url: URL;
103103 /** The plan was given by a gift code the caller has already claimed (`actions/codes.ts`): no admin, no payment. */
104104 readonly gift?: boolean;
105 /** An app a gift's giver chose to share (`billing/gifts.ts`): the friend need not be able to read it, the giver already could write to it. */
106 readonly sharedApp?: string;
105107 /**
106108 * The child's own model key, when the spawner gives it one: an API key, or
107109 * a person's own setup-token under a budget (their choice), sealed in the child with the
@@ -264,7 +266,7 @@ export async function spawnForge(
264266 names.add(name.toLowerCase());
265267 const [o, n] = a.ref.split("/") as [string, string];
266268 const repo = getRepo(app.db, o, n);
267 if (!repo || !canRead(app.db, repo, owner))
269 if (!repo || (a.ref !== deps.sharedApp && !canRead(app.db, repo, owner)))
268270 return err({ kind: "invalid", field: "apps", reason: `${a.ref} is not readable by you` });
269271 }
270272 for (const b of plan.briefs) {
src/billing/codes.ts +21 −3
@@ -34,6 +34,15 @@ export interface Code {
3434 readonly revokedAt?: string;
3535 readonly madeBy: string;
3636 readonly madeAt: string;
37 /** `operator` (an admin's code), `gift` (a subscriber's free forge for a friend) or `send` (an app sent to someone): `billing/gifts.ts`. */
38 readonly kind: string;
39 readonly giver?: string;
40 /** `owner/name` of the app the friend's forge starts with; "" for none. */
41 readonly shareApp: string;
42 readonly message: string;
43 /** How long a gifted forge is free; 0 for an operator's code, which names no end. */
44 readonly days: number;
45 readonly showBuilt: boolean;
3746 }
3847
3948 export interface Redeemed {
@@ -44,6 +53,7 @@ export interface Redeemed {
4453 interface Row {
4554 id: string; plan: string; note: string; uses: number; used: number; expires_at: string | null;
4655 revoked_at: string | null; made_by: string; made_at: string;
56 kind: string; giver: string | null; share_app: string; message: string; days: number; show_built: number;
4757 }
4858
4959 const fromRow = (r: Row): Code => ({
@@ -51,6 +61,7 @@ const fromRow = (r: Row): Code => ({
5161 ...(r.expires_at === null ? {} : { expiresAt: r.expires_at }),
5262 ...(r.revoked_at === null ? {} : { revokedAt: r.revoked_at }),
5363 madeBy: r.made_by, madeAt: r.made_at,
64 kind: r.kind, ...(r.giver === null ? {} : { giver: r.giver }), shareApp: r.share_app, message: r.message, days: r.days, showBuilt: r.show_built === 1,
5465 });
5566
5667 /** What a person typed, as the code it means: trimmed, lowercased, and of the code's shape, else undefined. */
@@ -73,6 +84,12 @@ export interface NewCode {
7384 uses: number;
7485 expiresAt?: string;
7586 madeBy: string;
87 kind?: string;
88 giver?: string;
89 shareApp?: string;
90 message?: string;
91 days?: number;
92 showBuilt?: boolean;
7693 }
7794
7895 /** Make a code: its row (hashed) and the plain code, which exists nowhere else. */
@@ -81,8 +98,9 @@ export function insertCode(db: Database, n: NewCode, now = new Date()): { code:
8198 const id = crypto.randomUUID().slice(0, 8);
8299 const at = now.toISOString();
83100 db.query(
84 "INSERT INTO gift_code (id, hash, plan, note, uses, expires_at, made_by, made_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
85 ).run(id, hashCode(code), n.plan, n.note, n.uses, n.expiresAt ?? null, n.madeBy, at);
101 `INSERT INTO gift_code (id, hash, plan, note, uses, expires_at, made_by, made_at, kind, giver, share_app, message, days, show_built)
102 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)`,
103 ).run(id, hashCode(code), n.plan, n.note, n.uses, n.expiresAt ?? null, n.madeBy, at, n.kind ?? "operator", n.giver ?? null, n.shareApp ?? "", n.message ?? "", n.days ?? 0, n.showBuilt === true ? 1 : 0);
86104 return { code, row: getCode(db, id)! };
87105 }
88106
@@ -144,7 +162,7 @@ export interface Listed extends Code {
144162 export function listCodes(db: Database, limit = 200): Listed[] {
145163 const rows = db
146164 .query<Row & { name: string | null }, [number]>(
147 "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",
165 "SELECT g.*, u.username AS name FROM gift_code g LEFT JOIN user u ON u.id = g.made_by WHERE g.kind = 'operator' ORDER BY g.made_at DESC, g.rowid DESC LIMIT ?1",
148166 )
149167 .all(limit);
150168 const redeemed = db.query<{ code_id: string; forge: string; at: string }, []>("SELECT code_id, forge, at FROM gift_redeem ORDER BY id").all();
src/billing/gifts.ts added +178
@@ -0,0 +1,178 @@
1 /**
2 * Gifts a subscriber gives (#11655): the rules and the reads. A gift is a
3 * gift code (`billing/codes.ts`) with one use, a giver, a message and
4 * optionally an app the giver shares; the friend's forge starts on the gift's
5 * plan for a number of days, with a copy of the app running. Who may give:
6 * the holder of a forge on a paid plan, active, found by the payer's email or
7 * the forge's "for" name; each such forge has `gifts.per_forge` gifts. Who
8 * took one, and who then subscribed, is read from `gift_redeem` and the
9 * entitlement the forge got, so the giver sees it and the operator's funnel
10 * counts it. The thank-you for a friend who subscribes is one row
11 * (`gift_thanks`) per gift, its days the `gifts.thanks_days` setting (0 turns the credit off, not the count). Nothing here posts anywhere: a gift is a link the
12 * giver sends themselves. Pure data; authorization is in `actions/gifts.ts`.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import type { App } from "../app.ts";
17 import { FREE, getPlans } from "../settings/plans.ts";
18 import { limitValue } from "../settings/limits.ts";
19 import { insertCode, type Code } from "./codes.ts";
20 import { getStored } from "./store.ts";
21
22 export const MAX_MESSAGE = 280;
23 /** Apps sent to someone, per giver per day: a send is free, so it is capped on its own. */
24 export const SENDS_PER_DAY = 10;
25 const DAY_MS = 86_400_000;
26
27 /** The plan a gift gives: the cheapest paid plan, or undefined when no plan is paid. */
28 export function giftPlan(db: Database): string | undefined {
29 return getPlans(db)
30 .filter((p) => p.key !== FREE && p.priceUsd > 0)
31 .sort((a, b) => a.priceUsd - b.priceUsd)[0]?.key;
32 }
33
34 /** The friend allowed the giver to see what they build: kept on the gift when it is taken. */
35 export function allowShowing(db: Database, codeId: string): void {
36 db.query("UPDATE gift_code SET show_built = 1 WHERE id = ?1").run(codeId);
37 }
38
39 /** The forges a person holds on a paid plan: payer's email or the forge's "for" name, active, not from a code. */
40 export function paidForgesOf(db: Database, email: string, username: string, forNames: () => ReadonlyMap<string, string | null>): string[] {
41 const rows = db
42 .query<{ forge: string; payer: string }, []>(
43 "SELECT forge, payer FROM entitlement WHERE status = 'active' AND plan != 'free' AND source NOT LIKE 'code:%'",
44 )
45 .all();
46 if (rows.length === 0) return [];
47 const names = forNames();
48 const mail = email.trim().toLowerCase();
49 const who = username.toLowerCase();
50 return rows
51 .filter((r) => (mail !== "" && r.payer.trim().toLowerCase() === mail) || (names.get(r.forge) ?? "").trim().toLowerCase() === who)
52 .map((r) => r.forge);
53 }
54
55 export interface Given {
56 readonly id: string;
57 readonly kind: string;
58 readonly app: string;
59 readonly message: string;
60 readonly showBuilt: boolean;
61 readonly madeAt: string;
62 readonly revoked: boolean;
63 /** The forge the friend made, once they took it. */
64 readonly takenBy?: string;
65 readonly takenAt?: string;
66 /** Days of thanks earned when that forge became a paying one. */
67 readonly thanksDays?: number;
68 /** The friend allowed it: the apps their forge holds. Filled in by `actions/gifts.ts`. */
69 readonly built?: readonly string[];
70 }
71
72 interface GivenRow {
73 id: string; kind: string; share_app: string; message: string; show_built: number; made_at: string;
74 revoked_at: string | null; forge: string | null; at: string | null; thanks: number | null;
75 }
76
77 /** Everything one person gave, newest first: gifts and sends. */
78 export function givenBy(db: Database, giver: string, limit = 100): Given[] {
79 return db
80 .query<GivenRow, [string, number]>(
81 `SELECT g.id, g.kind, g.share_app, g.message, g.show_built, g.made_at, g.revoked_at,
82 r.forge AS forge, r.at AS at, t.days AS thanks
83 FROM gift_code g
84 LEFT JOIN gift_redeem r ON r.code_id = g.id
85 LEFT JOIN gift_thanks t ON t.code_id = g.id
86 WHERE g.giver = ?1 AND g.kind IN ('gift', 'send')
87 ORDER BY g.made_at DESC, g.rowid DESC LIMIT ?2`,
88 )
89 .all(giver, limit)
90 .map((r) => ({
91 id: r.id, kind: r.kind, app: r.share_app, message: r.message, showBuilt: r.show_built === 1, madeAt: r.made_at, revoked: r.revoked_at !== null,
92 ...(r.forge === null ? {} : { takenBy: r.forge }),
93 ...(r.at === null ? {} : { takenAt: r.at }),
94 ...(r.thanks === null ? {} : { thanksDays: r.thanks }),
95 }));
96 }
97
98 /** Gifts (not sends) a person has made and not cancelled: the ones that count against their allowance. */
99 export function giftsHeld(db: Database, giver: string): number {
100 return db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM gift_code WHERE giver = ?1 AND kind = 'gift' AND revoked_at IS NULL").get(giver)!.n;
101 }
102
103 export function sendsSince(db: Database, giver: string, since: number): number {
104 return db.query<{ n: number }, [string, string]>("SELECT COUNT(*) AS n FROM gift_code WHERE giver = ?1 AND kind = 'send' AND made_at >= ?2").get(giver, new Date(since).toISOString())!.n;
105 }
106
107 export const sendsToday = (db: Database, giver: string, now = Date.now()): number => sendsSince(db, giver, now - DAY_MS);
108
109 export interface NewGift {
110 readonly kind: "gift" | "send";
111 readonly giver: string;
112 readonly plan: string;
113 readonly days: number;
114 readonly app: string;
115 readonly message: string;
116 readonly showBuilt: boolean;
117 }
118
119 /** Make the gift: its row, one use, and the plain code, which exists nowhere else. */
120 export function insertGift(db: Database, g: NewGift): { code: string; row: Code } {
121 return insertCode(db, {
122 plan: g.plan, note: "", uses: 1, madeBy: g.giver, kind: g.kind, giver: g.giver, shareApp: g.app, message: g.message, days: g.days, showBuilt: g.showBuilt,
123 });
124 }
125
126 /** The gift one forge came from, if any: its code, and the giver. */
127 export function giftOfForge(db: Database, forge: string): { id: string; giver: string } | undefined {
128 const r = db
129 .query<{ id: string; giver: string }, [string]>(
130 "SELECT g.id, g.giver FROM gift_redeem r JOIN gift_code g ON g.id = r.code_id WHERE r.forge = ?1 AND g.kind = 'gift' AND g.giver IS NOT NULL LIMIT 1",
131 )
132 .get(forge);
133 return r ?? undefined;
134 }
135
136 /** A gifted forge became a paying one: the giver's thank-you, once. Returns it when it was just made. */
137 export function thank(db: Database, forge: string, now = new Date()): { codeId: string; giver: string; days: number } | undefined {
138 const days = limitValue(db, "gifts.thanks_days");
139 const from = giftOfForge(db, forge);
140 if (from === undefined) return undefined;
141 const done = db
142 .query("INSERT OR IGNORE INTO gift_thanks (code_id, forge, giver, days, at) VALUES (?1, ?2, ?3, ?4, ?5)")
143 .run(from.id, forge, from.giver, days, now.toISOString());
144 return done.changes === 0 || days === 0 ? undefined : { codeId: from.id, giver: from.giver, days };
145 }
146
147 /** Days of thanks a giver has earned in all. */
148 export const thanksEarned = (db: Database, giver: string): number =>
149 db.query<{ n: number | null }, [string]>("SELECT SUM(days) AS n FROM gift_thanks WHERE giver = ?1").get(giver)?.n ?? 0;
150
151 export interface GiftCounts {
152 readonly given: number;
153 readonly taken: number;
154 readonly converted: number;
155 }
156
157 /** What the funnel counts since `since` (epoch ms): gifts made and not cancelled, taken, and taken ones that became paying. Sends are not gifts of a forge's time and are left out. */
158 export function giftCounts(db: Database, since: number): GiftCounts {
159 const at = new Date(since).toISOString();
160 const n = (sql: string): number => db.query<{ n: number }, [string]>(sql).get(at)!.n;
161 return {
162 given: n("SELECT COUNT(*) AS n FROM gift_code WHERE kind = 'gift' AND revoked_at IS NULL AND made_at >= ?1"),
163 taken: n("SELECT COUNT(*) AS n FROM gift_redeem r JOIN gift_code g ON g.id = r.code_id WHERE g.kind = 'gift' AND r.at >= ?1"),
164 converted: n("SELECT COUNT(*) AS n FROM gift_thanks WHERE at >= ?1"),
165 };
166 }
167
168 /** Called whenever a forge is told its plan: a forge that came from a gift and is now paid for at a provider thanks its giver, once. Never throws. */
169 export function thankGiver(app: App, forge: string): void {
170 try {
171 const s = getStored(app.db, forge);
172 if (s === undefined || s.status !== "active" || s.plan === FREE || s.provider === "none" || s.provider === "") return;
173 const t = thank(app.db, forge);
174 if (t !== undefined) app.bus.append({ kind: "billing.gift.thanks", payload: { id: t.codeId, forge, giver: t.giver, days: t.days } });
175 } catch {
176 // a thank-you is never worth failing a payment's bookkeeping
177 }
178 }
src/billing/notice.ts +2
@@ -15,6 +15,7 @@ import type { App } from "../app.ts";
1515 import { childDirOf, listChildrenNow } from "../actions/spawn.ts";
1616 import { getPortalUrl, parseLink } from "../settings/billing.ts";
1717 import { getPlan } from "../settings/plans.ts";
18 import { thankGiver } from "./gifts.ts";
1819 import { lapseFor } from "./lapse.ts";
1920 import { entitlementOf, getStored } from "./store.ts";
2021 import type { EntitlementStatus } from "./types.ts";
@@ -76,6 +77,7 @@ export function keepNotice(dataDir: string, notice: PlanNotice): boolean {
7677
7778 /** Tell one forge its plan as the host holds it now. Never throws: a forge that cannot be reached is told at the next change. */
7879 export function tellPlan(app: App, forge: string): boolean {
80 thankGiver(app, forge);
7981 try {
8082 const child = listChildrenNow(app).find((c) => c.name === forge && c.done);
8183 if (child === undefined) return false;
src/core/migration-pins/20261112150000-gifts.pin added +1
@@ -0,0 +1,1 @@
1 73b7775ef659919686ddd04df6acd24c96575af806616fb6c8d6d291b1e9a1a0
src/core/migrations/20261112150000-gifts.ts added +22
@@ -0,0 +1,22 @@
1 // Gifts a subscriber gives (#11655): a gift is a gift code (#11157) with a giver, a message and
2 // optionally an app the giver shares, so the friend's first forge opens with it. `kind` tells the
3 // operator's codes from a subscriber's gifts and from an app sent to someone. `gift_thanks` is
4 // the thank-you a giver earned when a friend's gifted forge became a paying one: one per code.
5 // Additive.
6 export default `
7 ALTER TABLE gift_code ADD COLUMN kind TEXT NOT NULL DEFAULT 'operator';
8 ALTER TABLE gift_code ADD COLUMN giver TEXT;
9 ALTER TABLE gift_code ADD COLUMN share_app TEXT NOT NULL DEFAULT '';
10 ALTER TABLE gift_code ADD COLUMN message TEXT NOT NULL DEFAULT '';
11 ALTER TABLE gift_code ADD COLUMN days INTEGER NOT NULL DEFAULT 0;
12 ALTER TABLE gift_code ADD COLUMN show_built INTEGER NOT NULL DEFAULT 0;
13 CREATE INDEX gift_code_giver ON gift_code (giver, kind, made_at);
14 CREATE TABLE gift_thanks (
15 code_id TEXT PRIMARY KEY,
16 forge TEXT NOT NULL,
17 giver TEXT NOT NULL,
18 days INTEGER NOT NULL,
19 at TEXT NOT NULL
20 );
21 CREATE INDEX gift_thanks_giver ON gift_thanks (giver, at);
22 `;
src/core/reserved.ts +2
@@ -80,6 +80,8 @@ export const SYSTEM_NAMES: readonly string[] = [
8080 "fleet",
8181 "flow",
8282 "front",
83 "gift",
84 "gifts",
8385 "go",
8486 "home",
8587 "hooks",
src/http/mcp/tools/gift.ts added +30
@@ -0,0 +1,30 @@
1 import { GIFT_WORDS, giveGift, readGifts, sendApp } from "../../../actions/gifts.ts";
2 import { publicOrigin } from "../../../core/public_origin.ts";
3 import { good, bad, type Tool, REVEAL_ARG } from "../shared.ts";
4
5 export const tool: Tool = {
6 name: "gift",
7 doc: "gifts, the same as the Gifts page: with no argument, what you may give, what is left and who took each; `reveal: true` makes a gift link (a free forge for a friend; needs a forge on a paid plan; `app` owner/name of an app of yours it opens with, `message` your words) and shows it once; `send: true` with `app` sends that app to someone as a gift link instead. Nothing is posted anywhere",
8 description: "Give a friend a forge, or send an app as a gift; see who took what you gave.",
9 inputSchema: {
10 type: "object",
11 properties: {
12 reveal: REVEAL_ARG,
13 send: { type: "boolean" },
14 app: { type: "string" },
15 message: { type: "string" },
16 },
17 },
18 writes: true,
19 async run(ctx, user, args) {
20 if (args["reveal"] !== true && args["send"] !== true) {
21 const view = readGifts(ctx.app, user);
22 return view === null ? bad("not_found", "Gifts come with a forge on a paid plan") : good({ ...view });
23 }
24 const origin = publicOrigin(ctx.app.config.url, ctx.url.origin);
25 const input = { app: args["app"], message: args["message"] };
26 const made = args["send"] === true ? sendApp(ctx.app, user, input, origin) : giveGift(ctx.app, user, input, origin);
27 if (!made.ok) return bad(made.error, made.error === "not_found" ? "Gifts come with a forge on a paid plan" : GIFT_WORDS[made.error]);
28 return good({ link: made.value.link, message: made.value.message, says: "Shown once: the plain code is not kept. Send the link yourself; it works once." });
29 },
30 };
src/http/server.ts +9
@@ -290,6 +290,7 @@ import { funnelSubmit } from "./funnel.ts";
290290 import { pricingDone, pricingOrder, pricingPage, resendPage, resendSubmit } from "../web/pages/pricing.ts";
291291 import { forgeWaitingPage } from "../web/pages/forge-waiting.ts";
292292 import { startForgeSubmit } from "../web/pages/start-forge.ts";
293 import { giftCancel, giftMake, giftOpen, giftPage, giftSend, giftsPage, giftStart } from "../web/pages/gifts.ts";
293294 import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
294295 import { askedPage } from "../web/studio/asked_page.ts";
295296 import { notesOverrule, notesSave, notesView } from "../web/pages/notes.ts";
@@ -883,6 +884,14 @@ export function buildRouter(): Router<Handler> {
883884 router.add("GET", "/forges/new", newForgePage);
884885 router.add("POST", "/forges/new", newForgeSubmit);
885886 router.add("POST", "/forges/start", startForgeSubmit);
887 // Gifts (#11655): a subscriber gives a friend a forge; the friend opens the link.
888 router.add("GET", "/gifts", giftsPage);
889 router.add("POST", "/gifts/make", giftMake);
890 router.add("POST", "/gifts/send", giftSend);
891 router.add("POST", "/gifts/cancel", giftCancel);
892 router.add("GET", "/gift", giftPage);
893 router.add("POST", "/gift/start", giftStart);
894 router.add("GET", "/gift/:code", giftOpen);
886895 // The front page as a stranger sees it, for anyone; a site admin there
887896 // also gets the controls that decide it (#686).
888897 router.add("GET", "/front", studioDoor);
src/perf/funnel.ts +4
@@ -13,6 +13,7 @@
1313 */
1414
1515 import type { Database } from "bun:sqlite";
16 import { giftCounts, type GiftCounts } from "../billing/gifts.ts";
1617 import type { Origin } from "./sources.ts";
1718 import { flushViews, noteView } from "./views_store.ts";
1819 import { DAY_MS } from "./views_report.ts";
@@ -38,6 +39,8 @@ export interface FunnelReport {
3839 readonly clicks_by_plan: { plan: string; count: number }[];
3940 /** Where visits that clicked a plan came from, top 5; "(direct)" when no referrer or campaign. */
4041 readonly referrers: { source: string; count: number }[];
42 /** Gifts a subscriber made, friends who took them and taken ones that became paying (#11655). */
43 readonly gifts: GiftCounts;
4144 }
4245
4346 /** `days` from the query: a whole number 1..90, else 7. */
@@ -132,6 +135,7 @@ export function funnelReport(db: Database, days: number, now: number = Date.now(
132135 days,
133136 steps: labels.map(([id, label], i) => ({ id, label, count: counts[i]!, pct: i === 0 ? null : pct(counts[i]!, counts[i - 1]!) })),
134137 clicks_by_plan: top([...byPlan].map(([plan, s]) => ({ plan, count: s.size })), (t) => t.plan, 50),
138 gifts: giftCounts(db, since),
135139 referrers: top([...sources].map(([source, count]) => ({ source, count })), (t) => t.source, 5),
136140 };
137141 }
src/settings/limits.ts +28 −1
@@ -55,7 +55,10 @@ export type LimitKey =
5555 | "model_review.slack_pct"
5656 | "shell_idle_minutes"
5757 | "billing.grace_days"
58 | "billing.retention_days";
58 | "billing.retention_days"
59 | "gifts.per_forge"
60 | "gifts.days"
61 | "gifts.thanks_days";
5962
6063 export interface LimitDef {
6164 readonly label: string;
@@ -339,6 +342,30 @@ export const LIMITS: Record<LimitKey, LimitDef> = {
339342 max: 365,
340343 reason: "A forge that lapsed may come back, so its data waits this long before anything is allowed to remove it; paying again makes it active at once.",
341344 },
345 "gifts.per_forge": {
346 label: "Gifts a paid forge may give",
347 unit: "gifts",
348 default: 3,
349 min: 0,
350 max: 100,
351 reason: "Each gift is a free forge for a friend; the number keeps the generosity from becoming a way around the plans. 0 turns gifts off.",
352 },
353 "gifts.days": {
354 label: "Days a gifted forge is free",
355 unit: "days",
356 default: 30,
357 min: 1,
358 max: 365,
359 reason: "A gift is a taste, not a plan: the friend's forge is on the gift's plan this long, then they choose.",
360 },
361 "gifts.thanks_days": {
362 label: "Days of credit a giver gets when a friend subscribes",
363 unit: "days",
364 default: 30,
365 min: 0,
366 max: 365,
367 reason: "The thank-you for a gift that became a paying forge; 0 turns the thank-you off.",
368 },
342369 };
343370
344371 export const LIMIT_KEYS = Object.keys(LIMITS) as LimitKey[];
src/spawn/door.ts +10 −5
@@ -40,7 +40,7 @@ import { readdir, stat } from "node:fs/promises";
4040 import { join } from "node:path";
4141 import { FREE, getPlan, getPlans, PAID_PLAN_ADMIN_ONLY } from "../settings/plans.ts";
4242 import { giftOf, REDEEM_WORDS, settleGift, unclaimGift } from "../actions/codes.ts";
43 import { claimCode, CODE_WORDS, type Code } from "../billing/codes.ts";
43 import { claimCode, CODE_WORDS, lookupCode, type Code } from "../billing/codes.ts";
4444
4545 export interface Door {
4646 readonly status: number;
@@ -204,8 +204,12 @@ export async function spawnDoor(
204204 if (raw["dryRun"] !== undefined && typeof raw["dryRun"] !== "boolean")
205205 return invalid("dryRun", "must be true or false");
206206 const dry = raw["dryRun"] !== false;
207 const apps = names(raw["apps"], "apps", MAX_APPS);
208 if (!Array.isArray(apps)) return apps;
207 const named = names(raw["apps"], "apps", MAX_APPS);
208 if (!Array.isArray(named)) return named;
209 // A gift can open with an app its giver chose to share: it is read as the giver's to give, not as the stranger's to see (`actions/gifts.ts`).
210 const shared = raw["code"] === undefined || raw["code"] === null || raw["code"] === "" ? undefined : lookupCode(ctx.app.db, raw["code"]);
211 const giftApp = shared?.ok === true ? shared.value.shareApp : "";
212 const apps = giftApp !== "" && !named.includes(giftApp) ? [...named, giftApp] : named;
209213 const crew = names(raw["crew"], "crew", MAX_CREW);
210214 if (!Array.isArray(crew)) return crew;
211215 if (anon && crew.length > 0)
@@ -253,7 +257,7 @@ export async function spawnDoor(
253257 for (const ref of new Set(apps)) {
254258 const [o, n, ...rest] = ref.split("/");
255259 const repo = o && n && rest.length === 0 ? getRepo(db, o, n) : undefined;
256 if (!repo || !canRead(db, repo, user)) continue;
260 if (!repo || (ref !== giftApp && !canRead(db, repo, user))) continue;
257261 catalog.push({
258262 ref,
259263 readable: true,
@@ -363,6 +367,7 @@ export async function spawnDoor(
363367 try {
364368 made = await spawnForge(ctx.app, user, input, source, {
365369 ...(gift === undefined && !paid ? {} : { gift: true }),
370 ...(gift === undefined || gift.shareApp === "" ? {} : { sharedApp: gift.shareApp }),
366371 placement: placementFor(ctx.app),
367372 request: ctx.request,
368373 url: ctx.url,
@@ -370,7 +375,7 @@ export async function spawnDoor(
370375 ...(modelEndpoint === undefined ? {} : { modelEndpoint }),
371376 });
372377 if (made.ok && gift !== undefined && !made.value.existed) {
373 settleGift(ctx.app, gift, made.value.name);
378 settleGift(ctx.app, gift, made.value.name, { showBuilt: raw["showBuilt"] === true });
374379 settled = true;
375380 }
376381 } finally {
src/tui/screens/funnel.ts +1
@@ -17,6 +17,7 @@ const mayRead = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind
1717 /** One row per step with its share of the step before, then clicks by plan, then referrers. */
1818 export function funnelRows(r: FunnelReport): ListRow[] {
1919 const rows: ListRow[] = r.steps.map((s) => ({ title: s.label, meta: s.pct === null ? `${s.count}` : `${s.count} · ${s.pct}% of the step before` }));
20 rows.push({ title: "Gifts given", meta: `${r.gifts.given}` }, { title: "Gifts taken", meta: `${r.gifts.taken}` }, { title: "Gifts that became paying", meta: `${r.gifts.converted}` });
2021 for (const c of r.clicks_by_plan) rows.push({ title: `Clicked ${c.plan}`, meta: `${c.count}` });
2122 for (const x of r.referrers) rows.push({ title: `Plan clicks from ${x.source}`, meta: `${x.count}` });
2223 return rows;
src/web/pages/billing.ts +3
@@ -158,6 +158,9 @@ function funnelRow(r: FunnelReport): Html {
158158 <h2>Last 7 days: from visit to paid</h2>
159159 <dl class="status-rows" data-funnel>
160160 ${r.steps.map((s) => row(s.label, s.pct === null ? `${s.count}` : `${s.count} · ${s.pct}% of the step before`))}
161 ${row("Gifts given", `${r.gifts.given}`)}
162 ${row("Gifts taken", `${r.gifts.taken}`)}
163 ${row("Gifts that became paying", `${r.gifts.converted}`)}
161164 ${r.clicks_by_plan.map((c) => row(`Clicked ${c.plan}`, `${c.count}`))}
162165 ${r.referrers.map((x) => row(`Plan clicks from ${x.source}`, `${x.count}`))}
163166 </dl>
src/web/pages/gifts.ts added +217
@@ -0,0 +1,217 @@
1 /**
2 * Gifts (#11655), both sides. The giver's side: the one quiet line on the
3 * home (`giftLine`), `GET /gifts` with the gifts made, who took them and the
4 * thank-yous, `POST /gifts/make` (one tap: a link to copy or share and the
5 * message already written), `POST /gifts/send` (an app sent as a gift, from
6 * its page) and `POST /gifts/cancel`. The friend's side: `GET /gift/<code>`
7 * keeps the code in an HttpOnly cookie and moves to `/gift`, which says who
8 * it is from and starts the forge (`POST /gift/start`) with the same one
9 * step as the home form, opening with the shared app when there is one. The
10 * forge posts nothing anywhere; a gift link works once and a second use is
11 * refused in plain words.
12 */
13
14 import { FRIEND_WORDS, GIFT_WORDS, cancelGift, friendLook, giveGift, readGifts, sendApp, type GiftError, type GiftsView } from "../../actions/gifts.ts";
15 import { publicOrigin } from "../../core/public_origin.ts";
16 import { listReposWritableTo } from "../../core/repos.ts";
17 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
18 import type { Ctx } from "../../http/context.ts";
19 import { spawnDoor } from "../../spawn/door.ts";
20 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
21 import { field, readForm } from "../form.ts";
22 import { dropGift, keepGift, keptGift } from "../gift_cookie.ts";
23 import { noteForgeMade } from "../funnel_door.ts";
24 import { waitingAddress } from "../claim_code.ts";
25 import { html, type Html } from "../html.ts";
26 import { flashTo, page, redirect } from "../layout.ts";
27 import { btn, copyField } from "../ui.ts";
28 import { startWaitBody, startWaitJs } from "./start-forge.ts";
29
30 const words = (e: GiftError): string => (e === "not_found" ? "Not found" : GIFT_WORDS[e]);
31 const originOf = (ctx: Ctx): string => publicOrigin(ctx.app.config.url, ctx.url.origin);
32
33 /** The home's one quiet line: null when this person holds no gift, so most homes say nothing. */
34 export function giftLine(ctx: Ctx): Html | null {
35 const v = readGifts(ctx.app, ctx.auth.user);
36 if (v === null) return null;
37 const taken = v.given.filter((g) => g.takenBy !== undefined).length;
38 return html`<p class="small muted" id="gift-line">
39 ${v.left > 0
40 ? html`<form method="post" action="/gifts/make" class="inline">${btn("Give a friend a forge", { size: "sm", variant: "link" })}</form>`
41 : html`<a href="/gifts">Your gifts</a>`}
42 ${v.given.length === 0 ? null : html` · <a href="/gifts">${taken} of ${v.given.length} taken</a>`}
43 </p>`;
44 }
45
46 interface Shown {
47 readonly link: string;
48 readonly message: string;
49 readonly what: string;
50 }
51
52 function givenRows(v: GiftsView): Html {
53 if (v.given.length === 0) return html`<p class="muted small">No gift given yet.</p>`;
54 return html`<ul class="list setting-list">${v.given.map((g) => {
55 const what = g.kind === "send" ? `App ${g.app}` : g.app === "" ? "A forge" : `A forge with ${g.app}`;
56 const state = g.takenBy !== undefined
57 ? html`taken by <span class="mono">${g.takenBy}</span>${g.thanksDays !== undefined ? html` · subscribed, thank you: ${g.thanksDays} days of credit` : null}${g.built === undefined ? null : g.built.length === 0 ? html` · nothing built yet` : html` · built ${g.built.join(", ")}`}`
58 : g.revoked ? html`cancelled` : html`waiting for a friend`;
59 return html`<li class="row" data-gift="${g.id}" data-state="${g.takenBy !== undefined ? "taken" : g.revoked ? "cancelled" : "waiting"}">
60 <span>${what}</span> <span class="muted small">${state}</span>
61 ${g.takenBy === undefined && !g.revoked
62 ? html`<form method="post" action="/gifts/cancel"><input type="hidden" name="id" value="${g.id}" />${btn("Cancel", { size: "sm" })}</form>`
63 : null}
64 </li>`;
65 })}</ul>`;
66 }
67
68 function giftsView(ctx: Ctx, shown?: Shown, error?: string, status = 200): Response {
69 const v = readGifts(ctx.app, ctx.auth.user);
70 if (v === null || ctx.auth.user === undefined) return notFoundPage(ctx);
71 const repos = listReposWritableTo(ctx.app.db, ctx.auth.user, { limit: 200, withoutArchived: true });
72 const body = html`<div class="narrow stack">
73 ${pageHead("Gifts")}
74 ${error === undefined ? null : html`<p class="error" role="alert">${error}</p>`}
75 ${shown === undefined
76 ? null
77 : html`<section class="stack stack-tight" id="new-gift" role="status">
78 <h2>${shown.what}</h2>
79 <p class="muted small">Send this link yourself, in your own words. It works once, and the forge posts it nowhere.</p>
80 ${copyField("gift-link", shown.link, "The gift link", "Copy the link")}
81 <p class="small" id="gift-message">${shown.message}</p>
82 </section>`}
83 <section class="stack stack-tight">
84 <p>${v.left} of ${v.allowed} gifts left. A gift is a free forge for a friend for ${v.days} days.</p>
85 ${v.thanksDays > 0 ? html`<p class="small" id="gift-thanks">Friends who subscribed have earned you ${v.thanksDays} days of credit.</p>` : null}
86 ${v.left > 0
87 ? html`<form method="post" action="/gifts/make" class="stack stack-tight" id="make-gift">
88 <label for="gift-app">Open with an app of yours (optional)</label>
89 <select class="input" id="gift-app" name="app"><option value="">None</option>${repos.map((r) => html`<option value="${r.ownerName}/${r.name}">${r.ownerName}/${r.name}</option>`)}</select>
90 <label for="gift-text">Your words (optional)</label>
91 <textarea class="input" id="gift-text" name="message" rows="3" maxlength="280" placeholder="Left empty, a message is written for you"></textarea>
92 ${btn("Give a friend a forge", { variant: "primary" })}
93 </form>`
94 : null}
95 </section>
96 <section><h2>Given</h2>${givenRows(v)}</section>
97 </div>`;
98 const response = page({ ctx, title: "Gifts", body }, status);
99 if (shown !== undefined) response.headers.set("cache-control", "no-store");
100 return response;
101 }
102
103 // GET /gifts
104 export function giftsPage(ctx: Ctx): Response {
105 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
106 if (!ctx.auth.user) return signInFirst(ctx);
107 return giftsView(ctx);
108 }
109
110 // POST /gifts/make
111 export async function giftMake(ctx: Ctx): Promise<Response> {
112 const form = await readForm(ctx);
113 if (form instanceof Response) return form;
114 const made = giveGift(ctx.app, ctx.auth.user, { app: field(form, "app"), message: field(form, "message") }, originOf(ctx));
115 if (!made.ok) return made.error === "not_found" ? notFoundPage(ctx) : giftsView(ctx, undefined, `${words(made.error)}.`, 422);
116 return giftsView(ctx, { link: made.value.link, message: made.value.message, what: "A forge for a friend" });
117 }
118
119 // POST /gifts/send: an app, sent as a gift, from its page.
120 export async function giftSend(ctx: Ctx): Promise<Response> {
121 const form = await readForm(ctx);
122 if (form instanceof Response) return form;
123 const sent = sendApp(ctx.app, ctx.auth.user, { app: field(form, "app"), message: field(form, "message") }, originOf(ctx));
124 if (!sent.ok) return sent.error === "not_found" ? notFoundPage(ctx) : flashTo(ctx, "/", { tone: "danger", message: `${words(sent.error)}.` });
125 // The sender may be someone with no paid forge: the link is shown here, in this one answer.
126 const body = html`<div class="narrow stack">
127 ${pageHead("Send this app")}
128 <section class="stack stack-tight" id="new-gift" role="status">
129 <p class="muted small">Send this link yourself, in your own words. The person who opens it gets their own copy on a forge of their own, free. It works once.</p>
130 ${copyField("gift-link", sent.value.link, "The link to send", "Copy the link")}
131 <p class="small" id="gift-message">${sent.value.message}</p>
132 </section>
133 </div>`;
134 const response = page({ ctx, title: "Send this app", body });
135 response.headers.set("cache-control", "no-store");
136 return response;
137 }
138
139 // POST /gifts/cancel
140 export async function giftCancel(ctx: Ctx): Promise<Response> {
141 const form = await readForm(ctx);
142 if (form instanceof Response) return form;
143 const done = cancelGift(ctx.app, ctx.auth.user, field(form, "id"));
144 if (!done.ok && done.error === "not_found") return notFoundPage(ctx);
145 return flashTo(ctx, "/gifts", done.ok ? { message: "Gift cancelled. It is yours to give again." } : { tone: "danger", message: `${words(done.error)}.` });
146 }
147
148 /** "Send this app", for an app's page: one button that makes the link. */
149 export function sendThisApp(repo: string): Html {
150 return html`<form method="post" action="/gifts/send" class="inline"><input type="hidden" name="app" value="${repo}" />${btn("Send this app", { size: "sm" })}</form>`;
151 }
152
153 // GET /gift/:code — the code moves to a cookie, out of the address.
154 export function giftOpen(ctx: Ctx): Response {
155 return keepGift((ctx.params["code"] ?? "").slice(0, 64), "/gift", ctx.url, ctx.app.config.url);
156 }
157
158 function friendView(ctx: Ctx, values: { name: string }, error?: string, status = 200): Response {
159 const code = keptGift(ctx.request);
160 const look = code === "" ? undefined : friendLook(ctx.app, ctx.request, code);
161 let body: Html;
162 if (look === undefined || !look.ok) {
163 const says = look === undefined ? FRIEND_WORDS.unknown : FRIEND_WORDS[look.error];
164 body = html`<div class="narrow stack" data-gift-refused>${pageHead("This gift")}<p class="error" role="alert" id="gift-refused">${says}.</p>
165 <p>${btn("Start a forge of your own", { href: "/", variant: "outline" })}</p></div>`;
166 return page({ ctx, title: "A gift", body }, look === undefined ? 404 : look.error === "slow_down" ? 429 : 410);
167 }
168 const g = look.value;
169 const lead = g.kind === "send" ? `${g.from} sent you an app` : `A forge from ${g.from}`;
170 const action = g.app === "" ? "Start my forge" : `Start with ${g.app.split("/")[1] ?? g.app}`;
171 body = html`<div class="narrow stack" data-gift>
172 ${pageHead(lead)}
173 <p id="gift-message">${g.message}</p>
174 <p class="muted small">${g.kind === "send" ? "A forge of your own, free." : `A ${g.planName} forge, free for ${g.days} days.`}</p>
175 <form method="post" action="/gift/start" class="door-start" id="start-gift">
176 ${error === undefined ? null : html`<p class="error" role="alert" id="gift-error">${error}</p>`}
177 <div class="field">
178 <label for="gift-name">Forge name</label>
179 <input class="input" id="gift-name" name="name" type="text" value="${values.name}" required autocomplete="off" autocapitalize="none" spellcheck="false" />
180 </div>
181 <label class="small"><input type="checkbox" name="showBuilt" value="1" /> Let ${g.from} see what I build</label>
182 ${btn(action, { variant: "primary", size: "lg" })}
183 </form>
184 </div>`;
185 const response = page({ ctx, title: lead, body }, status);
186 response.headers.set("cache-control", "no-store");
187 return response;
188 }
189
190 // GET /gift
191 export function giftPage(ctx: Ctx): Response {
192 return friendView(ctx, { name: "" });
193 }
194
195 // POST /gift/start
196 export async function giftStart(ctx: Ctx): Promise<Response> {
197 const user = ctx.auth.user;
198 if (user && user.kind !== "user") return notFoundPage(ctx);
199 const form = await readForm(ctx, user === undefined ? undefined : "admin");
200 if (form instanceof Response) return form;
201 // Someone already signed in uses the fuller form, which keeps the gift in its cookie too.
202 if (user !== undefined) return redirect("/forges/new");
203 const name = field(form, "name").trim().toLowerCase();
204 const code = keptGift(ctx.request);
205 const door = await spawnDoor(ctx, undefined, { name, dryRun: false, code, ...(field(form, "showBuilt") === "1" ? { showBuilt: true } : {}) });
206 if (door.status >= 400) return friendView(ctx, { name }, String(door.body["message"] ?? "The forge could not be made"), door.status === 429 ? 429 : 422);
207 const link = door.body["claimUrl"];
208 if (typeof link !== "string") return friendView(ctx, { name }, "That name is taken; choose another", 409);
209 noteForgeMade(ctx);
210 const waiting = field(form, "js") === "1" ? waitingAddress(door.body) : undefined;
211 const response = waiting !== undefined
212 ? redirect(waiting)
213 : page({ ctx, title: "Setting up…", body: startWaitBody(name, link), scriptJs: startWaitJs });
214 response.headers.set("cache-control", "no-store");
215 response.headers.append("set-cookie", dropGift(ctx.url, ctx.app.config.url));
216 return response;
217 }
src/web/studio/home.ts +3 −2
@@ -25,6 +25,7 @@ import { accountsClosedIn } from "../../core/users.ts";
2525 import { markTold, untoldAnswer } from "../../core/requests.ts";
2626 import { requestsCard } from "../requests_card.ts";
2727 import { plansRow } from "../plans_row.ts";
28 import { giftLine } from "../pages/gifts.ts";
2829 import { freePlanName, funnelJs, noteHomeVisit } from "../funnel_door.ts";
2930 import { publicPlans } from "../../settings/plans.ts";
3031 import { getDoorSettings } from "../../settings/door.ts";
@@ -328,7 +329,7 @@ export async function studioHome(
328329 // Before the first tell the card is the one box and carries the key line and the composer.
329330 const firstTell = steps.some((s) => s.key === "tell" && !s.done);
330331 const lean = html`<h1 class="sr-only">Home</h1>
331 ${firstSteps} ${address} ${firstTell ? null : crewKeyCard(ctx)} ${heldLine(ctx, user)} ${apps}
332 ${firstSteps} ${address} ${giftLine(ctx)} ${firstTell ? null : crewKeyCard(ctx)} ${heldLine(ctx, user)} ${apps}
332333 <div class="stack">
333334 ${firstTell ? null : composer(ctx, user)}
334335 <p class="small muted">
@@ -376,7 +377,7 @@ export async function studioHome(
376377 const body = html`<h1 class="sr-only">Home</h1>
377378 ${allowed ? html`<div class="toast" data-tone="success" role="status" id="youre-in"><strong>${YOURE_IN_MESSAGE}</strong> Your account is open: tell the crew what you want to build.</div>` : null}
378379 ${tellBox(ctx, user)}
379 ${ask} ${address}
380 ${ask} ${address} ${giftLine(ctx)}
380381 ${when(String(needsYou).trim() !== "", () => html`<section class="stack stack-tight" id="needs-you" aria-label="Needs you"><h2 class="small muted">Needs you</h2>${needsYou}</section>`)}
381382 ${when(String(since).trim() !== "", () => html`<section aria-label="Since you were here">${since}</section>`)}
382383 <section aria-label="Live">${timePhase(ctx.request, "moving", () => movingRegion(ctx.app.db, user))}</section>
src/web/studio/toolbar.ts +2
@@ -15,6 +15,7 @@
1515 * links to #606's page. Signed out, the page is where you are and home.
1616 */
1717
18 import { sendThisApp } from "../pages/gifts.ts";
1819 import { HELP_BUILD } from "../../core/contribute.ts";
1920 import { lacks } from "../../core/roles.ts";
2021 import { addCommentThrough, openIssueThrough } from "../../actions/issues.ts";
@@ -269,6 +270,7 @@ export async function toolbarPage(ctx: Ctx): Promise<Response> {
269270 !canWrite(db, repo, user),
270271 () => btn(user !== undefined && lacks(db, user, "make_it_yours") ? HELP_BUILD : "Make it yours", { href: `${base}/make-it-yours`, icon: "fork" }),
271272 )}
273 ${when(user !== undefined && user.kind === "user" && canWrite(db, repo, user), () => sendThisApp(`${repo.ownerName}/${repo.name}`))}
272274 ${other}${home}
273275 </div>
274276 </div>`;
test/gifts.test.ts added +206
@@ -0,0 +1,206 @@
1 /**
2 * Gifts a subscriber gives (#11655): a person with a paid forge makes a link, a
3 * stranger opens it, sees who it is from, starts a forge with the shared app,
4 * the giver sees it taken, a second use is refused plainly, a friend who
5 * subscribes earns a thank-you, and the funnel counts it all.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { childNamed } from "../src/actions/spawn.ts";
14 import { tellPlan } from "../src/billing/notice.ts";
15 import { entitlementOf, getStored, putEntitlement } from "../src/billing/store.ts";
16 import { setMember } from "../src/core/roles.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser } from "../src/core/users.ts";
19 import { ok } from "../src/kernel/result.ts";
20 import { funnelReport } from "../src/perf/funnel.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { bootHostedChild } from "../src/spawn/host.ts";
23 import { usePlacement, useProbe } from "../src/spawn/door.ts";
24 import { resetAnonSpawns } from "../src/spawn/rate.ts";
25 import { setLimit } from "../src/settings/limits.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 describe("gifts", () => {
31 let dataDir: string;
32 let app: App;
33 let servers: Servers;
34 let carol = "";
35 let bob = "";
36 let adminId = "";
37 const made: string[] = [];
38
39 const as = (token: string | undefined, path: string, init: { method?: string; body?: Record<string, string>; cookie?: string } = {}) =>
40 fetch(`${servers.url}${path}`, {
41 method: init.method ?? "GET",
42 redirect: "manual",
43 headers: {
44 ...(token ? { authorization: `Bearer ${token}` } : {}),
45 ...(init.cookie ? { cookie: init.cookie } : {}),
46 ...(init.body ? { "content-type": "application/x-www-form-urlencoded", origin: servers.url } : {}),
47 },
48 ...(init.body ? { body: new URLSearchParams(init.body) } : {}),
49 });
50 const fresh = () => {
51 app.db.exec("DELETE FROM gift_try");
52 resetAnonSpawns(app.db);
53 };
54 const linkOf = (text: string) => /\/gift\/(forge-[a-z0-9]{4}-[a-z0-9]{4})/.exec(text)![0];
55 /** What a stranger's browser does with a link: follow it to the gift page, keeping the cookie. */
56 const open = async (link: string) => {
57 const hop = await fetch(link, { redirect: "manual" });
58 expect(hop.status).toBe(303);
59 expect(hop.headers.get("location")).toBe("/gift");
60 const cookie = hop.headers.get("set-cookie")!;
61 expect(cookie).toContain("HttpOnly");
62 const jar = cookie.split(";")[0]!;
63 const res = await as(undefined, "/gift", { cookie: jar });
64 return { jar, res, text: await res.text() };
65 };
66
67 beforeAll(async () => {
68 dataDir = await mkdtemp(join(tmpdir(), "forge-gifts-"));
69 app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge-code" });
70 servers = await serve(app);
71 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
72 if (!a.ok) throw new Error("user");
73 adminId = a.value.id;
74 const c = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
75 if (!c.ok) throw new Error("user");
76 setMember(app.db, c.value.id, true, a.value.id, new Date(0));
77 carol = createToken(app.db, c.value.id, "admin", "admin").token;
78 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
79 if (!b.ok) throw new Error("user");
80 bob = createToken(app.db, b.value.id, "admin", "admin").token;
81 const code = await createRepo(app, a.value, { name: "forge-code", visibility: "public" });
82 if (!code.ok) throw new Error("repo");
83 await commitToBranch(app, a.value, code.value, { message: "v1", files: [{ path: "src/main.ts", content: "1" }] });
84 // Carol's app is private: only the gift opens it to the friend.
85 const notes = await createRepo(app, c.value, { name: "notes", visibility: "private" });
86 if (!notes.ok) throw new Error("repo " + JSON.stringify(notes.error));
87 await commitToBranch(app, c.value, notes.value, { message: "v1", files: [{ path: "src/main.ts", content: "console.log(1)" }] });
88 // Carol pays for a forge: her email is its payer.
89 putEntitlement(app.db, { forge: "carols", plan: "small", status: "active", source: "checkout", provider: "stripe", payer: "[email protected]" }, "small", "");
90 useProbe(app, () => async () => true);
91 usePlacement(app, { place: async (p) => ok({ url: `https://${p.name}.fake.test`, bodyId: `fake-${p.name}` }), retire: async () => ok() });
92 }, 30_000);
93
94 afterAll(async () => {
95 for (const name of made) await bootHostedChild(app, name);
96 servers.stop();
97 app.close();
98 await rm(dataDir, { recursive: true, force: true });
99 });
100
101 test("only a person with a paid forge is offered a gift", async () => {
102 expect(await (await as(carol, "/")).text()).toContain("Give a friend a forge");
103 expect(await (await as(bob, "/")).text()).not.toContain("Give a friend a forge");
104 expect((await as(bob, "/gifts/make", { method: "POST", body: {} })).status).toBe(404);
105 expect((await as(bob, "/gifts")).status).toBe(404);
106 expect((await as(undefined, "/gifts/make", { method: "POST", body: {} })).status).toBe(404);
107 });
108
109 test("a gift is copied, opened by a stranger, taken with the shared app, shown taken, and refused a second time", async () => {
110 fresh();
111 const res = await as(carol, "/gifts/make", { method: "POST", body: { app: "carol/notes", message: "" } });
112 expect(res.status).toBe(200);
113 expect(res.headers.get("cache-control")).toBe("no-store");
114 const text = await res.text();
115 const link = linkOf(text);
116 expect(text).toContain("I built something I wanted you to have: carol/notes");
117 // Only a hash is kept.
118 expect(JSON.stringify(app.db.query("SELECT * FROM gift_code").all())).not.toContain(link.split("/").pop()!);
119 expect(await (await as(carol, "/gifts")).text()).not.toContain(link.split("/").pop()!);
120
121 const seen = await open(`${servers.url}${link.slice(link.indexOf("/gift/"))}`);
122 expect(seen.res.status).toBe(200);
123 expect(seen.text).toContain("A forge from carol");
124 expect(seen.text).toContain("Start with notes");
125 expect(seen.text).not.toContain("[email protected]");
126
127 made.push("friend-one");
128 const started = await as(undefined, "/gift/start", { method: "POST", cookie: seen.jar, body: { name: "friend-one", showBuilt: "1" } });
129 const startedText = started.status === 200 ? "" : await started.clone().text();
130 expect(startedText.match(/id="gift-error"[^>]*>([^<]*)/)?.[1] ?? "").toBe("");
131 expect(started.status).toBe(200);
132 expect(started.headers.get("cache-control")).toBe("no-store");
133 const e = entitlementOf(app.db, "friend-one", "small");
134 expect(e).toMatchObject({ plan: "small", status: "active" });
135 expect(e.source).toStartWith("code:");
136 expect(e.periodEnd! - Date.now() / 1000).toBeGreaterThan(29 * 86_400);
137 expect(getStored(app.db, "friend-one")?.provider).toBe("none");
138 expect((await childNamed(app, "friend-one"))?.apps).toContain("carol/notes");
139
140 const mine = await (await as(carol, "/gifts")).text();
141 expect(mine).toContain('data-state="taken"');
142 expect(mine).toContain("friend-one");
143 expect(mine).toContain("built carol/notes");
144 expect(await (await as(carol, "/")).text()).toContain("1 of 1 taken");
145
146 // The link works once.
147 fresh();
148 const again = await open(`${servers.url}${link.slice(link.indexOf("/gift/"))}`);
149 expect(again.res.status).toBe(410);
150 expect(again.text).toContain("This gift has already been taken");
151 const second = await as(undefined, "/gift/start", { method: "POST", cookie: again.jar, body: { name: "friend-two" } });
152 expect(second.status).toBe(410);
153 expect(await childNamed(app, "friend-two")).toBeUndefined();
154 });
155
156 test("the funnel counts gifts given, taken and converted; a friend who subscribes thanks the giver once", async () => {
157 let c = funnelReport(app.db, 7).gifts;
158 expect(c).toEqual({ given: 1, taken: 1, converted: 0 });
159 putEntitlement(app.db, { forge: "friend-one", plan: "small", status: "active", source: "checkout", provider: "stripe", payer: "[email protected]" }, "small", "");
160 tellPlan(app, "friend-one");
161 tellPlan(app, "friend-one");
162 c = funnelReport(app.db, 7).gifts;
163 expect(c).toEqual({ given: 1, taken: 1, converted: 1 });
164 expect(app.db.query("SELECT days FROM gift_thanks").all()).toEqual([{ days: 30 }]);
165 expect(await (await as(carol, "/gifts")).text()).toContain("30 days of credit");
166 expect(await (await as(adminToken(), "/settings/billing")).text()).toContain("Gifts that became paying");
167 });
168
169 function adminToken(): string {
170 return createToken(app.db, adminId, "admin2", "admin").token;
171 }
172
173 test("a gift is limited, can be cancelled, and refuses a bad app or message", async () => {
174 fresh();
175 expect((await as(carol, "/gifts/make", { method: "POST", body: { app: "alice/forge-code", message: "" } })).status).toBe(422);
176 expect((await as(carol, "/gifts/make", { method: "POST", body: { app: "", message: "x".repeat(281) } })).status).toBe(422);
177 // One was made already (taken); two more fit under three.
178 for (let i = 0; i < 2; i++) expect((await as(carol, "/gifts/make", { method: "POST", body: {} })).status).toBe(200);
179 const full = await as(carol, "/gifts/make", { method: "POST", body: {} });
180 expect(full.status).toBe(422);
181 expect(await full.text()).toContain("Every gift you have is made");
182 const id = app.db.query<{ id: string }, []>("SELECT id FROM gift_code WHERE kind = 'gift' AND revoked_at IS NULL AND used = 0 LIMIT 1").get()!.id;
183 expect((await as(bob, "/gifts/cancel", { method: "POST", body: { id } })).status).toBe(303);
184 expect(app.db.query("SELECT revoked_at FROM gift_code WHERE id = ?").get(id)).toEqual({ revoked_at: null });
185 expect((await as(carol, "/gifts/cancel", { method: "POST", body: { id } })).status).toBe(303);
186 expect((await as(carol, "/gifts/make", { method: "POST", body: {} })).status).toBe(200);
187 setLimit(app.db, "gifts.per_forge", 0, adminId);
188 expect((await as(carol, "/gifts/make", { method: "POST", body: {} })).status).toBe(422);
189 });
190
191 test("sending an app gives the receiver a copy on a free forge; only a writer may send", async () => {
192 fresh();
193 expect((await as(bob, "/gifts/send", { method: "POST", body: { app: "carol/notes" } })).status).toBe(303);
194 const res = await as(carol, "/gifts/send", { method: "POST", body: { app: "carol/notes" } });
195 expect(res.status).toBe(200);
196 const link = linkOf(await res.text());
197 const seen = await open(`${servers.url}${link.slice(link.indexOf("/gift/"))}`);
198 expect(seen.text).toContain("carol sent you an app");
199 made.push("friend-three");
200 expect((await as(undefined, "/gift/start", { method: "POST", cookie: seen.jar, body: { name: "friend-three" } })).status).toBe(200);
201 expect(entitlementOf(app.db, "friend-three", "small")).toMatchObject({ plan: "free", status: "active" });
202 expect((await childNamed(app, "friend-three"))?.apps).toContain("carol/notes");
203 // A send is not a forge gift: the funnel does not count it.
204 expect(funnelReport(app.db, 7).gifts.given).toBe(3);
205 });
206 });

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

Keyboard shortcuts

Docs