Skip to content
Myr

credentials.ts

This file

Path

apps/cli/src/credentials.ts

310 lines · 9.0 KiB · TypeScript

Last changed by

landed by oscarf7b8ef2

History of this file

Take it

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

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 1–4why, one step back
1import { Brand } from "@repo/brand";
2import { Handle } from "@repo/protocol/ids";3import {4 Array,

landed by oscarf7b8ef2

line 5why, one step back
5 Clock,

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 6–7why, one step back
6 Config,
7 Context,

landed by oscarf7b8ef2

line 8why, one step back
8 Duration,

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 9–14why, one step back
9 Effect,
10 FileSystem,11 Layer,12 Option,13 Order,14 Path,

landed by oscarf7b8ef2

line 15why, one step back
15 Redacted,

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 16–18why, one step back
16 Schema,
17} from "effect";1819import { renew } from "./oauth-token.ts";2021// A browser sign-in keeps the token's lapse, in epoch milliseconds, and the22// refresh token that renews it; a token given by hand keeps neither, and lasts23// as long as the platform lets it.

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

line 24why, one step back
24export const Profile = Schema.Struct({

landed by oscarf7b8ef2

line 25why, one step back
25 expiresAt: Schema.optionalKey(Schema.Int),

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

line 26why, one step back
26 handle: Schema.optionalKey(Handle),
27 refreshToken: Schema.optionalKey(28 Schema.RedactedFromValue(Schema.NonEmptyString)29 ),

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 30–53why, one step back
30 token: Schema.RedactedFromValue(Schema.NonEmptyString),
31 url: Schema.NonEmptyString,32});3334export type Profile = typeof Profile.Type;3536export class CredentialsUnwritable extends Schema.TaggedError<CredentialsUnwritable>()(37 "CredentialsUnwritable",38 { path: Schema.String }39) {40 override get message() {41 return `cannot write ${this.path}: check that it is yours and is JSON, or remove it`;42 }43}4445export class Credentials extends Context.Service<46 Credentials,47 {48 readonly current: Effect.Effect<Option.Option<Profile>>;49 readonly forHost: (host: string) => Effect.Effect<Option.Option<Profile>>;50 readonly put: (51 name: string,52 profile: Profile53 ) => Effect.Effect<void, CredentialsUnwritable>;

landed by oscarf7b8ef2

line 54why, one step back
54 // The profile it removed, if there was one.

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 55–56why, one step back
55 readonly remove: (
56 name: string

landed by oscarf7b8ef2

line 57why, one step back
57 ) => Effect.Effect<Option.Option<Profile>, CredentialsUnwritable>;

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 58–87why, one step back
58 }
59>()("cli/Credentials") {}6061const Store = Schema.fromJsonString(62 Schema.Struct({ profiles: Schema.Record(Schema.String, Profile) })63);6465const decodeStore = Schema.decodeEffect(Store);6667const encodeStore = Schema.encodeEffect(Store);6869const SLUG = Brand.slug.toUpperCase();7071const Env = Config.all({72 configHome: Config.option(Config.NonEmptyString("XDG_CONFIG_HOME")),73 home: Config.option(Config.NonEmptyString("HOME")),74 profile: Config.option(Config.NonEmptyString(`${SLUG}_PROFILE`)),75 token: Config.option(Config.Redacted(`${SLUG}_TOKEN`)),76 url: Config.option(Config.NonEmptyString(`${SLUG}_URL`)),77});7879const hostOf = Option.liftThrowable((url: string) =>80 new URL(url).host.toLowerCase()81);8283/** Owner only: the file holds tokens. */84const FILE_MODE = 0o600;8586const DIR_MODE = 0o700;8788/** Renewed this long before it lapses, so no call carries a token that dies on the way. */89export const RENEW_MARGIN = Duration.minutes(1);9091const sameToken = (one: Redacted.Redacted, other: Redacted.Redacted) =>92 Redacted.value(one) === Redacted.value(other);93

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

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

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 95–161why, one step back
95export const CredentialsFile = Layer.effect(Credentials)(
96 Effect.gen(function* () {97 const fs = yield* FileSystem.FileSystem;98 const path = yield* Path.Path;99 const env = yield* Effect.orDie(Env);100101 const dir = Option.map(102 Option.orElse(env.configHome, () =>103 Option.map(env.home, (home) => path.join(home, ".config"))104 ),105 (config) => path.join(config, Brand.slug)106 );107108 const file = Option.map(dir, (folder) =>109 path.join(folder, "credentials.json")110 );111112 const named = Option.getOrElse(env.profile, () => "default");113114 const fromEnv = Option.map(115 Option.all({ token: env.token, url: env.url }),116 ({ token, url }): Profile => ({ token, url })117 );118119 const load = Option.match(file, {120 onNone: () => Effect.succeed<Readonly<Record<string, Profile>>>({}),121 onSome: (at) =>122 Effect.gen(function* () {123 if (!(yield* fs.exists(at))) {124 return {};125 }126127 const store = yield* Effect.flatMap(128 fs.readFileString(at),129 decodeStore130 );131132 return store.profiles;133 }).pipe(Effect.mapError(() => new CredentialsUnwritable({ path: at }))),134 });135136 const readable = Effect.orElseSucceed(137 load,138 (): Readonly<Record<string, Profile>> => ({})139 );140141 const save = (profiles: Readonly<Record<string, Profile>>) =>142 Effect.gen(function* () {143 const at = yield* Effect.fromOption(file);144 const folder = path.dirname(at);145 const staged = `${at}.tmp`;146147 yield* fs.makeDirectory(folder, { mode: DIR_MODE, recursive: true });148 yield* fs.writeFileString(staged, yield* encodeStore({ profiles }), {149 mode: FILE_MODE,150 });151 yield* fs.chmod(staged, FILE_MODE);152 yield* fs.rename(staged, at);153 }).pipe(154 Effect.mapError(155 () =>156 new CredentialsUnwritable({157 path: Option.getOrElse(file, () => "credentials.json"),158 })159 )160 );161162 /**163 * A stored profile whose token is about to lapse, renewed and written back.164 * When the platform refuses the renewal, another process (git's helper, a165 * second command) may have renewed it first, so the file is read again; if166 * it holds no newer token, the old one is handed back, and the call it167 * carries is refused as signed out.168 */169 const fresh = (name: string, profile: Profile) =>170 Effect.gen(function* () {171 const now = yield* Clock.currentTimeMillis;172173 if (174 profile.refreshToken === undefined ||175 profile.expiresAt === undefined ||176 profile.expiresAt - Duration.toMillis(RENEW_MARGIN) > now177 ) {178 return profile;179 }180181 const { refreshToken } = profile;182183 const issued = yield* renew(profile.url, refreshToken).pipe(184 Effect.option185 );186187 if (Option.isNone(issued)) {188 const latest = Option.fromNullishOr((yield* readable)[name]);189190 return Option.match(191 Option.filter(192 latest,193 (kept) =>194 kept.url === profile.url &&195 !sameToken(kept.token, profile.token)196 ),197 { onNone: () => profile, onSome: (kept) => kept }198 );199 }200201 const renewed: Profile = {202 ...profile,203 ...Option.match(issued.value.expiresAt, {204 onNone: () => ({}),205 onSome: (expiresAt) => ({ expiresAt }),206 }),207 refreshToken: Option.getOrElse(208 issued.value.refreshToken,209 () => refreshToken210 ),211 token: issued.value.token,212 };213214 // The renewal stands even if the file cannot take it: this call carries it.215 yield* Effect.flatMap(load, (profiles) =>216 save({ ...profiles, [name]: renewed })217 ).pipe(Effect.ignore);218219 return renewed;220 });221

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 222–223why, one step back
222 const current = Option.match(fromEnv, {
223 onNone: () =>224 Effect.flatMap(readable, (profiles) =>225 Option.match(Option.fromNullishOr(profiles[named]), {226 onNone: () => Effect.succeedNone,227 onSome: (profile) => Effect.asSome(fresh(named, profile)),228 })

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 229–235why, one step back
229 ),
230 onSome: (profile) => Effect.succeedSome(profile),231 });232233 return {234 current,235 forHost: (host) =>

landed by oscarf7b8ef2

line 236why, one step back
236 Effect.flatMap(readable, (profiles) => {

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 237–241why, one step back
237 const stored = Array.sort(Object.keys(profiles), Order.String)
238 .toSorted(239 (one, other) => Number(other === named) - Number(one === named)240 )241 .flatMap((name) =>242 Option.toArray(243 Option.map(244 Option.fromNullishOr(profiles[name]),245 (profile) => [Option.some(name), profile] as const246 )247 )

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 248–249why, one step back
248 );
249250 const found = Array.findFirst(251 [252 ...Option.toArray(253 Option.map(254 fromEnv,255 (profile) => [Option.none<string>(), profile] as const256 )257 ),258 ...stored,259 ],260 ([, profile]) =>

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 261–262why, one step back
261 Option.contains(hostOf(profile.url), host.toLowerCase())
262 );263264 return Option.match(found, {265 onNone: () => Effect.succeedNone,266 onSome: ([name, profile]) =>267 Option.match(name, {268 onNone: () => Effect.succeedSome(profile),269 onSome: (at) => Effect.asSome(fresh(at, profile)),270 }),271 });

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 272–278why, one step back
272 }),
273 put: (name, profile) =>274 Effect.flatMap(load, (profiles) =>275 save({ ...profiles, [name]: profile })276 ),277 remove: (name) =>278 Effect.flatMap(load, (profiles) => {

landed by oscarf7b8ef2

line 279why, one step back
279 const { [name]: removed, ...rest } = profiles;

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

line 280why, one step back
280
281 return removed === undefined282 ? Effect.succeedNone283 : Effect.as(save(rest), Option.some(removed));

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 284–288why, one step back
284 }),
285 };286 })287);288

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

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

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 290–310why, one step back
290export const gitHelperConfig = (
291 url: string292): readonly (readonly string[])[] => [293 [294 "git",295 "config",296 "--global",297 "--replace-all",298 `credential.${url}.helper`,299 "",300 ],301 [302 "git",303 "config",304 "--global",305 "--add",306 `credential.${url}.helper`,307 Brand.slug,308 ],309 ["git", "config", "--global", `credential.${url}.useHttpPath`, "true"],310];