Skip to content

Commit 172756f

Browse files
feat(devices): Simlock hosts find this machine's agent-device gateway and token, and check each token as you enter it
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3676438 commit 172756f

11 files changed

Lines changed: 316 additions & 30 deletions

File tree

‎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: 66 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);
@@ -1486,9 +1501,60 @@ export const make = Effect.gen(function* () {
14861501
),
14871502
);
14881503

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 saved =
1517+
input.hostId === undefined
1518+
? ""
1519+
: ((yield* settings.getSettings).simlockDeviceHosts.find(
1520+
(host) => host.id === input.hostId,
1521+
)?.agentToken ?? "");
1522+
const token = input.agentToken
1523+
? { agentToken: input.agentToken, source: "entered" as const }
1524+
: SimlockDeviceHost.resolveSimlockToken(gatewayUrl, saved, environment);
1525+
if (!token)
1526+
return yield* new DeviceSimlockIdentityError({
1527+
reason: "No agent token for this gateway on this machine.",
1528+
});
1529+
const identity = yield* SimlockDeviceHost.simlockIdentity(gatewayUrl, token.agentToken).pipe(
1530+
Effect.mapError(
1531+
(cause) =>
1532+
new DeviceSimlockIdentityError({
1533+
reason: SimlockDeviceHost.describeGatewayFailure(
1534+
cause,
1535+
gatewayUrl,
1536+
token.source === "env" ? "this machine" : "this environment",
1537+
),
1538+
}),
1539+
),
1540+
);
1541+
if (identity.role !== "agent")
1542+
return yield* new DeviceSimlockIdentityError({
1543+
reason: `That is a ${identity.role} token. Create one with --role agent.`,
1544+
});
1545+
return { gatewayUrl, signedInAs: identity.name, tokenSource: token.source };
1546+
},
1547+
Effect.catchTags({
1548+
ServerSettingsError: () =>
1549+
Effect.fail(new DeviceSimlockIdentityError({ reason: "Could not read the saved token." })),
1550+
}),
1551+
Effect.provide(simlockContext),
1552+
);
1553+
14891554
return {
14901555
...service,
14911556
easAccount,
1557+
simlockIdentity,
14921558
};
14931559
});
14941560

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

Lines changed: 32 additions & 0 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";
@@ -274,6 +275,37 @@ describe("Simlock device host", () => {
274275
}).pipe(Effect.scoped, Effect.provide(layer)),
275276
);
276277

278+
it.effect("uses this machine's agent-device token only for the gateway it targets", () =>
279+
Effect.gen(function* () {
280+
const pool = yield* fakePool();
281+
const availability = (baseUrl: string) =>
282+
Effect.gen(function* () {
283+
const scope = yield* Scope.make();
284+
const host = yield* makeHost(pool, config({ agentToken: "" }), scope).pipe(
285+
Effect.provideService(HostProcess.Environment, {
286+
AGENT_DEVICE_DAEMON_BASE_URL: baseUrl,
287+
AGENT_DEVICE_DAEMON_AUTH_TOKEN: "agent-token",
288+
}),
289+
);
290+
const result = yield* host.platformAvailability("ios");
291+
yield* Scope.close(scope, Exit.void);
292+
return result;
293+
});
294+
295+
expect(yield* availability(`${GATEWAY}/v1/agent-device`)).toEqual({
296+
platform: "ios",
297+
available: true,
298+
});
299+
const requests = pool.requests.length;
300+
expect(yield* availability("https://elsewhere.example:4700/v1/agent-device")).toEqual({
301+
platform: "ios",
302+
available: false,
303+
reason: "Add an agent token for Device pool in Settings.",
304+
});
305+
expect(pool.requests).toHaveLength(requests);
306+
}).pipe(Effect.scoped, Effect.provide(layer)),
307+
);
308+
277309
it.effect("closes the session of a failed open so no lease is left behind", () =>
278310
Effect.gen(function* () {
279311
const pool = yield* fakePool({ failOpen: true });

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

Lines changed: 81 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,75 @@ const parseCatalogId = (id: string) => {
8484
const platformVersion = (platform: DevicePlatform, runtime: string | undefined) =>
8585
`${platform === "ios" ? "iOS" : "Android"}${runtime ? ` ${runtime}` : ""}`;
8686

87+
const AGENT_DEVICE_PATH = "/v1/agent-device";
88+
const sameOrigin = (left: string, right: string) => {
89+
try {
90+
return new URL(left).origin === new URL(right).origin;
91+
} catch {
92+
return false;
93+
}
94+
};
95+
96+
/**
97+
* The gateway and token this machine's agent-device uses, from agent-device's own remote-daemon
98+
* variables, which Simlock tells its clients to set. Null unless they point at a Simlock gateway.
99+
*/
100+
export const machineSimlockToken = (environment: NodeJS.ProcessEnv) => {
101+
const base = environment.AGENT_DEVICE_DAEMON_BASE_URL?.trim().replace(/\/+$/, "");
102+
const agentToken = environment.AGENT_DEVICE_DAEMON_AUTH_TOKEN?.trim();
103+
if (!base?.endsWith(AGENT_DEVICE_PATH) || !agentToken) return null;
104+
const gatewayUrl = base.slice(0, -AGENT_DEVICE_PATH.length);
105+
return URL.canParse(gatewayUrl) ? { gatewayUrl, agentToken } : null;
106+
};
107+
108+
/** The saved token, else this machine's agent-device token, but only for the gateway it targets. */
109+
export const resolveSimlockToken = (
110+
gatewayUrl: string,
111+
saved: string,
112+
environment: NodeJS.ProcessEnv,
113+
) => {
114+
if (saved) return { agentToken: saved, source: "settings" as const };
115+
const machine = machineSimlockToken(environment);
116+
return machine && sameOrigin(machine.gatewayUrl, gatewayUrl)
117+
? { agentToken: machine.agentToken, source: "env" as const }
118+
: null;
119+
};
120+
121+
/** What went wrong talking to a gateway, without the gateway's own text. */
122+
export const describeGatewayFailure = (cause: unknown, gatewayUrl: string, tokenOwner: string) => {
123+
const status = HttpClientError.isHttpClientError(cause) ? cause.response?.status : undefined;
124+
return status === 401 || status === 403
125+
? `The Simlock gateway refused the agent token for ${tokenOwner}.`
126+
: status !== undefined
127+
? `The Simlock gateway at ${gatewayUrl} answered HTTP ${status}.`
128+
: `Could not reach the Simlock gateway at ${gatewayUrl}.`;
129+
};
130+
131+
const decodeIdentity = Schema.decodeUnknownEffect(
132+
Schema.Struct({ name: Schema.String, role: Schema.String }),
133+
);
134+
135+
/** Who the gateway says a token is, via GET /v1/identity. */
136+
export const simlockIdentity = Effect.fn("SimlockDeviceHost.identity")(function* (
137+
gatewayUrl: string,
138+
agentToken: string,
139+
) {
140+
const http = yield* HttpClient.HttpClient;
141+
return yield* http
142+
.execute(
143+
HttpClientRequest.get(`${gatewayUrl.replace(/\/$/, "")}/v1/identity`).pipe(
144+
HttpClientRequest.bearerToken(agentToken),
145+
),
146+
)
147+
.pipe(
148+
Effect.flatMap(HttpClientResponse.filterStatusOk),
149+
Effect.flatMap((response) => response.json),
150+
Effect.flatMap(decodeIdentity),
151+
Effect.scoped,
152+
Effect.timeout(REQUEST_TIMEOUT),
153+
);
154+
});
155+
87156
/** T3's own agent-device CLI, installed on first use. */
88157
export type AgentDeviceCli = Effect.Effect<
89158
{ readonly nodePath: string; readonly entryPath: string },
@@ -103,6 +172,8 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
103172
const environment = yield* HostProcess.Environment;
104173
const hostId = config.id;
105174
const gateway = config.gatewayUrl.replace(/\/$/, "");
175+
const agentToken =
176+
resolveSimlockToken(config.gatewayUrl, config.agentToken, environment)?.agentToken ?? "";
106177
const agentDeviceUrl = `${gateway}/v1/agent-device`;
107178
const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
108179
const leases = new Map<string, Lease>();
@@ -142,7 +213,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
142213
HttpClientRequest.bodyJsonUnsafe(body ?? {}),
143214
)
144215
: HttpClientRequest.delete(`${gateway}${route}`)
145-
).pipe(HttpClientRequest.bearerToken(config.agentToken)),
216+
).pipe(HttpClientRequest.bearerToken(agentToken)),
146217
)
147218
.pipe(
148219
Effect.flatMap(HttpClientResponse.filterStatusOk),
@@ -203,24 +274,17 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
203274
const fetchCatalog = Effect.gen(function* () {
204275
const now = yield* Clock.currentTimeMillis;
205276
if (catalog && now - catalog.at < CATALOG_TTL_MS) return catalog.devices;
206-
if (!config.agentToken) {
277+
if (!agentToken) {
207278
return yield* unavailable(`Add an agent token for ${config.label} in Settings.`);
208279
}
209280
const decoded = yield* request("GET", "/v1/catalog").pipe(
210281
Effect.flatMap(decodeCatalog),
211-
Effect.mapError((cause) => {
212-
const status = HttpClientError.isHttpClientError(cause)
213-
? cause.response?.status
214-
: undefined;
215-
return unavailable(
216-
status === 401 || status === 403
217-
? `The Simlock gateway refused the agent token for ${config.label}. Check it in Settings.`
218-
: status !== undefined
219-
? `The Simlock gateway at ${gateway} answered HTTP ${status}.`
220-
: `Could not reach the Simlock gateway at ${gateway}.`,
282+
Effect.mapError((cause) =>
283+
unavailable(
284+
`${describeGatewayFailure(cause, gateway, config.label)} Check it in Settings.`,
221285
cause,
222-
);
223-
}),
286+
),
287+
),
224288
);
225289
const devices = decoded.platforms.flatMap((entry) => {
226290
if (entry.platform !== "ios" && entry.platform !== "android") return [];
@@ -354,7 +418,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
354418
const configPath = path.join(dir, "agent-device.json");
355419
yield* writeAgentDeviceConfig(configPath, {
356420
baseUrl: agentDeviceUrl,
357-
token: config.agentToken,
421+
token: agentToken,
358422
stateDir: dir,
359423
}).pipe(
360424
Effect.provide(services),
@@ -480,7 +544,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
480544
onSome: (lease) =>
481545
Effect.succeed({
482546
baseUrl: agentDeviceUrl,
483-
token: config.agentToken,
547+
token: agentToken,
484548
agentDeviceId: null,
485549
session: lease.session,
486550
stateDir: lease.dir,
@@ -511,7 +575,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
511575
if (!lease) return null;
512576
return {
513577
url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
514-
headers: { authorization: `Bearer ${config.agentToken}` },
578+
headers: { authorization: `Bearer ${agentToken}` },
515579
protocols: [],
516580
};
517581
});

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ const RPC_AGGREGATES = {
203203
[WS_METHODS.deviceConfigure]: "device",
204204
[WS_METHODS.deviceTestHost]: "device",
205205
[WS_METHODS.deviceEasAccount]: "device",
206+
[WS_METHODS.deviceSimlockIdentity]: "device",
206207
[WS_METHODS.deviceList]: "device",
207208
[WS_METHODS.deviceOpen]: "device",
208209
[WS_METHODS.deviceClose]: "device",

‎apps/server/src/ws.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3020,6 +3020,7 @@ export const layerWsRpc = (
30203020
[WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input),
30213021
[WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input),
30223022
[WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input),
3023+
[WS_METHODS.deviceSimlockIdentity]: (input) => deviceService.simlockIdentity(input),
30233024
[WS_METHODS.deviceList]: (input) =>
30243025
input.inspectOnly && !input.updateTool
30253026
? deviceService.inspect

‎apps/web/src/components/settings/DeviceSourcesSettings.tsx‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -507,14 +507,8 @@ export function DeviceSourcesSettings(props: {
507507
label: member.label,
508508
added: true,
509509
platforms: hostPlatforms(member.state, host.id),
510-
status:
511-
held.agentToken === ""
512-
? ({
513-
tone: "warning",
514-
label: "No agent token",
515-
...(disabled ? {} : { action: { label: "Add token", run: edit } }),
516-
} as const)
517-
: hostStatus(member.state, host.id),
510+
// A blank token can still resolve to the machine's own, so the host's answer decides.
511+
status: hostStatus(member.state, host.id),
518512
};
519513
}),
520514
actions: rowActions(edit, () => removeSimlock(host)),

0 commit comments

Comments
 (0)