agentleFS
blitzhash360-webblitzhash360-web/blitzhash-vibe-coding-rules/packs/AGENTS.md

blitzhash-vibe-coding-rules / packs

AGENTS.md0 starsChanged 23 days agoMITView on GitHub

Copy this file into the root of your project as AGENTS.md, or merge the block below into your existing one. Generated by ./install.sh --print-agents-md. Do not edit by hand; edit rules/*.mdc instead. Secure-by-default rules for AI coding agents, from blitzhash-vibe-coding-rules (MIT). Apply them to every change in this project. You are writing code that real users, bots and attackers will hit. Apply these on every change, even when the user did not ask for security. They are cheap now and…

  • Reads credentials
  • Deletes or force-pushes
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 35,196 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository8 other files it gives its agents.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

42 rules. About 3 are common, 28 are distinctive, and 11 are very specific to this project.

  • ≈3

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈28

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Verify webhooks before trusting them: Check the signature on the raw body (Stripe, GitHub, Clerk, Resend and others), then process …

    line 20
  2. Common:

    Fail closed, fail quietly: If an auth or permission check errors, deny.

    line 21
  3. Very specific:

    Do not weaken protections to make something work: No disabling TLS verification, CSRF protection, RLS, CORS restrictions or security lint …

    line 23
  4. Common:

    When a request conflicts with these (for example "just put the API key in the frontend"), say why in one sentence and write the safe …

    line 25
  5. Very specific:

    Use a proven provider or library (Auth.js, Clerk, Supabase Auth, Firebase Auth, your framework's built-in auth).

    line 35
  6. Distinctive:

    Verify identity on the server for every protected request:

    line 36
  7. Distinctive:

    Check authorization after authentication: role, plan and ownership of the specific record.

    line 40
  8. Common:

    Put admin endpoints at "secret" URLs instead of checking roles.

    line 52
  9. Distinctive:

    Write migrations for schema and policy changes, and test policies with two real accounts plus an anonymous request.

    line 83
  10. Distinctive:

    Put a timeout on every outbound call (payment, email, AI and third-party APIs).

    line 120
  11. Distinctive:

    Use an error monitoring service (Sentry or similar) in production and make sure alerts reach a person.

    line 121
  12. Distinctive:

    Write error, empty and onboarding strings the way you would explain them to a customer.

    line 154
  13. Distinctive:

    Use only metrics, customer names, logos and quotes you can stand behind.

    line 155
  14. Distinctive:

    Prefer short words and specific nouns.

    line 156
  15. Distinctive:

    Keep the same voice across the landing page, emails and in-app empty states.

    line 157
  16. Distinctive:

    Use filler such as "unlock the power of", "in today's fast-paced world", "seamless experience" or "we're thrilled to announce" unless that …

    line 162
  17. Distinctive:

    Treat LLM output as user input: validate structured output against a schema before acting on it.

    line 192
  18. Distinctive:

    Delete or simplify dead code before adding a new helper, hook or folder.

    line 230
  19. Distinctive:

    Keep names, files and patterns the project already uses unless the user asked for a rename.

    line 232
  20. Distinctive:

    If a larger redesign would be better, say so in one short paragraph and still ship the small fix first, unless the user asked for the …

    line 233
  21. Distinctive:

    Add a new layer (service, hook, context, state library, folder of utils) "for later" or for a single use.

    line 237
  22. Distinctive:

    Use a store shared by all instances.

    line 259
  23. Distinctive:

    Add edge protection for public forms: Cloudflare Turnstile, hCaptcha or reCAPTCHA on signup and contact forms.

    line 262
  24. Distinctive:

    Use one global limit for everyone.

    line 270
  25. Very specific:

    Read secrets from environment variables on the server only.

    line 301
  26. Very specific:

    Keep .env, .env.local and .env.*.local in .gitignore.

    line 302
  27. Very specific:

    Use the platform's secret store in production: Vercel or Netlify environment variables, wrangler secret put on Cloudflare, Firebase or …

    line 303
  28. Distinctive:

    Use the narrowest key: restricted Stripe keys, scoped tokens, read-only database roles for read-only jobs.

    line 305
  29. Very specific:

    Put a secret behind a public prefix: NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_, REACT_APP_, PUBLIC_, NUXT_PUBLIC_.

    line 310
  30. Distinctive:

    Call a paid AI API directly from the browser with your key.

    line 314
  31. Distinctive:

    Update the value in every environment and redeploy.

    line 319
  32. Distinctive:

    Check the provider's logs and billing for use you do not recognise.

    line 321
  33. Very specific:

    Verify every event with the raw request body, the Stripe-Signature header and your endpoint secret (STRIPE_WEBHOOK_SECRET):

    line 341
  34. Very specific:

    Read the body as raw text or bytes.

    line 345
  35. Very specific:

    Do not depend on event order.

    line 348
  36. Distinctive:

    Create Checkout Sessions on the server with Price IDs you control.

    line 351
  37. Very specific:

    Test locally with stripe listen --forward-to localhost:3000/api/webhooks/stripe and stripe trigger checkout.session.completed.

    line 352
  38. Distinctive:

    Treat "the user reached /success" as proof of payment.

    line 359
  39. Distinctive:

    Keep the primary action reachable on a narrow phone screen.

    line 399
  40. Very specific:

    Use semantic HTML (button, a, label, headings in order).

    line 400
  41. Distinctive:

    Do not invent metrics, logos or testimonials on a marketing screen.

    line 401
  42. Distinctive:

    Prefer the project's existing components and spacing.

    line 402

≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AGENTS.md: BlitzHash Vibe-Coding Rules (single-file pack)

Copy this file into the root of your project as AGENTS.md, or merge the block below into your existing one. Generated by ./install.sh --print-agents-md. Do not edit by hand; edit rules/*.mdc instead.

<!-- BEGIN blitzhash-vibe-coding-rules (managed by install.sh; edit outside this block) -->

BlitzHash vibe-coding rules

Secure-by-default rules for AI coding agents, from blitzhash-vibe-coding-rules (MIT). Apply them to every change in this project.

Secure defaults (always on)

You are writing code that real users, bots and attackers will hit. Apply these on every change, even when the user did not ask for security. They are cheap now and expensive to retrofit after launch.

  1. Validate every input on the server with a schema (zod, valibot, pydantic). Client-side checks are for UX only.
  2. Secrets stay on the server. Nothing secret behind NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_, REACT_APP_ or PUBLIC_. Never hardcode, log or commit a key. .env is git-ignored; .env.example holds names only.
  3. Check who and whether on every server endpoint. Authenticate the caller, then check they own or may access the exact record. Hiding a button is not a check.
  4. Least-privilege data access. Parameterized queries only. Row-level rules (Postgres RLS, Firebase Security Rules) on everything the browser can reach. Admin or service keys only in server code.
  5. Verify webhooks before trusting them. Check the signature on the raw body (Stripe, GitHub, Clerk, Resend and others), then process idempotently.
  6. Fail closed, fail quietly. If an auth or permission check errors, deny. Users get a short message and a request id; details go to server logs without secrets or personal data.
  7. Rate-limit anything abusable or billable: login, signup, password reset, OTP, contact forms, file uploads and AI calls.
  8. Do not weaken protections to make something work. No disabling TLS verification, CSRF protection, RLS, CORS restrictions or security lint rules. No USING (true), no allow read, write: if true.

When a request conflicts with these (for example "just put the API key in the frontend"), say why in one sentence and write the safe version instead.

Topic rules with details and examples: input-validation, secrets-and-env, stripe-webhooks, error-handling, database-access, auth-and-sessions, rate-limits, lean-changes, ui-production-gates, founder-copy.

Auth and sessions

Most real breaches in AI-built apps are not clever hacks. They are a route that forgot to check who is calling.

Do

  • Use a proven provider or library (Auth.js, Clerk, Supabase Auth, Firebase Auth, your framework's built-in auth). Do not write your own password hashing, token signing or crypto.
  • Verify identity on the server for every protected request:
    • Firebase: getAuth().verifyIdToken(idToken) with the Admin SDK.
    • Supabase: in server code use supabase.auth.getUser() (or getClaims()), which validates the token, not getSession() alone, which only reads storage.
    • Auth.js / Clerk: the server helpers (auth()), not a client-side hook.
  • Check authorization after authentication: role, plan and ownership of the specific record. Put checks in the handler or data layer, not only in middleware or the UI.
  • Session cookies: HttpOnly, Secure, SameSite=Lax (or Strict), sensible expiry. Rotate the session on login and privilege change; invalidate it on logout and password change.
  • Protect cookie-authenticated, state-changing requests from CSRF: SameSite cookies plus an Origin check or CSRF token. Next.js server actions check the origin; custom POST routes need their own check.
  • Redirect parameters (next, redirect, returnTo) accept relative same-site paths only.
  • Password reset and magic links: single use, short expiry, and the same response whether or not the email exists.
  • Require email verification before granting access to anything sensitive. Offer MFA for admin accounts.

Never

  • Trust isAdmin, role or userId from the request body, query string, localStorage or a decoded-but-unverified JWT.
  • Store session tokens or refresh tokens in localStorage when a cookie option exists.
  • Protect a page only by hiding it in the navigation, or only in client-side route guards.
  • Put admin endpoints at "secret" URLs instead of checking roles.
  • Disable CSRF protection, email verification or rate limits on login to "fix" a bug.

Example

// lib/auth-guard.ts
import "server-only";

export async function requireOwner(resourceUserId: string) {
  const user = await getVerifiedUser(); // validates the session on the server
  if (!user) throw new HttpError(401, "Sign in required");
  if (user.id !== resourceUserId && user.role !== "admin") throw new HttpError(403, "Not allowed");
  return user;
}

Database access

Assume every query can be called by an attacker with a valid account. The database, not the UI, decides who sees which rows.

Do

  • Parameterized queries only. pg: query("select * from orders where id = $1", [id]). Prisma: the ORM API or the $queryRaw tagged template. Drizzle: sql`...${value}`. Python: cursor.execute(sql, params). Allowlist column names when sorting by user choice.
  • Scope every query to the caller. Filter by the verified user or org id from the session, and check ownership before update or delete (prevents IDOR: user A reading user B's invoice by changing an id).
  • Row-level security when the browser talks to the database (Supabase, PostgREST, Firebase, Hasura):
    • Postgres or Supabase: alter table ... enable row level security; on every table in exposed schemas, then one policy per action. Use using (...) for reads and with check (...) for inserts and updates, for example using ((select auth.uid()) = user_id). Index the columns your policies filter on.
    • Firebase: start from deny-all, then allow read, write: if request.auth != null && request.auth.uid == userId; and validate fields in rules. Never ship test-mode rules.
    • Storage buckets follow the same rules: private by default, signed URLs for downloads.
  • Least privilege. The app's database user is not a superuser and cannot drop tables. Use a separate role for migrations. Service-role or admin SDK credentials only in server code, and still filter by user there.
  • Bound every list. Paginate (limit plus cursor), select only the columns you need, and never return password hashes, tokens or internal flags.
  • Write migrations for schema and policy changes, and test policies with two real accounts plus an anonymous request.

Never

  • Build SQL with string concatenation or template literals: `... where email = '${email}'`. Not even "just for this admin page".
  • $queryRawUnsafe or execute_sql with user input.
  • using (true) or allow read, write: if true on non-public data, or "temporarily disable RLS to debug".
  • Ship a Supabase service_role / secret key or a Firebase Admin credential to the browser.
  • Trust a userId sent by the client for authorization.

Example (Postgres row-level security)

alter table public.invoices enable row level security;

create policy "owners read their invoices" on public.invoices
  for select to authenticated
  using ((select auth.uid()) = user_id);

create policy "owners create their invoices" on public.invoices
  for insert to authenticated
  with check ((select auth.uid()) = user_id);

create index if not exists invoices_user_id_idx on public.invoices (user_id);

auth.uid() is the Supabase helper; on plain Postgres use your own session variable or do the ownership check in server code.

Error handling and logging

Errors are where apps leak data and where silent failures cost money. Handle them on purpose.

Do

  • Catch errors at boundaries (route handlers, server actions, jobs, webhook handlers) and return a consistent shape: { error: "Something went wrong", requestId } with the right status code (400, 401, 403, 404, 409, 429, 500).
  • Log the real error on the server with context (route, user id, request id), as structured JSON where possible.
  • Fail closed: if a permission check, signature check or token verification throws, deny the request.
  • Put a timeout on every outbound call (payment, email, AI and third-party APIs). Retry with exponential backoff only for idempotent operations, with a maximum attempt count.
  • Use an error monitoring service (Sentry or similar) in production and make sure alerts reach a person.
  • In React, add error boundaries (error.tsx in Next.js) so one broken component does not blank the page.
  • Show users what to do next: retry, contact support, or check their input.

Never

  • Send stack traces, SQL errors, file paths, internal hostnames or raw provider errors to the client in production.
  • Swallow errors with an empty catch {} or catch (e) { console.log(e) } and carry on as if it worked.
  • Log passwords, tokens, API keys, full card or bank details, or full request bodies of auth and payment routes.
  • Reveal whether an email exists in login, signup or password-reset errors ("If that account exists, we sent an email").
  • Retry a non-idempotent operation (charging a card, sending an email) without an idempotency key.

Example

export async function POST(req: Request) {
  const requestId = crypto.randomUUID();
  try {
    return await handle(req);
  } catch (err) {
    logger.error({ requestId, route: "/api/orders", err: serializeError(err) });
    return Response.json({ error: "Something went wrong. Please try again.", requestId }, { status: 500 });
  }
}

Founder copy that sounds human

Users can tell when a landing page or an error message was left as AI filler. Say what the product does, honestly, in the words you would use in an email.

Do

  • Lead with what the product does and who it is for, in one short sentence. Then one clear action.
  • Write error, empty and onboarding strings the way you would explain them to a customer. Name the next step.
  • Use only metrics, customer names, logos and quotes you can stand behind. If you do not have them yet, omit them.
  • Prefer short words and specific nouns. Cut throat-clearing openers and padded adjectives.
  • Keep the same voice across the landing page, emails and in-app empty states.

Never

  • Invent "trusted by 10,000 teams", award badges, or testimonials.
  • Use filler such as "unlock the power of", "in today's fast-paced world", "seamless experience" or "we're thrilled to announce" unless that is genuinely how this founder talks and the fact is true.
  • Hide the product behind a metaphor. If it is a billing tool, say it is a billing tool.

Example (honest hero, no invented proof)

export function Hero() {
  return (
    <section>
      <h1>See which leftover files your app still exposes, before your customers do.</h1>
      <p>A one-command check for founders who built with AI. No account.</p>
      <a href="/start">Scan your site</a>
    </section>
  );
}

Input validation

Anything that crosses into your server (body, query string, route params, headers, cookies, uploaded files, webhook payloads, LLM output) is untrusted until validated.

Do

  • Parse input with a schema at the top of every handler and use only the parsed result: zod or valibot in TypeScript, pydantic in Python. Reject unknown keys (.strict() in zod).
  • Constrain everything: types, min and max lengths, number ranges, enums, email and URL formats, array sizes. Cap request body size.
  • Pick fields explicitly when writing to the database. Never spread req.body into an insert or update. Users must not be able to set role, is_admin, user_id, plan, price or credits.
  • Take identity (userId, orgId) from the verified session, never from the request body.
  • Uploads: limit size, check type by content (magic bytes), not by extension or Content-Type; generate a random file name; store in a private bucket and serve with short-lived signed URLs.
  • Fetching a user-supplied URL (webhooks, link previews, imports): allow only https, allowlist hosts where possible, and block private, loopback and link-local addresses to prevent SSRF.
  • Render user content as text. If HTML is required, sanitize it (DOMPurify) before dangerouslySetInnerHTML or v-html.
  • Treat LLM output as user input: validate structured output against a schema before acting on it.

Never

  • eval, new Function, or building shell commands, SQL or file paths from user input.
  • Trust a hidden form field, a disabled input or a client-side price.
  • Return the raw validation library error object to the client in production; return a short list of field messages.

Example (Next.js route handler)

import { z } from "zod";

const UpdateProfile = z
  .object({
    displayName: z.string().trim().min(1).max(60),
    bio: z.string().max(500).optional(),
  })
  .strict();

export async function PATCH(req: Request) {
  const user = await requireUser(); // throws 401 if not signed in
  const parsed = UpdateProfile.safeParse(await req.json().catch(() => null));
  if (!parsed.success) {
    return Response.json({ error: "Invalid input", fields: parsed.error.flatten().fieldErrors }, { status: 400 });
  }
  await db.profile.update({ where: { userId: user.id }, data: parsed.data });
  return Response.json({ ok: true });
}

Prefer the smallest change

A senior engineer changes as little as possible. Extra files, wrappers and "while we're here" refactors are how AI-built apps get hard to ship.

Do

  • Restate the request in one sentence, then change only what that sentence needs.
  • Delete or simplify dead code before adding a new helper, hook or folder.
  • Reuse a function or component that already does the job. Do not invent a new abstraction for a single call site.
  • Keep names, files and patterns the project already uses unless the user asked for a rename.
  • If a larger redesign would be better, say so in one short paragraph and still ship the small fix first, unless the user asked for the redesign.

Never

  • Add a new layer (service, hook, context, state library, folder of utils) "for later" or for a single use.
  • Rewrite unrelated files, reformat the repo, or swap libraries as a side effect of a small request.
  • Duplicate a feature that already exists elsewhere in the app.

Example (smallest fix, not a new helper)

// BEFORE: a new useOrderTotals hook, a totals.ts util and a rename, just to show a total.
// AFTER: use the price already computed on the order in this component.
export function OrderTotal({ order }: { order: Order }) {
  const total = order.lines.reduce((sum, line) => sum + line.qty * line.unitPrice, 0);
  return <p>Total {formatMoney(total)}</p>;
}

Rate limits and abuse controls

Without limits, one script can brute-force logins, spam your signup, drain your email quota or run up an AI bill overnight.

Do

  • Rate-limit at least: login, signup, password reset, OTP and magic-link sends, contact and waitlist forms, file uploads, search, and every route that calls a paid API (AI models, SMS, email).
  • Use a store shared by all instances. Serverless functions and multiple containers do not share memory, so an in-memory counter does little. Use Redis or Upstash (@upstash/ratelimit), Cloudflare rate limiting rules or Workers KV / Durable Objects, or your API gateway.
  • Key limits by user id when signed in and by IP otherwise. Read the client IP only from your platform's trusted header or helper; a raw X-Forwarded-For can be spoofed.
  • Return 429 Too Many Requests with a Retry-After header and a friendly message.
  • Add edge protection for public forms: Cloudflare Turnstile, hCaptcha or reCAPTCHA on signup and contact forms.
  • AI features: per-user daily quotas, max_tokens on every call, a cheaper model for simple tasks, timeouts, and a hard spend cap or budget alert in the provider dashboard.
  • Log and alert on spikes of 401, 403 and 429 responses.

Never

  • Rely only on client-side throttling or a disabled button.
  • Ship an unauthenticated endpoint that calls a paid API.
  • Use one global limit for everyone; a single abuser should not lock out all users.

Example (Upstash Ratelimit in a Next.js route)

import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const limiter = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "1 m"),
  prefix: "rl:ai-chat",
});

export async function POST(req: Request) {
  const user = await requireUser();
  const { success, reset } = await limiter.limit(user.id);
  if (!success) {
    const retryAfter = Math.max(1, Math.ceil((reset - Date.now()) / 1000));
    return Response.json({ error: "Too many requests. Try again shortly." }, { status: 429, headers: { "Retry-After": String(retryAfter) } });
  }
  // ...call the AI provider with max_tokens and a timeout
}

Secrets and environment variables

A secret is anything that grants access or costs money: payment keys, AI API keys, database URLs with passwords, service or admin keys, webhook signing secrets, OAuth client secrets, SMTP passwords, JWT signing keys.

Do

  • Read secrets from environment variables on the server only. In Next.js, put secret-using code in modules that start with import "server-only";.
  • Keep .env, .env.local and .env.*.local in .gitignore. Commit .env.example with variable names and harmless placeholders only.
  • Use the platform's secret store in production: Vercel or Netlify environment variables, wrangler secret put on Cloudflare, Firebase or Google Secret Manager, GitHub Actions secrets in CI.
  • Fail fast at startup if a required secret is missing, with a message that names the variable but never prints its value.
  • Use the narrowest key: restricted Stripe keys, scoped tokens, read-only database roles for read-only jobs.
  • Know which keys are public by design: a Firebase web config apiKey or a Supabase anon/publishable key can ship to the browser, but only because Security Rules or RLS protect the data. A service-role, secret or admin key never can.

Never

  • Put a secret behind a public prefix: NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_, REACT_APP_, PUBLIC_, NUXT_PUBLIC_. These are copied into the JavaScript bundle.
  • Hardcode a key "temporarily", including in tests, seed scripts, comments or README examples. Use obvious placeholders such as sk_test_REPLACE_ME.
  • Log process.env, request headers with Authorization, full tokens or connection strings. Mask to the first 4 characters if you must log.
  • Send secrets to the client in API responses, server-rendered props or error messages.
  • Call a paid AI API directly from the browser with your key. Proxy it through your server with auth and rate limits.

If a secret leaked

  1. Rotate first in the provider dashboard; the old value is compromised the moment it was pushed or shipped.
  2. Update the value in every environment and redeploy.
  3. Then remove it from code and, if it was committed, from git history. Deleting the file in a new commit is not enough.
  4. Check the provider's logs and billing for use you do not recognise.

Example

// lib/stripe.ts
import "server-only";
import Stripe from "stripe";

const key = process.env.STRIPE_SECRET_KEY;
if (!key) throw new Error("Missing STRIPE_SECRET_KEY (set it in your hosting env, not in code)");
export const stripe = new Stripe(key);

Stripe webhooks and payments

Anyone can POST to your webhook URL. Until the signature is verified, the payload is a stranger's claim that someone paid.

Do

  • Verify every event with the raw request body, the Stripe-Signature header and your endpoint secret (STRIPE_WEBHOOK_SECRET):
    • Node: stripe.webhooks.constructEvent(rawBody, signature, secret).
    • Edge runtimes (Cloudflare Workers, Deno, Vercel Edge): await stripe.webhooks.constructEventAsync(...) with Stripe.createSubtleCryptoProvider().
    • Python: stripe.Webhook.construct_event(payload, sig_header, secret).
  • Read the body as raw text or bytes. In Next.js App Router use await req.text(). In Express mount express.raw({ type: "application/json" }) on the webhook route, before any JSON body parser.
  • Return 400 on a bad signature and do nothing else.
  • Make handlers idempotent: store processed event.id values (unique constraint) and skip duplicates. Stripe retries failed deliveries for days and can send the same event more than once.
  • Do not depend on event order. When state matters, re-fetch the object from the Stripe API (stripe.subscriptions.retrieve(id)) instead of trusting the event snapshot.
  • Fulfil orders, grant credits and change plans from the webhook (checkout.session.completed, invoice.paid, customer.subscription.updated), never from the success redirect page.
  • Respond 2xx quickly; move slow work to a queue or background job.
  • Create Checkout Sessions on the server with Price IDs you control. Map users to Stripe customers on the server.
  • Test locally with stripe listen --forward-to localhost:3000/api/webhooks/stripe and stripe trigger checkout.session.completed.

Never

  • JSON.parse the body and act on it without verifying the signature.
  • Accept amount, price or priceId chosen freely by the browser.
  • Log the full event payload with customer personal data, or log the webhook secret.
  • Treat "the user reached /success" as proof of payment.

Example (Next.js App Router)

import "server-only";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const body = await req.text();
  const signature = req.headers.get("stripe-signature");
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, signature!, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }

  if (await alreadyProcessed(event.id)) return new Response("ok");

  if (event.type === "checkout.session.completed") {
    const session = event.data.object as Stripe.Checkout.Session;
    await grantAccess(session.client_reference_id!, session.id);
  }

  await markProcessed(event.id);
  return new Response("ok");
}

Production UI gates

Pretty mocks are not enough. Every screen a user can reach needs a loading state, an empty state, an error state, a usable mobile layout and forms that fail safely.

Do

  • Give every data-backed view three states besides "success": loading, empty, and error, with a way to retry when a request fails.
  • Forms: visible labels, autocomplete where it helps, a disabled submit while in flight, errors next to the field, and no lost input after a failed submit.
  • Keep the primary action reachable on a narrow phone screen. No hover-only controls, no horizontal overflow of the main content.
  • Use semantic HTML (button, a, label, headings in order). Images need alt text; icon-only buttons need an accessible name.
  • Do not invent metrics, logos or testimonials on a marketing screen. If a trust signal is not real, leave it out.
  • Prefer the project's existing components and spacing. Do not drop in a new UI kit for one page.

Never

  • Ship a blank page, a hanging spinner, or a raw exception as the only failed state.
  • Submit a form with no server-side check because the button looked validated.
  • Block the whole app on a single widget failing to load.

Example (empty, error and loading, not just the table)

export function ProjectList({ state }: { state: ListState }) {
  if (state.status === "loading") return <p>Loading your projects…</p>;
  if (state.status === "error") return <p role="alert">Could not load projects. <button onClick={state.retry}>Try again</button></p>;
  if (state.items.length === 0) return <p>No projects yet. <a href="/new">Create the first one</a>.</p>;
  return <ul>{state.items.map((p) => <li key={p.id}><a href={`/projects/${p.id}`}>{p.name}</a></li>)}</ul>;
}
<!-- END blitzhash-vibe-coding-rules -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.