Security audit · 2026-10-03 · commit 7d659be · deps: osv-scanner (docker): 5 vulnerable packages · secrets: gitleaks (docker): 2 hits, 2 commits of this repo

ledgerly

27 issues to fix (2 critical, 14 high, 8 medium, 3 low).

23 areas verified safe · 7 checks not assessed

To fix

Verified findings, most severe first. “Failing test” means a regression test in the project’s own runner fails today; “code reading only” means it was confirmed by tracing the code.

Fix first

  1. Identifiers on public project pages let any self-registered account read and overwrite other organizations' customers, invoices, projects and filescritical · code reading only · src/app/p/[slug]/page.tsx:7
  2. next 16.3.0 has an unauthenticated RCE advisory in the image optimizer, and the config lets anyone choose the image source through *.r2.devcritical · code reading only · pnpm-lock.yaml:238
  3. Admin stats API has no authentication and returns recent users' names and emailshigh · failing test · src/app/api/admin/stats/route.ts:5

critical · 2

criticalIdentifiers on public project pages let any self-registered account read and overwrite other organizations' customers, invoices, projects and filesCode reading onlysrc/app/p/[slug]/page.tsx:7

How to fix

Fix all five; order by what breaks the most at once. First exposure-101 (select only name, description and document id/filename for the public page), which removes the anonymous source of ids. Then the consumers, each of which must stop trusting a client-supplied identifier: auth-104 (use the session's organization only), auth-107 (drop orgId from the tool input), auth-106 (scope the update by ctx.orgId), auth-109 (generate storage keys on the server under the organization's prefix and check the prefix on download). Treat any id that was ever on a public page as known to outsiders.

Evidence

  • File: src/app/p/[slug]/page.tsx:7 (enabler, exposure-101)
  • Code:
  const project = await db.query.projects.findFirst({
    where: (p, { and, eq }) => and(eq(p.slug, slug), eq(p.isPublic, true)),
    with: { documents: true },
  });
  if (!project) notFound();
  return <PublicProjectView project={project} />;
  • The full rows go to the client component (src/components/public-project-view.tsx:1,7), so an anonymous page response carries the project's id and orgId and each document's s3Key (src/db/schema.ts:95-96,159). /p/[slug] is outside the proxy matcher (src/proxy.ts:14-22).
  • Those identifiers are random (crypto.randomUUID() for projects, src/app/(app)/projects/actions.ts:32; Better Auth ids for organizations), so without this page an outsider has no way to obtain them. Each consumer below accepts them from any signed-in user:
  • organization id: src/app/api/export/route.ts:11 (searchParams.get("org"), auth-104) and src/server/ai/tools.ts:12,29 (model-chosen orgId, auth-107)
  • project id: src/server/trpc/routers/project.ts:24 (where(eq(projects.id, id)), returns the full row, auth-106)
  • storage key: src/app/api/uploads/route.ts:25,33 (client-chosen Key presigned and stored in the caller's own organization, then presigned for GET by src/app/api/documents/[id]/download/route.ts:26, auth-109)
  • The account those consumers need is self-service: open email sign-up (src/lib/auth.ts:12-14) and allowUserToCreateOrganization: true (src/lib/auth.ts:39).

Data flow

  • Source: anonymous GET /p/<slug> of any public project (src/app/p/[slug]/page.tsx:5-6)
  • Transformations: full project and document rows serialized into the page payload (page.tsx:7-12); the attacker's own self-registered session then carries those ids into the four consumers
  • Sink: customers query bound to the foreign organization (src/app/api/export/route.ts:23); invoices joined with customers (src/server/ai/tools.ts:29); UPDATE projects ... WHERE id = $1 RETURNING * (src/server/trpc/routers/project.ts:24); presigned PUT and later GET on the foreign object key (src/app/api/uploads/route.ts:23-27, src/app/api/documents/[id]/download/route.ts:22-30)
  • Sanitization: none on the page (no column selection) and no organization check in any of the four consumers
  • Verdict: VULNERABLE

Impact

Anyone, starting with no account and no relation to the victim, can take any organization that has a public project page and, after creating a free Ledgerly account, export that organization's whole customer list with emails, phone numbers and tax ids, pull its invoices through the assistant, edit or take down its public projects, and read or replace the files attached to them. Alone, auth-104, auth-106, auth-107 and auth-109 each need an identifier that an outsider has no way to get (only current or former members know it), and exposure-101 alone discloses one project's internal fields; together they turn every public page into an entry point for bulk cross-tenant data theft and tampering.

Rating: CRITICAL. The only credential is an account anyone can create in a minute, so in substance no authorization is needed, and the impact includes data loss (overwritten files and project fields) as well as bulk personal data of other organizations' customers. Prerequisite (1): the victim organization marked a project public, a normal product action (same as exposure-101); scale is every organization with a public page whose slug the attacker knows or guesses (slugs are short, globally unique words, src/app/(app)/projects/actions.ts:22-24, src/db/schema.ts:109).

Regression test

proof: static. Every link has its own failing test (.security-audit/tests/exposure-101.test.ts, auth-104.test.ts, auth-106.test.ts, auth-107.test.ts, auth-109.test.ts); the combined path needs a real database and an S3-compatible store end to end, which the harness does not provide. Fixing exposure-101 breaks step 1; fixing the four consumers removes the impact even if ids leak another way.

Chained with

  • exposure-101
  • auth-104
  • auth-106
  • auth-107
  • auth-109

chain-901 · Chains

criticalnext 16.3.0 has an unauthenticated RCE advisory in the image optimizer, and the config lets anyone choose the image source through *.r2.devCode reading onlypnpm-lock.yaml:238

How to fix

Upgrade next to 16.3.6 or later (covers all three advisories) and re-lock. Replace *.r2.dev with the exact bucket hostname, or drop it if no page renders R2 images through next/image (none does in src/). Confirm the deployment platform and record it in the repo.

Evidence

  • File: pnpm-lock.yaml:238
  • Code:
  next@16.3.0:            # package.json "next": "16.3.0" (exact pin)
    optionalDependencies:
      sharp: 0.34.5
  • osv-scanner (.security-audit/tools/osv.json), next 16.3.0:
GHSA-2xp9-vwfh-vxw4  Unauthenticated Remote Code Execution in Image Optimization API when AVIF files are used
                     (libheif inside sharp, reached when AVIF files are optimized); affected 16.0.0 to <16.3.3
GHSA-p293-qw3h-jr36  Unauthenticated RCE on windows-hosted servers; affected 16.0.0 to <16.3.3
GHSA-vcvr-r3jv-pc5j  RCE in next/og ImageResponse (Node runtime, attacker values in SVG); affected 16.2.0 to <16.3.6
  • File: next.config.ts:4
  images: {
    remotePatterns: [
      { protocol: "https", hostname: "avatars.githubusercontent.com" },
      { protocol: "https", hostname: "*.r2.dev" },
    ],
  },
  • No images.unoptimized and no custom loader, so the built-in optimizer endpoint is active under next start. src/ imports neither next/image nor next/og (grep); the optimizer endpoint does not depend on the component being used (Next.js documentation; the package is not installed here).

Data flow

  • Source: anonymous request to the image optimization endpoint naming a remote image URL
  • Transformations: the URL must match remotePatterns; *.r2.dev matches public development hostnames that any Cloudflare account can create, so the image's origin is outside Ledgerly's control
  • Sink: sharp/libheif decoding the fetched image inside the Next.js server process (GHSA-2xp9-vwfh-vxw4)
  • Sanitization: none in the app
  • Verdict: VULNERABLE under one condition: the deployment runs Next's own image optimizer (self-hosted next start, the start script in package.json). If the app is behind a platform image service (for example Vercel's), the decode does not run in the app process and this drops sharply. GHSA-vcvr: not reachable (no next/og). GHSA-p293: only if hosted on Windows (unknown, no evidence of it).

Impact

Per the advisory, anyone on the internet, without an account, could run code on the Ledgerly web server through the image optimizer, and the *.r2.dev pattern lets them supply the image from a host they control. Code execution on the web server means access to every environment secret (database, Stripe, R2, Anthropic, auth secret) and to all tenants' data. Rating kept CRITICAL with 0 admin prerequisites: the reachability condition is the deployment platform (not visible in the repo: not-assessed.md), not a configuration step, and CRITICAL is exempt from prerequisite downgrade for RCE. A long-running pg-boss worker (pnpm worker) suggests a server deployment, which is consistent with, but does not prove, self-hosting.

Regression test

proof: static. next is not installed in node_modules (no package files in the .pnpm store) and the flaw is in native image decoding; a runtime test would need the vulnerable package and a crafted image, neither of which an audit test should use. Version and range come from osv.json and pnpm-lock.yaml.

Chained with

  • dependency-102 (same decoder path; sharp's own advisories)

dependency-101 · Dependencies

high · 14

highAdmin stats API has no authentication and returns recent users' names and emailsFailing testsrc/app/api/admin/stats/route.ts:5

How to fix

Check the session and role === "admin" inside the handler and return 401/403 (not a redirect). Fix auth-103 in the same change, otherwise the role check is bypassable by any registered user.

Docs also claim the opposite: README.md:30 ("Every API route requires an authenticated session or an API key").

Evidence

  • File: src/app/api/admin/stats/route.ts:5
  • Code:
export async function GET() {
  const [users] = await db.select({ total: count() }).from(user);
  const [orgs] = await db.select({ total: count() }).from(organization);
  const [projectCount] = await db.select({ total: count() }).from(projects);
  const recentSignups = await db
    .select({ id: user.id, name: user.name, email: user.email, createdAt: user.createdAt })
    .from(user)
    .orderBy(desc(user.createdAt))
    .limit(25);
  • The handler imports no session helper at all (route.ts:1-3). The /admin page checks requireAdmin() (src/app/admin/page.tsx:5), but the API it fetches from the browser (src/components/admin-stats.tsx:16) does not, and /api/* is outside the proxy matcher (src/proxy.ts:15-22).
  • EXPAND: this is the only route under /api/admin (prepass entry points 1-45); no other path prefix reaches these queries.

Data flow

  • Source: any GET to /api/admin/stats, no session needed
  • Transformations: none
  • Sink: JSON response with recentSignups and platform counts (route.ts:19-25)
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

Anyone, without signing in, can read the names and email addresses of the 25 most recent sign-ups plus platform-wide counts of users, organizations, projects and subscriptions per plan. Polling the endpoint over time collects the email of every new user.

Regression test

  • Path: .security-audit/tests/auth-102.test.ts
  • Asserts: an anonymous caller, and a signed-in non-admin, get 401/403 (or a redirect) and no SQL statement is issued.
  • Output today (fails, both cases):
FAIL auth-102.test.ts > auth-102 admin stats API > an anonymous caller gets 401/403 (or a redirect) and no user data is read
AssertionError: expected [ { …(2) }, { …(2) }, { …(2) }, …(2) ] to deeply equal []
+   "sql": "select count(*) from \"user\"" ...
+   "sql": "select \"id\", \"name\", \"email\", \"created_at\" from \"user\" order by \"user\".\"created_at\" desc limit $1"
+   "sql": "select \"plan\", count(*) from \"subscriptions\" group by \"subscriptions\".\"plan\""

Chained with

  • auth-103 (a role check in this handler is bypassable while users can set their own role)

auth-102 · Authentication & authorization

highUser-writable role field lets any account give itself the admin roleFailing testsrc/lib/auth.ts:29

How to fix

role: { type: "string", defaultValue: "member", input: false } (same for any field users must not set). Audit existing rows for role = 'admin' not granted by staff. Consider Better Auth's admin plugin for role management.

Evidence

  • File: src/lib/auth.ts:29
  • Code:
  user: {
    additionalFields: {
      role: { type: "string", defaultValue: "member" },
      emailDigest: { type: "boolean", defaultValue: true },
    },
  },
  • Admin check reads that field: src/lib/session.ts:24 if (session.user.role !== "admin") redirect("/dashboard");, used by src/app/admin/page.tsx:5.
  • Library behaviour confirmed in better-auth 1.6.27 (installed copy under node_modules/.pnpm/better-auth@1.6.27*/node_modules/better-auth/dist):
  • api/routes/sign-up.mjs:14-21: the body schema is z.object({...}).and(z.record(z.string(), z.any())), so extra keys pass; sign-up.mjs:149 takes ...rest and sign-up.mjs:164 calls parseUserInput(ctx.context.options, rest, "create"); sign-up.mjs:221-227 spreads the result into createUser.
  • api/routes/update-user.mjs:11 body is z.record(...); update-user.mjs:52-54 takes ...rest and calls parseUserInput(ctx.context.options, rest, "update"); update-user.mjs:56 writes the result with updateUser(session.user.id, ...).
  • db/schema.mjs:59-94 (parseInputData): a field is refused or reset only when fields[key].input === false; otherwise the client value is copied (schema.mjs:92).

Data flow

  • Source: role in the JSON body of POST /api/auth/sign-up/email or POST /api/auth/update-user (src/app/api/auth/[...all]/route.ts:4)
  • Transformations: parseUserInput keeps it because input is not false
  • Sink: user.role column (src/db/schema.ts:10), read back as session.user.role by requireAdmin (src/lib/session.ts:24)
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

Anyone who registers, and any signed-in user through update-user, can set their own account's platform role to admin and pass requireAdmin, which opens /admin. Today the admin page shows the same data that auth-102 already exposes, but this finding stands on its own: once auth-102 is fixed with a role check it keeps that data open to every registered user, and every future admin feature inherits it.

Regression test

  • Path: .security-audit/tests/auth-103.test.ts
  • Asserts: with the app's real Better Auth options (auth.options from src/lib/auth.ts), parseUserInput (the function both endpoints call) keeps role at the default member on create and refuses or drops it on update. A control case shows both assertions hold once input: false is set.
  • Output today (2 fail, control passes):
FAIL auth-103.test.ts > auth-103 user role field > sign-up ignores a client-supplied role and stores the default
AssertionError: expected 'admin' to be 'member'
FAIL auth-103.test.ts > auth-103 user role field > update-user refuses or drops a client-supplied role
AssertionError: expected 'admin' to be undefined
Tests  2 failed | 1 passed (3)

Chained with

  • auth-102

auth-103 · Authentication & authorization

highCustomer export takes the organization id from the query stringFailing testsrc/app/api/export/route.ts:11

How to fix

Use session.session.activeOrganizationId only (and see auth-801 for the membership check behind it). If exporting another of the user's organizations is a feature, check a member row for (userId, orgId) first.

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/app/api/export/route.ts:11
  • Code:
  const session = await getSession();
  if (!session) return new Response("Unauthorized", { status: 401 });

  const { searchParams } = new URL(request.url);
  const orgId = searchParams.get("org") ?? session.session.activeOrganizationId;
  if (!orgId) return new Response("No organization selected", { status: 400 });

  const rows = await db
    .select({ name: customers.name, email: customers.email, phone: customers.phone, taxId: customers.taxId, createdAt: customers.createdAt })
    .from(customers)
    .where(eq(customers.orgId, orgId));

Data flow

  • Source: ?org= query parameter (route.ts:11)
  • Transformations: none; no member lookup for (user, org)
  • Sink: customers query (route.ts:14-23), returned as CSV (route.ts:30-35)
  • Sanitization: session existence only (route.ts:8)
  • Verdict: VULNERABLE

Impact

Any signed-in user (sign-up and organization creation are open, src/lib/auth.ts:12-13,39) can download another organization's full customer list, with names, emails, phone numbers and tax ids, by naming that organization's id in the org parameter. Organization ids are readable on public project pages (exposure-101) and are known to anyone who was ever a member.

Regression test

  • Path: .security-audit/tests/auth-104.test.ts
  • Asserts: a member of org B calling /api/export?org=org-A never causes a customers query bound to org-A (either the query uses org B or the request is refused).
  • Output today (fails):
FAIL auth-104.test.ts > auth-104 customer export > a member of org B naming org A in ?org= does not get org A's customers
AssertionError: expected [ 'org-A' ] to not include 'org-A'

Chained with

  • chain-901
  • chain-902
  • exposure-101

auth-104 · Authentication & authorization

highgetInvoice server action reads any invoice by id with no session or organization checkFailing testsrc/app/(app)/invoices/actions.ts:10

How to fix

In getInvoice, call requireOrg() and filter and(eq(invoices.id, id), eq(invoices.orgId, orgId)), or reuse invoiceRouter.byId, which already does (src/server/trpc/routers/invoice.ts:26). Return only the fields the quick view needs.

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/app/(app)/invoices/actions.ts:10
  • Code:
"use server";
...
export async function getInvoice(id: string) {
  const [invoice] = await db.select().from(invoices).where(eq(invoices.id, id)).limit(1);
  if (!invoice) return null;
  const lines = await db.select().from(invoiceLines).where(eq(invoiceLines.invoiceId, invoice.id));
  return { ...invoice, lines };
}
  • Exported from a "use server" file and imported by a client component (src/components/invoice-quick-view.tsx:4,13), so it is a server action with its own POST endpoint, callable directly.
  • Also the data source of src/app/(app)/invoices/[id]/page.tsx:7, whose only guards are the layout (src/app/(app)/layout.tsx:6) and the proxy (src/proxy.ts:5), which checks only that a cookie with the session cookie name exists, not that it is valid.
  • Sibling markInvoicePaid in the same file scopes by org (actions.ts:20,25); invoiceRouter.byId does too (src/server/trpc/routers/invoice.ts:26).

Data flow

  • Source: id argument of the server action POST, or the [id] route param of /invoices/[id]
  • Transformations: none
  • Sink: invoices select by id only (actions.ts:11), invoiceLines by parent id (actions.ts:13), full rows returned to the caller
  • Sanitization: none in the action
  • Verdict: VULNERABLE

Impact

A signed-in member of any organization can read another organization's invoice (all columns: amount, currency, status, notes, customer id, project id) and its line items by id, through the server action or by opening /invoices/<id>. Through the server action a valid session is not needed either: the action has no check of its own, the proxy accepts any value in a cookie with the session cookie's name, and the Next.js documentation states that a page or layout check does not extend to the Server Actions used there (an action call that does not revalidate returns only the action result, without rendering the layout). Next.js is not installed in this checkout, so that last part comes from documentation and was not executed. Invoice ids are not exposed across organizations anywhere in src/ (checked: public page, public API, digest, assistant tools return no invoice id), so an attacker needs an id they saw before, for example as a former member or from a shared /invoices/<id> link; that limits discovery, not access.

Regression test

  • Path: .security-audit/tests/auth-105.test.ts
  • Asserts: (1) without a session the action rejects and no invoice query runs; (2) for a member of org B the invoice query is bound to org B.
  • Output today (both fail):
FAIL auth-105.test.ts > auth-105 getInvoice server action > without a session the action is refused and no invoice is read
AssertionError: expected [ { …(2) } ] to deeply equal []
+   "params": [ "inv-of-org-A", 1 ],
+   "sql": "select \"id\", \"org_id\", ... from \"invoices\" where \"invoices\".\"id\" = $1 limit $2"
FAIL auth-105.test.ts > auth-105 getInvoice server action > for a member of org B the invoice query is scoped to org B
AssertionError: expected [ 'inv-of-org-A', 1 ] to include 'org-B'

Chained with

  • none

auth-105 · Authentication & authorization

hightRPC project.update changes any organization's project by idFailing testsrc/server/trpc/routers/project.ts:24

How to fix

.where(and(eq(projects.id, id), eq(projects.orgId, ctx.orgId))) and return only the columns the UI needs. Replace the existing update test, which mocks the database and asserts only the returned name (src/server/trpc/routers/project.test.ts:20-31).

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/server/trpc/routers/project.ts:24
  • Code:
  update: orgProcedure
    .input(z.object({ id: z.string(), name: ..., description: ..., internalNotes: ..., isPublic: z.boolean().optional() }))
    .mutation(async ({ ctx, input }) => {
      const { id, ...patch } = input;
      const [updated] = await ctx.db.update(projects).set(patch).where(eq(projects.id, id)).returning();
      if (!updated) throw new TRPCError({ code: "NOT_FOUND" });
      return updated;
    }),
  • ctx.orgId is available (src/server/trpc/init.ts:25) and used by list (project.ts:9) but not here.
  • EXPAND (write path vs read path on the same resource): getProject and deleteProject server actions scope by org (src/app/(app)/projects/actions.ts:15,42); summarizeProject scopes by org (src/server/ai/tools.ts:46). Only update is unscoped.

Data flow

  • Source: tRPC input id and patch fields (POST /api/trpc/project.update)
  • Transformations: zod shape validation only (unknown keys such as orgId are stripped, see non-auth-801)
  • Sink: UPDATE projects SET ... WHERE id = $1 RETURNING * (project.ts:24), full row returned to the caller
  • Sanitization: none for ownership
  • Verdict: VULNERABLE

Impact

Any signed-in member of any organization can change another organization's project (name, description, internal notes, public flag) if they know its id, and the response returns the full updated row, including internal notes, budget and client contact email. Setting isPublic publishes the project at /p/<slug> to anonymous visitors; clearing it takes a public page down. Ids of public projects are in the /p/[slug] page payload (exposure-101), so every public project can be edited this way.

Regression test

  • Path: .security-audit/tests/auth-106.test.ts
  • Asserts: a member of org B updating a project id of org A gets NOT_FOUND and the UPDATE statement is bound to org B in its WHERE clause.
  • Output today (fails):
FAIL auth-106.test.ts > auth-106 project.update > a member of org B updating project id of org A gets NOT_FOUND and the UPDATE is scoped to org B
AssertionError: expected [ true, 'proj-of-org-A' ] to include 'org-B'

Chained with

  • chain-901
  • chain-902
  • exposure-101
  • config-101 (private project ids)

auth-106 · Authentication & authorization

highAssistant tool searchInvoices takes the organization id from the modelFailing testsrc/server/ai/tools.ts:12

How to fix

Remove orgId from inputSchema and use ctx.orgId in the where clause, as summarizeProject does.

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/server/ai/tools.ts:12
  • Code:
    searchInvoices: tool({
      inputSchema: z.object({
        orgId: z.string().describe("Organization id to search in"),
        status: z.enum(["draft", "open", "paid", "void"]).optional(),
        customerName: z.string().optional(),
      }),
      execute: async ({ orgId, status, customerName }) => {
        return db.select({ number: ..., amountCents: ..., status: ..., customer: customers.name, customerEmail: customers.email })
          .from(invoices).innerJoin(customers, eq(customers.id, invoices.customerId))
          .where(and(eq(invoices.orgId, orgId), ...))
  • The trusted ctx.orgId is passed in (src/app/api/chat/route.ts:17) and used by summarizeProject (tools.ts:46), but not here. The system prompt (src/app/api/chat/route.ts:15) is the only thing steering the model to the right id; it is an instruction, not a control.

Data flow

  • Source: user chat messages (src/app/api/chat/route.ts:11), which steer the model-chosen tool argument orgId
  • Transformations: model output, zod z.string()
  • Sink: invoices joined with customers filtered by that orgId (tools.ts:29); up to 20 rows returned to the model and streamed to the user
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

A signed-in user can get the assistant to return another organization's invoices (number, amount, status) with customer names and emails by asking about an organization id other than their own; the tool trusts whatever id the model passes, and the model has no way to tell which ids the user may see. Whether a given prompt makes the model comply varies, but nothing in code stops it. Organization ids are readable on public project pages (exposure-101).

Regression test

  • Path: .security-audit/tests/auth-107.test.ts
  • Asserts: a tool call naming org A, from a chat whose session organization is org B, issues exactly one query and that query is bound to org B, not org A.
  • Output today (fails):
FAIL auth-107.test.ts > auth-107 searchInvoices tool > a tool call naming org A from a chat in org B queries org B only
AssertionError: expected [ 'org-A', 20 ] to not include 'org-A'

Chained with

  • chain-901
  • chain-902
  • exposure-101 (organization ids readable on public project pages)

auth-107 · Authentication & authorization

highWeekly overdue digest emails each organization's invoices to every user on the platformFailing testsrc/server/jobs/digest.ts:28

How to fix

Join member on member.userId = user.id AND member.organizationId = orgId in the recipients query (optionally also require emailVerified).

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/server/jobs/digest.ts:28
  • Code:
  const recipients = await db
    .select({ email: user.email, name: user.name })
    .from(user)
    .where(eq(user.emailDigest, true));
  ...
  for (const r of recipients) {
    await sendEmail({ to: r.email, subject: `${org.name}: ${overdue.length} overdue invoices`, html: `<p>Hi ${r.name},</p><table>${rows}</table>` });
  }
  • The fan-out runs for every organization every Monday 08:00 (src/server/jobs/worker.ts:13-17).
  • emailDigest defaults to true for new users (src/lib/auth.ts:30, src/db/schema.ts:11), and the recipient query does not filter on email_verified.

Data flow

  • Source: job payload orgId from the internal fan-out (worker.ts:17)
  • Transformations: overdue invoices are correctly scoped to orgId (digest.ts:25)
  • Sink: recipient list with no organization or membership filter (digest.ts:28-31), each recipient sent the organization's rows (digest.ts:37-42)
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

Every week each organization's overdue invoices (invoice numbers, customer names, amounts, due dates) and the organization's name are emailed to every platform user with digests enabled, not only to that organization's members. This already happens to all existing users without anyone acting, and anyone who registers an account (no email verification needed for this) starts receiving every organization's overdue invoices.

Regression test

  • Path: .security-audit/tests/auth-108.test.ts
  • Asserts: when the digest for org A runs, the recipient query references the member table and is bound to org A.
  • Output today (fails):
FAIL auth-108.test.ts > auth-108 overdue digest recipients > the recipient query for org A is restricted to members of org A
AssertionError: expected 'select "email", "name" from "user" wh…' to contain '"member"'
Received: "select "email", "name" from "user" where "user"."email_digest" = $1"

Chained with

  • injection-102 (the same email interpolates customer names as raw HTML; chain rejected in COMBINE: no in-app writer of customer names or invoice numbers)

auth-108 · Authentication & authorization

highUpload route signs a client-chosen storage key, so files are not scoped to the organizationFailing testsrc/app/api/uploads/route.ts:25

How to fix

Generate the key on the server (${orgId}/${crypto.randomUUID()}) and never accept it from the client. In download, also assert doc.s3Key.startsWith(${orgId}/) so legacy rows cannot point outside the organization.

Docs also claim the opposite: README.md:33 ("Documents are uploaded straight to R2 with presigned URLs scoped to your organization").

Evidence

  • File: src/app/api/uploads/route.ts:25
  • Code:
const uploadInput = z.object({ projectId: z.string().min(1), filename: ..., contentType: z.string().min(1), key: z.string().min(1) });
...
  const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: BUCKET, Key: input.key, ContentType: input.contentType }), { expiresIn: 900 });
  await db.insert(documents).values({ id: crypto.randomUUID(), orgId, projectId: input.projectId, s3Key: input.key, ... });
  • One bucket for all organizations (src/lib/s3.ts:3). No key convention exists in src/ (no client upload code; grep s3Key, uploads).
  • Download signs whatever key the row holds: src/app/api/documents/[id]/download/route.ts:26 Key: doc.s3Key; the row lookup itself is org-scoped (non-auth-103).

Data flow

  • Source: key in the JSON body of POST /api/uploads (uploads/route.ts:13)
  • Transformations: zod min(1) only
  • Sink: presigned PUT for that key in the shared bucket (route.ts:23-27); documents.s3Key (route.ts:33), later a presigned GET for it (download/route.ts:22-30)
  • Sanitization: none; no organization prefix
  • Verdict: VULNERABLE

Impact

A signed-in user can get a presigned upload URL for any object key in the shared documents bucket, so they can overwrite another organization's stored files; and since the same request stores a document row with that key in the caller's own organization, the download route then gives them a presigned GET for the other organization's file. Storage keys of documents on public projects are in the /p/[slug] page payload (exposure-101), and those files are otherwise not downloadable by outsiders (the public page lists filenames only). Two organizations choosing the same key also overwrite each other by accident.

Regression test

  • Path: .security-audit/tests/auth-109.test.ts
  • Asserts: a member of org B asking for key org-A/contract.pdf never gets that key presigned or stored; any key that is presigned starts with org-B/.
  • Output today (fails):
FAIL auth-109.test.ts > auth-109 upload storage key > a member of org B asking for another organization's key never gets that key signed or stored
AssertionError: expected [ 'org-A/contract.pdf' ] to not include 'org-A/contract.pdf'

Chained with

  • chain-901
  • exposure-101

auth-109 · Authentication & authorization

highRemoved organization members keep access: the tenant key is trusted without a membership check (systematic: 7 locations)Failing testsrc/lib/session.ts:17

How to fix

Resolve the organization in one shared helper that confirms a member row for (session.user.id, activeOrganizationId) on every request (or auth.api.getActiveMember), and use it in requireOrg, orgProcedure, the Hono middleware and the four route handlers. Optionally, in Better Auth's organizationHooks.afterRemoveMember, clear activeOrganizationId on the removed user's sessions or revoke them.

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/lib/session.ts:17
  • Code:
export async function requireOrg() {
  const session = await requireUser();
  const orgId = session.session.activeOrganizationId;
  if (!orgId) redirect("/onboarding");
  return { session, orgId };
}
  • Same pattern, activeOrganizationId taken from the session row with no member lookup:
  1. src/lib/session.ts:17 (requireOrg: every server action and app page)
  2. src/server/trpc/init.ts:23 (orgProcedure: every tRPC procedure)
  3. src/server/api/index.ts:32 (Hono public API, session path)
  4. src/app/api/chat/route.ts:8
  5. src/app/api/uploads/route.ts:18
  6. src/app/api/documents/[id]/download/route.ts:11
  7. src/app/api/export/route.ts:11 (fallback when ?org= is absent; the ?org= part is auth-104)
  • Library behaviour, better-auth 1.6.27 organization plugin (installed copy under node_modules/.pnpm/better-auth@1.6.27*/node_modules/better-auth/dist):
  • Membership is checked only when the active organization is selected: plugins/organization/routes/crud-org.mjs:383 (checkMembership in set-active).
  • Removing a member clears activeOrganizationId only on the remover's own session when they remove themselves: plugins/organization/routes/crud-members.mjs:206 (if (session.user.id === toBeRemovedMember.userId && ...) setActiveOrganization(session.session.token, null)). The removed user's own sessions are not touched.
  • Sessions last 7 days by default and are extended on use: context/create-context.mjs:146-147 (updateAge 1 day, expiresIn 7 days), api/routes/session.mjs:206-207 (refresh when older than updateAge). src/lib/auth.ts sets neither.

Data flow

  • Source: the removed user's existing session cookie (any request to the entry points above)
  • Transformations: auth.api.getSession returns the session row, whose activeOrganizationId still names the old organization
  • Sink: every org-scoped query, read and write, that uses that id (for example src/server/trpc/routers/project.ts:9, src/app/api/export/route.ts:23, src/app/(app)/invoices/actions.ts:25)
  • Sanitization: none; no member row is consulted after selection
  • Verdict: VULNERABLE

Impact

A person removed from an organization (a former employee or contractor) keeps full member access to that organization's data from any session that had it active: invoices, customers including the CSV export, projects, documents and uploads, the assistant, and every member action such as deleting projects or marking invoices paid. Because Better Auth extends sessions on use, the access lasts until that session is signed out or goes unused for a week.

Regression test

  • Path: .security-audit/tests/auth-801.test.ts
  • Asserts: with a session whose activeOrganizationId is org A and no member row for that user (and auth.api.getActiveMember returning null), requireOrg() refuses, and tRPC project.list returns FORBIDDEN/UNAUTHORIZED without querying org A's projects.
  • Output today (both fail):
FAIL auth-801.test.ts > auth-801 membership behind activeOrganizationId > requireOrg refuses a session whose active organization the user is not a member of
AssertionError: expected 'allowed' to be 'refused'
FAIL auth-801.test.ts > auth-801 membership behind activeOrganizationId > tRPC orgProcedure refuses it too (project.list returns FORBIDDEN, org A's projects are not read)
AssertionError: expected [ { …(2) } ] to deeply equal []
+   "params": [ "org-A" ],
+   "sql": "select \"id\", \"org_id\", \"name\", ... from \"projects\" where \"projects\".\"org_id\" = $1 order by ..."

Chained with

  • auth-104 (same route; separate fix for the ?org= override)

auth-801 · Authentication & authorization

highPublic project page sends every project and document column to anonymous visitorsFailing testsrc/app/p/[slug]/page.tsx:7

How to fix

Select only displayed columns: columns: { name: true, description: true } and with: { documents: { columns: { id: true, filename: true } } }, and type the client component's props to that shape (or render the list in a server component). Keep ids out of public payloads unless needed.

Evidence

  • File: src/app/p/[slug]/page.tsx:7
  • Code:
  const project = await db.query.projects.findFirst({
    where: (p, { and, eq }) => and(eq(p.slug, slug), eq(p.isPublic, true)),
    with: { documents: true },
  });
  if (!project) notFound();
  return <PublicProjectView project={project} />;
  • src/components/public-project-view.tsx:1 is "use client". Props passed from a server component to a client component are serialized into the RSC payload embedded in the HTML response (React Server Components design; Next.js itself is not installed here, so this is from the framework documentation). The component renders only name, description and filenames (public-project-view.tsx:13-18) but is typed to receive the full rows (public-project-view.tsx:6-8).
  • Columns sent: projects id, orgId, internalNotes, budgetCents, clientContactEmail, createdBy, createdAt, isPublic (src/db/schema.ts:95-107); documents orgId, projectId, s3Key, contentType, uploadedBy, createdAt (src/db/schema.ts:154-163).
  • /p/[slug] is outside the proxy matcher (src/proxy.ts:15-22) and the page has no session check: public by design.

Data flow

  • Source: anonymous GET /p/<slug> (src/app/p/[slug]/page.tsx:5-6)
  • Transformations: relational query loads the full project row plus all document rows (page.tsx:7-10), no columns selection
  • Sink: props of the client component PublicProjectView (page.tsx:12), serialized into the page payload
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

Anyone, without an account, can read every column of a public project, including internal notes, budget, the client contact's email address, the organization id, the project id and the creator's user id, plus each attached document's storage key and uploader id, although the page displays only the name, description and filenames. Prerequisite (1): a member marked the project public, which is a normal product action. The organization ids, project ids and storage keys are exactly the identifiers several access-control findings need (see Chained With).

Regression test

.security-audit/tests/exposure-101.test.ts (run with --config ./tmp/vitest.jsx.config.mjs, the shared harness plus a JSX transform because tsconfig has jsx: preserve). It calls the page with a mocked db.query.projects.findFirst that honours columns like Drizzle would, and asserts the element handed to the client component carries only name, description, slug, documents[].id, documents[].filename. Fails today:

FAIL  exposure-101.test.ts > public project page (exposure-101) > passes the client component only displayed fields
AssertionError: expected [ 'id', 'orgId', 'isPublic', …(11) ] to deeply equal []
+   "id", "orgId", "isPublic", "internalNotes", "budgetCents", "clientContactEmail", "createdBy", "createdAt",
+   "documents[].orgId", "documents[].projectId", "documents[].s3Key", "documents[].contentType",
+   "documents[].uploadedBy", "documents[].createdAt"

Chained with

  • chain-901 (this finding is the enabler)
  • chain-902 (a project published through auth-106 shows its internal fields here)
  • auth-104 (organization id for the customer export)
  • auth-106 (project id for project.update)
  • auth-107 (organization id for the assistant's searchInvoices)
  • auth-109 (document storage keys)
  • auth-101 (organization id for forged subscription events; no separate chain, the effect stays display-only)
  • config-102 (framed click publishes a project; chain rejected in COMBINE, chain-902 reaches the same result without a click)

exposure-101 · Data exposure & secrets

hightestWebhook makes server-side requests to any URL and returns the response bodyFailing testsrc/server/trpc/routers/integration.ts:18

How to fix

Accept https: only; resolve the hostname and reject loopback, private, link-local, CGNAT and metadata ranges (re-check the resolved address at connect time to avoid DNS rebinding, for example with an undici dispatcher); set redirect: "manual" or re-validate every hop; return only the status code, not the body. Apply the same URL validation to integration.save before any sender uses stored URLs (non-injection-851).

Evidence

  • File: src/server/trpc/routers/integration.ts:18
  • Code:
  testWebhook: orgProcedure.input(z.object({ url: z.string().url() })).mutation(async ({ input }) => {
    const res = await fetch(input.url, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ type: "ledgerly.test", sentAt: new Date().toISOString() }),
      redirect: "follow",
      signal: AbortSignal.timeout(5000),
    });
    const text = await res.text();
    return { status: res.status, ok: res.ok, body: text.slice(0, 2000) };
  }),
  • orgProcedure (src/server/trpc/init.ts:22-26) only requires a session with an active organization; sign-up and organization creation are open (src/lib/auth.ts:12-15,39).

Data flow

  • Source: tRPC input url (integration.ts:18), any signed-in member of any organization
  • Transformations: z.string().url() checks syntax only; loopback and private hosts pass (confirmed by the test below)
  • Sink: server-side fetch (integration.ts:19) with redirect: "follow"; status and first 2000 characters of the body returned to the caller (integration.ts:26-27)
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

Any signed-in user (anyone can sign up and create an organization) can make the Ledgerly server send POST requests to addresses only it can reach, such as localhost services, the private network and the cloud provider's metadata service, and read the status and up to 2000 characters of each response. Following redirects means even an allowlist on the first URL would not be enough.

Regression test

.security-audit/tests/injection-101.test.ts calls integrationRouter.createCaller(ctx).testWebhook with a loopback URL and a stubbed global fetch, and asserts the call is rejected and fetch is never called. Fails today:

FAIL  injection-101.test.ts > integration.testWebhook (injection-101) > rejects a loopback URL before fetch is called
AssertionError: promise resolved "{ status: 200, ok: true, …(1) }" instead of rejecting
+   "body": "internal",
+   "ok": true,
+   "status": 200,

Chained with

  • rate-limit-101 (no per-user limit on this mutation either)

injection-101 · Injection & SSRF

highAny site a member visits learns the organization's private project ids, which project.update turns into full read and write of those projects and the customer listCode reading onlysrc/server/api/index.ts:15

How to fix

Fix config-101 (allowlist widget origins, no credentialed CORS for unknown origins, Vary: Origin) and auth-106 (scope the update by ctx.orgId, return only the columns the UI needs); either one breaks this chain. auth-104 and auth-107 need their own fixes regardless (see chain-901). Also filter /api/public/projects to what the widget actually needs.

Evidence

  • File: src/server/api/index.ts:15 (enabler, config-101)
  • Code:
api.use("*", cors({ origin: (origin) => origin, credentials: true, allowMethods: ["GET", "POST", "OPTIONS"] }));
...
api.get("/projects", async (c) => {
  const rows = await db
    .select({ id: projects.id, name: projects.name, slug: projects.slug })
    .from(projects)
    .where(eq(projects.orgId, c.get("orgId")));
  • The session path resolves the organization from the visitor's cookie (src/server/api/index.ts:31-34); cookies are SameSite=None on .ledgerly.app (src/lib/auth.ts:35-36). /api/public/projects lists every project of the organization, public or not (no isPublic filter, index.ts:54-59).
  • Consumer of those ids: src/server/trpc/routers/project.ts:24 updates by id alone and returns RETURNING *, which includes orgId, internalNotes, budgetCents, clientContactEmail (src/db/schema.ts:95-107) (auth-106).
  • Consumer of the returned orgId: src/app/api/export/route.ts:11 (auth-104); also src/server/ai/tools.ts:12 (auth-107).
  • The tRPC and export routes send no CORS headers, so the cross-site page cannot use them as the victim; it does not need to, because the ids work from the attacker's own self-registered account (src/lib/auth.ts:12-14,39).

Data flow

  • Source: a credentialed cross-site GET from an attacker-controlled page that a signed-in member of the victim organization opens (src/server/api/index.ts:54)
  • Transformations: the browser attaches the SameSite=None session cookie; hono cors echoes the page's origin with credentials allowed (index.ts:15-18), so the page reads the JSON; the ids are handed to the attacker's own session
  • Sink: UPDATE projects ... WHERE id = $1 RETURNING * (src/server/trpc/routers/project.ts:24), then the customers query bound to the returned organization id (src/app/api/export/route.ts:23)
  • Sanitization: no origin allowlist; no organization scope on project.update or the export
  • Verdict: VULNERABLE

Impact

One visit by any signed-in member of an organization to a page the attacker controls is enough for the attacker to read all of that organization's private projects (internal notes, budgets, client contact emails), change or publish them, and export its whole customer list with emails, phone numbers and tax ids. config-101 alone leaks only invoice totals and project names, and auth-106 alone reaches only projects whose ids leak elsewhere (public ones, via exposure-101); together they reach organizations that never published anything.

Rating: HIGH. Remote, needs only a free account plus one page visit by a victim member, impact is cross-organization read and write of confidential data. Not CRITICAL because it depends on victim interaction and on a browser that still sends third-party cookies (Chromium defaults do; Safari and Firefox block or partition them). Prerequisite count 0: no admin or configuration step is involved.

Regression test

proof: static. The links have failing tests (.security-audit/tests/config-101.test.ts, auth-106.test.ts, auth-104.test.ts); the browser cookie behaviour that joins step 1 to a real session cannot be exercised in this harness.

Chained with

  • config-101
  • auth-106
  • auth-104
  • auth-107
  • exposure-101

chain-902 · Chains

highsharp 0.34.5 (the Next image optimizer's decoder) has libvips and libheif advisoriesCode reading onlypnpm-lock.yaml:246

How to fix

Pin sharp to 0.35.4 or later with a pnpm override ("pnpm": { "overrides": { "sharp": ">=0.35.4" } }) or upgrade next and confirm the re-locked sharp version; narrow remotePatterns as in dependency-101.

Evidence

  • File: pnpm-lock.yaml:246
  • Code:
  next@16.3.0:
    optionalDependencies:
      sharp: 0.34.5
  sharp@0.34.5: {}          # pnpm-lock.yaml:266
  • osv-scanner (.security-audit/tools/osv.json), sharp 0.34.5:
GHSA-f88m-g3jw-g9cj  inherited libvips vulnerabilities (two rated High, CVSSv4); fixed in 0.35.0
GHSA-rgj7-g3m4-5g8c  libheif vulnerabilities, possible RCE on glibc-based Linux under certain conditions
                     (rated High by sharp because sharp has no network features); fixed in 0.35.4
  • The network path the sharp advisory discounts exists here: the Next image optimizer fetches images from any *.r2.dev host (next.config.ts:4-8, see dependency-101).
  • The local store has sharp@0.35.5, but a production install from the lockfile resolves 0.34.5.

Data flow

  • Source: remote image fetched by the image optimizer from a *.r2.dev host
  • Transformations: decoded by sharp (libvips, libheif) at runtime
  • Sink: native image decoding in the web server process
  • Sanitization: none in the app
  • Verdict: VULNERABLE under the same deployment condition as dependency-101 (Next's own optimizer runs in the app)

Impact

Per the advisory summaries, images processed by the bundled libvips/libheif can trigger the listed native-library flaws, up to possible code execution for libheif; anyone without an account can make the server process an image from a host they control. HIGH rather than CRITICAL because the libheif path is already counted in dependency-101 and the libvips issues are rated High upstream. Distinct from dependency-101 because the fix is the sharp version, which a next upgrade alone may not change.

Regression test

proof: static. Native-library flaws in a version that is not installed locally (store has 0.35.5); a test would need the lockfile version and a crafted image, which an audit test should not use.

Chained with

  • dependency-101

dependency-102 · Dependencies

highAnthropic API key is shipped to the browserCode reading onlysrc/lib/ai-client.ts:3

How to fix

Delete browserAnthropic and the NEXT_PUBLIC_ANTHROPIC_API_KEY variable; move the reminder suggestion into the authenticated /api/chat route or a server action that uses the server-only ANTHROPIC_API_KEY, behind a per-user limit. Revoke the key in the Anthropic console if it was ever set in any build.

Evidence

  • File: src/lib/ai-client.ts:3
  • Code:
export const browserAnthropic = createAnthropic({
  apiKey: process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY,
  headers: { "anthropic-dangerous-direct-browser-access": "true" },
});
  • Imported by the client component src/components/assistant-panel.tsx:1,6 and used at assistant-panel.tsx:14-17 (generateText runs in the browser and calls the provider directly with this key).
  • .env.example:5 lists NEXT_PUBLIC_ANTHROPIC_API_KEY as a variable to set (value not read), next to the server-side ANTHROPIC_API_KEY.
  • The assistant page is reachable by any signed-in member of an organization (src/app/(app)/assistant/page.tsx:5), and anyone can sign up and create an organization (src/lib/auth.ts:39).

Data flow

  • Source: build-time env var with the NEXT_PUBLIC_ prefix
  • Transformations: Next.js inlines NEXT_PUBLIC_* values into client bundles at build time (framework documentation; Next.js is not installed here)
  • Sink: the client JS chunk for the assistant panel, and the x-api-key header of every "Suggest reminder" request the browser sends to the provider
  • Sanitization: none
  • Verdict: VULNERABLE (if the variable is set at build)

Impact

Any signed-in user, and anyone can sign up, can read Ledgerly's Anthropic API key from the assistant's JavaScript or its outgoing requests and use it outside the app, at Ledgerly's expense and outside any rate limit, until it is revoked. Prerequisite (1): the variable is set in the production build; .env.example asks for it, but the production value is not verifiable here.

Regression test

proof: static. The exposure depends on Next.js build-time inlining (package not installed) and on a production env value the audit does not read, so no test in this harness can show it; the code path is unambiguous from src/lib/ai-client.ts:4 and src/components/assistant-panel.tsx:1,6,15.

Chained with

  • rate-limit-101 (both are model-usage abuse paths; a server-side limit does not help while the key is public)

exposure-102 · Data exposure & secrets

medium · 8

mediumStripe webhook accepts unsigned events and writes subscription statesrc/app/api/webhooks/stripe/route.ts:7

How to fix

Read the raw body with request.text() and call stripe.webhooks.constructEvent(body, request.headers.get("stripe-signature") ?? "", process.env.STRIPE_WEBHOOK_SECRET!) before any parsing; return 400 on failure. Validate metadata.plan against the keys of PRICES (or derive the plan from the subscription's price id).

Docs also claim the opposite: README.md:32 ("Stripe webhooks are verified before any state changes") and README.md:30 ("Every API route requires an authenticated session or an API key").

Evidence

  • File: src/app/api/webhooks/stripe/route.ts:7
  • Code:
export async function POST(request: Request) {
  const event = (await request.json()) as Stripe.Event;

  switch (event.type) {
    case "checkout.session.completed": {
      const checkout = event.data.object as Stripe.Checkout.Session;
      const orgId = checkout.metadata?.orgId;
      if (!orgId) break;
      const plan = checkout.metadata?.plan ?? "pro";
      await db.insert(subscriptions).values({ ... }).onConflictDoUpdate({ target: subscriptions.orgId, set: { plan, status: "active", stripeSubscriptionId: ... } });
    ...
    case "customer.subscription.deleted": { ... .set({ status: "canceled" }).where(eq(subscriptions.stripeSubscriptionId, sub.id)) }
  • STRIPE_WEBHOOK_SECRET is declared in .env.example but never read in src/ (grep STRIPE_WEBHOOK_SECRET, constructEvent, stripe-signature: no matches). The route is outside the proxy matcher (src/proxy.ts:15-22), which is correct for a webhook, so the signature is the only possible control.
  • Plan is read for display only: src/app/(app)/settings/billing/page.tsx:14 and counted in src/app/api/admin/stats/route.ts:15. Verified by grep: no code gates a feature, limit or access on subscriptions.plan or subscriptions.status.

Data flow

  • Source: unauthenticated POST body (src/app/api/webhooks/stripe/route.ts:7)
  • Transformations: cast to Stripe.Event; metadata.orgId and metadata.plan used as-is (route.ts:12,14)
  • Sink: upsert into subscriptions keyed by org_id (route.ts:15-28); update by stripe_subscription_id (route.ts:33-36)
  • Sanitization: none, no signature check
  • Verdict: VULNERABLE

Impact

Anyone on the internet, without an account, can make the app record an active subscription with any plan name for any organization whose id they know, overwrite a paying organization's stored Stripe subscription id (so Stripe's real cancellation event no longer matches the row), or mark a stored subscription canceled if they know its Stripe id. Today the stored plan and status are only displayed and counted, so the effect is corrupted billing records, not free features; any plan gating added later inherits the bypass.

Rating: unauthenticated, but the only effect today is integrity of display-only billing data, so MEDIUM rather than the proposed HIGH. Organization ids are needed and are readable on public project pages (exposure-101).

Regression test

  • Path: .security-audit/tests/auth-101.test.ts
  • Asserts: a POST with a checkout.session.completed body and no Stripe signature gets 400 and no SQL statement is issued.
  • Output today (fails):
FAIL auth-101.test.ts > auth-101 stripe webhook > rejects an event without a valid Stripe signature and leaves subscriptions untouched
AssertionError: expected [ { …(2) } ] to deeply equal []
+   { "params": [ "<uuid>", "org-victim", "cus_x", "sub_x", "team", "active", "sub_x", "team", "active", "<date>" ],
+     "sql": "insert into \"subscriptions\" ... on conflict (\"org_id\") do update set ..." }

Chained with

  • exposure-101 (organization ids are readable on public project pages)

auth-101 · Authentication & authorization

mediumDashboard usage cache key does not include the organizationsrc/server/queries/dashboard.ts:22

How to fix

Define the cached function once at module scope taking (orgId, sinceIso) as arguments, as getOrgStats does, or at least add orgId and the month to keyParts.

Docs also claim the opposite: README.md:31 ("Tenant isolation: all queries are scoped to the active organization").

Evidence

  • File: src/server/queries/dashboard.ts:22
  • Code:
export async function getUsageThisMonth(orgId: string) {
  const since = startOfMonth(new Date());
  const load = unstable_cache(
    async () =>
      db.select({ kind: usageEvents.kind, units: sum(usageEvents.units) })
        .from(usageEvents)
        .where(and(eq(usageEvents.orgId, orgId), gte(usageEvents.createdAt, since)))
        .groupBy(usageEvents.kind),
    ["usage-month"],
    { revalidate: 600 },
  );
  return load();
}
  • Contrast getOrgStats, which takes orgId as an argument (src/server/queries/dashboard.ts:8, non-auth-108).
  • Source of the cache semantics: Next.js documentation for unstable_cache ("unstable_cache already uses the arguments and the stringified version of your function as the cache key", plus keyParts). Closure values such as orgId and since are not part of the key. The next package is not installed in this checkout (not-assessed.md), so this is from documentation, not from the Next.js source or a running app.

Data flow

  • Source: orgId from the session (src/app/(app)/dashboard/page.tsx:6-7)
  • Transformations: captured in a closure, not passed as an argument
  • Sink: one shared cache entry for usage-month with no arguments (dashboard.ts:22-32), rendered on the dashboard (dashboard/page.tsx:20-24)
  • Sanitization: none
  • Verdict: VULNERABLE

Impact

Members of one organization are shown another organization's usage for the month (event kinds and unit totals) on their dashboard: whichever organization loads the dashboard first in each 10-minute window fills the shared entry for everyone. No attacker action is needed; the data is low-sensitivity aggregate usage, hence MEDIUM.

Regression test

  • Path: .security-audit/tests/auth-111.test.ts (runs against the harness stub tests/stubs/next-cache.ts, which models the documented key: function source + keyParts + arguments)
  • Asserts: after org A loads its usage, a call for org B does not return org A's rows.
  • Output today (fails):
FAIL auth-111.test.ts > auth-111 getUsageThisMonth cache > org B never receives the usage cached for org A
AssertionError: expected [ 'kind-of-org-A' ] to not include 'kind-of-org-A'

Chained with

  • none

auth-111 · Authentication & authorization

mediumPublic API grants credentialed CORS access to any Origin while session cookies are SameSite=Nonesrc/server/api/index.ts:15

How to fix

Return the origin only when it is on an allowlist (per-organization registered widget origins, stored server-side), otherwise return null; add Vary: Origin to every response. Prefer a narrow, read-only widget token over the full session cookie, and set the session cookie back to SameSite=Lax once the widget no longer needs it.

Evidence

  • File: src/server/api/index.ts:15
  • Code:
api.use(
  "*",
  cors({
    origin: (origin) => origin,
    credentials: true,
    allowMethods: ["GET", "POST", "OPTIONS"],
  }),
);
...
  const session = await auth.api.getSession({ headers: c.req.raw.headers });
  const orgId = session?.session.activeOrganizationId;
  • src/lib/auth.ts:35-36: crossSubDomainCookies: { enabled: true, domain: ".ledgerly.app" }, defaultCookieAttributes: { sameSite: "none", secure: true }
  • hono 4.12.25 dist/middleware/cors/index.js: a function origin option is used as-is (return optsOrigin), so whatever the function returns becomes Access-Control-Allow-Origin; Access-Control-Allow-Credentials: true is set on every response; Vary: Origin is set only on OPTIONS.
  • README.md:23-25 says the widget uses the visitor's session cross-site by design. Cross-site cookies are therefore intended; the defect is that every origin, not only the sites embedding the widget, is allowed to read the responses.

Data flow

  • Source: a credentialed cross-site GET from any web page the signed-in user visits (the Origin header is the page's origin)
  • Transformations: browser attaches the SameSite=None session cookie (if it sends third-party cookies); hono cors echoes the Origin and sets Access-Control-Allow-Credentials: true (index.ts:16-17); auth middleware resolves orgId from that session (index.ts:31-34)
  • Sink: JSON bodies of GET /api/public/invoices (index.ts:38-51: number, amountCents, currency, status, dueDate, latest 100) and GET /api/public/projects (index.ts:54-59: id, name, slug), readable by the calling page because of the echoed origin
  • Sanitization: none; no origin allowlist. The two GET routes need no preflight (simple requests).
  • Verdict: VULNERABLE

Impact

Any website that a signed-in Ledgerly user visits can read, in the background, that user's active organization's latest 100 invoices (number, amount, currency, status, due date) and all its project ids, names and slugs through /api/public. Rated MEDIUM, not HIGH: it needs the victim to be signed in and to open the other site in a browser that still sends third-party cookies, and the two routes return a narrow column set without customer names. The leaked project ids are what auth-106 needs to modify that organization's projects (see chain-902), which is where the larger impact lies.

Regression test

.security-audit/tests/config-101.test.ts runs the Hono app in-process (api.request, db and auth mocked) and asserts that a request carrying Origin: https://unrelated-site.example gets no Access-Control-Allow-Origin for that origin, on a credentialed GET to /api/public/projects and on a preflight to /api/public/invoices. Both fail today:

FAIL  config-101.test.ts > public API CORS (config-101) > does not allow a disallowed origin to read a credentialed GET
AssertionError: expected 'https://unrelated-site.example' not to be 'https://unrelated-site.example'
FAIL  config-101.test.ts > public API CORS (config-101) > does not approve a preflight from a disallowed origin
AssertionError: expected 'https://unrelated-site.example' not to be 'https://unrelated-site.example'

Chained with

  • chain-902
  • auth-106 (project ids of the victim's organization, including non-public projects, are what project.update needs)
  • exposure-101

config-101 · Headers, CORS & configuration

mediumUpload accepts a projectId from another organizationsrc/app/api/uploads/route.ts:32

How to fix

Before insert, confirm the project exists with orgId = session org. On the public page, also filter documents by documents.orgId = project.orgId.

Evidence

  • File: src/app/api/uploads/route.ts:32
  • Code:
  await db.insert(documents).values({
    id: crypto.randomUUID(),
    orgId,
    projectId: input.projectId,
    s3Key: input.key,
    filename: input.filename,
  • projectId comes from the body (route.ts:10) and the project's organization is never checked.
  • The public page loads documents through the relation by projectId only: src/app/p/[slug]/page.tsx:9 with: { documents: true } (relation src/db/schema.ts:211-218) and lists every filename (src/components/public-project-view.tsx:17-19).

Data flow

  • Source: projectId and filename (max 200 chars) in the body of POST /api/uploads (uploads/route.ts:10-11)
  • Transformations: none
  • Sink: documents.projectId (route.ts:32), then the public page relation (p/[slug]/page.tsx:9) renders filename
  • Sanitization: React escapes the text; project ownership is not checked
  • Verdict: VULNERABLE

Impact

A signed-in user can attach document records to another organization's project. If that project is public, each attached filename (arbitrary text up to 200 characters, as many entries as they like) appears in the "Shared files" list on the owner's public page, which lets an outsider put misleading text on another company's public page. Rendering is escaped and filenames are not links, so the effect is content injection only. Prerequisite (1): the owning organization made the project public; its id is then in the page payload (exposure-101).

Chained with

  • auth-109 (same route; separate fix)
  • exposure-101

auth-110 · Authentication & authorization

mediumhono 4.12.25 CORS middleware ReDoS advisory, reachable without authpnpm-lock.yaml:147

How to fix

Upgrade hono to 4.12.34 or later (latest 4.13.x also clears the other listed advisories); as an immediate mitigation set an explicit allowHeaders list in the cors options, which skips the vulnerable parsing.

Evidence

  • File: pnpm-lock.yaml:147
  • Code:
  hono@4.12.25:          # package.json "hono": "4.12.25" (exact pin)
  osv: GHSA-8j4g-w8fx-2239  ReDoS in CORS middleware via Access-Control-Request-Headers
       affected <4.12.34; applies when allowHeaders is not configured (the default)
  • Installed hono 4.12.25, dist/middleware/cors/index.js:57-61: on OPTIONS, when opts.allowHeaders is empty, the request's Access-Control-Request-Headers value is split with a whitespace-tolerant regular expression.
  • src/server/api/index.ts:13-20 configures cors without allowHeaders, on *, before the auth middleware (index.ts:22), so preflights need no credentials.
  • The other hono advisories in osv.json concern features this app does not use (language middleware, proxy helper, JSX/memo/cx, toSSG, parseBody, API Gateway adapter, query-parser cache keys); src/ imports only hono, hono/cors and hono/vercel (grep).

Data flow

  • Source: unauthenticated OPTIONS request header to /api/public/*
  • Transformations: hono cors middleware (no allowHeaders)
  • Sink: regular-expression split with quadratic running time on long whitespace runs (per advisory)
  • Sanitization: only the server's maximum header size
  • Verdict: VULNERABLE

Impact

Per the advisory, anyone can send preflight requests to /api/public that each consume seconds of server CPU, making the API (and, on a single Node process, the whole app) slow or unresponsive for everyone. MEDIUM: availability only, no data access.

Chained with

  • none

dependency-103 · Dependencies

mediumStripe key and a second API secret committed in git history./.env:4

How to fix

Treat both as leaked: roll the Stripe key (Stripe Dashboard, Developers, API keys) and rotate the secret at .env:3 (if it is BETTER_AUTH_SECRET, rotating signs everyone out). Rewrite history (for example git filter-repo --path .env --invert-paths) before the repository is pushed anywhere shared, and add a pre-commit secret scan.

Evidence

  • File: ./.env:4 (history only, commit be4989f; ./.env:3 likewise)
  • Code:
gitleaks via prepass.md (values redacted; .env not read by the verifier):
stripe-access-token  .env:4  commit be4989f  2026-05-04  file still present: no (history only)
generic-api-key      .env:3  commit be4989f  2026-05-04  file still present: no (history only)
  • .env is listed in .gitignore:3 and is no longer tracked (current tree, git ls-files); per prepass.md the file remains in commit be4989f (the verifier did not open that commit).
  • git remote lists no remotes (verified), so the history is not known to be on any shared host.
  • Correction to the raw finding: the variable at .env:3 is not identifiable without reading the secret. generic-api-key is a generic rule; that it is BETTER_AUTH_SECRET is an assumption (.env is not laid out like .env.example, whose line 4 is not a Stripe variable, so line numbers cannot be mapped to names).

Data flow

  • Source: commit be4989f
  • Transformations: none
  • Sink: every copy of the repository history (clones, backups, any future push)
  • Sanitization: none
  • Verdict: VULNERABLE (liveness unknown)

Impact

Anyone who holds a copy of this repository's history holds a Stripe API key and a second API secret. If the Stripe key is a live secret key, it gives API access to Ledgerly's Stripe account (customers, charges, refunds). Whether either value is live or already rotated is unknown and stays unknown (not-assessed.md). MEDIUM because the audience is currently limited to whoever has the repository (no remote configured) and liveness is unconfirmed.

Chained with

  • none

exposure-103 · Data exposure & secrets

mediumUser-controlled text is inserted unescaped into email HTML (systematic: 2 locations, 1 with an in-app writer)src/lib/auth.ts:23

How to fix

Escape every interpolated value in both templates (a small escapeHtml helper, or React Email components which escape by default), and cap the sign-up name length and characters in a Better Auth before hook.

Evidence

  • File: src/lib/auth.ts:23
  • Code:
    sendVerificationEmail: async ({ user, url }) => {
      await sendEmail({
        to: user.email,
        subject: "Verify your Ledgerly account",
        html: `<p>Hi ${user.name},</p><p><a href="${url}">Verify your email</a></p>`,
  • Better Auth 1.6.27 accepts any string as the sign-up name (better-auth/dist/api/routes/sign-up.mjs:15: name: z.string()); sendOnSignUp: true (auth.ts:18) mails the address given at sign-up.
  • File: src/server/jobs/digest.ts:34
    .map((i) => `<tr><td>${i.number}</td><td>${i.customer}</td><td>${formatMoney(i.amountCents)}</td><td>${formatDate(i.dueDate)}</td></tr>`)
  ...
      html: `<p>Hi ${r.name},</p><table>${rows}</table>`,
  • No code in src/ writes customers or invoices rows (grep for inserts finds only projects and documents), so the writer of i.customer and i.number is outside this repository.

Data flow

  • Source: sign-up name (src/components/sign-up-form.tsx:13, or a direct call to /api/auth/sign-up/email); customer names and invoice numbers from an unknown writer
  • Transformations: none
  • Sink: sendEmail HTML body (src/lib/email.ts:10) sent from notifications@ledgerly.app
  • Sanitization: none
  • Verdict: VULNERABLE (verification email); PARTIAL (digest: sink confirmed, in-app source not found)

Impact

Anyone can sign up with HTML in the name field and an address that is not yet registered, and Ledgerly sends a genuine, domain-authenticated verification email to that address containing their markup (links, styled text), which makes convincing phishing from Ledgerly's own sender. Mail clients do not run scripts, so the effect is content injection, not code execution. The digest template has the same flaw; with auth-108 a customer name with markup would reach every platform user, but no in-app path writes customer names today.

Chained with

  • auth-108 (the digest goes to every user on the platform; chain rejected in COMBINE until something writes customer names or invoice numbers)

injection-102 · Injection & SSRF

mediumAssistant endpoint has no per-user rate limit or usage capsrc/app/api/chat/route.ts:13

How to fix

Per-user and per-organization limits (for example a token bucket in Postgres or Upstash) on /api/chat and integration.testWebhook; cap the number and size of messages; record usage in usage_events.

Evidence

  • File: src/app/api/chat/route.ts:13
  • Code:
  const { messages }: { messages: UIMessage[] } = await request.json();

  const result = streamText({
    model: anthropic("claude-sonnet-4-5"),
    system: `You are Ledgerly's billing assistant. ...`,
    messages: convertToModelMessages(messages),
    tools: buildTools({ orgId, userId: session.user.id }),
    stopWhen: stepCountIs(5),
  });
  • Better Auth's limiter (src/lib/auth.ts:33) applies only to the routes Better Auth serves under /api/auth/* (src/app/api/auth/[...all]/route.ts:4). No limiter or usage counter exists in src/app/api/chat/route.ts; usage_events is never written in src/ (grep).
  • messages is taken whole from the client with no length or size check (route.ts:11); serverActions.bodySizeLimit in next.config.ts applies to server actions, not route handlers.
  • EXPAND: same gap on integration.testWebhook (src/server/trpc/routers/integration.ts:18, see injection-101) and POST /api/uploads (src/app/api/uploads/route.ts:16); the cost impact is specific to /api/chat.

Data flow

  • Source: POST /api/chat by any signed-in user with an active organization (route.ts:7-9)
  • Transformations: none
  • Sink: Anthropic API call, up to 5 model steps per request (route.ts:13-19)
  • Sanitization: none; history size unbounded
  • Verdict: VULNERABLE

Impact

Any signed-in user, and anyone can sign up and create an organization, can drive an unlimited number of model calls billed to Ledgerly, each up to five model steps over a client-supplied message history of any length, which raises cost and can exhaust the provider rate limit shared by all customers.

Chained with

  • injection-101 (testWebhook is unlimited too)
  • exposure-102 (a browser-shipped Anthropic key bypasses any server-side limit)

rate-limit-101 · Rate limiting & abuse

low · 3

lowPost-login redirect check can be bypassed to leave the sitesrc/components/login-form.tsx:19

How to fix

Parse instead of prefix-checking: const u = new URL(next, window.location.origin); if (u.origin === window.location.origin) router.push(u.pathname + u.search + u.hash); else router.push("/dashboard").

Evidence

  • File: src/components/login-form.tsx:19
  • Code:
    const next = params.get("next");
    router.push(next && next.startsWith("/") && !next.startsWith("//") ? next : "/dashboard");

Data flow

  • Source: ?next= on /login (login-form.tsx:18)
  • Transformations: string prefix check only
  • Sink: router.push after a successful sign-in (login-form.tsx:19)
  • Sanitization: the prefix check; browsers' URL parsing treats some characters after the first slash as starting a host, which a prefix check does not cover (confirmed by the test below)
  • Verdict: VULNERABLE

Impact

A link to the Ledgerly login page can send a user to an outside site right after they sign in, which makes a phishing page look like the next step of the Ledgerly login. That router.push performs a full navigation for a cross-origin URL is taken from Next.js behaviour as documented (package not installed here). LOW: needs a crafted link and a user who signs in through it; no data is exposed by the redirect itself.

Regression test

.security-audit/tests/injection-103.test.ts (pure URL parsing). It asserts that every next value the login form's check accepts resolves, via new URL(next, origin), to the app's own origin, using one representative value; a second test pins the mirrored check to the source line. Fails today:

FAIL  injection-103.test.ts > post-login redirect check (injection-103) > only accepts values that stay on the app origin
AssertionError: expected 'https://outside.example' to be 'https://app.ledgerly.test'

Chained with

  • none

injection-103 · Injection & SSRF

lowNo security headers (frame protection, CSP, HSTS)next.config.ts:3

How to fix

Add headers() in next.config.ts with Content-Security-Policy: frame-ancestors 'none' (or X-Frame-Options: DENY), X-Content-Type-Options: nosniff, Strict-Transport-Security, Referrer-Policy: strict-origin-when-cross-origin, then a CSP. Confirm what the hosting edge already sends.

Evidence

  • File: next.config.ts:3
  • Code:
const config: NextConfig = {
  images: { remotePatterns: [ ... ] },
  experimental: { serverActions: { bodySizeLimit: "2mb" } },
};
  • No headers() in next.config.ts; src/proxy.ts:4-12 sets no headers and matches only app pages; src/app/layout.tsx sets only metadata. No other header source in the repo (grep).
  • Session cookies are SameSite=None (src/lib/auth.ts:36), so a framed Ledgerly page is rendered signed in.

Data flow

  • Source: any page response
  • Transformations: none
  • Sink: browser (frame embedding allowed, no CSP, no HSTS)
  • Sanitization: none in the repo; an edge/CDN may add headers (not-assessed.md, deployment unknown)
  • Verdict: PARTIAL

Impact

Any website can frame signed-in Ledgerly pages, so a user can be tricked into a single click inside the frame, for example the "Public page" checkbox on the projects list (src/components/project-list.tsx:17-21), which publishes a project and, with exposure-101, exposes its internal fields. There is also no CSP to contain a future XSS. LOW because it needs user interaction and the hosting edge may already set these headers.

Chained with

  • exposure-101 (a framed click on the public toggle publishes a project)

config-102 · Headers, CORS & configuration

lowPresigned uploads have no content-type allowlist or size limitsrc/app/api/uploads/route.ts:25

How to fix

Allowlist content types; switch to a presigned POST with a content-length-range condition (or check HeadObject size after upload and delete oversized objects); add a per-organization storage quota.

Evidence

  • File: src/app/api/uploads/route.ts:25
  • Code:
const uploadInput = z.object({
  projectId: z.string().min(1),
  filename: z.string().min(1).max(200),
  contentType: z.string().min(1),
  key: z.string().min(1),
});
...
    new PutObjectCommand({ Bucket: BUCKET, Key: input.key, ContentType: input.contentType }),
    { expiresIn: 900 },
  • No ContentLength in the signed command and no per-user or per-organization quota; each call to the route returns a new 15-minute URL.
  • Downloads force attachment disposition (src/app/api/documents/[id]/download/route.ts:27), so stored files are not rendered on the app origin (non-upload-101). Whether the bucket is also publicly readable through an r2.dev host is unknown (not-assessed.md).

Data flow

  • Source: contentType and object size chosen by the client (route.ts:12, 21)
  • Transformations: none
  • Sink: presigned PUT URL (route.ts:23-27)
  • Sanitization: authentication and an active organization only (route.ts:17-19)
  • Verdict: PARTIAL

Impact

Any signed-in user can store files of any type and any size in the documents bucket, as many as they like, which costs Ledgerly storage and lets the bucket hold arbitrary content. Files are served as downloads, not rendered in the app. LOW because the effect is cost and content hygiene, not data access.

Chained with

  • auth-109 (the same signed URL also lets the client choose the object key)

upload-101 · File upload & storage

Verified safe

Areas the audit examined and found protected, each with the control that protects it.

Authentication & authorization 11
  • tRPC procedures invoice.list, invoice.byId, project.list, integration.list, integration.save: tenant scope.Each runs under orgProcedure, which takes orgId from the server session (init.ts:23-25), and each query filters by ctx.orgId; integration.save writes orgId: ctx.orgId and zod strips any client orgId. · src/server/trpc/routers/invoice.ts:26
  • Server actions markInvoicePaid, getProject, createProject, deleteProject, startCheckout: authentication and tenant scope.Each calls requireOrg() first (session-derived orgId) and filters or writes with it; createProject spreads only zod-parsed fields (name, slug, isPublic) after orgId, so the client cannot override it; startCheckout validates the plan with z.enum and puts the session orgId in metadata. · src/app/(app)/invoices/actions.ts:25
  • Document download by id: object-level authorization on the documents row.The row lookup requires both the id and the session's organization, and the presigned GET lives 60 seconds with attachment disposition. (The key stored in the row is a separate issue: auth-109.) · src/app/api/documents/[id]/download/route.ts:18
  • Hono public API routes /api/public/invoices and /api/public/projects: authentication and scope (CORS handled in config-101).A middleware requires either a valid API key or a session with an active organization and sets orgId from that source only; both routes filter by it and return a narrow column set. · src/server/api/index.ts:48
  • Cross-site request forgery against tRPC mutations given SameSite=None session cookies.tRPC 11.8.0's fetch adapter only accepts POST bodies with content-type application/json, multipart/form-data or application/octet-stream and rejects others with 415. A cross-site form can send only multipart/form-data, which reaches the procedure as a FormData object; every mutation here declares a z.object input wit · server@11.8.0_typescript@5.9.2/node_modules/@trpc/server/dist/resolveResponse-D7zvnoIM.mjs:211
  • Resend webhook authenticity.The raw body is verified with svix against RESEND_WEBHOOK_SECRET before any parsing or database write; failures return 400. · src/app/api/webhooks/resend/route.ts:14
  • Assistant tool summarizeProject and chat route authentication.The chat route requires a session with an active organization; summarizeProject filters by the server-side ctx.orgId, not a model argument. · src/server/ai/tools.ts:46
  • Dashboard getOrgStats cache key.orgId is a call argument of the cached function, and Next.js includes call arguments in the unstable_cache key, so entries are per organization (contrast auth-111). · src/server/queries/dashboard.ts:8
  • Better Auth base configuration: password policy, email verification, auth rate limiting, trusted origins.Email verification is required before sign-in, minimum password length is 10, the built-in limiter is enabled for auth endpoints, and only APP_URL is a trusted origin. Password hashing and session token generation are Better Auth defaults (library, not audited line by line: not-assessed.md). · src/lib/auth.ts:14
  • Mass assignment on tRPC project.update (EXPAND from auth-106): can a caller move a project to another organization or set columns outside the patch?The input is a zod object with five named keys; zod objects strip unknown keys by default, so orgId, createdBy, budgetCents, clientContactEmail or slug in the request never reach .set(patch). The ownership gap on the WHERE clause is auth-106; the SET clause is limited to the listed fields. · src/server/trpc/routers/project.ts:14
  • Other admin entry points and path prefixes reaching admin data (EXPAND from auth-102).The only admin page calls requireAdmin() before rendering, and the only admin data handler is /api/admin/stats (auth-102). No other route, action, tRPC procedure or Hono route reads platform-wide user data (prepass entry points 1-45; grep requireAdmin and from(user) outside auth, digest and admin stats). · src/app/admin/page.tsx:5
Injection & SSRF 5
  • SQL injection across all queries.Every query uses the Drizzle query builder with bound parameters; there is no sql template, sql.raw or .execute( in src/ (grep). The only pattern match (ilike) binds the user string as a parameter. · src/server/ai/tools.ts:31
  • Exchange-rate fetch (outbound request built from input).The host is fixed and the only variable is checked against a four-value allowlist first. (The function also has no caller in src/.) · src/server/services/rates.ts:5
  • Cross-site scripting in rendered pages (invoice notes, project descriptions, assistant output, admin list).All output goes through React's escaping; there is no dangerouslySetInnerHTML or innerHTML in src/ (grep), and assistant parts are rendered as text. · src/components/assistant-panel.tsx:26
  • EXPAND from injection-101: stored integration webhook URLs (integration.save) as a second outbound-request sink.Stored webhookUrl values are never fetched: the column is written by integration.save and read back only by integration.list for the same organization. No job, route or service sends to it (grep for webhookUrl and fetch( in src/). The validation is as weak as testWebhook's (z.string().url()), so it must b · src/server/trpc/routers/integration.ts:14
  • EXPAND from injection-103 (open redirect sibling): links in emails and auth redirects built from the request's Host header.Better Auth builds verification and callback URLs from the fixed baseURL (APP_URL) and only trusts APP_URL as an origin, so a forged Host header cannot change the link in an email. The proxy's login redirect is built from the incoming request URL, which only affects the response to that same request. · src/lib/auth.ts:10
Data exposure & secrets 3
  • Secret files in the working tree and server-only boundaries..env is ignored and no longer tracked (history is exposure-103); session and dashboard query modules import server-only; Stripe, S3 and Resend clients read non-public env vars only in server code. · src/lib/session.ts:1
  • EXPAND from exposure-101: other server-to-client component boundaries that could serialize full database rows to the browser.The only other client components fed from server components get an id or nothing: the invoices list passes only id to InvoiceQuickView; InvoiceDetail is a server component (no "use client"), so the full invoice row it receives is rendered on the server and only displayed text is sent; ProjectList and `AdminSt · src/app/(app)/invoices/page.tsx:35
  • EXPAND from exposure-102 and exposure-103: other NEXT_PUBLIC_ variables shipped to the browser and hardcoded credentials in source and config.The only other public variables are the PostHog project key and host, which PostHog designs to be public (ingest-only key). A grep of src/, next.config.ts and drizzle.config.ts for key, secret, password and bearer literals finds none; all server credentials are read from non-public env vars in server modules. · src/lib/analytics.ts:7
Concurrency & races 1
  • Double-submit and race conditions: subscription writes, invoice payment marking, project creation.Subscription writes are an upsert on a unique org_id, so replays converge to one row; marking an invoice paid is idempotent; project slugs have a unique index. No balance, counter or quota is read-then-written. · src/app/api/webhooks/stripe/route.ts:25
Headers, CORS & configuration 1
  • EXPAND from config-101: permissive CORS on the other API surfaces (tRPC, Better Auth, chat, export, uploads, download).Only the Hono app installs a CORS middleware. The tRPC route and the other route handlers set no Access-Control-Allow-* headers, so browsers block cross-site reads of their responses even though cookies are SameSite=None (cross-site writes are covered by non-auth-105). Better Auth only trusts APP_URL as an origin. · src/app/api/trpc/[trpc]/route.ts:5
Cryptography 1
  • API key verification (README claim 5).Keys need the lk_ prefix and at least 40 characters; the lookup uses a non-secret 12-character prefix, and the full key's SHA-256 is compared with timingSafeEqual after a length check. SHA-256 without salt is appropriate for high-entropy random keys (not passwords). · src/server/api/keys.ts:15
File upload & storage 1
  • Stored-XSS through uploaded files served back to users.Files are never served from the app origin: downloads redirect to a 60-second presigned R2 URL with Content-Disposition: attachment and an encoded filename. · src/app/api/documents/[id]/download/route.ts:27

Not assessed

Nobody checked these. They are unknown, not safe.

  • Runtime inspection of Next.js 16.3.0 internals (unstable_cache keying, image optimizer, server action origin check)`next` package files are missing from node_modules/.pnpm; behaviour taken from Next.js documentation, not source · dependency
  • Production environment values (whether NEXT_PUBLIC_ANTHROPIC_API_KEY is set, which Stripe key mode is live)Audit does not read .env or production config · config
  • Whether the two secrets in git history (commit be4989f) are live or already rotatedValues are redacted by design; only the Stripe and Better Auth dashboards can tell · exposure
  • Deployment platform and edge configuration (security headers set by a CDN/proxy, Vercel image optimization vs self-hosted)No deployment config in the repo · config
  • Cloudflare R2 bucket policy and public r2.dev access for ledgerly-documentsInfrastructure outside the repo · config
  • Better Auth organization plugin internals (membership check on setActiveOrganization, invitation flow)Library code trusted, not audited line by line · auth
  • Project test suite in its installed state`pnpm test` fails on module resolution (incomplete node_modules); results come from the audit harness instead · test-gap

Hotspots

Where the audit started: entry points and configuration ranked by risk signals. A ranking, not a verdict.

#ScoreWhereWhy
113src/app/api/webhooks/stripe/route.ts:6
webhook POST
payments area, webhooks area; webhook: public by design; no signature verification seen; unscoped query on subscriptions
210src/app/(app)/invoices/actions.ts:10
server-action getInvoice
payments area; server-action: callable directly as a POST; no auth check in the handler; unscoped query on invoices, invoiceLines
310src/app/api/admin/stats/route.ts:5
route-handler GET
admin area; no auth check in the handler; unscoped query on projects, subscriptions
410src/lib/auth.ts:1
config auth.ts
auth configuration (betterAuth); additionalFields.role is writable at sign-up (no input: false); SameSite=None session cookies
59src/server/ai/tools.ts:9
ai-tool searchInvoices
payments area, ai area; ai-tool: arguments chosen by the model; tool schema lets the model choose the tenant/user
67src/server/trpc/routers/integration.ts:18
trpc integrationRouter.testWebhook
webhooks area; outbound request to a non-constant URL (SSRF)
76src/app/api/export/route.ts:6
route-handler GET
files area; tenant/user id taken from the request
86src/app/p/[slug]/page.tsx:1
page page
page without a guard reads the database (what reaches the client?); unscoped query on projects
96src/server/api/index.ts:1
config index.ts
CORS reflects any origin with credentials
106src/server/trpc/routers/project.ts:12
trpc projectRouter.update
unscoped query on projects; request object written to the database as-is
115src/app/api/documents/[id]/download/route.ts:9
route-handler GET
files area; presigned storage URL
125src/app/api/uploads/route.ts:16
route-handler POST
files area; presigned storage URL
135src/app/api/webhooks/resend/route.ts:8
webhook POST
webhooks area; webhook: public by design
145src/lib/ai-client.ts:1
code ai-client.ts
NEXT_PUBLIC_ANTHROPIC_API_KEY looks like a secret and is shipped to the browser
155src/server/queries/dashboard.ts:1
code dashboard.ts
unstable_cache over a zero-argument function at line 22: cache key may be shared across users/tenants
164src/app/(app)/invoices/actions.ts:19
server-action markInvoicePaid
payments area; server-action: callable directly as a POST
174src/app/(app)/settings/billing/actions.ts:10
server-action startCheckout
payments area; server-action: callable directly as a POST
184src/app/api/auth/[...all]/route.ts:4
route-handler GET, POST
auth area; dispatcher: the routes it mounts are ranked separately
194src/server/ai/tools.ts:39
ai-tool summarizeProject
ai area; ai-tool: arguments chosen by the model
204src/server/jobs/worker.ts:20
job overdue-digest
jobs area; job: trusts its payload; sends email (who are the recipients?); handler: src/server/jobs/digest.ts:10

Dependencies

osv-scanner (docker): 5 vulnerable packages

PackageVersionScopeCVSSFixed inAdvisories
next16.3.0prod (direct)9.515.5.24, 16.3.3, 16.3.6GHSA-2xp9-vwfh-vxw4, GHSA-p293-qw3h-jr36, GHSA-vcvr-r3jv-pc5j
sharp0.34.5unknown8.90.35.0, 0.35.4GHSA-f88m-g3jw-g9cj, GHSA-rgj7-g3m4-5g8c
postcss8.4.31unknown7.58.5.12, 8.5.23, 8.5.10, 8.5.18GHSA-6g55-p6wh-862q, GHSA-fxqj-rqcc-2cmp, GHSA-qx2v-qp2m-jg93, GHSA-r28c-9q8g-f849
hono4.12.25prod (direct)6.54.12.34, 4.13.5, 4.12.27, 4.13.7GHSA-54fx-42gc-7vw4, GHSA-79qm-7rj5-m7r9, GHSA-8j4g-w8fx-2239, GHSA-crvj-82cr-hjcx +7
vitest4.1.8dev (direct)5.94.1.11, 5.0.0-rc.2GHSA-82fw-gwwq-j7x9

Secrets

gitleaks (docker): 2 hits, 2 commits of this repo. Values are redacted; anything real that was ever committed must be rotated.

RuleWhereCommitStill in tree
stripe-access-token.env:4be4989f 2026-05-04no (history only)
generic-api-key.env:3be4989f 2026-05-04no (history only)

Filtered out

Candidates the verifier rejected after reading the code. Kept for the record; none of them needs action.

FindingReason
Subscription lifecycle handles only checkout and deletion; plan string is not validated
business-logic-101
best_practice
No organization role checks on destructive and billing actions
business-logic-102
best_practice
postcss 8.4.31 and vitest 4.1.8 advisories (build-time and dev-only)
dependency-104
best_practice
README security section claims four controls the code does not implement
docs-vs-reality-101
duplicate_of_auth-101
Customer CSV export does not neutralize spreadsheet formulas
injection-104
best_practice
No security event logging
logging-101
best_practice