From 4dea902dbde020e3303c550d1e491a32f245e081 Mon Sep 17 00:00:00 2001 From: "Paul K." Date: Fri, 20 Nov 2026 20:37:32 -0500 Subject: [PATCH] feat: act for a Connect user with ONE_CONNECT_USER_ID (v2.18.0) Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++- package-lock.json | 4 +- package.json | 2 +- skills/one/SKILL.md | 2 + src/cli.ts | 5 +- src/commands/connection.ts | 35 ++++++--- src/lib/access-gate.ts | 2 +- src/lib/access.ts | 19 +++++ src/lib/api.ts | 70 ++++++++++++++++-- src/lib/config.ts | 25 ++++++- src/lib/connect-grant.test.ts | 135 ++++++++++++++++++++++++++++++++++ src/lib/guide-content.ts | 4 +- src/lib/types.ts | 19 +++++ 13 files changed, 314 insertions(+), 26 deletions(-) create mode 100644 src/lib/connect-grant.test.ts diff --git a/README.md b/README.md index 344f408..afe6c7c 100644 --- a/README.md +++ b/README.md @@ -175,11 +175,11 @@ Both overrides apply to the current process only and are never written to config ### `one whoami` -Show the user, organization, project, environment (live/test) and key name for the current API key, plus the active config scope and API base. +Show the user, organization, project, environment (live/test) and key name for the current API key, plus the active config scope and API base. Under a Connect grant it shows the connected user and their `cu_…` id ([Acting for a Connect user](#acting-for-a-connect-user)). ```bash one whoami -one --agent whoami # {user, organization, project, env, configScope, apiBase, keyName} +one --agent whoami # {user, organization, project, env, configScope, apiBase, keyName, connectUserId?} ``` ### `--agent` (machine-readable mode) @@ -832,6 +832,7 @@ Drop a `.onerc` file in your project root to override settings per-project (sepa | Key | Purpose | |-----|---------| | `ONE_SECRET` | API key (also honored as env var) | +| `ONE_CONNECT_USER_ID` | The `cu_…` user a Connect key acts for (also honored as env var); see [Acting for a Connect user](#acting-for-a-connect-user) | | `ONE_API_BASE` | API base URL, `https://api.withone.ai` or `https://development-api.withone.ai` only (the env var accepts any origin) | | `OPENAI_API_KEY` | OpenAI key for `one mem` semantic search (also honored as env var) | | `ONE_PERMISSIONS` | `admin` / `write` / `read`, can only lower the configured level | @@ -841,7 +842,7 @@ Drop a `.onerc` file in your project root to override settings per-project (sepa Precedence: env var > `.onerc` > project config > global config. The access keys are the exception: they are not read from the environment, and a `.onerc` can only narrow the access settings in your config, never widen them, because it can arrive with a cloned repository. A value that would widen them is ignored with a warning; use `one config` instead. -The access settings are enforced on every call to a connected app, whatever the command: `actions execute`, flows, sync and its validation runs. Headers named `x-one-secret`, `x-one-connection-key` or `x-one-action-id` cannot be passed with `--headers`, method-override headers are judged against the permission level, and a path variable cannot be `.` or `..`. `--dry-run` is checked too. API requests never carry your key to another origin: a redirect to a different origin fails instead of being followed. +The access settings are enforced on every call to a connected app, whatever the command: `actions execute`, flows, sync and its validation runs. Headers named `x-one-secret`, `x-one-connect-user-id`, `x-one-connection-key` or `x-one-action-id` cannot be passed with `--headers`, method-override headers are judged against the permission level, and a path variable cannot be `.` or `..`. `--dry-run` is checked too. API requests never carry your key to another origin: a redirect to a different origin fails instead of being followed. They also apply to commands that change One's own resources. Creating, updating or activating a relay needs the `write` level and deleting one needs `admin`; `connection delete` needs `admin`; knowledge-only refuses all of them. A relay's `passthrough` actions are checked like `actions execute` when they are set, because they run later on One's servers. `url` and `agent` relay actions are allowed only when the connection and action allowlists are both `*`. With a connection allowlist, relay endpoints, events and deliveries on other connections are hidden or refused. @@ -854,6 +855,17 @@ ONE_PERMISSIONS=read > ⚠️ **Add `.onerc` to your `.gitignore`.** If you put `ONE_SECRET` in it, committing the file will leak your API key. Treat `.onerc` like `.env` — never check it in. +### Acting for a Connect user + +An app built on `@withone/connect` can run the CLI as one of its users. Set `ONE_SECRET` to the app's Connect key and `ONE_CONNECT_USER_ID` to the user's `cu_…` id, in the environment or `.onerc`. Every request then carries both, and One holds it to the grant that user gave the app, as it does for the SDK. + +- `whoami` shows the connected user. +- `list` shows the connections the grant reaches, with the access it gives on each. +- `actions load` and `actions execute` run under the grant. An action outside it is refused with a 403. +- Adding or removing connections and managing relays need an ordinary key. One refuses them under a grant. + +One refuses a Connect key without `ONE_CONNECT_USER_ID`, and an ordinary key with it, so setting one by mistake can't widen what a key reaches. + ### Relocating the CLI's state (`ONE_HOME`) Everything the CLI stores — `~/.one/config.json`, the knowledge cache, memory diff --git a/package-lock.json b/package-lock.json index e8a723d..e8f38f1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@withone/cli", - "version": "2.17.0", + "version": "2.18.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@withone/cli", - "version": "2.17.0", + "version": "2.18.0", "dependencies": { "@clack/prompts": "^0.9.1", "commander": "^13.1.0", diff --git a/package.json b/package.json index 5793746..c1eaebe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@withone/cli", - "version": "2.17.0", + "version": "2.18.0", "description": "CLI for managing One", "type": "module", "files": [ diff --git a/skills/one/SKILL.md b/skills/one/SKILL.md index 0c451ca..1dad5a2 100644 --- a/skills/one/SKILL.md +++ b/skills/one/SKILL.md @@ -35,6 +35,8 @@ one logout # Clear local credentials The consent page asks which harness will use the key (Claude Code, Codex, Cursor, …) and records the install location as tags on the key (`scope:global` / `scope:project`, `path:`, `host:`, `user:`, `harness:`, and `device:` unless telemetry is off). The CLI prints what it will send before opening the browser. `one whoami` shows the key's name once it is stored. +**Acting for a Connect user:** with `ONE_SECRET` set to an app's Connect key and `ONE_CONNECT_USER_ID` to one of its users' `cu_…` id (env or `.onerc`), every call runs under the grant that user gave the app. `one --agent whoami` then includes `connectUserId`, `connection list` shows only what the grant reaches, and `actions load` and `actions execute` work within it. An action outside the grant is refused with a 403. Adding connections and relays need an ordinary key. + **Onboarding a user with no prompts:** run `one init --auth browser` — it opens a login window (the user authenticates there), saves the key, and installs this skill for Claude Code, Claude Desktop and Codex, all without blocking on stdin. Add `-g`/`-p` for scope (default global). For CI/CD or headless environments, use `one init --auth manual --api-key sk_live_...`. ## Core Workflow: find -> execute diff --git a/src/cli.ts b/src/cli.ts index 6a627f9..27b910b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -880,7 +880,7 @@ program program .command('whoami') - .description('Show the user, organization, and project for the current API key') + .description('Show the user, organization, and project for the current API key, and the Connect user it acts for when ONE_CONNECT_USER_ID is set') .action(async () => { const apiKey = getApiKey(); if (!apiKey) { @@ -906,6 +906,7 @@ program // The name describes the config's key; an ONE_SECRET env or .onerc key // that won this call is a different credential and carries no name. const keyName = resolved.config?.apiKey === apiKey ? resolved.config.apiKeyName : undefined; + const { connectUserId } = api; if (isAgentMode()) { outputJson({ @@ -916,6 +917,7 @@ program configScope, apiBase, keyName, + ...(connectUserId && { connectUserId }), }); return; } @@ -934,6 +936,7 @@ program console.log(` ${pc.bold(scopeDisplay)} ${pc.dim('·')} ${envLabel}`); console.log(` ${whoami.user.name} ${pc.dim(`(${whoami.user.email})`)}`); if (keyName) console.log(` ${pc.dim('Key:')} ${keyName}`); + if (connectUserId) console.log(` ${pc.dim('Acting for Connect user:')} ${connectUserId}`); if (whoami.organization) console.log(` ${pc.dim('Org:')} ${whoami.organization.name} ${pc.dim(`(${whoami.organization.id})`)}`); if (whoami.project) console.log(` ${pc.dim('Project:')} ${whoami.project.name} ${pc.dim(`(${whoami.project.id})`)}`); console.log(); diff --git a/src/commands/connection.ts b/src/commands/connection.ts index 5d097a6..4217e04 100644 --- a/src/commands/connection.ts +++ b/src/commands/connection.ts @@ -2,10 +2,11 @@ import * as p from '@clack/prompts'; import pc from 'picocolors'; import { getApiKey, getApiBase, getAccessControlFromAllSources, ensureWhoAmI, getEnvFromApiKey } from '../lib/config.js'; import { checkManagementAccess, DELETE_CONFIRMATION_HINT } from '../lib/access-gate.js'; -import { OneApi, TimeoutError, PERMISSION_METHODS } from '../lib/api.js'; +import { OneApi, TimeoutError, PERMISSION_METHODS, asConnection } from '../lib/api.js'; import { resolveAllowedActions, formatAccess, + grantAccessDocument, serverEnvelope, localEnvelope, intersectEnvelopes, @@ -173,6 +174,20 @@ export async function connectionAddCommand(platformArg?: string, options?: { tag } } +/** + * A Connect grant's listing, read off the connections it reaches: the routes + * a key's access and levels come from (`/access/me`, `/connections`) refuse a + * grant, and each reachable row carries both. + */ +async function grantListing( + api: OneApi +): Promise<[Connection[], { ok: true; doc: KeyAccessDocument }, Map]> { + const reachable = await api.listReachable(); + const levels = new Map(); + for (const row of reachable) if (row.viewerAccessLevel) levels.set(row.key, row.viewerAccessLevel); + return [reachable.map(asConnection), { ok: true, doc: grantAccessDocument(reachable) }, levels]; +} + export async function connectionListCommand(options?: { search?: string; limit?: string }): Promise { const apiKey = getApiKey(); if (!apiKey) { @@ -191,14 +206,16 @@ export async function connectionListCommand(options?: { search?: string; limit?: // and says so. // The person's own level (their share, or App Controls) caps every call // too; an older backend sends none, which leaves the listing as it was. - const [allConnections, serverAccess, viewerLevels] = await Promise.all([ - api.listConnections(), - api.getOwnAccess().then( - doc => ({ ok: true as const, doc }), - () => ({ ok: false as const, doc: null }), - ), - api.listViewerLevels().catch(() => new Map()), - ]); + const [allConnections, serverAccess, viewerLevels] = api.connectUserId + ? await grantListing(api) + : await Promise.all([ + api.listConnections(), + api.getOwnAccess().then( + doc => ({ ok: true as const, doc }), + () => ({ ok: false as const, doc: null }), + ), + api.listViewerLevels().catch(() => new Map()), + ]); // The CLI's own access settings (`one config`) narrow it further. const ac = getAccessControlFromAllSources(); diff --git a/src/lib/access-gate.ts b/src/lib/access-gate.ts index 551f16f..21b32fa 100644 --- a/src/lib/access-gate.ts +++ b/src/lib/access-gate.ts @@ -40,7 +40,7 @@ export function isConnectionAllowed(connectionKey: string, allowedConnectionKeys * connection and action from these, so a caller-supplied copy would replace * what was checked. */ -export const IDENTITY_HEADERS = ['x-one-secret', 'x-one-connection-key', 'x-one-action-id']; +export const IDENTITY_HEADERS = ['x-one-secret', 'x-one-connect-user-id', 'x-one-connection-key', 'x-one-action-id']; /** * Headers that ask an upstream to treat the request as another method. One diff --git a/src/lib/access.ts b/src/lib/access.ts index 1b4984a..a694c4b 100644 --- a/src/lib/access.ts +++ b/src/lib/access.ts @@ -20,7 +20,9 @@ import type { ActionLevel, ConnectionAccess, KeyAccessDocument, + KeyAccessRule, PermissionLevel, + ReachableConnection, ResolvedAllowedAction, ViewerAccessLevel, } from './types.js'; @@ -128,6 +130,23 @@ export function serverEnvelope(doc: KeyAccessDocument | null, connectionKey: str }; } +/** + * A Connect grant's access as the document `serverEnvelope` reads: one rule + * per connection the grant reaches, so a connection it doesn't reach is + * unreachable. + */ +export function grantAccessDocument(reachable: ReachableConnection[]): KeyAccessDocument { + return { + methods: null, + rules: reachable.map(({ key, access }): KeyAccessRule => { + const rule: KeyAccessRule = { type: 'connection', connectionKey: key }; + if (access.policy === 'methods') rule.methods = access.methods; + if (access.policy === 'actions') rule.actionIds = access.actions.map(a => a.actionId); + return rule; + }), + }; +} + /** What the CLI's own access settings (`one config`) allow on one connection. */ export function localEnvelope( permissions: PermissionLevel, diff --git a/src/lib/api.ts b/src/lib/api.ts index b884a7e..019d186 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,6 +1,6 @@ import { callerHeaders } from './caller.js'; import { checkPassthroughAccess, IDENTITY_HEADERS, AccessDeniedError, writeMethodOf, WRITE_CONFIRMATION_HINT } from './access-gate.js'; -import { getAccessControlFromAllSources } from './config.js'; +import { getAccessControlFromAllSources, getConnectUserId } from './config.js'; import { createWriteStream } from 'node:fs'; import { resolve } from 'node:path'; import { pipeline } from 'node:stream/promises'; @@ -24,6 +24,7 @@ import type { AccessControlSettings, ViewerAccessLevel, RelayFormField, + ReachableConnection, } from './types.js'; export class ApiError extends Error { @@ -148,9 +149,29 @@ export class OneApi { */ requireWriteConfirmation = false; - constructor(private apiKey: string, apiBase?: string, accessSettings?: AccessControlSettings) { + /** + * The Connect user (`cu_…`) the key acts for, sent on every request beside + * it. Read from `ONE_CONNECT_USER_ID` unless a caller supplies it; `null` + * for an ordinary key. + */ + readonly connectUserId: string | null; + + constructor( + private apiKey: string, + apiBase?: string, + accessSettings?: AccessControlSettings, + connectUserId: string | null = getConnectUserId() + ) { this.accessSettings = accessSettings; this.apiBase = apiBase ?? 'https://api.withone.ai/v1'; + this.connectUserId = connectUserId; + } + + /** The key, and the Connect user it acts for when there is one. */ + private credentialHeaders(): Record { + return this.connectUserId + ? { 'x-one-secret': this.apiKey, 'x-one-connect-user-id': this.connectUserId } + : { 'x-one-secret': this.apiKey }; } private async request(path: string, signal?: AbortSignal): Promise { @@ -172,7 +193,7 @@ export class OneApi { } const headers: Record = { - 'x-one-secret': this.apiKey, + ...this.credentialHeaders(), 'Content-Type': 'application/json', ...opts.headers, }; @@ -229,7 +250,31 @@ export class OneApi { } } + /** + * The connections a Connect grant reaches, each with the access it confers + * (`GET /v1/connections/reachable`, the route a grant may list). + */ + async listReachable(signal?: AbortSignal): Promise { + const reachable: ReachableConnection[] = []; + let page = 1; + let totalPages = 1; + + do { + const response = await this.request<{ rows?: ReachableConnection[]; pages?: number }>( + `/connections/reachable?page=${page}&limit=100`, + signal + ); + reachable.push(...(response.rows || [])); + totalPages = response.pages || 1; + page++; + } while (page <= totalPages); + + return reachable; + } + async listConnections(signal?: AbortSignal): Promise { + if (this.connectUserId) return (await this.listReachable(signal)).map(asConnection); + const allConnections: Connection[] = []; let page = 1; let totalPages = 1; @@ -428,7 +473,7 @@ export class OneApi { } const headers: Record = { - 'x-one-secret': this.apiKey, + ...this.credentialHeaders(), 'Content-Type': 'application/json', ...opts.headers, }; @@ -538,7 +583,7 @@ export class OneApi { for (const name of Object.keys(requestHeaders)) { if (IDENTITY_HEADERS.includes(name.toLowerCase())) delete requestHeaders[name]; } - requestHeaders['x-one-secret'] = this.apiKey; + Object.assign(requestHeaders, this.credentialHeaders()); requestHeaders['x-one-connection-key'] = args.connectionKey; requestHeaders['x-one-action-id'] = action._id; @@ -851,6 +896,21 @@ function sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } +/** + * A reachable connection as a listed one. One sends a grant no record id, so + * the key stands in for it: it is as unique, and the routes that take an id + * (delete, tag) refuse a grant anyway. + */ +export function asConnection(reachable: ReachableConnection): Connection { + return { + id: reachable.key, + platform: reachable.platform, + key: reachable.key, + state: 'unknown', + ...(reachable.name && { name: reachable.name }), + }; +} + /** * A path variable fills one segment. `.` and `..` would make fetch drop * segments and leave `/v1/passthrough` for another One route, so they are diff --git a/src/lib/config.ts b/src/lib/config.ts index e4241a5..8a5104f 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -255,6 +255,18 @@ export function getApiKey(): string | null { return readConfig()?.apiKey ?? null; } +/** + * The Connect user (`cu_…`) a Connect key acts for: `ONE_CONNECT_USER_ID` from + * the env, then `.onerc`. Set, every request runs under that user's grant. + * Never stored in config: it pairs with a Connect key, which an `ONE_SECRET` + * env or `.onerc` carries. One refuses it beside an ordinary key, so a cloned + * `.onerc` naming one cannot widen what that key reaches. + */ +export function getConnectUserId(): string | null { + const value = process.env.ONE_CONNECT_USER_ID?.trim() || readOneRc().ONE_CONNECT_USER_ID?.trim(); + return value || null; +} + /** * Resolve the OpenAI API key using the same precedence as ONE_SECRET: * env > .onerc > project config > global config. @@ -439,6 +451,7 @@ export function updateApiBase(url: string | null): void { // Clear cached whoami — base URL changed, so it needs to be re-fetched delete config.whoami; delete config.whoamiApiBase; + delete config.whoamiConnectUserId; writeConfig(config); } @@ -491,6 +504,7 @@ export function saveCredentials(apiKey: string, scope: ConfigScope, opts: SaveCr whoami: opts.whoami, whoamiApiBase: getApiBase(), }; + delete next.whoamiConnectUserId; if (opts.keyName) next.apiKeyName = opts.keyName; else delete next.apiKeyName; const userSetKnowledge = !!existing?.accessControl?.knowledgeAgent && !existing.knowledgeAgentFromGrant; @@ -547,15 +561,17 @@ export function updateAccessControl(settings: AccessControlSettings): void { /** * The cached account record, or null when there is none or it was fetched - * from a different API base than the one active now. A record written - * before `whoamiApiBase` existed counts as fetched from the configured - * base, so existing configs keep their cache until an override is active. + * from a different API base, or for a different Connect user, than the one + * active now. A record written before `whoamiApiBase` existed counts as + * fetched from the configured base, so existing configs keep their cache + * until an override is active. */ export function getWhoAmI(): WhoAmIResponse | null { const config = readConfig(); if (!config?.whoami) return null; const fetchedFrom = config.whoamiApiBase ?? withV1(config.apiBase ?? DEFAULT_API_BASE); if (fetchedFrom !== getApiBase()) return null; + if ((config.whoamiConnectUserId ?? null) !== getConnectUserId()) return null; return config.whoami; } @@ -564,6 +580,9 @@ export function updateWhoAmI(whoami: WhoAmIResponse): void { if (!config) return; config.whoami = whoami; config.whoamiApiBase = getApiBase(); + const connectUserId = getConnectUserId(); + if (connectUserId) config.whoamiConnectUserId = connectUserId; + else delete config.whoamiConnectUserId; writeConfig(config); } diff --git a/src/lib/connect-grant.test.ts b/src/lib/connect-grant.test.ts new file mode 100644 index 0000000..3cbe406 --- /dev/null +++ b/src/lib/connect-grant.test.ts @@ -0,0 +1,135 @@ +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { OneApi } from './api.js'; +import { checkPassthroughAccess } from './access-gate.js'; +import { grantAccessDocument, serverEnvelope } from './access.js'; +import { getConnectUserId, getWhoAmI, updateWhoAmI } from './config.js'; +import { withTempHome, assertHomeIsSandboxed } from '../test-support/home.js'; +import type { ReachableConnection, WhoAmIResponse } from './types.js'; + +const CONNECT_USER = `cu_${'a'.repeat(64)}`; +const realFetch = globalThis.fetch; +const action = { _id: 'conn_mod_def::1', title: 'List customers', method: 'GET', path: '/v1/customers', tags: [] } as never; + +function serve(bodies: Record = {}): { calls: { url: string; headers: Record }[] } { + const calls: { url: string; headers: Record }[] = []; + globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(url), headers: (init?.headers ?? {}) as Record }); + const body = Object.entries(bodies).find(([prefix]) => String(url).includes(prefix))?.[1] ?? {}; + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); + }) as typeof fetch; + return { calls }; +} + +afterEach(() => { globalThis.fetch = realFetch; }); + +describe('OneApi under a Connect grant', () => { + it('sends the Connect user beside the key on API, knowledge and passthrough calls', async () => { + const { calls } = serve({ '/knowledge': { rows: [action] } }); + const api = new OneApi('sk_live_connect', 'https://api.test/v1', {}, CONNECT_USER); + await api.whoami(); + await api.getActionDetailsWithMeta('conn_mod_def::1'); + await api.executePassthroughRequest({ platform: 'stripe', actionId: 'conn_mod_def::1', connectionKey: 'live::stripe::default::s' }, action); + assert.equal(calls.length, 3); + for (const call of calls) { + assert.equal(call.headers['x-one-secret'], 'sk_live_connect'); + assert.equal(call.headers['x-one-connect-user-id'], CONNECT_USER); + } + }); + + it('sends no Connect user for an ordinary key', async () => { + const { calls } = serve(); + await new OneApi('sk_live_k', 'https://api.test/v1', {}, null).whoami(); + assert.equal(calls[0].headers['x-one-connect-user-id'], undefined); + }); + + it('lists the connections the grant reaches, every page, rather than the vault', async () => { + const pages: Record = { + 'reachable?page=1': { rows: [{ key: 'live::gmail::default::g', platform: 'gmail', name: 'Work', access: { policy: 'full' } }], pages: 2 }, + 'reachable?page=2': { rows: [{ key: 'live::slack::default::s', platform: 'slack', access: { policy: 'full' } }], pages: 2 }, + }; + const { calls } = serve(pages); + const connections = await new OneApi('sk_live_connect', 'https://api.test/v1', {}, CONNECT_USER).listConnections(); + assert.deepEqual(calls.map(c => new URL(c.url).pathname), ['/v1/connections/reachable', '/v1/connections/reachable']); + assert.deepEqual(connections, [ + { id: 'live::gmail::default::g', platform: 'gmail', key: 'live::gmail::default::g', state: 'unknown', name: 'Work' }, + { id: 'live::slack::default::s', platform: 'slack', key: 'live::slack::default::s', state: 'unknown' }, + ]); + }); + + it('refuses a caller-supplied Connect user on a passthrough call', () => { + assert.throws( + () => checkPassthroughAccess({}, { actionId: 'a', connectionKey: 'k', method: 'GET', headers: { 'X-One-Connect-User-Id': CONNECT_USER } }), + /is set by the CLI and cannot be passed/, + ); + }); +}); + +describe('grantAccessDocument', () => { + const reachable: ReachableConnection[] = [ + { key: 'full', platform: 'gmail', access: { policy: 'full' } }, + { key: 'reads', platform: 'slack', access: { policy: 'methods', methods: ['GET'], access: ['read'] } }, + { key: 'listed', platform: 'linear', access: { policy: 'actions', actions: [{ actionId: 'conn_mod_def::x', title: 'List issues', method: 'POST' }] } }, + ]; + + it('holds each connection to what the grant confers on it, and reaches nothing else', () => { + const doc = grantAccessDocument(reachable); + assert.deepEqual(serverEnvelope(doc, 'full'), { reachable: true, methods: null, actionIds: null }); + assert.deepEqual(serverEnvelope(doc, 'reads'), { reachable: true, methods: ['GET'], actionIds: null }); + assert.deepEqual(serverEnvelope(doc, 'listed'), { reachable: true, methods: null, actionIds: ['conn_mod_def::x'] }); + assert.equal(serverEnvelope(doc, 'other').reachable, false); + }); +}); + +describe('getConnectUserId and the whoami cache', () => { + const home = withTempHome(); + const WHOAMI: WhoAmIResponse = { user: { id: 'u1', name: 'Jane', email: 'jane@example.com' } } as WhoAmIResponse; + let saved: string | undefined; + beforeEach(() => { + home.setup(); + saved = process.env.ONE_CONNECT_USER_ID; + delete process.env.ONE_CONNECT_USER_ID; + fs.writeFileSync( + path.join(home.oneDir, 'config.json'), + JSON.stringify({ apiKey: 'sk_test_x', installedAgents: [], createdAt: 'now', whoami: WHOAMI }), + ); + }); + afterEach(() => { + if (saved === undefined) delete process.env.ONE_CONNECT_USER_ID; + else process.env.ONE_CONNECT_USER_ID = saved; + home.teardown(); + }); + + it('reads the env above .onerc', () => { + assertHomeIsSandboxed(); + const cwd = process.cwd(); + const project = path.join(home.dir, 'proj'); + fs.mkdirSync(project); + fs.writeFileSync(path.join(project, '.onerc'), `ONE_CONNECT_USER_ID=${CONNECT_USER}\n`); + process.chdir(project); + try { + assert.equal(getConnectUserId(), CONNECT_USER); + process.env.ONE_CONNECT_USER_ID = 'cu_env'; + assert.equal(getConnectUserId(), 'cu_env'); + } finally { + process.chdir(cwd); + } + }); + + it('serves the cache only to the credential it was fetched for', () => { + assertHomeIsSandboxed(); + process.env.ONE_CONNECT_USER_ID = CONNECT_USER; + assert.equal(getWhoAmI(), null, "the key's record must not describe a Connect user"); + + const connected: WhoAmIResponse = { user: { id: 'u2', name: 'Sam', email: 'sam@example.com' } } as WhoAmIResponse; + updateWhoAmI(connected); + assert.deepEqual(getWhoAmI(), connected); + + process.env.ONE_CONNECT_USER_ID = 'cu_other'; + assert.equal(getWhoAmI(), null, 'one Connect user must not be reported as another'); + delete process.env.ONE_CONNECT_USER_ID; + assert.equal(getWhoAmI(), null, "a Connect user's record must not describe the key"); + }); +}); diff --git a/src/lib/guide-content.ts b/src/lib/guide-content.ts index 09cad9f..f84f8f7 100644 --- a/src/lib/guide-content.ts +++ b/src/lib/guide-content.ts @@ -11,6 +11,8 @@ export const GUIDE_OVERVIEW = `# One CLI — Agent Guide You can also use \`one login\` / \`one logout\` to manage authentication separately (global or per-directory). \`one login\` refuses \`--agent\`; use \`one init --auth browser\` instead. **\`one --agent logout\` needs \`--force\`**: without it, it returns \`confirmation_required\` and the config it would clear. It clears only the config in effect (the project config if there is one) unless \`--scope global|both\`. Run it only when the user asked to log out. \`one --agent whoami\` shows the user, organization, project, env, config scope, API base and key name. +To act for one user of an app built on Connect, set \`ONE_SECRET\` to the app's Connect key and \`ONE_CONNECT_USER_ID\` to the user's \`cu_…\` id (env or \`.onerc\`). One then holds every call to that user's grant: \`whoami\` shows the connected user and \`connectUserId\`, \`connection list\` shows what the grant reaches, and \`actions load\` and \`actions execute\` run under it. Adding connections and relays need an ordinary key. + Browser login opens a consent page that names the key and tags it with where the CLI runs (scope, project path, machine, OS user, CLI version, the agent harnesses you pick, and the per-install device id unless telemetry is off), so the dashboard can show every install. The terminal prints what will be sent before the browser opens. Set \`ONE_APP_URL\` (dashboard origin) and \`ONE_API_BASE\` (API origin) to run against a local stack; neither is written to config, so pair them with \`ONE_HOME\` to keep a local stack's credentials separate. ### Agent-driven setup (no prompts) @@ -430,7 +432,7 @@ An action gets an event only when it matches both the endpoint's and the action' } \`\`\` -\`body\`, \`headers\`, \`query\` and \`pathVariables\` all take Handlebars templates. \`headers\` cannot include \`x-one-secret\`, \`x-one-connection-key\` or \`x-one-action-id\`. +\`body\`, \`headers\`, \`query\` and \`pathVariables\` all take Handlebars templates. \`headers\` cannot include \`x-one-secret\`, \`x-one-connect-user-id\`, \`x-one-connection-key\` or \`x-one-action-id\`. **url** — POST the event to a public URL (private and internal addresses are refused; nothing is templated): \`\`\`json diff --git a/src/lib/types.ts b/src/lib/types.ts index 650c42e..87e47f6 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -185,6 +185,12 @@ export interface Config { * local backend's org and project ids to the hosted one, or vice versa. */ whoamiApiBase?: string; + /** + * Connect user `whoami` was fetched for (`ONE_CONNECT_USER_ID`), absent for + * the key alone. Matched like `whoamiApiBase`, so a grant's user is never + * reported as the config key's owner, or one Connect user as another. + */ + whoamiConnectUserId?: string; /** * Unified-memory subsystem config. Shape defined in lib/memory/config.ts * (kept loose here to avoid import cycles between the core config layer @@ -206,6 +212,19 @@ export interface ConnectionsResponse { page: number; } +/** + * One connection a Connect grant reaches (`GET /v1/connections/reachable`), + * with the access the grant confers on it. One leaves out the record fields + * (id, state, tags) a grant may not see. + */ +export interface ReachableConnection { + key: string; + platform: string; + name?: string | null; + access: ConnectionAccess; + viewerAccessLevel?: ViewerAccessLevel; +} + export interface AvailableAction { systemId: string; title: string;