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
246 changes: 246 additions & 0 deletions apps/server/src/cloud-android-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
import { randomUUID } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
import { BridgeError } from "./types.js";

type PendingState = "provisioning" | "restoring" | "stopping" | "releasing";
type WorkspaceStatus = PendingState | "running" | "stopped" | "released";

interface Workspace {
id: string;
owner_id: string;
handset_id: string | null;
status: WorkspaceStatus;
operation_id: string | null;
carrier_id: string | null;
}

const workspaceColumns = "id, owner_id, handset_id, status, operation_id, carrier_id";

export function isCloudAndroidCarrier(db: DatabaseSync, deviceId: string): boolean {
return !!db.prepare("SELECT 1 FROM cloud_android_carriers WHERE id=?").get(deviceId);
}

export class CloudAndroidStore {
constructor(private readonly db: DatabaseSync) {
db.exec(`
CREATE TABLE IF NOT EXISTS cloud_android_handsets(
device_id TEXT PRIMARY KEY REFERENCES devices(id),
credential_version INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS cloud_android_workspaces(
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES users(id),
handset_id TEXT UNIQUE REFERENCES devices(id),
status TEXT NOT NULL CHECK(status IN (
'provisioning', 'restoring', 'stopping', 'releasing', 'running', 'stopped', 'released'
)),
operation_id TEXT UNIQUE,
carrier_id TEXT REFERENCES cloud_android_carriers(id)
);
CREATE UNIQUE INDEX IF NOT EXISTS cloud_android_active_owner
ON cloud_android_workspaces(owner_id) WHERE status<>'released';
CREATE TABLE IF NOT EXISTS cloud_android_carriers(
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL REFERENCES cloud_android_workspaces(id),
operation_id TEXT UNIQUE NOT NULL
);
`);
}

/** Called by trusted physical handset enrollment after verifying device identity. */
authorizeHandset(ownerId: string, handsetId: string): void {
const result = this.db
.prepare(
`INSERT INTO cloud_android_handsets(device_id, credential_version)
SELECT id, credential_version FROM devices
WHERE id=? AND owner_id=? AND revoked_at IS NULL AND kind='computer' AND platform='android'
AND NOT EXISTS (SELECT 1 FROM cloud_android_carriers WHERE id=devices.id)
ON CONFLICT(device_id) DO UPDATE SET credential_version=excluded.credential_version`,
)
.run(handsetId, ownerId);
if (!result.changes) throw new BridgeError("not_found", "Eligible handset not found", 404);
}

getForHandset(ownerId: string, handsetId: string): Workspace | undefined {
return this.db
.prepare(
`SELECT w.id, w.owner_id, w.handset_id, w.status, w.operation_id, w.carrier_id
FROM cloud_android_workspaces w
JOIN cloud_android_handsets h ON h.device_id=w.handset_id
JOIN devices d ON d.id=h.device_id
WHERE w.owner_id=? AND d.owner_id=w.owner_id AND w.handset_id=? AND d.revoked_at IS NULL
AND h.credential_version=d.credential_version`,
)
.get(ownerId, handsetId) as unknown as Workspace | undefined;
}

/** Callers must authenticate both the account and the enrolled handset. */
requestProvision(ownerId: string, handsetId: string): Workspace {
return this.transaction(() => {
const current = this.getForHandset(ownerId, handsetId);
if (current) {
if (current.status === "releasing")
throw new BridgeError("workspace_conflict", "Workspace is being released", 409);
return current;
}
const handset = this.db
.prepare(
`SELECT 1 FROM devices d JOIN cloud_android_handsets h ON h.device_id=d.id
WHERE d.id=? AND d.owner_id=? AND d.revoked_at IS NULL AND d.credential_version=h.credential_version`,
)
.get(handsetId, ownerId);
if (!handset) throw new BridgeError("not_found", "Enrolled handset not found", 404);
if (
this.db
.prepare(
"SELECT 1 FROM cloud_android_workspaces WHERE (owner_id=? OR handset_id=?) AND status<>'released'",
)
.get(ownerId, handsetId)
)
throw new BridgeError("workspace_conflict", "Workspace already has a bound handset", 409);
const id = randomUUID();
this.db
.prepare(
`INSERT INTO cloud_android_workspaces(id,owner_id,handset_id,status,operation_id)
VALUES(?,?,?,'provisioning',?)`,
)
.run(id, ownerId, handsetId, randomUUID());
return this.workspace(id)!;
});
}

requestStop(workspaceId: string, ownerId: string, handsetId: string): Workspace {
return this.request(workspaceId, ownerId, handsetId, "stopping", ["running"]);
}

requestRestore(workspaceId: string, ownerId: string, handsetId: string): Workspace {
return this.request(workspaceId, ownerId, handsetId, "restoring", ["stopped"]);
}

requestRelease(workspaceId: string, ownerId: string, handsetId: string): Workspace {
return this.request(workspaceId, ownerId, handsetId, "releasing", [
"provisioning",
"restoring",
"running",
"stopping",
"stopped",
]);
}

/** Trusted operator recovery when the workspace's original handset can no longer prove its identity. */
requestOperatorRelease(workspaceId: string): Workspace {
return this.transaction(() => {
const workspace = this.workspace(workspaceId);
if (!workspace) throw new BridgeError("not_found", "Workspace not found", 404);
if (workspace.status === "released" || workspace.status === "releasing") return workspace;
return this.startOperation(workspace.id, "releasing");
});
}

/** Trusted runtime reserves a new carrier ID before creating its device record. */
reserveCarrier(workspaceId: string, operationId: string): string {
return this.transaction(() => {
const workspace = this.pending(workspaceId, operationId);
if (workspace.status !== "provisioning" && workspace.status !== "restoring")
throw new BridgeError("workspace_conflict", "Operation cannot reserve a carrier", 409);
const existing = this.db
.prepare("SELECT id FROM cloud_android_carriers WHERE operation_id=?")
.get(operationId);
if (existing) return existing.id as string;
let id: string;
do {
id = randomUUID();
} while (
this.db.prepare("SELECT 1 FROM devices WHERE id=?").get(id) ||
isCloudAndroidCarrier(this.db, id)
);
this.db.prepare("INSERT INTO cloud_android_carriers VALUES(?,?,?)").run(id, workspaceId, operationId);
this.db.prepare("UPDATE cloud_android_workspaces SET carrier_id=? WHERE id=?").run(id, workspaceId);
return id;
});
}

/** Trusted runtime confirms that the requested action has finished. */
complete(workspaceId: string, operationId: string): Workspace {
return this.transaction(() => {
const workspace = this.pending(workspaceId, operationId);
if (workspace.status === "releasing") {
this.db
.prepare(
`UPDATE cloud_android_workspaces SET status='released',operation_id=NULL,carrier_id=NULL,
handset_id=NULL WHERE id=?`,
)
.run(workspaceId);
} else if (workspace.status === "stopping") {
this.db
.prepare(
"UPDATE cloud_android_workspaces SET status='stopped',operation_id=NULL,carrier_id=NULL WHERE id=?",
)
.run(workspaceId);
} else {
if (
!this.db
.prepare(
`SELECT 1 FROM cloud_android_carriers c JOIN devices d ON d.id=c.id
WHERE c.id=? AND c.operation_id=? AND d.owner_id=? AND d.kind='computer' AND d.revoked_at IS NULL`,
)
.get(workspace.carrier_id, operationId, workspace.owner_id)
)
throw new BridgeError("workspace_conflict", "Current carrier is not registered", 409);
this.db
.prepare("UPDATE cloud_android_workspaces SET status='running',operation_id=NULL WHERE id=?")
.run(workspaceId);
}
return this.workspace(workspaceId)!;
});
}

private request(
id: string,
ownerId: string,
handsetId: string,
status: PendingState,
from: WorkspaceStatus[],
): Workspace {
return this.transaction(() => {
const workspace = this.getForHandset(ownerId, handsetId);
if (!workspace || workspace.id !== id) throw new BridgeError("not_found", "Workspace not found", 404);
if (workspace.status === status) return workspace;
if (!from.includes(workspace.status))
throw new BridgeError("workspace_conflict", "Workspace has an incompatible lifecycle state", 409);
return this.startOperation(id, status);
});
}

private startOperation(id: string, status: PendingState): Workspace {
this.db
.prepare("UPDATE cloud_android_workspaces SET status=?,operation_id=? WHERE id=?")
.run(status, randomUUID(), id);
return this.workspace(id)!;
}

private workspace(id: string): Workspace | undefined {
return this.db
.prepare(`SELECT ${workspaceColumns} FROM cloud_android_workspaces WHERE id=?`)
.get(id) as unknown as Workspace | undefined;
}

private pending(id: string, operationId: string): Workspace {
const workspace = this.workspace(id);
if (!workspace || workspace.operation_id !== operationId)
throw new BridgeError("workspace_conflict", "Cloud Android operation is no longer current", 409);
return workspace;
}

private transaction<T>(action: () => T): T {
this.db.exec("BEGIN IMMEDIATE");
try {
const result = action();
this.db.exec("COMMIT");
return result;
} catch (error) {
this.db.exec("ROLLBACK");
throw error;
}
}
}
30 changes: 30 additions & 0 deletions apps/server/src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,36 @@ export async function serverMain(args = process.argv.slice(2)): Promise<void> {
dataDir = resolve(values["data-dir"] ?? defaultDataDirectory()),
dbPath = resolve(values.db ?? process.env.ABRIDGE_DB ?? join(dataDir, "server", "server.db"));

if (command === "cloud-android") {
const [, action, ownerId, handsetId] = positionals;
if (
positionals.length !== 4 ||
!ownerId ||
!handsetId ||
(action !== "enroll" && action !== "provision" && action !== "status")
)
throw new Error(
"Usage: abridge cloud-android <enroll|provision|status> --db <file> -- <owner-id> <handset-id>",
);
if (!values.db) throw new Error("cloud-android requires an explicit --db for the development database");
await access(dbPath);
const { Store } = await import("./store.js");
const store = new Store(dbPath);
try {
if (action === "enroll") {
store.cloudAndroid.authorizeHandset(ownerId, handsetId);
} else {
const workspace =
action === "provision"
? store.cloudAndroid.requestProvision(ownerId, handsetId)
: store.cloudAndroid.getForHandset(ownerId, handsetId);
console.log(JSON.stringify(workspace ?? null));
}
} finally {
store.close();
}
return;
}
if (command !== "serve") throw new Error(`Unknown command: ${command}`);
const { createServer } = await import("./server.js");
const port = Number(values.port ?? process.env.ABRIDGE_PORT ?? 8765);
Expand Down
29 changes: 23 additions & 6 deletions apps/server/src/control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,15 +163,23 @@ export class ControlService {
authorizedDevice(agentConnection: AgentConnection, deviceId: string): Device {
const current = this.currentAgentConnection(agentConnection),
device = this.store.device(deviceId);
if (!device || device.owner_id !== current.owner_id || deviceAccess(current, device).access !== "allowed")
if (
!device ||
this.store.isCloudAndroidCarrier(deviceId) ||
device.owner_id !== current.owner_id ||
deviceAccess(current, device).access !== "allowed"
)
throw new BridgeError("not_found", "Device does not exist or is not granted", 404);
return device;
}
devices(agentConnection: AgentConnection): DeviceView[] {
const current = this.currentAgentConnection(agentConnection);
return this.store
.devices(current.owner_id)
.filter((device) => deviceAccess(current, device).access === "allowed")
.filter(
(device) =>
!this.store.isCloudAndroidCarrier(device.id) && deviceAccess(current, device).access === "allowed",
)
.map((device) => this.deviceView(device, current));
}
deviceView(
Expand Down Expand Up @@ -416,6 +424,7 @@ export class ControlService {
agentConnection.revoked_at !== null ||
agentConnectionExpired(agentConnection, this.now()) ||
!device ||
this.store.isCloudAndroidCarrier(device.id) ||
!connection ||
connection.paused ||
this.mono() - connection.heartbeatAt > 30 ||
Expand Down Expand Up @@ -481,7 +490,11 @@ export class ControlService {
private ownedSession(agentConnection: AgentConnection, id: string): ControlSession {
this.currentAgentConnection(agentConnection);
const session = this.store.session(id);
if (!session || session.agent_connection_id !== agentConnection.id)
if (
!session ||
session.agent_connection_id !== agentConnection.id ||
this.store.isCloudAndroidCarrier(session.device_id)
)
throw new BridgeError("not_found", "Session does not exist or is not granted", 404);
return session;
}
Expand Down Expand Up @@ -519,7 +532,8 @@ export class ControlService {
return { session_id: id, status: "stopped" };
}
taskDeviceReady(device: Device): boolean {
if (!this.deviceConnections.get(device.id)?.taskSessionAck) return false;
if (this.store.isCloudAndroidCarrier(device.id) || !this.deviceConnections.get(device.id)?.taskSessionAck)
return false;
const view = this.deviceView(device);
return view.available.screen === true && view.available.input === true;
}
Expand Down Expand Up @@ -922,7 +936,7 @@ export class ControlService {
},
devices: this.store
.devices(agentConnection.owner_id)
.filter((device) => device.revoked_at === null)
.filter((device) => device.revoked_at === null && !this.store.isCloudAndroidCarrier(device.id))
.map((device) => {
const access = deviceAccess(agentConnection, device),
view = this.deviceView(device);
Expand Down Expand Up @@ -962,7 +976,10 @@ export class ControlService {
await Promise.allSettled(
this.store.agentConnectionSessions(agentConnection.id).map(async (session) => {
const device = this.store.device(session.device_id);
const capabilities = device ? deviceAccess(updated, device).capabilities : [];
const capabilities =
device && !this.store.isCloudAndroidCarrier(device.id)
? deviceAccess(updated, device).capabilities
: [];
if (
agentConnectionExpired(updated, this.now()) ||
session.capabilities.some((cap) => !capabilities.includes(cap))
Expand Down
9 changes: 7 additions & 2 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ export async function createServer(config: ServerConfig) {
function owned(request: FastifyRequest): Device {
const user = account(request),
device = store.device((request.params as { id: string }).id);
if (!device || device.owner_id !== user.id) throw new BridgeError("not_found", "Device not found", 404);
if (!device || device.owner_id !== user.id || store.isCloudAndroidCarrier(device.id))
throw new BridgeError("not_found", "Device not found", 404);
return device;
}
function rateLimit(request: FastifyRequest, scope = "signin", limit = 10): void {
Expand Down Expand Up @@ -315,6 +316,7 @@ export async function createServer(config: ServerConfig) {
requireAdmin(request);
const devicesByOwner = new Map<string, AdminOverview["users"][number]["devices"]>();
for (const device of store.activeDevices()) {
if (store.isCloudAndroidCarrier(device.id)) continue;
const view = control.deviceView(device);
const devices = devicesByOwner.get(device.owner_id) ?? [];
devices.push({
Expand Down Expand Up @@ -400,7 +402,10 @@ export async function createServer(config: ServerConfig) {
});
app.get("/api/me", async (request) => account(request));
app.get("/api/devices", async (request) => ({
devices: store.devices(account(request).id).map((device) => control.deviceView(device)),
devices: store
.devices(account(request).id)
.filter((device) => !store.isCloudAndroidCarrier(device.id))
.map((device) => control.deviceView(device)),
}));
app.post("/api/devices", async (request) => {
const user = account(request),
Expand Down
Loading
Loading