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.
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
Provenance
- Commit
150cedd- Tree
7cf0a68- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
650cb35
6 files changed+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+ */14+import { BunHttpServer } from "@effect/platform-bun";15+import { Brand } from "@repo/brand";16+import { detectHarness } from "@repo/protocol/audit";17+import { Contracts } from "@repo/protocol/contracts";18+import type { Client } from "@repo/protocol/contracts";19+import {20+ Deferred,21+ Context,22+ Effect,23+ Layer,24+ Option,25+ Redacted,26+ Schema,27+ Stdio,28+ Stream,29+} from "effect";1-import { Effect } from "effect";2-import { Command } from "effect/cli";30+import type { Scope } from "effect";31+import { Command, Flag } from "effect/cli";32+import {33+ FetchHttpClient,34+ HttpClient,35+ HttpClientRequest,36+ HttpServerRequest,37+ HttpServerResponse,38+} from "effect/http";39+import type { HttpServer, HttpServerError } from "effect/http";40+import { ChildProcess, ChildProcessSpawner } from "effect/process";41+import { RpcClient, RpcSerialization } from "effect/rpc";42 4-/** `login`: issue 412 replaces this stub (PKCE, or `--token-stdin`). */5-export const login = Command.make("login", {}, () =>6- Effect.die("not built: issue 412")43+import { currentEnv } from "../credential-helper.ts";44+import { Credentials, gitHelperConfig } from "../credentials.ts";45+import type { Profile } from "../credentials.ts";46+import { Output } from "../output.ts";47+48+/** The env names the CLI reads, spelled from the brand: `<SLUG>_URL`. */49+const SLUG = Brand.slug.toUpperCase();50+51+/** The address the loopback server binds: this machine only. */52+const LOOPBACK = "127.0.0.1";53+54+/** How long `login` waits for the browser to come back. */55+const SIGN_IN_WAIT = "5 minutes";56+57+/**58+ * The CLI's OAuth client id on a platform: the URL of the Client ID59+ * Metadata Document the platform serves for it (W3 316,60+ * `apps/platform/src/auth/cli-client.ts`). It asks for no scope.61+ */62+const clientIdOf = (origin: string) => `${origin}/oauth/cli`;63+64+// --- The host seams: each has a default the binary runs on, and tests swap it.65+66+/**67+ * Where `login` hears the browser come back: an HTTP server on one address,68+ * for one scope. The binary listens with Bun.69+ */70+export const Loopback = Context.Reference<{71+ readonly listen: (address: {72+ readonly hostname: string;73+ readonly port: number;74+ }) => Effect.Effect<75+ HttpServer.HttpServer["Service"],76+ HttpServerError.ServeError,77+ Scope.Scope78+ >;79+}>("cli/login/Loopback", {80+ defaultValue: () => ({81+ listen: ({ hostname, port }) => BunHttpServer.make({ hostname, port }),82+ }),83+});84+85+/**86+ * A client of the platform at `url` that presents `token` as its bearer:87+ * what `login` checks a token with before it keeps it. The binary's calls88+ * go over HTTP to `<url>/rpc`.89+ */90+export const PlatformClient = Context.Reference<{91+ readonly connect: (profile: {92+ readonly token: Redacted.Redacted;93+ readonly url: string;94+ }) => Effect.Effect<Client["Service"], never, Scope.Scope>;95+}>("cli/login/PlatformClient", {96+ defaultValue: () => ({97+ connect: ({ token, url }) =>98+ RpcClient.make(Contracts).pipe(99+ Effect.provide(100+ RpcClient.layerProtocolHttp({101+ transformClient: HttpClient.mapRequest(102+ HttpClientRequest.bearerToken(token)103+ ),104+ url: `${url}/rpc`,105+ }).pipe(106+ Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])107+ )108+ )109+ ),110+ }),111+});112+113+/** Opens `url` with the first of `commands` that runs; none running is fine. */114+const openWith = (url: string, commands: readonly string[]) =>115+ Effect.gen(function* () {116+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;117+118+ for (const command of commands) {119+ const code = yield* spawner120+ .exitCode(121+ ChildProcess.make(command, [url], {122+ stderr: "ignore",123+ stdin: "ignore",124+ stdout: "ignore",125+ })126+ )127+ .pipe(Effect.timeout("10 seconds"), Effect.option);128+129+ if (Option.exists(code, (exit) => exit === 0)) {130+ return;131+ }132+ }133+ });134+135+/**136+ * The person's browser. The binary asks the desktop's opener (`xdg-open`,137+ * else macOS's `open`); the URL is printed either way.138+ */139+export const Browser = Context.Reference<{140+ readonly open: (141+ url: string142+ ) => Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner>;143+}>("cli/login/Browser", {144+ defaultValue: () => ({145+ open: (url) => openWith(url, ["xdg-open", "open"]),146+ }),147+});148+149+// --- Failures.150+151+/** `login` was run in a way that cannot work; the message says what to run. */152+export class LoginUsage extends Schema.TaggedError<LoginUsage>()("LoginUsage", {153+ reason: Schema.String,154+}) {155+ override get message() {156+ return this.reason;157+ }158+}159+160+/** The platform, or the sign-in, said no; nothing was stored. */161+export class LoginRefused extends Schema.TaggedError<LoginRefused>()(162+ "LoginRefused",163+ { reason: Schema.String }164+) {165+ override get message() {166+ return this.reason;167+ }168+}169+170+/** git would not take a config line; the message names it, to run by hand. */171+export class GitConfigFailed extends Schema.TaggedError<GitConfigFailed>()(172+ "GitConfigFailed",173+ { command: Schema.String }174+) {175+ override get message() {176+ return `git did not take this; run it yourself: ${this.command}`;177+ }178+}179+180+// --- Shared parts.181+182+const flags = {183+ json: Flag.Boolean("json").pipe(184+ Flag.withDefault(false),185+ Flag.withDescription("Print machine-readable JSON")186+ ),187+ profile: Flag.String("profile").pipe(188+ Flag.withDescription(189+ `The profile to use (default: $${SLUG}_PROFILE, else "default")`190+ ),191+ Flag.optional192+ ),193+};194+195+/** The profile a command acts on: the flag, else `<SLUG>_PROFILE`, else `default`. */196+const profileName = (197+ flag: Option.Option<string>,198+ env: Readonly<Record<string, string>>199+) => Option.getOrElse(flag, () => env[`${SLUG}_PROFILE`] ?? "default");200+201+/** An argv list as a person would type it in a shell. */202+const typed = (argv: readonly string[]) =>203+ argv204+ .map((arg) => {205+ if (arg === "") {206+ return '""';207+ }208+209+ return /^[\w./:@=-]+$/u.test(arg) ? arg : `'${arg}'`;210+ })211+ .join(" ");212+213+/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */214+const 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;222+223+ 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);234+235+ return Option.exists(code, (exit) => allowed.includes(exit))236+ ? undefined237+ : yield* new GitConfigFailed({ command: typed(argv) });238+ });239+240+const asUrl = Option.liftThrowable((text: string) => new URL(text));241+242+/** Hosts that are this machine, where plain http keeps a token local. */243+const THIS_MACHINE = new Set(["localhost", "127.0.0.1", "[::1]"]);244+245+/** `given`'s origin, if it is a platform url: https, or http on this machine. */246+const 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+ );264+265+/** The platform to log in to: `--url`, else `<SLUG>_URL`, else the profile's own. */266+const 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+ );274+275+ if (Option.isSome(named)) {276+ return yield* originOf(named.value);277+ }278+279+ const current = yield* (yield* Credentials).current;280+281+ if (Option.isSome(current)) {282+ return yield* originOf(current.value.url);283+ }284+285+ return yield* new LoginUsage({286+ reason: `no platform to log in to: run ${Brand.cli} login --url https://<platform host>`,287+ });288+ });289+290+// --- The token, by one of two ways.291+292+/** The token piped to `--token-stdin`: its first line, read no further. */293+const tokenFromStdin = Effect.gen(function* () {294+ const { stdin } = yield* Stdio.Stdio;295+296+ const [line = ""] = yield* stdin.pipe(297+ Stream.decodeText(),298+ Stream.splitLines,299+ Stream.take(1),300+ Stream.runCollect,301+ Effect.orElseSucceed((): readonly string[] => [])302+ );303+304+ const token = line.trim();305+306+ 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+ }311+312+ return Redacted.make(token);313+});314+315+const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);316+317+/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */318+const randomText = (size: number) =>319+ Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(320+ Effect.flatMap(encodeBase64Url),321+ Effect.orDie322+ );323+324+/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */325+const 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+ );332+333+/**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+ */338+const 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>();342+343+ yield* server.serve(344+ Effect.gen(function* () {345+ const request = yield* HttpServerRequest.HttpServerRequest;346+ const at = new URL(request.url, `http://${LOOPBACK}`);347+348+ if (request.method !== "GET" || at.pathname !== "/callback") {349+ return HttpServerResponse.text("Not found.", { status: 404 });350+ }351+352+ const first = yield* Deferred.succeed(returned, at.searchParams);353+354+ 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+ );366+367+ if (!("port" in server.address)) {368+ return yield* Effect.die("the loopback server listens on a socket");369+ }370+371+ return {372+ redirectUri: `http://${LOOPBACK}:${server.address.port}/callback`,373+ returned: Deferred.await(returned),374+ };375+});376+377+/** What `/token` answers a good code with. */378+const TokenResponse = Schema.Struct({379+ access_token: Schema.RedactedFromValue(Schema.NonEmptyString),380+ token_type: Schema.String,381+});382+383+const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);384+385+/** Trades the code for an access token at `<url>/token`, showing the verifier. */386+const 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+ });395+396+ return Effect.gen(function* () {397+ const client = yield* HttpClient.HttpClient;398+399+ 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+ );411+412+ if (response.status !== 200) {413+ return yield* refused;414+ }415+416+ const body = yield* decodeTokenResponse(yield* response.json);417+418+ if (body.token_type.toLowerCase() !== "bearer") {419+ return yield* refused;420+ }421+422+ return body.access_token;423+ }).pipe(424+ Effect.provide(FetchHttpClient.layer),425+ Effect.mapError(() => refused)426+ );427+};428+429+/**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+ */435+const 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;442+443+ const authorize = new URL("/authorize", url);444+445+ 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();453+454+ 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+ );460+461+ if (opens) {462+ yield* (yield* Browser).open(authorize.href);463+ }464+465+ 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+ );477+478+ 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+ }483+484+ const code = query.get("code");485+486+ 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+ }491+492+ return yield* exchange({ code, redirectUri, url, verifier });493+ })494+ );495+496+/** The handle `status` shows: the claimant of the caller's claims, if any. */497+const handleOf = (status: {498+ readonly claims: readonly { readonly claimant: Profile["handle"] }[];499+}) => Option.fromNullishOr(status.claims[0]?.claimant);500+501+/** Asks the platform at `url` who `token` is; a refusal or no answer stores nothing. */502+const verify = (url: string, token: Redacted.Redacted) =>503+ Effect.scoped(504+ Effect.gen(function* () {505+ const client = yield* (yield* PlatformClient).connect({ token, url });506+507+ 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+ );517+518+/** Whether `login` may open a browser: only for a person at a terminal. */519+const mayOpenBrowser = (env: Readonly<Record<string, string>>) =>520+ Effect.gen(function* () {521+ const { mode } = yield* Output;522+ const { stdoutIsTerminal } = yield* Stdio.Stdio;523+524+ return (525+ mode === "human" &&526+ detectHarness(env).harness === undefined &&527+ env.CI === undefined &&528+ (yield* stdoutIsTerminal)529+ );530+ });531+532+/** The lines of a view: a sentence, then each command on its own line. */533+const viewOf = (said: string, commands: readonly (readonly string[])[]) => {534+ const lines = commands.map((argv) => typed(argv));535+536+ 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+};544+545+export 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);579+580+ const token = given.tokenStdin581+ ? yield* tokenFromStdin582+ : yield* tokenFromBrowser(583+ url,584+ !given.noBrowser && (yield* mayOpenBrowser(env))585+ );586+587+ const handle = yield* verify(url, token);588+589+ yield* credentials.put(590+ name,591+ Option.match(handle, {592+ onNone: (): Profile => ({ token, url }),593+ onSome: (who): Profile => ({ handle: who, token, url }),594+ })595+ );596+597+ const commands = gitHelperConfig(url);598+599+ if (!given.noGitConfig) {600+ for (const argv of commands) {601+ yield* runGit(argv, env);602+ }603+ }604+605+ const who = Option.match(handle, {606+ onNone: () => "",607+ onSome: (known) => ` as ${known}`,608+ });609+610+ 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 );635 13-/** `logout`: issue 412 replaces this stub. */14-export const logout = Command.make("logout", {}, () =>15- Effect.die("not built: issue 412")16-).pipe(Command.withDescription("Forget a platform's stored token."));636+/** The `git config --global` lines that undo `gitHelperConfig(url)`; exit 5 means already gone. */637+const gitHelperUnset = (url: string): readonly (readonly string[])[] => [638+ ["git", "config", "--global", "--unset-all", `credential.${url}.helper`],639+ ["git", "config", "--global", "--unset", `credential.${url}.useHttpPath`],640+];641+642+const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;643+644+/** The urls whose git config names this CLI's helper. */645+const helperUrls = (env: Readonly<Record<string, string>>) =>646+ Effect.gen(function* () {647+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;648+649+ 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[] => []));663+664+ 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;669+670+ return value === Brand.slug && url !== undefined ? [url] : [];671+ });672+673+ return [...new Set(urls)];674+ });675+676+export 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);683+684+ // git keeps asking the helper for a platform another profile is still on.685+ const unused: string[] = [];686+687+ for (const url of yield* helperUrls(env)) {688+ const host = Option.map(asUrl(url), ({ host: at }) => at);689+690+ if (691+ Option.isSome(host) &&692+ Option.isNone(yield* credentials.forHost(host.value))693+ ) {694+ unused.push(url);695+ }696+ }697+698+ const commands = unused.flatMap(gitHelperUnset);699+700+ for (const argv of commands) {701+ yield* runGit(argv, env, [0, 5]);702+ }703+704+ 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
12345678910111213141516171819202112222324456252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228/** * git's credential helper: `git-credential-<slug>`, which `login` names in * git's config for the platform's url (`gitHelperConfig`). git asks it for a * password after a 401 that names Basic; it answers from the stored profile * for that host, and never prompts, opens a terminal, or reads past the * blank line that ends git's request. * * The username it hands back carries the harness behind the push as audit * metadata (`@repo/protocol/audit`), never identity: the token in the * password slot is the only identity the platform reads. */import { Brand } from "@repo/brand";import { auditUser, detectHarness } from "@repo/protocol/audit";import { ConfigProvider, Effect, Match, Option, Redacted, Stdio, Stream,import { Effect } from "effect";import { Command } from "effect/cli";} from "effect";import { Argument, Command } from "effect/cli";
/** `credential <get|store|erase>`, git's credential helper: issue 412 replaces this stub. */export const credential = Command.make("credential", {}, () => Effect.die("not built: issue 412")import { Credentials } from "./credentials.ts";import { Output } from "./output.ts";
/** What git asks a helper to do. */export type Operation = "get" | "store" | "erase";
const operations = [ "get", "store", "erase",] as const satisfies readonly Operation[];
/** The env, by name: what `detectHarness` reads. */export type Env = Readonly<Record<string, string | undefined>>;
/** The env-name parts below `path` and their values, from the CLI's config provider. */const namesBelow = ( provider: ConfigProvider.ConfigProvider, path: ConfigProvider.Path): Effect.Effect<readonly (readonly [string, string])[]> => provider.load(path).pipe( Effect.map(Option.fromNullishOr), Effect.orElseSucceed(() => Option.none<ConfigProvider.Node>()), Effect.flatMap( Option.match({ onNone: () => Effect.succeed([]), onSome: (node) => { const own = path.length > 0 && node.value !== undefined ? [[path.join("_"), node.value] as const] : [];
const children = Match.valueTags(node, { Array: ({ length }) => Array.from({ length }, (_, at) => String(at)), Record: ({ keys }) => [...keys], Value: () => [], });
return Effect.map( Effect.forEach(children, (child) => namesBelow(provider, [...path, child]) ), (nested) => [...own, ...nested.flat()] ); }, }) ) );
/** * The env as the CLI sees it, every name with its value: read through the * config provider (the process env when nothing else is given), so a test's * env is the one a command sees and passes on. */export const currentEnv: Effect.Effect<Readonly<Record<string, string>>> = Effect.gen(function* () { const provider = yield* ConfigProvider.ConfigProvider;
return Object.fromEntries(yield* namesBelow(provider, [])); });
/** git's request: its `key=value` lines, up to the blank line that ends it. */const requestOf = (input: string) => { const fields = new Map<string, string>();
for (const line of input.split("\n")) { if (line === "") { break; }
const equals = line.indexOf("=");
if (equals > 0) { fields.set(line.slice(0, equals), line.slice(equals + 1)); } }
return fields;};
/** `url`'s scheme without its colon, if it is a URL. */const schemeOf = Option.liftThrowable((url: string) => new URL(url).protocol.replace(/:$/u, ""));
/** A value git's credential protocol can carry: one line, no NUL. */const fitsOneLine = (value: string) => !/[\n\r\0]/u.test(value);
/** What the helper prints: for git on stdout, and maybe a line for a person on stderr. */interface Answer { readonly stdout: string; readonly note: Option.Option<string>;}
const silent: Answer = { note: Option.none(), stdout: "" };
/** * The helper's answer to `op` with git's `input`. `get` answers only for a * host a profile is on, over that profile's scheme; with no login at all it * also says, once, how to log in. `store` and `erase` do nothing: the stored * token changes only through `login` and `logout`. */const answer = (op: Operation, input: string, env: Env) => Effect.gen(function* () { if (op !== "get") { return silent; }
const request = requestOf(input); const host = request.get("host"); const protocol = request.get("protocol");
if (host === undefined || protocol === undefined) { return silent; }
const credentials = yield* Credentials;
const profile = Option.filter( yield* credentials.forHost(host), ({ token, url }) => Option.contains(schemeOf(url), protocol) && fitsOneLine(Redacted.value(token)) );
if (Option.isSome(profile)) { return { note: Option.none(), stdout: `username=${auditUser(detectHarness(env))}\npassword=${Redacted.value(profile.value.token)}\n`, } satisfies Answer; }
return Option.isNone(yield* credentials.current) ? { note: Option.some( `no ${Brand.cli} login for ${host}: run ${Brand.cli} login --url ${protocol}://${host}` ), stdout: "", } : silent; });
/** * What the helper prints on stdout for `op`, given git's `input` and the * env it runs in: `username=<audit>\npassword=<token>\n`, or nothing. */export const credentialHelper = ( op: Operation, input: string, env: Env): Effect.Effect<string, never, Credentials> => Effect.map(answer(op, input, env), ({ stdout }) => stdout);
/** * git's request from stdin: the lines up to the first blank one, read no * further, or up to the end if git closes stdin first. */const readRequest = Effect.gen(function* () { const { stdin } = yield* Stdio.Stdio;
const lines = yield* stdin.pipe( Stream.decodeText(), Stream.splitLines, Stream.takeWhile((line) => line !== ""), Stream.runCollect, Effect.orElseSucceed((): readonly string[] => []) );
return `${lines.join("\n")}\n\n`;});
/** `<cli> credential <get|store|erase>`: what `git-credential-<slug>` runs. */export const credential = Command.make( "credential", { operation: Argument.Literals("operation", operations).pipe( Argument.withDescription("What git asks: get, store or erase") ), }, ({ operation }) => Effect.gen(function* () { const stdio = yield* Stdio.Stdio; const output = yield* Output; const request = yield* readRequest; const given = yield* answer(operation, request, yield* currentEnv);
if (given.stdout !== "") { yield* Stream.make(given.stdout).pipe( Stream.run(stdio.stdout()), Effect.orDie ); }
yield* Option.match(given.note, { onNone: () => Effect.void, onSome: output.note, }); })).pipe( Command.withDescription( "Be git's credential helper: hand git the stored token for a platform." ));added:apps/cli/test/local/credential-helper.test.ts+437 added
1+import { NodeHttpServer, NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client } from "@repo/protocol/contracts";5+import { gitOk, spawn } from "@repo/testkit/git";6+import { httpBackend } from "@repo/testkit/http-backend";7+import {8+ ConfigProvider,9+ Context,10+ Effect,11+ Exit,12+ FileSystem,13+ Layer,14+ Option,15+ Path,16+ Predicate,17+ Queue,18+ Redacted,19+ Ref,20+ Schema,21+ Sink,22+ Stdio,23+ Stream,24+ Terminal,25+} from "effect";26+import type { Cause } from "effect";27+import { CliOutput } from "effect/cli";28+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";29+import type { ChildProcessSpawner } from "effect/process";30+import { TestConsole } from "effect/testing";31+32+import { credentialHelper } from "../../src/credential-helper.ts";33+import { Credentials, CredentialsFile } from "../../src/credentials.ts";34+import type { Profile } from "../../src/credentials.ts";35+import { program } from "../../src/main.ts";36+import { OutputPlain } from "../../src/output.ts";37+38+/** The env names the CLI reads, spelled from the brand. */39+const SLUG = Brand.slug.toUpperCase();40+41+const token = "t0ken-0123456789abcdefghijklmnopqrstuvwxyz";42+43+const platform: Profile = {44+ token: Redacted.make(token),45+ url: "https://platform.test",46+};47+48+/** What git writes to its helper for a repo on `host`, blank line and all. */49+const asked = (host: string, protocol = "https") =>50+ `protocol=${protocol}\nhost=${host}\npath=datekit--fix-week--alice.git\n\n`;51+52+/** A pi session's env, as pi hands it to the git it runs. */53+const pi = { AI_AGENT: "pi", PI_MODEL: "kimi-k3" };54+55+const encoder = new TextEncoder();56+57+const decoder = new TextDecoder();58+59+/** The credentials file in the config dir `env` names. */60+const credentialsIn = (env: Record<string, string>) =>61+ CredentialsFile.pipe(62+ Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))63+ );64+65+/**66+ * A fresh config dir holding `profiles`, and the env that names it: the67+ * shell a person who ran `login` would give git.68+ */69+const storedIn = (profiles: Readonly<Record<string, Profile>>) =>70+ Effect.gen(function* () {71+ const fs = yield* FileSystem.FileSystem;72+ const dir = yield* fs.makeTempDirectoryScoped();73+ const env = { HOME: "/nonexistent", XDG_CONFIG_HOME: dir };74+75+ const credentials = yield* Effect.provide(76+ Effect.service(Credentials),77+ credentialsIn(env)78+ );79+80+ for (const [name, profile] of Object.entries(profiles)) {81+ yield* credentials.put(name, profile);82+ }83+84+ return env;85+ });86+87+/** A terminal that no helper may touch: every use of it dies. */88+const noTerminal = Layer.succeed(89+ Terminal.Terminal,90+ Terminal.make({91+ columns: Effect.die("the helper read the terminal's width"),92+ display: () => Effect.die("the helper wrote to the terminal"),93+ readInput: Effect.die("the helper read the terminal"),94+ readLine: Effect.die("the helper prompted on the terminal"),95+ rows: Effect.die("the helper read the terminal's height"),96+ })97+);98+99+/**100+ * Runs `<cli> credential <op>` as git runs its helper: `stdin` in, with101+ * `env`. What it wrote to stdout and stderr, and whether it succeeded.102+ */103+const helper = (104+ op: string,105+ stdin: Stream.Stream<Uint8Array>,106+ env: Record<string, string>107+) =>108+ Effect.gen(function* () {109+ const written = yield* Queue.unbounded<string | Uint8Array, Cause.Done>();110+111+ const stdio = Stdio.layerTest({112+ stdin,113+ stdout: () => Sink.fromQueue(written),114+ });115+116+ const exit = yield* Effect.exit(117+ program(["credential", op]).pipe(118+ Effect.provide(119+ // The test stdio and terminal come last, so they stand in for Node's.120+ Layer.mergeAll(121+ Layer.mergeAll(122+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),123+ Layer.mock(Client)({}),124+ OutputPlain,125+ credentialsIn(env),126+ ConfigProvider.layer(ConfigProvider.fromEnv({ env }))127+ ).pipe(Layer.provideMerge(NodeServices.layer)),128+ stdio,129+ noTerminal130+ )131+ )132+ )133+ );134+135+ const stderr = (yield* TestConsole.errorLines).map(String);136+137+ const stdout = (yield* Queue.clear(written))138+ .map((chunk) =>139+ Predicate.isString(chunk) ? chunk : decoder.decode(chunk)140+ )141+ .join("");142+143+ return { ok: Exit.isSuccess(exit), stderr, stdout };144+ }).pipe(Effect.provide(TestConsole.layer));145+146+/** `text` as stdin that ends after it. */147+const input = (text: string) => Stream.make(encoder.encode(text));148+149+describe(`${Brand.cli} credential, git's credential helper`, () => {150+ it.live(151+ "hands git the stored token for the platform's host, with the harness as audit metadata in the username",152+ () =>153+ Effect.gen(function* () {154+ const env = yield* storedIn({ default: platform });155+156+ const ran = yield* helper("get", input(asked("platform.test")), {157+ ...env,158+ ...pi,159+ });160+161+ expect(ran).toStrictEqual({162+ ok: true,163+ stderr: [],164+ stdout: `username=audit;harness=pi&model=kimi-k3\npassword=${token}\n`,165+ });166+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))167+ );168+169+ it.live("says nothing for another host, so git asks its next helper", () =>170+ Effect.gen(function* () {171+ const env = yield* storedIn({ default: platform });172+173+ const ran = yield* helper("get", input(asked("github.com")), {174+ ...env,175+ ...pi,176+ });177+178+ expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });179+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))180+ );181+182+ it.live("never hands the token to the platform's host over plain http", () =>183+ Effect.gen(function* () {184+ const env = yield* storedIn({ default: platform });185+186+ const ran = yield* helper(187+ "get",188+ input(asked("platform.test", "http")),189+ env190+ );191+192+ expect(ran.ok).toBeTruthy();193+ expect(ran.stdout).toBe("");194+ expect(ran.stderr.join("\n")).not.toContain(token);195+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))196+ );197+198+ it.live(199+ "with no login, says nothing to git and one line to the person naming login",200+ () =>201+ Effect.gen(function* () {202+ const env = yield* storedIn({});203+204+ const ran = yield* helper("get", input(asked("platform.test")), env);205+206+ expect(ran.ok).toBeTruthy();207+ expect(ran.stdout).toBe("");208+ expect(ran.stderr).toHaveLength(1);209+ expect(ran.stderr[0]).toContain(`${Brand.cli} login`);210+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))211+ );212+213+ it.live.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 });218+219+ const ran = yield* helper(220+ op,221+ input(`${asked("platform.test")}username=x\npassword=${token}\n\n`),222+ env223+ );224+225+ expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });226+227+ const kept = yield* Effect.provide(228+ Effect.flatMap(229+ Effect.service(Credentials),230+ (stored) => stored.current231+ ),232+ credentialsIn(env)233+ );234+235+ expect(236+ Option.map(kept, (profile) => Redacted.value(profile.token))237+ ).toStrictEqual(Option.some(token));238+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))239+ );240+241+ 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 });246+247+ const endless = Stream.concat(248+ input(asked("platform.test")),249+ Stream.never250+ );251+252+ const pastTheEnd = Stream.concat(253+ input(asked("platform.test")),254+ Stream.die("the helper read past the blank line")255+ );256+257+ for (const stdin of [endless, pastTheEnd]) {258+ const ran = yield* helper("get", stdin, env);259+260+ expect(ran.stdout).toBe(`username=audit;\npassword=${token}\n`);261+ }262+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))263+ );264+});265+266+describe(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+ });278+279+ const stdout = yield* credentialHelper(280+ "get",281+ asked("platform.test"),282+ {}283+ ).pipe(Effect.provide(credentialsIn(env)));284+285+ expect(stdout).toBe(`username=audit;\npassword=${token}\n`);286+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))287+ );288+});289+290+const Basic = /^Basic (?<encoded>\S+)$/u;291+292+const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);293+294+/**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+ */299+const guarded = (root: string) =>300+ Effect.gen(function* () {301+ const spawner =302+ yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();303+304+ const seen = yield* Ref.make<readonly { user: string; password: string }[]>(305+ []306+ );307+308+ const backend = httpBackend(root);309+310+ const app = Effect.gen(function* () {311+ const request = yield* HttpServerRequest.toWeb(312+ yield* HttpServerRequest.HttpServerRequest313+ );314+315+ const pair = Option.fromNullishOr(316+ Basic.exec(request.headers.get("authorization") ?? "")?.groups?.encoded317+ ).pipe(Option.flatMap(fromBase64));318+319+ if (Option.isNone(pair)) {320+ return HttpServerResponse.text("sign in", {321+ headers: { "www-authenticate": 'Basic realm="test"' },322+ status: 401,323+ });324+ }325+326+ const colon = pair.value.indexOf(":");327+328+ yield* Ref.update(seen, (all) => [329+ ...all,330+ {331+ password: pair.value.slice(colon + 1),332+ user: pair.value.slice(0, colon),333+ },334+ ]);335+336+ return HttpServerResponse.fromWeb(337+ yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))338+ );339+ }).pipe(Effect.orDie);340+341+ const server = yield* Layer.build(342+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))343+ ).pipe(Effect.orDie);344+345+ const { address } = Context.get(server, HttpServer.HttpServer);346+347+ 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");351+352+ return { origin, seen: Ref.get(seen) };353+ });354+355+describe("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();364+365+ 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+ );383+384+ const head = yield* gitOk(work, "rev-parse", "HEAD");385+ const server = yield* guarded(root);386+387+ const env = yield* storedIn({388+ default: { token: Redacted.make(token), url: server.origin },389+ });390+391+ const bin = yield* path.fromFileUrl(392+ new URL("../../src/bin.ts", import.meta.url)393+ );394+395+ 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+ );418+419+ 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+ );427+428+ 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
1+import { NodeHttpServer, NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client, Contracts } from "@repo/protocol/contracts";5+import { ClaimView } from "@repo/protocol/domain/claim";6+import { Handle } from "@repo/protocol/ids";7+import {8+ Authenticated,9+ CurrentPrincipal,10+ Person,11+ Unauthenticated,12+} from "@repo/protocol/principal";13+import { asPerson, unanswered } from "@repo/protocol/testing";14+import { spawn } from "@repo/testkit/git";15+import {16+ Clock,17+ ConfigProvider,18+ Context,19+ Effect,20+ Exit,21+ Fiber,22+ FileSystem,23+ Layer,24+ Option,25+ Path,26+ Redacted,27+ Ref,28+ Schema,29+ Stdio,30+ Stream,31+ Terminal,32+} from "effect";33+import { CliOutput } from "effect/cli";34+import { FetchHttpClient, HttpClient, HttpServer } from "effect/http";35+import { RpcTest } from "effect/rpc";36+import { TestClock, TestConsole } from "effect/testing";37+38+import { Credentials, CredentialsFile } from "../../src/credentials.ts";39+import { Browser, Loopback, PlatformClient } from "../../src/local/login.ts";40+import { program } from "../../src/main.ts";41+import { OutputPlain } from "../../src/output.ts";42+import { oauthServer } from "../oauth-server.ts";43+44+/** The env names the CLI reads, spelled from the brand. */45+const SLUG = Brand.slug.toUpperCase();46+47+const url = "https://platform.test";48+49+const given = "tok-given-0123456789abcdefghijklmnopqrstuvwxyz";50+51+const issued = "tok-issued-0123456789abcdefghijklmnopqrstuvwxyz";52+53+/** The three lines `login` sets in git's global config for `at`. */54+const helperLines = (at: string) => [55+ `git config --global --replace-all credential.${at}.helper ""`,56+ `git config --global --add credential.${at}.helper ${Brand.slug}`,57+ `git config --global credential.${at}.useHttpPath true`,58+];59+60+/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */61+const home = Effect.gen(function* () {62+ const fs = yield* FileSystem.FileSystem;63+ const path = yield* Path.Path;64+ const dir = yield* fs.makeTempDirectoryScoped();65+66+ return { GIT_CONFIG_GLOBAL: path.join(dir, ".gitconfig"), HOME: dir };67+});68+69+const credentialsIn = (env: Record<string, string>) =>70+ CredentialsFile.pipe(71+ Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))72+ );73+74+/** The profile `name` as the file holds it: its url, handle and token. */75+const 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+ );88+89+/** `git config --global <args>` in `env`: its stdout and exit code. */90+const 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+ });96+97+ 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);104+105+ return { exitCode, stdout };106+ })107+ );108+109+const claim = Schema.decodeUnknownSync(ClaimView);110+111+const isPerson = Schema.is(Person);112+113+/** One live claim of `handle`'s, as `status` lists it. */114+const 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+ });128+129+/**130+ * The platform's side of a call, as `status` sees it: whoever the server131+ * side takes the caller for holds one claim.132+ */133+const statusHandler = Contracts.toLayerHandler("status", () =>134+ Effect.map(Effect.service(CurrentPrincipal), (principal) => ({135+ answers: [],136+ claims: isPerson(principal) ? [claimOf(principal.handle)] : [],137+ }))138+);139+140+/** A server side that refuses every credential, as for a revoked token. */141+const refusesEveryone = Layer.succeed(Authenticated, () =>142+ Effect.fail(new Unauthenticated())143+);144+145+/**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+ */151+const seams = (server: Layer.Layer<Authenticated>) =>152+ Effect.gen(function* () {153+ const connected = yield* Ref.make<154+ readonly { token: string; url: string }[]155+ >([]);156+157+ const opened = yield* Ref.make<readonly string[]>([]);158+159+ const listened = yield* Ref.make<160+ readonly { hostname: string; port: number }[]161+ >([]);162+163+ 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]);183+184+ const built = yield* Layer.build(NodeHttpServer.layerTest);185+186+ return Context.get(built, HttpServer.HttpServer);187+ }),188+ })189+ );190+191+ return {192+ connected: Ref.get(connected),193+ layer,194+ listened: Ref.get(listened),195+ opened: Ref.get(opened),196+ };197+ });198+199+/** A platform that takes the caller for `handle`. */200+const signedInAs = (handle: string) => asPerson(Handle.make(handle));201+202+/** What the tests themselves run on: a test console, and Node for files, git and servers. */203+const testServices = Layer.mergeAll(TestConsole.layer, NodeServices.layer);204+205+/** A terminal nothing may touch: every use of it dies. */206+const 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+);216+217+interface 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+}225+226+/** Runs `argv` as the CLI would, in `run`'s world; how it ended. */227+const 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+ );250+251+/** What was printed, one entry per line however it was written. */252+const lines = (all: readonly unknown[]) =>253+ all.flatMap((chunk) => String(chunk).split("\n"));254+255+/** Every line printed so far, on stdout and on stderr. */256+const printed = Effect.gen(function* () {257+ return {258+ stderr: lines(yield* TestConsole.errorLines),259+ stdout: lines(yield* TestConsole.logLines),260+ };261+});262+263+/** The sign-in URL `login` printed for `origin`, once it has. */264+const 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?`));270+271+ if (line !== undefined) {272+ return line;273+ }274+275+ yield* Effect.sleep("20 millis");276+ }277+278+ return yield* Effect.die("login printed no sign-in URL");279+ });280+281+/** GET `at` as a browser would, following redirects: the page's status. */282+const visit = (at: string) =>283+ Effect.gen(function* () {284+ const client = yield* HttpClient.HttpClient;285+ const response = yield* client.get(at);286+287+ return response.status;288+ }).pipe(Effect.provide(FetchHttpClient.layer));289+290+/** The query `/authorize` was sent, field by field. */291+const fieldsOf = (query: URLSearchParams | undefined) =>292+ Object.fromEntries(query?.entries() ?? []);293+294+describe(`${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"));301+302+ const exit = yield* cli(303+ ["login", "--url", url, "--token-stdin", "--profile", "alice"],304+ { env, seams: platform.layer, stdin: `${given}\n` }305+ );306+307+ 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+ });330+331+ const { stderr, stdout } = yield* printed;332+333+ 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+ );340+341+ 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"));347+348+ yield* cli(["login", "--url", url, "--token-stdin", "--json"], {349+ env,350+ seams: platform.layer,351+ stdin: `${given}\n`,352+ });353+354+ const { stdout } = yield* printed;355+ const text = stdout.join("\n");356+357+ 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+ );396+397+ 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);403+404+ const exit = yield* cli(["login", "--url", url, "--token-stdin"], {405+ env,406+ seams: platform.layer,407+ stdin: `${given}\n`,408+ });409+410+ 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);416+417+ const { stderr, stdout } = yield* printed;418+419+ 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+ );424+425+ 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"));431+432+ const exit = yield* cli(433+ ["login", "--url", "http://platform.test", "--token-stdin"],434+ { env, seams: platform.layer, stdin: `${given}\n` }435+ );436+437+ 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+ );443+444+ 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"));450+451+ const exit = yield* cli(["login", "--token-stdin"], {452+ env,453+ seams: platform.layer,454+ stdin: `${given}\n`,455+ });456+457+ 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+});463+464+describe(`${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"));472+473+ 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+ );486+487+ expect(yield* visit(yield* signInUrl(server.origin))).toBe(200);488+ expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();489+490+ const [query] = yield* server.authorizations;491+ const fields = fieldsOf(query);492+ const urlSafe43 = /^[A-Za-z0-9_-]{43}$/u;493+494+ 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+ });536+537+ // 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+ );541+542+ const { stderr, stdout } = yield* printed;543+544+ 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+ );551+552+ 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"));559+560+ const fiber = yield* Effect.forkChild(561+ cli(["login", "--url", server.origin, "--no-browser"], {562+ env,563+ seams: platform.layer,564+ })565+ );566+567+ yield* visit(yield* signInUrl(server.origin));568+569+ 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+ );576+577+ 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"));584+585+ const fiber = yield* Effect.forkChild(586+ cli(["login", "--url", server.origin], {587+ env,588+ seams: platform.layer,589+ terminal: true,590+ })591+ );592+593+ const shown = yield* signInUrl(server.origin);594+595+ 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+ );601+602+ 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"));609+610+ const fiber = yield* Effect.forkChild(611+ cli(["login", "--url", server.origin], {612+ env,613+ seams: platform.layer,614+ terminal: true,615+ })616+ );617+618+ 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+ );624+625+ 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();633+634+ 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+ );640+641+ const shown = yield* signInUrl(server.origin);642+643+ yield* clock.adjust("5 minutes");644+645+ expect(Exit.isFailure(yield* Fiber.join(fiber))).toBeTruthy();646+647+ const said = (yield* printed).stderr.join("\n");648+649+ expect(said).toContain("5 minutes");650+ expect(said).toContain("--token-stdin");651+ expect(yield* stored(env, "default")).toStrictEqual(Option.none());652+653+ const callback = new URL(shown).searchParams.get("redirect_uri") ?? "";654+655+ 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+});664+665+describe(`${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` };673+674+ yield* cli(675+ ["login", "--url", url, "--token-stdin", "--profile", "alice"],676+ run677+ );678+679+ const exit = yield* cli(["logout", "--profile", "alice"], run);680+681+ 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+ );694+695+ 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` };702+703+ for (const name of ["alice", "bob"]) {704+ yield* cli(705+ ["login", "--url", url, "--token-stdin", "--profile", name],706+ run707+ );708+ }709+710+ yield* cli(["logout", "--profile", "alice"], run);711+712+ 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();716+717+ yield* cli(["logout", "--profile", "bob"], run);718+719+ 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 lines5 import { Cause, Effect, Exit, Layer } from "effect";6 import { CliOutput, Command } from "effect/cli";7 import { TestConsole } from "effect/testing";8 9+import { Credentials } from "../src/credentials.ts";10 import { program, root } from "../src/main.ts";11 import { OutputPlain } from "../src/output.ts";12 13 /** What was printed to stdout, one entry per line however it was written. */2 unmodified lines16 );17 18 /**19 * What the CLI runs with in these tests: a test console, plain output, and19- * a client no command here calls.20+ * a client and credentials no command here calls.21 */22 const services = Layer.mergeAll(23 TestConsole.layer,24 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),25 Layer.mock(Client)({}),26+ Layer.mock(Credentials)({}),27 OutputPlain28 ).pipe(Layer.provideMerge(NodeServices.layer));29 30 /** The help `root` prints for `--help`, line by line. */63 unmodified lines94 });95 96 describe("each command a later issue builds", () => {97 const stubs = [96- { args: ["login"], issue: "412" },97- { args: ["logout"], issue: "412" },98- { args: ["credential"], issue: "412" },98 { args: ["init"], issue: "413" },99 { args: ["check"], issue: "405" },100 { args: ["why"], issue: "414" },101 { args: ["env", "set"], issue: "414" },19 unmodified linesadded:apps/cli/test/oauth-server.ts+156 added
1+/**2+ * A stand-in for the platform's OAuth authorization server, as the CLI's3+ * `login` meets it: `/authorize` sends the browser back to the loopback4+ * `redirect_uri` with a code and the state it was given, and `/token` trades5+ * that code for an access token only if the `code_verifier` hashes (S256,6+ * RFC 7636) to the challenge `/authorize` saw.7+ */8+import { NodeHttpServer } from "@effect/platform-node";9+import { Context, Effect, Layer, Ref, Schema } from "effect";10+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";11+12+export interface OAuthServerOptions {13+ /** The access token `/token` issues. */14+ readonly token: string;15+ /** The state `/authorize` sends back: the client's own, or another one. */16+ readonly state?: "same" | "other";17+}18+19+/** A code `/authorize` gave out, and what `/token` must be shown for it. */20+interface Grant {21+ readonly challenge: string;22+ readonly clientId: string;23+ readonly redirectUri: string;24+}25+26+const TokenForm = Schema.Struct({27+ client_id: Schema.String,28+ code: Schema.String,29+ code_verifier: Schema.String,30+ grant_type: Schema.String,31+ redirect_uri: Schema.String,32+});33+34+/** Base64url without padding, as RFC 7636 §4.2 spells the S256 challenge. */35+const base64url = (bytes: Uint8Array) =>36+ btoa(String.fromCodePoint(...bytes))37+ .replaceAll("+", "-")38+ .replaceAll("/", "_")39+ .replace(/=+$/u, "");40+41+/** `BASE64URL(SHA256(verifier))`. */42+const s256 = (verifier: string) =>43+ Effect.map(44+ Effect.promise(() =>45+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))46+ ),47+ (digest) => base64url(new Uint8Array(digest))48+ );49+50+const refused = (error: string) =>51+ HttpServerResponse.jsonUnsafe({ error }, { status: 400 });52+53+/**54+ * The server on a local port: its origin, and the query of every55+ * `/authorize` request it answered.56+ */57+export const oauthServer = (options: OAuthServerOptions) =>58+ Effect.gen(function* () {59+ const grants = yield* Ref.make<ReadonlyMap<string, Grant>>(new Map());60+ const authorizations = yield* Ref.make<readonly URLSearchParams[]>([]);61+ const issued = yield* Ref.make(0);62+63+ const authorize = (query: URLSearchParams) =>64+ Effect.gen(function* () {65+ yield* Ref.update(authorizations, (all) => [...all, query]);66+67+ const redirectUri = query.get("redirect_uri") ?? "";68+ const challenge = query.get("code_challenge") ?? "";69+70+ if (71+ query.get("response_type") !== "code" ||72+ query.get("code_challenge_method") !== "S256" ||73+ challenge === ""74+ ) {75+ return refused("invalid_request");76+ }77+78+ const code = `code-${yield* Ref.updateAndGet(issued, (n) => n + 1)}`;79+80+ yield* Ref.update(grants, (all) =>81+ new Map(all).set(code, {82+ challenge,83+ clientId: query.get("client_id") ?? "",84+ redirectUri,85+ })86+ );87+88+ const back = new URL(redirectUri);89+90+ back.searchParams.set("code", code);91+ back.searchParams.set(92+ "state",93+ options.state === "other"94+ ? "not-the-state"95+ : (query.get("state") ?? "")96+ );97+98+ return HttpServerResponse.redirect(back.href, { status: 302 });99+ });100+101+ const token = Effect.gen(function* () {102+ const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);103+ const grant = (yield* Ref.get(grants)).get(form.code);104+105+ yield* Ref.update(grants, (all) => {106+ const left = new Map(all);107+108+ left.delete(form.code);109+110+ return left;111+ });112+113+ if (114+ form.grant_type !== "authorization_code" ||115+ grant === undefined ||116+ grant.clientId !== form.client_id ||117+ grant.redirectUri !== form.redirect_uri ||118+ (yield* s256(form.code_verifier)) !== grant.challenge119+ ) {120+ return refused("invalid_grant");121+ }122+123+ return HttpServerResponse.jsonUnsafe({124+ access_token: options.token,125+ token_type: "bearer",126+ });127+ }).pipe(Effect.orElseSucceed(() => refused("invalid_request")));128+129+ const app = Effect.gen(function* () {130+ const request = yield* HttpServerRequest.HttpServerRequest;131+ const url = new URL(request.url, "http://localhost");132+133+ if (request.method === "GET" && url.pathname === "/authorize") {134+ return yield* authorize(url.searchParams);135+ }136+137+ if (request.method === "POST" && url.pathname === "/token") {138+ return yield* token;139+ }140+141+ return HttpServerResponse.empty({ status: 404 });142+ });143+144+ const server = yield* Layer.build(145+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))146+ ).pipe(Effect.orDie);147+148+ const { address } = Context.get(server, HttpServer.HttpServer);149+150+ const origin =151+ "port" in address152+ ? `http://127.0.0.1:${address.port}`153+ : yield* Effect.die("the test server listens on a socket, not a port");154+155+ return { authorizations: Ref.get(authorizations), origin };156+ });