diff --git a/apps/api/src/account/credential-change-policy.test.ts b/apps/api/src/account/credential-change-policy.test.ts new file mode 100644 index 000000000..011f4439d --- /dev/null +++ b/apps/api/src/account/credential-change-policy.test.ts @@ -0,0 +1,286 @@ +import { de, en } from "@openmapx/i18n"; +import { APIError } from "better-auth/api"; +import { describe, expect, it, vi } from "vitest"; +import { + type CredentialChangeDeps, + type CredentialChangeSession, + type EmailChangeNoticeCtx, + enforceCredentialChangePolicy, + FRESH_SIGN_IN_PATHS, + IMPERSONATION_REFUSED_PATHS, + notifyPreviousAddressOfEmailChange, + refuseSecondProviderIdentity, +} from "./credential-change-policy"; + +function signedIn(overrides: { + impersonatedBy?: string | null; + twoFactorEnabled?: boolean | null; +}): CredentialChangeSession { + return { + session: { id: "session-1", userId: "user-1", impersonatedBy: overrides.impersonatedBy }, + user: { id: "user-1", twoFactorEnabled: overrides.twoFactorEnabled }, + }; +} + +function deps(options: { + session?: CredentialChangeSession | null; + fresh?: boolean; + linked?: string[]; +}) { + return { + loadSession: vi.fn(async () => + options.session === undefined ? signedIn({}) : options.session, + ), + isFresh: vi.fn(async () => options.fresh ?? false), + linkedProviderIds: vi.fn(async () => options.linked ?? []), + } satisfies CredentialChangeDeps; +} + +async function refusal(promise: Promise) { + const error = await promise.then( + () => undefined, + (caught: unknown) => caught, + ); + expect(error).toBeInstanceOf(APIError); + const apiError = error as APIError; + return { status: apiError.statusCode, code: (apiError.body as { code?: string }).code }; +} + +const PASSWORD_PROTECTED_PATHS = [ + "/change-password", + "/two-factor/enable", + "/two-factor/disable", + "/two-factor/generate-backup-codes", + "/two-factor/get-totp-uri", +]; + +describe("enforceCredentialChangePolicy", () => { + it.each([...FRESH_SIGN_IN_PATHS])("refuses %s from a stale session", async (path) => { + const fake = deps({ fresh: false }); + await expect(refusal(enforceCredentialChangePolicy({ path, body: {} }, fake))).resolves.toEqual( + { status: 401, code: "FRESH_SIGN_IN_REQUIRED" }, + ); + }); + + it.each([...FRESH_SIGN_IN_PATHS])("allows %s after a recent sufficient sign-in", async (path) => { + const fake = deps({ session: signedIn({ twoFactorEnabled: true }), fresh: true }); + await expect(enforceCredentialChangePolicy({ path, body: {} }, fake)).resolves.toBeUndefined(); + expect(fake.isFresh).toHaveBeenCalledWith({ + sessionId: "session-1", + userId: "user-1", + mfaConfigured: true, + }); + }); + + it.each([...IMPERSONATION_REFUSED_PATHS])( + "refuses %s from an impersonation session even when it is fresh", + async (path) => { + const fake = deps({ + session: signedIn({ impersonatedBy: "admin-1" }), + fresh: true, + linked: ["openstreetmap"], + }); + await expect( + refusal(enforceCredentialChangePolicy({ path, body: { provider: "openstreetmap" } }, fake)), + ).resolves.toEqual({ status: 403, code: "IMPERSONATION_NOT_ALLOWED" }); + expect(fake.isFresh).not.toHaveBeenCalled(); + }, + ); + + it.each(PASSWORD_PROTECTED_PATHS)( + "leaves %s to its password check for a stale session", + async (path) => { + const fake = deps({ fresh: false }); + await expect( + enforceCredentialChangePolicy({ path, body: {} }, fake), + ).resolves.toBeUndefined(); + expect(fake.isFresh).not.toHaveBeenCalled(); + }, + ); + + it("refuses linking a provider the account does not have yet from a stale session", async () => { + const fake = deps({ fresh: false, linked: ["credential"] }); + await expect( + refusal( + enforceCredentialChangePolicy( + { path: "/link-social", body: { provider: "openstreetmap" } }, + fake, + ), + ), + ).resolves.toEqual({ status: 401, code: "FRESH_SIGN_IN_REQUIRED" }); + expect(fake.linkedProviderIds).toHaveBeenCalledWith("user-1"); + }); + + it("allows more scopes for an already linked provider without a new sign-in", async () => { + const fake = deps({ fresh: false, linked: ["credential", "openstreetmap"] }); + await expect( + enforceCredentialChangePolicy( + { path: "/link-social", body: { provider: "openstreetmap" } }, + fake, + ), + ).resolves.toBeUndefined(); + expect(fake.isFresh).not.toHaveBeenCalled(); + }); + + it.each([{}, { provider: 42 }, null])( + "treats a link request without a provider name (%j) as a new provider", + async (body) => { + const fake = deps({ fresh: false, linked: ["openstreetmap"] }); + await expect( + refusal(enforceCredentialChangePolicy({ path: "/link-social", body }, fake)), + ).resolves.toEqual({ status: 401, code: "FRESH_SIGN_IN_REQUIRED" }); + }, + ); + + it.each(["/update-user", "/get-session"])("does not read the session on %s", async (path) => { + const fake = deps({ fresh: false }); + await expect(enforceCredentialChangePolicy({ path, body: {} }, fake)).resolves.toBeUndefined(); + expect(fake.loadSession).not.toHaveBeenCalled(); + }); + + it("leaves a request without a session to the endpoint's own 401", async () => { + const fake = deps({ session: null }); + await expect( + enforceCredentialChangePolicy({ path: "/delete-user", body: {} }, fake), + ).resolves.toBeUndefined(); + expect(fake.isFresh).not.toHaveBeenCalled(); + }); + + it("lets a passkey-only or federated account delete itself after a fresh sign-in", async () => { + const fake = deps({ session: signedIn({ twoFactorEnabled: false }), fresh: true }); + await expect( + enforceCredentialChangePolicy({ path: "/delete-user", body: {} }, fake), + ).resolves.toBeUndefined(); + expect(fake.isFresh).toHaveBeenCalledWith(expect.objectContaining({ mfaConfigured: false })); + }); +}); + +describe("refuseSecondProviderIdentity", () => { + function database(rows: { accountId: string }[]) { + const where = vi.fn(async () => rows); + const from = vi.fn(() => ({ where })); + const select = vi.fn(() => ({ from })); + return { select } as unknown as Parameters[1]; + } + const data = { userId: "user-1", providerId: "openstreetmap", accountId: "4242" }; + + it("allows the first identity of a provider", async () => { + await expect(refuseSecondProviderIdentity(data, database([]))).resolves.toBeUndefined(); + }); + + it("allows the same identity again", async () => { + await expect( + refuseSecondProviderIdentity(data, database([{ accountId: "4242" }])), + ).resolves.toBeUndefined(); + }); + + it("allows a different provider", async () => { + // The query is scoped to the provider, so another provider's rows never match. + await expect( + refuseSecondProviderIdentity({ ...data, providerId: "mapillary" }, database([])), + ).resolves.toBeUndefined(); + }); + + it("refuses a second identity of an already linked provider", async () => { + await expect( + refuseSecondProviderIdentity(data, database([{ accountId: "9999" }])), + ).resolves.toBe(false); + }); +}); + +describe("notifyPreviousAddressOfEmailChange", () => { + function ctx(overrides: Partial = {}): EmailChangeNoticeCtx { + return { + path: "/email-otp/change-email", + body: { newEmail: "new@example.test", otp: "123456" }, + headers: new Headers(), + context: { + returned: { success: true }, + session: { user: { id: "user-1", email: "old@example.test" } }, + logger: { error: vi.fn() }, + }, + ...overrides, + }; + } + + it("tells the previous address after a successful change", async () => { + const send = vi.fn(async () => undefined); + await notifyPreviousAddressOfEmailChange(ctx(), send); + expect(send).toHaveBeenCalledTimes(1); + const [message] = send.mock.calls[0] as unknown as [ + { to: string; subject: string; text: string; html: string; disclosure: unknown }, + ]; + expect(message.to).toBe("old@example.test"); + expect(message.subject).toContain(en.account.emailChangeNotice.subject); + expect(message.disclosure).toEqual({ + userId: "user-1", + operationCode: "auth.email-change.notice", + }); + expect(message.text).not.toContain("new@example.test"); + expect(message.html).not.toContain("new@example.test"); + }); + + it("writes in the language of the request", async () => { + const send = vi.fn(async () => undefined); + await notifyPreviousAddressOfEmailChange( + ctx({ headers: new Headers({ cookie: "theme=dark; NEXT_LOCALE=de" }) }), + send, + ); + const [message] = send.mock.calls[0] as unknown as [{ subject: string; text: string }]; + expect(message.subject).toContain(de.account.emailChangeNotice.subject); + expect(message.text).toContain(de.account.emailChangeNotice.unexpected); + }); + + it("skips a failed change", async () => { + const send = vi.fn(async () => undefined); + const base = ctx(); + await notifyPreviousAddressOfEmailChange( + { ...base, context: { ...base.context, returned: new APIError("BAD_REQUEST") } }, + send, + ); + expect(send).not.toHaveBeenCalled(); + }); + + it("skips other routes", async () => { + const send = vi.fn(async () => undefined); + await notifyPreviousAddressOfEmailChange( + ctx({ path: "/email-otp/request-email-change" }), + send, + ); + expect(send).not.toHaveBeenCalled(); + }); + + it("skips a provider placeholder address", async () => { + const send = vi.fn(async () => undefined); + const base = ctx(); + await notifyPreviousAddressOfEmailChange( + { + ...base, + context: { + ...base.context, + session: { user: { id: "user-1", email: "4242@osm.invalid" } }, + }, + }, + send, + ); + expect(send).not.toHaveBeenCalled(); + }); + + it("skips an unchanged address", async () => { + const send = vi.fn(async () => undefined); + await notifyPreviousAddressOfEmailChange( + ctx({ body: { newEmail: "OLD@example.test", otp: "123456" } }), + send, + ); + expect(send).not.toHaveBeenCalled(); + }); + + it("logs a delivery failure without failing the change", async () => { + const send = vi.fn(async () => { + throw new Error("mail down"); + }); + const notice = ctx(); + await expect(notifyPreviousAddressOfEmailChange(notice, send)).resolves.toBeUndefined(); + expect(notice.context.logger?.error).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/account/credential-change-policy.ts b/apps/api/src/account/credential-change-policy.ts new file mode 100644 index 000000000..0d3ec4ebb --- /dev/null +++ b/apps/api/src/account/credential-change-policy.ts @@ -0,0 +1,209 @@ +import { defaultLocale, resolveLocale } from "@openmapx/i18n"; +import { APIError, getAuthoritativeSessionFromCtx, isAPIError } from "better-auth/api"; +import { and, eq } from "drizzle-orm"; +import { account as accountTable } from "../db/schema"; +import { hasFreshAssurance } from "../privacy/session-assurance"; +import { sendMail } from "../utils/email"; +import { emailChangeNoticeEmail } from "../utils/emailTemplates"; +import { type AuthDatabase, currentAuthDatabase } from "./auth-database"; + +/** + * Routes that change how the account is reached, or delete it. They need a + * recent interactive sign-in with a method that also covers a configured + * second factor, the same rule as the privacy export. + */ +export const FRESH_SIGN_IN_PATHS: ReadonlySet = new Set([ + "/email-otp/request-email-change", + "/email-otp/change-email", + "/change-email", + "/delete-user", + "/delete-user/callback", + "/passkey/generate-register-options", + "/passkey/verify-registration", + "/passkey/delete-passkey", + "/unlink-account", +]); + +/** + * Every credential route an administrator impersonation session may not use. + * Linking a provider needs a recent sign-in only for a provider the account + * does not have yet; the password and second-factor routes keep the account + * password as their proof. + */ +export const IMPERSONATION_REFUSED_PATHS: ReadonlySet = new Set([ + ...FRESH_SIGN_IN_PATHS, + "/link-social", + "/change-password", + "/two-factor/enable", + "/two-factor/disable", + "/two-factor/generate-backup-codes", + "/two-factor/get-totp-uri", +]); + +/** + * Provider sign-in gives OpenStreetMap and Mapillary accounts + * `@osm.invalid` and `@mapillary.invalid`, so an address in the + * reserved `.invalid` domain never reaches a real mailbox. + */ +export function isReservedInvalidAddress(address: string): boolean { + const domain = address + .slice(address.lastIndexOf("@") + 1) + .trim() + .toLowerCase() + .replace(/\.+$/, ""); + return domain === "invalid" || domain.endsWith(".invalid"); +} + +export interface CredentialChangeSession { + session: { id: string; userId: string; impersonatedBy?: string | null }; + user: { id: string; twoFactorEnabled?: boolean | null }; +} + +export interface CredentialChangeDeps { + loadSession(): Promise; + isFresh(input: { sessionId: string; userId: string; mfaConfigured: boolean }): Promise; + linkedProviderIds(userId: string): Promise; +} + +async function needsFreshSignIn( + request: { path: string; body: unknown }, + userId: string, + deps: CredentialChangeDeps, +): Promise { + if (FRESH_SIGN_IN_PATHS.has(request.path)) return true; + if (request.path !== "/link-social") return false; + // Requesting more scopes from a provider the account already has adds no + // way into the account, so the contribution flow can upgrade OpenStreetMap + // access without a new sign-in. A second identity of that provider is + // refused when its account row would be created. + const provider = (request.body as { provider?: unknown } | null | undefined)?.provider; + if (typeof provider !== "string") return true; + return !(await deps.linkedProviderIds(userId)).includes(provider); +} + +/** + * Refuses credential changes from impersonation sessions, and from sessions + * without a recent sufficient sign-in on the routes that need one. Other + * routes pass without a session read; a request without a session passes so + * the endpoint answers it with its own 401. + */ +export async function enforceCredentialChangePolicy( + request: { path: string; body: unknown }, + deps: CredentialChangeDeps, +): Promise { + if (!IMPERSONATION_REFUSED_PATHS.has(request.path)) return; + const current = await deps.loadSession(); + if (!current) return; + if (current.session.impersonatedBy) + throw new APIError("FORBIDDEN", { + code: "IMPERSONATION_NOT_ALLOWED", + message: "Not available while impersonating an account", + }); + if (!(await needsFreshSignIn(request, current.user.id, deps))) return; + const fresh = await deps.isFresh({ + sessionId: current.session.id, + userId: current.user.id, + mfaConfigured: current.user.twoFactorEnabled === true, + }); + if (!fresh) + throw new APIError("UNAUTHORIZED", { + code: "FRESH_SIGN_IN_REQUIRED", + message: "Sign in again to continue", + }); +} + +type AuthMiddlewareContext = Parameters[0]; + +/** Dependencies backed by a Better Auth middleware context. */ +export function credentialChangeDepsFor(ctx: AuthMiddlewareContext): CredentialChangeDeps { + return { + loadSession: async () => + (await getAuthoritativeSessionFromCtx(ctx)) as CredentialChangeSession | null, + isFresh: (input) => hasFreshAssurance(input, currentAuthDatabase()), + linkedProviderIds: async (userId) => + (await ctx.context.internalAdapter.findAccounts(userId)).map((row) => row.providerId), + }; +} + +/** + * Database hook for new account rows: an account may hold one identity per + * provider. Without this, linking an already linked provider (which needs no + * recent sign-in) could attach a different identity at that provider. + */ +export async function refuseSecondProviderIdentity( + data: { userId: string; providerId: string; accountId: string }, + database: Pick = currentAuthDatabase(), +): Promise { + const rows = await database + .select({ accountId: accountTable.accountId }) + .from(accountTable) + .where(and(eq(accountTable.userId, data.userId), eq(accountTable.providerId, data.providerId))); + return rows.some((row) => row.accountId !== data.accountId) ? false : undefined; +} + +/** The part of a Better Auth after-hook context the email change notice reads. */ +export interface EmailChangeNoticeCtx { + path: string; + body?: unknown; + headers?: Headers; + request?: { headers: Headers }; + context: { + returned?: unknown; + session?: { user?: { id?: string; email?: string } | null } | null; + logger?: { error(message: string, ...args: unknown[]): void }; + }; +} + +function cookieValue(cookieHeader: string | null | undefined, name: string): string | undefined { + for (const part of cookieHeader?.split(";") ?? []) { + const separator = part.indexOf("="); + if (separator < 0 || part.slice(0, separator).trim() !== name) continue; + try { + return decodeURIComponent(part.slice(separator + 1).trim()); + } catch { + return undefined; + } + } + return undefined; +} + +/** + * The language of the request that changed the address: the web app's + * `NEXT_LOCALE` cookie, then the first `Accept-Language` tag. These are the + * sources the Better Auth error translations use; accounts store no locale. + */ +function mailLocale(headers: Headers | undefined): string { + const cookieLocale = cookieValue(headers?.get("cookie"), "NEXT_LOCALE"); + if (cookieLocale) return resolveLocale(cookieLocale); + const acceptLanguage = headers?.get("accept-language")?.split(",")[0]?.split(";")[0]?.trim(); + return acceptLanguage ? resolveLocale(acceptLanguage) : defaultLocale; +} + +/** + * Tells the previous address that the account's email address was changed. + * Runs after a successful change, while the session still carries the old + * address. The notice names neither the new address nor a link, and a + * delivery failure is only logged because the change has already been made. + */ +export async function notifyPreviousAddressOfEmailChange( + ctx: EmailChangeNoticeCtx, + send: typeof sendMail = sendMail, +): Promise { + if (ctx.path !== "/email-otp/change-email") return; + const returned = ctx.context.returned; + if (isAPIError(returned) || returned instanceof Error) return; + const userId = ctx.context.session?.user?.id; + const previous = ctx.context.session?.user?.email; + if (!userId || !previous || isReservedInvalidAddress(previous)) return; + const newEmail = (ctx.body as { newEmail?: unknown } | null | undefined)?.newEmail; + if (String(newEmail ?? "").toLowerCase() === previous.toLowerCase()) return; + try { + await send({ + to: previous, + ...emailChangeNoticeEmail(mailLocale(ctx.headers ?? ctx.request?.headers)), + disclosure: { userId, operationCode: "auth.email-change.notice" }, + }); + } catch (error) { + ctx.context.logger?.error("email change notice failed", error); + } +} diff --git a/apps/api/src/account/password-verification-policy.test.ts b/apps/api/src/account/password-verification-policy.test.ts index 3e94bd1b4..8f93017e1 100644 --- a/apps/api/src/account/password-verification-policy.test.ts +++ b/apps/api/src/account/password-verification-policy.test.ts @@ -1,9 +1,7 @@ import { expect, it } from "vitest"; import { unactivatedAuthPolicy } from "./auth-policy"; -import { - applyPasswordVerificationPolicy, - isReservedInvalidAddress, -} from "./password-verification-policy"; +import { isReservedInvalidAddress } from "./credential-change-policy"; +import { applyPasswordVerificationPolicy } from "./password-verification-policy"; it.each([ ["4242@osm.invalid", true], diff --git a/apps/api/src/account/password-verification-policy.ts b/apps/api/src/account/password-verification-policy.ts index ecf9342c2..c15368793 100644 --- a/apps/api/src/account/password-verification-policy.ts +++ b/apps/api/src/account/password-verification-policy.ts @@ -3,12 +3,18 @@ import type { BetterAuthOptions } from "better-auth"; import { APIError, createAuthMiddleware } from "better-auth/api"; import { configuredTrustedWebOrigins } from "../utils/csrf"; import { accountRoleSchema } from "./account-mutations"; +import { + credentialChangeDepsFor, + enforceCredentialChangePolicy, + isReservedInvalidAddress, +} from "./credential-change-policy"; /** * Better Auth routes that let a mailbox alone produce a session, or stand in * for an enrolled authenticator app. No client uses them. Password reset and * email change keep their own email-code routes, and a reset still ends at - * the ordinary sign-in with its second factor. + * the ordinary sign-in with its second factor. Email change also requires a + * recent sign-in. */ const EMAIL_ONLY_SIGN_IN_PATHS = new Set([ "/sign-in/email-otp", @@ -33,15 +39,6 @@ const NEW_ADDRESS_FIELDS: Readonly> = { "/change-email": "newEmail", }; -export function isReservedInvalidAddress(address: string): boolean { - const domain = address - .slice(address.lastIndexOf("@") + 1) - .trim() - .toLowerCase() - .replace(/\.+$/, ""); - return domain === "invalid" || domain.endsWith(".invalid"); -} - /** Paths where Better Auth signs someone in on the strength of their email alone. */ const EMAIL_PROVEN_SESSION_PATHS = new Set(["/verify-email", ...EMAIL_ONLY_SIGN_IN_PATHS]); @@ -119,6 +116,10 @@ export function applyPasswordVerificationPolicy(policy: AuthPolicySnapshot) { code: "INVALID_PASSWORD", message: "Password does not meet the instance policy", }); + await enforceCredentialChangePolicy( + { path: ctx.path, body: ctx.body }, + credentialChangeDepsFor(ctx), + ); }); return { userHooks, sessionHooks, before }; } diff --git a/apps/api/src/auth-postgres.test.ts b/apps/api/src/auth-postgres.test.ts index 5b9debfe3..31063b71e 100644 --- a/apps/api/src/auth-postgres.test.ts +++ b/apps/api/src/auth-postgres.test.ts @@ -1,4 +1,8 @@ import { createHash, createPublicKey, randomBytes, verify } from "node:crypto"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { en } from "@openmapx/i18n"; import { symmetricDecrypt } from "better-auth/crypto"; import { eq } from "drizzle-orm"; import Fastify, { type FastifyInstance } from "fastify"; @@ -27,9 +31,20 @@ describeDatabase("production authentication on migrated PostgreSQL", () => { let auth: typeof import("./auth")["auth"]; let server: FastifyInstance; const mail: { to: string; text: string }[] = []; + let journalDirectory = ""; beforeAll(async () => { fixture = await createMigratedPostgresFixture(); + // Account deletion writes a pseudonymous erasure receipt. + journalDirectory = mkdtempSync(join(tmpdir(), "openmapx-auth-postgres-")); + const journal = join(journalDirectory, "erasure.jsonl"); + const keyFile = join(journalDirectory, "journal.key"); + const journalKey = randomBytes(32); + writeFileSync(keyFile, journalKey.toString("base64url"), { mode: 0o444 }); + (await import("@openmapx/core/erasure-journal")).initializeErasureJournal(journal, journalKey); + vi.stubEnv("ERASURE_JOURNAL_KEY_FILE", keyFile); + vi.stubEnv("ERASURE_JOURNAL_KEY_UID", String(process.getuid?.() ?? 0)); + vi.stubEnv("ERASURE_JOURNAL_PATH", journal); vi.stubEnv("BETTER_AUTH_URL", BASE_URL); vi.stubEnv("BETTER_AUTH_SECRET", SECRET); vi.stubEnv("CORS_ORIGIN", "http://localhost:3000"); @@ -93,6 +108,7 @@ describeDatabase("production authentication on migrated PostgreSQL", () => { vi.doUnmock("./utils/email"); vi.unstubAllGlobals(); vi.unstubAllEnvs(); + if (journalDirectory) rmSync(journalDirectory, { recursive: true, force: true }); } } }); @@ -425,6 +441,129 @@ describeDatabase("production authentication on migrated PostgreSQL", () => { email: changedEmail, emailVerified: true, }); + const notices = mail.filter( + (message) => + message.to === email && message.text.includes(en.account.emailChangeNotice.subject), + ); + expect(notices).toHaveLength(1); + expect(notices[0]?.text).not.toContain(changedEmail); + }); + + async function ageAssurance(userId: string) { + await fixture.db + .update(sessionAuthAssurance) + .set({ authenticatedAt: new Date(Date.now() - 11 * 60_000) }) + .where(eq(sessionAuthAssurance.userId, userId)); + } + + async function osmSignIn() { + const started = await request("/api/auth/sign-in/social", { + provider: "openstreetmap", + callbackURL: "http://localhost:3000/", + }); + expect(started.statusCode, started.body).toBe(200); + const authorization = new URL(started.json().url as string); + const redirect = new URL(authorization.searchParams.get("redirect_uri") ?? ""); + const callback = await request( + `${redirect.pathname}?code=fixture-code&state=${authorization.searchParams.get("state")}`, + undefined, + cookies(started), + ); + expect(callback.statusCode, callback.body).toBe(302); + expect(callback.headers.location).not.toContain("error"); + const [owner] = await fixture.db.select().from(user).where(eq(user.email, "4242@osm.invalid")); + if (!owner) throw new Error("OpenStreetMap sign-in created no account"); + return { userId: owner.id, cookie: cookies(callback) }; + } + + function expectRefusal( + response: Awaited>, + label: string, + status: number, + code: string, + ) { + expect(response.statusCode, `${label}: ${response.body}`).toBe(status); + expect(response.json(), label).toMatchObject({ code }); + } + + it("refuses credential changes from a stale session and allows them after a new sign-in", async () => { + const email = "stale-session-fixture@example.test"; + const { userId, cookie } = await verifiedUser(email); + await ageAssurance(userId); + const mailBefore = mail.length; + + // Every gated path is requested, so a renamed library path shows up here. + for (const [path, body] of [ + ["/api/auth/email-otp/request-email-change", { newEmail: "stale-new@example.test" }], + ["/api/auth/email-otp/change-email", { newEmail: "stale-new@example.test", otp: "123456" }], + ["/api/auth/change-email", { newEmail: "stale-new@example.test" }], + ["/api/auth/delete-user", { password: PASSWORD }], + ["/api/auth/delete-user/callback?token=x", undefined], + ["/api/auth/passkey/generate-register-options", undefined], + ["/api/auth/passkey/verify-registration", { response: {} }], + ["/api/auth/passkey/delete-passkey", { id: "missing-passkey" }], + ["/api/auth/unlink-account", { providerId: "openstreetmap" }], + [ + "/api/auth/link-social", + { + provider: "openstreetmap", + callbackURL: "http://localhost:3000/", + disableRedirect: true, + }, + ], + ] as const) { + expectRefusal(await request(path, body, cookie), path, 401, "FRESH_SIGN_IN_REQUIRED"); + } + expect(mail.length).toBe(mailBefore); + // A password no longer substitutes for a recent sign-in. + expect((await fixture.db.select().from(user).where(eq(user.id, userId)))[0]?.email).toBe(email); + + const signin = await request("/api/auth/sign-in/email", { email, password: PASSWORD }); + expect(signin.statusCode, signin.body).toBe(200); + const options = await request( + "/api/auth/passkey/generate-register-options", + undefined, + cookies(signin), + ); + expect(options.statusCode, options.body).toBe(200); + }); + + it("refuses impersonation sessions on credential routes", async () => { + const admin = await verifiedUser("impersonating-admin@example.test"); + await fixture.db.update(user).set({ role: "admin" }).where(eq(user.id, admin.userId)); + const targetEmail = "impersonated-target@example.test"; + const target = await verifiedUser(targetEmail); + + const impersonated = await request( + "/api/auth/admin/impersonate-user", + { userId: target.userId }, + admin.cookie, + ); + expect(impersonated.statusCode, impersonated.body).toBe(200); + const cookie = cookies(impersonated); + + for (const [path, body] of [ + ["/api/auth/email-otp/request-email-change", { newEmail: "taken-over@example.test" }], + ["/api/auth/delete-user", {}], + ["/api/auth/passkey/generate-register-options", undefined], + [ + "/api/auth/change-password", + { currentPassword: PASSWORD, newPassword: "impersonator-password-9999" }, + ], + [ + "/api/auth/link-social", + { + provider: "openstreetmap", + callbackURL: "http://localhost:3000/", + disableRedirect: true, + }, + ], + ] as const) { + expectRefusal(await request(path, body, cookie), path, 403, "IMPERSONATION_NOT_ALLOWED"); + } + expect( + (await fixture.db.select().from(user).where(eq(user.id, target.userId)))[0], + ).toMatchObject({ email: targetEmail }); }); it("refuses reserved .invalid addresses at sign-up without revealing existing placeholders", async () => { @@ -506,6 +645,41 @@ describeDatabase("production authentication on migrated PostgreSQL", () => { expect(await sessions(created?.id ?? "")).toHaveLength(1); }); + // These reuse the OpenStreetMap identity of the test above, so they run after it. + it("allows OpenStreetMap scope upgrades of a linked account without a new sign-in", async () => { + const { userId, cookie } = await osmSignIn(); + await ageAssurance(userId); + const upgraded = await request( + "/api/auth/link-social", + { + provider: "openstreetmap", + callbackURL: "http://localhost:3000/", + disableRedirect: true, + scopes: ["openid", "read_prefs", "write_api"], + }, + cookie, + ); + expect(upgraded.statusCode, upgraded.body).toBe(200); + expect(upgraded.json()).toMatchObject({ url: expect.any(String) }); + }); + + it("lets a federated OpenStreetMap account delete itself after a fresh provider sign-in", async () => { + const fresh = await osmSignIn(); + const deleted = await request("/api/auth/delete-user", {}, fresh.cookie); + expect(deleted.statusCode, deleted.body).toBe(200); + expect(await fixture.db.select().from(user).where(eq(user.id, fresh.userId))).toHaveLength(0); + + const stale = await osmSignIn(); + await ageAssurance(stale.userId); + expectRefusal( + await request("/api/auth/delete-user", {}, stale.cookie), + "/api/auth/delete-user", + 401, + "FRESH_SIGN_IN_REQUIRED", + ); + expect(await fixture.db.select().from(user).where(eq(user.id, stale.userId))).toHaveLength(1); + }); + it("persists managed OIDC consent and signed PKCE tokens while rejecting invalid and reused codes", async () => { const email = "oidc-fixture@example.test"; const { userId, cookie } = await verifiedUser(email); diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index 079a8560e..42e91860c 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -5,6 +5,7 @@ import { passkey } from "@better-auth/passkey"; import { envString } from "@openmapx/core/server-env"; import { type BetterAuthOptions, betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; +import { createAuthMiddleware } from "better-auth/api"; import { admin, customSession, emailOTP, jwt, oneTimeToken, twoFactor } from "better-auth/plugins"; import { emailHarmony } from "better-auth-harmony"; import { eq } from "drizzle-orm"; @@ -15,6 +16,11 @@ import { } from "./account/account-mail-capture"; import { type AuthDatabase, currentAuthDatabase } from "./account/auth-database"; import { createAuthRuntime } from "./account/auth-runtime"; +import { + type EmailChangeNoticeCtx, + notifyPreviousAddressOfEmailChange, + refuseSecondProviderIdentity, +} from "./account/credential-change-policy"; import { applyPasswordVerificationPolicy } from "./account/password-verification-policy"; import { shareGenericOAuthProviders } from "./account/shared-oauth-providers"; import { @@ -28,7 +34,7 @@ import { managedOAuthProviderOptions } from "./managed-oauth-provider"; import { recordDataDisclosureBestEffort } from "./privacy/disclosures.js"; import { recordSessionFromAuthContext } from "./privacy/session-assurance.js"; import { userErasureHooks } from "./services/user-erasure"; -import { auditAdminActionsHook } from "./utils/auth-audit-hook"; +import { type AdminAuditCtx, handleAdminAuditEvent } from "./utils/auth-audit-hook"; import { configuredTrustedWebOrigins } from "./utils/csrf.js"; import { sendAuthMail } from "./utils/email"; import { @@ -262,6 +268,7 @@ function createPolicyAuth( }, account: { create: { + before: (account) => refuseSecondProviderIdentity(account), after: async (account) => { await providerAvatarSync.onAccountCreated( account.id, @@ -305,7 +312,12 @@ function createPolicyAuth( }, hooks: { before: passwordPolicy.before, - after: auditAdminActionsHook, + // The admin plugin and the email-code plugin handle these endpoints + // internally, so the after hook is where their results can be observed. + after: createAuthMiddleware(async (ctx) => { + await handleAdminAuditEvent(ctx as unknown as AdminAuditCtx); + await notifyPreviousAddressOfEmailChange(ctx as unknown as EmailChangeNoticeCtx); + }), }, plugins: [ i18n({ diff --git a/apps/api/src/privacy/session-assurance.ts b/apps/api/src/privacy/session-assurance.ts index a21ae4f48..f1e622aae 100644 --- a/apps/api/src/privacy/session-assurance.ts +++ b/apps/api/src/privacy/session-assurance.ts @@ -68,7 +68,7 @@ export async function recordSessionAuthAssurance(input: { export async function getSessionAuthAssurance( sessionId: string, - database: typeof defaultDb = defaultDb, + database: Pick = defaultDb, ): Promise<{ sessionId: string; userId: string | null; @@ -109,7 +109,7 @@ export async function recordSessionFromAuthContext( return true; } -/** How long a sign-in counts as fresh for an export or an admin ceremony. */ +/** How long a sign-in counts as fresh for an export, an admin ceremony or a credential change. */ export const REAUTH_TTL_MS = 10 * 60_000; export interface ReauthenticationSession { @@ -148,7 +148,7 @@ export function isAssuranceSufficient(method: SessionAuthMethod, mfaConfigured: */ export async function hasFreshAssurance( session: { sessionId: string; userId: string; mfaConfigured: boolean }, - database: typeof defaultDb = defaultDb, + database: Pick = defaultDb, now: Date = new Date(), maxAgeMs = REAUTH_TTL_MS, ): Promise { diff --git a/apps/api/src/utils/auth-audit-hook.ts b/apps/api/src/utils/auth-audit-hook.ts index b35013997..6f2192d81 100644 --- a/apps/api/src/utils/auth-audit-hook.ts +++ b/apps/api/src/utils/auth-audit-hook.ts @@ -1,4 +1,3 @@ -import { createAuthMiddleware } from "better-auth/api"; import { currentAccountMutation } from "../account/account-context"; import { writeAuditLog } from "./audit-log"; @@ -43,8 +42,9 @@ function pickString(value: unknown): string | undefined { } // Records an audit log entry for the admin-plugin user-management endpoints. -// Extracted from the `hooks.after` middleware so it can be tested directly; the -// middleware below delegates to it with the real better-auth context. +// The `hooks.after` middleware in auth.ts calls it with the real better-auth +// context; the plugin handles those endpoints internally, so that hook is the +// only seam where they can be observed without forking the plugin. export async function handleAdminAuditEvent(ctx: AdminAuditCtx): Promise { if (ctx.path === "/admin/set-user-password" && currentAccountMutation()?.action === "password") return; @@ -91,11 +91,3 @@ export async function handleAdminAuditEvent(ctx: AdminAuditCtx): Promise { request: ctx.request, }); } - -// `hooks.after` middleware for better-auth that records audit log entries -// for the admin-plugin user-management endpoints. The plugin handles those -// endpoints internally, so this is the only seam where we can observe them -// without forking the plugin. -export const auditAdminActionsHook = createAuthMiddleware(async (ctx) => { - await handleAdminAuditEvent(ctx as unknown as AdminAuditCtx); -}); diff --git a/apps/api/src/utils/emailTemplates.ts b/apps/api/src/utils/emailTemplates.ts index fc77fdd10..caae168e1 100644 --- a/apps/api/src/utils/emailTemplates.ts +++ b/apps/api/src/utils/emailTemplates.ts @@ -191,6 +191,32 @@ export function privacyRequestEmail( }; } +/** + * Security notice for the previous address after an email change. It names + * neither the new address nor a link, because the old mailbox may be shared. + */ +export function emailChangeNoticeEmail(locale: string = defaultLocale): { + subject: string; + text: string; + html: string; +} { + const t = createTranslator(locale, "account.emailChangeNotice"); + const subject = t("subject"); + const description = t("description"); + const unexpected = t("unexpected"); + return { + subject: `${subject} — OpenMapX`, + text: [subject, description, unexpected].join("\n\n"), + html: layout( + heading(escapeHtml(subject)) + + paragraph(escapeHtml(description)) + + paragraph(escapeHtml(unexpected)), + locale, + escapeHtml(t("footer")), + ), + }; +} + export function setupPasswordEmail(url: string): { subject: string; text: string; html: string } { return { subject: "Set your password — OpenMapX", diff --git a/apps/mobile/qa/webview/auth-checklist.md b/apps/mobile/qa/webview/auth-checklist.md index 7ae731f09..c45d83746 100644 --- a/apps/mobile/qa/webview/auth-checklist.md +++ b/apps/mobile/qa/webview/auth-checklist.md @@ -92,6 +92,10 @@ a clean failure; the session helper itself returns `failed` for a mismatched URL - [ ] Email verification and email OTP run in the WebView. - [ ] TOTP entry and backup codes run in the WebView. - [ ] Password reset runs in the WebView. +- [ ] With a sign-in older than ten minutes, deleting the account, changing the + email and adding a passkey each ask to sign in again and then repeat the + change. A passkey or provider re-sign-in through the system browser + returns to the app, and the change succeeds when repeated. ### Platform-specific offerings diff --git a/apps/web/src/app/(legal)/delete-account/DeleteAccountActions.tsx b/apps/web/src/app/(legal)/delete-account/DeleteAccountActions.tsx index 016b9926e..786160e87 100644 --- a/apps/web/src/app/(legal)/delete-account/DeleteAccountActions.tsx +++ b/apps/web/src/app/(legal)/delete-account/DeleteAccountActions.tsx @@ -8,6 +8,11 @@ import { authClient, useSession } from "@openmapx/core"; import { useQueryClient } from "@tanstack/react-query"; import { useTranslations } from "next-intl"; import { useCallback, useState } from "react"; +import { + type CredentialRefusal, + credentialRefusal, + FreshSignInPrompt, +} from "@/components/auth/freshSignIn"; import { clearPrivateDeviceData } from "@/lib/accountDeletionCleanup"; /** @@ -27,12 +32,18 @@ export function DeleteAccountActions() { const queryClient = useQueryClient(); const [confirming, setConfirming] = useState(false); const [state, setState] = useState<"idle" | "working" | "done" | "error">("idle"); + // A deletion refused for an old sign-in or an impersonation session explains + // that instead of the generic failure. A recent sign-in is the confirmation + // for every kind of account, so no password is asked for. + const [refusal, setRefusal] = useState(null); const remove = useCallback(async () => { setState("working"); + setRefusal(null); try { - const { error } = await authClient.deleteUser({ callbackURL: "/" }); + const { error } = await authClient.deleteUser({}); if (error) { + setRefusal(credentialRefusal(error)); setState("error"); return; } @@ -66,11 +77,16 @@ export function DeleteAccountActions() { return ( - {state === "error" && ( - - {tAccount("failedDeleteAccount")} - - )} + {state === "error" && + (refusal === "sign-in" ? ( + + ) : ( + + {refusal === "impersonating" + ? tAccount("freshSignIn.impersonating") + : tAccount("failedDeleteAccount")} + + ))} {confirming ? ( {/* The consequences are stated at the moment of the decision, not diff --git a/apps/web/src/app/(legal)/delete-account/DeleteAccountPage.test.tsx b/apps/web/src/app/(legal)/delete-account/DeleteAccountPage.test.tsx index 206b926c0..e370837ae 100644 --- a/apps/web/src/app/(legal)/delete-account/DeleteAccountPage.test.tsx +++ b/apps/web/src/app/(legal)/delete-account/DeleteAccountPage.test.tsx @@ -9,6 +9,8 @@ const deleteCalls: unknown[] = []; let deleteResult: { error?: unknown } = {}; vi.mock("@openmapx/core", () => ({ + FRESH_SIGN_IN_REQUIRED: "FRESH_SIGN_IN_REQUIRED", + IMPERSONATION_NOT_ALLOWED: "IMPERSONATION_NOT_ALLOWED", useSession: () => sessionState, authClient: { deleteUser: async (input: unknown) => { @@ -69,10 +71,41 @@ describe("DeleteAccountActions", () => { const buttons = view.getAllByRole("button", { name: en.legal.deleteAccountButton }); fireEvent.click(buttons[buttons.length - 1]); - await waitFor(() => expect(deleteCalls).toHaveLength(1)); + await waitFor(() => expect(deleteCalls).toEqual([{}])); await view.findByRole("status"); }); + it("asks for a new sign-in when the last one is too old, without retrying", async () => { + // The same for password, two-factor, passkey-only and provider accounts: + // no password field, a recent sign-in is the confirmation. + deleteResult = { error: { code: "FRESH_SIGN_IN_REQUIRED", status: 401 } }; + const view = renderActions(); + fireEvent.click(view.getByRole("button", { name: en.legal.deleteAccountButton })); + expect(view.container.querySelector('input[type="password"]')).toBeNull(); + + const buttons = view.getAllByRole("button", { name: en.legal.deleteAccountButton }); + fireEvent.click(buttons[buttons.length - 1]); + + const signIn = await view.findByText(en.account.freshSignIn.signInAgain); + expect(view.getByText(en.account.freshSignIn.notice)).toBeInTheDocument(); + expect(signIn.closest("a")?.getAttribute("href")).toBe( + "/auth/confirm?return=%2Fdelete-account", + ); + expect(view.queryByText(en.account.failedDeleteAccount)).toBeNull(); + expect(deleteCalls).toHaveLength(1); + }); + + it("explains that an impersonation session cannot delete the account", async () => { + deleteResult = { error: { code: "IMPERSONATION_NOT_ALLOWED", status: 403 } }; + const view = renderActions(); + fireEvent.click(view.getByRole("button", { name: en.legal.deleteAccountButton })); + const buttons = view.getAllByRole("button", { name: en.legal.deleteAccountButton }); + fireEvent.click(buttons[buttons.length - 1]); + + expect(await view.findByText(en.account.freshSignIn.impersonating)).toBeInTheDocument(); + expect(view.queryByText(en.account.freshSignIn.signInAgain)).toBeNull(); + }); + it("reports a failure rather than claiming success", async () => { deleteResult = { error: { message: "nope" } }; const view = renderActions(); diff --git a/apps/web/src/app/auth/confirm/page.test.tsx b/apps/web/src/app/auth/confirm/page.test.tsx new file mode 100644 index 000000000..ca9abb23b --- /dev/null +++ b/apps/web/src/app/auth/confirm/page.test.tsx @@ -0,0 +1,63 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { render, screen } from "@/test"; + +vi.mock("next-intl", async () => (await import("@/test/intl")).mockNextIntl()); + +const dialogProps: Array> = []; +vi.mock("@/components/auth/AuthDialog", () => ({ + AuthDialog: (props: Record) => { + dialogProps.push(props); + return
{String(props.notice)}
; + }, +})); + +const assign = vi.fn(); + +beforeEach(() => { + dialogProps.length = 0; + assign.mockReset(); + vi.stubGlobal("location", { ...window.location, assign, search: "" }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +async function renderWithReturn(value: string | null) { + const search = value === null ? "" : `?${new URLSearchParams({ return: value })}`; + vi.stubGlobal("location", { ...window.location, assign, search }); + const { default: Page } = await import("./page"); + render(); + return dialogProps[dialogProps.length - 1]; +} + +describe("confirm sign-in page", () => { + it("asks for a sign-in that cannot be dismissed and explains why", async () => { + const props = await renderWithReturn("/delete-account"); + expect(screen.getByRole("dialog").textContent).toBe("account.freshSignIn.notice"); + expect(props.open).toBe(true); + expect(props.dismissible).toBe(false); + }); + + it("returns to the same-site page it was sent from", async () => { + const props = await renderWithReturn("/?place=osm%3Anode%3A12"); + expect(props.callbackPath).toBe("/?place=osm%3Anode%3A12"); + (props.onClose as () => void)(); + expect(assign).toHaveBeenCalledWith("/?place=osm%3Anode%3A12"); + }); + + it.each(["https://evil.example/", "//evil.example/", "/\\evil.example", "javascript:alert(1)"])( + "never returns to %s", + async (value) => { + const props = await renderWithReturn(value); + expect(props.callbackPath).toBe("/"); + (props.onClose as () => void)(); + expect(assign).toHaveBeenCalledWith("/"); + }, + ); + + it("falls back to / without a return path", async () => { + const props = await renderWithReturn(null); + expect(props.callbackPath).toBe("/"); + }); +}); diff --git a/apps/web/src/app/auth/confirm/page.tsx b/apps/web/src/app/auth/confirm/page.tsx new file mode 100644 index 000000000..135f91cf4 --- /dev/null +++ b/apps/web/src/app/auth/confirm/page.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { AuthDialog } from "@/components/auth/AuthDialog"; +import { safeReturnPath } from "@/components/auth/freshSignIn"; + +/** + * Always asks for an interactive sign-in, even when a session exists, so an + * account change refused for an old sign-in can be repeated. Afterwards, or + * when the dialog is left, the person returns to the page they came from. + */ +export default function ConfirmSignInPage() { + const t = useTranslations("account.freshSignIn"); + const [returnPath] = useState(() => + typeof window === "undefined" + ? "/" + : safeReturnPath(new URLSearchParams(window.location.search).get("return")), + ); + return ( + window.location.assign(returnPath)} + /> + ); +} diff --git a/apps/web/src/components/auth/AccountSettingsDialog.test.tsx b/apps/web/src/components/auth/AccountSettingsDialog.test.tsx index 2cff35187..5a7d9e899 100644 --- a/apps/web/src/components/auth/AccountSettingsDialog.test.tsx +++ b/apps/web/src/components/auth/AccountSettingsDialog.test.tsx @@ -51,6 +51,11 @@ const credentials = vi.hoisted(() => ({ unlink: vi.fn(), requestEmail: vi.fn(), changeEmail: vi.fn(), + deleteUser: vi.fn(), + clearDeviceData: vi.fn(), +})); +vi.mock("@/lib/accountDeletionCleanup", () => ({ + clearPrivateDeviceData: credentials.clearDeviceData, })); vi.mock("@openmapx/core", async (importOriginal) => { const actual = await importOriginal(); @@ -69,6 +74,7 @@ vi.mock("@openmapx/core", async (importOriginal) => { requestEmailChange: credentials.requestEmail, changeEmail: credentials.changeEmail, }, + deleteUser: credentials.deleteUser, }, getInitials: () => "AT", oauthProviders: [{ providerId: "openstreetmap", name: "OpenStreetMap", icon: "/osm-logo.svg" }], @@ -88,6 +94,8 @@ beforeEach(() => { credentials.unlink.mockResolvedValue({ data: { status: true }, error: null }); credentials.requestEmail.mockResolvedValue(emailOk); credentials.changeEmail.mockResolvedValue(emailOk); + credentials.deleteUser.mockResolvedValue({ data: { success: true }, error: null }); + credentials.clearDeviceData.mockResolvedValue(undefined); }); import { AccountSettingsDialog } from "./AccountSettingsDialog"; @@ -1018,3 +1026,74 @@ describe("AccountSettingsDialog email change", () => { }); }); }); + +describe("AccountSettingsDialog recent sign-in refusals", () => { + const freshRefusal = { + data: null, + error: { code: "FRESH_SIGN_IN_REQUIRED", status: 401, statusText: "Unauthorized" }, + }; + const signInLink = () => + screen.getByText("account.freshSignIn.signInAgain").closest("a")?.getAttribute("href"); + + async function confirmDeletion() { + await userEvent.click(screen.getByRole("button", { name: "account.deleteAccount" })); + await userEvent.click(screen.getByRole("button", { name: "account.confirmDeletion" })); + } + + it("deletes after confirmation without asking for a password", async () => { + credentials.listAccounts.mockResolvedValue({ + data: [{ id: "account-c", providerId: "credential" }], + }); + const onClose = vi.fn(); + render(, { + wrapper: createQueryWrapper(), + }); + await waitFor(() => expect(credentials.listAccounts).toHaveBeenCalled()); + await userEvent.click(screen.getByRole("button", { name: "account.deleteAccount" })); + expect(document.querySelector('input[type="password"]')).toBeNull(); + expect(screen.getByRole("button", { name: "account.confirmDeletion" })).not.toBeDisabled(); + await userEvent.click(screen.getByRole("button", { name: "account.confirmDeletion" })); + await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)); + expect(credentials.deleteUser).toHaveBeenCalledWith({}); + }); + + it("asks for a new sign-in instead of deleting with an old one", async () => { + window.history.replaceState({}, "", "/?place=osm%3Anode%3A12"); + credentials.deleteUser.mockResolvedValue(freshRefusal); + renderAccount(); + await confirmDeletion(); + await screen.findByText("account.freshSignIn.notice"); + expect(signInLink()).toBe( + `/auth/confirm?return=${encodeURIComponent("/?place=osm%3Anode%3A12")}`, + ); + expect(screen.queryByText("account.failedDeleteAccount")).not.toBeInTheDocument(); + expect(credentials.deleteUser).toHaveBeenCalledTimes(1); + expect(credentials.clearDeviceData).not.toHaveBeenCalled(); + }); + + it("shows the sign-in prompt for a refused email request and does not retry it", async () => { + window.history.replaceState({}, "", "/"); + credentials.requestEmail.mockResolvedValue(freshRefusal); + renderAccount(); + await openEmailForm(); + await requestCode("new@example.test"); + await screen.findByText("account.freshSignIn.notice"); + expect(signInLink()).toBe("/auth/confirm?return=%2F"); + expect(codeField()).not.toBeInTheDocument(); + expect(sendButton()).not.toBeDisabled(); + expect(credentials.requestEmail).toHaveBeenCalledTimes(1); + }); + + it("explains an impersonation refusal without offering a sign-in", async () => { + credentials.add.mockResolvedValue({ + data: null, + error: { code: "IMPERSONATION_NOT_ALLOWED", status: 403, statusText: "Forbidden" }, + }); + renderAccount(); + await userEvent.click(screen.getByRole("button", { name: "account.addPasskey" })); + expect(await screen.findByText("account.freshSignIn.impersonating")).toBeInTheDocument(); + expect(screen.queryByText("account.freshSignIn.signInAgain")).not.toBeInTheDocument(); + expect(screen.queryByText("account.failedAddPasskey")).not.toBeInTheDocument(); + expect(credentials.add).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/src/components/auth/AccountSettingsDialog.tsx b/apps/web/src/components/auth/AccountSettingsDialog.tsx index d0ab12670..808d90635 100644 --- a/apps/web/src/components/auth/AccountSettingsDialog.tsx +++ b/apps/web/src/components/auth/AccountSettingsDialog.tsx @@ -42,6 +42,7 @@ import { } from "@/integration-api/runtime/useFullScreenOnMobile"; import { clearPrivateDeviceData } from "@/lib/accountDeletionCleanup"; import type { AccountSettingsSection } from "@/stores/accountSettingsStore"; +import { type AccountMessage, FreshSignInPrompt, useCredentialRefusalMessage } from "./freshSignIn"; import { MangroveAccountSection } from "./MangroveAccountSection"; import { PrivacyDataSection } from "./PrivacyDataSection"; import { SharedLinksSection } from "./SharedLinksSection"; @@ -74,10 +75,8 @@ export function AccountSettingsDialog({ const avatarSrc = user.image ? proxyImageUrl(user.image) : undefined; const [name, setName] = useState(user.name); const [saving, setSaving] = useState(false); - const [message, setMessage] = useState<{ - type: "success" | "error"; - text: string; - } | null>(null); + const [message, setMessage] = useState(null); + const refusalMessage = useCredentialRefusalMessage(); const { passkeys, linkedAccounts, @@ -91,7 +90,6 @@ export function AccountSettingsDialog({ unlinkProvider: handleUnlinkProvider, } = useAccountCredentials(open ? user.id : null, setMessage); const [confirmDelete, setConfirmDelete] = useState(false); - const [deletePassword, setDeletePassword] = useState(""); const timelineHeadingRef = useRef(null); const sharingHeadingRef = useRef(null); const privacyHeadingRef = useRef(null); @@ -160,7 +158,6 @@ export function AccountSettingsDialog({ setName(user.name); setMessage(null); setConfirmDelete(false); - setDeletePassword(""); setChangingEmail(false); setNewEmail(""); setEmailOtp(""); @@ -263,10 +260,12 @@ export function AccountSettingsDialog({ }); if (!owned()) return; if (error) { - publishEmailMessage({ - type: "error", - text: String(error.message ?? t("failedEmailChange")), - }); + publishEmailMessage( + refusalMessage(error) ?? { + type: "error", + text: String(error.message ?? t("failedEmailChange")), + }, + ); return; } setEmailOtpSent(true); @@ -288,10 +287,12 @@ export function AccountSettingsDialog({ }); if (!owned()) return; if (error) { - publishEmailMessage({ - type: "error", - text: String(error.message ?? t("failedChangeEmail")), - }); + publishEmailMessage( + refusalMessage(error) ?? { + type: "error", + text: String(error.message ?? t("failedChangeEmail")), + }, + ); return; } publishEmailMessage({ type: "success", text: t("emailUpdated") }); @@ -438,15 +439,13 @@ export function AccountSettingsDialog({ URL.revokeObjectURL(url); }; - const hasCredential = linkedAccounts.some((a) => a.providerId === "credential"); - + // A recent sign-in confirms the deletion for every kind of account, so no + // password is asked for here. const handleDeleteAccount = async () => { try { - const { error } = await authClient.deleteUser( - hasCredential ? { password: deletePassword } : { callbackURL: "/" }, - ); + const { error } = await authClient.deleteUser({}); if (error) { - setMessage({ type: "error", text: t("failedDeleteAccount") }); + setMessage(refusalMessage(error) ?? { type: "error", text: t("failedDeleteAccount") }); return; } await clearPrivateDeviceData({ queryClient }); @@ -478,10 +477,16 @@ export function AccountSettingsDialog({ - {message && ( - - {message.text} - + {message?.type === "fresh-sign-in" ? ( + + + + ) : ( + message && ( + + {message.text} + + ) )} {/* Profile Section */} @@ -1192,35 +1197,11 @@ export function AccountSettingsDialog({ {t("deleteAccountWarning")} - {hasCredential && ( - setDeletePassword(e.target.value)} - sx={{ mb: 1 }} - /> - )} - - diff --git a/apps/web/src/components/auth/AuthDialog.test.tsx b/apps/web/src/components/auth/AuthDialog.test.tsx index 70dab4c0f..6e24ab054 100644 --- a/apps/web/src/components/auth/AuthDialog.test.tsx +++ b/apps/web/src/components/auth/AuthDialog.test.tsx @@ -108,6 +108,20 @@ describe("AuthDialog in the installed app", () => { }); }); +describe("AuthDialog notice", () => { + it("renders the notice when provided", async () => { + const { AuthDialog } = await import("./AuthDialog"); + const { unmount } = render( + , + ); + expect(screen.getByText("Sign in again to confirm")).not.toBeNull(); + unmount(); + + render(); + expect(screen.queryByText("Sign in again to confirm")).toBeNull(); + }); +}); + describe("AuthDialog dismissal policy", () => { it("passes the hosting contribution return path to social sign-in", async () => { const { AuthDialog } = await import("./AuthDialog"); diff --git a/apps/web/src/components/auth/AuthDialog.tsx b/apps/web/src/components/auth/AuthDialog.tsx index aece7af5a..e025cc40a 100644 --- a/apps/web/src/components/auth/AuthDialog.tsx +++ b/apps/web/src/components/auth/AuthDialog.tsx @@ -37,6 +37,8 @@ interface AuthDialogProps { onAuthenticated?: () => void; /** Fixed same-origin return path supplied by the hosting page. */ callbackPath?: string; + /** Why the hosting page asks for this sign-in, shown above the form. */ + notice?: string; } export function AuthDialog({ @@ -45,6 +47,7 @@ export function AuthDialog({ onAuthenticated, dismissible = true, callbackPath, + notice, }: AuthDialogProps) { const t = useTranslations("auth"); const tMobile = useTranslations("mobileAuth"); @@ -374,6 +377,12 @@ export function AuthDialog({ + {notice && ( + + {notice} + + )} + {successMessage && ( {successMessage} diff --git a/apps/web/src/components/auth/freshSignIn.test.tsx b/apps/web/src/components/auth/freshSignIn.test.tsx new file mode 100644 index 000000000..26ef3252f --- /dev/null +++ b/apps/web/src/components/auth/freshSignIn.test.tsx @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from "vitest"; +import { render, screen } from "@/test"; + +vi.mock("next-intl", async () => (await import("@/test/intl")).mockNextIntl()); + +const { credentialRefusal, freshSignInHref, FreshSignInPrompt, safeReturnPath } = await import( + "./freshSignIn" +); + +describe("credentialRefusal", () => { + it("maps the API's account-security codes", () => { + expect(credentialRefusal({ code: "FRESH_SIGN_IN_REQUIRED", status: 401 })).toBe("sign-in"); + expect(credentialRefusal({ code: "IMPERSONATION_NOT_ALLOWED", status: 403 })).toBe( + "impersonating", + ); + }); + + it("reads the code from a thrown error that carries the API body", () => { + expect(credentialRefusal({ body: { code: "FRESH_SIGN_IN_REQUIRED" } })).toBe("sign-in"); + }); + + it.each([null, undefined, "FRESH_SIGN_IN_REQUIRED", { code: "INVALID_OTP" }, { status: 401 }])( + "leaves any other error (%j) to the caller", + (error) => { + expect(credentialRefusal(error)).toBeNull(); + }, + ); +}); + +describe("safeReturnPath", () => { + it.each([ + ["/", "/"], + ["/delete-account", "/delete-account"], + ["/?place=osm%3Anode%3A12&tab=overview", "/?place=osm%3Anode%3A12&tab=overview"], + ])("keeps the same-site path %s", (value, expected) => { + expect(safeReturnPath(value)).toBe(expected); + }); + + it.each([ + null, + "", + "delete-account", + "//evil.example/steal", + "/\\evil.example", + "\\\\evil.example", + "https://evil.example/", + "javascript:alert(1)", + "/\tevil", + `/${"a".repeat(2048)}`, + ])("falls back to / for %j", (value) => { + expect(safeReturnPath(value)).toBe("/"); + }); +}); + +describe("FreshSignInPrompt", () => { + it("links to the sign-in page with the return path", () => { + render(); + + expect(screen.getByText("account.freshSignIn.notice")).not.toBeNull(); + const link = screen.getByText("account.freshSignIn.signInAgain").closest("a"); + expect(link?.getAttribute("href")).toBe("/auth/confirm?return=%2Fdelete-account"); + }); + + it("never links to an off-site return target", () => { + expect(freshSignInHref("//evil.example")).toBe("/auth/confirm?return=%2F"); + }); +}); diff --git a/apps/web/src/components/auth/freshSignIn.tsx b/apps/web/src/components/auth/freshSignIn.tsx new file mode 100644 index 000000000..1325bafaa --- /dev/null +++ b/apps/web/src/components/auth/freshSignIn.tsx @@ -0,0 +1,106 @@ +"use client"; + +import Alert from "@mui/material/Alert"; +import Button from "@mui/material/Button"; +import { FRESH_SIGN_IN_REQUIRED, IMPERSONATION_NOT_ALLOWED } from "@openmapx/core"; +import { useTranslations } from "next-intl"; + +/** Why the API refused a credential change, if it was one of its account-security refusals. */ +export type CredentialRefusal = "sign-in" | "impersonating"; + +function codeOf(value: unknown): unknown { + if (typeof value !== "object" || value === null) return undefined; + const record = value as { code?: unknown; body?: unknown }; + if (record.code !== undefined) return record.code; + return typeof record.body === "object" && record.body !== null + ? (record.body as { code?: unknown }).code + : undefined; +} + +/** + * Reads the refusal from an auth-client error, a returned response body or a + * thrown error that carries the API body. + */ +export function credentialRefusal(error: unknown): CredentialRefusal | null { + const code = codeOf(error); + if (code === FRESH_SIGN_IN_REQUIRED) return "sign-in"; + if (code === IMPERSONATION_NOT_ALLOWED) return "impersonating"; + return null; +} + +/** A status line in the account UI; a refused change can ask for a new sign-in instead. */ +export type AccountMessage = + | { type: "success" | "error"; text: string } + | { type: "fresh-sign-in"; returnPath: string }; + +/** + * The message for an account-security refusal, or null for any other error, + * which the caller handles as before. + */ +export function useCredentialRefusalMessage(): (error: unknown) => AccountMessage | null { + const t = useTranslations("account.freshSignIn"); + return (error) => { + const refusal = credentialRefusal(error); + if (refusal === "sign-in") return { type: "fresh-sign-in", returnPath: currentReturnPath() }; + if (refusal === "impersonating") return { type: "error", text: t("impersonating") }; + return null; + }; +} + +/** The page that asks for a new sign-in and then returns to `return`. */ +export const FRESH_SIGN_IN_PAGE = "/auth/confirm"; + +const RETURN_BASE = "https://return.invalid"; + +/** + * A return target is accepted only as a path on this site: it starts with one + * `/`, carries no scheme, host, backslash or control character, and resolves + * to the same place against any origin. Anything else returns to `/`. + */ +export function safeReturnPath(value: string | null | undefined): string { + if ( + !value || + value.length > 2048 || + !value.startsWith("/") || + value.startsWith("//") || + value.includes("\\") || + Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) + ) + return "/"; + try { + const url = new URL(value, RETURN_BASE); + if (url.origin !== RETURN_BASE) return "/"; + return `${url.pathname}${url.search}`; + } catch { + return "/"; + } +} + +export function freshSignInHref(returnPath: string): string { + return `${FRESH_SIGN_IN_PAGE}?${new URLSearchParams({ return: safeReturnPath(returnPath) })}`; +} + +/** The current page, as the place to come back to after signing in again. */ +export function currentReturnPath(): string { + return `${window.location.pathname}${window.location.search}`; +} + +/** + * Explains that the change needs a recent sign-in and links to the sign-in + * page. Nothing resumes afterwards; the person repeats the change. + */ +export function FreshSignInPrompt({ returnPath }: { returnPath: string }) { + const t = useTranslations("account.freshSignIn"); + return ( + + {t("signInAgain")} + + } + > + {t("notice")} + + ); +} diff --git a/apps/web/src/components/auth/useAccountCredentials.ts b/apps/web/src/components/auth/useAccountCredentials.ts index 5f40ede26..052c56b69 100644 --- a/apps/web/src/components/auth/useAccountCredentials.ts +++ b/apps/web/src/components/auth/useAccountCredentials.ts @@ -3,11 +3,9 @@ import { authClient } from "@openmapx/core"; import { useTranslations } from "next-intl"; import { useEffect, useLayoutEffect, useState } from "react"; +import { type AccountMessage, useCredentialRefusalMessage } from "./freshSignIn"; -export interface CredentialMessage { - type: "success" | "error"; - text: string; -} +export type CredentialMessage = AccountMessage; interface Passkey { id: string; @@ -30,12 +28,16 @@ function initialState(ownerId: string | null) { type CredentialState = ReturnType; -/** Credential inventory and actions belong to one open-account lifetime, including A→B→A. */ +/** + * Credential inventory and actions belong to one open-account lifetime, including A→B→A. + * A change the API refuses for an old sign-in asks the person to sign in again and repeat it. + */ export function useAccountCredentials( ownerId: string | null, onMessage: (message: CredentialMessage | null) => void, ) { const t = useTranslations("account"); + const refusalMessage = useCredentialRefusalMessage(); const loadFailureText = t("unexpectedError"); const [state, setState] = useState(() => initialState(ownerId)); if (state.ownerId !== ownerId) setState(initialState(ownerId)); @@ -117,6 +119,9 @@ export function useAccountCredentials( lifetime[family]++; update((prev) => ({ ...prev, pending: false })); }; + const notifyError = (error: unknown, fallback: string) => { + notify(refusalMessage(error) ?? { type: "error", text: fallback }); + }; const addPasskey = async () => { if (state.loadingPasskeys || !begin("passkeysRevision")) return; @@ -124,7 +129,7 @@ export function useAccountCredentials( const { data, error } = await authClient.passkey.addPasskey(); if (!current()) return; if (error || !data) { - notify({ type: "error", text: t("failedAddPasskey") }); + notifyError(error, t("failedAddPasskey")); return; } // The successful plugin response is the new passkey; a failed refetch cannot undo it. @@ -146,7 +151,7 @@ export function useAccountCredentials( try { const { error } = await authClient.passkey.deletePasskey({ id }); if (error) { - notify({ type: "error", text: t("failedRemovePasskey") }); + notifyError(error, t("failedRemovePasskey")); return; } update((prev) => ({ ...prev, passkeys: prev.passkeys.filter((key) => key.id !== id) })); @@ -168,7 +173,7 @@ export function useAccountCredentials( }); if (!current()) return; if (error) { - notify({ type: "error", text: t("failedLink", { provider: providerName }) }); + notifyError(error, t("failedLink", { provider: providerName })); return; } // Keep the server-generated OAuth URL/callback; retire stale responses before navigation. @@ -186,7 +191,7 @@ export function useAccountCredentials( try { const { error } = await authClient.unlinkAccount({ accountId: account.id }); if (error) { - notify({ type: "error", text: t("failedUnlink", { provider: providerName }) }); + notifyError(error, t("failedUnlink", { provider: providerName })); return; } update((prev) => ({ diff --git a/apps/web/src/components/panels/place/contributions/OsmContributionGate.test.tsx b/apps/web/src/components/panels/place/contributions/OsmContributionGate.test.tsx index 8c91ac2c6..d5866b1df 100644 --- a/apps/web/src/components/panels/place/contributions/OsmContributionGate.test.tsx +++ b/apps/web/src/components/panels/place/contributions/OsmContributionGate.test.tsx @@ -45,7 +45,8 @@ function renderGate( } beforeEach(() => { - link.mockClear(); + link.mockReset(); + link.mockResolvedValue({ data: null, error: null }); }); describe("linkScopesFor", () => { @@ -87,6 +88,23 @@ describe("gate states", () => { ); }); + it("asks for a new sign-in when the first link is refused for an old sign-in", async () => { + window.history.replaceState({}, "", "/place/node%2F12?tab=overview"); + link.mockResolvedValue({ + data: null, + error: { code: "FRESH_SIGN_IN_REQUIRED", status: 401, statusText: "Unauthorized" }, + }); + renderGate({ ...BASE, linked: false, canWriteApi: false, canWriteNotes: false }); + await userEvent.click(screen.getByText("osmContributions.gateLinkAction")); + + const signIn = await screen.findByText("account.freshSignIn.signInAgain"); + expect(screen.getByText("account.freshSignIn.notice")).not.toBeNull(); + expect(signIn.closest("a")?.getAttribute("href")).toBe( + `/auth/confirm?return=${encodeURIComponent("/place/node%2F12?tab=overview")}`, + ); + expect(link).toHaveBeenCalledTimes(1); + }); + it("asks for the missing action scope", async () => { renderGate({ ...BASE, canWriteApi: false }); await userEvent.click(screen.getByText("osmContributions.gateScopeAction")); diff --git a/apps/web/src/components/panels/place/contributions/OsmContributionGate.tsx b/apps/web/src/components/panels/place/contributions/OsmContributionGate.tsx index d8f9f1f20..1e374c3b3 100644 --- a/apps/web/src/components/panels/place/contributions/OsmContributionGate.tsx +++ b/apps/web/src/components/panels/place/contributions/OsmContributionGate.tsx @@ -9,7 +9,12 @@ import Typography from "@mui/material/Typography"; import type { OsmContributionCapabilities } from "@openmapx/core"; import { authClient, safeHref } from "@openmapx/core"; import { useTranslations } from "next-intl"; -import type { ReactNode } from "react"; +import { type ReactNode, useState } from "react"; +import { + type AccountMessage, + FreshSignInPrompt, + useCredentialRefusalMessage, +} from "@/components/auth/freshSignIn"; /** The marker the OAuth callback carries back. Deliberately a boolean only. */ export const OSM_CONTRIBUTE_CALLBACK_PARAM = "osm-contribute"; @@ -58,6 +63,10 @@ export function OsmContributionGate({ onRetry, }: Props) { const t = useTranslations("osmContributions"); + const refusalMessage = useCredentialRefusalMessage(); + // Linking OpenStreetMap for the first time needs a recent sign-in; more + // scopes for an account that is already linked never do. + const [refusal, setRefusal] = useState(null); if (isLoading) { return ( @@ -81,16 +90,26 @@ export function OsmContributionGate({ } const authorize = async () => { - await authClient.linkSocial({ + setRefusal(null); + const { error } = await authClient.linkSocial({ provider: "openstreetmap", callbackURL: callbackUrlFor(window.location.href), scopes: linkScopesFor(intent), }); + if (error) setRefusal(refusalMessage(error)); }; + const refusalNotice = + refusal?.type === "fresh-sign-in" ? ( + + ) : refusal ? ( + {refusal.text} + ) : null; + if (!capabilities.linked) { return ( + {refusalNotice} {hasUnsentInput && {t("gateDiscardWarning")}}