From 1f60a8b28a478129e3cabc954043e78e72c801e8 Mon Sep 17 00:00:00 2001 From: James Easter Date: Tue, 25 Aug 2026 21:44:25 -0500 Subject: [PATCH 1/5] Add a paths-core module that resolves every state path through ARCQ_HOME. --- lib/paths-core.ts | 49 +++++++++++++++++ test/paths-core.test.ts | 119 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 lib/paths-core.ts create mode 100644 test/paths-core.test.ts diff --git a/lib/paths-core.ts b/lib/paths-core.ts new file mode 100644 index 0000000..89d4e5b --- /dev/null +++ b/lib/paths-core.ts @@ -0,0 +1,49 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +// Every arcq state path is resolved here, and resolved on each call rather than +// captured in a module-level constant, so an environment change made after +// import is honored. +// +// ARCQ_HOME isolates a complete set of state - config, context, cache, token, +// OAuth credential, token metadata - as a unit. Isolating only the config, as +// ARCQ_CONFIG does on its own, still leaves the token shared, which means a +// token minted for one portal gets sent to whatever host the queried service +// lives on. +export function resolveStateDir(): string { + return process.env.ARCQ_HOME || os.homedir(); +} + +// ARCQ_CONFIG names a single file and keeps precedence over ARCQ_HOME, so +// existing setups that point it at a shared config keep working unchanged. +export function resolveConfigPath(): string { + return process.env.ARCQ_CONFIG || path.join(resolveStateDir(), '.arcq.json'); +} + +export function resolveContextPath(): string { + return path.join(resolveStateDir(), '.arcq-context.json'); +} + +export function resolveCachePath(): string { + return path.join(resolveStateDir(), '.arcq-cache.json'); +} + +export function resolveTokenPath(): string { + return path.join(resolveStateDir(), '.arcq-token'); +} + +export function resolveOAuthPath(): string { + return path.join(resolveStateDir(), '.arcq-oauth.json'); +} + +export function resolveTokenMetaPath(): string { + return path.join(resolveStateDir(), '.arcq-token-meta.json'); +} + +// A custom ARCQ_HOME need not exist yet, so every write path calls this first. +// Mode 0700 because the directory holds files written 0600. +export function ensureStateDir(): void { + const dir = resolveStateDir(); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); +} diff --git a/test/paths-core.test.ts b/test/paths-core.test.ts new file mode 100644 index 0000000..d723f9f --- /dev/null +++ b/test/paths-core.test.ts @@ -0,0 +1,119 @@ +import * as chai from 'chai'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { + ensureStateDir, + resolveCachePath, + resolveConfigPath, + resolveContextPath, + resolveOAuthPath, + resolveStateDir, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; + +const { expect } = chai; + +// name -> resolver, so the "defaults to ~" and "follows ARCQ_HOME" cases can be +// asserted for every state file rather than a representative one. +const RESOLVERS: Array<[string, () => string]> = [ + ['.arcq.json', resolveConfigPath], + ['.arcq-context.json', resolveContextPath], + ['.arcq-cache.json', resolveCachePath], + ['.arcq-token', resolveTokenPath], + ['.arcq-oauth.json', resolveOAuthPath], + ['.arcq-token-meta.json', resolveTokenMetaPath], +]; + +describe('paths-core', () => { + let originalHome: string | undefined; + let originalConfig: string | undefined; + let tempDir: string; + + beforeEach(() => { + originalHome = process.env.ARCQ_HOME; + originalConfig = process.env.ARCQ_CONFIG; + delete process.env.ARCQ_HOME; + delete process.env.ARCQ_CONFIG; + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcq-paths-')); + }); + + afterEach(() => { + if (originalHome === undefined) delete process.env.ARCQ_HOME; + else process.env.ARCQ_HOME = originalHome; + if (originalConfig === undefined) delete process.env.ARCQ_CONFIG; + else process.env.ARCQ_CONFIG = originalConfig; + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + describe('resolveStateDir', () => { + it('returns the home directory when ARCQ_HOME is unset', () => { + expect(resolveStateDir()).to.equal(os.homedir()); + }); + + it('returns ARCQ_HOME when it is set', () => { + process.env.ARCQ_HOME = tempDir; + expect(resolveStateDir()).to.equal(tempDir); + }); + }); + + for (const [name, resolve] of RESOLVERS) { + describe(`resolver for ${name}`, () => { + it('resolves under the home directory by default', () => { + expect(resolve()).to.equal(path.join(os.homedir(), name)); + }); + + it('resolves under ARCQ_HOME when it is set', () => { + process.env.ARCQ_HOME = tempDir; + expect(resolve()).to.equal(path.join(tempDir, name)); + }); + + // The defect this module fixes: the old module-level constants captured + // the path at import time, so an env change made afterwards was ignored. + it('observes an ARCQ_HOME change made after import', () => { + const before = resolve(); + process.env.ARCQ_HOME = tempDir; + expect(resolve()).to.not.equal(before); + expect(resolve()).to.equal(path.join(tempDir, name)); + }); + }); + } + + describe('resolveConfigPath', () => { + it('prefers ARCQ_CONFIG over ARCQ_HOME', () => { + const explicit = path.join(tempDir, 'explicit.json'); + process.env.ARCQ_HOME = tempDir; + process.env.ARCQ_CONFIG = explicit; + expect(resolveConfigPath()).to.equal(explicit); + }); + + it('falls back to $ARCQ_HOME/.arcq.json when only ARCQ_HOME is set', () => { + process.env.ARCQ_HOME = tempDir; + expect(resolveConfigPath()).to.equal(path.join(tempDir, '.arcq.json')); + }); + }); + + describe('ensureStateDir', () => { + it('creates a missing state directory with mode 0700', () => { + const missing = path.join(tempDir, 'nested', 'state'); + process.env.ARCQ_HOME = missing; + ensureStateDir(); + expect(fs.existsSync(missing)).to.equal(true); + expect(fs.statSync(missing).mode & 0o777).to.equal(0o700); + }); + + it('leaves an existing directory alone', () => { + const marker = path.join(tempDir, 'marker'); + fs.writeFileSync(marker, 'kept'); + process.env.ARCQ_HOME = tempDir; + ensureStateDir(); + expect(fs.readFileSync(marker, 'utf-8')).to.equal('kept'); + }); + + it('is a no-op for the default home directory', () => { + ensureStateDir(); + expect(fs.existsSync(os.homedir())).to.equal(true); + }); + }); +}); From 9c046d9c13e278048ac3aaa292b79ee5a1185bf6 Mon Sep 17 00:00:00 2001 From: James Easter Date: Tue, 25 Aug 2026 21:46:04 -0500 Subject: [PATCH 2/5] Resolve every state file through paths-core so ARCQ_HOME isolates all six. --- lib/cache-core.ts | 13 +++---- lib/config-core.ts | 8 ++-- lib/context-core.ts | 13 +++---- lib/help-cmd.ts | 2 +- lib/oauth-core.ts | 24 +++++++----- lib/token-connect-cmd.ts | 5 ++- lib/token-core.ts | 8 ++-- test/active-cmd.test.ts | 20 +++++----- test/bin.test.ts | 14 +++---- test/cache-core.test.ts | 33 +++++++++-------- test/context-core.test.ts | 37 ++++++++++--------- test/fields-cmd.test.ts | 63 +++++++++++++++++--------------- test/index.test.ts | 15 ++++---- test/interactive-cmd.test.ts | 31 ++++++++-------- test/list-cmd.test.ts | 46 ++++++++++++----------- test/oauth-core.test.ts | 43 +++++++++++++--------- test/query-cmd.test.ts | 67 +++++++++++++++++++--------------- test/refresh-cmd.test.ts | 30 +++++++-------- test/sync-cmd.test.ts | 16 ++++---- test/token-cmd.test.ts | 26 +++++++------ test/token-connect-cmd.test.ts | 22 ++++++----- test/token-core.test.ts | 43 +++++++++++++--------- test/token-refresh-cmd.test.ts | 21 ++++++++--- 23 files changed, 328 insertions(+), 272 deletions(-) diff --git a/lib/cache-core.ts b/lib/cache-core.ts index a9a28ee..0c686d2 100644 --- a/lib/cache-core.ts +++ b/lib/cache-core.ts @@ -1,15 +1,14 @@ import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import { ensureStateDir, resolveCachePath } from './paths-core.js'; import type { Cache } from './types.js'; -export const CACHE_PATH = path.join(os.homedir(), '.arcq-cache.json'); - export function loadCache(): Cache { - if (!fs.existsSync(CACHE_PATH)) return {}; - return JSON.parse(fs.readFileSync(CACHE_PATH, 'utf-8')) as Cache; + const cachePath = resolveCachePath(); + if (!fs.existsSync(cachePath)) return {}; + return JSON.parse(fs.readFileSync(cachePath, 'utf-8')) as Cache; } export function saveCache(cache: Cache): void { - fs.writeFileSync(CACHE_PATH, JSON.stringify(cache, null, 2)); + ensureStateDir(); + fs.writeFileSync(resolveCachePath(), JSON.stringify(cache, null, 2)); } diff --git a/lib/config-core.ts b/lib/config-core.ts index b2bc127..b5cf323 100644 --- a/lib/config-core.ts +++ b/lib/config-core.ts @@ -1,11 +1,8 @@ import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import { ensureStateDir, resolveConfigPath } from './paths-core.js'; import type { Config } from './types.js'; -export function resolveConfigPath(): string { - return process.env.ARCQ_CONFIG || path.join(os.homedir(), '.arcq.json'); -} +export { resolveConfigPath }; export function loadConfig(): Config { const configPath = resolveConfigPath(); @@ -18,5 +15,6 @@ export function loadConfig(): Config { } export function saveConfig(config: Config): void { + ensureStateDir(); fs.writeFileSync(resolveConfigPath(), JSON.stringify(config, null, 2)); } diff --git a/lib/context-core.ts b/lib/context-core.ts index 5db9b8b..31f7cac 100644 --- a/lib/context-core.ts +++ b/lib/context-core.ts @@ -1,15 +1,14 @@ import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import { ensureStateDir, resolveContextPath } from './paths-core.js'; import type { Context } from './types.js'; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); - export function loadContext(): Context | null { - if (!fs.existsSync(CONTEXT_PATH)) return null; - return JSON.parse(fs.readFileSync(CONTEXT_PATH, 'utf-8')) as Context; + const contextPath = resolveContextPath(); + if (!fs.existsSync(contextPath)) return null; + return JSON.parse(fs.readFileSync(contextPath, 'utf-8')) as Context; } export function saveContext(ctx: Context): void { - fs.writeFileSync(CONTEXT_PATH, JSON.stringify(ctx, null, 2)); + ensureStateDir(); + fs.writeFileSync(resolveContextPath(), JSON.stringify(ctx, null, 2)); } diff --git a/lib/help-cmd.ts b/lib/help-cmd.ts index bae752a..92beabb 100644 --- a/lib/help-cmd.ts +++ b/lib/help-cmd.ts @@ -1,4 +1,4 @@ -import { resolveConfigPath } from './config-core.js'; +import { resolveConfigPath } from './paths-core.js'; export default function helpCmd(): void { console.log(` diff --git a/lib/oauth-core.ts b/lib/oauth-core.ts index 87d59cb..b91019f 100644 --- a/lib/oauth-core.ts +++ b/lib/oauth-core.ts @@ -1,19 +1,19 @@ import { execSync } from 'child_process'; import fs from 'fs'; -import os from 'os'; -import path from 'path'; import { requestOAuthToken } from './arcgis-core.js'; import { ArcqError } from './errors.js'; +import { + ensureStateDir, + resolveOAuthPath, + resolveTokenMetaPath, +} from './paths-core.js'; import { getToken, setTokenValue } from './token-core.js'; import type { OAuthTokenError, OAuthTokenResponse } from './types.js'; // OAuth credentials live in their own file, separate from the plain access -// token in ~/.arcq-token, so the token file's format stays backward compatible. -export const oauthPath = path.join(os.homedir(), '.arcq-oauth.json'); - -// The access token's expiry is tracked alongside it so `token show` can report -// how much life is left without decoding the (opaque) token itself. -export const tokenMetaPath = path.join(os.homedir(), '.arcq-token-meta.json'); +// token in .arcq-token, so the token file's format stays backward compatible. +// The access token's expiry is tracked in a third file so `token show` can +// report how much life is left without decoding the (opaque) token itself. export interface OAuthConfig { portalUrl: string; @@ -37,7 +37,7 @@ export interface TokenMeta { export function loadOAuth(): OAuthConfig | null { try { const parsed = JSON.parse( - fs.readFileSync(oauthPath, 'utf-8') + fs.readFileSync(resolveOAuthPath(), 'utf-8') ) as OAuthConfig; if ( !parsed || @@ -55,6 +55,8 @@ export function loadOAuth(): OAuthConfig | null { export function saveOAuth(config: OAuthConfig): void { // Same secret-hygiene as setTokenValue: owner-only, and re-tightened in case // the file already existed with looser permissions. + ensureStateDir(); + const oauthPath = resolveOAuthPath(); fs.writeFileSync(oauthPath, JSON.stringify(config, null, 2), { mode: 0o600 }); fs.chmodSync(oauthPath, 0o600); } @@ -62,7 +64,7 @@ export function saveOAuth(config: OAuthConfig): void { export function loadTokenMeta(): TokenMeta | null { try { const parsed = JSON.parse( - fs.readFileSync(tokenMetaPath, 'utf-8') + fs.readFileSync(resolveTokenMetaPath(), 'utf-8') ) as TokenMeta; if (!parsed || typeof parsed.expires !== 'number') return null; return parsed; @@ -72,6 +74,8 @@ export function loadTokenMeta(): TokenMeta | null { } export function saveTokenMeta(meta: TokenMeta): void { + ensureStateDir(); + const tokenMetaPath = resolveTokenMetaPath(); fs.writeFileSync(tokenMetaPath, JSON.stringify(meta), { mode: 0o600 }); fs.chmodSync(tokenMetaPath, 0o600); } diff --git a/lib/token-connect-cmd.ts b/lib/token-connect-cmd.ts index 8683b55..9e4d2e1 100644 --- a/lib/token-connect-cmd.ts +++ b/lib/token-connect-cmd.ts @@ -4,13 +4,13 @@ import { loadContext } from './context-core.js'; import { ArcqError } from './errors.js'; import { makePrompter } from './prompt-core.js'; import { - oauthPath, parseEsriOAuthBlob, performRefresh, saveOAuth, type OAuthConfig, type RefreshResult, } from './oauth-core.js'; +import { resolveOAuthPath } from './paths-core.js'; import { getToken } from './token-core.js'; export interface ConnectDeps { @@ -153,6 +153,9 @@ async function runConnect( // Save, then validate. On failure, restore whatever oauth file was there // before so a botched connect never clobbers a working setup. + // Resolved once so the backup and the restore below cannot target different + // files if the environment changes mid-command. + const oauthPath = resolveOAuthPath(); const prior = fs.existsSync(oauthPath) ? fs.readFileSync(oauthPath, 'utf-8') : null; diff --git a/lib/token-core.ts b/lib/token-core.ts index a0d77af..ca70427 100644 --- a/lib/token-core.ts +++ b/lib/token-core.ts @@ -1,10 +1,8 @@ import fs from 'fs'; -import os from 'os'; -import path from 'path'; - -export const tokenPath = path.join(os.homedir(), '.arcq-token'); +import { ensureStateDir, resolveTokenPath } from './paths-core.js'; export function getToken(): string | null { + const tokenPath = resolveTokenPath(); if (fs.existsSync(tokenPath)) { return fs.readFileSync(tokenPath, 'utf-8').trim(); } @@ -15,6 +13,8 @@ export function setTokenValue(token: string): void { // The token is a secret: keep it readable only by the owner. writeFileSync's // `mode` applies only when creating the file, so chmod afterwards to also // tighten a pre-existing file written with looser permissions. + ensureStateDir(); + const tokenPath = resolveTokenPath(); fs.writeFileSync(tokenPath, token.trim(), { mode: 0o600 }); fs.chmodSync(tokenPath, 0o600); } diff --git a/test/active-cmd.test.ts b/test/active-cmd.test.ts index fa6fde9..2d95db8 100644 --- a/test/active-cmd.test.ts +++ b/test/active-cmd.test.ts @@ -1,28 +1,26 @@ import * as chai from 'chai'; import fs from 'fs'; -import path from 'path'; -import os from 'os'; import activeCmd from '../lib/active-cmd.js'; import type { Context } from '../lib/types.js'; +import { resolveContextPath } from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); - describe('active-cmd', () => { let contextBackup: string | null; let logs: string[]; let originalLog: typeof console.log; function setContext(ctx: Context) { - fs.writeFileSync(CONTEXT_PATH, JSON.stringify(ctx)); + fs.writeFileSync(resolveContextPath(), JSON.stringify(ctx)); } beforeEach(() => { - contextBackup = fs.existsSync(CONTEXT_PATH) - ? fs.readFileSync(CONTEXT_PATH, 'utf-8') + contextBackup = fs.existsSync(resolveContextPath()) + ? fs.readFileSync(resolveContextPath(), 'utf-8') : null; - if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH); + if (fs.existsSync(resolveContextPath())) + fs.unlinkSync(resolveContextPath()); logs = []; originalLog = console.log; @@ -33,9 +31,9 @@ describe('active-cmd', () => { console.log = originalLog; if (contextBackup !== null) { - fs.writeFileSync(CONTEXT_PATH, contextBackup); - } else if (fs.existsSync(CONTEXT_PATH)) { - fs.unlinkSync(CONTEXT_PATH); + fs.writeFileSync(resolveContextPath(), contextBackup); + } else if (fs.existsSync(resolveContextPath())) { + fs.unlinkSync(resolveContextPath()); } }); diff --git a/test/bin.test.ts b/test/bin.test.ts index f026385..2719a2e 100644 --- a/test/bin.test.ts +++ b/test/bin.test.ts @@ -5,7 +5,7 @@ import http from 'http'; import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; -import { tokenPath } from '../lib/token-core.js'; +import { resolveTokenPath } from '../lib/paths-core.js'; const { expect } = chai; @@ -81,17 +81,17 @@ describe('bin/arcq', function () { }); beforeEach(() => { - tokenBackup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + tokenBackup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); }); afterEach(() => { if (tokenBackup !== null) { - fs.writeFileSync(tokenPath, tokenBackup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), tokenBackup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } }); diff --git a/test/cache-core.test.ts b/test/cache-core.test.ts index 39c93f8..923659a 100644 --- a/test/cache-core.test.ts +++ b/test/cache-core.test.ts @@ -1,7 +1,8 @@ import * as chai from 'chai'; import fs from 'fs'; -import { CACHE_PATH, loadCache, saveCache } from '../lib/cache-core.js'; +import { loadCache, saveCache } from '../lib/cache-core.js'; import type { Cache } from '../lib/types.js'; +import { resolveCachePath } from '../lib/paths-core.js'; const { expect } = chai; @@ -9,17 +10,17 @@ describe('cache-core', () => { let backup: string | null; beforeEach(() => { - backup = fs.existsSync(CACHE_PATH) - ? fs.readFileSync(CACHE_PATH, 'utf-8') + backup = fs.existsSync(resolveCachePath()) + ? fs.readFileSync(resolveCachePath(), 'utf-8') : null; - if (fs.existsSync(CACHE_PATH)) fs.unlinkSync(CACHE_PATH); + if (fs.existsSync(resolveCachePath())) fs.unlinkSync(resolveCachePath()); }); afterEach(() => { if (backup !== null) { - fs.writeFileSync(CACHE_PATH, backup); - } else if (fs.existsSync(CACHE_PATH)) { - fs.unlinkSync(CACHE_PATH); + fs.writeFileSync(resolveCachePath(), backup); + } else if (fs.existsSync(resolveCachePath())) { + fs.unlinkSync(resolveCachePath()); } }); @@ -30,27 +31,27 @@ describe('cache-core', () => { it('returns the parsed cache when the file exists', () => { const data = { 'my-service': [{ id: 0, name: 'Parcels' }] }; - fs.writeFileSync(CACHE_PATH, JSON.stringify(data)); + fs.writeFileSync(resolveCachePath(), JSON.stringify(data)); expect(loadCache()).to.deep.equal(data); }); }); describe('saveCache', () => { - it('writes the cache as JSON to CACHE_PATH', () => { + it('writes the cache as JSON to resolveCachePath()', () => { const data = { 'my-service': [{ id: 0, name: 'Parcels' }] }; saveCache(data as unknown as Cache); - expect(JSON.parse(fs.readFileSync(CACHE_PATH, 'utf-8'))).to.deep.equal( - data - ); + expect( + JSON.parse(fs.readFileSync(resolveCachePath(), 'utf-8')) + ).to.deep.equal(data); }); it('overwrites an existing cache file', () => { - fs.writeFileSync(CACHE_PATH, JSON.stringify({ old: [] })); + fs.writeFileSync(resolveCachePath(), JSON.stringify({ old: [] })); const data = { new: [{ id: 1, name: 'Roads' }] }; saveCache(data as unknown as Cache); - expect(JSON.parse(fs.readFileSync(CACHE_PATH, 'utf-8'))).to.deep.equal( - data - ); + expect( + JSON.parse(fs.readFileSync(resolveCachePath(), 'utf-8')) + ).to.deep.equal(data); }); }); diff --git a/test/context-core.test.ts b/test/context-core.test.ts index 3cfdd1d..374f2d3 100644 --- a/test/context-core.test.ts +++ b/test/context-core.test.ts @@ -1,28 +1,26 @@ import * as chai from 'chai'; import fs from 'fs'; -import path from 'path'; -import os from 'os'; import { loadContext, saveContext } from '../lib/context-core.js'; +import { resolveContextPath } from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); - describe('context-core', () => { let backup: string | null; beforeEach(() => { - backup = fs.existsSync(CONTEXT_PATH) - ? fs.readFileSync(CONTEXT_PATH, 'utf-8') + backup = fs.existsSync(resolveContextPath()) + ? fs.readFileSync(resolveContextPath(), 'utf-8') : null; - if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH); + if (fs.existsSync(resolveContextPath())) + fs.unlinkSync(resolveContextPath()); }); afterEach(() => { if (backup !== null) { - fs.writeFileSync(CONTEXT_PATH, backup); - } else if (fs.existsSync(CONTEXT_PATH)) { - fs.unlinkSync(CONTEXT_PATH); + fs.writeFileSync(resolveContextPath(), backup); + } else if (fs.existsSync(resolveContextPath())) { + fs.unlinkSync(resolveContextPath()); } }); @@ -38,13 +36,13 @@ describe('context-core', () => { name: 'Parcels', url: 'https://example.com/0', }; - fs.writeFileSync(CONTEXT_PATH, JSON.stringify(ctx)); + fs.writeFileSync(resolveContextPath(), JSON.stringify(ctx)); expect(loadContext()).to.deep.equal(ctx); }); }); describe('saveContext', () => { - it('writes the context as JSON to CONTEXT_PATH', () => { + it('writes the context as JSON to resolveContextPath()', () => { const ctx = { service: 'svc', layerId: 1, @@ -52,12 +50,17 @@ describe('context-core', () => { url: 'https://example.com/1', }; saveContext(ctx); - const written = JSON.parse(fs.readFileSync(CONTEXT_PATH, 'utf-8')); + const written = JSON.parse( + fs.readFileSync(resolveContextPath(), 'utf-8') + ); expect(written).to.deep.equal(ctx); }); it('overwrites an existing context', () => { - fs.writeFileSync(CONTEXT_PATH, JSON.stringify({ service: 'old' })); + fs.writeFileSync( + resolveContextPath(), + JSON.stringify({ service: 'old' }) + ); const ctx = { service: 'new', layerId: 2, @@ -65,9 +68,9 @@ describe('context-core', () => { url: 'https://example.com/2', }; saveContext(ctx); - expect(JSON.parse(fs.readFileSync(CONTEXT_PATH, 'utf-8'))).to.deep.equal( - ctx - ); + expect( + JSON.parse(fs.readFileSync(resolveContextPath(), 'utf-8')) + ).to.deep.equal(ctx); }); }); diff --git a/test/fields-cmd.test.ts b/test/fields-cmd.test.ts index 5c52daa..7031eb4 100644 --- a/test/fields-cmd.test.ts +++ b/test/fields-cmd.test.ts @@ -3,15 +3,18 @@ import fs from 'fs'; import path from 'path'; import os from 'os'; import http from 'http'; -import { tokenPath } from '../lib/token-core.js'; -import { oauthPath, tokenMetaPath } from '../lib/oauth-core.js'; import fieldsCmd from '../lib/fields-cmd.js'; import { ArcqError } from '../lib/errors.js'; import type { Context } from '../lib/types.js'; +import { + resolveContextPath, + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-fields-config.json'); const SERVER_FIELDS = [ @@ -63,7 +66,7 @@ describe('fields-cmd', () => { } function setContext(ctx: Context) { - fs.writeFileSync(CONTEXT_PATH, JSON.stringify(ctx)); + fs.writeFileSync(resolveContextPath(), JSON.stringify(ctx)); } function writeConfig(layers: Record) { @@ -103,25 +106,27 @@ describe('fields-cmd', () => { delete process.env.ARCQ_CONFIG; if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - contextBackup = fs.existsSync(CONTEXT_PATH) - ? fs.readFileSync(CONTEXT_PATH, 'utf-8') + contextBackup = fs.existsSync(resolveContextPath()) + ? fs.readFileSync(resolveContextPath(), 'utf-8') : null; - tokenBackup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + tokenBackup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; // Isolate the developer's real OAuth setup: with it present, the exit-2 // path would trigger a real credential-command run and portal request. - oauthBackup = fs.existsSync(oauthPath) - ? fs.readFileSync(oauthPath, 'utf-8') + oauthBackup = fs.existsSync(resolveOAuthPath()) + ? fs.readFileSync(resolveOAuthPath(), 'utf-8') : null; - tokenMetaBackup = fs.existsSync(tokenMetaPath) - ? fs.readFileSync(tokenMetaPath, 'utf-8') + tokenMetaBackup = fs.existsSync(resolveTokenMetaPath()) + ? fs.readFileSync(resolveTokenMetaPath(), 'utf-8') : null; - if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH); - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); - if (fs.existsSync(oauthPath)) fs.unlinkSync(oauthPath); - if (fs.existsSync(tokenMetaPath)) fs.unlinkSync(tokenMetaPath); + if (fs.existsSync(resolveContextPath())) + fs.unlinkSync(resolveContextPath()); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); + if (fs.existsSync(resolveOAuthPath())) fs.unlinkSync(resolveOAuthPath()); + if (fs.existsSync(resolveTokenMetaPath())) + fs.unlinkSync(resolveTokenMetaPath()); logs = []; originalLog = console.log; @@ -139,27 +144,27 @@ describe('fields-cmd', () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); if (contextBackup !== null) { - fs.writeFileSync(CONTEXT_PATH, contextBackup); - } else if (fs.existsSync(CONTEXT_PATH)) { - fs.unlinkSync(CONTEXT_PATH); + fs.writeFileSync(resolveContextPath(), contextBackup); + } else if (fs.existsSync(resolveContextPath())) { + fs.unlinkSync(resolveContextPath()); } if (tokenBackup !== null) { - fs.writeFileSync(tokenPath, tokenBackup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), tokenBackup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } if (oauthBackup !== null) { - fs.writeFileSync(oauthPath, oauthBackup); - } else if (fs.existsSync(oauthPath)) { - fs.unlinkSync(oauthPath); + fs.writeFileSync(resolveOAuthPath(), oauthBackup); + } else if (fs.existsSync(resolveOAuthPath())) { + fs.unlinkSync(resolveOAuthPath()); } if (tokenMetaBackup !== null) { - fs.writeFileSync(tokenMetaPath, tokenMetaBackup); - } else if (fs.existsSync(tokenMetaPath)) { - fs.unlinkSync(tokenMetaPath); + fs.writeFileSync(resolveTokenMetaPath(), tokenMetaBackup); + } else if (fs.existsSync(resolveTokenMetaPath())) { + fs.unlinkSync(resolveTokenMetaPath()); } }); @@ -181,7 +186,7 @@ describe('fields-cmd', () => { }); it('sends f=json and the stored token', async () => { - fs.writeFileSync(tokenPath, 'my-token'); + fs.writeFileSync(resolveTokenPath(), 'my-token'); setContext({ url: baseUrl }); await fieldsCmd([]); const params = (requests[0] as unknown as { bodyParams: URLSearchParams }) diff --git a/test/index.test.ts b/test/index.test.ts index 081df0c..07cf9e5 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -5,10 +5,10 @@ import os from 'os'; import { run, resolveInsecure } from '../index.js'; import { getHttpsAgent } from '../lib/tls-core.js'; import { ArcqError } from '../lib/errors.js'; +import { resolveContextPath } from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-index-test-config.json'); describe('index', () => { @@ -76,17 +76,18 @@ describe('index', () => { let contextBackup: string | null; beforeEach(() => { - contextBackup = fs.existsSync(CONTEXT_PATH) - ? fs.readFileSync(CONTEXT_PATH, 'utf-8') + contextBackup = fs.existsSync(resolveContextPath()) + ? fs.readFileSync(resolveContextPath(), 'utf-8') : null; - if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH); + if (fs.existsSync(resolveContextPath())) + fs.unlinkSync(resolveContextPath()); }); afterEach(() => { if (contextBackup !== null) { - fs.writeFileSync(CONTEXT_PATH, contextBackup); - } else if (fs.existsSync(CONTEXT_PATH)) { - fs.unlinkSync(CONTEXT_PATH); + fs.writeFileSync(resolveContextPath(), contextBackup); + } else if (fs.existsSync(resolveContextPath())) { + fs.unlinkSync(resolveContextPath()); } }); diff --git a/test/interactive-cmd.test.ts b/test/interactive-cmd.test.ts index ced8d21..f3ec4fc 100644 --- a/test/interactive-cmd.test.ts +++ b/test/interactive-cmd.test.ts @@ -2,15 +2,15 @@ import * as chai from 'chai'; import fs from 'fs'; import path from 'path'; import os from 'os'; -import { CACHE_PATH, saveCache } from '../lib/cache-core.js'; +import { saveCache } from '../lib/cache-core.js'; import { loadContext } from '../lib/context-core.js'; import interactiveCmd from '../lib/interactive-cmd.js'; import { ArcqError } from '../lib/errors.js'; import type { Cache } from '../lib/types.js'; +import { resolveCachePath, resolveContextPath } from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-use-config.json'); // Fake fzf: if ARCQ_TEST_SELECT is set, grep for that string; otherwise head -1. @@ -54,14 +54,15 @@ describe('interactive-cmd', () => { }); beforeEach(() => { - cacheBackup = fs.existsSync(CACHE_PATH) - ? fs.readFileSync(CACHE_PATH, 'utf-8') + cacheBackup = fs.existsSync(resolveCachePath()) + ? fs.readFileSync(resolveCachePath(), 'utf-8') : null; - contextBackup = fs.existsSync(CONTEXT_PATH) - ? fs.readFileSync(CONTEXT_PATH, 'utf-8') + contextBackup = fs.existsSync(resolveContextPath()) + ? fs.readFileSync(resolveContextPath(), 'utf-8') : null; - if (fs.existsSync(CACHE_PATH)) fs.unlinkSync(CACHE_PATH); - if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH); + if (fs.existsSync(resolveCachePath())) fs.unlinkSync(resolveCachePath()); + if (fs.existsSync(resolveContextPath())) + fs.unlinkSync(resolveContextPath()); originalPath = process.env.PATH; process.env.PATH = `${FAKE_FZF_DIR}:${process.env.PATH}`; @@ -84,15 +85,15 @@ describe('interactive-cmd', () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); if (cacheBackup !== null) { - fs.writeFileSync(CACHE_PATH, cacheBackup); - } else if (fs.existsSync(CACHE_PATH)) { - fs.unlinkSync(CACHE_PATH); + fs.writeFileSync(resolveCachePath(), cacheBackup); + } else if (fs.existsSync(resolveCachePath())) { + fs.unlinkSync(resolveCachePath()); } if (contextBackup !== null) { - fs.writeFileSync(CONTEXT_PATH, contextBackup); - } else if (fs.existsSync(CONTEXT_PATH)) { - fs.unlinkSync(CONTEXT_PATH); + fs.writeFileSync(resolveContextPath(), contextBackup); + } else if (fs.existsSync(resolveContextPath())) { + fs.unlinkSync(resolveContextPath()); } }); @@ -140,7 +141,7 @@ describe('interactive-cmd', () => { it('overwrites an existing context', async () => { fs.writeFileSync( - CONTEXT_PATH, + resolveContextPath(), JSON.stringify({ service: 'old', layerId: 99, diff --git a/test/list-cmd.test.ts b/test/list-cmd.test.ts index 78e4411..fae6723 100644 --- a/test/list-cmd.test.ts +++ b/test/list-cmd.test.ts @@ -3,9 +3,12 @@ import fs from 'fs'; import path from 'path'; import os from 'os'; import http from 'http'; -import { tokenPath } from '../lib/token-core.js'; -import { oauthPath, tokenMetaPath } from '../lib/oauth-core.js'; import listCmd from '../lib/list-cmd.js'; +import { + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; @@ -65,21 +68,22 @@ describe('list-cmd', () => { delete process.env.ARCQ_CONFIG; if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - tokenBackup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + tokenBackup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); // Isolate the developer's real OAuth setup: with it present, the exit-2 // path would trigger a real credential-command run and portal request. - oauthBackup = fs.existsSync(oauthPath) - ? fs.readFileSync(oauthPath, 'utf-8') + oauthBackup = fs.existsSync(resolveOAuthPath()) + ? fs.readFileSync(resolveOAuthPath(), 'utf-8') : null; - tokenMetaBackup = fs.existsSync(tokenMetaPath) - ? fs.readFileSync(tokenMetaPath, 'utf-8') + tokenMetaBackup = fs.existsSync(resolveTokenMetaPath()) + ? fs.readFileSync(resolveTokenMetaPath(), 'utf-8') : null; - if (fs.existsSync(oauthPath)) fs.unlinkSync(oauthPath); - if (fs.existsSync(tokenMetaPath)) fs.unlinkSync(tokenMetaPath); + if (fs.existsSync(resolveOAuthPath())) fs.unlinkSync(resolveOAuthPath()); + if (fs.existsSync(resolveTokenMetaPath())) + fs.unlinkSync(resolveTokenMetaPath()); logs = []; originalLog = console.log; @@ -97,21 +101,21 @@ describe('list-cmd', () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); if (tokenBackup !== null) { - fs.writeFileSync(tokenPath, tokenBackup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), tokenBackup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } if (oauthBackup !== null) { - fs.writeFileSync(oauthPath, oauthBackup); - } else if (fs.existsSync(oauthPath)) { - fs.unlinkSync(oauthPath); + fs.writeFileSync(resolveOAuthPath(), oauthBackup); + } else if (fs.existsSync(resolveOAuthPath())) { + fs.unlinkSync(resolveOAuthPath()); } if (tokenMetaBackup !== null) { - fs.writeFileSync(tokenMetaPath, tokenMetaBackup); - } else if (fs.existsSync(tokenMetaPath)) { - fs.unlinkSync(tokenMetaPath); + fs.writeFileSync(resolveTokenMetaPath(), tokenMetaBackup); + } else if (fs.existsSync(resolveTokenMetaPath())) { + fs.unlinkSync(resolveTokenMetaPath()); } }); @@ -148,7 +152,7 @@ describe('list-cmd', () => { }); it('includes the stored token in the request', async () => { - fs.writeFileSync(tokenPath, 'test-token-abc'); + fs.writeFileSync(resolveTokenPath(), 'test-token-abc'); await listCmd([serviceUrl]); const params = (requests[0] as unknown as { bodyParams: URLSearchParams }) .bodyParams; diff --git a/test/oauth-core.test.ts b/test/oauth-core.test.ts index 13ac6dd..c3fbdb1 100644 --- a/test/oauth-core.test.ts +++ b/test/oauth-core.test.ts @@ -1,10 +1,8 @@ import * as chai from 'chai'; import fs from 'fs'; -import { tokenPath, getToken } from '../lib/token-core.js'; +import { getToken } from '../lib/token-core.js'; import { ArcqError } from '../lib/errors.js'; import { - oauthPath, - tokenMetaPath, loadOAuth, saveOAuth, loadTokenMeta, @@ -17,6 +15,11 @@ import { type OAuthConfig, } from '../lib/oauth-core.js'; import type { OAuthTokenResponse } from '../lib/types.js'; +import { + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; @@ -40,18 +43,22 @@ describe('oauth-core', () => { } beforeEach(() => { - oauthBackup = snapshot(oauthPath); - metaBackup = snapshot(tokenMetaPath); - tokenBackup = snapshot(tokenPath); - for (const p of [oauthPath, tokenMetaPath, tokenPath]) { + oauthBackup = snapshot(resolveOAuthPath()); + metaBackup = snapshot(resolveTokenMetaPath()); + tokenBackup = snapshot(resolveTokenPath()); + for (const p of [ + resolveOAuthPath(), + resolveTokenMetaPath(), + resolveTokenPath(), + ]) { if (fs.existsSync(p)) fs.unlinkSync(p); } }); afterEach(() => { - restore(oauthPath, oauthBackup); - restore(tokenMetaPath, metaBackup); - restore(tokenPath, tokenBackup); + restore(resolveOAuthPath(), oauthBackup); + restore(resolveTokenMetaPath(), metaBackup); + restore(resolveTokenPath(), tokenBackup); }); describe('oauth storage', () => { @@ -67,14 +74,14 @@ describe('oauth-core', () => { it('writes the oauth file with mode 600', () => { saveOAuth({ portalUrl: 'https://portal.example.com', appId: 'a' }); - expect(fs.statSync(oauthPath).mode & 0o777).to.equal(0o600); + expect(fs.statSync(resolveOAuthPath()).mode & 0o777).to.equal(0o600); }); it('tightens a pre-existing loosely-permissioned file to 600', () => { - fs.writeFileSync(oauthPath, '{}', { mode: 0o644 }); - fs.chmodSync(oauthPath, 0o644); + fs.writeFileSync(resolveOAuthPath(), '{}', { mode: 0o644 }); + fs.chmodSync(resolveOAuthPath(), 0o644); saveOAuth({ portalUrl: 'https://portal.example.com', appId: 'a' }); - expect(fs.statSync(oauthPath).mode & 0o777).to.equal(0o600); + expect(fs.statSync(resolveOAuthPath()).mode & 0o777).to.equal(0o600); }); it('treats a missing file as not configured', () => { @@ -83,12 +90,12 @@ describe('oauth-core', () => { }); it('treats a corrupt file as not configured', () => { - fs.writeFileSync(oauthPath, 'not json {'); + fs.writeFileSync(resolveOAuthPath(), 'not json {'); expect(loadOAuth()).to.be.null; }); it('treats a file missing required fields as not configured', () => { - fs.writeFileSync(oauthPath, JSON.stringify({ appId: 'a' })); + fs.writeFileSync(resolveOAuthPath(), JSON.stringify({ appId: 'a' })); expect(loadOAuth()).to.be.null; }); @@ -106,7 +113,7 @@ describe('oauth-core', () => { it('writes the meta file with mode 600', () => { saveTokenMeta({ expires: 1 }); - expect(fs.statSync(tokenMetaPath).mode & 0o777).to.equal(0o600); + expect(fs.statSync(resolveTokenMetaPath()).mode & 0o777).to.equal(0o600); }); it('treats a missing meta file as absent', () => { @@ -114,7 +121,7 @@ describe('oauth-core', () => { }); it('treats corrupt meta as absent', () => { - fs.writeFileSync(tokenMetaPath, 'nope'); + fs.writeFileSync(resolveTokenMetaPath(), 'nope'); expect(loadTokenMeta()).to.be.null; }); }); diff --git a/test/query-cmd.test.ts b/test/query-cmd.test.ts index d07a7dc..7e91195 100644 --- a/test/query-cmd.test.ts +++ b/test/query-cmd.test.ts @@ -3,15 +3,20 @@ import fs from 'fs'; import path from 'path'; import os from 'os'; import http from 'http'; -import { tokenPath, getToken } from '../lib/token-core.js'; -import { oauthPath, tokenMetaPath, saveOAuth } from '../lib/oauth-core.js'; +import { getToken } from '../lib/token-core.js'; +import { saveOAuth } from '../lib/oauth-core.js'; import queryCmd from '../lib/query-cmd.js'; import { ArcqError } from '../lib/errors.js'; import type { Context } from '../lib/types.js'; +import { + resolveContextPath, + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-config.json'); describe('query-cmd', () => { @@ -44,7 +49,7 @@ describe('query-cmd', () => { } function setContext(ctx: Context) { - fs.writeFileSync(CONTEXT_PATH, JSON.stringify(ctx)); + fs.writeFileSync(resolveContextPath(), JSON.stringify(ctx)); } function writeConfig(layers: Record) { @@ -86,23 +91,25 @@ describe('query-cmd', () => { delete process.env.ARCQ_CONFIG; if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - contextBackup = fs.existsSync(CONTEXT_PATH) - ? fs.readFileSync(CONTEXT_PATH, 'utf-8') + contextBackup = fs.existsSync(resolveContextPath()) + ? fs.readFileSync(resolveContextPath(), 'utf-8') : null; - tokenBackup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + tokenBackup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; - oauthBackup = fs.existsSync(oauthPath) - ? fs.readFileSync(oauthPath, 'utf-8') + oauthBackup = fs.existsSync(resolveOAuthPath()) + ? fs.readFileSync(resolveOAuthPath(), 'utf-8') : null; - metaBackup = fs.existsSync(tokenMetaPath) - ? fs.readFileSync(tokenMetaPath, 'utf-8') + metaBackup = fs.existsSync(resolveTokenMetaPath()) + ? fs.readFileSync(resolveTokenMetaPath(), 'utf-8') : null; - if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH); - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); - if (fs.existsSync(oauthPath)) fs.unlinkSync(oauthPath); - if (fs.existsSync(tokenMetaPath)) fs.unlinkSync(tokenMetaPath); + if (fs.existsSync(resolveContextPath())) + fs.unlinkSync(resolveContextPath()); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); + if (fs.existsSync(resolveOAuthPath())) fs.unlinkSync(resolveOAuthPath()); + if (fs.existsSync(resolveTokenMetaPath())) + fs.unlinkSync(resolveTokenMetaPath()); logs = []; originalLog = console.log; @@ -126,27 +133,27 @@ describe('query-cmd', () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); if (contextBackup !== null) { - fs.writeFileSync(CONTEXT_PATH, contextBackup); - } else if (fs.existsSync(CONTEXT_PATH)) { - fs.unlinkSync(CONTEXT_PATH); + fs.writeFileSync(resolveContextPath(), contextBackup); + } else if (fs.existsSync(resolveContextPath())) { + fs.unlinkSync(resolveContextPath()); } if (tokenBackup !== null) { - fs.writeFileSync(tokenPath, tokenBackup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), tokenBackup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } if (oauthBackup !== null) { - fs.writeFileSync(oauthPath, oauthBackup); - } else if (fs.existsSync(oauthPath)) { - fs.unlinkSync(oauthPath); + fs.writeFileSync(resolveOAuthPath(), oauthBackup); + } else if (fs.existsSync(resolveOAuthPath())) { + fs.unlinkSync(resolveOAuthPath()); } if (metaBackup !== null) { - fs.writeFileSync(tokenMetaPath, metaBackup); - } else if (fs.existsSync(tokenMetaPath)) { - fs.unlinkSync(tokenMetaPath); + fs.writeFileSync(resolveTokenMetaPath(), metaBackup); + } else if (fs.existsSync(resolveTokenMetaPath())) { + fs.unlinkSync(resolveTokenMetaPath()); } }); @@ -249,7 +256,7 @@ describe('query-cmd', () => { }); it('makes only the query request when a token is stored (no preflight)', async () => { - fs.writeFileSync(tokenPath, 'my-token'); + fs.writeFileSync(resolveTokenPath(), 'my-token'); setContext({ url: baseUrl }); await queryCmd(['1=1']); expect(requests).to.have.length(1); @@ -257,7 +264,7 @@ describe('query-cmd', () => { }); it('includes the token in the query request', async () => { - fs.writeFileSync(tokenPath, 'my-token'); + fs.writeFileSync(resolveTokenPath(), 'my-token'); setContext({ url: baseUrl }); await queryCmd(['1=1']); const queryReq = requests.find((r: http.IncomingMessage) => diff --git a/test/refresh-cmd.test.ts b/test/refresh-cmd.test.ts index 58ceb2d..315cb61 100644 --- a/test/refresh-cmd.test.ts +++ b/test/refresh-cmd.test.ts @@ -3,9 +3,9 @@ import fs from 'fs'; import path from 'path'; import os from 'os'; import http from 'http'; -import { CACHE_PATH, loadCache } from '../lib/cache-core.js'; -import { tokenPath } from '../lib/token-core.js'; +import { loadCache } from '../lib/cache-core.js'; import refreshCmd from '../lib/refresh-cmd.js'; +import { resolveCachePath, resolveTokenPath } from '../lib/paths-core.js'; const { expect } = chai; @@ -70,15 +70,15 @@ describe('refresh-cmd', () => { if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - cacheBackup = fs.existsSync(CACHE_PATH) - ? fs.readFileSync(CACHE_PATH, 'utf-8') + cacheBackup = fs.existsSync(resolveCachePath()) + ? fs.readFileSync(resolveCachePath(), 'utf-8') : null; - tokenBackup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + tokenBackup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; - if (fs.existsSync(CACHE_PATH)) fs.unlinkSync(CACHE_PATH); - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); + if (fs.existsSync(resolveCachePath())) fs.unlinkSync(resolveCachePath()); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); logs = []; errors = []; @@ -106,15 +106,15 @@ describe('refresh-cmd', () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); if (cacheBackup !== null) { - fs.writeFileSync(CACHE_PATH, cacheBackup); - } else if (fs.existsSync(CACHE_PATH)) { - fs.unlinkSync(CACHE_PATH); + fs.writeFileSync(resolveCachePath(), cacheBackup); + } else if (fs.existsSync(resolveCachePath())) { + fs.unlinkSync(resolveCachePath()); } if (tokenBackup !== null) { - fs.writeFileSync(tokenPath, tokenBackup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), tokenBackup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } }); @@ -161,7 +161,7 @@ describe('refresh-cmd', () => { }); it('passes the stored token with each request', async () => { - fs.writeFileSync(tokenPath, 'refresh-token'); + fs.writeFileSync(resolveTokenPath(), 'refresh-token'); writeConfig({ 'my-service': serviceUrl }); await refreshCmd(); const params = (requests[0] as unknown as { bodyParams: URLSearchParams }) diff --git a/test/sync-cmd.test.ts b/test/sync-cmd.test.ts index 36af25a..4a28a46 100644 --- a/test/sync-cmd.test.ts +++ b/test/sync-cmd.test.ts @@ -3,9 +3,9 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import http from 'http'; -import { tokenPath } from '../lib/token-core.js'; import syncCmd from '../lib/sync-cmd.js'; import type { Config } from '../lib/types.js'; +import { resolveTokenPath } from '../lib/paths-core.js'; const { expect } = chai; @@ -72,10 +72,10 @@ describe('sync-cmd', () => { if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - tokenBackup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + tokenBackup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); logs = []; errors = []; @@ -104,9 +104,9 @@ describe('sync-cmd', () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); if (tokenBackup !== null) { - fs.writeFileSync(tokenPath, tokenBackup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), tokenBackup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } }); @@ -184,7 +184,7 @@ describe('sync-cmd', () => { }); it('passes the stored token with each request', async () => { - fs.writeFileSync(tokenPath, 'sync-token'); + fs.writeFileSync(resolveTokenPath(), 'sync-token'); writeConfig({ services: { 'my-service': serviceUrl } }); await syncCmd(); const params = (requests[0] as unknown as { bodyParams: URLSearchParams }) diff --git a/test/token-cmd.test.ts b/test/token-cmd.test.ts index f73b68d..ff9ca06 100644 --- a/test/token-cmd.test.ts +++ b/test/token-cmd.test.ts @@ -1,13 +1,13 @@ import * as chai from 'chai'; import fs from 'fs'; -import { tokenPath, setTokenValue } from '../lib/token-core.js'; -import { - oauthPath, - tokenMetaPath, - saveOAuth, - saveTokenMeta, -} from '../lib/oauth-core.js'; +import { setTokenValue } from '../lib/token-core.js'; +import { saveOAuth, saveTokenMeta } from '../lib/oauth-core.js'; import tokenCmd from '../lib/token-cmd.js'; +import { + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; @@ -18,7 +18,11 @@ describe('token-cmd', () => { let originalLog: typeof console.log; let originalError: typeof console.error; - const paths = [tokenPath, oauthPath, tokenMetaPath]; + const paths = [ + resolveTokenPath(), + resolveOAuthPath(), + resolveTokenMetaPath(), + ]; beforeEach(() => { backups = {}; @@ -102,7 +106,7 @@ describe('token-cmd', () => { describe('set', () => { it('saves the token', async () => { await tokenCmd(['set', 'my-new-token']); - expect(fs.readFileSync(tokenPath, 'utf-8').trim()).to.equal( + expect(fs.readFileSync(resolveTokenPath(), 'utf-8').trim()).to.equal( 'my-new-token' ); }); @@ -116,7 +120,7 @@ describe('token-cmd', () => { await tokenCmd(['set'], { prompt: async () => ' prompted-token ', }); - expect(fs.readFileSync(tokenPath, 'utf-8').trim()).to.equal( + expect(fs.readFileSync(resolveTokenPath(), 'utf-8').trim()).to.equal( 'prompted-token' ); }); @@ -129,7 +133,7 @@ describe('token-cmd', () => { error = err; } expect(String(error)).to.include('no token provided'); - expect(fs.existsSync(tokenPath)).to.equal(false); + expect(fs.existsSync(resolveTokenPath())).to.equal(false); }); }); diff --git a/test/token-connect-cmd.test.ts b/test/token-connect-cmd.test.ts index cb8080e..ead74b9 100644 --- a/test/token-connect-cmd.test.ts +++ b/test/token-connect-cmd.test.ts @@ -1,23 +1,22 @@ import * as chai from 'chai'; import fs from 'fs'; -import os from 'os'; -import path from 'path'; -import { tokenPath } from '../lib/token-core.js'; import { ArcqError } from '../lib/errors.js'; import { - oauthPath, - tokenMetaPath, loadOAuth, saveOAuth, type OAuthConfig, type RefreshResult, } from '../lib/oauth-core.js'; import tokenConnectCmd from '../lib/token-connect-cmd.js'; +import { + resolveContextPath, + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; -const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json'); - // A queued fake prompt: each call returns the next answer in order. function promptQueue(answers: string[]): (q: string) => Promise { const queue = [...answers]; @@ -41,7 +40,12 @@ describe('token-connect-cmd', () => { let logs: string[]; let originalLog: typeof console.log; - const paths = [oauthPath, tokenMetaPath, tokenPath, CONTEXT_PATH]; + const paths = [ + resolveOAuthPath(), + resolveTokenMetaPath(), + resolveTokenPath(), + resolveContextPath(), + ]; beforeEach(() => { backups = {}; @@ -165,7 +169,7 @@ describe('token-connect-cmd', () => { prompt: promptQueue([raw]), refresh: okRefresh, }); - expect(fs.statSync(oauthPath).mode & 0o777).to.equal(0o600); + expect(fs.statSync(resolveOAuthPath()).mode & 0o777).to.equal(0o600); }); it('restores the prior oauth file when validation fails', async () => { diff --git a/test/token-core.test.ts b/test/token-core.test.ts index a424520..732aaa7 100644 --- a/test/token-core.test.ts +++ b/test/token-core.test.ts @@ -1,6 +1,7 @@ import * as chai from 'chai'; import fs from 'fs'; -import { tokenPath, getToken, setTokenValue } from '../lib/token-core.js'; +import { getToken, setTokenValue } from '../lib/token-core.js'; +import { resolveTokenPath } from '../lib/paths-core.js'; const { expect } = chai; @@ -8,17 +9,17 @@ describe('token-core', () => { let backup: string | null; beforeEach(() => { - backup = fs.existsSync(tokenPath) - ? fs.readFileSync(tokenPath, 'utf-8') + backup = fs.existsSync(resolveTokenPath()) + ? fs.readFileSync(resolveTokenPath(), 'utf-8') : null; - if (fs.existsSync(tokenPath)) fs.unlinkSync(tokenPath); + if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); }); afterEach(() => { if (backup !== null) { - fs.writeFileSync(tokenPath, backup); - } else if (fs.existsSync(tokenPath)) { - fs.unlinkSync(tokenPath); + fs.writeFileSync(resolveTokenPath(), backup); + } else if (fs.existsSync(resolveTokenPath())) { + fs.unlinkSync(resolveTokenPath()); } }); @@ -28,43 +29,49 @@ describe('token-core', () => { }); it('returns the token string when the file exists', () => { - fs.writeFileSync(tokenPath, 'abc123'); + fs.writeFileSync(resolveTokenPath(), 'abc123'); expect(getToken()).to.equal('abc123'); }); it('trims whitespace from the stored token', () => { - fs.writeFileSync(tokenPath, ' my-token\n'); + fs.writeFileSync(resolveTokenPath(), ' my-token\n'); expect(getToken()).to.equal('my-token'); }); }); describe('setTokenValue', () => { - it('writes the token to tokenPath', () => { + it('writes the token to resolveTokenPath()', () => { setTokenValue('new-token'); - expect(fs.readFileSync(tokenPath, 'utf-8')).to.equal('new-token'); + expect(fs.readFileSync(resolveTokenPath(), 'utf-8')).to.equal( + 'new-token' + ); }); it('trims whitespace before writing', () => { setTokenValue(' padded-token '); - expect(fs.readFileSync(tokenPath, 'utf-8')).to.equal('padded-token'); + expect(fs.readFileSync(resolveTokenPath(), 'utf-8')).to.equal( + 'padded-token' + ); }); it('overwrites an existing token', () => { - fs.writeFileSync(tokenPath, 'old-token'); + fs.writeFileSync(resolveTokenPath(), 'old-token'); setTokenValue('new-token'); - expect(fs.readFileSync(tokenPath, 'utf-8')).to.equal('new-token'); + expect(fs.readFileSync(resolveTokenPath(), 'utf-8')).to.equal( + 'new-token' + ); }); it('writes the token file with mode 600', () => { setTokenValue('secret'); - expect(fs.statSync(tokenPath).mode & 0o777).to.equal(0o600); + expect(fs.statSync(resolveTokenPath()).mode & 0o777).to.equal(0o600); }); it('tightens a pre-existing loosely-permissioned file to 600', () => { - fs.writeFileSync(tokenPath, 'old-token', { mode: 0o644 }); - fs.chmodSync(tokenPath, 0o644); + fs.writeFileSync(resolveTokenPath(), 'old-token', { mode: 0o644 }); + fs.chmodSync(resolveTokenPath(), 0o644); setTokenValue('new-token'); - expect(fs.statSync(tokenPath).mode & 0o777).to.equal(0o600); + expect(fs.statSync(resolveTokenPath()).mode & 0o777).to.equal(0o600); }); }); diff --git a/test/token-refresh-cmd.test.ts b/test/token-refresh-cmd.test.ts index 4a595ed..65d3927 100644 --- a/test/token-refresh-cmd.test.ts +++ b/test/token-refresh-cmd.test.ts @@ -1,10 +1,8 @@ import * as chai from 'chai'; import fs from 'fs'; -import { tokenPath, getToken } from '../lib/token-core.js'; +import { getToken } from '../lib/token-core.js'; import { ArcqError } from '../lib/errors.js'; import { - oauthPath, - tokenMetaPath, loadOAuth, loadTokenMeta, saveOAuth, @@ -12,6 +10,11 @@ import { } from '../lib/oauth-core.js'; import tokenRefreshCmd from '../lib/token-refresh-cmd.js'; import type { OAuthTokenResponse } from '../lib/types.js'; +import { + resolveOAuthPath, + resolveTokenMetaPath, + resolveTokenPath, +} from '../lib/paths-core.js'; const { expect } = chai; @@ -32,7 +35,11 @@ describe('token-refresh-cmd', () => { beforeEach(() => { backups = {}; - for (const p of [oauthPath, tokenMetaPath, tokenPath]) { + for (const p of [ + resolveOAuthPath(), + resolveTokenMetaPath(), + resolveTokenPath(), + ]) { backups[p] = fs.existsSync(p) ? fs.readFileSync(p, 'utf-8') : null; if (fs.existsSync(p)) fs.unlinkSync(p); } @@ -43,7 +50,11 @@ describe('token-refresh-cmd', () => { afterEach(() => { console.log = originalLog; - for (const p of [oauthPath, tokenMetaPath, tokenPath]) { + for (const p of [ + resolveOAuthPath(), + resolveTokenMetaPath(), + resolveTokenPath(), + ]) { const backup = backups[p]; if (backup != null) fs.writeFileSync(p, backup); else if (fs.existsSync(p)) fs.unlinkSync(p); From 9639701a3d6a77a6111d2ece5db074bb38cbf3da Mon Sep 17 00:00:00 2001 From: James Easter Date: Tue, 25 Aug 2026 21:50:43 -0500 Subject: [PATCH 3/5] Run the test suite against a temp ARCQ_HOME instead of the real credentials. --- test/active-cmd.test.ts | 16 ++------- test/bin.test.ts | 25 +++----------- test/cache-core.test.ts | 20 ++---------- test/config-core.test.ts | 21 ++++-------- test/context-core.test.ts | 21 ++---------- test/fields-cmd.test.ts | 60 +++------------------------------- test/index.test.ts | 26 +++------------ test/interactive-cmd.test.ts | 29 +++------------- test/layers-cmd.test.ts | 16 ++------- test/list-cmd.test.ts | 47 +++----------------------- test/oauth-core.test.ts | 39 ++-------------------- test/query-cmd.test.ts | 58 +++----------------------------- test/refresh-cmd.test.ts | 41 +++-------------------- test/services-cmd.test.ts | 16 ++------- test/state-dir.ts | 37 +++++++++++++++++++++ test/sync-cmd.test.ts | 28 ++-------------- test/token-cmd.test.ts | 28 +++------------- test/token-connect-cmd.test.ts | 28 +++------------- test/token-core.test.ts | 20 ++---------- test/token-refresh-cmd.test.ts | 28 ++-------------- 20 files changed, 108 insertions(+), 496 deletions(-) create mode 100644 test/state-dir.ts diff --git a/test/active-cmd.test.ts b/test/active-cmd.test.ts index 2d95db8..1608a6c 100644 --- a/test/active-cmd.test.ts +++ b/test/active-cmd.test.ts @@ -3,11 +3,13 @@ import fs from 'fs'; import activeCmd from '../lib/active-cmd.js'; import type { Context } from '../lib/types.js'; import { resolveContextPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; describe('active-cmd', () => { - let contextBackup: string | null; + useTempStateDir(); + let logs: string[]; let originalLog: typeof console.log; @@ -16,12 +18,6 @@ describe('active-cmd', () => { } beforeEach(() => { - contextBackup = fs.existsSync(resolveContextPath()) - ? fs.readFileSync(resolveContextPath(), 'utf-8') - : null; - if (fs.existsSync(resolveContextPath())) - fs.unlinkSync(resolveContextPath()); - logs = []; originalLog = console.log; console.log = (...args) => logs.push(args.join(' ')); @@ -29,12 +25,6 @@ describe('active-cmd', () => { afterEach(() => { console.log = originalLog; - - if (contextBackup !== null) { - fs.writeFileSync(resolveContextPath(), contextBackup); - } else if (fs.existsSync(resolveContextPath())) { - fs.unlinkSync(resolveContextPath()); - } }); it('prints service:id → name and the url for a full context', () => { diff --git a/test/bin.test.ts b/test/bin.test.ts index 2719a2e..a4d071a 100644 --- a/test/bin.test.ts +++ b/test/bin.test.ts @@ -5,7 +5,6 @@ import http from 'http'; import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; -import { resolveTokenPath } from '../lib/paths-core.js'; const { expect } = chai; @@ -31,7 +30,6 @@ describe('bin/arcq', function () { let server: http.Server; let baseUrl: string; let handler: (req: http.IncomingMessage, res: http.ServerResponse) => void; - let tokenBackup: string | null; function respond(data: unknown) { handler = (req: http.IncomingMessage, res: http.ServerResponse) => { @@ -42,13 +40,15 @@ describe('bin/arcq', function () { function runBin(args: string[]): Promise { return new Promise((resolve, reject) => { - // The child gets an empty temp HOME so the developer's real token and - // OAuth files can't leak in (a real OAuth setup would turn the token- - // error test into a live credential-command run and portal request). + // The child gets an empty temp state directory so the developer's real + // token and OAuth files can't leak in (a real OAuth setup would turn the + // token-error test into a live credential-command run and portal + // request). HOME is overridden too, in case anything else consults it. const child = spawn(TSX, [BIN, ...args], { env: { ...process.env, ARCQ_CONFIG: TEMP_CONFIG, + ARCQ_HOME: TEMP_HOME, HOME: TEMP_HOME, USERPROFILE: TEMP_HOME, }, @@ -80,21 +80,6 @@ describe('bin/arcq', function () { await new Promise((resolve) => server.close(() => resolve())); }); - beforeEach(() => { - tokenBackup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - }); - - afterEach(() => { - if (tokenBackup !== null) { - fs.writeFileSync(resolveTokenPath(), tokenBackup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } - }); - it('exits 1 and prints error: on an ArcGIS response error', async () => { respond({ error: { code: 400, message: 'Unable to complete operation.' } }); const res = await runBin(['-q', baseUrl, 'BAD = "SYNTAX"']); diff --git a/test/cache-core.test.ts b/test/cache-core.test.ts index 923659a..e8ace66 100644 --- a/test/cache-core.test.ts +++ b/test/cache-core.test.ts @@ -3,26 +3,12 @@ import fs from 'fs'; import { loadCache, saveCache } from '../lib/cache-core.js'; import type { Cache } from '../lib/types.js'; import { resolveCachePath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; describe('cache-core', () => { - let backup: string | null; - - beforeEach(() => { - backup = fs.existsSync(resolveCachePath()) - ? fs.readFileSync(resolveCachePath(), 'utf-8') - : null; - if (fs.existsSync(resolveCachePath())) fs.unlinkSync(resolveCachePath()); - }); - - afterEach(() => { - if (backup !== null) { - fs.writeFileSync(resolveCachePath(), backup); - } else if (fs.existsSync(resolveCachePath())) { - fs.unlinkSync(resolveCachePath()); - } - }); + useTempStateDir(); describe('loadCache', () => { it('returns {} when the file does not exist', () => { @@ -37,7 +23,7 @@ describe('cache-core', () => { }); describe('saveCache', () => { - it('writes the cache as JSON to resolveCachePath()', () => { + it('writes the cache as JSON to the resolved cache path', () => { const data = { 'my-service': [{ id: 0, name: 'Parcels' }] }; saveCache(data as unknown as Cache); expect( diff --git a/test/config-core.test.ts b/test/config-core.test.ts index 1c58d96..0af009c 100644 --- a/test/config-core.test.ts +++ b/test/config-core.test.ts @@ -3,24 +3,21 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import { loadConfig } from '../lib/config-core.js'; +import { resolveConfigPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; -const DEFAULT_PATH = path.join(os.homedir(), '.arcq.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-config.json'); describe('config-core', () => { + useTempStateDir(); + let originalEnv: string | undefined; - let defaultBackup: string | null; beforeEach(() => { originalEnv = process.env.ARCQ_CONFIG; delete process.env.ARCQ_CONFIG; - - defaultBackup = fs.existsSync(DEFAULT_PATH) - ? fs.readFileSync(DEFAULT_PATH, 'utf-8') - : null; - if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); }); @@ -31,12 +28,6 @@ describe('config-core', () => { process.env.ARCQ_CONFIG = originalEnv; } - if (defaultBackup !== null) { - fs.writeFileSync(DEFAULT_PATH, defaultBackup); - } else if (fs.existsSync(DEFAULT_PATH)) { - fs.unlinkSync(DEFAULT_PATH); - } - if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); }); @@ -44,9 +35,9 @@ describe('config-core', () => { expect(loadConfig()).to.deep.equal({}); }); - it('reads ~/.arcq.json by default when ARCQ_CONFIG is not set', () => { + it('reads the state directory config when ARCQ_CONFIG is not set', () => { const config = { services: { svc: 'https://example.com' } }; - fs.writeFileSync(DEFAULT_PATH, JSON.stringify(config)); + fs.writeFileSync(resolveConfigPath(), JSON.stringify(config)); expect(loadConfig()).to.deep.equal(config); }); diff --git a/test/context-core.test.ts b/test/context-core.test.ts index 374f2d3..cf497da 100644 --- a/test/context-core.test.ts +++ b/test/context-core.test.ts @@ -2,27 +2,12 @@ import * as chai from 'chai'; import fs from 'fs'; import { loadContext, saveContext } from '../lib/context-core.js'; import { resolveContextPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; describe('context-core', () => { - let backup: string | null; - - beforeEach(() => { - backup = fs.existsSync(resolveContextPath()) - ? fs.readFileSync(resolveContextPath(), 'utf-8') - : null; - if (fs.existsSync(resolveContextPath())) - fs.unlinkSync(resolveContextPath()); - }); - - afterEach(() => { - if (backup !== null) { - fs.writeFileSync(resolveContextPath(), backup); - } else if (fs.existsSync(resolveContextPath())) { - fs.unlinkSync(resolveContextPath()); - } - }); + useTempStateDir(); describe('loadContext', () => { it('returns null when no context file exists', () => { @@ -42,7 +27,7 @@ describe('context-core', () => { }); describe('saveContext', () => { - it('writes the context as JSON to resolveContextPath()', () => { + it('writes the context as JSON to the resolved context path', () => { const ctx = { service: 'svc', layerId: 1, diff --git a/test/fields-cmd.test.ts b/test/fields-cmd.test.ts index 7031eb4..2cdd4dd 100644 --- a/test/fields-cmd.test.ts +++ b/test/fields-cmd.test.ts @@ -6,12 +6,8 @@ import http from 'http'; import fieldsCmd from '../lib/fields-cmd.js'; import { ArcqError } from '../lib/errors.js'; import type { Context } from '../lib/types.js'; -import { - resolveContextPath, - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { resolveContextPath, resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; @@ -45,15 +41,13 @@ const EXPECTED_FIELDS = [ ]; describe('fields-cmd', () => { + useTempStateDir(); + let server: http.Server; let baseUrl: string; let handler: (req: http.IncomingMessage, res: http.ServerResponse) => void; let requests: http.IncomingMessage[]; let originalEnv: string | undefined; - let contextBackup: string | null; - let tokenBackup: string | null; - let oauthBackup: string | null; - let tokenMetaBackup: string | null; let logs: string[]; let originalLog: typeof console.log; @@ -106,28 +100,6 @@ describe('fields-cmd', () => { delete process.env.ARCQ_CONFIG; if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - contextBackup = fs.existsSync(resolveContextPath()) - ? fs.readFileSync(resolveContextPath(), 'utf-8') - : null; - tokenBackup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - // Isolate the developer's real OAuth setup: with it present, the exit-2 - // path would trigger a real credential-command run and portal request. - oauthBackup = fs.existsSync(resolveOAuthPath()) - ? fs.readFileSync(resolveOAuthPath(), 'utf-8') - : null; - tokenMetaBackup = fs.existsSync(resolveTokenMetaPath()) - ? fs.readFileSync(resolveTokenMetaPath(), 'utf-8') - : null; - - if (fs.existsSync(resolveContextPath())) - fs.unlinkSync(resolveContextPath()); - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - if (fs.existsSync(resolveOAuthPath())) fs.unlinkSync(resolveOAuthPath()); - if (fs.existsSync(resolveTokenMetaPath())) - fs.unlinkSync(resolveTokenMetaPath()); - logs = []; originalLog = console.log; console.log = (...args) => logs.push(args.join(' ')); @@ -142,30 +114,6 @@ describe('fields-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - - if (contextBackup !== null) { - fs.writeFileSync(resolveContextPath(), contextBackup); - } else if (fs.existsSync(resolveContextPath())) { - fs.unlinkSync(resolveContextPath()); - } - - if (tokenBackup !== null) { - fs.writeFileSync(resolveTokenPath(), tokenBackup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } - - if (oauthBackup !== null) { - fs.writeFileSync(resolveOAuthPath(), oauthBackup); - } else if (fs.existsSync(resolveOAuthPath())) { - fs.unlinkSync(resolveOAuthPath()); - } - - if (tokenMetaBackup !== null) { - fs.writeFileSync(resolveTokenMetaPath(), tokenMetaBackup); - } else if (fs.existsSync(resolveTokenMetaPath())) { - fs.unlinkSync(resolveTokenMetaPath()); - } }); it('resolves the active context when called with no args', async () => { diff --git a/test/index.test.ts b/test/index.test.ts index 07cf9e5..0688225 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -5,13 +5,15 @@ import os from 'os'; import { run, resolveInsecure } from '../index.js'; import { getHttpsAgent } from '../lib/tls-core.js'; import { ArcqError } from '../lib/errors.js'; -import { resolveContextPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-index-test-config.json'); describe('index', () => { + useTempStateDir(); + let logs: string[]; let errors: string[]; let originalLog: typeof console.log; @@ -73,24 +75,6 @@ describe('index', () => { }); describe('flag-first query shorthand', () => { - let contextBackup: string | null; - - beforeEach(() => { - contextBackup = fs.existsSync(resolveContextPath()) - ? fs.readFileSync(resolveContextPath(), 'utf-8') - : null; - if (fs.existsSync(resolveContextPath())) - fs.unlinkSync(resolveContextPath()); - }); - - afterEach(() => { - if (contextBackup !== null) { - fs.writeFileSync(resolveContextPath(), contextBackup); - } else if (fs.existsSync(resolveContextPath())) { - fs.unlinkSync(resolveContextPath()); - } - }); - it('still routes arcq -q "1=1" to query', async () => { // With no active context the query itself rejects, which proves the // -q allowlist routed to query instead of the unknown-flag guard. @@ -113,8 +97,8 @@ describe('index', () => { beforeEach(() => { envConfig = process.env.ARCQ_CONFIG; envInsecure = process.env.ARCQ_INSECURE; - // Point config resolution at an empty temp file so the real - // ~/.arcq.json cannot flip these cases on or off. + // Point config resolution at an empty temp file so a stray config + // cannot flip these cases on or off. process.env.ARCQ_CONFIG = TEMP_CONFIG; fs.writeFileSync(TEMP_CONFIG, '{}'); delete process.env.ARCQ_INSECURE; diff --git a/test/interactive-cmd.test.ts b/test/interactive-cmd.test.ts index f3ec4fc..64d3d76 100644 --- a/test/interactive-cmd.test.ts +++ b/test/interactive-cmd.test.ts @@ -7,7 +7,8 @@ import { loadContext } from '../lib/context-core.js'; import interactiveCmd from '../lib/interactive-cmd.js'; import { ArcqError } from '../lib/errors.js'; import type { Cache } from '../lib/types.js'; -import { resolveCachePath, resolveContextPath } from '../lib/paths-core.js'; +import { resolveContextPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; @@ -30,8 +31,8 @@ const FAKE_CACHE = { } as unknown as Cache; describe('interactive-cmd', () => { - let cacheBackup: string | null; - let contextBackup: string | null; + useTempStateDir(); + let originalPath: string | undefined; let originalEnv: string | undefined; @@ -54,16 +55,6 @@ describe('interactive-cmd', () => { }); beforeEach(() => { - cacheBackup = fs.existsSync(resolveCachePath()) - ? fs.readFileSync(resolveCachePath(), 'utf-8') - : null; - contextBackup = fs.existsSync(resolveContextPath()) - ? fs.readFileSync(resolveContextPath(), 'utf-8') - : null; - if (fs.existsSync(resolveCachePath())) fs.unlinkSync(resolveCachePath()); - if (fs.existsSync(resolveContextPath())) - fs.unlinkSync(resolveContextPath()); - originalPath = process.env.PATH; process.env.PATH = `${FAKE_FZF_DIR}:${process.env.PATH}`; delete process.env.ARCQ_TEST_SELECT; @@ -83,18 +74,6 @@ describe('interactive-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - - if (cacheBackup !== null) { - fs.writeFileSync(resolveCachePath(), cacheBackup); - } else if (fs.existsSync(resolveCachePath())) { - fs.unlinkSync(resolveCachePath()); - } - - if (contextBackup !== null) { - fs.writeFileSync(resolveContextPath(), contextBackup); - } else if (fs.existsSync(resolveContextPath())) { - fs.unlinkSync(resolveContextPath()); - } }); it('saves the selected layer as the active context', async () => { diff --git a/test/layers-cmd.test.ts b/test/layers-cmd.test.ts index ed05333..80c798d 100644 --- a/test/layers-cmd.test.ts +++ b/test/layers-cmd.test.ts @@ -2,28 +2,24 @@ import * as chai from 'chai'; import fs from 'fs'; import os from 'os'; import path from 'path'; +import { useTempStateDir } from './state-dir.js'; import layersCmd from '../lib/layers-cmd.js'; import type { Config } from '../lib/types.js'; const { expect } = chai; -const DEFAULT_PATH = path.join(os.homedir(), '.arcq.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-layers-config.json'); describe('layers-cmd', () => { + useTempStateDir(); + let originalEnv: string | undefined; - let defaultBackup: string | null; let logs: string[]; let originalLog: typeof console.log; beforeEach(() => { originalEnv = process.env.ARCQ_CONFIG; process.env.ARCQ_CONFIG = TEMP_CONFIG; - - defaultBackup = fs.existsSync(DEFAULT_PATH) - ? fs.readFileSync(DEFAULT_PATH, 'utf-8') - : null; - if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); logs = []; @@ -40,12 +36,6 @@ describe('layers-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } - if (defaultBackup !== null) { - fs.writeFileSync(DEFAULT_PATH, defaultBackup); - } else if (fs.existsSync(DEFAULT_PATH)) { - fs.unlinkSync(DEFAULT_PATH); - } - if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); }); diff --git a/test/list-cmd.test.ts b/test/list-cmd.test.ts index fae6723..4a54482 100644 --- a/test/list-cmd.test.ts +++ b/test/list-cmd.test.ts @@ -4,11 +4,8 @@ import path from 'path'; import os from 'os'; import http from 'http'; import listCmd from '../lib/list-cmd.js'; -import { - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; @@ -23,13 +20,12 @@ const CATALOG_RESPONSE = { }; describe('list-cmd', () => { + useTempStateDir(); + let server: http.Server; let serviceUrl: string; let requests: http.IncomingMessage[]; let originalEnv: string | undefined; - let tokenBackup: string | null; - let oauthBackup: string | null; - let tokenMetaBackup: string | null; let logs: string[]; let originalLog: typeof console.log; @@ -68,23 +64,6 @@ describe('list-cmd', () => { delete process.env.ARCQ_CONFIG; if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - tokenBackup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - - // Isolate the developer's real OAuth setup: with it present, the exit-2 - // path would trigger a real credential-command run and portal request. - oauthBackup = fs.existsSync(resolveOAuthPath()) - ? fs.readFileSync(resolveOAuthPath(), 'utf-8') - : null; - tokenMetaBackup = fs.existsSync(resolveTokenMetaPath()) - ? fs.readFileSync(resolveTokenMetaPath(), 'utf-8') - : null; - if (fs.existsSync(resolveOAuthPath())) fs.unlinkSync(resolveOAuthPath()); - if (fs.existsSync(resolveTokenMetaPath())) - fs.unlinkSync(resolveTokenMetaPath()); - logs = []; originalLog = console.log; console.log = (...args) => logs.push(args.join(' ')); @@ -99,24 +78,6 @@ describe('list-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - - if (tokenBackup !== null) { - fs.writeFileSync(resolveTokenPath(), tokenBackup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } - - if (oauthBackup !== null) { - fs.writeFileSync(resolveOAuthPath(), oauthBackup); - } else if (fs.existsSync(resolveOAuthPath())) { - fs.unlinkSync(resolveOAuthPath()); - } - - if (tokenMetaBackup !== null) { - fs.writeFileSync(resolveTokenMetaPath(), tokenMetaBackup); - } else if (fs.existsSync(resolveTokenMetaPath())) { - fs.unlinkSync(resolveTokenMetaPath()); - } }); function writeConfig(services: Record) { diff --git a/test/oauth-core.test.ts b/test/oauth-core.test.ts index c3fbdb1..ee191be 100644 --- a/test/oauth-core.test.ts +++ b/test/oauth-core.test.ts @@ -15,11 +15,8 @@ import { type OAuthConfig, } from '../lib/oauth-core.js'; import type { OAuthTokenResponse } from '../lib/types.js'; -import { - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { resolveOAuthPath, resolveTokenMetaPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; @@ -29,37 +26,7 @@ function blob(entries: Record): string { } describe('oauth-core', () => { - let oauthBackup: string | null; - let metaBackup: string | null; - let tokenBackup: string | null; - - function snapshot(p: string): string | null { - return fs.existsSync(p) ? fs.readFileSync(p, 'utf-8') : null; - } - - function restore(p: string, backup: string | null): void { - if (backup !== null) fs.writeFileSync(p, backup); - else if (fs.existsSync(p)) fs.unlinkSync(p); - } - - beforeEach(() => { - oauthBackup = snapshot(resolveOAuthPath()); - metaBackup = snapshot(resolveTokenMetaPath()); - tokenBackup = snapshot(resolveTokenPath()); - for (const p of [ - resolveOAuthPath(), - resolveTokenMetaPath(), - resolveTokenPath(), - ]) { - if (fs.existsSync(p)) fs.unlinkSync(p); - } - }); - - afterEach(() => { - restore(resolveOAuthPath(), oauthBackup); - restore(resolveTokenMetaPath(), metaBackup); - restore(resolveTokenPath(), tokenBackup); - }); + useTempStateDir(); describe('oauth storage', () => { it('round-trips a saved config', () => { diff --git a/test/query-cmd.test.ts b/test/query-cmd.test.ts index 7e91195..900f5a1 100644 --- a/test/query-cmd.test.ts +++ b/test/query-cmd.test.ts @@ -8,27 +8,21 @@ import { saveOAuth } from '../lib/oauth-core.js'; import queryCmd from '../lib/query-cmd.js'; import { ArcqError } from '../lib/errors.js'; import type { Context } from '../lib/types.js'; -import { - resolveContextPath, - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { resolveContextPath, resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-config.json'); describe('query-cmd', () => { + useTempStateDir(); + let server: http.Server; let baseUrl: string; let handler: (req: http.IncomingMessage, res: http.ServerResponse) => void; let requests: http.IncomingMessage[]; let originalEnv: string | undefined; - let contextBackup: string | null; - let tokenBackup: string | null; - let oauthBackup: string | null; - let metaBackup: string | null; let logs: string[]; let originalLog: typeof console.log; let errs: string[]; @@ -91,26 +85,6 @@ describe('query-cmd', () => { delete process.env.ARCQ_CONFIG; if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - contextBackup = fs.existsSync(resolveContextPath()) - ? fs.readFileSync(resolveContextPath(), 'utf-8') - : null; - tokenBackup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - oauthBackup = fs.existsSync(resolveOAuthPath()) - ? fs.readFileSync(resolveOAuthPath(), 'utf-8') - : null; - metaBackup = fs.existsSync(resolveTokenMetaPath()) - ? fs.readFileSync(resolveTokenMetaPath(), 'utf-8') - : null; - - if (fs.existsSync(resolveContextPath())) - fs.unlinkSync(resolveContextPath()); - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - if (fs.existsSync(resolveOAuthPath())) fs.unlinkSync(resolveOAuthPath()); - if (fs.existsSync(resolveTokenMetaPath())) - fs.unlinkSync(resolveTokenMetaPath()); - logs = []; originalLog = console.log; console.log = (...args) => logs.push(args.join(' ')); @@ -131,30 +105,6 @@ describe('query-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - - if (contextBackup !== null) { - fs.writeFileSync(resolveContextPath(), contextBackup); - } else if (fs.existsSync(resolveContextPath())) { - fs.unlinkSync(resolveContextPath()); - } - - if (tokenBackup !== null) { - fs.writeFileSync(resolveTokenPath(), tokenBackup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } - - if (oauthBackup !== null) { - fs.writeFileSync(resolveOAuthPath(), oauthBackup); - } else if (fs.existsSync(resolveOAuthPath())) { - fs.unlinkSync(resolveOAuthPath()); - } - - if (metaBackup !== null) { - fs.writeFileSync(resolveTokenMetaPath(), metaBackup); - } else if (fs.existsSync(resolveTokenMetaPath())) { - fs.unlinkSync(resolveTokenMetaPath()); - } }); describe('single arg — where clause against active layer', () => { diff --git a/test/refresh-cmd.test.ts b/test/refresh-cmd.test.ts index 315cb61..efb7761 100644 --- a/test/refresh-cmd.test.ts +++ b/test/refresh-cmd.test.ts @@ -5,11 +5,11 @@ import os from 'os'; import http from 'http'; import { loadCache } from '../lib/cache-core.js'; import refreshCmd from '../lib/refresh-cmd.js'; -import { resolveCachePath, resolveTokenPath } from '../lib/paths-core.js'; +import { resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; -const DEFAULT_PATH = path.join(os.homedir(), '.arcq.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-config.json'); const CATALOG = { @@ -18,13 +18,12 @@ const CATALOG = { }; describe('refresh-cmd', () => { + useTempStateDir(); + let server: http.Server; let serviceUrl: string; let requests: http.IncomingMessage[]; let originalEnv: string | undefined; - let defaultBackup: string | null; - let cacheBackup: string | null; - let tokenBackup: string | null; let logs: string[]; let errors: string[]; let originalLog: typeof console.log; @@ -63,23 +62,8 @@ describe('refresh-cmd', () => { originalEnv = process.env.ARCQ_CONFIG; delete process.env.ARCQ_CONFIG; - - defaultBackup = fs.existsSync(DEFAULT_PATH) - ? fs.readFileSync(DEFAULT_PATH, 'utf-8') - : null; - if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - cacheBackup = fs.existsSync(resolveCachePath()) - ? fs.readFileSync(resolveCachePath(), 'utf-8') - : null; - tokenBackup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - - if (fs.existsSync(resolveCachePath())) fs.unlinkSync(resolveCachePath()); - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - logs = []; errors = []; originalLog = console.log; @@ -98,24 +82,7 @@ describe('refresh-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } - if (defaultBackup !== null) { - fs.writeFileSync(DEFAULT_PATH, defaultBackup); - } else if (fs.existsSync(DEFAULT_PATH)) { - fs.unlinkSync(DEFAULT_PATH); - } if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - - if (cacheBackup !== null) { - fs.writeFileSync(resolveCachePath(), cacheBackup); - } else if (fs.existsSync(resolveCachePath())) { - fs.unlinkSync(resolveCachePath()); - } - - if (tokenBackup !== null) { - fs.writeFileSync(resolveTokenPath(), tokenBackup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } }); function writeConfig(services: Record) { diff --git a/test/services-cmd.test.ts b/test/services-cmd.test.ts index c5276f1..87e313f 100644 --- a/test/services-cmd.test.ts +++ b/test/services-cmd.test.ts @@ -2,28 +2,24 @@ import * as chai from 'chai'; import fs from 'fs'; import os from 'os'; import path from 'path'; +import { useTempStateDir } from './state-dir.js'; import servicesCmd from '../lib/services-cmd.js'; import type { Config } from '../lib/types.js'; const { expect } = chai; -const DEFAULT_PATH = path.join(os.homedir(), '.arcq.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-services-config.json'); describe('services-cmd', () => { + useTempStateDir(); + let originalEnv: string | undefined; - let defaultBackup: string | null; let logs: string[]; let originalLog: typeof console.log; beforeEach(() => { originalEnv = process.env.ARCQ_CONFIG; process.env.ARCQ_CONFIG = TEMP_CONFIG; - - defaultBackup = fs.existsSync(DEFAULT_PATH) - ? fs.readFileSync(DEFAULT_PATH, 'utf-8') - : null; - if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); logs = []; @@ -40,12 +36,6 @@ describe('services-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } - if (defaultBackup !== null) { - fs.writeFileSync(DEFAULT_PATH, defaultBackup); - } else if (fs.existsSync(DEFAULT_PATH)) { - fs.unlinkSync(DEFAULT_PATH); - } - if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); }); diff --git a/test/state-dir.ts b/test/state-dir.ts new file mode 100644 index 0000000..2e02300 --- /dev/null +++ b/test/state-dir.ts @@ -0,0 +1,37 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +// Point arcq's state at a throwaway directory for the duration of a suite, so +// no test ever reads or writes the developer's real token, OAuth credential, +// config, context, or cache. A crash between hooks can no longer destroy a +// live credential, because the tests never touch one. +// +// Call inside a `describe`; it registers its own beforeEach/afterEach and +// returns a handle whose `path` is the directory for the running test. +export interface TempStateDir { + readonly path: string; +} + +export function useTempStateDir(): TempStateDir { + let dir = ''; + let priorHome: string | undefined; + + beforeEach(() => { + priorHome = process.env.ARCQ_HOME; + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcq-state-')); + process.env.ARCQ_HOME = dir; + }); + + afterEach(() => { + if (priorHome === undefined) delete process.env.ARCQ_HOME; + else process.env.ARCQ_HOME = priorHome; + fs.rmSync(dir, { recursive: true, force: true }); + }); + + return { + get path(): string { + return dir; + }, + }; +} diff --git a/test/sync-cmd.test.ts b/test/sync-cmd.test.ts index 4a28a46..bf9e414 100644 --- a/test/sync-cmd.test.ts +++ b/test/sync-cmd.test.ts @@ -6,10 +6,10 @@ import http from 'http'; import syncCmd from '../lib/sync-cmd.js'; import type { Config } from '../lib/types.js'; import { resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; -const DEFAULT_PATH = path.join(os.homedir(), '.arcq.json'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-sync-config.json'); const CATALOG = { @@ -21,12 +21,12 @@ const CATALOG = { }; describe('sync-cmd', () => { + useTempStateDir(); + let server: http.Server; let serviceUrl: string; let requests: http.IncomingMessage[]; let originalEnv: string | undefined; - let defaultBackup: string | null; - let tokenBackup: string | null; let logs: string[]; let errors: string[]; let originalLog: typeof console.log; @@ -65,18 +65,8 @@ describe('sync-cmd', () => { originalEnv = process.env.ARCQ_CONFIG; process.env.ARCQ_CONFIG = TEMP_CONFIG; - - defaultBackup = fs.existsSync(DEFAULT_PATH) - ? fs.readFileSync(DEFAULT_PATH, 'utf-8') - : null; - if (fs.existsSync(DEFAULT_PATH)) fs.unlinkSync(DEFAULT_PATH); if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - tokenBackup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - logs = []; errors = []; originalLog = console.log; @@ -95,19 +85,7 @@ describe('sync-cmd', () => { process.env.ARCQ_CONFIG = originalEnv; } - if (defaultBackup !== null) { - fs.writeFileSync(DEFAULT_PATH, defaultBackup); - } else if (fs.existsSync(DEFAULT_PATH)) { - fs.unlinkSync(DEFAULT_PATH); - } - if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); - - if (tokenBackup !== null) { - fs.writeFileSync(resolveTokenPath(), tokenBackup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } }); function writeConfig(config: Config) { diff --git a/test/token-cmd.test.ts b/test/token-cmd.test.ts index ff9ca06..0f10003 100644 --- a/test/token-cmd.test.ts +++ b/test/token-cmd.test.ts @@ -3,34 +3,20 @@ import fs from 'fs'; import { setTokenValue } from '../lib/token-core.js'; import { saveOAuth, saveTokenMeta } from '../lib/oauth-core.js'; import tokenCmd from '../lib/token-cmd.js'; -import { - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; describe('token-cmd', () => { - let backups: Record; + useTempStateDir(); + let logs: string[]; let errs: string[]; let originalLog: typeof console.log; let originalError: typeof console.error; - const paths = [ - resolveTokenPath(), - resolveOAuthPath(), - resolveTokenMetaPath(), - ]; - beforeEach(() => { - backups = {}; - for (const p of paths) { - backups[p] = fs.existsSync(p) ? fs.readFileSync(p, 'utf-8') : null; - if (fs.existsSync(p)) fs.unlinkSync(p); - } - logs = []; errs = []; originalLog = console.log; @@ -42,12 +28,6 @@ describe('token-cmd', () => { afterEach(() => { console.log = originalLog; console.error = originalError; - - for (const p of paths) { - const backup = backups[p]; - if (backup != null) fs.writeFileSync(p, backup); - else if (fs.existsSync(p)) fs.unlinkSync(p); - } }); describe('show', () => { diff --git a/test/token-connect-cmd.test.ts b/test/token-connect-cmd.test.ts index ead74b9..cf589ad 100644 --- a/test/token-connect-cmd.test.ts +++ b/test/token-connect-cmd.test.ts @@ -8,12 +8,8 @@ import { type RefreshResult, } from '../lib/oauth-core.js'; import tokenConnectCmd from '../lib/token-connect-cmd.js'; -import { - resolveContextPath, - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { resolveOAuthPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; @@ -36,23 +32,12 @@ function blob(entries: Record): string { } describe('token-connect-cmd', () => { - let backups: Record; + useTempStateDir(); + let logs: string[]; let originalLog: typeof console.log; - const paths = [ - resolveOAuthPath(), - resolveTokenMetaPath(), - resolveTokenPath(), - resolveContextPath(), - ]; - beforeEach(() => { - backups = {}; - for (const p of paths) { - backups[p] = fs.existsSync(p) ? fs.readFileSync(p, 'utf-8') : null; - if (fs.existsSync(p)) fs.unlinkSync(p); - } logs = []; originalLog = console.log; console.log = (...args) => logs.push(args.join(' ')); @@ -60,11 +45,6 @@ describe('token-connect-cmd', () => { afterEach(() => { console.log = originalLog; - for (const p of paths) { - const backup = backups[p]; - if (backup != null) fs.writeFileSync(p, backup); - else if (fs.existsSync(p)) fs.unlinkSync(p); - } }); it('parses a pasted blob and stores portalUrl, appId, refreshToken', async () => { diff --git a/test/token-core.test.ts b/test/token-core.test.ts index 732aaa7..769b653 100644 --- a/test/token-core.test.ts +++ b/test/token-core.test.ts @@ -2,26 +2,12 @@ import * as chai from 'chai'; import fs from 'fs'; import { getToken, setTokenValue } from '../lib/token-core.js'; import { resolveTokenPath } from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; describe('token-core', () => { - let backup: string | null; - - beforeEach(() => { - backup = fs.existsSync(resolveTokenPath()) - ? fs.readFileSync(resolveTokenPath(), 'utf-8') - : null; - if (fs.existsSync(resolveTokenPath())) fs.unlinkSync(resolveTokenPath()); - }); - - afterEach(() => { - if (backup !== null) { - fs.writeFileSync(resolveTokenPath(), backup); - } else if (fs.existsSync(resolveTokenPath())) { - fs.unlinkSync(resolveTokenPath()); - } - }); + useTempStateDir(); describe('getToken', () => { it('returns null when no token file exists', () => { @@ -40,7 +26,7 @@ describe('token-core', () => { }); describe('setTokenValue', () => { - it('writes the token to resolveTokenPath()', () => { + it('writes the token to the resolved token path', () => { setTokenValue('new-token'); expect(fs.readFileSync(resolveTokenPath(), 'utf-8')).to.equal( 'new-token' diff --git a/test/token-refresh-cmd.test.ts b/test/token-refresh-cmd.test.ts index 65d3927..53d32ec 100644 --- a/test/token-refresh-cmd.test.ts +++ b/test/token-refresh-cmd.test.ts @@ -1,5 +1,4 @@ import * as chai from 'chai'; -import fs from 'fs'; import { getToken } from '../lib/token-core.js'; import { ArcqError } from '../lib/errors.js'; import { @@ -10,11 +9,7 @@ import { } from '../lib/oauth-core.js'; import tokenRefreshCmd from '../lib/token-refresh-cmd.js'; import type { OAuthTokenResponse } from '../lib/types.js'; -import { - resolveOAuthPath, - resolveTokenMetaPath, - resolveTokenPath, -} from '../lib/paths-core.js'; +import { useTempStateDir } from './state-dir.js'; const { expect } = chai; @@ -25,7 +20,8 @@ const CONFIG: OAuthConfig = { }; describe('token-refresh-cmd', () => { - let backups: Record; + useTempStateDir(); + let logs: string[]; let originalLog: typeof console.log; @@ -34,15 +30,6 @@ describe('token-refresh-cmd', () => { } beforeEach(() => { - backups = {}; - for (const p of [ - resolveOAuthPath(), - resolveTokenMetaPath(), - resolveTokenPath(), - ]) { - backups[p] = fs.existsSync(p) ? fs.readFileSync(p, 'utf-8') : null; - if (fs.existsSync(p)) fs.unlinkSync(p); - } logs = []; originalLog = console.log; console.log = (...args) => logs.push(args.join(' ')); @@ -50,15 +37,6 @@ describe('token-refresh-cmd', () => { afterEach(() => { console.log = originalLog; - for (const p of [ - resolveOAuthPath(), - resolveTokenMetaPath(), - resolveTokenPath(), - ]) { - const backup = backups[p]; - if (backup != null) fs.writeFileSync(p, backup); - else if (fs.existsSync(p)) fs.unlinkSync(p); - } }); it('saves the token and meta and prints the expiry on success', async () => { From 0978a4f015ffb61cdd828ed46459d6aacf7e3c7b Mon Sep 17 00:00:00 2001 From: James Easter Date: Tue, 25 Aug 2026 21:51:43 -0500 Subject: [PATCH 4/5] Prove an isolated ARCQ_HOME sends no token from the home directory. --- test/bin.test.ts | 85 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 12 deletions(-) diff --git a/test/bin.test.ts b/test/bin.test.ts index a4d071a..71ad8c9 100644 --- a/test/bin.test.ts +++ b/test/bin.test.ts @@ -13,6 +13,10 @@ const TSX = path.join(ROOT, 'node_modules', '.bin', 'tsx'); const BIN = path.join(ROOT, 'bin', 'arcq.ts'); const TEMP_CONFIG = path.join(os.tmpdir(), 'arcq-test-bin-config.json'); const TEMP_HOME = path.join(os.tmpdir(), 'arcq-test-bin-home'); +// A stand-in for the developer's real home: it holds a token, and no test may +// let that token reach the server when ARCQ_HOME points somewhere else. +const DECOY_HOME = path.join(os.tmpdir(), 'arcq-test-bin-decoy-home'); +const DECOY_TOKEN = 'decoy-home-token'; interface BinResult { status: number | null; @@ -30,29 +34,43 @@ describe('bin/arcq', function () { let server: http.Server; let baseUrl: string; let handler: (req: http.IncomingMessage, res: http.ServerResponse) => void; + let bodies: URLSearchParams[]; function respond(data: unknown) { handler = (req: http.IncomingMessage, res: http.ServerResponse) => { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify(data)); + let raw = ''; + req.on('data', (chunk) => { + raw += chunk; + }); + req.on('end', () => { + bodies.push(new URLSearchParams(raw)); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(data)); + }); }; } - function runBin(args: string[]): Promise { + function runBin( + args: string[], + envOverrides: Record = {} + ): Promise { return new Promise((resolve, reject) => { // The child gets an empty temp state directory so the developer's real // token and OAuth files can't leak in (a real OAuth setup would turn the // token-error test into a live credential-command run and portal // request). HOME is overridden too, in case anything else consults it. - const child = spawn(TSX, [BIN, ...args], { - env: { - ...process.env, - ARCQ_CONFIG: TEMP_CONFIG, - ARCQ_HOME: TEMP_HOME, - HOME: TEMP_HOME, - USERPROFILE: TEMP_HOME, - }, - }); + const env: Record = { + ...process.env, + ARCQ_CONFIG: TEMP_CONFIG, + ARCQ_HOME: TEMP_HOME, + HOME: TEMP_HOME, + USERPROFILE: TEMP_HOME, + ...envOverrides, + }; + for (const [key, value] of Object.entries(envOverrides)) { + if (value === undefined) delete env[key]; + } + const child = spawn(TSX, [BIN, ...args], { env }); let stdout = ''; let stderr = ''; child.stdout.on('data', (d: Buffer) => (stdout += d.toString())); @@ -62,9 +80,17 @@ describe('bin/arcq', function () { }); } + beforeEach(() => { + bodies = []; + }); + before(async () => { fs.writeFileSync(TEMP_CONFIG, '{}'); fs.mkdirSync(TEMP_HOME, { recursive: true }); + fs.mkdirSync(DECOY_HOME, { recursive: true }); + fs.writeFileSync(path.join(DECOY_HOME, '.arcq-token'), DECOY_TOKEN, { + mode: 0o600, + }); server = http.createServer((req, res) => handler(req, res)); await new Promise((resolve) => { server.listen(0, '127.0.0.1', () => { @@ -77,6 +103,7 @@ describe('bin/arcq', function () { after(async () => { if (fs.existsSync(TEMP_CONFIG)) fs.unlinkSync(TEMP_CONFIG); fs.rmSync(TEMP_HOME, { recursive: true, force: true }); + fs.rmSync(DECOY_HOME, { recursive: true, force: true }); await new Promise((resolve) => server.close(() => resolve())); }); @@ -102,4 +129,38 @@ describe('bin/arcq', function () { expect(res.status).to.equal(0); expect(res.stdout.trim()).to.match(/^\d+\.\d+\.\d+$/); }); + + // The defect ARCQ_HOME exists to fix: state other than the config stayed + // bound to the home directory, so a token minted for one portal was sent to + // whatever host the queried service happened to live on. + describe('state isolation', () => { + it('sends no token when ARCQ_HOME is an empty directory', async () => { + respond({ features: [] }); + const isolated = fs.mkdtempSync(path.join(os.tmpdir(), 'arcq-isolated-')); + try { + const res = await runBin(['-q', baseUrl, '1=1'], { + ARCQ_HOME: isolated, + HOME: DECOY_HOME, + USERPROFILE: DECOY_HOME, + }); + expect(res.status).to.equal(0); + expect(bodies).to.have.length(1); + expect(bodies[0]!.has('token')).to.equal(false); + } finally { + fs.rmSync(isolated, { recursive: true, force: true }); + } + }); + + it('still sends the home-directory token when ARCQ_HOME is unset', async () => { + respond({ features: [] }); + const res = await runBin(['-q', baseUrl, '1=1'], { + ARCQ_HOME: undefined, + HOME: DECOY_HOME, + USERPROFILE: DECOY_HOME, + }); + expect(res.status).to.equal(0); + expect(bodies).to.have.length(1); + expect(bodies[0]!.get('token')).to.equal(DECOY_TOKEN); + }); + }); }); From 9ac7dd897731484f06927c3e9879484cb59ab64d Mon Sep 17 00:00:00 2001 From: James Easter Date: Tue, 25 Aug 2026 21:53:08 -0500 Subject: [PATCH 5/5] Document the ARCQ_HOME state directory in the README, help, and skill. --- README.md | 28 +++++++++++++++++++++++++++- lib/help-cmd.ts | 11 +++++++++-- skills/arcq/SKILL.md | 10 ++++++++++ test/help-cmd.test.ts | 42 +++++++++++++++++++++++++++++++++++------- 4 files changed, 81 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 88e271c..bae31b0 100644 --- a/README.md +++ b/README.md @@ -124,10 +124,36 @@ Two more hardening details: - The auth token is stored at `~/.arcq-token` with file mode `600` (owner read/write only). OAuth refresh credentials (`~/.arcq-oauth.json`) and the token-expiry meta (`~/.arcq-token-meta.json`) are written `600` as well - see [Authentication](#authentication) for the trade-off between a stored refresh token and a `--command` credential helper. - Requests are sent as HTTP `POST` with form-encoded bodies, so the token is never placed in a URL query string where it would land in server or proxy access logs. +- The stored token is sent to whatever host the queried service lives on. If you work with more than one portal, give each its own state directory via `ARCQ_HOME` (see [State directory](#state-directory)) so a token minted for one portal is never sent to another. + +## State directory + +All six of arcq's state files live in your home directory by default: + +| File | Purpose | +| ------------------------- | ------------------------ | +| `~/.arcq.json` | Service/layer URL config | +| `~/.arcq-context.json` | Active layer selection | +| `~/.arcq-cache.json` | Cached layer catalog | +| `~/.arcq-token` | ArcGIS auth token | +| `~/.arcq-oauth.json` | OAuth refresh credential | +| `~/.arcq-token-meta.json` | Access-token expiry | + +Set `ARCQ_HOME` to keep a complete, independent set somewhere else. It is created on first write with mode `700`: + +```bash +export ARCQ_HOME=~/.arcq-portal-a +arcq token set +arcq services add my-service "https://portal-a.example.com/arcgis/rest/services" +``` + +A second portal gets a second directory, and neither one's token can reach the other's host. + +`ARCQ_CONFIG` still names a single config file and takes precedence over `ARCQ_HOME`, so an existing setup that points it at a shared config keeps working. Note that it isolates _only_ the config - the token and OAuth credential follow `ARCQ_HOME`. ## Configuration -arcq reads a JSON config file from `~/.arcq.json` by default. Override the path with the `ARCQ_CONFIG` environment variable. +arcq reads a JSON config file from `~/.arcq.json` by default (or `$ARCQ_HOME/.arcq.json`; see [State directory](#state-directory)). Override the path directly with the `ARCQ_CONFIG` environment variable, which wins over `ARCQ_HOME`. ```json { diff --git a/lib/help-cmd.ts b/lib/help-cmd.ts index 92beabb..0f93a06 100644 --- a/lib/help-cmd.ts +++ b/lib/help-cmd.ts @@ -1,4 +1,4 @@ -import { resolveConfigPath } from './paths-core.js'; +import { resolveConfigPath, resolveStateDir } from './paths-core.js'; export default function helpCmd(): void { console.log(` @@ -57,8 +57,15 @@ Examples: arcq query --limit 5 --out-fields OBJECTID,STATUS "STATUS = 'ACTIVE'" arcq parcels "1=1" +State directory: + ${resolveStateDir()} (override with ARCQ_HOME env var) + + Holds .arcq.json, .arcq-context.json, .arcq-cache.json, .arcq-token, + .arcq-oauth.json, and .arcq-token-meta.json. Point ARCQ_HOME at a separate + directory per portal to keep one portal's token from reaching another. + Config: - ${resolveConfigPath()} (override with ARCQ_CONFIG env var) + ${resolveConfigPath()} (override with ARCQ_CONFIG env var, which wins over ARCQ_HOME) { "services": { "my-service": "https://example.com/.../FeatureServer" }, diff --git a/skills/arcq/SKILL.md b/skills/arcq/SKILL.md index fc338cb..6e04f19 100644 --- a/skills/arcq/SKILL.md +++ b/skills/arcq/SKILL.md @@ -92,6 +92,16 @@ query/list/fields commands auto-refresh once on an exit-2 before giving up. (never the refresh token itself). Use `example.com` hosts and placeholder ids when demonstrating this to a user. +## State directory + +arcq's config, context, cache, token, OAuth credential, and token-expiry files +all live in the user's home directory unless `ARCQ_HOME` points at another +directory, which holds a complete independent set. A user working with more +than one portal should have one directory per portal - without that, the token +stored for one portal is sent to whatever host the queried service lives on. +`ARCQ_CONFIG` overrides the config file alone and wins over `ARCQ_HOME`; it +does not isolate the token. + ## TLS Certificates are verified by default. If a query fails with a TLS diff --git a/test/help-cmd.test.ts b/test/help-cmd.test.ts index 9ac2e28..172420d 100644 --- a/test/help-cmd.test.ts +++ b/test/help-cmd.test.ts @@ -19,20 +19,24 @@ function captureHelp(): string { describe('help-cmd', () => { let output: string; - let originalEnv: string | undefined; + let originalConfig: string | undefined; + let originalHome: string | undefined; + // Both overrides are cleared so the default-path assertions below describe + // what a user with no arcq environment set would actually see. beforeEach(() => { - originalEnv = process.env.ARCQ_CONFIG; + originalConfig = process.env.ARCQ_CONFIG; + originalHome = process.env.ARCQ_HOME; delete process.env.ARCQ_CONFIG; + delete process.env.ARCQ_HOME; output = captureHelp(); }); afterEach(() => { - if (originalEnv === undefined) { - delete process.env.ARCQ_CONFIG; - } else { - process.env.ARCQ_CONFIG = originalEnv; - } + if (originalConfig === undefined) delete process.env.ARCQ_CONFIG; + else process.env.ARCQ_CONFIG = originalConfig; + if (originalHome === undefined) delete process.env.ARCQ_HOME; + else process.env.ARCQ_HOME = originalHome; }); it('prints output', () => { @@ -78,6 +82,30 @@ describe('help-cmd', () => { expect(output).to.include(path.join(os.homedir(), '.arcq.json')); }); + it('shows the state directory and names ARCQ_HOME', () => { + expect(output).to.include('State directory'); + expect(output).to.include(os.homedir()); + expect(output).to.include('ARCQ_HOME'); + }); + + it('reflects an ARCQ_HOME override in both paths', () => { + const override = path.join(os.tmpdir(), 'arcq-help-test-home'); + process.env.ARCQ_HOME = override; + const help = captureHelp(); + expect(help).to.include(override); + expect(help).to.include(path.join(override, '.arcq.json')); + }); + + it('keeps ARCQ_CONFIG winning over ARCQ_HOME', () => { + const home = path.join(os.tmpdir(), 'arcq-help-test-home'); + const config = path.join(os.tmpdir(), 'arcq-help-test-explicit.json'); + process.env.ARCQ_HOME = home; + process.env.ARCQ_CONFIG = config; + const help = captureHelp(); + expect(help).to.include(config); + expect(help).to.not.include(path.join(home, '.arcq.json')); + }); + it('reflects an ARCQ_CONFIG override in the config path', () => { const override = path.join(os.tmpdir(), 'arcq-help-test.json'); const original = process.env.ARCQ_CONFIG;