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
6 changes: 6 additions & 0 deletions .changeset/brave-links-arrive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@emdash-cms/auth": patch
"emdash": patch
---

Fixes email-verification signup, which could not be completed: the verification email linked to the JSON API endpoint instead of the signup page, the signup page itself redirected anonymous visitors to login, and that redirect dropped the `?token=` from the URL. The email now links to `/_emdash/admin/signup?token=…` (as the invite email already did), the page is reachable without a session, and the login redirect preserves the query string of the page it returns to.
6 changes: 3 additions & 3 deletions e2e/tests/auth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const SECURITY_SETTINGS_URL_PATTERN = /\/settings\/security/;
const LOGIN_OR_ADMIN_URL_PATTERN = /\/(login|admin)/;
const SECURITY_MENUITEM_REGEX = /Security/i;
const ADD_PASSKEY_REGEX = /Add Passkey/i;
const SIGN_HEADING_REGEX = /sign/i;
const SIGNUP_OR_LOGIN_HEADING_REGEX = /create an account|sign in/i;

test.describe("Authentication", () => {
test.describe("Login Page", () => {
Expand Down Expand Up @@ -238,10 +238,10 @@ test.describe("Signup Page", () => {
// Navigate directly (not through admin which has auth)
await admin.page.goto("/_emdash/admin/signup");

// Wait for the React app to hydrate and render a heading with sign-related content.
// Wait for the React app to hydrate and render the signup heading.
// The SPA may render the login page if signup is disabled, so accept either.
await expect(
admin.page.getByRole("heading", { level: 1, name: SIGN_HEADING_REGEX }),
admin.page.getByRole("heading", { level: 1, name: SIGNUP_OR_LOGIN_HEADING_REGEX }),
).toBeVisible({
timeout: 15000,
});
Expand Down
6 changes: 4 additions & 2 deletions packages/auth/src/signup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ export async function requestSignup(
expiresAt: new Date(Date.now() + TOKEN_EXPIRY_MS),
});

// Build verification URL
const url = new URL("/_emdash/api/auth/signup/verify", config.baseUrl);
// Build the verification URL pointing at the admin UI page, not the API
// endpoint: the page reads `?token=` and calls the API itself. Same shape
// as the invite link (see invite.ts).
const url = new URL(`${config.baseUrl}/admin/signup`);
url.searchParams.set("token", token);

// Send email
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/astro/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,8 +331,11 @@ async function handleEmDashAuth(
const { url, locals } = context;
const { emdash } = locals;

// Pages an anonymous visitor must be able to reach: login itself, and the
// two token-bearing pages that emails link to.
const isPublicAdminRoute =
url.pathname.startsWith("/_emdash/admin/login") ||
url.pathname.startsWith("/_emdash/admin/signup") ||
url.pathname.startsWith("/_emdash/admin/invite/accept");
const isApiRoute = url.pathname.startsWith("/_emdash/api");

Expand Down Expand Up @@ -681,7 +684,9 @@ async function handlePasskeyAuth(
return apiError("NOT_AUTHENTICATED", "Not authenticated", 401);
}
const loginUrl = new URL("/_emdash/admin/login", getPublicOrigin(url, emdash?.config));
loginUrl.searchParams.set("redirect", url.pathname);
// Keep the query string: a token-bearing link that lands here must
// still carry its token after login.
loginUrl.searchParams.set("redirect", url.pathname + url.search);
return context.redirect(loginUrl.toString());
}

Expand Down
4 changes: 1 addition & 3 deletions packages/core/tests/unit/auth/signup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,7 @@ describe("Self-Signup", () => {
expect(mockEmailSend).toHaveBeenCalledTimes(1);
expect(sentEmails[0]!.to).toBe("newuser@allowed.com");
expect(sentEmails[0]!.subject).toContain("Test Site");
expect(sentEmails[0]!.text).toContain(
"https://example.com/_emdash/api/auth/signup/verify?token=",
);
expect(sentEmails[0]!.text).toContain("https://example.com/admin/signup?token=");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The updated assertion no longer verifies the real email link.

The production caller (packages/core/src/astro/routes/api/auth/signup/request.ts) passes baseUrl from getSiteBaseUrl, which returns the public origin suffixed with /_emdash (e.g. https://example.com/_emdash). The new code in packages/auth/src/signup.ts uses new URL(\${config.baseUrl}/admin/signup`), so the emitted link is https://example.com/_emdash/admin/signup?token=…`, matching the PR description and the middleware public route /_emdash/admin/signup.

However, the test still passes baseUrl: "https://example.com" (line 103) and asserts "https://example.com/admin/signup?token=". The test will pass, but it validates a URL shape that is never sent to users and could miss regressions in the mount path.

Update the fixture to pass baseUrl: "https://example.com/_emdash" and assert the production URL:

Suggested change
expect(sentEmails[0]!.text).toContain("https://example.com/admin/signup?token=");
expect(sentEmails[0]!.text).toContain(
"https://example.com/_emdash/admin/signup?token=",
);

expect(sentEmails[0]!.text).toContain("verify");
});

Expand Down
79 changes: 79 additions & 0 deletions packages/core/tests/unit/middleware/admin-public-routes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { beforeAll, describe, expect, it, vi } from "vitest";

vi.mock("virtual:emdash/auth", () => ({ authenticate: vi.fn() }));
vi.mock("virtual:emdash/config", () => ({ default: {} }));
vi.mock("astro:middleware", () => ({
defineMiddleware: (handler: unknown) => handler,
}));
vi.mock("@emdash-cms/auth", () => ({
TOKEN_PREFIXES: {},
generatePrefixedToken: vi.fn(),
hashPrefixedToken: vi.fn(),
VALID_SCOPES: [],
validateScopes: vi.fn(),
hasScope: vi.fn(() => false),
computeS256Challenge: vi.fn(),
Role: { ADMIN: 50 },
}));
vi.mock("@emdash-cms/auth/adapters/kysely", () => ({
createKyselyAdapter: vi.fn(() => ({
getUserById: vi.fn(),
getUserByEmail: vi.fn(),
})),
}));

type AuthMiddlewareModule = typeof import("../../../src/astro/middleware/auth.js");

let onRequest: AuthMiddlewareModule["onRequest"];

beforeAll(async () => {
({ onRequest } = await import("../../../src/astro/middleware/auth.js"));
});

/** An anonymous GET to an admin page. */
async function visit(
pathname: string,
): Promise<{ response: Response; next: ReturnType<typeof vi.fn> }> {
const url = new URL(pathname, "https://site.example.com");
const session = {
get: vi.fn().mockResolvedValue(null),
set: vi.fn(),
destroy: vi.fn(),
};
const next = vi.fn(async () => new Response("ok"));
const response = await onRequest(
{
url,
request: new Request(url, { method: "GET" }),
locals: { emdash: { db: {}, config: {} } },
session,
redirect: (location: string) =>
new Response(null, { status: 302, headers: { Location: location } }),
} as Parameters<AuthMiddlewareModule["onRequest"]>[0],
next,
);
return { response, next };
}

describe("Anonymous access to admin pages", () => {
it.each([
"/_emdash/admin/login",
"/_emdash/admin/signup?token=abc",
"/_emdash/admin/invite/accept?token=abc",
])("serves %s without a session — emails link there", async (pathname) => {
const { response, next } = await visit(pathname);
expect(next).toHaveBeenCalledOnce();
expect(response.status).toBe(200);
});

it("redirects other admin pages to login, keeping the full URL to return to", async () => {
const { response, next } = await visit("/_emdash/admin/content/posts?token=abc&x=1");
expect(next).not.toHaveBeenCalled();
expect(response.status).toBe(302);
const location = new URL(response.headers.get("Location")!);
expect(location.pathname).toBe("/_emdash/admin/login");
expect(location.searchParams.get("redirect")).toBe(
"/_emdash/admin/content/posts?token=abc&x=1",
);
});
});
Loading