Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mise.toml
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ flag "-L --log-level <level>" {
}
flag "--log-output <path>" help="Write logs to a file"
flag "-S --no-seed" help="Skip database seeding"
flag "--login-link <email>" 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"

Expand Down
43 changes: 43 additions & 0 deletions packages/drfed/src/dev-login.ts
Original file line number Diff line number Diff line change
@@ -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 <https://www.gnu.org/licenses/>.
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<URL | undefined> {
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);
}
24 changes: 24 additions & 0 deletions packages/drfed/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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 {
Expand Down Expand Up @@ -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);
Expand All @@ -252,6 +260,22 @@ async function runServer(configuration: ServerOptions) {
}
}

async function logLoginLink(
db: Database,
email: string,
origin: string,
): Promise<void> {
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<void> {
Expand Down
47 changes: 47 additions & 0 deletions packages/drfed/src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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", {
Expand Down Expand Up @@ -313,6 +331,30 @@ function required<T>(
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<string>,
): { 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.
Expand Down Expand Up @@ -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,
Expand Down
12 changes: 0 additions & 12 deletions packages/graphql/src/auth/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,6 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// 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<string> =>
new Uint8Array(
await crypto.subtle.digest("SHA-256", textEncoder.encode(raw)),
Expand Down
4 changes: 2 additions & 2 deletions packages/graphql/src/auth/magic-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
23 changes: 22 additions & 1 deletion packages/models/src/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
19 changes: 16 additions & 3 deletions scripts/dev.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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,
Expand Down
Loading