Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
052746a
Fix security finding acf_063f530a5742d0498761f77e05d88516
raphaeltm Nov 17, 2026
82b5994
Fix security finding acf_8945e62841b7e9ba0e81c197587f84d1
raphaeltm Nov 17, 2026
19834c8
Fix security finding acf_064e2f55492d2ba99b2867ce3bcee6c9
raphaeltm Nov 17, 2026
00f04b4
task: plan bounded Library multipart correction
raphaeltm Nov 17, 2026
dcb89be
fix(library): bound multipart parsing without changing encryption
raphaeltm Nov 17, 2026
b400c6d
test(library): verify historical ciphertext and complete request budgets
raphaeltm Nov 17, 2026
3ea072d
Merge remote-tracking branch 'origin/main' into sam/investigate-compl…
raphaeltm Nov 17, 2026
2f54d76
fix(library): retain shared memory ownership through transfer completion
raphaeltm Nov 17, 2026
4804979
test(library): return owned buffers from MCP resource fixtures
raphaeltm Nov 17, 2026
c2fcfac
refactor(library): simplify bounded multipart parsing
raphaeltm Nov 17, 2026
f44bd1b
docs(task): record final Library validation and release gates
raphaeltm Nov 17, 2026
955b2a4
fix(library): release download ownership for HEAD requests
raphaeltm Nov 17, 2026
fe1e14d
fix(library): preserve retryable debug capture capacity errors
raphaeltm Nov 17, 2026
426b779
Merge origin/main into #2874 branch
raphaeltm Nov 18, 2026
f6dde96
fix: guard cookie-authenticated multipart writes by origin
raphaeltm Nov 18, 2026
0e02535
fix: admit the local dev app origin and cover every multipart sink
raphaeltm Nov 18, 2026
c0f2301
fix(library): share the multipart memory permit as a 50 MiB byte budget
raphaeltm Nov 18, 2026
6d2c177
Merge remote-tracking branch 'origin/main' into codex-security/arp_fe…
raphaeltm Nov 18, 2026
f86af08
fix: count readable task threads with parameterized SQL and test the …
raphaeltm Nov 18, 2026
c1a69e7
fix(library): reserve fixed transfer overhead and size downloads
raphaeltm Nov 18, 2026
aa72226
fix: filter unreadable task threads in the comment ranking SQL
raphaeltm Nov 18, 2026
07aeb09
fix: validate an empty Origin header and correct the JSON preflight c…
raphaeltm Nov 18, 2026
5b4fc0c
Merge origin/main and set the scanner draft aside
raphaeltm Nov 18, 2026
cc11c9f
fix: close a user's project sockets when their project access ends
raphaeltm Nov 18, 2026
af7dcbc
fix: close legacy sockets on revocation and surface failed closes
raphaeltm Nov 18, 2026
d38e623
test(library): expect interactive preview to pass its stored size
raphaeltm Nov 18, 2026
bfa8cc5
fix(inbox): archive closes questions and reviews without telling the …
simple-agent-manager[bot] Nov 18, 2026
78688c8
fix: re-check socket access after admission; page suspension closes
raphaeltm Nov 18, 2026
de65041
Merge remote-tracking branch 'origin/main' into codex-security/arp_5e…
raphaeltm Nov 18, 2026
90c7bc2
Merge remote-tracking branch 'origin/main' into codex-security/arp_fe…
raphaeltm Nov 18, 2026
98b332c
Merge remote-tracking branch 'origin/main' into codex-security/arp_b3…
raphaeltm Nov 18, 2026
8880381
chore(deps): bump workers-ai-provider from 4.0.0 to 4.0.1 (#2796)
dependabot[bot] Nov 18, 2026
0f1681d
Merge origin/main into #2874 branch
raphaeltm Nov 18, 2026
296de59
chore(deps): bump github.com/klauspost/compress in /packages/vm-agent…
dependabot[bot] Nov 18, 2026
1df83b1
feat(selfhost): L20 observability and storage seams
raphaeltm Nov 18, 2026
96d3745
chore(deps): bump github.com/MicahParks/keyfunc/v3 from 3.9.1 to 3.9.…
dependabot[bot] Nov 18, 2026
cede142
test(web): visual audit for the Admin logs/stream server-logs notice
raphaeltm Nov 18, 2026
3bab529
chore(deps): bump yaml from 2.9.0 to 2.9.1 (#2875)
dependabot[bot] Nov 18, 2026
6898d17
fix(selfhost): address L20 review findings
raphaeltm Nov 18, 2026
0d89285
chore(quality): re-pin reviewed gitleaks finding moved by L20
raphaeltm Nov 18, 2026
5bef309
Merge pull request #2865 from raphaeltm/codex-security/arp_5e903d7944…
simple-agent-manager[bot] Nov 18, 2026
3abc8ef
fix(selfhost): address CodeRabbit review on L20
raphaeltm Nov 18, 2026
1603264
chore(deps): bump github.com/moby/patternmatcher in /packages/vm-agen…
dependabot[bot] Nov 18, 2026
d28fe52
Merge pull request #2866 from raphaeltm/codex-security/arp_fe713626c3…
simple-agent-manager[bot] Nov 18, 2026
4dfea4c
Merge pull request #2874 from raphaeltm/sam/investigate-complete-smal…
simple-agent-manager[bot] Nov 18, 2026
974a997
chore(deps): bump ai from 7.0.137 to 7.0.173 (#2877)
dependabot[bot] Nov 18, 2026
0c5fd10
L18: reverse-tunnel cloud-init (frpc boot mode) for self-host (#2885)
simple-agent-manager[bot] Nov 18, 2026
67333b5
ci: run api-unit when the self-host migration projection helpers change
raphaeltm Nov 18, 2026
779f77a
Merge pull request #2867 from raphaeltm/codex-security/arp_b36976cdce…
simple-agent-manager[bot] Nov 18, 2026
c26b3b6
fix(web): Admin Logs/Stream wait for the capabilities answer
raphaeltm Nov 18, 2026
b602eff
test(web): admin logs audit dismisses onboarding and asserts the surf…
raphaeltm Nov 18, 2026
672e9f5
docs(www): journal post on connecting GitHub to an email account (#2890)
simple-agent-manager[bot] Nov 18, 2026
52969c8
Merge origin/main into L20 branch
raphaeltm Nov 18, 2026
4cc8f01
L21: SMTP sign-in and self-host inbound email (#2887)
simple-agent-manager[bot] Nov 18, 2026
c6641dd
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
114e1d9
Merge pull request #2889 from raphaeltm/sam/self-host-landing-slice-t…
simple-agent-manager[bot] Nov 18, 2026
8653496
Merge L18 #2885 (0c5fd10e7) from main into sam/selfhost-pass-2 (M5 st…
raphaeltm Nov 18, 2026
7a05dac
Merge L21 #2887 (4cc8f0198) from main into sam/selfhost-pass-2 (M5 st…
raphaeltm Nov 18, 2026
f46fc91
Merge main 114e1d98b (L20 #2889 and the tip) into sam/selfhost-pass-2…
raphaeltm Nov 18, 2026
d4297e1
fix(selfhost): operator-store presign fixtures carry R2_S3_REGION; do…
raphaeltm Nov 18, 2026
4e2e435
fix(selfhost): M5 review fixes
raphaeltm Nov 18, 2026
6d8126d
task: M5 box evidence (upgrade to 4e2e43509 and smoke)
raphaeltm Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/rules/06-vm-agent-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Required pattern:

1. Edit `packages/cloud-init/src/template.ts`
2. Update variable types in `src/variables.ts`, validation in `src/validate.ts` and wiring in `src/generate.ts` when needed
3. Ingress-mode blocks (Origin CA direct mode, Cloudflare Tunnel mode) live in `src/template-ingress.ts` and render only for their mode; keep user-data under the 32 KB Hetzner limit
3. Ingress-mode blocks (Origin CA direct mode, Cloudflare Tunnel mode) live in `src/template-ingress.ts`, and the self-host reverse-tunnel (frpc) blocks in `src/template-reverse-tunnel.ts`; each renders only for its mode. Keep user-data under the 32 KB Hetzner limit, and keep `tests/cloudflare-output-snapshot.test.ts` passing unchanged when editing shared fragments
4. Test cloud-init generation through the workspace provisioning flow

### Runcmd Interpreter Contract
Expand Down
35 changes: 35 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ jobs:
web-ui: ${{ steps.filter.outputs.web-ui }}
browser-install: ${{ steps.filter.outputs.browser-install }}
go-modules: ${{ steps.filter.outputs.go-modules }}
selfhost-email: ${{ github.event_name == 'push' && 'true' || steps.filter.outputs.selfhost-email }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3
Expand Down Expand Up @@ -135,7 +136,11 @@ jobs:
- 'scripts/deploy/deploy-signing-keys.ts'
- 'scripts/deploy/types.ts'
- 'scripts/deploy/vapid-keys.ts'
- 'scripts/selfhost/observability-migrations.ts'
- 'scripts/selfhost/reverse-tunnel-migrations.ts'
- 'scripts/selfhost/selfhost-migrations.ts'
# selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only).
- 'deploy/selfhost/sam-mx/**'
- 'scripts/quality/node-pool-boundary.ts'
- 'scripts/quality/node-pool-boundary/**'
- 'tests/fixtures/acp-activity-report-v1.json'
Expand Down Expand Up @@ -302,6 +307,29 @@ jobs:
- '**/go.mod'
- '**/go.sum'
- 'scripts/quality/check-go-vulnerability-diff.ts'
# Self-host email: the sam-mx receiver and the SMTP path (landing plan F12, D9).
# Deliberately not packages/cloud-init: the VM path does not reach this code.
selfhost-email:
- 'deploy/selfhost/sam-mx/**'
- 'packages/agent-email/**'
- 'apps/api/src/selfhost/**'
- 'apps/api/src/services/agent-email/**'
- 'apps/api/src/services/email-sign-in.ts'
- 'apps/api/src/services/security-alerts.ts'
- 'apps/api/src/routes/account-linking.ts'
- 'apps/api/src/routes/admin-agent-email.ts'
- 'apps/api/src/routes/auth.ts'
- 'apps/api/src/routes/setup.ts'
- 'apps/api/src/env.ts'
- 'apps/api/tests/unit/routes/setup-email.test.ts'
- 'apps/api/tests/integration/github-link-social.test.ts'
- 'apps/api/tests/helpers/fake-smtp-server.ts'
- 'apps/api/tests/mocks/cloudflare-sockets.ts'
- 'apps/api/tests/integration/selfhost-inbound-email.test.ts'
- 'apps/api/tests/integration/email-sign-in-smtp.test.ts'
- 'apps/api/tests/workers/smtp-client-workerd.test.ts'
- 'apps/api/tests/workers/support/smtp-native-entry.ts'
- '.github/workflows/selfhost-email-tests.yml'

# One job for the PR-body and PR-content checks. They used to be three jobs that each
# spent a runner slot on checkout and install for a few seconds of work. Each check
Expand Down Expand Up @@ -1114,6 +1142,7 @@ jobs:
- hosted-git
- pulumi-infra
- vm-agent-test
- selfhost-email
- cli-test
- vm-agent-integration
- devcontainer
Expand Down Expand Up @@ -1231,6 +1260,12 @@ jobs:
working-directory: packages/vm-agent
run: go test -race ./...

selfhost-email:
name: Self-host Email
needs: [changes]
if: needs.changes.outputs.selfhost-email == 'true' && !github.event.pull_request.draft
uses: ./.github/workflows/selfhost-email-tests.yml

cli-test:
name: CLI Test
needs: [changes]
Expand Down
81 changes: 81 additions & 0 deletions .github/workflows/selfhost-email-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
name: Self-host Email Tests

# The self-host email path (landing plan finding F12, decision D9): the sam-mx SMTP receiver's
# Go tests, the inbound vertical test that builds and runs the real receiver binary, the SMTP
# sign-in tests, and the SMTP client in real workerd. CI calls this only when self-host email
# paths change (never on the cloud-init path filter); it also runs nightly and on demand.
on:
workflow_call:
schedule:
- cron: '41 4 * * *'
workflow_dispatch:

permissions:
contents: read

env:
GO_VERSION: '1.26.11'

jobs:
selfhost-email:
name: Self-host email (sam-mx + SMTP)
# Nightly runs only in the canonical repository; forks dispatch it by hand if they want it.
if: github.event_name != 'schedule' || github.repository == 'raphaeltm/simple-agent-manager'
timeout-minutes: 20
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Setup Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: deploy/selfhost/sam-mx/go.sum

- name: Assert Go version
run: go version | grep -E '^go version go1\.26\.11 '

- name: Vet sam-mx
working-directory: deploy/selfhost/sam-mx
run: go vet ./...

- name: Test sam-mx
working-directory: deploy/selfhost/sam-mx
run: go test -race ./...

- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1

- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
cache: 'pnpm'

- name: Install dependencies
run: pnpm install --frozen-lockfile --ignore-scripts

# Only the lockfile-pinned native builds these tests need (as the CLI contract job does).
- name: Build trusted native dependencies
run: pnpm --filter @simple-agent-manager/api rebuild better-sqlite3 esbuild

- name: Build API dependencies
run: pnpm exec turbo run build --filter=@simple-agent-manager/api^...

# SAM_MX_RECEIVER_TESTS=1 makes the real-receiver block run, and fail rather than skip
# if the Go toolchain is missing.
- name: SMTP and inbound email tests (real sam-mx receiver)
working-directory: apps/api
env:
SAM_MX_RECEIVER_TESTS: '1'
run: >-
pnpm exec vitest run
tests/integration/selfhost-inbound-email.test.ts
tests/integration/email-sign-in-smtp.test.ts
tests/integration/github-link-social.test.ts
tests/unit/routes/setup-email.test.ts
tests/unit/services/smtp-client.test.ts
tests/unit/services/email-transport.test.ts
tests/unit/selfhost/inbound-email-gateway-secret.test.ts

- name: SMTP client in workerd
working-directory: apps/api
run: pnpm exec vitest run --config vitest.sam-runtime.config.ts tests/workers/smtp-client-workerd.test.ts
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 12 additions & 9 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,17 @@ BASE_DOMAIN=workspaces.example.com
# Leave unset for existing/manual installs; do not change during routine updates.
# BOOTSTRAP_OWNER_EMAIL=owner@example.com

# Optional SMTP relay for sign-in codes when the AGENT_EMAIL binding is absent (self-hosted
# installs). Ignored when AGENT_EMAIL exists. SMTP_TLS=none is accepted only for loopback hosts.
# Optional SMTP relay for SAM's own email (sign-in codes, owner security alerts) when the
# AGENT_EMAIL binding is absent (self-hosted installs). Ignored when AGENT_EMAIL exists.
# SMTP_TLS=none is accepted only for loopback hosts.
# SMTP_HOST=smtp.example.com
# SMTP_TLS=starttls
# SMTP_PORT=587
# SMTP_USERNAME=
# SMTP_PASSWORD=
# SMTP_FROM=sign-in@example.com
# Self-hosted box only: "true" when the sam-mx SMTP receiver is installed (inbound agent email).
# AGENT_EMAIL_INBOUND_SMTP=

# Local development secrets (optional, for testing auth)
# GITHUB_CLIENT_ID=
Expand Down Expand Up @@ -1213,6 +1216,8 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000
# ANALYTICS_TOP_EVENTS_LIMIT=50 # Max rows returned by top-events query
# ANALYTICS_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT=20 # Max top pages per section in website traffic
# ANALYTICS_INGEST_ENABLED=true # Set to "false" to accept browser events without writing them
# ANALYTICS_SINK= # Self-host build only: "d1" stores and reads analytics in OBSERVABILITY_DATABASE
# LOG_TAIL_AVAILABLE= # "false" when no tail worker feeds Admin → Stream (self-host)

# Analytics forwarding — external event export (Phase 4)
# ANALYTICS_FORWARD_ENABLED=false # Set to "true" to enable daily batch forwarding
Expand Down Expand Up @@ -1259,13 +1264,11 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000
# R2_ACCESS_KEY_ID= # R2 S3-compatible Access Key ID (required for file attachments)
# R2_SECRET_ACCESS_KEY= # R2 S3-compatible Secret Access Key (required for file attachments)
# R2_BUCKET_NAME= # R2 bucket name (set by deploy script)
# Non-Cloudflare runtimes (celld): presign against the operator's S3 store that holds the R2
# binding's objects. Use a credential limited to R2_S3_KEY_PREFIX, never the fleet credential.
# R2_S3_ENDPOINT= # e.g. https://s3.example.com (unset = Cloudflare R2)
# R2_S3_BUCKET= # store bucket, e.g. celld-fleet
# R2_S3_KEY_PREFIX= # e.g. r2/<R2 bucket name>/
# R2_S3_REGION=auto # SigV4 region (MinIO usually us-east-1)
# R2_S3_FORCE_PATH_STYLE=true # "false" for virtual-host addressing
# R2_S3_ENDPOINT= # Non-Cloudflare runtime only: S3 store holding the R2 binding's objects
# R2_S3_BUCKET= # Bucket in that store (required with R2_S3_ENDPOINT)
# R2_S3_KEY_PREFIX= # Prefix ending in "/" where the binding keeps objects (required with R2_S3_ENDPOINT)
# R2_S3_REGION= # SigV4 signing region of that store (required with R2_S3_ENDPOINT; "auto" for GCS)
# R2_S3_FORCE_PATH_STYLE=true # "false" for virtual-host addressing on that store
# ATTACHMENT_UPLOAD_MAX_BYTES=52428800 # Max per-file attachment size (50MB)
# ATTACHMENT_UPLOAD_BATCH_MAX_BYTES=209715200 # Max total attachment batch size per task (200MB)
# ATTACHMENT_MAX_FILES=20 # Max files per task submission
Expand Down
7 changes: 4 additions & 3 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
"@cloudflare/workers-oauth-provider": "1.2.4",
"@hono/node-server": "1.19.9",
"@hono/valibot-validator": "0.6.1",
"@mastra/core": "1.81.0",
"@mastra/core": "1.84.0",
"@modelcontextprotocol/server": "2.3.1",
"@remix-run/multipart-parser": "1.1.1",
"@simple-agent-manager/agent-email": "workspace:*",
"@simple-agent-manager/ai-proxy": "workspace:*",
"@simple-agent-manager/app-deployment": "workspace:*",
Expand All @@ -45,7 +46,7 @@
"@simple-agent-manager/shared": "workspace:*",
"@simple-agent-manager/worker-core": "workspace:*",
"@valibot/to-json-schema": "catalog:",
"ai": "7.0.137",
"ai": "7.0.173",
"better-auth": "catalog:",
"better-auth-cloudflare": "0.3.1",
"drizzle-orm": "catalog:",
Expand All @@ -55,7 +56,7 @@
"pako": "^2.1.0",
"tsx": "catalog:",
"valibot": "catalog:",
"workers-ai-provider": "4.0.0",
"workers-ai-provider": "4.0.1",
"yaml": "catalog:"
},
"devDependencies": {
Expand Down
21 changes: 10 additions & 11 deletions apps/api/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,18 @@ export interface Env
ASSETS?: Fetcher;
// Agent email (preview): AGENT_EMAIL and AGENT_EMAIL_WORKER_NAME are declared in
// @simple-agent-manager/agent-email's AgentEmailEnv.
// SMTP relay for SAM's own email (sign-in codes) where AGENT_EMAIL is absent, e.g. a
// self-hosted celld box (scripts/selfhost/mail-settings.ts). Ignored when AGENT_EMAIL exists.
// Parsed and validated by @simple-agent-manager/agent-email's smtp-config.ts; invalid settings
// disable it.
// SMTP relay for SAM's own email (sign-in codes, owner security alerts) where AGENT_EMAIL is
// absent, e.g. a self-hosted celld box. Ignored when AGENT_EMAIL exists. Parsed and validated by
// @simple-agent-manager/agent-email's smtp-config.ts; invalid settings disable it.
SMTP_HOST?: string;
SMTP_PORT?: string; // default by SMTP_TLS: 587 (starttls), 465 (tls); required for none
SMTP_TLS?: string; // 'starttls' (default) | 'tls' | 'none' (loopback hosts only)
SMTP_USERNAME?: string;
SMTP_PASSWORD?: string; // secret
SMTP_FROM?: string; // address sign-in codes come from, e.g. sign-in@<BASE_DOMAIN>
// 'true' when the self-host deploy installed the sam-mx SMTP receiver (compose profile mail-in):
// agent email then runs without AGENT_EMAIL, inbound through the loopback gateway route and
// replies over SMTP (services/agent-email/self-host-inbound.ts). Ignored when AGENT_EMAIL exists.
SMTP_FROM?: string; // address SAM's own email comes from, e.g. sign-in@<BASE_DOMAIN>
// 'true' when the self-host deploy installed the sam-mx SMTP receiver: agent email then runs
// without AGENT_EMAIL, inbound through the loopback gateway route and replies over SMTP
// (services/agent-email/self-host-inbound.ts). Ignored when AGENT_EMAIL exists.
AGENT_EMAIL_INBOUND_SMTP?: string;
// Cloudflare Artifacts for SAM-native Git repos (optional — absent when ARTIFACTS_ENABLED is falsy)
ARTIFACTS?: ArtifactsBinding;
Expand Down Expand Up @@ -1288,7 +1287,7 @@ export interface Env
ANALYTICS_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT?: string; // Max top pages per section in website traffic (default: 20)
// Analytics ingest endpoint (Phase 2 — client-side events)
ANALYTICS_INGEST_ENABLED?: string; // "true" (default) or "false"
/** "d1" records and reads product analytics in OBSERVABILITY_DATABASE (self-host; services/analytics-d1-sink.ts). Unset: Analytics Engine. */
/** "d1" records and reads product analytics in OBSERVABILITY_DATABASE when the self-host build installed the D1 sink (selfhost/analytics/). Unset: Analytics Engine. */
ANALYTICS_SINK?: string;
RATE_LIMIT_ANALYTICS_INGEST?: string; // Rate limit per IP per hour (default: 500)
MAX_ANALYTICS_INGEST_BATCH_SIZE?: string; // Max events per batch (default: 25)
Expand Down Expand Up @@ -1328,11 +1327,11 @@ export interface Env
R2_BUCKET_NAME?: string;
// Operator-run S3 store that holds the R2 binding's objects (non-Cloudflare runtimes such as
// celld). When R2_S3_ENDPOINT is set, presigned URLs target R2_S3_BUCKET at
// `${R2_S3_KEY_PREFIX}${key}` instead of Cloudflare R2. See services/r2-s3-client.ts.
// `${R2_S3_KEY_PREFIX}${key}` instead of Cloudflare R2. See services/r2-presign-config.ts.
R2_S3_ENDPOINT?: string;
R2_S3_BUCKET?: string;
R2_S3_KEY_PREFIX?: string;
R2_S3_REGION?: string; // Signing region (default: "auto"; MinIO-style stores usually "us-east-1")
R2_S3_REGION?: string; // Signing region of that store; required with R2_S3_ENDPOINT ("auto" for GCS/R2, e.g. "us-east-1" for MinIO or AWS)
R2_S3_FORCE_PATH_STYLE?: string; // "false" for virtual-host addressing (default with R2_S3_ENDPOINT: path style)
// Task attachment upload limits (all configurable per constitution Principle XI)
ATTACHMENT_UPLOAD_MAX_BYTES?: string;
Expand Down
7 changes: 4 additions & 3 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,12 @@ app.use('*', async (c, next) => {
baseDomain,
appPagesProjectName: c.env.PAGES_PROJECT_NAME,
wwwPagesProjectName: c.env.WWW_PAGES_PROJECT_NAME,
hasWebAssets: c.env.ASSETS !== undefined,
hasWebAssets: Boolean(c.env.ASSETS),
});

// Self-hosted deployments serve the web UI from the Worker's static assets. (`c.env.ASSETS`
// is re-checked only so TypeScript narrows the optional binding.)
// Self-hosted deployments bind the apps/web build as ASSETS and serve app.* from it.
// Cloudflare deployments have no ASSETS binding and keep proxying to Pages. (`c.env.ASSETS` is
// re-checked only so TypeScript narrows the optional binding.)
if (pagesTarget.type === 'assets' && c.env.ASSETS) {
return c.env.ASSETS.fetch(c.req.raw);
}
Expand Down
11 changes: 5 additions & 6 deletions apps/api/src/lib/analytics-config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import type { Env } from '../env';
import { ANALYTICS_EVENTS_TABLE, isAnalyticsD1SinkEnabled } from '../services/analytics-d1-sink';
import { activeLocalAnalyticsSink } from '../services/analytics-sink';

const ANALYTICS_DATASET_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;

export function getAnalyticsDataset(
env: Pick<Env, 'ANALYTICS_DATASET' | 'ANALYTICS_SINK' | 'OBSERVABILITY_DATABASE'>
): string {
// The D1 sink has one fixed table and no generated dataset name.
if (isAnalyticsD1SinkEnabled(env)) return ANALYTICS_EVENTS_TABLE;
export function getAnalyticsDataset(env: Env): string {
// A self-host local sink has one fixed table and no generated dataset name.
const local = activeLocalAnalyticsSink(env);
if (local) return local.table;
const dataset = env.ANALYTICS_DATASET?.trim();

if (!dataset) {
Expand Down
42 changes: 41 additions & 1 deletion apps/api/src/lib/browser-write-origin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
* also admits the marketing and docs hosts, and same-site workspace hosts still receive the
* session cookie, so an origin check is the boundary rather than CORS alone.
*/
import type { MiddlewareHandler } from 'hono';

import type { Env } from '../env';
import { errors } from '../middleware/error';
import { isLocalDevelopmentBaseDomain, LOCAL_DEVELOPMENT_HOSTS } from './cors-origin';
import { getTrustedApiOrigin } from './trusted-origins';

/** `https://app.<BASE_DOMAIN>`, derived from the trusted API origin. */
Expand All @@ -16,6 +19,23 @@ export function exactAppOrigin(env: Pick<Env, 'BASE_DOMAIN'>): string {
return url.toString().replace(/\/$/u, '');
}

/**
* Local development serves the app from a loopback port (Vite, `:5173`) while the API runs on
* another (`BASE_DOMAIN=localhost:8787`), so the derived app origin cannot match there. Loopback
* origins are admitted only when BASE_DOMAIN itself is local, the rule `appFrameAncestors` and
* credentialed CORS already use.
*/
function isAppOrigin(origin: string, env: Pick<Env, 'BASE_DOMAIN'>): boolean {
if (origin === exactAppOrigin(env)) return true;
if (!isLocalDevelopmentBaseDomain(env.BASE_DOMAIN)) return false;
try {
const url = new URL(origin);
return url.protocol === 'http:' && LOCAL_DEVELOPMENT_HOSTS.includes(url.hostname);
} catch {
return false;
}
}

export function requireExactBrowserOrigin(
c: { req: { header: (name: string) => string | undefined }; env: Env },
what = 'interaction'
Expand All @@ -25,7 +45,27 @@ export function requireExactBrowserOrigin(
if (fetchSite === 'cross-site') {
throw errors.forbidden(`Cross-site ${what} writes are not allowed`);
}
if (!origin || origin !== exactAppOrigin(c.env)) {
if (!origin || !isAppOrigin(origin, c.env)) {
throw errors.forbidden(`Untrusted ${what} write origin`);
}
}

/**
* Guard a cookie-authenticated write that is also available to non-browser API clients.
* Browsers attach Origin to unsafe cross-origin requests and modern browsers also attach Fetch
* Metadata; if either signal is present, require the exact app origin. Clients with neither
* browser-controlled header retain their authenticated API path.
*/
export function requireTrustedWriteOrigin(
what = 'state-changing'
): MiddlewareHandler<{ Bindings: Env }> {
return async (c, next) => {
const origin = c.req.header('Origin');
const fetchSite = c.req.header('Sec-Fetch-Site');
// `undefined` is "header absent"; an empty Origin is still a browser signal to validate.
if (origin !== undefined || fetchSite !== undefined) {
requireExactBrowserOrigin(c, what);
}
await next();
};
}
Loading
Loading