Skip to content
Myr

credential-helper.ts

This file

Path

apps/cli/src/credential-helper.ts

217 lines · 5.8 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 1why, one step back
1// The username carries the harness as audit metadata, never identity: the token is the only identity the platform reads.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 2–27why, one step back
2import { Brand } from "@repo/brand";
3import { auditUser, detectHarness } from "@repo/protocol/audit";4import {5 ConfigProvider,6 Effect,7 Match,8 Option,9 Redacted,10 Stdio,11 Stream,12} from "effect";13import { Argument, Command } from "effect/cli";1415import { Credentials } from "./credentials.ts";16import { Output } from "./output.ts";1718export type Operation = "get" | "store" | "erase";1920const operations = [21 "get",22 "store",23 "erase",24] as const satisfies readonly Operation[];2526export type Env = Readonly<Record<string, string | undefined>>;27

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 28why, one step back
28/** The config provider reports only an all-numeric level's largest index, so a name like `RUN_4294967294` would make the walk count to four billion. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 29–108why, one step back
29const INDEX_LIMIT = 1024;
3031const namesBelow = (32 provider: ConfigProvider.ConfigProvider,33 path: ConfigProvider.Path34): Effect.Effect<readonly (readonly [string, string])[]> =>35 provider.load(path).pipe(36 Effect.map(Option.fromNullishOr),37 Effect.orElseSucceed(() => Option.none<ConfigProvider.Node>()),38 Effect.flatMap(39 Option.match({40 onNone: () => Effect.succeed([]),41 onSome: (node) => {42 const own =43 path.length > 0 && node.value !== undefined44 ? [[path.join("_"), node.value] as const]45 : [];4647 const children = Match.valueTags(node, {48 Array: ({ length }) =>49 Array.from({ length: Math.min(length, INDEX_LIMIT) }, (_, at) =>50 String(at)51 ),52 Record: ({ keys }) => [...keys],53 Value: () => [],54 });5556 return Effect.map(57 Effect.forEach(children, (child) =>58 namesBelow(provider, [...path, child])59 ),60 (nested) => [...own, ...nested.flat()]61 );62 },63 })64 )65 );6667export const currentEnv: Effect.Effect<Readonly<Record<string, string>>> =68 Effect.gen(function* () {69 const provider = yield* ConfigProvider.ConfigProvider;7071 return Object.fromEntries(yield* namesBelow(provider, []));72 });7374const requestOf = (input: string) => {75 const fields = new Map<string, string>();7677 for (const line of input.split("\n")) {78 if (line === "") {79 break;80 }8182 const equals = line.indexOf("=");8384 if (equals > 0) {85 fields.set(line.slice(0, equals), line.slice(equals + 1));86 }87 }8889 return fields;90};9192const SLUG = Brand.slug.toUpperCase();9394const placeOf = Option.liftThrowable((url: string) => {95 const { host, protocol } = new URL(url);9697 return { host: host.toLowerCase(), scheme: protocol.replace(/:$/u, "") };98});99100const fitsOneLine = (value: string) => !/[\n\r\0]/u.test(value);101102interface Answer {103 readonly stdout: string;104 readonly note: Option.Option<string>;105}106107const silent: Answer = { note: Option.none(), stdout: "" };108

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 109why, one step back
109/** Under `<SLUG>_PROFILE` only that profile may answer, so another person's token for the same host is never handed over. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 110–217why, one step back
110const answer = (op: Operation, input: string, env: Env) =>
111 Effect.gen(function* () {112 if (op !== "get") {113 return silent;114 }115116 const request = requestOf(input);117 const host = request.get("host");118 const protocol = request.get("protocol");119120 if (host === undefined || protocol === undefined) {121 return silent;122 }123124 const credentials = yield* Credentials;125126 const named = Option.filter(127 Option.fromNullishOr(env[`${SLUG}_PROFILE`]),128 (name) => name !== ""129 );130131 const candidate = Option.isSome(named)132 ? yield* credentials.current133 : yield* credentials.forHost(host);134135 const profile = Option.filter(136 candidate,137 ({ token, url }) =>138 Option.exists(139 placeOf(url),140 (at) => at.scheme === protocol && at.host === host.toLowerCase()141 ) && fitsOneLine(Redacted.value(token))142 );143144 if (Option.isSome(profile)) {145 return {146 note: Option.none(),147 stdout: `username=${auditUser(detectHarness(env))}\npassword=${Redacted.value(profile.value.token)}\n`,148 } satisfies Answer;149 }150151 const flag = Option.match(named, {152 onNone: () => "",153 onSome: (name) => ` --profile ${name}`,154 });155156 return Option.isNone(yield* credentials.current)157 ? {158 note: Option.some(159 `no ${Brand.cli} login for ${host}: run ${Brand.cli} login${flag} --url ${protocol}://${host}`160 ),161 stdout: "",162 }163 : silent;164 });165166export const credentialHelper = (167 op: Operation,168 input: string,169 env: Env170): Effect.Effect<string, never, Credentials> =>171 Effect.map(answer(op, input, env), ({ stdout }) => stdout);172173const readRequest = Effect.gen(function* () {174 const { stdin } = yield* Stdio.Stdio;175176 const lines = yield* stdin.pipe(177 Stream.decodeText(),178 Stream.splitLines,179 Stream.takeWhile((line) => line !== ""),180 Stream.runCollect,181 Effect.orElseSucceed((): readonly string[] => [])182 );183184 return `${lines.join("\n")}\n\n`;185});186187export const credential = Command.make(188 "credential",189 {190 operation: Argument.Literals("operation", operations).pipe(191 Argument.withDescription("What git asks: get, store or erase")192 ),193 },194 ({ operation }) =>195 Effect.gen(function* () {196 const stdio = yield* Stdio.Stdio;197 const output = yield* Output;198 const request = yield* readRequest;199 const given = yield* answer(operation, request, yield* currentEnv);200201 if (given.stdout !== "") {202 yield* Stream.make(given.stdout).pipe(203 Stream.run(stdio.stdout()),204 Effect.orDie205 );206 }207208 yield* Option.match(given.note, {209 onNone: () => Effect.void,210 onSome: output.note,211 });212 })213).pipe(214 Command.withDescription(215 "Be git's credential helper: hand git the stored token for a platform."216 )217);