# Bansat (بنسټ): Master Project Framework
*Bansat* is Pashto for **foundation**: lay it before you build.
**Product · Architecture · Design · Security · Privacy & Compliance · Delivery**
Created by **Muhammad Tufail Khan** ([github.com/bewithkhan](https://github.com/bewithkhan)) · Framework version **3.1** · Legal position checked **4 November 2026** against official sources, with AI assistance (not yet reviewed by a lawyer) · Supersedes *Comprehensive App Development Framework & Master Blueprint* (v1)
> **Cite as:** Khan, M. T. (2026). *Bansat (بنسټ): A blueprint-first framework for building software* (Version 3.1). https://github.com/bewithkhan/bansat
> Text and templates: **CC BY 4.0**. Code samples: **MIT**. Keep this credit when you copy, adapt or share the framework.
This is the single source of truth for **every project, new or existing**. For a new project, complete it **before any code is generated**. For an existing or live project, use the **retrofit track (Part 14)**: reverse-engineer the blueprint from what's built, triage the live risks first, then close the gaps. Either way, it turns your product into decisions that an AI coding agent (Claude, Cursor, Lovable, Bolt, Copilot) can build from without guessing. Privacy and security are built in from the first commit rather than bolted on after launch: UK GDPR, PECR, EU GDPR, Nigeria's NDPA 2023 and GAID 2025, and the EU AI Act.
> **Not legal advice.** This framework summarises the law and regulator guidance as at the date above. Its legal sections were checked against the official sources in Appendix B with AI assistance, and no lawyer has reviewed them yet. Laws change; the EU's Digital Omnibus, for example, is still being negotiated. For high-risk processing (health, children, biometrics, worker monitoring, large-scale tracking), get a qualified review before launch.
---
## Document control
| Field | Value |
|---|---|
| Project | {{APP_NAME}} |
| Blueprint version | {{0.1}} |
| Status | Draft · In review · Approved for build · Superseded |
| Accountable owner | {{NAME, ROLE}} |
| Data controller (legal entity) | {{LEGAL NAME, COMPANY NO., REGISTERED ADDRESS}}. A sole trader is personally the controller. |
| Privacy contact / DPO | {{NAME, privacy@DOMAIN}} |
| Repository | {{URL}} |
| Last updated · Next review | {{YYYY-MM-DD}} · {{YYYY-MM-DD}} |
| Framework | Bansat (بنسټ) v3.1 by Muhammad Tufail Khan, https://github.com/bewithkhan/bansat (CC BY 4.0) |
**Revision history**
| Version | Date | Author | Summary |
|---|---|---|---|
| 0.1 | {{YYYY-MM-DD}} | {{NAME}} | First draft from framework v3.1 |
**Gate approvals**
| Gate | Approver | Date | Notes |
|---|---|---|---|
| G1 Blueprint approved | | | |
| G2 Data-ready | | | |
| G3 Release candidate | | | |
| G4 Post-launch review | | | |
> **Only a person signs a gate.** An AI agent never fills in this table. With the optional G1 hook from the Bansat repo (`hooks/bansat-g1-guard.mjs`), Claude Code refuses code edits until the G1 row names an approver and a date.
### What changed in v3.1
To re-check an existing blueprint, update its Framework row to v3.1 and run the twelve new rows of the launch-trap audit (9.26) against it.
| Area | Change |
|---|---|
| Launch traps ★ | Twelve more traps in 9.26, now 29: AI that doesn't say it's AI (EU AI Act Art. 50); Global Privacy Control ignored; biometric features without written consent (Illinois BIPA); health features without consent (Washington's My Health My Data Act); no online way to withdraw or cancel (the EU withdrawal function, from 19 Jun 2026); no legal notice; the European Accessibility Act; authorisation only in the UI or middleware; AI endpoints with no quota or spend cap; app store labels that don't match the app; card details in your own form; unsigned payment webhooks. |
| Privacy | 9.13 names the US biometric and health-data laws; 9.25 adds the EU withdrawal function to the consumer information row. |
### What changed in v3.0
To re-check an existing blueprint, update its Framework row to v3.0. If the project isn't built on Next.js and Supabase, read the profile for its stack (`stacks/`) and record any differences in Part 3. For each market the project serves, compare Part 9 with that market's entry in the law registry (`laws/`), and re-check the entry against its official sources if it was checked more than 90 days ago.
| Area | Change |
|---|---|
| Stack profiles ★ | 24 profiles say what changes from the reference stack (Next.js and Supabase) on seven backend frameworks, six frontend and full-stack ones, four mobile platforms and seven no-code or backend-as-a-service platforms. The skill loads only the one a project uses (`stacks/`). |
| Law registry ★ | 120 jurisdictions: 62 full entries with every obligation and 58 basic entries with the main laws and the regulator. Every claim cites an official source, 2,944 URLs in all (`laws/`). |
| Law Watch | A weekly watch of 105 official sources for 46 full entries. An AI verify task drafts each update with its sources, and a person reviews every change (`watch/`). |
| Law tracker | A page for every jurisdiction on the site, grouped by region, with a feed of changes and no cookies or trackers. |
### What changed in v2.4
To re-check an existing blueprint, update its Framework row to v2.4; copy the new rules into your agent rules file (12.1); run Day-0 triage T11 (14.2) on live projects; check the new launch-gate items, two of them blocking (Part 13); and change any reference to Day-0 triage T11 "Was anything exposed?" to T12.
| Area | Change |
|---|---|
| Breach casebook ★ | 20 documented incidents and regulators' decisions from 2025 and 2026, each mapped to the checks that catch its class of failure (Appendix F). |
| AI coding agents ★ | The agent works with development keys only, asks before destructive commands, never switches off its own approval prompts, and treats text it reads in tool results, issues and error reports as data (12.1, T-13, T-14, Day-0 triage T11). |
| CI/CD and connected apps | Pinned actions, read-only workflow tokens, trusted publishing with 2FA and aged dependency updates; integration tokens and third-party app grants (7.4, T-15, T-16). |
| Launch gate | Three new checks, two of them blocking: no default passwords or test accounts, no open data stores, and agent and CI credentials (Part 13). |
| Other checks | No default passwords or test accounts at launch (7.1); nothing that stores data open to the internet (7.4); backups kept apart (5.7); report triage (7.6); credible claims treated as possible breaches (9.20); passkeys or MFA for special category data (9.13); leavers' access removed the same day (7.4); uploaded code never run outside a sandbox (T-07); secrets stored as write-only values (7.4); agents in AI features get the least access that works (8.4). |
### What changed in v2.3
To re-check an existing blueprint, update its Framework row to v2.3, answer the delivery questions (0.4) and record the method you choose in an ADR.
| Area | Change |
|---|---|
| Delivery questions ★ | Eight questions on team size, teams, how settled the requirements are, what's fixed, the contract, evidence needs, the kind of work and any method already in use (0.4). |
| Choosing a method ★ | A picker recommends an outer method for approvals, when one is needed, and an inner method for the build. It's hybrid by default, and the choice goes in an ADR (11.7). |
| Method profiles | Scrum, Kanban, stage gates (the PRINCE2® method and the *PMBOK® Guide*), Shape Up, a solo loop and scaled methods, each showing where G0–G4 and Bansat's documents fall (Appendix E). |
| Toolkit | RACI, RAID log, stakeholder map, status report, change request, a Mermaid timeline, and forecasting from throughput, each with the way it usually goes wrong (11.8). |
| UK regulator (v2.3.1) | The Information Commission took over from the ICO on 30 September 2026 (9.1). |
### What changed in v2.2
To re-check an existing blueprint, update its Framework row to v2.2 and add the new research rule to your agent rules file (12.1). The rows marked ★ change how you work.
| Area | Change |
|---|---|
| Research first ★ | Before building anything new, look at how others have done it: official docs, GitHub repositories and issues, Stack Overflow. Note the problems they hit, then reuse, adapt or build, and say why (12.1, 12.2 step 0, 12.3, the ADR template in 4.1, Definition of Ready in 11.2). |
| Prompts ★ | New prompts: Research first, Logic first and Full audit. The Debug prompt now carries the whole method on its own: 5–7 possible sources, distilled to 1–2, with logs to confirm before any fix (12.4). |
| App flow | A navigation map (screen → action → next screen, and the state each failure shows) sits alongside the journey diagram (10.1, 10.3). The screen template adds Layout and Actions lines (10.4). |
| Design brief | A look-and-feel brief to fill in before choosing tokens (10.5). |
| Diagrams | An authentication flow based on the OWASP cheat sheets (7.1), and an entity-relationship diagram of the reference schema (5.3). |
| UI states | The typed pattern now covers forms as well: validation (S9) and success (S10) (10.7). |
| Privacy test ★ | The "Reject all" check now records requests from the start, so a leak fired by the click itself fails it (9.9). Copy the new version into your tests. |
| Tested code | The framework is split into modules (`framework/` in the repo) and this file is generated from them. The code samples run in CI from `examples/`, and CI fails if a sample in the text and its tested copy differ. |
### What changed in v2.1
From reviewer feedback ([issue #1](https://github.com/bewithkhan/bansat/issues/1)). To re-check an existing blueprint, update its Framework row to v2.1 and look at the rows marked ★.
| Area | Change |
|---|---|
| Gates | Described as instructions the agent follows. An optional Claude Code hook makes G1 a hard stop, and only a person may sign a gate (Document control). |
| Data access ★ | The rule is now "enforce per-user and per-tenant access at the data layer, with RLS where the database supports it" (5.4, 7.2, 9.26, Part 13, 14.2). Databases without RLS, such as MySQL, use scoped queries and policies with the same isolation tests. |
| Server entry points ★ | Authorisation is re-checked in every server entry point (Server Action, route handler, controller, function), not only in Server Actions (12.1). |
| Your process | A project's own rules, `CLAUDE.md` workflow and planning stages take priority; this framework fills the gaps (How to use, item 7). |
| Legal review | The header and the disclaimer say how the law was checked, and that no lawyer has reviewed it yet. |
### What changed from framework v1
| Area | v1 | v2 |
|---|---|---|
| Scope | 8 sections | 15 parts + 4 appendices: intake, non-functional requirements, security, AI, privacy & compliance, testing & operations, agent rules, launch gate, retrofit track, stack profiles |
| Existing projects | Not covered | Retrofit track (Part 14): Day-0 triage for live apps, reverse-engineering the blueprint from code, a gap register with deadlines, keeping blueprints current, and a portfolio register. Stack profiles (Appendix D) cover PWAs, mobile, wearables, admin/CRM tools, research prototypes, websites and AI prototypes. |
| Schema | Prisma with `url = env(...)` in the schema | Prisma 7 rejects `url` in the schema, so the connection now lives in `prisma.config.ts`. Adds consent, rights-request, suppression, audit and AI-usage tables, snake_case mapping, indexes and length limits. Fixes the `creator` relation that blocked account deletion. Adds tested RLS policies. |
| Colours | Indigo-500 `#6366F1` as primary | White on `#6366F1` is 4.47:1 and `#6366F1` on near-black is 4.43:1, so both fail WCAG AA (4.5:1). Buttons now use indigo-600 and links on dark use indigo-400. Zinc-950 is corrected to `#09090B` (`#0A0A0A` is neutral-950). |
| UI states | 10 states | 10 core + 7 extended states, a per-screen state matrix, a typed implementation pattern and an acceptance test for each state |
| Debugging | 5 steps | 8 steps with a stop rule and a mandatory regression test |
| Plan | 5 phases | 9 phases with exit criteria; compliance work starts in Phase 0 |
| Stack | Fixed versions (Next.js 15, gpt-4o-mini) | Versions are chosen and pinned per project in an ADR, because they age |
---
## Contents
- [How to use this blueprint](#how)
- [Part 0 — Project intake & risk classification](#p0)
- [Part 1 — Product requirements (PRD)](#p1)
- [Part 2 — Non-functional requirements](#p2)
- [Part 3 — Technical requirements & architecture (TRD)](#p3)
- [Part 4 — Architecture decision records (ADRs)](#p4)
- [Part 5 — Data architecture](#p5)
- [Part 6 — API & integration contract](#p6)
- [Part 7 — Identity, access & security](#p7)
- [Part 8 — AI & LLM features](#p8)
- [Part 9 — Privacy, data protection & compliance](#p9)
- [Part 10 — Experience design: flows, design system, accessibility, UI states](#p10)
- [Part 11 — Delivery plan, quality & operations](#p11)
- [Part 12 — AI coding agent operating manual](#p12)
- [Part 13 — Launch readiness gate](#p13)
- [Part 14 — Existing & live projects: retrofit track and keeping every blueprint current](#p14)
- [Appendix A — Templates](#appa) · [Appendix B — References](#appb) · [Appendix C — Glossary](#appc) · [Appendix D — Stack & project-type profiles](#appd) · [Appendix E — Delivery method profiles](#appe) · [Appendix F — Breach casebook](#appf)
---
## How to use this blueprint
**Pick your track first:**
| Your project | Track | Start at |
|---|---|---|
| New: an idea or a throwaway prototype | New project | Part 0, then gates G0–G4 |
| Existing: built, with no real users yet | Retrofit, light | Part 14.3 |
| Live: real users, customers or a client | Retrofit, urgent | **Part 14.2 Day-0 triage (within 48 hours)** |
Then add the matching **stack profile** from Appendix D (web, PWA, mobile, wearable, admin/CRM, research, website, AI prototype, hardware), and the **delivery method** from Appendix E, chosen in 11.7.
1. **Copy, don't edit the master.** For each project, copy this file to `docs/BLUEPRINT.md` in the repo, and keep the "Framework" credit row in Document control (CC BY 4.0 attribution). Paste Part 12.1 into `CLAUDE.md`, `AGENTS.md` or `.cursor/rules` (or your Lovable/Bolt project knowledge) so every agent session follows it.
2. **Fill every `{{placeholder}}`.** Before each gate, search the file for `{{`. Nothing in scope may remain.
3. **Respect the tags.** Complete `[CORE]` sections for every project. Complete `[IF: …]` sections when Part 0 says they apply; otherwise write `N/A, because …`.
4. **Use the keywords.** **MUST**, **SHOULD** and **MAY** follow RFC 2119.
5. **Trace everything.** Requirements carry IDs (`FR-`, `NFR-`, `BR-`, `SCR-`, `API-`, `DATA-`, `ROPA-`, `ADR-`, `RISK-`, `TEST-`). Every `FR` links to its screens, endpoints, data, tests and processing record (Appendix A6).
6. **Treat examples as illustrations.** The worked example throughout is **TaskFlow AI** from v1: a team workspace with AI standups. Replace it with your own content.
7. **Your project's rules win.** If the repo already has its own planning stages, templates or agent workflow (in `CLAUDE.md`, `AGENTS.md` or its docs), follow those. Map these gates onto its stages, use this framework to fill the gaps, and note where the two differ.
8. **Research before you build.** For anything new, look at how others have done something similar (official docs, GitHub repositories and issues, Stack Overflow) and the problems they hit, before making assumptions or building from scratch (12.2, step 0).
### Where the usual planning documents live
Many builders plan with six documents plus decision records and prompts. In Bansat they're parts of one blueprint, so they can't contradict each other:
| Document | Where it lives |
|---|---|
| Product requirements (PRD) | Part 1, with the numbers in Part 2 |
| Technical requirements (TRD) | Part 3 |
| Architecture decision records (ADRs) | Part 4 |
| App flow | 10.1 journey diagram, 10.2 key flows, 10.3 screen inventory and navigation map |
| UI/UX design brief | 10.4 screen specs, 10.5 look-and-feel brief and design system, 10.6 accessibility, 10.7 UI states |
| Backend schema | Part 5: data dictionary, entity-relationship diagram, schema, access rules; Part 6: API |
| Implementation plan | 11.1 phased plan, with 11.2 Definition of Ready and Done |
| Delivery method and project management | 0.4 delivery questions, 11.7 choosing a method, 11.8 toolkit (RACI, RAID, status, change requests, timeline), Appendix E profiles |
| Prompts for agents | 12.4: research first, logic first, feature, debug, full audit and more |
### Depth by risk tier
| Tier (from Part 0) | Minimum to complete before build |
|---|---|
| **Low**: no accounts, little personal data | Parts 0, 1.1–1.5, 3.1, 9.8–9.9, 9.26, 10.7, 11.7 and 13 |
| **Medium**: accounts, analytics, email, B2B | Every `[CORE]` section plus the `[IF]` modules that apply |
| **High**: health or biometric data, children, location or worker monitoring, significant automated decisions, large scale | Everything, plus a full DPIA (9.21) and an independent privacy and security review before G3 |
### Gates
| Gate | Unlocks | Exit criteria |
|---|---|---|
| **G0 Idea** | Writing this blueprint | Part 0 and 1.1–1.3 drafted |
| **G1 Blueprint approved** | Production code (throwaway spikes are allowed earlier) | All in-scope sections complete; ADRs accepted; DPIA screening done; no `{{` left in scope |
| **G2 Data-ready** | Collecting **any** real personal data, including waitlists and beta testers | Privacy notice live; RoPA and lawful bases recorded; consent capture working; processor DPAs signed; data-access isolation tests (RLS where supported) passing; ICO fee paid (UK controller) |
| **G3 Release candidate** | Public launch | Part 11 testing complete; every Part 13 item green, or N/A with a reason |
| **G4 Post-launch** | The next major scope | 30-day review: metrics against targets, incidents, rights requests, compliance calendar running |
> A "coming soon" page with an email box is already processing personal data, so G2 applies to it.
---
## Part 0 — Project intake & risk classification `[CORE]`
### 0.1 Snapshot
| Field | Answer |
|---|---|
| One-line description | {{e.g. "TaskFlow AI turns a team's task board into a daily standup in one click."}} |
| Problem, and who has it | {{ }} |
| Platforms | {{Web · PWA · iOS · Android · Desktop · Wearable/IoT}} |
| Markets (where users are) | {{e.g. UK, Ireland, Nigeria}} |
| B2C, B2B or internal | {{ }} |
| Target launch · Budget cap | {{date}} · {{£/month infrastructure, £/month AI}} |
### 0.2 Screening questions
Answer every question. Each **Yes** switches on the linked module.
| # | Question | Y/N | If yes, complete |
|---|---|---|---|
| Q1 | Will you collect any personal data at all (emails, names, IP addresses in logs, analytics or device IDs)? | | Part 9. The answer is practically always yes. |
| Q2 | Users in the **UK**? | | UK GDPR, DPA 2018, PECR (9.1) |
| Q3 | Users in the **EU/EEA** (you offer them services or monitor their behaviour)? | | EU GDPR, ePrivacy, EU representative check, AI Act |
| Q4 | Users in **Nigeria**? | | NDPA 2023 + GAID 2025; major-importance check (9.2) |
| Q5 | Users in the **US** or elsewhere? | | COPPA, CAN-SPAM, state laws; add rows to 9.1 |
| Q6 | Could anyone **under 18** use it, even if it isn't aimed at them? | | 9.12 Children |
| Q7 | **Health** or wellbeing, biometric, genetic, sex life or orientation, religion, ethnicity, political or trade-union data? | | 9.13 Special category data; DPIA |
| Q8 | **Precise location** or continuous tracking? | | 9.14; DPIA |
| Q9 | Monitoring **workers** (employees, drivers, contractors)? | | 9.14; DPIA |
| Q10 | **Wearables, IoT** devices or sensors? | | 9.13 and 9.14; device security |
| Q11 | **AI/LLM** features, or **automated decisions** about people? | | Part 8; 9.22 |
| Q12 | Can users share **content with other users** (comments, chat, uploads, profiles)? | | 7.3 abuse threats; Online Safety Act screen (9.1) |
| Q13 | **Payments** or subscriptions? | | 1.8; 9.25 (PCI scope, consumer law) |
| Q14 | **Marketing** email, SMS or push; a waitlist or newsletter? | | 9.11 |
| Q15 | Analytics, heatmaps, **session replay**, ad pixels, A/B tests? | | 9.8–9.10 |
| Q16 | Third-party **fonts, CDNs, embeds** or widgets (maps, video, chat, CAPTCHA)? | | 9.9 |
| Q17 | Distribution through **app stores**? | | 9.25 platform rules |
| Q18 | B2B: will customers put **their own people's data** into it, so you act as their processor? | | 9.2 processor duties; customer DPA |
| Q19 | Selling to the **public sector, NHS or enterprises**? | | 7.4 assurance (Cyber Essentials, ISO 27001 or SOC 2); NHS DTAC and DSPT (9.13) |
| Q20 | Could processing be **large-scale** (thousands of people, or sensitive data in any volume)? | | DPO assessment (9.2); DPIA |
### 0.3 Risk tier
- **High** if Q7, Q8, Q9 or Q10 is yes; if children are a target or likely audience (Q6); or if Q11 involves significant decisions about people. A DPIA is then mandatory and an external review is recommended.
- **Medium** if you have accounts, analytics, marketing or a B2B processor role.
- **Low** otherwise.
**Result:** Tier {{Low / Medium / High}} · DPIA required {{Y/N}} · Modules in scope: {{list}}
### 0.4 Delivery questions
These decide how the project runs (11.7). There are no wrong answers, and you can change the method later with an ADR.
| # | Question | Answer |
|---|---|---|
| D1 | How many people will build it? | {{1 · 2–10 · 11–50 · more than 50}} |
| D2 | How many teams work on the same product? | {{1 · 2–8 · more than 8}} |
| D3 | How settled are the requirements? | {{fixed and well understood · mostly known · still being discovered}} |
| D4 | What's fixed: the date, the budget or the scope? | {{any of them, or none}} |
| D5 | Who's paying, and how? | {{your own product · a client, fixed price · a client, paid for time · an internal team}} |
| D6 | Does anyone need formal evidence of control, such as a regulator, an auditor, a public-sector buyer or a client's project office? | {{Y/N}} |
| D7 | Is the work mostly planned features, or a stream of requests and fixes? | {{planned features · a stream · both}} |
| D8 | Does the organisation already use a method you're expected to follow? | {{its name, or no}} |
**Result:** Outer method {{the organisation's method, E3, or none}} · Inner method {{…}} (11.7) · Reason {{one sentence}} · Recorded in ADR-{{NNN}}
---
## Part 1 — Product requirements (PRD) `[CORE]`
### 1.1 Executive summary
| Field | Content |
|---|---|
| App name | {{ }}. *Example: TaskFlow AI* |
| Vision | {{ }}. *Example: a streamlined, intelligent workspace that helps remote teams triage tasks and run daily standups from contextual AI summaries, with dependable error handling and state management.* |
| Target audience | {{ }}. *Example: remote engineering and product teams of 5–50 people.* |
| Value proposition | {{What gets faster, cheaper or safer for them, and by how much?}} |
| Business model | {{Free · Freemium · Subscription · One-off · Internal tool}} |
### 1.2 Problem statement & evidence
- **Who** has the problem: {{ }}
- **Current workaround** and its cost: {{ }}
- **Evidence** (interviews, data, sign-ups, support tickets): {{ }}
- **Why now**: {{ }}
### 1.3 Goals, non-goals & success metrics
| Metric | Definition | Target | How it's measured |
|---|---|---|---|
| Activation | % of new workspaces that create ≥ 3 tasks within 24 h | {{≥ 40%}} | Server-side counts |
| Core value | % of active teams generating ≥ 3 standups per week | {{≥ 30%}} | Server-side counts |
| Retention | Week-4 workspace retention | {{≥ 25%}} | Aggregate analytics (9.10) |
| Reliability | Monthly availability | {{≥ 99.5%}} | Uptime monitor |
> **Guide:** Prefer server-side counts and aggregate analytics. A metric that needs invasive tracking is a design smell (9.10).
**Non-goals** (deliberately out of scope for this release): {{e.g. native mobile apps, public task sharing, time tracking}}
### 1.4 Users, personas & roles
| Persona | Context | Goals | Frustrations | Accessibility needs | Data sensitivity |
|---|---|---|---|---|---|
| {{Team lead "Amara"}} | {{Runs a 12-person remote team}} | {{Standup in 2 minutes}} | {{Chasing updates}} | {{Keyboard-heavy user}} | {{Work data, names}} |
Roles map to the permission matrix in 7.2: {{OWNER, ADMIN, MEMBER}}.
### 1.5 Features & prioritisation (MoSCoW)
| ID | Feature | Priority | Release | Personal data? | Notes |
|---|---|---|---|---|---|
| FR-001 | Authentication & workspace setup (Google OAuth, magic link) | Must | MVP | Yes | Age check and consent capture at sign-up (9.7, 9.12) |
| FR-002 | Task triage board: Kanban with AI tagging, priority and assignee suggestions | Must | MVP | Yes | Non-drag way to move cards (WCAG 2.5.7) |
| FR-003 | AI daily standup generator, exported as Markdown | Must | MVP | Yes | Part 8 |
| FR-004 | Real-time threaded comments with optimistic updates | Should | MVP | Yes | Sanitised Markdown; abuse threats (7.3) |
| FR-005 | Organisation & member management | Must | MVP | Yes | Permission matrix (7.2) |
| FR-006 | Privacy centre: export, delete, consents, marketing preferences, complaints | Must | MVP | Yes | **Required for any app with accounts** (9.15) |
| FR-007 | Cookie & consent management | Must | MVP | Yes | **Required if anything non-essential runs** (9.8) |
### 1.6 User stories & acceptance criteria
Write one block per requirement, using this template.
```text
FR-003 — Generate a daily standup
As a team member, I want a one-click summary of yesterday's completed tasks, blockers and today's
commitments, so that standups take two minutes.
Acceptance criteria
Scenario: Summary generated
Given I am a member of workspace W with tasks completed in the last 24 h
When I select "Generate standup"
Then a structured Markdown summary appears within 15 s, labelled "AI-generated — check before sharing"
And I can copy it or download it as a .md file
Scenario: Nothing to summarise → Empty state (S1)
Given no tasks changed in the last 24 h
Then I see "Nothing to summarise yet" and a link back to the board
Scenario: AI provider slow or down → Slow network (S5), then Error (S3)
Given the provider has not responded after 5 s
Then I see "Still working…" with Cancel
And after 30 s I see an error with Retry, and none of my input is lost
Scenario: Daily limit reached → Rate limited (S13)
Given my workspace has used today's AI quota
Then I see when the quota resets and nothing is charged
Traceability: SCR-07 · API-003 · DATA tasks, ai_generations · TEST-E2E-012 · ROPA-03
Privacy: task text is minimised before it is sent to the AI provider (8.2); no special category data
```
### 1.7 Business rules
| ID | Rule |
|---|---|
| BR-01 | A workspace always has at least one OWNER. The last owner cannot leave or be demoted. |
| BR-02 | {{Free plan: maximum 5 members and 20 AI standups per month}} |
| BR-03 | Deleting a workspace starts a 30-day recovery window, then hard-deletes everything (5.6). |
### 1.8 Monetisation & pricing `[IF: payments]`
Plans and limits: {{ }} · Trial: {{ }} · Billing provider: {{e.g. Stripe Checkout or Billing}} · VAT: {{ }} · Cancellation and refunds: {{ }} (consumer law, 9.25) · Failed payments: {{retries, grace period}}
### 1.9 Assumptions, constraints & dependencies
| Type | Statement | Impact if wrong | Owner |
|---|---|---|---|
| Assumption | {{Teams already use Google Workspace}} | {{Add email/password sign-in}} | {{ }} |
| Constraint | {{Data must stay in the UK/EU}} | — | {{ }} |
| Dependency | {{AI provider API availability}} | {{Feature-flag the AI off; the app still works}} | {{ }} |
### 1.10 Out of scope
{{Explicit list. Anything not listed here or in 1.5 is out of scope by default.}}
---
## Part 2 — Non-functional requirements `[CORE]`
Every NFR needs a number and a way to verify it. Defaults below are sensible starting points; change them deliberately.
| ID | Category | Requirement | Target (default) | Verified by |
|---|---|---|---|---|
| NFR-PERF-01 | Performance | Core Web Vitals at p75 on mobile | LCP ≤ 2.5 s · INP ≤ 200 ms · CLS ≤ 0.1 | Lighthouse CI + real-user monitoring (aggregate) |
| NFR-PERF-02 | Performance | API latency (excluding AI calls) | p95 ≤ {{300}} ms reads, ≤ {{800}} ms writes | APM / logs |
| NFR-PERF-03 | Performance | JavaScript on the initial route | ≤ {{170}} KB gzipped | Bundle analyser in CI |
| NFR-AVL-01 | Availability | Monthly uptime | {{99.5%}} (≈ 3.6 h downtime per 30 days) | Uptime monitor |
| NFR-REL-01 | Recoverability | Backup and restore | RPO ≤ {{24 h}} (≤ 5 min with point-in-time recovery) · RTO ≤ {{4 h}} | Quarterly restore drill |
| NFR-SCL-01 | Scalability | Load | {{N}} concurrent users, {{M}} records, no degradation | Load test before launch |
| NFR-SEC-01 | Security | Verification baseline | OWASP ASVS Level 1 for all; **Level 2** when processing sensitive data or payments | Security review (7.4) |
| NFR-PRIV-01 | Privacy | Privacy by default | Zero non-essential cookies or third-party requests before consent | Playwright test (9.9) |
| NFR-PRIV-02 | Privacy | Rights requests | Completed within 30 days | DSR log (9.15) |
| NFR-PRIV-03 | Privacy | Data residency | Primary data stored in {{UK/EU region}} | Infrastructure review |
| NFR-A11Y-01 | Accessibility | Standard | WCAG 2.2 AA | axe in CI + manual audit (10.6) |
| NFR-CMP-01 | Compatibility | Browsers and devices | Last 2 versions of Chrome, Edge, Firefox and Safari; iOS {{17+}}; Android {{10+}}; viewports from 320 px | Device test matrix |
| NFR-I18N-01 | Localisation | Locale handling | {{en-GB}} default; times stored in UTC and shown in local time; formatting through `Intl` | Unit tests |
| NFR-OBS-01 | Observability | Error alerting | Alert when the error rate exceeds {{2%}} over 5 min | Alert test |
| NFR-MNT-01 | Maintainability | Code quality | TypeScript strict; zero lint errors; ≥ {{80%}} coverage of domain logic | CI |
| NFR-COST-01 | Cost | Budgets | Infrastructure ≤ {{£X}}/month; AI ≤ {{£Y}}/month, with alerts at 50/80/100% | Billing alerts |
---
## Part 3 — Technical requirements & architecture (TRD) `[CORE]`
### 3.1 Stack decisions
Pin exact versions at project start (lockfile plus this table), and change them only through an ADR. The reference stack below is the default for web projects.
| Layer | Choice (reference default) | Pinned version | Why | ADR |
|---|---|---|---|---|
| Framework | Next.js (App Router) + React + TypeScript `strict` | {{ }} | One codebase for UI and server; Server Components | ADR-001 |
| Styling & motion | Tailwind CSS · Motion (formerly Framer Motion), honouring `prefers-reduced-motion` | {{ }} | Speed and consistency | — |
| Server logic | Server Actions for internal mutations · Route Handlers for webhooks and the public API | — | Typed end to end | ADR-001 |
| Database | PostgreSQL on Supabase in a {{UK/EU}} region · Prisma ORM · RLS on every table | {{ }} | Relational data, type safety, defence in depth | ADR-002, ADR-005 |
| Auth | Supabase Auth: Google OAuth + magic link; MFA for owners and admins | — | Managed, standards-based | ADR-002 |
| Validation & forms | Zod (schemas shared by client and server) · React Hook Form | {{ }} | One source of truth for input rules | — |
| Client state | TanStack Query for server state · Zustand for UI state (e.g. active filters) | {{ }} | Caching, retries, offline handling | — |
| AI | {{Provider}} through the Vercel AI SDK · model `{{pinned model ID}}` | {{ }} | Structured output, streaming | ADR-006 |
| Email | {{Provider}} with separate transactional and marketing streams | — | Deliverability and compliance | ADR-007 |
| Hosting | Vercel, functions region {{`lhr1` London / `fra1` Frankfurt}} | — | Preview deployments | ADR-005 |
| Monitoring | {{e.g. Sentry}} (EU data region, PII scrubbing, replay off) | — | Error visibility | 9.10 |
| Analytics | {{Privacy-first, aggregate tool}} | — | Measure without tracking people | 9.10 |
| Testing | Vitest · Playwright · @axe-core/playwright | {{ }} | Covers Part 11 | — |
> **Mobile or other stacks** (Flutter, React Native, native): keep this table's structure and add app-store privacy labels, account deletion (9.25), SDK inventories (9.8) and OS permission flows (9.14).
### 3.2 Environments
| Env | Purpose | Data allowed | Access | Secrets |
|---|---|---|---|---|
| Local | Development | Synthetic seed data only | Developer | `.env.local` (git-ignored) |
| Preview | One per pull request | Synthetic only | Team (deployment protection on) | Preview-scoped variables |
| Staging | Release candidate testing | Synthetic, or anonymised extracts with written approval | Team | Staging project and keys |
| Production | Live | Real | Least privilege, MFA | Production project and keys |
**Rule:** real personal data never leaves production. Each environment has its own Supabase project and keys.
### 3.3 System context
```mermaid
flowchart LR
user([User's browser or app])
subgraph svc [Your service]
web[Next.js app on Vercel UI, Server Actions, Route Handlers]
jobs[Scheduled jobs retention, deletion, email]
end
subgraph proc [Processors in a UK or EU region]
db[(Supabase Postgres RLS on every table)]
auth[Supabase Auth]
store[(Private storage signed URLs)]
end
ai[AI provider DPA, no training on your data]
mail[Email provider transactional and marketing streams]
mon[Error monitoring PII scrubbed]
ana[Analytics or replay consent-gated]
user -- HTTPS --> web
web --> auth
web --> db
web --> store
web -- minimised prompts --> ai
jobs --> db
jobs --> mail
web -. errors .-> mon
user -. only after consent .-> ana
```
### 3.4 Data flows & trust boundaries
| Flow | From → To | Personal data | Boundary crossed | Protection |
|---|---|---|---|---|
| Sign-up | Browser → Auth | Email, name, IP | Internet → processor | TLS; rate limits; no third-party scripts on auth pages |
| Task CRUD | Browser → Server Action → DB | Task content, names | Client → server → DB | Zod validation; authorisation check; RLS |
| AI standup | Server → AI provider | Minimised task text | You → third country | DPA; redaction; transfer mechanism (9.17) |
| Email | Job → email provider | Email address, name | You → processor | DPA; suppression list; one-click unsubscribe |
| Errors | App → monitoring | Stack traces, IDs | You → processor | PII scrubbing; no request bodies |
### 3.5 Repository structure
```text
app/ routes: (marketing)/, (auth)/, (app)/w/[slug]/…, api/
components/ui/ primitives (button, input, dialog …)
components/states/ the reusable UI-state components (10.7)
components/features/ feature components
lib/schemas/ Zod schemas shared by client and server
lib/server/ server-only code (import 'server-only'): data access, authorisation
lib/privacy/ consent store, script loader, redaction, export and deletion helpers
lib/ai/ versioned prompts, output schemas, evals
prisma/ schema.prisma, migrations/ · prisma.config.ts at repo root
supabase/policies/ RLS SQL (5.4) supabase/seed.sql (synthetic data)
tests/ unit/ integration/ e2e/ privacy/ a11y/ rls/
docs/ BLUEPRINT.md adr/ compliance/ (RoPA, DPIA, LIAs, registers)
```
### 3.6 Third-party services & processors register
Every service that receives personal data or runs in the user's browser **must** be listed here before it is added to the code.
| Service | Purpose | Data shared | Runs in browser? | Before consent? | Role | Location · Transfer mechanism | DPA signed | Exit plan |
|---|---|---|---|---|---|---|---|---|
| {{Vercel}} | Hosting | Request logs (IP) | No | n/a | Processor | {{EU/US · DPF + SCCs}} | {{date}} | {{ }} |
| {{Supabase}} | DB, auth, storage | All app data | Client SDK | Yes (strictly necessary) | Processor | {{eu-west-2 London}} | {{ }} | {{ }} |
| {{AI provider}} | Standups | Minimised task text | No | n/a | Processor | {{US · DPF / SCCs}} | {{ }} | {{ }} |
| {{Email provider}} | Email | Email, name | No | n/a | Processor | {{ }} | {{ }} | {{ }} |
| {{Analytics}} | Aggregate metrics | Pseudonymous events | Yes | **No** | Processor | {{ }} | {{ }} | {{ }} |
### 3.7 Configuration & secrets
| Variable | Scope | Purpose | Stored in | Rotation |
|---|---|---|---|---|
| `NEXT_PUBLIC_SUPABASE_URL` | Client (public) | Project URL | Vercel env | On project change |
| `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` | Client (public) | Publishable (anon) key. Safe only because RLS is on. | Vercel env | On leak |
| `SUPABASE_SECRET_KEY` | **Server only** | Secret / service-role key: bypasses RLS | Vercel env | Every 90 days and on leak |
| `DATABASE_URL` · `DIRECT_URL` | **Server only** | Pooled runtime connection · direct connection for migrations | Vercel env | On leak |
| `{{AI}}_API_KEY` · `{{EMAIL}}_API_KEY` | **Server only** | Provider keys | Vercel env | Every 90 days |
Rules:
- Anything prefixed `NEXT_PUBLIC_` ships to every visitor, so it must never be a secret.
- `.env*` files are git-ignored, and secret scanning (e.g. gitleaks) runs in CI.
- Each environment has separate keys.
- CI fails if the built client bundle contains a secret-key pattern.
### 3.8 Coding standards
- TypeScript `strict` with no `any` unless a comment justifies it. ESLint (including `jsx-a11y`) and Prettier run on every commit.
- Server-only modules start with `import 'server-only'`.
- Validate every input at every boundary with Zod: `.strict()` objects and a maximum length on every string.
- Errors use typed codes (6.3) that map to UI states (10.7). Never show stack traces to users.
- Logs are structured JSON with a correlation ID and no personal data (7.5).
- Store times in UTC, money in minor units (integer pence/kobo) and IDs as UUIDs.
---
## Part 4 — Architecture decision records (ADRs) `[CORE]`
### 4.1 ADR template
```text
ADR-NNN — {{Title}}
Status: Proposed | Accepted | Superseded by ADR-NNN Date: {{YYYY-MM-DD}} Review by: {{date}}
Context: {{forces, constraints, options considered}}
Prior art: {{how others solved this (docs, GitHub repos and issues, Stack Overflow, with links) and the problems they hit}}
Decision: {{what we will do: reuse, adapt or build, and why}}
Consequences: (+) {{benefits}} (−) {{costs, risks, follow-ups}}
Privacy & security impact: {{new data, vendors, transfers; RoPA/DPIA updates needed}}
```
### 4.2 Baseline ADRs (accepted unless a project overrides them)
**ADR-001 — Next.js App Router for full-stack development.** *Context:* fast iteration, good SEO and no separate backend cluster. *Decision:* Next.js App Router on Vercel. *Consequences:* (+) unified codebase and deployments. (−) Strict Server/Client Component boundaries. **Every Server Action is a public HTTP endpoint**, so each one MUST validate its input and re-check authentication and authorisation itself. Middleware or UI checks are never enough on their own.
**ADR-002 — Supabase Postgres + Prisma, with RLS as defence in depth.** *Context:* relational, multi-tenant data that needs type-safe queries. *Decision:* Prisma for server-side data access through one data-access layer (`lib/server/db/*`) that always scopes by `organizationId` and calls `assertCan()` (7.2). RLS is enabled on **every** table for any access through the Supabase client SDK. *Consequences:* (+) type safety, migrations, layered protection. (−) **Prisma connects as the table owner, which bypasses RLS**, so server code must enforce tenancy itself. Tenant-isolation tests (5.4, 11.3) cover both paths.
**ADR-003 — Mandatory UI-state architecture and systematic debugging.** *Context:* missing states and guessed bug fixes produce dead ends and regressions. *Decision:* every screen implements the applicable states from 10.7, proven by its state matrix, and all bug work follows the protocol in 12.3. *Consequences:* (+) no dead ends and verifiable fixes. (−) More upfront work per screen.
**ADR-004 — Privacy-by-default front end.** *Context:* third-party fonts, CDNs, pixels and widgets disclose visitors' IP addresses and behaviour before any consent (9.9). *Decision:* the browser contacts only first-party and strictly necessary hosts until consent is given. Fonts and libraries are self-hosted or bundled. Non-essential scripts load only through the consent-gated loader (9.7). A CSP allowlist and an automated test enforce this. *Consequences:* (+) compliant by construction, and faster pages. (−) Every new vendor goes through the register (3.6).
**ADR-005 — Data residency.** *Decision:* the primary database, storage and functions run in {{UK/EU}} regions. Any processor outside the UK/EU needs a recorded transfer mechanism (9.17). *Consequences:* (+) simpler transfers and customer trust. (−) Some vendor choices are ruled out.
**ADR-006 — AI provider & data handling.** *Decision:* use providers with a signed DPA that contractually exclude training on your data, with a stated retention period and a region choice where available. Send minimised, redacted inputs. Validate structured outputs. Pin model IDs. *Consequences:* (+) predictable cost and compliance. (−) Model upgrades need an eval run (8.5).
**ADR-007 — Email architecture.** *Decision:* separate transactional and marketing streams, with marketing sent from a subdomain (e.g. `news.{{domain}}`). A global suppression list is the source of truth, and SPF, DKIM and DMARC are set on all sending domains. *Consequences:* (+) deliverability, and unsubscribes are honoured everywhere. (−) Two templates and two configurations to maintain.
---
## Part 5 — Data architecture `[CORE]`
### 5.1 Data classification
| Class | Examples | Storage | Logs, analytics, replay, error tools | AI prompts | Access |
|---|---|---|---|---|---|
| **C0 Public** | Marketing pages, docs | Anywhere | Allowed | Allowed | Anyone |
| **C1 Internal** | Aggregate metrics, configuration | App storage | Allowed | Allowed | Team |
| **C2 Personal** | Name, email, IP, user ID, workspace content about people | Encrypted at rest; RLS | IDs only, never content | Minimised and redacted only | Least privilege |
| **C3 Sensitive** | Special category data (9.13), children's data, precise location, government IDs, financial details, credentials | Separate tables; app-level encryption where feasible; access logged | **Never** | Only with an approved DPIA | Named roles; audited |
### 5.2 Data dictionary
Every field has a reason to exist. If you can't fill the "Purpose" column, delete the field.
| Entity.field | Type | Class | Purpose | ROPA | Required | Retention | Shared with |
|---|---|---|---|---|---|---|---|
| profiles.email | text | C2 | Sign-in, service email | ROPA-01 | Yes | Life of account | Auth, email provider |
| profiles.age_status | enum | C2 | Prove the age rule was applied (9.12) | ROPA-01 | Yes | Life of account | — |
| tasks.description | varchar(10000) | C2 | Core feature | ROPA-02 | No | Life of workspace | AI provider (minimised) |
| {{ }} | | | | | | | |
### 5.3 Reference schema (Prisma)
Changes from v1:
- `snake_case` mapping, UUID columns, indexes and length limits.
- `creator` and `author` become `SetNull`, so deleting a user no longer fails or wipes team content.
- New tables: consent evidence, marketing suppressions, rights requests and complaints, audit log, and an AI usage ledger.
- The date of birth is never stored; only the age-check result is.
**Entity relationships.** The backend schema at a glance, showing keys and the fields that matter for privacy. Keep it in step with the Prisma schema below; `SetNull` relations keep team content when a person is erased.
```mermaid
erDiagram
profiles ||--o{ memberships : "has"
organizations ||--o{ memberships : "has"
organizations ||--o{ tasks : "owns"
profiles |o--o{ tasks : "creates (SetNull)"
profiles |o--o{ tasks : "is assigned (SetNull)"
tasks ||--o{ comments : "has"
organizations ||--o{ comments : "scopes"
profiles |o--o{ comments : "writes (SetNull)"
profiles |o--o{ consent_records : "gives"
profiles |o--o{ data_subject_requests : "makes"
organizations |o--o{ audit_logs : "records"
organizations ||--o{ ai_generations : "meters"
profiles {
uuid id PK "same as the auth user ID"
text email UK "C2"
enum age_status "the result, never the date of birth"
timestamp deletion_requested_at
}
organizations {
uuid id PK
varchar slug UK
timestamp deleted_at "soft delete"
}
memberships {
uuid id PK
uuid user_id FK
uuid organization_id FK
enum role "OWNER, ADMIN or MEMBER"
}
tasks {
uuid id PK
uuid organization_id FK
uuid creator_id FK "nullable"
uuid assignee_id FK "nullable"
varchar description "C2, nullable"
}
comments {
uuid id PK
uuid organization_id FK "copied from the task for simple RLS"
uuid task_id FK
uuid author_id FK "nullable"
}
consent_records {
uuid id PK
uuid profile_id FK "nullable before sign-up"
enum purpose
boolean granted
text notice_version
}
marketing_suppressions {
text email_hash PK "SHA-256, kept after erasure"
}
data_subject_requests {
uuid id PK
uuid profile_id FK "nullable"
enum type
timestamp due_at
}
audit_logs {
uuid id PK
uuid organization_id FK "nullable"
uuid actor_id "nullable"
}
ai_generations {
uuid id PK
uuid organization_id FK
int input_tokens
int output_tokens
}
```
```prisma
// prisma/schema.prisma — privacy-aware reference schema (example: TaskFlow AI)
// Conventions: snake_case tables/columns (@@map/@map), UUID keys, UTC timestamps.
// Data classes in comments: [C2] personal, [C3] sensitive — see 5.1.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql" // Prisma 7+: the connection URL lives in prisma.config.ts
}
/// One row per auth user. id = auth.users.id (set by a sign-up trigger).
model Profile {
id String @id @db.Uuid
email String @unique // [C2]
displayName String @map("display_name") // [C2]
avatarPath String? @map("avatar_path") // [C2] own storage bucket, never Gravatar
locale String @default("en-GB")
timezone String @default("Europe/London")
ageStatus AgeStatus @default(UNVERIFIED) @map("age_status") // store the result, not the DOB
ageCheckMethod AgeCheckMethod? @map("age_check_method")
ageCheckedAt DateTime? @map("age_checked_at")
lastActiveAt DateTime? @map("last_active_at") // drives inactive-account deletion
deletionRequestedAt DateTime? @map("deletion_requested_at") // starts the 30-day erasure grace period
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
memberships Membership[]
assignedTasks Task[] @relation("AssignedTasks")
createdTasks Task[] @relation("CreatedTasks")
comments Comment[]
consents ConsentRecord[]
requests DataSubjectRequest[]
@@map("profiles")
}
model Organization {
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(120)
slug String @unique @db.VarChar(60)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
deletedAt DateTime? @map("deleted_at") // soft delete; hard delete after 30 days
memberships Membership[]
tasks Task[]
comments Comment[]
auditLogs AuditLog[]
aiGenerations AiGeneration[]
@@map("organizations")
}
model Membership {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
role Role @default(MEMBER)
createdAt DateTime @default(now()) @map("created_at")
user Profile @relation(fields: [userId], references: [id], onDelete: Cascade)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
@@unique([userId, organizationId])
@@index([organizationId])
@@map("memberships")
}
model Task {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
title String @db.VarChar(200)
description String? @db.VarChar(10000) // [C2] may mention people: never sent to analytics
status TaskStatus @default(TODO)
priority Priority @default(MEDIUM)
aiSummary String? @map("ai_summary") // AI-generated: labelled in the UI (Part 8.6)
assigneeId String? @map("assignee_id") @db.Uuid
creatorId String? @map("creator_id") @db.Uuid // nullable so erasing a user keeps team content
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
deletedAt DateTime? @map("deleted_at")
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
assignee Profile? @relation("AssignedTasks", fields: [assigneeId], references: [id], onDelete: SetNull)
creator Profile? @relation("CreatedTasks", fields: [creatorId], references: [id], onDelete: SetNull)
comments Comment[]
@@index([organizationId, status])
@@index([assigneeId])
@@map("tasks")
}
model Comment {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid // denormalised: simple, fast RLS
taskId String @map("task_id") @db.Uuid
authorId String? @map("author_id") @db.Uuid
content String @db.VarChar(5000) // [C2]
createdAt DateTime @default(now()) @map("created_at")
editedAt DateTime? @map("edited_at")
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
task Task @relation(fields: [taskId], references: [id], onDelete: Cascade)
author Profile? @relation(fields: [authorId], references: [id], onDelete: SetNull)
@@index([taskId, createdAt])
@@map("comments")
}
/// Append-only evidence of every consent decision (9.7). Never update rows; insert a new one.
model ConsentRecord {
id String @id @default(uuid()) @db.Uuid
profileId String? @map("profile_id") @db.Uuid
anonymousId String? @map("anonymous_id") // random ID from the consent cookie, before sign-up
purpose ConsentPurpose
granted Boolean
noticeVersion String @map("notice_version") // version of the notice shown
wording String // exact text the person saw
source ConsentSource
createdAt DateTime @default(now()) @map("created_at")
profile Profile? @relation(fields: [profileId], references: [id], onDelete: SetNull)
@@index([profileId, purpose, createdAt])
@@map("consent_records")
}
/// Minimal record kept after unsubscribe or erasure so the address is never emailed again.
model MarketingSuppression {
emailHash String @id @map("email_hash") // SHA-256 of the lower-cased, trimmed email
reason SuppressionReason
createdAt DateTime @default(now()) @map("created_at")
@@map("marketing_suppressions")
}
/// Rights requests and privacy complaints (9.15, 9.16).
model DataSubjectRequest {
id String @id @default(uuid()) @db.Uuid
profileId String? @map("profile_id") @db.Uuid
requesterEmail String @map("requester_email") // [C2]
type DsrType
status DsrStatus @default(RECEIVED)
jurisdiction String? // e.g. "UK", "EU-IE", "NG"
receivedAt DateTime @default(now()) @map("received_at")
acknowledgedAt DateTime? @map("acknowledged_at")
dueAt DateTime @map("due_at") // one calendar month from receipt (UK/EU)
extendedTo DateTime? @map("extended_to")
completedAt DateTime? @map("completed_at")
outcomeNote String? @map("outcome_note") // no special category details
profile Profile? @relation(fields: [profileId], references: [id], onDelete: SetNull)
@@index([status, dueAt])
@@map("data_subject_requests")
}
/// Security and admin events. IDs only: no emails, names or content.
model AuditLog {
id String @id @default(uuid()) @db.Uuid
organizationId String? @map("organization_id") @db.Uuid
actorId String? @map("actor_id") @db.Uuid
action String // e.g. "member.role_changed", "data.exported"
targetType String? @map("target_type")
targetId String? @map("target_id")
metadata Json?
createdAt DateTime @default(now()) @map("created_at")
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: SetNull)
@@index([organizationId, createdAt])
@@map("audit_logs")
}
/// Usage and cost ledger for AI features. Prompts and outputs are NOT stored here.
model AiGeneration {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
requestedById String? @map("requested_by_id") @db.Uuid
feature String // e.g. "standup_summary"
model String // pinned model ID
promptVersion String @map("prompt_version")
inputTokens Int @map("input_tokens")
outputTokens Int @map("output_tokens")
status String // "succeeded" | "failed" | "cancelled"
createdAt DateTime @default(now()) @map("created_at")
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
@@index([organizationId, createdAt])
@@map("ai_generations")
}
enum Role {
OWNER
ADMIN
MEMBER
}
enum TaskStatus {
TODO
IN_PROGRESS
IN_REVIEW
DONE
}
enum Priority {
LOW
MEDIUM
HIGH
URGENT
}
enum AgeStatus {
UNVERIFIED
ADULT
MINOR_WITH_PARENTAL_CONSENT
}
enum AgeCheckMethod {
SELF_DECLARATION
AGE_ESTIMATION
ID_CHECK_VIA_PROVIDER
PARENT_VERIFIED
}
// Extend from your RoPA (9.3). One purpose per independent choice.
enum ConsentPurpose {
ANALYTICS
SESSION_REPLAY
MARKETING_EMAIL
PRODUCT_UPDATES
PARENTAL
SPECIAL_CATEGORY_EXPLICIT
}
enum ConsentSource {
SIGNUP_FORM
WAITLIST_FORM
COOKIE_BANNER
PRIVACY_SETTINGS
DOUBLE_OPT_IN
PARENT_PORTAL
}
enum DsrType {
ACCESS
RECTIFICATION
ERASURE
RESTRICTION
OBJECTION
PORTABILITY
AUTOMATED_DECISION_REVIEW
COMPLAINT
}
enum DsrStatus {
RECEIVED
VERIFYING
IN_PROGRESS
EXTENDED
COMPLETED
REFUSED
}
enum SuppressionReason {
UNSUBSCRIBED
HARD_BOUNCE
SPAM_COMPLAINT
ERASURE_REQUEST
}
```
**Prisma 7+** rejects `url` inside `schema.prisma`. Put the connection in `prisma.config.ts`, and give `PrismaClient` a driver adapter (e.g. `@prisma/adapter-pg`) that uses the pooled `DATABASE_URL` at runtime. On Prisma 6, put `url = env("DATABASE_URL")` and `directUrl = env("DIRECT_URL")` back in the `datasource` block instead.
```ts
// prisma.config.ts (repo root) — Prisma 7+
import { defineConfig, env } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
// Migrations need a direct (non-pooled) connection; the app uses a driver adapter at runtime.
datasource: { url: env('DIRECT_URL') },
});
```
> **Erasure decision:** when a member deletes their account, decide whether the content they authored is deleted or kept with the author shown as "Deleted user". In B2B, the customer workspace is the controller of that content (9.2), so follow its instructions.
### 5.4 Row-Level Security (Supabase)
Missing or wrong RLS is the most common data-exposure bug in AI-generated Supabase apps. The rules:
- Enable RLS on **every** table.
- Never trust `user_metadata`, which users can edit, in policies.
- Never ship the secret or service-role key to the client.
> **No RLS in your database?** MySQL, MariaDB and SQLite have no row-level security. Enforce the same rules in the data layer: scope every query by tenant and user (for example Laravel global scopes and Policies, Rails Pundit policy scopes, or Django custom managers), allow no raw query that skips the scope, and keep the same isolation tests: as anonymous, as a member, and as another tenant.
```sql
-- supabase/policies/001_rls.sql — run after the Prisma migration that creates the tables.
-- 1) Turn RLS on for EVERY table in the exposed schema. RLS on + no policy = no access (safe default).
alter table public.profiles enable row level security;
alter table public.organizations enable row level security;
alter table public.memberships enable row level security;
alter table public.tasks enable row level security;
alter table public.comments enable row level security;
alter table public.consent_records enable row level security; -- server-only: no policies
alter table public.marketing_suppressions enable row level security; -- server-only: no policies
alter table public.data_subject_requests enable row level security; -- server-only: no policies
alter table public.audit_logs enable row level security; -- server-only: no policies
alter table public.ai_generations enable row level security; -- server-only: no policies
-- 2) Helper functions live in a schema the API does not expose.
-- SECURITY DEFINER avoids recursive RLS on memberships; search_path is pinned for safety.
create schema if not exists private;
grant usage on schema private to authenticated;
create or replace function private.is_member(org uuid)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.memberships m
where m.organization_id = org
and m.user_id = (select auth.uid())
);
$$;
create or replace function private.has_role(org uuid, allowed text[])
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.memberships m
where m.organization_id = org
and m.user_id = (select auth.uid())
and m.role::text = any (allowed)
);
$$;
revoke execute on function private.is_member(uuid) from public;
revoke execute on function private.has_role(uuid, text[]) from public;
grant execute on function private.is_member(uuid) to authenticated;
grant execute on function private.has_role(uuid, text[]) to authenticated;
-- 3) Policies. Always name the role (to authenticated) and wrap auth.uid() in a sub-select (faster).
create policy "profiles: read own"
on public.profiles for select to authenticated
using (id = (select auth.uid()));
create policy "profiles: update own"
on public.profiles for update to authenticated
using (id = (select auth.uid()))
with check (id = (select auth.uid()));
create policy "organizations: members read"
on public.organizations for select to authenticated
using (private.is_member(id));
create policy "memberships: members read their org"
on public.memberships for select to authenticated
using (private.is_member(organization_id));
create policy "tasks: members read"
on public.tasks for select to authenticated
using (private.is_member(organization_id));
create policy "tasks: members create as themselves"
on public.tasks for insert to authenticated
with check (private.is_member(organization_id) and creator_id = (select auth.uid()));
create policy "tasks: members update"
on public.tasks for update to authenticated
using (private.is_member(organization_id))
with check (private.is_member(organization_id));
create policy "tasks: owners and admins delete"
on public.tasks for delete to authenticated
using (private.has_role(organization_id, array['OWNER', 'ADMIN']));
create policy "comments: members read"
on public.comments for select to authenticated
using (private.is_member(organization_id));
create policy "comments: members write as themselves"
on public.comments for insert to authenticated
with check (private.is_member(organization_id) and author_id = (select auth.uid()));
```
Run a tenant-isolation test in CI against a local Supabase stack (never production):
```sql
-- tests/rls/tenant_isolation.sql — run against a local Supabase stack (never production).
begin;
-- Act as user A (a member of org A only).
set local role authenticated;
set local request.jwt.claims = '{"sub": "00000000-0000-0000-0000-00000000000a", "role": "authenticated"}';
-- Must return 0: user A cannot see org B's tasks.
select count(*) as leaked_rows
from public.tasks
where organization_id = '00000000-0000-0000-0000-0000000000b0';
-- Must fail with an RLS violation: user A cannot write into org B.
insert into public.tasks (id, organization_id, title, creator_id, updated_at)
values (gen_random_uuid(), '00000000-0000-0000-0000-0000000000b0', 'should fail',
'00000000-0000-0000-0000-00000000000a', now());
rollback;
```
### 5.5 Migrations & seed data
- Every schema change is a committed migration. Never edit a migration that has already been applied.
- Make breaking changes in steps: **expand** (add new) → migrate data → **contract** (remove old).
- `supabase/seed.sql` holds synthetic data only: one user per role, two organisations (to test isolation), and edge cases such as an empty workspace and very long text.
### 5.6 Retention & deletion schedule
Defaults to adjust per project. Deletion is implemented as code (scheduled jobs plus tests), not as a policy promise.
| Data | Retention | Trigger | Method |
|---|---|---|---|
| Account profile | Life of account | User deletes account → 30-day grace period | Hard delete; cascades; processor propagation (9.15) |
| Workspace content | Life of workspace | Owner deletes workspace → 30-day recovery | Hard delete |
| Inactive accounts | {{24 months}} without sign-in | Warning email 30 days before | Hard delete |
| Security & audit logs | {{12 months}} audit · {{90 days}} auth events | Rolling | TTL job |
| Application logs (no personal data) | {{30 days}} | Rolling | Provider setting |
| Error-monitoring events | {{30–90 days}} | Rolling | Provider setting |
| Aggregate analytics | {{≤ 25 months}} | Rolling | Provider setting |
| Session replays (if used at all) | ≤ 30 days | Rolling | Provider setting |
| Consent records | Life of the consent + {{6 years}} | — | Archive, then delete |
| Marketing suppression list | Indefinitely (hashed email only) | Needed to honour the opt-out | — |
| Rights requests & complaints | {{3 years}} after closure | — | Delete |
| Invoices & payment records | 6 years from the end of the financial year (UK tax) | — | Delete |
| AI prompts & outputs held by the provider | Provider's minimum (aim for zero retention) | — | Contract (ADR-006) |
| Backups | {{30 days}} rolling | Deleted data ages out of backups; say so in the privacy notice | Never restore deleted records: re-apply the deletion log after any restore |
> **Nigeria:** where no law sets a period, stop storing data no later than 6 months after its purpose is achieved, unless it's needed for legal claims (GAID Art. 49). Tell people your retention policy (9.6).
### 5.7 Backups & disaster recovery
- Turn on automated daily backups. Add point-in-time recovery if RPO < 24 h. Backups stay encrypted and in-region.
- Keep backups apart from what they protect: in a separate account or project, or as provider backups that deleting the database, volume or project can't remove. Supabase deletes a project's backups with the project, and they don't include Storage files, so also keep a scheduled `supabase db dump` and a copy of your buckets in storage under another account, encrypted, in-region and on the same retention (5.6). Turn on deletion protection where the provider offers it, and prefer delayed (soft) deletion for production resources.
- Run a **quarterly restore drill** into a scratch project: record the time taken and any problems, and re-apply the deletion log afterwards.
- Keep a runbook (11.5) for DB restore, key rotation and rollback.
---
## Part 6 — API & integration contract `[CORE]`
### 6.1 Conventions
- JSON with camelCase fields, ISO-8601 UTC timestamps and UUIDs.
- Public and partner routes are versioned (`/api/v1/…`).
- Lists use cursor pagination (`?cursor=&limit=` with a server maximum).
- Writes with side effects (payments, emails, AI jobs) accept an `Idempotency-Key`.
- Server Actions are for first-party UI mutations only. Each one validates input and re-checks authorisation (ADR-001).
### 6.2 Endpoint & action inventory
| ID | Type | Name / path | Purpose | Auth · Roles | Input (Zod) | Errors | Rate limit | FR |
|---|---|---|---|---|---|---|---|---|
| API-001 | Action | `createTask` | Create a task | Member+ | `TaskCreate` | 401 403 422 | 60/min/user | FR-002 |
| API-002 | GET | `/api/v1/tasks` | List tasks (cursor) | Member+ | `TaskQuery` | 401 403 | 120/min/user | FR-002 |
| API-003 | POST | `/api/v1/standups` | Generate an AI standup | Member+ | `StandupRequest` | 401 403 429 504 | {{20/day/workspace}} | FR-003 |
| API-004 | POST | `/api/webhooks/billing` | Billing events | Signature | Provider schema | 400 401 | — | 1.8 |
| API-005 | POST | `/api/privacy/consent` | Record a consent decision | Any | `ConsentDecision` | 422 | 30/min/IP | FR-007 |
| API-006 | POST | `/api/privacy/export` | Start a data export | Self (re-auth) | — | 401 429 | 3/day/user | FR-006 |
| API-007 | POST | `/api/account/delete` | Request account deletion | Self (re-auth) | — | 401 409 | 3/day/user | FR-006 |
### 6.3 Error contract
Use RFC 9457 *Problem Details*. The `code` field drives the UI state (10.7), and `ref` lets support find the log entry.
```json
{
"type": "https://{{domain}}/errors/forbidden",
"title": "You don't have permission to do that",
"status": 403,
"code": "FORBIDDEN",
"detail": "Only workspace admins can invite members.",
"ref": "7F3K-92QD"
}
```
| HTTP | `code` | UI state |
|---|---|---|
| 400 / 422 | `VALIDATION_FAILED` (with a `fields` map) | S9 Form validation |
| 401 | `UNAUTHENTICATED` | S8 Session expired |
| 403 | `FORBIDDEN` | S7 Permission denied |
| 404 / 410 | `NOT_FOUND` | S11 Not found / deleted |
| 409 | `CONFLICT` | S12 Sync conflict |
| 429 | `RATE_LIMITED` (+ `Retry-After` header) | S13 Rate limited |
| 502 / 503 | `UPSTREAM_UNAVAILABLE` | S15 Degraded, or S3 Error |
| 504, or a client timeout | `TIMEOUT` | S5 Slow network, then S3 Error |
| 500 | `INTERNAL` | S3 Error |
| No response (fetch fails, `navigator.onLine === false`) | — | S4 No internet |
### 6.4 Validation & content safety
- Zod schemas live in `lib/schemas` and run on the server, which is the authority. Client-side validation only improves the UX.
- Every string has a maximum length, every number has bounds, and unknown fields are rejected.
- Rich text and Markdown (comments, AI output) is rendered through an allowlist sanitiser. No `dangerouslySetInnerHTML` without one.
- File uploads are checked for type (magic bytes, not the file extension) and size. Files go to private buckets and are served through short-lived signed URLs.
### 6.5 Webhooks
**Inbound:**
- Verify the HMAC signature and reject timestamps older than 5 minutes.
- Deduplicate by event ID.
- Return `2xx` quickly and process asynchronously.
**Outbound:**
- Sign payloads.
- Retry with exponential backoff and send failures to a dead-letter queue.
- Never send C3 data in a payload.
### 6.6 Rate limiting & abuse protection
| Surface | Limit (default) | Response |
|---|---|---|
| Sign-in / magic link / password reset | 5 per 15 min per IP and per account | 429 + generic message (no account enumeration) |
| AI endpoints | Per user {{20/hour}}; per workspace {{quota}} | 429 + reset time (S13) |
| Public forms (waitlist, contact) | 10 per hour per IP; bot protection only on these forms | 429 |
| Exports | 3 per day per user | 429 |
---
## Part 7 — Identity, access & security `[CORE]`
### 7.1 Authentication
- **Methods:** {{Google OAuth · magic link · passkeys}}. Request the minimum OAuth scopes (`openid email profile`).
- **Sessions:**
- Short-lived access tokens (Supabase default: 1 hour) with rotating refresh tokens.
- Refresh silently, and warn before a hard expiry (S8, WCAG 2.2.1).
- Sign-out clears local drafts and caches.
- **Re-authentication** is required for deleting the account, changing email, exporting data, changing roles and billing.
- **MFA:** TOTP or passkey, required for OWNER/ADMIN roles in workspaces with {{> 5}} members, for any internal admin console, and for every account that can see special category data (9.13).
- **No account enumeration:** sign-in, sign-up and reset give the same response whether or not the account exists.
- **Recovery:** verified email only. Notify the user when the email, MFA or sign-in method changes.
- **No default or shared credentials:** every person and service has its own. Before launch, remove or disable test, demo and seed accounts in production. If an app store needs a review account (9.25), give it a unique strong password, the lowest role and only synthetic data, and include it in the quarterly access review (7.4).
- **Passwords (if used):** check against breached-password lists, allow paste and password managers (WCAG 3.3.8), set no composition rules beyond length ≥ 12, and rate-limit attempts.
**Authentication flow.** Adapt it to your provider (Supabase Auth, Auth.js, Clerk, Firebase, Laravel Sanctum, Django) and keep the rules in the notes, which follow the OWASP Authentication and Session Management cheat sheets (Appendix B).
```mermaid
sequenceDiagram
actor U as User
participant App as Browser or app
participant S as Server entry point
participant Auth as Auth provider
participant DB as Database
U->>App: Sign up or sign in with an email link, OAuth or a passkey
App->>S: Submit, rate-limited per account and per IP
S->>Auth: Verify
alt Verified
Auth-->>S: User ID and tokens
opt OWNER or ADMIN in a large workspace
S->>U: Ask for the second factor
end
S-->>App: A new session in Secure, SameSite cookies, HttpOnly where the provider allows
else Unknown account or wrong credentials
S-->>App: The same message, status and timing either way
end
App->>S: Request with the session cookie
S->>S: Validate the session, then check the role (7.2)
S->>DB: Query scoped to the user and tenant
DB-->>S: Only the rows the access rules allow
S-->>App: Data, or 401 for S8 and 403 for S7
Note over App,S: Near expiry, refresh silently with a rotating refresh token
U->>App: Delete account, change email, export or change roles
App->>U: Re-authenticate first, then rotate the session
U->>App: Sign out
App->>S: Sign-out request
S->>Auth: Revoke the session and refresh token on the server
S-->>App: Clear the cookies, local drafts and caches
Note over S,Auth: An access token issued before sign-out stays valid until it expires
```
- A new session ID is issued at sign-in and whenever privileges change, so an old or planted one can't be reused.
- Cookies are `Secure`, with `SameSite=Lax` or `Strict` and no `Domain` attribute. Make them `HttpOnly` where your provider allows. Some SSR clients, Supabase's among them, keep the session in cookies that browser code reads, so a strict CSP (7.4) and short-lived tokens carry more of the weight.
- Sign-out revokes the session and refresh token on the server; deleting the cookie alone isn't enough. An access token issued before sign-out stays valid until it expires, so keep tokens short-lived, and before a sensitive action check the session with the provider on the server (with Supabase, `getClaims()` or `getUser()`, never `getSession()`).
- Errors and timing are the same whether or not the account exists, and repeated failures are throttled per account, not only per IP.
### 7.2 Authorisation
Deny by default. Enforce at three layers:
1. **Database:** RLS (5.4), or the same rules enforced in the data layer where the database has no RLS.
2. **Server:** `assertCan(user, action, resource)` in the data-access layer.
3. **UI:** hide or disable controls. This is a convenience, never protection.
| Action | OWNER | ADMIN | MEMBER |
|---|---|---|---|
| View and create tasks, comment | ✅ | ✅ | ✅ |
| Edit any task | ✅ | ✅ | ✅ |
| Delete any task | ✅ | ✅ | ❌ (own drafts only) |
| Invite and remove members | ✅ | ✅ | ❌ |
| Change roles | ✅ | ❌ | ❌ |
| Billing & plan | ✅ | ❌ | ❌ |
| Export workspace data | ✅ | ✅ | ❌ |
| Delete workspace | ✅ (re-auth, type to confirm) | ❌ | ❌ |
| View audit log | ✅ | ✅ | ❌ |
The matrix is also a test fixture: an automated test checks every cell (11.3).
### 7.3 Threat model
Use STRIDE (Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege) on each flow in 3.4. These threats are pre-filled because they are the most common failures in AI-built apps:
| ID | Threat | Scenario | Mitigation | Test |
|---|---|---|---|---|
| T-01 | Information disclosure | RLS missing, a policy uses `using (true)`, or queries aren't scoped | RLS on every table (data-layer scoping where the database has none); review every policy; tenant-isolation tests | 5.4 |
| T-02 | Elevation of privilege | The secret key is shipped in a `NEXT_PUBLIC_` variable or the client bundle | Secrets server-only; CI scans the bundle for key patterns | CI |
| T-03 | Elevation of privilege | IDOR: a Server Action trusts an `orgId` or `taskId` sent by the client | Re-derive tenancy on the server; `assertCan()` on every action | Integration |
| T-04 | Tampering | XSS through comments, Markdown or AI output | Allowlist sanitiser; CSP with nonces; no unsanitised HTML | E2E + DAST |
| T-05 | Tampering | Prompt injection in task or comment text that the AI reads | Treat content as data; no side-effect tools without user confirmation; validate output (8.4) | Eval set |
| T-06 | Information disclosure | SSRF through link previews, URL imports or webhook targets | Allowlist schemes and hosts; block private IP ranges; timeouts | Unit |
| T-07 | Tampering | Malicious or oversized uploads, including files that carry code, scripts or templates | Type and size checks; private buckets; signed URLs; scan shared files; never run code, scripts or templates from uploads outside an isolated sandbox with no credentials | Integration |
| T-08 | Spoofing | Credential stuffing or magic-link abuse | Rate limits, MFA, short-lived single-use links | E2E |
| T-09 | Denial of service | AI or export endpoints used to run up costs | Auth required; quotas; spend caps (8.7) | Load test |
| T-10 | Information disclosure | Third-party scripts, fonts or replay tools leak data | ADR-004; consent-gated loader; CSP | Privacy test (9.9) |
| T-11 | Information disclosure | Verbose errors or stack traces reach the client | Generic messages + `ref`; details only in logs | E2E |
| T-12 | Tampering | Supply chain: malicious, typosquatted or AI-hallucinated packages | Check that a package exists and is maintained before installing; lockfile; automated updates after a release-age delay; install scripts only for approved packages (7.4); audit in CI | CI |
| T-13 | Elevation of privilege | A coding agent, or malware driving one, uses production or account-wide credentials it can reach on a developer's machine or in CI, and deletes or changes production | Development keys only where agents run; production changes through CI/CD with approval; confirmation before destructive commands; backups kept apart (5.7); see 12.1 | Launch gate (Part 13) or Day-0 triage T11; restore drill |
| T-14 | Tampering | Instructions planted in content the coding agent reads (tool or MCP results, issues, error reports, web pages) make it run code or install packages | Content is data (12.1); approval before commands and installs; MCP servers and tools with the narrowest access; agent sandboxed | Review of agent permission settings |
| T-15 | Information disclosure | A vendor or connected app is breached, and its tokens or its copy of your data are used | Narrowest scopes; tokens encrypted server-side and rotated; staff accounts accept only reviewed apps; IDs, not personal data, to analytics, logging and error tools, and the minimum to other vendors (5.1, 9.18); revoke at the first sign of compromise (7.4) | Quarterly grant review (7.4); vendor review (9.24) |
| T-16 | Tampering | CI/CD or publishing compromise: a workflow runs untrusted code with secrets, or a stolen token publishes a malicious release | Pinned actions; read-only workflow tokens by default; no secrets for untrusted pull requests, and no untrusted text in `run:` scripts; trusted publishing with 2FA (7.4) | CodeQL scan of workflows + CI configuration review |
| {{T-17}} | {{ }} | {{ }} | {{ }} | {{ }} |
### 7.4 Security controls baseline
- [ ] **HTTP headers:**
- `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload`
- `X-Content-Type-Options: nosniff`
- `Referrer-Policy: strict-origin-when-cross-origin`
- `Permissions-Policy` that disables camera, microphone, geolocation and payment unless they're needed
- [ ] **Content Security Policy**, generated per request with a nonce. Start in `Content-Security-Policy-Report-Only`, review the reports, then enforce:
```text
default-src 'self';
script-src 'self' 'nonce-{NONCE}' 'strict-dynamic';
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https://{{project-ref}}.supabase.co;
font-src 'self';
connect-src 'self' https://{{project-ref}}.supabase.co wss://{{project-ref}}.supabase.co https://{{error-ingest-host}};
frame-src 'none';
frame-ancestors 'none';
base-uri 'self';
form-action 'self';
object-src 'none';
upgrade-insecure-requests
```
`font-src 'self'` alone blocks the Google Fonts leak (9.9). Add hosts only when a consented or strictly necessary feature needs them (for example, the payment provider's frame on checkout).
- [ ] **Cookies** are `Secure; HttpOnly; SameSite=Lax`. Session cookies are host-only.
- [ ] **CSRF:** Server Actions are POST-only and checked against the origin by Next.js. Route Handlers that change state verify `Origin` and use SameSite cookies.
- [ ] **Encryption:**
- TLS 1.2+ everywhere.
- Provider encryption at rest.
- App-level encryption for C3 fields where feasible.
- [ ] **Least privilege:** separate DB roles for migrations and runtime; production access only through MFA; quarterly access review.
- [ ] **Leavers:** remove a person's access to every system on the day they leave, including SaaS tools, and rotate any credential they shared. The quarterly access review confirms it.
- [ ] **Network exposure:** no database, cache, search index, queue or log store is reachable from the internet unless it has to be, and never without authentication. Where a provider exposes one by design (Supabase, Firebase), its access rules do the protecting (5.4). Before launch, scan your public hostnames and IP ranges for open services (for example with nmap).
- [ ] **Secrets storage:** secrets live in the platform's secret store as write-only values (Vercel: the Secret type, formerly Sensitive), with a separate set for each environment (3.2).
- [ ] **CI/CD and publishing:**
- pin third-party actions to a full commit SHA, or use GitHub's workflow lockfile (`.github/workflows/actions.lock`, in public preview), which also pins the actions they call;
- set workflow tokens to read-only by default, and raise permissions per job;
- never give untrusted pull-request code your secrets: use `pull_request`, not `pull_request_target`, unless the job needs secrets, and then never check out or run the pull request's code in it;
- never put untrusted text (pull request titles, branch names, comments) straight into a `run:` script; pass it in through an environment variable. CodeQL's checks for GitHub Actions flag both mistakes;
- publish packages through trusted publishing (OIDC) with 2FA, not long-lived tokens;
- install with `npm ci` from the lockfile, and let only the dependencies you've approved run install scripts: npm 12 and pnpm block the rest by default (approve with `npm install-scripts approve` or pnpm's `allowBuilds`); on recent npm 11 releases, set `strict-allow-scripts=true` and approve with `npm approve-scripts`;
- let new dependency versions age a few days before you adopt them, in the update bot (Dependabot `cooldown`, 3 days by default; Renovate `minimumReleaseAge`) and in the package manager, so installs by people and agents wait too (npm `min-release-age`, pnpm `minimumReleaseAge`). Keep security fixes exempt so the patch windows in 7.6 hold: the bots exempt them by default, and npm and pnpm take an exclude list (`min-release-age-exclude`, `minimumReleaseAgeExclude`).
- [ ] **Integrations and connected apps:**
- request the narrowest OAuth scopes;
- store the tokens you hold for customers' systems encrypted, server-side and apart from code and CI; rotate them, alert on unusual use, and revoke them all at the first sign that your systems are compromised;
- revoke a vendor's tokens to your systems at the first sign that the vendor is compromised;
- for your own team, allow only reviewed third-party apps to connect to Google Workspace or Microsoft 365 accounts (Google: don't allow unconfigured third-party apps, and mark the ones you've reviewed as trusted or limited; Microsoft Entra: turn off user consent and turn on the admin consent workflow). Review the grants already made now, then quarterly: in Entra, changing the consent setting leaves existing grants in place.
- [ ] **Scanning in CI:** secrets (gitleaks), dependencies (`npm audit` plus Dependabot or Renovate), static analysis (CodeQL or Semgrep). Run DAST (OWASP ZAP baseline) against staging before launch.
- [ ] **Pen test** before launch for High-tier projects, then annually.
- [ ] **Assurance for B2B and public-sector buyers:** Cyber Essentials (UK); ISO 27001 or SOC 2 when enterprise buyers ask.
### 7.5 Logging & audit
| Log this | Never log this |
|---|---|
| Sign-ins, failures, MFA changes, permission denials, role changes, exports, deletions, consent changes, admin actions (to `audit_logs`) | Passwords, tokens, magic links, API keys, full request bodies, email addresses (use IDs), C3 data, payment data, AI prompts that contain personal data |
Logs are structured, carry a correlation ID, are kept for the periods in 5.6, and only named roles can read them.
### 7.6 Vulnerability management
- **Patch windows:** critical within {{7 days}}, high within {{30 days}}. Update dependencies weekly.
- **Disclosure:** publish `/.well-known/security.txt` (RFC 9116) with `Contact` and `Expires`.
- **Report triage:** acknowledge a security report within {{2 working days}} and triage it within {{5 working days}}. Check it against the current design and access rules, not old documentation, and never close one as "intended" or "out of scope" without a review by whoever owns that part of the system. A report that could involve personal data starts a breach assessment (9.20).
- **Secret leaks:** rotate the secret immediately, purge it from git history, review the access logs and assess whether it's a breach (9.20).
---
## Part 8 — AI & LLM features `[IF: AI]`
### 8.1 AI feature register
| AI-ID | Feature | Model (pinned) | Inputs (data class) | Output | Human in the loop | Fallback | Est. cost / 1k calls | Eval metric |
|---|---|---|---|---|---|---|---|---|
| AI-01 | Daily standup | `{{model-id}}` | Task titles and status (C2, minimised) | Markdown summary (JSON schema) | User reviews before sharing | "Generate failed. Retry" (S3) | {{£}} | Format validity ≥ 99%, factual errors ≤ 2% |
| AI-02 | Task triage suggestions | `{{model-id}}` | Task title and description | Tags, priority, assignee suggestion | User accepts or rejects | Manual triage | {{£}} | Acceptance rate ≥ {{60%}} |
### 8.2 Data protection for AI
- **Lawful basis:** usually contract (the feature the user asked for) or legitimate interests (9.4). Optional AI on sensitive content needs consent and a DPIA.
- **Provider terms:**
- A signed DPA.
- **No training** on your data.
- A stated prompt retention period (aim for zero or the minimum).
- A processing region.
- Sub-processors listed (3.6). Recorded in ADR-006.
- **Minimise and redact:**
- Send only the fields the task needs.
- Replace names and emails with placeholders (`[PERSON_1]`) and rehydrate them server-side.
- Never send C3 data without an approved DPIA.
- **Storage:**
- AI output is user content, kept and deleted with its parent record.
- Prompt and response logging is off by default; if enabled for debugging, keep it ≤ 30 days.
- `ai_generations` records usage only.
- **Transparency:** the privacy notice names the AI provider, its purpose and any international transfer (9.6, 9.17).
### 8.3 Prompt & output contracts
- Prompts live in `lib/ai/prompts/*.ts` with a `PROMPT_VERSION`, are reviewed like code and are recorded in each `ai_generations` row.
- Structured output is validated with Zod. On failure, retry once with the validation error, then show S3.
- Set `maxOutputTokens`, a timeout ({{30 s}}) with a user-facing Cancel button (S14), and up to 2 retries on 429/5xx with jittered backoff.
- Stream long outputs, but render them as sanitised Markdown only.
### 8.4 Safety & security (OWASP Top 10 for LLM Applications)
- Keep system instructions separate from untrusted content, and wrap user or retrieved text in clear delimiters. **Instructions found inside content are data, not commands.**
- Model output never directly executes SQL, shell commands or HTML, and never triggers an action. Tool calls go through server-side authorisation and **explicit user confirmation for anything with side effects**.
- Moderate user-facing generation where misuse is plausible. Include jailbreak and injection cases in the eval set.
- Quotas and spend caps prevent cost exhaustion (8.7).
- Agents that act, in the product or as the coding agent that builds it, get the least access that works, short-lived credentials, and a person's approval for anything irreversible (12.1). The OWASP Top 10 for Agentic Applications lists the risks (Appendix B).
### 8.5 Quality & evaluation
- Keep a golden dataset of ≥ {{30}} representative cases, including edge cases: empty input, very long input, other languages, injection attempts.
- Set acceptance thresholds per metric (8.1). Run the eval suite in CI whenever the prompt, model or parameters change. Block the merge on regressions.
- Early on, review a weekly sample of {{20}} real outputs (pseudonymised) and feed what you find back into the dataset.
### 8.6 Transparency & legal duties
- **Label AI output** in the UI: "AI-generated — check before sharing". Make it editable before it's used.
- **EU AI Act Art. 50** (applicable since 2 Aug 2026):
- Tell people when they are interacting with an AI system, unless it's obvious.
- Generated synthetic audio, images, video or text must be marked in a machine-readable way. Systems already on the market before 2 Aug 2026 have until 2 Dec 2026 to comply with this marking duty.
- Deployers of deepfakes and of AI-generated text published to inform the public have disclosure duties.
- **AI literacy** (Art. 4, as amended by the Digital Omnibus on AI, Reg. (EU) 2026/1744, in force 27 Jul 2026): take measures that support AI literacy among the people who operate AI systems for you. No specific individual level has to be guaranteed.
- **High-risk check:**
- Using AI for recruitment, **worker management or monitoring**, education access or scoring, credit or essential services, or biometrics may make the system *high-risk* (AI Act Annex III). The Digital Omnibus on AI deferred these obligations to 2 Dec 2027.
- Get advice before building in these areas.
- **Automated decisions** with legal or similarly significant effects follow 9.22, including human review.
- **Nigeria:** before deploying emerging technologies such as AI, GAID Art. 43 expects three things: a DPIA (filed with the NDPC as part of the compliance audit return), an assessment of whether to test first in a low-risk environment, and continuous monitoring once deployed. NDPA s.37 gives rights over automated decisions, and GAID Art. 18(1)(f) lists consent before a decision based solely on automated processing with legal or similarly significant effects. The Act also allows such a decision where it's necessary for a contract or authorised by law with safeguards (s.37(2)) and prevails over the GAID in a conflict (Art. 3(2)), but how the NDPC reconciles the two is untested: get consent where you can, and record the basis you rely on.
### 8.7 Cost & reliability controls
- Per-user and per-workspace quotas; a monthly spend cap with alerts at 50/80/100%; hard stop at the cap.
- Cache identical requests where that's safe. Use the smallest model that passes the evals.
- Wrap AI behind a feature flag so the rest of the app works without it (S15). Configure a fallback model only after it passes the same evals.
---
## Part 9 — Privacy, data protection & compliance `[CORE]`
Compliance here is a set of **product features**, each with acceptance criteria and tests like any other: consent UI, privacy centre, deletion jobs, suppression lists, the age check. Legal position as at **4 November 2026**. Not legal advice.
> **Build rule:** implement once, to the strictest common standard across your markets (EU-style opt-in for all non-essential tracking, NDPA's consent and children's rules, UK complaint handling). One codebase then serves every market.
### 9.1 Which laws apply
| Regime | Applies when | Main build impact | Regulator | Maximum penalty |
|---|---|---|---|---|
| **UK GDPR + Data Protection Act 2018**, as amended by the **Data (Use and Access) Act 2025 (DUAA)**: most changes in force 5 Feb 2026, the complaints duty from 19 Jun 2026 | You're established in the UK, or you offer services to or monitor people in the UK | All of Part 9 | The Information Commission, which took over from the ICO on 30 Sep 2026 (still at ico.org.uk; this framework says "ICO" for short) | £17.5m or 4% of worldwide annual turnover, whichever is higher |
| **PECR** (as amended by DUAA) | Cookies or similar technologies on UK users' devices; electronic marketing to UK recipients | 9.8–9.11 | ICO | Now up to UK GDPR levels |
| **EU GDPR** | You're established in the EU, or you offer goods or services to or monitor people in the EU (Art. 3(2)) | All of Part 9, plus an **EU representative** (Art. 27) if you have no EU establishment, unless the processing is occasional, low-risk and not large-scale sensitive data | National DPAs | €20m or 4% of worldwide annual turnover |
| **ePrivacy Directive** (national laws) | Cookies and e-marketing for EU users | Opt-in consent for non-essential storage or access; e-marketing consent or soft opt-in | DPAs / national regulators | National |
| **EU AI Act** | AI systems placed on the EU market, or whose output is used in the EU | 8.6 | National authorities, AI Office | Up to €15m or 3% for most obligations |
| **Nigeria Data Protection Act 2023 (NDPA)** + **GAID 2025** | The controller or processor is in Nigeria, the processing happens in Nigeria, **or you process data of people in Nigeria from abroad** (s.2(2)(c)) | All of Part 9, plus the Nigeria rows below | NDPC | Up to the greater of ₦10m or 2% of annual gross revenue (major-importance controllers) or ₦2m or 2% (others) (s.48). Failing to comply with an NDPC order is an offence (s.49). Civil claims are also possible (s.51). |
| **UK Online Safety Act 2023** `[IF: UGC]` | User-to-user or search services with links to the UK | Illegal-content and children's-access risk assessments; reporting and blocking tools. Check the Schedule 1 exemptions and Ofcom's guidance. | Ofcom | £18m or 10% of qualifying worldwide revenue |
| **US** `[IF: US users]` | COPPA: service directed at under-13s, or actual knowledge of them (amended Rule; compliance date 22 Apr 2026) · CAN-SPAM: commercial email · TCPA: marketing texts and calls · state privacy laws (thresholds vary) | 9.11, 9.12 | FTC, state AGs | Per violation |
| {{Other markets}} | e.g. India DPDP Act 2023 & Rules 2025 (phased to 2027), South Africa POPIA, Kenya DPA 2019. **Pakistan** had no comprehensive data protection law as of March 2026: the Personal Data Protection Bill 2023 was not yet passed, but PECA 2016 and the constitutional right to privacy (Art. 14) apply. | {{ }} | {{ }} | {{ }} |
> **You as a processor for overseas clients:** if you're established in the UK or EU and build or host a system for a client abroad (a school, clinic or shop), UK/EU GDPR **processor** duties apply to your processing even when the client and its users are outside the UK/EU (Art. 3(1)). These cover security, records, sub-processors and breach notice to the client. Sign a DPA with the client (9.2, Appendix D5).
### 9.2 Roles, registration & accountability
**Who is the controller?** {{Legal entity}}. In B2C, you are the controller of user data. In **B2B SaaS**, the customer is the controller of what its people put into the workspace and **you are its processor**: publish a customer DPA and a sub-processor list, notify customers of sub-processor changes ({{30 days}}), and help them with rights requests and breaches. You remain the controller for account, billing and marketing data.
| Obligation | Applies to you if | Action | Status |
|---|---|---|---|
| **ICO data protection fee** (UK) | You're a UK controller processing personal data electronically. Exemptions are narrow. | Pay before G2: Tier 1 £52 (micro: ≤ 10 staff **or** ≤ £632k turnover); Tier 2 £78 (≤ 250 staff or ≤ £36m turnover); Tier 3 £3,763. £5 off by direct debit. Non-payment can cost up to £4,350. | {{ }} |
| **EU representative** (Art. 27) | No EU establishment, but you target or monitor people in the EU | Appoint one in a member state where your users are | {{ }} |
| **UK representative** | You're outside the UK but target or monitor people in the UK | Appoint one | {{ }} |
| **DPO** (UK/EU Art. 37) | Your core activities involve large-scale regular and systematic monitoring, or large-scale special category data | Appoint and publish contact details; otherwise name a privacy lead | {{ }} |
| **NDPC registration as a Data Controller/Processor of Major Importance (DCPMI)** | You're domiciled, resident or **operating in Nigeria** (which, under GAID Art. 8(2), **includes targeting people in Nigeria**), you keep a filing system (analogue or digital), and you process the data of **more than 200** people in Nigeria in any 6 months, provide commercial ICT services on other people's devices that store personal data, or work in a designated sector (GAID Schedule 7, para 1) | Register with NDPC. Some types are placed in a tier whatever their volume: **Ultra-High (₦250,000)** includes multinationals, fintechs, payment gateways, telecoms, commercial banks, insurers, and public social media and e-mail app developers; Extra-High (₦100,000) includes government bodies, microfinance and mortgage banks, and higher institutions. Otherwise by volume: UHL > 5,000; EHL 1,000–5,000; OHL 200–1,000 (₦10,000) (para 3). A DCPMI must also designate a **DPO** (NDPA s.32; GAID Art. 7(i)). | {{ }} |
| **NDPA compliance audit** (GAID Art. 7(b)) | NDPA applies to you | Audit within 15 months of starting business, then annually | {{ }} |
| **Compliance Audit Returns** (GAID Art. 7(c), 10) | UHL/EHL DCPMI | File through a licensed DPCO (Art. 10(14)): by **31 March** each year if established before 12 Jun 2023; otherwise **within 15 months of establishment**, then annually (Art. 10(7)–(8)). Late filing adds a 50% penalty (Art. 10(9)). | {{ }} |
| **NDPA staff training** (GAID Art. 7(v)) | NDPA applies to you | Train staff within 6 months of starting business, then annually | {{ }} |
> **Nigeria nuance:** the NDPC stopped applying the NDPR 2019 once it issued the GAID on 20 March 2025 (GAID Art. 3(3)); where the GAID and the Act conflict, the Act prevails (Art. 3(2)). A UK-based app with Nigerian users is covered by the NDPA (s.2(2)(c)). Under GAID Art. 8(2), **targeting people in Nigeria counts as "operating in Nigeria"**, even with no office there. Once you process the data of more than 200 Nigerian data subjects in 6 months, expect major-importance (DCPMI) duties: registration, a DPO, audits and returns. Confirm the details with a licensed DPCO before you reach that number.
**Accountability pack.** Keep these in `docs/compliance/`, versioned:
- RoPA (9.3)
- LIAs (Appendix A1) and DPIAs (A2)
- Data protection policy and retention schedule (5.6)
- Processor register and signed DPAs (3.6)
- Cookie register (9.8)
- Breach log (A4) and rights-request log (A3)
- Training records
- An **Appropriate Policy Document** if you rely on certain DPA 2018 Schedule 1 conditions for special category data
### 9.3 Record of Processing Activities (RoPA)
The privacy notice is **generated from this table**: if a purpose isn't recorded here, the product doesn't do it.
| ID | Activity / purpose | People | Personal data | Sensitive? | UK/EU basis (Art. 6) | NDPA basis (s.25) | Art. 9 / s.30 condition | Recipients | Transfers & mechanism | Retention |
|---|---|---|---|---|---|---|---|---|---|---|
| ROPA-01 | Accounts & authentication | Users | Name, email, auth IDs, IP, session data, age-check result | No | Contract | s.25(1)(b)(i) contract | — | Auth provider, email provider | {{ }} | Life of account |
| ROPA-02 | Workspace features (tasks, comments) | Users; people mentioned in content | Content, names | Incidental | Contract | s.25(1)(b)(i) | — | DB host | {{ }} | Life of workspace |
| ROPA-03 | AI summaries & suggestions | Users | Minimised task text | Avoid | Contract | s.25(1)(b)(i) | — | AI provider | {{US · DPF/SCCs}} | Provider minimum |
| ROPA-04 | Security, fraud prevention & audit | Users, visitors | IP, device, events | No | Legitimate interests (LIA-01) | s.25(1)(b)(v) | — | Hosting, monitoring | {{ }} | 90 days–12 months |
| ROPA-05 | Aggregate product analytics | Users, visitors | Pseudonymous usage events | No | Legitimate interests; UK storage exception with opt-out, EU consent (9.8) | Consent (GAID Art. 19) | — | Analytics processor | {{ }} | ≤ 25 months |
| ROPA-06 | Session replay (optional) | Visitors who consent | Masked interaction recordings | No | Consent | Consent | — | Replay vendor | {{ }} | ≤ 30 days |
| ROPA-07 | Transactional email | Users | Email, account events | No | Contract | s.25(1)(b)(i) | — | Email provider | {{ }} | {{ }} |
| ROPA-08 | Marketing email & waitlist | Subscribers | Email, name, preferences | No | Consent / soft opt-in (PECR reg. 22) | Consent (GAID Art. 18(1)(a)) | — | Email provider | {{ }} | Until unsubscribe; then hash in the suppression list |
| ROPA-09 | Support | Users | Messages, attachments | Possibly | Contract / legitimate interests | s.25(1)(b)(i)/(v) | {{if health data appears}} | Help-desk tool | {{ }} | {{24 months}} |
| ROPA-10 | Billing | Customers | Name, billing address, payment tokens (no card numbers), invoices | No | Contract + legal obligation (tax) | s.25(1)(b)(i)/(ii) | — | Payment provider | {{ }} | 6 years |
| ROPA-11 | Rights requests & complaints | Requesters | Identity check, correspondence | Possibly | Legal obligation | s.25(1)(b)(ii) | {{ }} | — | — | 3 years |
| {{ROPA-12}} | {{ }} | | | | | | | | | |
### 9.4 Choosing the lawful basis
| Processing | Typical basis (UK/EU) | Typical basis (NDPA) | Notes |
|---|---|---|---|
| Running the service the user asked for | Contract | s.25(1)(b)(i) | Only what's *necessary*. Analytics and marketing never count as necessary. |
| Security, fraud prevention, abuse handling | Legitimate interests | s.25(1)(b)(v) | Document an LIA. Under the DUAA, some purposes (e.g. crime prevention, safeguarding, emergencies) are **recognised legitimate interests** in the UK with no balancing test. They are narrow, and don't cover commercial analytics. |
| Aggregate product analytics | Legitimate interests (plus the cookie rules in 9.8) | Consent (GAID Art. 19 cookies) | |
| Non-essential cookies, replay, ad pixels | Consent | Consent | |
| B2C marketing email/SMS | Consent, or the UK/EU soft opt-in | Consent (GAID Art. 18(1)(a)) | 9.11 |
| B2B marketing to corporate addresses | Legitimate interests (UK PECR permits it with an opt-out) | Consent is the safe default | |
| Special category data | Explicit consent (typical for apps) | s.30(1)(a) consent | DPIA (9.13) |
| Children's data relying on consent | Parental consent below the national age | Parental consent under 18 (s.31) | 9.12 |
| Tax and accounting records | Legal obligation | s.25(1)(b)(ii) | |
**Legitimate interests require a documented LIA** (Appendix A1): purpose test, necessity test and balancing test. Under the NDPA, legitimate interests are invalid where they override the person's rights, conflict with the other bases, or go beyond what the person would reasonably expect (s.25(2)). The GAID expects the assessment to be completed *before* processing starts (Art. 26).
**Valid consent** is freely given, specific, informed, unambiguous and an affirmative act. It is not bundled with the terms, and it is as easy to withdraw as to give (UK/EU Art. 7; NDPA s.26, s.35). Under the NDPA:
- Silence or inactivity is not consent (s.26(3)).
- Pre-selected boxes are invalid (s.26(7)(a)).
- You must tell people about their right to withdraw *before* they consent (s.26(4)).
- You carry the burden of proof (s.26(1)).
### 9.5 Privacy by design & default
- [ ] **DP-01** Collect only fields with a documented purpose (5.2). Mark optional fields "optional".
- [ ] **DP-02** Defaults are the most protective: profiles private, marketing off, analytics and replay off until consent, location off.
- [ ] **DP-03** Store results, not evidence: an age-check result rather than a date of birth, and no ID scans unless a specialist provider handles them.
- [ ] **DP-04** Pseudonymise analytics and logs with internal IDs, never emails.
- [ ] **DP-05** C3 data lives in separate tables with stricter RLS and app-level encryption where feasible.
- [ ] **DP-06** Retention and deletion are automated (5.6).
- [ ] **DP-07** An in-product privacy centre covers export, delete, consents, marketing preferences, cookie settings and complaints.
- [ ] **DP-08** Show a just-in-time notice at every point where data is collected (9.6).
- [ ] **DP-09** UK services likely to be accessed by children take the **children's higher protection matters** into account in their design (UK GDPR Art. 25(1A)–(1B), inserted by DUAA s.81, in force since 5 Feb 2026). See also the Age Appropriate Design Code (9.12).
- [ ] **DP-10** No dark patterns: Accept and Reject carry equal weight, there's no confirmshaming, cancelling is easy, and nothing is pre-ticked.
- [ ] **DP-11** Every PR that touches personal data answers the privacy questions in the PR template (11.4).
### 9.6 Transparency: privacy notice & just-in-time notices
The privacy notice **must** cover the items below (UK/EU Arts. 13–14; NDPA s.27; GAID Art. 27(3)):
- [ ] Controller identity, place of business and contact details; representative and DPO, where applicable
- [ ] Each purpose **and its lawful basis**, including the legitimate interests pursued
- [ ] The categories of data, and their source where they weren't collected from the person
- [ ] Recipients, naming key processors and the AI provider
- [ ] International transfers and the safeguards used (9.17)
- [ ] Retention periods, or the criteria for them (5.6)
- [ ] Rights and how to use them (9.15), including withdrawing consent and **objecting to direct marketing**
- [ ] Your complaints route (9.16), and the right to complain to the **ICO**, the relevant **EU DPA** and the **NDPC** (NDPA s.27(1)(f))
- [ ] Automated decision-making and profiling: meaningful information about the logic involved (UK/EU), plus its significance, the envisaged consequences, and the right to object and challenge (NDPA s.27(1)(g))
- [ ] Whether giving the data is a requirement, and what happens if someone doesn't
- [ ] Cookies and tracking, with a link to the cookie notice
- [ ] A child-friendly version, if children can use the service
- [ ] Version number, effective date and a changelog
Write it in plain language, in layers, linked from every footer and every collection point. It must describe what the product *actually* does, generated from the RoPA, never copied. Update it **before** new processing starts, and tell users about material changes.
**Just-in-time examples:**
- *Sign-up:* "We use your email to create your account and send essential service messages. See our [Privacy Notice]."
- *Waitlist:* "We'll email you **once**, when we launch. Want occasional product news too? ☐ Yes (optional)."
- *AI feature:* "Your task text is sent to {{provider}} to write this summary. It isn't used to train their models."
### 9.7 Consent architecture
| ID | Requirement |
|---|---|
| CR-01 | One choice per purpose (analytics, replay, marketing …), kept separate from accepting the terms. |
| CR-02 | Consent takes an affirmative action. No pre-ticked boxes, and never "by continuing you agree". |
| CR-03 | Before asking, say who is asking (including named third parties), what for, and how to withdraw (NDPA s.26(4)). |
| CR-04 | Withdrawing takes the same effort as consenting: a persistent "Privacy settings" link, and the same number of clicks (UK/EU Art. 7(3); NDPA s.35(2)). |
| CR-05 | Record who, what, when, how, the notice version and the **exact wording** in the append-only `consent_records` table. Include these records in access requests. |
| CR-06 | Enforce consent at runtime: the server checks it before any marketing send, and the client loader checks it before any script loads. |
| CR-07 | Ask again when the purpose changes materially or a new third party is added (bump `CONSENT_VERSION`). |
| CR-08 | Never make consent a condition of the service unless the processing is genuinely necessary for it. |
| CR-09 | Where the law requires it, children's consent comes from a parent (9.12). |
**Sign-up form pattern:**
```text
Email [ ] [Continue with Google]
Year of birth [ Select ▾ ] ← no default, no hint of the cut-off (9.12)
☐ Send me product news and tips (optional; unsubscribe any time)
By creating an account you agree to our Terms. Our Privacy Notice explains how we use your data.
[ Create account ]
```
> Don't add an "I agree to the Privacy Policy" checkbox. A privacy notice is information, not a contract or a consent. Asking people to "agree" to it misrepresents the lawful basis.
**Client consent module** (`lib/privacy/consent.ts`, type-checked):
```ts
// lib/privacy/consent.ts — first-party consent state and a consent-gated script loader (client only)
export type ConsentPurpose = 'analytics' | 'replay' | 'marketing';
export type ConsentState = Record & { version: string; decidedAt: string };
const COOKIE_NAME = 'consent_v1'; // strictly necessary: it only remembers the choice itself
export const CONSENT_VERSION = '2026-11-01'; // bump when purposes or vendors change, so people are asked again
export function readConsent(): ConsentState | null {
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${COOKIE_NAME}=`))
?.slice(COOKIE_NAME.length + 1);
if (!raw) return null;
try {
const state = JSON.parse(decodeURIComponent(raw)) as ConsentState;
return state.version === CONSENT_VERSION ? state : null;
} catch {
return null;
}
}
export function saveConsent(choice: Record): ConsentState {
const state: ConsentState = { ...choice, version: CONSENT_VERSION, decidedAt: new Date().toISOString() };
const sixMonths = 60 * 60 * 24 * 182;
document.cookie = `${COOKIE_NAME}=${encodeURIComponent(JSON.stringify(state))}; Max-Age=${sixMonths}; Path=/; SameSite=Lax; Secure`;
window.dispatchEvent(new CustomEvent('consentchange', { detail: state }));
// Evidence for the append-only consent log (ConsentRecord); keepalive survives navigation.
void fetch('/api/privacy/consent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(state),
keepalive: true,
});
return state;
}
/** Injects a third-party script only after its purpose is granted. On withdrawal, clear the vendor's cookies and reload. */
export function loadWhenConsented(purpose: ConsentPurpose, src: string, onLoad?: () => void): void {
const inject = (state: ConsentState | null) => {
if (!state?.[purpose] || document.querySelector(`script[src="${src}"]`)) return;
const s = document.createElement('script');
s.src = src;
s.async = true;
if (onLoad) s.addEventListener('load', onLoad);
document.head.appendChild(s);
};
inject(readConsent());
window.addEventListener('consentchange', (e) => inject((e as CustomEvent).detail));
}
```
For Microsoft Clarity: load its official snippet only after consent, then immediately pass the signal with `window.clarity('consentv2', { ad_Storage: "denied", analytics_Storage: "granted" })`. Clarity has enforced consent signals for UK, EEA and Swiss traffic since 31 October 2025. For Google tags, use Consent Mode with every type set to `denied` by default.
### 9.8 Cookies, local storage, SDKs & tracking technologies
**Scope:** cookies, `localStorage`/`sessionStorage`/IndexedDB, pixels, fingerprinting, and mobile SDKs that read device identifiers. The ICO calls these "storage and access technologies" (final guidance, 29 Apr 2026).
| Category | Examples | UK (PECR as amended) | EU (ePrivacy) | Nigeria (GAID Art. 19) |
|---|---|---|---|---|
| Strictly necessary | Session and auth cookies, CSRF, load balancing, the consent-choice cookie, basket | No consent | No consent | No tick-box for necessary cookies that don't process sensitive, financial or privately stored data (Art. 19(5)); still disclose them |
| Security & fraud prevention | Bot defence, account security | No consent (DUAA exception) | Case by case. Usually fine if it's strictly for security of the requested service. | Treat as necessary only if it's limited to security |
| Appearance & preferences | Theme, language, layout | **No consent** if solely to remember the user's own choices. Give clear information and a free, simple opt-out. | Consent unless strictly necessary for a function the user requested | Consent ("specific selection") |
| Statistics / analytics (first-party, aggregate, solely to improve your service) | Page views, feature usage | **No consent** if that is the *sole* purpose. Give clear information and a free, simple opt-out. | **Consent**, apart from narrow national exemptions (e.g. CNIL-approved audience measurement) | **Consent** |
| Session replay, heatmaps, user-level journeys | Hotjar, Clarity, replay SDKs | Consent | Consent | Consent |
| Advertising, retargeting, social pixels | Meta, TikTok, Google Ads, LinkedIn | Consent | Consent | Consent |
| Third-party embeds that set cookies or read the device | YouTube, maps, chat widgets | Consent, or click-to-load (S17) | Consent / click-to-load | Consent / click-to-load |
**Banner & settings requirements (all markets):**
1. **Nothing non-essential runs before a choice is made.** No implied consent, and scrolling doesn't count.
2. The first layer has **Accept all** and **Reject all** with equal prominence (size, colour, position), plus **Manage choices**.
3. It's visible without scrolling on the homepage and every entry page. For Nigeria it must also cover the middle, left or right of the homepage; a bottom bar is treated as a transparency failure (GAID Art. 7(l), Art. 19). A centred or side panel satisfies every market.
4. Every category is **off by default**. The GAID lists pre-selected non-necessary cookies as a complaint category.
5. Name the providers and purposes, and link to the cookie notice table.
6. Store the choice in a necessary cookie with a version. Ask again only on material change, and never nag after a rejection.
7. A **"Cookie settings"** link in the footer of every page lets people change their mind.
8. Withdrawal works immediately: stop the vendor, delete its cookies where possible, and reload.
9. For UK exempt analytics, show the opt-out toggle and an explanation in cookie settings.
10. Respect **Global Privacy Control** where US state law requires it. As good practice, treat it as "Reject non-essential" everywhere.
11. In mobile apps, apply the same rules to SDKs. Cross-app tracking needs the iOS **App Tracking Transparency** prompt. Declare SDK data use in privacy manifests and store labels (9.25).
**Cookie & storage register** (published in the cookie notice):
| Name | Provider | Purpose | Category | Duration | 1st/3rd party | Basis or exception | Set before consent? |
|---|---|---|---|---|---|---|---|
| `consent_v1` | Us | Remembers the cookie choice | Strictly necessary | 6 months | 1st | Strictly necessary | Yes |
| `sb-*-auth-token` | Supabase (ours) | Keeps you signed in | Strictly necessary | Session / refresh | 1st | Strictly necessary | Yes (after sign-in) |
| {{ }} | | | | | | | |
### 9.9 Third-party requests & embedded resources (the "Google Fonts problem")
**Why it matters.** Every request the visitor's browser makes to another company's server discloses their **IP address**, user agent and, through the Referer, the page they're on. An IP address is personal data: an "online identifier" under the NDPA (s.65) and the GDPR (Art. 4(1)). In 2022 a Munich court ordered a site that loaded Google Fonts from Google's servers without consent to pay €100 in damages (LG München I, 3 O 17493/20), and a wave of claim letters followed. Under the NDPA, the same request can also be an unrecorded cross-border transfer (s.41).
**Rule (ADR-004).** Until consent is given, the browser may contact only:
- your own domains;
- your backend (e.g. `{{project-ref}}.supabase.co`);
- services strictly necessary for the specific page, such as the payment provider on checkout.
Everything else is consent-gated or click-to-load.
| Resource | Risky pattern | Compliant pattern |
|---|---|---|
| Web fonts | `` or a CSS `@import` | `next/font/google` (downloads at build time and self-hosts; the browser sends no requests to Google), `@fontsource/*` packages, or local `woff2` files with `font-src 'self'` |
| JS/CSS libraries | `