@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 390 lines 13.5 KB
Raw
1 import * as Os from "node:os";
2 import { DEFAULT_API_BASE_URL, type GqlTransport } from "@distilled.cloud/railway";
3 import {
4 AuthError,
5 AuthProviderLayer,
6 NeedsReauth,
7 type ConfigureField,
8 type ConfigureMethod,
9 type ProviderDetails,
10 } from "alchemy/Auth/AuthProvider";
11 import { displayRedacted } from "alchemy/Auth/Credentials";
12 import {
13 getEnv,
14 getEnvRedacted,
15 getEnvRedactedRequired,
16 mapPromptCancellation,
17 } from "alchemy/Auth/Env";
18 import {
19 storedSecret,
20 storedValueText,
21 validateFieldValues,
22 } from "alchemy/Auth/StoredAuthProvider";
23 import * as Interaction from "alchemy/Interaction";
24 import * as Effect from "effect/Effect";
25 import * as Match from "effect/Match";
26 import * as Redacted from "effect/Redacted";
27 import * as Schema from "effect/Schema";
28 import {
29 cancelLoginSession,
30 createLoginSession,
31 loginSessionUrl,
32 pollLoginSessionToken,
33 provideAnonymousRailway,
34 } from "./LoginSession.ts";
35
36 export const RAILWAY_AUTH_PROVIDER_NAME = "Railway";
37 export const RAILWAY_API_TOKEN_ENV = "RAILWAY_API_TOKEN";
38 export const RAILWAY_API_URL_ENV = "RAILWAY_API_URL";
39
40 /** Typed values stored in a Railway provider profile document. */
41 export const RailwayAuthConfigSchema = Schema.Union([
42 Schema.Struct({ method: Schema.Literal("env") }),
43 Schema.Struct({
44 method: Schema.Literal("stored"),
45 token: Schema.String,
46 apiBaseUrl: Schema.optional(Schema.String),
47 }),
48 Schema.Struct({
49 method: Schema.Literal("oauth"),
50 token: Schema.String,
51 apiBaseUrl: Schema.optional(Schema.String),
52 }),
53 ]);
54 export type RailwayAuthConfig = typeof RailwayAuthConfigSchema.Type;
55
56 export type RailwayResolvedCredentials = {
57 type: "token";
58 token: Redacted.Redacted<string>;
59 tokenKind: "account";
60 apiBaseUrl: string;
61 source: { type: RailwayAuthConfig["method"]; details?: string };
62 };
63
64 const options: Array<{ value: RailwayAuthConfig["method"]; label: string; description?: string }> =
65 [
66 {
67 value: "oauth",
68 label: "OAuth (CLI login session)",
69 description: "recommended — open railway.com/cli-login, confirm the pairing code",
70 },
71 {
72 value: "env",
73 label: "Environment Variables",
74 description: `${RAILWAY_API_TOKEN_ENV} + optional ${RAILWAY_API_URL_ENV}`,
75 },
76 {
77 value: "stored",
78 label: "API Token",
79 description: "enter interactively and store inline in the provider file",
80 },
81 ];
82
83 const normalizeApiBaseUrl = (explicit?: string) => {
84 const trimmed = (explicit ?? "").trim().replace(/\/+$/, "");
85 return trimmed.length > 0 ? trimmed : DEFAULT_API_BASE_URL;
86 };
87
88 const resolveApiBaseUrl = (explicit?: string) =>
89 getEnv(RAILWAY_API_URL_ENV).pipe(
90 Effect.map((fromEnv) => normalizeApiBaseUrl(explicit ?? fromEnv)),
91 );
92
93 /**
94 * Layer that registers the Railway {@link AuthProvider} into the
95 * {@link AuthProviders} registry. Include this in the Railway `providers()`
96 * layer so the alchemy CLI can discover it.
97 *
98 * Supported methods:
99 * - `env`: reads `RAILWAY_API_TOKEN` (account Bearer). Project tokens are
100 * not used — they cannot reach workspace-wide operations.
101 * - `stored`: prompts for an API token and stores it in the provider file.
102 * - `oauth`: CLI login session (`loginSessionCreate` → open the pairing URL →
103 * poll `loginSessionVerify` / `loginSessionConsume` → store the token).
104 * Does not require a pre-existing token. An optional `RAILWAY_API_URL`
105 * overrides the backboard host (default `https://backboard.railway.com`).
106 */
107 export const RailwayAuth = AuthProviderLayer<RailwayAuthConfig, RailwayResolvedCredentials>()(
108 RAILWAY_AUTH_PROVIDER_NAME,
109 Effect.gen(function* () {
110 const loginStored = Effect.fn(function* (_profileName: string) {
111 const token = yield* Interaction.password({
112 message: "Railway API Token",
113 validate: (v) => (v.length === 0 ? "Required" : undefined),
114 }).pipe(mapPromptCancellation);
115
116 const envUrl = yield* getEnv(RAILWAY_API_URL_ENV);
117 const urlPrompt = yield* Interaction.text({
118 message: "Railway API URL (Enter for default)",
119 placeholder: DEFAULT_API_BASE_URL,
120 defaultValue: envUrl ?? DEFAULT_API_BASE_URL,
121 }).pipe(mapPromptCancellation);
122 const trimmed = (urlPrompt ?? "").trim();
123 const apiBaseUrl =
124 trimmed.length > 0 && trimmed !== DEFAULT_API_BASE_URL ? trimmed : undefined;
125
126 yield* Interaction.success("Railway: credentials saved.");
127 return { method: "stored" as const, token, apiBaseUrl };
128 });
129
130 const loginOAuth = Effect.fn(function* (_profileName: string) {
131 const apiBaseUrl = yield* resolveApiBaseUrl();
132 const hostname = yield* Effect.sync(() => {
133 try {
134 return Os.hostname();
135 } catch {
136 return "alchemy";
137 }
138 });
139
140 const withAnonymous = <A, E>(effect: Effect.Effect<A, E, GqlTransport>) =>
141 provideAnonymousRailway(effect, apiBaseUrl);
142
143 const code = yield* withAnonymous(createLoginSession()).pipe(
144 Effect.mapError((e) =>
145 AuthError.make({ message: "Railway login session create failed", cause: e }),
146 ),
147 );
148
149 const url = loginSessionUrl(code, { hostname });
150 const cancel = withAnonymous(cancelLoginSession(code)).pipe(Effect.catch(() => Effect.void));
151
152 const token = yield* Interaction.browserLogin({
153 provider: "Railway",
154 url,
155 code,
156 waitFor: withAnonymous(pollLoginSessionToken(code)),
157 }).pipe(
158 mapPromptCancellation,
159 Effect.onInterrupt(() => cancel),
160 Effect.tapError(() => cancel),
161 Effect.mapError((e) =>
162 Schema.is(AuthError)(e)
163 ? e
164 : AuthError.make({ message: "Railway login session poll failed", cause: e }),
165 ),
166 );
167
168 if (token == null) {
169 yield* cancel;
170 return yield* AuthError.make({
171 message: "Railway login session timed out after 5 minutes.",
172 });
173 }
174
175 yield* Interaction.success("Railway: OAuth credentials saved.");
176 return {
177 method: "oauth" as const,
178 token: Redacted.value(token),
179 apiBaseUrl: apiBaseUrl === DEFAULT_API_BASE_URL ? undefined : apiBaseUrl,
180 };
181 });
182
183 const configureInteractive = (profileName: string) =>
184 Interaction.select({ message: "Railway authentication method", options }).pipe(
185 Effect.flatMap((method) =>
186 Match.value(method).pipe(
187 Match.when("env", () =>
188 Effect.gen(function* () {
189 const token = yield* getEnvRedacted(RAILWAY_API_TOKEN_ENV);
190 if (!token) {
191 yield* Interaction.warning(
192 `Railway: ${RAILWAY_API_TOKEN_ENV} is not currently set — export it before deploying.`,
193 );
194 }
195 return { method: "env" as const };
196 }),
197 ),
198 Match.when("stored", () => loginStored(profileName)),
199 Match.when("oauth", () => loginOAuth(profileName)),
200 Match.exhaustive,
201 ),
202 ),
203 );
204
205 const configureCredentials = (profileName: string) =>
206 configureInteractive(profileName).pipe(
207 Effect.mapError((e) =>
208 AuthError.make({ message: "failed to configure credentials", cause: e }),
209 ),
210 );
211
212 /**
213 * Flag-driven (`--method stored --set ...` / `--method env`) fields,
214 * mirroring the interactive prompts. OAuth requires a browser and stays
215 * interactive-only, so it is deliberately absent.
216 */
217 const tokenFields: ReadonlyArray<ConfigureField> = [
218 { name: "token", label: "Railway API Token", secret: true },
219 {
220 name: "apiBaseUrl",
221 label: "Railway API URL",
222 placeholder: DEFAULT_API_BASE_URL,
223 optional: true,
224 },
225 ];
226
227 const configureMethods: ReadonlyArray<ConfigureMethod> = [
228 { method: "stored", fields: tokenFields },
229 { method: "env", fields: [] },
230 ];
231
232 const configureWith = (
233 _profileName: string,
234 input: { readonly method: string; readonly values: Record<string, string> },
235 ): Effect.Effect<RailwayAuthConfig, AuthError, Interaction.Interaction> =>
236 input.method === "stored"
237 ? validateFieldValues(RAILWAY_AUTH_PROVIDER_NAME, tokenFields, input.values).pipe(
238 Effect.map((values) => ({
239 method: "stored" as const,
240 token: Redacted.value(storedSecret(values.token) ?? Redacted.make("")),
241 apiBaseUrl: storedValueText(values.apiBaseUrl),
242 })),
243 Effect.tap(() => Interaction.success("Railway: credentials saved.")),
244 )
245 : input.method === "env"
246 ? Effect.succeed({ method: "env" as const })
247 : Effect.fail(
248 AuthError.make({
249 message: `Railway: unknown method '${input.method}'. Valid methods: stored, env. (OAuth is interactive-only.)`,
250 }),
251 );
252
253 const readStoredToken = (
254 config: Extract<RailwayAuthConfig, { method: "stored" | "oauth" }>,
255 ): Effect.Effect<RailwayResolvedCredentials, AuthError> =>
256 Effect.gen(function* () {
257 const apiBaseUrl = yield* resolveApiBaseUrl(config.apiBaseUrl);
258 return {
259 type: "token" as const,
260 token: Redacted.make(config.token),
261 tokenKind: "account" as const,
262 apiBaseUrl,
263 source: { type: config.method },
264 };
265 });
266
267 const resolveCredentials = (
268 profileName: string,
269 config: RailwayAuthConfig,
270 ): Effect.Effect<RailwayResolvedCredentials, AuthError | NeedsReauth> =>
271 Match.value(config).pipe(
272 Match.when(
273 { method: "env" },
274 Effect.fn(function* () {
275 const token = yield* getEnvRedacted(RAILWAY_API_TOKEN_ENV);
276 if (!token) {
277 return yield* AuthError.make({
278 message: `Railway env credentials not found. Set ${RAILWAY_API_TOKEN_ENV}.`,
279 });
280 }
281 const apiBaseUrl = yield* resolveApiBaseUrl();
282 return {
283 type: "token" as const,
284 token,
285 tokenKind: "account" as const,
286 apiBaseUrl,
287 source: { type: "env" as const, details: RAILWAY_API_TOKEN_ENV },
288 } satisfies RailwayResolvedCredentials;
289 }),
290 ),
291 Match.when({ method: "stored" }, readStoredToken),
292 Match.when({ method: "oauth" }, readStoredToken),
293 Match.exhaustive,
294 );
295
296 const logout = (_profileName: string, config: RailwayAuthConfig) =>
297 Match.value(config).pipe(
298 Match.when({ method: "env" }, () => Effect.void),
299 Match.when({ method: "stored" }, () => Effect.void),
300 // Railway account tokens have no revocation endpoint for CLI-session
301 // tokens, so logout just drops the locally stored token.
302 Match.when({ method: "oauth" }, () => Effect.void),
303 Match.exhaustive,
304 );
305
306 const login = (profileName: string, config: RailwayAuthConfig) =>
307 Match.value(config).pipe(
308 Match.when({ method: "env" }, () =>
309 getEnvRedacted(RAILWAY_API_TOKEN_ENV).pipe(
310 Effect.flatMap((token) =>
311 token
312 ? Effect.void
313 : Effect.fail(
314 AuthError.make({
315 message:
316 `Railway: ${RAILWAY_API_TOKEN_ENV} is not set. Export it, or run ` +
317 `\`alchemy profile edit --profile ${profileName} --reconfigure ${RAILWAY_AUTH_PROVIDER_NAME}\` to switch methods.`,
318 }),
319 ),
320 ),
321 ),
322 ),
323 // Railway account tokens neither expire nor refresh, so login only
324 // (re-)prompts when no credential is stored yet.
325 Match.when({ method: "stored" }, (config) => Effect.succeed(config)),
326 Match.when({ method: "oauth" }, (config) => Effect.succeed(config)),
327 Match.exhaustive,
328 Effect.mapError((e) =>
329 Schema.is(AuthError)(e) ? e : AuthError.make({ message: "login failed", cause: e }),
330 ),
331 );
332
333 const details = (
334 profileName: string,
335 config: RailwayAuthConfig,
336 ): Effect.Effect<ProviderDetails, AuthError | NeedsReauth> =>
337 resolveCredentials(profileName, config).pipe(
338 Effect.map((creds) => ({
339 lines: [
340 { key: "token", value: displayRedacted(creds.token, 6) },
341 { key: "tokenKind", value: creds.tokenKind },
342 { key: "apiBaseUrl", value: creds.apiBaseUrl },
343 {
344 key: "source",
345 value: creds.source.details
346 ? `${creds.source.type} - ${creds.source.details}`
347 : creds.source.type,
348 },
349 ],
350 })),
351 );
352
353 const readEnvironment = Effect.gen(function* () {
354 const token = yield* getEnvRedactedRequired(RAILWAY_API_TOKEN_ENV);
355 const apiBaseUrl = yield* resolveApiBaseUrl();
356 return {
357 type: "token" as const,
358 token,
359 tokenKind: "account" as const,
360 apiBaseUrl,
361 source: { type: "env" as const, details: RAILWAY_API_TOKEN_ENV },
362 } satisfies RailwayResolvedCredentials;
363 });
364
365 return {
366 configSchema: RailwayAuthConfigSchema,
367 configure: configureCredentials,
368 configureWith,
369 configureMethods,
370 logout,
371 login,
372 details,
373 read: resolveCredentials,
374 readEnvironment,
375 environment: [
376 {
377 name: RAILWAY_API_TOKEN_ENV,
378 required: true,
379 secret: true,
380 description: "Account API token (Bearer).",
381 },
382 {
383 name: RAILWAY_API_URL_ENV,
384 required: false,
385 description: "Backboard API base URL override.",
386 },
387 ],
388 };
389 }),
390 );