diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1601d5e171..00dbbf093e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,7 +133,9 @@ 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' diff --git a/.pr-evidence/2889/admin-logs-cloudflare-desktop-1280x800.png b/.pr-evidence/2889/admin-logs-cloudflare-desktop-1280x800.png new file mode 100644 index 0000000000..0201ce4053 Binary files /dev/null and b/.pr-evidence/2889/admin-logs-cloudflare-desktop-1280x800.png differ diff --git a/.pr-evidence/2889/admin-logs-cloudflare-mobile-375x667.png b/.pr-evidence/2889/admin-logs-cloudflare-mobile-375x667.png new file mode 100644 index 0000000000..f09af653b1 Binary files /dev/null and b/.pr-evidence/2889/admin-logs-cloudflare-mobile-375x667.png differ diff --git a/.pr-evidence/2889/admin-logs-notice-dark-desktop-1280x800.png b/.pr-evidence/2889/admin-logs-notice-dark-desktop-1280x800.png new file mode 100644 index 0000000000..9c2d36be53 Binary files /dev/null and b/.pr-evidence/2889/admin-logs-notice-dark-desktop-1280x800.png differ diff --git a/.pr-evidence/2889/admin-logs-notice-dark-mobile-375x667.png b/.pr-evidence/2889/admin-logs-notice-dark-mobile-375x667.png new file mode 100644 index 0000000000..da002b3a97 Binary files /dev/null and b/.pr-evidence/2889/admin-logs-notice-dark-mobile-375x667.png differ diff --git a/.pr-evidence/2889/admin-logs-notice-light-desktop-1280x800.png b/.pr-evidence/2889/admin-logs-notice-light-desktop-1280x800.png new file mode 100644 index 0000000000..eccc457b8e Binary files /dev/null and b/.pr-evidence/2889/admin-logs-notice-light-desktop-1280x800.png differ diff --git a/.pr-evidence/2889/admin-logs-notice-light-mobile-375x667.png b/.pr-evidence/2889/admin-logs-notice-light-mobile-375x667.png new file mode 100644 index 0000000000..99fcaf2e74 Binary files /dev/null and b/.pr-evidence/2889/admin-logs-notice-light-mobile-375x667.png differ diff --git a/.pr-evidence/2889/admin-stream-cloudflare-desktop-1280x800.png b/.pr-evidence/2889/admin-stream-cloudflare-desktop-1280x800.png new file mode 100644 index 0000000000..a821a6c321 Binary files /dev/null and b/.pr-evidence/2889/admin-stream-cloudflare-desktop-1280x800.png differ diff --git a/.pr-evidence/2889/admin-stream-cloudflare-mobile-375x667.png b/.pr-evidence/2889/admin-stream-cloudflare-mobile-375x667.png new file mode 100644 index 0000000000..29d489d52c Binary files /dev/null and b/.pr-evidence/2889/admin-stream-cloudflare-mobile-375x667.png differ diff --git a/.pr-evidence/2889/admin-stream-notice-dark-desktop-1280x800.png b/.pr-evidence/2889/admin-stream-notice-dark-desktop-1280x800.png new file mode 100644 index 0000000000..efcdcf476e Binary files /dev/null and b/.pr-evidence/2889/admin-stream-notice-dark-desktop-1280x800.png differ diff --git a/.pr-evidence/2889/admin-stream-notice-dark-mobile-375x667.png b/.pr-evidence/2889/admin-stream-notice-dark-mobile-375x667.png new file mode 100644 index 0000000000..fc22023aaa Binary files /dev/null and b/.pr-evidence/2889/admin-stream-notice-dark-mobile-375x667.png differ diff --git a/.pr-evidence/2889/admin-stream-notice-light-desktop-1280x800.png b/.pr-evidence/2889/admin-stream-notice-light-desktop-1280x800.png new file mode 100644 index 0000000000..4912ece782 Binary files /dev/null and b/.pr-evidence/2889/admin-stream-notice-light-desktop-1280x800.png differ diff --git a/.pr-evidence/2889/admin-stream-notice-light-mobile-375x667.png b/.pr-evidence/2889/admin-stream-notice-light-mobile-375x667.png new file mode 100644 index 0000000000..965e93eaf7 Binary files /dev/null and b/.pr-evidence/2889/admin-stream-notice-light-mobile-375x667.png differ diff --git a/apps/api/.env.example b/apps/api/.env.example index 1b4e2a4bfa..a726c3fd3e 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -1208,6 +1208,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 @@ -1254,6 +1256,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) +# 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 diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index fd5dc54d3c..b663622905 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -62,6 +62,9 @@ export interface Env R2: R2Bucket; // Private R2 archive for ProjectData tool payload JSON PROJECT_DATA_ARCHIVE_R2: R2Bucket; + // apps/web build served for app.${BASE_DOMAIN}. Bound only on self-hosted (celld) + // deployments; Cloudflare deployments serve the web UI from Pages (lib/pages-proxy.ts). + ASSETS?: Fetcher; // Workers AI for speech-to-text transcription AI: Ai; // Agent email (preview): AGENT_EMAIL and AGENT_EMAIL_WORKER_NAME are declared in @@ -1262,6 +1265,8 @@ 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 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) MAX_ANALYTICS_INGEST_BODY_BYTES?: string; // Max request body bytes (default: 65536) @@ -1298,6 +1303,14 @@ export interface Env R2_SECRET_ACCESS_KEY?: string; // R2 bucket name (runtime — set by wrangler sync script; used for presigned URL generation) 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-presign-config.ts. + R2_S3_ENDPOINT?: string; + R2_S3_BUCKET?: string; + R2_S3_KEY_PREFIX?: string; + 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; ATTACHMENT_UPLOAD_BATCH_MAX_BYTES?: string; @@ -1463,6 +1476,8 @@ export interface Env CF_CONTAINER_HARNESS_LEASE_CHECK_TIMEOUT_MS?: string; // Max time for the ProjectData RPC that checks harness work lease before sleep (default: 5000) CF_CONTAINER_CLONE_FILTER?: string; // Git partial-clone filter passed to the container as STANDALONE_CLONE_FILTER (vm-agent default: blob:none; "off" disables) CF_CONTAINER_WORKSPACE_BASE_DIR?: string; // Base checkout dir inside raw container (default: /workspaces) + /** "false" when no tail consumer feeds the AdminLogs DO (self-host: celld has no tail handler). Unset: available. */ + LOG_TAIL_AVAILABLE?: string; // Legacy Sandbox SDK prototype (admin-only) SANDBOX_ENABLED?: string; // Legacy/fallback kill switch for sandbox routes and older staging config (default: false) SANDBOX_EXEC_TIMEOUT_MS?: string; // Default exec timeout in ms (default: 30000) diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 5ad2fec527..23106265cb 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -205,7 +205,8 @@ app.use('*', async (c, next) => { await next(); }); -// Proxy non-API subdomains to their respective Cloudflare Pages deployments. +// Proxy non-API subdomains to their respective Cloudflare Pages deployments (or, on a +// self-hosted deployment with an ASSETS binding, serve app.* from the Worker's assets). // The Worker wildcard route *.{domain}/* intercepts ALL subdomains, so we must // proxy app.* and www.* requests to Pages before any other middleware runs. // The apex domain is redirected to www.* for the marketing site. @@ -221,8 +222,16 @@ app.use('*', async (c, next) => { baseDomain, appPagesProjectName: c.env.PAGES_PROJECT_NAME, wwwPagesProjectName: c.env.WWW_PAGES_PROJECT_NAME, + hasWebAssets: Boolean(c.env.ASSETS), }); + // 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); + } + if (pagesTarget.type === 'missing-config') { return c.text(pagesTarget.message, 503); } diff --git a/apps/api/src/lib/analytics-config.ts b/apps/api/src/lib/analytics-config.ts index e5a50dad39..1cae70ce5c 100644 --- a/apps/api/src/lib/analytics-config.ts +++ b/apps/api/src/lib/analytics-config.ts @@ -1,8 +1,12 @@ import type { Env } from '../env'; +import { activeLocalAnalyticsSink } from '../services/analytics-sink'; const ANALYTICS_DATASET_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; -export function getAnalyticsDataset(env: Pick): string { +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) { diff --git a/apps/api/src/lib/pages-proxy.ts b/apps/api/src/lib/pages-proxy.ts index c12c253d41..5744d27fdd 100644 --- a/apps/api/src/lib/pages-proxy.ts +++ b/apps/api/src/lib/pages-proxy.ts @@ -1,5 +1,6 @@ export type PagesProxyTarget = | { type: 'none' } + | { type: 'assets' } | { type: 'proxy'; hostname: string } | { type: 'missing-config'; message: string } | { type: 'redirect'; hostname: string }; @@ -8,6 +9,12 @@ export interface PagesProxyConfig { baseDomain: string; appPagesProjectName?: string; wwwPagesProjectName?: string; + /** + * True when the Worker has an `ASSETS` binding holding the apps/web build. Only + * self-hosted (celld) deployments bind it (`scripts/selfhost/celld-config.ts`); Cloudflare + * deployments serve the web UI from Pages and never set it. + */ + hasWebAssets?: boolean; } export function resolvePagesProxyTarget( @@ -19,6 +26,9 @@ export function resolvePagesProxyTarget( } if (hostname === `app.${config.baseDomain}`) { + if (config.hasWebAssets) { + return { type: 'assets' }; + } if (!config.appPagesProjectName) { return { type: 'missing-config', message: 'PAGES_PROJECT_NAME is not configured' }; } diff --git a/apps/api/src/middleware/analytics.ts b/apps/api/src/middleware/analytics.ts index a7f58ad29c..9b34439098 100644 --- a/apps/api/src/middleware/analytics.ts +++ b/apps/api/src/middleware/analytics.ts @@ -2,6 +2,7 @@ import type { MiddlewareHandler } from 'hono'; import type { Env } from '../env'; import { log } from '../lib/logger'; +import { resolveAnalyticsSink } from '../services/analytics-sink'; // --------------------------------------------------------------------------- // Event name mapping: HTTP method + route pattern → human-readable event name @@ -176,8 +177,8 @@ export function analyticsMiddleware(): MiddlewareHandler<{ Bindings: Env }> { const enabled = c.env.ANALYTICS_ENABLED !== 'false'; if (!enabled) return; - // Check if the binding exists (graceful degradation for local dev) - const analytics = c.env.ANALYTICS; + // Analytics Engine, or a self-host local sink (graceful degradation for local dev) + const analytics = resolveAnalyticsSink(c.env); if (!analytics) return; const path = new URL(c.req.url).pathname; @@ -232,7 +233,7 @@ export function analyticsMiddleware(): MiddlewareHandler<{ Bindings: Env }> { const responseTimeMs = Date.now() - startTime; const statusCode = c.res.status; - await analytics.writeDataPoint({ + await analytics.write([{ indexes: [userId], blobs: [ eventName, // blob1 @@ -252,7 +253,7 @@ export function analyticsMiddleware(): MiddlewareHandler<{ Bindings: Env }> { statusCode, // double2 0, // double3 (reserved) ], - }); + }]); } catch (err) { // Analytics failures must NEVER surface to the user log.warn('analytics.write_failed', { error: err instanceof Error ? err.message : String(err) }); diff --git a/apps/api/src/routes/admin-analytics-query.ts b/apps/api/src/routes/admin-analytics-query.ts index 12a0135d81..60321517b7 100644 --- a/apps/api/src/routes/admin-analytics-query.ts +++ b/apps/api/src/routes/admin-analytics-query.ts @@ -5,7 +5,9 @@ import { log } from '../lib/logger'; import { readResponseJson } from '../lib/runtime-validation'; import { errors } from '../middleware/error'; import { resolveAdminSetting } from '../services/admin-settings-resolution'; +import { activeLocalAnalyticsSink } from '../services/analytics-sink'; import { fetchWithTimeout } from '../services/fetch-timeout'; +import { hasCloudflareAccountApi } from '../services/platform-capabilities'; export const DEFAULT_ANALYTICS_SQL_API_URL = 'https://api.cloudflare.com/client/v4/accounts'; @@ -68,16 +70,24 @@ export const FEATURE_EVENTS = [ ]; /** - * Execute an Analytics Engine SQL query via the Cloudflare API. + * Execute an Analytics Engine SQL query via the Cloudflare API, or, when the self-host build + * installed a local sink that is active here, the same query against that store. */ export async function queryAnalyticsEngine(env: Env, sql: string): Promise { + const local = activeLocalAnalyticsSink(env); + if (local) return local.query(env, sql); + + // The SQL API is Cloudflare's. Without an account to query there is no analytics to show; + // that is a property of the installation, not a server fault. + if (!hasCloudflareAccountApi(env)) { + throw errors.featureUnavailable( + 'analyticsQuery', + 'Analytics is not available on this installation' + ); + } const baseUrl = env.ANALYTICS_SQL_API_URL || DEFAULT_ANALYTICS_SQL_API_URL; const accountId = env.CF_ACCOUNT_ID; - if (!accountId) { - throw errors.internal('CF_ACCOUNT_ID is not configured'); - } - const url = `${baseUrl}/${accountId}/analytics_engine/sql`; const response = await fetchWithTimeout( diff --git a/apps/api/src/routes/admin-analytics.ts b/apps/api/src/routes/admin-analytics.ts index e41a6629c3..6856a39fbc 100644 --- a/apps/api/src/routes/admin-analytics.ts +++ b/apps/api/src/routes/admin-analytics.ts @@ -3,7 +3,9 @@ import { Hono } from 'hono'; import type { Env } from '../env'; import { getAnalyticsDataset } from '../lib/analytics-config'; import { requireApproved, requireAuth, requireSuperadmin } from '../middleware/auth'; +import { errors } from '../middleware/error'; import { getForwardStatus } from '../services/analytics-forward'; +import { resolvePlatformCapabilities } from '../services/platform-capabilities'; import { DEFAULT_PERIOD_DAYS, DEFAULT_TOP_EVENTS_LIMIT, @@ -18,6 +20,22 @@ const adminAnalyticsRoutes = new Hono<{ Bindings: Env }>(); // All analytics routes require superadmin adminAnalyticsRoutes.use('/*', requireAuth(), requireApproved(), requireSuperadmin()); + +// Every query route reads Cloudflare's Analytics Engine SQL API, or a self-host local sink. With +// neither there is nothing to query (and no dataset name is configured), so answer "not available" +// before any route builds SQL. Forward status is local state and stays readable. Pure: no I/O. +adminAnalyticsRoutes.use('/*', async (c, next) => { + if ( + !resolvePlatformCapabilities(c.env).analyticsQuery && + !c.req.path.endsWith('/forward-status') + ) { + throw errors.featureUnavailable( + 'analyticsQuery', + 'Analytics is not available on this installation' + ); + } + await next(); +}); /** * GET /api/admin/analytics/dau — Daily active users (last N days) */ diff --git a/apps/api/src/routes/admin/observability.ts b/apps/api/src/routes/admin/observability.ts index 410c5d519b..cc907d83fb 100644 --- a/apps/api/src/routes/admin/observability.ts +++ b/apps/api/src/routes/admin/observability.ts @@ -27,6 +27,7 @@ import { getLogQueryRateLimit, queryErrors, } from '../../services/observability'; +import { hasLiveLogStream } from '../../services/platform-capabilities'; import { runPlatformFeedbackTriage } from '../../services/platform-feedback-triage'; import { queryWorkerLogs, @@ -327,6 +328,13 @@ adminObservabilityRoutes.get('/logs/stream', async (c) => { if (!upgradeHeader || upgradeHeader.toLowerCase() !== 'websocket') { throw errors.badRequest('WebSocket upgrade required'); } + // Nothing feeds the AdminLogs DO without a tail worker; refuse instead of an empty stream. + if (!hasLiveLogStream(c.env)) { + throw errors.featureUnavailable( + 'liveLogStream', + 'The live log stream is not available on this installation; read logs on the server' + ); + } // Forward the upgrade request to the AdminLogs DO singleton const doId = c.env.ADMIN_LOGS.idFromName('admin-logs'); diff --git a/apps/api/src/routes/analytics-ingest.ts b/apps/api/src/routes/analytics-ingest.ts index 8967cff276..c4f2a85f38 100644 --- a/apps/api/src/routes/analytics-ingest.ts +++ b/apps/api/src/routes/analytics-ingest.ts @@ -8,6 +8,7 @@ import { bucketUserAgent } from '../middleware/analytics'; import { optionalAuth } from '../middleware/auth'; import { errors } from '../middleware/error'; import { getRateLimit, rateLimit } from '../middleware/rate-limit'; +import { resolveAnalyticsSink } from '../services/analytics-sink'; /** Default max body size: 64 KB (configurable via MAX_ANALYTICS_INGEST_BODY_BYTES) */ const DEFAULT_MAX_BODY_BYTES = 65_536; @@ -122,11 +123,11 @@ analyticsIngestRoutes.post('/', async (c) => { return c.body(null, 204); } - // Check if Analytics Engine binding exists (graceful degradation) - if (!c.env.ANALYTICS) { + // Analytics Engine, or a self-host local sink (graceful degradation) + const analytics = resolveAnalyticsSink(c.env); + if (!analytics) { return c.body(null, 204); } - const analytics = c.env.ANALYTICS; const maxBodyBytes = parseInt( c.env.MAX_ANALYTICS_INGEST_BODY_BYTES || String(DEFAULT_MAX_BODY_BYTES), @@ -202,9 +203,10 @@ analyticsIngestRoutes.post('/', async (c) => { /* malformed origin — ignore */ } - // Write each valid event to Analytics Engine (fire-and-forget via waitUntil) + // Write every valid event to the sink in one call (fire-and-forget via waitUntil) const writeAll = async () => { try { + const points: AnalyticsEngineDataPoint[] = []; for (const raw of events) { const validated = validateEvent(raw, maxDurationMs); if (!validated) continue; @@ -217,7 +219,7 @@ analyticsIngestRoutes.post('/', async (c) => { // (browsers enforce Origin on cross-origin requests; client JSON body is untrusted) const host = serverHost || validated.host; - analytics.writeDataPoint({ + points.push({ indexes: [index], blobs: [ validated.event, // blob1: event name @@ -239,6 +241,7 @@ analyticsIngestRoutes.post('/', async (c) => { ], }); } + await analytics.write(points); } catch (err) { log.warn('analytics_ingest.write_failed', { error: err instanceof Error ? err.message : String(err), diff --git a/apps/api/src/routes/projects/publish-job-spec.ts b/apps/api/src/routes/projects/publish-job-spec.ts index b883a17f6a..194992b090 100644 --- a/apps/api/src/routes/projects/publish-job-spec.ts +++ b/apps/api/src/routes/projects/publish-job-spec.ts @@ -1,10 +1,10 @@ -import { createBuildContextDownload } from '@simple-agent-manager/app-deployment'; import { Hono } from 'hono'; import type { Env } from '../../env'; import { extractBearerToken } from '../../lib/auth-helpers'; import { errors } from '../../middleware/error'; import { resolveAdminSetting } from '../../services/admin-settings'; +import { createBuildContextDownload } from '../../services/build-context-upload'; import { loadDeploymentBuildInterpolationEnv } from '../../services/deployment-environment-config'; import { verifyPublishJobToken } from '../../services/publish-job-token'; diff --git a/apps/api/src/routes/tasks/upload.ts b/apps/api/src/routes/tasks/upload.ts index 4f20c3f4c1..5c186f66b3 100644 --- a/apps/api/src/routes/tasks/upload.ts +++ b/apps/api/src/routes/tasks/upload.ts @@ -23,6 +23,7 @@ import { errors } from '../../middleware/error'; import { requireProjectCapability } from '../../middleware/project-auth'; import { jsonValidator, RequestAttachmentUploadSchema } from '../../schemas'; import { generatePresignedUploadUrl } from '../../services/attachment-upload'; +import { hasR2S3Credentials } from '../../services/r2-s3-client'; const uploadRoutes = new Hono<{ Bindings: Env }>(); @@ -50,8 +51,8 @@ uploadRoutes.post('/request-upload', requireAuth(), requireApproved(), jsonValid // Validate project ownership await requireProjectCapability(db, projectId, userId, 'task:write'); - // Check R2 S3 credentials are configured - if (!c.env.R2_ACCESS_KEY_ID || !c.env.R2_SECRET_ACCESS_KEY) { + // Check presigning is configured (Cloudflare R2 or an operator store; one shared check) + if (!hasR2S3Credentials(c.env)) { throw errors.forbidden('File attachments are not configured (R2 S3 credentials missing)'); } diff --git a/apps/api/src/scheduled/observability-purge.ts b/apps/api/src/scheduled/observability-purge.ts index 92aea47e75..ccbacf1a12 100644 --- a/apps/api/src/scheduled/observability-purge.ts +++ b/apps/api/src/scheduled/observability-purge.ts @@ -8,6 +8,8 @@ * See: specs/023-admin-observability/tasks.md (T023-T024) */ import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { activeLocalAnalyticsSink } from '../services/analytics-sink'; import { purgeExpiredErrors, type PurgeResult } from '../services/observability'; export async function runObservabilityPurge(env: Env): Promise { @@ -15,5 +17,28 @@ export async function runObservabilityPurge(env: Env): Promise { return { deletedByAge: 0, deletedByCount: 0 }; } - return purgeExpiredErrors(env.OBSERVABILITY_DATABASE, env); + // The error purge and the self-host analytics purge are isolated from each other (rule 53): + // a failure in either must not stop the other's retention. The error purge's failure is + // rethrown after the analytics purge ran, so the cron still records it. + let errorPurge: PurgeResult | undefined; + let errorPurgeFailure: unknown; + try { + errorPurge = await purgeExpiredErrors(env.OBSERVABILITY_DATABASE, env); + } catch (err) { + errorPurgeFailure = err; + } + // Self-host local analytics sink: age and row-cap bound. No call at all on Cloudflare, where + // nothing is installed. + const local = activeLocalAnalyticsSink(env); + if (local) { + try { + await local.purge(env); + } catch (err) { + log.error('analytics.local_purge_failed', { + error: err instanceof Error ? err.message : String(err), + }); + } + } + if (errorPurge === undefined) throw errorPurgeFailure; + return errorPurge; } diff --git a/apps/api/src/selfhost/analytics/d1-sink.ts b/apps/api/src/selfhost/analytics/d1-sink.ts new file mode 100644 index 0000000000..6f214de4e3 --- /dev/null +++ b/apps/api/src/selfhost/analytics/d1-sink.ts @@ -0,0 +1,334 @@ +/** + * D1 analytics sink for installations without Workers Analytics Engine (self-host on celld). + * + * Installed only by the self-host entry (`./index.ts`, `installAnalyticsD1Sink`). When the + * deployment also sets `ANALYTICS_SINK="d1"`, BOTH sides of product analytics move to the + * `analytics_events` table in `OBSERVABILITY_DATABASE` through the shared seam + * (`services/analytics-sink.ts`): + * - writes: the request middleware and the `/api/t` ingest route call `resolveAnalyticsSink()`; + * - reads: `queryAnalyticsEngine()` runs the admin queries here after `translateAnalyticsSql()`. + * Because one `active(env)` answer decides both, a deployment can never record into one store and + * read from the other. The Cloudflare Worker never imports this module. + * + * Write cost: one single-row INSERT per recorded API request (the middleware), one batched + * INSERT per `/api/t` call; both run in `waitUntil`, never on the response path. Each row holds + * at most ~1.3 KB (blob lengths are capped below). On celld a D1 write is one object-store + * round trip (p50 70-98 ms on GCS), so this costs one store write per recorded request. + * Growth bound: `purgeAnalyticsEvents()` runs in the 5-minute observability purge and deletes + * rows older than the admin setting analytics.d1.retentionDays (default 90, the longest admin + * period) and the oldest rows above analytics.d1.maxRows (default 500,000; ~650 MB worst case). + * + * No secrets: rows hold the fields Analytics Engine receives, minus detail: the page is stored + * without query string or fragment and with sensitive segments redacted, the referrer as its + * origin only, and an anonymous visitor's IP as its network prefix, so tokens in links (query + * strings, invite paths) and full client addresses are never kept. + */ +import { isSensitiveAnalyticsPathSegment } from '@simple-agent-manager/shared'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { resolveAdminSettingDetailsMany } from '../../services/admin-settings-resolution'; +import type { AnalyticsSink } from '../../services/analytics-sink'; +import { + ANALYTICS_D1_MAX_ROWS_SETTING, + ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING, + ANALYTICS_D1_PURGE_TICK_BUDGET_MS_SETTING, + ANALYTICS_D1_RETENTION_DAYS_SETTING, + DEFAULT_ANALYTICS_D1_MAX_ROWS, + DEFAULT_ANALYTICS_D1_PURGE_BATCH_ROWS, + DEFAULT_ANALYTICS_D1_PURGE_TICK_BUDGET_MS, + DEFAULT_ANALYTICS_D1_RETENTION_DAYS, +} from './settings'; + +export const ANALYTICS_EVENTS_TABLE = 'analytics_events'; +/** Longest stored blob; Analytics Engine caps the whole point at 16 KB, we keep rows small. */ +export const ANALYTICS_D1_MAX_BLOB_LENGTH = 256; +/** 1 index + 11 blobs + 3 doubles = 15 binds per row: one statement per row, under D1's 100. */ +const BLOB_COUNT = 11; +const DOUBLE_COUNT = 3; + +/** Whether this installation records and reads product analytics in D1. Pure: no I/O. */ +export function isAnalyticsD1SinkEnabled( + env: Pick +): boolean { + return env.ANALYTICS_SINK?.trim().toLowerCase() === 'd1' && !!env.OBSERVABILITY_DATABASE; +} + +/** The D1 sink for this installation's observability database. */ +export function analyticsD1Sink(db: D1Database): AnalyticsSink { + return { write: (points) => writeAnalyticsPointsToD1(db, points) }; +} + +/** Strip query string and fragment: a link can carry a token there. */ +function withoutQuery(value: string): string { + const cut = value.search(/[?#]/); + return cut === -1 ? value : value.slice(0, cut); +} + +const REDACTED_SEGMENT = '[redacted]'; + +/** + * The page path without query or fragment, with sensitive segments redacted by the same rule the + * web tracker applies (`isSensitiveAnalyticsPathSegment`, packages/shared/src/analytics-path.ts). + * `/api/t` accepts any page value, so the server cannot rely on the tracker having normalized it. + * Route-pattern parameters (`:projectId`, from the request middleware) are kept: they are names, + * not values, and admin queries group by them. + */ +function redactedPath(value: string): string { + const segments = withoutQuery(value).split('/'); + return segments + .map((segment, index) => { + if (!segment || segment.startsWith(':')) return segment; + const previous = index > 0 ? segments[index - 1] : undefined; + return isSensitiveAnalyticsPathSegment(segment, previous) ? REDACTED_SEGMENT : segment; + }) + .join('/'); +} + +/** + * The ingest route indexes anonymous browser events as `anon-`. The D1 sink keeps only + * the network prefix (IPv4 /24, IPv6 /48), enough to count distinct visitors roughly without + * storing a full address. Any other index (a user id) is stored as is. + */ +function maskedIndex(value: string): string { + if (!value.startsWith('anon-')) return value; + const ip = value.slice('anon-'.length); + const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/.exec(ip); + if (v4) return `anon-${v4[1]}.${v4[2]}.${v4[3]}.0/24`; + if (ip.includes(':')) { + const groups = (ip.split('::')[0] ?? '').split(':').filter(Boolean); + return `anon-${groups.slice(0, 3).join(':') || '0'}::/48`; + } + return 'anon'; +} + +function originOnly(value: string): string { + if (!value) return ''; + try { + return new URL(value).origin; + } catch { + return ''; + } +} + +function blobAt(point: AnalyticsEngineDataPoint, index: number): string { + const raw = point.blobs?.[index]; + let text = raw === null || raw === undefined ? '' : typeof raw === 'string' ? raw : ''; + // blob3 (page / route pattern): path only. The web tracker already redacts id- and + // token-shaped segments (apps/web/src/lib/analytics.ts normalizeAnalyticsPath). + if (index === 2) text = redactedPath(text); + // blob4 (referrer): origin only. For API requests it is the browser's Referer, the full app + // URL, whose path can carry a token (invite links); no admin query reads more than the origin. + if (index === 3) text = originOnly(text); + return text.slice(0, ANALYTICS_D1_MAX_BLOB_LENGTH); +} + +function doubleAt(point: AnalyticsEngineDataPoint, index: number): number { + const value = point.doubles?.[index]; + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +const INSERT_SQL = `INSERT INTO ${ANALYTICS_EVENTS_TABLE} (timestamp, index1, ${Array.from( + { length: BLOB_COUNT }, + (_, i) => `blob${i + 1}` +).join(', ')}, double1, double2, double3) VALUES (datetime('now'), ?, ${Array( + BLOB_COUNT + DOUBLE_COUNT +) + .fill('?') + .join(', ')})`; + +export async function writeAnalyticsPointsToD1( + db: D1Database, + points: AnalyticsEngineDataPoint[] +): Promise { + if (points.length === 0) return; + const statements = points.map((point) => { + const index = maskedIndex(String(point.indexes?.[0] ?? '')).slice( + 0, + ANALYTICS_D1_MAX_BLOB_LENGTH + ); + const blobs = Array.from({ length: BLOB_COUNT }, (_, i) => blobAt(point, i)); + const doubles = Array.from({ length: DOUBLE_COUNT }, (_, i) => doubleAt(point, i)); + return db.prepare(INSERT_SQL).bind(index, ...blobs, ...doubles); + }); + const [only] = statements; + if (statements.length === 1 && only) await only.run(); + else await db.batch(statements); +} + +/** + * Translate the Analytics Engine SQL dialect used by the admin analytics routes into SQLite. + * Covers exactly the constructs those routes use; anything else Analytics-Engine-specific left + * after translation is refused, so a new admin query fails loudly instead of returning wrong + * numbers on self-host. + */ +export function translateAnalyticsSql(sql: string): string { + let out = sql; + // FROM -> the D1 table (the dataset name is an identifier, see analytics-config.ts). + out = out.replace(/\bFROM\s+[A-Za-z_][A-Za-z0-9_]*/g, `FROM ${ANALYTICS_EVENTS_TABLE}`); + // NOW() - INTERVAL 'N' DAY + out = out.replace( + /NOW\(\)\s*-\s*INTERVAL\s*'(\d+)'\s*DAY/gi, + (_m, days: string) => `datetime('now', '-${Number(days)} days')` + ); + // toStartOfInterval(timestamp, INTERVAL 'N' DAY): epoch-aligned N-day buckets, as in AE. + out = out.replace( + /toStartOfInterval\(\s*timestamp\s*,\s*INTERVAL\s*'(\d+)'\s*DAY\s*\)/gi, + (_m, days: string) => { + const seconds = Number(days) * 86_400; + return `datetime((CAST(strftime('%s', timestamp) AS INTEGER) / ${seconds}) * ${seconds}, 'unixepoch')`; + } + ); + out = out.replace(/toDate\(\s*timestamp\s*\)/gi, 'date(timestamp)'); + out = out.replace(/\bcount\(\s*\)/gi, 'count(*)'); + + const leftover = + /(\bINTERVAL\b|\b(?:NOW|toStartOf\w*|toDate\w*|formatDateTime|quantile\w*|uniq\w*|if|countIf|sumIf)\s*\(|\b_sample_interval\b)/i.exec( + out + ); + if (leftover) { + throw new Error(`Analytics query uses "${leftover[1]}", which the D1 sink cannot translate`); + } + return out; +} + +/** Run an admin analytics query (Analytics Engine dialect) against the D1 sink. */ +export async function queryAnalyticsD1(db: D1Database, sql: string): Promise { + const result = await db.prepare(translateAnalyticsSql(sql)).all(); + return result.results ?? []; +} + +function positiveInteger(value: unknown, fallback: number): number { + return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback; +} + +interface RetentionSettings { + days: number; + maxRows: number; + batchRows: number; + tickBudgetMs: number; +} + +const DEFAULT_RETENTION: RetentionSettings = { + days: DEFAULT_ANALYTICS_D1_RETENTION_DAYS, + maxRows: DEFAULT_ANALYTICS_D1_MAX_ROWS, + batchRows: DEFAULT_ANALYTICS_D1_PURGE_BATCH_ROWS, + tickBudgetMs: DEFAULT_ANALYTICS_D1_PURGE_TICK_BUDGET_MS, +}; + +/** + * Retention bounds in one settings read, or null when the settings store cannot be read. A + * default must not stand in for the operator's policy here: with retention set to 180 days, a + * 90-day fallback would permanently delete rows the policy keeps. The purge skips that tick and + * the next one retries. + */ +async function resolveRetention(env: Env): Promise { + try { + const [days, maxRows, batchRows, tickBudgetMs] = await resolveAdminSettingDetailsMany(env, [ + ANALYTICS_D1_RETENTION_DAYS_SETTING, + ANALYTICS_D1_MAX_ROWS_SETTING, + ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING, + ANALYTICS_D1_PURGE_TICK_BUDGET_MS_SETTING, + ]); + return { + days: positiveInteger(days?.value, DEFAULT_RETENTION.days), + maxRows: positiveInteger(maxRows?.value, DEFAULT_RETENTION.maxRows), + batchRows: positiveInteger(batchRows?.value, DEFAULT_RETENTION.batchRows), + tickBudgetMs: positiveInteger(tickBudgetMs?.value, DEFAULT_RETENTION.tickBudgetMs), + }; + } catch (err) { + log.warn('analytics.d1_purge_skipped', { + reason: 'retention_settings_unreadable', + error: err instanceof Error ? err.message : String(err), + }); + return null; + } +} + +export interface AnalyticsPurgeResult { + deletedByAge: number; + deletedByCount: number; + /** False when the tick budget ran out first; the next 5-minute run continues. */ + complete: boolean; +} + +/** + * Deletes the rows `selectIds` names, one batch per statement, until a batch comes back short + * or the deadline passes. At least one batch runs per call, so every tick makes progress. + */ +async function deleteInBatches( + db: D1Database, + selectIds: string, + binds: unknown[], + batchRows: number, + deadline: number +): Promise<{ deleted: number; complete: boolean }> { + const statement = db.prepare( + `DELETE FROM ${ANALYTICS_EVENTS_TABLE} WHERE id IN (${selectIds} LIMIT ?)` + ); + let deleted = 0; + do { + const result = await statement.bind(...binds, batchRows).run(); + const changes = result.meta?.changes ?? 0; + deleted += changes; + if (changes < batchRows) return { deleted, complete: true }; + } while (Date.now() < deadline); + return { deleted, complete: false }; +} + +/** + * Retention and row cap for the D1 sink. A no-op (no D1 call) unless the sink is enabled, and + * skipped (null, logged) when the retention settings cannot be read. + * + * Bounded by time, not by count (rule 81): batches of `analytics.d1.purgeBatchRows` (default + * 5,000) repeat until done or `analytics.d1.purgeTickBudgetMs` (default 10 s) is spent, and the + * next 5-minute tick resumes. Both batch shapes use an index (timestamp for age, the rowid range + * for the cap), so a batch costs its own rows, not the table. At a conservative 250 ms per + * object-store-backed statement that is ~200,000 rows per tick (~57.6M a day) against an + * inflow of one row per recorded request; the worst backlog the settings allow (cap lowered + * from 10,000,000 to 1) clears in about 50 ticks, roughly 4 hours. + */ +export async function purgeAnalyticsEvents(env: Env): Promise { + if (!isAnalyticsD1SinkEnabled(env)) return null; + const db = env.OBSERVABILITY_DATABASE; + const retention = await resolveRetention(env); + if (!retention) return null; + const { days, maxRows, batchRows, tickBudgetMs } = retention; + const deadline = Date.now() + tickBudgetMs; + + const byAge = await deleteInBatches( + db, + `SELECT id FROM ${ANALYTICS_EVENTS_TABLE} WHERE timestamp < datetime('now', ?)`, + [`-${days} days`], + batchRows, + deadline + ); + // Keep at most the newest maxRows. Ids grow with insertion order, so every id at or below + // MAX(id) - maxRows goes; gaps left by earlier deletes only make this keep fewer rows. One + // primary-key lookup finds the boundary instead of an OFFSET walk over the table. + let byCount = { deleted: 0, complete: true }; + if (byAge.complete) { + const top = await db + .prepare(`SELECT MAX(id) AS maxId FROM ${ANALYTICS_EVENTS_TABLE}`) + .first<{ maxId: number | null }>(); + const boundary = (top?.maxId ?? 0) - maxRows; + if (boundary > 0) { + byCount = await deleteInBatches( + db, + `SELECT id FROM ${ANALYTICS_EVENTS_TABLE} WHERE id <= ? ORDER BY id`, + [boundary], + batchRows, + deadline + ); + } + } + const result = { + deletedByAge: byAge.deleted, + deletedByCount: byCount.deleted, + complete: byAge.complete && byCount.complete, + }; + if (result.deletedByAge > 0 || result.deletedByCount > 0 || !result.complete) { + log.info('analytics.d1_purge', { ...result, retentionDays: days, maxRows, batchRows }); + } + return result; +} diff --git a/apps/api/src/selfhost/analytics/index.ts b/apps/api/src/selfhost/analytics/index.ts new file mode 100644 index 0000000000..e9c2cb80e2 --- /dev/null +++ b/apps/api/src/selfhost/analytics/index.ts @@ -0,0 +1,39 @@ +/** + * The self-host build's analytics store: product analytics in OBSERVABILITY_DATABASE, for a + * runtime without Workers Analytics Engine. Imported only by the self-host entry, which calls + * `installAnalyticsD1Sink()` once before any request; the shared Worker entry (`src/index.ts`) + * never imports this directory, so the Cloudflare bundle does not contain it. + * + * The sink is active only when the deployment also sets `ANALYTICS_SINK="d1"` and binds + * OBSERVABILITY_DATABASE, whose migration projection includes + * `SELFHOST_OBSERVABILITY_MIGRATIONS` (../observability-migrations.ts). + */ +import { installAdminSettingDefinitions } from '../../services/admin-settings-registry'; +import { + installLocalAnalyticsSinkExtension, + type LocalAnalyticsSinkExtension, +} from '../../services/analytics-sink'; +import { + ANALYTICS_EVENTS_TABLE, + analyticsD1Sink, + isAnalyticsD1SinkEnabled, + purgeAnalyticsEvents, + queryAnalyticsD1, +} from './d1-sink'; +import { ANALYTICS_D1_SETTINGS } from './settings'; + +export const analyticsD1SinkExtension: LocalAnalyticsSinkExtension = { + table: ANALYTICS_EVENTS_TABLE, + active: (env) => isAnalyticsD1SinkEnabled(env), + sink: (env) => analyticsD1Sink(env.OBSERVABILITY_DATABASE), + query: (env, sql) => queryAnalyticsD1(env.OBSERVABILITY_DATABASE, sql), + purge: async (env) => { + await purgeAnalyticsEvents(env); + }, +}; + +/** Registers the retention settings and the D1 sink. Idempotent; call before any request. */ +export function installAnalyticsD1Sink(): void { + installAdminSettingDefinitions(ANALYTICS_D1_SETTINGS); + installLocalAnalyticsSinkExtension(analyticsD1SinkExtension); +} diff --git a/apps/api/src/selfhost/analytics/settings.ts b/apps/api/src/selfhost/analytics/settings.ts new file mode 100644 index 0000000000..a66a861d46 --- /dev/null +++ b/apps/api/src/selfhost/analytics/settings.ts @@ -0,0 +1,59 @@ +/** + * Retention bounds for the self-host D1 analytics sink. Only the self-host entry registers these + * (`installAnalyticsD1Sink`), so a Cloudflare admin never sees them: Cloudflare keeps analytics in + * Analytics Engine, whose retention Cloudflare manages. + */ +import { + type AdminSettingDefinition, + type AdminSettingName, + integerDefinition, +} from '../../services/admin-setting-definitions'; + +/** The longest admin analytics period is 90 days, so this keeps every period complete. */ +export const DEFAULT_ANALYTICS_D1_RETENTION_DAYS = 90; +/** At most ~1.3 KB per row (blob lengths are capped), so about 650 MB worst case. */ +export const DEFAULT_ANALYTICS_D1_MAX_ROWS = 500_000; + +/** Rows each purge DELETE removes; statements repeat until done or the tick budget is spent. */ +export const DEFAULT_ANALYTICS_D1_PURGE_BATCH_ROWS = 5_000; +/** Wall time one observability-purge tick may spend deleting analytics rows. */ +export const DEFAULT_ANALYTICS_D1_PURGE_TICK_BUDGET_MS = 10_000; + +/** These names exist only in the self-host build, so they are not in the shared name union. */ +export const ANALYTICS_D1_RETENTION_DAYS_SETTING = 'analytics.d1.retentionDays' as AdminSettingName; +export const ANALYTICS_D1_MAX_ROWS_SETTING = 'analytics.d1.maxRows' as AdminSettingName; +export const ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING = + 'analytics.d1.purgeBatchRows' as AdminSettingName; +export const ANALYTICS_D1_PURGE_TICK_BUDGET_MS_SETTING = + 'analytics.d1.purgeTickBudgetMs' as AdminSettingName; + +export const ANALYTICS_D1_SETTINGS: readonly AdminSettingDefinition[] = [ + integerDefinition( + ANALYTICS_D1_RETENTION_DAYS_SETTING, + DEFAULT_ANALYTICS_D1_RETENTION_DAYS, + 'Operations', + 'Days of product analytics events kept in the installation database (the longest admin analytics period is 90).', + { min: 1, max: 365 } + ), + integerDefinition( + ANALYTICS_D1_MAX_ROWS_SETTING, + DEFAULT_ANALYTICS_D1_MAX_ROWS, + 'Operations', + 'Most product analytics event rows kept in the installation database; the oldest above this are deleted (500,000 is about 650 MB worst case).', + { min: 1, max: 10_000_000 } + ), + integerDefinition( + ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING, + DEFAULT_ANALYTICS_D1_PURGE_BATCH_ROWS, + 'Operations', + 'Rows each analytics retention DELETE removes. The purge repeats it until nothing is left to delete or its per-run time budget is spent.', + { min: 1, max: 50_000 } + ), + integerDefinition( + ANALYTICS_D1_PURGE_TICK_BUDGET_MS_SETTING, + DEFAULT_ANALYTICS_D1_PURGE_TICK_BUDGET_MS, + 'Operations', + 'Milliseconds one 5-minute purge run may spend deleting old analytics rows; unfinished work continues on the next run.', + { min: 1, max: 60_000 } + ), +]; diff --git a/apps/api/src/selfhost/migrations/observability/0002_analytics_events.sql b/apps/api/src/selfhost/migrations/observability/0002_analytics_events.sql new file mode 100644 index 0000000000..c532753eea --- /dev/null +++ b/apps/api/src/selfhost/migrations/observability/0002_analytics_events.sql @@ -0,0 +1,37 @@ +-- Migration: D1 analytics sink for installations without Analytics Engine (self-host). +-- SELF-HOST ONLY: this file lives outside apps/api/wrangler.toml's observability migrations_dir, +-- so Cloudflare installs never create the table. The self-host packager appends it to the +-- observability database's flat migration projection (selfhost/observability-migrations.ts). +-- The filename is unchanged from the integration branch so an existing box's ledger still +-- matches it. Additive only. Written only when the self-host entry installed the D1 sink and +-- ANALYTICS_SINK="d1" (selfhost/analytics/d1-sink.ts). +-- +-- Columns mirror Analytics Engine's data point shape (index1, blob1..blob11, double1..double3, +-- timestamp) so the admin analytics SQL runs against both with only a dialect translation. +-- `timestamp` is UTC text 'YYYY-MM-DD HH:MM:SS' (SQLite datetime()), so range filters compare +-- lexicographically and date()/strftime() work without conversion. +-- Growth is bounded by the 5-minute observability purge: age (admin setting +-- analytics.d1.retentionDays, default 90) and row cap (analytics.d1.maxRows, default 500000). + +CREATE TABLE IF NOT EXISTS analytics_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp TEXT NOT NULL, + index1 TEXT NOT NULL DEFAULT '', + blob1 TEXT NOT NULL DEFAULT '', + blob2 TEXT NOT NULL DEFAULT '', + blob3 TEXT NOT NULL DEFAULT '', + blob4 TEXT NOT NULL DEFAULT '', + blob5 TEXT NOT NULL DEFAULT '', + blob6 TEXT NOT NULL DEFAULT '', + blob7 TEXT NOT NULL DEFAULT '', + blob8 TEXT NOT NULL DEFAULT '', + blob9 TEXT NOT NULL DEFAULT '', + blob10 TEXT NOT NULL DEFAULT '', + blob11 TEXT NOT NULL DEFAULT '', + double1 REAL NOT NULL DEFAULT 0, + double2 REAL NOT NULL DEFAULT 0, + double3 REAL NOT NULL DEFAULT 0 +); + +CREATE INDEX IF NOT EXISTS idx_analytics_events_timestamp ON analytics_events (timestamp); +CREATE INDEX IF NOT EXISTS idx_analytics_events_blob1_timestamp ON analytics_events (blob1, timestamp); diff --git a/apps/api/src/selfhost/observability-migrations.ts b/apps/api/src/selfhost/observability-migrations.ts new file mode 100644 index 0000000000..cf44554e3d --- /dev/null +++ b/apps/api/src/selfhost/observability-migrations.ts @@ -0,0 +1,10 @@ +/** + * Paths relative to apps/api/src. The self-host packager appends these to + * OBSERVABILITY_DATABASE's flat migration projection AFTER the shared observability SQL. + * Never add them to wrangler.toml's observability `migrations_dir`: Cloudflare installs must not + * create self-host-only tables. The filename matches the one the integration branch shipped in + * the shared directory, so a box that already applied it records it as applied. + */ +export const SELFHOST_OBSERVABILITY_MIGRATIONS = [ + 'selfhost/migrations/observability/0002_analytics_events.sql', +] as const; diff --git a/apps/api/src/services/analytics-forward.ts b/apps/api/src/services/analytics-forward.ts index ce62e1999a..d7bbc3c55c 100644 --- a/apps/api/src/services/analytics-forward.ts +++ b/apps/api/src/services/analytics-forward.ts @@ -12,6 +12,8 @@ import type { Env } from '../env'; import { getAnalyticsDataset } from '../lib/analytics-config'; import { log } from '../lib/logger'; import { expectJsonRecord, readResponseJson } from '../lib/runtime-validation'; +import { activeLocalAnalyticsSink } from './analytics-sink'; +import { hasCloudflareAccountApi } from './platform-capabilities'; // ─── Defaults (configurable via env vars per constitution Principle XI) ─── @@ -54,6 +56,8 @@ export interface AnalyticsEvent { } export interface ForwardResult { + /** Why an enabled forward did nothing on purpose (not a failure). */ + skipReason?: 'analytics_query_unavailable'; enabled: boolean; eventsQueried: number; segment: { sent: number; batches: number; enabled: boolean; error?: string }; @@ -410,9 +414,14 @@ export async function forwardToGA4( */ export async function runAnalyticsForward(env: Env): Promise { const enabled = (env.ANALYTICS_FORWARD_ENABLED ?? 'false').toLowerCase() === 'true'; - if (!enabled) { + // Forwarding reads Cloudflare's Analytics Engine SQL API. Without an account, or when a + // self-host local sink holds the events instead, there is nothing there to read: skip with a + // reason instead of throwing from the daily cron. + const queryable = hasCloudflareAccountApi(env) && !activeLocalAnalyticsSink(env); + if (!enabled || !queryable) { return { enabled: false, + ...(enabled ? { skipReason: 'analytics_query_unavailable' as const } : {}), eventsQueried: 0, segment: { sent: 0, batches: 0, enabled: false }, ga4: { sent: 0, batches: 0, enabled: false }, diff --git a/apps/api/src/services/analytics-sink.ts b/apps/api/src/services/analytics-sink.ts new file mode 100644 index 0000000000..8731332014 --- /dev/null +++ b/apps/api/src/services/analytics-sink.ts @@ -0,0 +1,65 @@ +/** + * Analytics sink seam: where product analytics data points are written and read. + * + * On Cloudflare nothing is installed here: writes go to the `ANALYTICS` Analytics Engine binding + * and the admin routes query Cloudflare's Analytics Engine SQL API, exactly as before. No D1 call + * and no setting read happens for analytics on Cloudflare. + * + * Only the self-host build installs a local sink (`apps/api/src/selfhost/analytics/`, the + * `analytics_events` table in OBSERVABILITY_DATABASE). The shared Worker entry never imports that + * module, so the Cloudflare bundle does not contain it. The installed sink decides both sides, + * writes and reads, from the same `active(env)` answer, so an installation cannot record into one + * store and read from the other. + */ +import type { Env } from '../env'; + +/** Where analytics data points go. Same shape as Analytics Engine's `writeDataPoint`. */ +export interface AnalyticsSink { + write(points: AnalyticsEngineDataPoint[]): Promise; +} + +export interface LocalAnalyticsSinkExtension { + /** Whether this installation records and reads analytics locally. Pure: no I/O. */ + active(env: Env): boolean; + /** The local sink. Called only when `active(env)`. */ + sink(env: Env): AnalyticsSink; + /** Runs an admin analytics query (Analytics Engine SQL dialect) against the local store. */ + query(env: Env, sql: string): Promise; + /** The table name admin queries name in their FROM clause. */ + readonly table: string; + /** Retention bound, run by the 5-minute observability purge. */ + purge(env: Env): Promise; +} + +let extension: LocalAnalyticsSinkExtension | undefined; + +/** Called once by the self-host entry, before any request runs. */ +export function installLocalAnalyticsSinkExtension(value: LocalAnalyticsSinkExtension): void { + if (extension && extension !== value) { + throw new Error('A local analytics sink extension is already installed'); + } + extension = value; +} + +/** Test seam: removes the installed extension. */ +export function resetLocalAnalyticsSinkExtensionForTests(): void { + extension = undefined; +} + +/** The installed local sink when it is active here, else undefined. Pure: no I/O. */ +export function activeLocalAnalyticsSink(env: Env): LocalAnalyticsSinkExtension | undefined { + return extension?.active(env) ? extension : undefined; +} + +/** The sink for this installation, or null when analytics has nowhere to go (local dev). */ +export function resolveAnalyticsSink(env: Env): AnalyticsSink | null { + const local = activeLocalAnalyticsSink(env); + if (local) return local.sink(env); + const dataset = env.ANALYTICS; + if (!dataset) return null; + return { + write: async (points) => { + for (const point of points) dataset.writeDataPoint(point); + }, + }; +} diff --git a/apps/api/src/services/attachment-upload.ts b/apps/api/src/services/attachment-upload.ts index 20dfbf5e33..d224d33fe9 100644 --- a/apps/api/src/services/attachment-upload.ts +++ b/apps/api/src/services/attachment-upload.ts @@ -12,7 +12,7 @@ import { ATTACHMENT_DEFAULTS, SAFE_FILENAME_REGEX } from '@simple-agent-manager/ import type { Env } from '../env'; import { log } from '../lib/logger'; import { parsePositiveInt } from '../lib/route-helpers'; -import { getR2S3Client } from './r2-s3-client'; +import { getR2PresignTarget } from './r2-s3-client'; function getMaxBytes(env: Env): number { return parsePositiveInt(env.ATTACHMENT_UPLOAD_MAX_BYTES, ATTACHMENT_DEFAULTS.UPLOAD_MAX_BYTES); @@ -83,22 +83,18 @@ export async function generatePresignedUploadUrl( } const r2Key = buildAttachmentR2Key(userId, uploadId, filename); - const bucketName = env.R2_BUCKET_NAME; - if (!bucketName) { - throw new Error('R2_BUCKET_NAME not configured'); - } - - const s3 = getR2S3Client(env); + // r2Key stays the R2 binding key; only the presigned URL addresses the store object. + const target = getR2PresignTarget(env); const expiresIn = getPresignExpiry(env); const command = new PutObjectCommand({ - Bucket: bucketName, - Key: r2Key, + Bucket: target.bucket, + Key: target.objectKey(r2Key), ContentLength: size, ContentType: contentType, }); - const uploadUrl = await getSignedUrl(s3, command, { expiresIn }); + const uploadUrl = await getSignedUrl(target.client, command, { expiresIn }); log.info('attachment_upload.presigned_url_generated', { userId, diff --git a/apps/api/src/services/build-context-upload.ts b/apps/api/src/services/build-context-upload.ts index 95c25805b1..56637d4000 100644 --- a/apps/api/src/services/build-context-upload.ts +++ b/apps/api/src/services/build-context-upload.ts @@ -1,6 +1,29 @@ // Canonical implementation lives in the app-deployment package. -export { - createBuildContextDownload, - createBuildContextUpload, - verifyBuildContextObject, +// The upload keeps its original `(env, …)` signature here and binds the worker's shared R2 S3 +// client (`WHEN_REQUIRED`, so the VM need not send a checksum header), which also serves compose +// artifacts, attachments and session snapshots, and works against an operator store. +import { + createBuildContextDownload as createDownload, + createBuildContextUpload as createUpload, } from '@simple-agent-manager/app-deployment'; + +import type { Env } from '../env'; +import { getR2PresignTarget } from './r2-s3-client'; + +export { verifyBuildContextObject } from '@simple-agent-manager/app-deployment'; + +type BuildContextUploadArgs = Parameters; + +// Async so a missing R2 credential rejects the returned promise instead of throwing. +export async function createBuildContextUpload( + env: Env, + owner: BuildContextUploadArgs[0], + descriptor: BuildContextUploadArgs[1], + expiresIn: BuildContextUploadArgs[2] +): ReturnType { + return createUpload(owner, descriptor, expiresIn, getR2PresignTarget(env, 'WHEN_REQUIRED')); +} + +export async function createBuildContextDownload(env: Env, r2Key: string, expiresIn: number) { + return createDownload(r2Key, expiresIn, getR2PresignTarget(env, 'WHEN_REQUIRED')); +} diff --git a/apps/api/src/services/compose-image-artifacts.ts b/apps/api/src/services/compose-image-artifacts.ts index cd003b7919..57cd16c991 100644 --- a/apps/api/src/services/compose-image-artifacts.ts +++ b/apps/api/src/services/compose-image-artifacts.ts @@ -1,6 +1,19 @@ // Moved to @simple-agent-manager/app-deployment (worker modularization W4). // Re-exported so existing importers keep working. A vi.mock of this path does not reach // imports made inside the package (see packages/app-deployment/AGENTS.md). +// The two URL-signing functions keep their original signatures here and bind the worker's shared +// R2 S3 client, which also serves attachments and session snapshots. +import { + type ComposeImageArtifactDescriptor, + type ComposeImageArtifactDownload, + type ComposeImageArtifactUpload, + createComposeImageArtifactDownloads as createDownloads, + createComposeImageArtifactUploads as createUploads, +} from '@simple-agent-manager/app-deployment'; + +import type { Env } from '../env'; +import { getR2PresignTarget } from './r2-s3-client'; + export type { ComposeImageArtifactDescriptor, ComposeImageArtifactDownload, @@ -9,9 +22,26 @@ export type { ComposeImageArtifactUpload, } from '@simple-agent-manager/app-deployment'; export { - createComposeImageArtifactDownloads, - createComposeImageArtifactUploads, + buildComposeImageArtifactKey, + COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, + COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, getComposeImageArtifactMaxBytes, validateCompletedComposeImageArtifacts, validateComposeImageArtifactDescriptor, } from '@simple-agent-manager/app-deployment'; + +// Compose artifacts have always been signed with the SDK's default checksum behaviour. Async so a +// missing R2 credential rejects the returned promise, as it did before, instead of throwing. +export async function createComposeImageArtifactUploads( + env: Env, + input: Parameters[1] +): Promise { + return createUploads(env, input, getR2PresignTarget(env, 'SDK_DEFAULT')); +} + +export async function createComposeImageArtifactDownloads( + env: Env, + artifacts: ComposeImageArtifactDescriptor[] +): Promise { + return createDownloads(env, artifacts, getR2PresignTarget(env, 'SDK_DEFAULT')); +} diff --git a/apps/api/src/services/platform-capabilities.ts b/apps/api/src/services/platform-capabilities.ts index 95ee0be7a5..c7a4abe55c 100644 --- a/apps/api/src/services/platform-capabilities.ts +++ b/apps/api/src/services/platform-capabilities.ts @@ -1,4 +1,4 @@ -import { LlmUnavailableError } from '@simple-agent-manager/ai-proxy'; +import { hasCloudflareAccountApi, LlmUnavailableError } from '@simple-agent-manager/ai-proxy'; import { resolveD1BindingIdentity } from '../lib/d1-session'; import { cache } from './admin-settings-resolution'; @@ -23,14 +23,25 @@ export { * with its bindings present resolves every capability to true, so its behaviour does not change. */ import type { Env } from '../env'; +import { activeLocalAnalyticsSink } from './analytics-sink'; import { getTTSConfig } from './tts-config'; /** One platform service. The name is also the `feature` field of a FEATURE_UNAVAILABLE error. */ -export type PlatformCapability = 'workersAi' | 'speechToText' | 'textToSpeech'; +export type PlatformCapability = + | 'workersAi' + | 'speechToText' + | 'textToSpeech' + | 'analyticsQuery' + | 'workersObservability' + | 'liveLogStream'; export type PlatformCapabilities = Readonly>; -type CapabilityEnv = Pick; +/** + * The Worker environment. Analytics availability can consult a local sink the self-host build + * installs (services/analytics-sink.ts), which reads its own bindings, so this takes the whole Env. + */ +type CapabilityEnv = Env; /** The Workers AI binding, or null when this runtime has none (or it lacks `run`). */ export function getWorkersAiBindingOrNull(env: Pick): Ai | null { @@ -39,11 +50,28 @@ export function getWorkersAiBindingOrNull(env: Pick): Ai | null { return ai as Ai; } +/** + * Whether Admin → Stream can receive anything. The stream is fed by the tail worker (a Cloudflare + * `tail_consumers` attachment), which the Worker cannot see from inside, so the deployment + * declares its absence: `LOG_TAIL_AVAILABLE="false"` (the self-host config generator sets it). + * Unset means available, which keeps Cloudflare deployments unchanged. + */ +export function hasLiveLogStream(env: Pick): boolean { + return env.LOG_TAIL_AVAILABLE?.trim().toLowerCase() !== 'false'; +} + /** Resolve every capability from bindings and settings. Pure and synchronous: no I/O. */ export function resolvePlatformCapabilities(env: CapabilityEnv): PlatformCapabilities { const workersAi = getWorkersAiBindingOrNull(env) !== null; + const cloudflareAccountApi = hasCloudflareAccountApi(env); return { workersAi, + // Admin analytics reads Cloudflare's Analytics Engine SQL API (CF_ACCOUNT_ID + CF_API_TOKEN), + // or a local sink the self-host build installed and enabled (selfhost/analytics/). + analyticsQuery: cloudflareAccountApi || activeLocalAnalyticsSink(env) !== undefined, + // Admin → Logs search reads Workers Observability through the same account API. + workersObservability: cloudflareAccountApi, + liveLogStream: hasLiveLogStream(env), // Whisper runs on Workers AI (routes/transcribe.ts). speechToText: workersAi, // Synthesis runs on Workers AI, and the operator can switch it off (routes/tts.ts). @@ -61,6 +89,10 @@ export interface PublicPlatformCapabilities { speechToText: boolean; /** Server read-aloud on agent messages and task summaries. */ textToSpeech: boolean; + /** Admin → Logs search (Workers Observability). False where logs are read on the server. */ + logSearch: boolean; + /** Admin → Stream (tail worker). False where no tail worker feeds it. */ + liveLogStream: boolean; /** * Whether agents can call Cloudflare-hosted models (Workers AI). Profile, skill and project * settings hide their model-access field when false instead of asking for a catalog that @@ -74,6 +106,8 @@ export function publicPlatformCapabilities(env: CapabilityEnv): PublicPlatformCa return { speechToText: capabilities.speechToText, textToSpeech: capabilities.textToSpeech, + logSearch: capabilities.workersObservability, + liveLogStream: capabilities.liveLogStream, agentModelCalls: capabilities.workersAi, }; } diff --git a/apps/api/src/services/r2-presign-config.ts b/apps/api/src/services/r2-presign-config.ts new file mode 100644 index 0000000000..d289cf55c2 --- /dev/null +++ b/apps/api/src/services/r2-presign-config.ts @@ -0,0 +1,160 @@ +/** + * Where presigned S3 URLs for R2 objects point. No SDK import, so the capability resolver can + * use it cheaply; `r2-s3-client.ts` builds the client from it. + * + * Cloudflare (default): `https://.r2.cloudflarestorage.com`, bucket + * `R2_BUCKET_NAME`, object key = the R2 key. + * + * Operator store (`R2_S3_ENDPOINT` set): a runtime such as celld keeps the R2 binding's objects + * in its own S3 bucket under a prefix, for example `r2//` in the fleet bucket. + * Presigned URLs then target `R2_S3_BUCKET` at `${R2_S3_KEY_PREFIX}${key}`, so the binding and + * the URL address the same object. `R2_ACCESS_KEY_ID`/`R2_SECRET_ACCESS_KEY` must be a credential + * limited to that prefix, never the fleet credential: the fleet bucket also holds deploy + * manifests with plaintext secrets. + */ +import { classifyHost } from '@simple-agent-manager/worker-core'; + +import type { Env } from '../env'; + +/** + * Cloudflare R2's S3 API ignores the region; SigV4 still needs one. Operator stores get no + * default: a wrong region signs every URL with the wrong credential scope (AWS S3 rejects it), + * so an operator store without R2_S3_REGION is not configured. GCS and R2-compatible stores take + * "auto". + */ +const CLOUDFLARE_R2_S3_REGION = 'auto'; + +export interface R2PresignConfig { + endpoint: string; + bucket: string; + /** Prepended to every R2 key. Empty on Cloudflare. */ + keyPrefix: string; + region: string; + /** Path-style (`//`) addressing; undefined keeps the SDK default. */ + forcePathStyle: boolean | undefined; + accessKeyId: string; + secretAccessKey: string; +} + +type R2PresignEnv = Pick< + Env, + | 'CF_ACCOUNT_ID' + | 'R2_ACCESS_KEY_ID' + | 'R2_SECRET_ACCESS_KEY' + | 'R2_BUCKET_NAME' + | 'R2_S3_ENDPOINT' + | 'R2_S3_BUCKET' + | 'R2_S3_KEY_PREFIX' + | 'R2_S3_REGION' + | 'R2_S3_FORCE_PATH_STYLE' +>; + +function text(value: string | undefined): string { + return value?.trim() ?? ''; +} + +/** + * An operator store URL: HTTPS to any host except a forbidden one (link-local, metadata), or + * plain HTTP only to a private-network host on the box. Never userinfo, query or fragment. + */ +function validEndpoint(value: string): boolean { + let url: URL; + try { + url = new URL(value); + } catch { + return false; + } + if (url.username || url.password || url.search || url.hash) return false; + const hostClass = classifyHost(url.hostname); + if (url.protocol === 'https:') return hostClass !== 'forbidden'; + return url.protocol === 'http:' && hostClass === 'private'; +} + +/** True when any path segment could resolve outside its parent or confuse a gateway. */ +function hasUnsafeKeySegment(value: string): boolean { + // eslint-disable-next-line no-control-regex -- control characters are exactly what is refused + if (value.startsWith('/') || value.includes('\\') || /[\u0000-\u001f\u007f]/.test(value)) + return true; + return value.split('/').some((segment) => segment === '.' || segment === '..'); +} + +/** + * A relative key prefix that ends in `/` (so `r2//` cannot glue onto the key) and has + * no empty, `.` or `..` segment, so it cannot escape its scope. + */ +function validKeyPrefix(value: string): boolean { + return ( + value.endsWith('/') && + !hasUnsafeKeySegment(value) && + !value + .slice(0, -1) + .split('/') + .some((segment) => segment === '') + ); +} + +/** Operator-store settings that mean nothing without R2_S3_ENDPOINT. */ +const OPERATOR_STORE_ONLY_VARS = [ + 'R2_S3_BUCKET', + 'R2_S3_KEY_PREFIX', + 'R2_S3_REGION', + 'R2_S3_FORCE_PATH_STYLE', +] as const; + +/** + * The presign target, or null when presigning is not configured. A partially configured + * operator store (endpoint without bucket or prefix, or an invalid one) is null too: it must + * never fall back to Cloudflare with keys meant for another store. + */ +export function resolveR2PresignConfig(env: R2PresignEnv): R2PresignConfig | null { + const accessKeyId = text(env.R2_ACCESS_KEY_ID); + const secretAccessKey = text(env.R2_SECRET_ACCESS_KEY); + if (!accessKeyId || !secretAccessKey) return null; + + const endpoint = text(env.R2_S3_ENDPOINT); + // A store setting without its endpoint is a misconfiguration, not "use Cloudflare": signing + // for R2 with an operator's key would put objects where the binding never reads them. + if (!endpoint && OPERATOR_STORE_ONLY_VARS.some((name) => text(env[name]))) return null; + if (endpoint) { + const bucket = text(env.R2_S3_BUCKET); + const keyPrefix = text(env.R2_S3_KEY_PREFIX); + const region = text(env.R2_S3_REGION); + if (!validEndpoint(endpoint) || !bucket || !validKeyPrefix(keyPrefix) || !region) return null; + return { + endpoint: endpoint.replace(/\/+$/, ''), + bucket, + keyPrefix, + region, + // Self-hosted stores (MinIO, SeaweedFS) are addressed by path; opt out with "false". + forcePathStyle: text(env.R2_S3_FORCE_PATH_STYLE).toLowerCase() !== 'false', + accessKeyId, + secretAccessKey, + }; + } + + const accountId = text(env.CF_ACCOUNT_ID); + const bucket = text(env.R2_BUCKET_NAME); + if (!accountId || !bucket) return null; + return { + endpoint: `https://${accountId}.r2.cloudflarestorage.com`, + bucket, + keyPrefix: '', + region: CLOUDFLARE_R2_S3_REGION, + forcePathStyle: undefined, + accessKeyId, + secretAccessKey, + }; +} + +/** + * The store key for an R2 key: where the R2 binding keeps that object. Under an operator prefix + * the key must not be able to climb out of it (a gateway that normalises `..` would otherwise + * sign a URL outside the prefix, toward the fleet bucket's secrets). On Cloudflare (no prefix) + * keys are opaque object names and pass through unchanged. + */ +export function r2PresignObjectKey(config: R2PresignConfig, r2Key: string): string { + if (config.keyPrefix && hasUnsafeKeySegment(r2Key)) { + throw new Error('R2 object key has an unsafe path segment'); + } + return `${config.keyPrefix}${r2Key}`; +} diff --git a/apps/api/src/services/r2-s3-client.ts b/apps/api/src/services/r2-s3-client.ts index fcbecee9b9..760594c83d 100644 --- a/apps/api/src/services/r2-s3-client.ts +++ b/apps/api/src/services/r2-s3-client.ts @@ -1,35 +1,83 @@ import { S3Client } from '@aws-sdk/client-s3'; import type { Env } from '../env'; +import { + type R2PresignConfig, + r2PresignObjectKey, + resolveR2PresignConfig, +} from './r2-presign-config'; -let client: S3Client | null = null; -let clientKey = ''; +/** + * How the SDK adds flexible checksums to requests. Attachments and snapshots presign with + * `WHEN_REQUIRED` so the browser or VM need not send a CRC header; compose image artifacts + * keep the SDK default they have always been signed with. + */ +export type R2ChecksumMode = 'WHEN_REQUIRED' | 'SDK_DEFAULT'; + +export interface R2PresignTarget { + client: S3Client; + /** S3 bucket the URL addresses. */ + bucket: string; + /** S3 object key for an R2 key (prefix applied for operator stores). */ + objectKey(r2Key: string): string; +} + +/** One client per configuration and checksum mode; a rotation adds at most a few entries. */ +const MAX_CACHED_CLIENTS = 4; +const clients = new Map(); export function hasR2S3Credentials(env: Env): boolean { - return Boolean( - env.R2_ACCESS_KEY_ID && env.R2_SECRET_ACCESS_KEY && env.CF_ACCOUNT_ID && env.R2_BUCKET_NAME - ); + return resolveR2PresignConfig(env) !== null; } -export function getR2S3Client(env: Env): S3Client { - const { CF_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_BUCKET_NAME, R2_SECRET_ACCESS_KEY } = env; - if (!CF_ACCOUNT_ID || !R2_ACCESS_KEY_ID || !R2_BUCKET_NAME || !R2_SECRET_ACCESS_KEY) { - throw new Error( - 'R2 S3 credentials not configured (R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, CF_ACCOUNT_ID, and R2_BUCKET_NAME required)' - ); - } - const key = `${CF_ACCOUNT_ID}:${R2_ACCESS_KEY_ID}`; - if (!client || clientKey !== key) { +function clientFor(config: R2PresignConfig, checksum: R2ChecksumMode): S3Client { + const cacheKey = JSON.stringify([ + config.endpoint, + config.region, + config.forcePathStyle ?? null, + config.accessKeyId, + // A secret rotated under the same key id must not keep signing with the old one. + config.secretAccessKey, + checksum, + ]); + let client = clients.get(cacheKey); + if (!client) { client = new S3Client({ - region: 'auto', - endpoint: `https://${CF_ACCOUNT_ID}.r2.cloudflarestorage.com`, - requestChecksumCalculation: 'WHEN_REQUIRED', + region: config.region, + endpoint: config.endpoint, + ...(config.forcePathStyle === undefined ? {} : { forcePathStyle: config.forcePathStyle }), + ...(checksum === 'WHEN_REQUIRED' ? { requestChecksumCalculation: 'WHEN_REQUIRED' } : {}), credentials: { - accessKeyId: R2_ACCESS_KEY_ID, - secretAccessKey: R2_SECRET_ACCESS_KEY, + accessKeyId: config.accessKeyId, + secretAccessKey: config.secretAccessKey, }, }); - clientKey = key; + // Rotated credentials must not accumulate clients for the life of the isolate. + if (clients.size >= MAX_CACHED_CLIENTS) clients.clear(); + clients.set(cacheKey, client); } return client; } + +/** The one place presigned R2 URLs get their client, bucket and object key (rule 24). */ +export function getR2PresignTarget( + env: Env, + checksum: R2ChecksumMode = 'WHEN_REQUIRED' +): R2PresignTarget { + const config = resolveR2PresignConfig(env); + if (!config) { + throw new Error( + 'R2 S3 credentials not configured (R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY, plus CF_ACCOUNT_ID and R2_BUCKET_NAME on Cloudflare, or R2_S3_ENDPOINT, R2_S3_BUCKET and R2_S3_KEY_PREFIX for an operator store)' + ); + } + return { + client: clientFor(config, checksum), + bucket: config.bucket, + objectKey: (r2Key) => r2PresignObjectKey(config, r2Key), + }; +} + +/** Test seam: forget cached clients. */ +export function resetR2S3ClientsForTests(): void { + clients.clear(); +} diff --git a/apps/api/src/services/session-snapshot-direct-upload.ts b/apps/api/src/services/session-snapshot-direct-upload.ts index cd82ad9bed..997193fc62 100644 --- a/apps/api/src/services/session-snapshot-direct-upload.ts +++ b/apps/api/src/services/session-snapshot-direct-upload.ts @@ -3,7 +3,7 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import type { Env } from '../env'; import { parsePositiveInt } from '../lib/route-helpers'; -import { getR2S3Client, hasR2S3Credentials } from './r2-s3-client'; +import { getR2PresignTarget, hasR2S3Credentials } from './r2-s3-client'; export const DEFAULT_SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS = 15 * 60; @@ -28,20 +28,19 @@ export async function generateSessionSnapshotDirectUploadUrl( checksumHeader?: boolean; } ): Promise { + const target = getR2PresignTarget(env); const command = new PutObjectCommand({ - Bucket: env.R2_BUCKET_NAME, - Key: input.key, + Bucket: target.bucket, + Key: target.objectKey(input.key), ContentLength: input.sizeBytes, ContentType: input.contentType, ChecksumSHA256: checksumBase64(input.sha256), }); - return getSignedUrl(getR2S3Client(env), command, { + return getSignedUrl(target.client, command, { expiresIn: parsePositiveInt( env.SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS, DEFAULT_SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS ), - ...(input.checksumHeader - ? { unhoistableHeaders: new Set(['x-amz-checksum-sha256']) } - : {}), + ...(input.checksumHeader ? { unhoistableHeaders: new Set(['x-amz-checksum-sha256']) } : {}), }); } diff --git a/apps/api/src/services/worker-log-query.ts b/apps/api/src/services/worker-log-query.ts index 10a8b46fce..13fb519583 100644 --- a/apps/api/src/services/worker-log-query.ts +++ b/apps/api/src/services/worker-log-query.ts @@ -3,6 +3,7 @@ import { errors } from '../middleware/error'; import { resolveAdminSetting } from './admin-settings'; import { MAX_LOG_QUERY_LIMIT } from './observability-common'; import { queryCloudflareLogs } from './observability-logs'; +import { hasCloudflareAccountApi } from './platform-capabilities'; export const WORKER_LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'log'] as const; @@ -32,9 +33,10 @@ export async function queryWorkerLogs( query: WorkerLogQuery, callerSignal?: AbortSignal ): ReturnType { - if (!env.CF_API_TOKEN || !env.CF_ACCOUNT_ID) { - throw errors.badRequest( - 'Cloudflare API credentials not configured. Set CF_API_TOKEN and CF_ACCOUNT_ID.' + if (!hasCloudflareAccountApi(env)) { + throw errors.featureUnavailable( + 'workersObservability', + 'Worker log search is not available on this installation' ); } const start = new Date(query.timeRange.start); diff --git a/apps/api/tests/unit/routes/admin-observability.test.ts b/apps/api/tests/unit/routes/admin-observability.test.ts index f3bac8cb32..54614f70b6 100644 --- a/apps/api/tests/unit/routes/admin-observability.test.ts +++ b/apps/api/tests/unit/routes/admin-observability.test.ts @@ -43,6 +43,8 @@ vi.mock('../../../src/middleware/error', () => { badRequest: (msg: string) => new AppError(400, 'BAD_REQUEST', msg), notFound: (entity: string) => new AppError(404, 'NOT_FOUND', `${entity} not found`), forbidden: (msg: string) => new AppError(403, 'FORBIDDEN', msg), + featureUnavailable: (_feature: string, msg: string) => + new AppError(404, 'FEATURE_UNAVAILABLE', msg), }, AppError, }; @@ -817,15 +819,17 @@ describe('Admin Observability Routes', () => { expect(mockQueryCloudflareLogs).not.toHaveBeenCalled(); }); - it('should return 400 when CF credentials are not configured', async () => { + it('reports log search as not available when no Cloudflare account is configured', async () => { const res = await postLogs(validBody, { CF_API_TOKEN: undefined as unknown as string, CF_ACCOUNT_ID: undefined as unknown as string, }); - expect(res.status).toBe(400); + expect(res.status).toBe(404); const body = await res.json(); - expect(body.message).toContain('credentials'); + expect(body.error).toBe('FEATURE_UNAVAILABLE'); + expect(body.message).toContain('not available'); + expect(mockQueryCloudflareLogs).not.toHaveBeenCalled(); }); it('should return 400 when timeRange is missing', async () => { @@ -973,6 +977,42 @@ describe('Admin Observability Routes', () => { const doRequest = mockDoStub.fetch.mock.calls[0][0] as Request; expect(new URL(doRequest.url).pathname).toBe('/ws'); }); + + function streamNamespace() { + const stub = { fetch: vi.fn().mockResolvedValue(new Response(null, { status: 200 })) }; + const namespace = { idFromName: vi.fn().mockReturnValue('do-id'), get: vi.fn(() => stub) }; + return { stub, namespace: namespace as unknown as DurableObjectNamespace }; + } + + it('refuses the stream with FEATURE_UNAVAILABLE when no tail worker feeds it (self-host)', async () => { + const { stub, namespace } = streamNamespace(); + + const res = await app.request( + '/api/admin/observability/logs/stream', + { headers: { Upgrade: 'websocket' } }, + createEnv({ ADMIN_LOGS: namespace, LOG_TAIL_AVAILABLE: 'false' }) + ); + + expect(res.status).toBe(404); + const body = await res.json(); + expect(body.error).toBe('FEATURE_UNAVAILABLE'); + expect(body.message).toContain('live log stream is not available'); + expect(stub.fetch).not.toHaveBeenCalled(); + }); + + it('opens the stream for the production shape (LOG_TAIL_AVAILABLE unset or not "false")', async () => { + for (const value of [undefined, 'true']) { + const { stub, namespace } = streamNamespace(); + + await app.request( + '/api/admin/observability/logs/stream', + { headers: { Upgrade: 'websocket' } }, + createEnv({ ADMIN_LOGS: namespace, LOG_TAIL_AVAILABLE: value }) + ); + + expect(stub.fetch, `LOG_TAIL_AVAILABLE=${String(value)}`).toHaveBeenCalledTimes(1); + } + }); }); // =========================================================================== diff --git a/apps/api/tests/unit/routes/attachment-upload.test.ts b/apps/api/tests/unit/routes/attachment-upload.test.ts index 420b644777..888fbe1e75 100644 --- a/apps/api/tests/unit/routes/attachment-upload.test.ts +++ b/apps/api/tests/unit/routes/attachment-upload.test.ts @@ -43,6 +43,8 @@ function makeEnv(overrides: Partial = {}): Env { DATABASE: {} as any, R2_ACCESS_KEY_ID: 'test-key-id', R2_SECRET_ACCESS_KEY: 'test-secret', + CF_ACCOUNT_ID: 'test-account', + R2_BUCKET_NAME: 'test-bucket', ...overrides, } as Env; } @@ -87,7 +89,7 @@ describe('POST /projects/:projectId/tasks/request-upload', () => { }); expect(res.status).toBe(200); - const json = await res.json() as any; + const json = (await res.json()) as any; expect(json.uploadId).toBe('TEST-UPLOAD-ID'); expect(json.uploadUrl).toBe('https://r2.example.com/presigned'); expect(json.r2Key).toBeUndefined(); // r2Key should NOT be exposed to client @@ -153,10 +155,12 @@ describe('POST /projects/:projectId/tasks/request-upload', () => { }); it('rejects when R2 credentials are missing', async () => { - const { app, env } = makeApp(makeEnv({ - R2_ACCESS_KEY_ID: undefined, - R2_SECRET_ACCESS_KEY: undefined, - })); + const { app, env } = makeApp( + makeEnv({ + R2_ACCESS_KEY_ID: undefined, + R2_SECRET_ACCESS_KEY: undefined, + }) + ); const res = await postUpload(app, env, { filename: 'test.txt', size: 1024, @@ -166,9 +170,11 @@ describe('POST /projects/:projectId/tasks/request-upload', () => { }); it('rejects file size exceeding limit', async () => { - const { app, env } = makeApp(makeEnv({ - ATTACHMENT_UPLOAD_MAX_BYTES: '500', - })); + const { app, env } = makeApp( + makeEnv({ + ATTACHMENT_UPLOAD_MAX_BYTES: '500', + }) + ); const res = await postUpload(app, env, { filename: 'big.bin', size: 1000, @@ -199,7 +205,23 @@ describe('POST /projects/:projectId/tasks/request-upload', () => { filename: 'data.csv', size: 2048, contentType: 'text/csv', - }), + }) + ); + }); +}); + +describe('request-upload presign configuration', () => { + it('refuses a partial operator store with 403 instead of failing inside the presigner', async () => { + mockGeneratePresignedUploadUrl.mockClear(); + const { app, env } = makeApp( + makeEnv({ R2_S3_ENDPOINT: 'https://s3.example.com', R2_S3_BUCKET: 'fleet' }) ); + const res = await postUpload(app, env, { + filename: 'a.txt', + size: 10, + contentType: 'text/plain', + }); + expect(res.status).toBe(403); + expect(mockGeneratePresignedUploadUrl).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/tests/unit/routes/platform-capabilities-route.test.ts b/apps/api/tests/unit/routes/platform-capabilities-route.test.ts index d14f56fb9d..b674c102c5 100644 --- a/apps/api/tests/unit/routes/platform-capabilities-route.test.ts +++ b/apps/api/tests/unit/routes/platform-capabilities-route.test.ts @@ -51,7 +51,13 @@ describe('GET /api/config/platform-capabilities', () => { const { res, body } = await getCapabilities(cloudflareEnv()); expect(res.status).toBe(200); - expect(body).toEqual({ speechToText: true, textToSpeech: true, agentModelCalls: true }); + expect(body).toEqual({ + speechToText: true, + textToSpeech: true, + logSearch: true, + liveLogStream: true, + agentModelCalls: true, + }); // Public config: cacheable by the browser like the other /api/config answers. expect(res.headers.get('Cache-Control')).toMatch(/max-age=\d+/); }); @@ -60,10 +66,32 @@ describe('GET /api/config/platform-capabilities', () => { const { res, body } = await getCapabilities(cloudflareEnv({ AI: undefined })); expect(res.status).toBe(200); - expect(body).toEqual({ speechToText: false, textToSpeech: false, agentModelCalls: false }); + expect(body).toEqual({ + speechToText: false, + textToSpeech: false, + logSearch: true, + liveLogStream: true, + agentModelCalls: false, + }); expect(res.headers.get('Cache-Control')).toContain('no-store'); }); + it('reports log search and the live stream absent on a self-hosted box', async () => { + // A box has no Cloudflare account API (Workers Observability) and declares no tail worker. + const { body } = await getCapabilities( + cloudflareEnv({ + CF_ACCOUNT_ID: undefined, + CF_API_TOKEN: undefined, + LOG_TAIL_AVAILABLE: 'false', + }) + ); + + expect(body.logSearch).toBe(false); + expect(body.liveLogStream).toBe(false); + // Liveness: the same answer still reports the services the box does have. + expect(body.speechToText).toBe(true); + }); + it('turns text-to-speech off with TTS_ENABLED=false while speech-to-text stays on', async () => { const { body } = await getCapabilities(cloudflareEnv({ TTS_ENABLED: 'false' })); diff --git a/apps/api/tests/unit/selfhost/analytics-and-log-search-unavailable.test.ts b/apps/api/tests/unit/selfhost/analytics-and-log-search-unavailable.test.ts new file mode 100644 index 0000000000..7b0daa6bdf --- /dev/null +++ b/apps/api/tests/unit/selfhost/analytics-and-log-search-unavailable.test.ts @@ -0,0 +1,222 @@ +/** + * The Cloudflare account-scoped REST APIs (Analytics Engine SQL, Workers Observability) on an + * installation with and without a Cloudflare account. + * + * - Admin analytics routes mounted behind the real global error handler. + * - runAnalyticsForward (the daily cron) with forwarding enabled. + * - queryWorkerLogs (behind Admin -> Logs and the `ops_query_worker_logs` tool). + * + * `fetch` is the only mock at the boundary; admin settings run against the real SQLite-backed + * settings tables so timeouts resolve the way production resolves them. + */ +import type Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { handleAppError } from '../../../src/middleware/app-error-handler'; +import { AppError } from '../../../src/middleware/error'; +import { adminAnalyticsRoutes } from '../../../src/routes/admin-analytics'; +import { runAnalyticsForward } from '../../../src/services/analytics-forward'; +import { queryWorkerLogs } from '../../../src/services/worker-log-query'; +import { createAdminSettingsEnv } from '../../helpers/admin-settings-env'; + +vi.mock('../../../src/middleware/auth', () => ({ + requireAuth: () => async (_c: unknown, next: () => Promise) => next(), + requireApproved: () => async (_c: unknown, next: () => Promise) => next(), + requireSuperadmin: () => async (_c: unknown, next: () => Promise) => next(), +})); + +let sqlite: Database.Database; +let baseEnv: Env; +let fetchMock: ReturnType; + +beforeEach(() => { + ({ sqlite, env: baseEnv } = createAdminSettingsEnv({ ANALYTICS_DATASET: 'sam_analytics' })); + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + sqlite.close(); +}); + +const cloudflare = (): Env => + ({ ...baseEnv, CF_ACCOUNT_ID: 'account-1', CF_API_TOKEN: 'token-1' }) as Env; +/** + * A runtime with no Cloudflare account. The Cloudflare deploy generates ANALYTICS_DATASET, so a + * self-hosted box has none either; the celld run failed with a 500 for exactly this shape. + */ +const selfHosted = (): Env => ({ ...baseEnv, ANALYTICS_DATASET: undefined }) as Env; + +describe('admin analytics routes', () => { + function app() { + const testApp = new Hono<{ Bindings: Env }>(); + testApp.onError(handleAppError); + testApp.route('/api/admin/analytics', adminAnalyticsRoutes); + return testApp; + } + + it('GET /dau queries the Cloudflare analytics SQL API when an account is configured (Cloudflare behaviour)', async () => { + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ data: [{ date: '2026-11-09', unique_users: '4' }] }), { + status: 200, + }) + ); + + const res = await app().request('/api/admin/analytics/dau', {}, cloudflare()); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + dau: [{ date: '2026-11-09', unique_users: 4 }], + periodDays: expect.any(Number), + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe( + 'https://api.cloudflare.com/client/v4/accounts/account-1/analytics_engine/sql' + ); + expect((init.headers as Record).Authorization).toBe('Bearer token-1'); + expect(String(init.body)).toContain('sam_analytics'); + }); + + it.each(['dau', 'events', 'feature-adoption', 'website-traffic'])( + 'GET /%s answers 404 FEATURE_UNAVAILABLE for analyticsQuery without an account, and never calls fetch', + async (route) => { + const res = await app().request(`/api/admin/analytics/${route}`, {}, selfHosted()); + + expect(res.status).toBe(404); + expect(await res.json()).toEqual({ + error: 'FEATURE_UNAVAILABLE', + message: 'Analytics is not available on this installation', + details: { feature: 'analyticsQuery' }, + }); + expect(fetchMock).not.toHaveBeenCalled(); + } + ); + + it('answers 404 when only the account id is set (the token is half of the credential)', async () => { + const res = await app().request('/api/admin/analytics/dau', {}, { + ...baseEnv, + CF_ACCOUNT_ID: 'account-1', + } as Env); + + expect(res.status).toBe(404); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('keeps GET /forward-status working without an account (it never queries Cloudflare)', async () => { + const res = await app().request('/api/admin/analytics/forward-status', {}, selfHosted()); + + expect(res.status).toBe(200); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +describe('runAnalyticsForward', () => { + const forwardingOn = { ANALYTICS_FORWARD_ENABLED: 'true' }; + + it('queries the analytics SQL API when forwarding is on and an account is configured (Cloudflare behaviour)', async () => { + fetchMock.mockResolvedValue(new Response(JSON.stringify({ data: [] }), { status: 200 })); + + const result = await runAnalyticsForward({ ...cloudflare(), ...forwardingOn } as Env); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(String((fetchMock.mock.calls[0] as [string])[0])).toContain( + '/accounts/account-1/analytics_engine/sql' + ); + expect(result).toMatchObject({ enabled: true, eventsQueried: 0 }); + expect(result.skipReason).toBeUndefined(); + }); + + it('resolves with skipReason analytics_query_unavailable, without throwing or fetching, when there is no account', async () => { + const result = await runAnalyticsForward({ ...selfHosted(), ...forwardingOn } as Env); + + expect(result).toEqual({ + enabled: false, + skipReason: 'analytics_query_unavailable', + eventsQueried: 0, + segment: { sent: 0, batches: 0, enabled: false }, + ga4: { sent: 0, batches: 0, enabled: false }, + cursorUpdated: false, + newCursor: null, + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('reports no skip reason when forwarding is simply switched off (a different, intended state)', async () => { + const result = await runAnalyticsForward(selfHosted()); + + expect(result.enabled).toBe(false); + expect('skipReason' in result).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +describe('queryWorkerLogs', () => { + const query = { + timeRange: { start: '2026-11-10T11:00:00Z', end: '2026-11-10T12:00:00Z' }, + levels: ['error'], + scriptName: 'sam-api-staging', + }; + + it('calls the Workers Observability API with the account and token when configured (Cloudflare behaviour)', async () => { + fetchMock.mockResolvedValue( + new Response( + JSON.stringify({ + result: { + events: { + events: [ + { + $metadata: { id: 'inv-1', level: 'error', message: 'boom' }, + $workers: { scriptName: 'sam-api-staging' }, + timestamp: Date.parse('2026-11-10T11:30:00Z'), + }, + ], + }, + }, + }), + { status: 200 } + ) + ); + + const result = await queryWorkerLogs(cloudflare(), query); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toContain('/accounts/account-1/workers/observability/telemetry/query'); + expect((init.headers as Record).Authorization).toBe('Bearer token-1'); + expect(JSON.parse(String(init.body))).toMatchObject({ + parameters: { + filters: expect.arrayContaining([expect.objectContaining({ value: 'sam-api-staging' })]), + }, + }); + expect(result.logs).toHaveLength(1); + expect(result.logs[0]).toMatchObject({ level: 'error' }); + }); + + it('throws a 404 FEATURE_UNAVAILABLE AppError for workersObservability without an account, with no fetch', async () => { + const failure = await queryWorkerLogs(selfHosted(), query).then( + () => null, + (err: unknown) => err + ); + + expect(failure).toBeInstanceOf(AppError); + expect(failure).toMatchObject({ + statusCode: 404, + error: 'FEATURE_UNAVAILABLE', + details: { feature: 'workersObservability' }, + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('still validates input once an account is configured (the guard does not swallow 400s)', async () => { + await expect( + queryWorkerLogs(cloudflare(), { ...query, levels: ['loud'] }) + ).rejects.toMatchObject({ statusCode: 400 }); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/tests/unit/selfhost/analytics-d1-sink.test.ts b/apps/api/tests/unit/selfhost/analytics-d1-sink.test.ts new file mode 100644 index 0000000000..6a7f4f70d7 --- /dev/null +++ b/apps/api/tests/unit/selfhost/analytics-d1-sink.test.ts @@ -0,0 +1,500 @@ +/** + * Self-host analytics on D1 (selfhost/analytics, installed by the self-host entry and switched on + * with ANALYTICS_SINK="d1"), end to end on a real SQLite engine: the request middleware and + * `/api/t` write through the real routes into the shared observability migration chain plus the + * self-host projection, then every admin analytics route reads it back through the real + * Analytics Engine SQL (translated). `fetch` is stubbed only to prove nothing calls Cloudflare. + * Auth and rate limiting are bypassed; they are not what is under test. + * + * The Cloudflare side of the same seam (nothing installed: Analytics Engine writes, the SQL API, + * no D1 call, no analytics table) is pinned at the end of this file. + */ +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { appendSelfhostObservabilityMigrations } from '../../../../../scripts/selfhost/observability-migrations'; +import type { Env } from '../../../src/env'; +import { analyticsMiddleware } from '../../../src/middleware/analytics'; +import { handleAppError } from '../../../src/middleware/app-error-handler'; +import { adminAnalyticsRoutes } from '../../../src/routes/admin-analytics'; +import { analyticsIngestRoutes } from '../../../src/routes/analytics-ingest'; +import { runObservabilityPurge } from '../../../src/scheduled/observability-purge'; +import { installAnalyticsD1Sink } from '../../../src/selfhost/analytics'; +import { purgeAnalyticsEvents } from '../../../src/selfhost/analytics/d1-sink'; +import { translateAnalyticsSql } from '../../../src/selfhost/analytics/d1-sink'; +import { + ANALYTICS_D1_MAX_ROWS_SETTING, + ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING, + ANALYTICS_D1_PURGE_TICK_BUDGET_MS_SETTING, + ANALYTICS_D1_SETTINGS, +} from '../../../src/selfhost/analytics/settings'; +import { SELFHOST_OBSERVABILITY_MIGRATIONS } from '../../../src/selfhost/observability-migrations'; +import { updateAdminSettings } from '../../../src/services/admin-settings-mutations'; +import { + adminSettingsRegistry, + resetInstalledAdminSettingDefinitionsForTests, +} from '../../../src/services/admin-settings-registry'; +import { resetLocalAnalyticsSinkExtensionForTests } from '../../../src/services/analytics-sink'; +import { resolvePlatformCapabilities } from '../../../src/services/platform-capabilities'; +import { createAdminSettingsEnv } from '../../helpers/admin-settings-env'; +import { createSqliteD1 } from '../../helpers/sqlite-d1'; + +vi.mock('../../../src/middleware/auth', () => ({ + requireAuth: () => async (_c: unknown, next: () => Promise) => next(), + requireApproved: () => async (_c: unknown, next: () => Promise) => next(), + requireSuperadmin: () => async (_c: unknown, next: () => Promise) => next(), + optionalAuth: () => async (_c: unknown, next: () => Promise) => next(), +})); +vi.mock('../../../src/middleware/rate-limit', () => ({ + rateLimit: () => async (_c: unknown, next: () => Promise) => next(), + getRateLimit: () => 500, +})); + +const MIGRATIONS = new URL('../../../src/db/migrations/observability/', import.meta.url); +const API_SRC = new URL('../../../src/', import.meta.url); + +let settingsDb: Database.Database; +let obsDb: Database.Database; +let env: Env; +let fetchMock: ReturnType; +let pending: Promise[]; + +/** The shared chain wrangler.toml applies on Cloudflare (the observability migrations_dir). */ +function sharedObservabilityMigrationFiles(): string[] { + return readdirSync(MIGRATIONS) + .filter((f) => f.endsWith('.sql')) + .sort(); +} + +/** What the self-host packager applies: the shared chain, then the self-host projection. */ +function applyObservabilityMigrations(db: Database.Database, selfHost = true) { + for (const file of sharedObservabilityMigrationFiles()) { + db.exec(readFileSync(new URL(file, MIGRATIONS), 'utf8')); + } + if (!selfHost) return; + for (const file of SELFHOST_OBSERVABILITY_MIGRATIONS) { + db.exec(readFileSync(fileURLToPath(new URL(file, API_SRC)), 'utf8')); + } +} + +const ctx = () => + ({ + waitUntil: (p: Promise) => pending.push(p), + passThroughOnException: () => undefined, + props: {}, + }) as unknown as ExecutionContext; + +function app() { + const a = new Hono<{ Bindings: Env }>(); + a.onError(handleAppError); + a.use('*', analyticsMiddleware()); + a.use('*', async (c, next) => { + // The real auth middleware sets this; the analytics middleware reads it after the handler. + // No header means an anonymous request, as on the real ingest route. + const userId = c.req.header('x-test-user'); + if (userId) c.set('auth' as never, { user: { id: userId } } as never); + await next(); + }); + a.get('/api/projects/:projectId', (c) => c.json({ ok: true })); + a.route('/api/t', analyticsIngestRoutes); + a.route('/api/admin/analytics', adminAnalyticsRoutes); + return a; +} + +async function call(path: string, init: RequestInit = {}) { + const res = await app().request(path, init, env, ctx()); + await Promise.all(pending.splice(0)); + return res; +} + +beforeEach(() => { + // What the self-host entry does once before any request. + installAnalyticsD1Sink(); + const created = createAdminSettingsEnv(); + settingsDb = created.sqlite; + obsDb = new Database(':memory:'); + applyObservabilityMigrations(obsDb); + // A box: no Analytics Engine binding, no Cloudflare account, no generated dataset name. + env = { + ...created.env, + OBSERVABILITY_DATABASE: createSqliteD1(obsDb), + ANALYTICS_SINK: 'd1', + ANALYTICS: undefined, + ANALYTICS_DATASET: undefined, + } as unknown as Env; + pending = []; + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + resetLocalAnalyticsSinkExtensionForTests(); + resetInstalledAdminSettingDefinitionsForTests(); + settingsDb.close(); + obsDb.close(); +}); + +const rows = () => + obsDb.prepare('SELECT * FROM analytics_events ORDER BY id').all() as Array< + Record + >; + +describe('D1 analytics sink (self-host)', () => { + it('advertises analyticsQuery only when the sink is switched on', () => { + expect(resolvePlatformCapabilities(env)).toMatchObject({ + analyticsQuery: true, + workersObservability: false, + }); + expect(resolvePlatformCapabilities({ ...env, ANALYTICS_SINK: undefined } as Env)).toMatchObject( + { analyticsQuery: false } + ); + }); + + it('records API requests and /api/t events, then every admin analytics route reads them back', async () => { + await call('/api/projects/proj-1', { + headers: { 'x-test-user': 'user-a', referer: 'https://app.box.example/invite/sekret-abc' }, + }); + await call('/api/projects/proj-2', { headers: { 'x-test-user': 'user-b' } }); + const ingest = await call('/api/t', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + origin: 'https://app.box.example', + 'x-test-user': 'user-a', + }, + body: JSON.stringify({ + events: [ + { + event: 'page_view', + page: '/projects/p1?token=sekret-123', + referrer: 'https://mail.example/invite/sekret-789?x=1#access_token=sekret-456', + }, + ], + }), + }); + expect(ingest.status).toBe(204); + + const stored = rows(); + // One row per project GET from the middleware, plus the page_view from /api/t. + expect(stored.filter((r) => r.blob1 === 'page_view')).toHaveLength(1); + expect(stored.map((r) => r.index1)).toEqual(expect.arrayContaining(['user-a', 'user-b'])); + // No query string or fragment survives into a stored row. + expect(JSON.stringify(stored)).not.toContain('sekret'); + const pageView = stored.find((r) => r.blob1 === 'page_view')!; + // The project id after the `projects` marker is redacted, as the web tracker would. + expect(pageView.blob3).toBe('/projects/[redacted]'); + // Request rows keep their route pattern: parameter names are not values. + expect(stored.find((r) => r.index1 === 'user-b')!.blob3).toBe('/api/projects/:projectId'); + expect(pageView.blob4).toBe('https://mail.example'); + + const dau = await call('/api/admin/analytics/dau'); + expect(dau.status, await dau.clone().text()).toBe(200); + const dauBody = (await dau.json()) as { dau: Array<{ unique_users: number }> }; + expect(dauBody.dau).toHaveLength(1); + expect(dauBody.dau[0]!.unique_users).toBe(2); + + const events = await call('/api/admin/analytics/events?period=24h'); + expect(events.status).toBe(200); + const eventBody = JSON.stringify(await events.json()); + expect(eventBody).toContain('page_view'); + + // Funnel, geo and retention were retired on main (Insights H2, #2822). + for (const route of ['feature-adoption', 'website-traffic']) { + const res = await call(`/api/admin/analytics/${route}`); + expect(res.status, route).toBe(200); + } + const traffic = await (await call('/api/admin/analytics/website-traffic')).json(); + expect(JSON.stringify(traffic)).toContain('app.box.example'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('without the switch, a box keeps answering FEATURE_UNAVAILABLE and writes nothing', async () => { + env = { ...env, ANALYTICS_SINK: undefined } as Env; + await call('/api/projects/proj-1', { headers: { 'x-test-user': 'user-a' } }); + expect(rows()).toHaveLength(0); + const res = await call('/api/admin/analytics/dau'); + expect(res.status).toBe(404); + }); + + it('the observability purge bounds the table by age and by row cap', async () => { + const insert = obsDb.prepare( + "INSERT INTO analytics_events (timestamp, index1, blob1) VALUES (datetime('now', ?), 'u', 'e')" + ); + insert.run('-200 days'); + insert.run('-100 days'); + for (let i = 0; i < 5; i += 1) insert.run(`-${i} hours`); + + await updateAdminSettings(env, { + changes: [{ name: ANALYTICS_D1_MAX_ROWS_SETTING, value: 3 }], + actorUserId: 'admin-1', + }); + await runObservabilityPurge(env); + + const left = rows(); + expect(left).toHaveLength(3); + // Both rows past the 90-day default are gone by age; the cap then keeps the newest three + // by insertion (ids 5..7 of 7). + expect(left.map((r) => r.id)).toEqual([5, 6, 7]); + }); + + it('stores anonymous visitors by network prefix and redacts sensitive page segments', async () => { + const post = (ip: string, page: string) => + call('/api/t', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + origin: 'https://app.box.example', + 'cf-connecting-ip': ip, + }, + body: JSON.stringify({ events: [{ event: 'page_view', page }] }), + }); + expect((await post('203.0.113.77', '/invite/sk-live-0123456789abcdefABCDEF')).status).toBe(204); + expect((await post('2001:db8:85a3:1:2:3:4:5', '/docs/getting-started')).status).toBe(204); + + const stored = rows().filter((r) => r.blob1 === 'page_view'); + expect(stored.map((r) => r.index1)).toEqual(['anon-203.0.113.0/24', 'anon-2001:db8:85a3::/48']); + expect(JSON.stringify(stored)).not.toContain('203.0.113.77'); + expect(JSON.stringify(stored)).not.toContain('2001:db8:85a3:1:2'); + expect(stored.map((r) => r.blob3)).toEqual(['/invite/[redacted]', '/docs/getting-started']); + }); + + it('skips the purge, deleting nothing, when the retention settings cannot be read', async () => { + obsDb + .prepare( + "INSERT INTO analytics_events (timestamp, index1, blob1) VALUES (datetime('now', '-120 days'), 'u', 'e')" + ) + .run(); + // The settings store fails while the observability database is healthy. + settingsDb.exec('DROP TABLE platform_settings'); + + expect(await purgeAnalyticsEvents(env)).toBeNull(); + // A 90-day default would have deleted this row under a 180-day policy; it stays. + expect(rows()).toHaveLength(1); + }); + + it('purges more rows than one batch holds in a single tick, oldest first (rule 81)', async () => { + const insert = obsDb.prepare( + "INSERT INTO analytics_events (timestamp, index1, blob1) VALUES (datetime('now', ?), 'u', 'e')" + ); + for (let i = 0; i < 5; i += 1) insert.run(`-${200 + i} days`); // ids 1..5, past retention + for (let i = 0; i < 12; i += 1) insert.run(`-${i} minutes`); // ids 6..17 + await updateAdminSettings(env, { + changes: [ + { name: ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING, value: 2 }, + { name: ANALYTICS_D1_MAX_ROWS_SETTING, value: 4 }, + ], + actorUserId: 'admin-1', + }); + + const result = await purgeAnalyticsEvents(env); + + // 5 aged rows and 8 over-cap rows, each larger than the 2-row batch, in one call. + expect(result).toEqual({ deletedByAge: 5, deletedByCount: 8, complete: true }); + expect(rows().map((r) => r.id)).toEqual([14, 15, 16, 17]); + }); + + it('stops at the tick budget and the next tick resumes, so a purge is bounded by time', async () => { + const insert = obsDb.prepare( + "INSERT INTO analytics_events (timestamp, index1, blob1) VALUES (datetime('now', '-200 days'), 'u', 'e')" + ); + for (let i = 0; i < 6; i += 1) insert.run(); + await updateAdminSettings(env, { + changes: [ + { name: ANALYTICS_D1_PURGE_BATCH_ROWS_SETTING, value: 2 }, + { name: ANALYTICS_D1_PURGE_TICK_BUDGET_MS_SETTING, value: 1 }, + ], + actorUserId: 'admin-1', + }); + // Every clock read moves 1 s on, so the 1 ms budget is spent after the first batch. + let now = Date.parse('2026-11-18T12:00:00Z'); + const clock = vi.spyOn(Date, 'now').mockImplementation(() => (now += 1_000)); + + try { + expect(await purgeAnalyticsEvents(env)).toMatchObject({ deletedByAge: 2, complete: false }); + expect(rows()).toHaveLength(4); + expect(await purgeAnalyticsEvents(env)).toMatchObject({ deletedByAge: 2, complete: false }); + expect(await purgeAnalyticsEvents(env)).toMatchObject({ deletedByAge: 2 }); + expect(await purgeAnalyticsEvents(env)).toEqual({ + deletedByAge: 0, + deletedByCount: 0, + complete: true, + }); + } finally { + clock.mockRestore(); + } + expect(rows()).toHaveLength(0); + }); + + it('still bounds analytics when the error purge fails, and still reports that failure', async () => { + const insert = obsDb.prepare( + "INSERT INTO analytics_events (timestamp, index1, blob1) VALUES (datetime('now', '-200 days'), 'u', 'e')" + ); + insert.run(); + obsDb.exec('DROP TABLE platform_errors'); + + await expect(runObservabilityPurge(env)).rejects.toThrow(); + expect(rows()).toHaveLength(0); + }); + + it('registers its settings only through the self-host install point', () => { + const names = adminSettingsRegistry().map((definition) => definition.name); + for (const definition of ANALYTICS_D1_SETTINGS) expect(names).toContain(definition.name); + resetInstalledAdminSettingDefinitionsForTests(); + const cloudflareNames = adminSettingsRegistry().map((definition) => definition.name); + for (const definition of ANALYTICS_D1_SETTINGS) { + expect(cloudflareNames).not.toContain(definition.name); + } + // Liveness: the shared registry is still populated. + expect(cloudflareNames.length).toBeGreaterThan(10); + }); + + it('the self-host packager projects the table into the observability database', () => { + const scratch = mkdtempSync(join(tmpdir(), 'sam-obs-projection-')); + try { + const flat = join(scratch, 'flat'); + mkdirSync(flat); + for (const file of sharedObservabilityMigrationFiles()) { + symlinkSync(fileURLToPath(new URL(file, MIGRATIONS)), join(flat, file)); + } + const apiDir = fileURLToPath(new URL('../../../', import.meta.url)); + appendSelfhostObservabilityMigrations(apiDir, flat); + appendSelfhostObservabilityMigrations(apiDir, flat); // idempotent + const db = new Database(':memory:'); + for (const file of readdirSync(flat).sort()) db.exec(readFileSync(join(flat, file), 'utf8')); + const tables = ( + db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Array<{ + name: string; + }> + ).map((t) => t.name); + expect(tables).toEqual(expect.arrayContaining(['platform_errors', 'analytics_events'])); + db.close(); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + }); + + it('refuses Analytics Engine SQL it cannot translate instead of returning wrong numbers', () => { + expect(() => translateAnalyticsSql('SELECT quantileWeighted(0.5)(double1) FROM ds')).toThrow( + /cannot translate/ + ); + expect( + translateAnalyticsSql( + "SELECT toDate(timestamp) AS d, count() FROM sam_ds WHERE timestamp >= NOW() - INTERVAL '7' DAY" + ) + ).toBe( + "SELECT date(timestamp) AS d, count(*) FROM analytics_events WHERE timestamp >= datetime('now', '-7 days')" + ); + }); +}); + +describe('Cloudflare (the shared Worker installs no local sink)', () => { + let writeDataPoint: ReturnType; + let observabilityPrepare: ReturnType; + + beforeEach(() => { + // The Cloudflare entry never imports selfhost/: undo the install the outer hook performed. + resetLocalAnalyticsSinkExtensionForTests(); + resetInstalledAdminSettingDefinitionsForTests(); + writeDataPoint = vi.fn(); + observabilityPrepare = vi.fn(() => { + throw new Error('Cloudflare analytics must not touch OBSERVABILITY_DATABASE'); + }); + // Production's shape (2026-11-18 script settings): Analytics Engine binding, generated dataset, + // Cloudflare account API, no ANALYTICS_SINK. Even a stray ANALYTICS_SINK="d1" does nothing + // without the self-host install. + env = { + ...env, + ANALYTICS: { writeDataPoint }, + ANALYTICS_DATASET: 'sam_analytics', + ANALYTICS_SINK: 'd1', + CF_ACCOUNT_ID: 'account-1', + CF_API_TOKEN: 'token-1', + OBSERVABILITY_DATABASE: { prepare: observabilityPrepare, batch: observabilityPrepare }, + } as unknown as Env; + }); + + it('writes requests and /api/t events to Analytics Engine, never to D1', async () => { + await call('/api/projects/proj-1', { headers: { 'x-test-user': 'user-a' } }); + const ingest = await call('/api/t', { + method: 'POST', + headers: { 'Content-Type': 'application/json', origin: 'https://app.example.com' }, + body: JSON.stringify({ events: [{ event: 'page_view', page: '/projects/p1' }] }), + }); + + expect(ingest.status).toBe(204); + // The project GET (middleware), the page_view (/api/t), and the middleware's own row for the + // /api/t request: every one reached Analytics Engine. + const written = writeDataPoint.mock.calls.map( + ([point]) => point as { indexes: string[]; blobs: string[] } + ); + expect(written.map((point) => point.blobs[0])).toContain('page_view'); + expect( + written.some((point) => point.indexes[0] === 'user-a' && point.blobs[1] === 'proj-1') + ).toBe(true); + expect(observabilityPrepare).not.toHaveBeenCalled(); + }); + + it('queries the Analytics Engine SQL API for admin analytics, with the generated dataset', async () => { + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ data: [{ date: '2026-11-18', unique_users: '3' }] }), { + status: 200, + }) + ); + + const res = await call('/api/admin/analytics/dau'); + + expect(res.status).toBe(200); + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe( + 'https://api.cloudflare.com/client/v4/accounts/account-1/analytics_engine/sql' + ); + expect(String(init.body)).toContain('FROM sam_analytics'); + expect(observabilityPrepare).not.toHaveBeenCalled(); + }); + + it('runs the observability purge without any analytics statement', async () => { + const statements: string[] = []; + const obs = createSqliteD1(obsDb); + env = { + ...env, + OBSERVABILITY_DATABASE: { + ...obs, + prepare: (sql: string) => { + statements.push(sql); + return obs.prepare(sql); + }, + batch: obs.batch.bind(obs), + }, + } as unknown as Env; + + await runObservabilityPurge(env); + + // Liveness: the error purge ran; and nothing touched analytics_events. + expect(statements.some((sql) => /platform_errors/.test(sql))).toBe(true); + expect(statements.some((sql) => /analytics_events/.test(sql))).toBe(false); + }); + + it('the shared observability migration chain never creates the analytics table', () => { + const cloudflareDb = new Database(':memory:'); + try { + applyObservabilityMigrations(cloudflareDb, false); + const tables = cloudflareDb + .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() as Array<{ name: string }>; + // Liveness: the shared chain did run. + expect(tables.map((t) => t.name)).toContain('platform_errors'); + expect(tables.map((t) => t.name)).not.toContain('analytics_events'); + expect(sharedObservabilityMigrationFiles().join('\n')).not.toMatch(/analytics/); + } finally { + cloudflareDb.close(); + } + }); +}); diff --git a/apps/api/tests/unit/selfhost/analytics-selfhost-only.test.ts b/apps/api/tests/unit/selfhost/analytics-selfhost-only.test.ts new file mode 100644 index 0000000000..b0eec14f6a --- /dev/null +++ b/apps/api/tests/unit/selfhost/analytics-selfhost-only.test.ts @@ -0,0 +1,41 @@ +/** + * The self-host D1 analytics sink (src/selfhost/analytics/) and its migration list must not reach + * the Cloudflare bundle, while the seam it plugs into (services/analytics-sink.ts) must. Positive + * control included so an empty walk cannot pass as "all clear". + */ +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { + API_SRC, + collectImportGraph, + selfhostOnlyFindings, +} from '../../helpers/selfhost-only-modules'; + +describe('self-host analytics sink placement', () => { + // Walking the full Worker graph can exceed Vitest's default under shared CI load. + it('the Worker entry reaches the analytics seam but no self-host analytics module', () => { + const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); + expect(graph.files).toContain('apps/api/src/services/analytics-sink.ts'); + expect( + graph.files.filter( + (file) => + file.startsWith('apps/api/src/selfhost/analytics/') || + file === 'apps/api/src/selfhost/observability-migrations.ts' + ) + ).toEqual([]); + }, 30_000); + + it('positive control: the analytics module is flagged as self-host-only when walked', () => { + const graph = collectImportGraph(resolve(API_SRC, 'selfhost/analytics/index.ts')); + expect(selfhostOnlyFindings(graph)).toEqual( + expect.arrayContaining([ + 'apps/api/src/selfhost/analytics/index.ts', + 'apps/api/src/selfhost/analytics/d1-sink.ts', + 'apps/api/src/selfhost/analytics/settings.ts', + ]) + ); + expect(graph.files).toContain('apps/api/src/services/analytics-sink.ts'); + }); +}); diff --git a/apps/api/tests/unit/services/attachment-upload.test.ts b/apps/api/tests/unit/services/attachment-upload.test.ts index 0936a4577c..91da458b1d 100644 --- a/apps/api/tests/unit/services/attachment-upload.test.ts +++ b/apps/api/tests/unit/services/attachment-upload.test.ts @@ -86,7 +86,7 @@ describe('generatePresignedUploadUrl', () => { const env = makePresignEnv({ R2_BUCKET_NAME: undefined }); await expect( generatePresignedUploadUrl(env, validOptions), - ).rejects.toThrow('R2_BUCKET_NAME not configured'); + ).rejects.toThrow('R2_BUCKET_NAME'); }); it('rejects when R2 S3 credentials are missing', async () => { diff --git a/apps/api/tests/unit/services/platform-capabilities.test.ts b/apps/api/tests/unit/services/platform-capabilities.test.ts index f10907ece1..43959dd283 100644 --- a/apps/api/tests/unit/services/platform-capabilities.test.ts +++ b/apps/api/tests/unit/services/platform-capabilities.test.ts @@ -1,6 +1,11 @@ -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; +import { + installLocalAnalyticsSinkExtension, + type LocalAnalyticsSinkExtension, + resetLocalAnalyticsSinkExtensionForTests, +} from '../../../src/services/analytics-sink'; import { getWorkersAiBindingOrNull, publicPlatformCapabilities, @@ -9,22 +14,40 @@ import { /** * The capability inputs exactly as the production API Worker (`sam-api-prod`) had them when read - * from the Cloudflare script-settings API on 2026-11-16: an `ai` binding (an object with `run` - * and `models`), and TTS_ENABLED and LOG_TAIL_AVAILABLE not bound at all. Everything else on the - * Worker is irrelevant to the resolver. + * from the Cloudflare script-settings API on 2026-11-16 and again on 2026-11-18 (binding names and + * types only): an `ai` binding (an object with `run` and `models`), an `analytics_engine` binding + * `ANALYTICS` (dataset `sam_analytics`) with `ANALYTICS_DATASET`, CF_ACCOUNT_ID and CF_API_TOKEN + * as secrets, a `tail_consumers` attachment, and TTS_ENABLED, LOG_TAIL_AVAILABLE and + * ANALYTICS_SINK not bound at all. Everything else on the Worker is irrelevant to the resolver. */ function cloudflareProductionEnv(overrides: Partial = {}): Env { return { AI: { run: async () => ({}), models: async () => [] }, AI_GATEWAY_ID: 'sam', + ANALYTICS: { writeDataPoint: () => undefined }, + ANALYTICS_DATASET: 'sam_analytics', CF_ACCOUNT_ID: 'account-1', CF_API_TOKEN: 'token-1', CF_ZONE_ID: 'zone-1', BASE_DOMAIN: 'example.com', + OBSERVABILITY_DATABASE: {}, ...overrides, } as unknown as Env; } +/** A local sink that is active whenever ANALYTICS_SINK is "d1", as the self-host one is. */ +const localSink: LocalAnalyticsSinkExtension = { + table: 'analytics_events', + active: (env) => env.ANALYTICS_SINK === 'd1', + sink: () => ({ write: vi.fn(async () => undefined) }), + query: vi.fn(async () => []), + purge: vi.fn(async () => undefined), +}; + +afterEach(() => { + resetLocalAnalyticsSinkExtensionForTests(); +}); + describe('resolvePlatformCapabilities', () => { // Rule 74: the condition is "this installation has the service"; the guard must not hide a // control on Cloudflare. Resolve production's shape through the real resolver and require @@ -32,12 +55,75 @@ describe('resolvePlatformCapabilities', () => { it('resolves every capability to true for the production Cloudflare configuration', () => { const capabilities = resolvePlatformCapabilities(cloudflareProductionEnv()); expect(Object.entries(capabilities).filter(([, value]) => !value)).toEqual([]); - expect(Object.keys(capabilities).sort()).toEqual(['speechToText', 'textToSpeech', 'workersAi']); + expect(Object.keys(capabilities).sort()).toEqual([ + 'analyticsQuery', + 'liveLogStream', + 'speechToText', + 'textToSpeech', + 'workersAi', + 'workersObservability', + ]); }); it('reports every Workers AI service absent without the binding', () => { const capabilities = resolvePlatformCapabilities(cloudflareProductionEnv({ AI: undefined })); - expect(capabilities).toEqual({ workersAi: false, speechToText: false, textToSpeech: false }); + expect(capabilities).toEqual({ + workersAi: false, + speechToText: false, + textToSpeech: false, + analyticsQuery: true, + workersObservability: true, + liveLogStream: true, + }); + }); + + it('keeps analytics, log search and the stream on for production even with a sink installed', () => { + // Divergence (rule 74): the self-host sink being installed in the isolate is not the condition; + // only ANALYTICS_SINK="d1" activates it, and production does not set it. + installLocalAnalyticsSinkExtension(localSink); + const capabilities = resolvePlatformCapabilities(cloudflareProductionEnv()); + expect(capabilities.analyticsQuery).toBe(true); + expect(capabilities.workersObservability).toBe(true); + expect(capabilities.liveLogStream).toBe(true); + }); + + it('reports analytics, log search and the stream absent on a box with nothing installed', () => { + const capabilities = resolvePlatformCapabilities( + cloudflareProductionEnv({ + CF_ACCOUNT_ID: undefined, + CF_API_TOKEN: undefined, + ANALYTICS: undefined, + LOG_TAIL_AVAILABLE: 'false', + }) + ); + expect(capabilities.analyticsQuery).toBe(false); + expect(capabilities.workersObservability).toBe(false); + expect(capabilities.liveLogStream).toBe(false); + }); + + it('reports analytics available on a box whose installed local sink is active', () => { + installLocalAnalyticsSinkExtension(localSink); + const box = cloudflareProductionEnv({ + CF_ACCOUNT_ID: undefined, + CF_API_TOKEN: undefined, + ANALYTICS: undefined, + }); + expect(resolvePlatformCapabilities({ ...box, ANALYTICS_SINK: 'd1' }).analyticsQuery).toBe(true); + // Control: the same box without the switch has no analytics to query. + expect(resolvePlatformCapabilities(box).analyticsQuery).toBe(false); + }); + + it('treats only LOG_TAIL_AVAILABLE="false" as no live stream', () => { + for (const value of ['true', '', 'TRUE']) { + expect( + resolvePlatformCapabilities(cloudflareProductionEnv({ LOG_TAIL_AVAILABLE: value })) + .liveLogStream + ).toBe(true); + } + expect( + resolvePlatformCapabilities(cloudflareProductionEnv({ LOG_TAIL_AVAILABLE: ' False ' })) + .liveLogStream + ).toBe(false); }); it('keeps TTS off when the binding exists but TTS_ENABLED is "false"', () => { @@ -69,6 +155,8 @@ describe('publicPlatformCapabilities', () => { expect(publicPlatformCapabilities(cloudflareProductionEnv())).toEqual({ speechToText: true, textToSpeech: true, + logSearch: true, + liveLogStream: true, agentModelCalls: true, }); }); diff --git a/apps/api/tests/unit/services/r2-presign-cloudflare-equivalence.test.ts b/apps/api/tests/unit/services/r2-presign-cloudflare-equivalence.test.ts new file mode 100644 index 0000000000..c3fd610f9a --- /dev/null +++ b/apps/api/tests/unit/services/r2-presign-cloudflare-equivalence.test.ts @@ -0,0 +1,196 @@ +/** + * Cloudflare pin for the shared R2 presign client (services/r2-s3-client.ts). + * + * Before L20 the worker signed R2 URLs with two clients: `getR2S3Client` (attachments, session + * snapshots; `requestChecksumCalculation: 'WHEN_REQUIRED'`) and app-deployment's `getS3Client` + * (compose image artifacts with `WHEN_SUPPORTED`, build contexts with `WHEN_REQUIRED`). Each test + * here rebuilds the former client exactly as main configured it, signs the same command at the + * same instant, and requires the URL the production entry point returns to be byte-identical. + * The env is production's shape (2026-11-18 script settings): R2_ACCESS_KEY_ID and + * R2_SECRET_ACCESS_KEY secrets, CF_ACCOUNT_ID, R2_BUCKET_NAME, and no R2_S3_* variable. + */ +import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { generatePresignedUploadUrl } from '../../../src/services/attachment-upload'; +import { + createBuildContextDownload, + createBuildContextUpload, +} from '../../../src/services/build-context-upload'; +import { + createComposeImageArtifactDownloads, + createComposeImageArtifactUploads, +} from '../../../src/services/compose-image-artifacts'; +import { resetR2S3ClientsForTests } from '../../../src/services/r2-s3-client'; +import { generateSessionSnapshotDirectUploadUrl } from '../../../src/services/session-snapshot-direct-upload'; + +const ACCOUNT = 'acct123'; +const BUCKET = 'sam-prod-assets'; + +function productionEnv(): Env { + return { + CF_ACCOUNT_ID: ACCOUNT, + R2_ACCESS_KEY_ID: 'AKIDEXAMPLE', + R2_SECRET_ACCESS_KEY: 'secret-example', + R2_BUCKET_NAME: BUCKET, + } as Env; +} + +/** The client main built, keyed by the checksum mode each caller used. */ +function formerClient(requestChecksumCalculation: 'WHEN_REQUIRED' | 'WHEN_SUPPORTED') { + return new S3Client({ + region: 'auto', + endpoint: `https://${ACCOUNT}.r2.cloudflarestorage.com`, + requestChecksumCalculation, + credentials: { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'secret-example' }, + }); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-11-18T12:00:00Z')); +}); + +afterEach(() => { + vi.useRealTimers(); + resetR2S3ClientsForTests(); +}); + +describe('shared R2 presign client on Cloudflare', () => { + it('signs attachment uploads exactly as before', async () => { + const result = await generatePresignedUploadUrl(productionEnv(), { + userId: 'u1', + uploadId: 'up1', + filename: 'report.pdf', + size: 10, + contentType: 'application/pdf', + }); + const expected = await getSignedUrl( + formerClient('WHEN_REQUIRED'), + new PutObjectCommand({ + Bucket: BUCKET, + Key: result.r2Key, + ContentLength: 10, + ContentType: 'application/pdf', + }), + { expiresIn: result.expiresIn } + ); + expect(result.uploadUrl).toBe(expected); + expect(new URL(result.uploadUrl).host).toBe(`${BUCKET}.${ACCOUNT}.r2.cloudflarestorage.com`); + }); + + it('signs session snapshot uploads exactly as before, with and without the checksum header', async () => { + const input = { + key: 'session-snapshots/p1/s1/a.tar.zst', + sizeBytes: 2048, + sha256: 'a'.repeat(64), + contentType: 'application/zstd', + }; + for (const checksumHeader of [false, true]) { + const actual = await generateSessionSnapshotDirectUploadUrl(productionEnv(), { + ...input, + checksumHeader, + }); + const command = new PutObjectCommand({ + Bucket: BUCKET, + Key: input.key, + ContentLength: input.sizeBytes, + ContentType: input.contentType, + ChecksumSHA256: btoa(String.fromCharCode(...new Uint8Array(32).fill(0xaa))), + }); + const expected = await getSignedUrl(formerClient('WHEN_REQUIRED'), command, { + expiresIn: 15 * 60, + ...(checksumHeader ? { unhoistableHeaders: new Set(['x-amz-checksum-sha256']) } : {}), + }); + expect(actual, `checksumHeader=${checksumHeader}`).toBe(expected); + } + }); + + it('signs compose image artifact uploads and downloads with the SDK default checksum mode, as before', async () => { + const uploads = await createComposeImageArtifactUploads(productionEnv(), { + projectId: 'p1', + workspaceId: 'w1', + environmentId: 'e1', + uploadId: 'up1', + services: [{ serviceName: 'web', sourceRef: 'nginx:1' }], + }); + const [upload] = uploads; + expect(upload).toBeDefined(); + const expectedUpload = await getSignedUrl( + formerClient('WHEN_SUPPORTED'), + new PutObjectCommand({ + Bucket: BUCKET, + Key: upload!.r2Key, + ContentType: 'application/vnd.docker.image.rootfs.diff.tar', + }), + { expiresIn: upload!.expiresIn } + ); + expect(upload!.uploadUrl).toBe(expectedUpload); + + const [download] = await createComposeImageArtifactDownloads(productionEnv(), [ + { + serviceName: 'web', + sourceRef: 'nginx:1', + localImageRef: 'nginx:1', + r2Key: upload!.r2Key, + sizeBytes: 10, + archiveSha256: 'b'.repeat(64), + archiveType: 'docker-save', + mediaType: 'application/vnd.docker.image.rootfs.diff.tar', + } as never, + ]); + const expectedDownload = await getSignedUrl( + formerClient('WHEN_SUPPORTED'), + new GetObjectCommand({ Bucket: BUCKET, Key: upload!.r2Key }), + { expiresIn: download!.downloadExpiresIn } + ); + expect(download!.downloadUrl).toBe(expectedDownload); + }); + + it('signs build context uploads and downloads exactly as before', async () => { + const owner = { + id: 'job1', + projectId: 'p1', + environmentId: 'e1', + workspaceId: 'w1', + requestedBy: 'u1', + attempt: 1, + }; + const descriptor = { sizeBytes: 4096, sha256: 'c'.repeat(64) }; + const upload = await createBuildContextUpload(productionEnv(), owner, descriptor, 600); + const expectedUpload = await getSignedUrl( + formerClient('WHEN_REQUIRED'), + new PutObjectCommand({ + Bucket: BUCKET, + Key: upload.r2Key, + ContentLength: descriptor.sizeBytes, + ContentType: 'application/zstd', + Metadata: { sha256: descriptor.sha256 }, + }), + { expiresIn: 600, unhoistableHeaders: new Set(['x-amz-meta-sha256']) } + ); + expect(upload.uploadUrl).toBe(expectedUpload); + + const download = await createBuildContextDownload(productionEnv(), upload.r2Key, 300); + const expectedDownload = await getSignedUrl( + formerClient('WHEN_REQUIRED'), + new GetObjectCommand({ Bucket: BUCKET, Key: upload.r2Key }), + { expiresIn: 300 } + ); + expect(download).toBe(expectedDownload); + }); + + it('still rejects with a configuration error when the bucket name is missing', async () => { + await expect( + createComposeImageArtifactUploads({ ...productionEnv(), R2_BUCKET_NAME: undefined } as Env, { + projectId: 'p1', + workspaceId: 'w1', + environmentId: 'e1', + uploadId: 'up1', + services: [{ serviceName: 'web', sourceRef: 'nginx:1' }], + }) + ).rejects.toThrow(/R2_BUCKET_NAME/); + }); +}); diff --git a/apps/api/tests/unit/services/r2-presign-config.test.ts b/apps/api/tests/unit/services/r2-presign-config.test.ts new file mode 100644 index 0000000000..a7a6fa8111 --- /dev/null +++ b/apps/api/tests/unit/services/r2-presign-config.test.ts @@ -0,0 +1,169 @@ +import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import { afterEach, describe, expect, it } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { generatePresignedUploadUrl } from '../../../src/services/attachment-upload'; +import { resolveR2PresignConfig } from '../../../src/services/r2-presign-config'; +import { + getR2PresignTarget, + hasR2S3Credentials, + resetR2S3ClientsForTests, +} from '../../../src/services/r2-s3-client'; + +const credentials = { R2_ACCESS_KEY_ID: 'AKIDEXAMPLE', R2_SECRET_ACCESS_KEY: 'secret-example' }; + +function cloudflareEnv(overrides: Partial = {}): Env { + return { + ...credentials, + CF_ACCOUNT_ID: 'acct123', + R2_BUCKET_NAME: 'sam-assets', + ...overrides, + } as Env; +} + +/** celld keeps the R2 binding's objects at r2// in its fleet bucket. */ +function operatorStoreEnv(overrides: Partial = {}): Env { + return { + ...credentials, + R2_BUCKET_NAME: 'sam-assets', + R2_S3_ENDPOINT: 'http://127.0.0.1:9000', + R2_S3_BUCKET: 'celld-fleet', + R2_S3_KEY_PREFIX: 'r2/sam-assets/', + R2_S3_REGION: 'us-east-1', + ...overrides, + } as Env; +} + +afterEach(() => resetR2S3ClientsForTests()); + +describe('resolveR2PresignConfig', () => { + it('targets Cloudflare R2 exactly as before when no operator store is configured', () => { + expect(resolveR2PresignConfig(cloudflareEnv())).toEqual({ + endpoint: 'https://acct123.r2.cloudflarestorage.com', + bucket: 'sam-assets', + keyPrefix: '', + region: 'auto', + forcePathStyle: undefined, + accessKeyId: 'AKIDEXAMPLE', + secretAccessKey: 'secret-example', + }); + }); + + it('targets the operator store with prefix, path style and region', () => { + expect(resolveR2PresignConfig(operatorStoreEnv())).toMatchObject({ + endpoint: 'http://127.0.0.1:9000', + bucket: 'celld-fleet', + keyPrefix: 'r2/sam-assets/', + region: 'us-east-1', + forcePathStyle: true, + }); + }); + + it('allows virtual-host addressing on an operator store when asked', () => { + expect( + resolveR2PresignConfig(operatorStoreEnv({ R2_S3_FORCE_PATH_STYLE: 'false' }))?.forcePathStyle + ).toBe(false); + }); + + it.each([ + ['no bucket', { R2_S3_BUCKET: '' }], + ['no key prefix', { R2_S3_KEY_PREFIX: '' }], + ['no signing region', { R2_S3_REGION: '' }], + ['absolute key prefix', { R2_S3_KEY_PREFIX: '/r2/sam-assets/' }], + ['escaping key prefix', { R2_S3_KEY_PREFIX: 'r2/../deploy/' }], + ['non-HTTP endpoint', { R2_S3_ENDPOINT: 'ftp://store' }], + ['endpoint with credentials', { R2_S3_ENDPOINT: 'https://user:pass@store.example.com' }], + ['prefix without a trailing slash', { R2_S3_KEY_PREFIX: 'r2/sam-assets' }], + ['prefix with an empty segment', { R2_S3_KEY_PREFIX: 'r2//sam-assets/' }], + ['plain HTTP to a public host', { R2_S3_ENDPOINT: 'http://s3.example.com' }], + ['a metadata address', { R2_S3_ENDPOINT: 'https://169.254.169.254' }], + ])('refuses a partial operator store (%s) instead of falling back to Cloudflare', (_, change) => { + // CF_ACCOUNT_ID is present: a fallback would sign store keys for Cloudflare R2. + const env = operatorStoreEnv({ CF_ACCOUNT_ID: 'acct123', ...change }); + expect(resolveR2PresignConfig(env)).toBeNull(); + expect(hasR2S3Credentials(env)).toBe(false); + }); + + it.each(['R2_S3_BUCKET', 'R2_S3_KEY_PREFIX', 'R2_S3_REGION', 'R2_S3_FORCE_PATH_STYLE'] as const)( + 'refuses %s without R2_S3_ENDPOINT instead of signing for Cloudflare R2', + (name) => { + const env = cloudflareEnv({ [name]: 'celld-fleet' }); + expect(resolveR2PresignConfig(env)).toBeNull(); + expect(hasR2S3Credentials(cloudflareEnv())).toBe(true); + } + ); + + it('needs both halves of the credential in either mode', () => { + expect(resolveR2PresignConfig(cloudflareEnv({ R2_SECRET_ACCESS_KEY: '' }))).toBeNull(); + expect(resolveR2PresignConfig(operatorStoreEnv({ R2_ACCESS_KEY_ID: '' }))).toBeNull(); + }); +}); + +describe('presigned URLs address the object the R2 binding reads', () => { + it('maps an R2 key to in the store bucket, path style', async () => { + const target = getR2PresignTarget(operatorStoreEnv()); + const url = new URL( + await getSignedUrl( + target.client, + new PutObjectCommand({ + Bucket: target.bucket, + Key: target.objectKey('attachments/u1/up1/report.pdf'), + ContentType: 'application/pdf', + }), + { expiresIn: 60 } + ) + ); + expect(url.origin).toBe('http://127.0.0.1:9000'); + expect(url.pathname).toBe('/celld-fleet/r2/sam-assets/attachments/u1/up1/report.pdf'); + expect(url.searchParams.get('X-Amz-Credential')).toContain('/us-east-1/s3/aws4_request'); + }); + + it('keeps the Cloudflare URL shape: bucket host, unprefixed key', async () => { + const target = getR2PresignTarget(cloudflareEnv()); + const url = new URL( + await getSignedUrl( + target.client, + new GetObjectCommand({ Bucket: target.bucket, Key: target.objectKey('a/b.txt') }), + { expiresIn: 60 } + ) + ); + expect(url.host).toBe('sam-assets.acct123.r2.cloudflarestorage.com'); + expect(url.pathname).toBe('/a/b.txt'); + expect(url.searchParams.get('X-Amz-Credential')).toContain('/auto/s3/aws4_request'); + }); + + it('attachment uploads return the binding key while the URL carries the store key', async () => { + const result = await generatePresignedUploadUrl(operatorStoreEnv(), { + userId: 'u1', + uploadId: 'up1', + filename: 'report.pdf', + size: 10, + contentType: 'application/pdf', + }); + expect(result.r2Key).not.toMatch(/^r2\//); + expect(new URL(result.uploadUrl).pathname).toBe(`/celld-fleet/r2/sam-assets/${result.r2Key}`); + }); +}); + +describe('object keys under an operator prefix', () => { + it.each([ + '../deploy/workspaces-api/manifest.json', + 'a/../../x', + 'a/./b', + '/abs', + 'a\\b', + 'a\u0000b', + ])('refuses %j so a signed URL cannot leave the prefix', (key) => { + const target = getR2PresignTarget(operatorStoreEnv()); + expect(() => target.objectKey(key)).toThrow('unsafe path segment'); + }); + + it('keeps ordinary keys, and leaves Cloudflare keys untouched', () => { + expect(getR2PresignTarget(operatorStoreEnv()).objectKey('a/b.c/d')).toBe( + 'r2/sam-assets/a/b.c/d' + ); + // On Cloudflare there is no prefix to escape; object names stay opaque as before. + expect(getR2PresignTarget(cloudflareEnv()).objectKey('a/../b')).toBe('a/../b'); + }); +}); diff --git a/apps/api/tests/unit/web-assets-host-dispatch.test.ts b/apps/api/tests/unit/web-assets-host-dispatch.test.ts new file mode 100644 index 0000000000..1292928c8a --- /dev/null +++ b/apps/api/tests/unit/web-assets-host-dispatch.test.ts @@ -0,0 +1,147 @@ +/** + * Self-hosted (celld) deployments bind the apps/web build as `ASSETS` and serve + * app.${BASE_DOMAIN} from it; Cloudflare deployments have no ASSETS binding and proxy + * app.* to Pages. These tests drive the real Worker entry (`src/index.ts` default export) + * through the real middleware chain. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { resolvePagesProxyTarget } from '../../src/lib/pages-proxy'; + +vi.mock('cloudflare:workers', () => ({ DurableObject: class {}, WorkerEntrypoint: class {} }), { + virtual: true, +}); +vi.mock('@cloudflare/sandbox', () => ({ Sandbox: class {} })); +vi.mock('@cloudflare/containers', () => ({ + Container: class {}, + switchPort: vi.fn((request: Request) => request), +})); + +const worker = await import('../../src/index'); + +const BASE_DOMAIN = 'sam.example.com'; +const WORKSPACE_ID = '01kr1000000000000000000001'; + +function assetsBinding() { + return { + fetch: vi.fn( + async (request: Request) => + new Response(`spa:${new URL(request.url).pathname}`, { + status: 200, + headers: { 'content-type': 'text/html', 'x-frame-options': 'DENY' }, + }) + ), + }; +} + +const ctx = { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), + props: {}, +} as unknown as ExecutionContext; + +function call(url: string, env: Record, init?: RequestInit) { + return worker.default.fetch(new Request(url, init), env as never, ctx); +} + +describe('web UI host dispatch', () => { + beforeEach(() => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('from-pages', { status: 200 })) + ); + }); + afterEach(() => { + vi.unstubAllGlobals(); + }); + + describe('with an ASSETS binding (self-hosted)', () => { + it('serves app.${BASE_DOMAIN} deep links from ASSETS and never calls Pages', async () => { + const ASSETS = assetsBinding(); + const response = await call(`https://app.${BASE_DOMAIN}/projects/abc/chat`, { + BASE_DOMAIN, + ASSETS, + PAGES_PROJECT_NAME: 'would-be-ignored', + }); + + expect(response.status).toBe(200); + expect(await response.text()).toBe('spa:/projects/abc/chat'); + expect(response.headers.get('x-frame-options')).toBe('DENY'); + expect(ASSETS.fetch).toHaveBeenCalledTimes(1); + expect(ASSETS.fetch.mock.calls[0]![0].url).toBe( + `https://app.${BASE_DOMAIN}/projects/abc/chat` + ); + expect(globalThis.fetch).not.toHaveBeenCalled(); + }); + + it('keeps api.${BASE_DOMAIN} on the Worker', async () => { + const ASSETS = assetsBinding(); + const response = await call(`https://api.${BASE_DOMAIN}/index.html`, { BASE_DOMAIN, ASSETS }); + + expect(ASSETS.fetch).not.toHaveBeenCalled(); + // The Worker's own 404, not the SPA shell. + expect(response.status).toBe(404); + expect(await response.json()).toMatchObject({ error: 'NOT_FOUND' }); + }); + + it('keeps ws-* hosts on the workspace proxy', async () => { + const ASSETS = assetsBinding(); + const response = await call(`https://ws-${WORKSPACE_ID}.${BASE_DOMAIN}/index.html`, { + BASE_DOMAIN, + ASSETS, + DATABASE: {}, + }); + + expect(ASSETS.fetch).not.toHaveBeenCalled(); + // Reached the workspace proxy (which fails here on the unmocked auth stack), not the SPA. + const body = await response.text(); + expect(body).not.toContain('spa:'); + expect(response.headers.get('content-type')).toContain('application/json'); + }); + }); + + describe('without an ASSETS binding (Cloudflare)', () => { + it('proxies app.${BASE_DOMAIN} to the Pages project exactly as before', async () => { + const response = await call(`https://app.${BASE_DOMAIN}/projects/abc/chat`, { + BASE_DOMAIN, + PAGES_PROJECT_NAME: 'sam-web-prod', + }); + + expect(response.status).toBe(200); + expect(await response.text()).toBe('from-pages'); + const pagesRequest = vi.mocked(globalThis.fetch).mock.calls[0]![0] as Request; + expect(new URL(pagesRequest.url).hostname).toBe('sam-web-prod.pages.dev'); + expect(new URL(pagesRequest.url).pathname).toBe('/projects/abc/chat'); + }); + + it('still fails visibly when the Pages project is not configured', async () => { + const response = await call(`https://app.${BASE_DOMAIN}/`, { BASE_DOMAIN }); + expect(response.status).toBe(503); + expect(await response.text()).toBe('PAGES_PROJECT_NAME is not configured'); + }); + }); +}); + +describe('resolvePagesProxyTarget with web assets', () => { + it('routes only the app host to assets', () => { + const config = { baseDomain: BASE_DOMAIN, hasWebAssets: true, wwwPagesProjectName: 'www' }; + expect(resolvePagesProxyTarget(`app.${BASE_DOMAIN}`, config)).toEqual({ type: 'assets' }); + expect(resolvePagesProxyTarget(`api.${BASE_DOMAIN}`, config)).toEqual({ type: 'none' }); + expect(resolvePagesProxyTarget(`www.${BASE_DOMAIN}`, config)).toEqual({ + type: 'proxy', + hostname: 'www.pages.dev', + }); + }); + + it('is unchanged when hasWebAssets is false or absent', () => { + for (const hasWebAssets of [false, undefined]) { + expect( + resolvePagesProxyTarget(`app.${BASE_DOMAIN}`, { + baseDomain: BASE_DOMAIN, + appPagesProjectName: 'p', + hasWebAssets, + }) + ).toEqual({ type: 'proxy', hostname: 'p.pages.dev' }); + } + }); +}); diff --git a/apps/web/src/components/admin/BoxLogsNotice.tsx b/apps/web/src/components/admin/BoxLogsNotice.tsx new file mode 100644 index 0000000000..8d90b19e6b --- /dev/null +++ b/apps/web/src/components/admin/BoxLogsNotice.tsx @@ -0,0 +1,30 @@ +import { Body, Card } from '@simple-agent-manager/ui'; +import type { FC } from 'react'; + +/** Commands for reading logs on a self-hosted box (the compose services the self-host deploy runs). */ +const BOX_LOG_COMMANDS = [ + 'cd deploy/selfhost', + 'docker compose logs -f --since 30m celld # Worker (API) logs, console.log and errors', + 'docker compose logs --since 30m caddy | grep http.log.access # redacted request log', +].join('\n'); + +/** + * Shown on Admin → Logs and Admin → Stream on an installation without Cloudflare log search or + * a tail worker (self-host). Errors SAM records itself still appear on Admin → Errors. + */ +export const BoxLogsNotice: FC<{ surface: 'search' | 'stream' }> = ({ surface }) => ( + +
+ + {surface === 'stream' + ? 'The live log stream is not available on this installation.' + : 'Log search is not available on this installation.'}{' '} + Request and runtime logs stay on the server. Read them there over SSH: + +
+        {BOX_LOG_COMMANDS}
+      
+ Errors that SAM records itself are listed on the Errors tab. +
+
+); diff --git a/apps/web/src/hooks/usePlatformCapabilities.ts b/apps/web/src/hooks/usePlatformCapabilities.ts index 20851c1aa5..530e49af01 100644 --- a/apps/web/src/hooks/usePlatformCapabilities.ts +++ b/apps/web/src/hooks/usePlatformCapabilities.ts @@ -17,6 +17,23 @@ export function usePlatformCapabilities(): PlatformCapabilities { return query.data ?? ASSUMED_PLATFORM_CAPABILITIES; } +/** + * The capabilities plus whether the answer has arrived. `known` is false only while the first + * request is outstanding; a failed query counts as known and keeps every service assumed present. + * For surfaces that would otherwise call a backend the installation may not have before the + * answer arrives (Admin → Logs and Admin → Stream). + */ +export function usePlatformCapabilitiesStatus(): { + capabilities: PlatformCapabilities; + known: boolean; +} { + const query = useQuery(platformCapabilitiesQueryOptions()); + return { + capabilities: query.data ?? ASSUMED_PLATFORM_CAPABILITIES, + known: query.data !== undefined || query.isError, + }; +} + /** * Whether agents can call Cloudflare-hosted models here. `known` stays false until the * capabilities answer arrives, so callers render as usual but hold the model catalog request diff --git a/apps/web/src/lib/analytics.ts b/apps/web/src/lib/analytics.ts index 770411eee7..fe3a454744 100644 --- a/apps/web/src/lib/analytics.ts +++ b/apps/web/src/lib/analytics.ts @@ -11,6 +11,8 @@ * setUserId(user.id) // after auth */ +import { normalizeAnalyticsPath, normalizeAnalyticsReferrer } from '@simple-agent-manager/shared'; + import { expectJsonRecord } from './runtime-validation'; interface AnalyticsEvent { @@ -55,15 +57,6 @@ const FLUSH_INTERVAL_MS = parseInt( const SESSION_ID_KEY = 'sam_analytics_session_id'; const VISITOR_ID_KEY = 'sam_analytics_visitor_id'; const UTM_KEY = 'sam_analytics_utm'; -const REDACTED_SEGMENT = '[redacted]'; -const EMAIL_RE = /^[^\s/@]+@[^\s/@]+\.[^\s/@]+$/i; -const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -const HEX_TOKEN_RE = /^[a-f0-9]{20,}$/i; -const SECRET_PREFIX_RE = /^(?:gh[pousr]_|github_pat_|sk-|xox[baprs]-|sam_[a-z0-9]+_|eyJ)/i; -const LONG_OPAQUE_SEGMENT_RE = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9_-]{24,}$/; -const SENSITIVE_ROUTE_MARKER_RE = /^(?:token|tokens|oauth|callback|auth|login|setup|invite|invites|reset|verify|verification|code|codes|secret|secrets|key|keys|repo|repos|repository|repositories|workspace|workspaces|project|projects|task|tasks|session|sessions|node|nodes|file|files)$/i; -const CODEBASE_FILE_SEGMENT_RE = /^[^/]+\.(?:git|ts|tsx|js|jsx|go|rs|py|java|rb|php|cs|cpp|c|h|hpp|swift|kt|md|mdx|json|ya?ml|toml|env|pem|key)$/i; // --- Module state --- let _apiUrl: string | null = null; @@ -79,94 +72,9 @@ let _utmMedium: string = ''; let _utmCampaign: string = ''; let _initialReferrer: string = ''; -// --------------------------------------------------------------------------- -// URL/path privacy normalization -// --------------------------------------------------------------------------- - -function stripTrailingSlashes(path: string): string { - if (path === '/') return path; - return path.replace(/\/+$/, '') || '/'; -} - -function safeDecodeURIComponent(value: string): string { - try { - return decodeURIComponent(value); - } catch { - return value; - } -} - -function isSensitiveSegment(segment: string, previousSegment?: string): boolean { - const decoded = safeDecodeURIComponent(segment); - return ( - EMAIL_RE.test(decoded) || - UUID_RE.test(decoded) || - ULID_RE.test(decoded) || - HEX_TOKEN_RE.test(decoded) || - SECRET_PREFIX_RE.test(decoded) || - LONG_OPAQUE_SEGMENT_RE.test(decoded) || - CODEBASE_FILE_SEGMENT_RE.test(decoded) || - (previousSegment !== undefined && SENSITIVE_ROUTE_MARKER_RE.test(previousSegment)) - ); -} - -function normalizePathname(pathname: string): string { - const normalized = pathname.startsWith('/') ? pathname : `/${pathname}`; - const segments = normalized.split('/').filter(Boolean); - if (segments.length === 0) return '/'; - - const safeSegments = segments.map((segment, index) => { - const previousSegment = index > 0 ? safeDecodeURIComponent(segments[index - 1] ?? '') : undefined; - if (isSensitiveSegment(segment, previousSegment)) return REDACTED_SEGMENT; - return encodeURIComponent(safeDecodeURIComponent(segment).slice(0, 80)); - }); - - return stripTrailingSlashes(`/${safeSegments.join('/')}`); -} - -function toUrl(value: string): URL | null { - try { - return new URL(value); - } catch { - try { - return new URL(value, 'https://analytics.local'); - } catch { - return null; - } - } -} - -/** - * Normalize analytics page values to a safe path-only contract. - * - * Contract: - * - Strip query strings, fragments, protocol, host, and userinfo. - * - Preserve non-sensitive nested path shape for aggregate reporting. - * - Redact emails, UUIDs/ULIDs, long opaque tokens, common secret prefixes, - * repository/code file identifiers, and values following sensitive route markers. - */ -export function normalizeAnalyticsPath(value: string | undefined): string { - if (!value) return ''; - const url = toUrl(value.trim()); - if (!url) return ''; - return normalizePathname(url.pathname); -} - -/** - * Normalize analytics referrers without sending full URLs. - * - * Referrers keep origin plus normalized path context. Search params, fragments, - * credentials, and sensitive path segments are removed. - */ -export function normalizeAnalyticsReferrer(value: string | undefined): string { - if (!value) return ''; - const url = toUrl(value.trim()); - if (!url || url.hostname === 'analytics.local') { - return normalizeAnalyticsPath(value); - } - const path = normalizePathname(url.pathname); - return path === '/' ? url.origin : `${url.origin}${path}`; -} +// URL/path privacy normalization lives in @simple-agent-manager/shared (analytics-path.ts), so the +// self-host D1 analytics sink applies the same rules server-side. +export { normalizeAnalyticsPath, normalizeAnalyticsReferrer }; // --------------------------------------------------------------------------- // Session & visitor ID management diff --git a/apps/web/src/lib/api/platform-capabilities.ts b/apps/web/src/lib/api/platform-capabilities.ts index ca9185625e..144ff66ca5 100644 --- a/apps/web/src/lib/api/platform-capabilities.ts +++ b/apps/web/src/lib/api/platform-capabilities.ts @@ -6,6 +6,10 @@ export interface PlatformCapabilities { speechToText: boolean; /** Server read-aloud on agent messages and task summaries. */ textToSpeech: boolean; + /** Admin → Logs search (Workers Observability). False where logs are read on the server. */ + logSearch: boolean; + /** Admin → Stream (tail worker). False where no tail worker feeds it. */ + liveLogStream: boolean; /** Whether agents can call Cloudflare-hosted models (needs Workers AI). */ agentModelCalls: boolean; } @@ -18,6 +22,8 @@ export interface PlatformCapabilities { export const ASSUMED_PLATFORM_CAPABILITIES: PlatformCapabilities = Object.freeze({ speechToText: true, textToSpeech: true, + logSearch: true, + liveLogStream: true, agentModelCalls: true, }); diff --git a/apps/web/src/pages/AdminLogs.tsx b/apps/web/src/pages/AdminLogs.tsx index 0a21a3339b..632bebd6ff 100644 --- a/apps/web/src/pages/AdminLogs.tsx +++ b/apps/web/src/pages/AdminLogs.tsx @@ -1,5 +1,11 @@ +import { BoxLogsNotice } from '../components/admin/BoxLogsNotice'; import { LogViewer } from '../components/admin/LogViewer'; +import { usePlatformCapabilitiesStatus } from '../hooks/usePlatformCapabilities'; export function AdminLogs() { - return ; + const { capabilities, known } = usePlatformCapabilitiesStatus(); + // Wait for the answer: LogViewer queries Workers Observability as soon as it mounts, and an + // installation without log search would refuse that query. + if (!known) return null; + return capabilities.logSearch ? : ; } diff --git a/apps/web/src/pages/AdminStream.tsx b/apps/web/src/pages/AdminStream.tsx index 5b555ee4bc..be15c845e7 100644 --- a/apps/web/src/pages/AdminStream.tsx +++ b/apps/web/src/pages/AdminStream.tsx @@ -1,5 +1,11 @@ +import { BoxLogsNotice } from '../components/admin/BoxLogsNotice'; import { LogStream } from '../components/admin/LogStream'; +import { usePlatformCapabilitiesStatus } from '../hooks/usePlatformCapabilities'; export function AdminStream() { - return ; + const { capabilities, known } = usePlatformCapabilitiesStatus(); + // Wait for the answer: LogStream opens a WebSocket as soon as it mounts, and nothing feeds the + // stream on an installation without a tail worker. + if (!known) return null; + return capabilities.liveLogStream ? : ; } diff --git a/apps/web/tests/playwright/admin-logs-notice-audit.spec.ts b/apps/web/tests/playwright/admin-logs-notice-audit.spec.ts new file mode 100644 index 0000000000..6b778f7eab --- /dev/null +++ b/apps/web/tests/playwright/admin-logs-notice-audit.spec.ts @@ -0,0 +1,173 @@ +/** + * Admin → Logs and Admin → Stream follow the installation's log capabilities (rule 17). + * + * `GET /api/config/platform-capabilities` reports `logSearch` (Workers Observability) and + * `liveLogStream` (a tail worker). A self-hosted box has neither, so each page shows where to + * read logs on the server instead of a search that errors or a stream that never receives + * anything. A Cloudflare installation reports both and keeps the real viewers (the control). + * + * The capabilities answer drives the real fetch -> query -> hook -> render path; no flag is + * hand-fed to a component (rule 62). Captured in both themes at the project's mobile and + * desktop viewports; `assertNoOverflow` also walks clipped overflow (rule 56), and the notice's + * long command lines must stay inside their own scroller. + */ +import { expect, type Page, type Route, test } from '@playwright/test'; + +import { + assertNoOverflow, + expectTheme, + makeMockUser, + screenshot, + seedTheme, +} from './audit-helpers'; + +const MOCK_USER = makeMockUser({ + email: 'admin@example.com', + name: 'Admin User', + role: 'superadmin', + sessionId: 'session-admin-1', + userId: 'user-admin-1', +}); + +const SELF_HOSTED = { + speechToText: false, + textToSpeech: false, + logSearch: false, + liveLogStream: false, + agentModelCalls: false, +}; +const CLOUDFLARE = { ...SELF_HOSTED, logSearch: true, liveLogStream: true }; + +async function setupMocks(page: Page, capabilities: Record) { + const logRequests: string[] = []; + const respond = (route: Route, status: number, body: unknown) => + route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) }); + + // The first-run onboarding wizard overlays every authenticated page for a user with no + // credentials and would cover the surface under test (rule 62); mark it dismissed first. + await page.addInitScript( + (id) => localStorage.setItem(`sam-onboarding-wizard-dismissed-${id}`, 'true'), + MOCK_USER.user.id + ); + await page.routeWebSocket('**/api/notifications/ws', () => undefined); + await page.routeWebSocket('**/api/admin/observability/logs/stream**', (ws) => { + logRequests.push('stream-ws'); + ws.send(JSON.stringify({ type: 'status', status: 'connected' })); + }); + await page.route('**/api/**', async (route: Route) => { + const path = new URL(route.request().url()).pathname; + if (path === '/api/config/platform-capabilities') return respond(route, 200, capabilities); + if (path.includes('/api/auth/')) return respond(route, 200, MOCK_USER); + if (path.startsWith('/api/notifications')) { + return respond(route, 200, { notifications: [], unreadCount: 0 }); + } + if (path.startsWith('/api/admin/observability/logs')) { + logRequests.push(path); + return respond(route, 200, { logs: [], cursor: null, hasMore: false }); + } + if (path === '/api/credentials' || path === '/api/github/installations') { + return respond(route, 200, []); + } + if (path.startsWith('/api/projects')) + return respond(route, 200, { projects: [], nextCursor: null }); + return respond(route, 200, {}); + }); + return { logRequests }; +} + +/** Whether `locator` is what a user would hit at its own center: nothing is drawn over it. */ +async function isTopmost(locator: ReturnType): Promise { + return locator.evaluate((el) => { + const box = el.getBoundingClientRect(); + const hit = document.elementFromPoint( + box.left + box.width / 2, + box.top + Math.min(box.height / 2, 40) + ); + return hit !== null && el.contains(hit); + }); +} + +const SURFACES = [ + { + slug: 'logs', + path: '/admin/logs', + heading: 'Log search is not available on this installation.', + viewerLabel: 'Worker script name', + }, + { + slug: 'stream', + path: '/admin/stream', + heading: 'The live log stream is not available on this installation.', + viewerLabel: 'Search stream', + }, +] as const; + +/** + * The project's own viewport (CI runs a mobile project) plus an explicit desktop layout, so both + * mobile and desktop evidence come from every run. + */ +const LAYOUTS = [ + { name: 'project viewport', slug: 'mobile', use: undefined }, + { + name: 'desktop 1280x800', + slug: 'desktop', + use: { viewport: { width: 1280, height: 800 }, isMobile: false, hasTouch: false }, + }, +] as const; + +for (const layout of LAYOUTS) { + for (const surface of SURFACES) { + test.describe(`Admin ${surface.slug} — self-hosted notice (${layout.name})`, () => { + if (layout.use) test.use(layout.use); + for (const theme of ['dark', 'light'] as const) { + test(`shows where to read logs (${theme})`, async ({ page }) => { + await seedTheme(page, theme); + const { logRequests } = await setupMocks(page, SELF_HOSTED); + await page.goto(surface.path); + + const notice = page.getByTestId('box-logs-notice'); + await expect(notice).toBeVisible(); + // Visible to a user, not just present: no overlay sits on top of it. + expect(await isTopmost(notice)).toBe(true); + await expect(notice).toContainText(surface.heading); + await expect(notice).toContainText('docker compose logs -f --since 30m celld'); + await expect(notice).toContainText('Errors that SAM records itself'); + await expectTheme(page, theme); + + // The command block scrolls inside itself; it must not widen the page. + const pre = notice.locator('pre'); + const [preBox, noticeBox] = await Promise.all([pre.boundingBox(), notice.boundingBox()]); + expect(preBox).not.toBeNull(); + expect(noticeBox).not.toBeNull(); + expect(preBox!.x + preBox!.width).toBeLessThanOrEqual( + noticeBox!.x + noticeBox!.width + 1 + ); + expect(await pre.evaluate((el) => getComputedStyle(el).overflowX)).toBe('auto'); + + // Nothing is asked of a log backend the box does not have. + expect(logRequests).toEqual([]); + + await screenshot(page, `admin-${surface.slug}-notice-${theme}-${layout.slug}`); + await assertNoOverflow(page); + }); + } + }); + + test.describe(`Admin ${surface.slug} — Cloudflare control (${layout.name})`, () => { + if (layout.use) test.use(layout.use); + test('keeps the real viewer when the installation has it', async ({ page }) => { + await seedTheme(page, 'dark'); + await setupMocks(page, CLOUDFLARE); + await page.goto(surface.path); + + // Liveness: the real viewer rendered, and the notice did not. + await expect(page.getByLabel(surface.viewerLabel)).toBeVisible(); + expect(await isTopmost(page.getByLabel(surface.viewerLabel))).toBe(true); + await expect(page.getByTestId('box-logs-notice')).toHaveCount(0); + + await screenshot(page, `admin-${surface.slug}-cloudflare-${layout.slug}`); + await assertNoOverflow(page); + }); + }); + } +} diff --git a/apps/web/tests/unit/pages/admin-box-logs-notice.test.tsx b/apps/web/tests/unit/pages/admin-box-logs-notice.test.tsx new file mode 100644 index 0000000000..4b966e0506 --- /dev/null +++ b/apps/web/tests/unit/pages/admin-box-logs-notice.test.tsx @@ -0,0 +1,115 @@ +/** + * Admin → Logs and Admin → Stream on a self-hosted install: the capabilities query (real, with + * fetch stubbed at the boundary) says log search and the live stream are off, so each page shows + * where logs are read instead of an error or a stream that waits forever. + */ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { render, screen, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { ASSUMED_PLATFORM_CAPABILITIES } from '../../../src/lib/api/platform-capabilities'; +import { AdminLogs } from '../../../src/pages/AdminLogs'; +import { AdminStream } from '../../../src/pages/AdminStream'; + +vi.mock('../../../src/components/admin/LogViewer', () => ({ + LogViewer: () =>
, +})); +vi.mock('../../../src/components/admin/LogStream', () => ({ + LogStream: () =>
, +})); + +function serveCapabilities(body: unknown) { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + if (String(input).endsWith('/api/config/platform-capabilities')) { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + throw new Error(`unexpected request ${String(input)}`); + }); + vi.stubGlobal('fetch', fetchMock); + return fetchMock; +} + +function withQuery(node: ReactNode) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return {node}; +} + +const SELF_HOST = { ...ASSUMED_PLATFORM_CAPABILITIES, logSearch: false, liveLogStream: false }; + +afterEach(() => vi.unstubAllGlobals()); + +describe('admin log pages on a self-hosted install', () => { + it('Logs shows the box log commands instead of the search viewer', async () => { + serveCapabilities(SELF_HOST); + render(withQuery()); + await waitFor(() => expect(screen.getByTestId('box-logs-notice')).toBeInTheDocument()); + expect(screen.queryByTestId('log-viewer')).toBeNull(); + expect(screen.getByText(/docker compose logs -f --since 30m celld/)).toBeInTheDocument(); + expect(screen.getByText(/Log search is not available/)).toBeInTheDocument(); + }); + + it('Stream shows the notice and never mounts the WebSocket stream', async () => { + serveCapabilities(SELF_HOST); + render(withQuery()); + await waitFor(() => expect(screen.getByTestId('box-logs-notice')).toBeInTheDocument()); + expect(screen.queryByTestId('log-stream')).toBeNull(); + expect(screen.getByText(/live log stream is not available/)).toBeInTheDocument(); + }); + + it('mounts neither the search viewer nor the stream until the capabilities answer arrives', async () => { + // Hold the answer open: a box must not get a log query or a WebSocket from the assumed + // "every service present" default while the request is outstanding. + let answer: (response: Response) => void = () => undefined; + vi.stubGlobal( + 'fetch', + vi.fn( + () => + new Promise((resolve) => { + answer = resolve; + }) + ) + ); + render( + withQuery( + <> + + + + ) + ); + await waitFor(() => expect(fetch).toHaveBeenCalled()); + expect(screen.queryByTestId('log-viewer')).toBeNull(); + expect(screen.queryByTestId('log-stream')).toBeNull(); + + answer( + new Response(JSON.stringify(SELF_HOST), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + ); + // Liveness: once answered, the box notice renders for both pages. + await waitFor(() => expect(screen.getAllByTestId('box-logs-notice')).toHaveLength(2)); + expect(screen.queryByTestId('log-viewer')).toBeNull(); + expect(screen.queryByTestId('log-stream')).toBeNull(); + }); + + it('Cloudflare installs keep the viewer and the stream', async () => { + const fetchMock = serveCapabilities(ASSUMED_PLATFORM_CAPABILITIES); + render( + withQuery( + <> + + + + ) + ); + await waitFor(() => expect(screen.getByTestId('log-viewer')).toBeInTheDocument()); + expect(fetchMock).toHaveBeenCalled(); + expect(screen.getByTestId('log-stream')).toBeInTheDocument(); + expect(screen.queryByTestId('box-logs-notice')).toBeNull(); + }); +}); diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index c8e35409fc..88241ec6dd 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -23,6 +23,12 @@ projection after the shared migrations, rejecting filename collisions. Cloudflar not receive the reverse-tunnel lease table. Existing boxes keep the additive table created by the earlier migration number. +Product analytics on the box use the same pattern. The self-host entry installs a D1 analytics +sink (`installAnalyticsD1Sink()` in `apps/api/src/selfhost/analytics/`), and the build appends +`apps/api/src/selfhost/observability-migrations.ts` to the **observability** database's flat +projection (`appendSelfhostObservabilityMigrations()` in `scripts/selfhost/`). Cloudflare +observability databases never receive the `analytics_events` table. + The transport setting admits new leases. Existing allocations adopt their original lease only while its exact stored owner remains live. Cleanup and the backstop follow the installed self-host driver, so changing the setting cannot strand an old lease. A build without that diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index 8d7f03c0d4..d638cfef13 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -1860,6 +1860,18 @@ them doesn't; the upload-link lifetime isn't checked in the browser. Set them in | `ATTACHMENT_MAX_FILES` | `20` | Max files per message | | `ATTACHMENT_PRESIGN_EXPIRY_SECONDS` | `900` (15 min) | Lifetime of each upload link | +Upload links (attachments, session snapshots, compose image artifacts and build contexts) are all +signed by one client, `getR2PresignTarget()` in `apps/api/src/services/r2-s3-client.ts`. On +Cloudflare it addresses `https://.r2.cloudflarestorage.com` with `R2_ACCESS_KEY_ID`, +`R2_SECRET_ACCESS_KEY` and `R2_BUCKET_NAME`. A runtime whose R2 binding keeps objects in its own S3 +store sets `R2_S3_ENDPOINT`, `R2_S3_BUCKET`, `R2_S3_KEY_PREFIX` and `R2_S3_REGION` (its SigV4 +signing region, for example `auto` for Google Cloud Storage or `us-west-2` for AWS S3; there is no +default, because a wrong region makes every signed URL fail), plus optional +`R2_S3_FORCE_PATH_STYLE` (default path style); links then target +`/` (`resolveR2PresignConfig()` in +`apps/api/src/services/r2-presign-config.ts`). A partially configured store disables presigning +rather than falling back to Cloudflare, and attachment requests then answer `403`. + ### Workspace uploads and downloads These apply to files uploaded straight into a workspace from its own page, and to files downloaded @@ -2049,6 +2061,25 @@ Client page/referrer fields follow a privacy normalization contract before enque | `MAX_ANALYTICS_INGEST_BODY_BYTES` | `65536` | Max ingest request body size in bytes | | `MAX_ANALYTICS_DURATION_MS` | `3600000` | Max accepted page-duration value; larger values are clamped | +Cloudflare installations write analytics to Workers Analytics Engine and read them through the +Analytics Engine SQL API (`queryAnalyticsEngine()` in `apps/api/src/routes/admin-analytics-query.ts`), +which needs `CF_ACCOUNT_ID` and `CF_API_TOKEN`. Without them the admin analytics routes answer +`404 FEATURE_UNAVAILABLE` (`analyticsQuery`) instead of a server error. A self-hosted build can +instead install a local sink (`installAnalyticsD1Sink()` in `apps/api/src/selfhost/analytics/`): +with `ANALYTICS_SINK="d1"` it records and reads the same events in the `analytics_events` table of +`OBSERVABILITY_DATABASE`. That table is created by a self-host-only migration +(`apps/api/src/selfhost/observability-migrations.ts`), never on Cloudflare, and its retention is +bounded by the self-host admin settings `analytics.d1.retentionDays` (default 90) and +`analytics.d1.maxRows` (default 500,000), applied by the 5-minute observability purge in batches +of `analytics.d1.purgeBatchRows` (default 5,000) for at most `analytics.d1.purgeTickBudgetMs` +(default 10,000) per run; unfinished deletes continue on the next run. The +Cloudflare Worker does not install the sink, so `ANALYTICS_SINK` has no effect there. + +Admin → Logs search reads Workers Observability with the same account API (`queryWorkerLogs()`), +and Admin → Stream is fed by the tail worker. A deployment without a tail worker declares +`LOG_TAIL_AVAILABLE="false"`; both pages then show where to read logs on the server instead +(`publicPlatformCapabilities()` reports `logSearch` and `liveLogStream`). + ## Analytics Forwarding External analytics forwarding is off by default. When enabled, SAM forwards only analytics rows already accepted by first-party ingestion/middleware; it does not bypass the client-side URL normalization contract. diff --git a/packages/app-deployment/src/build-context-upload.ts b/packages/app-deployment/src/build-context-upload.ts index 94c0e8b47c..6431a4e185 100644 --- a/packages/app-deployment/src/build-context-upload.ts +++ b/packages/app-deployment/src/build-context-upload.ts @@ -3,23 +3,25 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import type { BuildContextDescriptor, BuildContextOwner } from './build-context-state'; import { buildContextKey } from './build-context-state'; -import { getS3Client } from './compose-image-artifacts'; +import type { ComposeImageArtifactPresignTarget as PresignTarget } from './compose-image-artifacts'; import type { AppDeploymentEnv as Env } from './env'; /** Only job-derived keys are signed. Metadata binds the uploaded object to the - * digest declared before upload; builders must still hash bytes after download. */ + * digest declared before upload; builders must still hash bytes after download. + * The URL is signed through the worker's shared R2 S3 client (`target`, bound with the + * `WHEN_REQUIRED` checksum mode), as compose artifacts are, so an operator store works too. */ export async function createBuildContextUpload( - env: Env, owner: BuildContextOwner, descriptor: BuildContextDescriptor, - expiresIn: number + expiresIn: number, + target: PresignTarget ) { const r2Key = buildContextKey(owner); const uploadUrl = await getSignedUrl( - getS3Client(env, 'WHEN_REQUIRED'), + target.client, new PutObjectCommand({ - Bucket: env.R2_BUCKET_NAME, - Key: r2Key, + Bucket: target.bucket, + Key: target.objectKey(r2Key), ContentLength: descriptor.sizeBytes, ContentType: 'application/zstd', Metadata: { sha256: descriptor.sha256 }, @@ -43,10 +45,14 @@ export async function verifyBuildContextObject( ); } -export async function createBuildContextDownload(env: Env, r2Key: string, expiresIn: number) { +export async function createBuildContextDownload( + r2Key: string, + expiresIn: number, + target: PresignTarget +) { return getSignedUrl( - getS3Client(env, 'WHEN_REQUIRED'), - new GetObjectCommand({ Bucket: env.R2_BUCKET_NAME, Key: r2Key }), + target.client, + new GetObjectCommand({ Bucket: target.bucket, Key: target.objectKey(r2Key) }), { expiresIn } ); } diff --git a/packages/app-deployment/src/compose-image-artifacts.ts b/packages/app-deployment/src/compose-image-artifacts.ts index 20ca15cc4c..bec32f0e47 100644 --- a/packages/app-deployment/src/compose-image-artifacts.ts +++ b/packages/app-deployment/src/compose-image-artifacts.ts @@ -1,18 +1,29 @@ -import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import type { S3Client } from '@aws-sdk/client-s3'; +import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import { parsePositiveInt } from '@simple-agent-manager/worker-core'; import type { AppDeploymentEnv } from './env'; +/** + * Where compose artifact URLs are signed: the worker's shared R2 S3 client + * (`apps/api/src/services/r2-s3-client.ts`, `getR2PresignTarget(env, 'SDK_DEFAULT')`), passed in + * by the worker so this package does not resolve storage credentials itself. + */ +export interface ComposeImageArtifactPresignTarget { + client: S3Client; + /** S3 bucket the URL addresses. */ + bucket: string; + /** S3 object key for an R2 key (prefix applied for operator stores). */ + objectKey(r2Key: string): string; +} + const DEFAULT_UPLOAD_EXPIRY_SECONDS = 900; const DEFAULT_DOWNLOAD_EXPIRY_SECONDS = 900; export const DEFAULT_COMPOSE_IMAGE_ARTIFACT_MAX_BYTES = 2 * 1024 * 1024 * 1024; export const COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE = 'docker-save'; export const COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE = 'application/vnd.docker.image.rootfs.diff.tar'; -let s3Client: S3Client | null = null; -let s3ClientKey = ''; - export interface ComposeImageArtifactRequest { serviceName: string; sourceRef: string; @@ -77,31 +88,6 @@ function getDownloadExpiry(env: AppDeploymentEnv): number { ); } -export function getS3Client( - env: AppDeploymentEnv, - requestChecksumCalculation: 'WHEN_REQUIRED' | 'WHEN_SUPPORTED' = 'WHEN_SUPPORTED' -): S3Client { - if (!env.R2_ACCESS_KEY_ID || !env.R2_SECRET_ACCESS_KEY || !env.CF_ACCOUNT_ID) { - throw new Error( - 'R2 S3 credentials not configured (R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, CF_ACCOUNT_ID required)' - ); - } - const key = `${env.CF_ACCOUNT_ID}:${env.R2_ACCESS_KEY_ID}:${requestChecksumCalculation}`; - if (!s3Client || s3ClientKey !== key) { - s3Client = new S3Client({ - region: 'auto', - requestChecksumCalculation, - endpoint: `https://${env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com`, - credentials: { - accessKeyId: env.R2_ACCESS_KEY_ID, - secretAccessKey: env.R2_SECRET_ACCESS_KEY, - }, - }); - s3ClientKey = key; - } - return s3Client; -} - export function buildComposeImageArtifactKey( projectId: string, workspaceId: string, @@ -205,13 +191,9 @@ export async function createComposeImageArtifactUploads( environmentId: string; uploadId: string; services: ComposeImageArtifactRequest[]; - } + }, + target: ComposeImageArtifactPresignTarget ): Promise { - const bucket = env.R2_BUCKET_NAME; - if (!bucket) { - throw new Error('R2_BUCKET_NAME not configured'); - } - const s3 = getS3Client(env); const expiresIn = getUploadExpiry(env); const maxBytes = getComposeImageArtifactMaxBytes(env); @@ -230,8 +212,8 @@ export async function createComposeImageArtifactUploads( serviceName ); const command = new PutObjectCommand({ - Bucket: bucket, - Key: r2Key, + Bucket: target.bucket, + Key: target.objectKey(r2Key), ContentType: COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, }); return { @@ -239,7 +221,7 @@ export async function createComposeImageArtifactUploads( sourceRef, localImageRef: cleanString(service.localImageRef) || sourceRef, r2Key, - uploadUrl: await getSignedUrl(s3, command, { expiresIn }), + uploadUrl: await getSignedUrl(target.client, command, { expiresIn }), expiresIn, maxBytes, archiveType: COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, @@ -271,21 +253,17 @@ export async function validateCompletedComposeImageArtifacts( export async function createComposeImageArtifactDownloads( env: AppDeploymentEnv, - artifacts: ComposeImageArtifactDescriptor[] + artifacts: ComposeImageArtifactDescriptor[], + target: ComposeImageArtifactPresignTarget ): Promise { - const bucket = env.R2_BUCKET_NAME; - if (!bucket) { - throw new Error('R2_BUCKET_NAME not configured'); - } - const s3 = getS3Client(env); const downloadExpiresIn = getDownloadExpiry(env); return Promise.all( artifacts.map(async (artifact) => ({ ...artifact, downloadUrl: await getSignedUrl( - s3, - new GetObjectCommand({ Bucket: bucket, Key: artifact.r2Key }), + target.client, + new GetObjectCommand({ Bucket: target.bucket, Key: target.objectKey(artifact.r2Key) }), { expiresIn: downloadExpiresIn } ), downloadExpiresIn, diff --git a/packages/app-deployment/src/index.ts b/packages/app-deployment/src/index.ts index 27fb3eb3ba..d97ea1e68b 100644 --- a/packages/app-deployment/src/index.ts +++ b/packages/app-deployment/src/index.ts @@ -30,10 +30,14 @@ export type { ComposeImageArtifactDescriptor, ComposeImageArtifactDownload, ComposeImageArtifactPlatform, + ComposeImageArtifactPresignTarget, ComposeImageArtifactRequest, ComposeImageArtifactUpload, } from './compose-image-artifacts'; export { + buildComposeImageArtifactKey, + COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, + COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, getComposeImageArtifactMaxBytes, diff --git a/packages/app-deployment/tests/unit/build-context-presign.test.ts b/packages/app-deployment/tests/unit/build-context-presign.test.ts index 0dcadc7905..8d562ba080 100644 --- a/packages/app-deployment/tests/unit/build-context-presign.test.ts +++ b/packages/app-deployment/tests/unit/build-context-presign.test.ts @@ -1,18 +1,25 @@ import { createHash, createHmac } from 'node:crypto'; import { createServer, type IncomingHttpHeaders, request } from 'node:http'; +import { S3Client } from '@aws-sdk/client-s3'; import { describe, expect, it } from 'vitest'; import { createBuildContextUpload } from '../../src/build-context-upload'; -import type { AppDeploymentEnv as Env } from '../../src/env'; +import type { ComposeImageArtifactPresignTarget } from '../../src/compose-image-artifacts'; const secret = 'fake-secret'; -const env = { - CF_ACCOUNT_ID: 'fake-account', - R2_ACCESS_KEY_ID: 'fake-access', - R2_SECRET_ACCESS_KEY: secret, - R2_BUCKET_NAME: 'fake-bucket', -} as Env; +// The worker's shared R2 client (apps/api/src/services/r2-s3-client.ts) as it is configured on +// Cloudflare for build contexts: WHEN_REQUIRED checksums, the account endpoint, unprefixed keys. +const target: ComposeImageArtifactPresignTarget = { + client: new S3Client({ + region: 'auto', + endpoint: 'https://fake-account.r2.cloudflarestorage.com', + requestChecksumCalculation: 'WHEN_REQUIRED', + credentials: { accessKeyId: 'fake-access', secretAccessKey: secret }, + }), + bucket: 'fake-bucket', + objectKey: (key) => key, +}; // Independent SigV4 verification, deliberately not the SDK signer under test. // Only dummy credentials are used, and the HTTP destination is localhost. @@ -71,7 +78,6 @@ describe('real SDK context presigner', () => { const body = Buffer.from('nonempty compressed-context stand-in'); const sha256 = createHash('sha256').update(body).digest('hex'); const slot = await createBuildContextUpload( - env, { id: 'job', projectId: 'project', @@ -81,7 +87,8 @@ describe('real SDK context presigner', () => { attempt: 3, }, { sizeBytes: body.length, sha256 }, - 300 + 300, + target ); const url = new URL(slot.uploadUrl); expect(url.pathname).toContain('/compose-build-contexts/project/env/job/3.tar.zst'); diff --git a/packages/shared/src/analytics-path.ts b/packages/shared/src/analytics-path.ts new file mode 100644 index 0000000000..52b569f24f --- /dev/null +++ b/packages/shared/src/analytics-path.ts @@ -0,0 +1,110 @@ +/** + * Privacy normalization for analytics page and referrer values, shared by the web tracker + * (apps/web/src/lib/analytics.ts) and the self-host D1 analytics sink + * (apps/api/src/selfhost/analytics/d1-sink.ts), so both apply one definition of "sensitive". + * + * Contract: strip query strings, fragments, protocol, host and userinfo; keep non-sensitive + * nested path shape; redact emails, UUIDs/ULIDs, long opaque tokens, common secret prefixes, + * repository/code file identifiers, and values following sensitive route markers. + */ +const REDACTED_SEGMENT = '[redacted]'; +const EMAIL_RE = /^[^\s/@]+@[^\s/@]+\.[^\s/@]+$/i; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +const HEX_TOKEN_RE = /^[a-f0-9]{20,}$/i; +const SECRET_PREFIX_RE = /^(?:gh[pousr]_|github_pat_|sk-|xox[baprs]-|sam_[a-z0-9]+_|eyJ)/i; +const LONG_OPAQUE_SEGMENT_RE = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9_-]{24,}$/; +const SENSITIVE_ROUTE_MARKER_RE = + /^(?:token|tokens|oauth|callback|auth|login|setup|invite|invites|reset|verify|verification|code|codes|secret|secrets|key|keys|repo|repos|repository|repositories|workspace|workspaces|project|projects|task|tasks|session|sessions|node|nodes|file|files)$/i; +const CODEBASE_FILE_SEGMENT_RE = + /^[^/]+\.(?:git|ts|tsx|js|jsx|go|rs|py|java|rb|php|cs|cpp|c|h|hpp|swift|kt|md|mdx|json|ya?ml|toml|env|pem|key)$/i; + +function stripTrailingSlashes(path: string): string { + if (path === '/') return path; + return path.replace(/\/+$/, '') || '/'; +} + +function safeDecodeURIComponent(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +/** Whether one path segment must not be stored, given the segment before it. */ +export function isSensitiveAnalyticsPathSegment( + segment: string, + previousSegment?: string +): boolean { + const decoded = safeDecodeURIComponent(segment); + return ( + EMAIL_RE.test(decoded) || + UUID_RE.test(decoded) || + ULID_RE.test(decoded) || + HEX_TOKEN_RE.test(decoded) || + SECRET_PREFIX_RE.test(decoded) || + LONG_OPAQUE_SEGMENT_RE.test(decoded) || + CODEBASE_FILE_SEGMENT_RE.test(decoded) || + (previousSegment !== undefined && SENSITIVE_ROUTE_MARKER_RE.test(previousSegment)) + ); +} + +function normalizePathname(pathname: string): string { + const normalized = pathname.startsWith('/') ? pathname : `/${pathname}`; + const segments = normalized.split('/').filter(Boolean); + if (segments.length === 0) return '/'; + + const safeSegments = segments.map((segment, index) => { + const previousSegment = + index > 0 ? safeDecodeURIComponent(segments[index - 1] ?? '') : undefined; + if (isSensitiveAnalyticsPathSegment(segment, previousSegment)) return REDACTED_SEGMENT; + return encodeURIComponent(safeDecodeURIComponent(segment).slice(0, 80)); + }); + + return stripTrailingSlashes(`/${safeSegments.join('/')}`); +} + +function toUrl(value: string): URL | null { + try { + return new URL(value); + } catch { + try { + return new URL(value, 'https://analytics.local'); + } catch { + return null; + } + } +} + +/** + * Normalize analytics page values to a safe path-only contract. + * + * Contract: + * - Strip query strings, fragments, protocol, host, and userinfo. + * - Preserve non-sensitive nested path shape for aggregate reporting. + * - Redact emails, UUIDs/ULIDs, long opaque tokens, common secret prefixes, + * repository/code file identifiers, and values following sensitive route markers. + */ +export function normalizeAnalyticsPath(value: string | undefined): string { + if (!value) return ''; + const url = toUrl(value.trim()); + if (!url) return ''; + return normalizePathname(url.pathname); +} + +/** + * Normalize analytics referrers without sending full URLs. + * + * Referrers keep origin plus normalized path context. Search params, fragments, + * credentials, and sensitive path segments are removed. + */ +export function normalizeAnalyticsReferrer(value: string | undefined): string { + if (!value) return ''; + const url = toUrl(value.trim()); + if (!url || url.hostname === 'analytics.local') { + return normalizeAnalyticsPath(value); + } + const path = normalizePathname(url.pathname); + return path === '/' ? url.origin : `${url.origin}${path}`; +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index b6698cf9cb..49d5e650cd 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -72,6 +72,11 @@ export * from './runtime-validation'; export * from './resource-requirements'; // Chat message pagination cursors (web client ↔ API contract) +export { + isSensitiveAnalyticsPathSegment, + normalizeAnalyticsPath, + normalizeAnalyticsReferrer, +} from './analytics-path'; export { MERGED_MESSAGE_ROLES } from './chat-message-merge'; export { DEFAULT_GITHUB_TRIGGER_QUEUE_MAX_PENDING, diff --git a/scripts/quality/check-migration-safety.ts b/scripts/quality/check-migration-safety.ts index 7ac1436d7c..04eec21cb6 100644 --- a/scripts/quality/check-migration-safety.ts +++ b/scripts/quality/check-migration-safety.ts @@ -8,21 +8,32 @@ * pre-apply guard. */ -import { readFileSync, readdirSync } from 'node:fs'; +import { readdirSync,readFileSync } from 'node:fs'; import { basename, join, resolve } from 'node:path'; import { isIdentifier, isKeyword, logicalSqlStatements, + splitSqlStatements, type SqlStatement, type SqlToken, - splitSqlStatements, tokenizeSql, } from './sql-migration-parser'; const MIGRATIONS_DIR = resolve(import.meta.dirname, '../../apps/api/src/db/migrations'); -const DEFAULT_MIGRATION_DIRS = [MIGRATIONS_DIR, join(MIGRATIONS_DIR, 'observability')]; +// Self-host-only migrations (apps/api/src/selfhost/migrations/) are projected into the same +// databases on a self-hosted box, so they get the same data-loss checks. +const SELFHOST_MIGRATIONS_DIR = resolve( + import.meta.dirname, + '../../apps/api/src/selfhost/migrations' +); +const DEFAULT_MIGRATION_DIRS = [ + MIGRATIONS_DIR, + join(MIGRATIONS_DIR, 'observability'), + SELFHOST_MIGRATIONS_DIR, + join(SELFHOST_MIGRATIONS_DIR, 'observability'), +]; /** Historical violations that ran before the guard existed. Never add new entries. */ const ALLOWLISTED_VIOLATIONS = new Set([ diff --git a/scripts/quality/gitleaks-reviewed-baseline.json b/scripts/quality/gitleaks-reviewed-baseline.json index 714af52063..0c71302bf3 100644 --- a/scripts/quality/gitleaks-reviewed-baseline.json +++ b/scripts/quality/gitleaks-reviewed-baseline.json @@ -5,12 +5,13 @@ "groups": [ { "classification": "code-identifier", - "reason": "Fresh pinned current-tree review: analytics-forward.ts reads an environment-variable identifier; github-app-tokens.ts findings span PEM delimiter comments and parser/encoder code, with no embedded key body. Exact current rule/path/line/bytes only.", + "reason": "Fresh pinned current-tree review: analytics-forward.ts reads an environment-variable identifier (same bytes at line 339, and at line 343 after PR #2889 added four lines above it); github-app-tokens.ts findings span PEM delimiter comments and parser/encoder code, with no embedded key body. Exact current rule/path/line/bytes only.", "owner": "security", "reviewedAt": "2026-11-06T12:30:14.413Z", "expiresAt": "2026-12-06T12:30:14.413Z", "digests": [ "43311ab05444a3deed84ddf803f7d4a523e4ab4a97d044200e84fedc73661f5f", + "ecc456aef877ed66b358ddeca553c9a7ae1f9cf5aa429fb514335a9b0942de31", "81f3369b6025e96d9c0e14739af278a7174b8ea9387c1e8a307e7ee1b50ad36e", "b0eb549c5588a1c5a61aec95eca31cc8d4008a6f86f9f78845482246d19a19fb", "b1dcd2817cc876421ba0377a672cd178370f310251e33ea7936f5e25436359c6" diff --git a/scripts/quality/runtime-tunables-baseline.json b/scripts/quality/runtime-tunables-baseline.json index b5cc6fdde5..9e1c81cc58 100644 --- a/scripts/quality/runtime-tunables-baseline.json +++ b/scripts/quality/runtime-tunables-baseline.json @@ -1328,6 +1328,13 @@ "VM_AGENT_TUNNEL_PORT": "Written into immutable per-node cloud-init, the loopback agent listener and remote tunnel ingress together. A live update would split that bootstrap contract and disconnect existing nodes; applies only to newly provisioned VMs.", "VM_AGENT_TUNNEL_PROBE_INTERVAL_SECONDS": "Rendered into the connector health-probe script in VM cloud-init. Existing VMs retain their provisioned script; changing the Worker only affects subsequent VM bootstrap.", "VM_AGENT_TUNNEL_PROBE_TIMEOUT_SECONDS": "Rendered into the connector health-probe script in VM cloud-init. Existing VMs retain their provisioned script; changing the Worker only affects subsequent VM bootstrap.", - "VM_AGENT_TUNNEL_RESTART_SECONDS": "Rendered into the connector systemd unit at VM bootstrap. Changing this Worker variable cannot update installed units; it applies only to subsequently provisioned VMs." + "VM_AGENT_TUNNEL_RESTART_SECONDS": "Rendered into the connector systemd unit at VM bootstrap. Changing this Worker variable cannot update installed units; it applies only to subsequently provisioned VMs.", + "ANALYTICS_SINK": "Deployment shape, not a tunable: selects where product analytics are stored and read (Analytics Engine on Cloudflare, the observability D1 database on a self-hosted box whose entry installed the D1 sink, selfhost/analytics/). Set by the self-host config generator together with the self-host observability migration; switching it at runtime would split analytics across two stores. The D1 sink's retention bounds are admin settings installed by the self-host entry (analytics.d1.retentionDays, analytics.d1.maxRows).", + "LOG_TAIL_AVAILABLE": "Platform capability, not a tunable: declares that the runtime has no tail consumer feeding the AdminLogs Durable Object (a self-hosted box). Set by the self-host config generator; an admin cannot make a log stream exist by editing it (services/platform-capabilities.ts hasLiveLogStream).", + "R2_S3_BUCKET": "Names the S3 store that physically holds the R2 binding's objects on a non-Cloudflare runtime (for example a self-hosted box's object store). It is resource-binding identity written by the deployment config generator together with the R2 binding, like R2_BUCKET_NAME; an admin edit would point presigned URLs at a store the binding does not read, so uploads would land where SAM cannot see them (services/r2-presign-config.ts).", + "R2_S3_ENDPOINT": "Names the S3 store that physically holds the R2 binding's objects on a non-Cloudflare runtime (for example a self-hosted box's object store). It is resource-binding identity written by the deployment config generator together with the R2 binding, like R2_BUCKET_NAME; an admin edit would point presigned URLs at a store the binding does not read, so uploads would land where SAM cannot see them (services/r2-presign-config.ts).", + "R2_S3_KEY_PREFIX": "Names the S3 store that physically holds the R2 binding's objects on a non-Cloudflare runtime (for example a self-hosted box's object store). It is resource-binding identity written by the deployment config generator together with the R2 binding, like R2_BUCKET_NAME; an admin edit would point presigned URLs at a store the binding does not read, so uploads would land where SAM cannot see them (services/r2-presign-config.ts).", + "R2_S3_FORCE_PATH_STYLE": "SigV4 region (required with R2_S3_ENDPOINT) and addressing style of the store named by R2_S3_ENDPOINT. They describe that bootstrap store and must change together with it; an admin edit alone would make every presigned URL fail to authenticate against it (services/r2-presign-config.ts).", + "R2_S3_REGION": "SigV4 region (required with R2_S3_ENDPOINT) and addressing style of the store named by R2_S3_ENDPOINT. They describe that bootstrap store and must change together with it; an admin edit alone would make every presigned URL fail to authenticate against it (services/r2-presign-config.ts)." } } diff --git a/scripts/selfhost/observability-migrations.ts b/scripts/selfhost/observability-migrations.ts new file mode 100644 index 0000000000..6ddbab967f --- /dev/null +++ b/scripts/selfhost/observability-migrations.ts @@ -0,0 +1,11 @@ +/** Build-time projection; celld accepts one flat migration directory per database. */ +import { SELFHOST_OBSERVABILITY_MIGRATIONS } from '../../apps/api/src/selfhost/observability-migrations.js'; +import { appendSelfhostMigrations } from './selfhost-migrations.js'; + +/** Called after celld-project creates OBSERVABILITY_DATABASE's shared migration links. */ +export function appendSelfhostObservabilityMigrations( + apiDir: string, + observabilityMigrationDir: string +): void { + appendSelfhostMigrations(apiDir, observabilityMigrationDir, SELFHOST_OBSERVABILITY_MIGRATIONS); +} diff --git a/scripts/selfhost/reverse-tunnel-migrations.ts b/scripts/selfhost/reverse-tunnel-migrations.ts index 94c823ec6b..a2c68334ec 100644 --- a/scripts/selfhost/reverse-tunnel-migrations.ts +++ b/scripts/selfhost/reverse-tunnel-migrations.ts @@ -1,19 +1,8 @@ /** Build-time projection; celld accepts one flat migration directory per database. */ -import { existsSync, lstatSync, readlinkSync, symlinkSync } from 'node:fs'; -import { basename, join, resolve } from 'node:path'; - import { REVERSE_TUNNEL_MIGRATIONS } from '../../apps/api/src/selfhost/reverse-tunnel-migrations.js'; +import { appendSelfhostMigrations } from './selfhost-migrations.js'; /** Called after celld-project creates DATABASE's shared migration links. */ export function appendReverseTunnelMigrations(apiDir: string, databaseMigrationDir: string): void { - for (const migration of REVERSE_TUNNEL_MIGRATIONS) { - const source = resolve(apiDir, 'src', migration); - const target = join(databaseMigrationDir, basename(migration)); - if (existsSync(target) || (() => { try { return lstatSync(target).isSymbolicLink(); } catch { return false; } })()) { - if (lstatSync(target).isSymbolicLink() && readlinkSync(target) === source) continue; - throw new Error(`Self-host migration filename collision: ${basename(migration)}`); - } - if (!existsSync(source)) throw new Error(`Missing self-host migration: ${basename(migration)}`); - symlinkSync(source, target); - } + appendSelfhostMigrations(apiDir, databaseMigrationDir, REVERSE_TUNNEL_MIGRATIONS); } diff --git a/scripts/selfhost/selfhost-migrations.ts b/scripts/selfhost/selfhost-migrations.ts new file mode 100644 index 0000000000..739e6e03c8 --- /dev/null +++ b/scripts/selfhost/selfhost-migrations.ts @@ -0,0 +1,33 @@ +/** Build-time projection; celld accepts one flat migration directory per database. */ +import { existsSync, lstatSync, readlinkSync, symlinkSync } from 'node:fs'; +import { basename, join, resolve } from 'node:path'; + +function isSymlink(path: string): boolean { + try { + return lstatSync(path).isSymbolicLink(); + } catch { + return false; + } +} + +/** + * Links self-host-only migrations (paths relative to apps/api/src) into a database's flat + * migration directory AFTER its shared migrations. Re-running is a no-op; any other file with + * the same name is a collision and fails the build. + */ +export function appendSelfhostMigrations( + apiDir: string, + migrationDir: string, + migrations: readonly string[] +): void { + for (const migration of migrations) { + const source = resolve(apiDir, 'src', migration); + const target = join(migrationDir, basename(migration)); + if (existsSync(target) || isSymlink(target)) { + if (isSymlink(target) && readlinkSync(target) === source) continue; + throw new Error(`Self-host migration filename collision: ${basename(migration)}`); + } + if (!existsSync(source)) throw new Error(`Missing self-host migration: ${basename(migration)}`); + symlinkSync(source, target); + } +} diff --git a/tasks/active/2026-11-18-selfhost-l20-observability-storage-seams.md b/tasks/active/2026-11-18-selfhost-l20-observability-storage-seams.md new file mode 100644 index 0000000000..5080d538c9 --- /dev/null +++ b/tasks/active/2026-11-18-selfhost-l20-observability-storage-seams.md @@ -0,0 +1,104 @@ +# Self-host landing slice L20: observability and storage seams + +## Problem + +The integration branch `sam/selfhost-pass-2` (tip 942d2c0a4) carries the observability and +storage seams a self-hosted (celld) box needs: a D1 product-analytics sink, a shared R2 S3 +presign client that can target an operator S3 store, admin log notices for installs without +Workers Observability or a tail worker, and serving the web UI from an `ASSETS` binding. L20 +lands them on `main` without changing any Cloudflare behaviour. Plan row: idea +01M72M9AEB933ZY8269D376DKC, LANDING PLAN part 6. Coordinator task 01M7JMXS2JRW6QQMB1356ENPM3. + +## Findings to resolve (from M4 #2884 "Raised to the coordinator") + +1. The analytics D1 sink migration sat in the shared observability migrations directory, so it + would run on every Cloudflare install. Resolution: move it to + `apps/api/src/selfhost/migrations/observability/0002_analytics_events.sql` (same filename, so + the BOX's ledger entry still matches) with a projection list like L17a's + `REVERSE_TUNNEL_MIGRATIONS`. Cloudflare's `migrations_dir` never sees it. +2. HIGH-5: capability inputs not in the 2026-11-16 production capture. Checked production + `sam-api-prod` script settings on 2026-11-18 (names/types only): `ANALYTICS` + (analytics_engine, dataset sam_analytics), `ANALYTICS_DATASET`, `CF_ACCOUNT_ID` and + `CF_API_TOKEN` (secrets), `R2` (r2_bucket), `R2_ACCESS_KEY_ID` and `R2_SECRET_ACCESS_KEY` + (secrets), `R2_BUCKET_NAME` plain text; no `ANALYTICS_SINK`, no `LOG_TAIL_AVAILABLE`, no + `R2_S3_*`, no `ASSETS`; tail consumer `sam-tail-worker-prod` attached. So analyticsQuery, + logSearch, liveLogStream and R2 presign all resolve true / to Cloudflare R2 on production. + Pinned in tests with that exact shape. +3. Self-host-only runtime tunables (D1 sink retention days and row cap) go through + `installAdminSettingDefinitions` from the self-host install point, not the base registry. + +## Research Findings + +- Branch sink: `services/analytics-d1-sink.ts` read `ANALYTICS_SINK="d1"`; consumers + `middleware/analytics.ts`, `routes/analytics-ingest.ts`, `routes/admin-analytics-query.ts`, + `routes/admin-analytics.ts`, `scheduled/observability-purge.ts`, `lib/analytics-config.ts`. + Retention settings were in the base operations-telemetry group (finding 3). +- L14 precedent: `services/speech-backend.ts` is a shared extension seam; `selfhost/speech/` + installs a backend and settings. The Cloudflare entry never imports `selfhost/`. +- Branch R2: `services/r2-presign-config.ts` + `services/r2-s3-client.ts` + (`getR2PresignTarget`) replace main's two S3 clients (`r2-s3-client.ts` and + app-deployment's `getS3Client`). Compose artifacts keep the SDK default checksum mode + (main: explicit WHEN_SUPPORTED, which is the SDK default). +- Branch's `isAcceptableOperatorEndpoint` lives in a worker-core module main lacks; inline the + same rule with main's `classifyHost`. +- Admin log notices: `BoxLogsNotice`, `AdminLogs`/`AdminStream` gate on public capabilities + `logSearch`/`liveLogStream`; API refuses `/logs/stream` without a tail and log search without a + Cloudflare account API (FEATURE_UNAVAILABLE). +- ASSETS: `lib/pages-proxy.ts` `assets` target, `index.ts` serves `app.*` from `ASSETS` when bound. +- Excluded (other slices): `compact-r2.ts` shared-flight joins, `conditional-r2` helper (key + rotation), `app.ts` split, other capabilities (artifacts, email, sandbox, app deployments). +- Runtime-tunables gate needs bootstrap exceptions for `ANALYTICS_SINK`, `LOG_TAIL_AVAILABLE`, + `R2_S3_*`. + +## Implementation Checklist + +- [x] Shared seam `services/analytics-sink.ts` (AE default, installable local sink) +- [x] `selfhost/analytics/` D1 sink, SQL translation, purge, settings, install point +- [x] Move migration to `selfhost/migrations/observability/` + projection list +- [x] Wire middleware, ingest, admin query/gate, purge, forward skip reason, dataset name +- [x] Capabilities: analyticsQuery, workersObservability (logSearch), liveLogStream; public logSearch/liveLogStream +- [x] Log stream and log search refusals (FEATURE_UNAVAILABLE) +- [x] R2 presign config + shared client; attachments, snapshots, compose, build context, upload route +- [x] app-deployment package takes a presign target +- [x] ASSETS serving for app.* when bound +- [x] Web: BoxLogsNotice on Admin → Logs / Stream +- [x] Env declarations + runtime-tunables bootstrap exceptions +- [x] Docs: configuration reference / env example +- [x] Tests pinning Cloudflare branches (production capture) + self-host branches + +## Acceptance Criteria + +- [x] Cloudflare: analytics writes go to Analytics Engine, admin analytics queries the SQL API, + presigned URLs are `https://.r2.cloudflarestorage.com//`, app.* still + proxies to Pages, log search and stream unchanged. Pinned by tests using the production shape. +- [x] The analytics_events migration is not in any Cloudflare `migrations_dir`. +- [x] Self-host settings are installed only by the self-host install point. +- [ ] STG: admin analytics, attachment upload and session snapshot all work unchanged on Cloudflare. + +## Notes + +- PR #2889. Main is branch-protected, so this task file rides in the PR instead of a direct commit. +- Reviews: cloudflare-specialist, performance-reviewer and task-completion-validator found no + CRITICAL/HIGH. Fixed: row-cap purge uses `MAX(id)` instead of an OFFSET scan; purge deletes run + in batches under a per-tick time budget (`analytics.d1.purgeBatchRows`, + `analytics.d1.purgeTickBudgetMs`, self-host settings); error and analytics purges isolated both + ways; `ASSETS` presence check consistent; `quality:migration-safety` now also scans + `apps/api/src/selfhost/migrations/**`; `appendSelfhostObservabilityMigrations()` added + (`scripts/selfhost/`), sharing one projection helper with the reverse-tunnel list; route tests for + the live-stream refusal; registry and projection tests. +- Deferred MEDIUM: machine traffic in the self-host sink -> + `tasks/backlog/2026-11-18-selfhost-analytics-sink-machine-traffic.md`. +- Integration-branch follow-up for the next M-merge: delete + `apps/api/src/db/migrations/observability/0002_analytics_events.sql` there, call + `appendSelfhostObservabilityMigrations()` from `scripts/selfhost/celld-project.ts` for the + observability projection, and call `installAnalyticsD1Sink()` from the generated celld entry. + Its `operations.analyticsD1*` settings are replaced by `analytics.d1.*`. +- Workspace has no Chromium system libraries (no apt allowed): visual audit screenshots come from + the CI Playwright Visual Tests artifact; staging checks use the API with a workload-identity + session cookie. + +## Remaining + +- [ ] Staging2 verification (admin analytics, attachment upload via presigned PUT, session snapshot) +- [ ] Screenshot evidence for `admin-logs-notice-audit.spec.ts` +- [ ] CodeRabbit request and wait diff --git a/tasks/backlog/2026-11-18-admin-log-search-level-filter-cf-400.md b/tasks/backlog/2026-11-18-admin-log-search-level-filter-cf-400.md new file mode 100644 index 0000000000..4323644c0f --- /dev/null +++ b/tasks/backlog/2026-11-18-admin-log-search-level-filter-cf-400.md @@ -0,0 +1,22 @@ +# Admin → Logs search with a level filter returns 502 (Cloudflare Observability 400) + +## Problem + +`POST /api/admin/observability/logs/query` with a non-empty `levels` filter (for example +`["error"]`) returns `502 CF_API_ERROR` because the Cloudflare Workers Observability telemetry API +answers `400`. The same request without `levels` returns `200` with log rows. The API's error +message truncates Cloudflare's response body, so the rejected field is not visible from the client. + +## Context + +Found 2026-11-18 on staging2 while verifying PR #2889 (L20). That PR changed only the credentials +check in `apps/api/src/services/worker-log-query.ts` (`hasCloudflareAccountApi`); the query +building in `queryCloudflareLogs()` (`apps/api/src/services/observability-logs.ts`) is unchanged, +so this predates it. The Admin → Logs level chips send exactly this shape. + +## Acceptance Criteria + +- [ ] Reproduce against the real API and identify the rejected filter shape (log the Cloudflare + error body server-side, untruncated, without secrets) +- [ ] Level-filtered searches return 200 on staging +- [ ] A contract test pins the level filter's request shape to what the API accepts diff --git a/tasks/backlog/2026-11-18-mcp-insights-budget-test-window-flake.md b/tasks/backlog/2026-11-18-mcp-insights-budget-test-window-flake.md new file mode 100644 index 0000000000..06b93e8f40 --- /dev/null +++ b/tasks/backlog/2026-11-18-mcp-insights-budget-test-window-flake.md @@ -0,0 +1,15 @@ +# Flaky test: project_insights budget test fails across a rate-limit window boundary + +## Problem + +`apps/api/tests/workers/mcp-project-insights.test.ts` > "two tokens for one chat share one budget" +failed on PR #2889's CI (job 134947823444, Durable Object Workers shard 3/7) with +`expected undefined to be -32000`. Its requests ran from 16:29:59.978Z to 16:30:00.1Z, so the +per-window budget reset mid-test and the expected refusal never came. The PR does not touch MCP or +insights code. + +## Acceptance Criteria + +- [ ] The test controls the clock (fake timers or an injected window start) so it cannot straddle a + window boundary +- [ ] A variant that starts 10 ms before a boundary passes deterministically diff --git a/tasks/backlog/2026-11-18-selfhost-analytics-sink-machine-traffic.md b/tasks/backlog/2026-11-18-selfhost-analytics-sink-machine-traffic.md new file mode 100644 index 0000000000..393b8b5d33 --- /dev/null +++ b/tasks/backlog/2026-11-18-selfhost-analytics-sink-machine-traffic.md @@ -0,0 +1,27 @@ +# Self-host D1 analytics sink records machine traffic + +## Problem + +On a self-hosted box with the D1 analytics sink active (`installAnalyticsD1Sink()` + +`ANALYTICS_SINK="d1"`, `apps/api/src/selfhost/analytics/`), `analyticsMiddleware()` +(`apps/api/src/middleware/analytics.ts`) writes one `analytics_events` row per recorded API +request, including VM-agent heartbeats and callback routes. At a sustained 5 requests/s that is +~430k rows a day, so the default `analytics.d1.maxRows` (500,000) is reached in about 1.2 days +and the row cap, not the 90-day age limit, decides retention. Admin analytics for 30/90 days then +silently covers about a day. + +Cloudflare is unaffected (Analytics Engine; the sink is never installed there). + +## Context + +Raised as MEDIUM by the performance reviewer on PR #2889 (L20). Deferred because the sink has no +caller on main yet (the celld entry installs it with the self-host packaging slice) and the right +default skip list is a product decision about what counts as product analytics on a box. + +## Acceptance Criteria + +- [ ] The self-host sink skips machine routes by default (VM-agent callbacks, heartbeats, internal + ingest), e.g. a self-host default for `ANALYTICS_SKIP_ROUTES` or a sink-side filter +- [ ] The retention arithmetic (inflow vs `analytics.d1.maxRows`) is stated in the self-host docs +- [ ] A test drives the real middleware with a callback route and asserts no row is written, with + a product-route control that is written diff --git a/tasks/backlog/2026-11-18-session-sleep-500-without-agent-session.md b/tasks/backlog/2026-11-18-session-sleep-500-without-agent-session.md new file mode 100644 index 0000000000..41fae50861 --- /dev/null +++ b/tasks/backlog/2026-11-18-session-sleep-500-without-agent-session.md @@ -0,0 +1,22 @@ +# Session sleep returns 500 when the workspace has no resumable agent session + +## Problem + +`POST /api/projects/:projectId/sessions/:sessionId/sleep` returns `500 INTERNAL_ERROR` with the +logged error "Workspace has no resumable agent session" when the agent never started (for example +its credential was missing). This is a designed refusal, not a server fault, and should answer a +4xx (likely `409`) that the UI can explain. + +## Context + +Found 2026-11-18 on staging2 while verifying PR #2889 (L20), request +`9c8af072-ce5d-4331-abb0-9d9aa0e1eb82`: the bootstrap admin's `opencode` agent had no credential, +so no agent session existed. Unrelated to L20 (the route and `sleepWorkspaceSession()` are +unchanged). Once a claude-code agent session existed, the same route returned 200 and the snapshot +was captured. + +## Acceptance Criteria + +- [ ] `sleepWorkspaceSession()` (`apps/api/src/services/session-sleep.ts`) maps "no resumable + agent session" to a documented 4xx through the chat sleep route +- [ ] A route test drives a workspace with no agent session and asserts the status and message