From a33a15af8dd96f8e00d62429eeab730018047b40 Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Mon, 16 Nov 2026 16:51:32 +0900 Subject: [PATCH] Log a login link from the development server mise run dev --login-link= logs, right after the server starts listening, a link that logs in as the account with that email address, so that a seeded account can be used without reading login mail. An empty value, --login-link=, means owner@example.com, since mise task flags cannot take an optional value. The task passes the address to the new hidden --dev-login-link option of drfed-server, together with the origin of the frontend development server through the new hidden --dev-login-origin option, which must be one of the login origins. When the server serves the frontend, the origin defaults to the public web origin; otherwise it is required. The server stores a login challenge for the account and logs the frontend's confirmation link. An address no account has is only warned about. The challenge is the one loginByEmail stores, so it is single-use and expires after 15 minutes; the challenge code generator moves to @drfed/models/login as generateLoginChallengeCode() so that both share it. AI assistance: the maintainer asked Claude Code for a dev task option that logs a login link after startup. Claude Code designed the hidden server options, wrote the code, and moved the code generator. The maintainer found that the first design, which took the first login origin, pointed to the GraphQL server. The build, checks, and affected tests were run, and the logged link was completed through completeLoginChallenge against a PGlite server. Assisted-by: Claude Code:claude-opus-5-5 --- mise.toml | 1 + packages/drfed/src/dev-login.ts | 43 ++++++++++++++++++++++ packages/drfed/src/index.ts | 24 +++++++++++++ packages/drfed/src/parser.ts | 47 +++++++++++++++++++++++++ packages/graphql/src/auth/hash.ts | 12 ------- packages/graphql/src/auth/magic-link.ts | 4 +-- packages/models/src/login.ts | 23 +++++++++++- scripts/dev.mts | 19 ++++++++-- 8 files changed, 155 insertions(+), 18 deletions(-) create mode 100644 packages/drfed/src/dev-login.ts diff --git a/mise.toml b/mise.toml index 6f804a46..1d03215e 100644 --- a/mise.toml +++ b/mise.toml @@ -434,6 +434,7 @@ flag "-L --log-level " { } flag "--log-output " help="Write logs to a file" flag "-S --no-seed" help="Skip database seeding" +flag "--login-link " help="Log a login link for the account with this email address after startup; an empty value (--login-link=) means owner@example.com" ''' run = "node scripts/dev.mts" diff --git a/packages/drfed/src/dev-login.ts b/packages/drfed/src/dev-login.ts new file mode 100644 index 00000000..3d74af61 --- /dev/null +++ b/packages/drfed/src/dev-login.ts @@ -0,0 +1,43 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +import { type Database, normalizeEmail } from "@drfed/models"; +import { generateLoginChallengeCode } from "@drfed/models/login"; +import { loginChallenges } from "@drfed/models/schema"; +import { uuidV7 } from "@drfed/models/uuid"; + +/** + * Creates a login challenge for an existing account and composes the link + * that completes it on the web frontend, without sending any mail. The link + * follows the verify URL the frontend's sign-in page sends to `loginByEmail`. + * @param db The database to look the account up in and store the challenge. + * @param email The email address of the account to log in as. + * @param origin The web frontend origin that serves the confirmation page. + * @returns The login link, or `undefined` if no account has the address. + */ +export async function createLoginLink( + db: Database, + email: string, + origin: string, +): Promise { + const account = await db.query.accounts.findFirst({ + where: { email: normalizeEmail(email) }, + }); + if (account == null) return undefined; + const id = uuidV7(); + const code = generateLoginChallengeCode(); + await db.insert(loginChallenges).values({ id, accountId: account.id, code }); + return new URL(`/confirm/${id}?code=${code}`, origin); +} diff --git a/packages/drfed/src/index.ts b/packages/drfed/src/index.ts index e983aeab..5ceda02d 100644 --- a/packages/drfed/src/index.ts +++ b/packages/drfed/src/index.ts @@ -20,6 +20,7 @@ import process from "node:process"; import createFederation, { createInboundRecorder } from "@drfed/federation"; import { KeyGenerationQueue } from "@drfed/federation/task-queue"; import { createYogaServer } from "@drfed/graphql"; +import type { Database } from "@drfed/models"; import { type WebRuntime, createWebRuntime } from "@drfed/web"; import { PgliteKvStore } from "@fedify/pglite"; import { PostgresKvStore } from "@fedify/postgres"; @@ -35,6 +36,7 @@ import { printError, run } from "@optique/run"; import { serve } from "srvx"; import metadata from "../package.json" with { type: "json" }; +import { createLoginLink } from "./dev-login.ts"; import { describeServerConfiguration } from "./diagnostics.ts"; import { OperationRegistry } from "./operations.ts"; import { @@ -231,6 +233,12 @@ async function runServer(configuration: ServerOptions) { { origin: options.publicOrigin.origin }, ); } + const { loginLink } = options; + if (loginLink !== undefined) { + await operations.run(() => + logLoginLink(db, loginLink.email, loginLink.origin), + ); + } } catch (error) { process.off("SIGINT", shutdown); process.off("SIGTERM", shutdown); @@ -252,6 +260,22 @@ async function runServer(configuration: ServerOptions) { } } +async function logLoginLink( + db: Database, + email: string, + origin: string, +): Promise { + const logger = getLogger(["drfed", "server"]); + const link = await createLoginLink(db, email, origin); + if (link === undefined) { + logger.warn("Cannot create a login link; no account has {email}.", { + email, + }); + return; + } + logger.info("Log in as {email} at {link}.", { email, link: link.href }); +} + async function runSchemaGenerator( options: SchemaGeneratorOptions, ): Promise { diff --git a/packages/drfed/src/parser.ts b/packages/drfed/src/parser.ts index bf8a95e9..edebe826 100644 --- a/packages/drfed/src/parser.ts +++ b/packages/drfed/src/parser.ts @@ -61,6 +61,8 @@ export const valueOptionNames = { dataPath: ["--pglite-data-path", "--data-path", "-d"], postgresUrl: ["--postgres-url", "--database-url", "-D"], migrationLockTimeout: ["--migration-lock-timeout"], + devLoginLink: ["--dev-login-link"], + devLoginOrigin: ["--dev-login-origin"], ...mailValueOptionNames, logLevel: loggingValueOptionNames.logLevel, logFormat: loggingValueOptionNames.logFormat, @@ -226,6 +228,22 @@ export function createParser( description: message`Seed initial development data.`, hidden: true, }), + loginLink: optional( + option(...valueOptionNames.devLoginLink, email(), { + description: message`Log a link that logs in as the account with this email address once the server is listening.`, + hidden: true, + }), + ), + loginLinkOrigin: optional( + option( + ...valueOptionNames.devLoginOrigin, + origin({ allowedProtocols: ["http:", "https:"] }), + { + description: message`The web frontend origin of the logged login link. Defaults to the public web origin when serving the frontend.`, + hidden: true, + }, + ), + ), logging, printConfig: withDefault( flag("--print-config", { @@ -313,6 +331,30 @@ function required( return value.value; } +/** + * Pair the account of a development login link with the frontend origin + * that confirms it, which must be allowed in login links. + * @returns The link to log, or `undefined` if none was requested. + */ +function resolveLoginLink( + account: string | undefined, + frontend: URL | undefined, + loginOrigins: ReadonlySet, +): { readonly email: string; readonly origin: string } | undefined { + if (account === undefined) return undefined; + if (frontend === undefined) { + throw new Error( + "Option --dev-login-link needs --dev-login-origin when the frontend is not served.", + ); + } + if (!loginOrigins.has(frontend.origin)) { + throw new Error( + "The configured login origins must include the login link origin.", + ); + } + return { email: account, origin: frontend.origin }; +} + /** * Resolve domain constraints only after the source contexts have completed. * @returns Plain startup options; no database, mail or log sink is created. @@ -395,6 +437,11 @@ export function resolveOptions(options: RawOptions, cwd = process.cwd()) { mail: mail.mail, mailDiagnostic: mail.diagnostic, seed: server.seed, + loginLink: resolveLoginLink( + server.loginLink, + server.loginLinkOrigin ?? publicOrigin, + loginOrigins, + ), logging, drizzle: { ...database.database, diff --git a/packages/graphql/src/auth/hash.ts b/packages/graphql/src/auth/hash.ts index fec66934..75dfe751 100644 --- a/packages/graphql/src/auth/hash.ts +++ b/packages/graphql/src/auth/hash.ts @@ -15,18 +15,6 @@ // along with this program. If not, see . // oxlint-disable func-names func-style id-length -// oxlint-disable no-magic-numbers -const BASE36_CHAR = "0123456789abcdefghijklmnopqrstuvwxyz"; - -// It's not strictly uniform random sampling, but it's negligible enough. -export const generateBase36Code = (len: number): string => - Array.from( - // Choose `Uint16Array` cause `2 ** 16 % 36 = 16` - // It's greater than `2 ** 8 % 36 = 2 ** 32 % 36 = 4`. - crypto.getRandomValues(new Uint16Array(len)), - (num) => BASE36_CHAR[num % BASE36_CHAR.length], - ).join(""); - export const hashSecret = async (raw: string): Promise => new Uint8Array( await crypto.subtle.digest("SHA-256", textEncoder.encode(raw)), diff --git a/packages/graphql/src/auth/magic-link.ts b/packages/graphql/src/auth/magic-link.ts index 05d96e56..f55bfd51 100644 --- a/packages/graphql/src/auth/magic-link.ts +++ b/packages/graphql/src/auth/magic-link.ts @@ -17,11 +17,11 @@ // oxlint-disable no-magic-numbers import { schema } from "@drfed/models"; +import { generateLoginChallengeCode } from "@drfed/models/login"; import { type Uuid, uuidV7 } from "@drfed/models/uuid"; import builder, { type UserContext } from "../builder.ts"; import expandVerifyUrl from "./expand.ts"; -import { generateBase36Code } from "./hash.ts"; import { sendMail } from "./mail.ts"; interface LoginChallengeShape { @@ -61,7 +61,7 @@ builder.mutationFields((t) => ({ }, async resolve(_root, { email, verifyUrl }, ctx) { const challengeId = uuidV7(); - const code = generateBase36Code(schema.LOGIN_CHALLENGE_CODE_LENGTH); + const code = generateLoginChallengeCode(); const loginUrl = expandVerifyUrl({ challengeId, code, diff --git a/packages/models/src/login.ts b/packages/models/src/login.ts index 1502773d..331d9e98 100644 --- a/packages/models/src/login.ts +++ b/packages/models/src/login.ts @@ -18,9 +18,30 @@ import { type SQL, and, eq, gt, isNull, sql } from "drizzle-orm/sql"; import type { Database, Transaction } from "./db.ts"; -import { type LoginChallenge, loginChallenges } from "./schema.ts"; +import { + LOGIN_CHALLENGE_CODE_LENGTH, + type LoginChallenge, + loginChallenges, +} from "./schema.ts"; import type { Uuid } from "./uuid.ts"; +const LOGIN_CHALLENGE_CODE_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + +/** + * Generates the plaintext code of a login challenge: lowercase base-36 + * characters of {@link LOGIN_CHALLENGE_CODE_LENGTH}. + * @returns A random login challenge code. + */ +export const generateLoginChallengeCode = (): string => + Array.from( + // `Uint16Array` keeps the modulo bias small, since `2 ** 16 % 36 = 16` + // while `2 ** 8 % 36 = 2 ** 32 % 36 = 4`. It is not strictly uniform, + // but the bias is negligible. + crypto.getRandomValues(new Uint16Array(LOGIN_CHALLENGE_CODE_LENGTH)), + (num) => + LOGIN_CHALLENGE_CODE_ALPHABET[num % LOGIN_CHALLENGE_CODE_ALPHABET.length], + ).join(""); + /** * An error that occurs when a login challenge operation fails. */ diff --git a/scripts/dev.mts b/scripts/dev.mts index 1c2992bf..b28cd60c 100644 --- a/scripts/dev.mts +++ b/scripts/dev.mts @@ -48,9 +48,12 @@ try { // DNS or /etc/hosts setup, which is what makes per-instance subdomains usable // in development. const defaultRootOrigin = "http://drfed.localhost:8888"; -const defaultLoginOrigins = [ - process.env.DRFED_PUBLIC_ORIGIN ?? "http://localhost:3000", -]; +// The seeded owner account, logged in as when --login-link has no address. +const defaultLoginLinkEmail = "owner@example.com"; +// Where the frontend development server runs, which login links point to. +const frontendOrigin = + process.env.DRFED_PUBLIC_ORIGIN ?? "http://localhost:3000"; +const defaultLoginOrigins = [frontendOrigin]; const isWindows = process.platform === "win32"; const pnpm = isWindows ? "pnpm.cmd" : "pnpm"; @@ -364,6 +367,16 @@ try { serverArgs.push("--dev-seed"); } + // The variable is set, possibly to an empty string, only when the flag is + // given. + const loginLink = process.env.usage_login_link; + if (loginLink != null) { + serverArgs.push( + `--dev-login-link=${loginLink === "" ? defaultLoginLinkEmail : loginLink}`, + `--dev-login-origin=${frontendOrigin}`, + ); + } + serverProcess = spawnManaged( process.execPath, serverArgs,