pi-tsgw 0.0.13 → 0.0.16

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,63 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { UploadError } from "./errors.ts";
4
+ import { CONTENT_TYPE_PATTERN, RESUME_PATTERN, object, UPLOAD_TOOL, URL_TOOL } from "./protocol.ts";
5
+ import { uploadLocalFile, type UploadDependencies } from "./uploader.ts";
6
+
7
+ const linkSchema = Type.Object({ key: Type.String(), url: Type.String(), expiresAt: Type.String(), expiresIn: Type.Integer() });
8
+
9
+ /** 不注册 MCP,也不访问凭据或配置:使用调用方当前可用的工具。 */
10
+ export function registerUploadTool(pi: ExtensionAPI, dependencies: Pick<UploadDependencies, "put" | "remoteTimeoutMs"> = {}): void {
11
+ pi.registerTool({
12
+ name: "upload_local_file",
13
+ label: "上传本地文件",
14
+ description: "通过已连接的 ts_oht MCP,将明确授权的本地文件从 Pi 主机上传到私有 S3。" +
15
+ "读取操作系统允许访问的文件;这不是浏览器上传,也不是沙箱。文件不超过 32 MiB 时使用一次 PUT;更大的文件使用 3 个并发工作单元进行流式分片上传。" +
16
+ "返回持有者即可使用的临时下载 URL(默认有效期 24 小时,inline 展示;HTML 可能执行)。存储内容约 7 天后清理。" +
17
+ "不会自动重试。失败或结果未知时,请保留 key 和 resume 恢复凭条;仅在明确要求恢复时使用返回的凭条," +
18
+ "切勿盲目发起全新上传。恢复前,请停止其他客户端对同一文件的上传。不要记录预签名 URL。",
19
+ parameters: Type.Object({
20
+ path: Type.String({ minLength: 1, description: "插件运行环境中的路径;相对路径以会话 cwd 为基准。仅支持普通文件。" }),
21
+ contentType: Type.Optional(Type.String({ minLength: 3, maxLength: 127, pattern: CONTENT_TYPE_PATTERN.source, description: "不带 charset 的 MIME 类型;默认根据扩展名推断,无法推断时使用 application/octet-stream。" })),
22
+ expiresIn: Type.Optional(Type.Integer({ minimum: 1, maximum: 604800, description: "下载 URL 的有效期,单位为秒;默认 86400。不会延长存储保留时间。" })),
23
+ disposition: Type.Optional(Type.Union([Type.Literal("inline"), Type.Literal("attachment")])),
24
+ resume: Type.Optional(Type.String({ minLength: 1, maxLength: 8192, pattern: RESUME_PATTERN.source, description: "上次失败调用返回的原样恢复凭条;恢复前会检查旧对象。不含凭据。" })),
25
+ }),
26
+ outputSchema: Type.Object({
27
+ uploaded: Type.Union([Type.Boolean(), Type.Null()]),
28
+ uploadStatus: Type.Union([Type.Literal("not-started"), Type.Literal("incomplete"), Type.Literal("unknown"), Type.Literal("uploaded")]),
29
+ phase: Type.Union([Type.Literal("local"), Type.Literal("prepare"), Type.Literal("upload"), Type.Literal("complete"), Type.Literal("link")]),
30
+ linkStatus: Type.Union([Type.Literal("not-ready"), Type.Literal("ready"), Type.Literal("failed")]),
31
+ key: Type.Optional(Type.String()), uid: Type.Optional(Type.String()), url: Type.Optional(Type.String()),
32
+ expiresAt: Type.Optional(Type.String()), expiresIn: Type.Optional(Type.Integer()),
33
+ disposition: Type.Optional(Type.Union([Type.Literal("inline"), Type.Literal("attachment")])),
34
+ fallback: Type.Optional(linkSchema), resume: Type.Optional(Type.String()),
35
+ error: Type.Optional(Type.Object({ code: Type.String(), message: Type.String() })),
36
+ }),
37
+ reachesTools: () => [UPLOAD_TOOL, URL_TOOL],
38
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
39
+ async execute(_id, params, signal, onUpdate, ctx) {
40
+ const result = await uploadLocalFile(params, ctx.cwd, signal ?? ctx.signal ?? new AbortController().signal, {
41
+ ...dependencies,
42
+ async call(name, args, operationSignal) {
43
+ if (typeof ctx.executeTool !== "function" || !Array.isArray(ctx.tools))
44
+ throw new UploadError("unsupported-host", "此上传工具需要支持 ctx.executeTool 的 Pi 主机(已使用 1.1.0 测试)。");
45
+ if (![UPLOAD_TOOL, URL_TOOL].includes(name) || !ctx.tools.some(tool => tool.name === name))
46
+ throw new UploadError("mcp-unavailable", "所需的 ts_oht 工具尚未连接或不可调用。请在主机中启用它;本工具未创建连接。");
47
+ const outcome = await ctx.executeTool(name, args, { signal: operationSignal });
48
+ // Pi 将原始 MCP CallToolResult 包装在 result.structuredContent 中。
49
+ // 结构化结果缺失时,绝不能从文本中恢复它以绕过主机脱敏。
50
+ if (outcome.result.structuredContent === undefined)
51
+ throw new UploadError("mcp-unavailable", "主机阻止了调用,或未提供结构化 MCP 结果。");
52
+ const raw = object(outcome.result.structuredContent);
53
+ return outcome.isError ? { ...raw, isError: true } : raw;
54
+ },
55
+ onProgress(progress) {
56
+ onUpdate?.({ content: [{ type: "text", text: `上传:${({ local: "本地检查", prepare: "准备", upload: "上传", complete: "完成确认", link: "获取链接" })[progress.phase]}(${progress.completedParts}/${progress.totalParts} 个分片)` }], details: progress });
57
+ },
58
+ });
59
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: result,
60
+ structuredContent: { ...result }, ...(result.error ? { isError: true } : {}) };
61
+ },
62
+ });
63
+ }
@@ -0,0 +1,93 @@
1
+ import { constants } from "node:fs";
2
+ import { open, realpath, stat, type FileHandle } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
4
+ import { basename, extname, resolve } from "node:path";
5
+ import { homedir } from "node:os";
6
+ import { CONTENT_TYPE_PATTERN, MAX_BYTES, type FileMetadata } from "./protocol.ts";
7
+ import { checkAbort, UploadError } from "./errors.ts";
8
+
9
+ const MIME: Record<string, string> = {
10
+ ".txt": "text/plain", ".md": "text/markdown", ".csv": "text/csv", ".html": "text/html",
11
+ ".json": "application/json", ".pdf": "application/pdf", ".zip": "application/zip",
12
+ ".gz": "application/gzip", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
13
+ ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml", ".mp3": "audio/mpeg",
14
+ ".wav": "audio/wav", ".ogg": "audio/ogg", ".mp4": "video/mp4", ".webm": "video/webm",
15
+ };
16
+
17
+ type FileStat = Awaited<ReturnType<typeof fileStat>>;
18
+ const fileStat = (handle: FileHandle) => handle.stat({ bigint: true });
19
+ const identity = (s: FileStat): string =>
20
+ [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
21
+
22
+ export interface LocalFile {
23
+ metadata: FileMetadata;
24
+ fingerprint: string;
25
+ assertUnchanged(): Promise<void>;
26
+ bytes(offset: number, size: number, signal: AbortSignal): AsyncIterable<Uint8Array>;
27
+ snapshot(signal: AbortSignal): Promise<Uint8Array>;
28
+ close(): Promise<void>;
29
+ }
30
+
31
+ /** 使用操作系统的文件访问权限,而非沙箱或内置 read 工具的权限策略。 */
32
+ export async function openLocalFile(path: string, cwd: string, contentType?: string): Promise<LocalFile> {
33
+ let handle: FileHandle | undefined;
34
+ try {
35
+ if (!path || path.includes("\0")) throw new UploadError("invalid-path", "必须提供本地文件路径。");
36
+ const fullPath = await realpath(resolve(cwd, path.startsWith("~/") ? `${homedir()}/${path.slice(2)}` : path));
37
+ // NONBLOCK 防止普通文件被竞态替换为 FIFO 时导致 open() 挂起。
38
+ if (!(await stat(fullPath)).isFile()) throw new UploadError("not-file", "只能上传普通文件。");
39
+ handle = await open(fullPath, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
40
+ const opened = handle;
41
+ const initial = await fileStat(opened);
42
+ if (!initial.isFile()) throw new UploadError("not-file", "只能上传普通文件。");
43
+ const size = Number(initial.size);
44
+ if (!Number.isSafeInteger(size) || size < 1 || size > MAX_BYTES)
45
+ throw new UploadError("invalid-size", "文件大小必须在 1 字节到 5 TiB 之间。后端限制可能更低。");
46
+ const filename = basename(fullPath);
47
+ if (Buffer.byteLength(filename) > 255 || filename.trim() !== filename || /[\u0000-\u001f\u007f-\u009f\\%?#:<>"|*]/.test(filename))
48
+ throw new UploadError("invalid-filename", "上传服务不支持此文件名。");
49
+ const mime = contentType ?? MIME[extname(filename).toLowerCase()] ?? "application/octet-stream";
50
+ if (mime.length > 127 || !CONTENT_TYPE_PATTERN.test(mime))
51
+ throw new UploadError("invalid-content-type", "contentType 必须是不带参数的 MIME 类型。");
52
+ const metadata: FileMetadata = { filename, contentType: mime.toLowerCase(), size,
53
+ mtimeMs: Number(initial.mtimeNs) / 1e6, ctimeMs: Number(initial.ctimeNs) / 1e6 };
54
+ const stamp = identity(initial);
55
+ const fingerprint = createHash("sha256").update(JSON.stringify([fullPath, stamp, metadata])).digest("hex");
56
+ const assertUnchanged = async (): Promise<void> => {
57
+ try {
58
+ if (identity(await fileStat(opened)) !== stamp || identity(await stat(fullPath, { bigint: true })) !== stamp)
59
+ throw new Error();
60
+ } catch { throw new UploadError("file-changed", "源文件已更改。不得复用其旧分片或用旧分片完成上传。"); }
61
+ };
62
+ async function* bytes(offset: number, count: number, signal: AbortSignal): AsyncIterable<Uint8Array> {
63
+ checkAbort(signal);
64
+ await assertUnchanged();
65
+ let position = offset;
66
+ while (position < offset + count) {
67
+ checkAbort(signal);
68
+ // 显式指定位置,让并发分片无需共享文件描述符的游标。
69
+ const buffer = Buffer.allocUnsafe(Math.min(256 * 1024, offset + count - position));
70
+ const { bytesRead } = await opened.read(buffer, 0, buffer.length, position);
71
+ if (bytesRead === 0) throw new UploadError("file-changed", "源文件在上传期间被截断。");
72
+ position += bytesRead;
73
+ yield buffer.subarray(0, bytesRead);
74
+ }
75
+ await assertUnchanged();
76
+ }
77
+ await assertUnchanged();
78
+ return {
79
+ metadata, fingerprint, assertUnchanged, bytes,
80
+ async snapshot(signal) {
81
+ const data = new Uint8Array(size);
82
+ let offset = 0;
83
+ for await (const block of bytes(0, size, signal)) { data.set(block, offset); offset += block.byteLength; }
84
+ return data;
85
+ },
86
+ close: () => opened.close(),
87
+ };
88
+ } catch (error) {
89
+ await handle?.close().catch(() => {});
90
+ if (error instanceof UploadError) throw error;
91
+ throw new UploadError("file-unavailable", "无法读取插件运行环境中的本地文件。");
92
+ }
93
+ }
@@ -0,0 +1,180 @@
1
+ import { UploadError, invalidResponse } from "./errors.ts";
2
+
3
+ export const SINGLE_LIMIT = 32 * 1024 ** 2;
4
+ export const MAX_BYTES = 5 * 1024 ** 4;
5
+ export const UPLOAD_TOOL = "mcp__ts_oht__upload_file";
6
+ export const URL_TOOL = "mcp__ts_oht__get_file_url";
7
+ // 绝对结尾断言:JavaScript 单独使用 `$` 也会接受末尾换行。
8
+ export const CONTENT_TYPE_PATTERN = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$(?![\s\S])/;
9
+ export const RESUME_PATTERN = /^[A-Za-z0-9_-]+$(?![\s\S])/;
10
+
11
+ export interface FileMetadata {
12
+ filename: string;
13
+ contentType: string;
14
+ size: number;
15
+ mtimeMs: number;
16
+ ctimeMs: number;
17
+ }
18
+ export type Download = {
19
+ key: string;
20
+ url: string;
21
+ expiresAt: string;
22
+ expiresIn: number;
23
+ };
24
+ export interface Target {
25
+ partNumber: number;
26
+ offset: number;
27
+ size: number;
28
+ url: string;
29
+ method: "PUT";
30
+ headers: Record<string, string>;
31
+ expiresAt: string;
32
+ }
33
+ export interface Plan extends Download {
34
+ mode: "single" | "multipart";
35
+ uploaded: boolean;
36
+ uploads: Target[];
37
+ uid?: string;
38
+ partSize?: number;
39
+ totalParts?: number;
40
+ }
41
+ export interface Receipt {
42
+ version: 1;
43
+ key: string;
44
+ uid?: string;
45
+ mode: "single" | "multipart";
46
+ phase: "upload" | "complete" | "link";
47
+ fingerprint: string;
48
+ metadata: FileMetadata;
49
+ }
50
+
51
+ export function object(value: unknown): Record<string, unknown> {
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalidResponse();
53
+ return value as Record<string, unknown>;
54
+ }
55
+ function text(value: unknown, max = 16384): string {
56
+ if (typeof value !== "string" || !value || value.length > max) invalidResponse();
57
+ return value;
58
+ }
59
+ function integer(value: unknown, max: number): number {
60
+ if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > max) invalidResponse();
61
+ return value as number;
62
+ }
63
+ export function validKey(value: unknown): string {
64
+ const key = text(value, 1024);
65
+ if (Buffer.byteLength(key) > 1024 || /[\u0000-\u001f\u007f-\u009f\\%?#]/.test(key) || key.split("/").some(p => !p || p === "." || p === "..")) invalidResponse();
66
+ return key;
67
+ }
68
+ function httpsUrl(value: unknown): string {
69
+ const input = text(value);
70
+ try {
71
+ const url = new URL(input);
72
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || (url.port && url.port !== "443")) invalidResponse();
73
+ return input;
74
+ } catch { return invalidResponse(); }
75
+ }
76
+ function expiry(value: unknown): string {
77
+ const date = text(value, 64);
78
+ if (!Number.isFinite(Date.parse(date))) invalidResponse();
79
+ return date;
80
+ }
81
+
82
+ /** 主机适配器提供的是 MCP CallToolResult,而非 AgentToolCallOutcome。 */
83
+ export function mcpData(value: unknown): Record<string, unknown> {
84
+ const result = object(value);
85
+ let data: unknown = result.structuredContent;
86
+ if (data === undefined && Array.isArray(result.content)) {
87
+ const blocks = result.content.filter(b => b && b.type === "text");
88
+ if (blocks.length === 1 && typeof blocks[0].text === "string" && blocks[0].text.length <= 4 * 1024 ** 2) {
89
+ try { data = JSON.parse(blocks[0].text); } catch { /* 拒绝非 JSON 内容,绝不回显。 */ }
90
+ }
91
+ }
92
+ const body = object(data);
93
+ if (result.isError === true || body.error !== undefined) {
94
+ const error = body.error && typeof body.error === "object" ? body.error as Record<string, unknown> : {};
95
+ // 只有明确的 not-found 才允许继续恢复分片上传。
96
+ const code = error.code === "not-found" ? "not-found" : "mcp-error";
97
+ throw new UploadError(code, code === "not-found"
98
+ ? "先前的对象不存在。"
99
+ : "远程工具调用失败;为保护凭据,未提供其原始响应。");
100
+ }
101
+ return body;
102
+ }
103
+
104
+ export function download(value: unknown, expectedKey?: string, expectedSeconds = 86400): Download {
105
+ const data = object(value);
106
+ const result = {
107
+ key: validKey(data.key), url: httpsUrl(data.url),
108
+ expiresAt: expiry(data.expiresAt), expiresIn: integer(data.expiresIn, 604800),
109
+ };
110
+ if ((expectedKey && result.key !== expectedKey) || result.expiresIn !== expectedSeconds) invalidResponse();
111
+ return result;
112
+ }
113
+
114
+ export function planIdentity(value: unknown, size: number, previous?: Receipt): Pick<Plan, "key" | "mode" | "uploaded" | "uid" | "partSize" | "totalParts"> {
115
+ const data = object(value);
116
+ const key = validKey(data.key);
117
+ if (previous && key !== previous.key)
118
+ throw new UploadError("session-changed", "旧的分片上传任务已不可用。已拒绝不同的上传计划,未向其发送任何字节。");
119
+ const mode = size <= SINGLE_LIMIT ? "single" : "multipart";
120
+ if (data.mode !== mode || typeof data.uploaded !== "boolean" ||
121
+ !Array.isArray(data.uploads) || data.uploads.length > 1024) invalidResponse();
122
+ const result: Pick<Plan, "key" | "mode" | "uploaded" | "uid" | "partSize" | "totalParts"> = { key, mode, uploaded: data.uploaded };
123
+ if (result.mode === "multipart") {
124
+ result.uid = text(data.uid, 64);
125
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(result.uid)) invalidResponse();
126
+ if (previous && previous.uid !== result.uid) invalidResponse();
127
+ result.partSize = integer(data.partSize, 5 * 1024 ** 3);
128
+ result.totalParts = integer(data.totalParts, 1024);
129
+ if (result.partSize < 5 * 1024 ** 2 || Math.ceil(size / result.partSize) !== result.totalParts ||
130
+ data.remainingParts !== data.uploads.length) invalidResponse();
131
+ } else if (result.uploaded || data.uploads.length !== 1) invalidResponse();
132
+ if (result.uploaded !== (data.uploads.length === 0)) invalidResponse();
133
+ return result;
134
+ }
135
+
136
+ export function plan(value: unknown, size: number, previous?: Receipt): Plan {
137
+ const identity = planIdentity(value, size, previous);
138
+ const data = object(value);
139
+ const link = download(data);
140
+ const result: Plan = { ...identity, ...link, uploads: [] };
141
+ const seen = new Set<number>();
142
+ for (const item of data.uploads as unknown[]) {
143
+ const part = object(item);
144
+ const number = integer(part.partNumber, result.totalParts ?? 1);
145
+ const offset = (number - 1) * (result.partSize ?? size);
146
+ const bytes = Math.min(result.partSize ?? size, size - offset);
147
+ if (seen.has(number) || part.offset !== offset || part.size !== bytes || part.method !== "PUT") invalidResponse();
148
+ seen.add(number);
149
+ const url = httpsUrl(part.url);
150
+ if (new URL(url).origin !== new URL(link.url).origin) invalidResponse();
151
+ const headers = object(part.headers);
152
+ if (Object.keys(headers).length > 64 || Object.values(headers).some(v => typeof v !== "string" || v.length > 8192)) invalidResponse();
153
+ result.uploads.push({ partNumber: number, offset, size: bytes, url, method: "PUT",
154
+ headers: headers as Record<string, string>, expiresAt: expiry(part.expiresAt) });
155
+ }
156
+ return result;
157
+ }
158
+
159
+ /** 凭条不包含 URL、请求头、S3 凭据或 MCP 密钥。 */
160
+ export function encodeReceipt(receipt: Receipt): string {
161
+ return Buffer.from(JSON.stringify(receipt)).toString("base64url");
162
+ }
163
+ export function decodeReceipt(token: string): Receipt {
164
+ try {
165
+ if (!token || token.length > 8192 || !RESUME_PATTERN.test(token)) invalidResponse();
166
+ const data = object(JSON.parse(Buffer.from(token, "base64url").toString("utf8")));
167
+ const meta = object(data.metadata);
168
+ if (data.version !== 1 || !["single", "multipart"].includes(String(data.mode)) ||
169
+ !["upload", "complete", "link"].includes(String(data.phase)) ||
170
+ typeof data.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(data.fingerprint) ||
171
+ typeof meta.mtimeMs !== "number" || !Number.isFinite(meta.mtimeMs) ||
172
+ typeof meta.ctimeMs !== "number" || !Number.isFinite(meta.ctimeMs)) invalidResponse();
173
+ const metadata: FileMetadata = { filename: text(meta.filename, 255), contentType: text(meta.contentType, 127),
174
+ size: integer(meta.size, MAX_BYTES), mtimeMs: meta.mtimeMs, ctimeMs: meta.ctimeMs };
175
+ const mode = data.mode as Receipt["mode"];
176
+ if ((metadata.size <= SINGLE_LIMIT) !== (mode === "single")) invalidResponse();
177
+ return { version: 1, key: validKey(data.key), mode, phase: data.phase as Receipt["phase"],
178
+ uid: mode === "multipart" ? text(data.uid, 64) : undefined, fingerprint: data.fingerprint, metadata };
179
+ } catch { throw new UploadError("invalid-resume", "恢复凭条无效。不要以全新上传尝试代替恢复。"); }
180
+ }
@@ -0,0 +1,216 @@
1
+ import { Resolver } from "node:dns/promises";
2
+ import { request, type RequestOptions } from "node:https";
3
+ import type { ClientRequest, IncomingMessage } from "node:http";
4
+ import { isIP } from "node:net";
5
+ import { UploadError } from "./errors.ts";
6
+
7
+ export interface PutTarget {
8
+ url: string;
9
+ method: "PUT";
10
+ headers: Record<string, string>;
11
+ expiresAt: string;
12
+ size: number;
13
+ }
14
+
15
+ type Address = { address: string; family: 4 | 6 };
16
+ /** 供离线传输测试使用的有限依赖注入点;生产环境始终使用 Node DNS 和 HTTPS。 */
17
+ export interface TransportDeps {
18
+ resolve(host: string, signal: AbortSignal): Promise<Address[]>;
19
+ request(options: RequestOptions, response: (response: IncomingMessage) => void): ClientRequest;
20
+ }
21
+
22
+ const messages = {
23
+ "http-error": "上传服务器拒绝了所发送的字节。不要自动重复上传。",
24
+ redirect: "上传不允许重定向。",
25
+ "network-error": "上传传输或字节流失败。不要自动重复上传。",
26
+ timeout: "上传已超过截止时间。不要自动重复上传。",
27
+ cancelled: "上传已取消。不要自动重复上传。",
28
+ "invalid-target": "上传目标不是有效的公网 HTTPS 地址。",
29
+ "invalid-headers": "上传请求头不被允许,或与字节数不匹配。",
30
+ } as const;
31
+ type Code = keyof typeof messages;
32
+ const failure = (code: Code) => new UploadError(code, messages[code]);
33
+
34
+ /** 拒绝特殊用途 IPv4,以及非全球可达、过渡机制或文档用途的 IPv6。 */
35
+ export function isPublicAddress(address: string): boolean {
36
+ if (isIP(address) === 4) {
37
+ const [a, b, c] = address.split(".").map(Number) as [number, number, number, number];
38
+ return !(a === 0 || a === 10 || a === 127 || a >= 224 ||
39
+ (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
40
+ (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||
41
+ (a === 192 && b === 0) || (a === 192 && b === 88 && c === 99) ||
42
+ (a === 198 && (b === 18 || b === 19)) || (a === 198 && b === 51 && c === 100) ||
43
+ (a === 203 && b === 0 && c === 113));
44
+ }
45
+ if (isIP(address) !== 6 || address.includes("%")) return false;
46
+ const canonical = new URL(`https://[${address}]/`).hostname.slice(1, -1);
47
+ const parts = canonical.split(":");
48
+ const first = Number.parseInt(parts[0]!, 16);
49
+ const second = Number.parseInt(parts[1] || "0", 16);
50
+ return first >= 0x2000 && first <= 0x3fff &&
51
+ // 2001::/23 包含 Teredo、基准测试、ORCHID 和协议分配地址。
52
+ !(first === 0x2001 && second < 0x200) &&
53
+ !(first === 0x2001 && second === 0xdb8) && first !== 0x2002 &&
54
+ !(first === 0x3fff && second < 0x1000);
55
+ }
56
+
57
+ async function resolvePublic(host: string, signal: AbortSignal): Promise<Address[]> {
58
+ const resolver = new Resolver();
59
+ const cancel = () => resolver.cancel();
60
+ signal.addEventListener("abort", cancel, { once: true });
61
+ try {
62
+ if (signal.aborted) throw failure("cancelled");
63
+ const results = await Promise.allSettled([resolver.resolve4(host), resolver.resolve6(host)]);
64
+ return results.flatMap((result, index) => result.status === "fulfilled"
65
+ ? result.value.map(address => ({ address, family: (index === 0 ? 4 : 6) as 4 | 6 })) : []);
66
+ } finally {
67
+ signal.removeEventListener("abort", cancel);
68
+ }
69
+ }
70
+
71
+ function validate(target: PutTarget): { url: URL; headers: Record<string, string>; deadline: number } {
72
+ let url: URL;
73
+ try { url = new URL(target.url); } catch { throw failure("invalid-target"); }
74
+ const expiry = Date.parse(target.expiresAt);
75
+ if (target.method !== "PUT" || !Number.isSafeInteger(target.size) || target.size < 0 ||
76
+ url.protocol !== "https:" || url.username || url.password || url.hash ||
77
+ (url.port && url.port !== "443") || !Number.isFinite(expiry) || expiry <= Date.now()) {
78
+ throw failure("invalid-target");
79
+ }
80
+ const headers: Record<string, string> = Object.create(null) as Record<string, string>;
81
+ for (const [key, value] of Object.entries(target.headers)) {
82
+ const name = key.toLowerCase();
83
+ if (!(name === "content-type" || name === "content-length" || name === "if-none-match" ||
84
+ /^x-amz-[a-z0-9-]+$/.test(name)) || name in headers || typeof value !== "string" ||
85
+ /[^\x20-\x7e]/.test(value) || (name === "if-none-match" && value !== "*") ||
86
+ (name === "content-length" && value !== String(target.size))) throw failure("invalid-headers");
87
+ headers[name] = value;
88
+ }
89
+ headers["content-length"] = String(target.size);
90
+ // 这是总时限,而非套接字空闲超时:至少允许 330 秒,再按 64 KiB/s 计算。
91
+ const budget = Math.max(330_000, Math.ceil(target.size / 65_536) * 1000);
92
+ return { url, headers, deadline: Math.min(expiry, Date.now() + budget) };
93
+ }
94
+
95
+ export async function putBytes(
96
+ target: PutTarget, body: AsyncIterable<Uint8Array> | Uint8Array, signal: AbortSignal,
97
+ ): Promise<void> {
98
+ return putBytesWithDeps(target, body, signal, { resolve: resolvePublic, request });
99
+ }
100
+
101
+ export async function putBytesWithDeps(
102
+ target: PutTarget, body: AsyncIterable<Uint8Array> | Uint8Array, signal: AbortSignal, deps: TransportDeps,
103
+ ): Promise<void> {
104
+ let iterator: AsyncIterator<Uint8Array> | undefined;
105
+ let req: ClientRequest | undefined;
106
+ let response: IncomingMessage | undefined;
107
+ let requestClosed: Promise<void> | undefined;
108
+ let pumping: Promise<void> | undefined;
109
+ let timer: ReturnType<typeof setTimeout> | undefined;
110
+ const controller = new AbortController();
111
+ let error: UploadError | undefined;
112
+ let rejectStopped!: (error: UploadError) => void;
113
+ const stopped = new Promise<never>((_, reject) => { rejectStopped = reject; });
114
+ void stopped.catch(() => {});
115
+ const stop = (code: Code) => {
116
+ if (error) return;
117
+ error = failure(code);
118
+ controller.abort();
119
+ response?.destroy();
120
+ req?.destroy();
121
+ rejectStopped(error);
122
+ };
123
+ const abort = () => stop("cancelled");
124
+ try {
125
+ iterator = body instanceof Uint8Array ? (async function* () { yield body; })() : body[Symbol.asyncIterator]();
126
+ signal.addEventListener("abort", abort, { once: true });
127
+ if (signal.aborted) { stop("cancelled"); throw error; }
128
+ const { url, headers, deadline } = validate(target);
129
+ const arm = () => {
130
+ const remaining = deadline - Date.now();
131
+ if (remaining <= 0) stop("timeout");
132
+ else timer = setTimeout(arm, Math.min(remaining, 2_147_483_647));
133
+ };
134
+ arm();
135
+ const host = url.hostname.replace(/^\[|\]$/g, "");
136
+ const addresses = isIP(host) ? [{ address: host, family: isIP(host) as 4 | 6 }]
137
+ : await deps.resolve(host, controller.signal);
138
+ if (error) throw error;
139
+ if (!addresses.length) throw failure("network-error");
140
+ if (addresses.some(item => !isPublicAddress(item.address))) throw failure("invalid-target");
141
+ const pinned = addresses[0]!;
142
+ let sent = false;
143
+ let resolveResponse!: () => void;
144
+ const received = new Promise<void>(resolve => { resolveResponse = resolve; });
145
+ req = deps.request({
146
+ protocol: "https:", hostname: host, port: 443, method: "PUT",
147
+ path: url.pathname + url.search, headers, agent: false, rejectUnauthorized: true,
148
+ lookup: (_hostname, options, callback) => {
149
+ if (options.all) callback(null, [pinned]);
150
+ else callback(null, pinned.address, pinned.family);
151
+ },
152
+ }, incoming => {
153
+ response = incoming;
154
+ incoming.on("error", () => stop("network-error"));
155
+ const status = incoming.statusCode ?? 0;
156
+ if (status >= 300 && status < 400) { stop("redirect"); return; }
157
+ if (status < 200 || status >= 300) { stop("http-error"); return; }
158
+ if (!sent) { stop("network-error"); return; }
159
+ incoming.on("aborted", () => stop("network-error"));
160
+ incoming.on("end", resolveResponse);
161
+ incoming.on("close", () => { if (!incoming.complete) stop("network-error"); });
162
+ incoming.resume();
163
+ });
164
+ const active = req;
165
+ requestClosed = new Promise(resolve => active.once("close", resolve));
166
+ active.on("error", () => stop("network-error"));
167
+ active.on("close", () => { if (!response?.complete) stop("network-error"); });
168
+ pumping = (async () => {
169
+ let count = 0;
170
+ while (!error) {
171
+ const item = await iterator!.next();
172
+ if (error) break;
173
+ if (item.done) {
174
+ if (count !== target.size) throw failure("network-error");
175
+ await new Promise<void>((resolve, reject) => {
176
+ active.end(() => { sent = true; resolve(); });
177
+ void stopped.catch(reject);
178
+ });
179
+ return;
180
+ }
181
+ if (!(item.value instanceof Uint8Array) || item.value.byteLength > target.size - count) {
182
+ throw failure("network-error");
183
+ }
184
+ count += item.value.byteLength;
185
+ // 限制单次写入大小并通过回调施加背压;绝不拼接整个上传内容。
186
+ for (let offset = 0; offset < item.value.byteLength && !error; offset += 65_536) {
187
+ await new Promise<void>((resolve, reject) => {
188
+ const interrupted = () => finish(error);
189
+ const finish = (err?: Error | null) => {
190
+ controller.signal.removeEventListener("abort", interrupted);
191
+ err ? reject(err) : resolve();
192
+ };
193
+ controller.signal.addEventListener("abort", interrupted, { once: true });
194
+ try { active.write(item.value.subarray(offset, offset + 65_536), finish); }
195
+ catch { finish(failure("network-error")); }
196
+ });
197
+ }
198
+ }
199
+ })();
200
+ void pumping.catch(() => stop("network-error"));
201
+ await Promise.race([stopped, Promise.all([pumping, received])]);
202
+ } catch (caught) {
203
+ if (!error) stop(caught instanceof UploadError && caught.code in messages ? caught.code as Code : "network-error");
204
+ } finally {
205
+ if (timer) clearTimeout(timer);
206
+ signal.removeEventListener("abort", abort);
207
+ controller.abort();
208
+ response?.destroy();
209
+ req?.destroy();
210
+ // 请求或正在运行的数据生产者尚未结束时,不得返回。
211
+ await pumping?.catch(() => {});
212
+ try { await iterator?.return?.(); } catch { if (!error) error = failure("network-error"); }
213
+ await requestClosed;
214
+ }
215
+ if (error) throw error;
216
+ }