Skip to content
Myr

Log in once with login, then plain git reaches the platform through the credential helper with no token in a url and no prompt

Before adoption: this commit came in with the history the project adopted, so no landing records it.

W4 group A (412). `<cli> login` signs in through the browser (PKCE, S256, against the platform's own OAuth server) or takes a token on stdin, checks it with `status`, keeps it as a profile and names `git-credential-<slug>` in git's global config for the platform's url; `<cli> credential get` answers git from that profile; `<cli> logout` forgets it. - credential-helper.ts: `credentialHelper(op, input, env)` (string in, stdout out) and the `credential <get|store|erase>` command 416 dispatches to. `get` answers only for a host a profile is on and only over that profile's scheme (an https profile never answers protocol=http), with `username=<auditUser(detectHarness(env))>` as audit metadata, never identity, and the token as the password; another host gets nothing (git tries its next helper); no login at all gets nothing on stdout and one stderr line naming `<cli> login`. `store` and `erase` read and do nothing (erase must not drop the profile: git sends it after any 401). stdin is read up to the blank line and no further; no terminal is touched. The answer goes straight to Stdio.stdout (a wire protocol, not a view). - `currentEnv` walks the CLI's ConfigProvider into an env record, so the harness detection and the git children see the env a test gives (apps/cli has no process types). - login.ts: `login [--url] [--profile] [--token-stdin] [--no-browser] [--no-git-config] [--json]` and `logout [--profile] [--json]`. The url is --url, else <SLUG>_URL, else the profile's; https, or plain http only on localhost/127.0.0.1/[::1]. The profile is --profile, else <SLUG>_PROFILE, else default. The token stays Redacted from stdin or /token to the credentials file, and is written out only in the Authorization header that checks it (HttpClientRequest.bearerToken takes the Redacted). - PKCE: verifier and state are 32 bytes each from WebCrypto getRandomValues (no diagnostic fired, no escape); client_id `<origin>/oauth/cli` (316's CIMD), no scope. The loopback server binds 127.0.0.1 on port 0, answers /callback once (410 after) with `connection: close` so closing it never waits on a keep-alive socket, and closes with the login's scope; the 5-minute wait wraps printing the URL and ends in a LoginUsage naming `--token-stdin`. A state that comes back different is refused and nothing is stored. - The browser opens only for a person: Output's mode human, no harness from detectHarness, no CI, stdout a terminal. The URL is always printed on stderr, so an agent hands it to a person; nothing ever prompts. - Host seams are Context.References with the binary's defaults (Loopback: BunHttpServer; PlatformClient: RpcClient over HTTP at <url>/rpc with the bearer; Browser: xdg-open, else open), so bin.ts needs no change and tests swap all three. - Decision: the handle comes from the caller's claims in `status` (its success carries no handle), so a first login stores none; the protocol change is requested in the issue's Comments (#1). PKCE tokens last an hour (the provider's default TTL) and Profile cannot hold the refresh token: Comments #2. - Decision: logout cannot read a named profile's url (Credentials has no get), so after removing the profile it unsets the helper config for every url naming `<slug>` that no remaining profile is on; two profiles on one platform keep git asking until the last logs out. - Outside the territory: apps/cli/test/main.test.ts drops 412's three stub rows and mocks Credentials, which program now needs. - Tests, red by assertion against the stubs first: test/local/credential-helper.test.ts (the exact username/password lines under AI_AGENT=pi PI_MODEL=kimi-k3, another host, http to an https profile, no login, store/erase keep the profile, endless stdin and a stdin that dies past the blank line, the function seam, and an it.live real `git ls-remote` through `!bun <bin.ts> credential` against a basic-auth git http-backend that sees the token as the password and the audit username); test/local/login.test.ts (token-stdin stores the profile with the handle and sets the git config in a temp HOME and GIT_CONFIG_GLOBAL; one --json envelope without the token; a refused token stores nothing and leaves git alone; http to a remote host refused; no url asks for --url; PKCE with --no-browser against test/oauth-server.ts, which checks code_verifier against the S256 challenge; a wrong state refused; a person's terminal opens the browser; CLAUDECODE=1 prints the URL and never prompts; the 5-minute timeout on a TestClock closes the loopback; logout removes the profile and the git lines, and keeps them while another profile shares the platform). - Live, on dev-oscabriel with a temp HOME: --token-stdin with the operator token, a bogus token refused, credential get, logout, and a full PKCE login as the W3 test account all behaved as tested. ASSUMPTION confirmed there: no scope or resource parameter is needed. - bun run fix && bun run verify green: cli 63 tests; gen:check current, imports:check no violations, debt at baseline, brand:check no leaks.

authored by oscabriel · committed by oscabriel · parent 650cb35 · Browse files · 6 files+2259 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+2259 added−18 removed

  • tests:+1322 added−4 removed
  • other:+937 added−14 removed

6 files+2259 added−18 removed

modified:apps/cli/src/local/login.ts+715 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) ? arg : `'${arg}'`;210 })211 .join(" ");212213/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */214const runGit = (215 argv: readonly string[],216 env: Readonly<Record<string, string>>,217 allowed: readonly number[] = [0]218) =>219 Effect.gen(function* () {220 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;221 const [command = "git", ...args] = argv;222223 const code = yield* spawner224 .exitCode(225 ChildProcess.make(command, args, {226 env,227 extendEnv: true,228 stderr: "ignore",229 stdin: "ignore",230 stdout: "ignore",231 })232 )233 .pipe(Effect.option);234235 return Option.exists(code, (exit) => allowed.includes(exit))236 ? undefined237 : yield* new GitConfigFailed({ command: typed(argv) });238 });239240const asUrl = Option.liftThrowable((text: string) => new URL(text));241242/** Hosts that are this machine, where plain http keeps a token local. */243const THIS_MACHINE = new Set(["localhost", "127.0.0.1", "[::1]"]);244245/** `given`'s origin, if it is a platform url: https, or http on this machine. */246const originOf = (given: string) =>247 Option.match(248 Option.filter(249 asUrl(given),250 ({ hostname, protocol }) =>251 protocol === "https:" ||252 (protocol === "http:" && THIS_MACHINE.has(hostname))253 ),254 {255 onNone: () =>256 Effect.fail(257 new LoginUsage({258 reason: `${given} is not a platform url: use https://<host> (plain http only for this machine)`,259 })260 ),261 onSome: ({ origin }) => Effect.succeed(origin),262 }263 );264265/** The platform to log in to: `--url`, else `<SLUG>_URL`, else the profile's own. */266const platformOf = (267 flag: Option.Option<string>,268 env: Readonly<Record<string, string>>269) =>270 Effect.gen(function* () {271 const named = Option.orElse(flag, () =>272 Option.fromNullishOr(env[`${SLUG}_URL`])273 );274275 if (Option.isSome(named)) {276 return yield* originOf(named.value);277 }278279 const current = yield* (yield* Credentials).current;280281 if (Option.isSome(current)) {282 return yield* originOf(current.value.url);283 }284285 return yield* new LoginUsage({286 reason: `no platform to log in to: run ${Brand.cli} login --url https://<platform host>`,287 });288 });289290// --- The token, by one of two ways.291292/** The token piped to `--token-stdin`: its first line, read no further. */293const tokenFromStdin = Effect.gen(function* () {294 const { stdin } = yield* Stdio.Stdio;295296 const [line = ""] = yield* stdin.pipe(297 Stream.decodeText(),298 Stream.splitLines,299 Stream.take(1),300 Stream.runCollect,301 Effect.orElseSucceed((): readonly string[] => [])302 );303304 const token = line.trim();305306 if (token === "") {307 return yield* new LoginUsage({308 reason: `--token-stdin read no token: pipe it in, one line, e.g. ${Brand.cli} login --token-stdin < token.txt`,309 });310 }311312 return Redacted.make(token);313});314315const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);316317/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */318const randomText = (size: number) =>319 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(320 Effect.flatMap(encodeBase64Url),321 Effect.orDie322 );323324/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */325const challengeOf = (verifier: string) =>326 Effect.promise(() =>327 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))328 ).pipe(329 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),330 Effect.orDie331 );332333/**334 * A server on 127.0.0.1 at a port the system picks, for this scope, that335 * takes the browser's one return to `/callback`: its `redirect_uri`, and336 * the query the browser brought back.337 */338const loopback = Effect.gen(function* () {339 const { listen } = yield* Loopback;340 const server = yield* listen({ hostname: LOOPBACK, port: 0 });341 const returned = yield* Deferred.make<URLSearchParams>();342343 yield* server.serve(344 Effect.gen(function* () {345 const request = yield* HttpServerRequest.HttpServerRequest;346 const at = new URL(request.url, `http://${LOOPBACK}`);347348 if (request.method !== "GET" || at.pathname !== "/callback") {349 return HttpServerResponse.text("Not found.", { status: 404 });350 }351352 const first = yield* Deferred.succeed(returned, at.searchParams);353354 return HttpServerResponse.text(355 first356 ? `${Brand.cli} login has the sign-in. You can close this tab; the terminal says how it ended.`357 : "This sign-in has already come back.",358 {359 // One request per connection, so closing the server waits on none.360 headers: { "cache-control": "no-store", connection: "close" },361 status: first ? 200 : 410,362 }363 );364 })365 );366367 if (!("port" in server.address)) {368 return yield* Effect.die("the loopback server listens on a socket");369 }370371 return {372 redirectUri: `http://${LOOPBACK}:${server.address.port}/callback`,373 returned: Deferred.await(returned),374 };375});376377/** What `/token` answers a good code with. */378const TokenResponse = Schema.Struct({379 access_token: Schema.RedactedFromValue(Schema.NonEmptyString),380 token_type: Schema.String,381});382383const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);384385/** Trades the code for an access token at `<url>/token`, showing the verifier. */386const exchange = (input: {387 readonly code: string;388 readonly redirectUri: string;389 readonly url: string;390 readonly verifier: string;391}) => {392 const refused = new LoginRefused({393 reason: `${input.url}/token would not trade the sign-in for a token: run ${Brand.cli} login again`,394 });395396 return Effect.gen(function* () {397 const client = yield* HttpClient.HttpClient;398399 const response = yield* client.execute(400 HttpClientRequest.post(`${input.url}/token`).pipe(401 HttpClientRequest.acceptJson,402 HttpClientRequest.bodyUrlParams({403 client_id: clientIdOf(input.url),404 code: input.code,405 code_verifier: input.verifier,406 grant_type: "authorization_code",407 redirect_uri: input.redirectUri,408 })409 )410 );411412 if (response.status !== 200) {413 return yield* refused;414 }415416 const body = yield* decodeTokenResponse(yield* response.json);417418 if (body.token_type.toLowerCase() !== "bearer") {419 return yield* refused;420 }421422 return body.access_token;423 }).pipe(424 Effect.provide(FetchHttpClient.layer),425 Effect.mapError(() => refused)426 );427};428429/**430 * The token from a browser sign-in: PKCE (S256) against the platform's431 * `/authorize`, its code at the loopback server, then `/token`. The URL is432 * always printed; the browser opens only when `opens`. Waits at most five433 * minutes for the browser, then stops with a usage error.434 */435const tokenFromBrowser = (url: string, opens: boolean) =>436 Effect.scoped(437 Effect.gen(function* () {438 const output = yield* Output;439 const verifier = yield* randomText(32);440 const state = yield* randomText(32);441 const { redirectUri, returned } = yield* loopback;442443 const authorize = new URL("/authorize", url);444445 authorize.search = new URLSearchParams({446 client_id: clientIdOf(url),447 code_challenge: yield* challengeOf(verifier),448 code_challenge_method: "S256",449 redirect_uri: redirectUri,450 response_type: "code",451 state,452 }).toString();453454 const query = yield* Effect.gen(function* () {455 yield* output.note(456 opens457 ? `Opening a browser to sign in to ${url}. If it does not open, visit:\n ${authorize.href}`458 : `To sign in to ${url}, open this in a browser:\n ${authorize.href}`459 );460461 if (opens) {462 yield* (yield* Browser).open(authorize.href);463 }464465 return yield* returned;466 }).pipe(467 Effect.timeoutOrElse({468 duration: SIGN_IN_WAIT,469 orElse: () =>470 Effect.fail(471 new LoginUsage({472 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`,473 })474 ),475 })476 );477478 if (query.get("state") !== state) {479 return yield* new LoginRefused({480 reason: `the sign-in came back with another state, so it may not be yours; nothing was stored: run ${Brand.cli} login again`,481 });482 }483484 const code = query.get("code");485486 if (code === null || code === "") {487 return yield* new LoginRefused({488 reason: `${url} did not sign you in (${query.get("error") ?? "no code"}): run ${Brand.cli} login again`,489 });490 }491492 return yield* exchange({ code, redirectUri, url, verifier });493 })494 );495496/** The handle `status` shows: the claimant of the caller's claims, if any. */497const handleOf = (status: {498 readonly claims: readonly { readonly claimant: Profile["handle"] }[];499}) => Option.fromNullishOr(status.claims[0]?.claimant);500501/** Asks the platform at `url` who `token` is; a refusal or no answer stores nothing. */502const verify = (url: string, token: Redacted.Redacted) =>503 Effect.scoped(504 Effect.gen(function* () {505 const client = yield* (yield* PlatformClient).connect({ token, url });506507 return handleOf(yield* client.status({}));508 })509 ).pipe(510 Effect.mapError(511 () =>512 new LoginRefused({513 reason: `${url} did not take this token, or could not be reached; nothing was stored`,514 })515 )516 );517518/** Whether `login` may open a browser: only for a person at a terminal. */519const mayOpenBrowser = (env: Readonly<Record<string, string>>) =>520 Effect.gen(function* () {521 const { mode } = yield* Output;522 const { stdoutIsTerminal } = yield* Stdio.Stdio;523524 return (525 mode === "human" &&526 detectHarness(env).harness === undefined &&527 env.CI === undefined &&528 (yield* stdoutIsTerminal)529 );530 });531532/** The lines of a view: a sentence, then each command on its own line. */533const viewOf = (said: string, commands: readonly (readonly string[])[]) => {534 const lines = commands.map((argv) => typed(argv));535536 return {537 markdown:538 lines.length === 0539 ? said540 : `${said}\n\n\`\`\`sh\n${lines.join("\n")}\n\`\`\``,541 text: [said, ...lines.map((line) => ` ${line}`)].join("\n"),542 };543};544545export const login = Command.make(546 "login",547 {548 ...flags,549 noBrowser: Flag.Boolean("no-browser").pipe(550 Flag.withDefault(false),551 Flag.withDescription("Print the sign-in URL instead of opening a browser")552 ),553 noGitConfig: Flag.Boolean("no-git-config").pipe(554 Flag.withDefault(false),555 Flag.withDescription(556 "Leave git's config alone; print the lines to set instead"557 )558 ),559 tokenStdin: Flag.Boolean("token-stdin").pipe(560 Flag.withDefault(false),561 Flag.withDescription(562 "Read a token you were given from stdin, one line, instead of signing in"563 )564 ),565 url: Flag.String("url").pipe(566 Flag.withDescription(567 `The platform's origin, e.g. https://<host> (default: $${SLUG}_URL, else the profile's)`568 ),569 Flag.optional570 ),571 },572 (given) =>573 Effect.gen(function* () {574 const output = yield* Output;575 const credentials = yield* Credentials;576 const env = yield* currentEnv;577 const name = profileName(given.profile, env);578 const url = yield* platformOf(given.url, env);579580 const token = given.tokenStdin581 ? yield* tokenFromStdin582 : yield* tokenFromBrowser(583 url,584 !given.noBrowser && (yield* mayOpenBrowser(env))585 );586587 const handle = yield* verify(url, token);588589 yield* credentials.put(590 name,591 Option.match(handle, {592 onNone: (): Profile => ({ token, url }),593 onSome: (who): Profile => ({ handle: who, token, url }),594 })595 );596597 const commands = gitHelperConfig(url);598599 if (!given.noGitConfig) {600 for (const argv of commands) {601 yield* runGit(argv, env);602 }603 }604605 const who = Option.match(handle, {606 onNone: () => "",607 onSome: (known) => ` as ${known}`,608 });609610 yield* output.success({611 command: "login",612 data: {613 gitConfig: given.noGitConfig ? [] : commands,614 ...Option.match(handle, {615 onNone: () => ({}),616 onSome: (known) => ({ handle: known }),617 }),618 profile: name,619 url,620 },621 json: given.json,622 view: viewOf(623 given.noGitConfig624 ? `Logged in to ${url}${who} (profile ${name}). git's config is unchanged; for git to use this login, run:`625 : `Logged in to ${url}${who} (profile ${name}). git now asks ${Brand.cli} for this platform's token; its global config got:`,626 commands627 ),628 });629 })630).pipe(631 Command.withDescription(632 "Sign in to a platform; git and this CLI then use its token."633 )634);63513/** `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."));636/** The `git config --global` lines that undo `gitHelperConfig(url)`; exit 5 means already gone. */637const gitHelperUnset = (url: string): readonly (readonly string[])[] => [638 ["git", "config", "--global", "--unset-all", `credential.${url}.helper`],639 ["git", "config", "--global", "--unset", `credential.${url}.useHttpPath`],640];641642const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;643644/** The urls whose git config names this CLI's helper. */645const helperUrls = (env: Readonly<Record<string, string>>) =>646 Effect.gen(function* () {647 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;648649 const lines = yield* spawner650 .lines(651 ChildProcess.make(652 "git",653 [654 "config",655 "--global",656 "--get-regexp",657 String.raw`^credential\..*\.helper$`,658 ],659 { env, extendEnv: true, stderr: "ignore", stdin: "ignore" }660 )661 )662 .pipe(Effect.orElseSucceed((): readonly string[] => []));663664 const urls = lines.flatMap((line) => {665 const space = line.indexOf(" ");666 const key = space === -1 ? line : line.slice(0, space);667 const value = space === -1 ? "" : line.slice(space + 1);668 const url = HELPER_KEY.exec(key)?.groups?.url;669670 return value === Brand.slug && url !== undefined ? [url] : [];671 });672673 return [...new Set(urls)];674 });675676export const logout = Command.make("logout", flags, (given) =>677 Effect.gen(function* () {678 const output = yield* Output;679 const credentials = yield* Credentials;680 const env = yield* currentEnv;681 const name = profileName(given.profile, env);682 const removed = yield* credentials.remove(name);683684 // git keeps asking the helper for a platform another profile is still on.685 const unused: string[] = [];686687 for (const url of yield* helperUrls(env)) {688 const host = Option.map(asUrl(url), ({ host: at }) => at);689690 if (691 Option.isSome(host) &&692 Option.isNone(yield* credentials.forHost(host.value))693 ) {694 unused.push(url);695 }696 }697698 const commands = unused.flatMap(gitHelperUnset);699700 for (const argv of commands) {701 yield* runGit(argv, env, [0, 5]);702 }703704 yield* output.success({705 command: "logout",706 data: { gitConfig: commands, profile: name, removed },707 json: given.json,708 view: viewOf(709 `${removed ? `Logged out: profile ${name} removed.` : `No profile ${name} to remove.`}${710 commands.length === 0711 ? ""712 : ` git no longer asks ${Brand.cli} for ${unused.join(", ")}; its global config lost:`713 }`,714 commands715 ),716 });717 })718).pipe(719 Command.withDescription(720 "Forget a profile's token, and stop git asking for a platform no profile is on."721 )722);
modified:apps/cli/src/credential-helper.ts+222 added-5 removed
added:apps/cli/test/local/credential-helper.test.ts+437 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 } 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.each(["store", "erase"])(214 "%s reads what git sends, prints nothing and keeps the stored token",215 (op) =>216 Effect.gen(function* () {217 const env = yield* storedIn({ default: platform });218219 const ran = yield* helper(220 op,221 input(`${asked("platform.test")}username=x\npassword=${token}\n\n`),222 env223 );224225 expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });226227 const kept = yield* Effect.provide(228 Effect.flatMap(229 Effect.service(Credentials),230 (stored) => stored.current231 ),232 credentialsIn(env)233 );234235 expect(236 Option.map(kept, (profile) => Redacted.value(profile.token))237 ).toStrictEqual(Option.some(token));238 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))239 );240241 it.live(242 "answers at the blank line without reading further, even if stdin never ends",243 () =>244 Effect.gen(function* () {245 const env = yield* storedIn({ default: platform });246247 const endless = Stream.concat(248 input(asked("platform.test")),249 Stream.never250 );251252 const pastTheEnd = Stream.concat(253 input(asked("platform.test")),254 Stream.die("the helper read past the blank line")255 );256257 for (const stdin of [endless, pastTheEnd]) {258 const ran = yield* helper("get", stdin, env);259260 expect(ran.stdout).toBe(`username=audit;\npassword=${token}\n`);261 }262 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))263 );264});265266describe(credentialHelper, () => {267 it.live(268 "names no harness when none runs it, and answers from the profile on the asked host",269 () =>270 Effect.gen(function* () {271 const env = yield* storedIn({272 default: {273 token: Redacted.make("other-token"),274 url: "https://x.test",275 },276 platform,277 });278279 const stdout = yield* credentialHelper(280 "get",281 asked("platform.test"),282 {}283 ).pipe(Effect.provide(credentialsIn(env)));284285 expect(stdout).toBe(`username=audit;\npassword=${token}\n`);286 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))287 );288});289290const Basic = /^Basic (?<encoded>\S+)$/u;291292const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);293294/**295 * `git http-backend` over `root` behind basic auth, on a local port: a296 * request without credentials gets the 401 that makes git ask its helper.297 * Its base URL, and every `user:password` pair it was sent.298 */299const guarded = (root: string) =>300 Effect.gen(function* () {301 const spawner =302 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();303304 const seen = yield* Ref.make<readonly { user: string; password: string }[]>(305 []306 );307308 const backend = httpBackend(root);309310 const app = Effect.gen(function* () {311 const request = yield* HttpServerRequest.toWeb(312 yield* HttpServerRequest.HttpServerRequest313 );314315 const pair = Option.fromNullishOr(316 Basic.exec(request.headers.get("authorization") ?? "")?.groups?.encoded317 ).pipe(Option.flatMap(fromBase64));318319 if (Option.isNone(pair)) {320 return HttpServerResponse.text("sign in", {321 headers: { "www-authenticate": 'Basic realm="test"' },322 status: 401,323 });324 }325326 const colon = pair.value.indexOf(":");327328 yield* Ref.update(seen, (all) => [329 ...all,330 {331 password: pair.value.slice(colon + 1),332 user: pair.value.slice(0, colon),333 },334 ]);335336 return HttpServerResponse.fromWeb(337 yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))338 );339 }).pipe(Effect.orDie);340341 const server = yield* Layer.build(342 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))343 ).pipe(Effect.orDie);344345 const { address } = Context.get(server, HttpServer.HttpServer);346347 const origin =348 "port" in address349 ? `http://127.0.0.1:${address.port}`350 : yield* Effect.die("the test server listens on a socket, not a port");351352 return { origin, seen: Ref.get(seen) };353 });354355describe("real git with the helper", () => {356 it.live(357 "git ls-remote sends the stored token as the basic-auth password, with no token in the url",358 () =>359 Effect.gen(function* () {360 const fs = yield* FileSystem.FileSystem;361 const path = yield* Path.Path;362 const root = yield* fs.makeTempDirectoryScoped();363 const work = yield* fs.makeTempDirectoryScoped();364365 yield* gitOk(366 root,367 "init",368 "--quiet",369 "--bare",370 "-b",371 "main",372 "demo.git"373 );374 yield* gitOk(work, "init", "--quiet", "-b", "main");375 yield* gitOk(work, "commit", "--quiet", "--allow-empty", "-m", "first");376 yield* gitOk(377 work,378 "push",379 "--quiet",380 path.join(root, "demo.git"),381 "main"382 );383384 const head = yield* gitOk(work, "rev-parse", "HEAD");385 const server = yield* guarded(root);386387 const env = yield* storedIn({388 default: { token: Redacted.make(token), url: server.origin },389 });390391 const bin = yield* path.fromFileUrl(392 new URL("../../src/bin.ts", import.meta.url)393 );394395 const child = yield* spawn(396 "git",397 [398 "-c",399 "credential.helper=",400 "-c",401 `credential.helper=!bun '${bin}' credential`,402 "ls-remote",403 `${server.origin}/demo.git`,404 ],405 {406 cwd: work,407 env: {408 ...env,409 ...pi,410 [`${SLUG}_PROFILE`]: "",411 [`${SLUG}_TOKEN`]: "",412 [`${SLUG}_URL`]: "",413 PI_PROVIDER: "",414 PI_SESSION_ID: "",415 },416 }417 );418419 const [stdout, stderr, exitCode] = yield* Effect.all(420 [421 child.stdout.pipe(Stream.decodeText(), Stream.mkString),422 child.stderr.pipe(Stream.decodeText(), Stream.mkString),423 child.exitCode,424 ],425 { concurrency: "unbounded" }426 );427428 expect({ exitCode, stderr }).toStrictEqual({ exitCode: 0, stderr: "" });429 expect(stdout).toBe(`${head}\tHEAD\n${head}\trefs/heads/main\n`);430 expect(yield* server.seen).toContainEqual({431 password: token,432 user: "audit;harness=pi&model=kimi-k3",433 });434 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),435 30_000436 );437});
added:apps/cli/test/local/login.test.ts+726 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/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */61const home = Effect.gen(function* () {62 const fs = yield* FileSystem.FileSystem;63 const path = yield* Path.Path;64 const dir = yield* fs.makeTempDirectoryScoped();6566 return { GIT_CONFIG_GLOBAL: path.join(dir, ".gitconfig"), HOME: dir };67});6869const credentialsIn = (env: Record<string, string>) =>70 CredentialsFile.pipe(71 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))72 );7374/** The profile `name` as the file holds it: its url, handle and token. */75const stored = (env: Record<string, string>, name: string) =>76 Effect.provide(77 Effect.flatMap(Effect.service(Credentials), ({ current }) => current),78 credentialsIn({ ...env, [`${SLUG}_PROFILE`]: name })79 ).pipe(80 Effect.map(81 Option.map(({ handle, token, url: at }) => ({82 handle,83 token: Redacted.value(token),84 url: at,85 }))86 )87 );8889/** `git config --global <args>` in `env`: its stdout and exit code. */90const gitConfig = (env: Record<string, string>, ...args: string[]) =>91 Effect.scoped(92 Effect.gen(function* () {93 const child = yield* spawn("git", ["config", "--global", ...args], {94 env,95 });9697 const [stdout, exitCode] = yield* Effect.all(98 [99 child.stdout.pipe(Stream.decodeText(), Stream.mkString),100 child.exitCode,101 ],102 { concurrency: "unbounded" }103 ).pipe(Effect.orDie);104105 return { exitCode, stdout };106 })107 );108109const claim = Schema.decodeUnknownSync(ClaimView);110111const isPerson = Schema.is(Person);112113/** One live claim of `handle`'s, as `status` lists it. */114const claimOf = (handle: string) =>115 claim({116 ask: "fix-week",117 base: "a".repeat(40),118 checkCommand: "bun test",119 claimant: handle,120 fork: `datekit--fix-week--${handle}`,121 lapsesAt: "2026-10-09T12:00:00.000Z",122 openedAt: "2026-10-07T12:00:00.000Z",123 project: "datekit",124 remote: `${url}/datekit--fix-week--${handle}.git`,125 state: "live",126 warnsAt: "2026-10-08T12:00:00.000Z",127 });128129/**130 * The platform's side of a call, as `status` sees it: whoever the server131 * side takes the caller for holds one claim.132 */133const statusHandler = Contracts.toLayerHandler("status", () =>134 Effect.map(Effect.service(CurrentPrincipal), (principal) => ({135 answers: [],136 claims: isPerson(principal) ? [claimOf(principal.handle)] : [],137 }))138);139140/** A server side that refuses every credential, as for a revoked token. */141const refusesEveryone = Layer.succeed(Authenticated, () =>142 Effect.fail(new Unauthenticated())143);144145/**146 * The world `login` runs in, faked at its three host seams: the platform's147 * client (an in-process one, whose server side is `server`), the person's148 * browser, and the loopback server (a Node server on an ephemeral port).149 * Each records what `login` asked of it.150 */151const seams = (server: Layer.Layer<Authenticated>) =>152 Effect.gen(function* () {153 const connected = yield* Ref.make<154 readonly { token: string; url: string }[]155 >([]);156157 const opened = yield* Ref.make<readonly string[]>([]);158159 const listened = yield* Ref.make<160 readonly { hostname: string; port: number }[]161 >([]);162163 const layer = Layer.mergeAll(164 Layer.succeed(PlatformClient, {165 connect: ({ token, url: at }) =>166 Effect.andThen(167 Ref.update(connected, (all) => [168 ...all,169 { token: Redacted.value(token), url: at },170 ]),171 RpcTest.makeClient(Contracts).pipe(172 Effect.provide(Layer.mergeAll(unanswered, statusHandler, server))173 )174 ),175 }),176 Layer.succeed(Browser, {177 open: (at) => Ref.update(opened, (all) => [...all, at]),178 }),179 Layer.succeed(Loopback, {180 listen: (address) =>181 Effect.gen(function* () {182 yield* Ref.update(listened, (all) => [...all, address]);183184 const built = yield* Layer.build(NodeHttpServer.layerTest);185186 return Context.get(built, HttpServer.HttpServer);187 }),188 })189 );190191 return {192 connected: Ref.get(connected),193 layer,194 listened: Ref.get(listened),195 opened: Ref.get(opened),196 };197 });198199/** A platform that takes the caller for `handle`. */200const signedInAs = (handle: string) => asPerson(Handle.make(handle));201202/** What the tests themselves run on: a test console, and Node for files, git and servers. */203const testServices = Layer.mergeAll(TestConsole.layer, NodeServices.layer);204205/** A terminal nothing may touch: every use of it dies. */206const noTerminal = Layer.succeed(207 Terminal.Terminal,208 Terminal.make({209 columns: Effect.die("login read the terminal's width"),210 display: () => Effect.die("login wrote to the terminal"),211 readInput: Effect.die("login read the terminal"),212 readLine: Effect.die("login prompted on the terminal"),213 rows: Effect.die("login read the terminal's height"),214 })215);216217interface Run {218 readonly env: Record<string, string>;219 readonly seams: Layer.Layer<never>;220 /** What stdin holds. */221 readonly stdin?: string;222 /** Whether stdout is a terminal, as a person's would be. */223 readonly terminal?: boolean;224}225226/** Runs `argv` as the CLI would, in `run`'s world; how it ended. */227const cli = (argv: readonly string[], run: Run) =>228 Effect.exit(229 program(argv).pipe(230 Effect.provide(231 // The test stdio and terminal come last, so they stand in for Node's.232 Layer.mergeAll(233 Layer.mergeAll(234 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),235 Layer.mock(Client)({}),236 OutputPlain,237 credentialsIn(run.env),238 ConfigProvider.layer(ConfigProvider.fromEnv({ env: run.env })),239 run.seams240 ).pipe(Layer.provideMerge(NodeServices.layer)),241 Stdio.layerTest({242 stdin: Stream.make(new TextEncoder().encode(run.stdin ?? "")),243 stdoutIsTerminal: Effect.succeed(run.terminal ?? false),244 }),245 noTerminal246 )247 )248 )249 );250251/** What was printed, one entry per line however it was written. */252const lines = (all: readonly unknown[]) =>253 all.flatMap((chunk) => String(chunk).split("\n"));254255/** Every line printed so far, on stdout and on stderr. */256const printed = Effect.gen(function* () {257 return {258 stderr: lines(yield* TestConsole.errorLines),259 stdout: lines(yield* TestConsole.logLines),260 };261});262263/** The sign-in URL `login` printed for `origin`, once it has. */264const signInUrl = (origin: string) =>265 Effect.gen(function* () {266 for (let attempt = 0; attempt < 250; attempt += 1) {267 const line = (yield* printed).stderr268 .map((text) => text.trim())269 .find((text) => text.startsWith(`${origin}/authorize?`));270271 if (line !== undefined) {272 return line;273 }274275 yield* Effect.sleep("20 millis");276 }277278 return yield* Effect.die("login printed no sign-in URL");279 });280281/** GET `at` as a browser would, following redirects: the page's status. */282const visit = (at: string) =>283 Effect.gen(function* () {284 const client = yield* HttpClient.HttpClient;285 const response = yield* client.get(at);286287 return response.status;288 }).pipe(Effect.provide(FetchHttpClient.layer));289290/** The query `/authorize` was sent, field by field. */291const fieldsOf = (query: URLSearchParams | undefined) =>292 Object.fromEntries(query?.entries() ?? []);293294describe(`${Brand.cli} login --token-stdin`, () => {295 it.live(296 "checks the token with the platform, keeps it under the profile with the handle, and points git at the helper",297 () =>298 Effect.gen(function* () {299 const env = yield* home;300 const platform = yield* seams(signedInAs("alice"));301302 const exit = yield* cli(303 ["login", "--url", url, "--token-stdin", "--profile", "alice"],304 { env, seams: platform.layer, stdin: `${given}\n` }305 );306307 expect(Exit.isSuccess(exit)).toBeTruthy();308 expect({309 checked: yield* platform.connected,310 kept: yield* stored(env, "alice"),311 }).toStrictEqual({312 checked: [{ token: given, url }],313 kept: Option.some({ handle: "alice", token: given, url }),314 });315 expect({316 helper: yield* gitConfig(317 env,318 "--get-all",319 `credential.${url}.helper`320 ),321 useHttpPath: yield* gitConfig(322 env,323 "--get",324 `credential.${url}.useHttpPath`325 ),326 }).toStrictEqual({327 helper: { exitCode: 0, stdout: `\n${Brand.slug}\n` },328 useHttpPath: { exitCode: 0, stdout: "true\n" },329 });330331 const { stderr, stdout } = yield* printed;332333 expect(stdout.map((line) => line.trim())).toStrictEqual(334 expect.arrayContaining(helperLines(url))335 );336 expect([...stdout, ...stderr].join("\n")).not.toContain(given);337 }).pipe(Effect.scoped, Effect.provide(testServices)),338 30_000339 );340341 it.live(342 "prints one envelope under --json, with the git config and without the token",343 () =>344 Effect.gen(function* () {345 const env = yield* home;346 const platform = yield* seams(signedInAs("alice"));347348 yield* cli(["login", "--url", url, "--token-stdin", "--json"], {349 env,350 seams: platform.layer,351 stdin: `${given}\n`,352 });353354 const { stdout } = yield* printed;355 const text = stdout.join("\n");356357 expect(text).not.toContain(given);358 expect(JSON.parse(text)).toStrictEqual({359 command: "login",360 data: {361 gitConfig: [362 [363 "git",364 "config",365 "--global",366 "--replace-all",367 `credential.${url}.helper`,368 "",369 ],370 [371 "git",372 "config",373 "--global",374 "--add",375 `credential.${url}.helper`,376 Brand.slug,377 ],378 [379 "git",380 "config",381 "--global",382 `credential.${url}.useHttpPath`,383 "true",384 ],385 ],386 handle: "alice",387 profile: "default",388 url,389 },390 ok: true,391 v: 1,392 });393 }).pipe(Effect.scoped, Effect.provide(testServices)),394 30_000395 );396397 it.live(398 "keeps nothing, and leaves git alone, when the platform refuses the token",399 () =>400 Effect.gen(function* () {401 const env = yield* home;402 const platform = yield* seams(refusesEveryone);403404 const exit = yield* cli(["login", "--url", url, "--token-stdin"], {405 env,406 seams: platform.layer,407 stdin: `${given}\n`,408 });409410 expect(Exit.isFailure(exit)).toBeTruthy();411 expect(yield* stored(env, "default")).toStrictEqual(Option.none());412 expect(413 (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))414 .exitCode415 ).toBe(1);416417 const { stderr, stdout } = yield* printed;418419 expect(stderr.join("\n")).toContain(url);420 expect([...stdout, ...stderr].join("\n")).not.toContain(given);421 }).pipe(Effect.scoped, Effect.provide(testServices)),422 30_000423 );424425 it.live(426 "never sends a token over plain http to a host that is not this machine",427 () =>428 Effect.gen(function* () {429 const env = yield* home;430 const platform = yield* seams(signedInAs("alice"));431432 const exit = yield* cli(433 ["login", "--url", "http://platform.test", "--token-stdin"],434 { env, seams: platform.layer, stdin: `${given}\n` }435 );436437 expect(Exit.isFailure(exit)).toBeTruthy();438 expect(yield* platform.connected).toStrictEqual([]);439 expect((yield* printed).stderr.join("\n")).toContain("https://");440 }).pipe(Effect.scoped, Effect.provide(testServices)),441 30_000442 );443444 it.live(445 "with no --url and no stored profile, asks for --url",446 () =>447 Effect.gen(function* () {448 const env = yield* home;449 const platform = yield* seams(signedInAs("alice"));450451 const exit = yield* cli(["login", "--token-stdin"], {452 env,453 seams: platform.layer,454 stdin: `${given}\n`,455 });456457 expect(Exit.isFailure(exit)).toBeTruthy();458 expect((yield* printed).stderr.join("\n")).toContain("--url");459 }).pipe(Effect.scoped, Effect.provide(testServices)),460 30_000461 );462});463464describe(`${Brand.cli} login in the browser (PKCE)`, () => {465 it.live(466 "with --no-browser, prints the sign-in URL; following it signs in and keeps the platform's token",467 () =>468 Effect.gen(function* () {469 const env = yield* home;470 const server = yield* oauthServer({ token: issued });471 const platform = yield* seams(signedInAs("alice"));472473 const fiber = yield* Effect.forkChild(474 cli(475 [476 "login",477 "--url",478 server.origin,479 "--no-browser",480 "--profile",481 "alice",482 ],483 { env, seams: platform.layer }484 )485 );486487 expect(yield* visit(yield* signInUrl(server.origin))).toBe(200);488 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();489490 const [query] = yield* server.authorizations;491 const fields = fieldsOf(query);492 const urlSafe43 = /^[A-Za-z0-9_-]{43}$/u;493494 expect({495 asked: {496 challenge: urlSafe43.test(fields.code_challenge ?? ""),497 clientId: fields.client_id,498 method: fields.code_challenge_method,499 names: Object.keys(fields).toSorted(),500 redirect: /^http:\/\/127\.0\.0\.1:\d+\/callback$/u.test(501 fields.redirect_uri ?? ""502 ),503 responseType: fields.response_type,504 state: urlSafe43.test(fields.state ?? ""),505 },506 checked: yield* platform.connected,507 kept: yield* stored(env, "alice"),508 listened: yield* platform.listened,509 opened: yield* platform.opened,510 }).toStrictEqual({511 asked: {512 challenge: true,513 clientId: `${server.origin}/oauth/cli`,514 method: "S256",515 names: [516 "client_id",517 "code_challenge",518 "code_challenge_method",519 "redirect_uri",520 "response_type",521 "state",522 ],523 redirect: true,524 responseType: "code",525 state: true,526 },527 checked: [{ token: issued, url: server.origin }],528 kept: Option.some({529 handle: "alice",530 token: issued,531 url: server.origin,532 }),533 listened: [{ hostname: "127.0.0.1", port: 0 }],534 opened: [],535 });536537 // The loopback server took its one callback and closed.538 const again = yield* Effect.exit(539 visit(`${fields.redirect_uri}?code=code-1&state=${fields.state}`)540 );541542 const { stderr, stdout } = yield* printed;543544 expect({545 closed: Exit.isFailure(again),546 leaked: [...stdout, ...stderr].join("\n").includes(issued),547 }).toStrictEqual({ closed: true, leaked: false });548 }).pipe(Effect.scoped, Effect.provide(testServices)),549 30_000550 );551552 it.live(553 "refuses a sign-in that comes back with another state, and keeps nothing",554 () =>555 Effect.gen(function* () {556 const env = yield* home;557 const server = yield* oauthServer({ state: "other", token: issued });558 const platform = yield* seams(signedInAs("alice"));559560 const fiber = yield* Effect.forkChild(561 cli(["login", "--url", server.origin, "--no-browser"], {562 env,563 seams: platform.layer,564 })565 );566567 yield* visit(yield* signInUrl(server.origin));568569 expect(Exit.isFailure(yield* Fiber.join(fiber))).toBeTruthy();570 expect((yield* printed).stderr.join("\n")).toContain("state");571 expect(yield* platform.connected).toStrictEqual([]);572 expect(yield* stored(env, "default")).toStrictEqual(Option.none());573 }).pipe(Effect.scoped, Effect.provide(testServices)),574 30_000575 );576577 it.live(578 "at a person's terminal, opens the browser on the sign-in URL",579 () =>580 Effect.gen(function* () {581 const env = yield* home;582 const server = yield* oauthServer({ token: issued });583 const platform = yield* seams(signedInAs("alice"));584585 const fiber = yield* Effect.forkChild(586 cli(["login", "--url", server.origin], {587 env,588 seams: platform.layer,589 terminal: true,590 })591 );592593 const shown = yield* signInUrl(server.origin);594595 expect(yield* platform.opened).toStrictEqual([shown]);596 expect(yield* visit(shown)).toBe(200);597 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();598 }).pipe(Effect.scoped, Effect.provide(testServices)),599 30_000600 );601602 it.live(603 "under an agent, prints the URL for a person instead of opening a browser, and never prompts",604 () =>605 Effect.gen(function* () {606 const env = { ...(yield* home), CLAUDECODE: "1" };607 const server = yield* oauthServer({ token: issued });608 const platform = yield* seams(signedInAs("alice"));609610 const fiber = yield* Effect.forkChild(611 cli(["login", "--url", server.origin], {612 env,613 seams: platform.layer,614 terminal: true,615 })616 );617618 expect(yield* visit(yield* signInUrl(server.origin))).toBe(200);619 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();620 expect(yield* platform.opened).toStrictEqual([]);621 }).pipe(Effect.scoped, Effect.provide(testServices)),622 30_000623 );624625 it.live(626 "stops waiting after 5 minutes, says how to sign in instead, and closes the loopback server",627 () =>628 Effect.gen(function* () {629 const env = yield* home;630 const server = yield* oauthServer({ token: issued });631 const platform = yield* seams(signedInAs("alice"));632 const clock = yield* TestClock.make();633634 const fiber = yield* Effect.forkChild(635 cli(["login", "--url", server.origin, "--no-browser"], {636 env,637 seams: platform.layer,638 }).pipe(Effect.provideService(Clock.Clock, clock))639 );640641 const shown = yield* signInUrl(server.origin);642643 yield* clock.adjust("5 minutes");644645 expect(Exit.isFailure(yield* Fiber.join(fiber))).toBeTruthy();646647 const said = (yield* printed).stderr.join("\n");648649 expect(said).toContain("5 minutes");650 expect(said).toContain("--token-stdin");651 expect(yield* stored(env, "default")).toStrictEqual(Option.none());652653 const callback = new URL(shown).searchParams.get("redirect_uri") ?? "";654655 expect(656 Exit.isFailure(657 yield* Effect.exit(visit(`${callback}?code=x&state=y`))658 )659 ).toBeTruthy();660 }).pipe(Effect.scoped, Effect.provide(testServices)),661 30_000662 );663});664665describe(`${Brand.cli} logout`, () => {666 it.live(667 "removes the profile and the git config that names the helper for its platform",668 () =>669 Effect.gen(function* () {670 const env = yield* home;671 const platform = yield* seams(signedInAs("alice"));672 const run = { env, seams: platform.layer, stdin: `${given}\n` };673674 yield* cli(675 ["login", "--url", url, "--token-stdin", "--profile", "alice"],676 run677 );678679 const exit = yield* cli(["logout", "--profile", "alice"], run);680681 expect(Exit.isSuccess(exit)).toBeTruthy();682 expect(yield* stored(env, "alice")).toStrictEqual(Option.none());683 expect(684 (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))685 .exitCode686 ).toBe(1);687 expect(688 (yield* gitConfig(env, "--get", `credential.${url}.useHttpPath`))689 .exitCode690 ).toBe(1);691 }).pipe(Effect.scoped, Effect.provide(testServices)),692 30_000693 );694695 it.live(696 "keeps git asking the helper while another profile is on the same platform",697 () =>698 Effect.gen(function* () {699 const env = yield* home;700 const platform = yield* seams(signedInAs("alice"));701 const run = { env, seams: platform.layer, stdin: `${given}\n` };702703 for (const name of ["alice", "bob"]) {704 yield* cli(705 ["login", "--url", url, "--token-stdin", "--profile", name],706 run707 );708 }709710 yield* cli(["logout", "--profile", "alice"], run);711712 expect(713 yield* gitConfig(env, "--get-all", `credential.${url}.helper`)714 ).toStrictEqual({ exitCode: 0, stdout: `\n${Brand.slug}\n` });715 expect(Option.isSome(yield* stored(env, "bob"))).toBeTruthy();716717 yield* cli(["logout", "--profile", "bob"], run);718719 expect(720 (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))721 .exitCode722 ).toBe(1);723 }).pipe(Effect.scoped, Effect.provide(testServices)),724 30_000725 );726});
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: ["check"], issue: "405" },100 { args: ["why"], issue: "414" },101 { args: ["env", "set"], issue: "414" },
19 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 });