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

CliTokenManager.ts

276 lines10.4 KB

1// @effect-diagnostics nodeBuiltinImport:off - The CLI loopback OAuth callback is a Node HTTP boundary.
2import * as NodeHttp from "node:http";
3​
4import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
5import * as Clock from "effect/Clock";
6import * as Console from "effect/Console";
7import * as Context from "effect/Context";
8import * as Crypto from "effect/Crypto";
9import * as Deferred from "effect/Deferred";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Encoding from "effect/Encoding";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17import * as HttpClient from "effect/unstable/http/HttpClient";
18import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
19import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
20import * as HttpRouter from "effect/unstable/http/HttpRouter";
21import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
22import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
23​
24import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
25import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
26​
27const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
28const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
29const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
30​
31const PersistedToken = Schema.Struct({
32 accessToken: Schema.String,
33 refreshToken: Schema.String,
34 expiresAtEpochMs: Schema.Number,
35});
36type PersistedToken = typeof PersistedToken.Type;
37​
38const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
39const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
40const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
41​
42const OAuthTokenResponse = Schema.Struct({
43 access_token: Schema.String,
44 refresh_token: Schema.optional(Schema.String),
45 expires_in: Schema.Number,
46 token_type: Schema.String,
47});
48​
49export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
50 "CloudCliCredentialRemovalError",
51 { cause: Schema.Defect() },
52) {
53 override get message(): string {
54 return "Could not remove the stored V12 Connect CLI credential.";
55 }
57​
58export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
59 "CloudCliCredentialRefreshError",
60 { cause: Schema.Defect() },
61) {
62 override get message(): string {
63 return "Could not refresh the V12 Connect CLI credential.";
64 }
66​
67export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
68 "CloudCliCredentialReadError",
69 { cause: Schema.Defect() },
70) {
71 override get message(): string {
72 return "Could not read the stored V12 Connect CLI credential.";
73 }
75​
76export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
77 "CloudCliAuthorizationError",
78 { cause: Schema.Defect() },
79) {
80 override get message(): string {
81 return "Could not authorize the V12 Connect CLI.";
82 }
84​
85export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
86 "CloudCliAuthorizationTimeoutError",
87 { cause: Schema.Defect() },
88) {
89 override get message(): string {
90 return "Timed out waiting for V12 Connect authorization.";
91 }
93​
94export const CloudCliTokenManagerError = Schema.Union([
95 CloudCliCredentialRemovalError,
96 CloudCliCredentialRefreshError,
97 CloudCliCredentialReadError,
98 CloudCliAuthorizationError,
99 CloudCliAuthorizationTimeoutError,
100]);
101export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
102​
103export class CloudCliTokenManager extends Context.Service<
104 CloudCliTokenManager,
105 {
106 readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
107 readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
108 readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
109 readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
110 }
111>()("v12/cloud/CliTokenManager/CloudCliTokenManager") {}
112​
113const wrapError =
114 <WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
115 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
116 effect.pipe(Effect.mapError(makeError));
117​
118function stringToBytes(value: string): Uint8Array {
119 return new TextEncoder().encode(value);
121​
122function bytesToString(value: Uint8Array): string {
123 return new TextDecoder().decode(value);
125​
126export const make = Effect.gen(function* () {
127 const crypto = yield* Crypto.Crypto;
128 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
129 const secrets = yield* ServerSecretStore.ServerSecretStore;
130 const semaphore = yield* Semaphore.make(1);
131 const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
132 const encoded = yield* encodePersistedToken(token);
133 yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
134 return token;
135 });
136​
137 const clear = secrets
138 .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
139 .pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
140​
141 const read = Effect.fn("cloud.cli_token.read")(function* () {
142 const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
143 if (Option.isNone(encoded)) return Option.none<PersistedToken>();
144 return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
145 });
146​
147 const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
148 metadata: CloudCliOAuthConfig,
149 params: Record<string, string>,
150 ) {
151 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
152 HttpClientRequest.bodyUrlParams(params),
153 httpClient.execute,
154 Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
155 );
156 const now = yield* Clock.currentTimeMillis;
157 return {
158 accessToken: response.access_token,
159 refreshToken: response.refresh_token ?? params.refresh_token ?? "",
160 expiresAtEpochMs: now + response.expires_in * 1_000,
161 } satisfies PersistedToken;
162 });
163​
164 const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
165 const metadata = yield* cloudCliOAuthConfig;
166 return yield* exchangeToken(metadata, {
167 grant_type: "refresh_token",
168 refresh_token: token.refreshToken,
169 client_id: metadata.clientId,
170 });
171 });
172​
173 const login = Effect.fn("cloud.cli_token.login")(function* () {
174 const metadata = yield* cloudCliOAuthConfig;
175 const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
176 const challenge = Encoding.encodeBase64Url(
177 yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
178 );
179 const state = yield* crypto.randomUUIDv4;
180 const callback = yield* Deferred.make<string>();
181 const callbackRoute = HttpRouter.add(
182 "GET",
183 "/callback",
184 Effect.gen(function* () {
185 const request = yield* HttpServerRequest.HttpServerRequest;
186 const url = new URL(request.originalUrl, metadata.redirectUri);
187 const code = url.searchParams.get("code");
188 if (url.searchParams.get("state") !== state || !code) {
189 return HttpServerResponse.text("Invalid V12 Connect authorization callback.", {
190 status: 400,
191 });
192 }
193 yield* Deferred.succeed(callback, code);
194 return yield* HttpServerResponse.html`
195<html>
196 <body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
197 <h1>V12 Connect authorization complete</h1>
198 <p>You can close this window and return to your terminal.</p>
199 </body>
200</html>
201`;
202 }),
203 );
204 yield* HttpRouter.serve(callbackRoute, {
205 disableListenLog: true,
206 disableLogger: true,
207 }).pipe(
208 Layer.provide(
209 NodeHttpServer.layer(NodeHttp.createServer, {
210 host: "127.0.0.1",
211 port: 34338,
212 disablePreemptiveShutdown: true,
213 }),
214 ),
215 Layer.build,
216 );
217 const authorizationUrl = new URL(metadata.authorizationEndpoint);
218 authorizationUrl.searchParams.set("client_id", metadata.clientId);
219 authorizationUrl.searchParams.set("redirect_uri", metadata.redirectUri);
220 authorizationUrl.searchParams.set("response_type", "code");
221 authorizationUrl.searchParams.set("scope", metadata.scopes.join(" "));
222 authorizationUrl.searchParams.set("state", state);
223 authorizationUrl.searchParams.set("code_challenge", challenge);
224 authorizationUrl.searchParams.set("code_challenge_method", "S256");
225 yield* Console.log(`Open this URL to authorize V12 Connect:\n${authorizationUrl.toString()}\n`);
226 const code = yield* Deferred.await(callback).pipe(
227 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
228 Effect.catchTag("TimeoutError", (cause) =>
229 Effect.fail(
230 new CloudCliAuthorizationTimeoutError({
231 cause,
232 }),
233 ),
234 ),
235 );
236 return yield* exchangeToken(metadata, {
237 grant_type: "authorization_code",
238 code,
239 redirect_uri: metadata.redirectUri,
240 client_id: metadata.clientId,
241 code_verifier: verifier,
242 });
243 });
244​
245 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
246 const token = yield* read();
247 if (Option.isNone(token)) return token;
248 const now = yield* Clock.currentTimeMillis;
249 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
250 return token;
251 }
252 return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
253 });
254​
255 const getExisting = semaphore.withPermits(1)(
256 getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
257 );
258 const hasCredential = semaphore.withPermits(1)(
259 read().pipe(
260 Effect.map(Option.isSome),
261 wrapError((cause) => new CloudCliCredentialReadError({ cause })),
262 ),
263 );
264 const get = semaphore.withPermits(1)(
265 Effect.gen(function* () {
266 const token = yield* getExistingNoLock();
267 return Option.isSome(token)
268 ? token.value
269 : yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
270 }).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
271 );
272​
273 return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
274});
275​
276export const layer = Layer.effect(CloudCliTokenManager, make);