eust-w 6d2dcebe65 feat(ide): clone the project into IDE workspaces and push back through Git (FR-H2)
While someone has a workspace open, the gateway asks the API for a 15-minute
write token for the project's platform repository on behalf of that person
(membership and role checked each time) and delivers it to the workspace
backend. The backend writes it to a Git config file outside the repository
(a memory volume in Kubernetes) that the clone includes, and on the first
delivery clones the target branch into a folder named after the project. The
workspace cannot mint credentials itself, so access ends with the last
session.

- People commit and push to the target branch like with any Git server; the
  platform only accepts fast-forwards, and the next wish starts from that
  commit (covered end to end in the local loop test).
- Commits are authored by whoever opened the latest session, from the name and
  email in their sign-in; their own git config overrides it.
- Only the gateway can reach the delivery endpoint: it needs Theia's
  connection token, and the gateway refuses the path for browsers.
- The provisioner pins the workspace to its repository and lets the pod reach
  the Git service; the Kubernetes baseline admits that traffic. External
  repositories are not cloned.
- The local shared Theia clones each project into its own folder.
- The Theia image installs Git, and its stage is named theia: the default
  build target of that Dockerfile is the gateway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:52:37 +08:00

147 lines
6.4 KiB
TypeScript

import { resolveGatewayTarget } from './domain/gateway-target.js';
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';
import { DomainError, type Actor, isProduction, type Run, type RunnerRegistration } from '@wishforge/contracts';
import { sameSecret } from './domain/policy.js';
import type { Store } from './db/store.js';
import { ServiceTokens } from './service-tokens.js';
import { dispatchTenants } from './tenants.js';
/** Name and email for display and commit authorship; text that could forge a Git identity is dropped. */
function profile(payload: JWTPayload): Pick<Actor, 'displayName' | 'email'> {
const text = (value: unknown) =>
typeof value === 'string' && value.trim() && value.length <= 200 && !/[\u0000-\u001f\u007f<>]/.test(value)
? value.trim()
: undefined;
const email = text(payload.email);
return {
displayName: text(payload.name) ?? text(payload.preferred_username),
email: email && payload.email_verified !== false && /^[^\s@]+@[^\s@]+$/.test(email) ? email : undefined,
};
}
export class Authenticator {
private jwks;
constructor(
private store: Store,
private env = process.env,
) {
if (env.OIDC_ISSUER) {
let issuer: URL;
try {
issuer = new URL(env.OIDC_ISSUER);
} catch {
throw new Error('OIDC issuer URL is invalid');
}
if (
issuer.username ||
issuer.password ||
issuer.search ||
issuer.hash ||
!['https:', 'http:'].includes(issuer.protocol) ||
(isProduction(env) && issuer.protocol !== 'https:')
)
throw new Error('OIDC issuer must be HTTPS in production and contain no credentials, query or fragment');
this.jwks = createRemoteJWKSet(new URL(`${env.OIDC_ISSUER.replace(/\/$/, '')}/protocol/openid-connect/certs`));
}
if (isProduction(env) && env.WF_DEV_AUTH_TOKEN)
throw new Error('Development authentication cannot be configured in production');
}
async authenticate(authorization?: string): Promise<Actor> {
if (!authorization?.startsWith('Bearer ')) throw new DomainError('UNAUTHENTICATED', 'Sign in to continue', 401);
const token = authorization.slice(7);
if (!isProduction(this.env) && this.env.WF_DEV_AUTH_TOKEN && sameSecret(token, this.env.WF_DEV_AUTH_TOKEN)) {
return {
...(await this.member('demo', '11111111-1111-4111-8111-111111111111', 'human', 'wishforge-web')),
displayName: 'Local Developer',
email: 'developer@wishforge.invalid',
};
}
if (!this.jwks || !this.env.OIDC_ISSUER || !this.env.OIDC_AUDIENCE)
throw new DomainError('UNAUTHENTICATED', 'OIDC is not configured', 401);
try {
const { payload } = await jwtVerify(token, this.jwks, {
issuer: this.env.OIDC_ISSUER,
audience: this.env.OIDC_AUDIENCE,
algorithms: ['RS256', 'ES256'],
});
if (
typeof payload.sub !== 'string' ||
typeof payload.tenant_id !== 'string' ||
typeof payload.exp !== 'number' ||
!Number.isFinite(payload.exp) ||
payload.exp * 1000 <= Date.now()
)
throw new Error('Missing identity claims');
const clientId = typeof payload.azp === 'string' ? payload.azp : undefined;
return {
...(await this.member(
payload.tenant_id,
payload.sub,
clientId === this.env.WF_WEB_CLIENT_ID ? 'human' : 'connector',
clientId,
)),
...profile(payload),
authExpiresAt: payload.exp * 1000,
};
} catch (error) {
if (error instanceof DomainError) throw error;
throw new DomainError('UNAUTHENTICATED', 'Access token is invalid or expired', 401);
}
}
/**
* The person behind an established IDE session, with their current membership, so the
* gateway keeps checking access (and sees revocation) after their access token expired.
*/
async sessionUser(tenantId: string, userId: string): Promise<Actor> {
return this.member(tenantId, userId, 'human');
}
private async member(tenantId: string, userId: string, kind: Actor['kind'], clientId?: string): Promise<Actor> {
const role = await this.store.read(tenantId, tx => tx.membership(userId));
if (!role) throw new DomainError('FORBIDDEN', 'Tenant membership is missing or revoked', 403);
return { tenantId, userId, role, kind, clientId };
}
async internal(authorization: string | undefined, tenant: string | undefined): Promise<Actor> {
if (!tenant || !dispatchTenants(this.env).includes(tenant))
throw new DomainError('FORBIDDEN', 'Service identity is not assigned to this tenant', 403);
const token = authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
const scoped = await new ServiceTokens(this.env.WF_INTERNAL_TOKEN_KEY).verify(token);
if (scoped && scoped.tenantId === tenant) {
const run = await this.store.transaction(tenant, tx => tx.get<Run>('run', scoped.runId!));
if (
run &&
run.executionGeneration === scoped.credentialId &&
!['paused', 'canceled', 'succeeded', 'failed'].includes(String(run.status))
)
return scoped;
throw new DomainError('UNAUTHENTICATED', 'Execution credential was revoked or superseded', 401);
}
const gateway = await resolveGatewayTarget(this.env, tenant);
if (gateway && sameSecret(token, gateway.token))
return { tenantId: tenant, userId: 'workspace-gateway', role: 'admin', kind: 'worker' };
// Verifiers only ever use run-scoped tokens; there is no static verifier identity.
for (const [name, kind] of [
['WF_WORKER_TOKEN', 'worker'],
['WF_DEPLOYER_TOKEN', 'deployer'],
] as const) {
if (this.env[name] && sameSecret(token, this.env[name]!))
return { tenantId: tenant, userId: kind, role: 'admin', kind };
}
const { createHash } = await import('node:crypto');
if (token.length >= 32) {
const hash = createHash('sha256').update(token).digest('hex');
const registration = await this.store.transaction(tenant, async tx =>
(await tx.list<RunnerRegistration>('runner')).find(r => r.tokenHash === hash && r.status === 'active'),
);
if (registration)
return {
tenantId: tenant,
userId: `runner:${registration.environmentId}`,
role: 'deployer',
kind: 'deployer',
clientId: registration.id,
};
}
throw new DomainError('UNAUTHENTICATED', 'Invalid service identity', 401);
}
}