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

A forge's owner sees their plan in their forge's settings, with a link to manage billing at the provider #11308

Parked opened this in answer to
Closed without merging

scout/forge:scout/11141-a-forge-s-owner-sees-their-plan-in-their → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +332 −7
docs/features/plan-row.md added +7
@@ -0,0 +1,7 @@
1 # The Plan row in a forge's settings (#11141)
2
3 A forge's admins see one line at the top of `/settings`: the plan's name and size, the crew credit used this month, and the status (`Active`, or `Past due, sleeps <date>`). With a billing portal set and a Stripe payer, **Manage billing** links to the provider's customer-portal sign-in (the buyer signs in with the email they paid with); **Change size** links to the host's `/pricing`. A forge with no notice (never told, or a host that is not its parent) shows no row.
4
5 - **Host:** Settings → Billing → *Billing portal* sets `billing.portal_url` (https only, empty clears). Changing it tells every forge sent from here.
6 - **How a forge learns its plan:** the host writes a notice (`src/billing/notice.ts`) into that one forge's `parent.json` when the forge is made, a gift is redeemed, a plan is granted, or Stripe changes the subscription. The forge reads only its own file and calls nothing on the host, so it cannot read another forge's plan; the notice has no forge name, customer or subscription id.
7 - No terminal screen: the row is a line on an existing page, not a page.
src/actions/billing.ts +2
@@ -6,6 +6,7 @@
66 * shows in the audit trail. Anyone else is told `not_found`.
77 */
88
9 import { tellPlan } from "../billing/notice.ts";
910 import type { App } from "../app.ts";
1011 import { changesOf, entitlementOf, putEntitlement, type EntitlementChange } from "../billing/store.ts";
1112 import type { Entitlement } from "../billing/types.ts";
@@ -87,6 +88,7 @@ export function grantPlan(app: App, actor: User | undefined, forge: unknown, pla
8788 const { from, to } = planned.value;
8889 const size = listChildrenNow(app).find((c) => c.name === to.forge)?.size ?? from.plan;
8990 const entitlement = putEntitlement(app.db, { forge: to.forge, plan: to.plan, status: "active", source: "granted", provider: "none" }, size, who.id);
91 tellPlan(app, to.forge);
9092 app.bus.append({ kind: "billing.plan", actorId: who.id, payload: { forge: to.forge, from: from.plan, to: to.plan, source: "granted" } });
9193 return ok({ entitlement, changes: changesOf(app.db, to.forge) });
9294 }
src/actions/codes.ts +2
@@ -8,6 +8,7 @@
88 * `billing.code.*` event, so it shows in the audit trail.
99 */
1010
11 import { tellPlan } from "../billing/notice.ts";
1112 import type { App } from "../app.ts";
1213 import {
1314 CODE_WORDS, MAX_NOTE, MAX_USES, insertCode, listCodes, lookupCode, noteRedeemed,
@@ -112,5 +113,6 @@ export function settleGift(app: App, code: Code, forge: string): void {
112113 const size = getPlan(app.db, code.plan)?.size ?? "small";
113114 noteRedeemed(app.db, code.id, forge);
114115 putEntitlement(app.db, { forge, plan: code.plan, status: "active", source: `code:${code.id}`, provider: "none" }, size, "");
116 tellPlan(app, forge);
115117 app.bus.append({ kind: "billing.code.redeem", payload: { id: code.id, forge, plan: code.plan } });
116118 }
src/actions/signup.ts +11 −1
@@ -14,7 +14,8 @@ import {
1414 } from "../settings/signup.ts";
1515 import { getAgentStart, parseAgentStart, setAgentStart, type AgentStartMode } from "../settings/agent_start.ts";
1616 import { forgeSource, parseForgeSource, setForgeSource, storedForgeSource } from "../settings/forge_source.ts";
17 import { getBillingLinks, parseBillingLinks, setBillingLinks, type BillingLinks } from "../settings/billing.ts";
17 import { tellAll } from "../billing/notice.ts";
18 import { getBillingLinks, parseBillingLinks, setBillingLinks, setPortalUrl, type BillingLinks } from "../settings/billing.ts";
1819 import type { User } from "../core/users.ts";
1920 import { err, ok, type Result } from "../kernel/result.ts";
2021
@@ -110,3 +111,12 @@ export function changeBillingLinks(
110111 setBillingLinks(app.db, links.value, who.value.id);
111112 return ok(links.value);
112113 }
114
115 /** The billing portal address (`settings/billing.ts`) and every forge told it, for a forge admin who is a person. */
116 export function changePortalUrl(app: App, actor: User | undefined, raw: unknown): Result<string, "not_found" | "invalid_portal_url"> {
117 const who = admin(actor);
118 if (!who.ok) return who;
119 const set = setPortalUrl(app.db, raw, who.value.id);
120 if (set.ok) tellAll(app);
121 return set;
122 }
src/actions/spawn.ts +2
@@ -12,6 +12,7 @@
1212 * idempotent — and a finished one is answered, not made twice.
1313 */
1414
15 import { tellPlan } from "../billing/notice.ts";
1516 import { readdirSync, readFileSync } from "node:fs";
1617 import { mkdir, readdir, rename } from "node:fs/promises";
1718 import { join } from "node:path";
@@ -336,6 +337,7 @@ async function make(
336337 grantPlanCredit(app, plan, ledger.bodyId);
337338 ledger.done = true;
338339 await writeLedger(app, ledger);
340 tellPlan(app, plan.name);
339341 app.bus.append({
340342 kind: "forge.spawned",
341343 actorId: owner?.id,
src/billing/checkout_completed.ts +2
@@ -7,6 +7,7 @@
77 * event is already kept by the hook, and that is the record.
88 */
99
10 import { tellPlan } from "./notice.ts";
1011 import type { App } from "../app.ts";
1112 import { listChildrenNow } from "../actions/spawn.ts";
1213 import { parseSize } from "../spawn/sizes.ts";
@@ -41,6 +42,7 @@ export function bindCheckout(app: App, event: unknown): boolean {
4142 child.size,
4243 "",
4344 );
45 tellPlan(app, forge);
4446 app.bus.append({ kind: "billing.plan", payload: { forge, to: plan, source: "stripe" } });
4547 return true;
4648 }
src/billing/notice.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * What a forge is told of its own plan (#11141): its plan's name and size,
3 * its status and period end, and the host's public billing-portal address
4 * (`billing.portal_url`) when it pays through Stripe. The host writes it into
5 * that one child's `parent.json` under `plan` when the forge is made and
6 * whenever its entitlement changes; the child only ever reads its own file.
7 * No call from a forge reaches the host for it, so a forge cannot learn
8 * another's plan, and the notice carries no forge name, customer or
9 * subscription id.
10 */
11
12 import { readFileSync, renameSync, writeFileSync } from "node:fs";
13 import { join } from "node:path";
14 import type { App } from "../app.ts";
15 import { childDirOf, listChildrenNow } from "../actions/spawn.ts";
16 import { getPortalUrl, parseLink } from "../settings/billing.ts";
17 import { getPlan } from "../settings/plans.ts";
18 import { entitlementOf, getStored } from "./store.ts";
19 import type { EntitlementStatus } from "./types.ts";
20
21 export interface PlanNotice {
22 readonly name: string;
23 readonly size: string;
24 readonly priceUsd: number;
25 readonly creditUsd: number;
26 readonly status: EntitlementStatus;
27 /** Unix seconds the paid period ends (and a past-due forge sleeps), when known. */
28 readonly periodEnd?: number;
29 /** The provider's customer-portal sign-in; absent without a provider or a URL. */
30 readonly portalUrl?: string;
31 }
32
33 const file = (dataDir: string): string => join(dataDir, "parent.json");
34 const STATUSES: readonly string[] = ["active", "grace", "none"];
35
36 function readDoc(dataDir: string): Record<string, unknown> | undefined {
37 try {
38 const d = JSON.parse(readFileSync(file(dataDir), "utf8"));
39 return typeof d === "object" && d !== null && !Array.isArray(d) ? (d as Record<string, unknown>) : undefined;
40 } catch {
41 return undefined;
42 }
43 }
44
45 const short = (v: unknown, max: number): string | undefined => (typeof v === "string" && v.length > 0 && v.length <= max && !/[\x00-\x1f]/.test(v) ? v : undefined);
46 const money = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 100_000 ? v : 0);
47
48 /** This forge's own notice, validated on read; undefined when it was told none. */
49 export function noticeOf(dataDir: string): PlanNotice | undefined {
50 const p = readDoc(dataDir)?.["plan"];
51 if (typeof p !== "object" || p === null) return undefined;
52 const r = p as Record<string, unknown>;
53 const name = short(r["name"], 60);
54 const size = short(r["size"], 20);
55 if (name === undefined || size === undefined || typeof r["status"] !== "string" || !STATUSES.includes(r["status"])) return undefined;
56 const portal = typeof r["portalUrl"] === "string" ? parseLink(r["portalUrl"]) : undefined;
57 return {
58 name,
59 size,
60 priceUsd: money(r["priceUsd"]),
61 creditUsd: money(r["creditUsd"]),
62 status: r["status"] as EntitlementStatus,
63 ...(typeof r["periodEnd"] === "number" && Number.isFinite(r["periodEnd"]) && r["periodEnd"] > 0 ? { periodEnd: r["periodEnd"] } : {}),
64 ...(portal === undefined || portal === "" ? {} : { portalUrl: portal }),
65 };
66 }
67
68 /** Write the notice into a child's `parent.json`, keeping the rest; false when it has none yet. */
69 export function keepNotice(dataDir: string, notice: PlanNotice): boolean {
70 const doc = readDoc(dataDir);
71 if (doc === undefined) return false;
72 writeFileSync(`${file(dataDir)}.tmp`, JSON.stringify({ ...doc, plan: notice }), { mode: 0o600 });
73 renameSync(`${file(dataDir)}.tmp`, file(dataDir));
74 return true;
75 }
76
77 /** 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. */
78 export function tellPlan(app: App, forge: string): boolean {
79 try {
80 const child = listChildrenNow(app).find((c) => c.name === forge && c.done);
81 if (child === undefined) return false;
82 const e = entitlementOf(app.db, forge, child.size);
83 const plan = getPlan(app.db, e.plan);
84 const portal = getPortalUrl(app.db);
85 const paysAtProvider = getStored(app.db, forge)?.provider === "stripe";
86 return keepNotice(childDirOf(app, child.bodyId), {
87 name: plan?.name ?? e.plan,
88 size: plan?.size ?? child.size,
89 priceUsd: plan?.priceUsd ?? 0,
90 creditUsd: plan?.creditUsd ?? 0,
91 status: e.status,
92 ...(e.periodEnd === undefined ? {} : { periodEnd: e.periodEnd }),
93 ...(paysAtProvider && portal !== "" ? { portalUrl: portal } : {}),
94 });
95 } catch {
96 return false;
97 }
98 }
99
100 /** Tell every forge sent from here, after the portal address changes. */
101 export function tellAll(app: App): void {
102 for (const c of listChildrenNow(app)) tellPlan(app, c.name);
103 }
src/billing/sync.ts +2
@@ -10,6 +10,7 @@
1010
1111 import type { App } from "../app.ts";
1212 import { listChildrenNow } from "../actions/spawn.ts";
13 import { tellPlan } from "./notice.ts";
1314 import { openKey } from "./connection.ts";
1415 import { getStored, putEntitlement } from "./store.ts";
1516 import { stripeClient, type StripeError } from "./stripe.ts";
@@ -50,6 +51,7 @@ export async function syncSubscription(app: App, id: string | undefined): Promis
5051 if (put === undefined) return;
5152 const size = listChildrenNow(app).find((c) => c.name === put.forge)?.size ?? getStored(app.db, put.forge)?.plan ?? "small";
5253 putEntitlement(app.db, put, size, "stripe");
54 tellPlan(app, put.forge);
5355 });
5456 return failed;
5557 }
src/http/settings_routes.ts +2 −1
@@ -18,7 +18,7 @@ import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts
1818 import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts";
1919 import { flagsPage, flagsSet } from "../web/pages/flags.ts";
2020 import { appTemplatesPage, appTemplatesSet } from "../web/pages/app_templates.ts";
21 import { billingPage, billingGrant, billingSetLinks, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret } from "../web/pages/billing.ts";
21 import { billingPage, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret } from "../web/pages/billing.ts";
2222 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
2323 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
2424 import { usagePage } from "../web/pages/usage.ts";
@@ -212,6 +212,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
212212 router.add("GET", "/settings/billing", billingPage);
213213 router.add("POST", "/settings/billing/grant", billingGrant);
214214 router.add("POST", "/settings/billing/links", billingSetLinks);
215 router.add("POST", "/settings/billing/portal", billingSetPortal);
215216 router.add("POST", "/settings/billing/stripe/connect", stripeConnect);
216217 router.add("POST", "/settings/billing/stripe/secret", stripeSecret);
217218 router.add("POST", "/settings/billing/stripe/disconnect", stripeDisconnect);
src/settings/billing.ts +19 −1
@@ -20,7 +20,7 @@ const MAX_URL = 300;
2020 export const BILLING_WORDS = "billing links are an object of small, medium and large, each an https URL or empty";
2121
2222 /** One https URL with no credentials and no spaces, or the empty string. */
23 function parseLink(raw: unknown): string | undefined {
23 export function parseLink(raw: unknown): string | undefined {
2424 if (raw === null || raw === "") return "";
2525 if (typeof raw !== "string") return undefined;
2626 const s = raw.trim();
@@ -80,3 +80,21 @@ export function sizeWords(size: Size): string {
8080 const gb = (mib: number): string => `${mib / 1024} GB`;
8181 return `${s.cpu} ${s.cpu === 1 ? "CPU" : "CPUs"}, ${gb(s.memoryMiB)} memory, ${gb(s.diskMiB)} disk`;
8282 }
83
84 export const PORTAL_URL_KEY = "billing.portal_url";
85 export const PORTAL_WORDS = "the billing portal address is one https URL with no spaces, or empty";
86
87 /** The provider's customer-portal sign-in, one https URL the host sets; "" when none. */
88 export function getPortalUrl(db: Database): string {
89 const row = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(PORTAL_URL_KEY);
90 return row === null ? "" : (parseLink(row.value) ?? "");
91 }
92
93 /** Keep the portal URL (validated, empty clears it) with who changed it; the same value again keeps nothing. */
94 export function setPortalUrl(db: Database, raw: unknown, actorId: string): Result<string, "invalid_portal_url"> {
95 const link = parseLink(raw);
96 if (link === undefined) return err("invalid_portal_url");
97 const from = getPortalUrl(db);
98 if (from !== link) writeSetting(db, PORTAL_URL_KEY, link === "" ? null : link, from, link, actorId);
99 return ok(link);
100 }
src/web/pages/account.ts +2 −1
@@ -62,6 +62,7 @@ import {
6262 import { accountSections } from "./origins.ts";
6363 import { field, readForm } from "../form.ts";
6464 import { html, when, type Html } from "../html.ts";
65 import { planRow } from "../plan_row.ts";
6566 import { flashTo, page } from "../layout.ts";
6667 import { readFlash } from "../flash.ts";
6768 import {
@@ -519,7 +520,7 @@ export function accountPage(ctx: Ctx): Response {
519520 ctx,
520521 "profile",
521522 "Settings",
522 html`${pair}${profile}${edge}${parent}${notify}`,
523 html`${planRow(ctx.app.config.dataDir, parentIssuerOf(ctx.app.config), user.isAdmin === true)}${pair}${profile}${edge}${parent}${notify}`,
523524 200,
524525 // The everyday form makes its account with a passkey (#1890).
525526 pair ? passkeyJs : undefined,
src/web/pages/billing.ts +30 −3
@@ -12,9 +12,9 @@ import { publicOrigin } from "../../core/public_origin.ts";
1212 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1313 import type { Ctx } from "../../http/context.ts";
1414 import { SIZES } from "../../spawn/sizes.ts";
15 import { BILLING_SIZES, parseBillingLinks } from "../../settings/billing.ts";
15 import { BILLING_SIZES, getPortalUrl, PORTAL_WORDS, parseBillingLinks } from "../../settings/billing.ts";
1616 import { getPlans } from "../../settings/plans.ts";
17 import { changeBillingLinks, readBillingLinks } from "../../actions/signup.ts";
17 import { changeBillingLinks, changePortalUrl, readBillingLinks } from "../../actions/signup.ts";
1818 import { funnelReport, type FunnelReport } from "../../perf/funnel.ts";
1919 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
2020 import { field, readForm } from "../form.ts";
@@ -103,6 +103,32 @@ function linksSection(ctx: Ctx, retry?: { values: Record<string, string>; error:
103103 </section>`;
104104 }
105105
106 /** The one billing-portal address every paying forge's Plan row links to. */
107 function portalSection(ctx: Ctx, retry?: { value: string; error: string }): Html | null {
108 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return null;
109 return html`<section class="settings-block" id="portal">
110 <h2>Billing portal</h2>
111 <p class="muted small">Stripe's customer-portal sign-in. A forge that pays through Stripe links its owner here to change a card; empty shows no link.</p>
112 ${retry === undefined ? null : html`<p class="error" role="alert">${retry.error}</p>`}
113 <form class="stack" method="post" action="${PATH}/portal">
114 ${formField({ label: "Portal sign-in address", name: "portal_url", type: "url", value: retry?.value ?? getPortalUrl(ctx.app.db), hint: "https://billing.stripe.com/p/login/…" })}
115 ${btn("Save portal address", { variant: "primary" })}
116 </form>
117 </section>`;
118 }
119
120 // POST /settings/billing/portal
121 export async function billingSetPortal(ctx: Ctx): Promise<Response> {
122 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx);
123 const form = await readForm(ctx, "admin");
124 if (form instanceof Response) return form;
125 const value = field(form, "portal_url");
126 const changed = changePortalUrl(ctx.app, ctx.auth.user, value);
127 if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx);
128 if (changed.ok) return flashTo(ctx, `${PATH}#portal`, { message: "Billing portal address saved." });
129 return billingView(ctx, undefined, {}, undefined, 422, undefined, { value, error: `${PORTAL_WORDS}. Nothing was saved.` });
130 }
131
106132 // POST /settings/billing/links
107133 export async function billingSetLinks(ctx: Ctx): Promise<Response> {
108134 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx);
@@ -141,7 +167,7 @@ export function billingPage(ctx: Ctx): Response {
141167 return billingView(ctx);
142168 }
143169
144 function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {}, error?: string, status = 200, links?: { values: Record<string, string>; error: string }): Response {
170 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 {
145171 const read = readBilling(ctx.app, ctx.auth.user);
146172 if (!read.ok) return notFoundPage(ctx);
147173 const b = read.value;
@@ -196,6 +222,7 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
196222 ${ledBlock(ctx)}
197223 ${funnelRow(funnelReport(ctx.app.db, 7))}
198224 ${linksSection(ctx, links)}
225 ${portalSection(ctx, portal)}
199226 ${codesSection(ctx, shown, values, error)}`;
200227 const response = page({
201228 ctx,
src/web/plan_row.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * The Plan row in a forge's settings (#11141), one line for its admins: the
3 * plan's name and size, the crew credit used this month, and the status (past
4 * due says the date it sleeps). Everything is what the host told this forge
5 * (`billing/notice.ts`) and its own funding file; nothing is asked of the
6 * host. "Manage billing" is the provider's portal sign-in, shown only when
7 * the host set one and this forge pays through it; "Change size" is the
8 * host's /pricing.
9 */
10
11 import { noticeOf, type PlanNotice } from "../billing/notice.ts";
12 import { fundingOf } from "../spawn/funding.ts";
13 import { usdWords } from "../spawn/credit.ts";
14 import { sizeWords } from "../settings/billing.ts";
15 import { isSize } from "../spawn/sizes.ts";
16 import { html, type Html } from "./html.ts";
17
18 const day = (secs: number): string => new Date(secs * 1000).toISOString().slice(0, 10);
19
20 /** "Active", or "Past due, sleeps 2026-12-01". */
21 export function statusWords(n: Pick<PlanNotice, "status" | "periodEnd">): string {
22 if (n.status === "grace") return n.periodEnd === undefined ? "Past due" : `Past due, sleeps ${day(n.periodEnd)}`;
23 return n.status === "none" ? "No active plan" : "Active";
24 }
25
26 export function planRow(dataDir: string, parentOrigin: string | undefined, admin: boolean): Html | null {
27 if (!admin) return null;
28 const n = noticeOf(dataDir);
29 if (n === undefined) return null;
30 const f = fundingOf(dataDir);
31 const credit =
32 n.creditUsd > 0 && f?.spentUsd != null ? ` · ${usdWords(f.spentUsd)} of ${usdWords(n.creditUsd)} crew credit used this month` : "";
33 const size = isSize(n.size) ? ` (${sizeWords(n.size)})` : "";
34 return html`<p class="plan-row"><strong>Plan</strong> ${n.name}${size} · ${statusWords(n)}${credit}${
35 n.portalUrl === undefined ? "" : html` · <a href="${n.portalUrl}" rel="noopener noreferrer" target="_blank">Manage billing</a>`
36 }${parentOrigin === undefined ? "" : html` · <a href="${parentOrigin}/pricing">Change size</a>`}</p>`;
37 }
test/plan-notice.test.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * A forge's Plan row (#11141): the host tells each forge its own plan (name,
3 * size, status, the public portal URL) and nothing of any other; the row
4 * shows it to the forge's admins, in one line, with Manage billing only when
5 * a portal URL is set and the forge pays through Stripe.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { childDirOf } from "../src/actions/spawn.ts";
12 import { changePortalUrl } from "../src/actions/signup.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { noticeOf, tellPlan } from "../src/billing/notice.ts";
15 import { putEntitlement } from "../src/billing/store.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { getPortalUrl } from "../src/settings/billing.ts";
18 import { planRow, statusWords } from "../src/web/plan_row.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 describe("plan notice", () => {
24 let dir: string;
25 let app: App;
26 let admin: User;
27 const PORTAL = "https://billing.stripe.com/p/login/abc123";
28
29 const child = async (name: string): Promise<string> => {
30 const bodyId = `body-${name}`;
31 await mkdir(join(dir, "spawn"), { recursive: true });
32 await writeFile(join(dir, "spawn", `${name}.json`), JSON.stringify({ name, bodyId, done: true, size: "small", org: name, apps: [] }));
33 const cd = childDirOf(app, bodyId);
34 await mkdir(cd, { recursive: true });
35 await writeFile(join(cd, "parent.json"), JSON.stringify({ upstream: "https://host.example" }));
36 return cd;
37 };
38
39 beforeAll(async () => {
40 dir = await mkdtemp(join(tmpdir(), "forge-notice-"));
41 app = createApp({ dataDir: dir, port: 0 });
42 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
43 if (!a.ok) throw new Error("user");
44 admin = a.value;
45 });
46 afterAll(async () => {
47 app.close?.();
48 await rm(dir, { recursive: true, force: true });
49 });
50
51 test("the portal URL is https only, kept for admins, and empty clears it", () => {
52 expect(changePortalUrl(app, admin, "http://x.example/").ok).toBe(false);
53 expect(changePortalUrl(app, admin, "https://u:[email protected]/").ok).toBe(false);
54 expect(changePortalUrl(app, { ...admin, isAdmin: false }, PORTAL)).toEqual({ ok: false, error: "not_found" });
55 expect(getPortalUrl(app.db)).toBe("");
56 expect(changePortalUrl(app, admin, PORTAL).ok).toBe(true);
57 expect(getPortalUrl(app.db)).toBe(PORTAL);
58 });
59
60 test("a forge is told its own plan, and only its own; a Stripe payer gets the portal link", async () => {
61 const a = await child("alpha");
62 const b = await child("beta");
63 putEntitlement(app.db, { forge: "alpha", plan: "medium", status: "grace", periodEnd: 1_796_000_000, provider: "stripe", customerId: "cus_secret1", subscriptionId: "sub_secret1", source: "stripe" }, "small", "");
64 expect(tellPlan(app, "alpha")).toBe(true);
65 const n = noticeOf(a)!;
66 expect(n).toMatchObject({ name: "Medium", size: "medium", status: "grace", portalUrl: PORTAL });
67 // beta was never told: no call and no file of alpha's reaches it.
68 expect(noticeOf(b)).toBeUndefined();
69 tellPlan(app, "beta");
70 const told = noticeOf(b)!;
71 expect(told.name).toBe("Small");
72 expect(told.portalUrl).toBeUndefined();
73 // Nothing of another forge, nor any provider id, is in what a forge holds.
74 for (const d of [a, b]) {
75 const raw = await readFile(join(d, "parent.json"), "utf8");
76 expect(raw).not.toContain("cus_secret1");
77 expect(raw).not.toContain("sub_secret1");
78 expect(raw).not.toContain(d === a ? "beta" : "alpha");
79 }
80 expect(tellPlan(app, "nobody")).toBe(false);
81 });
82
83 test("the row is one line for admins only, with the status date and the links", async () => {
84 const a = childDirOf(app, "body-alpha");
85 const row = planRow(a, "https://host.example", true)!.toString();
86 expect(row.split("\n").length).toBe(1);
87 expect(row).toContain("Medium");
88 expect(row).toContain("Past due, sleeps 2026-");
89 expect(row).toContain(`href="${PORTAL}"`);
90 expect(row).toContain('href="https://host.example/pricing"');
91 expect(planRow(a, "https://host.example", false)).toBeNull();
92 // No portal URL for a forge that does not pay through Stripe: the plan, no link.
93 const free = planRow(childDirOf(app, "body-beta"), undefined, true)!.toString();
94 expect(free).toContain("Small");
95 expect(free).not.toContain("Manage billing");
96 expect(free).not.toContain("Change size");
97 // A forge told nothing shows no row.
98 expect(planRow(join(dir, "nowhere"), undefined, true)).toBeNull();
99 });
100
101 test("a hostile notice is refused on read", async () => {
102 const cd = childDirOf(app, "body-beta");
103 await writeFile(join(cd, "parent.json"), JSON.stringify({ plan: { name: "x", size: "small", status: "active", portalUrl: "javascript:alert(1)" } }));
104 expect(noticeOf(cd)?.portalUrl).toBeUndefined();
105 await writeFile(join(cd, "parent.json"), JSON.stringify({ plan: { name: "x", size: "small", status: "bogus" } }));
106 expect(noticeOf(cd)).toBeUndefined();
107 expect(statusWords({ status: "active" })).toBe("Active");
108 });
109 });
test/spawn.test.ts +2
@@ -86,6 +86,8 @@ describe("spawnForge", () => {
8686 url: "https://kid--forge.test",
8787 keepAccess: false,
8888 size: "small",
89 // Its own plan, told by the host (#11141): no id, no other forge.
90 plan: { name: "Small", size: "small", priceUsd: 19, creditUsd: 5, status: "active" },
8991 // A hash only: what the parent answers to stays in its own ledger.
9092 statusHash: expect.stringMatching(/^[0-9a-f]{64}$/),
9193 // The child signs heartbeats to its parent with it (#425).

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs