Skip to content
Back to skills

Bondery Security

ASecurity

Bondery security patterns — tenant isolation, auth areas, sessions, secrets, input validation, uploads, webhooks, client trust boundaries, and deployment hardening. Use when adding authentication, authorization, API routes, secrets, uploads, webhooks, payments, sensitive data, extension bridges, or reviewing security-sensitive changes.

  • 41 stars
  • 0 votes
  • 0 copies
  • 4 views
  • Added November 24, 2026
databasesjavascriptrustgojavashellbashnodeapidatabasesecurity

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 9 files and shows the line behind each finding

Scanned November 24, 2026

npx -y skills add usebondery/bondery --skill bondery-security --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Bondery Security?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Bondery Security
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/usebondery-bondery-security/badge)](https://www.skillsdirectory.com/skills/usebondery-bondery-security)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: bondery-security
description: >
  Bondery security patterns — tenant isolation, auth areas, sessions, secrets,
  input validation, uploads, webhooks, client trust boundaries, and deployment hardening.
  Use when adding authentication, authorization, API routes, secrets, uploads, webhooks,
  payments, sensitive data, extension bridges, or reviewing security-sensitive changes.
metadata:
  version: "1.1.0"
  namespace: bondery
---

# Bondery Security

## When to use

- Implementing authentication, authorization, or session handling
- Adding or changing API routes, webhooks, or internal service calls
- Handling user input, file uploads, or HTML/markdown rendering
- Working with secrets, env vars, or client token storage
- Integrating payments (Stripe), AI tools, sync WebSockets, or third-party APIs
- Reviewing changes that touch tenant data, cookies, CORS, or extension bridges
- Planning self-hosted deployment or production hardening

Do **not** activate for routine UI refactors, copy changes, or non-security API contract work — use `bondery-api` / `bondery-ux` instead.

## Trust-boundary workflow

1. Identify which trust boundary the change crosses (browser, BFF, API, DB, extension, webhook).
2. Read the matching reference file from the decision tree below.
3. Verify auth is wired through route shells — never ad-hoc in route handlers.
4. Confirm tenant-owned Prisma queries scope by authenticated `userId`, not request input.
5. Run contextual verification commands (see below).
6. Complete the security checklist before merge.

## Non-negotiables (ranked)

1. **Tenant isolation** — `getAuth(request).client` is unscoped Prisma. Every tenant-owned query must filter by `where: { userId: user.id }` (or equivalent join). There is **no RLS** on the current API path. Foreign and nonexistent resources should normally be indistinguishable (404, not 403).
2. **Route shell auth** — Auth hooks live only in `apps/api/src/lib/platform/route-areas.ts`, mounted via `routes/register-all.ts`. Custom-auth routes (webhooks, WS tickets) must implement their own verification.
3. **JWT vs opaque bearer** — JWT-shaped bearer tokens route exclusively to OAuth JWT verification. On failure, return `null` — **never** fall back to `auth.api.getSession`.
4. **Secrets in env only** — Use `packages/helpers/src/env/manifest.ts` (`BONDERY_PRIVATE_*`, `secret: true`). No hardcoded keys, tokens, or passwords.
5. **Public clients never get secrets** — Webapp OAuth client secrets stay server-only. Mobile and extension use PKCE + state validation.
6. **CORS is not authorization** — Trusted origins (`lib/platform/trusted-origins.ts`) control browser cross-origin access, not who can read data.
7. **Webhooks verify raw bytes** — HMAC/signature validation on the exact request body before parsing (Stripe pattern in `routes/webhooks/stripe.ts`).
8. **5xx errors are sanitized** — Client sees generic message; details only in server logs (`map-to-response.ts`).
9. **AI tool arguments are untrusted** — Zod-validate and scope to user-owned domain context; model output never grants authority.
10. **No secrets or PII in logs or client bundles** — Redact tokens, cookies, passwords, and contact PII from structured logs.
11. **CSP is built in exactly one place** — Every policy comes from `@bondery/helpers/security`. No app hand-writes a directive, and `script-src` never carries `'unsafe-inline'`. `pnpm run check:security-headers` enforces both.
12. **Redis requires TLS, authentication, and a client certificate** — Redis serves TLS only, clients verify its certificate, and it requires a strong password. It also requires a client certificate from its own CA (`tls-auth-clients yes`). Redis is always the bundled Compose service. There is no external Redis: do not add a supported path for a Redis that an operator runs. Never `rejectUnauthorized: false`. There is no exception for local development. Details: [Redis: TLS and authentication](references/secrets-deployment-and-supply-chain.md#redis-tls-and-authentication-required), ADR `docs/adr/0032-redis-mtls.mdx`. `node deploy/bondery/scripts/check-compose.mjs` enforces it for Compose.
13. **Compare secrets in constant time** — Compare a caller-supplied secret, signature, or token with `constantTimeEqual()` (`apps/api/src/lib/platform/security/constant-time-equal.ts`), never `===`. The Biome plugin `biome/plugins/no-unsafe-secret-compare.grit` rejects `==`/`===` on secret-named values in server code.
14. **Stored HTML is sanitized at the API** — Contact notes are stored as HTML. Every write path (`applyContactPatch`, ZIP import, any new one) runs the value through `sanitizeNotesHtml()` (`apps/api/src/lib/notes/sanitize-notes-html.ts`), an allowlist that drops scripts, event handlers, and `javascript:`/`data:` links. Clients never sanitize on the API's behalf, and nothing renders a stored string with `innerHTML`. Any other free-text field that can carry markup gets a max length in `@bondery/schemas`. `pnpm run check:input-safety` and Biome plugin `biome/plugins/no-raw-html-sink.grit` enforce it. Details: [Contact notes](references/input-storage-and-output.md#contact-notes-stored-html).
15. **Cap uploads while they stream** — A size check after `toBuffer()` is not a limit: the bytes are already in memory. Read uploads with `readUploadedFile()` (one file) or `request.parts({ limits: { fileSize: UPLOAD_LIMITS.<name> } })`, with caps named in `UPLOAD_LIMITS` (`apps/api/src/lib/platform/config.ts`). The global multipart ceiling is small, so a new route is safe by default. Biome plugin `biome/plugins/no-uncapped-multipart.grit` rejects a multipart read with no cap. Details: [Size limits](references/input-storage-and-output.md#size-limits-cap-the-stream-not-the-buffer).
16. **Postgres requires verified TLS** — Every connection to Postgres (API pool, pg-boss, Prisma CLI, scripts, tunnelled tools) uses TLS that verifies the server (`verify-full` by default), and the bundled Postgres refuses plaintext TCP. Build every `pg` Pool, Client, and pg-boss with `...pgConnectionConfig(url)` and the Prisma CLI URL with `prismaCliUrl(url)` from `@bondery/db`; never pass `ssl` options or `sslmode` by hand, and never `rejectUnauthorized: false`. Details: [Postgres: TLS](references/secrets-deployment-and-supply-chain.md#postgres-tls-required). `check:db-connections` and `check-compose.mjs` enforce it.
17. **Object storage requires mutual TLS** — The API reaches the S3 gateway over HTTPS that verifies the server and presents its own client certificate, the `traefik-transport` job publishes Traefik's separate client certificate, and the gateway accepts only callers from the storage CA (`-tlsVerifyClientCert`). The bundled SeaweedFS nodes also accept each other only over mutual TLS (`deploy/bondery/seaweedfs/security.toml`). Create every S3 client with `createS3Client()` (`apps/api/src/lib/storage/s3-client.ts`); never `new S3Client(` elsewhere and never turn certificate checks off. Details: [Object storage: TLS](references/secrets-deployment-and-supply-chain.md#object-storage-tls-required). Biome plugin `biome/plugins/use-s3-client-factory.grit`, `check-compose.mjs`, and the release smoke enforce it.
18. **The API serves HTTPS only** — Traefik, the webapp's server side, and the healthcheck call its only listener (port 26631, TLS 1.3); development uses it too (Portless, `tailscale serve`). The webapp trusts the API CA through `trustInternalApiCa()` at startup; Traefik through the `serversTransport` that the `traefik-transport` job publishes to Traefik's file provider (Dokploy's folder, or `BONDERY_INFRA_TRAEFIK_DYNAMIC_DIR`). The public storage route also reaches SeaweedFS over verified HTTPS, for reads only and without `Cookie` or `Authorization`. There is no plain HTTP port. Never add one, never call the API over plain HTTP, and never disable certificate checks. Details: [Internal API: TLS](references/secrets-deployment-and-supply-chain.md#internal-api-tls-required). `check-compose.mjs` and the release smoke enforce it.

## Decision tree

| Task                                                  | Read                                                                                                   |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Trust boundaries, route shells, tenant isolation      | [references/security-architecture.md](references/security-architecture.md)                             |
| Better Auth, sessions, API keys, OAuth, client tokens | [references/auth-and-sessions.md](references/auth-and-sessions.md)                                     |
| Input validation, uploads, XSS, errors, public files  | [references/input-storage-and-output.md](references/input-storage-and-output.md)                       |
| Security headers, CSP, Trusted Types, CORS, reporting | [references/headers-csp-and-cors.md](references/headers-csp-and-cors.md)                               |
| Webhooks, WS, AI tools, extension/mobile bridges      | [references/integrations-and-clients.md](references/integrations-and-clients.md)                       |
| Secrets, env, deploy, Redis, supply chain             | [references/secrets-deployment-and-supply-chain.md](references/secrets-deployment-and-supply-chain.md) |
| Security review process, severity, false positives    | [references/review-playbook.md](references/review-playbook.md)                                         |

Full index: [references/README.md](references/README.md).

Cross-skill owners: API contracts → `bondery-api`; UI error display → `bondery-ux`; Prisma schema/migrations (classic) → `bondery-database` (Prisma Next → `prisma-next-*` via `bondery-database/references/prisma-skills.md`); generic Postgres indexes/RLS (legacy stack) → `supabase-postgres-best-practices`; E2E auth flows → `bondery-e2e-tests`; policy/subprocessor disclosure accuracy → `bondery-legal`.

## Verification commands

Run only what applies to the change:

```bash
# Route auth wiring + OpenAPI area audit
pnpm run check:types -w api          # includes check-route-security

# OAuth / auth integration (optional; Postgres + migrate required)
pnpm run test:auth -w api

# Notes sanitizer wiring + global upload ceiling (Biome plugins run inside `biome ci`)
pnpm run check:input-safety

# Env contract drift
pnpm run env -- --check

# Compose secret isolation (self-host)
node deploy/bondery/scripts/check-compose.mjs

# Extension architecture boundaries
pnpm run check:types -w chrome-extension
```

## Known-safe patterns (not bugs)

- API Helmet with **CSP disabled** — JSON API, not HTML (`build-app.ts`)
- Webapp session cookies use **`SameSite=Lax`** — required for OAuth redirect flows
- CORS allows requests **with no `Origin` header** — non-browser clients (`trusted-origins.ts`)
- `GET /files/:bucket/*` is **intentionally unauthenticated** — public avatars/logos by UUID path
- Global rate limit with Redis required in production (`rate-limit.ts`)
- Legacy `apps/supabase-db` RLS migrations apply only to Supabase stacks — **not** the current Prisma API

## Security checklist (before merge)

- [ ] Tenant-owned Prisma queries scoped by authenticated `userId` — not request params alone
- [ ] Route mounted through correct shell (`integration`, `session`, `admin`, `internal`, or custom with explicit auth)
- [ ] `openApiArea` set on every shelled route (CI enforces)
- [ ] Input validated with Zod at route + domain layer
- [ ] New secrets added to `packages/helpers/src/env/manifest.ts` with `secret: true`
- [ ] Any Redis change keeps TLS (`rediss://`, verified certificate), password auth, and mutual TLS (`tls-auth-clients yes`), and does not add a supported external Redis
- [ ] Any new Postgres connection spreads `pgConnectionConfig(url)` (Prisma CLI: `prismaCliUrl(url)`); no hand-written `ssl` options or `sslmode`
- [ ] Any new S3 client uses `createS3Client()`; any SeaweedFS change keeps `security.toml` mutual TLS (both `[tls]` version bounds) and the HTTPS endpoint
- [ ] Any new server-side call to the API goes through `resolveServerApiBaseUrl()` (the API's HTTPS listener), never a hard-coded `http://` URL
- [ ] No secrets, tokens, or PII in logs or client bundles
- [ ] Webhook handler verifies signature on raw body before JSON parse
- [ ] Secrets, signatures, and tokens are compared with `constantTimeEqual()`, not `===`
- [ ] Upload routes enforce MIME whitelist + magic-byte validation + a size cap on the stream (`readUploadedFile` / `limits.fileSize`, named in `UPLOAD_LIMITS`), not only a check after `toBuffer()`
- [ ] Stored HTML or markdown is sanitized at the API on every write path and rendered as text or through a schema; no `innerHTML`, `dangerouslySetInnerHTML`, or `document.write` with stored or imported strings
- [ ] Free-text fields that can hold markup have a max length in `@bondery/schemas`
- [ ] `pnpm run check:input-safety` passes if an upload route, a notes write path, or `build-app.ts` changed
- [ ] 5xx responses use catalog/generic messages — no stack traces to client
- [ ] Policy headers come from `@bondery/helpers/security`; `proxy.ts` exports `config`
- [ ] `pnpm run check:security-headers` passes if a proxy or policy changed
- [ ] CORS changes go through `trusted-origins.ts` and are not treated as authorization
- [ ] Negative tests for unauthenticated, unauthorized, and cross-tenant access where applicable
- [ ] `pnpm run check:types -w api` passes if API routes changed
- [ ] Known gaps documented as review triggers, not silently assumed safe — see reference files

Files in this skill

  • SKILL.md13.4 KB
  • references/README.md1.5 KB
  • references/auth-and-sessions.md7.3 KB
  • references/headers-csp-and-cors.md13.6 KB
  • references/input-storage-and-output.md10.7 KB
  • references/integrations-and-clients.md5.2 KB
  • references/review-playbook.md10.8 KB
  • references/secrets-deployment-and-supply-chain.md31.1 KB
  • references/security-architecture.md5.6 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in databases →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.