Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
2f77686
feat(selfhost): SAM-signed box object URLs for uploads without store …
raphaeltm Nov 23, 2026
579860c
test(selfhost): box object URL tokens, resolver choice, route and gate
raphaeltm Nov 23, 2026
a915e19
fix(selfhost): create-only box uploads above celld's 8 MiB conditiona…
raphaeltm Nov 23, 2026
2fa9109
style: format and sort imports
raphaeltm Nov 23, 2026
14e8cfa
docs(selfhost): uploads through the box; the static store key is opti…
raphaeltm Nov 23, 2026
2ea4b88
test(selfhost): celld config and entry derive self-host classes from …
raphaeltm Nov 23, 2026
332b35b
fix(selfhost): review findings for box uploads
raphaeltm Nov 23, 2026
4fc3f59
test(selfhost): live celld proof that a bad-token body is not buffere…
raphaeltm Nov 23, 2026
14b2d12
fix(selfhost): Cloudflare review findings for box uploads
raphaeltm Nov 23, 2026
b8e9f8b
test(selfhost): build the forged-token URL instead of a token-shaped …
raphaeltm Nov 23, 2026
8bedbfb
fix(selfhost): session snapshots upload through the box
raphaeltm Nov 23, 2026
3194e6b
test(api): compose init answers 503 naming the settings; task file br…
raphaeltm Nov 23, 2026
1733dfc
chore(secret-scan): review the placeholder box token literal in 4fc3f…
raphaeltm Nov 23, 2026
a1fef9b
task: GCS box proof evidence; backlog the profile-less publish failure
raphaeltm Nov 23, 2026
3bc337f
test(selfhost): the sealed celld entry also wraps BoxUploadGate; reco…
raphaeltm Nov 23, 2026
1e09823
fix(selfhost): CodeRabbit findings for box uploads
raphaeltm Nov 23, 2026
acdc904
Merge remote-tracking branch 'origin/main' into sam/self-host-uploads…
raphaeltm Nov 23, 2026
578bb63
fix(selfhost): Codex findings: snapshot uploads carry their workspace…
raphaeltm Nov 23, 2026
80143b6
fix(selfhost): wait briefly for an upload slot before answering 503
raphaeltm Nov 23, 2026
64a1a39
task: archive self-host box uploads
raphaeltm Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,9 @@ composeImageArtifactsCallbackRoute.post('/:id/compose-image-artifacts/init', asy

return c.json({
uploadId,
maxBytes: getComposeImageArtifactMaxBytes(c.env),
// Every slot carries the same bound: the configured maximum, lowered on a self-hosted box to
// what one request through it can carry (composeImageArtifactMaxBytesFor).
maxBytes: uploads[0]?.maxBytes ?? getComposeImageArtifactMaxBytes(c.env),
uploads,
});
});
Expand Down
12 changes: 8 additions & 4 deletions apps/api/src/routes/tasks/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +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';
import { resolveR2ObjectUrlSigner } from '../../services/r2-s3-client';

const uploadRoutes = new Hono<{ Bindings: Env }>();

Expand Down Expand Up @@ -51,8 +51,10 @@ uploadRoutes.post('/request-upload', requireAuth(), requireApproved(), jsonValid
// Validate project ownership
await requireProjectCapability(db, projectId, userId, 'task:write');

// Check presigning is configured (Cloudflare R2 or an operator store; one shared check)
if (!hasR2S3Credentials(c.env)) {
// Uploads need a URL signer: R2 presign (Cloudflare or an operator store with a key), or a
// self-hosted box's own upload route. The same resolver mints the URL below.
const signer = resolveR2ObjectUrlSigner(c.env);
if (!signer) {
throw errors.forbidden('File attachments are not configured (R2 S3 credentials missing)');
}

Expand All @@ -69,9 +71,11 @@ uploadRoutes.post('/request-upload', requireAuth(), requireApproved(), jsonValid
}

// Validate file size limit
const maxBytes = c.env.ATTACHMENT_UPLOAD_MAX_BYTES
const configuredMaxBytes = c.env.ATTACHMENT_UPLOAD_MAX_BYTES
? parseInt(c.env.ATTACHMENT_UPLOAD_MAX_BYTES, 10)
: ATTACHMENT_DEFAULTS.UPLOAD_MAX_BYTES;
// A box carries at most signer.maxPutBytes per request.
const maxBytes = Math.min(configuredMaxBytes, signer.maxPutBytes ?? configuredMaxBytes);
if (body.size > maxBytes) {
throw errors.badRequest(`File size ${body.size} exceeds maximum ${maxBytes} bytes`);
}
Expand Down
5 changes: 5 additions & 0 deletions apps/api/src/routes/workspaces/session-snapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,11 @@ sessionSnapshotRoutes.post('/:id/session-snapshot/artifacts/:artifact/upload-url
sha256,
contentType: artifact === 'home' ? 'application/x-tar' : 'application/octet-stream',
checksumHeader: body.checksumHeader === true,
owner: {
workspaceId: c.req.param('id'),
userId: workspace.userId,
projectId: workspace.projectId,
},
});
const recorded = await recordSessionSnapshotArtifactAuthorization(db, {
chatSessionId,
Expand Down
7 changes: 6 additions & 1 deletion apps/api/src/selfhost/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
* with its `analytics.d1.*` retention settings;
* - the reverse-tunnel transport, gateway routes and lease sweep (`reverse-tunnel/entry.ts`),
* with the shared cloud-init generator as the frpc boot renderer;
* - the box's own DNS zone when SAM_DNS_PROVIDER="box" (`dns/`, served by deploy/selfhost/sam-dns).
* - the box's own DNS zone when SAM_DNS_PROVIDER="box" (`dns/`, served by deploy/selfhost/sam-dns);
* - uploads and downloads through the box when no static store key is configured (`object-urls/`).
*/
import { generateCloudInit } from '@simple-agent-manager/cloud-init';
import type { Hono } from 'hono';
Expand All @@ -19,9 +20,11 @@ import { mountHostedGitRoute } from './hosted-git';
import { hostedGitTokenRoutes } from './hosted-git/token-route';

export { HostedGitRepo } from './hosted-git';
export { BoxUploadGate } from './object-urls';

import { installAnalyticsD1Sink } from './analytics';
import { installBoxDns } from './dns';
import { installBoxObjectUrls, mountBoxObjectRoute } from './object-urls';
import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry';
import { installSpeechEndpoints } from './speech';

Expand All @@ -34,10 +37,12 @@ export function withSelfHostBuild<T extends SharedWorkerEntry>(
if (!mounted.has(app)) {
mountHostedGitRoute(app);
app.route('/api/projects', hostedGitTokenRoutes);
mountBoxObjectRoute(app);
mounted.add(app);
}
installSpeechEndpoints();
installAnalyticsD1Sink();
installBoxDns();
installBoxObjectUrls();
return withReverseTunnel(worker, generateCloudInit);
}
80 changes: 5 additions & 75 deletions apps/api/src/selfhost/hosted-git/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* project, that the user is still an active member, and that a workspace-bound token's workspace
* is still active on its current runtime (callback generation).
*/
import { mintSignedToken, type SignedTokenPurpose, verifySignedToken } from '../signed-token';
import type { HostedGitEnv as Env } from './env';

export type HostedGitScope = 'read' | 'write';
Expand Down Expand Up @@ -40,56 +41,12 @@ export const MAX_HOSTED_GIT_TOKEN_TTL_SECONDS = 86_400;
/** Repository names SAM generates (toArtifactsRepoName): lowercase, digits, dashes. */
const REPO_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,127}$/;

const encoder = new TextEncoder();
const decoder = new TextDecoder();
const PURPOSE: SignedTokenPurpose = { prefix: TOKEN_PREFIX, label: KEY_LABEL };

export function isHostedGitRepoName(name: string): boolean {
return REPO_NAME_PATTERN.test(name);
}

function base64UrlEncode(bytes: Uint8Array): string {
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
}

function base64UrlDecode(value: string): Uint8Array | null {
if (!/^[A-Za-z0-9_-]+$/.test(value)) return null;
try {
const padded =
value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (value.length % 4)) % 4);
return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
} catch {
return null;
}
}

/**
* The derived key, cached once derived. Only a finished key is shared: a request never waits on a
* derivation another request started, which on the self-hosted celld runtime could be dropped
* with that request (lib/shared-flight.ts). Concurrent cold callers each derive once (one HKDF).
*/
let cachedKey: { secret: string; key: CryptoKey } | null = null;

/** HKDF-SHA256 from ENCRYPTION_KEY with a purpose label; no other use shares this key. */
async function signingKey(env: Pick<Env, 'ENCRYPTION_KEY'>): Promise<CryptoKey> {
const secret = env.ENCRYPTION_KEY;
if (!secret) throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories');
if (cachedKey?.secret === secret) return cachedKey.key;
const root = await crypto.subtle.importKey('raw', encoder.encode(secret), 'HKDF', false, [
'deriveKey',
]);
const key = await crypto.subtle.deriveKey(
{ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: encoder.encode(KEY_LABEL) },
root,
{ name: 'HMAC', hash: 'SHA-256', length: 256 },
false,
['sign', 'verify']
);
cachedKey = { secret, key };
return key;
}

export function clampHostedGitTokenTtl(ttlSeconds: number | undefined): number {
if (ttlSeconds === undefined || !Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
return DEFAULT_HOSTED_GIT_TOKEN_TTL_SECONDS;
Expand Down Expand Up @@ -117,15 +74,8 @@ export async function mintHostedGitToken(
claims.callbackGeneration = input.callbackGeneration ?? null;
}
if (input.userId) claims.userId = input.userId;
const payload = base64UrlEncode(encoder.encode(JSON.stringify(claims)));
const unsigned = `${TOKEN_PREFIX}.${payload}`;
const signature = await crypto.subtle.sign(
'HMAC',
await signingKey(env),
encoder.encode(unsigned)
);
return {
token: `${unsigned}.${base64UrlEncode(new Uint8Array(signature))}`,
token: await mintSignedToken(env, PURPOSE, claims),
expiresAt: new Date(exp * 1000).toISOString(),
};
}
Expand All @@ -136,28 +86,8 @@ export async function verifyHostedGitToken(
token: string,
now: number = Date.now()
): Promise<HostedGitTokenClaims | null> {
if (token.length > 2048) return null;
const parts = token.split('.');
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null;
const [prefix, payload, signaturePart] = parts as [string, string, string];
const signature = base64UrlDecode(signaturePart);
const payloadBytes = base64UrlDecode(payload);
if (!signature || !payloadBytes) return null;
const valid = await crypto.subtle.verify(
'HMAC',
await signingKey(env),
signature,
encoder.encode(`${prefix}.${payload}`)
);
if (!valid) return null;
let parsed: unknown;
try {
parsed = JSON.parse(decoder.decode(payloadBytes));
} catch {
return null;
}
if (!parsed || typeof parsed !== 'object') return null;
const claims = parsed as Record<string, unknown>;
const claims = await verifySignedToken(env, PURPOSE, token);
if (!claims) return null;
if (typeof claims.repo !== 'string' || !isHostedGitRepoName(claims.repo)) return null;
if (claims.scope !== 'read' && claims.scope !== 'write') return null;
if (typeof claims.exp !== 'number' || claims.exp * 1000 <= now) return null;
Expand Down
132 changes: 132 additions & 0 deletions apps/api/src/selfhost/object-urls/gate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* The box-wide limit on concurrent object uploads (`BoxUploadGate`, one instance per box).
*
* Why a limit: celld streams an upload into the R2 binding without holding it in the isolate, but
* every in-flight upload still costs process memory. Measured on celld v0.6.3 with 1 GB bodies
* (task tasks/active/2026-11-23-selfhost-box-object-uploads.md): peak RSS 220 MB for one upload,
* 284 / 427 / 896 MB for 2 / 4 / 8 at once, so roughly 85 MB per upload over a ~150 MB base, while
* aggregate throughput stops growing after two (~180 MB/s). The default of 4 keeps the peak near
* 430 MB. An upload over the limit waits briefly in the route (`uploadAdmissionWaitSeconds`), then is refused with 503 and Retry-After. One
* uploader (a workspace, else a user) may hold only part of the slots, and the route drops an
* upload that stops sending bytes (`route.ts`), so a slow or stalled client cannot keep the box's
* uploads blocked.
*
* Why a Durable Object: the limit must hold across every Worker isolate celld runs, and a single
* object is the box's one serialization point. Each acquire is a lease with a short expiry that the
* route renews while bytes keep arriving, so a handler that dies without releasing (celld restart,
* a killed isolate) frees its slot within one lease instead of holding it forever. `acquire` and `release` do all their work in synchronous SQL with
* no `await`, so two calls cannot interleave inside one (rule 45).
*/
import { DurableObject } from 'cloudflare:workers';

export interface BoxUploadGateEnv {
BOX_UPLOAD_GATE?: DurableObjectNamespace;
}

export type BoxUploadLease =
| { granted: true }
/** The box (or this uploader) is at its limit. */
| { granted: false; reason: 'busy'; active: number; retryAfterSeconds: number }
/** Another live upload is writing the same object key. */
| { granted: false; reason: 'key-in-use' };

/** Shortest and longest Retry-After hint (seconds) a refusal suggests. */
const MIN_RETRY_AFTER_SECONDS = 5;
const MAX_RETRY_AFTER_SECONDS = 60;

export class BoxUploadGate extends DurableObject {
constructor(ctx: DurableObjectState, env: unknown) {
super(ctx, env as never);
ctx.storage.sql.exec(
'CREATE TABLE IF NOT EXISTS upload_slots (id TEXT PRIMARY KEY, uploader TEXT NOT NULL, object_key TEXT NOT NULL, expires_at INTEGER NOT NULL)'
);
}

/** The gate's clock (a method, not an RPC argument, so no caller can move it). */
protected now(): number {
return Date.now();
}

/**
* Grants a lease to `id` while fewer than `limits.total` unexpired leases exist on the box,
* fewer than `limits.perUploader` belong to `uploader` (so one uploader cannot hold every slot),
* and no live lease is writing `objectKey`. The key claim makes create-only hold for streams
* celld cannot write conditionally (route.ts): from the existence check through the write, only
* one upload may create a given object.
*/
acquire(
id: string,
uploader: string,
objectKey: string,
limits: { total: number; perUploader: number; leaseMs: number }
): BoxUploadLease {
const now = this.now();
const sql = this.ctx.storage.sql;
sql.exec('DELETE FROM upload_slots WHERE expires_at <= ?', now);
const row = sql
.exec<{ active: number; mine: number; sameKey: number; next: number | null }>(
'SELECT COUNT(*) AS active, COALESCE(SUM(uploader = ?), 0) AS mine, COALESCE(SUM(object_key = ?), 0) AS sameKey, MIN(expires_at) AS next FROM upload_slots',
uploader,
objectKey
)
.one();
if (row.sameKey > 0) return { granted: false, reason: 'key-in-use' };
if (row.active >= limits.total || row.mine >= limits.perUploader) {
// A hint, not a promise: most leases end when their upload finishes, long before expiry.
const untilExpiry = Math.ceil(((row.next ?? now) - now) / 1000);
const retryAfterSeconds = Math.min(
MAX_RETRY_AFTER_SECONDS,
Math.max(MIN_RETRY_AFTER_SECONDS, untilExpiry)
);
return { granted: false, reason: 'busy', active: row.active, retryAfterSeconds };
}
sql.exec(
'INSERT OR REPLACE INTO upload_slots (id, uploader, object_key, expires_at) VALUES (?, ?, ?, ?)',
id,
uploader,
objectKey,
now + limits.leaseMs
);
return { granted: true };
}

/**
* Extends a held, unexpired lease while its upload is still receiving bytes (route.ts). False when
* the lease is gone: the route then stops the upload rather than let it run uncounted.
*/
renew(id: string, leaseMs: number): boolean {
const now = this.now();
const cursor = this.ctx.storage.sql.exec(
'UPDATE upload_slots SET expires_at = ? WHERE id = ? AND expires_at > ?',
now + leaseMs,
id,
now
);
return cursor.rowsWritten > 0;
}

release(id: string): void {
this.ctx.storage.sql.exec('DELETE FROM upload_slots WHERE id = ?', id);
}
}

/** The box's one gate instance. */
export const BOX_UPLOAD_GATE_NAME = 'box';

interface BoxUploadGateStub {
acquire(
id: string,
uploader: string,
objectKey: string,
limits: { total: number; perUploader: number; leaseMs: number }
): Promise<BoxUploadLease>;
renew(id: string, leaseMs: number): Promise<boolean>;
release(id: string): Promise<void>;
}

export function boxUploadGate(env: BoxUploadGateEnv): BoxUploadGateStub | null {
const namespace = env.BOX_UPLOAD_GATE;
if (!namespace) return null;
// Typed RPC stub: Cloudflare's generated stub type cannot express this class's methods.
return namespace.get(namespace.idFromName(BOX_UPLOAD_GATE_NAME)) as unknown as BoxUploadGateStub;
}
33 changes: 33 additions & 0 deletions apps/api/src/selfhost/object-urls/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Box object URLs for the self-host build: uploads and downloads that go through the box instead
* of S3 presigned URLs, for a box with no static store key (task
* tasks/active/2026-11-23-selfhost-box-object-uploads.md).
*
* Only `selfhost/build.ts` imports this module, so the Cloudflare bundle carries none of it and
* keeps minting R2 presigned URLs (tests/unit/selfhost/selfhost-only-modules.test.ts).
*/
import type { Hono } from 'hono';

import type { Env } from '../../env';
import { installAdminSettingDefinitions } from '../../services/admin-settings-registry';
import { installBoxObjectUrlSigner } from '../../services/r2-s3-client';
import { handleBoxObjectRequest } from './route';
import { BOX_OBJECT_SETTINGS } from './settings';
import { BOX_OBJECT_ROUTE, createBoxObjectUrlSigner } from './signer';

export { BoxUploadGate } from './gate';

/** Registers the signer and settings (idempotent). */
export function installBoxObjectUrls(): void {
installAdminSettingDefinitions(BOX_OBJECT_SETTINGS);
installBoxObjectUrlSigner(createBoxObjectUrlSigner);
}

/**
* Mounts the route. Call once, after `src/index.ts` registered the shared routes: like hosted git's
* route, it then runs after exactly the global middleware (request logging, CORS) and no
* session-auth middleware, which it must not have (the token is the credential).
*/
export function mountBoxObjectRoute(app: Hono<{ Bindings: Env }>): void {
app.on(['PUT', 'GET'], BOX_OBJECT_ROUTE, (c) => handleBoxObjectRequest(c));
}
Loading
Loading