Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,9 @@ jobs:
run: |
node dist/cli.js test/fixtures/next-app --json > report.json || true
node -e "const r=require('./report.json'); if (r.summary.unprotected !== 2) process.exit(1)"
# The fixture is a subfolder of this repository, like an app in a monorepo. Written to a file
# so the runner does not turn the lines into annotations
- name: Annotations use paths from the repository root
run: |
node dist/cli.js test/fixtures/next-app --format github --fail-on never > annotations.txt
grep -q '^::error file=test/fixtures/next-app/app/' annotations.txt
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Changelog

## 0.2.0 (unreleased)
## 0.2.1 (unreleased)

- Fix: in a monorepo (`path: apps/web` in the Action, or `npx server-action-audit apps/web`), annotations used paths from the app's folder (`app/actions.ts`) instead of the repository root (`apps/web/app/actions.ts`), so GitHub could not show them on the line in the pull request. The `github`, `sarif` and `markdown` formats and the pull request comment now use paths from the repository root. The `pretty` and `json` formats are unchanged.

## 0.2.0 (2026-10-31)

- `--pr-comment`: in GitHub Actions, posts the report as a comment on the pull request through the GitHub REST API, and updates that same comment on every push. A pull request with nothing to fix gets no comment. If the token can't write (forks, missing `pull-requests: write`), it shows a warning and keeps the exit code.
- GitHub Action: `comment` and `github-token` inputs for the above.
Expand Down
2 changes: 1 addition & 1 deletion README.fr.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Tout est décrit dans le [README en anglais](README.md#configuration) :
- le fichier `server-action-audit.config.json` ;
- le plugin ESLint (`server-action-audit/eslint`) ;
- les options `--fail-on`, `--json` et `--quiet` ;
- l'Action GitHub, qui annote les pull requests et peut aussi y poster le rapport en commentaire (`comment: true`).
- l'Action GitHub, qui annote les pull requests et peut aussi y poster le rapport en commentaire (`comment: true`). Dans un monorepo, indiquez le dossier de l'application avec `path` (par exemple `apps/web`).

## Limites

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ jobs:
fail-on: unprotected
```

In a monorepo, set `path` to the app's folder, like `apps/web`. Annotations, comment links and SARIF results still point to the right file, with its path from the repository root.

To also get the report as a comment on the pull request, set `comment: true` and let the job write to pull requests. The action keeps a single comment and updates it on every push. It only comments once there is something to fix. If the job can't comment (pull requests from forks only get a read-only token), it shows a warning and the audit result stays the same.

```yaml
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "server-action-audit",
"version": "0.2.0",
"version": "0.2.1",
"description": "Find Next.js Server Actions that anyone can call: a CLI and an ESLint plugin that flag \"use server\" functions without an authorization check or input validation.",
"keywords": [
"nextjs",
Expand All @@ -27,6 +27,9 @@
},
"bugs": "https://github.com/i6moons/server-action-audit/issues",
"type": "module",
"publishConfig": {
"registry": "https://registry.npmjs.org/"
},
"engines": {
"node": ">=20"
},
Expand Down
32 changes: 17 additions & 15 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isAbsolute, relative, resolve, sep } from 'node:path'
import { resolve } from 'node:path'
import { formatGithub, formatJson, formatMarkdown, formatPretty, formatSarif } from './format.js'
import { pullRequestFromEnv, upsertComment } from './github.js'
import { fromRepositoryRoot, repositoryPath } from './repository.js'
import { loadConfig, scanProject, type ProjectReport } from './scan.js'
import { VERSION } from './version.js'

Expand Down Expand Up @@ -28,15 +29,11 @@ Options
Exit codes: 0 ok, 1 problems found, 2 usage error.
`

/** The link prefix for files of the scanned directory, when it is inside the checked-out repository. */
function sourceUrl(root: string, serverUrl: string, repository: string, sha: string | undefined): string | undefined {
const path = relative(process.env.GITHUB_WORKSPACE || process.cwd(), root)
if (!sha || path.startsWith('..') || isAbsolute(path)) return undefined
return `${serverUrl}/${repository}/blob/${sha}/${path ? `${path.split(sep).join('/')}/` : ''}`
}

/** Never changes the exit code: a missing permission must not fail the audit. */
async function commentOnPullRequest(report: ProjectReport, root: string): Promise<void> {
/**
* Never changes the exit code: a missing permission must not fail the audit. `report` has its paths from the
* repository root when `inRepository` is true, so they can be appended to a link to the commit.
*/
async function commentOnPullRequest(report: ProjectReport, inRepository: boolean): Promise<void> {
let pr
try {
pr = pullRequestFromEnv()
Expand All @@ -49,7 +46,8 @@ async function commentOnPullRequest(report: ProjectReport, root: string): Promis
}
const { unprotected, unvalidated } = report.summary
try {
const body = formatMarkdown(report, { sourceUrl: sourceUrl(root, pr.serverUrl, pr.repository, pr.headSha) })
const sourceUrl = inRepository && pr.headSha ? `${pr.serverUrl}/${pr.repository}/blob/${pr.headSha}/` : undefined
const body = formatMarkdown(report, { sourceUrl })
const result = await upsertComment(pr, body, { clean: !unprotected && !unvalidated })
const done = { created: 'commented on', updated: 'updated its comment on', skipped: 'nothing new to post on' }[result]
process.stderr.write(`--pr-comment: ${done} pull request #${pr.number}.\n`)
Expand Down Expand Up @@ -106,18 +104,22 @@ async function main(argv: string[]): Promise<number> {
process.stderr.write(`server-action-audit: ${(error as Error).message}\n`)
return 2
}
// What GitHub reads (annotations, code scanning, pull request comments) needs paths from the repository
// root, while the terminal and JSON keep them from the scanned directory
const repoPath = repositoryPath(root)
const forGithub = repoPath === undefined ? report : fromRepositoryRoot(report, repoPath)
const output =
format === 'json'
? formatJson(report)
: format === 'github'
? formatGithub(report)
? formatGithub(forGithub)
: format === 'sarif'
? formatSarif(report, VERSION)
? formatSarif(forGithub, VERSION)
: format === 'markdown'
? formatMarkdown(report)
? formatMarkdown(forGithub)
: formatPretty(report, { quiet })
process.stdout.write(`${output}\n`)
if (prComment) await commentOnPullRequest(report, root)
if (prComment) await commentOnPullRequest(forGithub, repoPath !== undefined)

const { unprotected, unvalidated } = report.summary
if (failOn === 'unprotected' && unprotected) return 1
Expand Down
43 changes: 43 additions & 0 deletions src/repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { existsSync } from 'node:fs'
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
import type { ProjectReport } from './scan.js'

const posix = (path: string) => path.split(sep).join('/')

function inside(parent: string, path: string): boolean {
const rel = relative(parent, path)
return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
}

/**
* Where the scanned directory sits in its repository, with forward slashes: `''` at the root, `'apps/web'` in a
* monorepo, `undefined` when it is in no repository.
*
* The nearest `.git` marks the root (a folder, or a file in worktrees and submodules). In GitHub Actions only
* directories inside the workspace count, and the workspace is the root when the checkout has no `.git` (no git
* on the runner).
*/
export function repositoryPath(root: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
const dir = resolve(root)
const top = env.GITHUB_WORKSPACE ? resolve(env.GITHUB_WORKSPACE) : undefined
if (top !== undefined && !inside(top, dir)) return undefined
for (let current = dir; ; current = dirname(current)) {
if (existsSync(join(current, '.git'))) return posix(relative(current, dir))
if (current === top || dirname(current) === current) break
}
return top === undefined ? undefined : posix(relative(top, dir))
}

/**
* The report with its paths starting from the repository root instead of the scanned directory. GitHub needs
* them that way to place annotations and code scanning results on the right file, and to link to it.
*/
export function fromRepositoryRoot(report: ProjectReport, path: string): ProjectReport {
if (!path) return report
const prefix = (file: string) => `${path}/${file}`
return {
...report,
files: report.files.map((file) => ({ ...file, file: prefix(file.file) })),
errors: report.errors.map((error) => ({ ...error, file: prefix(error.file) })),
}
}
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/** Kept in sync with package.json by test/version.test.ts. */
export const VERSION = '0.2.0'
export const VERSION = '0.2.1'
71 changes: 71 additions & 0 deletions test/repository.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterAll, describe, expect, it } from 'vitest'
import { formatGithub, formatMarkdown, formatSarif, loadConfig, scanProject } from '../src/index.js'
import { fromRepositoryRoot, repositoryPath } from '../src/repository.js'

const tmp = mkdtempSync(join(tmpdir(), 'saa-repo-'))
afterAll(() => rmSync(tmp, { recursive: true, force: true }))

/** Creates the folders (and a `.git` folder or file) under a fresh directory, and returns its path. */
function tree(name: string, dirs: string[], gitFile?: string): string {
const base = join(tmp, name)
for (const dir of dirs) mkdirSync(join(base, dir), { recursive: true })
if (gitFile) writeFileSync(join(base, gitFile), 'gitdir: /elsewhere/.git/worktrees/x\n')
return base
}

describe('repositoryPath', () => {
it('gives the path of an app inside a repository, from its root', () => {
const repo = tree('monorepo', ['.git', 'apps/web'])
expect(repositoryPath(join(repo, 'apps/web'), {})).toBe('apps/web')
expect(repositoryPath(repo, {})).toBe('')
})

it('accepts a .git file, as in worktrees and submodules', () => {
const repo = tree('worktree', ['apps/web'], '.git')
expect(repositoryPath(join(repo, 'apps/web'), {})).toBe('apps/web')
})

it('finds a repository checked out in a subfolder of the workspace', () => {
const workspace = tree('checkout-path', ['repo/.git', 'repo/apps/web'])
expect(repositoryPath(join(workspace, 'repo/apps/web'), { GITHUB_WORKSPACE: workspace })).toBe('apps/web')
})

it('counts the workspace as the root of a checkout without .git, and never looks above it', () => {
const outer = tree('no-git', ['.git', 'workspace/apps/web'])
const workspace = join(outer, 'workspace')
expect(repositoryPath(join(workspace, 'apps/web'), { GITHUB_WORKSPACE: workspace })).toBe('apps/web')
})

it('gives nothing for a directory outside the workspace', () => {
const outer = tree('outside', ['.git', 'workspace', 'other/app'])
expect(repositoryPath(join(outer, 'other/app'), { GITHUB_WORKSPACE: join(outer, 'workspace') })).toBeUndefined()
})
})

describe('fromRepositoryRoot', () => {
const root = fileURLToPath(new URL('./fixtures/next-app', import.meta.url))
const report = scanProject(root, loadConfig(root))
const inMonorepo = fromRepositoryRoot(report, 'apps/web')

it('prefixes the paths of files and skipped files, and leaves the report alone at the root', () => {
expect(inMonorepo.files.map((f) => f.file)).toEqual(['apps/web/app/(auth)/actions.ts', 'apps/web/app/(dashboard)/posts/actions.ts', 'apps/web/app/page.tsx'])
expect(fromRepositoryRoot({ ...report, errors: [{ file: 'app/broken.ts', message: 'x' }] }, 'apps/web').errors).toEqual([{ file: 'apps/web/app/broken.ts', message: 'x' }])
expect(fromRepositoryRoot(report, '')).toBe(report)
expect(report.files[0]!.file).toBe('app/(auth)/actions.ts')
})

it('puts annotations, code scanning results and links on the file in the repository', () => {
expect(formatGithub(inMonorepo).split('\n')).toContain(
'::error file=apps/web/app/(dashboard)/posts/actions.ts,line=16,col=1,title=server-action-audit/require-auth::Server Action "deletePost" has no authorization check: anyone can call it with a POST request. Check the session inside the action, or mark it with // @public-action if it is public on purpose.',
)
const sarif = JSON.parse(formatSarif(inMonorepo, '9.9.9'))
expect(sarif.runs[0].results[0].locations[0].physicalLocation.artifactLocation).toEqual({ uri: 'apps/web/app/(auth)/actions.ts' })
expect(formatMarkdown(inMonorepo, { sourceUrl: 'https://github.com/acme/shop/blob/f00/' })).toContain(
'[apps/web/app/(dashboard)/posts/actions.ts:16](https://github.com/acme/shop/blob/f00/apps/web/app/%28dashboard%29/posts/actions.ts#L16)',
)
})
})
Loading