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
43 changes: 43 additions & 0 deletions web/app/api/coderouter/accounts/[accountId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { removeAccount } from "../../../../../services/coderouter/accounts";
import { resolveCodeRouterRequestContext } from "../../../../../services/coderouter/requestContext";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

export function createDeleteAccountHandler(dependencies: {
readonly resolve: typeof resolveCodeRouterRequestContext;
readonly remove: (input: {
readonly teamId: string;
readonly accountId: string;
}) => ReturnType<typeof removeAccount>;
}) {
return async (
request: Request,
context: { params: Promise<{ accountId: string }> },
): Promise<Response> => {
const resolved = await dependencies.resolve(request, "manage");
if (!resolved.ok) return resolved.response;
const { accountId } = await context.params;
if (!UUID.test(accountId)) {
return Response.json({ error: "invalid_request" }, { status: 400 });
}
const result = await dependencies.remove({
teamId: resolved.value.team.teamId,
accountId,
});
if (!result.removed) {
return Response.json({ error: "not_found" }, { status: 404 });
}
return Response.json(result, {
headers: { "cache-control": "no-store" },
});
};
}

export const DELETE = createDeleteAccountHandler({
resolve: resolveCodeRouterRequestContext,
remove: async ({ teamId, accountId }) =>
await removeAccount(teamId, accountId),
});
42 changes: 37 additions & 5 deletions web/app/api/coderouter/accounts/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,41 @@ export const dynamic = "force-dynamic";
const MAX_BODY_BYTES = 128 * 1_024;

export async function GET(request: Request): Promise<Response> {
const startedAt = performance.now();
const authStartedAt = performance.now();
const resolved = await resolveCoderouterUsageTeam(request);
if (!resolved.ok) return resolved.response;
const accounts = await accountsWithUsage(resolved.teamId);
return Response.json(
{ teamId: resolved.teamId, accounts },
{ headers: { "cache-control": "no-store" } },
);
const authMs = performance.now() - authStartedAt;
const result = await accountsWithUsage(resolved.teamId);
const serializeStartedAt = performance.now();
const body = JSON.stringify({
teamId: resolved.teamId,
accounts: result.accounts,
usageAsOf: result.usageAsOf,
usageAgeSeconds: Math.max(
0,
Math.floor((Date.now() - result.usageGeneratedAtMs) / 1_000),
),
cacheMaxAgeSeconds: result.cacheMaxAgeSeconds,
});
const serializeMs = performance.now() - serializeStartedAt;
const serverTiming = [
timing("auth", authMs),
timing("rds", result.timing.rdsMs),
timing("provider", result.timing.providerMs),
timing("serialize", serializeMs),
timing("total", performance.now() - startedAt),
Comment on lines +32 to +37

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not report cached refresh time as current request time.

accountsWithUsage can return a cached result whose rdsMs and providerMs were captured during an earlier refresh. These lines emit those values in the current Server-Timing response, while total measures only the current request. A cache hit can therefore report RDS or provider time greater than total time.

Return cache-hit metadata separately. Emit refresh timings only when this request performed the refresh. Emit a cache metric for cache hits.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/app/api/coderouter/accounts/route.ts` around lines 32 - 37, Update the
Server-Timing construction in the accounts route to distinguish timings from the
current request versus a cached refresh: have accountsWithUsage return
cache-hit/refresh metadata separately, emit rds and provider timings only when
this request performed the refresh, and emit a cache metric for cache hits while
preserving auth, serialize, and total timings.

].join(", ");
return new Response(body, {
headers: {
"cache-control": "no-store",
"content-type": "application/json",
"server-timing": serverTiming,
// Vercel may reserve/strip Server-Timing at the edge. Keep the same
// standards-formatted value observable under a product header.
"x-coderouter-server-timing": serverTiming,
},
});
}

export async function POST(request: Request): Promise<Response> {
Expand Down Expand Up @@ -47,3 +75,7 @@ export async function POST(request: Request): Promise<Response> {
headers: { "cache-control": "no-store" },
});
}

function timing(name: string, duration: number): string {
return `${name};dur=${Math.max(0, duration).toFixed(1)}`;
}
7 changes: 6 additions & 1 deletion web/app/coderouter/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,15 @@ export default function CoderouterLandingPage() {
cr codex
</code>
<span className="select-none rounded-lg bg-black px-4 py-2 font-mono text-xs text-white">
coming soon
private beta
</span>
</div>

<p className="mt-5 max-w-xl font-mono text-[11px] leading-5 text-black/40">
Codex and OpenCode Go are available now. Pi support is experimental.
Claude Max and API-key routing are coming soon.
</p>
Comment on lines +38 to +45

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Move the new landing-page copy into the locale catalogs.

Lines 38, 43, and 44 add raw English user-facing text. Read these strings from next-intl or the established locale source. Add matching translations for every supported locale.

As per coding guidelines, “User-facing web UI text ... must use next-intl or another locale-specific runtime source and be represented for every supported locale.” As per path instructions, update every supported locale in web/i18n/routing.ts and web/messages/.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/app/coderouter/page.tsx` around lines 38 - 45, Move the landing-page
strings in the coderouter page, including “private beta” and the availability
paragraph, to the established next-intl locale source. Add keys and matching
translations for every locale listed in web/i18n/routing.ts under web/messages/,
then read them through the page’s existing localization mechanism instead of
hardcoded English text.

Sources: Coding guidelines, Path instructions


<div className="mt-20 grid max-w-3xl gap-px overflow-hidden rounded-xl border border-black/10 bg-black/10 sm:grid-cols-3">
{[
["01", "connect", "Add subscriptions with provider-native authorization."],
Expand Down
6 changes: 3 additions & 3 deletions web/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,9 @@ export const subrouterTenants = pgTable(
);

/**
* Non-secret routing metadata for CodeRouter accounts. Provider credentials
* live only in the Stack team server-metadata vault; Postgres coordinates
* selection and rotating refresh-token leases.
* Non-secret routing metadata for coderouter accounts. Provider credentials
* live in the envelope-encrypted coderouterCredentials table; this table
* coordinates selection and rotating refresh-token leases.
*/
export const coderouterAccounts = pgTable(
"coderouter_accounts",
Expand Down
41 changes: 41 additions & 0 deletions web/services/coderouter/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { randomUUID } from "node:crypto";
import {
findAccountByProviderIdentity,
deleteAccount,
insertAccountWithCredential,
listAccounts,
replaceAccountCredential,
withVaultLease,
} from "./repository";
import { encryptCredential } from "./encryption";
import type { CodeRouterCredential } from "./types";
import { deleteVaultCredential } from "./vault";
import { reportCoderouterFailure } from "./observability";

export async function addAccount(
teamId: string,
Expand Down Expand Up @@ -56,6 +60,43 @@ export async function addAccount(

export { listAccounts };

type RemoveAccountResult = {
removed: boolean;
lastAccount: boolean;
legacyCleanupPending: boolean;
};

export function createAccountRemover(dependencies: {
readonly deleteRuntime: typeof deleteAccount;
readonly deleteLegacy: typeof deleteVaultCredential;
readonly withLease: typeof withVaultLease;
readonly report: typeof reportCoderouterFailure;
}): (teamId: string, accountId: string) => Promise<RemoveAccountResult> {
return async (teamId, accountId) => {
const result = await dependencies.deleteRuntime({ teamId, accountId });
if (!result.removed) return { ...result, legacyCleanupPending: false };
try {
// Temporary rollback copy only. This call disappears after the migration
// cleanup window; failure cannot restore runtime access to the credential.
await dependencies.withLease(
teamId,
async () => await dependencies.deleteLegacy(teamId, accountId),
);
return { ...result, legacyCleanupPending: false };
} catch (error) {
dependencies.report("legacy_cleanup", error);
return { ...result, legacyCleanupPending: true };
Comment on lines +76 to +88

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file sizes =="
wc -l web/services/coderouter/accounts.ts web/app/api/coderouter/accounts/[accountId]/route.ts web/tests/coderouter-account-removal.test.ts web/services/coderouter/vault.ts web/services/coderouter/repository.ts 2>/dev/null || true

echo "== accounts.ts relevant section =="
sed -n '1,140p' web/services/coderouter/accounts.ts

echo "== route.ts =="
sed -n '1,90p' 'web/app/api/coderouter/accounts/[accountId]/route.ts'

echo "== tests relevant section =="
sed -n '1,180p' web/tests/coderouter-account-removal.test.ts

echo "== search legacy cleanup pending / reconciler / deleteVaultCredential =="
rg -n "legacyCleanupPending|clean.*legacy|deleteLegacy|deleteVault|legacy cleanup|legacy_cleanup|Delete.*Account|removeAccount" web -S || true

Repository: manaflow-ai/cmux

Length of output: 13763


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file sizes =="
wc -l web/services/coderouter/accounts.ts 'web/app/api/coderouter/accounts/[accountId]/route.ts' web/tests/coderouter-account-removal.test.ts web/services/coderouter/vault.ts web/services/coderouter/repository.ts 2>/dev/null || true

echo "== accounts.ts relevant section =="
sed -n '1,140p' web/services/coderouter/accounts.ts

echo "== route.ts =="
sed -n '1,90p' 'web/app/api/coderouter/accounts/[accountId]/route.ts'

echo "== tests relevant section =="
sed -n '1,180p' web/tests/coderouter-account-removal.test.ts

echo "== search legacy cleanup pending / reconciler / deleteVaultCredential =="
rg -n "legacyCleanupPending|clean.*legacy|deleteLegacy|deleteVault|legacy cleanup|legacy_cleanup|Delete.*Account|removeAccount" web -S || true

Repository: manaflow-ai/cmux

Length of output: 13763


Sensitive Data Exposure (CWE-459)

Reachability: Internal

Reachability path
● Entry
  web/app/api/coderouter/accounts/route.ts:8
  runtime
│
▼
● Hop
  web/app/api/coderouter/accounts/[accountId]/route.ts:9
  createDeleteAccountHandler
│
▼
● Sink
  web/services/coderouter/accounts.ts

Make failed legacy cleanup recoverable.

removeAccount() deletes the runtime account before the leased legacy vault cleanup, and cleanup failures return legacyCleanupPending: true. A retry DELETE reuses removeAccount(); when the runtime account is already absent, 404 is returned, so this path cannot retry the vault cleanup. Persist an idempotent cleanup job or retry legacy cleanup even after the runtime account is gone, and add a recovery test for failed legacy cleanup.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/services/coderouter/accounts.ts` around lines 76 - 88, Update
removeAccount() so a failed deleteLegacy cleanup remains recoverable when
deleteRuntime reports the account is already absent: persist an idempotent
legacy-cleanup job or invoke cleanup during the retry path before returning 404.
Preserve idempotency, ensure successful retries clear legacyCleanupPending, and
add a recovery test covering failure followed by a retry DELETE.

}
};
}

export const removeAccount = createAccountRemover({
deleteRuntime: deleteAccount,
deleteLegacy: deleteVaultCredential,
withLease: withVaultLease,
report: reportCoderouterFailure,
});

export function parseCredential(value: unknown): CodeRouterCredential | null {
if (!isRecord(value)) return null;
const provider = value.provider;
Expand Down
122 changes: 75 additions & 47 deletions web/services/coderouter/codexProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {
selectAccountForRequest,
} from "./repository";
import { freshCredential } from "./refresh";
import { fetchProviderRead } from "./providerFetch";
import { reportCoderouterFailure } from "./observability";

const CODEX_UPSTREAM = "https://chatgpt.com/backend-api/codex/responses";
const CODEX_MODELS_UPSTREAM = "https://chatgpt.com/backend-api/codex/models";
Expand Down Expand Up @@ -70,6 +72,10 @@ export async function proxyCodexRequest(request: Request): Promise<Response> {
}
}
if (upstream.status === 429) {
reportCoderouterFailure("provider_rate_limit", new Error("rate limited"), {
provider: "codex",
status: 429,
});
await markAccountCooldown(account.id, rateLimitDelay(upstream.headers));
continue;
}
Expand All @@ -95,60 +101,82 @@ export async function proxyCodexRequest(request: Request): Promise<Response> {
});
}

export async function proxyCodexModels(request: Request): Promise<Response> {
const token = bearerToken(request);
if (!token) return jsonError("unauthorized", 401);
const identity = await authenticateRouteToken(token);
if (!identity) return jsonError("unauthorized", 401);
type CodexModelsDependencies = {
readonly authenticate: typeof authenticateRouteToken;
readonly select: typeof selectAccountForRequest;
readonly credential: typeof freshCredential;
readonly cooldown: typeof markAccountCooldown;
readonly providerRead: typeof fetchProviderRead;
};

const attempted: string[] = [];
let upstream: Response | null = null;
for (let attempt = 0; attempt < 8; attempt++) {
const account = await selectAccountForRequest(
identity.teamId,
"codex",
attempted,
);
if (!account) break;
attempted.push(account.id);
let credential;
try {
credential = await freshCredential({
teamId: identity.teamId,
accountId: account.id,
expectedRevision: account.vaultRevision,
});
} catch {
continue;
export function createCodexModelsProxy(dependencies: CodexModelsDependencies) {
return async (request: Request): Promise<Response> => {
const token = bearerToken(request);
if (!token) return jsonError("unauthorized", 401);
const identity = await dependencies.authenticate(token);
if (!identity) return jsonError("unauthorized", 401);

const attempted: string[] = [];
let upstream: Response | null = null;
for (let attempt = 0; attempt < 8; attempt++) {
const account = await dependencies.select(
identity.teamId,
"codex",
attempted,
);
if (!account) break;
attempted.push(account.id);
let credential;
try {
credential = await dependencies.credential({
teamId: identity.teamId,
accountId: account.id,
expectedRevision: account.vaultRevision,
});
} catch {
continue;
}
Comment on lines +129 to +138

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Unclassified credential errors turn infrastructure outages into silent 503s. Both new account-selection loops catch every error from the credential dependency and continue to the next account. Neither one distinguishes a routing-skip condition (CodeRouterRefreshBusy, CodeRouterCredentialBroken) from an infrastructure fault such as a KMS outage, an RDS failure, or a decryption error. The caller receives no_usable_account (503) after the attempt bound, and reportCoderouterFailure never runs, so the outage produces no alert. proxyCodexRequest at web/services/coderouter/codexProxy.ts lines 49-56 already classifies the error correctly, so the two paths now disagree.

  • web/services/coderouter/codexProxy.ts#L129-L138: replace the bare catch with the tag check used by proxyCodexRequest, and rethrow anything that is not a routing-skip tag.
  • web/services/coderouter/opencodeProxy.ts#L90-L92: replace the bare catch in openCodeAccount with the same tag check, and report or rethrow anything else instead of skipping silently.

Extract the skip predicate into one shared helper in the CodeRouter service directory, then call it from all three loops. That keeps the entrypoints from diverging again.

As per coding guidelines: "When behavior has multiple entrypoints, implement one shared action path and verify every entrypoint rather than duplicating logic."

📍 Affects 2 files
  • web/services/coderouter/codexProxy.ts#L129-L138 (this comment)
  • web/services/coderouter/opencodeProxy.ts#L90-L92
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/services/coderouter/codexProxy.ts` around lines 129 - 138, Extract the
routing-skip tag predicate currently used by proxyCodexRequest into a shared
CodeRouter helper, then use it in proxyCodexRequest and both account-selection
loops. In codexProxy.ts at lines 129-138 and opencodeProxy.ts at lines 90-92,
skip only CodeRouterRefreshBusy and CodeRouterCredentialBroken errors; report or
rethrow all other credential failures so infrastructure errors reach the
existing failure handling.

Source: Coding guidelines

if (credential.provider !== "codex") continue;
const upstreamUrl = new URL(CODEX_MODELS_UPSTREAM);
upstreamUrl.search = new URL(request.url).search;
upstream = await dependencies.providerRead(() => fetch(upstreamUrl, {
headers: {
authorization: `Bearer ${credential.accessToken}`,
"chatgpt-account-id": credential.accountId,
originator: "codex_cli_rs",
"user-agent": request.headers.get("user-agent") ?? "coderouter",
},
cache: "no-store",
}));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (upstream.status === 429) {
reportCoderouterFailure("provider_rate_limit", new Error("rate limited"), {
provider: "codex",
status: 429,
});
await dependencies.cooldown(account.id, rateLimitDelay(upstream.headers));
continue;
}
break;
}
if (credential.provider !== "codex") continue;
const upstreamUrl = new URL(CODEX_MODELS_UPSTREAM);
upstreamUrl.search = new URL(request.url).search;
upstream = await fetch(upstreamUrl, {
if (!upstream) return jsonError("no_usable_account", 503);
return new Response(upstream.body, {
status: upstream.status,
headers: {
authorization: `Bearer ${credential.accessToken}`,
"chatgpt-account-id": credential.accountId,
originator: "codex_cli_rs",
"user-agent": request.headers.get("user-agent") ?? "coderouter",
"cache-control": "no-store",
"content-type": upstream.headers.get("content-type") ?? "application/json",
},
cache: "no-store",
});
if (upstream.status === 429) {
await markAccountCooldown(account.id, rateLimitDelay(upstream.headers));
continue;
}
break;
}
if (!upstream) return jsonError("no_usable_account", 503);
return new Response(upstream.body, {
status: upstream.status,
headers: {
"cache-control": "no-store",
"content-type": upstream.headers.get("content-type") ?? "application/json",
},
});
};
}

export const proxyCodexModels = createCodexModelsProxy({
authenticate: authenticateRouteToken,
select: selectAccountForRequest,
credential: freshCredential,
cooldown: markAccountCooldown,
providerRead: fetchProviderRead,
});

async function sendCodex(
request: Request,
forwardedHeaders: Headers,
Expand Down
Loading