@avclabs.ai/media-mcp 0.2.1 → 0.3.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.
- package/README.md +245 -31
- package/README_CN.md +246 -32
- package/config.json +1 -0
- package/dist/image-enhancement.d.ts +3 -0
- package/dist/image-enhancement.d.ts.map +1 -0
- package/dist/image-enhancement.js +185 -0
- package/dist/image-enhancement.js.map +1 -0
- package/dist/sam3.d.ts +7 -0
- package/dist/sam3.d.ts.map +1 -1
- package/dist/sam3.js +148 -104
- package/dist/sam3.js.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +77 -53
- package/dist/server.js.map +1 -1
- package/dist/service-config.d.ts +62 -0
- package/dist/service-config.d.ts.map +1 -0
- package/dist/service-config.js +58 -0
- package/dist/service-config.js.map +1 -0
- package/dist/tooling.d.ts +42 -0
- package/dist/tooling.d.ts.map +1 -0
- package/dist/tooling.js +153 -0
- package/dist/tooling.js.map +1 -0
- package/dist/tos.d.ts +35 -0
- package/dist/tos.d.ts.map +1 -0
- package/dist/tos.js +281 -0
- package/dist/tos.js.map +1 -0
- package/dist/upload.d.ts +79 -0
- package/dist/upload.d.ts.map +1 -0
- package/dist/upload.js +190 -0
- package/dist/upload.js.map +1 -0
- package/dist/video-enhancement.d.ts.map +1 -1
- package/dist/video-enhancement.js +73 -153
- package/dist/video-enhancement.js.map +1 -1
- package/package.json +10 -5
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Media host configuration: one deep module owning precedence, validation,
|
|
2
|
+
// and derivation for everything the enhancement and SAM3 hosts need. Adapters
|
|
3
|
+
// consume the resolved MediaHostConfig; callers never merge layers themselves
|
|
4
|
+
// and never need to know variable initialization order.
|
|
5
|
+
export const SAM3_POLL_INTERVAL_MS_BOUNDS = { min: 500, max: 60000 };
|
|
6
|
+
export const SAM3_POLL_MAX_ATTEMPTS_BOUNDS = { min: 1, max: 1000 };
|
|
7
|
+
const DEFAULT_ENHANCEMENT_API_BASE_URL = 'https://mcp.avc.ai/enhance';
|
|
8
|
+
const DEFAULT_SAM3_API_BASE_URL = 'https://mcp.avc.ai/sam';
|
|
9
|
+
const DEFAULT_SAM3_POLL_INTERVAL_MS = 2000;
|
|
10
|
+
const DEFAULT_SAM3_POLL_MAX_ATTEMPTS = 25;
|
|
11
|
+
export class ConfigError extends Error {
|
|
12
|
+
}
|
|
13
|
+
// Blank values are "not provided" at every layer, so a resolved address is
|
|
14
|
+
// never empty and a blank override cannot mask a valid lower layer.
|
|
15
|
+
function highestPrecedence(...values) {
|
|
16
|
+
for (const value of values) {
|
|
17
|
+
if (value !== undefined && value.trim() !== '')
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
export function parseSam3WaitInt(raw, name, bounds, fallback) {
|
|
23
|
+
if (raw === undefined)
|
|
24
|
+
return fallback;
|
|
25
|
+
const parsed = Number.parseInt(raw, 10);
|
|
26
|
+
if (!Number.isFinite(parsed) || parsed < bounds.min || parsed > bounds.max) {
|
|
27
|
+
throw new ConfigError(`Invalid ${name} "${raw}": expected an integer between ${bounds.min} and ${bounds.max}`);
|
|
28
|
+
}
|
|
29
|
+
return parsed;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Resolves the final Media host configuration.
|
|
33
|
+
*
|
|
34
|
+
* Precedence per key: CLI override > environment > file config > built-in
|
|
35
|
+
* default. The image API base URL is derived only after the merge: an unset
|
|
36
|
+
* image base falls back to the resolved enhancement base, no matter which
|
|
37
|
+
* layer provided it. All validation happens here, before any tool is created
|
|
38
|
+
* or request is made; error messages never echo secret values.
|
|
39
|
+
*/
|
|
40
|
+
export function resolveMediaHostConfig(options) {
|
|
41
|
+
const cli = options.cli ?? {};
|
|
42
|
+
const env = options.env ?? {};
|
|
43
|
+
const file = options.file ?? {};
|
|
44
|
+
const enhancementApiBaseUrl = highestPrecedence(cli.baseUrl, env.HTTP_API_BASE_URL, file.baseUrl) ?? DEFAULT_ENHANCEMENT_API_BASE_URL;
|
|
45
|
+
const sam3ApiBaseUrl = highestPrecedence(cli.sam3BaseUrl, env.SAM3_API_BASE_URL, file.sam3BaseUrl) ?? DEFAULT_SAM3_API_BASE_URL;
|
|
46
|
+
const imageApiBaseUrl = highestPrecedence(cli.imageBaseUrl, env.IMAGE_API_BASE_URL, file.imageBaseUrl) ?? enhancementApiBaseUrl;
|
|
47
|
+
const apiKey = highestPrecedence(cli.apiKey, env.API_KEY);
|
|
48
|
+
if (!apiKey) {
|
|
49
|
+
throw new ConfigError('API key is required: pass --api-key or set the API_KEY environment variable');
|
|
50
|
+
}
|
|
51
|
+
// SAM3_POLL_INTERVAL_MS is the canonical name; SAM3_POLL_INTERVAL is kept as
|
|
52
|
+
// a deprecated alias. Both are milliseconds (unlike the per-tool
|
|
53
|
+
// poll_interval argument, which is seconds).
|
|
54
|
+
const sam3PollIntervalMs = parseSam3WaitInt(highestPrecedence(cli.sam3PollIntervalMs, env.SAM3_POLL_INTERVAL_MS, env.SAM3_POLL_INTERVAL), 'SAM3_POLL_INTERVAL_MS', SAM3_POLL_INTERVAL_MS_BOUNDS, DEFAULT_SAM3_POLL_INTERVAL_MS);
|
|
55
|
+
const sam3PollMaxAttempts = parseSam3WaitInt(highestPrecedence(cli.sam3PollMaxAttempts, env.SAM3_POLL_MAX_ATTEMPTS), 'SAM3_POLL_MAX_ATTEMPTS', SAM3_POLL_MAX_ATTEMPTS_BOUNDS, DEFAULT_SAM3_POLL_MAX_ATTEMPTS);
|
|
56
|
+
return { enhancementApiBaseUrl, imageApiBaseUrl, sam3ApiBaseUrl, apiKey, sam3PollIntervalMs, sam3PollMaxAttempts };
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=service-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-config.js","sourceRoot":"","sources":["../src/service-config.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA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F,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CAAC;AACrH,CAAC"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
export declare function registerTool(server: McpServer, name: string, description: string, schema: z.ZodRawShape, handler: (args: any) => Promise<unknown>): void;
|
|
4
|
+
export declare const POLL_REQUEST_TIMEOUT_MS = 10000;
|
|
5
|
+
export declare const MAX_CONSECUTIVE_POLL_FAILURES = 3;
|
|
6
|
+
export declare const MAX_UNKNOWN_STATUS_SIGHTINGS = 3;
|
|
7
|
+
export declare function sleep(ms: number): Promise<void>;
|
|
8
|
+
export declare function clampNumber(value: number, min: number, max: number, fallback: number): number;
|
|
9
|
+
export declare function remainingSleepMs(intervalMs: number, deadline: number, now?: number): number;
|
|
10
|
+
export declare function requestBudgetMs(deadline: number, now?: number): number;
|
|
11
|
+
export type StatusKind = 'ok' | 'failed' | 'processing' | 'unknown';
|
|
12
|
+
export declare function classifyStatus(status: unknown): StatusKind;
|
|
13
|
+
export interface PollFetchResult {
|
|
14
|
+
status: unknown;
|
|
15
|
+
payload: Record<string, any>;
|
|
16
|
+
}
|
|
17
|
+
export interface PollParams {
|
|
18
|
+
taskId: string;
|
|
19
|
+
timeoutSeconds: number;
|
|
20
|
+
pollIntervalSeconds: number;
|
|
21
|
+
fetchStatus: (signal: AbortSignal) => Promise<PollFetchResult>;
|
|
22
|
+
continueHint: string;
|
|
23
|
+
/**
|
|
24
|
+
* Independent query-count limit: the first query counts, and the wait is
|
|
25
|
+
* truncated as soon as this many queries have been made while the task is
|
|
26
|
+
* still processing (no trailing sleep). Time and count limits run in
|
|
27
|
+
* parallel; whichever is exhausted first ends the wait.
|
|
28
|
+
*/
|
|
29
|
+
maxAttempts?: number;
|
|
30
|
+
/** Injectable clock and delay for deterministic tests; defaults to real time. */
|
|
31
|
+
now?: () => number;
|
|
32
|
+
delay?: (ms: number) => Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Deadline- and attempt-aware polling: never sleeps past the deadline, aborts
|
|
36
|
+
* each status request at the remaining wait budget, tolerates transient
|
|
37
|
+
* network failures, treats unknown statuses as errors after a few sightings,
|
|
38
|
+
* and always keeps task_id in the response so the task is never lost.
|
|
39
|
+
* A cancellation fired at the budget edge is not counted as a query failure.
|
|
40
|
+
*/
|
|
41
|
+
export declare function pollUntilTerminal(params: PollParams): Promise<Record<string, any>>;
|
|
42
|
+
//# sourceMappingURL=tooling.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tooling.d.ts","sourceRoot":"","sources":["../src/tooling.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAEpE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,wBAAgB,YAAY,CAC1B,MAAM,EAAE,SAAS,EACjB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,CAAC,CAAC,WAAW,EACrB,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,OAAO,CAAC,GACvC,IAAI,CAeN;AAMD,eAAO,MAAM,uBAAuB,QAAQ,CAAC;AAC7C,eAAO,MAAM,6BAA6B,IAAI,CAAC;AAC/C,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE/C;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAG7F;AAED,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,MAAM,CAEvG;AAID,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,MAAM,CAElF;AAMD,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,QAAQ,GAAG,YAAY,GAAG,SAAS,CAAC;AAEpE,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,GAAG,UAAU,CAM1D;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC9B;AAED,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,WAAW,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,eAAe,CAAC,CAAC;IAC/D,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACvC;AAQD;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CA2FxF"}
|
package/dist/tooling.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Tool registration wrapper: business failures surface as MCP isError results
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
export function registerTool(server, name, description, schema, handler) {
|
|
5
|
+
server.tool(name, description, schema, async (args) => {
|
|
6
|
+
try {
|
|
7
|
+
const result = await handler(args);
|
|
8
|
+
const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
|
|
9
|
+
const failed = typeof result === 'object' && result !== null && result.success === false;
|
|
10
|
+
return { content: [{ type: 'text', text }], ...(failed ? { isError: true } : {}) };
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
14
|
+
return {
|
|
15
|
+
content: [{ type: 'text', text: JSON.stringify({ success: false, error: message }, null, 2) }],
|
|
16
|
+
isError: true,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
// Polling primitives
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
export const POLL_REQUEST_TIMEOUT_MS = 10000;
|
|
25
|
+
export const MAX_CONSECUTIVE_POLL_FAILURES = 3;
|
|
26
|
+
export const MAX_UNKNOWN_STATUS_SIGHTINGS = 3;
|
|
27
|
+
export function sleep(ms) {
|
|
28
|
+
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
|
29
|
+
}
|
|
30
|
+
export function clampNumber(value, min, max, fallback) {
|
|
31
|
+
if (!Number.isFinite(value))
|
|
32
|
+
return fallback;
|
|
33
|
+
return Math.min(max, Math.max(min, value));
|
|
34
|
+
}
|
|
35
|
+
export function remainingSleepMs(intervalMs, deadline, now = Date.now()) {
|
|
36
|
+
return Math.max(0, Math.min(intervalMs, deadline - now));
|
|
37
|
+
}
|
|
38
|
+
// A single status request never outlives the remaining wait budget (and never
|
|
39
|
+
// runs with timeout 0, which axios treats as "no timeout").
|
|
40
|
+
export function requestBudgetMs(deadline, now = Date.now()) {
|
|
41
|
+
return Math.max(250, Math.min(POLL_REQUEST_TIMEOUT_MS, deadline - now));
|
|
42
|
+
}
|
|
43
|
+
const TERMINAL_OK_STATUSES = new Set(['completed', 'succeeded', 'success']);
|
|
44
|
+
const TERMINAL_FAIL_STATUSES = new Set(['failed', 'canceled', 'cancelled', 'expired', 'rejected']);
|
|
45
|
+
const TRANSIENT_STATUSES = new Set(['processing', 'pending', 'running', 'queued']);
|
|
46
|
+
export function classifyStatus(status) {
|
|
47
|
+
const normalized = typeof status === 'string' ? status.toLowerCase() : '';
|
|
48
|
+
if (TERMINAL_OK_STATUSES.has(normalized))
|
|
49
|
+
return 'ok';
|
|
50
|
+
if (TERMINAL_FAIL_STATUSES.has(normalized))
|
|
51
|
+
return 'failed';
|
|
52
|
+
if (TRANSIENT_STATUSES.has(normalized))
|
|
53
|
+
return 'processing';
|
|
54
|
+
return 'unknown';
|
|
55
|
+
}
|
|
56
|
+
function formatElapsedSeconds(ms) {
|
|
57
|
+
const seconds = ms / 1000;
|
|
58
|
+
if (seconds >= 10)
|
|
59
|
+
return `${Math.round(seconds)} seconds`;
|
|
60
|
+
return `${(Math.round(seconds * 10) / 10).toFixed(1)} seconds`;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Deadline- and attempt-aware polling: never sleeps past the deadline, aborts
|
|
64
|
+
* each status request at the remaining wait budget, tolerates transient
|
|
65
|
+
* network failures, treats unknown statuses as errors after a few sightings,
|
|
66
|
+
* and always keeps task_id in the response so the task is never lost.
|
|
67
|
+
* A cancellation fired at the budget edge is not counted as a query failure.
|
|
68
|
+
*/
|
|
69
|
+
export async function pollUntilTerminal(params) {
|
|
70
|
+
const now = params.now ?? Date.now;
|
|
71
|
+
const delay = params.delay ?? sleep;
|
|
72
|
+
// Budget bounds are the caller's contract (tool schemas validate before task
|
|
73
|
+
// submission); a non-finite or sub-second budget falls back to the historical
|
|
74
|
+
// 45 s default rather than being silently rewritten to some other cap.
|
|
75
|
+
const timeoutSeconds = Number.isFinite(params.timeoutSeconds) && params.timeoutSeconds >= 1 ? params.timeoutSeconds : 45;
|
|
76
|
+
const intervalMs = Number.isFinite(params.pollIntervalSeconds) && params.pollIntervalSeconds >= 0.5
|
|
77
|
+
? params.pollIntervalSeconds * 1000
|
|
78
|
+
: 5000;
|
|
79
|
+
const maxAttempts = params.maxAttempts === undefined ? Number.POSITIVE_INFINITY : Math.floor(params.maxAttempts);
|
|
80
|
+
const startedAt = now();
|
|
81
|
+
const deadline = startedAt + timeoutSeconds * 1000;
|
|
82
|
+
let consecutiveFailures = 0;
|
|
83
|
+
let unknownSightings = 0;
|
|
84
|
+
let attempts = 0;
|
|
85
|
+
while (attempts < maxAttempts && now() < deadline) {
|
|
86
|
+
attempts++;
|
|
87
|
+
const requestBudget = requestBudgetMs(deadline, now());
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const abortTimer = setTimeout(() => controller.abort(), requestBudget);
|
|
90
|
+
const budgetExceeded = new Promise((_, reject) => {
|
|
91
|
+
controller.signal.addEventListener('abort', () => reject(new Error(`Status request aborted at the wait budget edge (capped at ${requestBudget} ms)`)), { once: true });
|
|
92
|
+
});
|
|
93
|
+
let fetched;
|
|
94
|
+
try {
|
|
95
|
+
fetched = await Promise.race([params.fetchStatus(controller.signal), budgetExceeded]);
|
|
96
|
+
consecutiveFailures = 0;
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (now() >= deadline) {
|
|
100
|
+
// The request was cancelled by the wait budget, not by a query error.
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
consecutiveFailures++;
|
|
104
|
+
if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
|
|
105
|
+
return {
|
|
106
|
+
success: false,
|
|
107
|
+
task_id: params.taskId,
|
|
108
|
+
status: 'unknown',
|
|
109
|
+
error: `Status polling failed ${consecutiveFailures} times in a row: ${error instanceof Error ? error.message : String(error)}`,
|
|
110
|
+
note: `The task has been created and may still be running. Use ${params.continueHint} with this task_id to follow up.`,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
await delay(remainingSleepMs(intervalMs, deadline, now()));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
clearTimeout(abortTimer);
|
|
118
|
+
}
|
|
119
|
+
const kind = classifyStatus(fetched.status);
|
|
120
|
+
if (kind === 'ok') {
|
|
121
|
+
return { success: true, task_id: params.taskId, status: fetched.status, ...fetched.payload };
|
|
122
|
+
}
|
|
123
|
+
if (kind === 'failed') {
|
|
124
|
+
return { success: false, task_id: params.taskId, status: fetched.status, ...fetched.payload };
|
|
125
|
+
}
|
|
126
|
+
if (kind === 'unknown') {
|
|
127
|
+
unknownSightings++;
|
|
128
|
+
if (unknownSightings >= MAX_UNKNOWN_STATUS_SIGHTINGS) {
|
|
129
|
+
return {
|
|
130
|
+
success: false,
|
|
131
|
+
task_id: params.taskId,
|
|
132
|
+
status: fetched.status ?? 'unknown',
|
|
133
|
+
error: `Unrecognized task status: ${JSON.stringify(fetched.status)}`,
|
|
134
|
+
note: `The backend reported an unknown status. Use ${params.continueHint} with this task_id to follow up manually.`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Still processing: stop before exceeding either limit; no trailing sleep.
|
|
139
|
+
if (attempts >= maxAttempts || now() >= deadline) {
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
await delay(remainingSleepMs(intervalMs, deadline, now()));
|
|
143
|
+
}
|
|
144
|
+
const queryText = attempts === 1 ? '1 status query' : `${attempts} status queries`;
|
|
145
|
+
return {
|
|
146
|
+
success: true,
|
|
147
|
+
status: 'processing',
|
|
148
|
+
task_id: params.taskId,
|
|
149
|
+
message: `Task is still processing (waited ${formatElapsedSeconds(now() - startedAt)}, ${queryText}). Please use ${params.continueHint} to continue polling.`,
|
|
150
|
+
note: 'The synchronous wait for this long-running task has been truncated. Switch to task status polling.',
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
//# sourceMappingURL=tooling.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tooling.js","sourceRoot":"","sources":["../src/tooling.ts"],"names":[],"mappings":"AAIA,8EAA8E;AAC9E,8EAA8E;AAC9E,8EAA8E;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KAC3G,CAAC;AACJ,CAAC"}
|
package/dist/tos.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AxiosResponse } from 'axios';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
export declare const MAX_FILE_SIZE_BYTES: number;
|
|
4
|
+
export declare const TOS_UPLOAD_TIMEOUT_MS = 120000;
|
|
5
|
+
export declare const DOWNLOAD_TIMEOUT_MS = 15000;
|
|
6
|
+
export type MediaKind = 'image' | 'video';
|
|
7
|
+
export declare function checkLocalFile(filePath: string, kind: MediaKind): {
|
|
8
|
+
filePath: string;
|
|
9
|
+
fileName: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function decodeBase64Image(input: string): {
|
|
12
|
+
buffer: Buffer;
|
|
13
|
+
fileName: string;
|
|
14
|
+
};
|
|
15
|
+
export declare function isPrivateIp(ip: string): boolean;
|
|
16
|
+
export declare function assertPublicHttpUrl(rawUrl: string): Promise<URL>;
|
|
17
|
+
export declare function downloadToBuffer(rawUrl: string): Promise<Buffer>;
|
|
18
|
+
export type UnwrapResult = {
|
|
19
|
+
ok: true;
|
|
20
|
+
data: any;
|
|
21
|
+
} | {
|
|
22
|
+
ok: false;
|
|
23
|
+
error: string;
|
|
24
|
+
};
|
|
25
|
+
export declare function unwrapEnvelope(response: Pick<AxiosResponse, 'data' | 'status'>, successCodes?: Set<number>): UnwrapResult;
|
|
26
|
+
export declare function formatRequestError(error: any, rawUrl?: string): string;
|
|
27
|
+
export interface TosUploadTarget {
|
|
28
|
+
url: string;
|
|
29
|
+
fileId: string;
|
|
30
|
+
objectKey: string;
|
|
31
|
+
fields: Record<string, string>;
|
|
32
|
+
}
|
|
33
|
+
export declare function parseTosSignature(signatureData: any): TosUploadTarget;
|
|
34
|
+
export declare function uploadToTos(target: TosUploadTarget, data: fs.ReadStream | Buffer, fileName: string): Promise<void>;
|
|
35
|
+
//# sourceMappingURL=tos.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version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C,EAAE,MAAM,GAAG,MAAM,CAatE;AAMD,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AA2BD,wBAAgB,iBAAiB,CAAC,aAAa,EAAE,GAAG,GAAG,eAAe,CA6CrE;AAED,wBAAsB,WAAW,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxH"}
|
package/dist/tos.js
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import * as dns from 'dns/promises';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as net from 'net';
|
|
5
|
+
import * as path from 'path';
|
|
6
|
+
import FormData from 'form-data';
|
|
7
|
+
export const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;
|
|
8
|
+
export const TOS_UPLOAD_TIMEOUT_MS = 120000;
|
|
9
|
+
export const DOWNLOAD_TIMEOUT_MS = 15000;
|
|
10
|
+
const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.bmp', '.webp']);
|
|
11
|
+
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v', '.avi', '.mkv', '.webm']);
|
|
12
|
+
const MAGIC_SIGNATURES = [
|
|
13
|
+
{ extensions: ['.png'], matches: (h) => h.length >= 4 && h[0] === 0x89 && h[1] === 0x50 && h[2] === 0x4e && h[3] === 0x47 },
|
|
14
|
+
{ extensions: ['.jpg', '.jpeg'], matches: (h) => h.length >= 3 && h[0] === 0xff && h[1] === 0xd8 && h[2] === 0xff },
|
|
15
|
+
{ extensions: ['.bmp'], matches: (h) => h.length >= 2 && h[0] === 0x42 && h[1] === 0x4d },
|
|
16
|
+
{ extensions: ['.webp'], matches: (h) => h.length >= 12 && h.toString('ascii', 0, 4) === 'RIFF' && h.toString('ascii', 8, 12) === 'WEBP' },
|
|
17
|
+
{ extensions: ['.mp4', '.mov', '.m4v'], matches: (h) => h.length >= 8 && h.toString('ascii', 4, 8) === 'ftyp' },
|
|
18
|
+
{ extensions: ['.avi'], matches: (h) => h.length >= 12 && h.toString('ascii', 0, 4) === 'RIFF' && h.toString('ascii', 8, 12) === 'AVI ' },
|
|
19
|
+
{ extensions: ['.mkv', '.webm'], matches: (h) => h.length >= 4 && h[0] === 0x1a && h[1] === 0x45 && h[2] === 0xdf && h[3] === 0xa3 },
|
|
20
|
+
];
|
|
21
|
+
function readFileHeader(filePath, length) {
|
|
22
|
+
const fd = fs.openSync(filePath, 'r');
|
|
23
|
+
try {
|
|
24
|
+
const header = Buffer.alloc(length);
|
|
25
|
+
const bytesRead = fs.readSync(fd, header, 0, length, 0);
|
|
26
|
+
return header.subarray(0, bytesRead);
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
fs.closeSync(fd);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function checkLocalFile(filePath, kind) {
|
|
33
|
+
if (!fs.existsSync(filePath)) {
|
|
34
|
+
throw new Error(`File does not exist: ${filePath}`);
|
|
35
|
+
}
|
|
36
|
+
const stats = fs.statSync(filePath);
|
|
37
|
+
if (!stats.isFile()) {
|
|
38
|
+
throw new Error(`Not a regular file: ${filePath}`);
|
|
39
|
+
}
|
|
40
|
+
if (stats.size > MAX_FILE_SIZE_BYTES) {
|
|
41
|
+
throw new Error('File size exceeds 100MB limit');
|
|
42
|
+
}
|
|
43
|
+
const extension = path.extname(filePath).toLowerCase();
|
|
44
|
+
const allowed = kind === 'image' ? IMAGE_EXTENSIONS : VIDEO_EXTENSIONS;
|
|
45
|
+
if (!allowed.has(extension)) {
|
|
46
|
+
throw new Error(`Unsupported ${kind} file extension "${extension}"; allowed: ${[...allowed].join(', ')}`);
|
|
47
|
+
}
|
|
48
|
+
const signature = MAGIC_SIGNATURES.find((entry) => entry.extensions.includes(extension));
|
|
49
|
+
if (signature && !signature.matches(readFileHeader(filePath, 12))) {
|
|
50
|
+
throw new Error(`File content does not match its "${extension}" extension (magic number check failed): ${filePath}`);
|
|
51
|
+
}
|
|
52
|
+
return { filePath, fileName: path.basename(filePath) };
|
|
53
|
+
}
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
// Base64 image input
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
const MIME_EXTENSION = {
|
|
58
|
+
'image/png': 'png',
|
|
59
|
+
'image/jpeg': 'jpg',
|
|
60
|
+
'image/bmp': 'bmp',
|
|
61
|
+
'image/webp': 'webp',
|
|
62
|
+
};
|
|
63
|
+
const DATA_URL_PATTERN = /^data:([^;,]+);base64,(.*)$/s;
|
|
64
|
+
export function decodeBase64Image(input) {
|
|
65
|
+
const trimmed = input.trim();
|
|
66
|
+
const match = DATA_URL_PATTERN.exec(trimmed);
|
|
67
|
+
const extension = match ? MIME_EXTENSION[match[1].toLowerCase()] ?? 'png' : 'png';
|
|
68
|
+
const base64 = match ? match[2] : trimmed;
|
|
69
|
+
const buffer = Buffer.from(base64, 'base64');
|
|
70
|
+
if (buffer.length === 0) {
|
|
71
|
+
throw new Error('imageBase64 decoded to empty content');
|
|
72
|
+
}
|
|
73
|
+
if (buffer.length > MAX_FILE_SIZE_BYTES) {
|
|
74
|
+
throw new Error('Image size exceeds 100MB limit');
|
|
75
|
+
}
|
|
76
|
+
return { buffer, fileName: `image.${extension}` };
|
|
77
|
+
}
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
// SSRF guard for remote fetches
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
export function isPrivateIp(ip) {
|
|
82
|
+
if (net.isIPv4(ip)) {
|
|
83
|
+
const [a, b] = ip.split('.').map(Number);
|
|
84
|
+
return (a === 0 ||
|
|
85
|
+
a === 10 ||
|
|
86
|
+
a === 127 ||
|
|
87
|
+
(a === 100 && b >= 64 && b <= 127) || // CGNAT 100.64.0.0/10 (cloud metadata, e.g. 100.100.100.200)
|
|
88
|
+
(a === 172 && b >= 16 && b <= 31) ||
|
|
89
|
+
(a === 192 && b === 168) ||
|
|
90
|
+
(a === 169 && b === 254) ||
|
|
91
|
+
(a === 198 && (b === 18 || b === 19)) || // benchmarking 198.18.0.0/15
|
|
92
|
+
a >= 224);
|
|
93
|
+
}
|
|
94
|
+
if (net.isIPv6(ip)) {
|
|
95
|
+
const lower = ip.toLowerCase();
|
|
96
|
+
if (lower === '::1' || lower === '::')
|
|
97
|
+
return true;
|
|
98
|
+
if (lower.startsWith('fe80') || lower.startsWith('fc') || lower.startsWith('fd'))
|
|
99
|
+
return true;
|
|
100
|
+
if (lower.startsWith('::ffff:'))
|
|
101
|
+
return isPrivateIp(lower.slice(7));
|
|
102
|
+
}
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
export async function assertPublicHttpUrl(rawUrl) {
|
|
106
|
+
let url;
|
|
107
|
+
try {
|
|
108
|
+
url = new URL(rawUrl);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
throw new Error(`Invalid URL: ${rawUrl}`);
|
|
112
|
+
}
|
|
113
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
114
|
+
throw new Error(`Only http(s) URLs are allowed: ${rawUrl}`);
|
|
115
|
+
}
|
|
116
|
+
const hostname = url.hostname;
|
|
117
|
+
if (net.isIP(hostname)) {
|
|
118
|
+
if (isPrivateIp(hostname)) {
|
|
119
|
+
throw new Error(`Refusing to fetch from a private or reserved address: ${hostname}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
const { address } = await dns.lookup(hostname);
|
|
124
|
+
if (isPrivateIp(address)) {
|
|
125
|
+
throw new Error(`Refusing to fetch ${hostname}: resolves to private or reserved address ${address}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return url;
|
|
129
|
+
}
|
|
130
|
+
export async function downloadToBuffer(rawUrl) {
|
|
131
|
+
await assertPublicHttpUrl(rawUrl);
|
|
132
|
+
const response = await axios.get(rawUrl, {
|
|
133
|
+
responseType: 'arraybuffer',
|
|
134
|
+
timeout: DOWNLOAD_TIMEOUT_MS,
|
|
135
|
+
maxContentLength: MAX_FILE_SIZE_BYTES,
|
|
136
|
+
maxRedirects: 3,
|
|
137
|
+
beforeRedirect: (options) => {
|
|
138
|
+
const host = String(options.hostname ?? options.host ?? '');
|
|
139
|
+
if (net.isIP(host) && isPrivateIp(host)) {
|
|
140
|
+
throw new Error(`Refusing redirect to a private or reserved address: ${host}`);
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
const buffer = Buffer.from(response.data);
|
|
145
|
+
if (buffer.length > MAX_FILE_SIZE_BYTES) {
|
|
146
|
+
throw new Error('Downloaded content exceeds 100MB limit');
|
|
147
|
+
}
|
|
148
|
+
return buffer;
|
|
149
|
+
}
|
|
150
|
+
const DEFAULT_SUCCESS_CODES = new Set([0, 200]);
|
|
151
|
+
export function unwrapEnvelope(response, successCodes = DEFAULT_SUCCESS_CODES) {
|
|
152
|
+
const body = response.data;
|
|
153
|
+
if (body && typeof body === 'object' && !Array.isArray(body) && !Buffer.isBuffer(body)) {
|
|
154
|
+
const code = body.code;
|
|
155
|
+
if (successCodes.has(code)) {
|
|
156
|
+
return { ok: true, data: body.data };
|
|
157
|
+
}
|
|
158
|
+
const message = body.message ?? body.error;
|
|
159
|
+
if (message !== undefined && message !== null && message !== '') {
|
|
160
|
+
return { ok: false, error: String(message) };
|
|
161
|
+
}
|
|
162
|
+
return { ok: false, error: `API returned code=${code === undefined ? 'missing' : code} (HTTP ${response.status})` };
|
|
163
|
+
}
|
|
164
|
+
const preview = String(body).slice(0, 200).replace(/\s+/g, ' ');
|
|
165
|
+
return { ok: false, error: `Non-JSON response (HTTP ${response.status}): ${preview}` };
|
|
166
|
+
}
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
// Error formatting (never leaks presigned URL query strings / credentials)
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
function safeUrlLocation(rawUrl) {
|
|
171
|
+
if (!rawUrl)
|
|
172
|
+
return '';
|
|
173
|
+
try {
|
|
174
|
+
const url = new URL(rawUrl);
|
|
175
|
+
return ` url=${url.host}${url.pathname}`;
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return '';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
export function formatRequestError(error, rawUrl) {
|
|
182
|
+
const location = safeUrlLocation(rawUrl);
|
|
183
|
+
if (error?.response) {
|
|
184
|
+
const data = error.response.data;
|
|
185
|
+
let bodyPreview = '';
|
|
186
|
+
if (typeof data === 'string') {
|
|
187
|
+
bodyPreview = ` data=${data.slice(0, 200).replace(/\s+/g, ' ')}`;
|
|
188
|
+
}
|
|
189
|
+
else if (data) {
|
|
190
|
+
bodyPreview = ` data=${JSON.stringify(data).slice(0, 200)}`;
|
|
191
|
+
}
|
|
192
|
+
return `status=${error.response.status} statusText=${error.response.statusText}${bodyPreview}${location}`;
|
|
193
|
+
}
|
|
194
|
+
return `${error?.message ?? String(error)}${location}`;
|
|
195
|
+
}
|
|
196
|
+
// Whitelist: only these signature fields are ever forwarded as TOS form fields.
|
|
197
|
+
const TOS_FIELD_MAPPING = {
|
|
198
|
+
algorithm: 'x-tos-algorithm',
|
|
199
|
+
credential: 'x-tos-credential',
|
|
200
|
+
date: 'x-tos-date',
|
|
201
|
+
signature: 'x-tos-signature',
|
|
202
|
+
};
|
|
203
|
+
function decodePolicyJson(policyValue) {
|
|
204
|
+
let text = policyValue.trim();
|
|
205
|
+
if (!text.startsWith('{')) {
|
|
206
|
+
try {
|
|
207
|
+
text = Buffer.from(text, 'base64').toString('utf-8');
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (!text.startsWith('{'))
|
|
214
|
+
return undefined;
|
|
215
|
+
try {
|
|
216
|
+
return JSON.parse(text);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
export function parseTosSignature(signatureData) {
|
|
223
|
+
if (!signatureData || typeof signatureData !== 'object') {
|
|
224
|
+
throw new Error('Invalid TOS signature response');
|
|
225
|
+
}
|
|
226
|
+
const url = signatureData.url;
|
|
227
|
+
if (typeof url !== 'string' || !url) {
|
|
228
|
+
throw new Error('Missing upload URL in TOS signature response');
|
|
229
|
+
}
|
|
230
|
+
const pathname = new URL(url).pathname;
|
|
231
|
+
const segments = pathname.split('/');
|
|
232
|
+
const fileId = decodeURIComponent(segments[segments.length - 1] || '');
|
|
233
|
+
if (!fileId) {
|
|
234
|
+
throw new Error('Could not extract file_id from upload URL');
|
|
235
|
+
}
|
|
236
|
+
const fields = {};
|
|
237
|
+
for (const [sourceKey, formKey] of Object.entries(TOS_FIELD_MAPPING)) {
|
|
238
|
+
const value = signatureData[sourceKey];
|
|
239
|
+
if (value !== undefined && value !== null) {
|
|
240
|
+
fields[formKey] = String(value);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
const policyValue = signatureData.origin_policy ?? signatureData.policy;
|
|
244
|
+
let objectKey = decodeURIComponent(pathname.slice(1));
|
|
245
|
+
if (policyValue !== undefined && policyValue !== null) {
|
|
246
|
+
let policyText = String(policyValue);
|
|
247
|
+
// Different volcengine-tos SDK versions return the policy as plain JSON or
|
|
248
|
+
// Base64; TOS expects Base64, so normalize here.
|
|
249
|
+
if (policyText.trim().startsWith('{')) {
|
|
250
|
+
policyText = Buffer.from(policyText, 'utf-8').toString('base64');
|
|
251
|
+
}
|
|
252
|
+
fields['policy'] = policyText;
|
|
253
|
+
// Prefer the key declared in the policy conditions when available.
|
|
254
|
+
const policyJson = decodePolicyJson(String(policyValue));
|
|
255
|
+
const keyCondition = policyJson?.conditions?.find((condition) => condition && typeof condition === 'object' && typeof condition.key === 'string');
|
|
256
|
+
if (keyCondition) {
|
|
257
|
+
objectKey = keyCondition.key;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return { url, fileId, objectKey, fields };
|
|
261
|
+
}
|
|
262
|
+
export async function uploadToTos(target, data, fileName) {
|
|
263
|
+
const formData = new FormData();
|
|
264
|
+
formData.append('key', target.objectKey);
|
|
265
|
+
for (const [key, value] of Object.entries(target.fields)) {
|
|
266
|
+
formData.append(key, value);
|
|
267
|
+
}
|
|
268
|
+
formData.append('file', data, fileName);
|
|
269
|
+
try {
|
|
270
|
+
await axios.post(target.url, formData, {
|
|
271
|
+
headers: formData.getHeaders(),
|
|
272
|
+
maxBodyLength: Infinity,
|
|
273
|
+
maxContentLength: Infinity,
|
|
274
|
+
timeout: TOS_UPLOAD_TIMEOUT_MS,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
throw new Error(`TOS upload failed: ${formatRequestError(error, target.url)}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
//# sourceMappingURL=tos.js.map
|
package/dist/tos.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tos.js","sourceRoot":"","sources":["../src/tos.ts"],"names":[],"mappings":"AAAA,OAAO,KAAwB,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,QAAQ,MAAM,WAAW,CAAC;AAEjC,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AACrD,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC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