Open History to see the last commit
1/**
2 * Expo's GraphQL API for EAS Simulator sessions. The operations in
3 * `ExpoApi.graphql` are the ones eas-cli's `simulator:*` commands send; their
4 * client is generated from `schema/expo.graphql` (`vp run generate`).
5 */
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Redacted from "effect/Redacted";
12import * as Schema from "effect/Schema";
13import {
14 GraphQLClient,
15 GraphQLClientError,
16 GraphQLMiddleware,
17 GraphQLProtocol,
18} from "effect/graphql";
19import { HttpClient } from "effect/http";
20import * as Headers from "effect/http/Headers";
21import * as HostProcess from "@t3tools/shared/HostProcess";
22
23import { ExpoApiGraphQLGroup, type T3EasSimulatorSession } from "./ExpoApi.graphql.ts";
24import type { DeviceRunSessionStatus } from "../../schema/expo.graphql.ts";
25
26const EXPO_GRAPHQL_URL = "https://api.expo.dev/graphql";
27const REQUEST_TIMEOUT = "30 seconds";
28
29export type ExpoCredentialSource = "settings" | "env" | "eas-login";
30
31export interface ExpoCredential {
32 readonly source: ExpoCredentialSource;
33 readonly header: {
34 readonly name: "authorization" | "expo-session";
35 readonly value: Redacted.Redacted<string>;
36 };
37}
38
39export class ExpoNotSignedInError extends Schema.TaggedError<ExpoNotSignedInError>()(
40 "ExpoNotSignedInError",
41 {},
42) {
43 override get message(): string {
44 return "No Expo credential on the server: save an access token for this host, set EXPO_TOKEN, or run `eas login`.";
45 }
46}
47
48const CREDENTIAL_SOURCE_NAMES: Record<ExpoCredentialSource, string> = {
49 settings: "The access token saved for this host",
50 env: "EXPO_TOKEN",
51 "eas-login": "The eas login session",
52};
53
54export class ExpoInvalidCredentialError extends Schema.TaggedError<ExpoInvalidCredentialError>()(
55 "ExpoInvalidCredentialError",
56 { source: Schema.Literals(["settings", "env", "eas-login"]) },
57) {
58 override get message(): string {
59 return `${CREDENTIAL_SOURCE_NAMES[this.source]} is not a usable Expo credential. Replace it.`;
60 }
61}
62
63/**
64 * Expo credentials are printable ASCII. Anything else (the redacted
65 * placeholder, a pasted newline) would fail inside fetch with the header
66 * value in its message, so it is refused here.
67 */
68const credential = (
69 source: ExpoCredentialSource,
70 header: ExpoCredential["header"]["name"],
71 value: string,
72) =>
73 /^[\x21-\x7e]+$/.test(value)
74 ? Effect.succeed({
75 source,
76 header: {
77 name: header,
78 value: Redacted.make(header === "authorization" ? `Bearer ${value}` : value),
79 },
80 } satisfies ExpoCredential)
81 : Effect.fail(new ExpoInvalidCredentialError({ source }));
82
83export class ExpoApiError extends Schema.TaggedError<ExpoApiError>()("ExpoApiError", {
84 operation: Schema.String,
85 detail: Schema.optional(Schema.String),
86 /**
87 * Expo answered and refused, so a mutation did nothing. Otherwise (no
88 * answer, a server error, an answer that did not decode) it may have run.
89 */
90 rejected: Schema.optional(Schema.Boolean),
91 /** The HTTP status Expo answered with, when it answered. */
92 status: Schema.optional(Schema.Int),
93}) {
94 override get message(): string {
95 return `Expo could not ${this.operation}${this.detail ? `: ${this.detail}` : "."}`;
96 }
97}
98
99/** `eas login` and `expo login` keep the session secret here. */
100const ExpoState = Schema.fromJsonString(
101 Schema.Struct({
102 auth: Schema.optional(
103 Schema.NullOr(
104 Schema.Struct({ sessionSecret: Schema.optional(Schema.NullOr(Schema.String)) }),
105 ),
106 ),
107 }),
108);
109const decodeExpoState = Schema.decodeUnknownOption(ExpoState);
110
111/** A token saved for the host, then EXPO_TOKEN, then the `eas login` session. */
112export const resolveExpoCredential = Effect.fn("ExpoApi.resolveExpoCredential")(function* (
113 savedToken: string,
114) {
115 const saved = savedToken.trim();
116 if (saved !== "") return yield* credential("settings", "authorization", saved);
117 const fromEnv = (yield* HostProcess.Environment).EXPO_TOKEN?.trim();
118 if (fromEnv) return yield* credential("env", "authorization", fromEnv);
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 const statePath = path.join(yield* HostProcess.HomeDirectory, ".expo", "state.json");
122 const state = yield* fs.readFileString(statePath).pipe(Effect.option);
123 const secret = Option.flatMap(state, decodeExpoState).pipe(
124 Option.flatMap((value) => Option.fromNullishOr(value.auth?.sessionSecret?.trim() || null)),
125 );
126 if (Option.isNone(secret)) return yield* new ExpoNotSignedInError();
127 return yield* credential("eas-login", "expo-session", secret.value);
128});
129
130export type EasSessionStatus = DeviceRunSessionStatus;
131
132export interface EasSession {
133 readonly id: string;
134 readonly status: EasSessionStatus;
135 /** Present once the simulator is ready; tokens grant full device control. */
136 readonly endpoints: {
137 readonly agentDevice: { readonly url: string; readonly token: Redacted.Redacted<string> };
138 readonly preview: { readonly url: string; readonly token: Redacted.Redacted<string> } | null;
139 } | null;
140}
141
142export interface EasApp {
143 readonly id: string;
144 readonly fullName: string;
145}
146
147export interface CreateEasSessionInput {
148 readonly appId: string;
149 readonly platform: "ios" | "android";
150 readonly name: string;
151 readonly maxRunTimeMinutes: number;
152 readonly maxIdleTimeMinutes: number;
153}
154
155const DEVICE_RUN_SESSIONS_GATE = "device-run-sessions";
156const isFeatureGates = Schema.is(Schema.Record(Schema.String, Schema.Unknown));
157
158/** Sends every operation with the resolved credential. */
159class ExpoAuth extends GraphQLMiddleware.Service<ExpoAuth>()("t3/server/device/ExpoApi/ExpoAuth") {}
160
161const ExpoGroup = ExpoApiGraphQLGroup.middleware(ExpoAuth);
162
163/**
164 * Expo's answer as an `ExpoApiError`, which has no cause: a transport error's
165 * holds the request with its credential header, and a decode error's can
166 * quote session tokens. These errors also travel to clients as RPC defects.
167 */
168const toExpoApiError = (
169 operation: string,
170 credential: ExpoCredential,
171 error: GraphQLClientError.GraphQLClientError,
172): ExpoApiError => {
173 const reason = error.reason;
174 const status =
175 reason._tag === "TransportError" || reason._tag === "ResponseError" ? reason.status : undefined;
176 // Expo user errors have `errorType: "USER"`, no `isTransient`, and null data (eas-cli's rule).
177 // Apollo's `code` is unreliable: Expo also uses INTERNAL_SERVER_ERROR for user errors.
178 // GraphQL errors at 5xx, beside data, or caused by Expo may follow a request that ran.
179 const errors = reason._tag === "ResponseError" ? reason.errors : [];
180 const fault = errors.some(
181 ({ extensions }) =>
182 extensions?.isTransient === true ||
183 (extensions?.errorType !== undefined && extensions.errorType !== "USER") ||
184 extensions?.errorCode === "INTERNAL_SERVER_ERROR",
185 );
186 const usersFault =
187 errors.length > 0 && errors.every(({ extensions }) => extensions?.errorType === "USER");
188 const uncertain =
189 reason._tag === "ResponseError" &&
190 (fault || (reason.data !== undefined && !(reason.data === null && usersFault)));
191 const rejected =
192 reason._tag === "EncodeError" ||
193 (status !== undefined &&
194 status < 500 &&
195 !uncertain &&
196 (status >= 400 || reason._tag === "ResponseError"));
197 // Expo's own messages are the reason the user acts on, but nothing promises
198 // they never echo a request: the credential is cut out, and they are bounded.
199 const secret = Redacted.value(credential.header.value);
200 const token = secret.replace(/^Bearer /, "");
201 const scrub = (text: string) =>
202 text.replaceAll(secret, "[redacted]").replaceAll(token, "[redacted]").slice(0, 300);
203 const failure = (detail: string) =>
204 new ExpoApiError({
205 operation,
206 detail: scrub(detail),
207 rejected,
208 ...(status !== undefined ? { status } : {}),
209 });
210 if (status === 401 || status === 403) {
211 const what = credential.source === "eas-login" ? "eas login session" : "access token";
212 return failure(`the ${what} was rejected (HTTP ${status})`);
213 }
214 switch (reason._tag) {
215 case "ResponseError":
216 return failure(reason.errors.map((graphQlError) => graphQlError.message).join("; "));
217 case "TransportError":
218 return failure(
219 status === undefined ? "Expo's API is unreachable" : `unexpected response (HTTP ${status})`,
220 );
221 case "EncodeError":
222 return failure("the request could not be encoded");
223 default:
224 return failure("unexpected response");
225 }
226};
227
228const toSession = (
229 session: T3EasSimulatorSession.Result["deviceRunSessions"]["byId"],
230): EasSession => {
231 const remote = session.remoteConfig;
232 return {
233 id: session.id,
234 status: session.status,
235 endpoints:
236 remote?.__typename === "AgentDeviceRunSessionRemoteConfig"
237 ? {
238 agentDevice: {
239 url: remote.agentDeviceRemoteSessionUrl,
240 token: Redacted.make(remote.agentDeviceRemoteSessionToken),
241 },
242 preview:
243 remote.previewApiUrl && remote.webPreviewToken
244 ? { url: remote.previewApiUrl, token: Redacted.make(remote.webPreviewToken) }
245 : null,
246 }
247 : null,
248 };
249};
250
251/** Typed calls against Expo's API with one resolved credential. */
252export const makeExpoApi = (http: HttpClient.HttpClient, credential: ExpoCredential) => {
253 const client = GraphQLClient.make(ExpoGroup).pipe(
254 Effect.provide(
255 Layer.mergeAll(
256 Layer.succeed(
257 ExpoAuth,
258 GraphQLMiddleware.mapRequest((request) =>
259 Effect.succeed({
260 ...request,
261 headers: Headers.set(
262 request.headers,
263 credential.header.name,
264 Redacted.value(credential.header.value),
265 ),
266 }),
267 ),
268 ),
269 GraphQLProtocol.layerHttp({ url: EXPO_GRAPHQL_URL }).pipe(
270 Layer.provide(Layer.succeed(HttpClient.HttpClient, http)),
271 ),
272 ),
273 ),
274 );
275 const call = <A>(
276 operation: string,
277 run: (
278 client: GraphQLClient.FromGroup<typeof ExpoGroup>,
279 ) => Effect.Effect<A, GraphQLClientError.GraphQLClientError>,
280 ) =>
281 Effect.flatMap(client, run).pipe(
282 Effect.mapError((error) => toExpoApiError(operation, credential, error)),
283 Effect.timeoutOrElse({
284 duration: REQUEST_TIMEOUT,
285 orElse: () =>
286 Effect.fail(new ExpoApiError({ operation, detail: "Expo's API did not answer in time" })),
287 }),
288 Effect.withSpan(`ExpoApi.${operation}`),
289 );
290
291 return {
292 credential,
293 viewer: call("read the signed-in account", (expo) => expo.T3ExpoViewer()).pipe(
294 Effect.flatMap(({ meActor }) =>
295 meActor === null
296 ? Effect.fail(
297 new ExpoApiError({
298 operation: "read the signed-in account",
299 detail: "no account is signed in",
300 }),
301 )
302 : Effect.succeed({
303 name:
304 "username" in meActor
305 ? meActor.username
306 : "firstName" in meActor
307 ? (meActor.firstName ?? meActor.__typename)
308 : meActor.__typename,
309 apps: meActor.accounts.flatMap((account) =>
310 account.appsPaginated.edges.map(({ node }): EasApp => node),
311 ),
312 }),
313 ),
314 ),
315 availability: (appId: string) =>
316 call("check EAS Simulator access", (expo) =>
317 expo.T3EasSimulatorAvailability({ appId, filter: [DEVICE_RUN_SESSIONS_GATE] }),
318 ).pipe(
319 Effect.map(({ app }) => {
320 const gates = app.byId.ownerAccount.accountFeatureGates;
321 return {
322 account: app.byId.ownerAccount.name,
323 available: isFeatureGates(gates) && gates[DEVICE_RUN_SESSIONS_GATE] === true,
324 };
325 }),
326 ),
327 create: (input: CreateEasSessionInput) =>
328 call("start a simulator session", (expo) =>
329 expo.T3CreateEasSimulatorSession({
330 input: {
331 appId: input.appId,
332 platform: input.platform === "ios" ? "IOS" : "ANDROID",
333 type: "AGENT_DEVICE",
334 name: input.name,
335 maxRunTimeMinutes: input.maxRunTimeMinutes,
336 maxIdleTimeMinutes: input.maxIdleTimeMinutes,
337 // Expo only issues the preview host's API URL when preview access is configured.
338 corsOrigins: ["http://localhost"],
339 },
340 }),
341 ).pipe(Effect.map(({ deviceRunSession }) => deviceRunSession.createDeviceRunSession.id)),
342 session: (id: string) =>
343 call("read a simulator session", (expo) => expo.T3EasSimulatorSession({ id })).pipe(
344 Effect.map(({ deviceRunSessions }) => toSession(deviceRunSessions.byId)),
345 ),
346 activeSessions: (appId: string) =>
347 call("list simulator sessions", (expo) =>
348 expo.T3ActiveEasSimulatorSessions({
349 appId,
350 filter: { statuses: ["NEW", "QUEUED", "STARTING", "IN_PROGRESS"] },
351 }),
352 ).pipe(
353 Effect.map(({ app }) => app.byId.deviceRunSessionsPaginated.edges.map(({ node }) => node)),
354 ),
355 stop: (id: string) =>
356 call("stop a simulator session", (expo) => expo.T3StopEasSimulatorSession({ id })).pipe(
357 Effect.map(({ deviceRunSession }) => deviceRunSession.ensureDeviceRunSessionStopped.status),
358 ),
359 };
360};
361
362export type ExpoApi = ReturnType<typeof makeExpoApi>;