nanocoai/nanoclaw / .claude/skills/add-onecli
add-onecli
FlaggedInstall or refresh OneCLI as NanoClaw's gateway provider. Use when setup selects OneCLI, an existing OneCLI-backed install is migrated to the gateway seam, or its runtime, approval bridge, setup, and agent guidance must be restored from the in-tree package.
scripts/provider-credentials.test.ts
View on GitHubimport { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {
createOneCliCredentialConnection,
createProviderCredentialConnection,
findOneCliCredential,
type OneCliCredential,
} from './provider-credentials.js';
const CHATGPT_SECRET: OneCliCredential = {
name: 'Provider ChatGPT',
type: 'openai',
hostPattern: 'chatgpt.com',
authMode: 'oauth',
};
const google: OneCliCredential = {
name: 'Provider google',
type: 'generic',
hostPattern: 'generativelanguage.googleapis.com',
injectionConfig: { headerName: 'x-goog-api-key', valueFormat: '{value}' },
};
const metadata = (spec: OneCliCredential = google) => ({
id: 'existing-key',
name: spec.name,
type: spec.type,
hostPattern: spec.hostPattern,
scope: 'project',
valueSource: 'inline',
pathPattern: null,
injectionConfig: spec.injectionConfig ?? null,
metadata: spec.authMode ? { authMode: spec.authMode } : {},
});
afterEach(() => vi.unstubAllEnvs());
describe('OneCLI vault management', () => {
it('reuses an inline credential when a legacy response omits its source', async () => {
const transport = vi.fn(
async (_url: string, init: RequestInit) =>
new Response(
JSON.stringify(init.method === 'GET' ? [{ ...metadata(), valueSource: undefined }] : { success: true }),
),
);
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport);
const id = await vault.find();
expect(id).toBe('existing-key');
await vault.keep(id!);
expect(transport.mock.calls.every(([, init]) => init.method === 'GET')).toBe(true);
expect(await vault.save('replacement-fixture', id)).toBe(id);
const writes = transport.mock.calls.filter(([, init]) => init.method !== 'GET');
expect(writes).toEqual([
['http://vault.example/v1/secrets/existing-key', expect.objectContaining({ method: 'PATCH' })],
]);
});
it.each([undefined, 'inline'])('rejects an external vault reference with source %s', async (valueSource) => {
const transport = vi.fn(
async () => new Response(JSON.stringify([{ ...metadata(), valueSource, opRef: 'op://fixture-vault/item/key' }])),
);
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport);
await expect(vault.save('replacement-fixture', 'existing-key')).rejects.toThrow('unexpected metadata in: opRef');
expect(transport.mock.calls.every(([, init]) => init.method === 'GET')).toBe(true);
});
it.each(['keep', 'save'] as const)(
'rechecks an omitted source before %s and rejects a newly external credential',
async (action) => {
for (const change of [{ valueSource: 'onepassword' }, { opRef: 'op://fixture-vault/item/key' }]) {
const current: Record<string, unknown> = { ...metadata(), valueSource: undefined };
const transport = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify([current])));
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport);
const id = await vault.find();
Object.assign(current, change);
await expect(action === 'keep' ? vault.keep(id!) : vault.save('replacement-fixture', id)).rejects.toThrow(
'unexpected metadata',
);
expect(transport).toHaveBeenCalledTimes(2);
expect(transport.mock.calls.every(([, init]) => init.method === 'GET')).toBe(true);
}
},
);
it('reads the gateway saved after the setup process imported configuration', async () => {
const cwd = process.cwd();
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-fresh-vault-'));
vi.stubEnv('ONECLI_URL', undefined);
vi.stubEnv('ONECLI_API_KEY', undefined);
try {
process.chdir(directory);
await import('../../../../src/config.js');
fs.writeFileSync('.env', 'ONECLI_URL=https://new-vault.example\nONECLI_API_KEY=new-management-fixture\n');
const transport = vi.fn(async () => new Response('[]'));
await createOneCliCredentialConnection(google, undefined, undefined, transport).find();
expect(transport).toHaveBeenCalledWith(
'https://new-vault.example/v1/secrets',
expect.objectContaining({
headers: expect.objectContaining({ Authorization: 'Bearer new-management-fixture' }),
}),
);
} finally {
process.chdir(cwd);
fs.rmSync(directory, { recursive: true, force: true });
}
});
it('repairs a legacy header while keeping the existing secret value and grants', async () => {
const transport = vi.fn(
async (_url: string, init: RequestInit) =>
new Response(
JSON.stringify(
init.method === 'GET'
? [{ ...metadata(), injectionConfig: { headerName: 'Authorization', valueFormat: 'Bearer {value}' } }]
: { success: true },
),
),
);
await createOneCliCredentialConnection(google, 'http://vault.example', '', transport as typeof fetch).keep(
'existing-key',
);
expect(transport.mock.calls.map(([, request]) => request.method)).toEqual(['GET', 'PATCH']);
expect(JSON.parse(transport.mock.calls[1][1].body as string)).toEqual({ injectionConfig: google.injectionConfig });
});
it('uses the configured gateway, key and project despite conflicting CLI settings', async () => {
vi.stubEnv('ONECLI_API_HOST', 'https://wrong-cli-vault.example');
vi.stubEnv('ONECLI_PROJECT_ID', 'project-fixture');
const requests: Array<[string, RequestInit]> = [];
const transport = vi.fn(async (url: string, init: RequestInit) => {
requests.push([url, init]);
return new Response(JSON.stringify(init.method === 'GET' ? [metadata()] : { success: true }));
});
const vault = createOneCliCredentialConnection(
google,
'https://configured.example/prefix/',
'management-fixture',
transport as typeof fetch,
);
const id = await vault.find();
expect(await vault.save('replacement-fixture', id)).toBe('existing-key');
expect(requests.map(([, request]) => request.method)).toEqual(['GET', 'GET', 'PATCH']);
expect(requests.at(-1)).toEqual([
'https://configured.example/prefix/v1/secrets/existing-key',
expect.objectContaining({
headers: expect.objectContaining({
Authorization: 'Bearer management-fixture',
'X-Project-Id': 'project-fixture',
}),
redirect: 'error',
body: JSON.stringify({ value: 'replacement-fixture', injectionConfig: google.injectionConfig }),
}),
]);
expect(JSON.stringify(requests)).not.toContain('wrong-cli-vault');
});
it('creates a correctly mapped Google key and returns no response preview', async () => {
const requests: RequestInit[] = [];
const transport = vi.fn(async (_url: string, init: RequestInit) => {
requests.push(init);
return new Response(JSON.stringify(init.method === 'GET' ? [] : { id: 'new-id', preview: 'must-not-leak' }));
});
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport as typeof fetch);
expect(await vault.save('google-fixture', null)).toBe('new-id');
expect(JSON.parse(requests[1].body as string)).toEqual({
name: google.name,
type: 'generic',
valueSource: 'inline',
hostPattern: google.hostPattern,
value: 'google-fixture',
injectionConfig: { headerName: 'x-goog-api-key', valueFormat: '{value}' },
});
});
it('repairs the recognized old Google bearer mapping without replacing the granted ID', async () => {
const old = { ...metadata(), injectionConfig: { headerName: 'Authorization', valueFormat: 'Bearer {value}' } };
const transport = vi.fn(
async (_url: string, init: RequestInit) =>
new Response(JSON.stringify(init.method === 'GET' ? [old] : { success: true })),
);
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport as typeof fetch);
await vault.save('replacement-fixture', await vault.find());
const write = transport.mock.calls.find(([, init]) => init.method === 'PATCH')!;
expect(write[0]).toMatch(/\/existing-key$/);
expect(JSON.parse(write[1].body as string).injectionConfig).toEqual(google.injectionConfig);
expect(transport.mock.calls.some(([, init]) => init.method === 'POST')).toBe(false);
});
it.each([
{ scope: 'organization' },
{ valueSource: 'onepassword' },
{ valueSource: null },
{ valueSource: '' },
{ valueSource: 'unknown' },
{ valueSource: 0 },
{ opRef: '' },
{ type: 'openai' },
{ hostPattern: '*.googleapis.com' },
{ pathPattern: '/restricted' },
{ injectionConfig: { headerName: 'X-Unrelated', valueFormat: '{value}' } },
])('rejects incompatible metadata before writing: %j', async (change) => {
const transport = vi.fn(async () => new Response(JSON.stringify([{ ...metadata(), ...change }])));
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport);
await expect(vault.save('replacement-fixture', 'existing-key')).rejects.toThrow(
`unexpected metadata in: ${Object.keys(change)[0]}`,
);
expect(transport).toHaveBeenCalledTimes(1);
});
it('names all mismatched fields without exposing their values or the secret response', () => {
const entry = {
...metadata(CHATGPT_SECRET),
scope: 'private-scope-value',
pathPattern: '/private-path-value',
metadata: { authMode: 'private-mode-value' },
value: 'private-credential-value',
preview: 'private-preview-value',
};
expect(() => findOneCliCredential([entry], CHATGPT_SECRET)).toThrow(
'unexpected metadata in: scope, pathPattern, metadata.authMode',
);
expect(() => findOneCliCredential([entry], CHATGPT_SECRET)).not.toThrow('private-');
});
it('refuses duplicates and a changed identity instead of creating another secret', async () => {
expect(() => findOneCliCredential([metadata(), metadata()], google)).toThrow('Multiple');
const transport = vi.fn(async () => new Response(JSON.stringify([{ ...metadata(), id: 'changed' }])));
await expect(
createOneCliCredentialConnection(google, 'http://vault.example', '', transport).save(
'key-fixture',
'existing-key',
),
).rejects.toThrow('changed during setup');
expect(transport).toHaveBeenCalledTimes(1);
});
it('does not recreate an entry after a failed update or reveal upstream error contents', async () => {
const transport = vi.fn(async (_url: string, init: RequestInit) =>
init.method === 'GET'
? new Response(JSON.stringify([metadata()]))
: new Response('private-key-preview', { status: 403 }),
);
const vault = createOneCliCredentialConnection(google, 'http://vault.example', '', transport as typeof fetch);
await expect(vault.save('replacement-fixture', 'existing-key')).rejects.toThrow('Check gateway connectivity');
expect(transport.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'PATCH']);
});
it('preserves ChatGPT OAuth metadata and rejects inherited names', () => {
expect(findOneCliCredential([metadata(CHATGPT_SECRET)], CHATGPT_SECRET)).toBe('existing-key');
expect(() =>
findOneCliCredential([{ ...metadata(CHATGPT_SECRET), scope: 'organization' }], CHATGPT_SECRET),
).toThrow();
});
});
describe('OneCLI credential host migration', () => {
const target: OneCliCredential = {
name: 'Provider openai',
type: 'generic',
hostPattern: 'new.example',
injectionConfig: { headerName: 'Authorization', valueFormat: 'Bearer {value}' },
};
it.each(['keep', 'replace'])('requires confirmation and updates the same granted ID on %s', async (mode) => {
let current = { ...metadata(target), hostPattern: 'old.example' };
const transport = vi.fn(async (_url: string, init: RequestInit) => {
if (init.method === 'PATCH') current = { ...current, ...JSON.parse(init.body as string) };
return new Response(JSON.stringify(init.method === 'GET' ? [current] : { success: true }));
});
const confirmHostChange = vi.fn(async () => true);
const vault = createOneCliCredentialConnection(target, 'https://vault.example', '', transport as typeof fetch);
const id = await vault.find({ confirmHostChange });
expect(confirmHostChange).toHaveBeenCalledWith('old.example', 'new.example');
expect(transport.mock.calls.map(([, init]) => init.method)).toEqual(['GET']);
if (mode === 'keep') await vault.keep(id!);
else expect(await vault.save('replacement-fixture', id)).toBe('existing-key');
const write = transport.mock.calls.at(-1)!;
expect(write[0]).toBe('https://vault.example/v1/secrets/existing-key');
expect(JSON.parse(write[1].body as string)).toEqual(
mode === 'keep'
? { hostPattern: 'new.example' }
: { value: 'replacement-fixture', hostPattern: 'new.example', injectionConfig: target.injectionConfig },
);
expect(await vault.find()).toBe(id);
});
it.each([
{ scope: 'organization' },
{ valueSource: 'onepassword' },
{ type: 'openai' },
{ pathPattern: '/restricted' },
{ injectionConfig: { headerName: 'X-Unrelated', valueFormat: '{value}' } },
{ hostPattern: '*.example' },
{ valueSource: undefined, opRef: 'op://fixture-vault/item/key' },
{ hostPattern: 'old.example/path' },
{ hostPattern: 'old.example:8443' },
])('rejects unsafe source metadata before offering a move: %j', async (change) => {
const transport = vi.fn(
async () => new Response(JSON.stringify([{ ...metadata(target), hostPattern: 'old.example', ...change }])),
);
const confirmHostChange = vi.fn(async () => true);
await expect(
createOneCliCredentialConnection(target, 'https://vault.example', '', transport).find({ confirmHostChange }),
).rejects.toThrow('unexpected metadata');
expect(confirmHostChange).not.toHaveBeenCalled();
expect(transport).toHaveBeenCalledTimes(1);
});
it.each(['identity', 'host', 'scope'])('refuses a concurrent %s change after confirmation', async (change) => {
const current: Record<string, unknown> = { ...metadata(target), hostPattern: 'old.example' };
const transport = vi.fn(async () => new Response(JSON.stringify([current])));
const vault = createOneCliCredentialConnection(target, 'https://vault.example', '', transport);
const id = await vault.find({ confirmHostChange: async () => true });
if (change === 'identity') current.id = 'another-id';
else if (change === 'host') current.hostPattern = 'another.example';
else current.scope = 'organization';
await expect(vault.save('replacement-fixture', id)).rejects.toThrow(
change === 'identity' ? 'changed during setup' : 'unexpected metadata',
);
expect(transport).toHaveBeenCalledTimes(2);
});
it('keeps ChatGPT host validation strict even when confirmation is supplied', async () => {
const transport = vi.fn(
async () => new Response(JSON.stringify([{ ...metadata(CHATGPT_SECRET), hostPattern: 'other.example' }])),
);
const confirmHostChange = vi.fn(async () => true);
await expect(
createOneCliCredentialConnection(CHATGPT_SECRET, 'https://vault.example', '', transport).find({
confirmHostChange,
}),
).rejects.toThrow('unexpected metadata');
expect(confirmHostChange).not.toHaveBeenCalled();
});
});
describe('gateway seam adapter', () => {
const key = (host = 'generativelanguage.googleapis.com') =>
({
name: google.name,
kind: 'api-key',
host,
proxyValue: 'nc-fixture-token',
injection: google.injectionConfig!,
}) as const;
const chatgpt = {
name: CHATGPT_SECRET.name,
kind: 'oauth',
host: 'chatgpt.com',
proxyValue: 'nc-fixture-token',
oauth: { profile: 'chatgpt', clientId: 'public', tokenEndpoint: 'https://auth.example.test/oauth/token' },
} as const;
const gateway = (rows: () => unknown[], onWrite?: (init: RequestInit, url: string) => void) => {
vi.stubEnv('ONECLI_URL', 'https://vault.example');
vi.stubEnv('ONECLI_API_KEY', 'management-fixture');
const transport = vi.fn(async (url: string, init: RequestInit) => {
if (init.method !== 'GET') onWrite?.(init, url);
return new Response(JSON.stringify(init.method === 'GET' ? rows() : { id: 'created-id' }));
});
vi.stubGlobal('fetch', transport);
return transport;
};
afterEach(() => vi.unstubAllGlobals());
it('keeps native ids inside the adapter and reports an inline entry as reusable', async () => {
const writes: Array<[string, unknown]> = [];
gateway(
() => [metadata()],
(init, url) => writes.push([url, JSON.parse(init.body as string)]),
);
const connection = createProviderCredentialConnection(key());
expect(await connection.find()).toEqual({ reusable: true });
await connection.keep();
await connection.save('rotated-fixture');
expect(writes).toEqual([
[
'https://vault.example/v1/secrets/existing-key',
{ value: 'rotated-fixture', injectionConfig: google.injectionConfig },
],
]);
});
it('creates an entry when none exists and refuses keep() without one', async () => {
const writes: unknown[] = [];
gateway(
() => [],
(init) => writes.push(JSON.parse(init.body as string)),
);
const connection = createProviderCredentialConnection(key());
expect(await connection.find()).toBeNull();
await expect(connection.keep()).rejects.toThrow(`No stored ${google.name} credential`);
await connection.save('google-fixture');
expect(writes).toEqual([expect.objectContaining({ name: google.name, type: 'generic', value: 'google-fixture' })]);
});
it('requires a lookup before a write so a concurrent change is always detected', async () => {
gateway(() => [metadata()]);
await expect(createProviderCredentialConnection(key()).save('x')).rejects.toThrow('Look up');
await expect(createProviderCredentialConnection(key()).keep()).rejects.toThrow('Look up');
});
it('limits an entry to the target path and reuses only an entry with the same path', async () => {
const writes: unknown[] = [];
let rows: unknown[] = [];
gateway(
() => rows,
(init) => writes.push(JSON.parse(init.body as string)),
);
const scoped = { ...key(), path: '/v1/exchange' };
const created = createProviderCredentialConnection(scoped);
expect(await created.find()).toBeNull();
await created.save('scoped-fixture');
expect(writes).toEqual([expect.objectContaining({ hostPattern: key().host, pathPattern: '/v1/exchange' })]);
rows = [{ ...metadata(), pathPattern: '/v1/exchange' }];
expect(await createProviderCredentialConnection(scoped).find()).toEqual({ reusable: true });
await expect(createProviderCredentialConnection(key()).find()).rejects.toThrow(
'unexpected metadata in: pathPattern',
);
rows = [{ ...metadata(), pathPattern: '/v1/other' }];
await expect(createProviderCredentialConnection(scoped).find()).rejects.toThrow(
'unexpected metadata in: pathPattern',
);
rows = [metadata()];
await expect(createProviderCredentialConnection(scoped).find()).rejects.toThrow(
'unexpected metadata in: pathPattern',
);
});
it('translates the ChatGPT profile into the native openai record and nothing else', async () => {
const writes: unknown[] = [];
gateway(
() => [],
(init) => writes.push(JSON.parse(init.body as string)),
);
const connection = createProviderCredentialConnection(chatgpt);
await connection.find();
await connection.save({ profile: 'chatgpt', accessToken: 'a', refreshToken: 'r', accountId: 'acct' });
const stored = JSON.parse((writes[0] as { value: string }).value);
expect(writes[0]).toMatchObject({ type: 'openai', hostPattern: 'chatgpt.com' });
expect(stored).toMatchObject({
tokens: { access_token: 'a', refresh_token: 'r', account_id: 'acct' },
OPENAI_API_KEY: null,
});
await expect(connection.save('not-an-oauth-value')).rejects.toThrow('chatgpt OAuth profile');
await expect(createProviderCredentialConnection(key()).save({} as never)).rejects.toThrow('Look up');
expect(() =>
createProviderCredentialConnection({ ...chatgpt, oauth: { ...chatgpt.oauth, profile: 'other' as never } }),
).toThrow('only the ChatGPT subscription OAuth profile');
});
it('records the saved or kept id under the target provider, and nothing without one', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'provider-record-'));
const record = () =>
JSON.parse(fs.readFileSync(path.join(root, 'data', 'onecli', 'provider-credentials.json'), 'utf8')).providers;
try {
let rows: unknown[] = [];
gateway(() => rows);
const created = createProviderCredentialConnection({ ...key(), provider: 'opencode' }, root);
await created.find();
await created.save('google-fixture');
expect(record()).toEqual({ opencode: ['created-id'] });
// A retried login that keeps the stored key records it again (here: an entry saved before ids were kept).
fs.rmSync(path.join(root, 'data'), { recursive: true });
rows = [metadata()];
const kept = createProviderCredentialConnection({ ...key(), provider: 'opencode' }, root);
await kept.find();
await kept.keep();
expect(record()).toEqual({ opencode: ['existing-key'] });
fs.rmSync(path.join(root, 'data'), { recursive: true });
const anonymous = createProviderCredentialConnection(key(), root);
await anonymous.find();
await anonymous.save('google-fixture');
expect(fs.existsSync(path.join(root, 'data'))).toBe(false);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
it('rejects a string value for an api-key connection given an object and vice versa', async () => {
gateway(() => []);
const connection = createProviderCredentialConnection(key());
await connection.find();
await expect(
connection.save({ profile: 'chatgpt', accessToken: 'a', refreshToken: 'r', accountId: 'x' }),
).rejects.toThrow('stores a string value');
});
});
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |