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!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix(auth): lock transferred documents while copying uploads
Amruth Pillaiaf027fa80f96
diff --git a/packages/api/src/features/auth/account.integration.test.ts b/packages/api/src/features/auth/account.integration.test.tsindex 5aefd31c1..9fe817d53 100644--- a/packages/api/src/features/auth/account.integration.test.ts+++ b/packages/api/src/features/auth/account.integration.test.ts@@ -3,7 +3,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";import { createRouterClient } from "@orpc/server";import { eq } from "drizzle-orm";import { Pool } from "pg";-import { auth, linkAnonymousAccount } from "@reactive-resume/auth/config";+import { auth, linkAnonymousAccount, registerAccountLinkHook } from "@reactive-resume/auth/config";import { db, withDatabasePool } from "@reactive-resume/db/client";import * as schema from "@reactive-resume/db/schema";import { env } from "@reactive-resume/env/server";@@ -101,6 +101,64 @@ describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("account wrapper ownership]);});+ it("rolls back ownership and URLs when upload copying fails", async () => {+ const data = { picture: "https://resume.example/api/uploads/failed-guest/pictures/a.png" };+ await pool.query(+ `INSERT INTO resume (id, name, slug, data, user_id) VALUES ('failed-resume', 'Guest', 'failed', $1, 'failed-guest')`,+ [JSON.stringify(data)],+ );+ const unregister = registerAccountLinkHook(async () => {+ throw new Error("Copy unavailable");+ });+ try {+ await expect(+ withDatabasePool(pool, () => linkAnonymousAccount({ fromUserId: "failed-guest", toUserId: "link-owner" })),+ ).rejects.toThrow("Copy unavailable");+ } finally {+ unregister();+ }+ expect((await pool.query("SELECT user_id, data FROM resume WHERE id = 'failed-resume'")).rows).toEqual([+ { user_id: "failed-guest", data },+ ]);+ });++ it("blocks guest saves while copying and rejects stale ownership after commit", async () => {+ const data = { picture: "https://resume.example/api/uploads/race-guest/pictures/a.png" };+ await pool.query(+ `INSERT INTO resume (id, name, slug, data, user_id) VALUES ('race-resume', 'Guest', 'race', $1, 'race-guest')`,+ [JSON.stringify(data)],+ );+ const copying = Promise.withResolvers<void>();+ const resumeCopy = Promise.withResolvers<void>();+ const unregister = registerAccountLinkHook(async () => {+ copying.resolve();+ await resumeCopy.promise;+ });+ const client = await pool.connect();+ const linking = withDatabasePool(pool, () =>+ linkAnonymousAccount({ fromUserId: "race-guest", toUserId: "link-owner" }),+ );+ try {+ await copying.promise;+ await client.query("SET lock_timeout = '100ms'");+ await expect(+ client.query("UPDATE resume SET data = '{}' WHERE id = 'race-resume' AND user_id = 'race-guest'"),+ ).rejects.toMatchObject({ code: "55P03" });+ } finally {+ resumeCopy.resolve();+ await linking;+ unregister();+ await client.query("RESET lock_timeout");+ client.release();+ }+ expect(+ (await pool.query("UPDATE resume SET data = '{}' WHERE id = 'race-resume' AND user_id = 'race-guest'")).rowCount,+ ).toBe(0);+ expect((await pool.query("SELECT user_id, data FROM resume WHERE id = 'race-resume'")).rows).toEqual([+ { user_id: "link-owner", data: { picture: "https://resume.example/api/uploads/link-owner/pictures/a.png" } },+ ]);+ });+it("reads only the authenticated profile, ignoring supplied identity and excluding private columns", async () => {await withDatabasePool(pool, async () => {const [owner, other] = await dbdiff --git a/packages/auth/src/account-link.test.ts b/packages/auth/src/account-link.test.tsindex d9522fcfc..2a3728f56 100644--- a/packages/auth/src/account-link.test.ts+++ b/packages/auth/src/account-link.test.ts@@ -42,18 +42,10 @@ beforeEach(() => {});describe("linkAnonymousAccount", () => {- it("keeps database ownership and URLs unchanged when storage preparation fails", async () => {- registerAccountLinkHook(vi.fn().mockRejectedValue(new Error("Storage unavailable")));-- await expect(linkAnonymousAccount({ fromUserId: "guest-123", toUserId: "user-456" })).rejects.toThrow(- "Storage unavailable",- );- expect(mocks.transaction).not.toHaveBeenCalled();- });-- it("copies before the transaction and cleans up only after commit", async () => {+ it("copies before commit and cleans up only after commit", async () => {const events: string[] = [];registerAccountLinkHook(async () => {+ expect(mocks.updateWhere).toHaveBeenCalled();events.push("copy");return async () => {events.push("cleanup");diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.tsindex 1cbb8e75d..bf4e6cc3a 100644--- a/packages/auth/src/config.ts+++ b/packages/auth/src/config.ts@@ -147,7 +147,7 @@ type WithoutEndpointMetadata<TPlugin> = TPlugin extends { endpoints: infer TEndp}: TPlugin;-/** Prepare external resources before the transaction; optional cleanup runs only after commit. */+/** Prepare external resources before commit; optional cleanup runs only after commit. */export type AccountLinkHook = (params: {fromUserId: string;toUserId: string;@@ -176,11 +176,6 @@ export async function linkAnonymousAccount({if (fromUserId === toUserId) return;const cleanups: (() => Promise<void>)[] = [];- for (const hook of accountLinkHooks) {- const cleanup = await hook({ fromUserId, toUserId });- if (cleanup) cleanups.push(cleanup);- }-await db.transaction(async (tx) => {const rewriteUploadsJson = (column: unknown) =>sql`cast(replace(cast(${column} as text), 'uploads/' || ${fromUserId} || '/', 'uploads/' || ${toUserId} || '/') as jsonb)`;@@ -244,6 +239,12 @@ export async function linkAnonymousAccount({.update(schema.resumeSlugRedirect).set({ userId: toUserId }).where(eq(schema.resumeSlugRedirect.userId, fromUserId));++ // Ownership updates lock document rows, so guest saves cannot add uncopied references during copying.+ for (const hook of accountLinkHooks) {+ const cleanup = await hook({ fromUserId, toUserId });+ if (cleanup) cleanups.push(cleanup);+ }});const results = await Promise.allSettled(