On this page
This document captures the security posture of the YNG Unified Commerce platform: what we do to prevent incidents, how we triage advisories, and what to do if something goes wrong.
Reporting a vulnerability#
Do not file a public GitHub issue. Email the maintainers at
security@younetgroup.com with:
- A description of the issue
- Steps to reproduce (or a PoC if safe to share)
- Your contact for follow-up
Expect an acknowledgment within two business days. We triage to CRITICAL / HIGH / MEDIUM / LOW and target: CRITICAL within 48h, HIGH within one week, MEDIUM within one sprint. The repository owner must verify that this alias routes to the active security/on-call team before publishing or deploying the platform; a policy with an unmonitored address is not a disclosure process.
Invariants we enforce#
These are load-bearing. Breaking them is a security incident, not a style preference.
- Row-level security is the database safety net. Every table with an
org_idmust have an RLS policy or an explicit threat-modelled, owner-approved exception. Context is only effective insiderunWithRlsContext; a bare setter is not enforcement. The database-backed inventory covers every migratedorg_idtable;org_membershipsandmagic_link_tokensare the two reviewed pre-context exceptions inpackages/schema/rls-exceptions.json. Every other pre-context read goes through a fixed-shape SECURITY DEFINER locator granted to one runtime role — the public-share slug, the tenant-host lookups, and the MCP bearer token (app_system_resolve_api_token, whose org id is precisely what the lookup exists to learn). The helper catalog is exact: an unreviewed function failsverify:rls. The tracked production topology uses separate exact-identityyng_appandyng_workerroles, both without SUPERUSER/BYPASSRLS. - Connector credentials are envelope-encrypted. AES-256-GCM uses a per-row IV and authentication tag; plaintext secrets must never leave the server, return through tRPC, or hit logs. Writes resolve the configured current version; reads resolve the envelope's exact stored version.
ENCRYPTION_KEYis a v1-only compatibility fallback. Never retire an oldENCRYPTION_KEY_V<n>until a checkpointed rewrap and inventory prove that no stored envelope references it. - Rate limits on every mutating / auth endpoint. The
rateLimithelper inapps/web/src/server/middleware/rate-limit.tsis the only approved implementation. CI fails if a mutating route lacks a call. - No secret fallbacks in infra config.
docker-compose.ymluses${VAR:?message}forNEXTAUTH_SECRET,SESSION_SECRET,ENCRYPTION_KEY— compose aborts when they're missing instead of booting with a predictable default. - Magic-link tokens are stored hashed. In production the raw token only exists in the outbound email. Tokens are single-use and expire in 15 minutes. In production, the magic-link route refuses to issue when
RESEND_API_KEY/RESEND_FROMare unset (returns HTTP 503email_not_configured). The console-log fallback only fires underNODE_ENV=developmentso developers can pick links out of dev logs. 5a. Settings gating.apps/web/src/lib/system-config.tsis the single source of truth for "is provider X configured?" (database / session secret / encryption / redis / email). Magic-link, alert-email send (worker), and/admin/healthconfig-status panel all consult these helpers. The alert worker logs[alerts/email] DROPPED — RESEND_API_KEY/RESEND_FROM not setin production rather than silentconsole.infowhen email is missing. 5b. 2FA (TOTP) + recovery codes. TOTP secrets are envelope-encrypted (same path as connector creds). Step is 30s, drift tolerance ±1 step. Recovery codes are stored as SHA-256 hashes, single-use, and regeneratable from/settingsafter re-auth with the current password. Disable 2FA wipes the secret + all recovery-code hashes atomically. 5c. Passkey / WebAuthn. Adding a passkey requires a sign-in within the previous five minutes. One credential row per registered authenticator (user_credentials). Challenges are atomically claimed, and per-credentialcounterupdates use compare-and-set clone defense. Discoverable credentials support one-tap sign-in and conditional UI. Production requires fixed HTTPSWEBAUTHN_RP_IDandWEBAUTHN_ORIGIN; request-derived fallback is development-only. Registration and authentication require user verification. 5d. Auth-token hygiene.webauthn_challengesandmagic_link_tokensare pruned daily by the audit-log-prune cron (anything pastexpires_at, plus already-used magic-link rows). Keeps both tables bounded without a separate schedule. - DSAR is admin-tier only and org-scoped, and the org comes from the REQUEST. The
/api/compliance/dsarendpoint requires themanage_org_settingscapability (owner or admin by default, or super-admin), pins org context, and scopes user lookups throughorgMembershipsso admins can't pivot across tenants. Which org it pins is resolved byresolveRequestOrg(session)(apps/web/src/server/request-org.ts), so on a tenant host the HOST decides and a non-member of that host's org is refused; the session's ownactiveOrgIdstands only on a platform host. Reading it from the session instead let an erasure anonymise another org's shoppers. Same fix atapi/org-data/[id]/download,api/marketing-systems/summaryandapi/auth/passkey/register/finish. Audit:no-session-active-org.py, now scanningapp/api/**as well as/adminand/settings(tokenaudit-ok-session-org; its one site isapi/auth/switch-brand, which needstenant.kindto tell an unknown host from a platform host). A brand-limited administrator cannot submit an organization-wide DSAR. Exports return the records to the requester without copying the export into the receipt. Erasure returns HTTP 202 and a request ID. The receipt stays inreceivedwhile the operator handles linked order payloads, previous receipts, and account retention. Shopper profile pseudonymization alone does not complete the request. - Cube is RLS-bound. Cube uses a dedicated Postgres app role with
NOBYPASSRLS. Every Cube request must carry a short-lived JWT security context, and the Cube Postgres driver pinsapp.current_org_idbefore query execution.
Enforcement#
Access and auth hardening (2026-10-19)
Custom-domain signed-out deep links validate active domain ownership before emitting
an absolute same-host redirect; unknown domains and lookup failures fail closed.
sign-in-redirect.test.ts exercises the installed Next.js response adapter, including
the previously failing relative Location. OIDC return hosts use one strict authority
parser before signing and again when consuming a signed state; ambiguous authorities
are rejected before tenant lookup or credential handoff. Regression coverage is in
oidc-return-host.test.ts and oidc-return-host-routes.test.ts.
Unexpected chat/MCP tool failures pass through publicToolErrorMessage; database
query strings and bound parameters are not returned to a model/client or stored as
tool-call error text. public-tool-error.test.ts covers both transports and successful
controls. The source scanner uses the current git inventory, including nonignored new
files, and excludes ignored untracked operator data and build artifacts; tracked files remain
in scope even if later ignored.
Dependency floors were raised for ip-address, fast-uri and markdown-it on their
existing major lines. The all-dependency audit also reports
GHSA-vfj7-8cjw-p6xm in dev-only
braces@3.0.3 through the ESLint glob tooling. On 2026-10-19 the npm registry lists
3.0.3 as latest and does not publish the advisory's proposed 3.0.4 fix. A local
pnpm patch now refuses combined brace/parenthesis AST nesting above 100 before
recursive walkers run. scripts/security-braces.test.mjs covers ordinary expansion,
escaped/quoted literals, the accepted boundary and bounded adversarial inputs.
The existing length limit remains in force. No audit suppression or nonexistent
version override is used: registry metadata still reports the same 3.0.3 advisory.
Replace the patch with a reviewed upstream fixed release when available. The package
is absent from the production dependency graph, but images carrying development
tooling still need the patch; graph exclusion alone does not certify an image.
The seed script's previously hardcoded demo administrator password has existed in git history. Removing that default cannot revoke any account already seeded with it. Its reuse in a running environment has not been verified; do not reuse it, and replace any affected local/demo credential through the authorized account-management process. This repair does not rotate production credentials or rewrite history.
Next.js push-gate remediation (2026-10-23)
The production dependency audit reported two critical advisories and one high advisory against Next.js 16.3.8 after the advisory database update. Next.js and its matching ESLint configuration now target 16.4.1, the vendor's fixed release. The workspace override and generated lockfile retain that runtime floor; the existing push security audit continues to reject vulnerable resolutions. No advisory ignore or hook bypass is added. See the vendor 16.4.1 security release for the typed-array cache, image optimization and Server Action fixes.
Egress, consumption and dependency checks (2026-10-22)
The shared outbound URL classifier normalizes trailing DNS dots and IPv4-mapped
IPv6 before applying private-address checks. public-endpoint.test.ts covers those
spellings and the explicit operator allowlist. DNS rebinding remains outside this
hostname check: transport-level address pinning is required to close it.
The push sender refuses redirects and aborts requests after 15 seconds;
web-push.test.ts covers its request options and timeout classification.
AI endpoint egress (2026-11-06, §197)
Every outbound AI request in @yng/ai goes through noRedirectFetch, which
asks for manual redirects and refuses any 3xx, including the SDK models built
for OpenRouter, Ollama and OpenAI-compatible endpoints. The AI connection
test and model-list procedures send a stored key only to the endpoint saved
with it; a different caller endpoint is refused (or, for the inherited
primary key, listed without the key). A failed live model listing returns
one fixed code, request_failed, never transport text. /api/mcp/exec caps
calls per token id as well as per client IP. Guards: tenant-fetch-redirect.py,
tenant-endpoint-redirect.test.ts, ai-configs-stored-key-endpoint.test.ts,
mcp-exec-token-rate-limit.test.ts. DNS rebinding remains the accepted
residual above.
Chat history rescue obeys the same character and message budgets as normal
trimming, including retained system messages (chat-payload.test.ts). MCP bridge
startup/fatal logs omit token fragments, endpoint URLs and arbitrary upstream
errors (mcp-startup-logging.test.ts). These tests run in the canonical unit gate.
Request, share and directory limits (2026-11-06)
Numeric values and their sources are in Limits and budgets.
- Request body cap.
proxy.tscaps a body atPROXY_BODY_MAX_BYTES(24 MiB) and answers 413 for a larger declaredContent-Length. Next truncates rather than rejects at the cap, so the value sits above the largest inline JSON upload (8 MiB decoded, base64 on the wire). The org-data restore upload is excluded from the matcher and streams to disk behindauth(), a super-admin check and a metered stream. Guards:request-body-cap.test.ts,scripts/audit/api-body-cap.py. Chunked anonymous POSTs without a length are still drained until the client stops; only an edge cap closes that. - SSO identity fields. OIDC issuer, claim map and group-role map, and LDAP host, port, base DNs, search filter and attribute map change only by a super-admin; an org admin gets FORBIDDEN
sso_identity_fields_super_admin_onlyand nothing is written. A super-admin replacing a set issuer or host also disables the slot until a super-admin re-enables it. A directory group can no longer grant owner or admin (it lands at editor) or demote an existing admin tier. Guard:sso-identity-fields.test.ts. - Share links. A new or changed share password is at least 8 characters (
newSharePasswordSchema); links created earlier keep opening. A private dashboard publishes only while its issuer is its creator or an admin-tier member, and the public read pins the share's brand. A signed-in or cookie-setting response carries nopublic, s-maxage=60cache header. - Brand scope. A restricted actor grants only a subset of its own brands, a tenant host with a restricted member pins a granted brand, and
/api/chatrefuses a restricted member with no brand (403no_brand_accessorbrand_required). Guard:scripts/audit/brand-input-asserted.py. - Retry-After. Every 429 from a route handler carries
Retry-After; tRPC procedure-level 429s carry a default 60 s because the limiter's exact wait is not known at the route. Guard:rate-limit-retry-after.test.ts.
The lockfile resolves Hono 4.13.13, Vite 8.3.5 and Vitest 4.1.12. Registry audits
on 2026-10-22 reported zero production advisories and one development-only high
advisory: the locally patched braces package described above. The version-based
advisory remains visible; no audit exception was added.
Docker stages install npm 12.2.3 and pnpm 12.23.0 to replace vulnerable bundled
package-manager dependencies. The tracked Node.js images, CI and local version
pins use 26.13.1, addressing the
October 21 security release,
including CVE-2026-111497. Source pins alone do not upgrade deployed containers;
the production rollout and connector checks require the normal deployment process.
The tracked database and cache pins use PostgreSQL 19.0 and Redis 8.10.3
(docker-compose.yml, docker-compose.prod.yml.example); backup and restore
images follow the database pin. scripts/ops/data-plane-upgrade.sh moves a
running stack from PostgreSQL 16.16, Redis 7.4 and RustFS 1.0.4 (dry run by
default; --apply and --rollback need --yes-production). The image's
bundled gosu reported Go-library vulnerabilities; those package matches do not
establish a PostgreSQL network attack path.
MinIO is replaced by RustFS 1.0.6 (pinned by digest) in the tracked compose
files; the production cutover evidence is recorded under RISK-009.
Docker build contexts explicitly exclude .agents, private, browser CLI artifacts
and environment files. Git ignores do not constrain Docker's COPY . .; agent
evidence or transient browser state must never enter an application or migrator image.
scripts/audit/docker-context-private.py enforces the exclusions in audit:all.
Google sign-in requests only openid email. A linked Google subject signs in; without
a link, an address links on first use only when Google vouches for it (email_verified
and either gmail.com or an hd claim equal to the address's domain) and the user
belongs to an org whose admins enabled organizations.google_signin_enabled. This is
the same trust as the emailed magic link: control of the mailbox. On a tenant host the
switch of that org decides; on the platform host any enabled membership, or super
admin. State, link tickets and confirm tokens are HMAC-signed and single-use through the
auth: rate-limit burn, which fails closed in production when Redis is unavailable.
The backup/rustfs-init image builds the checksummed upstream MinIO client release
with Go 1.27.4 and a committed module graph containing security updates. Seven
format-string compatibility fixes retain Go vet; the custom release suffix identifies
the local build. This replaces an unavailable Docker Hub input without changing the
storage provider. The unused gosu binary is removed only from this scheduler/client
image. The PostgreSQL service keeps its official image and privilege-drop mechanism.
The PDF appliance removes two unused WebKit GStreamer packages; Chromium protocol,
PDF, image and video checks passed. Candidate scans on 2026-10-22 report zero critical
or high findings for both images, with one unknown-severity deprecated OpenPGP finding
in the backup image and medium/low OS findings in the PDF image.
The restore drill now requires pg_restore --exit-on-error to succeed before checking
sanity tables. It uses an isolated target with the canonical nonlogin policy roles,
private temporary credentials and diagnostics, and removes its owned anonymous volume
before reporting PASS. scripts/ops/verify-restore.test.mjs covers restore failures that
the previous drill could incorrectly accept. A logical backup and a successful drill
do not replace the separately required off-host disaster-recovery plan.
Production migration, template-update, bootstrap and sample-cleanup one-shots use
docker compose run --no-deps after the explicit database health check. An earlier
up --no-recreate does not protect dependencies from a later compose run.
scripts/audit/deploy-data-plane.py rejects missing flags in the canonical audit;
a disposable Compose reproduction verifies both preservation and the unsafe control.
Scoped router masking uses the authenticated request context rather than resolving the session again inside an org transaction. Viewer-dependent market cache keys include the resolved role, super-admin status and complete masking posture; posture keys encode term boundaries, identity kinds and chrome/record switches. Anonymous public-share viewers remain explicit. Masking regressions cover the scoped identity and cache boundary.
Coverage is mixed. A passing scanner proves only the rows below marked automated; review-only/open controls remain release decisions and are tracked in the risk register.
| Gate | Where | Runs when |
|---|---|---|
scripts/ |
Static rules R1–R13 | pre-, pre-, CI, weekly audit |
pnpm audit - |
Dependency CVEs | pre-, weekly audit, CI |
pnpm run format:check |
Prettier | pre- (staged files only), pre-, CI |
pnpm run typecheck / lint / test |
Correctness | pre-, CI |
pnpm run verify:data |
Numeric/data behavior on Postgres | Local full gate, dedicated CI job |
pnpm run verify:rls |
Complete policy inventory plus runtime RLS behavior | Local full gate and dedicated CI job; privileged runtime is fatal when RLS_ |
pnpm run audit:all |
Registered domain/static audits | pre-, CI |
Not yet fully automated: checkpointed encryption rewrap/key retirement, full-system PITR/restore drills, durable telemetry/SLOs, artifact SBOM/provenance/signing, CSP enforcement, and migration-upgrade/lock budgets. Production bootstrap, authentication challenge use, tenant archive integrity, and topology verification are tracked and test-backed. Exact service-role table/column least privilege is machine-enforced; compromised-web credential containment remains an open production blocker (RISK-002). Exit criteria are tracked in the open risk register below.
scripts/security-scan.mjs enforces:
- R1 — API routes that touch org-scoped tables must pin org context.
- R2 — Mutating API routes must call
rateLimit(...). - R3 —
docker-compose.ymlmust not use${VAR:-default}for security secrets. - R4 — No hardcoded AWS / Stripe / GitHub / Slack / Anthropic / OpenAI keys in source.
- R5 — No
dangerouslySetInnerHTMLbound to non-constant expressions. Allowlisted:apps/web/src/app/layout.tsx(theme init) andapps/web/src/components/public/json-ld.tsx(JSON-LD fromJSON.stringifywith<escaped to\u003c; the values are super-admin SEO copy). - R6 — Routes touching brand-partitioned tables must pin brand context.
- R7 — Every tRPC
.mutation(...)must call arateLimit*helper. - R8 —
next.config.tsmust declare the baseline HTTP security headers (X-Content-Type-Options,X-Frame-Options,Referrer-Policy,Strict-Transport-Security,Permissions-Policy), and anyContent-Security-Policy-Report-Onlyit emits must carry a reporting directive (report-uri/report-to, withreport-tobacked by aReporting-Endpointsheader). - R9 — Third-party GitHub Actions must be pinned to a full immutable commit SHA.
- R10 — Turbo must never cache Next dev/cache output or Playwright E2E runs.
- R11 — A tenant-supplied outbound endpoint must pass the shared egress policy.
- R12 — A route on the
proxy.tsunauthenticated allow-list must not readorgIdfrom the request body without the internal-only origin guard (isInternalOnlyRequest, which classifies by header VALUE — proto, private-range hops, edge-only headers). - R13 — A
@/server/**module a route imports (one level) must pin org context if it touches org-scoped tables. R1 reads only the route file; the read that mattered lived one import away. Exceptions are allow-listed with the caller that provably pins the scope.
Allowlist entries live at the top of the scanner. Any exemption must come with a one-line justification comment.
Internal service seams (worker → web)#
proxy.ts allow-lists a few /api/... paths past the session wall so a machine
caller gets JSON instead of a 302 to the sign-in page. Those routes are
internet-reachable, so a bearer secret is the floor, never the whole gate. The
dashboard-export door (/api/exports/dashboard-payload) is the reference
posture, and R12 holds the line for any future body-scoped one:
- Origin, by value.
apps/web/src/server/internal-only-request.tsreads the forwarding metadata rather than testing for its presence: a request is internal only whenx-forwarded-protois absent orhttp(a TLS-terminating proxy forwards the originalhttps), everyx-forwarded-forhop is in a private/loopback range (the compose network is RFC1918; an edge client is public), and none of the edge-only headers Next never writes are present (x-real-ip— Traefik always sets it;forwarded;cf-connecting-ip/cf-rayon the Cloudflare-fronted apex). Presence is NOT a signal: Next synthesisesx-forwarded-host/-port/-proto/-forfrom the local socket on every request before a route handler runs (next/dist/server/base-server.js), so the worker's own call carries them too. An external caller still cannot forge its way back to internal, because it cannot stop the proxy in front of it from appending its real address or stampinghttps. A request that crossed the edge gets the same 404 an unconfigured deployment answers. - Scope. The body carries an HMAC over
orgId | dashboardId | expiresAt, keyed by the same shared secret and verified constant-time inside a 120 s window (packages/crypto/src/service-signature.ts). The route reads its tenancy from the body, so the token alone must not be enough to NAME a tenant: the caller has to sign the exact deck it is asking for, and a captured request dies with its deadline. - Pin. The resolver still runs inside
runWithRlsContext(orgId, brandId)and matches the deck ondashboards.org_id, so a signature for one org cannot read another's rows even if the first two gates were bypassed.
DASHBOARD_EXPORT_TOKEN is shared by apps/web and apps/worker, and the
signature is REQUIRED — the two services must be deployed together.
The second door: GET /api/edge/traefik-dynamic. The balancer polls it for the
white-label routing table, so it is on the /api/edge/ allow-list and it RETURNS
org ids rather than reading one from a body — which is why R12 does not reach it
and why gate 1 above is applied here deliberately rather than by the scanner.
Order matters: isInternalOnlyRequest(req.headers) runs BEFORE the
TRAEFIK_CONFIG_TOKEN compare, so an edge request gets the same 404 an
unconfigured deployment answers and a valid stolen token buys nothing from
outside the compose network. It has no HMAC and no runWithRlsContext pin —
gates 2 and 3 do not apply, because the route's whole purpose is the
cross-tenant list and its read is a fixed-shape SECURITY DEFINER locator. A
60-request-per-60-second limit per client address caps the poll, and it fails
OPEN by design: the balancer losing its config is worse than an unthrottled
internal poll. Operator side: docs/runbooks/tenant-domains.md.
RLS enforcement (mechanism + production contract)#
The 2026-07-02 architecture review found two compounding defects that made every RLS policy inert — both reproduced live before fixing:
- C5 — the context pin never survived.
setOrgContextranset_config('app.current_org_id', …, is_local := true)OUTSIDE a transaction. postgres.js autocommits every statement, so the transaction-local GUC evaporated before the next statement (verified: the next statement read''), and on a pool the set and the query can land on different connections. Under a non-BYPASSRLS role that pattern fails CLOSED (0 rows). - C4 — the historical runtime role bypassed RLS. The base development database provisions
POSTGRES_USER: yngas a superuser; a superuser skips policy evaluation entirely (FORCE ROW LEVEL SECURITYincluded). Production services must never use it.
Mechanism (shipped). runWithRlsContext(orgId, brandId, fn) in packages/schema/src/client.ts (+ pure core rls-context.ts) opens ONE transaction, pins both GUCs via SET LOCAL, and routes every db.* call inside fn onto that transaction through an AsyncLocalStorage proxy — no call-site changes needed. orgProcedure/brandProcedure wrap every resolver in it; nested scopes reuse the ambient transaction and restore the outer context. setOrgContext/setBrandContext are compatibility-only helpers that may re-pin an already active transaction. They provide no enforcement outside a scope and are forbidden in executable production and operational paths.
Deployment-scoped audit and the cross-org delivery reader. Platform-level notification changes (policy edited or reset, channel configuration changed) and account actions made from the platform console (edit, disable, password set or reset, invitation resend, delete, super-admin grant or revoke) are audit rows with no organization; the account rows carry only the target id and email and the names of changed fields, never a password or hash. A fixed-shape SECURITY DEFINER writer (app_system_write_platform_audit) inserts them with org_id NULL, accepts only the resource types notification_setting, notification_channel_config, user_account and super_admin_grant (writeAuditLog logs and, under test, throws on a null-org row of any other type instead of dropping it silently), and caps the action at 64 characters; a definer reader (app_system_list_platform_audit) pages them, and app_system_search_audit backs the cross-org search at /admin/audit (actor, action, resource, org, date range, keyset paging) over platform and tenant audit metadata with no diff column in its result, so a tenant's diff bodies stay behind /admin/orgs/<slug>/logs. The super-admin delivery log across organizations reads notification_deliveries through another fixed-shape definer function (app_system_list_notification_deliveries) that returns only the displayed columns, masks the recipient in SQL and pages 20 rows. All four are executable by yng_app only (revoked from PUBLIC and yng_worker); the super-admin check stays in the tRPC procedure, and migration 0267 adds the two indexes they read through. Source: packages/schema/sql/runtime-service-helpers.sql.
Platform AI-cost and delivery-summary readers. app_system_ai_cost_by_org, app_system_ai_cost_by_purpose (the /admin/ai "Chi phi AI" section) and app_system_notification_delivery_summary (the strip on the cross-org delivery log) are fixed-shape SECURITY DEFINER readers executable by yng_app only (revoked from PUBLIC and yng_worker); they return aggregates and masked recipients, never a prompt, response body or credential, and the super-admin check stays in the tRPC procedure. app_system_list_notification_deliveries gained search, date-range and overdue parameters under the same grants. Source: packages/schema/sql/runtime-service-helpers.sql.
Org activity reader. org_user_activity_day (migration 0271, RLS) holds one row per member and org per day; super admins, prefetch requests and sample orgs are not counted. app_system_org_activity_summary(uuid[]) is a fixed-shape SECURITY DEFINER reader executable by yng_app only (revoked from PUBLIC and yng_worker) that returns last activity and four weekly distinct-user counts per org for /admin/orgs; a week before tracking began is NULL, never zero. The super-admin check stays in the tRPC procedure. Source: packages/schema/sql/runtime-service-helpers.sql.
Worker RLS-scope suppression in markSyncSuccess. worker-processor-rls-scope.py allows audit-ok-rls-scope: <reason> on the open-dead-letter read in apps/worker/src/processors/sync.ts markSyncSuccess: its SELECT is not lexically inside runWithRlsContext, but all seven call sites invoke it inside the job's pinned scope (the same scope as the sync_jobs and connector_credentials updates in that transaction), so the read is org-scoped under yng_worker. The token covers that one read; the file's baseline count is unchanged.
Roles (exact/default-deny). Migrations provision distinct yng_app, yng_worker, yng_cube, and yng_archive identities (NOSUPERUSER NOBYPASSRLS NOINHERIT NOREPLICATION; packages/schema/sql/app-role.sql). A machine-readable manifest owns exact table/operation/column grants, fixed-shape SECURITY DEFINER helpers have an exact grant matrix, historical grants are revoked, and all-owner future defaults are audited. Cube receives only generated-model columns and archive/restore runs in an isolated worker pool.
Gate. pnpm run verify:rls inventories every public org_id table and requires ENABLE + FORCE RLS plus complete policies unless a current machine-readable exception owns the risk. It verifies exact runtime posture, current table/column privileges, database/schema privileges, every owner default ACL, helper catalog/grants, wrong-service denials, zero rows without context, correct-org visibility, foreign-org isolation, and nested scope restoration. Unknown tables or extra grants fail closed. A privileged local development DATABASE_URL emits a warning; production makes the configured exact identity fatal.
Threat boundary. Until the enforcement deploy of ADR 0054, app.current_org_id is a caller-settable PostgreSQL custom GUC: RLS catches missing or wrong context in trusted application paths, but a stolen yng_app credential or arbitrary SQL can choose another tenant context and reach the auth/control-plane subset that role holds. Worker, Cube and archive blast radius is bounded by exact manifests. ADR 0054 closes the web residual in two deploys. (1) Attested context: a runtime pins org and brand only through app_set_rls_context, a SECURITY DEFINER function that verifies a 60-second HMAC token signed with RLS_CONTEXT_HMAC_KEY against a key in schema app_private, which no runtime role can read; every org policy then also requires app_rls_attested(), so a raw set_config yields zero rows. (2) Identity split: password hashes, TOTP secrets, passkeys, WebAuthn challenges and magic-link tokens are reachable only through a second pool as yng_auth, and yng_app loses user INSERT/DELETE, updates to email/email_verified/is_super_admin/disabled_at, and unattested membership and org writes. Once enforced, a runtime credential alone selects no tenant context, reads or forges no authentication material and grants itself no membership. Residual, accepted: yng_app still reads user names, emails and org/membership metadata; a web or worker process compromise holds the key and both pool URLs and reaches whatever that process can (controls there stay app authz, rate limits, dependency hygiene, image provenance, rotation); a sniffer on the compose bridge sees passwords, results and replayable 60-second tokens (bridge TLS is a separate item). Rollback of deploy 1: start the previous web/worker images with docker compose … up -d --no-build and no migrate (a start-prod.sh run of the previous commit aborts at migrate on the unknown user_auth_secrets table); the 0224 objects stay and the previous image ignores them.
Deck-chat samples exception (2026-10-13). chat-audience-isolation.py check D keeps every chat tool at counts and catalog labels (§44, ADR 0022 D2) with one structural exception: apps/web/src/server/chat/tools/audience-deck-scoped.ts (deckSamples, handoff D10.3) may reach readMentionEvidence, readMentionPiiSpans and maskFreeText. The audit admits them only while the module gates on the caller's record permission before the first read, masks each body against its own stored PII spans, then applies the deck alias merged with the org's record mask (readRecordsMask), and the deck route resolves that permission from the explore_data capability (the gate the in-app evidence drilldown uses; default viewer holds it). Links are withheld under any mask because the alias primitive leaves link destinations verbatim; a PII-span read that fills its cap withholds every body. sourceName, mention_source, the quote pool and the span tables stay banned there; every other deck tool stays counts-only. Check F admits exactly dayFrom/dayTo in audience-deck-scope-input.ts while the clamp inside the deck window is present. Residual, accepted: the org's configured AI provider receives masked excerpts (it has received fenced quote pools from the insight worker since ADR 0025), and the masked excerpts persist in the reader's own chat_messages thread as masked for that reader at write time. Record: private/MSO-unilever-202610/handoff/DECISION-chat-samples-fable.md.
Raw-GUC suppression. rls-raw-guc.py (§141) allows audit-ok-raw-rls-guc: <reason>, capped at 4 uses. All four are the BLO legacy exporter and its test (scripts/ops/org-transfer/export-legacy-core*.ts): the psql script it emits runs against the legacy source database, which has no setter and is read as a superuser that bypasses RLS, so its SET LOCAL pin is a no-op kept for parity with the product exporter.
Pending-membership suppression. pending-membership-reads.py (§227) allows audit-ok-pending-membership: <reason> on the line of an org_memberships read or within three lines above it, one token per read, capped per file: 27 in all. users.ts 5 (member list, invite upsert, rank check, orphan check), admin.ts 14 (super-admin console), auth/config.ts 2 (acceptance stamp, directory resolver), the OIDC callback 3, social-signin.ts 1, notification-settings.ts 1, org-archive/plan.ts 1. Each reads pending rows on purpose; the session load and last-admin count are not exempt. A token that covers no read, or sits in another file, fails the audit.
Production enforcement (shipped). docker-compose.prod.yml.example connects web as yng_app and worker as yng_worker, sets RLS_REQUIRE_APP_RUNTIME=1, and declares the exact expected RUNTIME_DB_ROLE. Startup renders and structurally compares the untracked live Compose file with the tracked template before migration or service startup. The privileged migration identity remains separate and is never a runtime fallback. Local docker-compose.yml may use yng for developer administration, so a local warning is expected and is not evidence about the production topology.
Pool protection (shipped). Because every RLS-scoped resolver now holds ONE pooled connection for its whole lifetime (one transaction per resolver), a resolver that awaits slow external I/O (an AI/HTTP call) inside the scope pins that connection the entire time — a burst of such resolvers can exhaust the bounded pool and starve other tenants (a cross-tenant DoS). Two guardrails in packages/schema/src/client.ts:
SET LOCAL statement_timeout+SET LOCAL idle_in_transaction_session_timeouton every RLS transaction (default 60000 ms, override viaRLS_TX_TIMEOUT_MS).idle_in_transaction_session_timeoutis the load-bearing one: it caps the time the transaction sits idle between statements — the exact window a resolver awaiting a slow external call keeps its connection reserved. Postgres aborts (→ rollback) past the budget, freeing the connection. Both areSET LOCAL, so they reset at COMMIT/ROLLBACK and never leak onto the pooled connection's next user.- Pool size stays bounded at 10, overridable via
DB_POOL_MAX(ops can raise the ceiling without a code change; the default is not auto-raised).
Resolvers that require network work use orgOrchestratedProcedure / brandOrchestratedProcedure: short runOrgRlsPhase / runBrandRlsPhase database units surround runExternalPhase. The external-phase guard fails loudly if a transaction is ambient.
Durable queue hand-off (shipped). Every web path that creates durable worker work inserts a job_outbox row with the domain mutation through enqueueDurableJob(...). The helper refuses a missing/mismatched tenant transaction. The worker-only dispatcher leases committed rows, publishes outside a DB transaction with a stable BullMQ job ID, records publication, retries failures with bounded backoff, and exposes backlog/age/outcome readiness metrics. Web production code cannot publish BullMQ directly; scripts/audit/durable-job-outbox.py ratchets all reviewed producers. deferAfterCommit remains only as a general primitive for explicitly lossy effects and is not used by production web code.
Trusted proxy / client IP#
IP-keyed rate limits (auth brute-force, magic-link, webhook flood) are only as trustworthy as the address they charge. clientIpFromHeaders (apps/web/src/server/middleware/rate-limit.ts) resolves it in two steps.
Step 1 — the PEER, the address of whoever opened the connection to the edge, taken only from something a client cannot write:
TRUSTED_PROXY_HOPS > 0— the operator has declared the topology, so the Nth-from-the-rightX-Forwarded-Forentry is the one a proxy stamped. Unchanged semantics.x-real-ip— Traefik always sets it to its immediate peer and strips inboundX-Forwarded-*from an untrusted peer. This is the production path (TRUSTED_PROXY_HOPS=0).- Leftmost
X-Forwarded-For— the dev / single-tier fallback. Forgeable, and only reached when no proxy stamped anything.
No forwarding metadata at all resolves to unknown; a cf-connecting-ip on its own is never a peer.
Step 2 — the Cloudflare leg. The apex msocloud.net is fronted by Cloudflare; the wildcard tenant hosts reach Traefik directly. On the apex the peer is a Cloudflare edge address, so every visitor would share a handful of buckets. cf-connecting-ip carries the real client but is an ordinary request header a direct caller can forge, so it is honoured only when the peer is inside Cloudflare's published ranges. Otherwise the peer wins. This holds at any hop count — what decides is who the peer is.
The ranges are a dated snapshot in apps/web/src/server/middleware/cloudflare-ranges.ts with a pure IPv4+IPv6 CIDR matcher. CLOUDFLARE_IP_RANGES (comma/whitespace-separated CIDRs) replaces the whole list at runtime for a rotation; an override that parses to nothing falls back to the snapshot rather than trusting every peer. Guard: apps/web/src/__tests__/client-ip-resolution.test.ts.
Edge hardening (operator-applied). Traefik should also overwrite inbound XFF (forwardedHeaders.trustedIPs) so a forged chain never reaches the app: docs/runbooks/traefik-trusted-proxy.md.
Session lifetime#
Sessions and JWTs are 14 days, rolling with a 24 h refresh (SESSION_MAX_AGE_SEC / SESSION_UPDATE_AGE_SEC in apps/web/src/auth/edge-config.ts, imported by both auth configs). session.maxAge, session.updateAge and jwt.maxAge are all set explicitly: NextAuth's implicit 30-day default was never chosen, and an unset jwt.maxAge lets a captured token outlive the session it represents. The edge (proxy) config and the full Node config construct separate NextAuth instances over the same cookie, so they share one constant — a drift is an edge that accepts a token the app has retired. Guard: apps/web/src/__tests__/session-lifetime.test.ts.
Signing in requires a persisted session. Signing out revokes that session. Changing a password or passphrase revokes every session for that account in the same database transaction. Each server caches a verified session for up to 60 seconds. If the revocation store is unavailable on a cache miss, the server denies access and retries on a subsequent request after 10 seconds.
Per-device sessions and 2FA reset. /settings/sessions lists a person's signed-in devices (browser and system, IP prefix, first and last use) and revokes one device or all the others; the admin user drawer Security tab does the same for any user and each revoke is audited. The raw session id never leaves the server: the list carries auth_sessions.public_id (migration 0270). Revoked and idle rows are pruned by app_worker_prune_runtime_data. A super admin resets another user's 2FA with admin.resetUserTwoFactor: reason of 8 to 300 characters, step-up with the actor's own current TOTP code (a used code is rejected), refused for self, super-admin, disabled and not-enrolled targets. One locked yng_auth transaction clears every TOTP column, then every session of the target ends, a platform audit row is written and the owner gets a security email. An admin edit of a user's email clears email_verified_at, ends the user's sessions and sends a verifying sign-in link to the new address only (none for a name-only edit or a disabled account); a later successful sign-in counts as verified.
Suspended organisation. tRPC org and brand procedures answer FORBIDDEN with message ORG_SUSPENDED to every non-super-admin. A suspended org is skipped when a session picks its org at sign-in, switch-org refuses it, a member who lands in one sees a notice page, and suspending an org ends the sessions of members left with no other active org.
Read-only support view ("Xem dưới quyền"). A super admin views the product as one accepted member of one org, never as a minted session. The admin starts it from the user drawer with a reason (8 to 300 characters), an explicit org and the actor's own current TOTP code; super-admin, disabled, pending and suspended-org targets are refused. The view is one row in auth_view_sessions (migration 0273, granted to yng_auth only, RLS forced, cascades with the admin's session), hard-capped at 15 minutes by a CHECK, and named by the signed host-only cookie yng_view_as. Every request re-checks that the row is live, the actor's session is live, the actor is still a super admin and the target is still a member. The request resolves as the member's role, brand grant and masking, never as super admin. Every tRPC mutation and every non-GET request except exit is refused, as are /admin, security and sessions settings, exports, satellite launch and IdP paths. Every tRPC RLS scope in view mode also runs SET TRANSACTION READ ONLY (rlsRunnerFor, §228), so a query that seeds data fails with 25006. Start and end each write a platform audit row and an org audit row; visits during a view do not count as the member's activity. Gates: support-view-rules.test.ts, trpc-support-view-read-only.test.ts, and scripts/audit/rls-support-view-read-only.ts in verify:rls.
HTTP security headers#
apps/web/next.config.ts sets X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN (cross-origin framing blocked — same-origin dashboard embeds still work), Referrer-Policy: strict-origin-when-cross-origin, Strict-Transport-Security (2y, includeSubDomains, preload), and Permissions-Policy (camera/mic/geo denied) on every response. Rule R8 fails the build if any is removed.
Content-Security-Policy-Report-Only ships alongside them and now reports somewhere: the policy carries report-uri /api/csp-report plus report-to csp-endpoint, backed by a Reporting-Endpoints header. Both are relative, so a report returns to the host it came from (ADR 0016). apps/web/src/app/api/csp-report/route.ts is on the proxy.ts unauthenticated allow-list because the browser posts it with no session: it accepts only application/csp-report and application/reports+json, caps the read at 16 KiB mid-stream (readBodyCapped), rate-limits per resolved client IP (fail-open — a telemetry sink must not take the app down), logs ONE structured line carrying document-uri / violated-directive / blocked-uri truncated to 200 chars and never the body verbatim, and always answers 204. It reads no tenancy. R8 fails the scan if a Report-Only header is emitted with no reporting directive. Guards: csp-report-route.test.ts, security-scan-csp-rule.test.ts.
A full ENFORCED Content-Security-Policy remains the follow-up — nonce wiring for Next's inline bootstrap, then dropping 'unsafe-eval' once the report stream shows ECharts is clean.
Secret rotation#
| Secret | Storage | Rotation signal | How |
|---|---|---|---|
ENCRYPTION_ |
Environment secret; KMS-backed storage is a target, not proven by this repo | On suspected compromise or the approved rotation cadence | Add the new versioned key, retain every referenced old key, set ENCRYPTION_ for new writes, verify mixed-version reads, then rewrap with checkpoints. Never retire an old key before a persisted-version inventory reaches zero. |
NEXTAUTH_ / SESSION_ |
Env var | Quarterly, or on suspected compromise | Rotate value; all existing JWTs immediately invalidate — users re-auth |
| Connector API credentials | Envelope-encrypted in Postgres | Per connector policy | Operator updates via / (shared service accounts: /; super admin: /); old envelope is overwritten |
RESEND_ |
Env var | On suspected compromise | Rotate in Resend dashboard, update env |
CUBE_ |
Env var | Quarterly, or on suspected compromise | Rotate value, restart web + Cube together, then rerun RUN_ |
RLS_ |
.; the migrator copies it into app_ (no runtime role can read it) |
On suspected compromise of any web/worker/Cube/archive process or of the host env | openssl rand - into ., then .: migrate converges key 1, every service restarts with the new key and boot self-checks it. The retiring replica's tokens are rejected from the migrate until the swap; once deploy 2 enforces attestation that window refuses its reads, so wire the key_ 2 path (insert row 2, sign with it, retire row 1 with active = false) before the first rotation. Never the public dev key: start-, verify- and migrate refuse it |
YNG_ |
.; the migrator sets the yng_ role password from it |
Quarterly, or on suspected compromise | openssl rand - into ., then .: migrate re-sets the role password and web restarts with the new AUTH_; the retiring replica cannot open new auth connections until the swap |
Cube threat model#
Cube is the semantic layer for analytics and agent grounding. The primary risks are cross-tenant reads, forged JWTs, generated-schema drift, and accidental direct Postgres access from embedded BI.
Controls:
- Cube JWTs are HS256, short-lived, and validated for issuer/audience before any query runs.
- Cube rejects every query without
securityContext.orgId; super-admin metadata is not a database bypass. - The exact Cube role is read-only,
NOBYPASSRLS, default-deny, and column-projected to generated semantic sources; the live ACL audit rejects any additional table or column. Cube pins its session context throughapp_set_rls_contextwith a token signed byRLS_CONTEXT_HMAC_KEYand refuses to start without the key (ADR 0054). Until policies require attestation, direct possession of the Cube credential can still choose an org GUC within that bounded projection; after, it reads zero rows. - Generated schema is checked by
pnpm cube:generate:check; report cubes are emitted by the generator, not edited in place. - Superset is documented and scaffolded to connect only to Cube SQL API, never app Postgres.
- E2E guard:
RUN_CUBE_E2E=1 pnpm cube:verify-tenant-isolation.
Open risk register#
An open risk is not automatically accepted. A release decision must name the owner, expiry/review date, compensating control, and exit evidence. P0 risks below block multi-tenant production readiness.
| ID | Severity | Open risk | Interim control | Exit evidence | Owner / review |
|---|---|---|---|---|---|
| RISK-002 | P0 / critical | Exact/default-deny ACLs now bound app/worker/Cube/archive, but yng_ still combines tenant web with reviewed auth/control-plane access and a stolen credential can select another tenant GUC. |
Keep runtime credentials private and network-restricted; retain exact live ACL/startup checks; rotate on suspected process compromise; do not approve multi-tenant production yet. Mitigation in progress: ADR 0054 (attested context + yng_ split); the row stays open until the enforcement deploy's probe output is quoted here. |
Split tenant web from auth/super-admin capabilities; replace broad caller-selected context with narrow authenticated helpers/identities; add compromised-web negative probes and production-like broad-grant upgrade evidence. | Security/platform owners; residual blocks production. |
| RISK-003 | P1 / medium | Version-aware decrypt is implemented, but persisted-version inventory, checkpointed rewrap and key-retirement alerts are not yet automated. | Retain every historical ENCRYPTION_; move only new writes to the new version. |
Inventory reports zero references before retirement; interrupted rewrap resumes safely. | Security owner; before retiring any old key. |
| RISK-008 | P3 / low | @simplewebauthn//browser bumped 9.x → 14.0.x on main (2026-09-09), past GHSA-6hxq-p678-4hr2's 13.3.2 fix line — apps/ and both client call sites (passkey-, signin-) rewritten for the v10/v11/v13 breaking changes, typecheck + the existing mock-level unit suite (apps/) green. Not yet closed: no register/login ceremony has been run against a real (or CDP virtual) authenticator in a browser — the unit suite mocks @simplewebauthn/ directly and proves nothing about the wire format change. |
- in . no longer flags this package at all (0 vulnerabilities). |
A manual passkey register + login pass in the browser against the deployed build (or a Playwright CDP virtual-authenticator spec, none exists yet), before or immediately after this deploy. | Whoever deploys this change; do the manual pass same-day. |
| RISK-007 | P1 / high | No automated PITR/off-site recovery drill; RPO/RTO targets are unmeasured. | Manual host snapshots/tenant exports where available. | Completed restore drill meeting ratified RPO/RTO. | Operations owner; monthly. |
| RISK-009 | P1 / high | The archived MinIO community binary has CVE-2026-33322 and CVE-2026-33419; Read-only persisted configuration checks on 2026-10-22 found no configured required OIDC/LDAP identity fields and no enabled identity integration; future configuration remains relevant. No patched community release was identified on that date. | Replacement implemented in the tracked compose files: RustFS (now 1.0.6, rustfs/), console disabled. On 2026-10-30, throwaway-store runs passed scripts/ (9/9) and scripts/ parity, and the parity check failed on injected corruption. Production cut over on 2026-10-30 (13-object parity, smoke 9/9); the MinIO container and volume were removed after operator sign-off, with an offline archive kept. |
Vendor-supported remediation or an explicitly approved replacement, with restore and S3 compatibility evidence. | Security/platform owners; review 2026-10-29 and before rollout. |
| RISK-010 | P2 / medium | The Python ML app (apps/) has no committed lockfile, no tests and no CI gate; its image installs uv unpinned (apps/). Carried over from the retired platform excellence programme (P2-04). |
Treat as non-production until it has an owner. | A locked, tested and owned Python release contract, or removal of the service. | Platform owner; before any production use of the ML app. |
| RISK-011 | P2 / medium | Migrations use a separate privileged identity and fail closed, but previous-release-to-head upgrade runs, lock and statement budgets and rollback rehearsal are not gated (retired programme P2-06). | Migrations run only inside start-; review each migration for locks by hand. |
CI job upgrading the previous release to head with lock/statement budgets and a documented rollback. | Platform owner; before the next schema-heavy release. |
| RISK-012 | P2 / medium | The worker image runs TypeScript through tsx (apps/) with a broad dependency set, and image SBOM/provenance/signing is absent (retired programme P2-07, P1-08). |
Images are built from pinned bases by start-; topology verified by verify:prod-. |
Pruned compiled worker artifact and a CI boot-smoke plus provenance for every production image. | Platform owner; no date set. |
The 2026-07 platform excellence programme document was retired on 2026-11-07; its still-open rows are RISK-010 to RISK-012 above (git history keeps the rest).
Historical / closed
- RISK-001 — bootstrap credential: closed 2026-07-15 by create-only, advisory-locked bootstrap that reads a strong operator secret only on the first create path and never resets an existing identity.
- RISK-004 — untracked topology drift: closed 2026-07-15 by
verify-prod-compose.mjs;start-prod.shrefuses a live file whose canonical rendered topology differs from the tracked template. - RISK-005 — best-effort queue publication: closed 2026-07-15 by the transactional outbox, worker-only dispatcher, retry/lease contract, readiness metrics and static producer ratchet.
- AI SDK 4 file-upload advisory: closed by the repository's completed upgrade to AI SDK 6 / Zod 4. The previous explanation that this upgrade was blocked is obsolete.
pnpm run security:auditreported no known high+ production advisory on 2026-07-15; future results supersede that dated statement.
Incident response playbook (summary)#
- Contain. Revoke the affected credential or take the affected route offline.
- Rotate. Generate replacements; deploy before restoring access.
- Scrub. If a secret landed in git history, use
git filter-repo(or BFG) and force-push with team coordination. - Audit. Check provider audit logs for abuse during the exposure window.
- Postmortem. Write it within a week. File a PR adding a regression check to
scripts/security-scan.mjsif the class of bug is statically detectable.
Source-popup filter declaration (2026-10-16). The audit-ok-presentation-field: ordered-filter-controls token on deck.sourceFilters admits an ordered list of existing filter addresses, not a new widget kind. explore.audienceRecordFilters resolves it from the active dataset inside brandProcedure; readRecordPopupFilters changes only the offered controls. The existing row-scope intersection and masking remain unchanged. Guard: audience-source-drilldown.test.ts; absent declarations preserve the catalog-derived behavior of existing decks.
Source-popup tools declaration (2026-11-16). The audit-ok-presentation-field: source-popup-tools token on deck.sourceTools admits five opt-in tools of the existing source-data popup: a row number, a date range, a CSV of the filtered rows, up to six taxonomy columns and a title column (the mention's stored post title under a declared label, read only when declared, a flat string cell the records mask reaches; titles have no stored PII spans, so matchPiiRuns from the ingest detector's own table masks them at read time through maskSourceTitle, CSV included; guard: audience-source-title.test.ts). explore.audienceRecords reads the declaration from the active dataset inside brandProcedure; the client never names a column. A declared dim the corpus does not carry is dropped (resolveSourceTools); its row cells are the rows' own tag labels as flat string cells, so the records mask reaches them like every other in-app record cell (the A6 carve-out holds). The date range is clamped inside the mark's window in narrowRecordScope and can only narrow it. The CSV pages through the same procedure, so PII spans and masks apply unchanged. Guard: audience-source-drilldown.test.ts; absent declarations leave every deck's popup unchanged. Cross-corpus narrowing (2026-11-17): sourceTools.join names a second corpus whose rows key to a record as <record external id><separator><n>; resolveSourceJoin resolves it inside the caller's org/brand (same brand as the records corpus, never that corpus itself) and reads the declared dims' active values. A pick on a joined dim or on sentiment becomes AudienceScope.sourceJoin, an uncorrelated semi-join on the record's external id with explicit org/brand/dataset predicates, every picked filter on ONE joined row; a value outside the declared set narrows to nothing, never widens, and the leg only adds a predicate (narrowRecordScope). Joined chips count distinct in-scope records and their labels pass the merged deck/records mask. sourceTools.filterLabels only renames chips. Guard: audience-source-join.test.ts. Unverified: that the deck's widgets read the joined corpus (the popup input carries no widget id).
Pie-form suppression (2026-10-23). chart-donut-standard.py (§168) allows audit-ok-pie-form: <form and reason> on a hand-rolled type: 'pie' series that is not a part-to-whole donut. Three sites: the half-ring sentiment gauge (audience-measure-cards.tsx GaugeBody), the concentric comparison rings (packages/charts/src/builders/panel-rings.ts), and the print-only share SVG (apps/web/src/server/share/chart-svg.ts donutSvg, which has no tooltip and so keeps names and values in a side legend). No security surface is affected; the token exists so a new hand-rolled donut cannot ship without a stated reason.
View-state URL-write suppression (2026-10-24). view-state-url-writes.py (§170) allows audit-ok-view-state: <reason> on a site that writes from/to/compare*/pf* into a URL. Sites: the adopt-strip and commit-strip in apps/web/src/lib/view-state.tsx (remove keys, add none) plus its no-provider fallback; the corpus-period pin and period pick in filter-bar.tsx (page-local, excluded from the shared window); the page-local windows of ai-search-window-select.tsx and campaign-window-picker.tsx (routes excluded from adoption); the drill-down in creator-directory-report.tsx the order deep link in validation/[runId]/_components/run-detail-client.tsx (adopted on arrival), and the pack frame's copy-link builder buildFrameShareHref in dashboards/[slug]/_components/dashboard-page-frame.tsx (a clipboard string, never the address bar; adopted on arrival). Deck sites are pinned in .view-state-url-writes-baseline.json, which may only shrink. Security-relevant only as tenancy hygiene: the store is org-scoped (stickyFiltersApplyToOrg, strict on the server-resolved org) and cleared at /post-login; the cookie is not httpOnly by design (the client commits it) and carries only filter values.
Theme-declared money scale (2026-10-23). vi-magnitude-suffix.py allows audit-ok-latin-magnitude: <reason>. One new site: VI_SHORT_CLASSIC_K in packages/charts/src/formatters.ts, the classic_k money scale (289,5K beside 673,8 tr). It is applied only when an org's skin declares moneyScale: 'classic_k' (the built-in ucip-blue skin, for an org migrated from the UCIP product) and the caller passes that scale (getActiveOrgFormatting, OrgCurrencyProvider / useVndShort). Every other caller keeps VI_SHORT, so the 2026-08-29 mixed-unit defect cannot reach an org that did not declare it. No security surface is affected. Guard: formatters.test.ts (the default scale prints thousands in full; classic_k adds the K tier only for a Vietnamese reader).
Web-platform tell suppression (2026-11-14). web-platform-tells.py (§223) allows audit-ok-ime-enter: <reason> on an Enter test that is not a text-input handler (button activation, a canvas key map, a pure key-to-intent map whose input handler guards composition) and audit-ok-transition-all: <reason> on a deliberate transition: all; there are no transition-all exemptions today. Sites are the Enter activations in templates-client.tsx, dataset-dim-stepper.tsx, deck-drilldown-surface.tsx, help-figure-zoom.tsx, keyboard-map.ts and structure-panel.tsx; five text-input or row handlers under files other work owned are pinned in .web-platform-tells-baseline.json, which may only shrink. No security surface is affected.
Slop-audit suppression (2026-11-14). slop-audit-added.py (§225) allows audit-ok-slop: <reason> on a line it would otherwise flag; a reason of TODO is rejected. It judges only lines added since the merge base with origin/main, so no site exists today and no baseline is kept. No security surface is affected.
AI-assisted scan (opt-in)#
pnpm run security:ai -- --max-usd N --run-label L [--diff REF | --working-tree | --full [--deep]] [--auth chatgpt|api-key] [--dry-run] wraps the OpenAI Codex Security CLI (npm i -g @openai/codex-security@0.10.0, not a project dependency). Run it by hand before a release or after auth, upload, payment or tenancy changes; the default scope is the diff against origin/main; --full is limited to apps and packages.
- Auth:
--auth chatgpt(default) draws on the subscription's Codex allowance;--auth api-keybills API credit. The wrapper always passes it, since a non-interactive run would otherwise preferOPENAI_API_KEY. A--diffscan needs a clean checkout. - Consent and budget: it makes model calls, so the operator approves each run and the wrapper refuses without a positive
--max-usdand a--run-label. The budget is an estimate; in-flight requests can overshoot it. - Never part of
verify,audit:all,check:affected,gate.sh, hooks or CI. - Reports land outside the repo under
~/.local/codex-security/reports/. Exit 1 means findings at high severity or above, exit 2 means the scan did not run and is never a clean result. - Findings are leads. A human or the lead traces each to a reachable path and a failing check before it counts; an unconfirmed finding is not a risk entry here.