Skip to content
Open
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
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 |
Expand All @@ -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.

Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@withone/cli",
"version": "2.17.0",
"version": "2.18.0",
"description": "CLI for managing One",
"type": "module",
"files": [
Expand Down
2 changes: 2 additions & 0 deletions skills/one/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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({
Expand All @@ -916,6 +917,7 @@ program
configScope,
apiBase,
keyName,
...(connectUserId && { connectUserId }),
});
return;
}
Expand All @@ -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();
Expand Down
35 changes: 26 additions & 9 deletions src/commands/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, ViewerAccessLevel>]> {
const reachable = await api.listReachable();
const levels = new Map<string, ViewerAccessLevel>();
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<void> {
const apiKey = getApiKey();
if (!apiKey) {
Expand All @@ -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<string, ViewerAccessLevel>()),
]);
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<string, ViewerAccessLevel>()),
]);

// The CLI's own access settings (`one config`) narrow it further.
const ac = getAccessControlFromAllSources();
Expand Down
2 changes: 1 addition & 1 deletion src/lib/access-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions src/lib/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import type {
ActionLevel,
ConnectionAccess,
KeyAccessDocument,
KeyAccessRule,
PermissionLevel,
ReachableConnection,
ResolvedAllowedAction,
ViewerAccessLevel,
} from './types.js';
Expand Down Expand Up @@ -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,
Expand Down
70 changes: 65 additions & 5 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -24,6 +24,7 @@ import type {
AccessControlSettings,
ViewerAccessLevel,
RelayFormField,
ReachableConnection,
} from './types.js';

export class ApiError extends Error {
Expand Down Expand Up @@ -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<string, string> {
return this.connectUserId
? { 'x-one-secret': this.apiKey, 'x-one-connect-user-id': this.connectUserId }
: { 'x-one-secret': this.apiKey };
}

private async request<T>(path: string, signal?: AbortSignal): Promise<T> {
Expand All @@ -172,7 +193,7 @@ export class OneApi {
}

const headers: Record<string, string> = {
'x-one-secret': this.apiKey,
...this.credentialHeaders(),
'Content-Type': 'application/json',
...opts.headers,
};
Expand Down Expand Up @@ -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<ReachableConnection[]> {
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<Connection[]> {
if (this.connectUserId) return (await this.listReachable(signal)).map(asConnection);

const allConnections: Connection[] = [];
let page = 1;
let totalPages = 1;
Expand Down Expand Up @@ -428,7 +473,7 @@ export class OneApi {
}

const headers: Record<string, string> = {
'x-one-secret': this.apiKey,
...this.credentialHeaders(),
'Content-Type': 'application/json',
...opts.headers,
};
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -851,6 +896,21 @@ function sleep(ms: number): Promise<void> {
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
Expand Down
Loading
Loading