Skip to content
Draft
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
6 changes: 6 additions & 0 deletions apps/server/src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export async function serverMain(args = process.argv.slice(2)): Promise<void> {
!["true", "false"].includes(process.env.ABRIDGE_ALLOW_INSECURE_HTTP)
)
throw new Error("ABRIDGE_ALLOW_INSECURE_HTTP must be true or false");
if (
process.env.ABRIDGE_MANAGED_BROWSER_ENABLED &&
!["true", "false"].includes(process.env.ABRIDGE_MANAGED_BROWSER_ENABLED)
)
throw new Error("ABRIDGE_MANAGED_BROWSER_ENABLED must be true or false");
const server = await createServer({
dbPath,
identity: {
Expand All @@ -79,6 +84,7 @@ export async function serverMain(args = process.argv.slice(2)): Promise<void> {
clientName: process.env.ABRIDGE_OIDC_CLIENT_NAME,
clientSecret: process.env.ABRIDGE_OIDC_CLIENT_SECRET,
delegationEnabled: process.env.ABRIDGE_DELEGATION_ENABLED === "true",
managedBrowserEnabled: process.env.ABRIDGE_MANAGED_BROWSER_ENABLED === "true",
},
adminToken: process.env.ABRIDGE_ADMIN_TOKEN,
resetAdminToken: values["reset-admin-token"],
Expand Down
18 changes: 12 additions & 6 deletions apps/server/src/control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,10 @@ export class ControlService {
const connection = this.deviceConnections.get(device.id),
now = this.mono();
const current = agentConnection ? this.currentAgentConnection(agentConnection) : undefined;
const online = !!connection && now - connection.heartbeatAt <= 30;
const online =
!!connection &&
connection.credentialVersion === device.credential_version &&
now - connection.heartbeatAt <= 30;
const capabilities = current
? deviceAccess(current, device).capabilities
: device.capabilities.filter((cap) => deviceCapabilities(device.kind).includes(cap)).sort();
Expand Down Expand Up @@ -776,11 +779,7 @@ export class ControlService {
}
async revokeAgentConnection(agentConnection: AgentConnection): Promise<void> {
this.store.revokeAgentConnection(agentConnection.id);
await Promise.allSettled(
this.store
.agentConnectionSessions(agentConnection.id)
.map((session) => this.endAgentConnectionSession(session, "Agent connection revoked")),
);
await this.stopAgentConnection(agentConnection.id);
this.store.audit(
agentConnection.owner_id,
null,
Expand All @@ -790,6 +789,13 @@ export class ControlService {
"revoked",
);
}
async stopAgentConnection(id: string, reason = "Agent connection revoked"): Promise<void> {
await Promise.allSettled(
this.store
.agentConnectionSessions(id)
.map((session) => this.endAgentConnectionSession(session, reason)),
);
}
async invalidateDevice(deviceId: string): Promise<void> {
const connection = this.deviceConnections.get(deviceId);
await this.stopDevice(deviceId, "Device credentials revoked", "revoked");
Expand Down
59 changes: 53 additions & 6 deletions apps/server/src/identity.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import * as oidc from "openid-client";
import { createRemoteJWKSet, jwtVerify, customFetch as jwksFetch, errors as joseErrors } from "jose";
import {
createRemoteJWKSet,
jwtVerify,
customFetch as jwksFetch,
errors as joseErrors,
type JWTPayload,
} from "jose";
import { managedBrowserClaimsSchema } from "@abridge/protocol";
import { digest, Store } from "./store.js";
import { BridgeError, type AgentConnection } from "./types.js";

Expand All @@ -9,6 +16,7 @@ export interface IdentityConfig {
clientName?: string;
clientSecret?: string;
delegationEnabled?: boolean;
managedBrowserEnabled?: boolean;
backchannelOrigin?: string;
allowInsecureHttp?: boolean;
}
Expand Down Expand Up @@ -83,9 +91,12 @@ export function validateIdentityConfig(config: IdentityConfig, origin: string |
config.clientName ||
config.clientSecret ||
config.delegationEnabled ||
config.managedBrowserEnabled ||
config.backchannelOrigin)
)
throw new Error("OIDC issuer is required");
if (config.managedBrowserEnabled && !config.delegationEnabled)
throw new Error("Managed browsers require OIDC platform delegation");
if (config.backchannelOrigin) {
const backchannel = new URL(config.backchannelOrigin);
if (!/^https?:$/.test(backchannel.protocol) || backchannel.origin !== config.backchannelOrigin)
Expand Down Expand Up @@ -213,8 +224,12 @@ export class Identity {
);
return { token: this.store.createLogin(user.id), returnTo: pending.returnTo };
}
/** 委托只接受特定受众、用途和客户端的短期签名令牌。 */
async authenticate(token: string): Promise<AgentConnection | undefined> {
get managedBrowserEnabled(): boolean {
return this.config.managedBrowserEnabled === true;
}

/** 委托只接受特定受众和客户端的短期签名令牌。调用方另行约束用途。 */
private async verifyPlatformToken(token: string, path: string) {
if (!this.config.delegationEnabled || !token || token.length > 16384) return undefined;
const config = await this.getConfiguration();
if (!this.keys)
Expand All @@ -226,7 +241,7 @@ export class Identity {
try {
({ payload } = await jwtVerify(token, this.keys, {
issuer: this.config.issuer!,
audience: this.origin + "/mcp",
audience: this.origin + path,
algorithms: ["RS256"],
requiredClaims: ["sub", "iat", "exp"],
maxTokenAge: 60,
Expand All @@ -246,7 +261,6 @@ export class Identity {
}
const now = Date.now() / 1000;
if (
payload.purpose !== "abridge-delegation" ||
payload.client_id !== this.config.clientId ||
typeof payload.iat !== "number" ||
typeof payload.exp !== "number" ||
Expand All @@ -255,7 +269,40 @@ export class Identity {
!payload.sub
)
return undefined;
return this.store.delegatedAgentConnection(this.config.issuer!, payload.sub, this.config.clientId!);
return payload;
}

private managedBrowser(payload: JWTPayload | undefined) {
if (!this.managedBrowserEnabled || !payload || typeof payload.aud !== "string") return undefined;
const result = managedBrowserClaimsSchema.safeParse(payload);
if (!result.success) return undefined;
return {
...result.data,
issuer: this.config.issuer!,
client_id: this.config.clientId!,
client_name: this.config.clientName?.trim(),
};
}

async authenticateManagedBrowser(token: string, action: "provision" | "stop") {
if (!this.managedBrowserEnabled)
throw new BridgeError("managed_browser_disabled", "Managed browsers are not enabled", 404);
const payload = await this.verifyPlatformToken(token, "/api/managed-browsers/" + action);
const managed = this.managedBrowser(payload);
if (!managed || payload?.purpose !== "abridge-managed-browser-" + action)
throw new BridgeError("unauthorized", "A managed browser grant is required", 401);
return managed;
}

async authenticate(token: string): Promise<AgentConnection | undefined> {
const payload = await this.verifyPlatformToken(token, "/mcp");
if (payload?.purpose === "abridge-delegation")
return this.store.delegatedAgentConnection(this.config.issuer!, payload.sub!, this.config.clientId!);
if (payload?.purpose === "abridge-managed-browser-delegation") {
const managed = this.managedBrowser(payload);
if (managed) return this.store.managedBrowserConnection(managed);
}
return undefined;
}
private getConfiguration(): Promise<oidc.Configuration> {
if (!this.enabled) throw new BridgeError("oidc_disabled", "External login is not configured", 404);
Expand Down
45 changes: 45 additions & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
deviceAuthorizationDecisionSchema,
deviceAuthorizationTokenRequestSchema,
deviceAuthorizationCancelSchema,
managedBrowserRedeemSchema,
adminCreateUserSchema,
type AdminOverview,
} from "@abridge/protocol";
Expand Down Expand Up @@ -497,6 +498,50 @@ export async function createServer(config: ServerConfig) {
request.headers.origin,
);
});
app.post("/api/managed-browsers/provision", async (request, reply) => {
const grant = await identity.authenticateManagedBrowser(bearer(request), "provision");
const { device, replaced } = store.provisionManagedBrowser(grant);
if (replaced) await control.invalidateDevice(device.id);
if (!store.managedBrowserConnection(grant))
throw new BridgeError("stale_sandbox", "The sandbox binding changed", 409);
const view = control.deviceView(device);
if (view.status === "online" && !view.available.browser)
throw new BridgeError("device_paused", "The managed browser is online but unavailable", 409);
const online = view.status === "online";
reply.header("Cache-Control", "no-store");
return {
device_id: device.id,
status: online ? "online" : "offline",
browser_origin: publicOrigin!.origin,
...(online ? {} : { bootstrap_token: store.issueManagedBrowserBootstrap(grant) }),
};
});
app.post("/api/managed-browsers/redeem", async (request, reply) => {
if (!identity.managedBrowserEnabled)
throw new BridgeError("managed_browser_disabled", "Managed browsers are not enabled", 404);
rateLimit(request, "managed-browser-redeem", 120);
const body = managedBrowserRedeemSchema.parse(request.body);
const existing = store.device(body.device_id);
if (existing && control.deviceView(existing).status === "online")
throw new BridgeError("invalid_grant", "Browser bootstrap credential is invalid or expired", 400);
const { device, key } = store.redeemManagedBrowser(body.device_id, body.bootstrap_token);
await control.invalidateDevice(device.id);
reply.header("Cache-Control", "no-store");
return {
device_id: device.id,
key,
kind: device.kind,
name: device.name,
capabilities: device.capabilities,
};
});
app.post("/api/managed-browsers/stop", async (request) => {
const grant = await identity.authenticateManagedBrowser(bearer(request), "stop");
const connection = store.stopManagedBrowser(grant);
if (connection) await control.stopAgentConnection(connection.id, "Managed browser access stopped");
return { ok: true };
});

app.all("/mcp", async (request, reply) => {
const token = bearer(request);
const agentConnection = store.authenticateAgent(token) ?? (await identity.authenticate(token));
Expand Down
Loading
Loading