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

open-platform.sh sign-in is a linked method, not a back door: it never creates an account outside the signup rules #2581

Parked opened this in answer to
Closed without merging

scout/forge:scout/668-open-platform-sh-sign-in-is-a-linked-met → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
24 files changed +445 −132
README.md +4 −1
@@ -327,7 +327,10 @@ adds `FORGE_URL` (the canonical public base URL, needed for OAuth callbacks),
327327 `FORGE_ORIGIN_ALLOW` (hosts an operator vouches for on a LAN). Behind a
328328 platform edge that signs people in for every app it serves, `FORGE_EDGE_TOKEN`
329329 is the edge's secret: a request carrying it and `X-Plat-User` is that person,
330 signed in by the platform, with an account made on first sight. Mail out
330 signed in by the platform — but only into an account that person linked
331 (Settings → Linked sign-in); an unlinked login makes no account and is sent to
332 the forge's own sign-up. `FORGE_LINKED_METHODS` (unset = all on; `none` = off)
333 turns the edge method off. Mail out
331334 (the link that proves a newcomer's email) is SMTP submission over TLS,
332335 configured by the forge-level secrets `MAIL_SMTP_URL`
333336 (`smtps://user:pass@host:465`) and `MAIL_FROM`, set live under Settings →
src/core/accounts.ts +7 −1
@@ -23,6 +23,8 @@ export interface AccountRow {
2323 readonly via: string | null;
2424 /** The address it signed up from, when one was recorded. */
2525 readonly address: string | null;
26 /** The sign-in methods linked to it (`core/linked_login.ts`). */
27 readonly linked: readonly string[];
2628 readonly repos: number;
2729 readonly apps: number;
2830 /** What crew runs on its repositories have cost, in dollars. */
@@ -51,6 +53,7 @@ export function listAccounts(db: Database): AccountRow[] {
5153 apps: number;
5254 spent: number | null;
5355 payload: string | null;
56 linked: string | null;
5457 },
5558 []
5659 >(
@@ -64,7 +67,9 @@ export function listAccounts(db: Database): AccountRow[] {
6467 WHERE r.owner_id = u.id) AS spent,
6568 (SELECT e.payload FROM event e
6669 WHERE e.kind = 'user.created' AND e.actor_id = u.id
67 ORDER BY e.id LIMIT 1) AS payload
70 ORDER BY e.id LIMIT 1) AS payload,
71 (SELECT group_concat(l.method) FROM linked_login l
72 WHERE l.user_id = u.id) AS linked
6873 FROM user u WHERE u.kind = 'user'
6974 ORDER BY u.created_at DESC, u.id DESC`,
7075 )
@@ -79,6 +84,7 @@ export function listAccounts(db: Database): AccountRow[] {
7984 createdAt: r.created_at,
8085 via: origin.via,
8186 address: origin.address,
87 linked: r.linked === null ? [] : [...new Set(r.linked.split(","))],
8288 repos: r.repos,
8389 apps: r.apps,
8490 spentUsd: Math.round((r.spent ?? 0) * 100) / 100,
src/core/linked_login.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * Linked sign-in methods: a login at the platform edge (open-platform.sh)
3 * that a person attached to an account they already have. The link is the
4 * only thing that lets the edge's word reach an account; a login nobody
5 * linked reaches nothing and makes nothing — an account is made at the
6 * forge's own signup, under its rules.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { getUserById, isActive, type User } from "./users.ts";
12
13 export const METHODS = ["edge"] as const;
14 export type Method = (typeof METHODS)[number];
15
16 /** The longest login a link keeps; the edge's own names are far shorter. */
17 const LOGIN_MAX = 64;
18
19 /** The account a login at `method` is linked to, if it is a live person. */
20 export function linkedUser(db: Database, method: Method, login: string): User | undefined {
21 const row = db
22 .query<{ user_id: string }, [string, string]>(
23 "SELECT user_id FROM linked_login WHERE method = ?1 AND login = ?2",
24 )
25 .get(method, login);
26 const user = row === null ? undefined : getUserById(db, row.user_id);
27 return user !== undefined && user.kind === "user" && isActive(user) ? user : undefined;
28 }
29
30 /** The logins linked to an account. */
31 export function linksOf(db: Database, userId: string): { method: Method; login: string; createdAt: string }[] {
32 return db
33 .query<{ method: Method; login: string; created_at: string }, [string]>(
34 "SELECT method, login, created_at FROM linked_login WHERE user_id = ?1 ORDER BY created_at",
35 )
36 .all(userId)
37 .map((r) => ({ method: r.method, login: r.login, createdAt: r.created_at }));
38 }
39
40 /** Link a login to an account; a login belongs to one account at a time. */
41 export function linkLogin(
42 db: Database,
43 user: User,
44 method: Method,
45 login: string,
46 ): Result<void, "invalid" | "taken"> {
47 if (login === "" || login.length > LOGIN_MAX) return err("invalid");
48 // eslint-disable-next-line no-control-regex
49 if (/[\u0000-\u001f\u007f]/.test(login)) return err("invalid");
50 const held = db
51 .query<{ user_id: string }, [string, string]>(
52 "SELECT user_id FROM linked_login WHERE method = ?1 AND login = ?2",
53 )
54 .get(method, login);
55 if (held !== null) return held.user_id === user.id ? ok() : err("taken");
56 db.query(
57 "INSERT INTO linked_login (method, login, user_id, created_at) VALUES (?1, ?2, ?3, ?4)",
58 ).run(method, login, user.id, new Date().toISOString());
59 return ok();
60 }
61
62 /**
63 * Remove an account's link. Refused when it is the account's only way in
64 * (no password, no passkey), which would lock the person out.
65 */
66 export function unlinkLogin(
67 db: Database,
68 user: User,
69 method: Method,
70 ): Result<void, "last_way_in"> {
71 const password = db
72 .query<{ password_hash: string }, [string]>("SELECT password_hash FROM user WHERE id = ?1")
73 .get(user.id);
74 const keys = db
75 .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM passkey WHERE user_id = ?1")
76 .get(user.id);
77 if ((password?.password_hash ?? "") === "" && (keys?.n ?? 0) === 0)
78 return err("last_way_in");
79 db.query("DELETE FROM linked_login WHERE method = ?1 AND user_id = ?2").run(method, user.id);
80 return ok();
81 }
src/core/migrations/20261018120000-linked-login.ts added +20
@@ -0,0 +1,20 @@
1 // A sign-in through the platform edge is a method linked to an account the
2 // forge already has (#668). An account the edge made before this is linked
3 // to the login it was made for, so it keeps working.
4 export default `
5 CREATE TABLE linked_login (
6 method TEXT NOT NULL,
7 login TEXT NOT NULL COLLATE NOCASE,
8 user_id TEXT NOT NULL,
9 created_at TEXT NOT NULL,
10 PRIMARY KEY (method, login)
11 ) WITHOUT ROWID;
12 CREATE INDEX linked_login_user ON linked_login(user_id);
13 INSERT OR IGNORE INTO linked_login (method, login, user_id, created_at)
14 SELECT 'edge', u.username, u.id, u.created_at
15 FROM user u
16 WHERE u.kind = 'user' AND EXISTS (
17 SELECT 1 FROM event e
18 WHERE e.kind = 'user.created' AND e.actor_id = u.id
19 AND json_extract(e.payload, '$.via') = 'edge');
20 `;
src/core/users.ts +2 −34
@@ -109,8 +109,8 @@ export type CreateUserError =
109109 * A stranger's door (the signup form, the API and the terminal through
110110 * `signUp`, the passkey door, the parent forge's sign-in) is refused while
111111 * signup is not open and must bring a place it took in the sign-up window.
112 * The platform edge is a stranger's door too; it vouches for the login and
113 * is held to the setting, not to the window, which it never was.
112 * The platform edge is no door: it signs in an account a person linked
113 * (`core/linked_login.ts`) and makes none.
114114 *
115115 * Every other origin is a named exemption, made by someone the forge already
116116 * trusts: a claim link the owner handed out, an admin's everyday account, a
@@ -135,7 +135,6 @@ export type AccountOrigin =
135135 */
136136 | { origin: "signup" | "passkey"; slot: SignupSlot; invite?: string | undefined }
137137 | { origin: "parent"; slot: SignupSlot }
138 | { origin: "edge" }
139138 | { origin: Exclude<ExemptOrigin, AdminOrigin> }
140139 | ({ origin: AdminOrigin } & AdminFields);
141140
@@ -244,8 +243,6 @@ function admission(db: Database, input: AccountOrigin): Admission {
244243 case "parent":
245244 if (input.slot.spent) throw new Error("a sign-up slot makes one account");
246245 return newAccountsClosed(db) ? REFUSED : ADMITTED;
247 case "edge":
248 return newAccountsClosed(db) ? REFUSED : ADMITTED;
249246 case "claim":
250247 case "everyday":
251248 case "agent":
@@ -450,35 +447,6 @@ export function getUserByName(
450447 return row ? toUser(row) : undefined;
451448 }
452449
453 /**
454 * The person behind an identity the platform edge vouched for: found by
455 * name, or made on first sight — with no password, because the edge is how
456 * they sign in, and a noreply address until they set one. Like a sign-up,
457 * it is never the admin, first or not. A name that is an
458 * organization or a crew member here is nobody's login.
459 */
460 export async function ensureEdgeUser(
461 db: Database,
462 login: string,
463 host: string,
464 ): Promise<User | undefined> {
465 const existing = getUserByName(db, login);
466 if (existing)
467 return existing.kind === "user" && isActive(existing) ? existing : undefined;
468 // The edge vouches for a login, not for its right to a name: createUser
469 // refuses a reserved one, so a platform account called after the crew or
470 // the owner is not let in under it.
471 const made = await createUser(db, {
472 username: login,
473 email: noreplyAddress(login, host),
474 origin: "edge",
475 });
476 if (!made.ok) return undefined;
477 // A newcomer through the edge starts unproven like one through /signup
478 // (its placeholder is no address at all).
479 return made.value;
480 }
481
482450 /** Why a password was not accepted: wrong, or tried too often to check. */
483451 export type PasswordRefusal =
484452 | { readonly reason: "bad_credentials" }
src/http/edge.ts +13
@@ -30,6 +30,19 @@ function sameSecret(a: string, b: string): boolean {
3030 return timingSafeEqual(ha, hb);
3131 }
3232
33 /**
34 * Whether to offer the edge's sign-in: there is an edge, and this request
35 * has not come through it signed in. A person it vouched for who is still
36 * anonymous has no linked account, and the edge cannot help them.
37 */
38 export function edgeDoor(ctx: {
39 app: { config: { edgeToken?: string | undefined } };
40 request: Request;
41 }): boolean {
42 const token = ctx.app.config.edgeToken;
43 return token !== undefined && edgeIdentity(ctx.request, token) === undefined;
44 }
45
3346 /** Where the edge starts a sign-in, coming back to `path` on this host. */
3447 export function edgeLoginUrl(path: string): string {
3548 return `/_plat/login?rd=${encodeURIComponent(samePath(path))}`;
src/http/server.ts +9 −20
@@ -56,15 +56,14 @@ import { trackPullHead } from "../core/pulls.ts";
5656 import { createRepo, repositoryLimitMessage, resolveOwner } from "../actions/repos.ts";
5757 import { sessionOf } from "../core/sessions.ts";
5858 import { scopeAllows, verifyToken } from "../core/tokens.ts";
59 import { forgeHost } from "../core/commit_identity.ts";
6059 import {
61 ensureEdgeUser,
6260 getUserByName,
6361 isActive,
6462 verifyPasswordThrottled,
6563 } from "../core/users.ts";
6664 import { edgeIdentity } from "./edge.ts";
67 import { signupClosed } from "../actions/users.ts";
65 import { linkedUser } from "../core/linked_login.ts";
66 import { linkEdge, linkedPage, unlinkEdge } from "../web/pages/linked.ts";
6867 import { liveResponse, readyResponse } from "./health.ts";
6968 import { running } from "../kernel/version.ts";
7069 import { runGit } from "../git/env.ts";
@@ -500,23 +499,10 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> {
500499 // in; its word outranks a cookie of ours.
501500 const login = edgeIdentity(request, app.config.edgeToken);
502501 if (login !== undefined) {
503 const existed = getUserByName(app.db, login) !== undefined;
504 // Existing accounts sign in; a new one is made only while signup allows.
505 const user =
506 !existed && signupClosed(app)
507 ? undefined
508 : await ensureEdgeUser(app.db, login, forgeHost(app.config));
509 if (user) {
510 // An account the edge made is audited like one made at /signup.
511 if (!existed) {
512 app.bus.append({
513 kind: "user.created",
514 actorId: user.id,
515 payload: { via: "edge", address: clientAddress(request) },
516 });
517 }
518 return { user, scope: "admin", via: "edge" };
519 }
502 // Only a login a person linked reaches an account; an unlinked one is
503 // nobody here and makes nothing (accounts are made at the forge's signup).
504 const user = linkedUser(app.db, "edge", login);
505 if (user) return { user, scope: "admin", via: "edge" };
520506 }
521507
522508 const session = cookieValue(request, "forge_session");
@@ -762,6 +748,9 @@ export function buildRouter(): Router<Handler> {
762748 router.add("POST", "/settings/tokens", tokenCreate);
763749 router.add("POST", "/settings/tokens/:id/delete", tokenDelete);
764750 router.add("POST", "/settings/sessions/:id/delete", sessionDelete);
751 router.add("GET", "/settings/linked", linkedPage);
752 router.add("POST", "/settings/linked/edge", linkEdge);
753 router.add("POST", "/settings/linked/edge/delete", unlinkEdge);
765754 router.add("GET", "/settings/passkeys", passkeysPage);
766755 router.add("POST", "/settings/passkeys/options", passkeyOptions);
767756 router.add("POST", "/settings/passkeys", passkeyAdd);
src/main.ts +7 −1
@@ -132,6 +132,12 @@ const canonicalUrl = hosted ? hostedAt : (process.env.FORGE_URL ?? "").trim();
132132 // FORGE_EDGE_TOKEN is the platform edge's secret: with it, the edge's
133133 // identity headers sign people in; without it they are ignored.
134134 const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim();
135 // FORGE_LINKED_METHODS lists the sign-in methods a person may link ("edge");
136 // unset leaves each on, "none" (or any list without it) turns it off.
137 const linkedMethodOn = (method: string): boolean => {
138 const raw = process.env.FORGE_LINKED_METHODS;
139 return raw === undefined || raw.split(",").map((s) => s.trim()).includes(method);
140 };
135141
136142 const dataDir = dataDirOf(process.env);
137143 // One answer for boot and `--preflight` (kernel/preflight.ts): the data
@@ -186,7 +192,7 @@ const app = createApp({
186192 ? {}
187193 : { host: process.env.FORGE_HOST }),
188194 ...(canonicalUrl === "" ? {} : { url: new URL(canonicalUrl).origin }),
189 ...(edgeToken === "" ? {} : { edgeToken }),
195 ...(edgeToken === "" || !linkedMethodOn("edge") ? {} : { edgeToken }),
190196 // Hosted, the host says how this forge's terminal is reached; printed
191197 // verbatim wherever the forge tells people how to connect.
192198 ...(hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== ""
src/web/chrome.ts +2 −2
@@ -13,7 +13,7 @@ import { mayDirectCrew } from "../crew/direct.ts";
1313 import { mayReadRuns } from "../actions/runs.ts";
1414 import { getAppByRepo } from "../core/apps.ts";
1515 import { audienceFacts, audienceOf } from "../core/audience.ts";
16 import { edgeLoginUrl } from "../http/edge.ts";
16 import { edgeDoor, edgeLoginUrl } from "../http/edge.ts";
1717 import {
1818 canAdmin,
1919 canRead,
@@ -94,7 +94,7 @@ export function signInHref(ctx: Ctx): string {
9494 const next = ctx.url.pathname + ctx.url.search;
9595 // Behind a platform edge the edge is how people sign in; an account it
9696 // made has no password here, so the password form would only refuse them.
97 if (ctx.app.config.edgeToken !== undefined) return edgeLoginUrl(next);
97 if (edgeDoor(ctx)) return edgeLoginUrl(next);
9898 return `/signin?next=${encodeURIComponent(next)}`;
9999 }
100100
src/web/layout.ts +4 −4
@@ -13,7 +13,7 @@ import { appsForRepos } from "../core/apps.ts";
1313 import { listReposVisibleTo } from "../core/repos.ts";
1414 import type { User } from "../core/users.ts";
1515 import type { Ctx } from "../http/context.ts";
16 import { edgeLoginUrl, edgeLogoutUrl } from "../http/edge.ts";
16 import { edgeDoor, edgeLoginUrl, edgeLogoutUrl } from "../http/edge.ts";
1717 import { json } from "../http/respond.ts";
1818 import { sha256 } from "../kernel/hash.ts";
1919 import { secret } from "../kernel/id.ts";
@@ -485,9 +485,9 @@ function topbar(
485485 )}`
486486 : btn("Sign in", {
487487 href:
488 ctx.app.config.edgeToken === undefined
489 ? "/signin"
490 : edgeLoginUrl(ctx.url.pathname + ctx.url.search),
488 edgeDoor(ctx)
489 ? edgeLoginUrl(ctx.url.pathname + ctx.url.search)
490 : "/signin",
491491 })}
492492 </span>
493493 </header>`;
src/web/pages/account.ts +1 −1
@@ -57,7 +57,7 @@ import {
5757 import { everydayLine } from "./everyday.ts";
5858 import { passkeyJs } from "../passkey-client.ts";
5959
60 type Section = "profile" | "password" | "tokens" | "keys" | "passkeys";
60 type Section = "profile" | "password" | "tokens" | "keys" | "passkeys" | "linked";
6161
6262 // The section list lives beside the newest page that joins it, so adding one
6363 // cannot leave the others pointing at a nav that has forgotten it.
src/web/pages/accounts.ts +1
@@ -75,6 +75,7 @@ function row(a: AccountRow, sole: readonly string[]): Html {
7575 const how = [
7676 a.via ?? (a.kind === "agent" ? "crew" : ""),
7777 a.address ?? "",
78 ...a.linked.map((m) => `linked: ${m === "edge" ? "open-platform.sh" : m}`),
7879 ].filter((s) => s !== "");
7980 const holds = [
8081 `${a.repos} ${a.repos === 1 ? "repository" : "repositories"}`,
src/web/pages/linked.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * Settings → Linked sign-in: the platform edge's sign-in (open-platform.sh)
3 * as a method a person links to the account they have, and removes later.
4 * Linking takes a signed-in browser that the edge is also vouching for on
5 * this request; the edge's word is what names the login being linked.
6 */
7
8 import { linkLogin, linksOf, unlinkLogin } from "../../core/linked_login.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { edgeIdentity } from "../../http/edge.ts";
11 import { signInFirst } from "../chrome.ts";
12 import { readForm } from "../form.ts";
13 import { html } from "../html.ts";
14 import { flashTo } from "../layout.ts";
15 import { btn, card, confirmAction, empty, time } from "../ui.ts";
16 import { accountShell } from "./account.ts";
17
18 const BACK = "/settings/linked";
19
20 /** Sessions and the edge are people at a browser; a token is not. */
21 const atBrowser = (ctx: Ctx): boolean =>
22 ctx.auth.via === "session" || ctx.auth.via === "edge";
23
24 // GET /settings/linked
25 export function linkedPage(ctx: Ctx): Response {
26 const user = ctx.auth.user;
27 if (!user) return signInFirst(ctx);
28 const name = ctx.app.config.edgeName ?? "the platform";
29 const links = linksOf(ctx.app.db, user.id);
30 const vouched = edgeIdentity(ctx.request, ctx.app.config.edgeToken);
31 const here = links.some((l) => vouched !== undefined && l.login.toLowerCase() === vouched.toLowerCase());
32 const body = html`<p class="muted small mb">
33 Linking ${name} lets its sign-in reach this account. It never makes an
34 account: that is the forge's own sign-up.
35 </p>
36 ${ctx.app.config.edgeToken === undefined
37 ? empty({ icon: "key", title: "Not available", note: "This forge has no linked sign-in methods turned on." })
38 : html`${links.length === 0
39 ? empty({ icon: "key", title: `${name} is not linked`, note: "Sign in through it to this account is off until you link it." })
40 : card(
41 html`<div class="table-scroll">
42 <table class="table" id="linked">
43 <thead><tr><th>Method</th><th>Login</th><th>Linked</th><th></th></tr></thead>
44 <tbody>
45 ${links.map(
46 (l) => html`<tr>
47 <td><strong>${name}</strong></td>
48 <td>${l.login}</td>
49 <td class="muted">${time(l.createdAt)}</td>
50 <td>${confirmAction({ action: "/settings/linked/edge/delete", verb: "Unlink", size: "sm" })}</td>
51 </tr>`,
52 )}
53 </tbody>
54 </table>
55 </div>`,
56 { pad: false },
57 )}
58 ${links.length === 0 || !here
59 ? card(
60 vouched === undefined
61 ? html`<p class="muted small">
62 Sign in at ${name} in this browser, then come back to
63 link that login to this account.
64 </p>`
65 : html`<form method="post" action="/settings/linked/edge">
66 <p class="small mb">${name} knows you as <strong>${vouched}</strong>.</p>
67 <div class="form-actions">${btn(`Link ${vouched}`, { type: "submit", variant: "primary" })}</div>
68 </form>`,
69 { head: html`<h3>Link ${name}</h3>` },
70 )
71 : null}`}`;
72 return accountShell(ctx, "linked", "Linked sign-in", body);
73 }
74
75 // POST /settings/linked/edge
76 export async function linkEdge(ctx: Ctx): Promise<Response> {
77 if (!ctx.auth.user) return signInFirst(ctx);
78 if (!atBrowser(ctx)) return new Response("forbidden", { status: 403 });
79 const form = await readForm(ctx, "admin");
80 if (form instanceof Response) return form;
81 const login = edgeIdentity(ctx.request, ctx.app.config.edgeToken);
82 if (login === undefined)
83 return flashTo(ctx, BACK, { tone: "danger", message: "Sign in at the platform first, then link it." });
84 const done = linkLogin(ctx.app.db, ctx.auth.user, "edge", login);
85 return flashTo(
86 ctx,
87 BACK,
88 done.ok
89 ? { message: "Linked." }
90 : { tone: "danger", message: done.error === "taken" ? "That login is linked to another account." : "That login cannot be linked." },
91 );
92 }
93
94 // POST /settings/linked/edge/delete
95 export async function unlinkEdge(ctx: Ctx): Promise<Response> {
96 if (!ctx.auth.user) return signInFirst(ctx);
97 if (!atBrowser(ctx)) return new Response("forbidden", { status: 403 });
98 const form = await readForm(ctx, "admin");
99 if (form instanceof Response) return form;
100 const done = unlinkLogin(ctx.app.db, ctx.auth.user, "edge");
101 return flashTo(
102 ctx,
103 BACK,
104 done.ok
105 ? { message: "Unlinked." }
106 : { tone: "danger", message: "It is your only way in. Add a passkey first." },
107 );
108 }
src/web/pages/origins.ts +7
@@ -75,6 +75,7 @@ export type AccountSection =
7575 | "keys"
7676 | "model"
7777 | "passkeys"
78 | "linked"
7879 | "origins"
7980 | "usage"
8081 | "crew"
@@ -226,6 +227,12 @@ export function accountSections(
226227 icon: "key",
227228 current: current === "passkeys",
228229 },
230 {
231 label: "Linked sign-in",
232 href: "/settings/linked",
233 icon: "globe",
234 current: current === "linked",
235 },
229236 {
230237 label: "Origins",
231238 href: "/settings/origins",
src/web/pages/site.ts +13 −7
@@ -25,7 +25,7 @@ import { isThemeName } from "../../design/themes.ts";
2525 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
2626 import { studioDoor, studioHome } from "../studio/home.ts";
2727 import { homeTop } from "../studio/asks_page.ts";
28 import { edgeLoginUrl } from "../../http/edge.ts";
28 import { edgeDoor, edgeLoginUrl } from "../../http/edge.ts";
2929 import { sshCommand } from "../../ssh/command.ts";
3030 import { hostOf, pageHead, signInFirst } from "../chrome.ts";
3131 import { SignupSlot, signupWindow } from "../../actions/signup-window.ts";
@@ -247,10 +247,16 @@ function authForm(
247247 // Behind a platform edge, that is the door: the button first, and the
248248 // password form kept for the accounts that have one — an account the edge
249249 // made has none, and the note says so before anyone types.
250 const edge =
251 ctx.app.config.edgeToken === undefined
252 ? undefined
253 : (ctx.app.config.edgeName ?? "the platform");
250 const edgeName = ctx.app.config.edgeName ?? "the platform";
251 const edge = edgeDoor(ctx) ? edgeName : undefined;
252 const unlinked =
253 ctx.app.config.edgeToken !== undefined && !edgeDoor(ctx)
254 ? html`<p class="muted small mb">
255 ${edgeName} knows who you are, but that sign-in is not linked to an
256 account here. ${kind === "signup" ? "Make one below" : "Sign in below, or make an account"},
257 then link ${edgeName} in Settings.
258 </p>`
259 : null;
254260 const throughEdge = when(
255261 edge,
256262 (name) =>
@@ -263,7 +269,7 @@ function authForm(
263269 <p class="muted small">
264270 ${kind === "signin"
265271 ? `Accounts made through ${name} sign in there and have no password here. The form below is for an account that was given one.`
266 : `Signing in through ${name} makes your account on first sight; the form below makes one with a password instead.`}
272 : `Signing in through ${name} works once you link it to an account: make one below, then link it in Settings.`}
267273 </p>
268274 </div>`,
269275 );
@@ -272,7 +278,7 @@ function authForm(
272278 // a passkey, made in the browser (`signup-passkey.ts`).
273279 const byPasskey = kind === "signup" && ctx.app.config.passkeyOnlySignup === true;
274280
275 const body = html`${throughEdge}
281 const body = html`${throughEdge}${unlinked}
276282 <form method="post" action="${action}">
277283 ${formField({
278284 label: "Username",
src/web/studio/home.ts +2 −2
@@ -22,7 +22,7 @@ import { LOOK_SIZES } from "../../core/looks.ts";
2222 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
2323 import { type User } from "../../core/users.ts";
2424 import type { Ctx } from "../../http/context.ts";
25 import { edgeLoginUrl } from "../../http/edge.ts";
25 import { edgeDoor, edgeLoginUrl } from "../../http/edge.ts";
2626 import { sshCommand } from "../../ssh/command.ts";
2727 import { repoBase, signInFirst } from "../chrome.ts";
2828 import { field, readForm, type Form } from "../form.ts";
@@ -488,7 +488,7 @@ export function studioDoor(ctx: Ctx): Response {
488488 <div class="bar">
489489 ${ctx.auth.user !== undefined
490490 ? null
491 : ctx.app.config.edgeToken === undefined
491 : !edgeDoor(ctx)
492492 ? html`${btn("Create an account", {
493493 href: `/signup${nextQuery}`,
494494 variant: "primary",
test/accounts.test.ts +8 −6
@@ -24,6 +24,8 @@ import { createRun, getRun } from "../src/core/runs.ts";
2424 import { createSession } from "../src/core/sessions.ts";
2525 import { createToken } from "../src/core/tokens.ts";
2626 import { createUser as insertAgent, getUserByName } from "../src/core/users.ts";
27 import { linkLogin } from "../src/core/linked_login.ts";
28 import { listAccounts } from "../src/core/accounts.ts";
2729 import { serve, type Servers } from "../src/http/server.ts";
2830 import { forgeSshSession, identityFor } from "../src/tui/ssh.ts";
2931 import { proveAll } from "./helpers/verified.ts";
@@ -120,16 +122,15 @@ describe("accounts: the owner sees, suspends and removes", () => {
120122 expect(typeof made?.payload["address"]).toBe("string");
121123 });
122124
123 test("an account the edge makes is audited too", async () => {
125 test("an account the edge made before is kept, linked and shown to the owner", async () => {
126 const made = await insertAgent(app.db, { origin: "seed", username: "edgy", email: "[email protected]" });
127 if (!made.ok) throw new Error(made.error);
128 app.bus.append({ kind: "user.created", actorId: made.value.id, payload: { via: "edge" } });
129 linkLogin(app.db, made.value, "edge", "edgy");
124130 const res = await fetch(`${base}/api/v1/user`, {
125131 headers: { "x-plat-user": "edgy", "x-plat-edge-token": EDGE },
126132 });
127133 expect(res.status).toBe(200);
128 const user = getUserByName(app.db, "edgy")!;
129 const made = listEvents(app.db, { kind: "user.created" }).find(
130 (e) => e.actorId === user.id,
131 );
132 expect(made?.payload["via"]).toBe("edge");
133134 });
134135
135136 test("the owner hears of a new account once", async () => {
@@ -186,6 +187,7 @@ describe("accounts: the owner sees, suspends and removes", () => {
186187 expect(ada.spentUsd).toBe(0);
187188 expect(ada.suspendedAt).toBeNull();
188189 expect(items.find((i) => i.username === "edgy")?.via).toBe("edge");
190 expect(listAccounts(app.db).find((a) => a.username === "edgy")?.linked).toEqual(["edge"]);
189191 const page = await fetch(`${base}/settings/accounts`, {
190192 headers: { authorization: `Bearer ${ownerToken}` },
191193 });
test/edge-auth.test.ts +20 −1
@@ -6,6 +6,8 @@ import { createApp, type App } from "../src/app.ts";
66 import { edgeIdentity, edgeLoginUrl, edgeLogoutUrl } from "../src/http/edge.ts";
77 import { serve, type Servers } from "../src/http/server.ts";
88 import { seedAdmin } from "./helpers/admin.ts";
9 import { linkLogin } from "../src/core/linked_login.ts";
10 import { createUser } from "../src/core/users.ts";
911
1012 const TOKEN = "edge-secret-0123456789";
1113
@@ -69,6 +71,11 @@ describe("a forge behind the platform edge", () => {
6971 base = servers.url;
7072 const olive = await seedAdmin(app, { username: "olive", email: "[email protected]" });
7173 if (!olive.ok) throw new Error(olive.error);
74 // The edge reaches only accounts a person linked.
75 const ada = await createUser(app.db, { origin: "seed", username: "ada", email: "[email protected]" });
76 if (!ada.ok) throw new Error(ada.error);
77 linkLogin(app.db, ada.value, "edge", "ada");
78 linkLogin(app.db, olive.value, "edge", "olive");
7279 });
7380
7481 afterAll(async () => {
@@ -83,7 +90,7 @@ describe("a forge behind the platform edge", () => {
8390 expect(page).not.toContain('href="/signin"');
8491 });
8592
86 test("the first person the edge vouches for is made on sight, not as admin", async () => {
93 test("a linked login is that account, not an admin", async () => {
8794 const me = await fetch(`${base}/api/v1/user`, { headers: asAda });
8895 expect(me.status).toBe(200);
8996 const body = (await me.json()) as { username: string; isAdmin: boolean };
@@ -97,6 +104,18 @@ describe("a forge behind the platform edge", () => {
97104 expect(page).toContain('href="/_plat/logout?rd=%2F"');
98105 });
99106
107 test("a login nobody linked is nobody, and makes no account", async () => {
108 const stranger = { "x-plat-user": "mallory", "x-plat-edge-token": TOKEN };
109 expect((await fetch(`${base}/api/v1/user`, { headers: stranger })).status).toBe(401);
110 expect(app.db.query("SELECT 1 FROM user WHERE username = 'mallory'").get()).toBeNull();
111 // An account of the same name that was not linked is not theirs either.
112 const squat = { "x-plat-user": "olive2", "x-plat-edge-token": TOKEN };
113 expect((await fetch(`${base}/api/v1/user`, { headers: squat })).status).toBe(401);
114 // They are sent to the forge's own sign-in, not round the edge again.
115 const page = await fetch(`${base}/new`, { headers: stranger, redirect: "manual" });
116 expect(page.headers.get("location")).toBe("/signin?next=%2Fnew");
117 });
118
100119 test("a page that needs a person sends a stranger to the edge, not the password form", async () => {
101120 const response = await fetch(`${base}/new`, { redirect: "manual" });
102121 expect(response.status).toBe(303);
test/linked-signin.test.ts added +130
@@ -0,0 +1,130 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { serve, type Servers } from "../src/http/server.ts";
7 import { createSession } from "../src/core/sessions.ts";
8 import { linkedUser, linksOf } from "../src/core/linked_login.ts";
9 import { createUser, getUserByName } from "../src/core/users.ts";
10 import { listAccounts } from "../src/core/accounts.ts";
11 import { setSignup } from "../src/settings/signup.ts";
12
13 const TOKEN = "edge-secret-0123456789";
14 const ORIGIN = "https://forge.example";
15 const edge = (login: string) => ({ "x-plat-user": login, "x-plat-edge-token": TOKEN });
16
17 describe("the platform edge is a linked method", () => {
18 let dataDir: string;
19 let app: App;
20 let servers: Servers;
21 let base: string;
22 let cookie: string;
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-linked-"));
26 app = createApp({ dataDir, port: 0, url: ORIGIN, edgeToken: TOKEN });
27 servers = await serve(app);
28 base = servers.url;
29 const made = await createUser(app.db, {
30 origin: "seed",
31 username: "grace",
32 email: "[email protected]",
33 password: "a-good-passphrase",
34 });
35 if (!made.ok) throw new Error(made.error);
36 cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
37 });
38 afterAll(async () => {
39 servers.stop();
40 app.close();
41 await rm(dataDir, { recursive: true, force: true });
42 });
43
44 const me = (login: string) => fetch(`${base}/api/v1/user`, { headers: edge(login) });
45 const post = (path: string, headers: Record<string, string>) =>
46 fetch(`${base}${path}`, { method: "POST", headers: { origin: ORIGIN, ...headers }, redirect: "manual" });
47
48 test("an edge sign-in for an unknown person creates nothing", async () => {
49 expect((await me("newbie")).status).toBe(401);
50 expect(getUserByName(app.db, "newbie")).toBeUndefined();
51 });
52
53 test("with signup closed, an unknown edge sign-in is refused and the signup page says so", async () => {
54 setSignup(app.db, "closed", "boot");
55 expect((await me("newbie")).status).toBe(401);
56 const page = await fetch(`${base}/signup`, { headers: edge("newbie") }).then((r) => r.text());
57 expect(page).toContain("Signup is closed on this forge.");
58 setSignup(app.db, "open", "boot");
59 });
60
61 test("linking needs a signed-in browser and the edge's word, and a cross-site post is refused", async () => {
62 expect((await post("/settings/linked/edge", { cookie })).headers.get("location")).toContain("/settings/linked");
63 expect(linksOf(app.db, getUserByName(app.db, "grace")!.id)).toEqual([]);
64 const cross = await post("/settings/linked/edge", { cookie, ...edge("grace-at-platform"), origin: "https://evil.example" });
65 expect(cross.status).toBe(403);
66 expect(linksOf(app.db, getUserByName(app.db, "grace")!.id)).toEqual([]);
67 });
68
69 test("link, then the linked sign-in reaches the same account", async () => {
70 const linked = await post("/settings/linked/edge", { cookie, ...edge("grace-at-platform") });
71 expect(linked.status).toBe(303);
72 const grace = getUserByName(app.db, "grace")!;
73 expect(linkedUser(app.db, "edge", "Grace-At-Platform")?.id).toBe(grace.id);
74 const who = await me("grace-at-platform");
75 expect(((await who.json()) as { username: string }).username).toBe("grace");
76 const page = await fetch(`${base}/settings/linked`, { headers: { cookie } }).then((r) => r.text());
77 expect(page).toContain("grace-at-platform");
78 });
79
80 test("another account cannot take a login that is linked", async () => {
81 const other = await createUser(app.db, { origin: "seed", username: "heidi", email: "[email protected]", password: "a-good-passphrase" });
82 if (!other.ok) throw new Error(other.error);
83 const heidi = `forge_session=${createSession(app.db, other.value.id).token}`;
84 await post("/settings/linked/edge", { cookie: heidi, ...edge("grace-at-platform") });
85 expect(linksOf(app.db, other.value.id)).toEqual([]);
86 expect(linkedUser(app.db, "edge", "grace-at-platform")?.username).toBe("grace");
87 });
88
89 test("unlinking removes the way in", async () => {
90 const gone = await post("/settings/linked/edge/delete", { cookie });
91 expect(gone.status).toBe(303);
92 expect((await me("grace-at-platform")).status).toBe(401);
93 });
94
95 test("the only way in is not removed", async () => {
96 const lone = await createUser(app.db, { origin: "seed", username: "ivan", email: "[email protected]" });
97 if (!lone.ok) throw new Error(lone.error);
98 const ivan = `forge_session=${createSession(app.db, lone.value.id).token}`;
99 await post("/settings/linked/edge", { cookie: ivan, ...edge("ivan") });
100 await post("/settings/linked/edge/delete", { cookie: ivan });
101 expect(linkedUser(app.db, "edge", "ivan")?.username).toBe("ivan");
102 });
103
104 test("an account the edge made before is kept, linked and listed", async () => {
105 const old = await createUser(app.db, { origin: "seed", username: "oldtimer", email: "[email protected]" });
106 if (!old.ok) throw new Error(old.error);
107 app.db.query("INSERT INTO event (id, kind, actor_id, payload) VALUES ('ev-old', 'user.created', ?1, '{\"via\":\"edge\"}')").run(old.value.id);
108 app.db.exec("DELETE FROM linked_login WHERE login = 'oldtimer'");
109 const migration = (await import("../src/core/migrations/20261018120000-linked-login.ts")).default;
110 app.db.exec(migration.replace(/CREATE TABLE linked_login[\s\S]*?WITHOUT ROWID;|CREATE INDEX[^;]*;/g, ""));
111 expect(linkedUser(app.db, "edge", "oldtimer")?.id).toBe(old.value.id);
112 const row = listAccounts(app.db).find((a) => a.username === "oldtimer");
113 expect(row?.linked).toEqual(["edge"]);
114 });
115 });
116
117 test("with the edge turned off nothing offers it and the headers are ignored", async () => {
118 const dataDir = await mkdtemp(join(tmpdir(), "forge-linked-off-"));
119 const app = createApp({ dataDir, port: 0, url: ORIGIN });
120 const servers = await serve(app);
121 try {
122 const page = await fetch(`${servers.url}/signin`).then((r) => r.text());
123 expect(page).not.toContain("/_plat/login");
124 expect((await fetch(`${servers.url}/api/v1/user`, { headers: edge("grace") })).status).toBe(401);
125 } finally {
126 servers.stop();
127 app.close();
128 await rm(dataDir, { recursive: true, force: true });
129 }
130 });
test/no-signup-admin.test.ts +2 −8
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { signUp } from "../src/actions/users.ts";
14 import { createUser, ensureEdgeUser, getUserByName } from "../src/core/users.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
1515 import { serve, type Servers } from "../src/http/server.ts";
1616 import { quietLogs } from "./helpers/globals.ts";
1717 import { passkeyFields } from "./helpers/passkey.ts";
@@ -88,19 +88,13 @@ test("the first account from the terminal's sign-up is not an admin", async () =
8888 expect(admins(app)).toBe(0);
8989 });
9090
91 test("the first account the platform edge makes is not an admin", async () => {
92 const app = await fresh();
93 expect((await ensureEdgeUser(app.db, "edgy", "f.test"))?.isAdmin).toBe(false);
94 expect(admins(app)).toBe(0);
95 });
96
9791 test("no other origin makes the admin of a forge with none, whatever its door", async () => {
9892 for (const origin of ["signup", "passkey", "parent"] as const) {
9993 const app = await fresh();
10094 const made = await createUser(app.db, { origin, slot: fixtureSlot(app), username: origin, email: `${origin}@f.test` });
10195 expect(made.ok && made.value.isAdmin).toBe(false);
10296 }
103 for (const origin of ["edge", "everyday", "agent", "spawn"] as const) {
97 for (const origin of ["everyday", "agent", "spawn"] as const) {
10498 const app = await fresh();
10599 const made = await createUser(app.db, { origin, username: origin, email: `${origin}@f.test` });
106100 expect(made.ok && made.value.isAdmin).toBe(false);
test/reserved-names.test.ts −11
@@ -10,7 +10,6 @@ import { updateProfile } from "../src/actions/users.ts";
1010 import { reservedName, SYSTEM_NAMES, skeleton } from "../src/core/reserved.ts";
1111 import {
1212 createUser,
13 ensureEdgeUser,
1413 getUserByName,
1514 } from "../src/core/users.ts";
1615 import { isSafeName } from "../src/git/guard.ts";
@@ -153,16 +152,6 @@ describe("reserved names", () => {
153152 expect(getUserByName(app.db, "sc0ut")).toBeUndefined();
154153 });
155154
156 test("the edge cannot bring in a reserved name", async () => {
157 expect(await ensureEdgeUser(app.db, "sc0ut", "f.dev")).toBeUndefined();
158 expect(await ensureEdgeUser(app.db, "admin", "f.dev")).toBeUndefined();
159 expect(getUserByName(app.db, "sc0ut")).toBeUndefined();
160 // An account that already exists still signs in by its own name.
161 expect((await ensureEdgeUser(app.db, "trevato", "f.dev"))?.username).toBe(
162 "trevato",
163 );
164 });
165
166155 test("an organization cannot take a reserved name", () => {
167156 // ada signed up over HTTP; founding an org needs a proven email first.
168157 proveAll(app);
test/signup-closed.test.ts +3 −8
@@ -73,18 +73,13 @@ describe("closed signup", () => {
7373 });
7474 }
7575
76 test("existing accounts still sign in through the edge when closed", async () => {
77 mode("open");
78 expect((await me("founder")).status).toBe(200);
79 mode("closed");
80 expect((await me("founder")).status).toBe(200);
81 });
82
8376 test("open makes accounts; switching takes effect on the next request", async () => {
8477 mode("open");
8578 expect(await (await fetch(`${base}/signup`)).text()).toContain('name="password"');
8679 expect((await post("newcomer")).status).toBe(201);
87 expect((await me("edgy")).status).toBe(200);
80 // Even open, the edge makes nothing: signup is the forge's own door.
81 expect((await me("edgy")).status).toBe(401);
82 expect(getUserByName(app.db, "edgy")).toBeUndefined();
8883 mode("closed");
8984 expect((await post("late")).status).toBe(403);
9085 expect((await me("later")).status).toBe(401);
test/signup.test.ts +1 −8
@@ -263,13 +263,6 @@ describe("signup closed (#2166)", () => {
263263 });
264264 }
265265
266 test("existing accounts still sign in by the edge while closed", async () => {
267 setSignup(app.db, "open", "boot");
268 expect((await edge("returning")).status).toBe(200);
269 setSignup(app.db, "closed", "boot");
270 expect((await edge("returning")).status).toBe(200);
271 });
272
273266 test("open: page has the form and the API makes the account", async () => {
274267 setSignup(app.db, "open", "boot");
275268 const text = await fetch(`${servers.url}/signup`).then((r) => r.text());
@@ -282,6 +275,6 @@ describe("signup closed (#2166)", () => {
282275 expect((await post(newcomer())).status).toBe(403);
283276 setSignup(app.db, "open", "boot");
284277 expect((await post(newcomer())).status).toBe(201);
285 expect((await edge("latecomer")).status).toBe(200);
278 expect((await edge("latecomer")).status).toBe(401);
286279 });
287280 });
test/verify-email.test.ts −17
@@ -212,23 +212,6 @@ describe("verified email", () => {
212212 ).toBe(true);
213213 });
214214
215 test("an account the edge makes must prove an address too", async () => {
216 const edged = createApp({
217 dataDir: await mkdtemp(join(tmpdir(), "forge-verify-edge-")),
218 port: 0,
219 url: "https://forge.example",
220 edgeToken: "edge-secret",
221 mailer: async () => true,
222 });
223 const { ensureEdgeUser } = await import("../src/core/users.ts");
224 const first = await ensureEdgeUser(edged.db, "founder", "forge.example");
225 const second = await ensureEdgeUser(edged.db, "newcomer", "forge.example");
226 // The first is no admin, so it is not proven by being first.
227 expect(emailVerified(edged.db, first!.id)).toBe(false);
228 expect(emailVerified(edged.db, second!.id)).toBe(false);
229 edged.close();
230 });
231
232215 test("a way in that does not vouch for the address is held back (fail closed)", async () => {
233216 // Any future path that makes a person without saying "trusted" — a
234217 // linked sign-in, an invite — starts unproven.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs