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

A client invite link says in one plain line when it expires #15125

Merged opened this

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

Merged

scout/forge:scout/15108-a-client-invite-link-says-in-one-plain-l → main 10 commits fork 4 threads · 4 unresolved

  • Merged. scout/15108-a-client-invite-link-says-in-one-plain-l was merged into main as 3ef9a3c.

Review

Sign in to review this change.
10 files changed +181 −18
docs/features/invite-expiry.md added +17
@@ -0,0 +1,17 @@
1 ---
2 topic: Every setting, by topic
3 row: An invite link says when it expires
4 ---
5 # An invite link says when it expires
6
7 Open `/signup?invite=<token>` and the page says in one plain line "This link works until <date> UTC.". A link that has run out says "This link has expired. Ask <who made it> for a new one." instead of
8 a form. Used or revoked links keep the older "used, revoked or has expired" sentence.
9
10 Try it: as an admin mint an invite (`POST /api/v1/admin/invites`, or the invites page) with signup set to `invite`,
11 then open its link; mint one with a past expiry to see the expired page.
12
13 The terminal (both doors): on Create account with signup = invite, the Invite field shows the same line as soon as a
14 token is pasted ("This link works until <date> UTC.", or "This link has expired. Ask <who made it> for a new one."),
15 before anything is submitted; an expired token is refused with the expired line on submit.
16
17 Pinned by `test/invite-expiry-words.test.ts` and `test/tui-signup-invite.test.ts`.
src/actions/invites.ts +10
@@ -41,3 +41,13 @@ export function revoke(app: App, actor: User | undefined, inviteId: string): Res
4141 app.bus.append({ kind: "invite.revoked", actorId: actor.id, payload: { id: inviteId } });
4242 return done;
4343 }
44
45 /** The one plain line an open invite says about time. `when` is the date, already written out. */
46 export function inviteExpiryLine(when: string): string {
47 return `This link works until ${when}.`;
48 }
49
50 /** What someone is told, kindly, when their link has run out: who to ask, in plain words. */
51 export function inviteExpiredLine(from: string | undefined): string {
52 return `This link has expired. Ask ${from ?? "whoever sent it"} for a new one.`;
53 }
src/core/invites.ts +15
@@ -135,3 +135,18 @@ export function revokeInvite(
135135 export function inviteSpentBy(db: Database, userId: string): string | undefined {
136136 return db.query<{ id: string }, [string]>("SELECT id FROM invite WHERE used_by = ?1").get(userId)?.id;
137137 }
138
139 /**
140 * The invite a token names, whatever its state, with the username of who made it; undefined when
141 * unknown.
142 */
143 export function inviteByToken(
144 db: Database,
145 token: string,
146 now: number = Date.now(),
147 ): { invite: Invite; from: string | undefined } | undefined {
148 const row = db.query<Row, [string]>(`${SELECT} WHERE invite.token_hash = ?1`).get(sha256(token));
149 if (row === null) return undefined;
150 const from = db.query<{ username: string }, [string]>("SELECT username FROM user WHERE id = ?1").get(row.created_by);
151 return { invite: view(row, now), from: from?.username };
152 }
src/core/when_words.ts added +6
@@ -0,0 +1,6 @@
1 /** A time written out for a person: `Nov 12, 14:30 UTC`, from an ISO time. */
2 export function whenWords(iso: string): string {
3 const d = new Date(iso);
4 const month = d.toLocaleString("en-US", { month: "short", timeZone: "UTC" });
5 return `${month} ${d.getUTCDate()}, ${iso.slice(11, 16)} UTC`;
6 }
src/tui/screens/signin.ts +22 −5
@@ -9,6 +9,9 @@
99 */
1010

The terminal only refuses an expired token on submit. It should also say 'works until <date>' for an open one, as the page does.

1111 import { activeEdgeToken } from "../../http/edge.ts";
12 import { inviteByToken } from "../../core/invites.ts";
13 import { whenWords } from "../../core/when_words.ts";
14 import { inviteExpiredLine, inviteExpiryLine } from "../../actions/invites.ts";
1215 import { INVITE_SPENT_MESSAGE, REQUEST_IN_MESSAGE, SIGNUP_CLOSED_MESSAGE, signUp, signupClosed } from "../../actions/users.ts";
1316 import { SignupSlot, waitText } from "../../actions/signup-window.ts";
1417 import { hasAnyUser } from "../../core/users.ts";
@@ -80,6 +83,16 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
8083 let error: string | undefined;
8184 let busy = false;
8285
86 // The invite step says when a pasted link works until, or that it has run out, before submit.
87 const inviteNote = (): string | undefined => {
88 const token = (values[3] ?? "").trim();
89 if (mode !== "create" || !invited() || token === "") return undefined;
90 const known = inviteByToken(f.db, token);
91 if (known === undefined) return undefined;
92 if (known.invite.state === "open") return inviteExpiryLine(whenWords(known.invite.expiresAt));
93 return known.invite.state === "expired" ? inviteExpiredLine(known.from) : undefined;
94 };
95
8396 const fields = (): Field[] => (mode === "create" ? (invited() ? [...CREATE, INVITE] : CREATE) : SIGN_IN);
8497
8598 const submit = (): void => {
@@ -118,8 +131,10 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
118131 );
119132 if (!created.ok) {
120133 // With signup = invite a refusal means the token did not open the door.
121 if (needsInvite && created.error === "signup_closed") error = INVITE_SPENT_MESSAGE;
122 else if (created.error === "weak_password") error = SIGNUP_WEAK_MESSAGE;
134 if (needsInvite && created.error === "signup_closed") {
135 const known = inviteByToken(f.db, invite);
136 error = known?.invite.state === "expired" ? inviteExpiredLine(known.from) : INVITE_SPENT_MESSAGE;
137 } else if (created.error === "weak_password") error = SIGNUP_WEAK_MESSAGE;
123138 else error = errorText(created.error);
124139 return;
125140 }
@@ -200,9 +215,11 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
200215 ...(focus === i ? { cursor: [...shownValue].length } : {}),
201216 ...(error !== undefined && focus === i
202217 ? { error }
203 : spec.hint === undefined
204 ? {}
205 : { hint: spec.hint }),
218 : spec === INVITE && inviteNote() !== undefined

Non-blocking: inviteNote() runs twice per render here (a DB lookup each) and needs an as string cast. Compute it once into a const above the ternary.

219 ? { hint: inviteNote() as string }
220 : spec.hint === undefined
221 ? {}
222 : { hint: spec.hint }),
206223 },
207224 );
208225 if (focus === i) cursor = at;
src/web/pages/claim.ts +1 −7
@@ -34,6 +34,7 @@ import { STRANGER_MAX } from "../../http/limits.ts";
3434 import { clientAddress } from "../../http/peer.ts";
3535 import { boundedBody, json, str } from "../../http/respond.ts";
3636 import { addPasskey } from "../../core/passkeys.ts";
37 import { whenWords } from "../../core/when_words.ts";
3738 import {
3839 listTeamMembers,
3940 listTeams,
@@ -88,13 +89,6 @@ interface Values {
8889 }
8990 type Errors = Partial<Record<"username" | "email" | "password" | "passkey", string>>;
9091
91 /** `Nov 12, 14:30 UTC`, from an ISO time. */
92 export function whenWords(iso: string): string {
93 const d = new Date(iso);
94 const month = d.toLocaleString("en-US", { month: "short", timeZone: "UTC" });
95 return `${month} ${d.getUTCDate()}, ${iso.slice(11, 16)} UTC`;
96 }
97
9892 /** "in 5 hours", "in 12 minutes", or "a minute ago", from a span in ms. */
9993 export function relativeWords(ms: number): string {
10094 const mins = Math.max(1, Math.round(Math.abs(ms) / 60_000));
src/web/pages/forges.ts +1 −1
@@ -31,7 +31,7 @@ import { countRefusals, mayReadRefusals } from "../../core/first_ask_refusals.ts
3131 import { revokePreview } from "../../spawn/manage.ts";
3232 import { clientsCsv } from "../../spawn/clients_csv.ts";
3333 import { claimLinkBody } from "./new-forge.ts";
34 import { whenWords } from "./claim.ts";
34 import { whenWords } from "../../core/when_words.ts";
3535 import { appLinkSummary, appLinkWords } from "../../spawn/app_links.ts";
3636 import { REACH_SETTINGS, reachByForge, type ForgeReach } from "../../actions/child_reach.ts";
3737 import { forgeReachRows } from "./hosted-forges.ts";
src/web/pages/site.ts +21 −3
@@ -24,6 +24,9 @@ import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/
2424 import { REPO_INIT_FAILED, REPO_NAME_RULES } from "../../actions/repo_words.ts";
2525 import { NOTE_MAX, requestOf } from "../../core/requests.ts";
2626 import { DECLINED_MESSAGE, REQUEST_IN_MESSAGE, STILL_WAITING_MESSAGE } from "../../actions/users.ts";
27 import { inviteByToken } from "../../core/invites.ts";
28 import { inviteExpiredLine, inviteExpiryLine } from "../../actions/invites.ts";
29 import { whenWords } from "../../core/when_words.ts";
2730 import { HUMAN_CHECK_MESSAGE, INVITE_SPENT_MESSAGE, PASSKEY_REQUIRED_MESSAGE, SIGNUP_CLOSED_MESSAGE, signUp, signupClosed } from "../../actions/users.ts";
2831 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
2932 import { listPins } from "../../core/pins.ts";
@@ -265,7 +268,7 @@ function linkedMethods(edge: string | undefined, next: string | undefined, paren
265268 function authForm(
266269 ctx: Ctx,
267270 kind: "signin" | "signup",
268 o: { values?: AuthValues; errors?: AuthErrors } = {},
271 o: { values?: AuthValues; errors?: AuthErrors; expiry?: string } = {},
269272 ): Html {
270273 const values = o.values ?? {};
271274 const errors = o.errors ?? {};
@@ -322,7 +325,11 @@ function authForm(
322325 ${when(mode === "invite" || mode === "closed" ? mode : undefined, () => byInvitationLine())}`,
323326 );
324327
328 // One quiet line in the form's own column, before the fields: the link says when it stops
329 // working.
330 const expiryLine = when(o.expiry, (said) => html`<p class="muted small mb" id="invite-expiry">${said}</p>`);
325331 const body = html`${unknownLink}
332 ${expiryLine}
326333 ${passkeyFirst}
327334 <form method="post" action="${action}">
328335 ${formField({
@@ -505,7 +512,14 @@ function byInvitationLine(): Html {
505512
506513 /** The whole of `/signup` while the forge makes no new accounts: a sentence, no form. */
507514 function signupClosedPage(ctx: Ctx): Response {
508 const said = inviteOf(ctx) === undefined ? SIGNUP_CLOSED_MESSAGE : INVITE_SPENT_MESSAGE;
515 const token = inviteOf(ctx);
516 const known = token === undefined ? undefined : inviteByToken(ctx.app.db, token);
517 const said =
518 token === undefined
519 ? SIGNUP_CLOSED_MESSAGE
520 : known?.invite.state === "expired"
521 ? inviteExpiredLine(known.from)
522 : INVITE_SPENT_MESSAGE;
509523 return page(
510524 {
511525 ctx,
@@ -530,7 +544,11 @@ export function signupPage(ctx: Ctx): Response {
530544 return timePhase(ctx.request, "render", () => signupClosedPage(ctx));
531545 const first = throughEdgeFirst(ctx);
532546 if (first) return first;
533 const body = authForm(ctx, "signup");
547 const token = inviteOf(ctx);
548 const known = token === undefined ? undefined : inviteByToken(ctx.app.db, token);
outdated

Principle 1 and 7: a hand-rolled wrapper with its own id instead of a named component. Use the design system's quiet-line component, and keep it inside the form's column.

549 const body = authForm(ctx, "signup", {
550 ...(known?.invite.state === "open" ? { expiry: inviteExpiryLine(whenWords(known.invite.expiresAt)) } : {}),
551 });
534552 return timePhase(ctx.request, "render", () =>
535553 page({ ctx, title: "Sign up", description: "Create an account with a passkey. Comment, and send changes to public apps for review.", body: html`${body}<p class="muted small" data-legal><a href="/terms">Terms</a> · <a href="/privacy">Privacy</a></p>`, turnstile: siteKey(ctx) !== undefined, scriptJs: passkeyJs }),
536554 );
test/invite-expiry-words.test.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * The invite page says when the link stops working, in one plain line; an expired one is kind and
3 * names who to ask.
4 */
5
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { inviteExpiredLine, inviteExpiryLine } from "../src/actions/invites.ts";
12 import { mintInvite } from "../src/core/invites.ts";
13 import { setSignup } from "../src/settings/signup.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { seedAdmin } from "./helpers/admin.ts";
16
17 describe("invite expiry words", () => {
18 let dir: string;
19 let app: App;
20 let servers: Servers;
21 let adminId: string;
22 const get = (token: string) => fetch(`${servers.url}/signup?invite=${token}`).then(async (r) => ({ status: r.status, text: await r.text() }));
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-invite-expiry-"));
26 app = createApp({ dataDir: dir, port: 0, url: "https://forge.example" });
27 servers = await serve(app);
28 const a = await seedAdmin(app, { username: "olive", email: "[email protected]", password: "owner-passphrase" });
29 if (!a.ok) throw new Error("admin");
30 adminId = a.value.id;
31 setSignup(app.db, "invite", "test");
32 });
33 afterAll(async () => {
34 servers.stop();
35 app.close();
36 await rm(dir, { recursive: true, force: true });
37 });
38

'does not expire' is asserted only on the pure function. Add a page-level test, or remove the unreachable branch.

39 test("the two lines", () => {
40 expect(inviteExpiryLine("Dec 1, 10:00 UTC")).toBe("This link works until Dec 1, 10:00 UTC.");
41 expect(inviteExpiredLine("olive")).toContain("Ask olive for a new one");
42 });
43
44 test("an open link says when it works until", async () => {
45 const { token } = mintInvite(app.db, adminId, 3);
46 const { status, text } = await get(token);
47 expect(status).toBe(200);
48 expect(text).toContain('id="invite-expiry"');
49 expect(text).toContain("This link works until");
50 // A quiet line inside the form's own column, not a wrapper above it.
51 expect(text).toMatch(/<p class="muted small mb" id="invite-expiry">This link works until [^<]+ UTC\.<\/p>/);
52 expect(text).not.toContain('<div class="narrow"><p');
53 });
54
55 test("an expired link says so kindly and names who sent it", async () => {
56 const { token } = mintInvite(app.db, adminId, 1, Date.now() - 3 * 86_400_000);
57 const { text } = await get(token);
58 expect(text).toContain("This link has expired");
59 expect(text).toContain("Ask olive for a new one");
60 expect(text).not.toContain("works until");
61 });
62 });
test/tui-signup-invite.test.ts +26 −2
@@ -42,7 +42,7 @@ describe("terminal sign-up with an invite", () => {
4242 await rm(dir, { recursive: true, force: true });
4343 });
4444
45 const attempt = async (name: string, token: string): Promise<string> => {
45 const attempt = async (name: string, token: string, submit = true): Promise<string> => {
4646 const identity: TuiIdentity = { sshUsername: "git", remoteAddress: "198.51.100.7", fingerprint: "SHA256:x", publicKey: KEY };
4747 const { app } = createForgeApp(forge, identity, { terminal: headlessTerminal(120, 32), exitHooks: false });
4848 app.start();
@@ -63,7 +63,7 @@ describe("terminal sign-up with an invite", () => {
6363 type("a-long-passphrase");
6464 key("tab");
6565 type(token);
66 key("enter");
66 if (submit) key("enter");
6767 await settleApp(app);
6868 return app.screen.toText();
6969 } finally {
@@ -78,6 +78,30 @@ describe("terminal sign-up with an invite", () => {
7878 expect(getUserByName(forge.db, "mallory")).toBeFalsy();
7979 });
8080
81 test("an expired token says so kindly and names who sent it", async () => {
82 const { token } = mintInvite(forge.db, adminId, 1, Date.now() - 3 * 86_400_000);
83 const text = await attempt("tardy", token);
84 expect(text).toContain("This link has expired");
85 expect(text).toContain("alice");
86 expect(getUserByName(forge.db, "tardy")).toBeFalsy();
87 forge.db.query("DELETE FROM invite WHERE expires_at < ?1").run(new Date().toISOString());
88 });
89
90 test("a pasted open token says when it works until, before anything is submitted", async () => {
91 const { token } = mintInvite(forge.db, adminId, 3);
92 const text = await attempt("early", token, false);
93 expect(text).toContain("This link works until");
94 expect(getUserByName(forge.db, "early")).toBeFalsy();
95 forge.db.query("DELETE FROM invite WHERE used_at IS NULL").run();
96 });
97
98 test("a pasted expired token says so on the invite step, before submit", async () => {
99 const { token } = mintInvite(forge.db, adminId, 1, Date.now() - 3 * 86_400_000);
100 const text = await attempt("early2", token, false);
101 expect(text).toContain("This link has expired");
102 forge.db.query("DELETE FROM invite WHERE expires_at < ?1").run(new Date().toISOString());
103 });
104
81105 test("a blank token is asked for, not called spent", async () => {
82106 const text = await attempt("blanca", "");
83107 expect(text).toContain("Paste the token from your invite link.");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs