Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
b1fb774
feat(selfhost): one-box compose stack, Caddy, frps and object store (…
raphaeltm Nov 19, 2026
ed1c92c
fix(selfhost): check box ports as docker compose runs them (F21 L5)
raphaeltm Nov 19, 2026
57e400a
fix(selfhost): upgrade rebuilds an image only when its build inputs c…
raphaeltm Nov 19, 2026
ba0403f
feat(selfhost): GCP node trust bootstrap (pnpm selfhost:gcp-bootstrap)
raphaeltm Nov 19, 2026
a20f593
docs(selfhost): short operator README for the experimental box
raphaeltm Nov 19, 2026
6c92cff
test(selfhost): Docker live suite for the box runtime, CI job on self…
raphaeltm Nov 19, 2026
2ef8050
docs(selfhost): README describes upgrade retry and box-scoped compose…
raphaeltm Nov 19, 2026
8549ccb
style(quality): drop useless quote escapes in dependency-governance test
raphaeltm Nov 19, 2026
943d36a
ci(selfhost): run box static tests on deploy/selfhost changes; route …
raphaeltm Nov 19, 2026
509a63f
ci(selfhost): drop the workspace build from Validate Deploy Scripts
raphaeltm Nov 19, 2026
9f58d14
fix(selfhost): gcp-bootstrap refuses a shared pool, pins its APIs and…
raphaeltm Nov 19, 2026
28749ee
fix(selfhost): celld and frps run with no capabilities and a read-onl…
raphaeltm Nov 19, 2026
6ffc0c8
fix(selfhost): the bundled object store refuses a root secret under 2…
raphaeltm Nov 19, 2026
4f83ce8
fix(selfhost): reserve sam-mx's port and check box ports before anyth…
raphaeltm Nov 19, 2026
73a3bf2
fix(selfhost): strip client X-SAM-* headers on every route, not only …
raphaeltm Nov 19, 2026
f422403
test(selfhost): one Caddy runner, HTTPS client and Docker skip rule f…
raphaeltm Nov 19, 2026
096c6a7
test(selfhost): type the malformed-range cases for the selfhost type …
raphaeltm Nov 19, 2026
c4fac57
docs(tasks): L22 task file records PR 2 shipped and PR 3 progress
raphaeltm Nov 19, 2026
14bf564
chore(quality): reviewed baseline entry for the deploy harness fleet …
raphaeltm Nov 19, 2026
adaf1c0
fix(selfhost): resolve every compose-interpolated variable from the s…
raphaeltm Nov 19, 2026
17e44da
fix(selfhost): refuse a bare port for SAM_MX_LISTEN
raphaeltm Nov 19, 2026
a06613f
test(selfhost): verify Caddy's certificate in the live suite (Sonar S…
raphaeltm Nov 19, 2026
0a16c1e
ci(selfhost-live): install dependencies without lifecycle scripts (So…
raphaeltm Nov 19, 2026
23db935
fix(selfhost): run the Caddy image as a non-root user (Sonar S6471)
raphaeltm Nov 19, 2026
2661e08
chore(selfhost): clear Sonar code smells in the box scripts
raphaeltm Nov 19, 2026
795bf67
test(selfhost): read the non-root Caddy's environment as a privileged…
raphaeltm Nov 19, 2026
754d86c
docs(selfhost): README and gcp-bootstrap messages from the fresh BOX …
raphaeltm Nov 19, 2026
ba95e29
docs(selfhost): build steps share the box's egress; task file records…
raphaeltm Nov 19, 2026
7ae5db3
docs(tasks): format L22 task file
raphaeltm Nov 19, 2026
6124df8
task: plan self-host-only hosted git landing
raphaeltm Nov 19, 2026
5bf419d
Merge remote-tracking branch 'origin/main' into sam/l22c-box-runtime-v3
raphaeltm Nov 19, 2026
cd175f7
fix(selfhost): GCP bootstrap trusts platform tokens only; refuse disa…
raphaeltm Nov 19, 2026
eba7151
fix(selfhost): Codex review round on L22c (overlays, state dir, profi…
raphaeltm Nov 19, 2026
662a092
fix(selfhost): refuse SAM_MX_LISTEN with an unbracketed IPv6 host
raphaeltm Nov 19, 2026
3e3ef8d
fix(selfhost): COMPOSE_PROFILES=* enables the mail profiles
raphaeltm Nov 19, 2026
424c7ba
feat: isolate hosted git runtime and bound git resource use
raphaeltm Nov 19, 2026
5396252
fix(selfhost): refuse stale pool bindings; list-form build args; READ…
raphaeltm Nov 19, 2026
75aeaea
fix: fence loose inflation and queued git collection
raphaeltm Nov 19, 2026
6c19b78
Merge commit '53962520254695df0ec3c700fd8e2ff44fbf76e1' into sam/self…
raphaeltm Nov 19, 2026
7f49d38
feat: wire hosted git into celld build and migration registry
raphaeltm Nov 19, 2026
0991b27
fix(selfhost): port bounds in Caddy's start guard; repo-root build co…
raphaeltm Nov 19, 2026
0c4ae82
Merge commit '0991b27ff422900d68077dc226dbad8cfa8681e1' into sam/self…
raphaeltm Nov 19, 2026
a7cad0d
style: format hosted git build wiring
raphaeltm Nov 19, 2026
f6c65e7
fix: use static identifiers and bound git SQL placeholders
raphaeltm Nov 19, 2026
083dcdd
ci: run isolated hosted git conformance and track its inputs
raphaeltm Nov 19, 2026
08e2f60
Merge remote-tracking branch 'origin/main' into sam/l22c-box-runtime-v3
raphaeltm Nov 19, 2026
6324f09
fix: fence hosted git lifecycle and preserve native RPC behavior
raphaeltm Nov 19, 2026
0f504c8
Merge remote-tracking branch 'origin/sam/l22c-box-runtime-v3' into sa…
raphaeltm Nov 19, 2026
4e1f208
docs: record hosted git review and live verification evidence
raphaeltm Nov 19, 2026
8c7927e
docs: clarify hosted git ref bounds and vendor adaptations
raphaeltm Nov 19, 2026
e7ac643
test: exercise rejected pack GC and deletion on real SQLite
raphaeltm Nov 19, 2026
c6a45ee
fix(selfhost): reclaim failed packs and retain bounded GC retries
raphaeltm Nov 19, 2026
0eda6a2
fix(selfhost): enforce Git ref component and suffix rules
raphaeltm Nov 19, 2026
553a906
Merge remote-tracking branch 'origin/main' into sam/continue-finish-s…
raphaeltm Nov 19, 2026
d16d153
fix(selfhost): prove push closure per command before trusting it
raphaeltm Nov 19, 2026
c1f7bc5
task: record H2 takeover, closure fix and evidence
raphaeltm Nov 19, 2026
f9eb945
fix(selfhost): harden hosted git push admission after adversarial review
raphaeltm Nov 19, 2026
8bc9a3a
fix(selfhost): admit only objects git can read; bound old-history reads
raphaeltm Nov 19, 2026
77e55db
fix(selfhost): never trust the reachable cache for admission; byte-ex…
raphaeltm Nov 19, 2026
dc8e9e4
fix(selfhost): pin the first header line; unstamp the cache before re…
raphaeltm Nov 19, 2026
ef45167
fix(selfhost): check reachable-cache validity when writing it
raphaeltm Nov 20, 2026
1bbf2ae
fix(selfhost): resolve Codex findings on hosted git ls-refs, GC, buff…
raphaeltm Nov 20, 2026
9d4887d
fix(selfhost): enforce the repository storage cap after the pack is s…
raphaeltm Nov 20, 2026
9d8a080
Merge remote-tracking branch 'origin/main' into sam/continue-finish-s…
raphaeltm Nov 20, 2026
fc56885
task: archive H2 hosted git with final BOX evidence
raphaeltm Nov 20, 2026
dd22fb5
task: record H2 final BOX evidence
raphaeltm Nov 20, 2026
7f086c7
Merge remote-tracking branch 'origin/main' into sam/continue-finish-s…
raphaeltm Nov 20, 2026
af30091
fix(selfhost): resolve Codex findings on upload lists, token minting,…
raphaeltm Nov 20, 2026
7b2b41f
fix(selfhost): screen pushed objects with SHA-1 collision detection
raphaeltm Nov 20, 2026
e04adb9
test(selfhost): cover SHA-1DC on delta-resolved push objects
raphaeltm Nov 20, 2026
023a40e
task: record SHA-1DC ingest LOW notes in hosted-git hardening backlog
raphaeltm Nov 20, 2026
ee54ce1
fix(projects): reject default branches git refuses with a 400
raphaeltm Nov 20, 2026
f433bb9
fix(selfhost): refuse every command for a ref a push names twice
raphaeltm Nov 20, 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
20 changes: 7 additions & 13 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,8 @@ jobs:
- 'scripts/deploy/durable-object-migrations.ts'
- 'scripts/deploy/types.ts'
- 'scripts/deploy/vapid-keys.ts'
# Self-host build tests import the celld generator, presign vars, SMTP settings and
# account SQL: these modules plus the scripts/selfhost modules they import. The
# transitive ones are listed by hand: ci-suite-selection.test.ts checks the direct
# imports but does not follow `./x.js` specifiers to `x.ts`.
- 'scripts/selfhost/account-sql.ts'
- 'scripts/selfhost/box-settings.ts'
- 'scripts/selfhost/celld-config.ts'
- 'scripts/selfhost/celld-project.ts'
- 'scripts/selfhost/mail-settings.ts'
- 'scripts/selfhost/observability-migrations.ts'
- 'scripts/selfhost/reverse-tunnel-migrations.ts'
- 'scripts/selfhost/secret-files.ts'
- 'scripts/selfhost/selfhost-migrations.ts'
# API build/conformance tests import the celld generator and its helpers.
- 'scripts/selfhost/**'
# selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only).
- 'deploy/selfhost/sam-mx/**'
# The self-host access-log redaction guard scans the API routes against this filter.
Expand Down Expand Up @@ -589,6 +578,11 @@ jobs:
--coverage.thresholds.statements=0 --coverage.thresholds.branches=0
--coverage.thresholds.functions=0 --coverage.thresholds.lines=0

# One shard owns the real-git suite; the dedicated config launches its own runtime.
- name: Hosted git conformance and celld bundle
if: matrix.shard == 1
run: pnpm --filter @simple-agent-manager/api test:hosted-git

- name: Upload API blob report
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
Expand Down
5 changes: 4 additions & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"openapi:generate": "tsx scripts/generate-openapi.ts",
"openapi:check": "tsx scripts/generate-openapi.ts --check",
"deploy": "wrangler deploy",
"deploy:staging": "wrangler deploy --env staging"
"deploy:staging": "wrangler deploy --env staging",
"test:hosted-git": "vitest run --config vitest.hosted-git.config.ts"
},
"dependencies": {
"@ai-sdk/openai-compatible": "2.0.87",
Expand Down Expand Up @@ -51,6 +52,7 @@
"drizzle-orm": "catalog:",
"hono": "4.13.4",
"jose": "catalog:",
"pako": "^2.1.0",
"tsx": "catalog:",
"valibot": "catalog:",
"workers-ai-provider": "4.0.1",
Expand All @@ -62,6 +64,7 @@
"@modelcontextprotocol/client": "2.4.0",
"@types/better-sqlite3": "^7.6.13",
"@types/diff": "^8.0.0",
"@types/pako": "^2.0.3",
"@typescript-eslint/eslint-plugin": "catalog:",
"@typescript-eslint/parser": "catalog:",
"@vitest/coverage-v8": "catalog:",
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ import { agentEmailConfig } from './services/agent-email/setup-state';
import { isAgentSignInEnabled } from './services/agent-sign-in/config';
import { isInstantRuntimeAvailable } from './services/vm-agent-container';

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

// Global error handler — catches errors from all routes including subrouters.
// Must use app.onError() instead of middleware try/catch because Hono's
Expand Down
32 changes: 32 additions & 0 deletions apps/api/src/lib/git-ref-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Git ref-name admission shared by hosted-git push validation (`validatePush` in the vendored
* dgit protocol) and project creation, which names the branch the seed push writes. One
* predicate, so a branch SAM accepts can always be pushed.
*
* Rules follow `git check-ref-format` (https://git-scm.com/docs/git-check-ref-format) plus SAM's
* conservative bounds: no whitespace, control, quote or HTML characters and at most 255
* characters in total. This module has no dependencies, so the Worker graph may import it.
*/
// eslint-disable-next-line no-control-regex -- git check-ref-format rejects ASCII control bytes
const BAD_REF_CHARS = /[\s~^:?*[\\'"<>&`\x00-\x1f\x7f]/;

Check warning on line 11 in apps/api/src/lib/git-ref-name.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove duplicates in this character class.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaH23WbiMWghXlhhpoHF&open=AaH23WbiMWghXlhhpoHF&pullRequest=2907
const MAX_REF_NAME_LENGTH = 255;

/** True when `ref` (a full name such as `refs/heads/main`) is a ref name git and SAM accept. */
export function isValidGitRefName(ref: string): boolean {
return (
ref.startsWith('refs/') &&
ref.length <= MAX_REF_NAME_LENGTH &&
!ref.includes('..') &&
!BAD_REF_CHARS.test(ref) &&
!ref.includes('@{') &&
!ref.includes('//') &&
!ref.endsWith('/') &&
!ref.endsWith('.') &&
!ref.split('/').some((c) => c.startsWith('.') || c.endsWith('.lock'))
);
}

/** True when `branch` (a short name such as `main`) names a valid `refs/heads/` ref. */
export function isValidGitBranchName(branch: string): boolean {
return branch.length > 0 && isValidGitRefName(`refs/heads/${branch}`);
}
2 changes: 1 addition & 1 deletion apps/api/src/repo-hosting-ports/artifacts.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ArtifactsBackendPort } from '@simple-agent-manager/repo-hosting/ports';

import type { Env } from '../env';
import { resolveArtifactsBackend } from '../services/hosted-git/backend';
import { resolveArtifactsBackend } from '../services/artifacts/backend';

/**
* Repo hosting resolves the SAM-native repository backend through the worker's hosted-git seam:
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/routes/artifacts-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Hono } from 'hono';

import type { Env } from '../env';
import { applyCacheHeaders } from '../lib/cache-headers';
import { isArtifactsAvailable } from '../services/hosted-git/backend';
import { isArtifactsAvailable } from '../services/artifacts/backend';

/**
* Public config: whether this install can create SAM-native (Artifacts) repositories. True only
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/routes/projects/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ import { toProjectSummaryResponse } from '../../lib/mappers';
import { parsePositiveInt } from '../../lib/route-helpers';
import { getUserId } from '../../middleware/auth';
import { requireProjectCapability } from '../../middleware/project-auth';
import { resolveArtifactsBackendForCleanup } from '../../services/artifacts/backend';
import {
buildProjectLibraryDeleteStatements,
buildProjectLibraryR2Prefix,
deleteProjectLibraryObjects,
getProjectDeleteCleanupBatchSize,
} from '../../services/file-library';
import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership';
import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend';
import { getRuntimeLimits } from '../../services/limits';
import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history';
import { registerProjectCreateRoute } from './project-create';
Expand Down
48 changes: 39 additions & 9 deletions apps/api/src/routes/projects/project-create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@ import { type Hono } from 'hono';

import * as schema from '../../db/schema';
import type { Env } from '../../env';
import { isValidGitBranchName } from '../../lib/git-ref-name';
import { log } from '../../lib/logger';
import { toProjectResponse } from '../../lib/mappers';
import { ulid } from '../../lib/ulid';
import { getUserId } from '../../middleware/auth';
import { errors } from '../../middleware/error';
import { AppError, errors } from '../../middleware/error';
import { createOwnerProjectMembership } from '../../middleware/project-auth';
import { CreateProjectSchema, jsonValidator } from '../../schemas';
import { artifactsBackendExtensions, resolveArtifactsBackend } from '../../services/artifacts/backend';
import { seedArtifactsReadme } from '../../services/artifacts/seed-readme';
import { getExternalInstallationId } from '../../services/github-installation-ids';
import {
listGitLabBranches,
requireGitLabUserAccessToken,
verifyGitLabProjectAccess,
} from '../../services/gitlab';
import { resolveArtifactsBackend } from '../../services/hosted-git/backend';
import { getRuntimeLimits } from '../../services/limits';
import {
assertRepositoryAccess,
Expand Down Expand Up @@ -103,7 +104,18 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
throw errors.badRequest(`Maximum ${maxRepos} Artifacts-backed projects allowed`);
}

const importUrl = body.importUrl?.trim() || null;
const extensions = artifactsBackendExtensions(c.env, artifacts);
const importer = extensions.importSource;
if (importUrl && !importer) {
throw errors.badRequest('This repository backend does not support importUrl');
}
const importBranch = importUrl && importer ? await importer.defaultBranch(importUrl) : null;
if (importUrl && !importBranch) {
throw errors.badRequest('Could not read the default branch of the repository at importUrl');
}
const defaultBranch =
importBranch ||
body.defaultBranch?.trim() ||
c.env.ARTIFACTS_DEFAULT_BRANCH ||
ARTIFACTS_DEFAULTS.DEFAULT_BRANCH;
Expand All @@ -116,6 +128,13 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
'defaultBranch contains invalid characters. Only alphanumeric, hyphens, underscores, slashes, and dots are allowed (max 255 chars).'
);
}
// The repository's first push writes this branch; refuse names git itself rejects
// (`foo.lock`, `.hidden`, `a..b`, `trailing.`) here rather than fail the seed push.
if (!isValidGitBranchName(defaultBranch)) {
throw errors.badRequest(
'defaultBranch is not a valid git branch name (see git check-ref-format).'
);
}

// Create Artifacts repo — name includes projectId for uniqueness.
// Must be sanitized: Artifacts rejects uppercase/spaces (the ULID projectId
Expand All @@ -133,13 +152,23 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
// also orients agents (project name, description, SAM MCP tools). If seeding
// fails the repo is unusable, so we abort creation and log the orphan.
try {
await seedArtifactsReadme({
remote: created.remote,
token: created.token,
branch: defaultBranch,
projectName: name,
description,
});
if (importUrl && importer) {
await importer.populate({
sourceUrl: importUrl,
branch: defaultBranch,
remote: created.remote,
token: created.token,
});
} else {
await seedArtifactsReadme({
remote: created.remote,
token: created.token,
branch: defaultBranch,
projectName: name,
description,
fetchImpl: extensions.remoteFetch,
});
}
} catch (seedError) {
log.error('project_create.artifacts_seed_failed', {
projectId,
Expand All @@ -159,6 +188,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
action: 'orphaned_artifacts_repo_cleanup_failed',
});
}
if (importUrl && seedError instanceof AppError) throw seedError;
throw errors.internal('Failed to initialize Artifacts repository');
}

Expand Down
11 changes: 9 additions & 2 deletions apps/api/src/routes/workspaces/runtime-git-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import * as schema from '../../db/schema';
import type { Env } from '../../env';
import { log } from '../../lib/logger';
import { errors } from '../../middleware/error';
import {
createArtifactsRuntimeToken,
resolveArtifactsBackend,
} from '../../services/artifacts/backend';
import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app';
import {
GitHubCliPolicyError,
Expand All @@ -19,7 +23,6 @@ import {
requireGitLabUserAccessTokenResultForOwner,
verifyGitLabProjectAccess,
} from '../../services/gitlab';
import { resolveArtifactsBackend } from '../../services/hosted-git/backend';
import { boundArtifactsRepositoryHost } from '../../services/workspace-git-source';
import { assertRepositoryAccess } from '../projects/_helpers';
import {
Expand Down Expand Up @@ -237,7 +240,11 @@ runtimeRoutes.post('/:id/git-token', async (c) => {
const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const);
const repo = await artifacts.get(artifactsRepoId);
await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token');
const tokenResult = await repo.createToken(requestedScope, ttl);
const tokenResult = await createArtifactsRuntimeToken(c.env, repo, requestedScope, ttl, {
userId: workspace.userId,
workspaceId: workspace.workspaceId,
callbackGeneration: workspace.callbackGeneration ?? null,
});

// Strip ?expires= suffix from token for git credential use
const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext;
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/schemas/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const AgentDefaultEntrySchema = v.object({
const AgentDefaultsSchema = v.record(v.string(), AgentDefaultEntrySchema);

export const CreateProjectSchema = v.object({
importUrl: v.optional(v.string()),
name: v.string(),
description: v.optional(v.string()),
installationId: v.optional(v.string()),
Expand Down
19 changes: 18 additions & 1 deletion apps/api/src/selfhost/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,29 @@
* with the shared cloud-init generator as the frpc boot renderer.
*/
import { generateCloudInit } from '@simple-agent-manager/cloud-init';
import type { Hono } from 'hono';

import type { Env } from '../env';
import { mountHostedGitRoute } from './hosted-git';
import { hostedGitTokenRoutes } from './hosted-git/token-route';

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

import { installAnalyticsD1Sink } from './analytics';
import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry';
import { installSpeechEndpoints } from './speech';

export function withSelfHostBuild<T extends SharedWorkerEntry>(worker: T): T {
const mounted = new WeakSet<object>();

export function withSelfHostBuild<T extends SharedWorkerEntry>(
worker: T,
app: Hono<{ Bindings: Env }>
): T {
if (!mounted.has(app)) {
mountHostedGitRoute(app);
app.route('/api/projects', hostedGitTokenRoutes);
mounted.add(app);
}
installSpeechEndpoints();
installAnalyticsD1Sink();
return withReverseTunnel(worker, generateCloudInit);
Expand Down
52 changes: 52 additions & 0 deletions apps/api/src/selfhost/hosted-git.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* SAM-hosted git for the self-host build only: the `HostedGitRepo` Durable Object class (vendored
* dgit core and pako) and the git smart-HTTP route.
*
* Only the celld entry generated by scripts/selfhost/celld-project.ts imports this module. The
* Cloudflare build's entry is `src/index.ts`, which does not, so the Cloudflare bundle carries
* neither the class nor the vendored git code (tests/unit/selfhost/selfhost-only-modules.test.ts
* fails if the shared entry reaches them again). The celld config declares the `HOSTED_GIT`
* binding and the class's migration (`SELFHOST_DURABLE_OBJECTS` in
* scripts/selfhost/selfhost-durable-objects.ts); `apps/api/wrangler.toml` does not.
*
* Loading this module also registers SAM's own git server as the Artifacts fallback in the shared
* seam (`registerArtifactsBackendFallback` in `services/artifacts/backend.ts`), so project
* creation, browsing, git tokens and deletion use it when no Cloudflare Artifacts binding exists.
* The backend (`selfhost/hosted-git/local-backend.ts`) reaches the Durable Object only through the
* `HOSTED_GIT` namespace binding, which exists only on a self-host deployment.
*/
import type { Hono } from 'hono';

import { registerArtifactsBackendFallback } from '../services/artifacts/backend';
import type { HostedGitEnv as Env } from './hosted-git/env';
import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './hosted-git/http';
import { isLocalHostedGitActive, localHostedGitBackendFallback } from './hosted-git/local-backend';

export { HostedGitRepo } from './hosted-git/hosted-git-repo';

// Once, at module load: the celld entry imports this module before any request is served.
registerArtifactsBackendFallback(localHostedGitBackendFallback);

/**
* Mounts git smart HTTP for SAM-hosted repositories (`/git/<repo>.git/...`). Authenticated per
* request with a repository token, not a session cookie. Inactive (falls through to the 404
* handler) unless this install uses the local hosted git backend.
*
* Call it once, after `src/index.ts` has registered the shared routes. Hono runs every matching
* handler in registration order, and nothing `index.ts` registers after its global middleware
* matches `/git/*`, so the route runs after exactly the middleware every request gets (preview,
* pages proxy, workspace proxy, request logging, analytics, CORS), inside the request-scoped D1
* session of the default `fetch`. tests/unit/selfhost/hosted-git-route-order.test.ts pins that.
*/
export function mountHostedGitRoute(app: Hono<{ Bindings: Env }>): void {
// An empty app means this is not the instance index.ts registered on (for example a bundle that
// loaded app.ts twice); the route would then serve nothing and every clone would 404 silently.
if (app.routes.length === 0) {
throw new Error('mountHostedGitRoute: the app has no routes; mount after src/index.ts');
}
app.all(`${HOSTED_GIT_PATH_PREFIX}*`, async (c, next) => {
if (!isLocalHostedGitActive(c.env)) return next();
const response = await handleHostedGitRequest(c.req.raw, c.env);
return response ?? next();
});
}
7 changes: 7 additions & 0 deletions apps/api/src/selfhost/hosted-git/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { Env } from '../../env';

/** celld-only bindings; Cloudflare never configures these. */
export interface HostedGitEnv extends Env {
HOSTED_GIT?: DurableObjectNamespace;
HOSTED_GIT_BACKEND?: string;
}
Loading
Loading