Skip to content

Commit be7d86f

Browse files
feat(devices): Simlock setup uses each machine's agent-device token, checks tokens, and lists the pool through worker reconnects (pingdotgg#26706)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 221610f commit be7d86f

13 files changed

Lines changed: 444 additions & 39 deletions

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ export const RPC_REQUIRED_SCOPES = {
193193
[WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
194194
[WS_METHODS.deviceTestHost]: AuthSettingsWriteScope,
195195
[WS_METHODS.deviceEasAccount]: AuthSettingsWriteScope,
196+
[WS_METHODS.deviceSimlockIdentity]: AuthSettingsWriteScope,
196197
[WS_METHODS.deviceList]: AuthOrchestrationReadScope,
197198
[WS_METHODS.deviceOpen]: AuthOrchestrationOperateScope,
198199
[WS_METHODS.deviceClose]: AuthOrchestrationOperateScope,

‎apps/server/src/device/DeviceService.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ import {
2020
type DeviceEasAccount,
2121
DeviceEasAccountError,
2222
type DeviceEasAccountInput,
23+
type DeviceSimlockIdentity,
24+
DeviceSimlockIdentityError,
25+
type DeviceSimlockIdentityInput,
2326
type DeviceHostConfig,
2427
type EasDeviceHostConfig,
2528
type SimlockDeviceHostConfig,
@@ -69,6 +72,7 @@ import * as DeviceHost from "./DeviceHost.ts";
6972
import * as SshDeviceHost from "./SshDeviceHost.ts";
7073
import * as EasDeviceHost from "./EasDeviceHost.ts";
7174
import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
75+
import * as HostProcess from "@t3tools/shared/HostProcess";
7276
import { makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
7377
import * as Exit from "effect/Exit";
7478
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
@@ -142,6 +146,10 @@ export class DeviceService extends Context.Service<
142146
readonly easAccount: (
143147
input: DeviceEasAccountInput,
144148
) => Effect.Effect<DeviceEasAccount, DeviceEasAccountError>;
149+
/** Who a Simlock agent token is; without a gateway or token, this machine's agent-device's. */
150+
readonly simlockIdentity: (
151+
input: DeviceSimlockIdentityInput,
152+
) => Effect.Effect<DeviceSimlockIdentity, DeviceSimlockIdentityError>;
145153
/**
146154
* The agent-device flags that reach the device: its config and session,
147155
* and the id agent-device selects it by, which can differ from its id here.
@@ -1012,6 +1020,13 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
10121020
}),
10131021
);
10141022
}),
1023+
simlockIdentity: Effect.fn("DeviceService.simlockIdentity")(function () {
1024+
return Effect.fail(
1025+
new DeviceSimlockIdentityError({
1026+
reason: "Simlock hosts are unavailable in this device service.",
1027+
}),
1028+
);
1029+
}),
10151030
agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {
10161031
const host = yield* resolveHost(input.hostId);
10171032
const ready = yield* agentReadinessIfSupported(input.hostId);
@@ -1379,6 +1394,14 @@ export const make = Effect.gen(function* () {
13791394
);
13801395
hosts.set(host.id, instance);
13811396
configured.set(host.id, { config: host, scope: hostScope });
1397+
// Ask the gateway now, so a refused token shows in Settings before anyone opens a device.
1398+
if ((yield* settings.getSettings).enableDeviceSupport)
1399+
yield* instance
1400+
.platformAvailability("ios")
1401+
.pipe(
1402+
Effect.andThen(service.withLifecycleLock(service.refreshHosts)),
1403+
Effect.forkIn(hostScope),
1404+
);
13821405
continue;
13831406
}
13841407
if (host.kind === "eas") {
@@ -1478,9 +1501,62 @@ export const make = Effect.gen(function* () {
14781501
),
14791502
);
14801503

1504+
const simlockIdentity: DeviceService["Service"]["simlockIdentity"] = Effect.fn(
1505+
"DeviceService.simlockIdentity",
1506+
)(
1507+
function* (input) {
1508+
const environment = yield* HostProcess.Environment;
1509+
const gatewayUrl = (
1510+
input.gatewayUrl || SimlockDeviceHost.machineSimlockToken(environment)?.gatewayUrl
1511+
)?.replace(/\/$/, "");
1512+
if (!gatewayUrl)
1513+
return yield* new DeviceSimlockIdentityError({
1514+
reason: "This machine's agent-device does not point at a Simlock gateway.",
1515+
});
1516+
const savedHost =
1517+
input.hostId === undefined
1518+
? undefined
1519+
: (yield* settings.getSettings).simlockDeviceHosts.find(
1520+
(host) => host.id === input.hostId,
1521+
);
1522+
const token = input.agentToken
1523+
? { agentToken: input.agentToken, source: "entered" as const }
1524+
: SimlockDeviceHost.resolveSimlockToken(gatewayUrl, savedHost, environment);
1525+
if (!token)
1526+
return yield* new DeviceSimlockIdentityError({
1527+
reason: savedHost?.agentToken
1528+
? "The saved token is for another gateway. Enter one for this gateway."
1529+
: "No agent token for this gateway on this machine.",
1530+
});
1531+
const identity = yield* SimlockDeviceHost.simlockIdentity(gatewayUrl, token.agentToken).pipe(
1532+
Effect.mapError(
1533+
(cause) =>
1534+
new DeviceSimlockIdentityError({
1535+
reason: SimlockDeviceHost.describeGatewayFailure(
1536+
cause,
1537+
gatewayUrl,
1538+
token.source === "env" ? "this machine" : "this environment",
1539+
),
1540+
}),
1541+
),
1542+
);
1543+
if (identity.role !== "agent")
1544+
return yield* new DeviceSimlockIdentityError({
1545+
reason: `That is a ${identity.role} token. Create one with --role agent.`,
1546+
});
1547+
return { gatewayUrl, signedInAs: identity.name, tokenSource: token.source };
1548+
},
1549+
Effect.catchTags({
1550+
ServerSettingsError: () =>
1551+
Effect.fail(new DeviceSimlockIdentityError({ reason: "Could not read the saved token." })),
1552+
}),
1553+
Effect.provide(simlockContext),
1554+
);
1555+
14811556
return {
14821557
...service,
14831558
easAccount,
1559+
simlockIdentity,
14841560
};
14851561
});
14861562

‎apps/server/src/device/SimlockDeviceHost.test.ts‎

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it } from "@effect/vitest";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import type { SimlockDeviceHostConfig } from "@t3tools/contracts";
4+
import * as HostProcess from "@t3tools/shared/HostProcess";
45
import * as Effect from "effect/Effect";
56
import * as Fiber from "effect/Fiber";
67
import * as Deferred from "effect/Deferred";
@@ -62,14 +63,16 @@ const fakePool = (
6263
const commands: Array<{ readonly args: ReadonlyArray<string>; readonly cwd?: string }> = [];
6364
let leases = 0;
6465
let renewStatus = 200;
66+
let catalog: unknown = CATALOG;
6567
const http = HttpClient.make((request) =>
6668
Effect.sync(() => {
6769
const url = new URL(request.url);
6870
requests.push(`${request.method} ${url.pathname}`);
69-
expect(request.headers.authorization).toBe("Bearer agent-token");
7071
const json = (body: unknown, status = 200) =>
7172
HttpClientResponse.fromWeb(request, Response.json(body, { status }));
72-
if (url.pathname === "/v1/catalog") return json(CATALOG);
73+
if (request.headers.authorization !== "Bearer agent-token")
74+
return json({ error: { code: "UNAUTHENTICATED", message: "Unknown bearer token" } }, 401);
75+
if (url.pathname === "/v1/catalog") return json(catalog);
7376
if (url.pathname.endsWith("/renew")) return json({}, renewStatus);
7477
if (request.method === "DELETE") return json({}, 202);
7578
return json({}, 404);
@@ -134,6 +137,9 @@ const fakePool = (
134137
endLeases: () => {
135138
renewStatus = 404;
136139
},
140+
setCatalog: (next: unknown) => {
141+
catalog = next;
142+
},
137143
};
138144
});
139145

@@ -257,6 +263,84 @@ describe("Simlock device host", () => {
257263
}).pipe(Effect.scoped, Effect.provide(layer)),
258264
);
259265

266+
it.effect("reports its platforms unavailable when the gateway refuses the agent token", () =>
267+
Effect.gen(function* () {
268+
const pool = yield* fakePool();
269+
const scope = yield* Scope.make();
270+
const host = yield* makeHost(pool, config({ agentToken: "revoked" }), scope);
271+
expect(yield* host.platformAvailability("ios")).toEqual({
272+
platform: "ios",
273+
available: false,
274+
reason: "The Simlock gateway refused the agent token for Device pool.",
275+
});
276+
expect((yield* host.summary).platforms.every((platform) => !platform.available)).toBe(true);
277+
yield* Scope.close(scope, Exit.void);
278+
}).pipe(Effect.scoped, Effect.provide(layer)),
279+
);
280+
281+
it.effect("sends saved and machine tokens only to the gateway each belongs to", () =>
282+
Effect.gen(function* () {
283+
const pool = yield* fakePool();
284+
const availability = (baseUrl: string) =>
285+
Effect.gen(function* () {
286+
const scope = yield* Scope.make();
287+
const host = yield* makeHost(pool, config({ agentToken: "" }), scope).pipe(
288+
Effect.provideService(HostProcess.Environment, {
289+
AGENT_DEVICE_DAEMON_BASE_URL: baseUrl,
290+
AGENT_DEVICE_DAEMON_AUTH_TOKEN: "agent-token",
291+
}),
292+
);
293+
const result = yield* host.platformAvailability("ios");
294+
yield* Scope.close(scope, Exit.void);
295+
return result;
296+
});
297+
298+
expect(
299+
SimlockDeviceHost.resolveSimlockToken(
300+
"https://elsewhere.example:4700",
301+
config({ agentToken: "saved-token" }),
302+
{},
303+
),
304+
).toBeNull();
305+
306+
expect(yield* availability(`${GATEWAY}/v1/agent-device`)).toEqual({
307+
platform: "ios",
308+
available: true,
309+
});
310+
const requests = pool.requests.length;
311+
expect(yield* availability("https://elsewhere.example:4700/v1/agent-device")).toEqual({
312+
platform: "ios",
313+
available: false,
314+
reason: "Add an agent token for Device pool in Settings.",
315+
});
316+
expect(pool.requests).toHaveLength(requests);
317+
}).pipe(Effect.scoped, Effect.provide(layer)),
318+
);
319+
320+
it.effect("lists a platform again as soon as its workers return", () =>
321+
Effect.gen(function* () {
322+
const pool = yield* fakePool();
323+
const scope = yield* Scope.make();
324+
const host = yield* makeHost(pool, config(), scope);
325+
const ready = yield* host.ensureReady(() => Effect.void);
326+
pool.setCatalog({ platforms: [] });
327+
expect((yield* ready.devices.list).devices).toEqual([]);
328+
// Mid-reconnect, the gateway knows the Android models but no worker that makes them.
329+
pool.setCatalog({
330+
platforms: [
331+
CATALOG.platforms[0]!,
332+
{ ...CATALOG.platforms[1]!, modelWorkers: { "Pixel 9": [], "Pixel 8": [] } },
333+
],
334+
});
335+
const during = (yield* ready.devices.list).devices;
336+
expect(during.some((device) => device.platform === "android")).toBe(false);
337+
pool.setCatalog(CATALOG);
338+
const after = (yield* ready.devices.list).devices;
339+
expect(after.some((device) => device.platform === "android")).toBe(true);
340+
yield* Scope.close(scope, Exit.void);
341+
}).pipe(Effect.scoped, Effect.provide(layer)),
342+
);
343+
260344
it.effect("closes the session of a failed open so no lease is left behind", () =>
261345
Effect.gen(function* () {
262346
const pool = yield* fakePool({ failOpen: true });

0 commit comments

Comments
 (0)