Skip to content

Commit 0ba3684

Browse files
author
hzq
committed
Recover interrupted profile initialization without rotating owner keys
1 parent d4cc105 commit 0ba3684

13 files changed

Lines changed: 431 additions & 4 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ English · [简体中文](CHANGELOG.zh-CN.md)
44

55
## Unreleased
66

7+
- After an interrupted first setup, `oaa init` can finish with the original private owner key. It refuses unsafe or incomplete keys and never overwrites an existing configuration or issues a replacement key for it.
8+
79
## 0.0.72 (2026-11-24)
810

911
- On macOS and Linux, discovering agents checks executable paths without opening the binaries. An agent installed on a removable volume no longer holds up startup while the OS requests access to its contents.

‎CHANGELOG.zh-CN.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
## 未发布
66

7+
- 首次初始化中断后,`oaa init` 可以沿用已经写好的私有管理员密钥,补齐配置。残缺或权限不安全的密钥不会被采用,已有配置也不会被覆盖或被补发新密钥。
8+
79
## 0.0.72(2026-11-24)
810

911
- macOS 和 Linux 发现本机智能体时只检查可执行文件的路径,不再读取程序内容。程序装在可移除磁盘上时,不会再因这次读取触发授权弹窗而卡住启动。

‎docs/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -979,6 +979,7 @@ Error codes and response shapes do not depend on language; only the text of `mes
979979
| `bundle_not_loaded` | 409 | The required bundle is not installed on the worker yet |
980980
| `insecure_endpoint` | 400 | Remote endpoints must use TLS and must not contain credentials |
981981
| `invalid_credential` | 500 | A service or node token is shorter than 24 characters (configuration error) |
982+
| `profile_key_conflict` | 409 | First setup cannot verify a pre-existing owner key; the key is not replaced |
982983
| `key_not_found` | 404 | No API key with that ID exists for this owner |
983984
| `node_authentication_denied` | — | Worker side: the gateway rejected the node credential; reconnecting stopped |
984985
| `node_connection_failed` | — | Worker side: could not connect to the gateway |

‎docs/quickstart.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ npm run oaa -- quickstart
2121

2222
`quickstart` creates `.oaa/`, starts the gateway bound strictly to `127.0.0.1:8787`, publishes an offline sample agent (`agent/sample`, requiring no model key), and verifies a live loopback call. Open `http://127.0.0.1:8787` in your browser and load `.oaa/admin.token` in the connection dialog to enter the admin console.
2323

24+
If first setup stopped after writing `admin.token` but before creating `config.json`, rerun `quickstart` with the same `--dir`. It can reuse a complete, private owner key in the original format. Do not delete the key. If the key is unsafe or the configuration is damaged, keep the profile for recovery and use a new private directory to start separately; `oaa init` does not overwrite a configuration.
25+
2426
---
2527

2628
## Step 1: Publish Your First Agent

‎docs/zh-CN/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,6 +1003,7 @@ HTTP 错误响应默认使用形状 `{"error":{"code":"…","message":"…","typ
10031003
| `bundle_not_loaded` | 409 | 所需能力包尚未安装到 worker |
10041004
| `insecure_endpoint` | 400 | 远程端点必须使用 TLS 且不得包含凭据 |
10051005
| `invalid_credential` | 500 | 服务或节点令牌少于 24 个字符(配置错误) |
1006+
| `profile_key_conflict` | 409 | 首次初始化无法确认已有管理员密钥完整且私有,不会替换密钥 |
10061007
| `key_not_found` | 404 | 该 owner 下找不到 API 密钥 |
10071008
| `node_authentication_denied` | — | worker 侧:网关拒绝节点凭据,停止重连 |
10081009
| `node_connection_failed` | — | worker 侧:连接网关失败 |

‎docs/zh-CN/quickstart.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ npm run oaa -- quickstart
2121

2222
`quickstart` 会自动在当前目录创建 `.oaa/` 数据目录、启动只监听 `127.0.0.1:8787` 的网关、发布一个无需模型密钥的离线示例智能体 `agent/sample`,并跑通一次自检调用。浏览器打开 `http://127.0.0.1:8787`,在连接弹窗里选择 `.oaa/admin.token` 即可进入管理控制台。
2323

24+
如果首次启动在写好 `admin.token` 后中断,且还没有 `config.json`,用同一个 `--dir` 再跑一次 `quickstart` 即可。完整、私有且符合原格式的管理员密钥可以继续使用,不要删除。如果密钥权限不安全或已有配置损坏,请保留原目录供恢复,另选一个私有目录开始;`oaa init` 不会覆盖已有配置。
25+
2426
---
2527

2628
## 第一步:发布你的第一个智能体

‎src/config/config.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@ import { applySecurityProfile } from './security-profile.js';
22
import { z } from 'zod';
33
import { readFile, mkdir, access } from 'node:fs/promises';
44
import { constants } from 'node:fs';
5-
import { randomBytes } from 'node:crypto';
65
import path from 'node:path';
76
import {
87
capabilitySchema,
98
domainPattern,
109
executionLevels,
1110
keyQuotaSchema,
1211
} from '../core/contracts.js';
13-
import { Fault, writePrivate } from '../core/util.js';
12+
import { Fault } from '../core/util.js';
13+
import { publishInitialFiles, requireNewConfig } from './initial-files.js';
1414
import { whichSync } from '../core/which.js';
1515
import { discoverAcpAgents, discoveredAdapterEntry, nativeEngines } from './agent-presets.js';
1616

@@ -484,8 +484,8 @@ export function validateEndpoint(url: string, websocket = false): void {
484484
export async function initialize(root: string): Promise<string> {
485485
const data = path.resolve(root);
486486
await mkdir(data, { recursive: true, mode: 0o700 });
487-
await writePrivate(data, 'admin.token', randomBytes(32).toString('base64url'), true);
488487
const file = path.join(data, 'config.json');
488+
await requireNewConfig(file);
489489
const native: Record<string, unknown> = {};
490490
for (const [engine, command] of Object.entries({
491491
codex: 'codex',
@@ -519,6 +519,6 @@ export async function initialize(root: string): Promise<string> {
519519
adapters,
520520
},
521521
});
522-
await writePrivate(data, 'config.json', JSON.stringify(config, null, 2) + '\n', true);
522+
await publishInitialFiles(data, JSON.stringify(config, null, 2) + '\n');
523523
return file;
524524
}

‎src/config/initial-files.ts‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
import { constants, type BigIntStats } from 'node:fs';
2+
import { copyFile, link, lstat, open, realpath, unlink } from 'node:fs/promises';
3+
import { randomBytes, randomUUID } from 'node:crypto';
4+
import { execFile } from 'node:child_process';
5+
import path from 'node:path';
6+
import { promisify } from 'node:util';
7+
import { Fault, sha } from '../core/util.js';
8+
import { ownerControlsOrphanKey, restrictToOwner } from '../core/win-acl.js';
9+
10+
const code = (error: unknown) => (error as NodeJS.ErrnoException).code;
11+
const alreadyInitialized = () =>
12+
Object.assign(new Error('config.json already exists; left unchanged.'), { code: 'EEXIST' });
13+
const unsafeKey = () =>
14+
new Fault(
15+
'profile_key_conflict',
16+
'Cannot safely resume initialization from admin.token. The original was not replaced. Use a new private profile or inspect the existing one.',
17+
409,
18+
);
19+
const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino;
20+
const info = (file: string) => lstat(file, { bigint: true });
21+
const keyTemp = (dir: string, bytes: Buffer) => path.join(dir, `.oaa-init-key-${sha(bytes)}.tmp`);
22+
23+
async function missing(file: string): Promise<boolean> {
24+
try {
25+
await lstat(file);
26+
return false;
27+
} catch (error) {
28+
if (code(error) === 'ENOENT') return true;
29+
throw error;
30+
}
31+
}
32+
33+
export async function requireNewConfig(file: string): Promise<void> {
34+
if (!(await missing(file))) throw alreadyInitialized();
35+
}
36+
37+
async function removeTemp(file: string): Promise<void> {
38+
try {
39+
await unlink(file);
40+
} catch (error) {
41+
if (code(error) !== 'ENOENT') throw error;
42+
}
43+
}
44+
45+
/** Stage complete bytes and publish without replacing an operator's or another initializer's file. */
46+
async function publishNew(temp: string, target: string, bytes: Buffer): Promise<boolean> {
47+
const out = await open(temp, 'wx', 0o600);
48+
try {
49+
try {
50+
if (process.platform === 'win32') await restrictToOwner(temp);
51+
await out.writeFile(bytes);
52+
await out.sync();
53+
} finally {
54+
await out.close();
55+
}
56+
try {
57+
try {
58+
await link(temp, target);
59+
} catch (error) {
60+
// Keep create-only behavior on volumes without hard links. A damaged copy is never adopted.
61+
if (!['ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EPERM'].includes(code(error) ?? '')) throw error;
62+
await copyFile(temp, target, constants.COPYFILE_EXCL);
63+
if (process.platform === 'win32') await restrictToOwner(target);
64+
}
65+
return true;
66+
} catch (error) {
67+
if (code(error) === 'EEXIST') return false;
68+
throw error;
69+
}
70+
} finally {
71+
await removeTemp(temp);
72+
}
73+
}
74+
75+
async function darwinOrphanAclIsPrivate(dir: string): Promise<boolean> {
76+
// An extended allow entry can grant access even on a mode-0600 file on macOS.
77+
try {
78+
const { stdout } = await promisify(execFile)('/bin/ls', ['-lde', '.', 'admin.token'], {
79+
cwd: dir,
80+
env: { LC_ALL: 'C', LANG: 'C' },
81+
timeout: 3000,
82+
maxBuffer: 65536,
83+
});
84+
return stdout
85+
.split('\n')
86+
.filter((line) => /^\s*\d+:/.test(line))
87+
.every((line) => /\bdeny\b/.test(line) && !/\ballow\b/.test(line));
88+
} catch {
89+
return false;
90+
}
91+
}
92+
93+
async function verifyOrphan(dir: string, file: string): Promise<void> {
94+
const uid = process.getuid?.();
95+
const parent = await info(dir);
96+
const before = await info(file);
97+
const privateFile = (s: BigIntStats) =>
98+
s.isFile() &&
99+
s.size === 43n &&
100+
(uid === undefined || (s.uid === BigInt(uid) && (s.mode & 0o077n) === 0n));
101+
if (
102+
!privateFile(before) ||
103+
(uid !== undefined && (parent.uid !== BigInt(uid) || (parent.mode & 0o022n) !== 0n))
104+
)
105+
throw unsafeKey();
106+
if (process.platform === 'win32' && !(await ownerControlsOrphanKey(file, dir))) throw unsafeKey();
107+
if (process.platform === 'darwin' && !(await darwinOrphanAclIsPrivate(dir))) throw unsafeKey();
108+
const handle = await open(
109+
file,
110+
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
111+
);
112+
try {
113+
const opened = await handle.stat({ bigint: true });
114+
if (!same(before, opened) || !privateFile(opened) || opened.nlink > 2n) throw unsafeKey();
115+
const bytes = Buffer.alloc(44);
116+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
117+
const key = bytes.subarray(0, bytesRead);
118+
const encoded = key.toString('latin1');
119+
if (bytesRead !== 43 || Buffer.from(encoded, 'base64url').toString('base64url') !== encoded)
120+
throw unsafeKey();
121+
if (opened.nlink === 2n) {
122+
// A process may die between linking its completed key and dropping this exact staging name.
123+
const temp = keyTemp(dir, key);
124+
try {
125+
if (!same(opened, await info(temp))) throw unsafeKey();
126+
await removeTemp(temp);
127+
} catch (error) {
128+
if (code(error) !== 'ENOENT') throw error;
129+
}
130+
}
131+
const final = await info(file);
132+
if (
133+
!same(opened, final) ||
134+
opened.mtimeNs !== final.mtimeNs ||
135+
!privateFile(final) ||
136+
final.nlink !== 1n
137+
)
138+
throw unsafeKey();
139+
} finally {
140+
await handle.close();
141+
}
142+
}
143+
144+
export async function publishInitialFiles(root: string, config: string): Promise<void> {
145+
const dir = await realpath(root);
146+
const file = path.join(dir, 'config.json'),
147+
key = path.join(dir, 'admin.token');
148+
await requireNewConfig(file);
149+
let created = false;
150+
if (await missing(key)) {
151+
const bytes = Buffer.from(randomBytes(32).toString('base64url'));
152+
created = await publishNew(keyTemp(dir, bytes), key, bytes);
153+
}
154+
if (!created) await verifyOrphan(dir, key);
155+
if (
156+
!(await publishNew(
157+
path.join(dir, `.oaa-init-config-${randomUUID()}.tmp`),
158+
file,
159+
Buffer.from(config),
160+
))
161+
)
162+
throw alreadyInitialized();
163+
}

‎src/core/errors-en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ export const ERROR_EN: Readonly<Record<string, readonly [string, string?]>> = {
264264
bundle_not_loaded: ['The required bundle is not installed on the worker yet.'],
265265
insecure_endpoint: ['Remote endpoints must use TLS and must not contain credentials.'],
266266
invalid_credential: ['A service or node token is shorter than 24 characters (configuration error).'],
267+
profile_key_conflict: ['Setup cannot verify that the existing owner key is complete and private.', 'Keep the existing key and profile. Check ownership and permissions or choose a new private directory.'],
267268
key_not_found: ['No API key with that ID exists for this owner.'],
268269
node_authentication_denied: ['Worker side: the gateway rejected the node credential; reconnecting stopped.'],
269270
node_connection_failed: ['Worker side: could not connect to the gateway.'],

‎src/core/errors.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,7 @@ const ROWS: Row[] = [
322322
['bundle_not_loaded', 409, 'node', _, '所需能力包尚未安装到 worker'],
323323
['insecure_endpoint', 400, 'node', _, '远程端点必须使用 TLS 且不得包含凭据'],
324324
['invalid_credential', 500, 'node', _, '服务或节点令牌少于 24 个字符(配置错误)'],
325+
['profile_key_conflict', 409, 'node', _, '无法确认首次初始化遗留的管理员密钥完整且私有', '保留现有密钥和数据目录,检查所有者和权限,或选用新的私有目录'],
325326
['key_not_found', 404, 'node', _, '该 owner 下找不到 API 密钥'],
326327
['node_authentication_denied', null, 'node', _, 'worker 侧:网关拒绝节点凭据,停止重连'],
327328
['node_connection_failed', null, 'node', _, 'worker 侧:连接网关失败'],

0 commit comments

Comments
 (0)