env-set.ts
This file
Path
apps/cli/src/local/env-set.ts
213 lines · 6.3 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake 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 back1// The value is never an argument, never printed, logged, hashed or measured, and nothing reads it back.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–28why, one step back2import { Brand } from "@repo/brand";3import { Client, SetEnv } from "@repo/protocol/contracts";4import { EnvKey, ProjectName } from "@repo/protocol/ids";5import {6 DateTime,7 Effect,8 Option,9 Redacted,10 Schema,11 Stdio,12 Stream,13} from "effect";14import { Argument, Command, Flag, Prompt } from "effect/cli";1516import { Output } from "../output.ts";17import type { Mode } from "../output.ts";18import { repoContext } from "../repo-context.ts";19import { WorkingDirectory, projectOf, reportRefusals, usage } from "./why.ts";20import type { UsageError } from "./why.ts";2122const command = "env set";2324const encodeSet = Schema.encodeEffect(SetEnv.successSchema);2526const pipeHint = (key: string) =>27 `printf '%s\\n' "$VALUE" | ${Brand.cli} ${command} ${key} --yes`;28Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 29why, one step back29/** Shows nothing typed, not even a mask, which would tell its length. An agent or script is never prompted. */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 30–74why, one step back30const prompted = (key: EnvKey, mode: Mode) =>31 mode === "human"32 ? Prompt.run(33 Prompt.Hidden({34 message: `Value for ${key} (nothing you type is shown)`,35 })36 )37 : usage(38 `${Brand.cli} never prompts an agent or a script, so pipe the value of ${key} on stdin: ${pipeHint(key)}`39 );4041const readValue = (key: EnvKey, mode: Mode) =>42 Effect.gen(function* () {43 const stdio = yield* Stdio.Stdio;4445 const value = (yield* stdio.stdinIsTerminal)46 ? yield* prompted(key, mode)47 : yield* stdio.stdin.pipe(48 Stream.decodeText(),49 Stream.mkString,50 Effect.map((text) => Redacted.make(text.replace(/\r?\n$/u, "")))51 );5253 // Whether anything arrived at all; nothing else about it is looked at.54 return Redacted.value(value) === ""55 ? yield* usage(`No value for ${key} arrived: ${pipeHint(key)}`)56 : value;57 });5859const projectFor = (named: Option.Option<ProjectName>) =>60 Effect.gen(function* () {61 if (Option.isSome(named)) {62 return named.value;63 }6465 const cwd = yield* WorkingDirectory;6667 const context = yield* repoContext(cwd).pipe(68 Effect.asSome,69 Effect.catchTag("NotARepo", () => Effect.succeedNone)70 );7172 return yield* projectOf(named, context);73 });74Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 75why, one step back75/** A test holds this list to the flags `env set --help` names. */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 76–100why, one step back76const spellings: ReadonlySet<string> = new Set([77 "--acknowledge-short",78 "--completions",79 "--dry-run",80 "--help",81 "--json",82 "--log-level",83 "--project",84 "--version",85 "--wizard",86 "--yes",87 "-h",88 "-v",89]);9091const strangeFlag = (word: string) => {92 const [flag = word] = word.split("=", 1);9394 return (95 word.startsWith("-") &&96 word !== "-" &&97 !spellings.has(flag.replace(/^--no-/u, "--"))98 );99};100Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 101why, one step back101/** effect/cli would print a stray flag back (or act on a `-h` inside it), so a value typed there must be refused before parsing. */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 102–213why, one step back102export const refuseStrangeFlags = (103 argv: readonly string[]104): Effect.Effect<void, UsageError> => {105 const end = argv.indexOf("--");106 const words = end === -1 ? argv : argv.slice(0, end);107108 const at = words.findIndex(109 (word, index) => word === "env" && words[index + 1] === "set"110 );111112 return at !== -1 && words.slice(at + 2).some(strangeFlag)113 ? usage(114 `${Brand.cli} ${command} was given a flag it does not take, not repeated here in case it holds the value; the value is read from stdin, never from arguments: ${pipeHint("<KEY>")}`115 )116 : Effect.void;117};118119export const envSet = Command.make(120 "set",121 {122 acknowledgeShort: Flag.Boolean("acknowledge-short").pipe(123 Flag.withDefault(false),124 Flag.withDescription(125 "Store a value shorter than the item's minimum anyway"126 )127 ),128 dryRun: Flag.Boolean("dry-run").pipe(129 Flag.withDefault(false),130 Flag.withDescription(131 "Print what would be sent, value redacted; send nothing"132 )133 ),134 json: Flag.Boolean("json").pipe(135 Flag.withDefault(false),136 Flag.withDescription("Print machine-readable JSON")137 ),138 key: Argument.String("key").pipe(139 Argument.withSchema(EnvKey),140 Argument.withDescription("The @sensitive env item to set")141 ),142 project: Flag.String("project").pipe(143 Flag.withSchema(ProjectName),144 Flag.optional,145 Flag.withDescription(146 "The project; the repo's platform remote names it by default"147 )148 ),149 // Caught here, so the parser never echoes a value typed as an argument.150 stray: Argument.String("not-the-value").pipe(151 Argument.variadic(),152 Argument.withDescription(153 "Refused: the value is read from stdin, never from arguments"154 )155 ),156 yes: Flag.Boolean("yes").pipe(157 Flag.withDefault(false),158 Flag.withDescription("Store the value (it needs approval)")159 ),160 },161 ({ acknowledgeShort, dryRun, json, key, project, stray, yes }) =>162 Effect.gen(function* () {163 if (stray.length > 0) {164 return yield* usage(165 `${Brand.cli} ${command} takes the value on stdin, never as an argument, so it stays out of shell history and process lists: ${pipeHint(key)}`166 );167 }168169 const name = yield* projectFor(project);170 const output = yield* Output;171 const acknowledged = acknowledgeShort ? { acknowledgeShort } : {};172173 if (dryRun) {174 return yield* output.plan({175 command,176 json,177 payload: { ...acknowledged, key, project: name, value: "<redacted>" },178 });179 }180181 if (!yes) {182 return yield* usage(183 `${command} stores a value for ${key}: add --yes to store it, or --dry-run to see what would be sent.`184 );185 }186187 const value = yield* readValue(key, output.mode);188 const client = yield* Client;189190 const set = yield* client.setEnv({191 ...acknowledged,192 key,193 project: name,194 value,195 });196197 const at = DateTime.formatIso(set.setAt);198199 return yield* output.success({200 command,201 data: yield* encodeSet(set).pipe(Effect.orDie),202 json,203 view: {204 markdown: `\`${set.key}\` on ${name} was set by ${set.setBy} at ${at}. Nobody can read it back.`,205 text: `${set.key} on ${name} was set by ${set.setBy} at ${at}. Nobody can read it back.`,206 },207 });208 }).pipe(reportRefusals(command, json))209).pipe(210 Command.withDescription(211 "Set a sensitive env item's value from stdin; nobody can read it back."212 )213);