@oneie/cli 4.1.0 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,10 @@
1
1
  import { Command } from 'commander';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
- import { homedir } from 'node:os';
4
- import { resolve } from 'node:path';
5
3
  import { mergeEnv } from './env.js';
6
4
  import { resolveBase, resolveKey, authHeaders } from './lib/client.js';
5
+ import { readKeyFolder, keyFolderStatus } from './lib/keyfile.js';
6
+ import { KEY_FILE } from './lib/paths.js';
7
7
  import { askPath } from './lib/api-path.js';
8
- const KEY_FILE = resolve(homedir(), '.config', 'oneie', 'key');
9
8
  /** api.one.ie (the gateway) answers `GET /health`; one.ie/web has no /health
10
9
  * route, so a HEAD / 200 is the reachability signal there — same host split
11
10
  * askPath() already makes for /ask. */
@@ -34,14 +33,70 @@ export async function runDoctor(dir, opts = {}) {
34
33
  const keyFile = opts.keyFile ?? KEY_FILE;
35
34
  const env = mergeEnv(dir);
36
35
  const checks = [];
37
- const hasConfig = existsSync(keyFile) || Boolean(env.ONE_API_KEY) || Boolean(env.ONEIE_API_KEY);
36
+ // A folder key outranks the machine key, the same order resolveKey uses — so
37
+ // doctor reports the credential the commands will actually send.
38
+ const folder = readKeyFolder(dir);
39
+ // A REFUSED folder key must be explained, not silently skipped. `foreign` means
40
+ // a .oneie/agent.key exists here but was minted for another directory — the
41
+ // credential-confusion guard. Silence would leave the operator staring at a key
42
+ // on disk that nothing uses, with no way to tell that from a bug.
43
+ const folderState = keyFolderStatus(dir);
44
+ if (folderState === 'foreign' || folderState === 'unsafe' || folderState === 'unreadable') {
45
+ checks.push({
46
+ name: 'folder-key',
47
+ ok: false,
48
+ detail: folderState === 'foreign'
49
+ ? 'a .oneie/agent.key here was minted for a DIFFERENT directory or machine — ignored. Run `one init --dir .` to mint one for this project.'
50
+ : folderState === 'unsafe'
51
+ ? 'a .oneie/agent.key here is a symlink, group/world-readable, or owned by another user — ignored. Delete it and re-mint.'
52
+ : 'a .oneie/agent.key here is empty or unreadable — ignored.',
53
+ });
54
+ }
55
+ const hasConfig = Boolean(folder) || existsSync(keyFile) || Boolean(env.ONE_API_KEY) || Boolean(env.ONEIE_API_KEY);
38
56
  checks.push({
39
57
  name: 'config',
40
58
  ok: hasConfig,
41
- detail: hasConfig ? `${keyFile} (0600)` : `${keyFile} missing — run \`one setup\` or \`one login\``,
59
+ detail: folder
60
+ ? `${dir}/.oneie/agent.key (0600, project)`
61
+ : hasConfig
62
+ ? `${keyFile} (0600)`
63
+ : `${keyFile} missing — run \`one setup\` or \`one login\``,
42
64
  });
43
- const key = env.ONE_API_KEY || env.ONEIE_API_KEY || (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
65
+ const key = env.ONE_API_KEY ||
66
+ env.ONEIE_API_KEY ||
67
+ folder?.apiKey ||
68
+ (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
44
69
  checks.push({ name: 'key', ok: Boolean(key), detail: key ? `${key.slice(0, 4)}***…` : 'no key found' });
70
+ // EXPIRY. Keys minted by the anonymous provision door carry a 90-day
71
+ // valid_to, and verifyWorldKey enforces it in SQL — so an unwatched folder
72
+ // key stops working one day with a bare 401, which `packages/cli/CLAUDE.md`
73
+ // documents as indistinguishable from a WRONG key. The metadata already
74
+ // records the date; reading it is what turns a scheduled outage into a
75
+ // warning. An absent expiresAt means a permanent key, not an unknown one, so
76
+ // it reports ok and says so rather than inventing a doubt.
77
+ const expiresAt = folder?.meta.expiresAt;
78
+ if (typeof expiresAt === 'string') {
79
+ const ms = Date.parse(expiresAt);
80
+ if (Number.isNaN(ms)) {
81
+ checks.push({ name: 'key-expiry', ok: false, detail: `unreadable expiresAt: ${expiresAt}` });
82
+ }
83
+ else {
84
+ const days = Math.floor((ms - Date.now()) / 86_400_000);
85
+ checks.push({
86
+ name: 'key-expiry',
87
+ // Expired is a failure; expiring is not, or doctor cries wolf for 83 days.
88
+ ok: days > 0,
89
+ detail: days > 14
90
+ ? `expires in ${days} days`
91
+ : days > 0
92
+ ? `expires in ${days} days — renew with \`one init --dir .\``
93
+ : `EXPIRED ${-days} days ago — renew with \`one init --dir .\``,
94
+ });
95
+ }
96
+ }
97
+ else if (folder) {
98
+ checks.push({ name: 'key-expiry', ok: true, detail: 'no expiry recorded (permanent key)' });
99
+ }
45
100
  const base = resolveBase({ api: opts.api });
46
101
  const reach = await checkReachability(base);
47
102
  checks.push({ name: 'substrate', ok: reach.ok, detail: `${base} ${reach.ms}ms` });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function endpointCmd(): Command;
@@ -0,0 +1,250 @@
1
+ import { Command } from 'commander';
2
+ import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
3
+ import { askPath } from './lib/api-path.js';
4
+ // `one endpoint` — enter your OWN https endpoints once, then name them from a
5
+ // workflow step.
6
+ //
7
+ // WHY A SUBCOMMAND RATHER THAN `one ask endpoint:register`. Three things a raw
8
+ // ask cannot do, and each one is a mistake a creator would otherwise make:
9
+ //
10
+ // add a SECRET is a credential, and pasting it into a shell as JSON puts it
11
+ // in the shell history. `--secret-env VAR` reads it from the environment
12
+ // instead, and the printed row never echoes it back.
13
+ // test `endpoint:call --dryRun` answers the GUARD question without spending a
14
+ // request. A creator's first failure is almost always the url, not the
15
+ // payload, and this names the reason — https_required, ip_literal,
16
+ // private_hostname, dns_unresolved, blocked_address.
17
+ // list the sealed secret has no read door anywhere, so the renderer prints
18
+ // `secret=yes|no`. A raw ask would print the same JSON; the point is that
19
+ // there is nothing else to print, and the column says so out loud.
20
+ //
21
+ // call IS here too, because a creator who cannot call his own endpoint from the
22
+ // terminal cannot tell a broken endpoint from a broken workflow.
23
+ const DEFAULT_API = 'https://api.one.ie';
24
+ function asker(api) {
25
+ const base = resolveBase({ api }, DEFAULT_API);
26
+ return async (receiver, data) => {
27
+ const res = await fetch(askPath(base, receiver), {
28
+ method: 'POST',
29
+ headers: authHeaders(),
30
+ body: JSON.stringify({ data }),
31
+ });
32
+ const text = await res.text();
33
+ let body;
34
+ try {
35
+ body = text ? JSON.parse(text) : undefined;
36
+ }
37
+ catch {
38
+ throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
39
+ }
40
+ if (!res.ok && !(body && typeof body === 'object' && 'outcome' in body)) {
41
+ throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
42
+ }
43
+ if (!body || typeof body !== 'object')
44
+ throw new Error(`${receiver}: empty response`);
45
+ const o = body;
46
+ if ('outcome' in o) {
47
+ if (o.outcome === 'result')
48
+ return o.result ?? {};
49
+ const inner = o.result;
50
+ if (inner && typeof inner === 'object' && ('ok' in inner || 'error' in inner)) {
51
+ return { ok: false, ...inner, error: inner.error ?? String(o.outcome) };
52
+ }
53
+ throw new Error(`${receiver}: ${String(o.outcome)}`);
54
+ }
55
+ if ('result' in o)
56
+ return o.result ?? {};
57
+ return o;
58
+ };
59
+ }
60
+ function fail(msg) {
61
+ process.stderr.write(`${msg}\n`);
62
+ process.exitCode = 1;
63
+ }
64
+ function renderRows(rows) {
65
+ const w = process.stdout;
66
+ if (!rows.length) {
67
+ w.write('no endpoints registered\n');
68
+ return;
69
+ }
70
+ w.write(`${rows.length} endpoint${rows.length === 1 ? '' : 's'}\n\n`);
71
+ for (const r of rows) {
72
+ w.write(`${r.name} ${r.method} ${r.url}\n` +
73
+ ` returns=${r.returnMode} timeout=${r.timeoutMs}ms max=${r.maxBytes}B ` +
74
+ `secret=${r.hasSecret ? `yes (${r.authHeader})` : 'no'} status=${r.status}` +
75
+ `${r.lastStatus ? ` last=${r.lastStatus}` : ''}\n`);
76
+ }
77
+ }
78
+ function parseJsonOption(raw) {
79
+ if (raw === undefined)
80
+ return undefined;
81
+ try {
82
+ const v = JSON.parse(raw);
83
+ if (!v || typeof v !== 'object' || Array.isArray(v))
84
+ return 'bad';
85
+ return v;
86
+ }
87
+ catch {
88
+ return 'bad';
89
+ }
90
+ }
91
+ export function endpointCmd() {
92
+ const cmd = new Command('endpoint').description('Your own https endpoints — register one under a handle, then name it from a workflow `tool` step ' +
93
+ '(config: { receiver: "endpoint:call", args: { endpoint: "<handle>", input: {…} } })');
94
+ cmd
95
+ .command('add <name> <url>')
96
+ .description('Register or update an endpoint. The url is SSRF-checked here and again on every call.')
97
+ .option('--workspace <slug>', 'Group slug (default: your own). A workspace you may not write is REFUSED, never downgraded.')
98
+ .option('--method <m>', 'GET | POST | PUT | PATCH', 'POST')
99
+ .option('--returns <mode>', 'json (the answer) | url (a link we fetch and file) | bytes (an image we file)', 'json')
100
+ .option('--auth-header <name>', 'Header NAME the secret travels in, e.g. Authorization')
101
+ .option('--secret-env <VAR>', 'Read the secret from this environment variable — never from the command line, which the shell records')
102
+ .option('--timeout <ms>', 'Per-call timeout. Default 20000, clamped 1000–120000.')
103
+ .option('--max-bytes <n>', 'Response byte ceiling. Default 5242880, clamped to 10485760.')
104
+ .option('--api <url>', 'API base URL', DEFAULT_API)
105
+ .option('--json', 'Print the raw response')
106
+ .action(async (name, url, opts, sub) => {
107
+ let secret;
108
+ if (opts.secretEnv) {
109
+ secret = process.env[opts.secretEnv];
110
+ // An unset variable is a REFUSAL, not an unauthenticated registration —
111
+ // silently registering without the credential would send an anonymous
112
+ // request to a host that answers 401, and the creator would debug the url.
113
+ if (!secret)
114
+ return fail(`--secret-env ${opts.secretEnv} is unset or empty in this environment`);
115
+ if (!opts.authHeader)
116
+ return fail('--secret-env needs --auth-header (the header the secret travels in)');
117
+ }
118
+ const data = {
119
+ name,
120
+ url,
121
+ method: opts.method.toUpperCase(),
122
+ returnMode: opts.returns,
123
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
124
+ ...(opts.authHeader ? { authHeader: opts.authHeader } : {}),
125
+ ...(secret ? { secret } : {}),
126
+ ...(opts.timeout ? { timeoutMs: Number(opts.timeout) } : {}),
127
+ ...(opts.maxBytes ? { maxBytes: Number(opts.maxBytes) } : {}),
128
+ };
129
+ let res;
130
+ try {
131
+ res = (await asker(opts.api)('endpoint:register', data));
132
+ }
133
+ catch (e) {
134
+ return fail(e instanceof Error ? e.message : String(e));
135
+ }
136
+ if (jsonMode(sub))
137
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
138
+ else if (res.ok !== false && res.endpoint)
139
+ renderRows([res.endpoint]);
140
+ if (res.ok === false)
141
+ fail(res.error ?? 'endpoint:register failed');
142
+ });
143
+ cmd
144
+ .command('list')
145
+ .description('List registered endpoints. The sealed secret has no read door — the column says yes or no.')
146
+ .option('--workspace <slug>', 'Group slug (default: your own)')
147
+ .option('--api <url>', 'API base URL', DEFAULT_API)
148
+ .option('--json', 'Print the raw response')
149
+ .action(async (opts, sub) => {
150
+ let res;
151
+ try {
152
+ res = (await asker(opts.api)('endpoint:list', opts.workspace ? { workspace: opts.workspace } : {}));
153
+ }
154
+ catch (e) {
155
+ return fail(e instanceof Error ? e.message : String(e));
156
+ }
157
+ if (jsonMode(sub))
158
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
159
+ else if (res.ok !== false)
160
+ renderRows(res.endpoints ?? []);
161
+ if (res.ok === false)
162
+ fail(res.error ?? 'endpoint:list failed');
163
+ });
164
+ cmd
165
+ .command('test <name>')
166
+ .description('Run the SSRF guard against a registered endpoint without spending a request — the reason comes back by name')
167
+ .option('--workspace <slug>', 'Group slug (default: your own)')
168
+ .option('--api <url>', 'API base URL', DEFAULT_API)
169
+ .option('--json', 'Print the raw response')
170
+ .action(async (name, opts, sub) => {
171
+ let res;
172
+ try {
173
+ res = (await asker(opts.api)('endpoint:call', {
174
+ endpoint: name,
175
+ dryRun: true,
176
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
177
+ }));
178
+ }
179
+ catch (e) {
180
+ return fail(e instanceof Error ? e.message : String(e));
181
+ }
182
+ if (jsonMode(sub))
183
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
184
+ else if (res.ok !== false)
185
+ process.stdout.write(`guard ${res.guard ?? 'passed'} ${res.url ?? ''}\n`);
186
+ if (res.ok === false)
187
+ fail(res.error ?? 'endpoint:call failed');
188
+ });
189
+ cmd
190
+ .command('call <name>')
191
+ .description('Call a registered endpoint for real — the same door a workflow `tool` step uses')
192
+ .option('--input <json>', 'The JSON object sent to your endpoint. The ONLY thing that crosses, beside its own sealed credential.')
193
+ .option('--returns <mode>', 'Override the row: json | url | bytes')
194
+ .option('--workspace <slug>', 'Group slug (default: your own)')
195
+ .option('--api <url>', 'API base URL', DEFAULT_API)
196
+ .option('--json', 'Print the raw response')
197
+ .action(async (name, opts, sub) => {
198
+ const input = parseJsonOption(opts.input);
199
+ if (input === 'bad')
200
+ return fail('--input must be a JSON object, e.g. \'{"title":"hello"}\'');
201
+ let res;
202
+ try {
203
+ res = (await asker(opts.api)('endpoint:call', {
204
+ endpoint: name,
205
+ ...(input ? { input } : {}),
206
+ ...(opts.returns ? { returnMode: opts.returns } : {}),
207
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
208
+ }));
209
+ }
210
+ catch (e) {
211
+ return fail(e instanceof Error ? e.message : String(e));
212
+ }
213
+ if (jsonMode(sub) || res.ok === false) {
214
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
215
+ }
216
+ else if (res.url) {
217
+ process.stdout.write(`${res.url} ${res.contentType ?? ''} ${res.size ?? '?'}B\n`);
218
+ }
219
+ else {
220
+ process.stdout.write(JSON.stringify(res.json ?? res.text ?? res, null, 2) + '\n');
221
+ }
222
+ if (res.ok === false)
223
+ fail(String(res.error ?? 'endpoint:call failed'));
224
+ });
225
+ cmd
226
+ .command('rm <name>')
227
+ .description('Delete a registered endpoint. Deleting something absent answers not_found, never a quiet success.')
228
+ .option('--workspace <slug>', 'Group slug (default: your own)')
229
+ .option('--api <url>', 'API base URL', DEFAULT_API)
230
+ .option('--json', 'Print the raw response')
231
+ .action(async (name, opts, sub) => {
232
+ let res;
233
+ try {
234
+ res = (await asker(opts.api)('endpoint:remove', {
235
+ name,
236
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
237
+ }));
238
+ }
239
+ catch (e) {
240
+ return fail(e instanceof Error ? e.message : String(e));
241
+ }
242
+ if (jsonMode(sub))
243
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
244
+ else if (res.ok !== false)
245
+ process.stdout.write(`removed ${name}\n`);
246
+ if (res.ok === false)
247
+ fail(res.error ?? 'endpoint:remove failed');
248
+ });
249
+ return cmd;
250
+ }
package/dist/src/eval.js CHANGED
@@ -18,6 +18,7 @@ export function evalCmd() {
18
18
  channelsUrl: opts.channels.replace(/\/$/, ''),
19
19
  eventsUrl: opts.events.replace(/\/$/, ''),
20
20
  groqApiKey: process.env.GROQ_API_KEY,
21
+ typesafeApiKey: process.env.TYPESAFE_API_KEY,
21
22
  });
22
23
  const failed = results.filter((r) => r.failed > 0).length;
23
24
  out({ ok: failed === 0, total: results.length, passed: results.length - failed, results });
package/dist/src/index.js CHANGED
@@ -33,6 +33,10 @@ import { initCmd } from './init.js';
33
33
  import { onboardCmd } from './onboard.js';
34
34
  import { pluginCmd } from './plugin.js';
35
35
  import { workflowCmd } from './workflow.js';
36
+ import { tasksCmd } from './tasks.js';
37
+ import { mediaCmd } from './media.js';
38
+ import { endpointCmd } from './endpoint.js';
39
+ import { shopCmd } from './shop.js';
36
40
  import { readFileSync } from 'node:fs';
37
41
  import { fileURLToPath } from 'node:url';
38
42
  import { resolve, dirname } from 'node:path';
@@ -78,6 +82,10 @@ program.addCommand(initCmd());
78
82
  program.addCommand(onboardCmd());
79
83
  program.addCommand(pluginCmd());
80
84
  program.addCommand(workflowCmd());
85
+ program.addCommand(tasksCmd());
86
+ program.addCommand(mediaCmd());
87
+ program.addCommand(endpointCmd());
88
+ program.addCommand(shopCmd());
81
89
  // Bare `oneie` (no args, no --help/--version): route the audience to its
82
90
  // journey instead of commander's default help dump. Never an interactive
83
91
  // prompt — agent env and human TTY both get a printed block (contract #10).
package/dist/src/init.js CHANGED
@@ -14,6 +14,7 @@ import { homedir } from 'node:os';
14
14
  import { renameSync, chmodSync } from 'node:fs';
15
15
  import { join } from 'node:path';
16
16
  import { mergeEnv, writeEnvLocal } from './env.js';
17
+ import { writeKeyFolder } from './lib/keyfile.js';
17
18
  const DEFAULT_API = process.env.ONEIE_BASE_URL ?? 'https://one.ie';
18
19
  const CONFIG_DIR = resolve(homedir(), '.config', 'oneie');
19
20
  const KEY_FILE = resolve(CONFIG_DIR, 'key');
@@ -66,6 +67,8 @@ export function initCmd() {
66
67
  .option('--no-content', 'Skip generating a starter agent.md')
67
68
  .option('--api <url>', 'API base URL', DEFAULT_API)
68
69
  .option('--write-env', 'Also write ONE_API_KEY to .env.local in the current directory')
70
+ .option('--dir <path>', 'Write the key into THIS project folder (.oneie/agent.key, 0600, gitignored) instead of the machine-wide ~/.config/oneie/key')
71
+ .option('--ttl-days <n>', 'Key lifetime in days (default 90, max 365)')
69
72
  .action(async (opts) => {
70
73
  const dir = process.cwd();
71
74
  if (opts.writeEnv) {
@@ -85,6 +88,8 @@ export function initCmd() {
85
88
  body.skills = skills;
86
89
  if (opts.email)
87
90
  body.invite = { email: opts.email, role: 'owner' };
91
+ if (opts.ttlDays)
92
+ body.ttlDays = Number(opts.ttlDays);
88
93
  let res;
89
94
  try {
90
95
  res = await fetch(`${opts.api.replace(/\/$/, '')}/api/provision/agent`, {
@@ -102,8 +107,32 @@ export function initCmd() {
102
107
  out(cmd, { ok: false, ...json });
103
108
  return;
104
109
  }
105
- const { workspace, apiKey, inviteUrl } = json;
106
- writeKey(apiKey);
110
+ const { workspace, apiKey, regKey, uid, expiresAt, inviteUrl } = json;
111
+ // --dir writes the credential INTO the project, which is narrower than the
112
+ // machine-wide default: one project's key, revocable alone, gone when the
113
+ // folder is. The ceremony writes the ignore entry BEFORE the key and
114
+ // refuses to write a key at all if it cannot — see lib/keyfile.ts.
115
+ let keyLocation;
116
+ if (opts.dir) {
117
+ const res = writeKeyFolder({
118
+ dir: opts.dir,
119
+ apiKey,
120
+ regKey,
121
+ workspace,
122
+ uid,
123
+ api: opts.api,
124
+ expiresAt,
125
+ });
126
+ if (!res.ok) {
127
+ out(cmd, { ok: false, error: res.error ?? 'could not write key folder' });
128
+ return;
129
+ }
130
+ keyLocation = `${res.keyPath} (0600, ignored via ${res.ignorePath})`;
131
+ }
132
+ else {
133
+ writeKey(apiKey);
134
+ keyLocation = `${KEY_FILE} (0600)`;
135
+ }
107
136
  if (opts.writeEnv) {
108
137
  writeEnvLocal(dir, { ONE_API_KEY: apiKey, ONE_API_URL: opts.api });
109
138
  }
@@ -111,7 +140,8 @@ export function initCmd() {
111
140
  ok: true,
112
141
  workspace,
113
142
  url: `${opts.api.replace(/\/$/, '')}/u/${workspace}`,
114
- key: `${KEY_FILE} (0600)`,
143
+ key: keyLocation,
144
+ ...(expiresAt ? { expires: new Date(expiresAt * 1000).toISOString() } : {}),
115
145
  ...(opts.writeEnv ? { env: `${dir}/.env.local`, mcp: 'export ONE_API_KEY before launching Claude Code — MCP reads the shell env, not .env.local directly' } : {}),
116
146
  ...(inviteUrl ? { invite: inviteUrl } : {}),
117
147
  ...(skills.length ? { skills: skills.join(', ') } : {}),
@@ -7,6 +7,13 @@ const AGENT_ENV_MARKERS = {
7
7
  CURSOR_TRACE_ID: 'cursor',
8
8
  WINDSURF: 'windsurf',
9
9
  GITHUB_COPILOT_CLI: 'copilot',
10
+ // Codex sets CODEX_SANDBOX (to "seatbelt" on macOS) for the child processes of
11
+ // its sandboxed tool calls. UNDOCUMENTED, and absent when sandboxing is off —
12
+ // so this NAMES a Codex shell when it can and never gates on it. The gate is
13
+ // still the TTY check below, which already answered true for every Codex shell;
14
+ // what was missing was `agentType()` being able to say WHICH agent, which is
15
+ // what the front door routes on.
16
+ CODEX_SANDBOX: 'codex',
10
17
  };
11
18
  /** The specific coding agent driving this shell, if env vars name one. */
12
19
  export function agentType(env = process.env) {
@@ -1,10 +1,9 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { resolve } from 'node:path';
1
+ import { readKeyFolder } from './keyfile.js';
2
+ import { readMachineKey } from './paths.js';
4
3
  // Every command resolves base URL, key, and --json the same way — this module
5
4
  // is the one place that knows the env contract. Composes askPath() from
6
5
  // ./api-path.js for the gateway-vs-web path split; does not replace it.
7
- const KEY_FILE = resolve(homedir(), '.config', 'oneie', 'key');
6
+ // Path canon lives in lib/paths.ts — six modules used to each carry their own.
8
7
  /** --api flag > ONE_API_URL (canonical) > ONEIE_BASE_URL (legacy) > fallback. ONE_BASE_URL is retired. */
9
8
  export function resolveBase(opts = {}, fallback = 'https://one.ie') {
10
9
  const base = opts.api ?? process.env.ONE_API_URL ?? process.env.ONEIE_BASE_URL ?? fallback;
@@ -18,9 +17,19 @@ export function resolveKey(opts = {}) {
18
17
  return process.env.ONE_API_KEY;
19
18
  if (process.env.ONEIE_API_KEY)
20
19
  return process.env.ONEIE_API_KEY;
21
- if (existsSync(KEY_FILE))
22
- return readFileSync(KEY_FILE, 'utf8').trim();
23
- return '';
20
+ // The PROJECT's key outranks the machine's. A folder that carries its own
21
+ // credential is saying "use mine", and `one init --dir .` wrote it there to
22
+ // narrow the blast radius — falling through to ~/.config/oneie/key would hand
23
+ // the command the machine-wide key instead and quietly undo that.
24
+ //
25
+ // Below the env vars on purpose: an explicit ONE_API_KEY in the shell is a
26
+ // deliberate override, and CI sets it that way.
27
+ const folder = readKeyFolder(process.cwd());
28
+ if (folder)
29
+ return folder.apiKey;
30
+ // readMachineKey tries ~/.config/one/key then the pre-rename ~/.config/oneie/key,
31
+ // so an upgrade does not silently log anyone out.
32
+ return readMachineKey();
24
33
  }
25
34
  export function authHeaders(opts = {}) {
26
35
  const h = { 'Content-Type': 'application/json' };
@@ -0,0 +1,130 @@
1
+ /** The per-project directory holding the key, the vault and their metadata. */
2
+ export declare const KEY_DIR_NAME = ".one";
3
+ /**
4
+ * The pre-rename project directory. READ-ONLY — a folder minted before the
5
+ * rename keeps working; nothing is ever written here again. Same fallback shape
6
+ * as `paths.ts` uses for ~/.config, and for the same reason: a rename must not
7
+ * present as "my key stopped working".
8
+ */
9
+ export declare const LEGACY_KEY_DIR_NAME = ".oneie";
10
+ /** `*.key` is already covered by the scaffold's root .gitignore. */
11
+ export declare const KEY_FILE_NAME = "agent.key";
12
+ export declare const META_FILE_NAME = "agent.json";
13
+ export interface KeyFolderInput {
14
+ /** Project root. The key lands at <dir>/.oneie/agent.key */
15
+ dir: string;
16
+ /** The workspace-scoped key — authenticates as the workspace actor. */
17
+ apiKey: string;
18
+ /** The uid-bound registration key. Distinct from apiKey; see the note below. */
19
+ regKey?: string;
20
+ workspace: string;
21
+ uid?: string;
22
+ api: string;
23
+ /** Unix seconds at which the key stops verifying, when the server set one. */
24
+ expiresAt?: number;
25
+ /** The spend ceiling the server reports for this actor, in USD. */
26
+ spendLimitUsd?: number;
27
+ }
28
+ export interface KeyFolderResult {
29
+ ok: boolean;
30
+ keyPath?: string;
31
+ metaPath?: string;
32
+ ignorePath?: string;
33
+ /** Set when the ceremony refused — the key was NOT written. */
34
+ error?: string;
35
+ }
36
+ /**
37
+ * True when `.gitignore` already ignores the key directory.
38
+ *
39
+ * Deliberately a literal scan, not a `git check-ignore` shell-out: the folder
40
+ * may not be a git repo yet (that is the common case — `npx oneie` runs before
41
+ * `git init`), and a check that silently passes on "not a repo" would be the
42
+ * false green this whole module exists to avoid.
43
+ */
44
+ export declare function ignoresKeyDir(ignoreText: string): boolean;
45
+ /**
46
+ * Ensure `<dir>/.gitignore` ignores the key directory. Returns the path on
47
+ * success, or null when it could not be written — in which case the caller must
48
+ * NOT write a key.
49
+ */
50
+ export declare function ensureIgnored(dir: string): string | null;
51
+ /**
52
+ * Canonical absolute path — symlinks resolved.
53
+ *
54
+ * `resolve()` alone is NOT enough for the path binding. On macOS `/tmp` is a
55
+ * symlink to `/private/tmp` and `/var` to `/private/var`, so a key minted at the
56
+ * path the user typed and read back after a `chdir` compares unequal and a
57
+ * legitimate credential is refused. Home directories and network mounts are
58
+ * symlinked on plenty of real machines too. Compare the REAL path on both sides
59
+ * or the check fails open on attackers and closed on users — the worst pairing.
60
+ *
61
+ * Falls back to `resolve()` when the path does not exist yet (realpath throws).
62
+ */
63
+ export declare function canonicalDir(p: string): string;
64
+ /**
65
+ * A stable, secret-ish id for THIS machine.
66
+ *
67
+ * The path binding alone is not enough where the path is predictable. A repo
68
+ * that ships `.oneie/agent.json` recording `dir:
69
+ * "/home/runner/work/<repo>/<repo>"` matches that path on EVERY GitHub Actions
70
+ * checkout of it — so the clone attack the binding closes for a laptop reopens
71
+ * for CI, which is exactly where nobody is watching. The machine id is a value
72
+ * the attacker cannot guess and cannot read from the victim's repo, so a key
73
+ * must be BOTH at the right path AND on the right machine.
74
+ *
75
+ * Stored 0600 beside the machine-wide key. Not a secret in the cryptographic
76
+ * sense — it authorises nothing on its own — so a read-only or unwritable home
77
+ * degrades to path-only binding rather than refusing all work.
78
+ */
79
+ export declare function machineId(): string | null;
80
+ /**
81
+ * Write `data` to `path` at 0600, refusing to follow a symlink.
82
+ *
83
+ * `writeFileSync` FOLLOWS symlinks. An attacker who can pre-plant
84
+ * `.oneie/agent.key.tmp` as a link to a file they control gets our chmod(0600)
85
+ * and our credential written to their target — the classic pre-plant, and the
86
+ * 0700 directory does not help because the link is created before we ever run.
87
+ * `O_NOFOLLOW` makes the kernel refuse, and `O_EXCL` means we never write onto
88
+ * an existing file at all.
89
+ */
90
+ export declare function writeSecret(path: string, data: string): void;
91
+ /**
92
+ * Write the key folder: ignore entry FIRST, then 0700 dir, then 0600 key via
93
+ * tmp+rename so a reader never observes a partial or world-readable file.
94
+ *
95
+ * Refuses (and writes nothing) when the ignore entry cannot be established.
96
+ */
97
+ export declare function writeKeyFolder(input: KeyFolderInput): KeyFolderResult;
98
+ /**
99
+ * Read a folder key back, or null when the folder has none — or when the key
100
+ * found there was minted for a DIFFERENT directory.
101
+ *
102
+ * THE PATH BINDING IS A SECURITY CONTROL, not bookkeeping. `resolveKey` consults
103
+ * the current working directory, so without this check any directory you `cd`
104
+ * into can supply your credentials: clone a repo that ships a `.oneie/agent.key`,
105
+ * run one `one` command inside it, and you are authenticated as WHOEVER MINTED
106
+ * THAT KEY. The damage is not that your key leaks — it is that your next
107
+ * `one push` writes your agents and skills into THEIR workspace, and your next
108
+ * `one trade` spends against their ledger. That is a credential-confusion
109
+ * exfiltration, and the folder-key rung introduced it.
110
+ *
111
+ * `agent.json` records the absolute path the key was minted for, so a key that
112
+ * travelled — by clone, copy, or archive — refuses rather than authenticates.
113
+ * This is the same shape as git's `safe.directory`, decided per key instead of
114
+ * per user.
115
+ *
116
+ * A key with NO recorded `dir` is pre-binding and also refused: the whole point
117
+ * is that an unbound credential is the untrustworthy case, and treating a
118
+ * missing field as permission is how the check gets bypassed by simply deleting
119
+ * a line.
120
+ */
121
+ export declare function readKeyFolder(dir: string): {
122
+ apiKey: string;
123
+ meta: Record<string, unknown>;
124
+ } | null;
125
+ /**
126
+ * Why a folder key present on disk was not used. Separate from `readKeyFolder`
127
+ * so a refusal can be EXPLAINED without the reader having to hold a credential:
128
+ * a silent null is right for `resolveKey` and useless for `doctor`.
129
+ */
130
+ export declare function keyFolderStatus(dir: string): 'none' | 'ok' | 'foreign' | 'unsafe' | 'unreadable';