The best way to control Claude Code, Codex and more from any computer or phone

main
ts 264 lines 8.37 KB
Raw
1 import * as firebaseappcheck from "@distilled.cloud/gcp/firebaseappcheck_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 createOwnership,
11 encodeDisplayName,
12 expandApp,
13 findOwnedDebugToken,
14 getDebugToken,
15 listDebugTokensForApp,
16 listOwnedDebugTokens,
17 ownedByAlchemy,
18 parseDebugTokenName,
19 parseDisplayName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 retryTransient,
23 sameText,
24 sameTextInsensitive,
25 toDisplayName,
26 toToken,
27 } from "./internal.ts";
28
29 export type AppsDebugTokenProps = {
30 /**
31 * Firebase App id (`1:123:web:abc`) or full resource name
32 * `projects/{project}/apps/{appId}`. Immutable — changing it replaces
33 * the debug token.
34 */
35 app: string;
36 /**
37 * Human-readable display name. Debug tokens have no labels field, so
38 * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it
39 * from attributes.
40 */
41 displayName?: string;
42 /**
43 * Secret token. Must be a UUID4 (case insensitive). If omitted, a UUID4
44 * is generated and stored in Alchemy state. Input-only on the GCP API
45 * — never returned by get/list. Immutable — changing it replaces the
46 * debug token. Each app may have at most 20 debug tokens.
47 */
48 token?: string;
49 };
50
51 export type AppsDebugToken = Resource<
52 "GCP.FirebaseAppCheck.AppsDebugToken",
53 AppsDebugTokenProps,
54 {
55 /** Full resource name. */
56 name: string;
57 /** Server-assigned debug token id (last path segment). */
58 debugTokenId: string;
59 /** Parent app resource `projects/{project}/apps/{appId}`. */
60 app: string;
61 /** Firebase App id. */
62 appId: string;
63 /** Project id. */
64 project: string;
65 /** User display name with the Alchemy ownership prefix stripped. */
66 displayName: string | undefined;
67 /**
68 * Secret token from create input / Alchemy state. Never populated by
69 * the App Check API after create.
70 */
71 token: string | undefined;
72 /** Server-assigned checksum for optimistic concurrency. */
73 etag: string | undefined;
74 /** RFC3339 last-update timestamp. */
75 updateTime: string | undefined;
76 },
77 never,
78 Providers
79 >;
80
81 /**
82 * A Firebase App Check debug token. Debug tokens let development and
83 * integration testing bypass app attestation while App Check still
84 * protects production Firebase services.
85 *
86 * Debug tokens have no labels field, so Alchemy stamps ownership into
87 * `displayName` for `list` / nuke. `app` and `token` are identity —
88 * changing either replaces the token. Display name updates in place.
89 * GCP never returns `token` after create; Alchemy stores the secret in
90 * state so {@link ExchangeDebugToken} can redeem it.
91 *
92 * ### Creating a Debug Token
93 * **Example:** Generated UUID
94 * ```typescript
95 * const debug = yield* GCP.FirebaseAppCheck.AppsDebugToken("Local", {
96 * app: "1:123:web:abc",
97 * displayName: "ios simulator",
98 * });
99 * ```
100 *
101 * **Example:** Explicit UUID4
102 * ```typescript
103 * const debug = yield* GCP.FirebaseAppCheck.AppsDebugToken("Local", {
104 * app: "1:123:web:abc",
105 * displayName: "android emulator",
106 * token: "123e4567-e89b-12d3-a456-426614174000",
107 * });
108 * ```
109 *
110 * ### Updating a Debug Token
111 * **Example:** Rename
112 * ```typescript
113 * const debug = yield* GCP.FirebaseAppCheck.AppsDebugToken("Local", {
114 * displayName: "ci runner",
115 * });
116 * ```
117 *
118 * ### Exchanging a Debug Token
119 * **Example:** Mint an App Check token
120 * ```typescript
121 * const exchange = yield* GCP.FirebaseAppCheck.ExchangeDebugToken(debug);
122 * const { token, ttl } = yield* exchange();
123 * ```
124 *
125 * @resource
126 * @category FirebaseAppCheck
127 */
128 export const AppsDebugToken = Resource<AppsDebugToken>("GCP.FirebaseAppCheck.AppsDebugToken");
129
130 const getByName = getDebugToken;
131
132 const toAttrs = (
133 token: firebaseappcheck.GoogleFirebaseAppcheckV1DebugToken,
134 project: string,
135 secret: string | undefined,
136 ): AppsDebugToken["Attributes"] => {
137 const name = token.name ?? "";
138 const parsed = parseDebugTokenName(name);
139 const { displayName } = parseDisplayName(token.displayName);
140 return {
141 name,
142 debugTokenId: parsed.debugTokenId,
143 app: parsed.app,
144 appId: parsed.appId,
145 project: parsed.project || project,
146 displayName,
147 token: secret,
148 etag: token.etag,
149 updateTime: token.updateTime,
150 };
151 };
152
153 export const AppsDebugTokenProvider = () =>
154 Provider.succeed(AppsDebugToken, {
155 stables: ["name", "debugTokenId", "app", "appId", "project", "token"],
156
157 diff: Effect.fn(function* ({ news, olds, output }) {
158 if (!isResolved(news)) return undefined;
159 const env = yield* GcpEnvironment.current;
160 const previousApp = expandApp(env.project, olds?.app ?? output?.app ?? "");
161 const nextApp = expandApp(env.project, news.app);
162 return replaceOnIdentity({
163 previous: previousApp.length > 0 ? previousApp : undefined,
164 next: nextApp,
165 extra:
166 news.token !== undefined &&
167 (output?.token ?? olds?.token) !== undefined &&
168 !sameTextInsensitive(news.token, output?.token ?? olds?.token),
169 deleteFirst: true,
170 });
171 }),
172
173 read: Effect.fn(function* ({ id, olds, output, previous }) {
174 const env = yield* GcpEnvironment.current;
175 let existing = yield* getByName(output?.name ?? "");
176 if (existing === undefined && olds?.app) {
177 const app = expandApp(env.project, olds.app);
178 existing = yield* findOwnedDebugToken(yield* listDebugTokensForApp(app), id, output?.name);
179 }
180 if (existing === undefined) return undefined;
181 const attrs = toAttrs(existing, env.project, output?.token);
182 return (yield* ownedByAlchemy(id, existing.displayName))
183 ? attrs
184 : unownedUnlessPrevious(attrs, previous, "name");
185 }),
186
187 list: () =>
188 Effect.gen(function* () {
189 const env = yield* GcpEnvironment.current;
190 const tokens = yield* listOwnedDebugTokens(env.project);
191 return tokens.map((token) => toAttrs(token, env.project, undefined));
192 }),
193
194 reconcile: Effect.fn(function* ({ id, news, output }) {
195 const env = yield* GcpEnvironment.current;
196 const app = expandApp(env.project, news.app);
197 const ownership = yield* createOwnership(id);
198 const userDisplay = yield* toDisplayName(id, news.displayName, output?.displayName);
199 const desiredDisplay = encodeDisplayName(ownership, userDisplay);
200 const secret = yield* toToken(news.token, output?.token);
201
202 let current = yield* getByName(output?.name ?? "");
203 if (current === undefined) {
204 current = yield* findOwnedDebugToken(yield* listDebugTokensForApp(app), id, output?.name);
205 }
206
207 if (current === undefined) {
208 const created = yield* retryTransient(
209 firebaseappcheck.createProjectsAppsDebugTokens({
210 parent: app,
211 body: {
212 displayName: desiredDisplay,
213 token: secret,
214 },
215 }),
216 ).pipe(
217 Effect.catchTag("Conflict", () =>
218 listDebugTokensForApp(app).pipe(
219 Effect.flatMap((tokens) => findOwnedDebugToken(tokens, id, output?.name)),
220 ),
221 ),
222 );
223 current = created ?? undefined;
224 }
225
226 if (current === undefined) {
227 return yield* new ResourceNotResolved({
228 resourceName: output?.name ?? `${app}/debugTokens`,
229 });
230 }
231
232 if (!sameText(current.displayName, desiredDisplay)) {
233 current = yield* retryTransient(
234 firebaseappcheck.patchProjectsAppsDebugTokens({
235 name: current.name ?? "",
236 updateMask: "display_name",
237 body: {
238 displayName: desiredDisplay,
239 etag: current.etag,
240 },
241 }),
242 );
243 }
244
245 return toAttrs(current, env.project, secret);
246 }),
247
248 delete: Effect.fn(function* ({ output }) {
249 if (!output.name) return;
250 yield* retryTransient(
251 firebaseappcheck.deleteProjectsAppsDebugTokens({
252 name: output.name,
253 etag: output.etag,
254 }),
255 ).pipe(
256 Effect.catchTag("Conflict", () =>
257 firebaseappcheck.deleteProjectsAppsDebugTokens({
258 name: output.name,
259 }),
260 ),
261 Effect.catchTag("NotFound", () => Effect.void),
262 );
263 }),
264 });