import { Query } from "@distilled.cloud/core/query";
import {
CredentialsFromToken,
GraphQLLive,
Railway,
type GqlTransport,
} from "@distilled.cloud/railway";
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Schedule from "effect/Schedule";
/** Dashboard host used by `railway login --browserless` pairing URLs. */
export const RAILWAY_CLI_LOGIN_HOST = "https://railway.com";
/**
* Build the Railway CLI pairing URL for a `loginSessionCreate`
* code.
*
* Mirrors `railway login --browserless`: the payload is
* `wordCode={code}&hostname={hostname}` (URL-safe base64) on
* `https://railway.com/cli-login?d=…`. The user confirms the pairing code
* in the browser; `loginSessionAuth` is the dashboard-side
* mutation that marks the session authorized. `loginSessionVerify`
* is a liveness check (true while the pairing session exists). The CLI then
* polls `loginSessionConsume` until a token is returned.
*
* Alchemy's AuthProvider `method: "oauth"` runs this flow: create → print
* the pairing URL → poll consume → store the token.
*
* ### Pairing URL
* **Example:** From a session code
* ```typescript
* const code = yield* createLoginSession();
* const url = loginSessionUrl(code, { hostname: "dev-box" });
* ```
*/
export const loginSessionUrl = (
code: string,
options?: { hostname?: string; host?: string },
): string => {
const hostname = options?.hostname ?? "alchemy";
const host = (options?.host ?? RAILWAY_CLI_LOGIN_HOST).replace(/\/+$/, "");
const payload = `wordCode=${code}&hostname=${hostname}`;
const encoded = Buffer.from(payload).toString("base64").replace(/\+/g, "-").replace(/\//g, "_");
return `${host}/cli-login?d=${encoded}`;
};
/**
* Credentials layer that sends no `Authorization` header. Login-session
* mutations are public: they run before the user has a token.
*/
const anonymousRailwayCredentials = (apiBaseUrl?: string) =>
CredentialsFromToken({ token: Redacted.make(""), tokenKind: "account", apiBaseUrl });
const anonymousRailway = (apiBaseUrl?: string) =>
Layer.mergeAll(GraphQLLive, anonymousRailwayCredentials(apiBaseUrl), FetchHttpClient.layer);
export const provideAnonymousRailway = <A, E>(
effect: Effect.Effect<A, E, GqlTransport>,
apiBaseUrl?: string,
): Effect.Effect<A, E> => effect.pipe(Effect.provide(anonymousRailway(apiBaseUrl)));
const LOGIN_POLL_TIMES = 300;
export const createLoginSession = Query.fn(() => Railway.loginSessionCreate());
export const cancelLoginSession = Query.fn((code: string) => Railway.loginSessionCancel({ code }));
const verifyLoginSession = Query.fn((code: string) => Railway.loginSessionVerify({ code }));
const consumeLoginSession = Query.fn((code: string) => Railway.loginSessionConsume({ code }));
/**
* Poll `loginSessionVerify` then
* `loginSessionConsume` until a token is returned, or 5 minutes
* elapse. Mirrors `railway login --browserless`: consume is the token source;
* verify is a liveness check. Does not cancel the session — the caller should
* cancel on timeout or interrupt.
*
* Exhaustion returns `undefined` (not a failure) so the AuthProvider can
* surface a timeout rather than a poll error.
*/
export const pollLoginSessionToken = (code: string) =>
verifyLoginSession(code).pipe(
Effect.catchTag("RailwayNotFound", () => Effect.succeed(false)),
Effect.flatMap(() =>
consumeLoginSession(code).pipe(
Effect.catchTag("RailwayNotFound", () => Effect.succeed(null)),
),
),
Effect.map((token) => (token != null && Redacted.value(token).length > 0 ? token : undefined)),
Effect.repeat({
schedule: Schedule.spaced("1 second"),
while: (token) => token == null,
times: LOGIN_POLL_TIMES,
}),
);