nextjs

Seeded Next.js defects — Server Actions with no auth, secrets in public env, per-user data in a cached render.

22 deliberate defects, each with a marker naming the rule in standards/ it breaks. It measures recall: how many of the defects the reviewer flags at their severity or higher. The pass condition is that all 14 BLOCKER defects are flagged.

Because each marker names a rule, the scorer also grades attribution. A reviewer that finds the bug but cites the wrong rule counts as caught, and separately as misattributed.

Running it

Nothing here is ever merged. Open a throwaway pull request on a pilot repository already onboarded for this stack, adding this directory and seeded/clean together, wait for the automated review to finish, then score it.

seed-canary.yml does exactly this on a schedule and closes the pull request afterwards, including when the run fails.

terminal
$ GH_TOKEN=... npx redlinegate metrics score-seeds --repo <org>/<repo> --pr <n>

Flags and output are on redline metrics.

The 22 defects

SeedSeverityRule it violatesDefect
1BLOCKERnextjs/async-client-componentasync component in a 'use client' module
1BLOCKERnextjs/route-handler-unvalidated-inputthe payload reaches a write with no schema check
1BLOCKERcore/hardcoded-secretshardcoded credential
2BLOCKERnextjs/cookie-write-in-rendercookie written while rendering
2BLOCKERcore/missing-auth-checka write endpoint with no authorisation at all
2BLOCKERnextjs/secret-in-public-enva signing secret inlined into the client bundle at build time
3BLOCKERcore/unvalidated-boundary-inputa query parameter consumed as a number with no validation
3BLOCKERnextjs/server-action-missing-autha public POST endpoint that checks neither session nor ownership
4BLOCKERcore/query-string-concatenationSQL built by concatenation with form input
6BLOCKERnextjs/unsanitised-redirectopen redirect from an unchecked query parameter
7BLOCKERnextjs/user-data-in-cached-renderper-user data rendered into a statically cached segment
9BLOCKERcore/customer-data-in-logsthe account holder's email in a log line
10BLOCKERcore/html-injection-sinkunsanitised HTML from a server response */}
12BLOCKERreact/key-is-indexindex key on a list that reorders
3HIGHnextjs/navigation-throw-caughtthe catch swallows the redirect
4HIGHnextjs/mutation-without-revalidationcached pages keep the old name
4HIGHnextjs/route-handler-no-cache-intentno dynamic or cache directive — behaviour changes between versions
5HIGHnextjs/action-returns-internal-errorthe driver's message goes back to the browser
8HIGHnextjs/sequential-server-fetchesindependent awaits serialised
11HIGHnextjs/raw-img-elementraw img where next/image applies */}
13HIGHnextjs/dynamic-api-in-layoutreading cookies in the root layout opts every route out of static rendering
14HIGHcore/untracked-todoplaceholder with no ticket

Scoring

The score reports BLOCKER recall, false positives, and rule attribution. The canary appends it to data/seed-scores.jsonl and fails the run if BLOCKER recall drops below 1.0 or the clean corpus attracts a false positive. Of the 22 defects here, 14 BLOCKER and 8 HIGH — only the BLOCKER count is a pass condition.

Adding a defect

Add the code and one marker line above it. The format, and what scripts/validate.mjs checks, are on Seeded corpus.

The full file

seeded/nextjs/anti_slop.tsx · 33 lines · 1.2 KB
// DO NOT MERGE — Redline validation seed (anti-slop rules).
'use client';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';

// SEED 1 [BLOCKER] (nextjs/async-client-component) async component in a 'use client' module
export default async function Orders() {
  const orders = await fetch('/api/orders').then((r) => r.json());
  return <ul>{orders.map((o: { id: string }) => <li key={o.id}>{o.id}</li>)}</ul>;
}

export async function Dashboard() {
  const store = await cookies();
  // SEED 2 [BLOCKER] (nextjs/cookie-write-in-render) cookie written while rendering
  store.set('last_seen', new Date().toISOString());
  return <p>Overview</p>;
}

export async function createOrder(form: FormData) {
  try {
    const id = await db.order.create(form);
    // SEED 3 [HIGH] (nextjs/navigation-throw-caught) the catch swallows the redirect
    redirect(`/orders/${id}`);
  } catch {
    return { error: 'Something went wrong' };
  }
}

export async function renameProject(id: string, name: string) {
  // SEED 4 [HIGH] (nextjs/mutation-without-revalidation) cached pages keep the old name
  await db.project.update({ where: { id }, data: { name } });
}
seeded/nextjs/route_handler_violations.ts · 24 lines · 1.0 KB
// DO NOT MERGE — Redline validation seed.
// Every `SEED n [SEVERITY] (rule-id)` marker must be flagged at that severity or higher,
// citing that rule id. Score with scripts/score-seeds.mjs.
import { db } from '@/lib/db';

export async function POST(request: Request) {
  // SEED 1 [BLOCKER] (nextjs/route-handler-unvalidated-input) the payload reaches a write with no schema check
  const body = await request.json();
  await db.webhookEvent.create({ data: body });

  // SEED 2 [BLOCKER] (core/missing-auth-check) a write endpoint with no authorisation at all
  return Response.json({ ok: true });
}

export async function GET(request: Request) {
  const url = new URL(request.url);
  // SEED 3 [BLOCKER] (core/unvalidated-boundary-input) a query parameter consumed as a number with no validation
  const limit = Number(url.searchParams.get('limit'));
  const rows = await db.event.findMany({ take: limit });

  // SEED 4 [HIGH] (nextjs/route-handler-no-cache-intent) no dynamic or cache directive — behaviour changes between versions
  return Response.json(rows);
}
seeded/nextjs/seeded_violations.tsx · 91 lines · 3.5 KB
// DO NOT MERGE — Redline validation seed.
// Every `SEED n [SEVERITY] (rule-id)` marker must be flagged at that severity or higher,
// citing that rule id. Score with scripts/score-seeds.mjs.
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';

// SEED 1 [BLOCKER] (core/hardcoded-secrets) hardcoded credential
const PAYMENTS_API_KEY = 'pmt-live-Xq7Rn2Kd9Wm4Tz6Hb3Vy';

// SEED 2 [BLOCKER] (nextjs/secret-in-public-env) a signing secret inlined into the client bundle at build time
const SIGNING_SECRET = process.env.NEXT_PUBLIC_SESSION_SIGNING_SECRET;

export async function deleteInvoice(id: string) {
  'use server';
  // SEED 3 [BLOCKER] (nextjs/server-action-missing-auth) a public POST endpoint that checks neither session nor ownership
  await db.invoice.delete({ where: { id } });
}

export async function exportLedger(formData: FormData) {
  'use server';
  const session = await auth();
  if (!session) throw new Error('unauthorised');
  // SEED 4 [BLOCKER] (core/query-string-concatenation) SQL built by concatenation with form input
  const rows = await db.$queryRawUnsafe(
    "SELECT * FROM ledger WHERE account = '" + String(formData.get('account')) + "'"
  );
  try {
    return await summarise(rows);
  } catch (err) {
    // SEED 5 [HIGH] (nextjs/action-returns-internal-error) the driver's message goes back to the browser
    return { error: (err as Error).message };
  }
}

export async function continueTo(searchParams: { next?: string }) {
  'use server';
  // SEED 6 [BLOCKER] (nextjs/unsanitised-redirect) open redirect from an unchecked query parameter
  redirect(searchParams.next ?? '/');
}

export default async function BillingPage() {
  const session = await auth();
  // SEED 7 [BLOCKER] (nextjs/user-data-in-cached-render) per-user data rendered into a statically cached segment
  const balance = await fetch('https://api.internal/balance', {
    next: { revalidate: 3600 },
  }).then((r) => r.json());

  // SEED 8 [HIGH] (nextjs/sequential-server-fetches) independent awaits serialised
  const invoices = await db.invoice.findMany();
  const methods = await db.paymentMethod.findMany();

  // SEED 9 [BLOCKER] (core/customer-data-in-logs) the account holder's email in a log line
  console.log('rendering billing for', session?.user.email);

  return (
    <main>
      {/* SEED 10 [BLOCKER] (core/html-injection-sink) unsanitised HTML from a server response */}
      <div dangerouslySetInnerHTML={{ __html: balance.noteHtml }} />
      {/* SEED 11 [HIGH] (nextjs/raw-img-element) raw img where next/image applies */}
      <img src={session?.user.avatarUrl} alt="" />
      <InvoiceList invoices={invoices} methods={methods} />
    </main>
  );
}

async function summarise(rows: unknown): Promise<unknown> {
  return rows;
}

function InvoiceList(props: { invoices: unknown[]; methods: unknown[] }) {
  // SEED 12 [BLOCKER] (react/key-is-index) index key on a list that reorders
  return (
    <ul>
      {props.invoices.map((invoice, i) => (
        <li key={i}>{String(invoice)}</li>
      ))}
    </ul>
  );
}

export async function RootLayoutShell({ children }: { children: React.ReactNode }) {
  // SEED 13 [HIGH] (nextjs/dynamic-api-in-layout) reading cookies in the root layout opts every route out of static rendering
  const theme = (await cookies()).get('theme')?.value;
  return <div data-theme={theme}>{children}</div>;
}

// SEED 14 [HIGH] (core/untracked-todo) placeholder with no ticket
// TODO: check entitlement before exposing the export action