Skip to content
Myr

credentials.ts

This file

Path

apps/cli/src/credentials.ts

208 lines · 5.6 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/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–74why, one step back
1import { Brand } from "@repo/brand";
2import { Handle } from "@repo/protocol/ids";3import {4 Array,5 Config,6 Context,7 Effect,8 FileSystem,9 Layer,10 Option,11 Order,12 Path,13 Schema,14} from "effect";1516export const Profile = Schema.Struct({17 handle: Schema.optionalKey(Handle),18 token: Schema.RedactedFromValue(Schema.NonEmptyString),19 url: Schema.NonEmptyString,20});2122export type Profile = typeof Profile.Type;2324export class CredentialsUnwritable extends Schema.TaggedError<CredentialsUnwritable>()(25 "CredentialsUnwritable",26 { path: Schema.String }27) {28 override get message() {29 return `cannot write ${this.path}: check that it is yours and is JSON, or remove it`;30 }31}3233export class Credentials extends Context.Service<34 Credentials,35 {36 readonly current: Effect.Effect<Option.Option<Profile>>;37 readonly forHost: (host: string) => Effect.Effect<Option.Option<Profile>>;38 readonly put: (39 name: string,40 profile: Profile41 ) => Effect.Effect<void, CredentialsUnwritable>;42 readonly remove: (43 name: string44 ) => Effect.Effect<boolean, CredentialsUnwritable>;45 }46>()("cli/Credentials") {}4748const Store = Schema.fromJsonString(49 Schema.Struct({ profiles: Schema.Record(Schema.String, Profile) })50);5152const decodeStore = Schema.decodeEffect(Store);5354const encodeStore = Schema.encodeEffect(Store);5556const SLUG = Brand.slug.toUpperCase();5758const Env = Config.all({59 configHome: Config.option(Config.NonEmptyString("XDG_CONFIG_HOME")),60 home: Config.option(Config.NonEmptyString("HOME")),61 profile: Config.option(Config.NonEmptyString(`${SLUG}_PROFILE`)),62 token: Config.option(Config.Redacted(`${SLUG}_TOKEN`)),63 url: Config.option(Config.NonEmptyString(`${SLUG}_URL`)),64});6566const hostOf = Option.liftThrowable((url: string) =>67 new URL(url).host.toLowerCase()68);6970/** Owner only: the file holds tokens. */71const FILE_MODE = 0o600;7273const DIR_MODE = 0o700;74

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

line 75why, one step back
75/** Replaced whole on every write so no reader sees half of one. */

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–186why, one step back
76export const CredentialsFile = Layer.effect(Credentials)(
77 Effect.gen(function* () {78 const fs = yield* FileSystem.FileSystem;79 const path = yield* Path.Path;80 const env = yield* Effect.orDie(Env);8182 const dir = Option.map(83 Option.orElse(env.configHome, () =>84 Option.map(env.home, (home) => path.join(home, ".config"))85 ),86 (config) => path.join(config, Brand.slug)87 );8889 const file = Option.map(dir, (folder) =>90 path.join(folder, "credentials.json")91 );9293 const named = Option.getOrElse(env.profile, () => "default");9495 const fromEnv = Option.map(96 Option.all({ token: env.token, url: env.url }),97 ({ token, url }): Profile => ({ token, url })98 );99100 const load = Option.match(file, {101 onNone: () => Effect.succeed<Readonly<Record<string, Profile>>>({}),102 onSome: (at) =>103 Effect.gen(function* () {104 if (!(yield* fs.exists(at))) {105 return {};106 }107108 const store = yield* Effect.flatMap(109 fs.readFileString(at),110 decodeStore111 );112113 return store.profiles;114 }).pipe(Effect.mapError(() => new CredentialsUnwritable({ path: at }))),115 });116117 const readable = Effect.orElseSucceed(118 load,119 (): Readonly<Record<string, Profile>> => ({})120 );121122 const save = (profiles: Readonly<Record<string, Profile>>) =>123 Effect.gen(function* () {124 const at = yield* Effect.fromOption(file);125 const folder = path.dirname(at);126 const staged = `${at}.tmp`;127128 yield* fs.makeDirectory(folder, { mode: DIR_MODE, recursive: true });129 yield* fs.writeFileString(staged, yield* encodeStore({ profiles }), {130 mode: FILE_MODE,131 });132 yield* fs.chmod(staged, FILE_MODE);133 yield* fs.rename(staged, at);134 }).pipe(135 Effect.mapError(136 () =>137 new CredentialsUnwritable({138 path: Option.getOrElse(file, () => "credentials.json"),139 })140 )141 );142143 const current = Option.match(fromEnv, {144 onNone: () =>145 Effect.map(readable, (profiles) =>146 Option.fromNullishOr(profiles[named])147 ),148 onSome: (profile) => Effect.succeedSome(profile),149 });150151 return {152 current,153 forHost: (host) =>154 Effect.map(readable, (profiles) => {155 const stored = Array.sort(Object.keys(profiles), Order.String)156 .toSorted(157 (one, other) => Number(other === named) - Number(one === named)158 )159 .flatMap((name) =>160 Option.toArray(Option.fromNullishOr(profiles[name]))161 );162163 return Array.findFirst(164 [...Option.toArray(fromEnv), ...stored],165 (profile) =>166 Option.contains(hostOf(profile.url), host.toLowerCase())167 );168 }),169 put: (name, profile) =>170 Effect.flatMap(load, (profiles) =>171 save({ ...profiles, [name]: profile })172 ),173 remove: (name) =>174 Effect.flatMap(load, (profiles) => {175 if (!Object.hasOwn(profiles, name)) {176 return Effect.succeed(false);177 }178179 const { [name]: _removed, ...rest } = profiles;180181 return Effect.as(save(rest), true);182 }),183 };184 })185);186

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

line 187why, one step back
187/** An empty helper comes first to drop any general one (a keychain) for this url. */

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 188–208why, one step back
188export const gitHelperConfig = (
189 url: string190): readonly (readonly string[])[] => [191 [192 "git",193 "config",194 "--global",195 "--replace-all",196 `credential.${url}.helper`,197 "",198 ],199 [200 "git",201 "config",202 "--global",203 "--add",204 `credential.${url}.helper`,205 Brand.slug,206 ],207 ["git", "config", "--global", `credential.${url}.useHttpPath`, "true"],208];