Works with the AI Agents you already use
Writing Secure Code — Client, Server & Browser Boundary
Writes code that is secure by construction: injection-proof queries, safe rendering, sessions, CSRF/CORS/CSP and authZ.
Free
Writing Secure Code — Client, Server & Browser Boundary
Example session with this skill installed
I'm adding invoice notes to our app. Express 4 + node-postgres, cookie sessions via express-session (req.session.userId, req.session.tenantId), multi-tenant. Can you make this safe before I open the PR?
// src/routes/invoices.js
router.get('/invoices/:id', requireLogin, async (req, res) => {
const { rows } = await db.query(`SELECT * FROM invoices WHERE id = ${req.params.id}`);
if (!rows[0]) return res.status(403).json({ error: 'forbidden' });
res.json(rows[0]);
});
router.post('/invoices/:id/notes', requireLogin, async (req, res) => {
await db.query('UPDATE invoices SET note = $1 WHERE id = $2', [req.body.note, req.params.id]);
res.redirect(req.query.next || '/invoices');
});
// src/client/invoice-view.js
notesEl.innerHTML = invoice.note;
- Read your context and instructions
- Compiled the writing secure code
Summary. The change crosses four trust boundaries: browser→server (:id, note, next), server→database, one tenant's data→another tenant's request, and one user's note→another user's screen. Every one of them has a defect:
- SQL injection in the read.
- No tenant scoping on the read or the write (BOLA).
- A
403that confirms the invoice exists. - An open redirect.
- Stored XSS through
innerHTML. SELECT *sends every column to the client.
The fix below keeps the feature's behavior and changes only the attack surface. Nothing here was executed. The tests are written but not run.
Trust boundaries and the rule for each
| Value the attacker controls | Crossing | Invariant | Fix |
|---|---|---|---|
req.params.id | server→database | Data never becomes code | Bound parameter ($1), plus shape validation |
req.params.id (another tenant's ID) | tenant→tenant | The server decides | AND tenant_id = $2 from the session, in the same statement. No row → 404 |
req.body.note | user→other users' screens | Encode late | Store raw. Render as text with textContent, because notes are plain text, not rich content |
req.query.next | redirect target | Fail closed | Map to an allow-list of named destinations |
| Response body | server→client | Excessive data exposure | Explicit column list, no SELECT * |
Server
// src/routes/invoices.js
const NOTE_MAX = 2000;
const NEXT_DESTINATIONS = { list: '/invoices', dashboard: '/dashboard' };
const isInvoiceId = (v) => /^\d{1,18}$/.test(v);
router.get('/invoices/:id', requireLogin, async (req, res) => {
if (!isInvoiceId(req.params.id)) return res.status(404).json({ code: 'NOT_FOUND' });
const { rows } = await db.query(
'SELECT id, number, status, total_cents, note FROM invoices WHERE id = $1 AND tenant_id = $2',
[req.params.id, req.session.tenantId],
);
if (!rows[0]) return res.status(404).json({ code: 'NOT_FOUND' });
res.json(rows[0]);
});
router.post('/invoices/:id/notes', requireLogin, async (req, res) => {
const note = req.body?.note;
if (!isInvoiceId(req.params.id)) return res.status(404).json({ code: 'NOT_FOUND' });
if (typeof note !== 'string' || note.length > NOTE_MAX) {
return res.status(422).json({ code: 'INVALID_NOTE' });
}
const { rowCount } = await db.query(
'UPDATE invoices SET note = $1 WHERE id = $2 AND tenant_id = $3',
[note, req.params.id, req.session.tenantId],
);
if (rowCount === 0) return res.status(404).json({ code: 'NOT_FOUND' });
res.redirect(303, NEXT_DESTINATIONS[req.query.next] ?? NEXT_DESTINATIONS.list);
});
A note to the caller: next now takes a destination name (?next=dashboard), not a path. Update any link that passes a path. If you'd rather keep paths, resolve the value against your own origin with new URL(value, origin) and require the resolved origin to equal yours. A "starts with /" check isn't enough, because //evil.com and /\evil.com both resolve off-site.
Client
// src/client/invoice-view.js
notesEl.textContent = invoice.note;
If notes later become Markdown, render it to HTML and run a maintained allow-list sanitizer such as DOMPurify immediately before insertion. Markdown renderers are not sanitizers.
Abuse tests next to the happy path (test/invoices.security.test.js, supertest; not run)
it('should_return_404_when_user_reads_another_tenants_invoice', async () => {
await asTenantA.get(`/invoices/${tenantBInvoice.id}`).expect(404);
});
it('should_return_404_when_user_writes_note_on_another_tenants_invoice', async () => {
await asTenantA.post(`/invoices/${tenantBInvoice.id}/notes`).send({ note: 'x' }).expect(404);
expect((await getInvoice(tenantBInvoice.id)).note).not.toBe('x');
});
it('should_return_404_when_id_is_an_injection_payload', async () => {
await asTenantA.get('/invoices/1%20OR%201=1').expect(404);
});
it('should_redirect_to_list_when_next_is_an_external_url', async () => {
const res = await asTenantA.post(`/invoices/${ownInvoice.id}/notes?next=//evil.example`).send({ note: 'ok' });
expect(res.headers.location).toBe('/invoices');
});
it('should_store_markup_note_raw_and_render_it_as_text', async () => {
await asTenantA.post(`/invoices/${ownInvoice.id}/notes`).send({ note: '<img src=x onerror=alert(1)>' }).expect(303);
expect((await getInvoice(ownInvoice.id)).note).toBe('<img src=x onerror=alert(1)>');
// client test: render, then assert no <img> element exists and the text is shown literally
});
Each test is written to fail if its control is removed; that is by design, not verified by a run. Run them with your test command, for example npx jest test/invoices.security.test.js.
Scope audit
- Fixed in place: only the lines in this change.
- Reported, not changed:
POST /invoices/:id/notesis a cookie-authenticated state change, so it needs CSRF protection. Confirm that your existing CSRF middleware covers this route. If the app has none, that's an app-wide change for its own PR (the framework's token protection, or Fetch Metadata with anOriginfallback), not something to bolt onto this route. - Worth a look elsewhere:
requireLoginshould take identity only from the session. I didn't see its code.
Next steps
- Run the tests above, plus your existing suite.
- Update callers of
?next=to the named destinations. - Check the CSRF coverage noted above, and grep the codebase for other template-string queries (
db.query(\``) andinnerHTML =` assignments.
Connects securely to your tools. The creator never sees your data.
About this skill
Writing Secure Code is the build-time security skill: it shapes code while it is being written, so the defect never lands. It works with any language, framework or architecture (monolith, microservices, serverless, SPA, mobile or desktop). Library names in the rules are only examples of "your stack's equivalent".
Problems it solves
- String-built SQL and document-store filters that an attacker can restructure.
innerHTMLand framework raw-HTML escape hatches fed with user data.- Tokens in
localStorage, missingSameSite, reflected CORS origins. - Queries not scoped by owner (BOLA/IDOR), and
403responses that confirm an object exists. - Open redirects that pass a "starts with
/" check. - SSRF through decimal or IPv4-mapped IPv6 addresses.
- Fast password hashes, and JWTs decoded but never verified.
How it works. Five invariants underlie every rule: data never becomes code; the server decides; validate early, encode late, sanitize only rich content; secrets stay server-side; fail closed. The workflow has four steps:
- Name every trust boundary the change crosses.
- Implement the rule for each crossing from the authoritative source, and test any library- or browser-specific behavior against your own version.
- Write the abuse test next to the happy-path test.
- Run a scope audit: fix defects in the lines you change, and report the rest.
It also sets defaults for when the project hasn't decided: __Host- session cookies, backend-for-frontend for OAuth, Argon2id, and a strict nonce-based CSP.
References
client.md: every client, XSS sinks, frames and messages, mobile.browser-boundary.md: cookies, CSRF, CORS, CSP, headers.server.md: injection, authentication, tokens, authorization, SSRF, files and parsers, secrets, crypto, logging.supply-chain.md: dependencies and CI.sources.md: authorities, test-backed observations, and advice it rejects.
When it triggers. Whenever code touches user input, rendering, auth, cookies, permissions, queries, outbound URLs, uploads, secrets or a new dependency, even if nobody says "security".
Free and MIT-licensed. Part of the claude-skills-czl collection.
Source on GitHub: this skill · full repository
Language- and framework-agnostic rules, so library-specific behavior is checked by running small scripts against your versions. Abuse tests need your project's test runner. Risky rollouts (CSP, rate limits, cookies, row-level policies) follow the bundled report-only-first protocol.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Free to use
No account required to browse
Trust & safety
Security scan
Security scan passed 9 days ago
- Free with an Agensi account
- Software
Git
Permissions
File Scopes
- Reads files: yes. It reads the code being changed, the project's stack and config, its `learnings/` folder, and only the references the change touches. - Edits files: yes. It writes the secure implementation and the abuse tests next to the happy-path tests. It may add a `learnings/YYYY-MM-DD-slug.md` entry for a project-specific trap. - Shell commands: yes. It runs your test suite. When a rule depends on how a specific library or browser version behaves, it writes and runs a small script or test against the version the project uses instead of assuming. - Network access: not required. It tells the agent to implement from authoritative sources (OWASP, official framework docs); an agent with web access may consult them. Fetched content is treated as data, not instructions. - Git / GitHub: no instructions to commit, push or post to GitHub. - Rollouts: for changes that can break legitimate users (CSP, rate limits, cookie changes, row-level policies), it follows the bundled safe-remediation protocol: report-only first, staging before production.
What's inside
Frequently Asked Questions
New in Security
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Security.