Public: anyone can read this; the crew can change it.
A subscriber gives a friend a forge in one tap, and sees who came #11860
Parked 21d 3h ago
scout/forge:scout/11655-a-subscriber-gives-a-friend-a-forge-in-o → main 4 commits fork
19 files
changed +643
−15
- docs/design/audit.md
- docs/features/gifts.md
- src/actions/codes.ts
- src/actions/gifts.ts
- src/billing/codes.ts
- src/billing/gifts.ts
- src/core/migration-pins/20261112140000-friend-gifts.pin
- src/core/migrations/20261112140000-friend-gifts.ts
- src/core/reserved.ts
- src/http/server.ts
- src/http/settings_routes.ts
- src/settings/gifts.ts
- src/web/pages/billing.ts
- src/web/pages/gifts.ts
- src/web/pages/new-forge.ts
- src/web/studio/home.ts
- test/forge-looks.test.ts
- test/friend-gifts.test.ts
- test/home-living.test.ts
docs/design/audit.md +1
| @@ -69,6 +69,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 69 | 69 | - `/notes` — `pages/notes.ts` · what the person wrote, newest first, with the planner's verdict and live state in one line, and one tap to overrule it · the home tell box (Notes button), the user menu, the palette · none seen; styles in `docs/design/areas/notes.md`. |
| 70 | 70 | - `/pipeline` — `pages/pipeline.ts` · the four steps a change follows (check, review, land, live), for a newcomer · a pull page's step line, `/flow` · none seen. |
| 71 | 71 | - `/packs` — `pages/packs.ts` · the premade forges this forge ships, what each brings, how to deploy it and how a stranger helps build its apps · the user menu, the signed-out menu, the palette · none seen; uses the shared card, list and button components. |
| 72 | - `/gifts` — `pages/gifts.ts` · a subscriber's one-use gift links and who took them · home's Give a friend a forge line · reuses the list and field classes, no private vocabulary. | |
| 72 | 73 | - `/map` — `pages/map.ts` (1,806 lines) · the dependency map of work across the forge · `/board`, issue dependency lists, `/:owner/:name/map` · colours 3, sizes 12: the largest private vocabulary. |
| 73 | 74 | - `/audit` — `pages/audit.ts` · every app's contract, who can do what · the app page's one-line policy · none seen. Names the audit of apps, not this document. |
| 74 | 75 | - `/repos` — `pages/my-repos.ts` · the repositories you may write, from the account menu · `/` (your apps), `/:owner` (a profile's repositories) · none seen. |
docs/features/gifts.md added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | # Gifts from subscribers | |
| 2 | ||
| 3 | A person who pays for a forge can give a friend one (`src/actions/gifts.ts`, `src/billing/gifts.ts`, `src/web/pages/gifts.ts`). A gift is a one-use gift code (`docs/features/billing.md`, *Gift codes*) with a giver, perhaps an app to start with, and a length in days. | |
| 4 | ||
| 5 | - **Who may give:** a signed-in person (not an agent) whose email is the payer of an active, paid entitlement. Anyone else gets a 404 from `/gifts`, and no line on home. | |
| 6 | - **Give:** home's quiet line *Give a friend a forge* → `/gifts` → *Make a gift link*. Optionally pick one of your own public apps ("Start with"), and tick *Let me see what they build*. The link and a message written in your voice are shown once; only a hash is kept. The forge never posts it anywhere. | |
| 7 | - **The friend:** opens the link (the code moves into an HttpOnly cookie, as for any gift), reads "A forge from <name>", and ticks *Start with <app>* (on by default) to get a copy of the shared app in the new forge. The form is the usual new-forge form. A second use says "That code has been used as many times as it allows". | |
| 8 | - **The giver sees:** each gift as waiting, or taken by which forge and when, "now subscribed" once that forge pays for itself, and what the friend built when allowed. Home says how many friends took one. | |
| 9 | - **Settings:** Settings → Billing → *Gifts from subscribers*: gifts held per plan (default 3), the plan a gift gives, and its days (default 30; the entitlement's `periodEnd`). | |
| 10 | - **Funnel:** Settings → Billing counts gifts given, taken and friends now subscribed. | |
| 11 | - **Audit:** `billing.gift.give` and `billing.code.redeem` events. | |
| 12 | ||
| 13 | Not done yet: the thank-you credit to the giver when a friend subscribes, "Send this app" from an app page, and nothing yet ends a gift forge at `periodEnd` (no lapse reads it for a code's forge). |
src/actions/codes.ts +13 −5
| @@ -14,6 +14,7 @@ import { | ||
| 14 | 14 | CODE_WORDS, MAX_NOTE, MAX_USES, insertCode, listCodes, lookupCode, noteRedeemed, |
| 15 | 15 | releaseCode, revokeCode, takeTry, type Code, type CodeRefusal, type Listed, |
| 16 | 16 | } from "../billing/codes.ts"; |
| 17 | import { giverOf } from "../billing/gifts.ts"; | |
| 17 | 18 | import { putEntitlement } from "../billing/store.ts"; |
| 18 | 19 | import type { User } from "../core/users.ts"; |
| 19 | 20 | import { clientBucket } from "../http/peer.ts"; |
| @@ -98,11 +99,17 @@ export function revoke(app: App, actor: User | undefined, id: unknown): Result<{ | ||
| 98 | 99 | export type RedeemRefusal = CodeRefusal | "slow_down"; |
| 99 | 100 | export const REDEEM_WORDS: Record<RedeemRefusal, string> = { ...CODE_WORDS, slow_down: "Too many codes tried from here; try again in a few minutes" }; |
| 100 | 101 | |
| 101 | /** What a visitor sees of a code before using it: that it is a gift, and which plan. The admin is not named. Counts one try for the client. */ | |
| 102 | export function giftOf(app: App, request: Request, input: unknown): Result<{ id: string; plan: string }, RedeemRefusal> { | |
| 102 | /** | |
| 103 | * What a visitor sees of a code before using it: that it is a gift, which plan, and, for a friend's gift, who it is from and the app it opens with. | |
| 104 | * An admin is not named. Counts one try for the client. | |
| 105 | */ | |
| 106 | export function giftOf(app: App, request: Request, input: unknown): Result<{ id: string; plan: string; from?: string; shareApp?: string; days: number }, RedeemRefusal> { | |
| 103 | 107 | if (!takeTry(app.db, clientBucket(request))) return err("slow_down"); |
| 104 | 108 | const seen = lookupCode(app.db, input); |
| 105 | return seen.ok ? ok({ id: seen.value.id, plan: seen.value.plan }) : seen; | |
| 109 | if (!seen.ok) return seen; | |
| 110 | const c = seen.value; | |
| 111 | const from = c.fromUser === undefined ? undefined : giverOf(app.db, c.id); | |
| 112 | return ok({ id: c.id, plan: c.plan, days: c.days, ...(from === undefined ? {} : { from }), ...(c.shareApp === undefined ? {} : { shareApp: c.shareApp }) }); | |
| 106 | 113 | } |
| 107 | 114 | |
| 108 | 115 | /** The forge was not made: the use goes back. */ |
| @@ -112,7 +119,8 @@ export const unclaimGift = (app: App, code: Code): void => releaseCode(app.db, c | ||
| 112 | 119 | export function settleGift(app: App, code: Code, forge: string): void { |
| 113 | 120 | const size = getPlan(app.db, code.plan)?.size ?? "small"; |
| 114 | 121 | noteRedeemed(app.db, code.id, forge); |
| 115 | putEntitlement(app.db, { forge, plan: code.plan, status: "active", source: `code:${code.id}`, provider: "none" }, size, ""); | |
| 122 | const periodEnd = code.days > 0 ? Math.floor(Date.now() / 1000) + code.days * 86_400 : undefined; | |
| 123 | putEntitlement(app.db, { forge, plan: code.plan, status: "active", source: `code:${code.id}`, provider: "none", ...(periodEnd === undefined ? {} : { periodEnd }) }, size, ""); | |
| 116 | 124 | tellPlan(app, forge); |
| 117 | app.bus.append({ kind: "billing.code.redeem", payload: { id: code.id, forge, plan: code.plan } }); | |
| 125 | app.bus.append({ kind: "billing.code.redeem", payload: { id: code.id, forge, plan: code.plan, ...(code.fromUser === undefined ? {} : { from: code.fromUser }) } }); | |
| 118 | 126 | } |
src/actions/gifts.ts added +74
| @@ -0,0 +1,74 @@ | ||
| 1 | /** | |
| 2 | * Gifts from subscribers as they are reached (#11655). A person who holds a | |
| 3 | * paid forge (an active entitlement naming their email as payer) may give a | |
| 4 | * few friends a forge: each gift is a one-use gift code on the plan and for | |
| 5 | * the days the gift settings say (`settings/gifts.ts`). The link is shown | |
| 6 | * once, to the giver, and the forge never posts it anywhere. An agent never | |
| 7 | * gives; anyone who holds nothing is told `not_found`. Every gift made is a | |
| 8 | * `billing.gift.give` event. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { allowance, gaveCount, givenBy, insertGift, type GivenGift } from "../billing/gifts.ts"; | |
| 13 | import { canRead, getRepo, listReposOwnedBy } from "../core/repos.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 16 | import { getGifts } from "../settings/gifts.ts"; | |
| 17 | import { linkFor } from "./codes.ts"; | |
| 18 | ||
| 19 | export type GiftError = "not_found" | "none_left" | "bad_app"; | |
| 20 | ||
| 21 | export const GIFT_ERRORS: Record<Exclude<GiftError, "not_found">, string> = { | |
| 22 | none_left: "You have given all the gifts you have", | |
| 23 | bad_app: "Share one of your own public apps, or none", | |
| 24 | }; | |
| 25 | ||
| 26 | export interface GiftsView { | |
| 27 | readonly allowed: number; | |
| 28 | readonly left: number; | |
| 29 | readonly days: number; | |
| 30 | readonly gifts: readonly GivenGift[]; | |
| 31 | /** The giver's public apps, by `owner/name`, that a gift may open with. */ | |
| 32 | readonly apps: readonly string[]; | |
| 33 | } | |
| 34 | ||
| 35 | const person = (a: User | undefined): a is User => a !== undefined && a.kind === "user"; | |
| 36 | ||
| 37 | /** What a person has to give and what became of it; not_found when they hold no paid forge and have given none. */ | |
| 38 | export function readGifts(app: App, actor: User | undefined): Result<GiftsView, "not_found"> { | |
| 39 | if (!person(actor)) return err("not_found"); | |
| 40 | const s = getGifts(app.db); | |
| 41 | const allowed = allowance(app.db, actor.email, s); | |
| 42 | const gifts = givenBy(app.db, actor.id); | |
| 43 | if (allowed === 0 && gifts.length === 0) return err("not_found"); | |
| 44 | const apps = listReposOwnedBy(app.db, actor.id).filter((r) => r.visibility === "public").map((r) => `${r.ownerName}/${r.name}`); | |
| 45 | return ok({ allowed, left: Math.max(0, allowed - gaveCount(app.db, actor.id)), days: s.days, gifts, apps }); | |
| 46 | } | |
| 47 | ||
| 48 | /** Whether the person holds a paid forge now, so the home says it. */ | |
| 49 | export const mayGive = (app: App, actor: User | undefined): boolean => person(actor) && allowance(app.db, actor.email, getGifts(app.db)) > 0; | |
| 50 | ||
| 51 | /** Give one gift. The plain link is in this answer and nowhere else. */ | |
| 52 | export function giveGift( | |
| 53 | app: App, | |
| 54 | actor: User | undefined, | |
| 55 | input: { app?: unknown; showBuilt?: unknown }, | |
| 56 | origin: string, | |
| 57 | ): Result<{ link: string; days: number; shareApp?: string }, GiftError> { | |
| 58 | if (!person(actor)) return err("not_found"); | |
| 59 | const s = getGifts(app.db); | |
| 60 | if (allowance(app.db, actor.email, s) === 0) return err("not_found"); | |
| 61 | if (gaveCount(app.db, actor.id) >= allowance(app.db, actor.email, s)) return err("none_left"); | |
| 62 | let shareApp: string | undefined; | |
| 63 | if (input.app !== undefined && input.app !== null && input.app !== "") { | |
| 64 | const ref = typeof input.app === "string" && input.app.length <= 120 ? input.app : ""; | |
| 65 | const [o, n, ...rest] = ref.split("/"); | |
| 66 | const repo = o && n && rest.length === 0 ? getRepo(app.db, o, n) : undefined; | |
| 67 | // Only the giver's own, and public: a stranger reads it to start with it. | |
| 68 | if (repo === undefined || repo.ownerId !== actor.id || !canRead(app.db, repo, undefined)) return err("bad_app"); | |
| 69 | shareApp = `${repo.ownerName}/${repo.name}`; | |
| 70 | } | |
| 71 | const made = insertGift(app.db, { fromUser: actor.id, plan: s.plan, days: s.days, ...(shareApp === undefined ? {} : { shareApp }), showBuilt: input.showBuilt === true || input.showBuilt === "on" || input.showBuilt === "1" }); | |
| 72 | app.bus.append({ kind: "billing.gift.give", actorId: actor.id, payload: { id: made.row.id, plan: s.plan, days: s.days, ...(shareApp === undefined ? {} : { app: shareApp }) } }); | |
| 73 | return ok({ link: linkFor(origin, made.code), days: s.days, ...(shareApp === undefined ? {} : { shareApp }) }); | |
| 74 | } |
src/billing/codes.ts +9
| @@ -34,6 +34,11 @@ export interface Code { | ||
| 34 | 34 | readonly revokedAt?: string; |
| 35 | 35 | readonly madeBy: string; |
| 36 | 36 | readonly madeAt: string; |
| 37 | /** A gift from a person (#11655): who, the app shared (`owner/name`), days it lasts (0: no end), whether the giver may see what was built. */ | |
| 38 | readonly fromUser?: string; | |
| 39 | readonly shareApp?: string; | |
| 40 | readonly days: number; | |
| 41 | readonly showBuilt: boolean; | |
| 37 | 42 | } |
| 38 | 43 | |
| 39 | 44 | export interface Redeemed { |
| @@ -44,6 +49,7 @@ export interface Redeemed { | ||
| 44 | 49 | interface Row { |
| 45 | 50 | id: string; plan: string; note: string; uses: number; used: number; expires_at: string | null; |
| 46 | 51 | revoked_at: string | null; made_by: string; made_at: string; |
| 52 | from_user: string | null; share_app: string | null; days: number; show_built: number; | |
| 47 | 53 | } |
| 48 | 54 | |
| 49 | 55 | const fromRow = (r: Row): Code => ({ |
| @@ -51,6 +57,9 @@ const fromRow = (r: Row): Code => ({ | ||
| 51 | 57 | ...(r.expires_at === null ? {} : { expiresAt: r.expires_at }), |
| 52 | 58 | ...(r.revoked_at === null ? {} : { revokedAt: r.revoked_at }), |
| 53 | 59 | madeBy: r.made_by, madeAt: r.made_at, |
| 60 | ...(r.from_user === null ? {} : { fromUser: r.from_user }), | |
| 61 | ...(r.share_app === null ? {} : { shareApp: r.share_app }), | |
| 62 | days: r.days, showBuilt: r.show_built === 1, | |
| 54 | 63 | }); |
| 55 | 64 | |
| 56 | 65 | /** What a person typed, as the code it means: trimmed, lowercased, and of the code's shape, else undefined. */ |
src/billing/gifts.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** | |
| 2 | * Gifts from subscribers (#11655): the store. A gift is a gift code | |
| 3 | * (`billing/codes.ts`) with one use, a giver, perhaps an app to start with, | |
| 4 | * and a length in days. What a person may give, who took it and whether the | |
| 5 | * friend then subscribed are read here as plain data; authorization is in | |
| 6 | * `actions/gifts.ts`. The forge never posts a gift anywhere. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { getCode, insertCode, type Code } from "./codes.ts"; | |
| 11 | import { getStored } from "./store.ts"; | |
| 12 | import { FREE } from "../settings/plans.ts"; | |
| 13 | import { giftsFor, type GiftSettings } from "../settings/gifts.ts"; | |
| 14 | ||
| 15 | /** The paid plans a person holds: forges whose entitlement names them as payer (by email) and is active. */ | |
| 16 | export function heldPlans(db: Database, email: string): string[] { | |
| 17 | if (email === "") return []; | |
| 18 | return db | |
| 19 | .query<{ plan: string }, [string, string]>("SELECT plan FROM entitlement WHERE lower(payer) = lower(?1) AND status = 'active' AND plan != ?2") | |
| 20 | .all(email, FREE) | |
| 21 | .map((r) => r.plan); | |
| 22 | } | |
| 23 | ||
| 24 | export const gaveCount = (db: Database, userId: string): number => | |
| 25 | db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM gift_code WHERE from_user = ?1 AND revoked_at IS NULL").get(userId)!.n; | |
| 26 | ||
| 27 | /** How many gifts this person may give in all: the most any plan they hold gives; 0 when they hold none. */ | |
| 28 | export function allowance(db: Database, email: string, s: GiftSettings): number { | |
| 29 | return Math.max(0, ...heldPlans(db, email).map((p) => giftsFor(s, p))); | |
| 30 | } | |
| 31 | ||
| 32 | export interface NewGift { | |
| 33 | readonly fromUser: string; | |
| 34 | readonly plan: string; | |
| 35 | readonly days: number; | |
| 36 | readonly shareApp?: string; | |
| 37 | readonly showBuilt: boolean; | |
| 38 | } | |
| 39 | ||
| 40 | export function insertGift(db: Database, g: NewGift): { code: string; row: Code } { | |
| 41 | return db.transaction(() => { | |
| 42 | const made = insertCode(db, { plan: g.plan, note: "a friend's gift", uses: 1, madeBy: g.fromUser }); | |
| 43 | db.query("UPDATE gift_code SET from_user = ?2, share_app = ?3, days = ?4, show_built = ?5 WHERE id = ?1").run( | |
| 44 | made.row.id, g.fromUser, g.shareApp ?? null, g.days, g.showBuilt ? 1 : 0, | |
| 45 | ); | |
| 46 | return { code: made.code, row: getCode(db, made.row.id)! }; | |
| 47 | })(); | |
| 48 | } | |
| 49 | ||
| 50 | export interface GivenGift { | |
| 51 | readonly id: string; | |
| 52 | readonly madeAt: string; | |
| 53 | readonly shareApp?: string; | |
| 54 | readonly showBuilt: boolean; | |
| 55 | readonly revoked: boolean; | |
| 56 | /** The forge that took it, when one did. */ | |
| 57 | readonly forge?: string; | |
| 58 | readonly tookAt?: string; | |
| 59 | /** Whether that forge then went on to a paid plan of its own. */ | |
| 60 | readonly subscribed: boolean; | |
| 61 | } | |
| 62 | ||
| 63 | /** Whether a forge a gift made is now paying for itself: its entitlement no longer comes from a code. */ | |
| 64 | export function subscribedSince(db: Database, forge: string): boolean { | |
| 65 | const e = getStored(db, forge); | |
| 66 | return e !== undefined && e.status === "active" && e.plan !== FREE && !e.source.startsWith("code:"); | |
| 67 | } | |
| 68 | ||
| 69 | /** A person's gifts, newest first, each with who took it. */ | |
| 70 | export function givenBy(db: Database, userId: string): GivenGift[] { | |
| 71 | const rows = db | |
| 72 | .query<{ id: string; made_at: string; share_app: string | null; show_built: number; revoked_at: string | null; forge: string | null; at: string | null }, [string]>( | |
| 73 | `SELECT g.id, g.made_at, g.share_app, g.show_built, g.revoked_at, r.forge, r.at | |
| 74 | FROM gift_code g LEFT JOIN gift_redeem r ON r.code_id = g.id | |
| 75 | WHERE g.from_user = ?1 ORDER BY g.made_at DESC, g.rowid DESC LIMIT 100`, | |
| 76 | ) | |
| 77 | .all(userId); | |
| 78 | return rows.map((r) => ({ | |
| 79 | id: r.id, madeAt: r.made_at, showBuilt: r.show_built === 1, revoked: r.revoked_at !== null, | |
| 80 | ...(r.share_app === null ? {} : { shareApp: r.share_app }), | |
| 81 | ...(r.forge === null ? {} : { forge: r.forge }), | |
| 82 | ...(r.at === null ? {} : { tookAt: r.at }), | |
| 83 | subscribed: r.forge !== null && subscribedSince(db, r.forge), | |
| 84 | })); | |
| 85 | } | |
| 86 | ||
| 87 | /** The giver's name for a gift, shown to the friend. */ | |
| 88 | export function giverOf(db: Database, codeId: string): string | undefined { | |
| 89 | return db | |
| 90 | .query<{ username: string }, [string]>("SELECT u.username FROM gift_code g JOIN user u ON u.id = g.from_user WHERE g.id = ?1") | |
| 91 | .get(codeId)?.username; | |
| 92 | } | |
| 93 | ||
| 94 | export interface GiftCounts { readonly given: number; readonly taken: number; readonly converted: number } | |
| 95 | ||
| 96 | /** The funnel's three numbers, over every subscriber gift. */ | |
| 97 | export function giftCounts(db: Database): GiftCounts { | |
| 98 | const given = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM gift_code WHERE from_user IS NOT NULL").get()!.n; | |
| 99 | const took = db | |
| 100 | .query<{ forge: string }, []>("SELECT r.forge FROM gift_redeem r JOIN gift_code g ON g.id = r.code_id WHERE g.from_user IS NOT NULL") | |
| 101 | .all(); | |
| 102 | return { given, taken: took.length, converted: took.filter((t) => subscribedSince(db, t.forge)).length }; | |
| 103 | } |
src/core/migration-pins/20261112140000-friend-gifts.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 081e9efb1e6ee404287ddc725068cfe5509c52e618640ccbf2d10c98ddfb23dc |
src/core/migrations/20261112140000-friend-gifts.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | // Gifts from subscribers (#11655): a gift code may come from a person (`from_user`), carry an app the | |
| 2 | // giver shares (`share_app`, `owner/name`), give a forge for `days` days (0: no end), and let the | |
| 3 | // giver see what the friend built (`show_built`). Additive columns on `gift_code`; an index so the | |
| 4 | // giver's list and their count read by `from_user`. | |
| 5 | export default ` | |
| 6 | ALTER TABLE gift_code ADD COLUMN from_user TEXT; | |
| 7 | ALTER TABLE gift_code ADD COLUMN share_app TEXT; | |
| 8 | ALTER TABLE gift_code ADD COLUMN days INTEGER NOT NULL DEFAULT 0; | |
| 9 | ALTER TABLE gift_code ADD COLUMN show_built INTEGER NOT NULL DEFAULT 0; | |
| 10 | CREATE INDEX gift_code_from ON gift_code (from_user, made_at); | |
| 11 | `; |
src/core/reserved.ts +1
src/http/server.ts +3
| @@ -286,6 +286,7 @@ import { firstAdminOptions, firstAdminPage, firstAdminSubmit } from "../web/page | ||
| 286 | 286 | import { familyPage } from "../web/pages/family.ts"; |
| 287 | 287 | import { forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit, |
| 288 | 288 | forgeOwnCodeSubmit, forgesPage } from "../web/pages/forges.ts"; |
| 289 | import { giftsMake, giftsPage } from "../web/pages/gifts.ts"; | |
| 289 | 290 | import { forgesRefusedPage } from "../web/pages/forges-refused.ts"; |
| 290 | 291 | import { forgeItSubmit } from "../web/pages/forge-it.ts"; |
| 291 | 292 | import { funnelSubmit } from "./funnel.ts"; |
| @@ -883,6 +884,8 @@ export function buildRouter(): Router<Handler> { | ||
| 883 | 884 | router.add("GET", "/pricing/resend", resendPage); |
| 884 | 885 | router.add("POST", "/pricing/resend", resendSubmit); |
| 885 | 886 | router.add("GET", "/forges/:name/waiting", forgeWaitingPage); |
| 887 | router.add("GET", "/gifts", giftsPage); | |
| 888 | router.add("POST", "/gifts", giftsMake); | |
| 886 | 889 | router.add("GET", "/forges/new", newForgePage); |
| 887 | 890 | router.add("POST", "/forges/new", newForgeSubmit); |
| 888 | 891 | router.add("POST", "/forges/start", startForgeSubmit); |
src/http/settings_routes.ts +2 −1
| @@ -19,7 +19,7 @@ import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts | ||
| 19 | 19 | import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts"; |
| 20 | 20 | import { flagsPage, flagsSet } from "../web/pages/flags.ts"; |
| 21 | 21 | import { appTemplatesPage, appTemplatesSet } from "../web/pages/app_templates.ts"; |
| 22 | import { billingPage, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; | |
| 22 | import { billingPage, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, billingSetGifts, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; | |
| 23 | 23 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 24 | 24 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 25 | 25 | import { usagePage } from "../web/pages/usage.ts"; |
| @@ -220,6 +220,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 220 | 220 | router.add("POST", "/settings/billing/stripe/secret", stripeSecret); |
| 221 | 221 | router.add("POST", "/settings/billing/stripe/disconnect", stripeDisconnect); |
| 222 | 222 | router.add("POST", "/settings/billing/orders/retry", orderRetry); |
| 223 | router.add("POST", "/settings/billing/gifts", billingSetGifts); | |
| 223 | 224 | router.add("POST", "/settings/billing/codes", billingMakeCode); |
| 224 | 225 | router.add("POST", "/settings/billing/codes/revoke", billingRevokeCode); |
| 225 | 226 | router.add("GET", "/settings/flags", flagsPage); |
src/settings/gifts.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | /** | |
| 2 | * What a subscriber may give (#11655), as a setting, never a constant: how | |
| 3 | * many gifts each plan holds (default 3), the plan a gift gives and for how | |
| 4 | * many days. Kept as one JSON value in `forge_setting` under `gifts`; a | |
| 5 | * stored value that does not parse reads as the defaults. Pure data; | |
| 6 | * authorization is in `actions/gifts.ts`. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | import { writeSetting } from "./limits.ts"; | |
| 12 | import { FREE, getPlan, getPlans } from "./plans.ts"; | |
| 13 | ||
| 14 | export const GIFTS_KEY = "gifts"; | |
| 15 | export const DEFAULT_GIFTS = 3; | |
| 16 | export const MAX_GIFTS = 100; | |
| 17 | export const MAX_DAYS = 366; | |
| 18 | ||
| 19 | export interface GiftSettings { | |
| 20 | /** Gifts each paid plan holds; a plan not named holds `DEFAULT_GIFTS`. */ | |
| 21 | readonly perPlan: Readonly<Record<string, number>>; | |
| 22 | /** The plan a gift gives. */ | |
| 23 | readonly plan: string; | |
| 24 | /** How long it lasts, in days. */ | |
| 25 | readonly days: number; | |
| 26 | } | |
| 27 | ||
| 28 | export const DEFAULTS: GiftSettings = { perPlan: {}, plan: "small", days: 30 }; | |
| 29 | ||
| 30 | const whole = (v: unknown, min: number, max: number): number | undefined => { | |
| 31 | const n = typeof v === "string" && /^\d{1,4}$/.test(v.trim()) ? Number(v) : v; | |
| 32 | return typeof n === "number" && Number.isInteger(n) && n >= min && n <= max ? n : undefined; | |
| 33 | }; | |
| 34 | ||
| 35 | /** Settings from untrusted input, or the sentence that says what is wrong. */ | |
| 36 | export function parseGifts(db: Database, raw: unknown): Result<GiftSettings, string> { | |
| 37 | if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return err("gift settings are an object"); | |
| 38 | const r = raw as Record<string, unknown>; | |
| 39 | const plans = getPlans(db).filter((p) => p.key !== FREE); | |
| 40 | const perPlan: Record<string, number> = {}; | |
| 41 | const given = typeof r["perPlan"] === "object" && r["perPlan"] !== null ? (r["perPlan"] as Record<string, unknown>) : {}; | |
| 42 | for (const p of plans) { | |
| 43 | if (given[p.key] === undefined || given[p.key] === "") continue; | |
| 44 | const n = whole(given[p.key], 0, MAX_GIFTS); | |
| 45 | if (n === undefined) return err(`${p.key}: gifts is a whole number from 0 to ${MAX_GIFTS}`); | |
| 46 | perPlan[p.key] = n; | |
| 47 | } | |
| 48 | const plan = typeof r["plan"] === "string" ? getPlan(db, r["plan"]) : undefined; | |
| 49 | if (plan === undefined || plan.key === FREE) return err("a gift gives one of the paid plans"); | |
| 50 | const days = whole(r["days"], 1, MAX_DAYS); | |
| 51 | if (days === undefined) return err(`a gift lasts a whole number of days from 1 to ${MAX_DAYS}`); | |
| 52 | return ok({ perPlan, plan: plan.key, days }); | |
| 53 | } | |
| 54 | ||
| 55 | /** The settings in force now; anything stored that no longer parses reads as the defaults. */ | |
| 56 | export function getGifts(db: Database): GiftSettings { | |
| 57 | const row = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(GIFTS_KEY); | |
| 58 | if (row !== null) { | |
| 59 | try { | |
| 60 | const parsed = parseGifts(db, JSON.parse(row.value)); | |
| 61 | if (parsed.ok) return parsed.value; | |
| 62 | } catch { | |
| 63 | // a hand-edited value reads as the defaults | |
| 64 | } | |
| 65 | } | |
| 66 | return DEFAULTS; | |
| 67 | } | |
| 68 | ||
| 69 | export const giftsFor = (s: GiftSettings, plan: string): number => s.perPlan[plan] ?? DEFAULT_GIFTS; | |
| 70 | ||
| 71 | export function setGifts(db: Database, raw: unknown, actorId: string): Result<GiftSettings, string> { | |
| 72 | const parsed = parseGifts(db, raw); | |
| 73 | if (!parsed.ok) return parsed; | |
| 74 | writeSetting(db, GIFTS_KEY, JSON.stringify(parsed.value), JSON.stringify(getGifts(db)), JSON.stringify(parsed.value), actorId); | |
| 75 | return parsed; | |
| 76 | } |
src/web/pages/billing.ts +38 −3
| @@ -19,6 +19,8 @@ import { SIZES } from "../../spawn/sizes.ts"; | ||
| 19 | 19 | import { BILLING_SIZES, getPortalUrl, PORTAL_WORDS, parseBillingLinks } from "../../settings/billing.ts"; |
| 20 | 20 | import { getPlans } from "../../settings/plans.ts"; |
| 21 | 21 | import { changeBillingLinks, changePortalUrl, readBillingLinks } from "../../actions/signup.ts"; |
| 22 | import { giftCounts, type GiftCounts } from "../../billing/gifts.ts"; | |
| 23 | import { getGifts, setGifts, giftsFor } from "../../settings/gifts.ts"; | |
| 22 | 24 | import { funnelReport, type FunnelReport } from "../../perf/funnel.ts"; |
| 23 | 25 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; |
| 24 | 26 | import { field, readForm } from "../form.ts"; |
| @@ -152,7 +154,7 @@ export async function billingSetLinks(ctx: Ctx): Promise<Response> { | ||
| 152 | 154 | } |
| 153 | 155 | |
| 154 | 156 | /** Last 7 days, from visit to paid: one `dl` row per step with its share of the step before; clicks by plan and where they came from as rows under it. */ |
| 155 | function funnelRow(r: FunnelReport): Html { | |
| 157 | function funnelRow(r: FunnelReport, gifts: GiftCounts): Html { | |
| 156 | 158 | const row = (label: string, value: string): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`; |
| 157 | 159 | return html`<section class="settings-block" id="funnel"> |
| 158 | 160 | <h2>Last 7 days: from visit to paid</h2> |
| @@ -160,6 +162,9 @@ function funnelRow(r: FunnelReport): Html { | ||
| 160 | 162 | ${r.steps.map((s) => row(s.label, s.pct === null ? `${s.count}` : `${s.count} · ${s.pct}% of the step before`))} |
| 161 | 163 | ${r.clicks_by_plan.map((c) => row(`Clicked ${c.plan}`, `${c.count}`))} |
| 162 | 164 | ${r.referrers.map((x) => row(`Plan clicks from ${x.source}`, `${x.count}`))} |
| 165 | ${row("Gifts given", `${gifts.given}`)} | |
| 166 | ${row("Gifts taken", `${gifts.taken}`)} | |
| 167 | ${row("Friends now subscribed", `${gifts.converted}`)} | |
| 163 | 168 | </dl> |
| 164 | 169 | </section>`; |
| 165 | 170 | } |
| @@ -179,7 +184,7 @@ export function billingPage(ctx: Ctx): Response { | ||
| 179 | 184 | return billingView(ctx); |
| 180 | 185 | } |
| 181 | 186 | |
| 182 | function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {}, error?: string, status = 200, links?: { values: Record<string, string>; error: string }, portal?: { value: string; error: string }): Response { | |
| 187 | function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {}, error?: string, status = 200, links?: { values: Record<string, string>; error: string }, portal?: { value: string; error: string }, giftsError?: string): Response { | |
| 183 | 188 | const read = readBilling(ctx.app, ctx.auth.user); |
| 184 | 189 | if (!read.ok) return notFoundPage(ctx); |
| 185 | 190 | const b = read.value; |
| @@ -246,7 +251,8 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = { | ||
| 246 | 251 | : html`<ul class="list setting-list">${rows}</ul>`} |
| 247 | 252 | </section> |
| 248 | 253 | ${ledBlock(ctx)} |
| 249 | ${funnelRow(funnelReport(ctx.app.db, 7))} | |
| 254 | ${funnelRow(funnelReport(ctx.app.db, 7), giftCounts(ctx.app.db))} | |
| 255 | ${giftSettingsSection(ctx, giftsError)} | |
| 250 | 256 | ${linksSection(ctx, links)} |
| 251 | 257 | ${portalSection(ctx, portal)} |
| 252 | 258 | ${codesSection(ctx, shown, values, error)}`; |
| @@ -334,3 +340,32 @@ export async function orderRetry(ctx: Ctx): Promise<Response> { | ||
| 334 | 340 | if (!r.ok) return r.error === "not_found" ? notFoundPage(ctx) : flashTo(ctx, PATH, { tone: "danger", message: "That order is not waiting for a retry." }); |
| 335 | 341 | return flashTo(ctx, PATH, r.value.state === "spawned" ? { message: `${r.value.name} is made.` } : { tone: "danger", message: `${r.value.name} still could not be made: ${r.value.reason}.` }); |
| 336 | 342 | } |
| 343 | ||
| 344 | /** What a subscriber may give: the gifts each paid plan holds, the plan a gift gives and for how many days. */ | |
| 345 | function giftSettingsSection(ctx: Ctx, error?: string): Html | null { | |
| 346 | if (!isPerson(ctx)) return null; | |
| 347 | const s = getGifts(ctx.app.db); | |
| 348 | return html`<section class="settings-block" id="gift-settings"> | |
| 349 | <h2>Gifts from subscribers</h2> | |
| 350 | <p class="muted small">Each person who pays for a forge may give a friend a forge: a link that works once.</p> | |
| 351 | ${error === undefined ? null : html`<p class="error" role="alert">${error}</p>`} | |
| 352 | <form class="stack" method="post" action="${PATH}/gifts"> | |
| 353 | ${getPlans(ctx.app.db).filter((p) => p.key !== "free").map((p) => formField({ label: `Gifts held by ${p.name}`, name: `count_${p.key}`, type: "number", value: String(giftsFor(s, p.key)) }))} | |
| 354 | ${selectField({ label: "A gift gives", name: "plan", options: getPlans(ctx.app.db).filter((p) => p.key !== "free").map((p) => ({ value: p.key, label: p.name, ...(p.key === s.plan ? { selected: true } : {}) })) })} | |
| 355 | ${formField({ label: "For how many days", name: "days", type: "number", value: String(s.days) })} | |
| 356 | ${btn("Save gift settings", { variant: "primary" })} | |
| 357 | </form> | |
| 358 | </section>`; | |
| 359 | } | |
| 360 | ||
| 361 | // POST /settings/billing/gifts | |
| 362 | export async function billingSetGifts(ctx: Ctx): Promise<Response> { | |
| 363 | if (!isPerson(ctx)) return notFoundPage(ctx); | |
| 364 | const form = await readForm(ctx, "admin"); | |
| 365 | if (form instanceof Response) return form; | |
| 366 | const perPlan: Record<string, string> = {}; | |
| 367 | for (const p of getPlans(ctx.app.db)) perPlan[p.key] = field(form, `count_${p.key}`); | |
| 368 | const set = setGifts(ctx.app.db, { perPlan, plan: field(form, "plan"), days: field(form, "days") }, ctx.auth.user!.id); | |
| 369 | if (!set.ok) return billingView(ctx, undefined, {}, undefined, 422, undefined, undefined, `${set.error}. Nothing was saved.`); | |
| 370 | return flashTo(ctx, `${PATH}-settings`, { message: "Gift settings saved." }); | |
| 371 | } |
src/web/pages/gifts.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * `/gifts` (#11655): a subscriber's gifts. The path: someone who pays for a | |
| 3 | * forge wants a friend to have one, in one tap, and to see that the friend | |
| 4 | * came. The page gives a link (shown once) with a message already written, | |
| 5 | * lists each gift as taken or waiting, and says what the friend built when | |
| 6 | * the friend allowed it. Nothing is posted anywhere by the forge. | |
| 7 | */ | |
| 8 | ||
| 9 | import { GIFT_ERRORS, giveGift, mayGive, readGifts, type GiftsView } from "../../actions/gifts.ts"; | |
| 10 | import { givenBy } from "../../billing/gifts.ts"; | |
| 11 | import { listChildrenNow } from "../../actions/spawn.ts"; | |
| 12 | import { publicOrigin } from "../../core/public_origin.ts"; | |
| 13 | import type { User } from "../../core/users.ts"; | |
| 14 | import type { App } from "../../app.ts"; | |
| 15 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 16 | import type { Ctx } from "../../http/context.ts"; | |
| 17 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 18 | import { field, readForm } from "../form.ts"; | |
| 19 | import { html, type Html } from "../html.ts"; | |
| 20 | import { page } from "../layout.ts"; | |
| 21 | import { btn, copyField, time } from "../ui.ts"; | |
| 22 | ||
| 23 | /** What the friend gets to read, in the giver's voice; the giver may edit it before sending. */ | |
| 24 | export const messageFor = (days: number, link: string, shareApp?: string): string => | |
| 25 | `I'm giving you a forge, free for ${days} days${shareApp === undefined ? "" : `, with ${shareApp.split("/")[1]} already on it`}. Open it and start: ${link}`; | |
| 26 | ||
| 27 | /** The one quiet line on the forge's home; nothing for a person with no gift to give. */ | |
| 28 | export function giveLine(ctx: Ctx, user: User): Html | null { | |
| 29 | if (!mayGive(ctx.app, user)) return null; | |
| 30 | const taken = givenBy(ctx.app.db, user.id).filter((g) => g.forge !== undefined).length; | |
| 31 | return html`<p class="small muted" id="give-a-forge"><a href="/gifts">Give a friend a forge</a>${taken === 0 ? null : html` · ${taken === 1 ? "1 friend has taken one" : `${taken} friends have taken one`}`}</p>`; | |
| 32 | } | |
| 33 | ||
| 34 | function builtBy(app: App, forge: string): string { | |
| 35 | const apps = listChildrenNow(app).find((c) => c.name === forge)?.apps ?? []; | |
| 36 | return apps.length === 0 ? "nothing yet" : apps.join(", "); | |
| 37 | } | |
| 38 | ||
| 39 | function view(ctx: Ctx, v: GiftsView, made?: { link: string; days: number; shareApp?: string }, error?: string, status = 200): Response { | |
| 40 | const rows = v.gifts.map((g) => { | |
| 41 | const state = | |
| 42 | g.forge === undefined | |
| 43 | ? g.revoked ? "cancelled" : "waiting for a friend" | |
| 44 | : html`taken by <b>${g.forge}</b> ${time(g.tookAt!)}${g.subscribed ? " · now subscribed" : ""}${g.showBuilt ? html` · built: ${builtBy(ctx.app, g.forge)}` : null}`; | |
| 45 | return html`<li data-gift="${g.id}">${state}${g.shareApp === undefined ? null : html` · opens with ${g.shareApp}`}</li>`; | |
| 46 | }); | |
| 47 | const body = html`<div class="page-head"><h1>Give a friend a forge</h1></div> | |
| 48 | <p class="muted small" id="gift-left">You have ${v.left} of ${v.allowed} gifts left. Each is a link that works once and gives a forge for ${v.days} days.</p> | |
| 49 | ${error === undefined ? null : html`<p class="error" role="alert">${error}</p>`} | |
| 50 | ${made === undefined | |
| 51 | ? null | |
| 52 | : html`<section class="stack" id="gift-made" aria-label="Your gift"> | |
| 53 | <p>This link works once and is shown only now. Send it to one friend.</p> | |
| 54 | ${copyField("gift-link", made.link, "The link", "Copy the link")} | |
| 55 | ${copyField("gift-message", messageFor(made.days, made.link, made.shareApp), "A message to send with it", "Copy the message", { lines: 3 })} | |
| 56 | </section>`} | |
| 57 | ${v.left === 0 | |
| 58 | ? null | |
| 59 | : html`<form class="stack" method="post" action="/gifts"> | |
| 60 | <label class="field"><span class="label">Start them with one of your apps (optional)</span> | |
| 61 | <select class="input" name="app"><option value="">Nothing: a blank forge</option>${v.apps.map((a) => html`<option value="${a}">${a}</option>`)}</select> | |
| 62 | </label> | |
| 63 | <label class="check"><input type="checkbox" name="showBuilt" value="1" /> Let me see what they build</label> | |
| 64 | ${btn("Make a gift link", { variant: "primary" })} | |
| 65 | </form>`} | |
| 66 | ${rows.length === 0 ? null : html`<h2 class="small muted mt">Your gifts</h2><ul class="list" id="gifts">${rows}</ul>`}`; | |
| 67 | const res = page({ ctx, title: "Give a friend a forge", body }, status); | |
| 68 | // A link just made is in this body only: never kept by a cache. | |
| 69 | res.headers.set("cache-control", "no-store"); | |
| 70 | return res; | |
| 71 | } | |
| 72 | ||
| 73 | // GET /gifts | |
| 74 | export function giftsPage(ctx: Ctx): Response { | |
| 75 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 76 | return timePhase(ctx.request, "render", () => { | |
| 77 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 78 | const v = readGifts(ctx.app, ctx.auth.user); | |
| 79 | return v.ok ? view(ctx, v.value) : notFoundPage(ctx); | |
| 80 | }); | |
| 81 | } | |
| 82 | ||
| 83 | // POST /gifts | |
| 84 | export async function giftsMake(ctx: Ctx): Promise<Response> { | |
| 85 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 86 | const form = await readForm(ctx, "admin"); | |
| 87 | if (form instanceof Response) return form; | |
| 88 | const made = giveGift(ctx.app, ctx.auth.user, { app: field(form, "app"), showBuilt: field(form, "showBuilt") }, publicOrigin(ctx.app.config.url, ctx.url.origin)); | |
| 89 | const v = readGifts(ctx.app, ctx.auth.user); | |
| 90 | if (!v.ok) return notFoundPage(ctx); | |
| 91 | if (made.ok) return view(ctx, v.value, made.value); | |
| 92 | if (made.error === "not_found") return notFoundPage(ctx); | |
| 93 | return view(ctx, v.value, undefined, `${GIFT_ERRORS[made.error]}.`, 422); | |
| 94 | } |
src/web/pages/new-forge.ts +21 −4
| @@ -219,6 +219,7 @@ function formView( | ||
| 219 | 219 | <section class="settings-block"> |
| 220 | 220 | <h2>Its name and apps</h2> |
| 221 | 221 | <form method="post" action="/forges/new" class="stack" id="new-forge" data-js> |
| 222 | ${values.apps.filter((a) => !repos.some((r) => `${r.ownerName}/${r.name}` === a)).map((a) => html`<input type="hidden" name="apps" value="${a}" />`)} | |
| 222 | 223 | ${formField({ |
| 223 | 224 | label: "Name", |
| 224 | 225 | name: "name", |
| @@ -429,9 +430,19 @@ function planView(ctx: Ctx, user: User | undefined, values: Values, body: Record | ||
| 429 | 430 | </section>`; |
| 430 | 431 | } |
| 431 | 432 | |
| 433 | /** A friend's gift says who it is from and, when the giver shared an app, offers to start with it (ticked; one tap to leave it). */ | |
| 434 | function friendGift(g: { plan: string; from?: string; shareApp?: string; days: number }, ticked = true): Html { | |
| 435 | const app = g.shareApp?.split("/")[1]; | |
| 436 | return html`<div class="stack stack-tight" id="gift" role="status"> | |
| 437 | ${g.from === undefined ? null : html`<p><b>A forge from ${g.from}</b></p>`} | |
| 438 | <p class="small"><b>${giftWords(g)}</b></p> | |
| 439 | ${g.shareApp === undefined ? null : html`<label class="check"><input type="checkbox" form="new-forge" name="apps" value="${g.shareApp}" ${ticked ? html`checked` : null} /> Start with <b>${app}</b></label>`} | |
| 440 | </div>`; | |
| 441 | } | |
| 442 | ||
| 432 | 443 | /** "A gift: a <plan> forge, free." */ |
| 433 | function giftWords(g: { plan: string }): string { | |
| 434 | return `A gift: a ${g.plan} forge, free.`; | |
| 444 | function giftWords(g: { plan: string; days?: number }): string { | |
| 445 | return g.days === undefined || g.days === 0 ? `A gift: a ${g.plan} forge, free.` : `A gift: a ${g.plan} forge, free for ${g.days} days.`; | |
| 435 | 446 | } |
| 436 | 447 | |
| 437 | 448 | function giftLine(g: unknown): Html | null { |
| @@ -499,6 +510,12 @@ function fromPack(ctx: Ctx, user: User | undefined): Partial<Values> { | ||
| 499 | 510 | return { apps, direction: pack.brief.slice(0, MAX_DIRECTION_CHARS) }; |
| 500 | 511 | } |
| 501 | 512 | |
| 513 | /** The friend's gift block again after the door refused something else: the code is read without spending a try on a bad one. */ | |
| 514 | function keptFriendGift(ctx: Ctx, code: string, apps: readonly string[]): Html | null { | |
| 515 | const seen = code === "" ? undefined : giftOf(ctx.app, ctx.request, code); | |
| 516 | return seen?.ok ? friendGift(seen.value, seen.value.shareApp !== undefined && apps.includes(seen.value.shareApp)) : null; | |
| 517 | } | |
| 518 | ||
| 502 | 519 | // GET /forges/new — any signed-in person, or a stranger (agents are refused). |
| 503 | 520 | export function newForgePage(ctx: Ctx): Response { |
| 504 | 521 | const user = ctx.auth.user; |
| @@ -513,7 +530,7 @@ export function newForgePage(ctx: Ctx): Response { | ||
| 513 | 530 | const code = keptGift(ctx.request); |
| 514 | 531 | const seen = code === "" ? undefined : giftOf(ctx.app, ctx.request, code); |
| 515 | 532 | const errors: Errors = seen !== undefined && !seen.ok ? { code: `${REDEEM_WORDS[seen.error]}.` } : {}; |
| 516 | const gift = seen?.ok ? html`<p class="small" id="gift" role="status"><b>${giftWords(seen.value)}</b></p>` : null; | |
| 533 | const gift = seen?.ok ? friendGift(seen.value) : null; | |
| 517 | 534 | const response = page({ |
| 518 | 535 | ctx, |
| 519 | 536 | title: "New forge", |
| @@ -572,7 +589,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 572 | 589 | { |
| 573 | 590 | ctx, |
| 574 | 591 | title: "New forge", |
| 575 | body: formView(ctx, user, values, errorsOf(door), null, readsFor(ctx, user)), | |
| 592 | body: formView(ctx, user, values, errorsOf(door), keptFriendGift(ctx, values.code, values.apps), readsFor(ctx, user)), | |
| 576 | 593 | }, |
| 577 | 594 | door.status === 422 ? 422 : door.status, |
| 578 | 595 | ); |
src/web/studio/home.ts +3 −1
| @@ -73,6 +73,7 @@ import { needsYouSection } from "./asks_page.ts"; | ||
| 73 | 73 | import { flowCards } from "./flow_card.ts"; |
| 74 | 74 | import { composer, feedJs, feedNote, feedRegion, registerWorkerJs } from "./feed.ts"; |
| 75 | 75 | import { heldLine } from "./held.ts"; |
| 76 | import { giveLine } from "../pages/gifts.ts"; | |
| 76 | 77 | import { interruptedOutLine } from "./interrupted_out.ts"; |
| 77 | 78 | import { appChips, movingRegion, tellBox } from "./living.ts"; |
| 78 | 79 | import { alarmLines, cachedAlarms } from "./alarm_lines.ts"; |
| @@ -328,7 +329,7 @@ export async function studioHome( | ||
| 328 | 329 | // Before the first tell the card is the one box and carries the key line and the composer. |
| 329 | 330 | const firstTell = steps.some((s) => s.key === "tell" && !s.done); |
| 330 | 331 | const lean = html`<h1 class="sr-only">Home</h1> |
| 331 | ${firstSteps} ${address} ${firstTell ? null : crewKeyCard(ctx)} ${heldLine(ctx, user)} ${apps} | |
| 332 | ${firstSteps} ${address} ${firstTell ? null : crewKeyCard(ctx)} ${heldLine(ctx, user)} ${giveLine(ctx, user)} ${apps} | |
| 332 | 333 | <div class="stack"> |
| 333 | 334 | ${firstTell ? null : composer(ctx, user)} |
| 334 | 335 | <p class="small muted"> |
| @@ -381,6 +382,7 @@ export async function studioHome( | ||
| 381 | 382 | ${when(String(since).trim() !== "", () => html`<section aria-label="Since you were here">${since}</section>`)} |
| 382 | 383 | <section aria-label="Live">${timePhase(ctx.request, "moving", () => movingRegion(ctx.app.db, user))}</section> |
| 383 | 384 | ${homeMilestones(ctx, mine)} |
| 385 | ${giveLine(ctx, user)} | |
| 384 | 386 | <section class="stack" aria-label="The forge">${kpis}</section> |
| 385 | 387 | ${pinnedSlot(ctx.app.db, user)} |
| 386 | 388 | ${appChips(ctx, user, mine)} |
test/forge-looks.test.ts +1
| @@ -20,6 +20,7 @@ quietLogs(); | ||
| 20 | 20 | |
| 21 | 21 | /** Top-level routes that are not pages, or are not worth a picture, and why. */ |
| 22 | 22 | const NOT_A_PAGE: Record<string, string> = { |
| 23 | "/gifts": "no picture: the cap of 24 looks is spent; a signed-out reader is sent to sign in, and the page is covered by test/friend-gifts.test.ts", | |
| 23 | 24 | "/pricing": "no picture: the cap of 24 looks is spent; the page is covered by test/pricing-order.test.ts", |
| 24 | 25 | "/audit": "no picture: its slot went to /pinned; /audit.csv is its download, covered by test/audit.test.ts", |
| 25 | 26 | "/deploy-to": "a form for a forge admin that fills from its link; covered by test/pinned-page.test.ts", |
test/friend-gifts.test.ts added +177
| @@ -0,0 +1,177 @@ | ||
| 1 | /** | |
| 2 | * Gifts from subscribers (#11655): a person who holds a paid forge makes a | |
| 3 | * one-use link; a stranger opens it, sees who it is from, starts a forge with | |
| 4 | * the shared app; the giver sees it taken; a second use is refused plainly; | |
| 5 | * the funnel counts it. A person with no paid forge has no gifts, and the | |
| 6 | * allowance is a setting. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { listChildrenNow } from "../src/actions/spawn.ts"; | |
| 15 | import { putEntitlement } from "../src/billing/store.ts"; | |
| 16 | import { giftCounts } from "../src/billing/gifts.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 { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { bootHostedChild } from "../src/spawn/host.ts"; | |
| 22 | import { usePlacement, useProbe } from "../src/spawn/door.ts"; | |
| 23 | import { resetAnonSpawns } from "../src/spawn/rate.ts"; | |
| 24 | import { setGifts } from "../src/settings/gifts.ts"; | |
| 25 | import { promote } from "./helpers/members.ts"; | |
| 26 | import { quietLogs } from "./helpers/globals.ts"; | |
| 27 | ||
| 28 | quietLogs(); | |
| 29 | ||
| 30 | describe("gifts from subscribers", () => { | |
| 31 | let dataDir: string; | |
| 32 | let app: App; | |
| 33 | let servers: Servers; | |
| 34 | let admin = ""; | |
| 35 | let sam = ""; | |
| 36 | let nobody = ""; | |
| 37 | let adminId = ""; | |
| 38 | const made: string[] = []; | |
| 39 | ||
| 40 | const get = (path: string, token?: string, cookie?: string) => | |
| 41 | fetch(`${servers.url}${path}`, { redirect: "manual", headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(cookie ? { cookie } : {}) } }); | |
| 42 | const form = (path: string, token: string | undefined, fields: Record<string, string | string[]>, cookie?: string) => { | |
| 43 | const body = new URLSearchParams(); | |
| 44 | for (const [k, v] of Object.entries(fields)) for (const x of Array.isArray(v) ? v : [v]) body.append(k, x); | |
| 45 | return fetch(`${servers.url}${path}`, { | |
| 46 | method: "POST", | |
| 47 | redirect: "manual", | |
| 48 | headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(cookie ? { cookie } : {}), "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 49 | body, | |
| 50 | }); | |
| 51 | }; | |
| 52 | const giveLink = async (fields: Record<string, string> = {}) => { | |
| 53 | const res = await form("/gifts", sam, fields); | |
| 54 | expect(res.status).toBe(200); | |
| 55 | const text = await res.text(); | |
| 56 | const link = /value="([^"]*\/\?code=forge-[a-z0-9-]+)"/.exec(text)?.[1]; | |
| 57 | expect(link).toBeDefined(); | |
| 58 | return { link: link!, text }; | |
| 59 | }; | |
| 60 | const open = async (link: string) => { | |
| 61 | const res = await fetch(link, { redirect: "manual" }); | |
| 62 | expect(res.status).toBe(303); | |
| 63 | return res.headers.get("set-cookie")!.split(";")[0]!; | |
| 64 | }; | |
| 65 | ||
| 66 | beforeAll(async () => { | |
| 67 | dataDir = await mkdtemp(join(tmpdir(), "forge-friend-gift-")); | |
| 68 | app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge-code" }); | |
| 69 | servers = await serve(app); | |
| 70 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 71 | if (!a.ok) throw new Error("user"); | |
| 72 | adminId = a.value.id; | |
| 73 | admin = createToken(app.db, a.value.id, "admin", "admin").token; | |
| 74 | const s = await createUser(app.db, { origin: "seed", trusted: true, username: "sam", email: "[email protected]", password: "a-good-passphrase" }); | |
| 75 | if (!s.ok) throw new Error("user"); | |
| 76 | sam = createToken(app.db, s.value.id, "admin", "admin").token; | |
| 77 | const n = await createUser(app.db, { origin: "seed", trusted: true, username: "pat", email: "[email protected]", password: "a-good-passphrase" }); | |
| 78 | if (!n.ok) throw new Error("user"); | |
| 79 | nobody = createToken(app.db, n.value.id, "admin", "admin").token; | |
| 80 | const code = await createRepo(app, a.value, { name: "forge-code", visibility: "public" }); | |
| 81 | if (!code.ok) throw new Error("repo"); | |
| 82 | await commitToBranch(app, a.value, code.value, { message: "v1", files: [{ path: "src/main.ts", content: "1" }] }); | |
| 83 | promote(app.db, s.value); | |
| 84 | for (const [name, visibility] of [["notes", "public"], ["secret", "private"]] as const) { | |
| 85 | const r = await createRepo(app, s.value, { name, visibility }); | |
| 86 | if (!r.ok) throw new Error(`repo ${JSON.stringify(r.error)}`); | |
| 87 | await commitToBranch(app, s.value, r.value, { message: "v1", files: [{ path: "src/main.ts", content: "1" }] }); | |
| 88 | } | |
| 89 | putEntitlement(app.db, { forge: "sams-forge", plan: "small", status: "active", provider: "stripe", payer: "[email protected]", source: "stripe" }, "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("a person with no paid forge has no gifts and no line on home", async () => { | |
| 102 | expect((await get("/gifts", nobody)).status).toBe(404); | |
| 103 | expect((await form("/gifts", nobody, {})).status).toBe(404); | |
| 104 | expect(await (await get("/", nobody)).text()).not.toContain("Give a friend a forge"); | |
| 105 | expect(await (await get("/", sam)).text()).toContain("Give a friend a forge"); | |
| 106 | }); | |
| 107 | ||
| 108 | test("the giver copies a link; a stranger sees who it is from and starts with the shared app; the giver sees it taken; a second use is refused", async () => { | |
| 109 | const { link, text } = await giveLink({ app: "sam/notes", showBuilt: "1" }); | |
| 110 | expect(text).toContain(link); | |
| 111 | expect(text).toContain("I'm giving you a forge, free for 30 days, with notes already on it"); | |
| 112 | expect(link).toStartWith(servers.url); | |
| 113 | // The link is shown once: the page after it carries none. | |
| 114 | expect(await (await get("/gifts", sam)).text()).not.toContain(link); | |
| 115 | expect(JSON.stringify(app.db.query("SELECT * FROM gift_code").all())).not.toContain(link.split("=")[1]!); | |
| 116 | ||
| 117 | const cookie = await open(link); | |
| 118 | const friend = await (await get("/forges/new", undefined, cookie)).text(); | |
| 119 | expect(friend).toContain("A forge from sam"); | |
| 120 | expect(friend).toContain("Start with <b>notes</b>"); | |
| 121 | expect(friend).toContain("free for 30 days"); | |
| 122 | ||
| 123 | resetAnonSpawns(app.db); | |
| 124 | made.push("friend-one"); | |
| 125 | const res = await form("/forges/new", undefined, { name: "friend-one", apps: "sam/notes", code: link.split("=")[1]! }); | |
| 126 | expect(res.status).toBe(201); | |
| 127 | const row = app.db.query<{ plan: string; source: string; period_end: number }, []>("SELECT plan, source, period_end FROM entitlement WHERE forge = 'friend-one'").get()!; | |
| 128 | expect(row.plan).toBe("small"); | |
| 129 | expect(row.source).toStartWith("code:"); | |
| 130 | expect(row.period_end).toBeGreaterThan(Date.now() / 1000 + 29 * 86_400); | |
| 131 | ||
| 132 | expect(listChildrenNow(app).find((c) => c.name === "friend-one")?.apps).toContain("sam/notes"); | |
| 133 | const mine = await (await get("/gifts", sam)).text(); | |
| 134 | expect(mine).toContain("taken by <b>friend-one</b>"); | |
| 135 | expect(mine).toContain("opens with sam/notes"); | |
| 136 | expect(await (await get("/", sam)).text()).toContain("1 friend has taken one"); | |
| 137 | ||
| 138 | // A second use of the link is refused plainly. | |
| 139 | app.db.exec("DELETE FROM gift_try"); | |
| 140 | resetAnonSpawns(app.db); | |
| 141 | const again = await form("/forges/new", undefined, { name: "friend-two", code: link.split("=")[1]! }); | |
| 142 | expect(again.status).toBe(422); | |
| 143 | expect(await again.text()).toContain("That code has been used as many times as it allows"); | |
| 144 | const page2 = await (await get("/forges/new", undefined, cookie)).text(); | |
| 145 | expect(page2).toContain("used as many times"); | |
| 146 | ||
| 147 | // The funnel counts it. | |
| 148 | expect(giftCounts(app.db)).toEqual({ given: 1, taken: 1, converted: 0 }); | |
| 149 | putEntitlement(app.db, { forge: "friend-one", plan: "small", status: "active", provider: "stripe", payer: "[email protected]", source: "stripe" }, "small", ""); | |
| 150 | expect(giftCounts(app.db).converted).toBe(1); | |
| 151 | const billing = await (await get("/settings/billing", admin)).text(); | |
| 152 | expect(billing).toContain("Gifts given"); | |
| 153 | expect(billing).toMatch(/Friends now subscribed<\/dt><dd>1</); | |
| 154 | }); | |
| 155 | ||
| 156 | test("the allowance is a setting, the shared app must be the giver's own public one", async () => { | |
| 157 | app.db.exec("DELETE FROM gift_try"); | |
| 158 | expect((await form("/gifts", sam, { app: "sam/secret" })).status).toBe(422); | |
| 159 | expect((await form("/gifts", sam, { app: "alice/forge-code" })).status).toBe(422); | |
| 160 | expect((await form("/gifts", sam, { app: "../x" })).status).toBe(422); | |
| 161 | expect(await (await get("/gifts", sam)).text()).toContain("2 of 3 gifts left"); | |
| 162 | await giveLink(); | |
| 163 | await giveLink(); | |
| 164 | const none = await form("/gifts", sam, {}); | |
| 165 | expect(none.status).toBe(422); | |
| 166 | expect(await none.text()).toContain("You have given all the gifts you have"); | |
| 167 | const set = setGifts(app.db, { perPlan: { small: "5" }, plan: "medium", days: "14" }, adminId); | |
| 168 | expect(set.ok).toBe(true); | |
| 169 | const more = await giveLink(); | |
| 170 | expect(more.text).toContain("free for 14 days"); | |
| 171 | expect(setGifts(app.db, { perPlan: { small: "x" }, plan: "small", days: 30 }, adminId).ok).toBe(false); | |
| 172 | expect(setGifts(app.db, { perPlan: {}, plan: "free", days: 30 }, adminId).ok).toBe(false); | |
| 173 | const saved = await form("/settings/billing/gifts", admin, { count_small: "4", plan: "small", days: "30" }); | |
| 174 | expect(saved.status).toBe(303); | |
| 175 | expect((await form("/settings/billing/gifts", sam, { plan: "small", days: "30" })).status).toBe(404); | |
| 176 | }); | |
| 177 | }); |
test/home-living.test.ts +2 −1
| @@ -191,8 +191,9 @@ describe("home", () => { | ||
| 191 | 191 | test("a warm home costs a bounded number of statements, the two scans read once per write", async () => { |
| 192 | 192 | await home(aliceCookie); |
| 193 | 193 | // Calm pass (#10298): home now also reads what waits on the owner, the last visit (a write) and the digest since: 3 more statements, bound raised 40 to 46. |
| 194 | // #11655 adds the gift line's one read: 47. | |
| 194 | 195 | const warm = await requestStatements(app.db, `${servers.url}/`, { headers: { cookie: aliceCookie } }); |
| 195 | expectWork(warm, { max: 46 }); | |
| 196 | expectWork(warm, { max: 47 }); | |
| 196 | 197 | const scans = await statements(app.db, async () => void (await get("/live/moving", aliceCookie).then((r) => r.text()))); |
| 197 | 198 | const again = await statements(app.db, async () => void (await get("/live/moving", aliceCookie).then((r) => r.text()))); |
| 198 | 199 | expect(again).toBeLessThanOrEqual(scans); |
new above
offline