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): preserve uploads across account link failures
Amruth Pillai6843e34613bf
diff --git a/apps/server/src/http/auth.test.ts b/apps/server/src/http/auth.test.tsindex b0563ff06..29f598b23 100644--- a/apps/server/src/http/auth.test.ts+++ b/apps/server/src/http/auth.test.ts@@ -240,7 +240,10 @@ describe("account link storage migration", () => {const registeredHook = mocks.registerAccountLinkHook.mock.calls.at(-1)?.[0];expect(typeof registeredHook).toBe("function");- await registeredHook({ fromUserId: "guest-old", toUserId: "user-new" });+ const cleanup = vi.fn();+ mocks.migrateUserStorage.mockResolvedValueOnce(cleanup);+ expect(await registeredHook({ fromUserId: "guest-old", toUserId: "user-new" })).toBe(cleanup);+ expect(cleanup).not.toHaveBeenCalled();expect(mocks.migrateUserStorage).toHaveBeenCalledWith("guest-old", "user-new");});diff --git a/apps/server/src/http/auth.ts b/apps/server/src/http/auth.tsindex 7ed7fbd12..b2aacd6ee 100644--- a/apps/server/src/http/auth.ts+++ b/apps/server/src/http/auth.ts@@ -8,7 +8,7 @@ import { isAllowedOAuthRedirectUri } from "@reactive-resume/utils/url-security.nconst accountLinkStorageMigrationHook = async ({ fromUserId, toUserId }: { fromUserId: string; toUserId: string }) => {try {- await migrateUserStorage(fromUserId, toUserId);+ return await migrateUserStorage(fromUserId, toUserId);} catch (error) {console.error("Failed to migrate storage from %s to %s:", fromUserId, toUserId, error);throw error;diff --git a/apps/server/src/static/uploads-local.test.ts b/apps/server/src/static/uploads-local.test.tsindex 2612ed5bf..9b17735f6 100644--- a/apps/server/src/static/uploads-local.test.ts+++ b/apps/server/src/static/uploads-local.test.ts@@ -48,11 +48,20 @@ it("migrates guest upload pictures so they are accessible via the new user URL aconst guestKey = "uploads/guest-user/pictures/avatar.png";const pngData = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);await storage.write({ key: guestKey, data: pngData, contentType: "image/png" });+ await storage.write({+ key: "uploads/guest-user/agent/thread-1/attachment-1",+ data: pngData,+ contentType: "image/png",+ private: true,+ });const beforeResponse = await handleUpload(new Request(`${envMock.APP_URL}/api/${guestKey}`));expect(beforeResponse.status).toBe(200);- await migrateUserStorage("guest-user", "registered-user");+ const cleanup = await migrateUserStorage("guest-user", "registered-user");+ // Sources remain usable until the database transition succeeds.+ expect((await handleUpload(new Request(`${envMock.APP_URL}/api/${guestKey}`))).status).toBe(200);+ await cleanup?.();const oldResponse = await handleUpload(new Request(`${envMock.APP_URL}/api/${guestKey}`));expect(oldResponse.status).toBe(404);@@ -61,6 +70,11 @@ it("migrates guest upload pictures so they are accessible via the new user URL aconst newResponse = await handleUpload(new Request(`${envMock.APP_URL}/api/${newKey}`));expect(newResponse.status).toBe(200);expect(new Uint8Array(await newResponse.arrayBuffer())).toEqual(pngData);+ if (process.platform !== "win32")+ expect(+ (await stat(join(envMock.LOCAL_STORAGE_PATH, "uploads/registered-user/agent/thread-1/attachment-1"))).mode &+ 0o777,+ ).toBe(0o600);});it("lists single file key when prefix points directly to an existing file", async () => {diff --git a/packages/api/src/features/auth/account.integration.test.ts b/packages/api/src/features/auth/account.integration.test.tsindex edf136db1..5aefd31c1 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 } from "@reactive-resume/auth/config";+import { auth, linkAnonymousAccount } 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";@@ -18,7 +18,19 @@ describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("account wrapper ownershipbeforeAll(async () => {admin = new Pool({ connectionString: process.env.OAUTH_TEST_DATABASE_URL });await admin.query(`CREATE SCHEMA ${schemaName}`);- for (const table of ["user", "session", "apikey", "oauth_resource", "jwks"]) {+ for (const table of [+ "user",+ "session",+ "apikey",+ "oauth_resource",+ "jwks",+ "resume",+ "resume_version",+ "cover_letter",+ "cover_letter_version",+ "application",+ "resume_slug_redirect",+ ]) {await admin.query(`CREATE TABLE ${schemaName}."${table}" (LIKE public."${table}" INCLUDING ALL)`);}pool = new Pool({@@ -33,6 +45,62 @@ describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("account wrapper ownershipawait admin?.end();});+ it("links guest documents, versions, attachments and redirects without changing destination assets", async () => {+ const oldUrl = "https://resume.example/api/uploads/link-guest/pictures/photo.png";+ const newUrl = "https://resume.example/api/uploads/link-owner/pictures/photo.png";+ await pool.query(+ `INSERT INTO resume (id, name, slug, data, user_id) VALUES+ ('guest-resume', 'Guest', 'shared', $1, 'link-guest'),+ ('owner-resume', 'Owner', 'shared', $2, 'link-owner')`,+ [JSON.stringify({ picture: oldUrl, nested: [oldUrl] }), JSON.stringify({ picture: "existing" })],+ );+ await pool.query(+ `INSERT INTO resume_version (id, resume_id, user_id, data) VALUES ('guest-version', 'guest-resume', 'link-guest', $1)`,+ [JSON.stringify({ picture: oldUrl })],+ );+ await pool.query(+ `INSERT INTO cover_letter (id, name, user_id, style) VALUES ('guest-letter', 'Guest', 'link-guest', $1)`,+ [JSON.stringify({ picture: oldUrl })],+ );+ await pool.query(+ `INSERT INTO cover_letter_version (id, cover_letter_id, user_id, data) VALUES ('guest-letter-version', 'guest-letter', 'link-guest', $1)`,+ [JSON.stringify({ style: { picture: oldUrl } })],+ );+ await pool.query(+ `INSERT INTO application (id, user_id, company, role, resume_file_url, cover_letter_url) VALUES ('guest-application', 'link-guest', 'Example', 'Engineer', $1, NULL)`,+ [oldUrl],+ );+ await pool.query(`INSERT INTO resume_slug_redirect (id, user_id, resume_id, slug, expires_at) VALUES+ ('guest-redirect', 'link-guest', 'guest-resume', 'old', now() + interval '1 day'),+ ('guest-conflict', 'link-guest', 'guest-resume', 'conflict', now() + interval '1 day'),+ ('owner-redirect', 'link-owner', 'owner-resume', 'conflict', now() + interval '1 day')`);++ await withDatabasePool(pool, () => linkAnonymousAccount({ fromUserId: "link-guest", toUserId: "link-owner" }));++ expect((await pool.query("SELECT user_id, slug, data FROM resume WHERE id = 'guest-resume'")).rows).toEqual([+ { user_id: "link-owner", slug: "shared-resume", data: { picture: newUrl, nested: [newUrl] } },+ ]);+ expect((await pool.query("SELECT data FROM resume WHERE id = 'owner-resume'")).rows[0]?.data).toEqual({+ picture: "existing",+ });+ for (const [table, column, value] of [+ ["resume_version", "data", { picture: newUrl }],+ ["cover_letter", "style", { picture: newUrl }],+ ["cover_letter_version", "data", { style: { picture: newUrl } }],+ ] as const) {+ expect((await pool.query(`SELECT user_id, ${column} AS value FROM ${table}`)).rows).toEqual([+ { user_id: "link-owner", value },+ ]);+ }+ expect((await pool.query("SELECT user_id, resume_file_url, cover_letter_url FROM application")).rows).toEqual([+ { user_id: "link-owner", resume_file_url: newUrl, cover_letter_url: null },+ ]);+ expect((await pool.query("SELECT id, user_id FROM resume_slug_redirect ORDER BY id")).rows).toEqual([+ { id: "guest-redirect", user_id: "link-owner" },+ { id: "owner-redirect", user_id: "link-owner" },+ ]);+ });+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/api/src/features/storage/migrate.test.ts b/packages/api/src/features/storage/migrate.test.tsindex 107a174e9..34194e885 100644--- a/packages/api/src/features/storage/migrate.test.ts+++ b/packages/api/src/features/storage/migrate.test.ts@@ -42,7 +42,9 @@ describe("migrateUserStorage", () => {mocks.write.mockResolvedValue(undefined);mocks.delete.mockResolvedValue(true);- await migrateUserStorage("guest-1", "user-2");+ const cleanup = await migrateUserStorage("guest-1", "user-2");+ expect(mocks.delete).not.toHaveBeenCalled();+ await cleanup?.();expect(mocks.list).toHaveBeenCalledWith("uploads/guest-1/");expect(mocks.write).toHaveBeenCalledWith({@@ -85,7 +87,9 @@ describe("migrateUserStorage", () => {it("skips keys that do not start with fromPrefix", async () => {mocks.list.mockResolvedValue(["other-prefix/photo.png"]);- await migrateUserStorage("guest-1", "user-2");+ const cleanup = await migrateUserStorage("guest-1", "user-2");+ expect(mocks.delete).not.toHaveBeenCalled();+ await cleanup?.();expect(mocks.read).not.toHaveBeenCalled();expect(mocks.write).not.toHaveBeenCalled();@@ -103,7 +107,7 @@ describe("migrateUserStorage", () => {expect(mocks.delete).not.toHaveBeenCalled();});- it("attempts to delete all copied keys and clean up prefix even if deleting one file fails", async () => {+ it("attempts every copied key cleanup even if one delete fails, without deleting the prefix", async () => {const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});const guestKey1 = "uploads/guest-1/pictures/photo1.png";const guestKey2 = "uploads/guest-1/pictures/photo2.png";@@ -116,15 +120,18 @@ describe("migrateUserStorage", () => {mocks.write.mockResolvedValue(undefined);mocks.delete.mockRejectedValueOnce(new Error("Storage timeout on key 1")).mockResolvedValue(true);- await migrateUserStorage("guest-1", "user-2");+ const cleanup = await migrateUserStorage("guest-1", "user-2");+ expect(mocks.delete).not.toHaveBeenCalled();+ await cleanup?.();expect(mocks.delete).toHaveBeenCalledWith(guestKey1);expect(mocks.delete).toHaveBeenCalledWith(guestKey2);- expect(mocks.delete).toHaveBeenCalledWith("uploads/guest-1/");+ expect(mocks.delete).not.toHaveBeenCalledWith("uploads/guest-1/");+ expect(mocks.delete).toHaveBeenCalledTimes(2);expect(consoleWarn).toHaveBeenCalled();consoleWarn.mockRestore();});- it("does not delete prefix and throws when some files cannot be read", async () => {+ it("preserves every source file when one listed file cannot be read", async () => {const guestKey1 = "uploads/guest-1/pictures/photo1.png";const guestKey2 = "uploads/guest-1/pictures/photo2.png";mocks.list.mockResolvedValue([guestKey1, guestKey2]);@@ -135,7 +142,7 @@ describe("migrateUserStorage", () => {mocks.write.mockResolvedValue(undefined);mocks.delete.mockResolvedValue(true);- await expect(migrateUserStorage("guest-1", "user-2")).rejects.toThrow();- expect(mocks.delete).not.toHaveBeenCalledWith("uploads/guest-1/");+ await expect(migrateUserStorage("guest-1", "user-2")).rejects.toThrow("Could not read");+ expect(mocks.delete).not.toHaveBeenCalled();});});diff --git a/packages/api/src/features/storage/s3.test.ts b/packages/api/src/features/storage/s3.test.tsnew file mode 100644index 000000000..16e344a55--- /dev/null+++ b/packages/api/src/features/storage/s3.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { DeleteObjectCommand, ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";++vi.mock("@reactive-resume/env/server", () => ({+ env: {+ STORAGE_BACKEND: "s3",+ S3_ACCESS_KEY_ID: "test-access-key",+ S3_SECRET_ACCESS_KEY: "test-secret-key",+ S3_BUCKET: "test-bucket",+ S3_REGION: "us-east-1",+ },+}));++const { getStorageService } = await import("./service");+afterEach(() => vi.restoreAllMocks());++describe("S3 storage migration prerequisites", () => {+ it("lists every page so all guest upload references can be migrated", async () => {+ const firstPage = Array.from({ length: 1_000 }, (_, i) => ({ Key: `uploads/guest/pictures/${i}.png` }));+ const send = vi.spyOn(S3Client.prototype, "send");+ send.mockImplementation(async (command) => {+ if (!(command instanceof ListObjectsV2Command)) throw new Error("Unexpected command");+ return command.input.ContinuationToken === "next"+ ? { Contents: [{ Key: "uploads/guest/pictures/last.png" }], IsTruncated: false }+ : { Contents: firstPage, IsTruncated: true, NextContinuationToken: "next" };+ });++ const keys = await getStorageService().list("uploads/guest/");+ expect(keys).toHaveLength(1_001);+ expect(keys.at(-1)).toBe("uploads/guest/pictures/last.png");+ });++ it("does not delete uncopied objects that only share a copied filename prefix", async () => {+ const deleted: string[] = [];+ vi.spyOn(S3Client.prototype, "send").mockImplementation(async (command) => {+ if (command instanceof ListObjectsV2Command)+ return {+ Contents: [{ Key: "uploads/guest/pictures/a.png" }, { Key: "uploads/guest/pictures/a.png-uncopied" }],+ };+ if (command instanceof DeleteObjectCommand) {+ deleted.push(command.input.Key ?? "");+ return {};+ }+ throw new Error("Unexpected command");+ });++ await getStorageService().delete("uploads/guest/pictures/a.png");+ expect(deleted).toEqual(["uploads/guest/pictures/a.png"]);+ });+});diff --git a/packages/api/src/features/storage/service.ts b/packages/api/src/features/storage/service.tsindex c39a0c01b..e2fdd0b90 100644--- a/packages/api/src/features/storage/service.ts+++ b/packages/api/src/features/storage/service.ts@@ -4,7 +4,7 @@ import { dirname, extname, join, relative } from "node:path";import {DeleteObjectCommand,GetObjectCommand,- ListObjectsV2Command,+ paginateListObjectsV2,PutObjectCommand,S3Client,} from "@aws-sdk/client-s3";@@ -132,7 +132,7 @@ class LocalStorageService implements StorageService {return entries.filter((entry) => entry.isFile()).map((entry) => {- const parent = entry.parentPath ?? (entry as { path?: string }).path ?? fullPath;+ const parent = entry.parentPath;const relativePath = relative(fullPath, join(parent, entry.name)).replaceAll("\\", "/");return normalizedPrefix ? `${normalizedPrefix}/${relativePath}` : relativePath;});@@ -265,10 +265,13 @@ class S3StorageService implements StorageService {}async list(prefix: string): Promise<string[]> {- const command = new ListObjectsV2Command({ Bucket: this.bucket, Prefix: prefix });- const response = await this.client.send(command);- if (!response.Contents) return [];- return response.Contents.map((object) => object.Key ?? "");+ const keys: string[] = [];+ for await (const page of paginateListObjectsV2({ client: this.client }, { Bucket: this.bucket, Prefix: prefix })) {+ for (const object of page.Contents ?? []) {+ if (object.Key) keys.push(object.Key);+ }+ }+ return keys;}async write({ key, data, contentType }: StorageWriteInput): Promise<void> {@@ -306,7 +309,8 @@ class S3StorageService implements StorageService {async delete(keyOrPrefix: string): Promise<boolean> {// Use list to find all matching keys (handles both single file and folder/prefix)- const keys = await this.list(keyOrPrefix);+ const prefix = keyOrPrefix.endsWith("/") ? keyOrPrefix : `${keyOrPrefix}/`;+ const keys = (await this.list(keyOrPrefix)).filter((key) => key === keyOrPrefix || key.startsWith(prefix));if (keys.length === 0) return false;@@ -377,51 +381,33 @@ export async function uploadFile(input: UploadFileInput): Promise<UploadFileResureturn { key, url: buildPublicUrl(key) };}-export async function migrateUserStorage(fromUserId: string, toUserId: string): Promise<void> {+/** Copy before linking; caller runs returned cleanup only after ownership commits. */+export async function migrateUserStorage(fromUserId: string, toUserId: string): Promise<(() => Promise<void>) | void> {if (fromUserId === toUserId) return;const storageService = getStorageService();const fromPrefix = `uploads/${fromUserId}/`;const toPrefix = `uploads/${toUserId}/`;+ const keys = (await storageService.list(fromPrefix)).filter((key) => key.startsWith(fromPrefix));- const keys = await storageService.list(fromPrefix);- const keysToMigrate = keys.filter((key) => key.startsWith(fromPrefix));-- const copiedKeys: string[] = [];- const unreadKeys: string[] = [];- for (const key of keysToMigrate) {- const targetKey = `${toPrefix}${key.slice(fromPrefix.length)}`;+ for (const key of keys) {const file = await storageService.read(key);- if (file) {- await storageService.write({- key: targetKey,- data: file.data,- contentType: file.contentType ?? inferContentType(key),- });- copiedKeys.push(key);- } else {- unreadKeys.push(key);- }+ if (!file) throw new Error(`Could not read storage key ${key}; source files were kept.`);+ await storageService.write({+ key: `${toPrefix}${key.slice(fromPrefix.length)}`,+ data: file.data,+ contentType: file.contentType ?? inferContentType(key),+ ...(key.startsWith(`${fromPrefix}agent/`) ? { private: true } : {}),+ });}- if (copiedKeys.length > 0) {- const deleteResults = await Promise.allSettled(copiedKeys.map((key) => storageService.delete(key)));- for (const result of deleteResults) {- if (result.status === "rejected") {- console.warn("Failed to delete migrated storage key:", result.reason);- }- }-- if (unreadKeys.length === 0) {- try {- await storageService.delete(fromPrefix);- } catch (error) {- console.warn("Failed to clean up storage prefix %s:", fromPrefix, error);+ return async () => {+ // Never delete the prefix: uploads outside this copy snapshot must survive.+ const results = await Promise.allSettled(keys.map((key) => storageService.delete(key)));+ for (const [index, result] of results.entries()) {+ if (result.status === "rejected" || !result.value) {+ console.warn("Failed to delete migrated storage key %s:", keys[index], result);}}- }-- if (unreadKeys.length > 0) {- throw new Error(`Could not read ${unreadKeys.length} storage key(s) under ${fromPrefix}; source files were kept.`);- }+ };}diff --git a/packages/auth/src/account-link.test.ts b/packages/auth/src/account-link.test.tsindex ed9e9e5fa..d9522fcfc 100644--- a/packages/auth/src/account-link.test.ts+++ b/packages/auth/src/account-link.test.ts@@ -42,6 +42,57 @@ 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 () => {+ const events: string[] = [];+ registerAccountLinkHook(async () => {+ events.push("copy");+ return async () => {+ events.push("cleanup");+ };+ });+ mocks.transaction.mockImplementationOnce(async (cb) => {+ await cb({ update: mocks.update, delete: mocks.delete });+ events.push("commit");+ });++ await linkAnonymousAccount({ fromUserId: "guest-123", toUserId: "user-456" });+ expect(events).toEqual(["copy", "commit", "cleanup"]);+ });++ it("preserves originals when the database transition fails", async () => {+ const cleanup = vi.fn();+ registerAccountLinkHook(async () => cleanup);+ mocks.transaction.mockRejectedValueOnce(new Error("Database unavailable"));++ await expect(linkAnonymousAccount({ fromUserId: "guest-123", toUserId: "user-456" })).rejects.toThrow(+ "Database unavailable",+ );+ expect(cleanup).not.toHaveBeenCalled();+ });++ it("does not reject a committed link or skip remaining cleanup when one cleanup fails", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const cleanup = vi.fn().mockResolvedValue(undefined);+ registerAccountLinkHook(async () => async () => {+ throw new Error("Cleanup unavailable");+ });+ registerAccountLinkHook(async () => cleanup);++ await expect(linkAnonymousAccount({ fromUserId: "guest-123", toUserId: "user-456" })).resolves.toBeUndefined();+ expect(cleanup).toHaveBeenCalledOnce();+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });+it("updates document ownership, rewrites upload URLs in DB, and executes registered hooks", async () => {const hook = vi.fn().mockResolvedValue(undefined);registerAccountLinkHook(hook);diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.tsindex 994713c2b..1cbb8e75d 100644--- a/packages/auth/src/config.ts+++ b/packages/auth/src/config.ts@@ -147,7 +147,11 @@ type WithoutEndpointMetadata<TPlugin> = TPlugin extends { endpoints: infer TEndp}: TPlugin;-export type AccountLinkHook = (params: { fromUserId: string; toUserId: string }) => Promise<void>;+/** Prepare external resources before the transaction; optional cleanup runs only after commit. */+export type AccountLinkHook = (params: {+ fromUserId: string;+ toUserId: string;+}) => Promise<(() => Promise<void>) | void>;const accountLinkHooks = new Set<AccountLinkHook>();@@ -171,6 +175,12 @@ export async function linkAnonymousAccount({}): Promise<void> {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)`;@@ -236,8 +246,13 @@ export async function linkAnonymousAccount({.where(eq(schema.resumeSlugRedirect.userId, fromUserId));});- for (const hook of accountLinkHooks) {- await hook({ fromUserId, toUserId });+ const results = await Promise.allSettled(+ cleanups.map(async (cleanup) => {+ await cleanup();+ }),+ );+ for (const result of results) {+ if (result.status === "rejected") console.warn("Failed to clean up linked account resources:", result.reason);}}