import * as fs from 'fs'; import { writeConfigFile } from './config/write'; import * as os from 'os'; import * as path from 'path'; import { DEFAULT_CONFIG } from './config'; import { DEFAULT_API_URL } from './auth/api-url'; // Shared credential + config writer — used by both `node9 login` and the // onboarding `node9 connect`. Writes ~/.node9/credentials.json (profile-merged, // 0o600) and, for the default profile, the ~/.node9/config.json approvers block. // Returns the effective cloud state so callers can print the right message. // One home for this value: the host pin in auth/api-url validates against it, // so a second copy here would let `node9 login` write a URL its own pin rejects. export function writeCredentialsAndConfig( apiKey: string, opts: { profileName?: string; isLocal?: boolean; homeDir?: string } = {} ): { profileName: string; effectiveCloud: boolean | null } { const profileName = opts.profileName || 'default'; const home = opts.homeDir ?? os.homedir(); const credPath = path.join(home, '.node9', 'credentials.json'); if (!fs.existsSync(path.dirname(credPath))) { fs.mkdirSync(path.dirname(credPath), { recursive: true }); } let existingCreds: Record = {}; try { if (fs.existsSync(credPath)) { const raw = JSON.parse(fs.readFileSync(credPath, 'utf-8')) as Record; // Migrate the legacy single-key shape into the profile map. existingCreds = raw.apiKey ? { default: { apiKey: raw.apiKey, apiUrl: raw.apiUrl || DEFAULT_API_URL } } : raw; } } catch { // Corrupt creds file — overwrite rather than fail the login/connect. } // PR-2 §0.1 — the `--local` promise ("all decisions stay on this machine") // is finally PERSISTED where keyedness is decided: getCredentials reads // localOnly and such a machine keeps the LOCAL policy stack (audit/telemetry // still ship on the key). Without this flag the promise evaporated the // moment replace-mode keyed on the bare apiKey. existingCreds[profileName] = { apiKey, apiUrl: DEFAULT_API_URL, ...(opts.isLocal ? { localOnly: true } : {}), }; fs.writeFileSync(credPath, JSON.stringify(existingCreds, null, 2), { mode: 0o600, }); // The approvers block lives on the default profile only. let effectiveCloud: boolean | null = null; if (profileName === 'default') { const configPath = path.join(home, '.node9', 'config.json'); // ONE approvers seed (login-v2 §5, B0). Defaults derive from DEFAULT_CONFIG // so an init-written config and a login-written config can never disagree // again — the old dual seed plus preserve-on-login locked cloud:false // forever for anyone who ran `init` before `login`. // // `cloud` is ALWAYS set from the caller's intent: connecting a machine to // the cloud MEANS cloud approvals unless --local says otherwise. A stale // seeded value must not win; --local remains the explicit off switch. // // The legacy `browser` approver (local dashboard removed in v3) is dropped // from the block on every write so it stops resurfacing in configs. const seed = () => writeConfigFile(configPath, (config) => { const s = (config.settings ??= {}); const existing = (s.approvers ?? {}) as Record; const d = DEFAULT_CONFIG.settings.approvers; s.approvers = { native: typeof existing.native === 'boolean' ? existing.native : d.native, terminal: typeof existing.terminal === 'boolean' ? existing.terminal : d.terminal, cloud: !opts.isLocal, }; }); try { seed(); } catch (err) { // A corrupt config must not fail a login that already saved its key: // move it aside (never delete it) and seed a fresh file. if (!/not valid JSON|not a JSON object/.test((err as Error).message)) throw err; fs.renameSync( configPath, `${configPath}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}` ); seed(); } effectiveCloud = !opts.isLocal; } return { profileName, effectiveCloud }; }