@hex4c59/pi-ext-config-sync 0.1.1 → 0.1.2

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,293 @@
1
+ import http from "node:http";
2
+ import https from "node:https";
3
+ import tls from "node:tls";
4
+ import type { Socket } from "node:net";
5
+
6
+ export const DEFAULT_ATTEMPTS = 4;
7
+ export const DEFAULT_TIMEOUT_MS = 12_000;
8
+ const RETRY_BASE_DELAY_MS = 800;
9
+
10
+ // 网络抖动、DNS 污染解析到不可达地址、连接被对端重置时,重试可以达到可用节点。
11
+ // HTTP 状态码错误由调用方处理,不在传输层重试。
12
+ const RETRYABLE_CODES = new Set([
13
+ "ECONNRESET",
14
+ "ECONNREFUSED",
15
+ "ECONNABORTED",
16
+ "EPIPE",
17
+ "ETIMEDOUT",
18
+ "ENOTFOUND",
19
+ "EAI_AGAIN",
20
+ "EHOSTUNREACH",
21
+ "ENETUNREACH",
22
+ ]);
23
+
24
+ export interface HttpResponse {
25
+ status: number;
26
+ statusText: string;
27
+ headers: http.IncomingHttpHeaders;
28
+ text: string;
29
+ }
30
+
31
+ export interface HttpRequestOptions {
32
+ method: string;
33
+ url: string;
34
+ headers?: Record<string, string>;
35
+ body?: string;
36
+ signal?: AbortSignal;
37
+ timeoutMs?: number;
38
+ }
39
+
40
+ export interface TransportConfig {
41
+ proxy?: string;
42
+ noProxy?: string;
43
+ attempts?: number;
44
+ }
45
+
46
+ export class NetworkError extends Error {
47
+ constructor(message: string) {
48
+ super(message);
49
+ this.name = "NetworkError";
50
+ }
51
+ }
52
+
53
+ // GitHub 相关流量全部是 HTTPS。代理使用 HTTP CONNECT 隧道,
54
+ // TLS 仍由本进程与目标站点协商,证书校验、SNI 和 HTTP/1.1 行为保持不变。
55
+ export class Transport {
56
+ private readonly directAgent: https.Agent;
57
+ private readonly tunnelAgent: https.Agent | null;
58
+ private readonly proxy: string;
59
+ private readonly noProxy: string[];
60
+ private readonly attempts: number;
61
+
62
+ constructor(config: TransportConfig = {}) {
63
+ this.proxy = config.proxy?.trim() ?? "";
64
+ this.noProxy = parseNoProxy(config.noProxy);
65
+ this.attempts = Math.max(1, config.attempts ?? DEFAULT_ATTEMPTS);
66
+ this.directAgent = new https.Agent({ keepAlive: true });
67
+ this.tunnelAgent = this.proxy.length > 0 ? new TunnelAgent(this.proxy) : null;
68
+ }
69
+
70
+ usesProxy(url: string): boolean {
71
+ if (this.tunnelAgent === null) return false;
72
+ let host: string;
73
+ try {
74
+ host = new URL(url).hostname.toLowerCase();
75
+ } catch {
76
+ return false;
77
+ }
78
+ return !matchesNoProxy(host, this.noProxy);
79
+ }
80
+
81
+ async request(options: HttpRequestOptions): Promise<HttpResponse> {
82
+ const url = parseUrl(options.url);
83
+ if (url.protocol !== "https:") {
84
+ throw new NetworkError(`Unsupported protocol for ${options.url}`);
85
+ }
86
+ let lastError: unknown = undefined;
87
+ for (let attempt = 1; attempt <= this.attempts; attempt++) {
88
+ try {
89
+ return await this.requestOnce(url, options);
90
+ } catch (error) {
91
+ lastError = error;
92
+ if (options.signal?.aborted === true) throw error;
93
+ if (attempt === this.attempts || !isRetryable(error)) {
94
+ throw describeFailure(error, this.proxy, attempt);
95
+ }
96
+ await delay(RETRY_BASE_DELAY_MS * attempt, options.signal);
97
+ }
98
+ }
99
+ throw describeFailure(lastError, this.proxy, this.attempts);
100
+ }
101
+
102
+ private requestOnce(url: URL, options: HttpRequestOptions): Promise<HttpResponse> {
103
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
104
+ const agent = this.usesProxy(url.href) ? this.tunnelAgent ?? this.directAgent : this.directAgent;
105
+ return new Promise((resolve, reject) => {
106
+ const request = https.request({
107
+ method: options.method,
108
+ host: url.hostname,
109
+ port: url.port.length > 0 ? Number(url.port) : 443,
110
+ path: `${url.pathname}${url.search}`,
111
+ headers: options.headers,
112
+ agent,
113
+ timeout: timeoutMs,
114
+ }, (response) => {
115
+ const chunks: Buffer[] = [];
116
+ response.on("data", (chunk: Buffer) => chunks.push(chunk));
117
+ response.once("error", reject);
118
+ response.once("end", () => {
119
+ resolve({
120
+ status: response.statusCode ?? 0,
121
+ statusText: response.statusMessage ?? "",
122
+ headers: response.headers,
123
+ text: Buffer.concat(chunks).toString("utf8"),
124
+ });
125
+ });
126
+ });
127
+ request.once("timeout", () => {
128
+ request.destroy(new NetworkError(`Request timed out after ${timeoutMs} ms.`));
129
+ });
130
+ request.once("error", reject);
131
+ if (options.signal !== undefined) {
132
+ const signal = options.signal;
133
+ const onAbort = (): void => {
134
+ request.destroy(toAbortError(signal));
135
+ };
136
+ if (signal.aborted) {
137
+ onAbort();
138
+ return;
139
+ }
140
+ signal.addEventListener("abort", onAbort, { once: true });
141
+ request.once("close", () => signal.removeEventListener("abort", onAbort));
142
+ }
143
+ if (options.body !== undefined) request.write(options.body);
144
+ request.end();
145
+ });
146
+ }
147
+ }
148
+
149
+ class TunnelAgent extends https.Agent {
150
+ private readonly proxy: string;
151
+
152
+ constructor(proxy: string) {
153
+ super({ keepAlive: true });
154
+ this.proxy = proxy;
155
+ }
156
+
157
+ override createConnection(
158
+ options: https.RequestOptions,
159
+ callback?: (error: Error | null, socket: Socket) => void,
160
+ ): undefined {
161
+ const host = options.host ?? "";
162
+ const port = typeof options.port === "number" ? options.port : 443;
163
+ const timeoutMs = options.timeout ?? DEFAULT_TIMEOUT_MS;
164
+ openTunnel(this.proxy, host, port, timeoutMs).then((socket) => {
165
+ const secure = tls.connect({
166
+ socket,
167
+ servername: options.servername ?? host,
168
+ ALPNProtocols: ["http/1.1"],
169
+ });
170
+ secure.once("error", (error: Error) => {
171
+ secure.destroy();
172
+ callback?.(error, undefined as unknown as Socket);
173
+ });
174
+ secure.once("secureConnect", () => callback?.(null, secure));
175
+ }).catch((error: Error) => {
176
+ callback?.(error, undefined as unknown as Socket);
177
+ });
178
+ return undefined;
179
+ }
180
+ }
181
+
182
+ function openTunnel(proxy: string, host: string, port: number, timeoutMs: number): Promise<Socket> {
183
+ return new Promise((resolve, reject) => {
184
+ let target: URL;
185
+ try {
186
+ target = new URL(proxy);
187
+ } catch {
188
+ reject(new NetworkError(`Invalid proxy URL: ${proxy}`));
189
+ return;
190
+ }
191
+ const request = http.request({
192
+ host: target.hostname,
193
+ port: target.port.length > 0 ? Number(target.port) : 80,
194
+ method: "CONNECT",
195
+ path: `${host}:${port}`,
196
+ headers: { Host: `${host}:${port}` },
197
+ timeout: timeoutMs,
198
+ });
199
+ request.once("connect", (response, socket) => {
200
+ if (response.statusCode === 200) {
201
+ resolve(socket);
202
+ return;
203
+ }
204
+ socket.destroy();
205
+ reject(new NetworkError(`Proxy refused CONNECT to ${host}:${port} (${response.statusCode}).`));
206
+ });
207
+ request.once("timeout", () => {
208
+ request.destroy(new NetworkError(`Proxy did not answer within ${timeoutMs} ms.`));
209
+ });
210
+ request.once("error", reject);
211
+ request.end();
212
+ });
213
+ }
214
+
215
+ function parseUrl(value: string): URL {
216
+ try {
217
+ return new URL(value);
218
+ } catch {
219
+ throw new NetworkError(`Invalid URL: ${value}`);
220
+ }
221
+ }
222
+
223
+ function parseNoProxy(value: string | undefined): string[] {
224
+ if (value === undefined) return [];
225
+ return value
226
+ .split(/[,\s]+/)
227
+ .map((entry) => entry.trim().toLowerCase().replace(/^\*?\./, ""))
228
+ .filter((entry) => entry.length > 0);
229
+ }
230
+
231
+ function matchesNoProxy(host: string, entries: string[]): boolean {
232
+ for (const entry of entries) {
233
+ if (entry === "*") return true;
234
+ if (host === entry || host.endsWith(`.${entry}`)) return true;
235
+ }
236
+ return false;
237
+ }
238
+
239
+ function isRetryable(error: unknown): boolean {
240
+ if (!(error instanceof Error)) return false;
241
+ if (error.name === "AbortError") return false;
242
+ if (error instanceof NetworkError) return true;
243
+ const code = errorCode(error);
244
+ return code !== undefined && RETRYABLE_CODES.has(code);
245
+ }
246
+
247
+ function errorCode(error: Error): string | undefined {
248
+ const code = (error as { code?: unknown }).code;
249
+ return typeof code === "string" ? code : undefined;
250
+ }
251
+
252
+ export function describeFailure(error: unknown, proxy: string, attempts: number): Error {
253
+ if (error instanceof Error && error.name === "AbortError") return error;
254
+ const message = error instanceof Error ? error.message : String(error);
255
+ const code = error instanceof Error ? errorCode(error) : undefined;
256
+ const tries = attempts > 1 ? ` after ${attempts} attempts` : "";
257
+ const hint = proxy.length > 0
258
+ ? ` Proxy: ${proxy}.`
259
+ : " Set httpProxy in settings.json or HTTPS_PROXY in the environment.";
260
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
261
+ return new NetworkError(`Cannot resolve GitHub${tries}: DNS lookup failed.${hint}`);
262
+ }
263
+ if (code === "ECONNREFUSED") {
264
+ return new NetworkError(`GitHub refused the connection${tries}.${hint}`);
265
+ }
266
+ return new NetworkError(`Cannot reach GitHub${tries}: ${message}${hint}`);
267
+ }
268
+
269
+ function toAbortError(signal: AbortSignal): Error {
270
+ const reason: unknown = signal.reason;
271
+ if (reason instanceof Error) return reason;
272
+ const error = new Error("Request was aborted.");
273
+ error.name = "AbortError";
274
+ return error;
275
+ }
276
+
277
+ export async function delay(ms: number, signal?: AbortSignal): Promise<void> {
278
+ await new Promise<void>((resolve, reject) => {
279
+ if (signal?.aborted === true) {
280
+ reject(signal.reason);
281
+ return;
282
+ }
283
+ const timer = setTimeout(() => {
284
+ signal?.removeEventListener("abort", onAbort);
285
+ resolve();
286
+ }, ms);
287
+ const onAbort = (): void => {
288
+ clearTimeout(timer);
289
+ reject(signal?.reason);
290
+ };
291
+ signal?.addEventListener("abort", onAbort, { once: true });
292
+ });
293
+ }
package/src/types.ts CHANGED
@@ -32,6 +32,7 @@ export interface SyncConfig {
32
32
  repo: string;
33
33
  branch: string;
34
34
  autoPull: boolean;
35
+ proxy: string;
35
36
  allowPublicRepo: boolean;
36
37
  localSettingsKeys: string[];
37
38
  includeAuthProviders: string[];