Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix: preserve guest work through two-factor sign-in (#3750)

Amruth Pillai05362bb9f220
diff --git a/packages/api/src/features/auth/account.integration.test.ts b/packages/api/src/features/auth/account.integration.test.ts
index 7a03599d5..c96fb56dc 100644
--- a/packages/api/src/features/auth/account.integration.test.ts
+++ b/packages/api/src/features/auth/account.integration.test.ts
@@ -1,6 +1,7 @@
import { createHmac, randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
import { createRouterClient } from "@orpc/server";
+import { symmetricDecrypt } from "better-auth/crypto";
import { eq } from "drizzle-orm";
import { Pool } from "pg";
import { auth, linkAnonymousAccount, setAccountLinkHook } from "@reactive-resume/auth/config";
@@ -21,7 +22,11 @@ describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("account wrapper ownership
for (const table of [
"user",
"session",
+ "account",
+ "verification",
+ "two_factor",
"apikey",
+ "oauth_access_token",
"oauth_resource",
"jwks",
"resume",
@@ -33,6 +38,8 @@ describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("account wrapper ownership
"application_pipeline",
"application_profile",
"career_answer",
+ "career_fact",
+ "career_story",
"resume_slug_redirect",
"released_username",
]) {
@@ -198,6 +205,314 @@ describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("account wrapper ownership
]);
});
+ // Two-step sign-in drives the real auth handler, carrying each browser's cookies in a jar.
+ type Jar = Map<string, string>;
+ const send = async (path: string, body: object, jar: Jar) => {
+ const response = await auth.handler(
+ new Request(`${env.APP_URL}/api/auth/${path}`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ origin: env.APP_URL,
+ cookie: [...jar].map(([name, value]) => `${name}=${value}`).join("; "),
+ },
+ body: JSON.stringify(body),
+ }),
+ );
+ for (const header of response.headers.getSetCookie()) {
+ const [pair = ""] = header.split(";", 1);
+ const name = pair.slice(0, pair.indexOf("="));
+ const value = pair.slice(pair.indexOf("=") + 1);
+ if (!value || /max-age=0/i.test(header)) jar.delete(name);
+ else jar.set(name, value);
+ }
+ return response;
+ };
+ const totp = async (userId: string) => {
+ const [row] = await db.select().from(schema.twoFactor).where(eq(schema.twoFactor.userId, userId));
+ const secret = await symmetricDecrypt({ key: (await auth.$context).secretConfig, data: row?.secret ?? "" });
+ return (await auth.api.generateTOTP({ body: { secret } })).code;
+ };
+ const signUp = async (name: string) => {
+ const credentials = { email: `${name}@example.test`, password: `${name}-password` };
+ const jar: Jar = new Map();
+ const signup = await send("sign-up/email", { ...credentials, name, username: name }, jar);
+ expect(signup.status, await signup.clone().text()).toBe(200);
+ return { id: (await signup.json()).user.id as string, credentials, jar };
+ };
+ const signUpWithTwoFactor = async (name: string) => {
+ const account = await signUp(name);
+ const enabled = await send("two-factor/enable", { password: account.credentials.password }, account.jar);
+ expect(enabled.status, await enabled.clone().text()).toBe(200);
+ const { backupCodes } = (await enabled.json()) as { backupCodes: string[] };
+ expect((await send("two-factor/verify-totp", { code: await totp(account.id) }, account.jar)).status).toBe(200);
+ return { ...account, backupCodes };
+ };
+ // A guest with one resume starts the password step from its own browser session.
+ const startGuest = async (id: string, credentials: { email: string; password: string }) => {
+ const authContext = await auth.$context;
+ const guest = await authContext.internalAdapter.createUser(
+ { email: `${id}@reactive-resume.local`, name: "Guest", emailVerified: false, isAnonymous: true },
+ { method: "anonymous" },
+ );
+ const session = await authContext.internalAdapter.createSession(guest.id);
+ const signature = createHmac("sha256", env.AUTH_SECRET).update(session.token).digest("base64");
+ await pool.query(`INSERT INTO resume (id, name, slug, data, user_id) VALUES ($1, 'Guest', $1, '{}', $2)`, [
+ id,
+ guest.id,
+ ]);
+ const sessionCookie = authContext.authCookies.sessionToken.name;
+ const jar: Jar = new Map([[sessionCookie, encodeURIComponent(`${session.token}.${signature}`)]]);
+ const challenge = await send("sign-in/email", credentials, jar);
+ await expect(challenge.json()).resolves.toMatchObject({ twoFactorRedirect: true });
+ expect(jar.has(sessionCookie)).toBe(false);
+ const signed = jar.get(authContext.createAuthCookie("two_factor").name) ?? "";
+ return { guest, session, jar, sessionCookie, challengeId: decodeURIComponent(signed).split(".")[0] ?? "" };
+ };
+ const resumeOwner = async (id: string) =>
+ (await pool.query("SELECT user_id FROM resume WHERE id = $1", [id])).rows[0]?.user_id;
+ const userExists = async (id: string) =>
+ (await pool.query(`SELECT 1 FROM "user" WHERE id = $1`, [id])).rowCount === 1;
+
+ it("moves guest work once into the account a two-step sign-in verifies, and keeps it on failure", async () => {
+ await withDatabasePool(pool, async () => {
+ const owner = await signUpWithTwoFactor("two-step");
+
+ const viaTotp = await startGuest("totp-guest", owner.credentials);
+ const wrongCode = String((Number(await totp(owner.id)) + 500_000) % 1_000_000).padStart(6, "0");
+ expect((await send("two-factor/verify-totp", { code: wrongCode }, new Map(viaTotp.jar))).status).toBe(401);
+ expect(await resumeOwner("totp-guest")).toBe(viaTotp.guest.id);
+ const replayJar = new Map(viaTotp.jar);
+ const verified = await send("two-factor/verify-totp", { code: await totp(owner.id) }, viaTotp.jar);
+ expect(verified.status, await verified.clone().text()).toBe(200);
+ expect(await resumeOwner("totp-guest")).toBe(owner.id);
+ expect(await userExists(viaTotp.guest.id)).toBe(false);
+ expect((await send("two-factor/verify-totp", { code: await totp(owner.id) }, replayJar)).status).toBe(401);
+
+ const viaBackup = await startGuest("backup-guest", owner.credentials);
+ const backup = await send("two-factor/verify-backup-code", { code: owner.backupCodes[0] }, viaBackup.jar);
+ expect(backup.status, await backup.clone().text()).toBe(200);
+ expect(await resumeOwner("backup-guest")).toBe(owner.id);
+ expect(await userExists(viaBackup.guest.id)).toBe(false);
+
+ // A failed move signs the browser back in as the guest, keeps the guest's work, and ends the new session.
+ const failing = await startGuest("failed-2fa-guest", owner.credentials);
+ const ownerSessions = async () =>
+ (await pool.query("SELECT count(*)::int AS count FROM session WHERE user_id = $1", [owner.id])).rows[0]?.count;
+ const sessionsBefore = await ownerSessions();
+ setAccountLinkHook(async () => {
+ throw new Error("Copy unavailable");
+ });
+ try {
+ const failed = await send("two-factor/verify-backup-code", { code: owner.backupCodes[1] }, failing.jar);
+ expect(failed.ok).toBe(false);
+ } finally {
+ setAccountLinkHook();
+ }
+ expect(failing.jar.get(failing.sessionCookie)?.startsWith(failing.session.token)).toBe(true);
+ expect(await resumeOwner("failed-2fa-guest")).toBe(failing.guest.id);
+ expect(await userExists(failing.guest.id)).toBe(true);
+ expect(await ownerSessions()).toBe(sessionsBefore);
+ expect((await pool.query("SELECT 1 FROM verification WHERE identifier LIKE 'guest-link:%'")).rowCount).toBe(0);
+ await pool.query("DELETE FROM session");
+ });
+ });
+
+ it("hands guest work to the challenge accepted at its deadline, only once, and only for that account", async () => {
+ await withDatabasePool(pool, async () => {
+ const owner = await signUpWithTwoFactor("deadline-owner");
+ const expire = (challengeId: string, at: string) =>
+ pool.query(`UPDATE verification SET expires_at = ${at} WHERE identifier IN ($1, $2)`, [
+ challengeId,
+ `guest-link:${owner.id}:${challengeId}`,
+ ]);
+
+ // The deadline passes after the endpoint accepts the challenge, while its session row is being written.
+ await pool.query(
+ "CREATE FUNCTION delay_session() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(0.6); RETURN NEW; END $$",
+ );
+ await pool.query(
+ "CREATE TRIGGER delay_session BEFORE INSERT ON session FOR EACH ROW EXECUTE FUNCTION delay_session()",
+ );
+ try {
+ for (const id of ["deadline-1", "deadline-2", "deadline-3"]) {
+ const pending = await startGuest(id, owner.credentials);
+ const code = await totp(owner.id);
+ await expire(pending.challengeId, "now() + interval '300 milliseconds'");
+ const verified = await send("two-factor/verify-totp", { code }, pending.jar);
+ expect(verified.status, await verified.clone().text()).toBe(200);
+ expect(await resumeOwner(id)).toBe(owner.id);
+ expect(await userExists(pending.guest.id)).toBe(false);
+ }
+ } finally {
+ await pool.query("DROP TRIGGER delay_session ON session");
+ await pool.query("DROP FUNCTION delay_session()");
+ }
+
+ const expired = await startGuest("expired-guest", owner.credentials);
+ await expire(expired.challengeId, "now() - interval '1 second'");
+ expect((await send("two-factor/verify-totp", { code: await totp(owner.id) }, expired.jar)).status).toBe(401);
+ expect(await resumeOwner("expired-guest")).toBe(expired.guest.id);
+
+ // Another account's successful verification, carrying this challenge's cookie, takes nothing.
+ const pending = await startGuest("foreign-guest", owner.credentials);
+ const other = await signUp("deadline-other");
+ expect((await send("two-factor/enable", { password: other.credentials.password }, other.jar)).status).toBe(200);
+ const mixed = new Map([...pending.jar, ...other.jar]);
+ expect((await send("two-factor/verify-totp", { code: await totp(other.id) }, mixed)).status).toBe(200);
+ expect(await resumeOwner("foreign-guest")).toBe(pending.guest.id);
+
+ // Concurrent verifications of one challenge: one succeeds and moves the work once.
+ const moves: string[] = [];
+ setAccountLinkHook(async ({ fromUserId }) => {
+ moves.push(fromUserId);
+ });
+ try {
+ const code = await totp(owner.id);
+ const responses = await Promise.all([
+ send("two-factor/verify-totp", { code }, new Map(pending.jar)),
+ send("two-factor/verify-totp", { code }, new Map(pending.jar)),
+ ]);
+ expect(responses.map((response) => response.status).sort()).toEqual([200, 401]);
+ } finally {
+ setAccountLinkHook();
+ }
+ expect(moves).toEqual([pending.guest.id]);
+ expect(await resumeOwner("foreign-guest")).toBe(owner.id);
+ await pool.query("DELETE FROM session");
+ });
+ }, 30_000);
+
+ it("finishes an accepted guest transfer even when expiring handoff cleanup is locked", async () => {
+ await withDatabasePool(pool, async () => {
+ const owner = await signUpWithTwoFactor("cleanup-owner");
+ const pending = await startGuest("cleanup-guest", owner.credentials);
+ const identifier = `guest-link:${owner.id}:${pending.challengeId}`;
+ const replay = new Map(pending.jar);
+ const timedPool = new Pool({
+ connectionString: process.env.OAUTH_TEST_DATABASE_URL,
+ options: `-c search_path=${schemaName} -c lock_timeout=100ms`,
+ });
+ const locker = await pool.connect();
+ await locker.query("BEGIN");
+ await locker.query("SELECT id FROM verification WHERE identifier = $1 FOR UPDATE", [identifier]);
+ try {
+ const code = await totp(owner.id);
+ const response = await withDatabasePool(timedPool, () => send("two-factor/verify-totp", { code }, pending.jar));
+ expect(response.status, await response.clone().text()).toBe(200);
+ expect(response.headers.getSetCookie().length).toBeGreaterThan(0);
+ expect(await resumeOwner("cleanup-guest")).toBe(owner.id);
+ expect(await userExists(pending.guest.id)).toBe(false);
+ const headers = new Headers({
+ cookie: [...pending.jar].map(([key, value]) => `${key}=${value}`).join("; "),
+ });
+ expect((await auth.api.getSession({ headers }))?.user.id).toBe(owner.id);
+ expect((await pool.query("SELECT 1 FROM verification WHERE identifier = $1", [identifier])).rowCount).toBe(1);
+ expect((await send("two-factor/verify-totp", { code: await totp(owner.id) }, replay)).status).toBe(401);
+ } finally {
+ await locker.query("ROLLBACK");
+ locker.release();
+ await timedPool.end();
+ await pool.query("DELETE FROM verification WHERE identifier = $1", [identifier]);
+ await pool.query("DELETE FROM session WHERE user_id IN ($1, $2)", [owner.id, pending.guest.id]);
+ }
+ });
+ });
+
+ it("links private profiles and reviewed answers through two-step verification without losing conflicting work", async () => {
+ await withDatabasePool(pool, async () => {
+ const { applicationProfileService: profiles } = await import("../application-profile/service");
+ const { reviewedAnswers: answers } = await import("../career/answers");
+ const { applicationProfileDataSchema } = await import("@reactive-resume/schema/application-profile");
+ const owner = await signUpWithTwoFactor("private-link-owner");
+ const pending = await startGuest("private-link-guest", owner.credentials);
+ const guestProfile = await profiles.save(pending.guest.id, {
+ data: applicationProfileDataSchema.parse({
+ phone: "PRIVATE GUEST PHONE",
+ workAuthorization: [{ countryCode: "DE", authorized: "unknown", needsSponsorship: "unknown" }],
+ }),
+ expectedRevision: null,
+ });
+ const ownerProfile = await profiles.save(owner.id, {
+ data: applicationProfileDataSchema.parse({ phone: "PRIVATE OWNER PHONE" }),
+ expectedRevision: null,
+ });
+ await db.insert(schema.application).values([
+ { id: "private-guest-app", userId: pending.guest.id, company: "Harbor", role: "Engineer" },
+ { id: "private-owner-app", userId: owner.id, company: "Nova", role: "Engineer" },
+ ]);
+ const input = {
+ question: "Describe your project",
+ answer: "I reviewed a fictional setup checklist.",
+ source: "manual" as const,
+ scope: "reusable" as const,
+ factIds: [],
+ storyIds: [],
+ expectedEvidence: [],
+ reviewed: true as const,
+ noEmployerWording: true,
+ };
+ const saved = await answers.save(pending.guest.id, { ...input, applicationId: "private-guest-app" });
+ const ownerSessions = async () =>
+ (await pool.query("SELECT count(*)::int AS count FROM session WHERE user_id = $1", [owner.id])).rows[0]?.count;
+ const sessionsBefore = await ownerSessions();
+ const verify = async () => send("two-factor/verify-totp", { code: await totp(owner.id) }, pending.jar);
+ const retry = async () => {
+ const response = await send("sign-in/email", owner.credentials, pending.jar);
+ await expect(response.json()).resolves.toMatchObject({ twoFactorRedirect: true });
+ };
+ const guestIntact = async () => {
+ const headers = new Headers({
+ cookie: [...pending.jar].map(([key, value]) => `${key}=${value}`).join("; "),
+ });
+ expect((await auth.api.getSession({ headers }))?.user.id).toBe(pending.guest.id);
+ expect(await profiles.get(pending.guest.id)).toEqual(guestProfile);
+ expect((await answers.list(pending.guest.id, "private-guest-app"))[0]).toMatchObject({
+ id: saved.id,
+ answer: input.answer,
+ });
+ expect(await ownerSessions()).toBe(sessionsBefore);
+ expect(await resumeOwner("private-link-guest")).toBe(pending.guest.id);
+ };
+ try {
+ expect((await verify()).status).toBe(409);
+ await guestIntact();
+ expect(await profiles.get(owner.id)).toEqual(ownerProfile);
+ await profiles.delete(owner.id, ownerProfile.revision);
+ const duplicate = await answers.save(owner.id, { ...input, applicationId: "private-owner-app" });
+ await retry();
+ expect((await verify()).status).toBe(409);
+ await guestIntact();
+ expect(await profiles.get(owner.id)).toBeNull();
+ await answers.delete(owner.id, duplicate.id, duplicate.revision);
+ setAccountLinkHook(async () => {
+ throw new Error("Synthetic copy failure");
+ });
+ await retry();
+ expect((await verify()).status).toBe(500);
+ await guestIntact();
+ expect(await profiles.get(owner.id)).toBeNull();
+ setAccountLinkHook();
+ await retry();
+ const response = await verify();
+ expect(response.status, await response.clone().text()).toBe(200);
+ expect(await userExists(pending.guest.id)).toBe(false);
+ expect(await resumeOwner("private-link-guest")).toBe(owner.id);
+ expect(await profiles.get(pending.guest.id)).toBeNull();
+ const transferred = await profiles.get(owner.id);
+ expect(transferred?.data).toEqual(guestProfile.data);
+ expect(transferred?.revision).not.toBe(guestProfile.revision);
+ expect((await answers.list(owner.id, "private-guest-app"))[0]).toMatchObject({
+ id: saved.id,
+ answer: input.answer,
+ });
+ } finally {
+ setAccountLinkHook();
+ await pool.query("DELETE FROM session WHERE user_id IN ($1, $2)", [owner.id, pending.guest.id]);
+ }
+ });
+ }, 30_000);
+
it("reads only the authenticated profile, ignoring supplied identity and excluding private columns", async () => {
await withDatabasePool(pool, async () => {
const [owner, other] = await db
diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.ts
index d05ae4079..445d72cc5 100644
--- a/packages/auth/src/config.ts
+++ b/packages/auth/src/config.ts
@@ -1,5 +1,10 @@
-import type { User } from "better-auth";
-import type { GenericOAuthConfig, GenericOAuthUserInfo } from "better-auth/plugins";
+import type { BetterAuthPlugin, User } from "better-auth";
+import type {
+ AnonymousOptions,
+ GenericOAuthConfig,
+ GenericOAuthUserInfo,
+ UserWithAnonymous,
+} from "better-auth/plugins";
import type { JWTPayload } from "jose";
import { AsyncLocalStorage } from "node:async_hooks";
import { apiKey } from "@better-auth/api-key";
@@ -9,8 +14,14 @@ import { oauthProvider } from "@better-auth/oauth-provider";
import { passkey } from "@better-auth/passkey";
import { compare, hash } from "bcryptjs";
import { APIError, betterAuth } from "better-auth";
-import { addOAuthServerContext, createAuthMiddleware, getOAuthState } from "better-auth/api";
-import { deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
+import {
+ addOAuthServerContext,
+ createAuthMiddleware,
+ getOAuthState,
+ getSessionFromCtx,
+ isAPIError,
+} from "better-auth/api";
+import { deleteSessionCookie, parseSetCookieHeader, setSessionCookie } from "better-auth/cookies";
import { admin, anonymous, jwt, openAPI } from "better-auth/plugins";
import { genericOAuth } from "better-auth/plugins/generic-oauth";
import { twoFactor } from "better-auth/plugins/two-factor";
@@ -347,6 +358,122 @@ export async function linkAnonymousAccount({
}
}
+type GuestLink = Parameters<NonNullable<AnonymousOptions["onLinkAccount"]>>[0];
+
+async function moveGuestWork({ anonymousUser, newUser, ctx }: GuestLink): Promise<void> {
+ try {
+ await linkAnonymousAccount({
+ fromUserId: anonymousUser.user.id,
+ toUserId: newUser.user.id,
+ });
+ } catch (error) {
+ // Better Auth sets the new session cookie before this runs. A failed transfer must leave the
+ // guest accessible, and must not expose a usable credential-session cookie on the error reply.
+ deleteSessionCookie(ctx);
+ await setSessionCookie(ctx, anonymousUser, undefined, {
+ maxAge: Math.max(0, Math.floor((anonymousUser.session.expiresAt.getTime() - Date.now()) / 1000)),
+ });
+ await ctx.context.internalAdapter.deleteSession(newUser.session.token).catch(() => {});
+ if (isAPIError(error)) throw error;
+ // Better Auth keeps these cookies only on an APIError reply; any other error drops them.
+ console.error("Failed to move guest work to account %s:", newUser.user.id, error);
+ throw new APIError("INTERNAL_SERVER_ERROR", {
+ message: "The guest work could not be moved to this account. Try again.",
+ });
+ }
+}
+
+// Better Auth 1.7 keeps this name internal to its two-factor plugin.
+const TWO_FACTOR_COOKIE = "two_factor";
+const guestLinkIdentifier = (userId: string, challenge: string) => `guest-link:${userId}:${challenge}`;
+const isTwoFactorVerification = (path: string | undefined) =>
+ path === "/two-factor/verify-totp" || path === "/two-factor/verify-backup-code" || path === "/two-factor/verify-otp";
+
+/** Read before a verification request runs; it carries the guest through to that request's after-hook. */
+type GuestHandoff = { userId: string; challengeId: string; guestId: string };
+
+// The anonymous plugin moves guest work only when a sign-in reply sets a session. With two-step verification,
+// the password step sets none and the verification step is outside the plugin's matcher. This plugin stores the
+// guest's id server-side, keyed by the account and the signed, single-use two-factor challenge, and moves the
+// work when that challenge succeeds for that account.
+const twoFactorGuestLink = {
+ id: "two-factor-guest-link",
+ hooks: {
+ before: [
+ {
+ matcher: (ctx) => isTwoFactorVerification(ctx.path),
+ handler: createAuthMiddleware(async (ctx) => {
+ // Read the handoff before the endpoint accepts the challenge. Both expire together, so a challenge the
+ // endpoint accepts had a live handoff here, even if the deadline passes while its session is created.
+ const challengeId = await ctx.getSignedCookie(
+ ctx.context.createAuthCookie(TWO_FACTOR_COOKIE).name,
+ ctx.context.secret,
+ );
+ if (!challengeId) return;
+ const internal = ctx.context.internalAdapter;
+ // These lookups return expired rows too.
+ const challenge = await internal.findVerificationValue(challengeId);
+ if (!challenge || challenge.expiresAt <= new Date()) return;
+ const link = await internal.findVerificationValue(guestLinkIdentifier(challenge.value, challengeId));
+ if (!link || link.expiresAt <= new Date()) return;
+ const guestHandoff: GuestHandoff = { userId: challenge.value, challengeId, guestId: link.value };
+ return { context: { context: { guestHandoff } } };
+ }),
+ },
+ ],
+ after: [
+ {
+ matcher: (ctx) => ctx.path === "/sign-in/email" || ctx.path === "/sign-in/username",
+ handler: createAuthMiddleware(async (ctx) => {
+ const cookieName = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE).name;
+ // Our own reply's signed value: `<identifier>.<signature>`, URL-encoded.
+ const signed = parseSetCookieHeader(ctx.context.responseHeaders?.get("set-cookie") ?? "").get(cookieName);
+ const challengeId = signed && decodeURIComponent(signed.value).split(".")[0];
+ if (!challengeId) return;
+ const challenge = await ctx.context.internalAdapter.findVerificationValue(challengeId);
+ if (!challenge) return;
+ const guest = await getSessionFromCtx(ctx, { disableRefresh: true });
+ if (!guest?.user.isAnonymous) return;
+ await ctx.context.internalAdapter.createVerificationValue({
+ identifier: guestLinkIdentifier(challenge.value, challengeId),
+ value: guest.user.id,
+ expiresAt: challenge.expiresAt,
+ });
+ }),
+ },
+ {
+ matcher: (ctx) => isTwoFactorVerification(ctx.path),
+ handler: createAuthMiddleware(async (ctx) => {
+ const { guestHandoff: handoff } = ctx.context as { guestHandoff?: GuestHandoff };
+ const newUser = ctx.context.newSession;
+ if (!handoff || newUser?.user.id !== handoff.userId) return;
+ const internal = ctx.context.internalAdapter;
+ // The endpoint consumes the challenge, atomically, before it signs in. A challenge still stored means
+ // this request did not accept it; one gone means this request was its only acceptance.
+ if (await internal.findVerificationValue(handoff.challengeId)) return;
+ // The anonymous plugin's schema adds this column; the adapter types only the core user.
+ const user = (await internal.findUserById(handoff.guestId)) as UserWithAnonymous | null;
+ if (!user?.isAnonymous) return;
+ // Like the anonymous plugin, only a guest that can still sign in is linked, and kept on failure.
+ const [session] = await internal.listSessions(user.id, { onlyActiveSessions: true });
+ if (!session) return;
+ try {
+ await moveGuestWork({ anonymousUser: { user, session }, newUser, ctx });
+ await internal.deleteUser(user.id).catch((error: unknown) => {
+ ctx.context.logger.error("Failed to delete the linked guest account", { userId: user.id, error });
+ });
+ } finally {
+ // The consumed challenge prevents replay; expiring bookkeeping must not undo a transfer or its recovery.
+ await internal
+ .deleteVerificationByIdentifier(guestLinkIdentifier(handoff.userId, handoff.challengeId))
+ .catch(() => ctx.context.logger.warn("Failed to clean up completed guest-link marker"));
+ }
+ }),
+ },
+ ],
+ },
+} satisfies BetterAuthPlugin;
+
const getAuthConfig = () => {
const authConfigs: GenericOAuthConfig[] = [];
@@ -780,28 +907,15 @@ const getAuthConfig = () => {
usernameValidator: (username) => /^[a-z0-9._-]+$/.test(username),
validationOrder: { username: "post-normalization", displayUsername: "post-normalization" },
}),
+ // After twoFactor, whose sign-in hook creates the challenge this binds the guest to. Like the anonymous plugin,
+ // after oauthProvider: an OAuth login must not continue with the guest session a failed move restores.
+ twoFactorGuestLink,
anonymous({
emailDomainName: "reactive-resume.local",
generateName: () => "Guest",
// Signing up or in from a guest session moves the guest's documents to that account; the plugin then
// deletes the guest account, along with anything not moved here (assistant threads, career data).
- onLinkAccount: async ({ anonymousUser, newUser, ctx }) => {
- try {
- await linkAnonymousAccount({
- fromUserId: anonymousUser.user.id,
- toUserId: newUser.user.id,
- });
- } catch (error) {
- // Better Auth sets the new session cookie before this hook. A failed transfer must leave the
- // guest accessible, and must not expose a usable credential-session cookie on the error reply.
- deleteSessionCookie(ctx);
- await setSessionCookie(ctx, anonymousUser, undefined, {
- maxAge: Math.max(0, Math.floor((anonymousUser.session.expiresAt.getTime() - Date.now()) / 1000)),
- });
- await ctx.context.internalAdapter.deleteSession(newUser.session.token).catch(() => {});
- throw error;
- }
- },
+ onLinkAccount: moveGuestWork,
}),
...(env.BETTER_AUTH_API_KEY
? [dash({ apiKey: env.BETTER_AUTH_API_KEY, activityTracking: { enabled: true } })]