ai-zero-token 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ # AI Zero Token
2
+
3
+ [English](README.md) | [简体中文](README.zh-CN.md)
4
+
5
+ AI Zero Token 是一个本地优先的 OpenAI 兼容网关,用于把 ChatGPT/Codex OAuth 账号能力包装成本地 CLI、管理页和 HTTP API。
6
+
7
+ 它适合本地单用户场景、原型验证、自动化脚本和 OpenAI-compatible 客户端接入。
8
+
9
+ > 这是实验性质的本地工具,不是 OpenAI 官方产品,也不建议作为生产级多租户网关使用。
10
+
11
+ ## 功能
12
+
13
+ - OpenAI 风格本地接口:
14
+ - `GET /v1/models`
15
+ - `POST /v1/responses`
16
+ - `POST /v1/chat/completions`
17
+ - `POST /v1/images/generations`
18
+ - `POST /v1/images/edits`
19
+ - 支持 ChatGPT/Codex OAuth 登录和本地 token 自动刷新。
20
+ - 管理页支持多账号保存、切换和删除。
21
+ - 支持账号 JSON 导入/导出,以及复选框选择后的批量导出。
22
+ - 支持把已保存账号应用到本机 Codex,并自动备份 `~/.codex/auth.json`。
23
+ - 支持 `gpt-image-2` 文生图和 JSON 图生图。
24
+ - 支持上游代理配置,覆盖 OAuth、模型刷新和接口转发。
25
+ - 模型列表优先读取本机 Codex 模型缓存,并支持手动刷新。
26
+
27
+ ## 快速开始
28
+
29
+ ```bash
30
+ npm install -g ai-zero-token
31
+ azt start
32
+ ```
33
+
34
+ 启动后会打开本地管理页,并暴露本地网关:
35
+
36
+ ```text
37
+ http://127.0.0.1:8787
38
+ http://127.0.0.1:8787/v1
39
+ ```
40
+
41
+ 如果客户端必须填写 API Key,可以填任意非空占位值;真正起作用的是本地网关里的账号授权。
42
+
43
+ ## 管理页
44
+
45
+ 管理页是推荐入口,可以完成:
46
+
47
+ - OpenAI Codex OAuth 登录。
48
+ - 导入一个或多个账号 JSON。
49
+ - 切换当前账号。
50
+ - 导出单个账号或勾选导出多个账号。
51
+ - 将已保存账号应用到本机 Codex。
52
+ - 配置默认文本模型和上游代理。
53
+ - 测试 `models`、`responses`、`chat.completions`、`images.generations`、`images.edits`。
54
+
55
+ ![AI Zero Token 管理页](docs/images/admin-dashboard.jpg)
56
+
57
+ ## API 使用
58
+
59
+ ### 模型列表
60
+
61
+ ```bash
62
+ curl http://127.0.0.1:8787/v1/models
63
+ ```
64
+
65
+ ### Responses
66
+
67
+ ```bash
68
+ curl http://127.0.0.1:8787/v1/responses \
69
+ -H "content-type: application/json" \
70
+ -d '{"model":"gpt-5.4","input":"请只回复 OK"}'
71
+ ```
72
+
73
+ ### Chat Completions
74
+
75
+ ```bash
76
+ curl http://127.0.0.1:8787/v1/chat/completions \
77
+ -H "content-type: application/json" \
78
+ -d '{
79
+ "model": "gpt-5.4",
80
+ "messages": [
81
+ {
82
+ "role": "user",
83
+ "content": "请只回复 OK"
84
+ }
85
+ ]
86
+ }'
87
+ ```
88
+
89
+ ### 文生图
90
+
91
+ ```bash
92
+ curl http://127.0.0.1:8787/v1/images/generations \
93
+ -H "content-type: application/json" \
94
+ -d '{
95
+ "model": "gpt-image-2",
96
+ "prompt": "生成一张白底红苹果商品图,构图简洁,光线干净。",
97
+ "size": "1024x1024",
98
+ "quality": "low",
99
+ "response_format": "b64_json"
100
+ }'
101
+ ```
102
+
103
+ 响应会返回 OpenAI 风格的 `data[].b64_json`。
104
+
105
+ ![AI Zero Token gpt-image-2 生图预览](docs/images/gpt-image-2-preview.png)
106
+
107
+ ### 图生图
108
+
109
+ `/v1/images/edits` 当前支持 JSON 请求,图片可以使用 URL、data URL 或裸 base64:
110
+
111
+ ```bash
112
+ curl http://127.0.0.1:8787/v1/images/edits \
113
+ -H "content-type: application/json" \
114
+ -d '{
115
+ "model": "gpt-image-2",
116
+ "prompt": "参考这张图,生成一张更适合科技产品广告的版本。",
117
+ "images": [
118
+ {
119
+ "image_url": "data:image/png;base64,替换为你的图片base64"
120
+ }
121
+ ],
122
+ "size": "1024x1024",
123
+ "quality": "low",
124
+ "response_format": "b64_json"
125
+ }'
126
+ ```
127
+
128
+ 更多示例见 [docs/API_USAGE.md](docs/API_USAGE.md)。
129
+
130
+ ## 账号管理
131
+
132
+ AI Zero Token 的账号状态默认保存在:
133
+
134
+ ```text
135
+ ~/.ai-zero-token/.state
136
+ ```
137
+
138
+ 管理页支持:
139
+
140
+ - OAuth 登录。
141
+ - 从单个 profile、数组或 `profiles` bundle 导入。
142
+ - 导出单个账号。
143
+ - 使用复选框批量导出已选择账号。
144
+ - 删除账号和切换当前账号。
145
+
146
+ 导出的账号 JSON 包含认证 token,等同于登录凭据,只应在可信环境中使用。
147
+
148
+ ### 应用到 Codex
149
+
150
+ `应用到 Codex` 会把选中的账号写入:
151
+
152
+ ```text
153
+ ~/.codex/auth.json
154
+ ```
155
+
156
+ 写入前会把原文件备份为 `auth.json.azt-backup-*`。新的 Codex 会话会使用该账号。
157
+
158
+ ## 配置
159
+
160
+ 默认监听:
161
+
162
+ ```text
163
+ 0.0.0.0:8787
164
+ ```
165
+
166
+ 本地网关 Base URL:
167
+
168
+ ```text
169
+ http://127.0.0.1:8787/v1
170
+ ```
171
+
172
+ 限制浏览器 CORS 来源:
173
+
174
+ ```bash
175
+ AZT_CORS_ORIGIN=http://127.0.0.1:8124 azt start
176
+ ```
177
+
178
+ 多个来源用英文逗号分隔:
179
+
180
+ ```bash
181
+ AZT_CORS_ORIGIN=http://127.0.0.1:8124,http://localhost:3000 azt start
182
+ ```
183
+
184
+ 覆盖持久化状态目录:
185
+
186
+ ```bash
187
+ AI_ZERO_TOKEN_HOME=/path/to/home azt start
188
+ ```
189
+
190
+ 默认请求体上限是 `32 MiB`,用于让 JSON base64 图片在本地图片编辑场景里更实用。可以用下面的环境变量覆盖:
191
+
192
+ ```bash
193
+ AZT_BODY_LIMIT_MB=64 azt start
194
+ ```
195
+
196
+ ## 生图额度
197
+
198
+ ChatGPT Images 的可用性和额度由上游账号决定。Free 账号可以尝试生图,但限制比付费账号更严格,官方没有公开固定张数。网关不会本地硬拦截 Free 账号,而是展示上游真实返回,例如 `usage_limit_reached` 和重置时间。
199
+
200
+ 图片请求内部使用 `gpt-5.4-mini` 作为编排模型,并把请求里的图片模型(例如 `gpt-image-2`)传给 `image_generation` tool。
201
+
202
+ 对于 JSON 图生图,base64 通常比原始图片大约 33%。在默认 `32 MiB` 请求体上限下,原始图片约 `24 MiB` 是比较实际的上限,再大就容易被 JSON 开销和本地内存影响。大图或批量场景建议优先使用可访问的图片 URL。
203
+
204
+ ## 当前限制
205
+
206
+ - 项目默认面向本地单用户使用。
207
+ - `stream=true` 目前只识别,并未对所有接口实现完整流式兼容。
208
+ - `/v1/images/generations` 当前返回 `b64_json`,暂不支持托管图片 URL。
209
+ - `/v1/images/generations` 暂不支持 `n > 1`。
210
+ - `/v1/images/edits` 当前只支持 JSON,暂不支持 `multipart/form-data`、`mask` 和 `file_id`。
211
+ - 超大的 base64 JSON 请求受 `AZT_BODY_LIMIT_MB` 和本地内存限制。
212
+ - OpenAI Responses API 兼容范围是常见本地客户端工作流,不是完整实现。
213
+
214
+ ## 安全
215
+
216
+ - `access_token`、`refresh_token`、`id_token` 都等同于登录凭据。
217
+ - 不要把本地网关暴露给不可信网络。
218
+ - 不要在不可信环境中传递导出的账号 JSON。
219
+ - 复制或发布本地文件前,请检查 `~/.ai-zero-token/.state` 和 `~/.codex/auth.json`。
220
+
221
+ ## 开发
222
+
223
+ 安装依赖:
224
+
225
+ ```bash
226
+ npm install
227
+ ```
228
+
229
+ 源码运行:
230
+
231
+ ```bash
232
+ bun src/cli.ts start
233
+ ```
234
+
235
+ 验证:
236
+
237
+ ```bash
238
+ npm run typecheck
239
+ npm run build
240
+ ```
241
+
242
+ CLI 构建和发布说明见 [BUILD_CLI.md](BUILD_CLI.md)。用户可见变更见 [CHANGELOG.md](CHANGELOG.md)。
243
+
244
+ ## 项目状态
245
+
246
+ AI Zero Token 仍在快速迭代。当前重点是稳定本地网关、账号迁移工作流,以及 OpenAI 风格客户端的图片生成/编辑兼容性。
247
+
248
+ 反馈和问题:[GitHub Issues](https://github.com/fchangjun/AI-Zero-Token/issues)
@@ -44,6 +44,7 @@ async function runServeCommand(args, options) {
44
44
  console.log(`admin: ${adminUrl}`);
45
45
  console.log(`apiBase: ${adminUrl}/v1`);
46
46
  console.log(`corsOrigin: ${server.corsOrigin}`);
47
+ console.log(`bodyLimitMB: ${(server.bodyLimit / 1024 / 1024).toFixed(1)}`);
47
48
  console.log(`activeProvider: ${status.activeProvider ?? "none"}`);
48
49
  console.log(`defaultModel: ${status.defaultModel}`);
49
50
  if (shouldOpenBrowser) {
@@ -80,7 +80,7 @@ function parseAuthorizationInput(value) {
80
80
  }
81
81
  return { code: trimmed };
82
82
  }
83
- function extractProfile(accessToken, refreshToken, expires) {
83
+ function extractProfile(accessToken, refreshToken, expires, idToken) {
84
84
  const payload = decodeJwtPayload(accessToken);
85
85
  const authClaim = payload?.[JWT_CLAIM_PATH];
86
86
  const accountId = authClaim?.chatgpt_account_id;
@@ -94,6 +94,7 @@ function extractProfile(accessToken, refreshToken, expires) {
94
94
  mode: "oauth_account",
95
95
  access: accessToken,
96
96
  refresh: refreshToken,
97
+ idToken,
97
98
  expires,
98
99
  accountId,
99
100
  email
@@ -124,6 +125,7 @@ async function exchangeAuthorizationCode(code, verifier) {
124
125
  return {
125
126
  access: json.access_token,
126
127
  refresh: json.refresh_token,
128
+ idToken: json.id_token,
127
129
  expires: Date.now() + json.expires_in * 1e3
128
130
  };
129
131
  }
@@ -150,7 +152,8 @@ async function refreshOpenAICodexToken(profile) {
150
152
  return extractProfile(
151
153
  json.access_token,
152
154
  json.refresh_token,
153
- Date.now() + json.expires_in * 1e3
155
+ Date.now() + json.expires_in * 1e3,
156
+ json.id_token ?? profile.idToken
154
157
  );
155
158
  }
156
159
  function tryOpenBrowser(url) {
@@ -284,7 +287,7 @@ async function loginOpenAICodex() {
284
287
  console.log("\u5DF2\u6536\u5230\u6388\u6743\u56DE\u8C03\uFF0C\u6B63\u5728\u4EA4\u6362 access token...");
285
288
  const token = await exchangeAuthorizationCode(code, verifier);
286
289
  console.log("token \u4EA4\u6362\u6210\u529F\uFF0C\u6B63\u5728\u89E3\u6790\u8D26\u53F7\u4FE1\u606F...");
287
- return extractProfile(token.access, token.refresh, token.expires);
290
+ return extractProfile(token.access, token.refresh, token.expires, token.idToken);
288
291
  } finally {
289
292
  callbackServer.close();
290
293
  }
@@ -13,6 +13,10 @@ import {
13
13
  refreshOpenAICodexToken
14
14
  } from "../providers/openai-codex/oauth.js";
15
15
  import { askOpenAICodex } from "../providers/openai-codex/chat.js";
16
+ import {
17
+ applyProfileToCodexAuth,
18
+ getCodexAuthStatus
19
+ } from "../store/codex-auth-store.js";
16
20
  import {
17
21
  exportProfilesToJson,
18
22
  exportProfileToJson,
@@ -97,6 +101,13 @@ class AuthService {
97
101
  getProfileImportTemplate() {
98
102
  return getProfileImportTemplate();
99
103
  }
104
+ async getCodexStatus() {
105
+ return getCodexAuthStatus();
106
+ }
107
+ async applyProfileToCodex(profileId, provider = "openai-codex") {
108
+ const profile = await this.requireFreshProfileWithIdToken(profileId, provider);
109
+ return applyProfileToCodexAuth(profile);
110
+ }
100
111
  async getActiveProfile(provider = "openai-codex") {
101
112
  const profile = await getActiveProfile();
102
113
  if (!profile || profile.provider !== provider) {
@@ -152,6 +163,22 @@ class AuthService {
152
163
  await saveProfile(refreshed);
153
164
  return this.toManagedProfile(refreshed);
154
165
  }
166
+ async requireFreshProfileWithIdToken(profileId, provider = "openai-codex") {
167
+ const profiles = await listProfiles();
168
+ const profile = profiles.find((item) => item.provider === provider && item.profileId === profileId);
169
+ if (!profile) {
170
+ throw new Error(`\u6CA1\u6709\u627E\u5230\u8D26\u53F7: ${profileId}`);
171
+ }
172
+ if (profile.idToken && Date.now() < profile.expires) {
173
+ return this.toManagedProfile(profile);
174
+ }
175
+ const refreshed = await refreshOpenAICodexToken(profile);
176
+ await saveProfile(refreshed);
177
+ if (!refreshed.idToken) {
178
+ throw new Error("\u5237\u65B0 token \u6210\u529F\uFF0C\u4F46\u4E0A\u6E38\u6CA1\u6709\u8FD4\u56DE id_token\u3002");
179
+ }
180
+ return this.toManagedProfile(refreshed);
181
+ }
155
182
  async logoutAll() {
156
183
  await clearStore();
157
184
  }
@@ -6,6 +6,7 @@ const SUPPORTED_IMAGE_MODELS = /* @__PURE__ */ new Set([
6
6
  "gpt-image-1.5",
7
7
  "gpt-image-2"
8
8
  ]);
9
+ const IMAGE_ORCHESTRATOR_MODEL = "gpt-5.4-mini";
9
10
  const SUPPORTED_IMAGE_QUALITIES = /* @__PURE__ */ new Set([
10
11
  "low",
11
12
  "medium",
@@ -260,15 +261,9 @@ class ImageService {
260
261
  }
261
262
  return model;
262
263
  }
263
- isFreePlan(profile) {
264
- return profile.quota?.planType === "free";
265
- }
266
264
  async generate(request) {
267
265
  const profile = await this.deps.authService.requireUsableProfile("openai-codex");
268
- if (this.isFreePlan(profile)) {
269
- throw new Error("\u5F53\u524D\u8D26\u53F7\u4E3A free \u5957\u9910\uFF0C\u4E0D\u652F\u6301\u56FE\u7247\u751F\u6210\u3002\u8BF7\u5207\u6362\u5230 Plus \u6216\u66F4\u9AD8\u5957\u9910\u8D26\u53F7\u3002");
270
- }
271
- const orchestratorModel = await this.deps.configService.getDefaultModel();
266
+ const orchestratorModel = IMAGE_ORCHESTRATOR_MODEL;
272
267
  const requestedImageModel = this.resolveRequestedImageModel(request.model);
273
268
  const requestSummary = {
274
269
  requestedImageModel,
@@ -280,7 +275,8 @@ class ImageService {
280
275
  background: request.background ?? "default",
281
276
  outputFormat: request.outputFormat ?? "default",
282
277
  outputCompression: typeof request.outputCompression === "number" ? request.outputCompression : void 0,
283
- moderation: request.moderation ?? "default"
278
+ moderation: request.moderation ?? "default",
279
+ inputImageCount: request.inputImages?.length ?? 0
284
280
  };
285
281
  console.info("[gateway:image] upstream request", requestSummary);
286
282
  const tool = {
@@ -305,6 +301,9 @@ class ImageService {
305
301
  if (request.moderation) {
306
302
  tool.moderation = request.moderation;
307
303
  }
304
+ if (request.inputImages && request.inputImages.length > 0) {
305
+ tool.action = "edit";
306
+ }
308
307
  for (let attempt = 1; attempt <= IMAGE_GENERATION_MAX_ATTEMPTS; attempt += 1) {
309
308
  let result;
310
309
  try {
@@ -320,7 +319,11 @@ class ImageService {
320
319
  {
321
320
  type: "input_text",
322
321
  text: request.prompt
323
- }
322
+ },
323
+ ...(request.inputImages ?? []).map((image) => ({
324
+ type: "input_image",
325
+ image_url: image.imageUrl
326
+ }))
324
327
  ]
325
328
  }
326
329
  ],
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ function getCodexHomeDir() {
6
+ return process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
7
+ }
8
+ function getCodexAuthPath() {
9
+ return path.join(getCodexHomeDir(), "auth.json");
10
+ }
11
+ function createBackupSuffix() {
12
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
13
+ }
14
+ function isRecord(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ async function readCodexAuth() {
18
+ try {
19
+ const raw = await fs.readFile(getCodexAuthPath(), "utf8");
20
+ const parsed = JSON.parse(raw);
21
+ return isRecord(parsed) ? parsed : null;
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+ async function getCodexAuthStatus() {
27
+ const authPath = getCodexAuthPath();
28
+ const auth = await readCodexAuth();
29
+ if (!auth) {
30
+ return {
31
+ path: authPath,
32
+ exists: false,
33
+ hasIdToken: false
34
+ };
35
+ }
36
+ const tokens = isRecord(auth.tokens) ? auth.tokens : {};
37
+ return {
38
+ path: authPath,
39
+ exists: true,
40
+ accountId: typeof tokens.account_id === "string" ? tokens.account_id : void 0,
41
+ hasIdToken: typeof tokens.id_token === "string" && tokens.id_token.length > 0,
42
+ lastRefresh: typeof auth.last_refresh === "string" ? auth.last_refresh : void 0
43
+ };
44
+ }
45
+ async function applyProfileToCodexAuth(profile) {
46
+ if (!profile.idToken) {
47
+ throw new Error("\u5F53\u524D\u8D26\u53F7\u7F3A\u5C11 id_token\u3002\u8BF7\u5148\u5237\u65B0\u8D26\u53F7 token \u6216\u91CD\u65B0\u5BFC\u5165\u5305\u542B id_token \u7684\u8D26\u53F7 JSON\u3002");
48
+ }
49
+ const authPath = getCodexAuthPath();
50
+ const codexHomeDir = path.dirname(authPath);
51
+ await fs.mkdir(codexHomeDir, { recursive: true });
52
+ let backupPath;
53
+ try {
54
+ await fs.access(authPath);
55
+ backupPath = `${authPath}.azt-backup-${createBackupSuffix()}`;
56
+ await fs.copyFile(authPath, backupPath);
57
+ } catch {
58
+ backupPath = void 0;
59
+ }
60
+ const authFile = {
61
+ auth_mode: "chatgpt",
62
+ OPENAI_API_KEY: null,
63
+ tokens: {
64
+ id_token: profile.idToken,
65
+ access_token: profile.access,
66
+ refresh_token: profile.refresh,
67
+ account_id: profile.accountId
68
+ },
69
+ last_refresh: (/* @__PURE__ */ new Date()).toISOString()
70
+ };
71
+ const tmpPath = `${authPath}.tmp-${process.pid}`;
72
+ await fs.writeFile(tmpPath, `${JSON.stringify(authFile, null, 2)}
73
+ `, {
74
+ encoding: "utf8",
75
+ mode: 384
76
+ });
77
+ await fs.rename(tmpPath, authPath);
78
+ await fs.chmod(authPath, 384);
79
+ return {
80
+ path: authPath,
81
+ exists: true,
82
+ accountId: profile.accountId,
83
+ hasIdToken: true,
84
+ lastRefresh: authFile.last_refresh,
85
+ backupPath,
86
+ appliedProfileId: profile.profileId,
87
+ appliedEmail: profile.email
88
+ };
89
+ }
90
+ export {
91
+ applyProfileToCodexAuth,
92
+ getCodexAuthPath,
93
+ getCodexAuthStatus
94
+ };
@@ -67,6 +67,7 @@ function importProfileFromJson(value) {
67
67
  }
68
68
  const access = getString(value.access_token) ?? getString(value.access);
69
69
  const refresh = getString(value.refresh_token) ?? getString(value.refresh);
70
+ const idToken = getString(value.id_token) ?? getString(value.idToken);
70
71
  if (!access || !refresh) {
71
72
  throw new Error("\u5BFC\u5165\u5931\u8D25: \u7F3A\u5C11 access_token/access \u6216 refresh_token/refresh\u3002");
72
73
  }
@@ -80,6 +81,7 @@ function importProfileFromJson(value) {
80
81
  mode: "oauth_account",
81
82
  access,
82
83
  refresh,
84
+ idToken,
83
85
  expires,
84
86
  accountId,
85
87
  email
@@ -101,6 +103,7 @@ function exportProfileToJson(profile) {
101
103
  type: "codex",
102
104
  access_token: profile.access,
103
105
  refresh_token: profile.refresh,
106
+ id_token: profile.idToken,
104
107
  expired: new Date(profile.expires).toISOString(),
105
108
  email: profile.email,
106
109
  account_id: profile.accountId,
@@ -124,6 +127,7 @@ function getProfileImportTemplate() {
124
127
  type: "codex",
125
128
  access_token: "eyJ...access_token",
126
129
  refresh_token: "rt_...",
130
+ id_token: "eyJ...id_token",
127
131
  expired: "2026-05-04T22:13:00.000Z",
128
132
  email: "user@example.com",
129
133
  account_id: "\u53EF\u9009\uFF0C\u901A\u5E38\u4F1A\u4ECE access_token \u81EA\u52A8\u89E3\u6790",