From 95ef3bd3cd5e7240d1565f3de815319ea74cd82c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=96=87=E6=9D=B0?= Date: Thu, 19 Nov 2026 22:10:01 +0800 Subject: [PATCH 1/2] feat(server): enroll managed sandbox browsers --- apps/server/src/command.ts | 6 + apps/server/src/control.ts | 13 +- apps/server/src/identity.ts | 59 +++++- apps/server/src/server.ts | 45 +++++ apps/server/src/store.ts | 290 +++++++++++++++++++++++----- apps/server/tests/identity.test.ts | 182 +++++++++++++++++ docs/deployment.md | 8 + packages/protocol/src/management.ts | 14 ++ 8 files changed, 556 insertions(+), 61 deletions(-) diff --git a/apps/server/src/command.ts b/apps/server/src/command.ts index f900b4c..9ad3956 100644 --- a/apps/server/src/command.ts +++ b/apps/server/src/command.ts @@ -69,6 +69,11 @@ export async function serverMain(args = process.argv.slice(2)): Promise { !["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: { @@ -79,6 +84,7 @@ export async function serverMain(args = process.argv.slice(2)): Promise { 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"], diff --git a/apps/server/src/control.ts b/apps/server/src/control.ts index abfbffb..0d94ee6 100644 --- a/apps/server/src/control.ts +++ b/apps/server/src/control.ts @@ -776,11 +776,7 @@ export class ControlService { } async revokeAgentConnection(agentConnection: AgentConnection): Promise { 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, @@ -790,6 +786,13 @@ export class ControlService { "revoked", ); } + async stopAgentConnection(id: string, reason = "Agent connection revoked"): Promise { + await Promise.allSettled( + this.store + .agentConnectionSessions(id) + .map((session) => this.endAgentConnectionSession(session, reason)), + ); + } async invalidateDevice(deviceId: string): Promise { const connection = this.deviceConnections.get(deviceId); await this.stopDevice(deviceId, "Device credentials revoked", "revoked"); diff --git a/apps/server/src/identity.ts b/apps/server/src/identity.ts index d12b6f3..93b52e8 100644 --- a/apps/server/src/identity.ts +++ b/apps/server/src/identity.ts @@ -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"; @@ -9,6 +16,7 @@ export interface IdentityConfig { clientName?: string; clientSecret?: string; delegationEnabled?: boolean; + managedBrowserEnabled?: boolean; backchannelOrigin?: string; allowInsecureHttp?: boolean; } @@ -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) @@ -213,8 +224,12 @@ export class Identity { ); return { token: this.store.createLogin(user.id), returnTo: pending.returnTo }; } - /** 委托只接受特定受众、用途和客户端的短期签名令牌。 */ - async authenticate(token: string): Promise { + 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) @@ -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, @@ -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" || @@ -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 { + 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 { if (!this.enabled) throw new BridgeError("oidc_disabled", "External login is not configured", 404); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d6adfe5..ba01361 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -20,6 +20,7 @@ import { deviceAuthorizationDecisionSchema, deviceAuthorizationTokenRequestSchema, deviceAuthorizationCancelSchema, + managedBrowserRedeemSchema, adminCreateUserSchema, type AdminOverview, } from "@abridge/protocol"; @@ -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)); diff --git a/apps/server/src/store.ts b/apps/server/src/store.ts index 02e71c1..5f79f59 100644 --- a/apps/server/src/store.ts +++ b/apps/server/src/store.ts @@ -1,4 +1,4 @@ -import { createHash, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto"; +import { createHash, createHmac, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto"; import { chmodSync, mkdirSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { DatabaseSync, type SQLInputValue } from "node:sqlite"; @@ -10,6 +10,7 @@ import { type DeviceKind, type DeviceMetadata, type ConnectionPolicy, + type ManagedBrowserClaims, } from "@abridge/protocol"; import { validatePolicy } from "./policy.js"; import { @@ -43,9 +44,25 @@ const SCHEMA = [ "CREATE INDEX operation_owner ON operations(owner_id,created_at); CREATE INDEX audit_owner ON audit(owner_id,created_at); PRAGMA user_version=6;", ].join("\n"); +type ManagedBrowserIdentity = ManagedBrowserClaims & { + issuer: string; + client_id: string; + client_name?: string; +}; + +interface ManagedBrowser { + device_id: string; + agent_connection_id: string; + generation: number; + bootstrap_nonce: string | null; + bootstrap_expires_at: number | null; + stopped_at: number; +} + /** One SQL implementation. Compound state and audit mutations share a transaction. */ export class Store { private readonly db: DatabaseSync; + private readonly bootstrapKey = randomBytes(32); readonly path: string; constructor(path: string) { this.path = resolve(path); @@ -63,6 +80,14 @@ export class Store { "CREATE INDEX IF NOT EXISTS active_session_device ON control_sessions(device_id) WHERE status='active'; " + "CREATE INDEX IF NOT EXISTS active_session_agent_connection ON control_sessions(agent_connection_id) WHERE status='active';", ); + this.db.exec(`CREATE TABLE IF NOT EXISTS managed_browsers( + issuer TEXT NOT NULL, subject TEXT NOT NULL, client_id TEXT NOT NULL, sandbox_id TEXT NOT NULL, + generation INTEGER NOT NULL, device_id TEXT UNIQUE NOT NULL REFERENCES devices(id), + agent_connection_id TEXT UNIQUE NOT NULL REFERENCES agent_connections(id), + bootstrap_nonce TEXT, bootstrap_expires_at REAL, stopped_at INTEGER NOT NULL DEFAULT -1, + PRIMARY KEY(issuer,subject,client_id,sandbox_id), + FOREIGN KEY(issuer,subject) REFERENCES external_identities(issuer,subject) + );`); } close(): void { this.db.close(); @@ -162,45 +187,197 @@ export class Store { /** 以签发方和稳定主体首次开户,绝不按显示名称合并。 */ externalUser(issuer: string, subject: string, label: string, clientId?: string, clientName?: string): User { return this.transaction(() => { - const existing = this.one<{ user_id: string }>( - "SELECT user_id FROM external_identities WHERE issuer=? AND subject=?", - issuer, - subject, - ); - const user = existing ? this.user(existing.user_id)! : { id: identifier("usr"), username: "" }; - if (!existing) { - user.username = label.slice(0, 50) + " · " + user.id.slice(4); - this.run("INSERT INTO users VALUES(?,?,NULL,NULL,?)", user.id, user.username, nowSeconds()); - this.run("INSERT INTO external_identities VALUES(?,?,?)", issuer, subject, user.id); - } - if (!clientId) return user; - const linked = this.one<{ agent_connection_id: string }>( - "SELECT agent_connection_id FROM platform_connections WHERE issuer=? AND subject=? AND client_id=?", - issuer, - subject, - clientId, - ); - if (!linked) { - const agentConnectionId = identifier("agt"); - this.run( - "INSERT INTO agent_connections VALUES(?,?,?,?,NULL,NULL,NULL,?,NULL)", - agentConnectionId, - user.id, - (clientName ?? clientId) + " 平台连接", - JSON.stringify({ mode: "all", capabilities: [...CAPABILITIES], overrides: [] }), - nowSeconds(), - ); + const user = this.ensureExternalUser(issuer, subject, label); + if (clientId) + this.ensurePlatformConnection(user.id, issuer, subject, clientId, clientName, { + mode: "all", + capabilities: [...CAPABILITIES], + overrides: [], + }); + return user; + }); + } + private ensurePlatformConnection( + owner: string, + issuer: string, + subject: string, + clientId: string, + clientName: string | undefined, + policy: ConnectionPolicy, + ): void { + const linked = this.one( + "SELECT 1 FROM platform_connections WHERE issuer=? AND subject=? AND client_id=?", + issuer, + subject, + clientId, + ); + if (linked) return; + const connection = this.insertPlatformConnection(owner, (clientName ?? clientId) + " 平台连接", policy); + this.run("INSERT INTO platform_connections VALUES(?,?,?,?)", issuer, subject, clientId, connection); + } + private insertPlatformConnection(owner: string, name: string, policy: ConnectionPolicy): string { + const id = identifier("agt"); + this.run( + "INSERT INTO agent_connections VALUES(?,?,?,?,NULL,NULL,NULL,?,NULL)", + id, + owner, + name, + JSON.stringify(policy), + nowSeconds(), + ); + return id; + } + private ensureExternalUser(issuer: string, subject: string, label: string): User { + const existing = this.one<{ user_id: string }>( + "SELECT user_id FROM external_identities WHERE issuer=? AND subject=?", + issuer, + subject, + ); + if (existing) return this.user(existing.user_id)!; + const id = identifier("usr"); + const username = label.slice(0, 50) + " · " + id.slice(4); + this.run("INSERT INTO users VALUES(?,?,NULL,NULL,?)", id, username, nowSeconds()); + this.run("INSERT INTO external_identities VALUES(?,?,?)", issuer, subject, id); + return { id, username }; + } + + private managedBrowser(grant: ManagedBrowserIdentity): ManagedBrowser | undefined { + return this.one( + "SELECT * FROM managed_browsers WHERE issuer=? AND subject=? AND client_id=? AND sandbox_id=?", + grant.issuer, + grant.sub, + grant.client_id, + grant.sandbox_id, + ); + } + + provisionManagedBrowser(grant: ManagedBrowserIdentity): { device: Device; replaced: boolean } { + return this.transaction(() => { + const existing = this.managedBrowser(grant); + if (existing) { + const device = this.device(existing.device_id)!; + const connection = this.agentConnection(existing.agent_connection_id)!; + if (device.revoked_at !== null || connection.revoked_at !== null || grant.iat <= existing.stopped_at) + throw new BridgeError( + "managed_browser_revoked", + "Managed browser access was revoked or stopped", + 403, + ); + if (grant.generation < existing.generation) + throw new BridgeError("stale_sandbox", "The sandbox has been replaced", 409); + if (grant.generation === existing.generation) return { device, replaced: false }; + this.rotateDevice(device.id); this.run( - "INSERT INTO platform_connections VALUES(?,?,?,?)", - issuer, - subject, - clientId, - agentConnectionId, + "UPDATE managed_browsers SET generation=?,bootstrap_nonce=NULL,bootstrap_expires_at=NULL WHERE device_id=?", + grant.generation, + device.id, ); + return { device: this.device(device.id)!, replaced: true }; } - return user; + + const user = this.ensureExternalUser(grant.issuer, grant.sub, grant.sub); + const name = grant.name ?? "沙盒浏览器"; + const device = this.insertDevice(user.id, name, ["browser"], "browser", secretKey("device")); + const policy: ConnectionPolicy = { + mode: "selected", + devices: [{ device_id: device.id, capabilities: ["browser"] }], + }; + const connectionId = this.insertPlatformConnection(user.id, name, policy); + // A first-time human can also use the ordinary platform connection, scoped to this device. + if (grant.user_kind === "human") + this.ensurePlatformConnection( + user.id, + grant.issuer, + grant.sub, + grant.client_id, + grant.client_name, + policy, + ); + this.run( + "INSERT INTO managed_browsers(issuer,subject,client_id,sandbox_id,generation,device_id,agent_connection_id) VALUES(?,?,?,?,?,?,?)", + grant.issuer, + grant.sub, + grant.client_id, + grant.sandbox_id, + grant.generation, + device.id, + connectionId, + ); + return { device, replaced: false }; }); } + + private bootstrapToken(deviceId: string, nonce: string): string { + return createHmac("sha256", this.bootstrapKey) + .update(deviceId + ":" + nonce) + .digest("base64url"); + } + + issueManagedBrowserBootstrap(grant: ManagedBrowserIdentity): string { + const row = this.managedBrowser(grant); + if (!row || row.generation !== grant.generation || grant.iat <= row.stopped_at) + throw new BridgeError("stale_sandbox", "The sandbox binding changed", 409); + if (row.bootstrap_nonce && row.bootstrap_expires_at! > nowSeconds()) + return this.bootstrapToken(row.device_id, row.bootstrap_nonce); + const nonce = randomBytes(24).toString("base64url"); + this.run( + "UPDATE managed_browsers SET bootstrap_nonce=?,bootstrap_expires_at=? WHERE device_id=?", + nonce, + nowSeconds() + 300, + row.device_id, + ); + return this.bootstrapToken(row.device_id, nonce); + } + + redeemManagedBrowser(deviceId: string, token: string): { device: Device; key: string } { + return this.transaction(() => { + const row = this.one("SELECT * FROM managed_browsers WHERE device_id=?", deviceId); + const device = row && this.device(deviceId); + const connection = row && this.agentConnection(row.agent_connection_id); + if ( + !row?.bootstrap_nonce || + row.bootstrap_expires_at! <= nowSeconds() || + !device || + device.revoked_at !== null || + !connection || + connection.revoked_at !== null || + !timingSafeEqual( + Buffer.from(digest(token)), + Buffer.from(digest(this.bootstrapToken(deviceId, row.bootstrap_nonce))), + ) + ) + throw new BridgeError("invalid_grant", "Browser bootstrap credential is invalid or expired", 400); + this.run( + "UPDATE managed_browsers SET bootstrap_nonce=NULL,bootstrap_expires_at=NULL WHERE device_id=?", + deviceId, + ); + return { device, key: this.rotateDevice(deviceId) }; + }); + } + + managedBrowserConnection(grant: ManagedBrowserIdentity): AgentConnection | undefined { + const row = this.managedBrowser(grant); + if (!row || row.generation !== grant.generation || grant.iat <= row.stopped_at) return undefined; + const connection = this.agentConnection(row.agent_connection_id); + if (!connection || connection.revoked_at !== null || this.device(row.device_id)?.revoked_at !== null) + return undefined; + return connection; + } + + stopManagedBrowser(grant: ManagedBrowserIdentity): AgentConnection | undefined { + const row = this.managedBrowser(grant); + if (!row || row.generation !== grant.generation || grant.iat <= row.stopped_at) return undefined; + this.run( + "UPDATE managed_browsers SET stopped_at=?,bootstrap_nonce=NULL,bootstrap_expires_at=NULL WHERE device_id=?", + Math.floor(nowSeconds()), + row.device_id, + ); + return this.agentConnection(row.agent_connection_id); + } + + isManagedBrowserConnection(id: string): boolean { + return !!this.one("SELECT 1 FROM managed_browsers WHERE agent_connection_id=?", id); + } /** 仅解析已登录建立且尚有效的外部平台授权。 */ delegatedAgentConnection(issuer: string, subject: string, clientId: string): AgentConnection | undefined { const row = this.one<{ agent_connection_id: string }>( @@ -280,27 +457,34 @@ export class Store { capabilities: Capability[], kind: DeviceKind = "computer", ): { device: Device; key: string } { + const key = secretKey("device"); + return { device: this.transaction(() => this.insertDevice(owner, name, capabilities, kind, key)), key }; + } + private insertDevice( + owner: string, + name: string, + capabilities: Capability[], + kind: DeviceKind, + key: string, + ): Device { if (!capabilities.length || capabilities.some((cap) => !deviceCapabilities(kind).includes(cap))) throw new BridgeError("invalid_capabilities", "Capabilities do not match device kind", 422); let id: string; do { id = randomBytes(9).toString("base64url"); } while (this.device(id)); - const key = secretKey("device"); - this.transaction(() => { - this.run( - "INSERT INTO devices(id,owner_id,name,capabilities,token_digest,credential_version,epoch,created_at,kind) VALUES(?,?,?,?,?,1,0,?,?)", - id, - owner, - name, - JSON.stringify(capabilities), - digest(key), - nowSeconds(), - kind, - ); - this.audit(owner, id, null, null, "device_create", "changed"); - }); - return { device: this.device(id)!, key }; + this.run( + "INSERT INTO devices(id,owner_id,name,capabilities,token_digest,credential_version,epoch,created_at,kind) VALUES(?,?,?,?,?,1,0,?,?)", + id, + owner, + name, + JSON.stringify(capabilities), + digest(key), + nowSeconds(), + kind, + ); + this.audit(owner, id, null, null, "device_create", "changed"); + return this.device(id)!; } renameDevice(id: string, name: string): void { this.transaction(() => { @@ -386,6 +570,12 @@ export class Store { const agentConnection = this.agentConnection(id); if (!agentConnection || agentConnection.revoked_at !== null) throw new BridgeError("not_found", "Connection not found", 404); + if (this.isManagedBrowserConnection(id)) + throw new BridgeError( + "managed_connection", + "Managed browser connections have a fixed device policy", + 409, + ); const validated = validatePolicy(agentConnection.owner_id, policy, (deviceId) => this.device(deviceId)); this.transaction(() => { this.run( diff --git a/apps/server/tests/identity.test.ts b/apps/server/tests/identity.test.ts index dabed37..6a4461d 100644 --- a/apps/server/tests/identity.test.ts +++ b/apps/server/tests/identity.test.ts @@ -6,6 +6,8 @@ import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createHash } from "node:crypto"; +import { once } from "node:events"; +import { WebSocket } from "ws"; import { createServer } from "../src/server.js"; import { Identity, validateIdentityConfig } from "../src/identity.js"; @@ -16,6 +18,7 @@ async function fixture( foreignToken?: boolean; redirectToken?: boolean; delegationEnabled?: boolean; + managedBrowserEnabled?: boolean; allowInsecureHttp?: boolean; publicOrigin?: string; httpIssuer?: boolean; @@ -103,6 +106,7 @@ async function fixture( clientName: "Yuxi", clientSecret: "fixture-secret", delegationEnabled: options.delegationEnabled ?? true, + managedBrowserEnabled: options.managedBrowserEnabled, allowInsecureHttp: options.allowInsecureHttp, ...(options.backchannel ? { backchannelOrigin } : {}), }; @@ -219,6 +223,184 @@ test("OIDC login isolates stable identities, persists mapping and defaults platf } }); +test("managed browser registration, one-time redemption and MCP use share a scoped, revocable binding", async () => { + const f = await fixture({ managedBrowserEnabled: true }); + let socket: WebSocket | undefined; + const subject = "shadow-app-user"; + const root = "/api/managed-browsers/"; + const origin = "http://127.0.0.1:43219"; + const iat = Math.floor(Date.now() / 1000) - 1; + function grant(path: string, action: string, generation = 1, user = subject) { + return f.token(user, { + aud: origin + path, + purpose: "abridge-managed-browser-" + action, + sandbox_id: "workspace", + generation, + iat, + exp: iat + 60, + }); + } + const provision = async (generation = 1) => + f.server.app.inject({ + method: "POST", + url: root + "provision", + headers: { authorization: "Bearer " + (await grant(root + "provision", "provision", generation)) }, + }); + const redeem = (deviceId: string, token: string) => + f.server.app.inject({ + method: "POST", + url: root + "redeem", + payload: { device_id: deviceId, bootstrap_token: token }, + }); + try { + const wrong = await f.server.app.inject({ + method: "POST", + url: root + "provision", + headers: { authorization: "Bearer " + (await grant("/mcp", "delegation")) }, + }); + assert.equal(wrong.statusCode, 401); + assert.equal(f.server.store.users().length, 0); + + const first = await provision(); + assert.equal(first.statusCode, 200, first.body); + const registration = first.json<{ device_id: string; status: string; bootstrap_token: string }>(); + assert.equal(registration.status, "offline"); + assert.deepEqual((await provision()).json(), registration); + const { device_id: deviceId, bootstrap_token: bootstrap } = registration; + const issued = await redeem(deviceId, bootstrap); + assert.equal(issued.statusCode, 200, issued.body); + assert.equal((await redeem(deviceId, bootstrap)).statusCode, 400); + assert.equal(f.calls().tokenCalls, 0, "registration requires no browser login"); + + const key = issued.json<{ key: string }>().key; + const delegation = await grant("/mcp", "delegation"); + const connection = await f.identity.authenticate(delegation); + assert.ok(connection); + assert.equal(await f.identity.authenticate(await f.token(subject)), undefined); + assert.equal( + await f.identity.authenticate(await grant("/mcp", "delegation", 1, "other-app-user")), + undefined, + ); + f.server.store.createDevice(connection.owner_id, "Other browser", ["browser"], "browser"); + assert.throws(() => + f.server.store.updateAgentConnection( + connection.id, + connection.name, + { mode: "all", capabilities: ["browser"], overrides: [] }, + null, + ), + ); + + socket = new WebSocket(f.serverUrl.replace("http:", "ws:") + "/ws/browser", { + origin: "chrome-extension://" + "a".repeat(32), + }); + await once(socket, "open"); + const welcome = once(socket, "message"); + socket.send( + JSON.stringify({ + type: "hello", + protocol: "abridge/1", + platform: "Browser extension", + version: "0.4.23", + paused: false, + instance_id: "managed-test", + device_key: key, + capabilities: { browser: true }, + }), + ); + const [frame] = await welcome; + assert.equal(JSON.parse(frame.toString()).type, "welcome"); + assert.deepEqual((await provision()).json(), { + device_id: deviceId, + status: "online", + browser_origin: origin, + }); + + const list = await f.server.app.inject({ + method: "POST", + url: "/mcp", + headers: { authorization: "Bearer " + delegation, accept: "application/json, text/event-stream" }, + payload: { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "devices_list", arguments: {} }, + }, + }); + assert.equal(list.statusCode, 200, list.body); + const devices = JSON.parse(list.json().result.content[0].text).devices as { id: string }[]; + assert.deepEqual( + devices.map((device) => device.id), + [deviceId], + ); + const session = f.server.control.openSession(connection, deviceId, ["browser"]); + const reconnect = await provision(2); + assert.equal(reconnect.statusCode, 200, reconnect.body); + assert.equal(reconnect.json().device_id, deviceId); + assert.equal(f.server.store.authenticateDevice(key), undefined); + assert.notEqual(f.server.store.session(session.id)?.status, "active"); + assert.equal(await f.identity.authenticate(delegation), undefined); + assert.equal((await provision()).statusCode, 409); + const stop = await f.server.app.inject({ + method: "POST", + url: root + "stop", + headers: { authorization: "Bearer " + (await grant(root + "stop", "stop", 2)) }, + }); + assert.equal(stop.statusCode, 200, stop.body); + assert.equal(await f.identity.authenticate(await grant("/mcp", "delegation", 2)), undefined); + assert.equal((await redeem(deviceId, reconnect.json().bootstrap_token)).statusCode, 400); + f.server.store.revokeDevice(deviceId); + assert.equal((await provision(3)).statusCode, 403); + } finally { + socket?.terminate(); + await f.close(); + } +}); + +test("managed registration is disabled unless the issuer is explicitly trusted for it", async () => { + const f = await fixture(); + try { + const response = await f.server.app.inject({ method: "POST", url: "/api/managed-browsers/provision" }); + assert.equal(response.statusCode, 404); + } finally { + await f.close(); + } +}); + +test("first-time human managed registration links the normal platform delegation to only that browser", async () => { + const f = await fixture({ managedBrowserEnabled: true }); + try { + const path = "/api/managed-browsers/provision"; + const registration = await f.server.app.inject({ + method: "POST", + url: path, + headers: { + authorization: + "Bearer " + + (await f.token("managed-human", { + aud: "http://127.0.0.1:43219" + path, + purpose: "abridge-managed-browser-provision", + sandbox_id: "workspace", + generation: 1, + user_kind: "human", + })), + }, + }); + assert.equal(registration.statusCode, 200, registration.body); + const standard = await f.identity.authenticate(await f.token("managed-human")); + assert.ok(standard); + f.server.store.createDevice(standard.owner_id, "Other device", ["files"]); + assert.deepEqual( + f.server.control.devices(standard).map((device) => device.id), + [registration.json().device_id], + ); + f.server.store.revokeAgentConnection(standard.id); + assert.equal(await f.identity.authenticate(await f.token("managed-human")), undefined); + } finally { + await f.close(); + } +}); + test("OIDC rejects browser mismatch, nonce mismatch and external return paths", async () => { const f = await fixture(); try { diff --git a/docs/deployment.md b/docs/deployment.md index 2d7640c..1bb422e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -215,6 +215,14 @@ ABRIDGE_ALLOW_INSECURE_HTTP=true 数据库开发 schema 为 6,设备表保存最近上报的 `platform`、`version` 和可空的 `details`,操作表以内部 `key_hash` 唯一映射完整作用域去重键到短执行 ID。历史开发数据库不能直接打开;请备份并在隔离副本中明确转换或重新初始化,禁止用现有服务的数据目录试运行。更换 issuer 或 sub 会建立新身份,必须事先安排设备归属恢复,不能靠显示名自动合并。 +### 可选 Yuxi 托管沙盒浏览器 + +部署方可在已配好 Yuxi OIDC 和平台委托的 aBridge Server 设置 `ABRIDGE_MANAGED_BROWSER_ENABLED=true`。Yuxi 后端使用受信任提供方签发的短期注册凭据,为当前用户及其沙盒创建独立浏览器设备和作用于该设备的连接。注册不需要管理台会话。影子用户能否接入由 Yuxi 超级管理员在 Yuxi 中控制。 + +Yuxi 后端访问配置的 aBridge 服务地址。Cube 内的 Chromium 必须能访问 `ABRIDGE_PUBLIC_ORIGIN`,且中间代理必须转发浏览器 WebSocket。Cube 默认禁止访问私网地址,部署时应使用沙盒可达的 HTTPS 来源并在目标沙盒中验证 HTTPS 与 WSS。需要使用现有公网 HTTP 部署时,Yuxi 与 aBridge 均须显式启用 `ABRIDGE_ALLOW_INSECURE_HTTP=true`。托管镜像需要预装浏览器扩展,并只授予部署中指定的 aBridge 主机权限。 + +托管注册返回一次性启动凭据,由沙盒启动器向同一 aBridge 来源换取 Device Key 并交给扩展。注册请求的重试复用同一设备,暂停恢复沿用已绑定的 Profile。新的沙盒代次使旧设备凭据和会话失效。用户撤销设备或其托管连接后,自动注册不恢复旧授权。原有桌面和浏览器设备继续使用各自的连接策略。 + ### 应用内更新 在 macOS 菜单选择“检查更新…”,或在设置的“软件更新”中检查。发现正式新版后,依次点击“下载更新”和“安装并重启”。下载期间可以继续使用;安装会结束当前执行,保留设备绑定、能力开关、暂停状态和数据目录。应用必须位于可写的本机目录;从磁盘镜像或 App Translocation 启动时先移入 Applications。 diff --git a/packages/protocol/src/management.ts b/packages/protocol/src/management.ts index c36a393..893cfd0 100644 --- a/packages/protocol/src/management.ts +++ b/packages/protocol/src/management.ts @@ -13,6 +13,20 @@ import { export const managementUserSchema = z.object({ id: z.string(), username: z.string() }); export type UserView = z.infer; +export const managedBrowserClaimsSchema = z.object({ + sub: z.string().min(1).max(160), + sandbox_id: z.string().min(1).max(160), + generation: z.number().int().nonnegative(), + name: z.string().trim().min(1).max(100).optional(), + user_kind: z.enum(["human", "end_user"]).optional(), + iat: z.number().int().nonnegative(), +}); +export type ManagedBrowserClaims = z.infer; +export const managedBrowserRedeemSchema = z.strictObject({ + device_id: z.string().min(1).max(160), + bootstrap_token: z.string().regex(/^[A-Za-z0-9_-]{43}$/), +}); + export const deviceViewSchema = deviceMetadataSchema.extend({ id: z.string(), name: z.string(), From 08e1f1bfc3f9f801cb3f0f99e4596b65e0320cc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=96=87=E6=9D=B0?= Date: Fri, 20 Nov 2026 09:55:46 +0800 Subject: [PATCH 2/2] fix(server): reject stale managed browser connections --- apps/server/src/control.ts | 5 ++++- apps/server/tests/identity.test.ts | 21 ++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/server/src/control.ts b/apps/server/src/control.ts index 0d94ee6..21055d0 100644 --- a/apps/server/src/control.ts +++ b/apps/server/src/control.ts @@ -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(); diff --git a/apps/server/tests/identity.test.ts b/apps/server/tests/identity.test.ts index 6a4461d..bcb3d9f 100644 --- a/apps/server/tests/identity.test.ts +++ b/apps/server/tests/identity.test.ts @@ -334,7 +334,26 @@ test("managed browser registration, one-time redemption and MCP use share a scop [deviceId], ); const session = f.server.control.openSession(connection, deviceId, ["browser"]); - const reconnect = await provision(2); + const invalidate = f.server.control.invalidateDevice.bind(f.server.control); + const entered = Promise.withResolvers(); + const resume = Promise.withResolvers(); + const hold = mock.method(f.server.control, "invalidateDevice", async (id: string) => { + entered.resolve(); + await resume.promise; + await invalidate(id); + }); + const replacing = provision(2); + await entered.promise; + try { + const overlapping = await provision(2); + assert.equal(overlapping.statusCode, 200, overlapping.body); + assert.equal(overlapping.json().status, "offline"); + assert.ok(overlapping.json().bootstrap_token); + } finally { + resume.resolve(); + hold.mock.restore(); + } + const reconnect = await replacing; assert.equal(reconnect.statusCode, 200, reconnect.body); assert.equal(reconnect.json().device_id, deviceId); assert.equal(f.server.store.authenticateDevice(key), undefined);