Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
13 changes: 6 additions & 7 deletions lib/cache-core.ts
Original file line number Diff line number Diff line change
@@ -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));
}
8 changes: 3 additions & 5 deletions lib/config-core.ts
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -18,5 +15,6 @@ export function loadConfig(): Config {
}

export function saveConfig(config: Config): void {
ensureStateDir();
fs.writeFileSync(resolveConfigPath(), JSON.stringify(config, null, 2));
}
13 changes: 6 additions & 7 deletions lib/context-core.ts
Original file line number Diff line number Diff line change
@@ -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));
}
11 changes: 9 additions & 2 deletions lib/help-cmd.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { resolveConfigPath } from './config-core.js';
import { resolveConfigPath, resolveStateDir } from './paths-core.js';

export default function helpCmd(): void {
console.log(`
Expand Down Expand Up @@ -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" },
Expand Down
24 changes: 14 additions & 10 deletions lib/oauth-core.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 ||
Expand All @@ -55,14 +55,16 @@ 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);
}

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;
Expand All @@ -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);
}
Expand Down
49 changes: 49 additions & 0 deletions lib/paths-core.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
5 changes: 4 additions & 1 deletion lib/token-connect-cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 4 additions & 4 deletions lib/token-core.ts
Original file line number Diff line number Diff line change
@@ -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();
}
Expand All @@ -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);
}
10 changes: 10 additions & 0 deletions skills/arcq/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 5 additions & 17 deletions test/active-cmd.test.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,30 @@
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';
import { useTempStateDir } from './state-dir.js';

const { expect } = chai;

const CONTEXT_PATH = path.join(os.homedir(), '.arcq-context.json');

describe('active-cmd', () => {
let contextBackup: string | null;
useTempStateDir();

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')
: null;
if (fs.existsSync(CONTEXT_PATH)) fs.unlinkSync(CONTEXT_PATH);

logs = [];
originalLog = console.log;
console.log = (...args) => logs.push(args.join(' '));
});

afterEach(() => {
console.log = originalLog;

if (contextBackup !== null) {
fs.writeFileSync(CONTEXT_PATH, contextBackup);
} else if (fs.existsSync(CONTEXT_PATH)) {
fs.unlinkSync(CONTEXT_PATH);
}
});

it('prints service:id → name and the url for a full context', () => {
Expand Down
Loading
Loading