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: float application bulk actions and enable auth joins (#3675)
Amruth Pillaib8710f43ad12
diff --git a/apps/web/src/features/applications/components/list-view.tsx b/apps/web/src/features/applications/components/list-view.tsxindex 80e15a77d..c1167c8c1 100644--- a/apps/web/src/features/applications/components/list-view.tsx+++ b/apps/web/src/features/applications/components/list-view.tsx@@ -15,6 +15,7 @@ import {DropdownMenuTrigger,} from "@reactive-resume/ui/components/dropdown-menu";import { Icon } from "@reactive-resume/ui/components/icon";+import { IconButton } from "@reactive-resume/ui/components/icon-button";import { Input } from "@reactive-resume/ui/components/input";import { Popover, PopoverContent, PopoverTrigger } from "@reactive-resume/ui/components/popover";import { toast } from "@reactive-resume/ui/components/toast";@@ -217,7 +218,7 @@ export function ApplicationList({ applications, showClosed, selectedId, onOpen }animate={{ opacity: 1, transform: "translateY(0%)" }}exit={{ opacity: 0, transform: "translateY(100%)", transition: { duration: D2 * EXIT, ease: EASE } }}transition={{ duration: D2, ease: EASE }}- className="sticky bottom-4 z-20 justify-self-center max-sm:bottom-[calc(69px+env(safe-area-inset-bottom))]"+ className="fixed inset-x-0 bottom-6 z-30 mx-auto w-fit max-w-[calc(100vw-32px)] max-sm:bottom-[calc(69px+env(safe-area-inset-bottom))]"><BulkBar ids={checkedIds} onDone={() => setChecked(new Set())} /></m.div>@@ -375,14 +376,18 @@ function BulkBar({ ids, onDone }: BulkBarProps) {});return (- <div className="flex flex-wrap items-center gap-1.5 rounded-xl bg-ink px-3 py-2 text-bg shadow-e3">- <span className="me-1 text-sm font-semibold">+ <div+ role="toolbar"+ aria-label={t`Applications`}+ className="flex flex-wrap items-center gap-1 rounded-xl border border-line bg-raised p-1.5 text-ink shadow-e3"+ >+ <span className="px-2 text-sm font-semibold whitespace-nowrap" aria-live="polite"><Plural value={ids.length} one="# selected" other="# selected" /></span><DropdownMenu>- <DropdownMenuTrigger render={<Button size="sm" variant="secondary" />}>- <Icon name="arrow-right" size={16} />+ <DropdownMenuTrigger render={<Button size="sm" variant="ghost" />}>+ <Icon name="arrow-right" /><Trans>Move to…</Trans></DropdownMenuTrigger><DropdownMenuContent align="start">@@ -396,8 +401,8 @@ function BulkBar({ ids, onDone }: BulkBarProps) {</DropdownMenu><Popover>- <PopoverTrigger render={<Button size="sm" variant="secondary" />}>- <Icon name="tag" size={16} />+ <PopoverTrigger render={<Button size="sm" variant="ghost" />}>+ <Icon name="tag" /><Trans>Add tag</Trans></PopoverTrigger><PopoverContent align="start" className="w-60 p-2">@@ -419,7 +424,7 @@ function BulkBar({ ids, onDone }: BulkBarProps) {</Popover><DropdownMenu>- <DropdownMenuTrigger render={<Button size="sm" variant="secondary" />}>+ <DropdownMenuTrigger render={<Button size="sm" variant="ghost" />}><Trans>Close…</Trans></DropdownMenuTrigger><DropdownMenuContent align="start">@@ -436,8 +441,8 @@ function BulkBar({ ids, onDone }: BulkBarProps) {<Buttonsize="sm"- variant="secondary"- className="text-danger-text"+ variant="ghost"+ className="text-danger-text hover:bg-danger-soft"onClick={async () => {const confirmed = await confirm(plural(ids.length, { one: "Delete # application?", other: "Delete # applications?" }),@@ -449,12 +454,11 @@ function BulkBar({ ids, onDone }: BulkBarProps) {if (confirmed) bulkDelete.mutate({ ids });}}>+ <Icon name="trash" /><Trans>Delete…</Trans></Button>- <Button size="sm" variant="ghost" className="ms-auto text-bg hover:bg-bg/15" onClick={onDone}>- <Trans>Clear</Trans>- </Button>+ <IconButton icon="x" size="icon-sm" label={t`Clear selection`} className="text-ink-2" onClick={onDone} /></div>);}diff --git a/packages/api/src/features/auth/joins.integration.test.ts b/packages/api/src/features/auth/joins.integration.test.tsnew file mode 100644index 000000000..54d07432c--- /dev/null+++ b/packages/api/src/features/auth/joins.integration.test.ts@@ -0,0 +1,89 @@+import { createHmac, randomUUID } from "node:crypto";+import { afterAll, beforeAll, describe, expect, it, vi } from "vite-plus/test";+import { Pool } from "pg";+import { auth } from "@reactive-resume/auth/config";+import { withDatabasePool } from "@reactive-resume/db/client";+import { env } from "@reactive-resume/env/server";++// Uses an explicitly supplied disposable, migrated database and private fixture tables.+describe.skipIf(!process.env.OAUTH_TEST_DATABASE_URL)("joined authentication reads", () => {+ const schemaName = `auth_joins_${randomUUID().replaceAll("-", "")}`;+ let admin: Pool;+ let pool: Pool;++ beforeAll(async () => {+ admin = new Pool({ connectionString: process.env.OAUTH_TEST_DATABASE_URL });+ await admin.query(`CREATE SCHEMA ${schemaName}`);+ for (const table of ["user", "session", "account"]) {+ await admin.query(`CREATE TABLE ${schemaName}."${table}" (LIKE public."${table}" INCLUDING ALL)`);+ }+ pool = new Pool({ connectionString: process.env.OAUTH_TEST_DATABASE_URL, options: `-c search_path=${schemaName}` });+ await pool.query(`INSERT INTO "user" (id,name,email,username,display_username) VALUES+ ('owner','Owner','[email protected]','owner','owner'),+ ('other','Other','[email protected]','other','other')`);+ await pool.query(`INSERT INTO session (id,token,user_id,expires_at) VALUES+ ('owner-session','owner-token','owner',now() + interval '7 days'),+ ('other-session','other-token','other',now() + interval '7 days'),+ ('expired-session','expired-token','owner',now() - interval '1 day')`);+ await pool.query(`INSERT INTO account (id,account_id,provider_id,user_id,password) VALUES+ ('owner-password','owner','credential','owner','private-password-hash'),+ ('owner-github','github-owner','github','owner',NULL),+ ('other-github','github-other','github','other',NULL)`);+ });++ afterAll(async () => {+ await pool?.end();+ await admin?.query(`DROP SCHEMA IF EXISTS ${schemaName} CASCADE`);+ await admin?.end();+ });++ it("returns only the session owner in one query and rejects expired or deleted sessions", async () => {+ await withDatabasePool(pool, async () => {+ const context = await auth.$context;+ const getSession = async (token: string) => {+ const signature = createHmac("sha256", env.AUTH_SECRET).update(token).digest("base64");+ return auth.handler(+ new Request(`${env.APP_URL}/api/auth/get-session`, {+ headers: {+ cookie: `${context.authCookies.sessionToken.name}=${encodeURIComponent(`${token}.${signature}`)}`,+ },+ }),+ );+ };+ const queries = vi.spyOn(pool, "query");+ try {+ const response = await getSession("owner-token");+ expect(response.status).toBe(200);+ const session = await response.json();+ expect(session).toMatchObject({ session: { id: "owner-session" }, user: { id: "owner" } });+ expect(queries).toHaveBeenCalledTimes(1);+ expect(JSON.stringify(session)).not.toContain("private-password-hash");+ await expect((await getSession("expired-token")).json()).resolves.toBeNull();+ await pool.query("DELETE FROM session WHERE token = 'owner-token'");+ await expect((await getSession("owner-token")).json()).resolves.toBeNull();+ } finally {+ queries.mockRestore();+ }+ });+ });++ it("loads a user's linked accounts and resolves a provider account's owner in one query each", async () => {+ await withDatabasePool(pool, async () => {+ const { internalAdapter } = await auth.$context;+ const queries = vi.spyOn(pool, "query");+ try {+ const found = await internalAdapter.findUserByEmail("[email protected]", { includeAccounts: true });+ expect(found?.user.id).toBe("owner");+ expect(found?.accounts.map((account) => account.id).sort()).toEqual(["owner-github", "owner-password"]);+ expect(queries).toHaveBeenCalledTimes(1);+ queries.mockClear();+ await expect(+ internalAdapter.findAccountOwnerByKey({ providerId: "github", accountId: "github-other" }),+ ).resolves.toMatchObject({ kind: "owned", account: { id: "other-github" }, user: { id: "other" } });+ expect(queries).toHaveBeenCalledTimes(1);+ } finally {+ queries.mockRestore();+ }+ });+ });+});diff --git a/packages/auth/src/config.test.ts b/packages/auth/src/config.test.tsindex 1a3e6b73d..7524259ea 100644--- a/packages/auth/src/config.test.ts+++ b/packages/auth/src/config.test.ts@@ -23,6 +23,7 @@ describe("session freshness", () => {});it.each([+ ["GET", "/reference"],["GET", "/token"],["POST", "/delete-anonymous-user"],])("does not serve %s %s", async (method, path) => {diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.tsindex 1d955b1c2..8bc61a963 100644--- a/packages/auth/src/config.ts+++ b/packages/auth/src/config.ts@@ -3,7 +3,7 @@ import type { GenericOAuthConfig, GenericOAuthUserInfo } from "better-auth/plugiimport type { JWTPayload } from "jose";import { AsyncLocalStorage } from "node:async_hooks";import { apiKey } from "@better-auth/api-key";-import { drizzleAdapter } from "@better-auth/drizzle-adapter";+import { drizzleAdapter } from "@better-auth/drizzle-adapter/relations-v2";import { dash } from "@better-auth/infra";import { oauthProvider } from "@better-auth/oauth-provider";import { passkey } from "@better-auth/passkey";@@ -458,7 +458,7 @@ const getAuthConfig = () => {onAPIError: { errorURL: "/auth/error" },advanced: {- database: { generateId },+ database: { generateId, joins: true },useSecureCookies: authBaseUrl.startsWith("https://"),ipAddress: { ipAddressHeaders: ["X-Real-IP"] },},@@ -604,6 +604,7 @@ const getAuthConfig = () => {},plugins: [+ // JSON schema only; no reference-page inline scripts need a CSP nonce.openAPI({ disableDefaultReference: true }),jwt({ disableSettingJwtHeader: true }),admin(),diff --git a/packages/db/src/client.ts b/packages/db/src/client.tsindex 3a5915a24..4321b3a20 100644--- a/packages/db/src/client.ts+++ b/packages/db/src/client.ts@@ -2,12 +2,14 @@ import { AsyncLocalStorage } from "node:async_hooks";import { drizzle } from "drizzle-orm/node-postgres";import { Pool } from "pg";import { env } from "@reactive-resume/env/server";+import { authRelations } from "./schema/auth";-const requestDatabase = new AsyncLocalStorage<{ pool: Pool; database: ReturnType<typeof drizzle> }>();+const createDatabase = (pool: Pool) => drizzle({ client: pool, relations: authRelations });+const requestDatabase = new AsyncLocalStorage<{ pool: Pool; database: ReturnType<typeof createDatabase> }>();declare global {var __pool: Pool | undefined;- var __drizzle: ReturnType<typeof drizzle> | undefined;+ var __drizzle: ReturnType<typeof createDatabase> | undefined;}export function getPool() {@@ -39,11 +41,11 @@ export function getPool() {}// ponytail: two private fns collapsed; getPool() is already a singleton, global cache preserved-globalThis.__drizzle ??= drizzle({ client: getPool() });+globalThis.__drizzle ??= createDatabase(getPool());/** Workers must create sockets inside a request and cannot reuse them in another request. */export function withDatabasePool<T>(pool: Pool, callback: () => T): T {- return requestDatabase.run({ pool, database: drizzle({ client: pool }) }, callback);+ return requestDatabase.run({ pool, database: createDatabase(pool) }, callback);}export const db = new Proxy(globalThis.__drizzle, {diff --git a/packages/db/src/schema/auth.ts b/packages/db/src/schema/auth.tsindex e5a422a2b..4c0f7e801 100644--- a/packages/db/src/schema/auth.ts+++ b/packages/db/src/schema/auth.ts@@ -1,6 +1,6 @@import type { SQL } from "drizzle-orm";import type { AnyPgColumn } from "drizzle-orm/pg-core";-import { sql } from "drizzle-orm";+import { defineRelations, sql } from "drizzle-orm";import * as pg from "drizzle-orm/pg-core";import { generateId } from "@reactive-resume/utils/string";@@ -125,6 +125,20 @@ export const account = pg.pgTable(],);+// Better Auth joins sessions to users, users to accounts, and provider accounts to their owners.+export const authRelations = defineRelations({ user, session, account }, (r) => ({+ user: {+ accounts: r.many.account({ from: r.user.id, to: r.account.userId }),+ sessions: r.many.session({ from: r.user.id, to: r.session.userId }),+ },+ session: {+ user: r.one.user({ from: r.session.userId, to: r.user.id }),+ },+ account: {+ user: r.one.user({ from: r.account.userId, to: r.user.id }),+ },+}));+export const verification = pg.pgTable("verification",{diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex fadfb6c95..32d40f210 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -94,3 +94,6 @@ overrides:dompurify@<3.4.17: ^3.4.17patchedDependencies:[email protected]: apps/mobile/patches/[email protected]+skills:+ dirs:+ - .agents/skills