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
- 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
- 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
- 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'sidandorgIdand each document'ss3Key(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) andsrc/server/ai/tools.ts:12,29(model-chosenorgId, 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-chosenKeypresigned and stored in the caller's own organization, then presigned for GET bysrc/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) andallowUserToCreateOrganization: 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
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.unoptimizedand no custom loader, so the built-in optimizer endpoint is active undernext start.src/imports neithernext/imagenornext/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.devmatches 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, thestartscript 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 (nonext/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)
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
/adminpage checksrequireAdmin()(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
recentSignupsand 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)
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:24if (session.user.role !== "admin") redirect("/dashboard");, used bysrc/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 isz.object({...}).and(z.record(z.string(), z.any())), so extra keys pass;sign-up.mjs:149takes...restandsign-up.mjs:164callsparseUserInput(ctx.context.options, rest, "create");sign-up.mjs:221-227spreads the result intocreateUser.api/routes/update-user.mjs:11body isz.record(...);update-user.mjs:52-54takes...restand callsparseUserInput(ctx.context.options, rest, "update");update-user.mjs:56writes the result withupdateUser(session.user.id, ...).db/schema.mjs:59-94(parseInputData): a field is refused or reset only whenfields[key].input === false; otherwise the client value is copied (schema.mjs:92).
Data flow
- Source:
rolein the JSON body ofPOST /api/auth/sign-up/emailorPOST /api/auth/update-user(src/app/api/auth/[...all]/route.ts:4) - Transformations:
parseUserInputkeeps it becauseinputis notfalse - Sink:
user.rolecolumn (src/db/schema.ts:10), read back assession.user.rolebyrequireAdmin(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.optionsfromsrc/lib/auth.ts),parseUserInput(the function both endpoints call) keepsroleat the defaultmemberon create and refuses or drops it on update. A control case shows both assertions hold onceinput: falseis 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
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
memberlookup 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-Anever causes a customers query bound toorg-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
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
markInvoicePaidin the same file scopes by org (actions.ts:20,25);invoiceRouter.byIddoes too (src/server/trpc/routers/invoice.ts:26).
Data flow
- Source:
idargument of the server action POST, or the[id]route param of/invoices/[id] - Transformations: none
- Sink:
invoicesselect by id only (actions.ts:11),invoiceLinesby 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
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.orgIdis available (src/server/trpc/init.ts:25) and used bylist(project.ts:9) but not here.- EXPAND (write path vs read path on the same resource):
getProjectanddeleteProjectserver actions scope by org (src/app/(app)/projects/actions.ts:15,42);summarizeProjectscopes by org (src/server/ai/tools.ts:46). Onlyupdateis unscoped.
Data flow
- Source: tRPC input
idand patch fields (POST /api/trpc/project.update) - Transformations: zod shape validation only (unknown keys such as
orgIdare 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)
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.orgIdis passed in (src/app/api/chat/route.ts:17) and used bysummarizeProject(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 argumentorgId - 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)
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). emailDigestdefaults to true for new users (src/lib/auth.ts:30,src/db/schema.ts:11), and the recipient query does not filter onemail_verified.
Data flow
- Source: job payload
orgIdfrom 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
membertable 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)
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 insrc/(no client upload code; greps3Key,uploads). - Download signs whatever key the row holds:
src/app/api/documents/[id]/download/route.ts:26Key: doc.s3Key; the row lookup itself is org-scoped (non-auth-103).
Data flow
- Source:
keyin the JSON body ofPOST /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.pdfnever gets that key presigned or stored; any key that is presigned starts withorg-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
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,
activeOrganizationIdtaken from the session row with nomemberlookup:
src/lib/session.ts:17(requireOrg: every server action and app page)src/server/trpc/init.ts:23(orgProcedure: every tRPC procedure)src/server/api/index.ts:32(Hono public API, session path)src/app/api/chat/route.ts:8src/app/api/uploads/route.ts:18src/app/api/documents/[id]/download/route.ts:11src/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(checkMembershipin set-active). - Removing a member clears
activeOrganizationIdonly 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(updateAge1 day,expiresIn7 days),api/routes/session.mjs:206-207(refresh when older thanupdateAge).src/lib/auth.tssets neither.
Data flow
- Source: the removed user's existing session cookie (any request to the entry points above)
- Transformations:
auth.api.getSessionreturns the session row, whoseactiveOrganizationIdstill 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
memberrow 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
activeOrganizationIdis org A and nomemberrow for that user (andauth.api.getActiveMemberreturning null),requireOrg()refuses, and tRPCproject.listreturns 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)
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:1is"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); documentsorgId,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
columnsselection - 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)
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) withredirect: "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)
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 areSameSite=Noneon.ledgerly.app(src/lib/auth.ts:35-36)./api/public/projectslists every project of the organization, public or not (noisPublicfilter, index.ts:54-59). - Consumer of those ids:
src/server/trpc/routers/project.ts:24updates byidalone and returnsRETURNING *, which includesorgId,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); alsosrc/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
corsechoes 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
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.devhost (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.devhost - 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
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,6and used at assistant-panel.tsx:14-17 (generateTextruns in the browser and calls the provider directly with this key). .env.example:5listsNEXT_PUBLIC_ANTHROPIC_API_KEYas a variable to set (value not read), next to the server-sideANTHROPIC_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-keyheader 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)
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_SECRETis declared in.env.examplebut never read insrc/(grepSTRIPE_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:14and counted insrc/app/api/admin/stats/route.ts:15. Verified by grep: no code gates a feature, limit or access onsubscriptions.planorsubscriptions.status.
Data flow
- Source: unauthenticated POST body (
src/app/api/webhooks/stripe/route.ts:7) - Transformations: cast to
Stripe.Event;metadata.orgIdandmetadata.planused as-is (route.ts:12,14) - Sink: upsert into
subscriptionskeyed byorg_id(route.ts:15-28); update bystripe_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.completedbody 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)
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 takesorgIdas 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", pluskeyParts). Closure values such asorgIdandsinceare not part of the key. Thenextpackage 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:
orgIdfrom 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-monthwith 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 stubtests/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
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 functionoriginoption is used as-is (return optsOrigin), so whatever the function returns becomesAccess-Control-Allow-Origin;Access-Control-Allow-Credentials: trueis set on every response;Vary: Originis 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
GETfrom any web page the signed-in user visits (theOriginheader is the page's origin) - Transformations: browser attaches the SameSite=None session cookie (if it sends third-party cookies); hono
corsechoes the Origin and setsAccess-Control-Allow-Credentials: true(index.ts:16-17); auth middleware resolvesorgIdfrom 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) andGET /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
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,
projectIdcomes from the body (route.ts:10) and the project's organization is never checked.- The public page loads documents through the relation by
projectIdonly:src/app/p/[slug]/page.tsx:9with: { documents: true }(relationsrc/db/schema.ts:211-218) and lists every filename (src/components/public-project-view.tsx:17-19).
Data flow
- Source:
projectIdandfilename(max 200 chars) in the body ofPOST /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) rendersfilename - 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
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, whenopts.allowHeadersis empty, the request'sAccess-Control-Request-Headersvalue is split with a whitespace-tolerant regular expression. src/server/api/index.ts:13-20configurescorswithoutallowHeaders, 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 onlyhono,hono/corsandhono/vercel(grep).
Data flow
- Source: unauthenticated
OPTIONSrequest header to/api/public/* - Transformations: hono
corsmiddleware (noallowHeaders) - 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
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:3likewise) - 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)
.envis listed in.gitignore:3and 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 remotelists no remotes (verified), so the history is not known to be on any shared host.- Correction to the raw finding: the variable at
.env:3is not identifiable without reading the secret.generic-api-keyis a generic rule; that it isBETTER_AUTH_SECRETis an assumption (.envis 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
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/writescustomersorinvoicesrows (grep for inserts finds onlyprojectsanddocuments), so the writer ofi.customerandi.numberis 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:
sendEmailHTML body (src/lib/email.ts:10) sent fromnotifications@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)
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 insrc/app/api/chat/route.ts;usage_eventsis never written insrc/(grep). messagesis taken whole from the client with no length or size check (route.ts:11);serverActions.bodySizeLimitinnext.config.tsapplies to server actions, not route handlers.- EXPAND: same gap on
integration.testWebhook(src/server/trpc/routers/integration.ts:18, see injection-101) andPOST /api/uploads(src/app/api/uploads/route.ts:16); the cost impact is specific to/api/chat.
Data flow
- Source: POST
/api/chatby 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)
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.pushafter 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
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()innext.config.ts;src/proxy.ts:4-12sets no headers and matches only app pages;src/app/layout.tsxsets 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)
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
ContentLengthin the signed command and no per-user or per-organization quota; each call to the route returns a new 15-minute URL. - Downloads force
attachmentdisposition (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:
contentTypeand 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)
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 takesorgIdfrom the server session (init.ts:23-25), and each query filters byctx.orgId;integration.savewritesorgId: ctx.orgIdand zod strips any clientorgId. ·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) afterorgId, so the client cannot override it; startCheckout validates the plan withz.enumand 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
orgIdfrom 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.objectinput 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_SECRETbefore 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.
orgIdis 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,clientContactEmailorslugin 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; greprequireAdminandfrom(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
sqltemplate,sql.rawor.execute(insrc/(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
dangerouslySetInnerHTMLorinnerHTMLinsrc/(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.StoredwebhookUrlvalues are never fetched: the column is written byintegration.saveand read back only byintegration.listfor the same organization. No job, route or service sends to it (grep forwebhookUrlandfetch(insrc/). 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.
.envis ignored and no longer tracked (history is exposure-103); session and dashboard query modules importserver-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
idtoInvoiceQuickView;InvoiceDetailis a server component (no"use client"), so the full invoice row it receives is rendered on the server and only displayed text is sent;ProjectListand `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 ofsrc/,next.config.tsanddrizzle.config.tsfor 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 withtimingSafeEqualafter 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: attachmentand 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.
| # | Score | Where | Why |
|---|---|---|---|
| 1 | 13 | src/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 |
| 2 | 10 | src/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 |
| 3 | 10 | src/app/api/admin/stats/route.ts:5 route-handler GET | admin area; no auth check in the handler; unscoped query on projects, subscriptions |
| 4 | 10 | src/lib/auth.ts:1 config auth.ts | auth configuration (betterAuth); additionalFields.role is writable at sign-up (no input: false); SameSite=None session cookies |
| 5 | 9 | src/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 |
| 6 | 7 | src/server/trpc/routers/integration.ts:18 trpc integrationRouter.testWebhook | webhooks area; outbound request to a non-constant URL (SSRF) |
| 7 | 6 | src/app/api/export/route.ts:6 route-handler GET | files area; tenant/user id taken from the request |
| 8 | 6 | src/app/p/[slug]/page.tsx:1 page page | page without a guard reads the database (what reaches the client?); unscoped query on projects |
| 9 | 6 | src/server/api/index.ts:1 config index.ts | CORS reflects any origin with credentials |
| 10 | 6 | src/server/trpc/routers/project.ts:12 trpc projectRouter.update | unscoped query on projects; request object written to the database as-is |
| 11 | 5 | src/app/api/documents/[id]/download/route.ts:9 route-handler GET | files area; presigned storage URL |
| 12 | 5 | src/app/api/uploads/route.ts:16 route-handler POST | files area; presigned storage URL |
| 13 | 5 | src/app/api/webhooks/resend/route.ts:8 webhook POST | webhooks area; webhook: public by design |
| 14 | 5 | src/lib/ai-client.ts:1 code ai-client.ts | NEXT_PUBLIC_ANTHROPIC_API_KEY looks like a secret and is shipped to the browser |
| 15 | 5 | src/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 |
| 16 | 4 | src/app/(app)/invoices/actions.ts:19 server-action markInvoicePaid | payments area; server-action: callable directly as a POST |
| 17 | 4 | src/app/(app)/settings/billing/actions.ts:10 server-action startCheckout | payments area; server-action: callable directly as a POST |
| 18 | 4 | src/app/api/auth/[...all]/route.ts:4 route-handler GET, POST | auth area; dispatcher: the routes it mounts are ranked separately |
| 19 | 4 | src/server/ai/tools.ts:39 ai-tool summarizeProject | ai area; ai-tool: arguments chosen by the model |
| 20 | 4 | src/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
| Package | Version | Scope | CVSS | Fixed in | Advisories |
|---|---|---|---|---|---|
| next | 16.3.0 | prod (direct) | 9.5 | 15.5.24, 16.3.3, 16.3.6 | GHSA-2xp9-vwfh-vxw4, GHSA-p293-qw3h-jr36, GHSA-vcvr-r3jv-pc5j |
| sharp | 0.34.5 | unknown | 8.9 | 0.35.0, 0.35.4 | GHSA-f88m-g3jw-g9cj, GHSA-rgj7-g3m4-5g8c |
| postcss | 8.4.31 | unknown | 7.5 | 8.5.12, 8.5.23, 8.5.10, 8.5.18 | GHSA-6g55-p6wh-862q, GHSA-fxqj-rqcc-2cmp, GHSA-qx2v-qp2m-jg93, GHSA-r28c-9q8g-f849 |
| hono | 4.12.25 | prod (direct) | 6.5 | 4.12.34, 4.13.5, 4.12.27, 4.13.7 | GHSA-54fx-42gc-7vw4, GHSA-79qm-7rj5-m7r9, GHSA-8j4g-w8fx-2239, GHSA-crvj-82cr-hjcx +7 |
| vitest | 4.1.8 | dev (direct) | 5.9 | 4.1.11, 5.0.0-rc.2 | GHSA-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.
| Rule | Where | Commit | Still in tree |
|---|---|---|---|
| stripe-access-token | .env:4 | be4989f 2026-05-04 | no (history only) |
| generic-api-key | .env:3 | be4989f 2026-05-04 | no (history only) |
Filtered out
Candidates the verifier rejected after reading the code. Kept for the record; none of them needs action.
| Finding | Reason |
|---|---|
| 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 |