Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ExpoApi.ts

366 lines13.4 KB

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 };
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 }
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 }
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 }
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;
141​
142export interface EasApp {
143 readonly id: string;
144 readonly fullName: string;
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;
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 refused: a request it never got, a 4xx, or GraphQL errors at a 2xx
177 // or 4xx that are the user's fault. Expo marks those `errorType: "USER"`
178 // and not `isTransient` (eas-cli's rule; Apollo's `code` says nothing, as
179 // Expo puts INTERNAL_SERVER_ERROR on user errors too) and answers them with
180 // `data: null`, since its mutations are non-null. GraphQL errors at a 5xx,
181 // beside data (the request ran), or that are Expo's own fault came from a
182 // request that may have run.
183 const errors = reason._tag === "ResponseError" ? reason.errors : [];
184 const fault = errors.some(
185 ({ extensions }) =>
186 extensions?.isTransient === true ||
187 (extensions?.errorType !== undefined && extensions.errorType !== "USER") ||
188 extensions?.errorCode === "INTERNAL_SERVER_ERROR",
189 );
190 const usersFault =
191 errors.length > 0 && errors.every(({ extensions }) => extensions?.errorType === "USER");
192 const uncertain =
193 reason._tag === "ResponseError" &&
194 (fault || (reason.data !== undefined && !(reason.data === null && usersFault)));
195 const rejected =
196 reason._tag === "EncodeError" ||
197 (status !== undefined &&
198 status < 500 &&
199 !uncertain &&
200 (status >= 400 || reason._tag === "ResponseError"));
201 // Expo's own messages are the reason the user acts on, but nothing promises
202 // they never echo a request: the credential is cut out, and they are bounded.
203 const secret = Redacted.value(credential.header.value);
204 const token = secret.replace(/^Bearer /, "");
205 const scrub = (text: string) =>
206 text.replaceAll(secret, "[redacted]").replaceAll(token, "[redacted]").slice(0, 300);
207 const failure = (detail: string) =>
208 new ExpoApiError({
209 operation,
210 detail: scrub(detail),
211 rejected,
212 ...(status !== undefined ? { status } : {}),
213 });
214 if (status === 401 || status === 403) {
215 const what = credential.source === "eas-login" ? "eas login session" : "access token";
216 return failure(`the ${what} was rejected (HTTP ${status})`);
217 }
218 switch (reason._tag) {
219 case "ResponseError":
220 return failure(reason.errors.map((graphQlError) => graphQlError.message).join("; "));
221 case "TransportError":
222 return failure(
223 status === undefined ? "Expo's API is unreachable" : `unexpected response (HTTP ${status})`,
224 );
225 case "EncodeError":
226 return failure("the request could not be encoded");
227 default:
228 return failure("unexpected response");
229 }
230};
231​
232const toSession = (
233 session: T3EasSimulatorSession.Result["deviceRunSessions"]["byId"],
234): EasSession => {
235 const remote = session.remoteConfig;
236 return {
237 id: session.id,
238 status: session.status,
239 endpoints:
240 remote?.__typename === "AgentDeviceRunSessionRemoteConfig"
241 ? {
242 agentDevice: {
243 url: remote.agentDeviceRemoteSessionUrl,
244 token: Redacted.make(remote.agentDeviceRemoteSessionToken),
245 },
246 preview:
247 remote.previewApiUrl && remote.webPreviewToken
248 ? { url: remote.previewApiUrl, token: Redacted.make(remote.webPreviewToken) }
249 : null,
250 }
251 : null,
252 };
253};
254​
255/** Typed calls against Expo's API with one resolved credential. */
256export const makeExpoApi = (http: HttpClient.HttpClient, credential: ExpoCredential) => {
257 const client = GraphQLClient.make(ExpoGroup).pipe(
258 Effect.provide(
259 Layer.mergeAll(
260 Layer.succeed(
261 ExpoAuth,
262 GraphQLMiddleware.mapRequest((request) =>
263 Effect.succeed({
264 ...request,
265 headers: Headers.set(
266 request.headers,
267 credential.header.name,
268 Redacted.value(credential.header.value),
269 ),
270 }),
271 ),
272 ),
273 GraphQLProtocol.layerHttp({ url: EXPO_GRAPHQL_URL }).pipe(
274 Layer.provide(Layer.succeed(HttpClient.HttpClient, http)),
275 ),
276 ),
277 ),
278 );
279 const call = <A>(
280 operation: string,
281 run: (
282 client: GraphQLClient.FromGroup<typeof ExpoGroup>,
283 ) => Effect.Effect<A, GraphQLClientError.GraphQLClientError>,
284 ) =>
285 Effect.flatMap(client, run).pipe(
286 Effect.mapError((error) => toExpoApiError(operation, credential, error)),
287 Effect.timeoutOrElse({
288 duration: REQUEST_TIMEOUT,
289 orElse: () =>
290 Effect.fail(new ExpoApiError({ operation, detail: "Expo's API did not answer in time" })),
291 }),
292 Effect.withSpan(`ExpoApi.${operation}`),
293 );
294​
295 return {
296 credential,
297 viewer: call("read the signed-in account", (expo) => expo.T3ExpoViewer()).pipe(
298 Effect.flatMap(({ meActor }) =>
299 meActor === null
300 ? Effect.fail(
301 new ExpoApiError({
302 operation: "read the signed-in account",
303 detail: "no account is signed in",
304 }),
305 )
306 : Effect.succeed({
307 name:
308 "username" in meActor
309 ? meActor.username
310 : "firstName" in meActor
311 ? (meActor.firstName ?? meActor.__typename)
312 : meActor.__typename,
313 apps: meActor.accounts.flatMap((account) =>
314 account.appsPaginated.edges.map(({ node }): EasApp => node),
315 ),
316 }),
317 ),
318 ),
319 availability: (appId: string) =>
320 call("check EAS Simulator access", (expo) =>
321 expo.T3EasSimulatorAvailability({ appId, filter: [DEVICE_RUN_SESSIONS_GATE] }),
322 ).pipe(
323 Effect.map(({ app }) => {
324 const gates = app.byId.ownerAccount.accountFeatureGates;
325 return {
326 account: app.byId.ownerAccount.name,
327 available: isFeatureGates(gates) && gates[DEVICE_RUN_SESSIONS_GATE] === true,
328 };
329 }),
330 ),
331 create: (input: CreateEasSessionInput) =>
332 call("start a simulator session", (expo) =>
333 expo.T3CreateEasSimulatorSession({
334 input: {
335 appId: input.appId,
336 platform: input.platform === "ios" ? "IOS" : "ANDROID",
337 type: "AGENT_DEVICE",
338 name: input.name,
339 maxRunTimeMinutes: input.maxRunTimeMinutes,
340 maxIdleTimeMinutes: input.maxIdleTimeMinutes,
341 // Expo only issues the preview host's API URL when preview access is configured.
342 corsOrigins: ["http://localhost"],
343 },
344 }),
345 ).pipe(Effect.map(({ deviceRunSession }) => deviceRunSession.createDeviceRunSession.id)),
346 session: (id: string) =>
347 call("read a simulator session", (expo) => expo.T3EasSimulatorSession({ id })).pipe(
348 Effect.map(({ deviceRunSessions }) => toSession(deviceRunSessions.byId)),
349 ),
350 activeSessions: (appId: string) =>
351 call("list simulator sessions", (expo) =>
352 expo.T3ActiveEasSimulatorSessions({
353 appId,
354 filter: { statuses: ["NEW", "QUEUED", "STARTING", "IN_PROGRESS"] },
355 }),
356 ).pipe(
357 Effect.map(({ app }) => app.byId.deviceRunSessionsPaginated.edges.map(({ node }) => node)),
358 ),
359 stop: (id: string) =>
360 call("stop a simulator session", (expo) => expo.T3StopEasSimulatorSession({ id })).pipe(
361 Effect.map(({ deviceRunSession }) => deviceRunSession.ensureDeviceRunSessionStopped.status),
362 ),
363 };
364};
365​
366export type ExpoApi = ReturnType<typeof makeExpoApi>;