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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 42 additions & 6 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ npm link # put the built `reply` binary on your PATH

The suite is fully offline — no test contacts the Reply.io API or the identity
server. `fetch` is stubbed, and the OAuth loopback flow is exercised against a
local `127.0.0.1` listener with an injected browser stub. CI runs the build and
tests on Linux and Windows.
local `127.0.0.1` listener with an injected browser stub. One test runs two
built CLI processes (`dist/`) against a fake identity server on `127.0.0.1`, so
run `npm run build` before `npm test`. CI runs the build and tests on Linux and
Windows.

`npm run smoke:hosts` is a separate check that runs `reply skills install`
entirely inside a throwaway `HOME`/`USERPROFILE` sandbox, and proves your real
Expand Down Expand Up @@ -56,10 +58,44 @@ do.

Each record is keyed by profile name, so multiple accounts never collide even
when they hit the same backend. A record is either an OAuth entry (access token
+ refresh token + expiry) or an API-key entry. Expired OAuth tokens refresh
automatically; if a refresh fails the record is cleared and the user is prompted
to log in again. The store sits behind a `CredentialStore` interface so an
OS-keychain backend can be added later without touching callers.
+ refresh token + expiry) or an API-key entry. The store sits behind a
`CredentialStore` interface so an OS-keychain backend can be added later without
touching callers.

Every write (a refresh, `auth login`, `auth logout`, a profile rename or delete)
reads, changes and rewrites the whole file while holding `credentials.json.lock`
beside it, and the rewrite is a temp file renamed into place, retried briefly
when Windows refuses the rename for a moment. The lock file is created
exclusively and holds the holder's pid, host name, pid namespace (on Linux) and
the time it was taken. A lock older than 30 s, or whose holder is gone, is taken
over; a live one is waited on for up to 45 s. The pid is trusted only on the host
and in the pid namespace that wrote it: sandboxes and containers that give each
command a pid namespace of its own give them equal pids, so elsewhere a lock is
judged by its age alone. A lock is
only ever removed, by its holder letting go or by a takeover, under a second
exclusive file, `credentials.json.lock.guard`, after reading it again, so no
process removes a lock it hasn't just checked. Letting go is best effort: a lock
left behind is taken over by the same rules.

Expired OAuth tokens refresh automatically, one process at a time: the identity
server hands out one-time refresh tokens, so two processes refreshing together
would otherwise spend the same one. Under the lock the record is read again, and
a token another process already refreshed is used with no request sent. The token
request times out after 20 s, and the new record is stored as soon as the answer
is read. What a failed refresh does:

| The token endpoint's answer | The stored record | The command fails with |
|---|---|---|
| `400` `invalid_grant` | removed — unless the file by then holds another record (another process refreshed first): that one is used, nothing is removed, and the command goes on | `auth.refresh_failed`, exit 2 |
| another OAuth error, `400` or `401` with an `error` | kept | `auth.refresh_failed`, exit 2 |
| `429` | kept | `rate_limited`, exit 1, with `retry_after` when it sent `Retry-After` |
| a `5xx`, any other status, a `2xx` that isn't a token answer, a timeout, a network error, or a lock wait that ran out | kept | `reply.unavailable`, exit 1 |

The error carries the failed refresh under `details.refresh`: `status` (the token
endpoint's HTTP status) and `error` (its OAuth error code) when it answered, and
`reason` (`timeout`, `network`, `unreadable` or `lock_wait`) when no usable
answer came. The top-level `status` stays unset, since it is Reply's answer to the
command itself, and no token or request body is ever printed.

## Credential resolution

Expand Down
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,16 @@ Pass a key for a single command with `--api-key` or the `REPLY_API_KEY`
environment variable; both take precedence over a stored login and are never
written to disk.

An OAuth login refreshes itself when it expires, one `reply` process at a time,
so commands started together don't sign you out. Only a refresh the sign-in
server refuses outright fails with `auth.refresh_failed` (exit 2) and needs a new
`reply auth login`. A refresh that hits a rate limit (`rate_limited`, with
`retry_after`), or a server error, an error page, a timeout or a network error
(`reply.unavailable`), keeps the login and exits 1: run the command again. With
`--json`, the error's `details.refresh` says what the sign-in server answered
(`status`, and `error`, its OAuth error code) or why no answer came (`reason`:
`timeout`, `network`, `unreadable` or `lock_wait`). Tokens are never printed.

## Profiles

Profiles keep more than one Reply.io account signed in at once — each stores its
Expand Down Expand Up @@ -776,7 +786,8 @@ sets it for each command it runs. The value must be one lower-case name of up to
32 letters, digits or dashes, a `/`, and a version of up to 32 letters, digits,
dots, `+` or `-`; anything else is left out and the User-Agent stays as it is.
It is a label, not an input: it never refuses a command and never prints
anything, and it is read only from the environment of the process.
anything, and it is read only from the environment of the process. The token
requests a sign-in and its refreshes make carry the same User-Agent.

## Contributing

Expand Down
11 changes: 8 additions & 3 deletions skills/reply-adapter/reply-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ description: >
Use when executing any Reply.io operation from a shell, setting up authentication,
or when another Reply skill needs commands executed.
metadata:
version: 1.5.0
version: 1.5.1
pack: reply-adapter
category: execution
maturity: reviewed
Expand Down Expand Up @@ -58,8 +58,10 @@ reply auth logout
```

Credential precedence (strict): `--api-key` flag → `REPLY_API_KEY` env → stored credential.
Flag/env are ephemeral — never written to disk. Expired OAuth sessions refresh automatically; if
refresh fails the CLI asks to log in again.
Flag/env are ephemeral — never written to disk. Expired OAuth sessions refresh automatically, one
process at a time. Only `auth.refresh_failed` (exit 2) needs `reply auth login`. A refresh that
failed with `rate_limited` or `reply.unavailable` (exit 1) keeps the sign-in: run the command again,
after `retry_after` seconds when the error gives it.

A user with no Reply.io account can create one during `reply auth login` — the sign-in page
offers registration, and a trial costs nothing. Say that rather than treating a missing account
Expand Down Expand Up @@ -170,6 +172,9 @@ explicit confirmation its Safety section requires.

## Changelog

- 1.5.1 (2026-11-25): *Authentication* says which failed refresh needs a new sign-in: only
`auth.refresh_failed`. After `rate_limited` or `reply.unavailable` the sign-in is kept and the
command can run again.
- 1.5.0 (2026-11-21): *Failure modes* no longer offers the hosted mailbox page: the CLI prints only
one-mailbox connection links, and `--allow-shared-page` is deprecated and does nothing.
- 1.4.1 (2026-11-21): `reply api` says that a 429 saying an active contacts limit was reached is
Expand Down
35 changes: 26 additions & 9 deletions src/__tests__/auth/oauth-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ vi.stubGlobal('fetch', mock_fetch);

import {build_authorize_url, run_login, refresh_stored, browser_open_command, CLIENT_ID, SCOPE} from '../../auth/oauth-flow';
import {RuntimeError} from '../../utils/errors';
import {cli_version} from '../../config';
import type {Oauth_record} from '../../credentials/types';

const AUTHORITY = 'https://oauth.dev.replyapp.io';
Expand Down Expand Up @@ -99,6 +100,7 @@ describe('auth/oauth-flow', ()=>{
expect(token_url).toBe('https://oauth.dev.replyapp.io/connect/token');
expect(String(init.body)).toContain('grant_type=authorization_code');
expect(String(init.body)).toContain('code_verifier=');
expect(init.headers['User-Agent']).toMatch(/^reply-cli\/\d+\.\d+\.\d+/);
});

it('rejects on a state mismatch (CSRF guard) without exchanging a token', async()=>{
Expand All @@ -124,21 +126,36 @@ describe('auth/oauth-flow', ()=>{
});

describe('refresh_stored', ()=>{
it('posts a refresh_token grant and maps the new record, keeping the old refresh token', async()=>{
mock_fetch.mockResolvedValue(token_res({access_token: 'AT2', expires_in: 3600}));
// The User-Agent breaks if a refresh goes out as Node's default: the identity server's logs
// could no longer tell this CLI's refreshes, or the program running it, from anything else.
// The mapping breaks if an answer with a usable access token is thrown away over its other
// fields: the server has already spent the old one-time refresh token by then.
it('posts a refresh_token grant under the CLI\'s User-Agent and maps the new record, keeping the old refresh token', async()=>{
mock_fetch.mockResolvedValue(token_res({access_token: 'AT2', refresh_token: null, expires_in: null}));
const prev: Oauth_record = {type: 'oauth', access_token: 'AT', refresh_token: 'RT', expires_at: 1};
const record = await refresh_stored({authority: AUTHORITY, record: prev, now: NOW});
expect(record.access_token).toBe('AT2');
expect(record.refresh_token).toBe('RT');
let record: Oauth_record;
try {
vi.stubEnv('REPLY_CLIENT', 'some-app/1.2.3');
record = await refresh_stored({authority: AUTHORITY, record: prev, now: NOW});
} finally {
vi.unstubAllEnvs();
}
expect(record).toEqual<Oauth_record>({type: 'oauth', access_token: 'AT2', refresh_token: 'RT', expires_at: NOW + 3_600_000});
const [, init] = mock_fetch.mock.calls[0];
expect(String(init.body)).toContain('grant_type=refresh_token');
expect(init.headers['User-Agent']).toBe(`some-app/1.2.3 reply-cli/${cli_version()}`);
});

it('throws when the token endpoint returns an error', async()=>{
mock_fetch.mockResolvedValue(token_res({error: 'invalid_grant'}, 400));
// Breaks if the status or the OAuth error of a failed refresh is lost: whether the sign-in is
// kept depends on them.
it('throws with the status and the OAuth error when the token endpoint returns an error', async()=>{
mock_fetch.mockResolvedValue(token_res({error: 'invalid_grant', error_description: 'Token was used'}, 400));
const prev: Oauth_record = {type: 'oauth', access_token: 'AT', refresh_token: 'RT', expires_at: 1};
await expect(refresh_stored({authority: AUTHORITY, record: prev, now: NOW}))
.rejects.toBeInstanceOf(RuntimeError);
const e = await refresh_stored({authority: AUTHORITY, record: prev, now: NOW}).catch((x: unknown)=>x);
expect(e).toBeInstanceOf(RuntimeError);
expect(e).toMatchObject({
code: 'oauth.token', detail: 'HTTP 400: Token was used', failure: {status: 400, error: 'invalid_grant'},
});
});
});
});
165 changes: 165 additions & 0 deletions src/__tests__/auth/refresh-processes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import {describe, it, expect, beforeEach, afterEach} from 'vitest';
import {spawn} from 'child_process';
import fs from 'fs';
import http from 'http';
import os from 'os';
import path from 'path';
import type {AddressInfo} from 'net';

// The built CLI: this test runs real processes, so `npm run build` comes first.
const CLI = path.resolve(__dirname, '..', '..', '..', 'dist', 'index.js');
const PROFILE = 'race';
// Long enough for the second process to start and reach the token endpoint while the first waits.
const HOLD_MS = 2_000;

type Fake_reply = {
url: string;
refreshes: number;
refresh_tokens: Set<string>;
access_tokens: Set<string>;
close: () => Promise<void>;
};

const read_body = (req: http.IncomingMessage): Promise<string>=>new Promise((resolve, reject)=>{
let body = '';
req.on('data', chunk=>{ body += chunk; });
req.on('end', ()=>resolve(body));
req.on('error', reject);
});

const send_json = (res: http.ServerResponse, status: number, body: unknown): void=>{
res.writeHead(status, {'Content-Type': 'application/json'});
res.end(JSON.stringify(body));
};

// One local server for the sign-in server and the API. Its token endpoint hands out one-time
// refresh tokens, as Reply's does, and answers a spent one with invalid_grant. It holds the first
// refresh until a second one arrives or HOLD_MS passes, so two processes that refresh at once both
// reach it with the same token.
const start_fake_reply = async(): Promise<Fake_reply>=>{
let next = 1;
let release_first: (() => void) | undefined;
const fake = {
refreshes: 0,
refresh_tokens: new Set(['rt-0']),
access_tokens: new Set<string>(),
};

const answer_refresh = (form: URLSearchParams): [number, unknown]=>{
const token = form.get('refresh_token') ?? '';
if (form.get('grant_type') !== 'refresh_token' || form.get('client_id') !== 'Reply.Cli' || !fake.refresh_tokens.delete(token))
{
return [400, {error: 'invalid_grant'}];
}
const n = next++;
fake.refresh_tokens.add(`rt-${n}`);
fake.access_tokens.add(`at-${n}`);
return [200, {access_token: `at-${n}`, refresh_token: `rt-${n}`, expires_in: 3600, token_type: 'Bearer'}];
};

const server = http.createServer(async(req, res)=>{
const body = await read_body(req);
if (req.method === 'POST' && req.url === '/connect/token')
{
fake.refreshes += 1;
if (release_first)
{
release_first();
release_first = undefined;
await new Promise(r=>setImmediate(r));
}
else if (fake.refreshes === 1)
{
await new Promise<void>(resolve=>{
release_first = resolve;
setTimeout(resolve, HOLD_MS);
});
release_first = undefined;
}
const [status, answer] = answer_refresh(new URLSearchParams(body));
send_json(res, status, answer);
return;
}
if (req.method === 'GET' && req.url === '/v3/whoami')
{
const token = (req.headers.authorization ?? '').replace(/^Bearer /, '');
if (!fake.access_tokens.has(token))
{
send_json(res, 401, {title: 'Unauthorized'});
return;
}
send_json(res, 200, {userId: 7, username: 'ann@example.com', teamId: 3});
return;
}
send_json(res, 404, {title: 'Not found'});
});
await new Promise<void>(resolve=>server.listen(0, '127.0.0.1', resolve));
const {port} = server.address() as AddressInfo;
return Object.assign(fake, {
url: `http://127.0.0.1:${port}`,
close: ()=>new Promise<void>(resolve=>server.close(()=>resolve())),
});
};

type Run = {code: number | null; stdout: string; stderr: string};

const run_cli = (args: string[], env: NodeJS.ProcessEnv): Promise<Run>=>new Promise(resolve=>{
const child = spawn(process.execPath, [CLI, ...args], {env, stdio: ['ignore', 'pipe', 'pipe']});
let stdout = '';
let stderr = '';
child.stdout.on('data', chunk=>{ stdout += chunk; });
child.stderr.on('data', chunk=>{ stderr += chunk; });
child.on('close', code=>resolve({code, stdout, stderr}));
});

describe('two reply processes refreshing one expired sign-in together', ()=>{
let dir: string;
let fake: Fake_reply;

beforeEach(async()=>{
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-race-'));
fake = await start_fake_reply();
});

afterEach(async()=>{
await fake.close();
fs.rmSync(dir, {recursive: true, force: true});
});

// Breaks if the second process spends the one-time refresh token the first already spent, and
// signs the person out on the refusal: what happens when an app starts several commands at once.
it('both end signed in, on one refresh', async()=>{
expect(fs.existsSync(CLI), `${CLI} is missing: run \`npm run build\` first`).toBe(true);
const credentials = path.join(dir, 'credentials.json');
fs.writeFileSync(path.join(dir, 'config.json'),
JSON.stringify({profiles: {[PROFILE]: {authority: fake.url, api_base: fake.url}}}));
fs.writeFileSync(credentials, JSON.stringify({[PROFILE]: {
type: 'oauth', access_token: 'at-0', refresh_token: 'rt-0', expires_at: Date.now() - 60_000,
}}));

// Nothing outside the temp dir: no credential, profile or home from the machine running the test.
const env: NodeJS.ProcessEnv = Object.fromEntries(
Object.entries(process.env).filter(([name])=>!name.startsWith('REPLY_')));
Object.assign(env, {
REPLY_CONFIG_DIR: dir, REPLY_PROFILE: PROFILE, REPLY_NO_UPDATE_CHECK: '1',
HOME: dir, USERPROFILE: dir, APPDATA: dir, XDG_CONFIG_HOME: dir,
});

const runs = await Promise.all([
run_cli(['auth', 'whoami', '--json'], env),
run_cli(['auth', 'whoami', '--json'], env),
]);

expect(runs.map(r=>r.code), runs.map(r=>r.stderr).join('\n')).toEqual([0, 0]);
for (const r of runs)
{
expect(JSON.parse(r.stdout)).toEqual({userId: 7, username: 'ann@example.com', teamId: 3});
}
expect(fake.refreshes).toBe(1);
const stored = JSON.parse(fs.readFileSync(credentials, 'utf8'))[PROFILE];
expect(stored).toMatchObject({type: 'oauth', access_token: 'at-1', refresh_token: 'rt-1'});
expect(stored.expires_at).toBeGreaterThan(Date.now());
expect(fake.refresh_tokens.has(stored.refresh_token)).toBe(true);
expect(fs.existsSync(`${credentials}.lock`)).toBe(false);
}, 30_000);
});
Loading
Loading