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(api): resolve renamed resume slugs in public PDF, social meta, and download stats (#3658)
Hoàng Anh Tuấn2559c42c7a9e
diff --git a/packages/api/src/features/resume/public-pdf.test.ts b/packages/api/src/features/resume/public-pdf.test.tsindex 52323e75b..ae4825178 100644--- a/packages/api/src/features/resume/public-pdf.test.ts+++ b/packages/api/src/features/resume/public-pdf.test.ts@@ -1,15 +1,15 @@-import { describe, expect, it, vi } from "vite-plus/test";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";import { defaultResumeData } from "@reactive-resume/schema/resume/default";import { createPublicResumePdf } from "./public-pdf";-// The default lookup runs its real query against a stand-in `pg` client that records the SQL and finds nothing.-const queries = vi.hoisted(() => [] as string[]);+// The real lookup query, run against a stand-in `pg` client that records the SQL and returns `rows`.+const pg = vi.hoisted(() => ({ queries: [] as { text: string; params: unknown[] }[], rows: [] as unknown[][] }));vi.mock("@reactive-resume/db/client", async () => {const { drizzle } = await import("drizzle-orm/node-postgres");const client = {- query: ({ text }: { text: string }) => {- queries.push(text);- return Promise.resolve({ rows: [] });+ query: ({ text }: { text: string }, params: unknown[]) => {+ pg.queries.push({ text, params });+ return Promise.resolve({ rows: pg.rows });},};return { db: drizzle({ client: client as never }) };@@ -40,6 +40,11 @@ const dependencies = (resume = buildResume()) => ({});describe("createPublicResumePdf", () => {+ beforeEach(() => {+ pg.queries = [];+ pg.rows = [];+ });+it("authorizes private and password-protected resumes before budget or render", async () => {const privateDependencies = dependencies(buildResume({ isPublic: false }));await expect(createPublicResumePdf(input, privateDependencies)).rejects.toMatchObject({ code: "NOT_FOUND" });@@ -55,7 +60,62 @@ describe("createPublicResumePdf", () => {it("does not look in Trash, so a trashed resume's link stops serving its PDF", async () => {await expect(createPublicResumePdf(input)).rejects.toMatchObject({ code: "NOT_FOUND" });- expect(queries.at(-1)).toContain('"resume"."trashed_at" is null');+ expect(pg.queries.at(-1)?.text).toContain('"resume"."trashed_at" is null');+ });++ it("matches renamed slugs via resumeSlugRedirect and returns rendered PDF", async () => {+ const resume = buildResume();+ resume.data.basics.name = "Ada Lovelace";+ pg.rows = [[resume.id, resume.userId, resume.data, resume.isPublic, resume.passwordHash]];++ const customDeps = {+ resolveCurrentUserId: vi.fn().mockResolvedValue(undefined),+ rateLimiter: { consume: vi.fn() },+ renderPdf: vi.fn().mockResolvedValue(new File(["%PDF"], "ada-lovelace.pdf", { type: "application/pdf" })),+ };+ const result = await createPublicResumePdf({ ...input, slug: "old-slug" }, customDeps);++ const [query] = pg.queries;+ expect(query?.text).toContain('"resume_slug_redirect"');+ expect(query?.text).toContain('"resume_slug_redirect"."expires_at" > now()');+ expect(query?.text).toContain('"resume_slug_redirect"."user_id" = "resume"."user_id"');+ expect(query?.text).toContain('order by "resume"."slug" = $4 desc');+ expect(query?.params[0]).toBe("old-slug");+ expect(query?.params[1]).toBe("old-slug");+ expect(query?.params[2]).toBe("jane");+ expect(query?.params[3]).toBe("old-slug");+ expect(customDeps.rateLimiter.consume).toHaveBeenCalledWith({+ trustedClient: input.trustedClient,+ resumeId: resume.id,+ });+ expect(customDeps.renderPdf).toHaveBeenCalledWith({ data: resume.data, filename: "ada-lovelace.pdf" });+ expect(result.filename).toBe("ada-lovelace.pdf");+ expect(result.body).toBeInstanceOf(File);+ });++ it("requires password when downloading via renamed slug", async () => {+ const resume = buildResume({ passwordHash: "hash" });+ pg.rows = [[resume.id, resume.userId, resume.data, resume.isPublic, resume.passwordHash]];++ await expect(+ createPublicResumePdf(+ { ...input, slug: "old-slug" },+ {+ rateLimiter: { consume: vi.fn() },+ renderPdf: vi.fn(),+ },+ ),+ ).rejects.toMatchObject({+ code: "NEED_PASSWORD",+ data: { username: "jane", slug: "old-slug" },+ });+ });++ it("rejects with NOT_FOUND when redirect or resume does not exist", async () => {+ pg.rows = [];+ await expect(createPublicResumePdf({ ...input, slug: "missing-slug" })).rejects.toMatchObject({+ code: "NOT_FOUND",+ });});it("renders on demand with canonical public stylesheet source", async () => {diff --git a/packages/api/src/features/resume/public-pdf.ts b/packages/api/src/features/resume/public-pdf.tsindex 4a556d6d4..a5c2b2905 100644--- a/packages/api/src/features/resume/public-pdf.ts+++ b/packages/api/src/features/resume/public-pdf.ts@@ -30,10 +30,11 @@ export type PublicResumePdfDependencies = {};const findResume = async ({ username, slug }: Pick<CreatePublicResumePdfInput, "username" | "slug">) => {- const [{ db }, schema, { and, eq, isNull }] = await Promise.all([+ const [{ db }, schema, { and, desc, eq, isNull, sql }, { matchesSlug }] = await Promise.all([import("@reactive-resume/db/client"),import("@reactive-resume/db/schema"),import("drizzle-orm"),+ import("./slugs"),]);const [resume] = await db.select({@@ -45,7 +46,9 @@ const findResume = async ({ username, slug }: Pick<CreatePublicResumePdfInput, "}).from(schema.resume).innerJoin(schema.user, eq(schema.resume.userId, schema.user.id))- .where(and(eq(schema.resume.slug, slug), eq(schema.user.username, username), isNull(schema.resume.trashedAt)));+ .where(and(matchesSlug(slug), eq(schema.user.username, username), isNull(schema.resume.trashedAt)))+ .orderBy(desc(sql`${schema.resume.slug} = ${slug}`))+ .limit(1);return resume ?? null;};@@ -62,19 +65,21 @@ const defaultDependencies: PublicResumePdfDependencies = {(await import("@reactive-resume/pdf/server")).createResumePdfFile({ ...input, uploadOrigin: env.APP_URL }),};+/**+ * Renders a PDF for a public resume identified by username and slug (current or unexpired redirect).+ * Enforces visibility, password access, and rate limiting before generating the file.+ */export async function createPublicResumePdf(input: CreatePublicResumePdfInput,- dependencies: PublicResumePdfDependencies = defaultDependencies,+ dependencies: Partial<PublicResumePdfDependencies> = {},): Promise<{ body: File; filename: string }> {- const resume = await dependencies.findResume(input);+ const deps = { ...defaultDependencies, ...dependencies };+ const resume = await deps.findResume(input);if (!resume) throw new ORPCError("NOT_FOUND");- const currentUserId = await dependencies.resolveCurrentUserId(input.requestHeaders);+ const currentUserId = await deps.resolveCurrentUserId(input.requestHeaders);assertCanView(resume, currentUserId ? { id: currentUserId } : null);- if (- resume.passwordHash &&- !(await dependencies.hasPasswordAccess(input.requestHeaders, resume.id, resume.passwordHash))- ) {+ if (resume.passwordHash && !(await deps.hasPasswordAccess(input.requestHeaders, resume.id, resume.passwordHash))) {throw new ORPCError("NEED_PASSWORD", {status: 401,data: { username: input.username, slug: input.slug },@@ -82,7 +87,7 @@ export async function createPublicResumePdf(}const data = parseStoredResumeData(resume.data);- await dependencies.rateLimiter.consume({ trustedClient: input.trustedClient, resumeId: resume.id });+ await deps.rateLimiter.consume({ trustedClient: input.trustedClient, resumeId: resume.id });const filename = generateFilename(data.basics.name || "Resume", "pdf");- return { body: await dependencies.renderPdf({ data, filename }), filename };+ return { body: await deps.renderPdf({ data, filename }), filename };}diff --git a/packages/api/src/features/resume/service.test.ts b/packages/api/src/features/resume/service.test.tsindex 67d69965e..0eda5337a 100644--- a/packages/api/src/features/resume/service.test.ts+++ b/packages/api/src/features/resume/service.test.ts@@ -488,13 +488,7 @@ describe("getBySlug", () => {describe("statistics.recordDownload", () => {it("lets the owner download a password-protected resume without an unlock cookie", async () => {- dbMock.select.mockReturnValueOnce({- from: () => ({- innerJoin: () => ({- where: () => Promise.resolve([{ id: "r1", userId: "u1", isPublic: true, passwordHash: "hash" }]),- }),- }),- });+ dbMock.select.mockReturnValueOnce(slugLookup([{ id: "r1", userId: "u1", isPublic: true, passwordHash: "hash" }]));await expect(resumeService.statistics.recordDownload({username: "owner",@@ -505,11 +499,56 @@ describe("statistics.recordDownload", () => {).resolves.toBe(true);});it("does not look in Trash for the resume", async () => {- const where = vi.fn((_condition: unknown) => Promise.resolve([]));+ const where = vi.fn((_condition: unknown) => ({ orderBy: () => ({ limit: () => Promise.resolve([]) }) }));dbMock.select.mockReturnValueOnce({ from: () => ({ innerJoin: () => ({ where }) }) });await expect(resumeService.statistics.recordDownload({ username: "owner", slug: "resume", requestHeaders: new Headers() }),).rejects.toMatchObject({ code: "NOT_FOUND" });expect(where.mock.calls[0]?.[0]).toContainEqual(["trashed_at"]);});++ it("matches renamed slugs via matchesSlug and orders by exact slug match", async () => {+ const limit = vi.fn(() => Promise.resolve([{ id: "r1", userId: "u1", isPublic: true, passwordHash: null }]));+ const orderBy = vi.fn((_order: unknown) => ({ limit }));+ const where = vi.fn((_condition: unknown) => ({ orderBy }));+ dbMock.select.mockReturnValueOnce({ from: () => ({ innerJoin: () => ({ where }) }) });++ await expect(+ resumeService.statistics.recordDownload({+ username: "owner",+ slug: "old-slug",+ requestHeaders: new Headers(),+ }),+ ).resolves.toBe(true);++ expect(where.mock.calls[0]?.[0]).toContainEqual(["slug", "old-slug"]);+ expect(orderBy).toHaveBeenCalledTimes(1);+ expect(orderBy.mock.calls[0]?.[0]).toMatchObject({ values: ["slug", "old-slug"] });+ expect(limit).toHaveBeenCalledWith(1);+ });++ it("requires password when downloading via renamed slug", async () => {+ dbMock.select.mockReturnValueOnce(slugLookup([{ id: "r1", userId: "u1", isPublic: true, passwordHash: "hash" }]));+ await expect(+ resumeService.statistics.recordDownload({+ username: "owner",+ slug: "old-slug",+ requestHeaders: new Headers(),+ }),+ ).rejects.toMatchObject({+ code: "NEED_PASSWORD",+ data: { username: "owner", slug: "old-slug" },+ });+ });++ it("throws NOT_FOUND when renamed slug redirect has expired or does not exist", async () => {+ dbMock.select.mockReturnValueOnce(slugLookup([]));+ await expect(+ resumeService.statistics.recordDownload({+ username: "owner",+ slug: "expired-slug",+ requestHeaders: new Headers(),+ }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });+ });});diff --git a/packages/api/src/features/resume/service.ts b/packages/api/src/features/resume/service.tsindex ebb32d46b..c9af072b5 100644--- a/packages/api/src/features/resume/service.ts+++ b/packages/api/src/features/resume/service.ts@@ -197,13 +197,9 @@ const statistics = {}).from(schema.resume).innerJoin(schema.user, eq(schema.resume.userId, schema.user.id))- .where(- and(- eq(schema.resume.slug, input.slug),- eq(schema.user.username, input.username),- isNull(schema.resume.trashedAt),- ),- );+ .where(and(matchesSlug(input.slug), eq(schema.user.username, input.username), isNull(schema.resume.trashedAt)))+ .orderBy(desc(sql`${schema.resume.slug} = ${input.slug}`))+ .limit(1);if (!resume) throw new ORPCError("NOT_FOUND");const viewer = input.currentUserId ? { id: input.currentUserId } : null;diff --git a/packages/api/src/features/resume/slugs.test.ts b/packages/api/src/features/resume/slugs.test.tsindex 3b979b03e..ebf78fd75 100644--- a/packages/api/src/features/resume/slugs.test.ts+++ b/packages/api/src/features/resume/slugs.test.ts@@ -1,9 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vite-plus/test";-const dbMock = vi.hoisted(() => ({ insert: vi.fn(), delete: vi.fn() }));+const dbMock = vi.hoisted(() => ({ insert: vi.fn(), delete: vi.fn(), select: vi.fn() }));vi.mock("@reactive-resume/db/client", () => ({ db: dbMock }));-const { recordSlugChange } = await import("./slugs");+const { matchesSlug, recordSlugChange } = await import("./slugs");beforeEach(() => {for (const mock of Object.values(dbMock)) mock.mockReset();@@ -26,3 +26,22 @@ describe("recordSlugChange", () => {expect(onConflictDoUpdate).toHaveBeenCalled();});});++describe("matchesSlug", () => {+ it("builds condition checking resume slug or unexpired redirect subquery", async () => {+ const { PgDialect } = await import("drizzle-orm/pg-core");+ const { drizzle } = await import("drizzle-orm/node-postgres");+ const testDb = drizzle({ client: {} as never });+ dbMock.select.mockImplementation((fields?: unknown) => testDb.select(fields as never));++ const condition = matchesSlug("old-slug");+ if (!condition) throw new Error("Expected condition");+ const query = new PgDialect().sqlToQuery(condition);++ expect(query.sql).toContain('"resume"."slug" = $1');+ expect(query.sql).toContain('"resume_slug_redirect"."slug" = $2');+ expect(query.sql).toContain('"resume_slug_redirect"."user_id" = "resume"."user_id"');+ expect(query.sql).toContain('"resume_slug_redirect"."expires_at" > now()');+ expect(query.params).toEqual(["old-slug", "old-slug"]);+ });+});diff --git a/packages/api/src/features/resume/social-meta.test.ts b/packages/api/src/features/resume/social-meta.test.tsindex 4ed4b8df7..cea72fbf3 100644--- a/packages/api/src/features/resume/social-meta.test.ts+++ b/packages/api/src/features/resume/social-meta.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from "vite-plus/test";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";import { sampleResumeData } from "@reactive-resume/schema/resume/sample";import { getPublicResumeSocialMeta } from "./social-meta";@@ -16,6 +16,11 @@ vi.mock("@reactive-resume/db/client", async () => {});describe("getPublicResumeSocialMeta", () => {+ beforeEach(() => {+ pg.queries = [];+ pg.rows = [];+ });+it("cards only public, password-free resumes outside Trash, showing what an anonymous visitor sees", async () => {const data = structuredClone(sampleResumeData);data.basics.name = "";@@ -25,10 +30,34 @@ describe("getPublicResumeSocialMeta", () => {const meta = await getPublicResumeSocialMeta({ username: "jane", slug: "resume" });const [query] = pg.queries;- expect(query?.text).toContain('"resume"."is_public" = $3');- expect(query?.params[2]).toBe(true);+ expect(query?.text).toContain('"resume"."is_public" = $4');+ expect(query?.params[3]).toBe(true);expect(query?.text).toContain('"resume"."password" is null');expect(query?.text).toContain('"resume"."trashed_at" is null');expect(meta).toMatchObject({ name: "Resume", description: data.basics.headline });});++ it("matches renamed slugs via resumeSlugRedirect when redirect is active", async () => {+ const data = structuredClone(sampleResumeData);+ data.basics.name = "Jane Doe";+ pg.rows = [["Resume", data]];++ const meta = await getPublicResumeSocialMeta({ username: "jane", slug: "old-slug" });++ const [query] = pg.queries;+ expect(query?.text).toContain('"resume_slug_redirect"');+ expect(query?.text).toContain('"resume_slug_redirect"."expires_at" > now()');+ expect(query?.text).toContain('"resume_slug_redirect"."user_id" = "resume"."user_id"');+ expect(query?.text).toContain('order by "resume"."slug" = $5 desc');+ expect(query?.params[0]).toBe("old-slug");+ expect(query?.params[1]).toBe("old-slug");+ expect(query?.params[2]).toBe("jane");+ expect(query?.params[4]).toBe("old-slug");+ expect(meta).toMatchObject({ name: expect.stringContaining("Jane Doe") });+ });++ it("returns null when redirect or resume does not exist", async () => {+ const meta = await getPublicResumeSocialMeta({ username: "jane", slug: "missing-slug" });+ expect(meta).toBeNull();+ });});diff --git a/packages/api/src/features/resume/social-meta.ts b/packages/api/src/features/resume/social-meta.tsindex 88af444ae..d80726f66 100644--- a/packages/api/src/features/resume/social-meta.ts+++ b/packages/api/src/features/resume/social-meta.ts@@ -9,10 +9,11 @@ export type PublicResumeSocialMetaInput = { username: string; slug: string };// leak their summary to an unauthenticated crawler, and this read deliberately skips the view counting// and access gating in resumeService.getBySlug — a card render is not a visit.const findResume = async ({ username, slug }: PublicResumeSocialMetaInput) => {- const [{ db }, schema, { and, eq, isNull }] = await Promise.all([+ const [{ db }, schema, { and, desc, eq, isNull, sql }, { matchesSlug }] = await Promise.all([import("@reactive-resume/db/client"),import("@reactive-resume/db/schema"),import("drizzle-orm"),+ import("./slugs"),]);const [resume] = await db.select({ name: schema.resume.name, data: schema.resume.data })@@ -20,17 +21,23 @@ const findResume = async ({ username, slug }: PublicResumeSocialMetaInput) => {.innerJoin(schema.user, eq(schema.resume.userId, schema.user.id)).where(and(- eq(schema.resume.slug, slug),+ matchesSlug(slug),eq(schema.user.username, username),eq(schema.resume.isPublic, true),isNull(schema.resume.password),isNull(schema.resume.trashedAt),),- );+ )+ .orderBy(desc(sql`${schema.resume.slug} = ${slug}`))+ .limit(1);return resume ?? null;};+/**+ * Loads metadata (title, description, image) for social card previews of a public resume.+ * Redacts hidden sections and respects password gating and trashed state.+ */export async function getPublicResumeSocialMeta(input: PublicResumeSocialMetaInput): Promise<ResumeSocialMeta | null> {const resume = await findResume(input);if (!resume) return null;