@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 118 lines 3.84 KB
Raw
1 import * as NodeCrypto from "node:crypto";
2 import { AuthError } from "alchemy/Auth/AuthProvider";
3 import * as Clock from "effect/Clock";
4 import * as Effect from "effect/Effect";
5 import * as FetchHttpClient from "effect/http/FetchHttpClient";
6 import * as HttpClient from "effect/http/HttpClient";
7 import * as HttpClientRequest from "effect/http/HttpClientRequest";
8 import * as Redacted from "effect/Redacted";
9
10 export interface ServiceAccountKey {
11 readonly type?: string;
12 readonly project_id?: string;
13 readonly client_email: string;
14 readonly private_key: string;
15 readonly token_uri?: string;
16 }
17
18 export interface MintedToken {
19 readonly accessToken: Redacted.Redacted<string>;
20 readonly expirationMs: number;
21 readonly project?: string;
22 }
23
24 const TOKEN_URL = "https://oauth2.googleapis.com/token";
25 const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
26
27 const signJwt = (sa: ServiceAccountKey, nowMs: number): string => {
28 const now = Math.floor(nowMs / 1000);
29 const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
30 const signingInput = `${encode({ alg: "RS256", typ: "JWT" })}.${encode({
31 iss: sa.client_email,
32 scope: CLOUD_PLATFORM_SCOPE,
33 aud: sa.token_uri ?? TOKEN_URL,
34 iat: now,
35 exp: now + 3600,
36 })}`;
37 const signer = NodeCrypto.createSign("RSA-SHA256");
38 signer.update(signingInput);
39 return `${signingInput}.${signer.sign(sa.private_key, "base64url")}`;
40 };
41
42 /**
43 * Exchange a service-account JSON key for an OAuth2 access token.
44 * Distilled GCP only accepts a bearer token, so Alchemy mints and refreshes
45 * it here.
46 */
47 export const mintAccessToken = (sa: ServiceAccountKey): Effect.Effect<MintedToken, AuthError> =>
48 Effect.gen(function* () {
49 const issuedAt = yield* Clock.currentTimeMillis;
50 const jwt = yield* Effect.try({
51 try: () => signJwt(sa, issuedAt),
52 catch: (cause) =>
53 AuthError.make({
54 message: "Failed to sign Google service-account JWT",
55 cause,
56 }),
57 });
58 const http = yield* HttpClient.HttpClient;
59 const tokenResponse = yield* http
60 .execute(
61 HttpClientRequest.post(TOKEN_URL).pipe(
62 HttpClientRequest.bodyUrlParams({
63 grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
64 assertion: jwt,
65 }),
66 ),
67 )
68 .pipe(
69 Effect.mapError((cause) =>
70 AuthError.make({
71 message: "Failed to mint Google access token",
72 cause,
73 }),
74 ),
75 );
76 const body = yield* tokenResponse.json.pipe(
77 Effect.mapError((cause) =>
78 AuthError.make({
79 message: "Google token response was not JSON",
80 cause,
81 }),
82 ),
83 );
84 if (
85 typeof body !== "object" ||
86 body === null ||
87 typeof (body as { access_token?: unknown }).access_token !== "string"
88 ) {
89 return yield* AuthError.make({
90 message: `Google token endpoint returned no access_token: ${JSON.stringify(body)}`,
91 });
92 }
93 const expiresIn =
94 typeof (body as { expires_in?: unknown }).expires_in === "number"
95 ? (body as { expires_in: number }).expires_in
96 : 3600;
97 return {
98 accessToken: Redacted.make((body as { access_token: string }).access_token),
99 expirationMs: issuedAt + expiresIn * 1000,
100 project: sa.project_id,
101 };
102 }).pipe(Effect.provide(FetchHttpClient.layer));
103
104 export const parseServiceAccountKey = (raw: string): Effect.Effect<ServiceAccountKey, AuthError> =>
105 Effect.try({
106 try: () => {
107 const parsed = JSON.parse(raw) as ServiceAccountKey;
108 if (!parsed.client_email || !parsed.private_key) {
109 throw new Error("JSON is missing client_email or private_key");
110 }
111 return parsed;
112 },
113 catch: (cause) =>
114 AuthError.make({
115 message: "Invalid Google service-account JSON",
116 cause,
117 }),
118 });