Skip to content
Myr

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

6 files+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 */14import { BunHttpServer } from "@effect/platform-bun";15import { Brand } from "@repo/brand";16import { detectHarness } from "@repo/protocol/audit";17import { Contracts } from "@repo/protocol/contracts";18import type { Client } from "@repo/protocol/contracts";19import {20 Deferred,21 Context,22 Effect,23 Layer,24 Option,25 Redacted,26 Schema,27 Stdio,28 Stream,29} from "effect";1import { Effect } from "effect";2import { Command } from "effect/cli";30import type { Scope } from "effect";31import { Command, Flag } from "effect/cli";32import {33 FetchHttpClient,34 HttpClient,35 HttpClientRequest,36 HttpServerRequest,37 HttpServerResponse,38} from "effect/http";39import type { HttpServer, HttpServerError } from "effect/http";40import { ChildProcess, ChildProcessSpawner } from "effect/process";41import { RpcClient, RpcSerialization } from "effect/rpc";424/** `login`: issue 412 replaces this stub (PKCE, or `--token-stdin`). */5export const login = Command.make("login", {}, () =>6 Effect.die("not built: issue 412")43import { currentEnv } from "../credential-helper.ts";44import { Credentials, gitHelperConfig } from "../credentials.ts";45import type { Profile } from "../credentials.ts";46import { Output } from "../output.ts";4748/** The env names the CLI reads, spelled from the brand: `<SLUG>_URL`. */49const SLUG = Brand.slug.toUpperCase();5051/** The address the loopback server binds: this machine only. */52const LOOPBACK = "127.0.0.1";5354/** How long `login` waits for the browser to come back. */55const SIGN_IN_WAIT = "5 minutes";5657/**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 */62const clientIdOf = (origin: string) => `${origin}/oauth/cli`;6364// --- The host seams: each has a default the binary runs on, and tests swap it.6566/**67 * Where `login` hears the browser come back: an HTTP server on one address,68 * for one scope. The binary listens with Bun.69 */70export 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});8485/**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 */90export 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});112113/** Opens `url` with the first of `commands` that runs; none running is fine. */114const openWith = (url: string, commands: readonly string[]) =>115 Effect.gen(function* () {116 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;117118 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);128129 if (Option.exists(code, (exit) => exit === 0)) {130 return;131 }132 }133 });134135/**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 */139export 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});148149// --- Failures.150151/** `login` was run in a way that cannot work; the message says what to run. */152export class LoginUsage extends Schema.TaggedError<LoginUsage>()("LoginUsage", {153 reason: Schema.String,154}) {155 override get message() {156 return this.reason;157 }158}159160/** The platform, or the sign-in, said no; nothing was stored. */161export class LoginRefused extends Schema.TaggedError<LoginRefused>()(162 "LoginRefused",163 { reason: Schema.String }164) {165 override get message() {166 return this.reason;167 }168}169170/** git would not take a config line; the message names it, to run by hand. */171export 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}179180// --- Shared parts.181182const 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};194195/** The profile a command acts on: the flag, else `<SLUG>_PROFILE`, else `default`. */196const profileName = (197 flag: Option.Option<string>,198 env: Readonly<Record<string, string>>199) => Option.getOrElse(flag, () => env[`${SLUG}_PROFILE`] ?? "default");200201/** An argv list as a person would type it in a shell. */202const typed = (argv: readonly string[]) =>203 argv204 .map((arg) => {205 if (arg === "") {206 return '""';207 }208209 return /^[\w./:@=-]+$/u.test(arg)210 ? arg211 : `'${arg.replaceAll("'", String.raw`'\''`)}'`;212 })213 .join(" ");214215/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */216const 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;224225 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);236237 return Option.exists(code, (exit) => allowed.includes(exit))238 ? undefined239 : yield* new GitConfigFailed({ command: typed(argv) });240 });241242const asUrl = Option.liftThrowable((text: string) => new URL(text));243244/** Hosts that are this machine, where plain http keeps a token local. */245const THIS_MACHINE = new Set(["localhost", "127.0.0.1", "[::1]"]);246247/** `given`'s origin, if it is a platform url: https, or http on this machine. */248const 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 );266267/**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 */273const 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 );282283 if (Option.isSome(named)) {284 return yield* originOf(named.value);285 }286287 const name = profileName(profile, env);288289 const current =290 name === profileName(Option.none(), env)291 ? yield* (yield* Credentials).current292 : Option.none<Profile>();293294 if (Option.isSome(current)) {295 return yield* originOf(current.value.url);296 }297298 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 });302303// --- The token, by one of two ways.304305/** The token piped to `--token-stdin`: its first line, read no further. */306const tokenFromStdin = Effect.gen(function* () {307 const { stdin } = yield* Stdio.Stdio;308309 const [line = ""] = yield* stdin.pipe(310 Stream.decodeText(),311 Stream.splitLines,312 Stream.take(1),313 Stream.runCollect,314 Effect.orElseSucceed((): readonly string[] => [])315 );316317 const token = line.trim();318319 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 }324325 return Redacted.make(token);326});327328const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);329330/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */331const randomText = (size: number) =>332 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(333 Effect.flatMap(encodeBase64Url),334 Effect.orDie335 );336337/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */338const 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 );345346/**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 */351const 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>();355356 yield* server.serve(357 Effect.gen(function* () {358 const request = yield* HttpServerRequest.HttpServerRequest;359 const at = new URL(request.url, `http://${LOOPBACK}`);360361 if (request.method !== "GET" || at.pathname !== "/callback") {362 return HttpServerResponse.text("Not found.", { status: 404 });363 }364365 const first = yield* Deferred.succeed(returned, at.searchParams);366367 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 );379380 if (!("port" in server.address)) {381 return yield* Effect.die("the loopback server listens on a socket");382 }383384 return {385 redirectUri: `http://${LOOPBACK}:${server.address.port}/callback`,386 returned: Deferred.await(returned),387 };388});389390/** What `/token` answers a good code with. */391const TokenResponse = Schema.Struct({392 access_token: Schema.RedactedFromValue(Schema.NonEmptyString),393 token_type: Schema.String,394});395396const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);397398/** Trades the code for an access token at `<url>/token`, showing the verifier. */399const 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 });408409 return Effect.gen(function* () {410 const client = yield* HttpClient.HttpClient;411412 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 );424425 if (response.status !== 200) {426 return yield* refused;427 }428429 const body = yield* decodeTokenResponse(yield* response.json);430431 if (body.token_type.toLowerCase() !== "bearer") {432 return yield* refused;433 }434435 return body.access_token;436 }).pipe(437 Effect.provide(FetchHttpClient.layer),438 Effect.mapError(() => refused)439 );440};441442/**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 */448const 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;455456 const authorize = new URL("/authorize", url);457458 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();466467 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 );473474 if (opens) {475 yield* (yield* Browser).open(authorize.href);476 }477478 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 );490491 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 }496497 const code = query.get("code");498499 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 }504505 return yield* exchange({ code, redirectUri, url, verifier });506 })507 );508509/** The handle `status` shows: the claimant of the caller's claims, if any. */510const handleOf = (status: {511 readonly claims: readonly { readonly claimant: Profile["handle"] }[];512}) => Option.fromNullishOr(status.claims[0]?.claimant);513514/** Asks the platform at `url` who `token` is; a refusal or no answer stores nothing. */515const verify = (url: string, token: Redacted.Redacted) =>516 Effect.scoped(517 Effect.gen(function* () {518 const client = yield* (yield* PlatformClient).connect({ token, url });519520 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 );530531/** Whether `login` may open a browser: only for a person at a terminal. */532const mayOpenBrowser = (env: Readonly<Record<string, string>>) =>533 Effect.gen(function* () {534 const { mode } = yield* Output;535 const { stdoutIsTerminal } = yield* Stdio.Stdio;536537 return (538 mode === "human" &&539 detectHarness(env).harness === undefined &&540 env.CI === undefined &&541 (yield* stdoutIsTerminal)542 );543 });544545/** The lines of a view: a sentence, then each command on its own line. */546const viewOf = (said: string, commands: readonly (readonly string[])[]) => {547 const lines = commands.map((argv) => typed(argv));548549 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};557558export 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);592593 const token = given.tokenStdin594 ? yield* tokenFromStdin595 : yield* tokenFromBrowser(596 url,597 !given.noBrowser && (yield* mayOpenBrowser(env))598 );599600 const handle = yield* verify(url, token);601602 yield* credentials.put(603 name,604 Option.match(handle, {605 onNone: (): Profile => ({ token, url }),606 onSome: (who): Profile => ({ handle: who, token, url }),607 })608 );609610 const commands = gitHelperConfig(url);611612 if (!given.noGitConfig) {613 for (const argv of commands) {614 yield* runGit(argv, env);615 }616 }617618 const who = Option.match(handle, {619 onNone: () => "",620 onSome: (known) => ` as ${known}`,621 });622623 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);65013/** `logout`: issue 412 replaces this stub. */14export 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. */652const 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];656657const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;658659/** The urls whose git config names this CLI's helper. */660const helperUrls = (env: Readonly<Record<string, string>>) =>661 Effect.gen(function* () {662 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;663664 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[] => []));678679 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;684685 return value === Brand.slug && url !== undefined ? [url] : [];686 });687688 return [...new Set(urls)];689 });690691export 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);698699 // git keeps asking the helper for a platform another profile is still on.700 const unused: string[] = [];701702 for (const url of yield* helperUrls(env)) {703 const host = Option.map(asUrl(url), ({ host: at }) => at);704705 if (706 Option.isSome(host) &&707 Option.isNone(yield* credentials.forHost(host.value))708 ) {709 unused.push(url);710 }711 }712713 const commands = unused.flatMap(gitHelperUnset);714715 for (const argv of commands) {716 yield* runGit(argv, env, [0, 5]);717 }718719 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
added:apps/cli/test/local/credential-helper.test.ts+497 added
1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client } from "@repo/protocol/contracts";5import { gitOk, spawn } from "@repo/testkit/git";6import { httpBackend } from "@repo/testkit/http-backend";7import {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";26import type { Cause } from "effect";27import { CliOutput } from "effect/cli";28import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";29import type { ChildProcessSpawner } from "effect/process";30import { TestConsole } from "effect/testing";3132import { credentialHelper, currentEnv } from "../../src/credential-helper.ts";33import { Credentials, CredentialsFile } from "../../src/credentials.ts";34import type { Profile } from "../../src/credentials.ts";35import { program } from "../../src/main.ts";36import { OutputPlain } from "../../src/output.ts";3738/** The env names the CLI reads, spelled from the brand. */39const SLUG = Brand.slug.toUpperCase();4041const token = "t0ken-0123456789abcdefghijklmnopqrstuvwxyz";4243const platform: Profile = {44 token: Redacted.make(token),45 url: "https://platform.test",46};4748/** What git writes to its helper for a repo on `host`, blank line and all. */49const asked = (host: string, protocol = "https") =>50 `protocol=${protocol}\nhost=${host}\npath=datekit--fix-week--alice.git\n\n`;5152/** A pi session's env, as pi hands it to the git it runs. */53const pi = { AI_AGENT: "pi", PI_MODEL: "kimi-k3" };5455const encoder = new TextEncoder();5657const decoder = new TextDecoder();5859/** The credentials file in the config dir `env` names. */60const credentialsIn = (env: Record<string, string>) =>61 CredentialsFile.pipe(62 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))63 );6465/**66 * A fresh config dir holding `profiles`, and the env that names it: the67 * shell a person who ran `login` would give git.68 */69const 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 };7475 const credentials = yield* Effect.provide(76 Effect.service(Credentials),77 credentialsIn(env)78 );7980 for (const [name, profile] of Object.entries(profiles)) {81 yield* credentials.put(name, profile);82 }8384 return env;85 });8687/** A terminal that no helper may touch: every use of it dies. */88const 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);9899/**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 */103const 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>();110111 const stdio = Stdio.layerTest({112 stdin,113 stdout: () => Sink.fromQueue(written),114 });115116 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 );134135 const stderr = (yield* TestConsole.errorLines).map(String);136137 const stdout = (yield* Queue.clear(written))138 .map((chunk) =>139 Predicate.isString(chunk) ? chunk : decoder.decode(chunk)140 )141 .join("");142143 return { ok: Exit.isSuccess(exit), stderr, stdout };144 }).pipe(Effect.provide(TestConsole.layer));145146/** `text` as stdin that ends after it. */147const input = (text: string) => Stream.make(encoder.encode(text));148149describe(`${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 });155156 const ran = yield* helper("get", input(asked("platform.test")), {157 ...env,158 ...pi,159 });160161 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 );168169 it.live("says nothing for another host, so git asks its next helper", () =>170 Effect.gen(function* () {171 const env = yield* storedIn({ default: platform });172173 const ran = yield* helper("get", input(asked("github.com")), {174 ...env,175 ...pi,176 });177178 expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });179 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))180 );181182 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 });185186 const ran = yield* helper(187 "get",188 input(asked("platform.test", "http")),189 env190 );191192 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 );197198 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({});203204 const ran = yield* helper("get", input(asked("platform.test")), env);205206 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 );212213 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 };221222 const env = yield* storedIn({ alice: platform, bob });223224 const asBob = yield* helper("get", input(asked("platform.test")), {225 ...env,226 [`${SLUG}_PROFILE`]: "bob",227 });228229 const asCarol = yield* helper("get", input(asked("platform.test")), {230 ...env,231 [`${SLUG}_PROFILE`]: "carol",232 });233234 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 );244245 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 });250251 const ran = yield* helper(252 op,253 input(`${asked("platform.test")}username=x\npassword=${token}\n\n`),254 env255 );256257 expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });258259 const kept = yield* Effect.provide(260 Effect.flatMap(261 Effect.service(Credentials),262 (stored) => stored.current263 ),264 credentialsIn(env)265 );266267 expect(268 Option.map(kept, (profile) => Redacted.value(profile.token))269 ).toStrictEqual(Option.some(token));270 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))271 );272273 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 });278279 const endless = Stream.concat(280 input(asked("platform.test")),281 Stream.never282 );283284 const pastTheEnd = Stream.concat(285 input(asked("platform.test")),286 Stream.die("the helper read past the blank line")287 );288289 for (const stdin of [endless, pastTheEnd]) {290 const ran = yield* helper("get", stdin, env);291292 expect(ran.stdout).toBe(`username=audit;\npassword=${token}\n`);293 }294 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))295 );296});297298describe(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 });310311 const stdout = yield* credentialHelper(312 "get",313 asked("platform.test"),314 {}315 ).pipe(Effect.provide(credentialsIn(env)));316317 expect(stdout).toBe(`username=audit;\npassword=${token}\n`);318 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))319 );320});321322describe("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 });330331 const reads = yield* Ref.make(0);332333 const counted = ConfigProvider.make((at) =>334 Effect.andThen(335 Ref.update(reads, (n) => n + 1),336 source.load(at)337 )338 );339340 const read = yield* currentEnv.pipe(341 Effect.provideService(ConfigProvider.ConfigProvider, counted)342 );343344 expect(read).toStrictEqual({ AI_AGENT: "pi", RUN_0: "first" });345 expect(yield* Ref.get(reads)).toBeLessThan(2000);346 })347 );348});349350const Basic = /^Basic (?<encoded>\S+)$/u;351352const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);353354/**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 */359const guarded = (root: string) =>360 Effect.gen(function* () {361 const spawner =362 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();363364 const seen = yield* Ref.make<readonly { user: string; password: string }[]>(365 []366 );367368 const backend = httpBackend(root);369370 const app = Effect.gen(function* () {371 const request = yield* HttpServerRequest.toWeb(372 yield* HttpServerRequest.HttpServerRequest373 );374375 const pair = Option.fromNullishOr(376 Basic.exec(request.headers.get("authorization") ?? "")?.groups?.encoded377 ).pipe(Option.flatMap(fromBase64));378379 if (Option.isNone(pair)) {380 return HttpServerResponse.text("sign in", {381 headers: { "www-authenticate": 'Basic realm="test"' },382 status: 401,383 });384 }385386 const colon = pair.value.indexOf(":");387388 yield* Ref.update(seen, (all) => [389 ...all,390 {391 password: pair.value.slice(colon + 1),392 user: pair.value.slice(0, colon),393 },394 ]);395396 return HttpServerResponse.fromWeb(397 yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))398 );399 }).pipe(Effect.orDie);400401 const server = yield* Layer.build(402 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))403 ).pipe(Effect.orDie);404405 const { address } = Context.get(server, HttpServer.HttpServer);406407 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");411412 return { origin, seen: Ref.get(seen) };413 });414415describe("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();424425 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 );443444 const head = yield* gitOk(work, "rev-parse", "HEAD");445 const server = yield* guarded(root);446447 const env = yield* storedIn({448 default: { token: Redacted.make(token), url: server.origin },449 });450451 const bin = yield* path.fromFileUrl(452 new URL("../../src/bin.ts", import.meta.url)453 );454455 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 );478479 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 );487488 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
1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";5import { ClaimView } from "@repo/protocol/domain/claim";6import { Handle } from "@repo/protocol/ids";7import {8 Authenticated,9 CurrentPrincipal,10 Person,11 Unauthenticated,12} from "@repo/protocol/principal";13import { asPerson, unanswered } from "@repo/protocol/testing";14import { spawn } from "@repo/testkit/git";15import {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";33import { CliOutput } from "effect/cli";34import { FetchHttpClient, HttpClient, HttpServer } from "effect/http";35import { RpcTest } from "effect/rpc";36import { TestClock, TestConsole } from "effect/testing";3738import { Credentials, CredentialsFile } from "../../src/credentials.ts";39import { Browser, Loopback, PlatformClient } from "../../src/local/login.ts";40import { program } from "../../src/main.ts";41import { OutputPlain } from "../../src/output.ts";42import { oauthServer } from "../oauth-server.ts";4344/** The env names the CLI reads, spelled from the brand. */45const SLUG = Brand.slug.toUpperCase();4647const url = "https://platform.test";4849const given = "tok-given-0123456789abcdefghijklmnopqrstuvwxyz";5051const issued = "tok-issued-0123456789abcdefghijklmnopqrstuvwxyz";5253/** The three lines `login` sets in git's global config for `at`. */54const 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];5960/** The same three, as the argv lists `--json` carries. */61const 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];6667/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */68const home = Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;71 const dir = yield* fs.makeTempDirectoryScoped();7273 return { GIT_CONFIG_GLOBAL: path.join(dir, ".gitconfig"), HOME: dir };74});7576const credentialsIn = (env: Record<string, string>) =>77 CredentialsFile.pipe(78 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))79 );8081/** The profile `name` as the file holds it: its url, handle and token. */82const 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 );9596/** `git config --global <args>` in `env`: its stdout and exit code. */97const 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 });103104 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);111112 return { exitCode, stdout };113 })114 );115116const claim = Schema.decodeUnknownSync(ClaimView);117118const isPerson = Schema.is(Person);119120/** One live claim of `handle`'s, as `status` lists it. */121const 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 });135136/**137 * The platform's side of a call, as `status` sees it: whoever the server138 * side takes the caller for holds one claim.139 */140const statusHandler = Contracts.toLayerHandler("status", () =>141 Effect.map(Effect.service(CurrentPrincipal), (principal) => ({142 answers: [],143 claims: isPerson(principal) ? [claimOf(principal.handle)] : [],144 }))145);146147/** A server side that refuses every credential, as for a revoked token. */148const refusesEveryone = Layer.succeed(Authenticated, () =>149 Effect.fail(new Unauthenticated())150);151152/**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 */158const seams = (server: Layer.Layer<Authenticated>) =>159 Effect.gen(function* () {160 const connected = yield* Ref.make<161 readonly { token: string; url: string }[]162 >([]);163164 const opened = yield* Ref.make<readonly string[]>([]);165166 const listened = yield* Ref.make<167 readonly { hostname: string; port: number }[]168 >([]);169170 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]);190191 const built = yield* Layer.build(NodeHttpServer.layerTest);192193 return Context.get(built, HttpServer.HttpServer);194 }),195 })196 );197198 return {199 connected: Ref.get(connected),200 layer,201 listened: Ref.get(listened),202 opened: Ref.get(opened),203 };204 });205206/** A platform that takes the caller for `handle`. */207const signedInAs = (handle: string) => asPerson(Handle.make(handle));208209/** What the tests themselves run on: a test console, and Node for files, git and servers. */210const testServices = Layer.mergeAll(TestConsole.layer, NodeServices.layer);211212/** A terminal nothing may touch: every use of it dies. */213const 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);223224interface 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}232233/** Runs `argv` as the CLI would, in `run`'s world; how it ended. */234const 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 );257258/** What was printed, one entry per line however it was written. */259const lines = (all: readonly unknown[]) =>260 all.flatMap((chunk) => String(chunk).split("\n"));261262/** Every line printed so far, on stdout and on stderr. */263const printed = Effect.gen(function* () {264 return {265 stderr: lines(yield* TestConsole.errorLines),266 stdout: lines(yield* TestConsole.logLines),267 };268});269270/** The sign-in URL `login` printed for `origin`, once it has. */271const 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?`));277278 if (line !== undefined) {279 return line;280 }281282 yield* Effect.sleep("20 millis");283 }284285 return yield* Effect.die("login printed no sign-in URL");286 });287288/** GET `at` as a browser would, following redirects: the page's status. */289const visit = (at: string) =>290 Effect.gen(function* () {291 const client = yield* HttpClient.HttpClient;292 const response = yield* client.get(at);293294 return response.status;295 }).pipe(Effect.provide(FetchHttpClient.layer));296297/** The query `/authorize` was sent, field by field. */298const fieldsOf = (query: URLSearchParams | undefined) =>299 Object.fromEntries(query?.entries() ?? []);300301describe(`${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"));308309 const exit = yield* cli(310 ["login", "--url", url, "--token-stdin", "--profile", "alice"],311 { env, seams: platform.layer, stdin: `${given}\n` }312 );313314 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 });337338 const { stderr, stdout } = yield* printed;339340 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 );347348 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"));354355 yield* cli(["login", "--url", url, "--token-stdin", "--json"], {356 env,357 seams: platform.layer,358 stdin: `${given}\n`,359 });360361 const { stdout } = yield* printed;362 const text = stdout.join("\n");363364 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 );380381 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"));387388 const exit = yield* cli(389 ["login", "--url", url, "--token-stdin", "--no-git-config", "--json"],390 { env, seams: platform.layer, stdin: `${given}\n` }391 );392393 expect(Exit.isSuccess(exit)).toBeTruthy();394 expect(395 (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))396 .exitCode397 ).toBe(1);398399 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 );406407 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";414415 yield* cli(["login", "--url", odd, "--token-stdin"], {416 env,417 seams: platform.layer,418 stdin: `${given}\n`,419 });420421 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 );431432 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);438439 const exit = yield* cli(["login", "--url", url, "--token-stdin"], {440 env,441 seams: platform.layer,442 stdin: `${given}\n`,443 });444445 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);451452 const { stderr, stdout } = yield* printed;453454 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 );459460 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"));466467 const exit = yield* cli(468 ["login", "--url", "http://platform.test", "--token-stdin"],469 { env, seams: platform.layer, stdin: `${given}\n` }470 );471472 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 );478479 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` };486487 yield* cli(["login", "--url", url, "--token-stdin"], run);488489 const again = yield* cli(["login", "--token-stdin"], run);490491 const other = yield* cli(492 ["login", "--token-stdin", "--profile", "bob"],493 run494 );495496 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 );511512 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"));518519 const exit = yield* cli(["login", "--token-stdin"], {520 env,521 seams: platform.layer,522 stdin: `${given}\n`,523 });524525 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});531532describe(`${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"));540541 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 );554555 expect(yield* visit(yield* signInUrl(server.origin))).toBe(200);556 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();557558 const [query] = yield* server.authorizations;559 const fields = fieldsOf(query);560 const urlSafe43 = /^[A-Za-z0-9_-]{43}$/u;561562 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 });604605 // 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 );609610 const { stderr, stdout } = yield* printed;611612 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 );619620 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"));627628 const fiber = yield* Effect.forkChild(629 cli(["login", "--url", server.origin, "--no-browser"], {630 env,631 seams: platform.layer,632 })633 );634635 yield* visit(yield* signInUrl(server.origin));636637 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 );644645 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"));652653 const fiber = yield* Effect.forkChild(654 cli(["login", "--url", server.origin], {655 env,656 seams: platform.layer,657 terminal: true,658 })659 );660661 const shown = yield* signInUrl(server.origin);662663 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 );669670 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"));677678 const fiber = yield* Effect.forkChild(679 cli(["login", "--url", server.origin], {680 env,681 seams: platform.layer,682 terminal: true,683 })684 );685686 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 );692693 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();701702 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 );708709 const shown = yield* signInUrl(server.origin);710711 yield* clock.adjust("5 minutes");712713 expect(Exit.isFailure(yield* Fiber.join(fiber))).toBeTruthy();714715 const said = (yield* printed).stderr.join("\n");716717 expect(said).toContain("5 minutes");718 expect(said).toContain("--token-stdin");719 expect(yield* stored(env, "default")).toStrictEqual(Option.none());720721 const callback = new URL(shown).searchParams.get("redirect_uri") ?? "";722723 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});732733describe(`${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` };741742 yield* cli(743 ["login", "--url", url, "--token-stdin", "--profile", "alice"],744 run745 );746747 const exit = yield* cli(["logout", "--profile", "alice"], run);748749 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 );762763 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` };770771 yield* cli(["login", "--url", url, "--token-stdin"], run);772 yield* gitConfig(env, "--add", `credential.${url}.useHttpPath`, "true");773774 const exit = yield* cli(["logout"], run);775776 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 );784785 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` };792793 for (const name of ["alice", "bob"]) {794 yield* cli(795 ["login", "--url", url, "--token-stdin", "--profile", name],796 run797 );798 }799800 yield* cli(["logout", "--profile", "alice"], run);801802 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();806807 yield* cli(["logout", "--profile", "bob"], run);808809 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 lines
5import { Cause, Effect, Exit, Layer } from "effect";6import { CliOutput, Command } from "effect/cli";7import { TestConsole } from "effect/testing";89import { Credentials } from "../src/credentials.ts";10import { program, root } from "../src/main.ts";11import { OutputPlain } from "../src/output.ts";1213/** What was printed to stdout, one entry per line however it was written. */
2 unmodified lines
16);1718/**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 */22const 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));2930/** The help `root` prints for `--help`, line by line. */
63 unmodified lines
94});9596describe("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 lines
added: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 */8import { NodeHttpServer } from "@effect/platform-node";9import { Context, Effect, Layer, Ref, Schema } from "effect";10import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";1112export 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}1819/** A code `/authorize` gave out, and what `/token` must be shown for it. */20interface Grant {21 readonly challenge: string;22 readonly clientId: string;23 readonly redirectUri: string;24}2526const 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});3334/** Base64url without padding, as RFC 7636 §4.2 spells the S256 challenge. */35const base64url = (bytes: Uint8Array) =>36 btoa(String.fromCodePoint(...bytes))37 .replaceAll("+", "-")38 .replaceAll("/", "_")39 .replace(/=+$/u, "");4041/** `BASE64URL(SHA256(verifier))`. */42const 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 );4950const refused = (error: string) =>51 HttpServerResponse.jsonUnsafe({ error }, { status: 400 });5253/**54 * The server on a local port: its origin, and the query of every55 * `/authorize` request it answered.56 */57export 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);6263 const authorize = (query: URLSearchParams) =>64 Effect.gen(function* () {65 yield* Ref.update(authorizations, (all) => [...all, query]);6667 const redirectUri = query.get("redirect_uri") ?? "";68 const challenge = query.get("code_challenge") ?? "";6970 if (71 query.get("response_type") !== "code" ||72 query.get("code_challenge_method") !== "S256" ||73 challenge === ""74 ) {75 return refused("invalid_request");76 }7778 const code = `code-${yield* Ref.updateAndGet(issued, (n) => n + 1)}`;7980 yield* Ref.update(grants, (all) =>81 new Map(all).set(code, {82 challenge,83 clientId: query.get("client_id") ?? "",84 redirectUri,85 })86 );8788 const back = new URL(redirectUri);8990 back.searchParams.set("code", code);91 back.searchParams.set(92 "state",93 options.state === "other"94 ? "not-the-state"95 : (query.get("state") ?? "")96 );9798 return HttpServerResponse.redirect(back.href, { status: 302 });99 });100101 const token = Effect.gen(function* () {102 const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);103 const grant = (yield* Ref.get(grants)).get(form.code);104105 yield* Ref.update(grants, (all) => {106 const left = new Map(all);107108 left.delete(form.code);109110 return left;111 });112113 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 }122123 return HttpServerResponse.jsonUnsafe({124 access_token: options.token,125 token_type: "bearer",126 });127 }).pipe(Effect.orElseSucceed(() => refused("invalid_request")));128129 const app = Effect.gen(function* () {130 const request = yield* HttpServerRequest.HttpServerRequest;131 const url = new URL(request.url, "http://localhost");132133 if (request.method === "GET" && url.pathname === "/authorize") {134 return yield* authorize(url.searchParams);135 }136137 if (request.method === "POST" && url.pathname === "/token") {138 return yield* token;139 }140141 return HttpServerResponse.empty({ status: 404 });142 });143144 const server = yield* Layer.build(145 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))146 ).pipe(Effect.orDie);147148 const { address } = Context.get(server, HttpServer.HttpServer);149150 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");154155 return { authorizations: Ref.get(authorizations), origin };156 });