@zenaigc/zenmcp 0.0.0-stage → 0.1.1
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/INSTALL.md +77 -0
- package/README.md +53 -2
- package/dist/src/acquire/download.js +152 -0
- package/dist/src/acquire/errors.js +8 -0
- package/dist/src/acquire/share.js +67 -0
- package/dist/src/acquire/social.js +98 -0
- package/dist/src/acquire/trim.js +95 -0
- package/dist/src/assets/files.js +29 -0
- package/dist/src/assets/generator.js +141 -0
- package/dist/src/assets/images.js +90 -0
- package/dist/src/assets/index.js +3 -0
- package/dist/src/assets/model-library.js +87 -0
- package/dist/src/assets/upload-cache.js +36 -0
- package/dist/src/contract/cloud-v1.js +334 -0
- package/dist/src/core/hash.js +18 -0
- package/dist/src/core/index.js +4 -0
- package/dist/src/core/job-store.js +251 -0
- package/dist/src/core/safety.js +43 -0
- package/dist/src/core/schema.js +295 -0
- package/dist/src/doctor.js +22 -0
- package/dist/src/effects/check.js +19 -0
- package/dist/src/effects/font.js +78 -0
- package/dist/src/effects/index.js +188 -0
- package/dist/src/engine/card.js +50 -0
- package/dist/src/engine/direct.js +493 -0
- package/dist/src/engine/generate.js +234 -0
- package/dist/src/engine/index.js +3 -0
- package/dist/src/engine/media.js +24 -0
- package/dist/src/engine/steps.js +444 -0
- package/dist/src/engine/storage.js +90 -0
- package/dist/src/gateway/attempt-store.js +110 -0
- package/dist/src/gateway/budget.js +39 -0
- package/dist/src/gateway/cloud-gateway.js +141 -0
- package/dist/src/gateway/config.js +10 -0
- package/dist/src/gateway/device-auth.js +53 -0
- package/dist/src/gateway/errors.js +105 -0
- package/dist/src/gateway/http.js +124 -0
- package/dist/src/gateway/index.js +8 -0
- package/dist/src/gateway/paid-runner.js +376 -0
- package/dist/src/gateway/types.js +42 -0
- package/dist/src/inspect/index.js +276 -0
- package/dist/src/inspect/media.js +43 -0
- package/dist/src/mcp/server.js +177 -0
- package/dist/src/models/wan3/index.js +173 -0
- package/dist/src/models/wan3/limits.js +25 -0
- package/dist/src/timeline/conform.js +255 -0
- package/dist/src/timeline/cuts.js +225 -0
- package/dist/src/timeline/diff.js +82 -0
- package/dist/src/timeline/errors.js +8 -0
- package/dist/src/timeline/ffmpeg.js +164 -0
- package/dist/src/timeline/index.js +6 -0
- package/dist/src/timeline/params.js +46 -0
- package/dist/src/timeline/probe.js +98 -0
- package/dist/src/timeline/types.js +1 -0
- package/dist/templates/pop-title/README.md +18 -0
- package/dist/templates/pop-title/index.html +102 -0
- package/dist/templates/pop-title/pop-title.js +97 -0
- package/dist/templates/pop-title/render.js +42 -0
- package/dist/templates/pop-title/size-1080/index.html +102 -0
- package/dist/templates/pop-title/variables.example.json +9 -0
- package/dist/templates/pop-title/vendor/FONT.md +10 -0
- package/dist/templates/pop-title/vendor/NotoSansCJKsc-Bold.otf +0 -0
- package/dist/templates/pop-title/vendor/OFL.txt +92 -0
- package/dist/templates/pop-title/vendor/gsap.min.js +11 -0
- package/package.json +35 -4
- package/skills/zenmcp/SKILL.md +27 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { BudgetExceededError } from "./errors.js";
|
|
2
|
+
function isReleased(attempt) {
|
|
3
|
+
return attempt.state === "rejected" || attempt.refund_state === "refunded";
|
|
4
|
+
}
|
|
5
|
+
/** Job budget, derived from durable attempts so it survives restarts. */
|
|
6
|
+
export class LocalBudget {
|
|
7
|
+
approved;
|
|
8
|
+
constructor(approved) {
|
|
9
|
+
this.approved = approved;
|
|
10
|
+
if (!Number.isInteger(approved) || approved < 0) {
|
|
11
|
+
throw new RangeError("approved credits must be a non-negative integer");
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
usage(attempts) {
|
|
15
|
+
const usage = { settled: 0, in_progress: 0 };
|
|
16
|
+
for (const attempt of attempts) {
|
|
17
|
+
if (isReleased(attempt)) {
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const credits = attempt.charged_credits ?? attempt.quote.credits;
|
|
21
|
+
if (attempt.state === "completed" ||
|
|
22
|
+
attempt.state === "mismatch" ||
|
|
23
|
+
attempt.refund_state === "not_refunded") {
|
|
24
|
+
usage.settled += credits;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
usage.in_progress += credits;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return usage;
|
|
31
|
+
}
|
|
32
|
+
assertAllows(attempts, credits) {
|
|
33
|
+
const { settled, in_progress } = this.usage(attempts);
|
|
34
|
+
const committed = settled + in_progress;
|
|
35
|
+
if (committed + credits > this.approved) {
|
|
36
|
+
throw new BudgetExceededError(credits, committed, this.approved);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { socialPostSchema, socialResolveRequestSchema } from "../contract/cloud-v1.js";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { GatewayError } from "./errors.js";
|
|
6
|
+
import { ApiClient, normalizeBaseUrl } from "./http.js";
|
|
7
|
+
import { assetStatusSchema, catalogSchema, generationCreateSchema, generationSchema, meSchema, priceRequestSchema, priceSchema, uploadRequestSchema, uploadTicketSchema, } from "./types.js";
|
|
8
|
+
const MAX_IDEMPOTENCY_KEY_LENGTH = 128;
|
|
9
|
+
const ASSET_POLL_INTERVAL_MS = 2_000;
|
|
10
|
+
const ASSET_POLL_TIMEOUT_MS = 120_000;
|
|
11
|
+
const UPLOAD_TIMEOUT_MS = 300_000;
|
|
12
|
+
/** baseUrl includes the /v1 prefix, e.g. https://host/api/v1. */
|
|
13
|
+
export class CloudGateway {
|
|
14
|
+
deployment;
|
|
15
|
+
api;
|
|
16
|
+
tokens;
|
|
17
|
+
fetchImpl;
|
|
18
|
+
sleep;
|
|
19
|
+
assetPollIntervalMs;
|
|
20
|
+
assetPollTimeoutMs;
|
|
21
|
+
uploadTimeoutMs;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.api = new ApiClient(options);
|
|
24
|
+
this.deployment = normalizeBaseUrl(options.baseUrl);
|
|
25
|
+
this.tokens = options.tokens;
|
|
26
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
27
|
+
this.sleep = options.sleep ?? ((ms) => delay(ms));
|
|
28
|
+
this.assetPollIntervalMs = options.assetPollIntervalMs ?? ASSET_POLL_INTERVAL_MS;
|
|
29
|
+
this.assetPollTimeoutMs = options.assetPollTimeoutMs ?? ASSET_POLL_TIMEOUT_MS;
|
|
30
|
+
this.uploadTimeoutMs = options.uploadTimeoutMs ?? UPLOAD_TIMEOUT_MS;
|
|
31
|
+
}
|
|
32
|
+
get requestTimeoutMs() {
|
|
33
|
+
return this.api.timeoutMs;
|
|
34
|
+
}
|
|
35
|
+
async resolveSocial(shareUrl) {
|
|
36
|
+
return this.api.json(socialPostSchema, "POST", "/social/resolve", {
|
|
37
|
+
token: await this.tokens.token(), body: socialResolveRequestSchema.parse({ share_url: shareUrl }),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async me() {
|
|
41
|
+
return this.api.json(meSchema, "GET", "/me", { token: await this.tokens.token() });
|
|
42
|
+
}
|
|
43
|
+
async catalog(etag) {
|
|
44
|
+
const token = await this.tokens.token();
|
|
45
|
+
const headers = etag === undefined ? {} : { "If-None-Match": etag };
|
|
46
|
+
const res = await this.api.send("GET", "/catalog", { token, headers });
|
|
47
|
+
const returned = res.headers.get("etag");
|
|
48
|
+
if (res.status === 304) {
|
|
49
|
+
return { modified: false, etag: returned ?? etag ?? "" };
|
|
50
|
+
}
|
|
51
|
+
this.api.check(res, token, "/catalog");
|
|
52
|
+
return { modified: true, catalog: this.api.parse(catalogSchema, res, "/catalog", token), etag: returned };
|
|
53
|
+
}
|
|
54
|
+
async price(req) {
|
|
55
|
+
return this.api.json(priceSchema, "POST", "/price", {
|
|
56
|
+
token: await this.tokens.token(),
|
|
57
|
+
body: priceRequestSchema.parse(req),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async upload(file, meta) {
|
|
61
|
+
const bytes = await readFile(file);
|
|
62
|
+
const request = uploadRequestSchema.parse({
|
|
63
|
+
...meta,
|
|
64
|
+
filename: meta.filename ?? basename(file),
|
|
65
|
+
size_bytes: bytes.byteLength,
|
|
66
|
+
});
|
|
67
|
+
const token = await this.tokens.token();
|
|
68
|
+
const ticket = await this.api.json(uploadTicketSchema, "POST", "/assets/uploads", {
|
|
69
|
+
token,
|
|
70
|
+
body: request,
|
|
71
|
+
});
|
|
72
|
+
await this.putObject(ticket.put_url, bytes, request.content_type);
|
|
73
|
+
const path = `/assets/${encodeURIComponent(ticket.asset_id)}`;
|
|
74
|
+
const confirmed = await this.api.json(assetStatusSchema, "POST", `${path}/confirm`, { token });
|
|
75
|
+
return this.awaitAsset(confirmed, path);
|
|
76
|
+
}
|
|
77
|
+
async submit(req, idempotencyKey, accountId) {
|
|
78
|
+
if (idempotencyKey.length < 1 || idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
|
|
79
|
+
throw new RangeError("Idempotency-Key must be 1-128 characters");
|
|
80
|
+
}
|
|
81
|
+
return this.api.json(generationSchema, "POST", "/generations", {
|
|
82
|
+
token: await this.tokens.token(),
|
|
83
|
+
body: generationCreateSchema.parse(req),
|
|
84
|
+
headers: { "Idempotency-Key": idempotencyKey, "X-Zen-Account": accountId },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async get(id) {
|
|
88
|
+
return this.api.json(generationSchema, "GET", `/generations/${encodeURIComponent(id)}`, {
|
|
89
|
+
token: await this.tokens.token(),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
async getAttempt(key, accountId) {
|
|
93
|
+
return this.api.json(generationSchema, "GET", `/attempts/${encodeURIComponent(key)}`, {
|
|
94
|
+
headers: { "X-Zen-Account": accountId },
|
|
95
|
+
token: await this.tokens.token(),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
async cancel(id) {
|
|
99
|
+
return this.api.json(generationSchema, "POST", `/generations/${encodeURIComponent(id)}/cancel`, {
|
|
100
|
+
token: await this.tokens.token(),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** The presigned URL is itself the credential: no Authorization, never logged or echoed. */
|
|
104
|
+
async putObject(putUrl, bytes, contentType) {
|
|
105
|
+
let status;
|
|
106
|
+
try {
|
|
107
|
+
const response = await this.fetchImpl(putUrl, {
|
|
108
|
+
method: "PUT",
|
|
109
|
+
headers: { "Content-Type": contentType },
|
|
110
|
+
body: new Uint8Array(bytes),
|
|
111
|
+
redirect: "error",
|
|
112
|
+
signal: AbortSignal.timeout(this.uploadTimeoutMs),
|
|
113
|
+
});
|
|
114
|
+
await response.body?.cancel();
|
|
115
|
+
status = response.status;
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
throw new GatewayError("asset upload got no complete response", { kind: "transport" });
|
|
119
|
+
}
|
|
120
|
+
if (status < 200 || status >= 300) {
|
|
121
|
+
throw new GatewayError(`asset upload failed with HTTP ${status}`, { kind: "http", status });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async awaitAsset(initial, path) {
|
|
125
|
+
const deadline = Date.now() + this.assetPollTimeoutMs;
|
|
126
|
+
let current = initial;
|
|
127
|
+
while (current.status === "probing") {
|
|
128
|
+
if (Date.now() >= deadline) {
|
|
129
|
+
throw new GatewayError("asset is still probing", { kind: "transport" });
|
|
130
|
+
}
|
|
131
|
+
await this.sleep(this.assetPollIntervalMs);
|
|
132
|
+
current = await this.api.json(assetStatusSchema, "GET", path, {
|
|
133
|
+
token: await this.tokens.token(),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (current.status === "failed") {
|
|
137
|
+
throw new GatewayError("asset processing failed", { kind: "http", code: "asset_failed" });
|
|
138
|
+
}
|
|
139
|
+
return current;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** How long the client keeps one request open before giving up on it. */
|
|
2
|
+
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
3
|
+
/**
|
|
4
|
+
* How long after a send with no verdict the job stays blocked. A client timeout only
|
|
5
|
+
* abandons the socket: a proxy or a busy server can process the POST later, so this must
|
|
6
|
+
* exceed the gateway's request timeout, which PaidRunner enforces. The contract states no
|
|
7
|
+
* upper bound and 10 minutes proves nothing, so expiry moves the attempt to unconfirmed
|
|
8
|
+
* and never releases its budget.
|
|
9
|
+
*/
|
|
10
|
+
export const SETTLE_WAIT_MS = 10 * 60_000;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import { DeviceAuthError, GatewayError } from "./errors.js";
|
|
4
|
+
import { ApiClient } from "./http.js";
|
|
5
|
+
import { deviceBindingSchema, deviceTokenSchema } from "./types.js";
|
|
6
|
+
const SLOW_DOWN_STEP_MS = 5_000;
|
|
7
|
+
/**
|
|
8
|
+
* Device authorization per docs/api/v1.md section 4. The token is returned to the
|
|
9
|
+
* caller only; storing it in a keychain is the caller's job.
|
|
10
|
+
*/
|
|
11
|
+
export async function authorizeDevice(options) {
|
|
12
|
+
const api = new ApiClient(options);
|
|
13
|
+
const sleep = options.sleep ?? ((ms) => delay(ms));
|
|
14
|
+
const codeVerifier = randomBytes(32).toString("base64url");
|
|
15
|
+
const state = randomBytes(16).toString("base64url");
|
|
16
|
+
const binding = await api.json(deviceBindingSchema, "POST", "/device/bindings", {
|
|
17
|
+
body: {
|
|
18
|
+
code_challenge: createHash("sha256").update(codeVerifier).digest("base64url"),
|
|
19
|
+
code_challenge_method: "S256",
|
|
20
|
+
state,
|
|
21
|
+
installation_id: options.installationId,
|
|
22
|
+
client_name: options.clientName,
|
|
23
|
+
client_version: options.clientVersion ?? null,
|
|
24
|
+
scopes: options.scopes,
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
await options.openUrl(binding.verification_url);
|
|
28
|
+
const deadline = Date.now() + binding.expires_in * 1000;
|
|
29
|
+
let intervalMs = binding.interval * 1000;
|
|
30
|
+
while (Date.now() < deadline) {
|
|
31
|
+
await sleep(intervalMs);
|
|
32
|
+
try {
|
|
33
|
+
return await api.json(deviceTokenSchema, "POST", "/device/token", {
|
|
34
|
+
body: { binding_id: binding.binding_id, code_verifier: codeVerifier, state },
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
if (!(err instanceof GatewayError)) {
|
|
39
|
+
throw err;
|
|
40
|
+
}
|
|
41
|
+
if (err.status === 429) {
|
|
42
|
+
intervalMs = Math.max(intervalMs, err.retryAfterMs ?? intervalMs);
|
|
43
|
+
}
|
|
44
|
+
else if (err.code === "slow_down") {
|
|
45
|
+
intervalMs += SLOW_DOWN_STEP_MS;
|
|
46
|
+
}
|
|
47
|
+
else if (err.kind === "http" && err.code !== "authorization_pending") {
|
|
48
|
+
throw new DeviceAuthError(err.code ?? `http_${err.status ?? "unknown"}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
throw new DeviceAuthError("expired_token");
|
|
53
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { errorRules } from "../contract/cloud-v1.js";
|
|
2
|
+
/** Any detail.code outside KNOWN_ERROR_CODES is reported as this; the raw value is dropped. */
|
|
3
|
+
export const UNKNOWN_ERROR_CODE = "unknown_error";
|
|
4
|
+
const KNOWN_ERROR_CODES = new Set(Object.keys(errorRules));
|
|
5
|
+
export function knownErrorCode(code) {
|
|
6
|
+
return KNOWN_ERROR_CODES.has(code) ? code : UNKNOWN_ERROR_CODE;
|
|
7
|
+
}
|
|
8
|
+
const DETAIL_KEYS = ["pricing_version", "price_credits", "required", "interval"];
|
|
9
|
+
/** Strip credentials and URL queries from text that may reach logs or error messages. */
|
|
10
|
+
export function redact(text, secret) {
|
|
11
|
+
const scrubbed = secret ? text.replaceAll(secret, "[redacted]") : text;
|
|
12
|
+
return scrubbed
|
|
13
|
+
.replace(/zk_(?:live|test)_[A-Za-z0-9_-]+/g, "[redacted]")
|
|
14
|
+
.replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
|
|
15
|
+
.replace(/(https?:\/\/[^\s?#"']+)[?#][^\s"']*/gi, "$1?[redacted]");
|
|
16
|
+
}
|
|
17
|
+
/** Replace a secret in every string of a JSON-like value, keys included. */
|
|
18
|
+
export function scrub(value, secret) {
|
|
19
|
+
if (secret === "") {
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
const walk = (item) => {
|
|
23
|
+
if (typeof item === "string") {
|
|
24
|
+
return item.replaceAll(secret, "[redacted]");
|
|
25
|
+
}
|
|
26
|
+
if (Array.isArray(item)) {
|
|
27
|
+
return item.map(walk);
|
|
28
|
+
}
|
|
29
|
+
if (item !== null && typeof item === "object") {
|
|
30
|
+
return Object.fromEntries(Object.entries(item).map(([key, entry]) => [walk(key), walk(entry)]));
|
|
31
|
+
}
|
|
32
|
+
return item;
|
|
33
|
+
};
|
|
34
|
+
return walk(value);
|
|
35
|
+
}
|
|
36
|
+
export function pickDetail(detail, secret) {
|
|
37
|
+
const picked = {};
|
|
38
|
+
for (const key of DETAIL_KEYS) {
|
|
39
|
+
const value = detail[key];
|
|
40
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
41
|
+
picked[key] = typeof value === "string" ? redact(value, secret) : value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return picked;
|
|
45
|
+
}
|
|
46
|
+
/** Every failure from the main site. `message` is built locally and never holds server text. */
|
|
47
|
+
export class GatewayError extends Error {
|
|
48
|
+
kind;
|
|
49
|
+
status;
|
|
50
|
+
code;
|
|
51
|
+
retryAfterMs;
|
|
52
|
+
detail;
|
|
53
|
+
constructor(message, init) {
|
|
54
|
+
super(message);
|
|
55
|
+
this.name = "GatewayError";
|
|
56
|
+
this.kind = init.kind;
|
|
57
|
+
this.status = init.status;
|
|
58
|
+
this.code = init.code;
|
|
59
|
+
this.retryAfterMs = init.retryAfterMs;
|
|
60
|
+
this.detail = init.detail ?? {};
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Shown while a charge can be neither proven nor ruled out. Offers no retry on purpose. */
|
|
64
|
+
export const CHARGE_UNCONFIRMED_NOTICE = "扣费状态待确认";
|
|
65
|
+
export class BudgetExceededError extends Error {
|
|
66
|
+
requested;
|
|
67
|
+
committed;
|
|
68
|
+
approved;
|
|
69
|
+
constructor(requested, committed, approved) {
|
|
70
|
+
super(`budget exceeded: ${committed} committed + ${requested} requested > ${approved} approved`);
|
|
71
|
+
this.requested = requested;
|
|
72
|
+
this.committed = committed;
|
|
73
|
+
this.approved = approved;
|
|
74
|
+
this.name = "BudgetExceededError";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
export class PaidSubmitBlockedError extends Error {
|
|
78
|
+
jobId;
|
|
79
|
+
blockers;
|
|
80
|
+
notice;
|
|
81
|
+
constructor(jobId, blockers,
|
|
82
|
+
/** User-facing text, set when a blocker's charge is unconfirmed. */
|
|
83
|
+
notice) {
|
|
84
|
+
super(`paid submits are blocked for job ${jobId}: ${blockers.join(", ")}`);
|
|
85
|
+
this.jobId = jobId;
|
|
86
|
+
this.blockers = blockers;
|
|
87
|
+
this.notice = notice;
|
|
88
|
+
this.name = "PaidSubmitBlockedError";
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** The message never quotes the request: it holds the credential. */
|
|
92
|
+
export class TokenInRequestError extends Error {
|
|
93
|
+
constructor() {
|
|
94
|
+
super("request contains the current credential and was not sent");
|
|
95
|
+
this.name = "TokenInRequestError";
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
export class DeviceAuthError extends Error {
|
|
99
|
+
code;
|
|
100
|
+
constructor(code) {
|
|
101
|
+
super(`device authorization failed: ${code}`);
|
|
102
|
+
this.code = code;
|
|
103
|
+
this.name = "DeviceAuthError";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { REQUEST_TIMEOUT_MS } from "./config.js";
|
|
3
|
+
import { GatewayError, knownErrorCode, pickDetail, redact, scrub } from "./errors.js";
|
|
4
|
+
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
5
|
+
/** Tokens may only travel over TLS, except to a loopback address. */
|
|
6
|
+
export function normalizeBaseUrl(raw) {
|
|
7
|
+
const url = new URL(raw);
|
|
8
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) {
|
|
9
|
+
throw new Error("baseUrl must be https or loopback http");
|
|
10
|
+
}
|
|
11
|
+
return url.href.replace(/\/+$/, "");
|
|
12
|
+
}
|
|
13
|
+
function parseRetryAfter(value) {
|
|
14
|
+
if (value === null) {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
const seconds = Number(value);
|
|
18
|
+
if (value.trim() !== "" && Number.isFinite(seconds) && seconds >= 0) {
|
|
19
|
+
return seconds * 1000;
|
|
20
|
+
}
|
|
21
|
+
const date = Date.parse(value);
|
|
22
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
23
|
+
}
|
|
24
|
+
function parseJson(text) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(text);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** detail.message is never kept: it is free server text and could reach a log or a file. */
|
|
33
|
+
function errorFrom(res, token) {
|
|
34
|
+
const parsed = parseJson(res.text);
|
|
35
|
+
const detail = parsed !== null && typeof parsed === "object" ? parsed.detail : undefined;
|
|
36
|
+
const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"));
|
|
37
|
+
const base = { status: res.status, ...(retryAfterMs === undefined ? {} : { retryAfterMs }) };
|
|
38
|
+
if (Array.isArray(detail)) {
|
|
39
|
+
// FastAPI request validation: the one documented error without detail.code.
|
|
40
|
+
return new GatewayError("request validation failed", { kind: "http", ...base, code: "validation_error" });
|
|
41
|
+
}
|
|
42
|
+
if (detail !== null && typeof detail === "object") {
|
|
43
|
+
const fields = detail;
|
|
44
|
+
if (typeof fields.code === "string") {
|
|
45
|
+
const code = knownErrorCode(fields.code);
|
|
46
|
+
return new GatewayError(`HTTP ${res.status} ${code}`, {
|
|
47
|
+
kind: "http",
|
|
48
|
+
...base,
|
|
49
|
+
code,
|
|
50
|
+
detail: pickDetail(fields, token),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return new GatewayError(`unexpected HTTP ${res.status}`, { kind: "http", ...base });
|
|
55
|
+
}
|
|
56
|
+
export class ApiClient {
|
|
57
|
+
baseUrl;
|
|
58
|
+
fetchImpl;
|
|
59
|
+
timeoutMs;
|
|
60
|
+
log;
|
|
61
|
+
constructor(options) {
|
|
62
|
+
this.baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
63
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
64
|
+
this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
65
|
+
this.log = options.log;
|
|
66
|
+
}
|
|
67
|
+
/** Raw exchange. Throws a transport error when no complete response arrives. */
|
|
68
|
+
async send(method, path, options = {}) {
|
|
69
|
+
const headers = { Accept: "application/json", ...options.headers };
|
|
70
|
+
if (options.token !== undefined) {
|
|
71
|
+
headers.Authorization = `Bearer ${options.token}`;
|
|
72
|
+
}
|
|
73
|
+
const init = {
|
|
74
|
+
method,
|
|
75
|
+
headers,
|
|
76
|
+
// A redirect would re-send the credential and hide the real outcome of a paid POST.
|
|
77
|
+
redirect: "error",
|
|
78
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
79
|
+
};
|
|
80
|
+
if (options.body !== undefined) {
|
|
81
|
+
headers["Content-Type"] = "application/json";
|
|
82
|
+
init.body = JSON.stringify(options.body);
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const response = await this.fetchImpl(`${this.baseUrl}${path}`, init);
|
|
86
|
+
const text = await response.text();
|
|
87
|
+
this.emit({ event: "http", method, path, status: response.status }, options.token);
|
|
88
|
+
return { status: response.status, headers: response.headers, text };
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// The underlying error can embed the URL, so it is not chained.
|
|
92
|
+
this.emit({ event: "http_transport_error", method, path }, options.token);
|
|
93
|
+
throw new GatewayError(redact(`${method} ${path} got no complete response`, options.token), {
|
|
94
|
+
kind: "transport",
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
check(res, token, path) {
|
|
99
|
+
if (res.status < 200 || res.status >= 300) {
|
|
100
|
+
const err = errorFrom(res, token);
|
|
101
|
+
this.emit({ event: "http_error", path, status: res.status, ...(err.code ? { code: err.code } : {}) }, token);
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
parse(schema, res, path, token) {
|
|
106
|
+
const result = schema.safeParse(parseJson(res.text));
|
|
107
|
+
if (!result.success) {
|
|
108
|
+
this.emit({ event: "http_parse_error", path, status: res.status }, token);
|
|
109
|
+
throw new GatewayError(redact(`response from ${path} failed schema validation`, token), {
|
|
110
|
+
kind: "parse",
|
|
111
|
+
status: res.status,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
return result.data;
|
|
115
|
+
}
|
|
116
|
+
async json(schema, method, path, options = {}) {
|
|
117
|
+
const res = await this.send(method, path, options);
|
|
118
|
+
this.check(res, options.token, path);
|
|
119
|
+
return this.parse(schema, res, path, options.token);
|
|
120
|
+
}
|
|
121
|
+
emit(entry, token) {
|
|
122
|
+
this.log?.(token === undefined ? entry : scrub(entry, token));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { FileAttemptStore, MemoryAttemptStore } from "./attempt-store.js";
|
|
2
|
+
export { LocalBudget } from "./budget.js";
|
|
3
|
+
export { REQUEST_TIMEOUT_MS, SETTLE_WAIT_MS } from "./config.js";
|
|
4
|
+
export { authorizeDevice } from "./device-auth.js";
|
|
5
|
+
export { BudgetExceededError, CHARGE_UNCONFIRMED_NOTICE, DeviceAuthError, GatewayError, PaidSubmitBlockedError, TokenInRequestError, redact, scrub, } from "./errors.js";
|
|
6
|
+
export { CloudGateway } from "./cloud-gateway.js";
|
|
7
|
+
export { PaidRunner, chargeNotice, owns } from "./paid-runner.js";
|
|
8
|
+
export { attemptSchema, attemptStates } from "./types.js";
|