4 files, 280 lines added, 18 removed.
--- a/client/src/config.ts
+++ b/client/src/config.ts
@@ -48,7 +48,11 @@
51−export function readConfig(root: string, env: Readonly<Record<string, string | undefined>> = process.env): Config {
51+export function readConfig( 53+ env: Readonly<Record<string, string | undefined>> = process.env, 5256 const raw = JSON.parse(readFileSync(configPath(root), "utf8")) as Partial<Settings>; 5357 if (raw.visitor === true) { 5458 for (const key of ["server", "project"] as const) { @@ -60,7 +64,7 @@
6064 for (const key of ["server", "project", "agent"] as const) { 6165 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`); 63− const token = tokenFor(raw.server!, env, root);
67+ const token = tokenFor(raw.server!, env, root, tokenFileOk); 6569 server: raw.server!, 6670 project: raw.project!, @@ -178,6 +182,7 @@
179183 env: Readonly<Record<string, string | undefined>> = process.env, 181186): string | undefined { 183188 const key = readKeyFile(root); @@ -187,9 +192,20 @@
190− const token = fromEnv(env, "TOKEN")?.trim() || runKey(env) || readToken(env);
191− const trusted = trustedServers(env);
192− if (token === undefined || tokenGoesTo(server, trusted)) return token;
195+ return trustedToken( 198+ fromEnv(env, "TOKEN")?.trim() || runKey(env) || (tokenFileOk ? readToken(env) : undefined), 202+/** The token as given, if abso may send it to this server; refused, in words, if not. */ 203+export function trustedToken( 205+ env: Readonly<Record<string, string | undefined>>, 206+ token: string | undefined, 207+): string | undefined { 208+ if (token === undefined || tokenGoesTo(server, trustedServers(env))) return token; 193209 throw new UsageError( 194210 `this folder's server is ${server}, and abso sends your token only to ${[...TOKEN_SERVERS, "this machine"].join(", ")}, and the servers ~/.abso/servers.json or ABSO_TRUSTED_SERVERS name. ` + 195211 `If ${server} is yours, name it in ~/.abso/servers.json or ABSO_TRUSTED_SERVERS (comma-separated); if you didn't set it, someone else wrote .abso/config.json.`, @@ -235,6 +251,11 @@
254+/** This machine's token file (~/.abso/token, else ~/.avcs/token), or none. abso init and join read it only with --token-file. */ 255+export function tokenFile(): string | undefined { 256+ return readToken({}); 238259/** ABSO_TOKEN if set, else ~/.abso/token, else ~/.avcs/token, else none. */ 239260export function readToken(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined { 240261 const fromVar = fromEnv(env, "TOKEN"); --- a/client/src/join-commands.ts
+++ b/client/src/join-commands.ts
@@ -19,7 +19,16 @@
1919import { CLIENT_DIR } from "./client-version.ts"; 2020import { type Env, type Output, plural } from "./command-env.ts"; 2121import { leftOutText, syncFolder, uploadBlobs } from "./commands.ts"; 22−import { findRoot, installKey, readConfig, type Settings, tokenFor, writeConfig } from "./config.ts";
2332import { elsewhereText } from "./doctor.ts"; 2433import { fromEnv } from "./env-names.ts"; 2534import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts"; @@ -59,6 +68,42 @@
5968 return ['The project is empty. Put its files in this folder, then abso push -m "why" publishes them.']; 71+/** A credential other than the box's, and how init and join name it when they say what they sign in with. */ 72+export interface Credential { 73+ readonly token: string | undefined; 74+ readonly words: string; 78+ * What init and join sign in with when it isn't the box's sign-in. The machine's token file only with --token-file, and 79+ * never into a folder that already has a key; else a token the environment names (ABSO_TOKEN, or a pipeline run's 80+ * ABSO_KEY_FILE); else none. The token file is never read unasked, so a project is never made or joined with a shared 81+ * credential nobody chose. 83+export function tokenCredential( 88+ file: () => string | undefined = tokenFile, 89+): Credential | undefined { 90+ if (bool(args, "token-file")) { 91+ if (existsSync(join(stateDir(root), "key"))) 92+ throw new UsageError(`${root} already has a key, so it signs in with that: leave off --token-file`); 93+ const token = trustedToken(server, env, file()); 94+ if (!token) throw new UsageError("--token-file reads ~/.abso/token, and this machine has none"); 95+ return { token, words: "the token file, ~/.abso/token, as --token-file asks" }; 97+ const named = fromEnv(env, "TOKEN")?.trim(); 98+ if (named) return { token: trustedToken(server, env, named), words: "ABSO_TOKEN" }; 99+ const run = runKey(env); 100+ if (run) return { token: trustedToken(server, env, run), words: "a pipeline run's key (ABSO_KEY_FILE)" }; 104+/** Why a token file is no fallback: said when one is here and nothing else signs in. */ 105+const TOKEN_FILE_ASKED = "~/.abso/token is used only with --token-file."; 62107export async function runInit(args: Parsed, env: Env): Promise<Output> { 63108 if (args.positionals.length > 1) throw new UsageError("init takes one folder"); 64109 const root = resolve(env.cwd, args.positionals[0] ?? "."); @@ -67,12 +112,21 @@
67112 const project = str(args, "project"); 68113 if (!project) throw new UsageError("give the project a name with --project <name>"); 69114 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both"); 70− // A box signed in here, and no token for this server: the project is made as the person who approved the box,
71− // the way the website makes one (abso 663).
115+ // A box signed in here, and no other credential asked for: the project is made as the person who approved the box, 116+ // the way the website makes one (abso 663). The token file only with --token-file, never by itself. 72117 const server = serverFrom(args, env); 73118 const box = readBox(server); 74− if (box && !tokenFor(server, env.env) && !fromEnv(env.env, "KEY_FILE"))
119+ const credential = tokenCredential(args, env.env, server, root); 120+ const say = env.writeErr ?? env.write; 121+ if (box && credential === undefined) { 122+ say(`Signing in with this box's sign-in, ${box.id}. 75124 return initFromBox(args, env, root, project, server, box); 126+ if (credential === undefined && tokenFile() !== undefined) 127+ throw new UsageError( 128+ `abso init signs in with this box's sign-in, and this box isn't signed in to ${server}: abso login signs it in. ${TOKEN_FILE_ASKED}`, 76130 const org = str(args, "org"); 77131 if (org !== undefined) return initInOrg(org, server); 78132 const config = makeSettings(args, env, project); @@ -83,7 +137,9 @@
83137 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest. 84138 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root); 85139 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root)); 86− const token = tokenFor(config.server, env.env);
140+ const token = credential?.token; 141+ say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}. 87143 const api = new Api({ ...config, ...(token ? { token } : {}) }); 88144 await uploadBlobs(api, blobs); 89145 const answer = await api.init( @@ -309,11 +365,16 @@
309365 const server = serverFrom(args, env); 310366 const box = readBox(server); 311367 const hasKey = existsSync(join(stateDir(root), "key")); 368+ const credential = tokenCredential(args, env.env, server, root); 369+ const tokenFileAsked = bool(args, "token-file"); 312370 let agent: string; 313371 let minted: { key: string; id: string } | undefined; 314372 if (str(args, "agent") !== undefined) { 315373 agent = agentFrom(args); 316− minted = box && !hasKey && !fromEnv(env.env, "KEY_FILE") ? await mintKey(box, project, agent) : undefined;
375+ box && !hasKey && !fromEnv(env.env, "KEY_FILE") && !tokenFileAsked 376+ ? await mintKey(box, project, agent) 317378 } else if (fromEnv(env.env, "KEY_FILE")) { 318379 // A pipeline run's key (ABSO_KEY_FILE) belongs to one agent, which the runner names in ABSO_AGENT. 319380 const named = fromEnv(env.env, "AGENT"); @@ -337,7 +398,13 @@
337398 writeConfig(root, config); 339400 if (minted) installKey(root, JSON.stringify(minted)); 340− const settings = readConfig(root, env.env);
401+ // The token file only with --token-file: readConfig reads it otherwise. 402+ const read = readConfig(root, env.env, false); 403+ const settings = tokenFileAsked ? { ...read, token: credential?.token } : read; 404+ (env.writeErr ?? env.write)( 405+ `Signing in with ${minted && box ? `a new key from this box's sign-in, ${box.id}` : hasKey ? "this folder's key" : (credential?.words ?? `no credential: nothing here signs in to ${server}`)}. 341408 const api = new Api(settings); 342409 let synced: Awaited<ReturnType<typeof syncFolder>>; @@ -348,7 +415,8 @@
349416 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error; 350417 rmSync(stateDir(root), { recursive: true, force: true }); 351− throw new UsageError(await signedOut(config.server, project));
418+ const why = await signedOut(config.server, project); 419+ throw new UsageError(!tokenFileAsked && tokenFile() !== undefined ? `${why} ${TOKEN_FILE_ASKED}` : why); --- a/client/src/main.ts
+++ b/client/src/main.ts
@@ -118,10 +118,12 @@
119119 public: "boolean", 120120 private: "boolean", 121+ "token-file": "boolean", 122− usage: "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private]",
124+ "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file]", 124− "Create a project on the server from a folder's text files The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no avcs.json and package.json gives a check or a build to guess, an avcs.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and the server's token.",
126+ "Create a project on the server from a folder's text files The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no avcs.json and package.json gives a check or a build to guess, an avcs.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and a token: ABSO_TOKEN, or with --token-file this machine's ~/.abso/token, which is never used unasked. Before it makes anything, it says what it signs in with.", 125127 run: (args, env) => runInit(args, env), @@ -322,10 +324,10 @@
325− flags: { server: "string", agent: "string", dir: "string", reader: "boolean" },
326− usage: "abso join <project> [--agent <name>] [--dir <folder>] [--reader]",
327+ flags: { server: "string", agent: "string", dir: "string", reader: "boolean", "token-file": "boolean" }, 328+ usage: "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file]", 328− "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused.",
330+ "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused. It says what it signs in with: a new key from this box's sign-in, the folder's key, or ABSO_TOKEN; this machine's ~/.abso/token only with --token-file, never unasked.", --- /dev/null
+++ b/client/test/init-credential.test.ts
@@ -0,0 +1,171 @@
1+// abso init and join sign in with the box sign-in, and use this machine's ~/.abso/token only with --token-file. A 2+// project is never made or joined with a shared credential that happened to be in a file, and both say what they sign 3+// in with. The client runs as its own process with its own home, so nothing on this machine is read. 5+import assert from "node:assert/strict"; 6+import { execFile } from "node:child_process"; 7+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; 8+import { createServer, type IncomingHttpHeaders, type Server } from "node:http"; 9+import type { AddressInfo } from "node:net"; 10+import { tmpdir } from "node:os"; 11+import { join, resolve } from "node:path"; 12+import { after, before, describe, it } from "node:test"; 13+import { parseArgs } from "../src/args.ts"; 14+import { writeBox } from "../src/box.ts"; 15+import { tokenCredential } from "../src/join-commands.ts"; 16+import { type Fake, startFake } from "./fake-server.ts"; 18+const CLIENT = resolve(import.meta.dirname, "..", "abso.ts"); 19+const TOKEN = "file-token-not-secret"; 20+const CREDENTIAL = "abso_bx_box-credential-not-secret"; 22+// Stands in for a server that takes box sign-ins: it notes each request, then answers 500 so the run stops there. 25+const heard: { url: string; headers: IncomingHttpHeaders }[] = []; 26+const dirs: string[] = []; 28+ const dir = mkdtempSync(join(tmpdir(), "abso-test-init-credential-")); 34+ fake = await startFake(0, TOKEN); 35+ boxes = createServer((req, res) => { 36+ heard.push({ url: req.url ?? "", headers: req.headers }); 37+ res.writeHead(500, { "content-type": "application/json" }).end('{"error":"stop here"}'); 39+ await new Promise<void>((done) => boxes.listen(0, "127.0.0.1", done)); 40+ boxesUrl = `http://127.0.0.1:${(boxes.address() as AddressInfo).port}`; 45+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); 48+/** A home holding a token file, and a box sign-in for `boxFor` when given. */ 49+function home(boxFor?: string): string { 51+ mkdirSync(join(dir, ".abso"), { recursive: true }); 52+ writeFileSync(join(dir, ".abso", "token"), `${TOKEN}\n`); 58+ credential: CREDENTIAL, 59+ grant: { projects: [], scopes: [{ kind: "member-all", role: "owner" }] }, 60+ expiresAt: Date.now() + 86_400_000, 71+): Promise<{ code: number; stdout: string; stderr: string }> { 72+ const env: Record<string, string> = { 73+ PATH: process.env.PATH ?? "", 75+ USERPROFILE: homeDir, 76+ AVCS_SERVERS_FILE: "no-servers.json", 77+ ABSO_NO_BROWSER: "1", 79+ if (process.env.CLAUDE_CONFIG_DIR) env.CLAUDE_CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR; 80+ if (process.env.SystemRoot) env.SystemRoot = process.env.SystemRoot; 81+ return new Promise((done) => { 82+ execFile(process.execPath, [CLIENT, ...args], { cwd, env }, (error, stdout, stderr) => 83+ done({ code: typeof error?.code === "number" ? error.code : 0, stdout, stderr }), 88+function folder(): string { 90+ writeFileSync(join(dir, "a.txt"), "hi\n"); 94+const FLAGS = { "token-file": "boolean" } as const; 96+describe("what init and join sign in with", () => { 97+ it("the token file only with --token-file, never into a folder with a key; ABSO_TOKEN as given", () => { 98+ const server = "http://127.0.0.1:1"; 99+ const file = () => TOKEN; 100+ const none = parseArgs("init", [], FLAGS); 101+ const asked = parseArgs("init", ["--token-file"], FLAGS); 102+ assert.equal(tokenCredential(none, {}, server, temp(), file), undefined, "a token file alone is not used"); 103+ assert.deepEqual(tokenCredential(asked, {}, server, temp(), file), { 105+ words: "the token file, ~/.abso/token, as --token-file asks", 107+ assert.throws(() => tokenCredential(asked, {}, server, temp(), () => undefined), /this machine has none/); 108+ const keyed = temp(); 109+ mkdirSync(join(keyed, ".abso")); 110+ writeFileSync(join(keyed, ".abso", "key"), "{}"); 111+ assert.throws(() => tokenCredential(asked, {}, server, keyed, file), /already has a key/); 112+ assert.equal(tokenCredential(none, { ABSO_TOKEN: "env-token" }, server, temp(), file)?.words, "ABSO_TOKEN"); 115+ it("init with a token file and a box sign-in, no flag: signs in with the box, and says so", async () => { 116+ const run = await client(home(boxesUrl), folder(), "init", "--project", "made", "--server", boxesUrl); 117+ assert.match(run.stderr, /Signing in with this box's sign-in, b_0123abcd\./); 118+ assert.ok(heard.length > 0); 120+ heard.every((h) => h.headers.authorization === `Box ${CREDENTIAL}`), 121+ "every request carried the box's sign-in", 124+ heard.every((h) => !String(h.headers.authorization).includes(TOKEN)), 125+ "the token file was never sent", 129+ it("init with only a token file, no flag: refused before anything is made, naming --token-file", async () => { 130+ const run = await client(home(), folder(), "init", "--project", "unasked", "--agent", "me", "--server", fake.url); 131+ assert.notEqual(run.code, 0); 132+ assert.match(run.stderr, /abso login signs it in\. ~\/\.abso\/token is used only with --token-file\./); 133+ const status = await fetch(`${fake.url}/p/unasked/status`, { headers: { authorization: `Bearer ${TOKEN}` } }); 134+ assert.equal(status.status, 404, "no project was made"); 137+ it("init and join with --token-file: sign in with the file, and say so", async () => { 138+ const homeDir = home(); 139+ const made = await client( 151+ assert.equal(made.code, 0, made.stderr); 152+ assert.match(made.stderr, /Signing in with the token file, ~\/\.abso\/token, as --token-file asks\./); 153+ assert.match(made.stdout, /Created project asked/); 154+ const unasked = await client(homeDir, temp(), "join", "asked", "--agent", "other", "--server", fake.url); 155+ assert.notEqual(unasked.code, 0, "join without the flag sends no token"); 156+ assert.match(unasked.stderr, /~\/\.abso\/token is used only with --token-file\./); 157+ const joined = await client( 168+ assert.equal(joined.code, 0, joined.stderr); 169+ assert.match(joined.stderr, /Signing in with the token file/);