Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions apps/api/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down
11 changes: 10 additions & 1 deletion apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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);
}
Expand Down
6 changes: 5 additions & 1 deletion apps/api/src/lib/analytics-config.ts
Original file line number Diff line number Diff line change
@@ -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<Env, 'ANALYTICS_DATASET'>): 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) {
Expand Down
10 changes: 10 additions & 0 deletions apps/api/src/lib/pages-proxy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type PagesProxyTarget =
| { type: 'none' }
| { type: 'assets' }
| { type: 'proxy'; hostname: string }
| { type: 'missing-config'; message: string }
| { type: 'redirect'; hostname: string };
Expand All @@ -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(
Expand All @@ -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' };
}
Expand Down
9 changes: 5 additions & 4 deletions apps/api/src/middleware/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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) });
Expand Down
20 changes: 15 additions & 5 deletions apps/api/src/routes/admin-analytics-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<unknown> {
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(
Expand Down
18 changes: 18 additions & 0 deletions apps/api/src/routes/admin-analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
*/
Expand Down
8 changes: 8 additions & 0 deletions apps/api/src/routes/admin/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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');
Expand Down
13 changes: 8 additions & 5 deletions apps/api/src/routes/analytics-ingest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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;
Expand All @@ -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({
Comment thread
simple-agent-manager[bot] marked this conversation as resolved.
Resolved
indexes: [index],
blobs: [
validated.event, // blob1: event name
Expand All @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/routes/projects/publish-job-spec.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down
5 changes: 3 additions & 2 deletions apps/api/src/routes/tasks/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }>();

Expand Down Expand Up @@ -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)');
}

Expand Down
27 changes: 26 additions & 1 deletion apps/api/src/scheduled/observability-purge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,37 @@
* 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<PurgeResult> {
if (!env.OBSERVABILITY_DATABASE) {
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;
}
Loading
Loading