@unscientificjszhai/howto 1.0.2 → 1.1.0

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.
Files changed (51) hide show
  1. package/README.md +88 -29
  2. package/{README.CN.md → README.zh-hans-cn.md} +84 -25
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/ai/chatgpt-models.js +148 -0
  5. package/dist/ai/chatgpt.js +495 -0
  6. package/dist/ai/command-schema.js +8 -0
  7. package/dist/ai/errors.js +6 -0
  8. package/dist/ai/gemini.js +117 -4
  9. package/dist/ai/index.js +4 -1
  10. package/dist/ai/openai.js +105 -2
  11. package/dist/ai/usage-session.js +144 -0
  12. package/dist/auth/chatgpt/commands.js +90 -0
  13. package/dist/auth/chatgpt/errors.js +85 -0
  14. package/dist/auth/chatgpt/http.js +97 -0
  15. package/dist/auth/chatgpt/index.js +229 -0
  16. package/dist/auth/chatgpt/instructions.js +22 -0
  17. package/dist/auth/chatgpt/oauth.js +320 -0
  18. package/dist/auth/chatgpt/storage.js +366 -0
  19. package/dist/auth/chatgpt/types.js +1 -0
  20. package/dist/cli.js +77 -16
  21. package/dist/config-file.js +2 -0
  22. package/dist/config.js +10 -3
  23. package/dist/errors.js +4 -0
  24. package/dist/index.js +11 -4
  25. package/dist/init/ChatGptInitializationStep.js +223 -0
  26. package/dist/init/InitializationApp.js +71 -37
  27. package/dist/init/index.js +24 -5
  28. package/dist/init/state.js +14 -3
  29. package/dist/prompt.js +36 -6
  30. package/dist/shell/command-analysis.js +24 -4
  31. package/dist/ui/App.js +99 -10
  32. package/dist/ui/ConfirmView.js +6 -39
  33. package/dist/ui/InteractiveSessionProvider.js +7 -8
  34. package/dist/ui/ResolvePlaceholdersView.js +6 -1
  35. package/dist/ui/UsageApprovalView.js +320 -0
  36. package/dist/ui/interactive-session.js +180 -39
  37. package/dist/ui/keyboard-framing.js +102 -0
  38. package/dist/ui/paste-framing.js +69 -32
  39. package/dist/ui/resize-safe-output.js +2 -2
  40. package/dist/ui/run-interactive-command.js +2 -2
  41. package/dist/ui/text-input.js +4 -1
  42. package/dist/ui/use-keyboard-input.js +6 -1
  43. package/dist/ui/use-paste-aware-input.js +8 -3
  44. package/dist/usage/arguments.js +61 -0
  45. package/dist/usage/generate.js +156 -0
  46. package/dist/usage/output.js +216 -0
  47. package/dist/usage/risk.js +17 -0
  48. package/dist/usage/runner.js +238 -0
  49. package/dist/usage/types.js +1 -0
  50. package/dist/validation/usage-response.js +39 -0
  51. package/package.json +21 -19
@@ -0,0 +1,229 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ChatGptError, TERMINAL_REFRESH_ERRORS } from "./errors.js";
3
+ import { CHATGPT_ISSUER, CHATGPT_RESOURCE, checkCancellation, discoverOpenIdConfiguration, OAuthHttpError, requestJson, } from "./http.js";
4
+ import { authorizeChatGpt, parseTokenResponse, validateIdentity, } from "./oauth.js";
5
+ import { createChatGptStore } from "./storage.js";
6
+ function accountInfo(account) {
7
+ return {
8
+ id: account.id,
9
+ label: account.label,
10
+ email: account.email,
11
+ signedIn: account.tokens !== undefined && account.refreshState === undefined,
12
+ planUsageEnabled: account.tokens?.scopes.includes("chatgpt.tokens.use.direct") ?? false,
13
+ };
14
+ }
15
+ function selectAccount(accounts, accountId) {
16
+ if (accountId !== undefined) {
17
+ const account = accounts.find((item) => item.id === accountId);
18
+ if (account === undefined)
19
+ throw new ChatGptError("account_not_found");
20
+ return account;
21
+ }
22
+ if (accounts.length === 0)
23
+ throw new ChatGptError("login_required");
24
+ if (accounts.length !== 1)
25
+ throw new ChatGptError("account_required");
26
+ return accounts[0];
27
+ }
28
+ export async function listChatGptAccounts(options = {}, dependencies = {}) {
29
+ return (await createChatGptStore(dependencies.homeDirectory).listAccounts(options.signal)).map(accountInfo);
30
+ }
31
+ export async function loginChatGpt(options = {}, dependencies = {}) {
32
+ const store = createChatGptStore(dependencies.homeDirectory);
33
+ const pending = await store.withLock(async (transaction) => {
34
+ if (options.callbackPort === transaction.lockPort)
35
+ throw new ChatGptError("callback_port_unavailable");
36
+ const data = await transaction.read();
37
+ const account = options.accountId === undefined ? undefined : selectAccount(data.accounts, options.accountId);
38
+ return {
39
+ hostId: await transaction.getHostId(),
40
+ lockPort: transaction.lockPort,
41
+ account,
42
+ generation: account?.generation ?? 0,
43
+ id: account?.id ?? randomUUID(),
44
+ };
45
+ }, options.signal);
46
+ let registeredClientId = pending.account?.clientId;
47
+ const result = await authorizeChatGpt({
48
+ hostId: pending.hostId,
49
+ clientId: pending.account?.clientId,
50
+ subject: pending.account?.subject,
51
+ idTokenHint: pending.account?.tokens?.idToken,
52
+ email: pending.account?.email,
53
+ requestPlanConsent: pending.account?.tokens !== undefined &&
54
+ !pending.account.tokens.scopes.includes("chatgpt.tokens.use.direct"),
55
+ signal: options.signal,
56
+ noBrowser: options.noBrowser,
57
+ callbackPort: options.callbackPort,
58
+ reservedCallbackPort: pending.lockPort,
59
+ onAuthorizationUrl: options.onAuthorizationUrl,
60
+ onRegistration: async (clientId) => {
61
+ registeredClientId = clientId;
62
+ await store.withLock(async (transaction) => {
63
+ const data = await transaction.read();
64
+ const current = data.accounts.find((item) => item.id === pending.id);
65
+ if (current !== undefined &&
66
+ (current.generation !== pending.generation || current.clientId !== clientId))
67
+ throw new ChatGptError("session_changed");
68
+ if (current === undefined) {
69
+ data.accounts.push({
70
+ id: pending.id,
71
+ label: `ChatGPT ${pending.id.slice(0, 8)}`,
72
+ clientId,
73
+ issuer: CHATGPT_ISSUER,
74
+ generation: pending.generation,
75
+ });
76
+ await transaction.save(data);
77
+ }
78
+ }, options.signal);
79
+ },
80
+ }, dependencies);
81
+ return store.withLock(async (transaction) => {
82
+ checkCancellation(options.signal);
83
+ const data = await transaction.read();
84
+ const account = data.accounts.find((item) => item.id === pending.id);
85
+ if (account === undefined ||
86
+ account.generation !== pending.generation ||
87
+ account.clientId !== registeredClientId)
88
+ throw new ChatGptError("session_changed");
89
+ account.subject = result.subject;
90
+ account.email = result.email;
91
+ account.label = `${result.email ?? "ChatGPT"} (${account.id.slice(0, 8)})`;
92
+ account.tokens = result.tokens;
93
+ account.refreshState = undefined;
94
+ account.generation += 1;
95
+ await transaction.save(data);
96
+ return accountInfo(account);
97
+ }, options.signal);
98
+ }
99
+ export async function getChatGptAccessToken(options = {}, dependencies = {}) {
100
+ const store = createChatGptStore(dependencies.homeDirectory);
101
+ return store.withLock(async (transaction) => {
102
+ checkCancellation(options.signal);
103
+ const data = await transaction.read();
104
+ const account = selectAccount(data.accounts, options.accountId);
105
+ const previous = account.tokens;
106
+ if (previous === undefined)
107
+ throw new ChatGptError("login_required");
108
+ observeCredentials(previous);
109
+ if (account.refreshState !== undefined)
110
+ throw new ChatGptError("refresh_invalid");
111
+ if (!previous.scopes.includes("chatgpt.tokens.use.direct"))
112
+ throw new ChatGptError("plan_permission");
113
+ const now = Date.now();
114
+ if (previous.expiresAt > now + 60_000 ||
115
+ (previous.expiresAt > now && (previous.earliestRefreshAt ?? 0) > now)) {
116
+ return { accessToken: previous.accessToken, accountId: account.id };
117
+ }
118
+ if (!previous.refreshToken)
119
+ throw new ChatGptError("refresh_invalid");
120
+ const metadata = await discoverOpenIdConfiguration(options.signal, dependencies.fetch);
121
+ account.refreshState = "refreshing";
122
+ await transaction.save(data);
123
+ const fetcher = dependencies.fetch ?? globalThis.fetch;
124
+ let refreshRequestStarted = false;
125
+ try {
126
+ const response = await requestJson(metadata.token_endpoint, {
127
+ method: "POST",
128
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
129
+ body: new URLSearchParams({
130
+ grant_type: "refresh_token",
131
+ client_id: account.clientId,
132
+ refresh_token: previous.refreshToken,
133
+ resource: CHATGPT_RESOURCE,
134
+ }),
135
+ }, options.signal, (input, init) => {
136
+ refreshRequestStarted = true;
137
+ return fetcher(input, init);
138
+ });
139
+ const tokens = parseTokenResponse(response, previous);
140
+ observeCredentials(tokens);
141
+ if (tokens.idToken !== previous.idToken) {
142
+ await validateIdentity(tokens.idToken, account.clientId, metadata, {
143
+ subject: account.subject,
144
+ signal: options.signal,
145
+ fetcher: dependencies.fetch,
146
+ });
147
+ }
148
+ account.tokens = tokens;
149
+ account.refreshState = undefined;
150
+ account.generation += 1;
151
+ await transaction.save(data);
152
+ if (!tokens.scopes.includes("chatgpt.tokens.use.direct"))
153
+ throw new ChatGptError("plan_permission");
154
+ return { accessToken: tokens.accessToken, accountId: account.id };
155
+ }
156
+ catch (error) {
157
+ if (account.refreshState === undefined)
158
+ throw error;
159
+ if (error instanceof OAuthHttpError && TERMINAL_REFRESH_ERRORS.has(error.oauthCode ?? "")) {
160
+ account.tokens = undefined;
161
+ account.refreshState = undefined;
162
+ account.generation += 1;
163
+ await transaction.save(data);
164
+ throw new ChatGptError("refresh_invalid");
165
+ }
166
+ // 尚未调用 fetch 的取消可以恢复;请求开始后的中断或响应丢失不能安全重放。
167
+ account.refreshState =
168
+ !refreshRequestStarted || error instanceof OAuthHttpError ? undefined : "reauth_required";
169
+ await transaction.save(data);
170
+ throw error;
171
+ }
172
+ }, options.signal);
173
+ function observeCredentials(tokens) {
174
+ options.onCredentials?.([tokens.accessToken, tokens.refreshToken, tokens.idToken].filter((value) => typeof value === "string" && value !== ""));
175
+ }
176
+ }
177
+ export async function logoutChatGpt(options = {}, dependencies = {}) {
178
+ const store = createChatGptStore(dependencies.homeDirectory);
179
+ return store.withLock(async (transaction) => {
180
+ const data = await transaction.read();
181
+ const account = selectAccount(data.accounts, options.accountId);
182
+ let remoteRevocationConfirmed = account.tokens === undefined;
183
+ try {
184
+ if (account.tokens?.refreshToken) {
185
+ const metadata = await discoverOpenIdConfiguration(options.signal, dependencies.fetch);
186
+ remoteRevocationConfirmed = await revokeSession(metadata.revocation_endpoint, account, options.signal, dependencies.fetch);
187
+ }
188
+ }
189
+ catch {
190
+ /* 即使远程撤销未确认,也清除本地凭证并明确报告。 */
191
+ }
192
+ account.tokens = undefined;
193
+ account.refreshState = undefined;
194
+ account.generation += 1;
195
+ await transaction.save(data);
196
+ checkCancellation(options.signal);
197
+ return { account: accountInfo(account), remoteRevocationConfirmed };
198
+ }, options.signal);
199
+ }
200
+ async function revokeSession(url, account, signal, fetcher = globalThis.fetch) {
201
+ for (let attempt = 0; attempt < 2; attempt += 1) {
202
+ checkCancellation(signal);
203
+ try {
204
+ const timeout = AbortSignal.timeout(15_000);
205
+ const response = await fetcher(url, {
206
+ method: "POST",
207
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
208
+ redirect: "error",
209
+ body: new URLSearchParams({
210
+ token: account.tokens?.refreshToken ?? "",
211
+ token_type_hint: "refresh_token",
212
+ client_id: account.clientId,
213
+ }),
214
+ signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
215
+ });
216
+ await response.body?.cancel();
217
+ if (response.status === 200)
218
+ return true;
219
+ if (response.status < 500)
220
+ return false;
221
+ }
222
+ catch {
223
+ checkCancellation(signal);
224
+ }
225
+ if (attempt === 0)
226
+ await new Promise((resolve) => setTimeout(resolve, 250));
227
+ }
228
+ return false;
229
+ }
@@ -0,0 +1,22 @@
1
+ import { renderTerminalSafeText } from "../../terminal-text.js";
2
+ export function formatChatGptAuthorizationInstructions(url) {
3
+ const instructions = [];
4
+ try {
5
+ const callback = new URL(new URL(url).searchParams.get("redirect_uri") ?? "");
6
+ if (callback.protocol === "http:" &&
7
+ callback.hostname === "127.0.0.1" &&
8
+ callback.pathname === "/auth/callback" &&
9
+ !callback.username &&
10
+ !callback.password &&
11
+ !callback.search &&
12
+ !callback.hash) {
13
+ const port = callback.port || "80";
14
+ instructions.push("If HowTo is running on an SSH server, first run this in another terminal on the computer with your browser:", `ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:${port}:127.0.0.1:${port} user@server`, "Replace user@server with your SSH destination. Keep the tunnel and HowTo running until sign-in completes.", "The callback uses 127.0.0.1 on the browser's computer; opening the URL alone will not reach the server.");
15
+ }
16
+ }
17
+ catch {
18
+ // 非标准链接仍可展示,但不从中拼接 SSH 指令。
19
+ }
20
+ instructions.push("Open this authorization URL in your browser:", renderTerminalSafeText(url));
21
+ return instructions.join("\n");
22
+ }
@@ -0,0 +1,320 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { createRemoteJWKSet, customFetch, jwtVerify } from "jose";
5
+ import { InteractionCancelledError } from "../../ui/tty.js";
6
+ import { ChatGptError } from "./errors.js";
7
+ import { CHATGPT_ISSUER, CHATGPT_RESOURCE, checkCancellation, discoverOpenIdConfiguration, isRecord, requestJson, } from "./http.js";
8
+ export const CHATGPT_SCOPES = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
9
+ export async function openSystemBrowser(url, signal) {
10
+ checkCancellation(signal);
11
+ return new Promise((resolve) => {
12
+ const child = spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], {
13
+ stdio: "ignore",
14
+ shell: false,
15
+ });
16
+ let settled = false;
17
+ let killTimer;
18
+ const finish = (opened) => {
19
+ if (settled)
20
+ return;
21
+ settled = true;
22
+ clearTimeout(timer);
23
+ signal?.removeEventListener("abort", stop);
24
+ resolve(opened);
25
+ };
26
+ const stop = () => {
27
+ if (settled)
28
+ return;
29
+ if (child.pid !== undefined) {
30
+ // 只终止本次启动器;不向进程组发信号,以免关闭用户已打开的浏览器。
31
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 500);
32
+ child.kill("SIGTERM");
33
+ }
34
+ finish(false);
35
+ };
36
+ const timer = setTimeout(stop, 10_000);
37
+ child.once("error", () => {
38
+ clearTimeout(killTimer);
39
+ finish(false);
40
+ });
41
+ child.once("exit", (code) => {
42
+ clearTimeout(killTimer);
43
+ finish(code === 0);
44
+ });
45
+ signal?.addEventListener("abort", stop, { once: true });
46
+ if (signal?.aborted)
47
+ stop();
48
+ });
49
+ }
50
+ export async function authorizeChatGpt(options, dependencies = {}) {
51
+ if (options.callbackPort !== undefined &&
52
+ (!Number.isSafeInteger(options.callbackPort) ||
53
+ options.callbackPort < 1 ||
54
+ options.callbackPort > 65535))
55
+ throw new ChatGptError("invalid_callback_port");
56
+ const timeout = AbortSignal.timeout(600_000);
57
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout]);
58
+ const metadata = await discoverOpenIdConfiguration(signal, dependencies.fetch);
59
+ const state = randomBytes(32).toString("base64url");
60
+ const nonce = randomBytes(32).toString("base64url");
61
+ const verifier = randomBytes(48).toString("base64url");
62
+ const listener = await listenForAuthorization(state, options.clientId, signal, options.callbackPort, options.reservedCallbackPort);
63
+ try {
64
+ const authorization = new URL(metadata.authorization_endpoint);
65
+ authorization.search = new URLSearchParams({
66
+ client_id: options.clientId ?? "dynamic_agent_client",
67
+ ext_agent_host_id: options.hostId,
68
+ response_type: "code",
69
+ redirect_uri: listener.redirectUri,
70
+ scope: CHATGPT_SCOPES,
71
+ resource: CHATGPT_RESOURCE,
72
+ state,
73
+ nonce,
74
+ code_challenge_method: "S256",
75
+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),
76
+ }).toString();
77
+ if (options.clientId === undefined)
78
+ authorization.searchParams.set("agent_name_hint", "HowTo");
79
+ else {
80
+ if (options.idTokenHint !== undefined)
81
+ authorization.searchParams.set("id_token_hint", options.idTokenHint);
82
+ if (options.email !== undefined)
83
+ authorization.searchParams.set("login_hint", options.email);
84
+ // 用户显式再次登录时可以补授此前未开放的 plan usage 权限。
85
+ if (options.requestPlanConsent)
86
+ authorization.searchParams.set("prompt", "consent");
87
+ }
88
+ checkCancellation(signal);
89
+ const opened = options.noBrowser
90
+ ? false
91
+ : await awaitWithCancellation((dependencies.openBrowser ?? openSystemBrowser)(authorization.toString(), signal), signal);
92
+ checkCancellation(signal);
93
+ if (!opened || options.idTokenHint === undefined) {
94
+ // 手动打开地址不得包含保留的 ID token,避免终端历史泄露。
95
+ authorization.searchParams.delete("id_token_hint");
96
+ authorization.searchParams.delete("login_hint");
97
+ options.onAuthorizationUrl?.(authorization.toString());
98
+ }
99
+ const result = await listener.result;
100
+ checkCancellation(signal);
101
+ await options.onRegistration(result.clientId);
102
+ const value = await requestJson(metadata.token_endpoint, {
103
+ method: "POST",
104
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
105
+ body: new URLSearchParams({
106
+ grant_type: "authorization_code",
107
+ client_id: result.clientId,
108
+ code: result.code,
109
+ code_verifier: verifier,
110
+ redirect_uri: listener.redirectUri,
111
+ resource: CHATGPT_RESOURCE,
112
+ }),
113
+ }, signal, dependencies.fetch);
114
+ const tokens = parseTokenResponse(value);
115
+ const identity = await validateIdentity(tokens.idToken, result.clientId, metadata, {
116
+ nonce,
117
+ subject: options.subject,
118
+ signal,
119
+ fetcher: dependencies.fetch,
120
+ });
121
+ return { clientId: result.clientId, tokens, ...identity };
122
+ }
123
+ catch (error) {
124
+ if (options.signal?.aborted)
125
+ throw new InteractionCancelledError();
126
+ if (timeout.aborted)
127
+ throw new ChatGptError("authorization_timeout");
128
+ if (error instanceof ChatGptError || error instanceof InteractionCancelledError)
129
+ throw error;
130
+ throw new ChatGptError("authorization_failed");
131
+ }
132
+ finally {
133
+ listener.close();
134
+ }
135
+ }
136
+ async function awaitWithCancellation(operation, signal) {
137
+ checkCancellation(signal);
138
+ let abort;
139
+ const cancelled = new Promise((_, reject) => {
140
+ abort = () => reject(new InteractionCancelledError());
141
+ signal.addEventListener("abort", abort, { once: true });
142
+ });
143
+ try {
144
+ return await Promise.race([operation, cancelled]);
145
+ }
146
+ finally {
147
+ signal.removeEventListener("abort", abort);
148
+ }
149
+ }
150
+ export function parseTokenResponse(value, previous) {
151
+ if (!isRecord(value) ||
152
+ typeof value.access_token !== "string" ||
153
+ value.access_token.length === 0 ||
154
+ typeof value.refresh_token !== "string" ||
155
+ value.refresh_token.length === 0 ||
156
+ typeof value.token_type !== "string" ||
157
+ value.token_type.toLowerCase() !== "bearer" ||
158
+ typeof value.expires_in !== "number" ||
159
+ !Number.isSafeInteger(value.expires_in) ||
160
+ value.expires_in <= 0 ||
161
+ value.expires_in > 86_400 ||
162
+ (value.scope !== undefined && typeof value.scope !== "string"))
163
+ throw new ChatGptError("invalid_response");
164
+ const idToken = typeof value.id_token === "string" ? value.id_token : previous?.idToken;
165
+ const scopes = typeof value.scope === "string" ? value.scope.split(/\s+/).filter(Boolean) : previous?.scopes;
166
+ if (!idToken || scopes === undefined)
167
+ throw new ChatGptError("invalid_response");
168
+ const savedAt = Date.now();
169
+ return {
170
+ accessToken: value.access_token,
171
+ refreshToken: value.refresh_token,
172
+ idToken,
173
+ scopes,
174
+ expiresAt: savedAt + value.expires_in * 1000,
175
+ savedAt,
176
+ earliestRefreshAt: typeof value.earliest_refresh_at === "number" &&
177
+ Number.isSafeInteger(value.earliest_refresh_at)
178
+ ? value.earliest_refresh_at * 1000
179
+ : undefined,
180
+ };
181
+ }
182
+ export async function validateIdentity(idToken, clientId, metadata, options = {}) {
183
+ try {
184
+ const jwks = createRemoteJWKSet(new URL(metadata.jwks_uri), {
185
+ timeoutDuration: 15_000,
186
+ [customFetch]: (url, init) => (options.fetcher ?? globalThis.fetch)(url, {
187
+ ...init,
188
+ redirect: "error",
189
+ signal: options.signal === undefined
190
+ ? init.signal
191
+ : AbortSignal.any([options.signal, ...(init.signal ? [init.signal] : [])]),
192
+ }),
193
+ });
194
+ const { payload } = await jwtVerify(idToken, jwks, {
195
+ issuer: CHATGPT_ISSUER,
196
+ audience: clientId,
197
+ requiredClaims: ["exp", "iat", "sub", ...(options.nonce === undefined ? [] : ["nonce"])],
198
+ algorithms: ["RS256", "ES256"],
199
+ });
200
+ if (typeof payload.sub !== "string" ||
201
+ payload.sub.length === 0 ||
202
+ (options.nonce !== undefined && payload.nonce !== options.nonce) ||
203
+ (options.subject !== undefined && payload.sub !== options.subject))
204
+ throw new ChatGptError("invalid_identity");
205
+ checkCancellation(options.signal);
206
+ return {
207
+ subject: payload.sub,
208
+ email: typeof payload.email === "string" ? payload.email : undefined,
209
+ };
210
+ }
211
+ catch {
212
+ checkCancellation(options.signal);
213
+ throw new ChatGptError("invalid_identity");
214
+ }
215
+ }
216
+ async function listenForAuthorization(state, clientId, signal, port = 0, reservedPort) {
217
+ let resolve;
218
+ let reject;
219
+ let settled = false;
220
+ const result = new Promise((yes, no) => {
221
+ resolve = yes;
222
+ reject = no;
223
+ });
224
+ void result.catch(() => undefined);
225
+ const onRequest = (request, response) => {
226
+ response.setHeader("Content-Type", "text/plain; charset=utf-8");
227
+ response.setHeader("Cache-Control", "no-store");
228
+ let url;
229
+ try {
230
+ url = new URL(request.url ?? "/", "http://127.0.0.1");
231
+ }
232
+ catch {
233
+ response.writeHead(400).end("Invalid callback path");
234
+ return;
235
+ }
236
+ if (request.method !== "GET" || url.pathname !== "/auth/callback") {
237
+ response.writeHead(404).end("Not found");
238
+ return;
239
+ }
240
+ if (settled ||
241
+ url.searchParams.getAll("state").length !== 1 ||
242
+ url.searchParams.get("state") !== state) {
243
+ response.writeHead(400).end("Invalid state");
244
+ return;
245
+ }
246
+ settled = true;
247
+ if (url.searchParams.has("error")) {
248
+ response.writeHead(400).end("Authorization was not completed. Return to HowTo.");
249
+ reject(new ChatGptError("authorization_failed"));
250
+ return;
251
+ }
252
+ const code = url.searchParams.get("code");
253
+ const issuedClientId = url.searchParams.get("client_id") ?? clientId;
254
+ if (!code ||
255
+ !issuedClientId ||
256
+ issuedClientId === "dynamic_agent_client" ||
257
+ url.searchParams.getAll("code").length !== 1 ||
258
+ url.searchParams.getAll("client_id").length > 1 ||
259
+ (clientId !== undefined && issuedClientId !== clientId)) {
260
+ response.writeHead(400).end("Invalid callback");
261
+ reject(new ChatGptError("authorization_failed"));
262
+ return;
263
+ }
264
+ response.end("HowTo authorization received. You can close this window and return to the terminal.");
265
+ resolve({ code, clientId: issuedClientId });
266
+ };
267
+ let server = createServer(onRequest);
268
+ let reservedServer;
269
+ const bind = async () => {
270
+ checkCancellation(signal);
271
+ server.requestTimeout = 10_000;
272
+ server.headersTimeout = 10_000;
273
+ await new Promise((yes, no) => {
274
+ server.once("error", no);
275
+ server.listen(port, "127.0.0.1", yes);
276
+ });
277
+ checkCancellation(signal);
278
+ const address = server.address();
279
+ if (address === null || typeof address === "string")
280
+ throw new ChatGptError("authorization_failed");
281
+ return address.port;
282
+ };
283
+ try {
284
+ let callbackPort = await bind();
285
+ if (callbackPort === reservedPort) {
286
+ if (port !== 0)
287
+ throw new ChatGptError("callback_port_unavailable");
288
+ // 暂时保留冲突监听,确保内核不会把同一端口再次分给替代监听。
289
+ reservedServer = server;
290
+ server = createServer(onRequest);
291
+ callbackPort = await bind();
292
+ }
293
+ const abort = () => {
294
+ settled = true;
295
+ reject(new InteractionCancelledError());
296
+ };
297
+ signal.addEventListener("abort", abort, { once: true });
298
+ if (signal.aborted)
299
+ abort();
300
+ return {
301
+ redirectUri: `http://127.0.0.1:${callbackPort}/auth/callback`,
302
+ result,
303
+ close() {
304
+ signal.removeEventListener("abort", abort);
305
+ server.closeAllConnections();
306
+ server.close();
307
+ },
308
+ };
309
+ }
310
+ catch {
311
+ server.closeAllConnections();
312
+ server.close();
313
+ checkCancellation(signal);
314
+ throw new ChatGptError("callback_port_unavailable");
315
+ }
316
+ finally {
317
+ reservedServer?.closeAllConnections();
318
+ reservedServer?.close();
319
+ }
320
+ }