Merge build/412-cli-login-and-credential-helper: log in once, then plain git pushes to the platform with no token in the URL and no prompt
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents ec8396c, 712ba61 · Browse files · 6 files·+2459 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+2459 added−18 removed
- tests:+1472 added−4 removed
- other:+987 added−14 removed
Provenance
- Commit
fa30de3- Tree
c8b4b93- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
ec8396c- Parent 2
712ba61
6 files changed+2459 added−18 removed
modified:apps/cli/src/local/login.ts+730 added-9 removed
1+/**2+ * `login` and `logout`. A person logs in once, through the browser (PKCE3+ * against the platform's own OAuth server, W3 316) or with a token piped to4+ * `--token-stdin`; the CLI checks the token with the platform, keeps it as5+ * a profile (`Credentials`), and names `git-credential-<slug>` in git's6+ * global config for the platform's url, so plain `git clone`, `fetch` and7+ * `push` work with no token in a url and no prompt. Profiles let one8+ * machine act for several people (`<SLUG>_PROFILE=<name>`).9+ *10+ * The token stays `Redacted` from stdin or `/token` to the credentials11+ * file; it is written out only in the `Authorization` header that checks12+ * it, and later in the helper's `password=` line.13+ */14+import { BunHttpServer } from "@effect/platform-bun";15+import { Brand } from "@repo/brand";16+import { detectHarness } from "@repo/protocol/audit";17+import { Contracts } from "@repo/protocol/contracts";18+import type { Client } from "@repo/protocol/contracts";19+import {20+ Deferred,21+ Context,22+ Effect,23+ Layer,24+ Option,25+ Redacted,26+ Schema,27+ Stdio,28+ Stream,29+} from "effect";1-import { Effect } from "effect";2-import { Command } from "effect/cli";30+import type { Scope } from "effect";31+import { Command, Flag } from "effect/cli";32+import {33+ FetchHttpClient,34+ HttpClient,35+ HttpClientRequest,36+ HttpServerRequest,37+ HttpServerResponse,38+} from "effect/http";39+import type { HttpServer, HttpServerError } from "effect/http";40+import { ChildProcess, ChildProcessSpawner } from "effect/process";41+import { RpcClient, RpcSerialization } from "effect/rpc";42 4-/** `login`: issue 412 replaces this stub (PKCE, or `--token-stdin`). */5-export const login = Command.make("login", {}, () =>6- Effect.die("not built: issue 412")43+import { currentEnv } from "../credential-helper.ts";44+import { Credentials, gitHelperConfig } from "../credentials.ts";45+import type { Profile } from "../credentials.ts";46+import { Output } from "../output.ts";47+48+/** The env names the CLI reads, spelled from the brand: `<SLUG>_URL`. */49+const SLUG = Brand.slug.toUpperCase();50+51+/** The address the loopback server binds: this machine only. */52+const LOOPBACK = "127.0.0.1";53+54+/** How long `login` waits for the browser to come back. */55+const SIGN_IN_WAIT = "5 minutes";56+57+/**58+ * The CLI's OAuth client id on a platform: the URL of the Client ID59+ * Metadata Document the platform serves for it (W3 316,60+ * `apps/platform/src/auth/cli-client.ts`). It asks for no scope.61+ */62+const clientIdOf = (origin: string) => `${origin}/oauth/cli`;63+64+// --- The host seams: each has a default the binary runs on, and tests swap it.65+66+/**67+ * Where `login` hears the browser come back: an HTTP server on one address,68+ * for one scope. The binary listens with Bun.69+ */70+export const Loopback = Context.Reference<{71+ readonly listen: (address: {72+ readonly hostname: string;73+ readonly port: number;74+ }) => Effect.Effect<75+ HttpServer.HttpServer["Service"],76+ HttpServerError.ServeError,77+ Scope.Scope78+ >;79+}>("cli/login/Loopback", {80+ defaultValue: () => ({81+ listen: ({ hostname, port }) => BunHttpServer.make({ hostname, port }),82+ }),83+});84+85+/**86+ * A client of the platform at `url` that presents `token` as its bearer:87+ * what `login` checks a token with before it keeps it. The binary's calls88+ * go over HTTP to `<url>/rpc`.89+ */90+export const PlatformClient = Context.Reference<{91+ readonly connect: (profile: {92+ readonly token: Redacted.Redacted;93+ readonly url: string;94+ }) => Effect.Effect<Client["Service"], never, Scope.Scope>;95+}>("cli/login/PlatformClient", {96+ defaultValue: () => ({97+ connect: ({ token, url }) =>98+ RpcClient.make(Contracts).pipe(99+ Effect.provide(100+ RpcClient.layerProtocolHttp({101+ transformClient: HttpClient.mapRequest(102+ HttpClientRequest.bearerToken(token)103+ ),104+ url: `${url}/rpc`,105+ }).pipe(106+ Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])107+ )108+ )109+ ),110+ }),111+});112+113+/** Opens `url` with the first of `commands` that runs; none running is fine. */114+const openWith = (url: string, commands: readonly string[]) =>115+ Effect.gen(function* () {116+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;117+118+ for (const command of commands) {119+ const code = yield* spawner120+ .exitCode(121+ ChildProcess.make(command, [url], {122+ stderr: "ignore",123+ stdin: "ignore",124+ stdout: "ignore",125+ })126+ )127+ .pipe(Effect.timeout("10 seconds"), Effect.option);128+129+ if (Option.exists(code, (exit) => exit === 0)) {130+ return;131+ }132+ }133+ });134+135+/**136+ * The person's browser. The binary asks the desktop's opener (`xdg-open`,137+ * else macOS's `open`); the URL is printed either way.138+ */139+export const Browser = Context.Reference<{140+ readonly open: (141+ url: string142+ ) => Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner>;143+}>("cli/login/Browser", {144+ defaultValue: () => ({145+ open: (url) => openWith(url, ["xdg-open", "open"]),146+ }),147+});148+149+// --- Failures.150+151+/** `login` was run in a way that cannot work; the message says what to run. */152+export class LoginUsage extends Schema.TaggedError<LoginUsage>()("LoginUsage", {153+ reason: Schema.String,154+}) {155+ override get message() {156+ return this.reason;157+ }158+}159+160+/** The platform, or the sign-in, said no; nothing was stored. */161+export class LoginRefused extends Schema.TaggedError<LoginRefused>()(162+ "LoginRefused",163+ { reason: Schema.String }164+) {165+ override get message() {166+ return this.reason;167+ }168+}169+170+/** git would not take a config line; the message names it, to run by hand. */171+export class GitConfigFailed extends Schema.TaggedError<GitConfigFailed>()(172+ "GitConfigFailed",173+ { command: Schema.String }174+) {175+ override get message() {176+ return `git did not take this; run it yourself: ${this.command}`;177+ }178+}179+180+// --- Shared parts.181+182+const flags = {183+ json: Flag.Boolean("json").pipe(184+ Flag.withDefault(false),185+ Flag.withDescription("Print machine-readable JSON")186+ ),187+ profile: Flag.String("profile").pipe(188+ Flag.withDescription(189+ `The profile to use (default: $${SLUG}_PROFILE, else "default")`190+ ),191+ Flag.optional192+ ),193+};194+195+/** The profile a command acts on: the flag, else `<SLUG>_PROFILE`, else `default`. */196+const profileName = (197+ flag: Option.Option<string>,198+ env: Readonly<Record<string, string>>199+) => Option.getOrElse(flag, () => env[`${SLUG}_PROFILE`] ?? "default");200+201+/** An argv list as a person would type it in a shell. */202+const typed = (argv: readonly string[]) =>203+ argv204+ .map((arg) => {205+ if (arg === "") {206+ return '""';207+ }208+209+ return /^[\w./:@=-]+$/u.test(arg)210+ ? arg211+ : `'${arg.replaceAll("'", String.raw`'\''`)}'`;212+ })213+ .join(" ");214+215+/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */216+const runGit = (217+ argv: readonly string[],218+ env: Readonly<Record<string, string>>,219+ allowed: readonly number[] = [0]220+) =>221+ Effect.gen(function* () {222+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;223+ const [command = "git", ...args] = argv;224+225+ const code = yield* spawner226+ .exitCode(227+ ChildProcess.make(command, args, {228+ env,229+ extendEnv: true,230+ stderr: "ignore",231+ stdin: "ignore",232+ stdout: "ignore",233+ })234+ )235+ .pipe(Effect.option);236+237+ return Option.exists(code, (exit) => allowed.includes(exit))238+ ? undefined239+ : yield* new GitConfigFailed({ command: typed(argv) });240+ });241+242+const asUrl = Option.liftThrowable((text: string) => new URL(text));243+244+/** Hosts that are this machine, where plain http keeps a token local. */245+const THIS_MACHINE = new Set(["localhost", "127.0.0.1", "[::1]"]);246+247+/** `given`'s origin, if it is a platform url: https, or http on this machine. */248+const originOf = (given: string) =>249+ Option.match(250+ Option.filter(251+ asUrl(given),252+ ({ hostname, protocol }) =>253+ protocol === "https:" ||254+ (protocol === "http:" && THIS_MACHINE.has(hostname))255+ ),256+ {257+ onNone: () =>258+ Effect.fail(259+ new LoginUsage({260+ reason: `${given} is not a platform url: use https://<host> (plain http only for this machine)`,261+ })262+ ),263+ onSome: ({ origin }) => Effect.succeed(origin),264+ }265+ );266+267+/**268+ * The platform to log in to: `--url`, else `<SLUG>_URL`, else the profile's269+ * own. `Credentials` reads back only the current profile, so another270+ * profile named by `--profile` needs `--url`: it is never logged in to the271+ * current profile's platform by default.272+ */273+const platformOf = (274+ flag: Option.Option<string>,275+ profile: Option.Option<string>,276+ env: Readonly<Record<string, string>>277+) =>278+ Effect.gen(function* () {279+ const named = Option.orElse(flag, () =>280+ Option.fromNullishOr(env[`${SLUG}_URL`])281+ );282+283+ if (Option.isSome(named)) {284+ return yield* originOf(named.value);285+ }286+287+ const name = profileName(profile, env);288+289+ const current =290+ name === profileName(Option.none(), env)291+ ? yield* (yield* Credentials).current292+ : Option.none<Profile>();293+294+ if (Option.isSome(current)) {295+ return yield* originOf(current.value.url);296+ }297+298+ return yield* new LoginUsage({299+ reason: `no platform to log in to for profile ${name}: run ${Brand.cli} login --url https://<platform host>${Option.isSome(profile) ? ` --profile ${name}` : ""}`,300+ });301+ });302+303+// --- The token, by one of two ways.304+305+/** The token piped to `--token-stdin`: its first line, read no further. */306+const tokenFromStdin = Effect.gen(function* () {307+ const { stdin } = yield* Stdio.Stdio;308+309+ const [line = ""] = yield* stdin.pipe(310+ Stream.decodeText(),311+ Stream.splitLines,312+ Stream.take(1),313+ Stream.runCollect,314+ Effect.orElseSucceed((): readonly string[] => [])315+ );316+317+ const token = line.trim();318+319+ if (token === "") {320+ return yield* new LoginUsage({321+ reason: `--token-stdin read no token: pipe it in, one line, e.g. ${Brand.cli} login --token-stdin < token.txt`,322+ });323+ }324+325+ return Redacted.make(token);326+});327+328+const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);329+330+/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */331+const randomText = (size: number) =>332+ Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(333+ Effect.flatMap(encodeBase64Url),334+ Effect.orDie335+ );336+337+/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */338+const challengeOf = (verifier: string) =>339+ Effect.promise(() =>340+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))341+ ).pipe(342+ Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),343+ Effect.orDie344+ );345+346+/**347+ * A server on 127.0.0.1 at a port the system picks, for this scope, that348+ * takes the browser's one return to `/callback`: its `redirect_uri`, and349+ * the query the browser brought back.350+ */351+const loopback = Effect.gen(function* () {352+ const { listen } = yield* Loopback;353+ const server = yield* listen({ hostname: LOOPBACK, port: 0 });354+ const returned = yield* Deferred.make<URLSearchParams>();355+356+ yield* server.serve(357+ Effect.gen(function* () {358+ const request = yield* HttpServerRequest.HttpServerRequest;359+ const at = new URL(request.url, `http://${LOOPBACK}`);360+361+ if (request.method !== "GET" || at.pathname !== "/callback") {362+ return HttpServerResponse.text("Not found.", { status: 404 });363+ }364+365+ const first = yield* Deferred.succeed(returned, at.searchParams);366+367+ return HttpServerResponse.text(368+ first369+ ? `${Brand.cli} login has the sign-in. You can close this tab; the terminal says how it ended.`370+ : "This sign-in has already come back.",371+ {372+ // One request per connection, so closing the server waits on none.373+ headers: { "cache-control": "no-store", connection: "close" },374+ status: first ? 200 : 410,375+ }376+ );377+ })378+ );379+380+ if (!("port" in server.address)) {381+ return yield* Effect.die("the loopback server listens on a socket");382+ }383+384+ return {385+ redirectUri: `http://${LOOPBACK}:${server.address.port}/callback`,386+ returned: Deferred.await(returned),387+ };388+});389+390+/** What `/token` answers a good code with. */391+const TokenResponse = Schema.Struct({392+ access_token: Schema.RedactedFromValue(Schema.NonEmptyString),393+ token_type: Schema.String,394+});395+396+const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);397+398+/** Trades the code for an access token at `<url>/token`, showing the verifier. */399+const exchange = (input: {400+ readonly code: string;401+ readonly redirectUri: string;402+ readonly url: string;403+ readonly verifier: string;404+}) => {405+ const refused = new LoginRefused({406+ reason: `${input.url}/token would not trade the sign-in for a token: run ${Brand.cli} login again`,407+ });408+409+ return Effect.gen(function* () {410+ const client = yield* HttpClient.HttpClient;411+412+ const response = yield* client.execute(413+ HttpClientRequest.post(`${input.url}/token`).pipe(414+ HttpClientRequest.acceptJson,415+ HttpClientRequest.bodyUrlParams({416+ client_id: clientIdOf(input.url),417+ code: input.code,418+ code_verifier: input.verifier,419+ grant_type: "authorization_code",420+ redirect_uri: input.redirectUri,421+ })422+ )423+ );424+425+ if (response.status !== 200) {426+ return yield* refused;427+ }428+429+ const body = yield* decodeTokenResponse(yield* response.json);430+431+ if (body.token_type.toLowerCase() !== "bearer") {432+ return yield* refused;433+ }434+435+ return body.access_token;436+ }).pipe(437+ Effect.provide(FetchHttpClient.layer),438+ Effect.mapError(() => refused)439+ );440+};441+442+/**443+ * The token from a browser sign-in: PKCE (S256) against the platform's444+ * `/authorize`, its code at the loopback server, then `/token`. The URL is445+ * always printed; the browser opens only when `opens`. Waits at most five446+ * minutes for the browser, then stops with a usage error.447+ */448+const tokenFromBrowser = (url: string, opens: boolean) =>449+ Effect.scoped(450+ Effect.gen(function* () {451+ const output = yield* Output;452+ const verifier = yield* randomText(32);453+ const state = yield* randomText(32);454+ const { redirectUri, returned } = yield* loopback;455+456+ const authorize = new URL("/authorize", url);457+458+ authorize.search = new URLSearchParams({459+ client_id: clientIdOf(url),460+ code_challenge: yield* challengeOf(verifier),461+ code_challenge_method: "S256",462+ redirect_uri: redirectUri,463+ response_type: "code",464+ state,465+ }).toString();466+467+ const query = yield* Effect.gen(function* () {468+ yield* output.note(469+ opens470+ ? `Opening a browser to sign in to ${url}. If it does not open, visit:\n ${authorize.href}`471+ : `To sign in to ${url}, open this in a browser:\n ${authorize.href}`472+ );473+474+ if (opens) {475+ yield* (yield* Browser).open(authorize.href);476+ }477+478+ return yield* returned;479+ }).pipe(480+ Effect.timeoutOrElse({481+ duration: SIGN_IN_WAIT,482+ orElse: () =>483+ Effect.fail(484+ new LoginUsage({485+ reason: `no sign-in came back within ${SIGN_IN_WAIT}: run ${Brand.cli} login again, or pipe a token to ${Brand.cli} login --token-stdin`,486+ })487+ ),488+ })489+ );490+491+ if (query.get("state") !== state) {492+ return yield* new LoginRefused({493+ reason: `the sign-in came back with another state, so it may not be yours; nothing was stored: run ${Brand.cli} login again`,494+ });495+ }496+497+ const code = query.get("code");498+499+ if (code === null || code === "") {500+ return yield* new LoginRefused({501+ reason: `${url} did not sign you in (${query.get("error") ?? "no code"}): run ${Brand.cli} login again`,502+ });503+ }504+505+ return yield* exchange({ code, redirectUri, url, verifier });506+ })507+ );508+509+/** The handle `status` shows: the claimant of the caller's claims, if any. */510+const handleOf = (status: {511+ readonly claims: readonly { readonly claimant: Profile["handle"] }[];512+}) => Option.fromNullishOr(status.claims[0]?.claimant);513+514+/** Asks the platform at `url` who `token` is; a refusal or no answer stores nothing. */515+const verify = (url: string, token: Redacted.Redacted) =>516+ Effect.scoped(517+ Effect.gen(function* () {518+ const client = yield* (yield* PlatformClient).connect({ token, url });519+520+ return handleOf(yield* client.status({}));521+ })522+ ).pipe(523+ Effect.mapError(524+ () =>525+ new LoginRefused({526+ reason: `${url} did not take this token, or could not be reached; nothing was stored`,527+ })528+ )529+ );530+531+/** Whether `login` may open a browser: only for a person at a terminal. */532+const mayOpenBrowser = (env: Readonly<Record<string, string>>) =>533+ Effect.gen(function* () {534+ const { mode } = yield* Output;535+ const { stdoutIsTerminal } = yield* Stdio.Stdio;536+537+ return (538+ mode === "human" &&539+ detectHarness(env).harness === undefined &&540+ env.CI === undefined &&541+ (yield* stdoutIsTerminal)542+ );543+ });544+545+/** The lines of a view: a sentence, then each command on its own line. */546+const viewOf = (said: string, commands: readonly (readonly string[])[]) => {547+ const lines = commands.map((argv) => typed(argv));548+549+ return {550+ markdown:551+ lines.length === 0552+ ? said553+ : `${said}\n\n\`\`\`sh\n${lines.join("\n")}\n\`\`\``,554+ text: [said, ...lines.map((line) => ` ${line}`)].join("\n"),555+ };556+};557+558+export const login = Command.make(559+ "login",560+ {561+ ...flags,562+ noBrowser: Flag.Boolean("no-browser").pipe(563+ Flag.withDefault(false),564+ Flag.withDescription("Print the sign-in URL instead of opening a browser")565+ ),566+ noGitConfig: Flag.Boolean("no-git-config").pipe(567+ Flag.withDefault(false),568+ Flag.withDescription(569+ "Leave git's config alone; print the lines to set instead"570+ )571+ ),572+ tokenStdin: Flag.Boolean("token-stdin").pipe(573+ Flag.withDefault(false),574+ Flag.withDescription(575+ "Read a token you were given from stdin, one line, instead of signing in"576+ )577+ ),578+ url: Flag.String("url").pipe(579+ Flag.withDescription(580+ `The platform's origin, e.g. https://<host> (default: $${SLUG}_URL, else the profile's)`581+ ),582+ Flag.optional583+ ),584+ },585+ (given) =>586+ Effect.gen(function* () {587+ const output = yield* Output;588+ const credentials = yield* Credentials;589+ const env = yield* currentEnv;590+ const name = profileName(given.profile, env);591+ const url = yield* platformOf(given.url, given.profile, env);592+593+ const token = given.tokenStdin594+ ? yield* tokenFromStdin595+ : yield* tokenFromBrowser(596+ url,597+ !given.noBrowser && (yield* mayOpenBrowser(env))598+ );599+600+ const handle = yield* verify(url, token);601+602+ yield* credentials.put(603+ name,604+ Option.match(handle, {605+ onNone: (): Profile => ({ token, url }),606+ onSome: (who): Profile => ({ handle: who, token, url }),607+ })608+ );609+610+ const commands = gitHelperConfig(url);611+612+ if (!given.noGitConfig) {613+ for (const argv of commands) {614+ yield* runGit(argv, env);615+ }616+ }617+618+ const who = Option.match(handle, {619+ onNone: () => "",620+ onSome: (known) => ` as ${known}`,621+ });622+623+ yield* output.success({624+ command: "login",625+ data: {626+ // The lines, set or not: under --no-git-config they are what to run.627+ gitConfig: commands,628+ gitConfigSet: !given.noGitConfig,629+ ...Option.match(handle, {630+ onNone: () => ({}),631+ onSome: (known) => ({ handle: known }),632+ }),633+ profile: name,634+ url,635+ },636+ json: given.json,637+ view: viewOf(638+ given.noGitConfig639+ ? `Logged in to ${url}${who} (profile ${name}). git's config is unchanged; for git to use this login, run:`640+ : `Logged in to ${url}${who} (profile ${name}). git now asks ${Brand.cli} for this platform's token; its global config got:`,641+ commands642+ ),643+ });644+ })645 ).pipe(646 Command.withDescription(647 "Sign in to a platform; git and this CLI then use its token."648 )649 );650 13-/** `logout`: issue 412 replaces this stub. */14-export const logout = Command.make("logout", {}, () =>15- Effect.die("not built: issue 412")16-).pipe(Command.withDescription("Forget a platform's stored token."));651+/** The `git config --global` lines that undo `gitHelperConfig(url)`; exit 5 means already gone. */652+const gitHelperUnset = (url: string): readonly (readonly string[])[] => [653+ ["git", "config", "--global", "--unset-all", `credential.${url}.helper`],654+ ["git", "config", "--global", "--unset-all", `credential.${url}.useHttpPath`],655+];656+657+const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;658+659+/** The urls whose git config names this CLI's helper. */660+const helperUrls = (env: Readonly<Record<string, string>>) =>661+ Effect.gen(function* () {662+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;663+664+ const lines = yield* spawner665+ .lines(666+ ChildProcess.make(667+ "git",668+ [669+ "config",670+ "--global",671+ "--get-regexp",672+ String.raw`^credential\..*\.helper$`,673+ ],674+ { env, extendEnv: true, stderr: "ignore", stdin: "ignore" }675+ )676+ )677+ .pipe(Effect.orElseSucceed((): readonly string[] => []));678+679+ const urls = lines.flatMap((line) => {680+ const space = line.indexOf(" ");681+ const key = space === -1 ? line : line.slice(0, space);682+ const value = space === -1 ? "" : line.slice(space + 1);683+ const url = HELPER_KEY.exec(key)?.groups?.url;684+685+ return value === Brand.slug && url !== undefined ? [url] : [];686+ });687+688+ return [...new Set(urls)];689+ });690+691+export const logout = Command.make("logout", flags, (given) =>692+ Effect.gen(function* () {693+ const output = yield* Output;694+ const credentials = yield* Credentials;695+ const env = yield* currentEnv;696+ const name = profileName(given.profile, env);697+ const removed = yield* credentials.remove(name);698+699+ // git keeps asking the helper for a platform another profile is still on.700+ const unused: string[] = [];701+702+ for (const url of yield* helperUrls(env)) {703+ const host = Option.map(asUrl(url), ({ host: at }) => at);704+705+ if (706+ Option.isSome(host) &&707+ Option.isNone(yield* credentials.forHost(host.value))708+ ) {709+ unused.push(url);710+ }711+ }712+713+ const commands = unused.flatMap(gitHelperUnset);714+715+ for (const argv of commands) {716+ yield* runGit(argv, env, [0, 5]);717+ }718+719+ yield* output.success({720+ command: "logout",721+ data: { gitConfig: commands, profile: name, removed },722+ json: given.json,723+ view: viewOf(724+ `${removed ? `Logged out: profile ${name} removed.` : `No profile ${name} to remove.`}${725+ commands.length === 0726+ ? ""727+ : ` git no longer asks ${Brand.cli} for ${unused.join(", ")}; its global config lost:`728+ }`,729+ commands730+ ),731+ });732+ })733+).pipe(734+ Command.withDescription(735+ "Forget a profile's token, and stop git asking for a platform no profile is on."736+ )737+);modified:apps/cli/src/credential-helper.ts+257 added-5 removed
12345678910111213141516171819202112222324456252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263/** * git's credential helper: `git-credential-<slug>`, which `login` names in * git's config for the platform's url (`gitHelperConfig`). git asks it for a * password after a 401 that names Basic; it answers from the stored profile * for that host, and never prompts, opens a terminal, or reads past the * blank line that ends git's request. * * The username it hands back carries the harness behind the push as audit * metadata (`@repo/protocol/audit`), never identity: the token in the * password slot is the only identity the platform reads. */import { Brand } from "@repo/brand";import { auditUser, detectHarness } from "@repo/protocol/audit";import { ConfigProvider, Effect, Match, Option, Redacted, Stdio, Stream,import { Effect } from "effect";import { Command } from "effect/cli";} from "effect";import { Argument, Command } from "effect/cli";
/** `credential <get|store|erase>`, git's credential helper: issue 412 replaces this stub. */export const credential = Command.make("credential", {}, () => Effect.die("not built: issue 412")import { Credentials } from "./credentials.ts";import { Output } from "./output.ts";
/** What git asks a helper to do. */export type Operation = "get" | "store" | "erase";
const operations = [ "get", "store", "erase",] as const satisfies readonly Operation[];
/** The env, by name: what `detectHarness` reads. */export type Env = Readonly<Record<string, string | undefined>>;
/** * The most indices the walk reads under one name. The config provider tells * an all-numeric level only its largest index, so a name like * `RUN_4294967294` would have the walk count to four billion on every git * call; names with an index past this are not read. No harness marker ends * in a number, and the binary's git child gets the process env whole. */const INDEX_LIMIT = 1024;
/** The env-name parts below `path` and their values, from the CLI's config provider. */const namesBelow = ( provider: ConfigProvider.ConfigProvider, path: ConfigProvider.Path): Effect.Effect<readonly (readonly [string, string])[]> => provider.load(path).pipe( Effect.map(Option.fromNullishOr), Effect.orElseSucceed(() => Option.none<ConfigProvider.Node>()), Effect.flatMap( Option.match({ onNone: () => Effect.succeed([]), onSome: (node) => { const own = path.length > 0 && node.value !== undefined ? [[path.join("_"), node.value] as const] : [];
const children = Match.valueTags(node, { Array: ({ length }) => Array.from({ length: Math.min(length, INDEX_LIMIT) }, (_, at) => String(at) ), Record: ({ keys }) => [...keys], Value: () => [], });
return Effect.map( Effect.forEach(children, (child) => namesBelow(provider, [...path, child]) ), (nested) => [...own, ...nested.flat()] ); }, }) ) );
/** * The env as the CLI sees it, every name with its value: read through the * config provider (the process env when nothing else is given), so a test's * env is the one a command sees and passes on. */export const currentEnv: Effect.Effect<Readonly<Record<string, string>>> = Effect.gen(function* () { const provider = yield* ConfigProvider.ConfigProvider;
return Object.fromEntries(yield* namesBelow(provider, [])); });
/** git's request: its `key=value` lines, up to the blank line that ends it. */const requestOf = (input: string) => { const fields = new Map<string, string>();
for (const line of input.split("\n")) { if (line === "") { break; }
const equals = line.indexOf("=");
if (equals > 0) { fields.set(line.slice(0, equals), line.slice(equals + 1)); } }
return fields;};
/** The env names the CLI reads, spelled from the brand: `<SLUG>_PROFILE`. */const SLUG = Brand.slug.toUpperCase();
/** `url`'s scheme without its colon, and its `host[:port]` in lowercase, if it is a URL. */const placeOf = Option.liftThrowable((url: string) => { const { host, protocol } = new URL(url);
return { host: host.toLowerCase(), scheme: protocol.replace(/:$/u, "") };});
/** A value git's credential protocol can carry: one line, no NUL. */const fitsOneLine = (value: string) => !/[\n\r\0]/u.test(value);
/** What the helper prints: for git on stdout, and maybe a line for a person on stderr. */interface Answer { readonly stdout: string; readonly note: Option.Option<string>;}
const silent: Answer = { note: Option.none(), stdout: "" };
/** * The helper's answer to `op` with git's `input`. `get` answers only for a * host a profile is on, over that profile's scheme. Under `<SLUG>_PROFILE` * only that profile may answer: it names the person git acts for, so the * helper never hands over another person's token for the same host. With no * login for the profile in use, it also says, once, how to log in. `store` * and `erase` do nothing: the stored token changes only through `login` * and `logout`. */const answer = (op: Operation, input: string, env: Env) => Effect.gen(function* () { if (op !== "get") { return silent; }
const request = requestOf(input); const host = request.get("host"); const protocol = request.get("protocol");
if (host === undefined || protocol === undefined) { return silent; }
const credentials = yield* Credentials;
const named = Option.filter( Option.fromNullishOr(env[`${SLUG}_PROFILE`]), (name) => name !== "" );
const candidate = Option.isSome(named) ? yield* credentials.current : yield* credentials.forHost(host);
const profile = Option.filter( candidate, ({ token, url }) => Option.exists( placeOf(url), (at) => at.scheme === protocol && at.host === host.toLowerCase() ) && fitsOneLine(Redacted.value(token)) );
if (Option.isSome(profile)) { return { note: Option.none(), stdout: `username=${auditUser(detectHarness(env))}\npassword=${Redacted.value(profile.value.token)}\n`, } satisfies Answer; }
const flag = Option.match(named, { onNone: () => "", onSome: (name) => ` --profile ${name}`, });
return Option.isNone(yield* credentials.current) ? { note: Option.some( `no ${Brand.cli} login for ${host}: run ${Brand.cli} login${flag} --url ${protocol}://${host}` ), stdout: "", } : silent; });
/** * What the helper prints on stdout for `op`, given git's `input` and the * env it runs in: `username=<audit>\npassword=<token>\n`, or nothing. */export const credentialHelper = ( op: Operation, input: string, env: Env): Effect.Effect<string, never, Credentials> => Effect.map(answer(op, input, env), ({ stdout }) => stdout);
/** * git's request from stdin: the lines up to the first blank one, read no * further, or up to the end if git closes stdin first. */const readRequest = Effect.gen(function* () { const { stdin } = yield* Stdio.Stdio;
const lines = yield* stdin.pipe( Stream.decodeText(), Stream.splitLines, Stream.takeWhile((line) => line !== ""), Stream.runCollect, Effect.orElseSucceed((): readonly string[] => []) );
return `${lines.join("\n")}\n\n`;});
/** `<cli> credential <get|store|erase>`: what `git-credential-<slug>` runs. */export const credential = Command.make( "credential", { operation: Argument.Literals("operation", operations).pipe( Argument.withDescription("What git asks: get, store or erase") ), }, ({ operation }) => Effect.gen(function* () { const stdio = yield* Stdio.Stdio; const output = yield* Output; const request = yield* readRequest; const given = yield* answer(operation, request, yield* currentEnv);
if (given.stdout !== "") { yield* Stream.make(given.stdout).pipe( Stream.run(stdio.stdout()), Effect.orDie ); }
yield* Option.match(given.note, { onNone: () => Effect.void, onSome: output.note, }); })).pipe( Command.withDescription( "Be git's credential helper: hand git the stored token for a platform." ));added:apps/cli/test/local/credential-helper.test.ts+497 added
1+import { NodeHttpServer, NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client } from "@repo/protocol/contracts";5+import { gitOk, spawn } from "@repo/testkit/git";6+import { httpBackend } from "@repo/testkit/http-backend";7+import {8+ ConfigProvider,9+ Context,10+ Effect,11+ Exit,12+ FileSystem,13+ Layer,14+ Option,15+ Path,16+ Predicate,17+ Queue,18+ Redacted,19+ Ref,20+ Schema,21+ Sink,22+ Stdio,23+ Stream,24+ Terminal,25+} from "effect";26+import type { Cause } from "effect";27+import { CliOutput } from "effect/cli";28+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";29+import type { ChildProcessSpawner } from "effect/process";30+import { TestConsole } from "effect/testing";31+32+import { credentialHelper, currentEnv } from "../../src/credential-helper.ts";33+import { Credentials, CredentialsFile } from "../../src/credentials.ts";34+import type { Profile } from "../../src/credentials.ts";35+import { program } from "../../src/main.ts";36+import { OutputPlain } from "../../src/output.ts";37+38+/** The env names the CLI reads, spelled from the brand. */39+const SLUG = Brand.slug.toUpperCase();40+41+const token = "t0ken-0123456789abcdefghijklmnopqrstuvwxyz";42+43+const platform: Profile = {44+ token: Redacted.make(token),45+ url: "https://platform.test",46+};47+48+/** What git writes to its helper for a repo on `host`, blank line and all. */49+const asked = (host: string, protocol = "https") =>50+ `protocol=${protocol}\nhost=${host}\npath=datekit--fix-week--alice.git\n\n`;51+52+/** A pi session's env, as pi hands it to the git it runs. */53+const pi = { AI_AGENT: "pi", PI_MODEL: "kimi-k3" };54+55+const encoder = new TextEncoder();56+57+const decoder = new TextDecoder();58+59+/** The credentials file in the config dir `env` names. */60+const credentialsIn = (env: Record<string, string>) =>61+ CredentialsFile.pipe(62+ Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))63+ );64+65+/**66+ * A fresh config dir holding `profiles`, and the env that names it: the67+ * shell a person who ran `login` would give git.68+ */69+const storedIn = (profiles: Readonly<Record<string, Profile>>) =>70+ Effect.gen(function* () {71+ const fs = yield* FileSystem.FileSystem;72+ const dir = yield* fs.makeTempDirectoryScoped();73+ const env = { HOME: "/nonexistent", XDG_CONFIG_HOME: dir };74+75+ const credentials = yield* Effect.provide(76+ Effect.service(Credentials),77+ credentialsIn(env)78+ );79+80+ for (const [name, profile] of Object.entries(profiles)) {81+ yield* credentials.put(name, profile);82+ }83+84+ return env;85+ });86+87+/** A terminal that no helper may touch: every use of it dies. */88+const noTerminal = Layer.succeed(89+ Terminal.Terminal,90+ Terminal.make({91+ columns: Effect.die("the helper read the terminal's width"),92+ display: () => Effect.die("the helper wrote to the terminal"),93+ readInput: Effect.die("the helper read the terminal"),94+ readLine: Effect.die("the helper prompted on the terminal"),95+ rows: Effect.die("the helper read the terminal's height"),96+ })97+);98+99+/**100+ * Runs `<cli> credential <op>` as git runs its helper: `stdin` in, with101+ * `env`. What it wrote to stdout and stderr, and whether it succeeded.102+ */103+const helper = (104+ op: string,105+ stdin: Stream.Stream<Uint8Array>,106+ env: Record<string, string>107+) =>108+ Effect.gen(function* () {109+ const written = yield* Queue.unbounded<string | Uint8Array, Cause.Done>();110+111+ const stdio = Stdio.layerTest({112+ stdin,113+ stdout: () => Sink.fromQueue(written),114+ });115+116+ const exit = yield* Effect.exit(117+ program(["credential", op]).pipe(118+ Effect.provide(119+ // The test stdio and terminal come last, so they stand in for Node's.120+ Layer.mergeAll(121+ Layer.mergeAll(122+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),123+ Layer.mock(Client)({}),124+ OutputPlain,125+ credentialsIn(env),126+ ConfigProvider.layer(ConfigProvider.fromEnv({ env }))127+ ).pipe(Layer.provideMerge(NodeServices.layer)),128+ stdio,129+ noTerminal130+ )131+ )132+ )133+ );134+135+ const stderr = (yield* TestConsole.errorLines).map(String);136+137+ const stdout = (yield* Queue.clear(written))138+ .map((chunk) =>139+ Predicate.isString(chunk) ? chunk : decoder.decode(chunk)140+ )141+ .join("");142+143+ return { ok: Exit.isSuccess(exit), stderr, stdout };144+ }).pipe(Effect.provide(TestConsole.layer));145+146+/** `text` as stdin that ends after it. */147+const input = (text: string) => Stream.make(encoder.encode(text));148+149+describe(`${Brand.cli} credential, git's credential helper`, () => {150+ it.live(151+ "hands git the stored token for the platform's host, with the harness as audit metadata in the username",152+ () =>153+ Effect.gen(function* () {154+ const env = yield* storedIn({ default: platform });155+156+ const ran = yield* helper("get", input(asked("platform.test")), {157+ ...env,158+ ...pi,159+ });160+161+ expect(ran).toStrictEqual({162+ ok: true,163+ stderr: [],164+ stdout: `username=audit;harness=pi&model=kimi-k3\npassword=${token}\n`,165+ });166+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))167+ );168+169+ it.live("says nothing for another host, so git asks its next helper", () =>170+ Effect.gen(function* () {171+ const env = yield* storedIn({ default: platform });172+173+ const ran = yield* helper("get", input(asked("github.com")), {174+ ...env,175+ ...pi,176+ });177+178+ expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });179+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))180+ );181+182+ it.live("never hands the token to the platform's host over plain http", () =>183+ Effect.gen(function* () {184+ const env = yield* storedIn({ default: platform });185+186+ const ran = yield* helper(187+ "get",188+ input(asked("platform.test", "http")),189+ env190+ );191+192+ expect(ran.ok).toBeTruthy();193+ expect(ran.stdout).toBe("");194+ expect(ran.stderr.join("\n")).not.toContain(token);195+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))196+ );197+198+ it.live(199+ "with no login, says nothing to git and one line to the person naming login",200+ () =>201+ Effect.gen(function* () {202+ const env = yield* storedIn({});203+204+ const ran = yield* helper("get", input(asked("platform.test")), env);205+206+ expect(ran.ok).toBeTruthy();207+ expect(ran.stdout).toBe("");208+ expect(ran.stderr).toHaveLength(1);209+ expect(ran.stderr[0]).toContain(`${Brand.cli} login`);210+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))211+ );212+213+ it.live(214+ "under a named profile, answers only as that person, never with another profile's token on the host",215+ () =>216+ Effect.gen(function* () {217+ const bob: Profile = {218+ token: Redacted.make("bob-token-0123456789abcdefghijklmnopqrstuv"),219+ url: "https://elsewhere.test",220+ };221+222+ const env = yield* storedIn({ alice: platform, bob });223+224+ const asBob = yield* helper("get", input(asked("platform.test")), {225+ ...env,226+ [`${SLUG}_PROFILE`]: "bob",227+ });228+229+ const asCarol = yield* helper("get", input(asked("platform.test")), {230+ ...env,231+ [`${SLUG}_PROFILE`]: "carol",232+ });233+234+ expect({ asBob, asCarol: asCarol.stdout }).toStrictEqual({235+ asBob: { ok: true, stderr: [], stdout: "" },236+ asCarol: "",237+ });238+ expect(asCarol.stderr).toHaveLength(1);239+ expect(asCarol.stderr[0]).toContain(240+ `${Brand.cli} login --profile carol`241+ );242+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))243+ );244+245+ it.live.each(["store", "erase"])(246+ "%s reads what git sends, prints nothing and keeps the stored token",247+ (op) =>248+ Effect.gen(function* () {249+ const env = yield* storedIn({ default: platform });250+251+ const ran = yield* helper(252+ op,253+ input(`${asked("platform.test")}username=x\npassword=${token}\n\n`),254+ env255+ );256+257+ expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });258+259+ const kept = yield* Effect.provide(260+ Effect.flatMap(261+ Effect.service(Credentials),262+ (stored) => stored.current263+ ),264+ credentialsIn(env)265+ );266+267+ expect(268+ Option.map(kept, (profile) => Redacted.value(profile.token))269+ ).toStrictEqual(Option.some(token));270+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))271+ );272+273+ it.live(274+ "answers at the blank line without reading further, even if stdin never ends",275+ () =>276+ Effect.gen(function* () {277+ const env = yield* storedIn({ default: platform });278+279+ const endless = Stream.concat(280+ input(asked("platform.test")),281+ Stream.never282+ );283+284+ const pastTheEnd = Stream.concat(285+ input(asked("platform.test")),286+ Stream.die("the helper read past the blank line")287+ );288+289+ for (const stdin of [endless, pastTheEnd]) {290+ const ran = yield* helper("get", stdin, env);291+292+ expect(ran.stdout).toBe(`username=audit;\npassword=${token}\n`);293+ }294+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))295+ );296+});297+298+describe(credentialHelper, () => {299+ it.live(300+ "names no harness when none runs it, and answers from the profile on the asked host",301+ () =>302+ Effect.gen(function* () {303+ const env = yield* storedIn({304+ default: {305+ token: Redacted.make("other-token"),306+ url: "https://x.test",307+ },308+ platform,309+ });310+311+ const stdout = yield* credentialHelper(312+ "get",313+ asked("platform.test"),314+ {}315+ ).pipe(Effect.provide(credentialsIn(env)));316+317+ expect(stdout).toBe(`username=audit;\npassword=${token}\n`);318+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))319+ );320+});321+322+describe("the env the CLI sees", () => {323+ it.effect(324+ "reads the env in a bounded walk, even with a huge number in a name",325+ () =>326+ Effect.gen(function* () {327+ const source = ConfigProvider.fromEnv({328+ env: { AI_AGENT: "pi", RUN_0: "first", RUN_100000: "far" },329+ });330+331+ const reads = yield* Ref.make(0);332+333+ const counted = ConfigProvider.make((at) =>334+ Effect.andThen(335+ Ref.update(reads, (n) => n + 1),336+ source.load(at)337+ )338+ );339+340+ const read = yield* currentEnv.pipe(341+ Effect.provideService(ConfigProvider.ConfigProvider, counted)342+ );343+344+ expect(read).toStrictEqual({ AI_AGENT: "pi", RUN_0: "first" });345+ expect(yield* Ref.get(reads)).toBeLessThan(2000);346+ })347+ );348+});349+350+const Basic = /^Basic (?<encoded>\S+)$/u;351+352+const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);353+354+/**355+ * `git http-backend` over `root` behind basic auth, on a local port: a356+ * request without credentials gets the 401 that makes git ask its helper.357+ * Its base URL, and every `user:password` pair it was sent.358+ */359+const guarded = (root: string) =>360+ Effect.gen(function* () {361+ const spawner =362+ yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();363+364+ const seen = yield* Ref.make<readonly { user: string; password: string }[]>(365+ []366+ );367+368+ const backend = httpBackend(root);369+370+ const app = Effect.gen(function* () {371+ const request = yield* HttpServerRequest.toWeb(372+ yield* HttpServerRequest.HttpServerRequest373+ );374+375+ const pair = Option.fromNullishOr(376+ Basic.exec(request.headers.get("authorization") ?? "")?.groups?.encoded377+ ).pipe(Option.flatMap(fromBase64));378+379+ if (Option.isNone(pair)) {380+ return HttpServerResponse.text("sign in", {381+ headers: { "www-authenticate": 'Basic realm="test"' },382+ status: 401,383+ });384+ }385+386+ const colon = pair.value.indexOf(":");387+388+ yield* Ref.update(seen, (all) => [389+ ...all,390+ {391+ password: pair.value.slice(colon + 1),392+ user: pair.value.slice(0, colon),393+ },394+ ]);395+396+ return HttpServerResponse.fromWeb(397+ yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))398+ );399+ }).pipe(Effect.orDie);400+401+ const server = yield* Layer.build(402+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))403+ ).pipe(Effect.orDie);404+405+ const { address } = Context.get(server, HttpServer.HttpServer);406+407+ const origin =408+ "port" in address409+ ? `http://127.0.0.1:${address.port}`410+ : yield* Effect.die("the test server listens on a socket, not a port");411+412+ return { origin, seen: Ref.get(seen) };413+ });414+415+describe("real git with the helper", () => {416+ it.live(417+ "git ls-remote sends the stored token as the basic-auth password, with no token in the url",418+ () =>419+ Effect.gen(function* () {420+ const fs = yield* FileSystem.FileSystem;421+ const path = yield* Path.Path;422+ const root = yield* fs.makeTempDirectoryScoped();423+ const work = yield* fs.makeTempDirectoryScoped();424+425+ yield* gitOk(426+ root,427+ "init",428+ "--quiet",429+ "--bare",430+ "-b",431+ "main",432+ "demo.git"433+ );434+ yield* gitOk(work, "init", "--quiet", "-b", "main");435+ yield* gitOk(work, "commit", "--quiet", "--allow-empty", "-m", "first");436+ yield* gitOk(437+ work,438+ "push",439+ "--quiet",440+ path.join(root, "demo.git"),441+ "main"442+ );443+444+ const head = yield* gitOk(work, "rev-parse", "HEAD");445+ const server = yield* guarded(root);446+447+ const env = yield* storedIn({448+ default: { token: Redacted.make(token), url: server.origin },449+ });450+451+ const bin = yield* path.fromFileUrl(452+ new URL("../../src/bin.ts", import.meta.url)453+ );454+455+ const child = yield* spawn(456+ "git",457+ [458+ "-c",459+ "credential.helper=",460+ "-c",461+ `credential.helper=!bun '${bin}' credential`,462+ "ls-remote",463+ `${server.origin}/demo.git`,464+ ],465+ {466+ cwd: work,467+ env: {468+ ...env,469+ ...pi,470+ [`${SLUG}_PROFILE`]: "",471+ [`${SLUG}_TOKEN`]: "",472+ [`${SLUG}_URL`]: "",473+ PI_PROVIDER: "",474+ PI_SESSION_ID: "",475+ },476+ }477+ );478+479+ const [stdout, stderr, exitCode] = yield* Effect.all(480+ [481+ child.stdout.pipe(Stream.decodeText(), Stream.mkString),482+ child.stderr.pipe(Stream.decodeText(), Stream.mkString),483+ child.exitCode,484+ ],485+ { concurrency: "unbounded" }486+ );487+488+ expect({ exitCode, stderr }).toStrictEqual({ exitCode: 0, stderr: "" });489+ expect(stdout).toBe(`${head}\tHEAD\n${head}\trefs/heads/main\n`);490+ expect(yield* server.seen).toContainEqual({491+ password: token,492+ user: "audit;harness=pi&model=kimi-k3",493+ });494+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),495+ 30_000496+ );497+});added:apps/cli/test/local/login.test.ts+816 added
1+import { NodeHttpServer, NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client, Contracts } from "@repo/protocol/contracts";5+import { ClaimView } from "@repo/protocol/domain/claim";6+import { Handle } from "@repo/protocol/ids";7+import {8+ Authenticated,9+ CurrentPrincipal,10+ Person,11+ Unauthenticated,12+} from "@repo/protocol/principal";13+import { asPerson, unanswered } from "@repo/protocol/testing";14+import { spawn } from "@repo/testkit/git";15+import {16+ Clock,17+ ConfigProvider,18+ Context,19+ Effect,20+ Exit,21+ Fiber,22+ FileSystem,23+ Layer,24+ Option,25+ Path,26+ Redacted,27+ Ref,28+ Schema,29+ Stdio,30+ Stream,31+ Terminal,32+} from "effect";33+import { CliOutput } from "effect/cli";34+import { FetchHttpClient, HttpClient, HttpServer } from "effect/http";35+import { RpcTest } from "effect/rpc";36+import { TestClock, TestConsole } from "effect/testing";37+38+import { Credentials, CredentialsFile } from "../../src/credentials.ts";39+import { Browser, Loopback, PlatformClient } from "../../src/local/login.ts";40+import { program } from "../../src/main.ts";41+import { OutputPlain } from "../../src/output.ts";42+import { oauthServer } from "../oauth-server.ts";43+44+/** The env names the CLI reads, spelled from the brand. */45+const SLUG = Brand.slug.toUpperCase();46+47+const url = "https://platform.test";48+49+const given = "tok-given-0123456789abcdefghijklmnopqrstuvwxyz";50+51+const issued = "tok-issued-0123456789abcdefghijklmnopqrstuvwxyz";52+53+/** The three lines `login` sets in git's global config for `at`. */54+const helperLines = (at: string) => [55+ `git config --global --replace-all credential.${at}.helper ""`,56+ `git config --global --add credential.${at}.helper ${Brand.slug}`,57+ `git config --global credential.${at}.useHttpPath true`,58+];59+60+/** The same three, as the argv lists `--json` carries. */61+const helperArgv = (at: string) => [62+ ["git", "config", "--global", "--replace-all", `credential.${at}.helper`, ""],63+ ["git", "config", "--global", "--add", `credential.${at}.helper`, Brand.slug],64+ ["git", "config", "--global", `credential.${at}.useHttpPath`, "true"],65+];66+67+/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */68+const home = Effect.gen(function* () {69+ const fs = yield* FileSystem.FileSystem;70+ const path = yield* Path.Path;71+ const dir = yield* fs.makeTempDirectoryScoped();72+73+ return { GIT_CONFIG_GLOBAL: path.join(dir, ".gitconfig"), HOME: dir };74+});75+76+const credentialsIn = (env: Record<string, string>) =>77+ CredentialsFile.pipe(78+ Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))79+ );80+81+/** The profile `name` as the file holds it: its url, handle and token. */82+const stored = (env: Record<string, string>, name: string) =>83+ Effect.provide(84+ Effect.flatMap(Effect.service(Credentials), ({ current }) => current),85+ credentialsIn({ ...env, [`${SLUG}_PROFILE`]: name })86+ ).pipe(87+ Effect.map(88+ Option.map(({ handle, token, url: at }) => ({89+ handle,90+ token: Redacted.value(token),91+ url: at,92+ }))93+ )94+ );95+96+/** `git config --global <args>` in `env`: its stdout and exit code. */97+const gitConfig = (env: Record<string, string>, ...args: string[]) =>98+ Effect.scoped(99+ Effect.gen(function* () {100+ const child = yield* spawn("git", ["config", "--global", ...args], {101+ env,102+ });103+104+ const [stdout, exitCode] = yield* Effect.all(105+ [106+ child.stdout.pipe(Stream.decodeText(), Stream.mkString),107+ child.exitCode,108+ ],109+ { concurrency: "unbounded" }110+ ).pipe(Effect.orDie);111+112+ return { exitCode, stdout };113+ })114+ );115+116+const claim = Schema.decodeUnknownSync(ClaimView);117+118+const isPerson = Schema.is(Person);119+120+/** One live claim of `handle`'s, as `status` lists it. */121+const claimOf = (handle: string) =>122+ claim({123+ ask: "fix-week",124+ base: "a".repeat(40),125+ checkCommand: "bun test",126+ claimant: handle,127+ fork: `datekit--fix-week--${handle}`,128+ lapsesAt: "2026-10-09T12:00:00.000Z",129+ openedAt: "2026-10-07T12:00:00.000Z",130+ project: "datekit",131+ remote: `${url}/datekit--fix-week--${handle}.git`,132+ state: "live",133+ warnsAt: "2026-10-08T12:00:00.000Z",134+ });135+136+/**137+ * The platform's side of a call, as `status` sees it: whoever the server138+ * side takes the caller for holds one claim.139+ */140+const statusHandler = Contracts.toLayerHandler("status", () =>141+ Effect.map(Effect.service(CurrentPrincipal), (principal) => ({142+ answers: [],143+ claims: isPerson(principal) ? [claimOf(principal.handle)] : [],144+ }))145+);146+147+/** A server side that refuses every credential, as for a revoked token. */148+const refusesEveryone = Layer.succeed(Authenticated, () =>149+ Effect.fail(new Unauthenticated())150+);151+152+/**153+ * The world `login` runs in, faked at its three host seams: the platform's154+ * client (an in-process one, whose server side is `server`), the person's155+ * browser, and the loopback server (a Node server on an ephemeral port).156+ * Each records what `login` asked of it.157+ */158+const seams = (server: Layer.Layer<Authenticated>) =>159+ Effect.gen(function* () {160+ const connected = yield* Ref.make<161+ readonly { token: string; url: string }[]162+ >([]);163+164+ const opened = yield* Ref.make<readonly string[]>([]);165+166+ const listened = yield* Ref.make<167+ readonly { hostname: string; port: number }[]168+ >([]);169+170+ const layer = Layer.mergeAll(171+ Layer.succeed(PlatformClient, {172+ connect: ({ token, url: at }) =>173+ Effect.andThen(174+ Ref.update(connected, (all) => [175+ ...all,176+ { token: Redacted.value(token), url: at },177+ ]),178+ RpcTest.makeClient(Contracts).pipe(179+ Effect.provide(Layer.mergeAll(unanswered, statusHandler, server))180+ )181+ ),182+ }),183+ Layer.succeed(Browser, {184+ open: (at) => Ref.update(opened, (all) => [...all, at]),185+ }),186+ Layer.succeed(Loopback, {187+ listen: (address) =>188+ Effect.gen(function* () {189+ yield* Ref.update(listened, (all) => [...all, address]);190+191+ const built = yield* Layer.build(NodeHttpServer.layerTest);192+193+ return Context.get(built, HttpServer.HttpServer);194+ }),195+ })196+ );197+198+ return {199+ connected: Ref.get(connected),200+ layer,201+ listened: Ref.get(listened),202+ opened: Ref.get(opened),203+ };204+ });205+206+/** A platform that takes the caller for `handle`. */207+const signedInAs = (handle: string) => asPerson(Handle.make(handle));208+209+/** What the tests themselves run on: a test console, and Node for files, git and servers. */210+const testServices = Layer.mergeAll(TestConsole.layer, NodeServices.layer);211+212+/** A terminal nothing may touch: every use of it dies. */213+const noTerminal = Layer.succeed(214+ Terminal.Terminal,215+ Terminal.make({216+ columns: Effect.die("login read the terminal's width"),217+ display: () => Effect.die("login wrote to the terminal"),218+ readInput: Effect.die("login read the terminal"),219+ readLine: Effect.die("login prompted on the terminal"),220+ rows: Effect.die("login read the terminal's height"),221+ })222+);223+224+interface Run {225+ readonly env: Record<string, string>;226+ readonly seams: Layer.Layer<never>;227+ /** What stdin holds. */228+ readonly stdin?: string;229+ /** Whether stdout is a terminal, as a person's would be. */230+ readonly terminal?: boolean;231+}232+233+/** Runs `argv` as the CLI would, in `run`'s world; how it ended. */234+const cli = (argv: readonly string[], run: Run) =>235+ Effect.exit(236+ program(argv).pipe(237+ Effect.provide(238+ // The test stdio and terminal come last, so they stand in for Node's.239+ Layer.mergeAll(240+ Layer.mergeAll(241+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),242+ Layer.mock(Client)({}),243+ OutputPlain,244+ credentialsIn(run.env),245+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: run.env })),246+ run.seams247+ ).pipe(Layer.provideMerge(NodeServices.layer)),248+ Stdio.layerTest({249+ stdin: Stream.make(new TextEncoder().encode(run.stdin ?? "")),250+ stdoutIsTerminal: Effect.succeed(run.terminal ?? false),251+ }),252+ noTerminal253+ )254+ )255+ )256+ );257+258+/** What was printed, one entry per line however it was written. */259+const lines = (all: readonly unknown[]) =>260+ all.flatMap((chunk) => String(chunk).split("\n"));261+262+/** Every line printed so far, on stdout and on stderr. */263+const printed = Effect.gen(function* () {264+ return {265+ stderr: lines(yield* TestConsole.errorLines),266+ stdout: lines(yield* TestConsole.logLines),267+ };268+});269+270+/** The sign-in URL `login` printed for `origin`, once it has. */271+const signInUrl = (origin: string) =>272+ Effect.gen(function* () {273+ for (let attempt = 0; attempt < 250; attempt += 1) {274+ const line = (yield* printed).stderr275+ .map((text) => text.trim())276+ .find((text) => text.startsWith(`${origin}/authorize?`));277+278+ if (line !== undefined) {279+ return line;280+ }281+282+ yield* Effect.sleep("20 millis");283+ }284+285+ return yield* Effect.die("login printed no sign-in URL");286+ });287+288+/** GET `at` as a browser would, following redirects: the page's status. */289+const visit = (at: string) =>290+ Effect.gen(function* () {291+ const client = yield* HttpClient.HttpClient;292+ const response = yield* client.get(at);293+294+ return response.status;295+ }).pipe(Effect.provide(FetchHttpClient.layer));296+297+/** The query `/authorize` was sent, field by field. */298+const fieldsOf = (query: URLSearchParams | undefined) =>299+ Object.fromEntries(query?.entries() ?? []);300+301+describe(`${Brand.cli} login --token-stdin`, () => {302+ it.live(303+ "checks the token with the platform, keeps it under the profile with the handle, and points git at the helper",304+ () =>305+ Effect.gen(function* () {306+ const env = yield* home;307+ const platform = yield* seams(signedInAs("alice"));308+309+ const exit = yield* cli(310+ ["login", "--url", url, "--token-stdin", "--profile", "alice"],311+ { env, seams: platform.layer, stdin: `${given}\n` }312+ );313+314+ expect(Exit.isSuccess(exit)).toBeTruthy();315+ expect({316+ checked: yield* platform.connected,317+ kept: yield* stored(env, "alice"),318+ }).toStrictEqual({319+ checked: [{ token: given, url }],320+ kept: Option.some({ handle: "alice", token: given, url }),321+ });322+ expect({323+ helper: yield* gitConfig(324+ env,325+ "--get-all",326+ `credential.${url}.helper`327+ ),328+ useHttpPath: yield* gitConfig(329+ env,330+ "--get",331+ `credential.${url}.useHttpPath`332+ ),333+ }).toStrictEqual({334+ helper: { exitCode: 0, stdout: `\n${Brand.slug}\n` },335+ useHttpPath: { exitCode: 0, stdout: "true\n" },336+ });337+338+ const { stderr, stdout } = yield* printed;339+340+ expect(stdout.map((line) => line.trim())).toStrictEqual(341+ expect.arrayContaining(helperLines(url))342+ );343+ expect([...stdout, ...stderr].join("\n")).not.toContain(given);344+ }).pipe(Effect.scoped, Effect.provide(testServices)),345+ 30_000346+ );347+348+ it.live(349+ "prints one envelope under --json, with the git config and without the token",350+ () =>351+ Effect.gen(function* () {352+ const env = yield* home;353+ const platform = yield* seams(signedInAs("alice"));354+355+ yield* cli(["login", "--url", url, "--token-stdin", "--json"], {356+ env,357+ seams: platform.layer,358+ stdin: `${given}\n`,359+ });360+361+ const { stdout } = yield* printed;362+ const text = stdout.join("\n");363+364+ expect(text).not.toContain(given);365+ expect(JSON.parse(text)).toStrictEqual({366+ command: "login",367+ data: {368+ gitConfig: helperArgv(url),369+ gitConfigSet: true,370+ handle: "alice",371+ profile: "default",372+ url,373+ },374+ ok: true,375+ v: 1,376+ });377+ }).pipe(Effect.scoped, Effect.provide(testServices)),378+ 30_000379+ );380+381+ it.live(382+ "with --no-git-config, leaves git's config alone and hands back the lines to set, in --json too",383+ () =>384+ Effect.gen(function* () {385+ const env = yield* home;386+ const platform = yield* seams(signedInAs("alice"));387+388+ const exit = yield* cli(389+ ["login", "--url", url, "--token-stdin", "--no-git-config", "--json"],390+ { env, seams: platform.layer, stdin: `${given}\n` }391+ );392+393+ expect(Exit.isSuccess(exit)).toBeTruthy();394+ expect(395+ (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))396+ .exitCode397+ ).toBe(1);398+399+ expect(JSON.parse((yield* printed).stdout.join("\n"))).toMatchObject({400+ data: { gitConfig: helperArgv(url), gitConfigSet: false },401+ ok: true,402+ });403+ }).pipe(Effect.scoped, Effect.provide(testServices)),404+ 30_000405+ );406+407+ it.live(408+ "prints each git config line so a shell takes it as it was run, quotes and all",409+ () =>410+ Effect.gen(function* () {411+ const env = yield* home;412+ const platform = yield* seams(signedInAs("alice"));413+ const odd = "https://o'brien.test";414+415+ yield* cli(["login", "--url", odd, "--token-stdin"], {416+ env,417+ seams: platform.layer,418+ stdin: `${given}\n`,419+ });420+421+ expect(422+ (yield* printed).stdout.map((line) => line.trim())423+ ).toStrictEqual(424+ expect.arrayContaining([425+ String.raw`git config --global --add 'credential.https://o'\''brien.test.helper' ${Brand.slug}`,426+ ])427+ );428+ }).pipe(Effect.scoped, Effect.provide(testServices)),429+ 30_000430+ );431+432+ it.live(433+ "keeps nothing, and leaves git alone, when the platform refuses the token",434+ () =>435+ Effect.gen(function* () {436+ const env = yield* home;437+ const platform = yield* seams(refusesEveryone);438+439+ const exit = yield* cli(["login", "--url", url, "--token-stdin"], {440+ env,441+ seams: platform.layer,442+ stdin: `${given}\n`,443+ });444+445+ expect(Exit.isFailure(exit)).toBeTruthy();446+ expect(yield* stored(env, "default")).toStrictEqual(Option.none());447+ expect(448+ (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))449+ .exitCode450+ ).toBe(1);451+452+ const { stderr, stdout } = yield* printed;453+454+ expect(stderr.join("\n")).toContain(url);455+ expect([...stdout, ...stderr].join("\n")).not.toContain(given);456+ }).pipe(Effect.scoped, Effect.provide(testServices)),457+ 30_000458+ );459+460+ it.live(461+ "never sends a token over plain http to a host that is not this machine",462+ () =>463+ Effect.gen(function* () {464+ const env = yield* home;465+ const platform = yield* seams(signedInAs("alice"));466+467+ const exit = yield* cli(468+ ["login", "--url", "http://platform.test", "--token-stdin"],469+ { env, seams: platform.layer, stdin: `${given}\n` }470+ );471+472+ expect(Exit.isFailure(exit)).toBeTruthy();473+ expect(yield* platform.connected).toStrictEqual([]);474+ expect((yield* printed).stderr.join("\n")).toContain("https://");475+ }).pipe(Effect.scoped, Effect.provide(testServices)),476+ 30_000477+ );478+479+ it.live(480+ "without --url, logs the current profile in again on its platform, but asks for --url for another profile",481+ () =>482+ Effect.gen(function* () {483+ const env = yield* home;484+ const platform = yield* seams(signedInAs("alice"));485+ const run = { env, seams: platform.layer, stdin: `${given}\n` };486+487+ yield* cli(["login", "--url", url, "--token-stdin"], run);488+489+ const again = yield* cli(["login", "--token-stdin"], run);490+491+ const other = yield* cli(492+ ["login", "--token-stdin", "--profile", "bob"],493+ run494+ );495+496+ expect({497+ again: Exit.isSuccess(again),498+ bob: yield* stored(env, "bob"),499+ checked: (yield* platform.connected).map(({ url: at }) => at),500+ other: Exit.isSuccess(other),501+ }).toStrictEqual({502+ again: true,503+ bob: Option.none(),504+ checked: [url, url],505+ other: false,506+ });507+ expect((yield* printed).stderr.join("\n")).toContain("--url");508+ }).pipe(Effect.scoped, Effect.provide(testServices)),509+ 30_000510+ );511+512+ it.live(513+ "with no --url and no stored profile, asks for --url",514+ () =>515+ Effect.gen(function* () {516+ const env = yield* home;517+ const platform = yield* seams(signedInAs("alice"));518+519+ const exit = yield* cli(["login", "--token-stdin"], {520+ env,521+ seams: platform.layer,522+ stdin: `${given}\n`,523+ });524+525+ expect(Exit.isFailure(exit)).toBeTruthy();526+ expect((yield* printed).stderr.join("\n")).toContain("--url");527+ }).pipe(Effect.scoped, Effect.provide(testServices)),528+ 30_000529+ );530+});531+532+describe(`${Brand.cli} login in the browser (PKCE)`, () => {533+ it.live(534+ "with --no-browser, prints the sign-in URL; following it signs in and keeps the platform's token",535+ () =>536+ Effect.gen(function* () {537+ const env = yield* home;538+ const server = yield* oauthServer({ token: issued });539+ const platform = yield* seams(signedInAs("alice"));540+541+ const fiber = yield* Effect.forkChild(542+ cli(543+ [544+ "login",545+ "--url",546+ server.origin,547+ "--no-browser",548+ "--profile",549+ "alice",550+ ],551+ { env, seams: platform.layer }552+ )553+ );554+555+ expect(yield* visit(yield* signInUrl(server.origin))).toBe(200);556+ expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();557+558+ const [query] = yield* server.authorizations;559+ const fields = fieldsOf(query);560+ const urlSafe43 = /^[A-Za-z0-9_-]{43}$/u;561+562+ expect({563+ asked: {564+ challenge: urlSafe43.test(fields.code_challenge ?? ""),565+ clientId: fields.client_id,566+ method: fields.code_challenge_method,567+ names: Object.keys(fields).toSorted(),568+ redirect: /^http:\/\/127\.0\.0\.1:\d+\/callback$/u.test(569+ fields.redirect_uri ?? ""570+ ),571+ responseType: fields.response_type,572+ state: urlSafe43.test(fields.state ?? ""),573+ },574+ checked: yield* platform.connected,575+ kept: yield* stored(env, "alice"),576+ listened: yield* platform.listened,577+ opened: yield* platform.opened,578+ }).toStrictEqual({579+ asked: {580+ challenge: true,581+ clientId: `${server.origin}/oauth/cli`,582+ method: "S256",583+ names: [584+ "client_id",585+ "code_challenge",586+ "code_challenge_method",587+ "redirect_uri",588+ "response_type",589+ "state",590+ ],591+ redirect: true,592+ responseType: "code",593+ state: true,594+ },595+ checked: [{ token: issued, url: server.origin }],596+ kept: Option.some({597+ handle: "alice",598+ token: issued,599+ url: server.origin,600+ }),601+ listened: [{ hostname: "127.0.0.1", port: 0 }],602+ opened: [],603+ });604+605+ // The loopback server took its one callback and closed.606+ const again = yield* Effect.exit(607+ visit(`${fields.redirect_uri}?code=code-1&state=${fields.state}`)608+ );609+610+ const { stderr, stdout } = yield* printed;611+612+ expect({613+ closed: Exit.isFailure(again),614+ leaked: [...stdout, ...stderr].join("\n").includes(issued),615+ }).toStrictEqual({ closed: true, leaked: false });616+ }).pipe(Effect.scoped, Effect.provide(testServices)),617+ 30_000618+ );619+620+ it.live(621+ "refuses a sign-in that comes back with another state, and keeps nothing",622+ () =>623+ Effect.gen(function* () {624+ const env = yield* home;625+ const server = yield* oauthServer({ state: "other", token: issued });626+ const platform = yield* seams(signedInAs("alice"));627+628+ const fiber = yield* Effect.forkChild(629+ cli(["login", "--url", server.origin, "--no-browser"], {630+ env,631+ seams: platform.layer,632+ })633+ );634+635+ yield* visit(yield* signInUrl(server.origin));636+637+ expect(Exit.isFailure(yield* Fiber.join(fiber))).toBeTruthy();638+ expect((yield* printed).stderr.join("\n")).toContain("state");639+ expect(yield* platform.connected).toStrictEqual([]);640+ expect(yield* stored(env, "default")).toStrictEqual(Option.none());641+ }).pipe(Effect.scoped, Effect.provide(testServices)),642+ 30_000643+ );644+645+ it.live(646+ "at a person's terminal, opens the browser on the sign-in URL",647+ () =>648+ Effect.gen(function* () {649+ const env = yield* home;650+ const server = yield* oauthServer({ token: issued });651+ const platform = yield* seams(signedInAs("alice"));652+653+ const fiber = yield* Effect.forkChild(654+ cli(["login", "--url", server.origin], {655+ env,656+ seams: platform.layer,657+ terminal: true,658+ })659+ );660+661+ const shown = yield* signInUrl(server.origin);662+663+ expect(yield* visit(shown)).toBe(200);664+ expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();665+ expect(yield* platform.opened).toStrictEqual([shown]);666+ }).pipe(Effect.scoped, Effect.provide(testServices)),667+ 30_000668+ );669+670+ it.live(671+ "under an agent, prints the URL for a person instead of opening a browser, and never prompts",672+ () =>673+ Effect.gen(function* () {674+ const env = { ...(yield* home), CLAUDECODE: "1" };675+ const server = yield* oauthServer({ token: issued });676+ const platform = yield* seams(signedInAs("alice"));677+678+ const fiber = yield* Effect.forkChild(679+ cli(["login", "--url", server.origin], {680+ env,681+ seams: platform.layer,682+ terminal: true,683+ })684+ );685+686+ expect(yield* visit(yield* signInUrl(server.origin))).toBe(200);687+ expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();688+ expect(yield* platform.opened).toStrictEqual([]);689+ }).pipe(Effect.scoped, Effect.provide(testServices)),690+ 30_000691+ );692+693+ it.live(694+ "stops waiting after 5 minutes, says how to sign in instead, and closes the loopback server",695+ () =>696+ Effect.gen(function* () {697+ const env = yield* home;698+ const server = yield* oauthServer({ token: issued });699+ const platform = yield* seams(signedInAs("alice"));700+ const clock = yield* TestClock.make();701+702+ const fiber = yield* Effect.forkChild(703+ cli(["login", "--url", server.origin, "--no-browser"], {704+ env,705+ seams: platform.layer,706+ }).pipe(Effect.provideService(Clock.Clock, clock))707+ );708+709+ const shown = yield* signInUrl(server.origin);710+711+ yield* clock.adjust("5 minutes");712+713+ expect(Exit.isFailure(yield* Fiber.join(fiber))).toBeTruthy();714+715+ const said = (yield* printed).stderr.join("\n");716+717+ expect(said).toContain("5 minutes");718+ expect(said).toContain("--token-stdin");719+ expect(yield* stored(env, "default")).toStrictEqual(Option.none());720+721+ const callback = new URL(shown).searchParams.get("redirect_uri") ?? "";722+723+ expect(724+ Exit.isFailure(725+ yield* Effect.exit(visit(`${callback}?code=x&state=y`))726+ )727+ ).toBeTruthy();728+ }).pipe(Effect.scoped, Effect.provide(testServices)),729+ 30_000730+ );731+});732+733+describe(`${Brand.cli} logout`, () => {734+ it.live(735+ "removes the profile and the git config that names the helper for its platform",736+ () =>737+ Effect.gen(function* () {738+ const env = yield* home;739+ const platform = yield* seams(signedInAs("alice"));740+ const run = { env, seams: platform.layer, stdin: `${given}\n` };741+742+ yield* cli(743+ ["login", "--url", url, "--token-stdin", "--profile", "alice"],744+ run745+ );746+747+ const exit = yield* cli(["logout", "--profile", "alice"], run);748+749+ expect(Exit.isSuccess(exit)).toBeTruthy();750+ expect(yield* stored(env, "alice")).toStrictEqual(Option.none());751+ expect(752+ (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))753+ .exitCode754+ ).toBe(1);755+ expect(756+ (yield* gitConfig(env, "--get", `credential.${url}.useHttpPath`))757+ .exitCode758+ ).toBe(1);759+ }).pipe(Effect.scoped, Effect.provide(testServices)),760+ 30_000761+ );762+763+ it.live(764+ "removes useHttpPath even when git's config holds it twice",765+ () =>766+ Effect.gen(function* () {767+ const env = yield* home;768+ const platform = yield* seams(signedInAs("alice"));769+ const run = { env, seams: platform.layer, stdin: `${given}\n` };770+771+ yield* cli(["login", "--url", url, "--token-stdin"], run);772+ yield* gitConfig(env, "--add", `credential.${url}.useHttpPath`, "true");773+774+ const exit = yield* cli(["logout"], run);775+776+ expect(Exit.isSuccess(exit)).toBeTruthy();777+ expect(778+ (yield* gitConfig(env, "--get-all", `credential.${url}.useHttpPath`))779+ .exitCode780+ ).toBe(1);781+ }).pipe(Effect.scoped, Effect.provide(testServices)),782+ 30_000783+ );784+785+ it.live(786+ "keeps git asking the helper while another profile is on the same platform",787+ () =>788+ Effect.gen(function* () {789+ const env = yield* home;790+ const platform = yield* seams(signedInAs("alice"));791+ const run = { env, seams: platform.layer, stdin: `${given}\n` };792+793+ for (const name of ["alice", "bob"]) {794+ yield* cli(795+ ["login", "--url", url, "--token-stdin", "--profile", name],796+ run797+ );798+ }799+800+ yield* cli(["logout", "--profile", "alice"], run);801+802+ expect(803+ yield* gitConfig(env, "--get-all", `credential.${url}.helper`)804+ ).toStrictEqual({ exitCode: 0, stdout: `\n${Brand.slug}\n` });805+ expect(Option.isSome(yield* stored(env, "bob"))).toBeTruthy();806+807+ yield* cli(["logout", "--profile", "bob"], run);808+809+ expect(810+ (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))811+ .exitCode812+ ).toBe(1);813+ }).pipe(Effect.scoped, Effect.provide(testServices)),814+ 30_000815+ );816+});modified:apps/cli/test/main.test.ts+3 added-4 removed
4 unmodified lines5 import { Cause, Effect, Exit, Layer } from "effect";6 import { CliOutput, Command } from "effect/cli";7 import { TestConsole } from "effect/testing";8 9+import { Credentials } from "../src/credentials.ts";10 import { program, root } from "../src/main.ts";11 import { OutputPlain } from "../src/output.ts";12 13 /** What was printed to stdout, one entry per line however it was written. */2 unmodified lines16 );17 18 /**19 * What the CLI runs with in these tests: a test console, plain output, and19- * a client no command here calls.20+ * a client and credentials no command here calls.21 */22 const services = Layer.mergeAll(23 TestConsole.layer,24 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),25 Layer.mock(Client)({}),26+ Layer.mock(Credentials)({}),27 OutputPlain28 ).pipe(Layer.provideMerge(NodeServices.layer));29 30 /** The help `root` prints for `--help`, line by line. */63 unmodified lines94 });95 96 describe("each command a later issue builds", () => {97 const stubs = [96- { args: ["login"], issue: "412" },97- { args: ["logout"], issue: "412" },98- { args: ["credential"], issue: "412" },98 { args: ["init"], issue: "413" },99 { args: ["why"], issue: "414" },100 { args: ["env", "set"], issue: "414" },101 { args: ["hook"], issue: "415" },18 unmodified linesadded:apps/cli/test/oauth-server.ts+156 added
1+/**2+ * A stand-in for the platform's OAuth authorization server, as the CLI's3+ * `login` meets it: `/authorize` sends the browser back to the loopback4+ * `redirect_uri` with a code and the state it was given, and `/token` trades5+ * that code for an access token only if the `code_verifier` hashes (S256,6+ * RFC 7636) to the challenge `/authorize` saw.7+ */8+import { NodeHttpServer } from "@effect/platform-node";9+import { Context, Effect, Layer, Ref, Schema } from "effect";10+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";11+12+export interface OAuthServerOptions {13+ /** The access token `/token` issues. */14+ readonly token: string;15+ /** The state `/authorize` sends back: the client's own, or another one. */16+ readonly state?: "same" | "other";17+}18+19+/** A code `/authorize` gave out, and what `/token` must be shown for it. */20+interface Grant {21+ readonly challenge: string;22+ readonly clientId: string;23+ readonly redirectUri: string;24+}25+26+const TokenForm = Schema.Struct({27+ client_id: Schema.String,28+ code: Schema.String,29+ code_verifier: Schema.String,30+ grant_type: Schema.String,31+ redirect_uri: Schema.String,32+});33+34+/** Base64url without padding, as RFC 7636 §4.2 spells the S256 challenge. */35+const base64url = (bytes: Uint8Array) =>36+ btoa(String.fromCodePoint(...bytes))37+ .replaceAll("+", "-")38+ .replaceAll("/", "_")39+ .replace(/=+$/u, "");40+41+/** `BASE64URL(SHA256(verifier))`. */42+const s256 = (verifier: string) =>43+ Effect.map(44+ Effect.promise(() =>45+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))46+ ),47+ (digest) => base64url(new Uint8Array(digest))48+ );49+50+const refused = (error: string) =>51+ HttpServerResponse.jsonUnsafe({ error }, { status: 400 });52+53+/**54+ * The server on a local port: its origin, and the query of every55+ * `/authorize` request it answered.56+ */57+export const oauthServer = (options: OAuthServerOptions) =>58+ Effect.gen(function* () {59+ const grants = yield* Ref.make<ReadonlyMap<string, Grant>>(new Map());60+ const authorizations = yield* Ref.make<readonly URLSearchParams[]>([]);61+ const issued = yield* Ref.make(0);62+63+ const authorize = (query: URLSearchParams) =>64+ Effect.gen(function* () {65+ yield* Ref.update(authorizations, (all) => [...all, query]);66+67+ const redirectUri = query.get("redirect_uri") ?? "";68+ const challenge = query.get("code_challenge") ?? "";69+70+ if (71+ query.get("response_type") !== "code" ||72+ query.get("code_challenge_method") !== "S256" ||73+ challenge === ""74+ ) {75+ return refused("invalid_request");76+ }77+78+ const code = `code-${yield* Ref.updateAndGet(issued, (n) => n + 1)}`;79+80+ yield* Ref.update(grants, (all) =>81+ new Map(all).set(code, {82+ challenge,83+ clientId: query.get("client_id") ?? "",84+ redirectUri,85+ })86+ );87+88+ const back = new URL(redirectUri);89+90+ back.searchParams.set("code", code);91+ back.searchParams.set(92+ "state",93+ options.state === "other"94+ ? "not-the-state"95+ : (query.get("state") ?? "")96+ );97+98+ return HttpServerResponse.redirect(back.href, { status: 302 });99+ });100+101+ const token = Effect.gen(function* () {102+ const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);103+ const grant = (yield* Ref.get(grants)).get(form.code);104+105+ yield* Ref.update(grants, (all) => {106+ const left = new Map(all);107+108+ left.delete(form.code);109+110+ return left;111+ });112+113+ if (114+ form.grant_type !== "authorization_code" ||115+ grant === undefined ||116+ grant.clientId !== form.client_id ||117+ grant.redirectUri !== form.redirect_uri ||118+ (yield* s256(form.code_verifier)) !== grant.challenge119+ ) {120+ return refused("invalid_grant");121+ }122+123+ return HttpServerResponse.jsonUnsafe({124+ access_token: options.token,125+ token_type: "bearer",126+ });127+ }).pipe(Effect.orElseSucceed(() => refused("invalid_request")));128+129+ const app = Effect.gen(function* () {130+ const request = yield* HttpServerRequest.HttpServerRequest;131+ const url = new URL(request.url, "http://localhost");132+133+ if (request.method === "GET" && url.pathname === "/authorize") {134+ return yield* authorize(url.searchParams);135+ }136+137+ if (request.method === "POST" && url.pathname === "/token") {138+ return yield* token;139+ }140+141+ return HttpServerResponse.empty({ status: 404 });142+ });143+144+ const server = yield* Layer.build(145+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))146+ ).pipe(Effect.orDie);147+148+ const { address } = Context.get(server, HttpServer.HttpServer);149+150+ const origin =151+ "port" in address152+ ? `http://127.0.0.1:${address.port}`153+ : yield* Effect.die("the test server listens on a socket, not a port");154+155+ return { authorizations: Ref.get(authorizations), origin };156+ });