# Security posture

This document summarizes the current code-backed security posture of
contextplusplus for operators, customers, and security reviewers. It is not a
certification, penetration-test report, or compliance attestation.

## Supported versions

| Version | Supported |
| --- | --- |
| 1.7.x | Yes |
| < 1.7 | No |

## Architecture and trust boundaries

contextplusplus is a multi-tenant URL-to-Markdown service with CLI, HTTP API,
and MCP interfaces. Public requests are authenticated and authorized before
quota-bearing provider work. Provider credentials, Supabase service-role keys,
Stripe secrets, and usage writes remain on server-side boundaries.

The primary security owners are:

- HTTP request parsing, route authorization, rate limits, and public errors:
  `apps/api/src/interfaces/http/**`.
- MCP protocol authentication, MCP-only Connect URLs, and tool boundaries:
  `apps/mcp/src/interfaces/mcp/**`.
- Request schemas and safe error types: `packages/core/src/domain/**`.
- Authentication, billing, usage, URL safety, provider access, rendering, and
  observability implementations: `packages/core/src/infrastructure/**`.
- Authenticated workflows and quota settlement:
  `packages/core/src/application/workflows/**`.
- Tenant state, grants, RLS, and RPCs: `supabase/migrations/**`.

The website and dashboard are separate Next.js applications. Dashboard route
protection and session refresh live in `apps/dashboard/middleware.ts`; shared
browser/API clients live under `packages/ui/src`.

## Authentication and authorization

### HTTP bearer tokens and API keys

`packages/core/src/infrastructure/auth/supabase-auth-live.ts` verifies hosted
Supabase JWTs through the project's JWKS and enforces issuer, audience, and
expiration. HS256 is reserved for local development unless the explicit hosted
compatibility flag is enabled. Missing verification configuration fails closed.

Programmatic keys are generated as `atmd_` plus 32 random bytes encoded with
base64url. Only a digest is stored. When `API_KEY_HASH_SECRET` is configured,
new keys use HMAC-SHA-256; verification retains the legacy SHA-256 path for
existing records. Revoked and expired keys are rejected before an identity is
returned. Routes authorize required scopes in addition to verifying the key.

Sensitive bearer actions that mint durable credentials revalidate the active
Supabase session. Admin access is fail-closed when `ADMIN_USER_IDS` is empty.

### MCP boundary

`apps/mcp/src/interfaces/mcp/server.ts` does not enable the framework OAuth
provider. Repository middleware authenticates `/mcp` and `/sse` requests with a
long-lived `atmd_` API key and requires the `process` scope. Missing or invalid
credentials return 401; insufficient scope returns 403.

Installer-owned Connect URLs use a separate MCP-only credential class. Their
raw value is returned once, stored only in the deliberate destination, and
looked up through a domain-separated HMAC-SHA-256 digest under
`MCP_CONNECTION_CREDENTIAL_HASH_SECRET`. The outer adapter revalidates every
request, strips credential-bearing request data before delegation, and does not
treat an MCP session id as authentication. Revocation and expiry fail closed.

## Tenant and data isolation

Supabase migrations enable RLS on tenant-facing tables such as profiles,
subscriptions, usage, quota reservations, API keys, and MCP connection metadata.
Owner-readable rows are scoped to `auth.uid()`. Sensitive digests and service
write paths are not granted to anonymous or authenticated roles.

Service RPCs used for billing, quota, provider spend, lifecycle email, and MCP
credentials have execution revoked from public roles. Backend writes use a
service-role client with browser session persistence and token refresh disabled.
The current schema, policy inventory, and known exceptions are documented in
`.agent-docs/reference/project/SECURITY_TESTING_AND_RISKS.md` and `supabase/AGENTS.md`.

## Billing, quota, and side-effect integrity

The Stripe webhook route in `apps/api/src/interfaces/http/app.ts` registers a
raw-body parser before JSON parsing. The billing implementation verifies the
Stripe signature before applying state. A webhook-event ledger prevents replay,
and an event-created watermark prevents older events from overwriting newer
subscription state. Checkout binds the authenticated user; portal customer
resolution remains server-side.

`AuthenticatedProcessRunWorkflow` authenticates and authorizes the caller,
checks the provider-spend ceiling, and reserves quota before provider work.
Reservations are released when a run fails or is interrupted and remain charged
after success. Database RPCs make reservation and release decisions atomic.
Provider-credit and Kernel-USD ceilings are maintained in service-role-only
daily ledgers.

Automatic production promotion is exact-main-SHA, serialized, and fail-closed.
Safe new Supabase migrations run only after all validation gates; destructive
SQL requires the protected `production-supabase-destructive` environment and a
verified reviewer rule. Migrations are forward-only and destructive statements
must carry an adjacent truthful rollback or PITR instruction.

## Fetch safety and input controls

Request schemas permit only HTTP(S) URLs, reject URL credentials, cap URL and
batch sizes, and bound concurrency and timeouts. The HTTP boundary also enforces
content type and a 1 MiB JSON body limit. Ordinary processing has a 90-second
request budget beneath the Node socket deadline. Hosted research separately
bounds authentication to three seconds, execution to 1–60 seconds, and shared
financial cleanup to ten seconds. Invalid URL failures remain permanent input
errors; partial research responses preserve completed evidence and identify
unresolved sources. See the [research contract](.agent-docs/spec/core/backend/hosted-research.md).

`packages/core/src/infrastructure/http/url-safety-live.ts` rejects localhost,
metadata destinations, unsafe IPv4/IPv6 ranges, and unsafe DNS results. The
Undici connection lookup repeats the address decision at connection time to
resist DNS rebinding. Generic scraping delegates to configured external
providers, while preserving the original target separately for safety checks
and diagnostics. Provider response bodies are bounded and non-success statuses
are rejected before rendering.

## Rate limiting and proxy trust

The API has separate global, authentication/billing, and webhook limiters.
Client identity derives from Express `request.ip`. `HTTP_TRUST_PROXY_HOPS` is a
non-negative integer passed directly to Express `trust proxy`; its default is
`0`, which trusts no proxy hops. Production operators must configure the exact
numeric hop count for their deployment topology. Client-supplied forwarding
headers are not trusted merely because they are present.

Rate limiting and application quotas are defense-in-depth controls, not a
replacement for provider-edge DDoS protection.

## Output, errors, secrets, and telemetry

Handlebars template selection is derived from a constrained strategy id, not
user-authored template source. Rendered Markdown is sanitized for volatile,
signed, unsafe, and tracking-bearing destinations before it is returned.

Domain error sanitizers redact credentials, secret-like assignments, sensitive
query values, private hosts, and IP addresses. HTTP error shaping exposes only
bounded tagged messages and safe context. Cache keys hash sensitive vary
headers; cached provider responses and persisted artifacts remove secret
headers and fields.

Secrets use Effect `Redacted` values and are unwrapped only at outbound library
or provider boundaries. Sentry and OpenTelemetry are optional, sanitize context,
disable default PII behavior, and cannot become request-path dependencies.
MCP Connect URLs require a separate platform-log canary before public exposure,
because application redaction does not prove Railway/CDN/edge retention policy.

## Supply-chain and CI controls

The repository requires Node `>=22`, pnpm `10.28.2`, and a committed
`pnpm-lock.yaml`. pnpm 10's build-script allowlist is declared in
`pnpm-workspace.yaml`. That file is also the authoritative dependency-override
location and currently pins `@opentelemetry/core`, `esbuild`, `hono`, and
`postcss`; the redundant npm-format root override is intentionally not an
authority.

Every executable push runs exact-SHA CI. The gate includes repository rules,
formatting, TypeScript checks, package and application builds, Vitest suites,
generated-artifact drift checks, CLI smoke, packed-skill validation, Docker and
database checks when routed, and a checksum-verified gitleaks working-tree scan
using `.gitleaks.toml` with redacted output. CI does not claim to run `npm audit`.
Dependency advisories are reviewed through the pnpm dependency graph and the
authoritative override policy instead of being represented as a zero-advisory
guarantee.

A successful run is evidence only for its exact commit SHA. Failed, cancelled,
timed-out, missing, or stale runs are not release proof. Railway and Vercel
deployment begins only after every planned package and migration promotion has
completed successfully.

## Operational limits

- Metrics can be public when `METRICS_AUTH_TOKEN` is unset; public deployments
  should configure it.
- `CORS_ALLOWED_ORIGINS` defaults to `*`; browser deployments should set explicit
  production origins when credential semantics require them.
- `/ready` can remain 200 when cache is degraded; operators should inspect its
  body or metrics when Redis availability is critical.
- Supabase Auth settings, Turnstile enforcement, provider mail configuration,
  backups, Stripe configuration, and provider alerts are dashboard-owned and
  require separate live proof.
- Upstream providers remain external dependencies with their own security
  posture and incident response.

## Reporting a vulnerability

Report suspected vulnerabilities to `security@yigitkonur.com` or through a
private GitHub Security Advisory. An acknowledgment is expected within five
business days. Coordinated disclosure is preferred so the issue can be validated
and remediated before public details are released.

In scope are the contextplusplus service, published CLI, HTTP API, MCP server,
website, dashboard, installer, and repository-owned workers. Report issues in
third-party packages or provider services to their respective maintainers unless
the issue is caused by contextplusplus integration behavior.

Social engineering, physical attacks, and unbounded denial-of-service traffic
are out of scope. Rate-limit bypasses, tenant-isolation failures, authentication
bypasses, secret disclosure, SSRF, unsafe rendering, and billing/quota integrity
failures are in scope.
