dsh-cliproxyapi-pro 1.8.0 → 1.9.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/CHANGELOG.md +23 -0
- package/README.en.md +38 -409
- package/README.md +38 -409
- package/lib/client.js +131 -28
- package/lib/host/accounts.js +176 -0
- package/lib/host/apply/agent-tool.js +406 -0
- package/lib/host/apply/commands.js +122 -0
- package/lib/host/apply/controller.js +105 -0
- package/lib/host/apply/http-routes.js +273 -0
- package/lib/host/apply/image-jobs.js +171 -0
- package/lib/host/apply/index.js +41 -0
- package/lib/host/apply/interpret.js +72 -0
- package/lib/host/apply/lifecycle.js +34 -0
- package/lib/host/apply/media-failures.js +68 -0
- package/lib/host/apply/media-service.js +202 -0
- package/lib/host/apply/quota-service.js +42 -0
- package/lib/host/apply/references.js +43 -0
- package/lib/host/apply/session-status.js +104 -0
- package/lib/host/apply/state.js +78 -0
- package/lib/host/apply/updates.js +55 -0
- package/lib/host/apply/video-command.js +152 -0
- package/lib/host/apply/video-edit.js +253 -0
- package/lib/host/apply/video-jobs.js +206 -0
- package/lib/host/apply-utils.js +39 -0
- package/lib/host/config.js +205 -0
- package/lib/host/controller.js +435 -0
- package/lib/host/discovery.js +295 -0
- package/lib/host/http-gate.js +144 -0
- package/lib/host/models.js +102 -0
- package/lib/host/mount-guard.js +56 -0
- package/lib/host/routes.js +165 -0
- package/lib/host/runtime.js +445 -0
- package/lib/host/state-store.js +39 -0
- package/lib/host/status-text.js +93 -0
- package/lib/index.js +17 -4330
- package/lib/media/agent-tool.js +255 -0
- package/lib/media/choice.js +83 -0
- package/lib/media/classify.js +65 -0
- package/lib/media/codec/fit.js +76 -0
- package/lib/media/codec/jpeg.js +158 -0
- package/lib/media/codec/png.js +102 -0
- package/lib/media/commands/parsing.js +269 -0
- package/lib/media/constants.js +46 -0
- package/lib/media/diagnose.js +134 -0
- package/lib/media/images.js +165 -0
- package/lib/media/index.js +29 -0
- package/lib/media/interpret.js +126 -0
- package/lib/media/job-store.js +99 -0
- package/lib/media/mp4.js +44 -0
- package/lib/media/output-files.js +59 -0
- package/lib/media/session-store.js +293 -0
- package/lib/media/settings.js +255 -0
- package/lib/media/util.js +45 -0
- package/lib/media/video.js +326 -0
- package/lib/quota/auth-state.js +33 -0
- package/lib/quota/constants.js +86 -0
- package/lib/quota/controller.js +467 -0
- package/lib/quota/helpers.js +325 -0
- package/lib/quota/index.js +19 -0
- package/lib/quota/management.js +216 -0
- package/lib/quota/matching.js +143 -0
- package/lib/quota/parsers.js +352 -0
- package/lib/quota/probes/billing.js +80 -0
- package/lib/quota/probes/google.js +120 -0
- package/lib/quota/probes/oauth.js +27 -0
- package/lib/quota/probes/plugin.js +18 -0
- package/lib/updater/constants.js +23 -0
- package/lib/updater/errors.js +8 -0
- package/lib/updater/index.js +11 -0
- package/lib/updater/registry.js +83 -0
- package/lib/updater/settings.js +45 -0
- package/lib/updater/store.js +23 -0
- package/lib/updater/updater.js +148 -0
- package/lib/updater/verify.js +110 -0
- package/lib/updater/version.js +31 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -9
- package/lib/media.js +0 -2528
- package/lib/quota.js +0 -1646
- package/lib/updater.js +0 -443
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
// Owns account refresh cycles, credential quarantine, generation fencing, and safe snapshots.
|
|
2
|
+
import { QUOTA_TTL_MS, DEFAULT_QUOTA_TIMEOUT_MS, DEFAULT_QUOTA_CONCURRENCY } from "./constants.js";
|
|
3
|
+
import { QuotaError, isObj, text, firstText, flagOf, getPath, normalizeProvider, credentialStatus, extractPlan, entryClaims, shortMessage, parseRecent, sortWindows } from "./helpers.js";
|
|
4
|
+
import { managementKeyRef, managementOrigin, createManagement, createLimiter } from "./management.js";
|
|
5
|
+
import { buildModelIndex } from "./matching.js";
|
|
6
|
+
import { createOAuthProbes } from "./probes/oauth.js";
|
|
7
|
+
import { createGoogleProbes } from "./probes/google.js";
|
|
8
|
+
import { createBillingProbes } from "./probes/billing.js";
|
|
9
|
+
import { createPluginProbe } from "./probes/plugin.js";
|
|
10
|
+
import { AUTH_ERROR_CODES, AUTH_FAILURE_LIMIT, normalizeQuotaAuthState } from "./auth-state.js";
|
|
11
|
+
|
|
12
|
+
//#region Quota Controller
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Owns the quota state of every plugin account: key lookups, management API
|
|
16
|
+
* reads, upstream quota probes, TTL/lockout policy and the public snapshot.
|
|
17
|
+
*/
|
|
18
|
+
export function createQuotaController(deps) {
|
|
19
|
+
const fetchImpl = deps.fetch ?? globalThis.fetch;
|
|
20
|
+
const now = deps.now ?? Date.now;
|
|
21
|
+
const ttlMs = Number.isFinite(deps.ttlMs) && deps.ttlMs >= 0 ? deps.ttlMs : QUOTA_TTL_MS;
|
|
22
|
+
const timeoutMs = Number.isFinite(deps.timeoutMs) && deps.timeoutMs > 0 ? deps.timeoutMs : DEFAULT_QUOTA_TIMEOUT_MS;
|
|
23
|
+
const concurrency = Number.isInteger(deps.concurrency) && deps.concurrency > 0 ? deps.concurrency : DEFAULT_QUOTA_CONCURRENCY;
|
|
24
|
+
const logger = deps.logger;
|
|
25
|
+
const root = new AbortController();
|
|
26
|
+
const pool = createLimiter(concurrency);
|
|
27
|
+
const states = new Map();
|
|
28
|
+
/** management origin → Antigravity endpoint that last returned usable rows. */
|
|
29
|
+
const agPreferred = new Map();
|
|
30
|
+
let disposed = false;
|
|
31
|
+
|
|
32
|
+
// Consecutive management 401/403 counts survive reloads through
|
|
33
|
+
// `deps.authStore` ({ read(), write(state) }); without one they live in memory.
|
|
34
|
+
const readAuth = () => {
|
|
35
|
+
try {
|
|
36
|
+
return normalizeQuotaAuthState(deps.authStore?.read?.());
|
|
37
|
+
} catch {
|
|
38
|
+
return normalizeQuotaAuthState(undefined);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const writeAuthEntry = (id, entry) => {
|
|
42
|
+
if (deps.authStore?.write === undefined) return;
|
|
43
|
+
try {
|
|
44
|
+
const next = readAuth();
|
|
45
|
+
if (entry === undefined) {
|
|
46
|
+
if (next.accounts[id] === undefined) return;
|
|
47
|
+
delete next.accounts[id];
|
|
48
|
+
} else {
|
|
49
|
+
next.accounts[id] = entry;
|
|
50
|
+
}
|
|
51
|
+
deps.authStore.write(normalizeQuotaAuthState(next));
|
|
52
|
+
} catch (error) {
|
|
53
|
+
log("warn", `dsh-cliproxyapi: could not save the quota key failure count: ${error instanceof Error ? error.message : String(error)}`);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const stateFor = (id) => {
|
|
58
|
+
let st = states.get(id);
|
|
59
|
+
if (st === undefined) {
|
|
60
|
+
const saved = readAuth().accounts[id];
|
|
61
|
+
st = {
|
|
62
|
+
gen: 0,
|
|
63
|
+
inflight: null,
|
|
64
|
+
result: saved === undefined ? null : { state: "error", errorCode: saved.errorCode, ...(saved.errorStatus === undefined ? {} : { errorStatus: saved.errorStatus }) },
|
|
65
|
+
data: null,
|
|
66
|
+
// Any non-key cycle failure: no automatic retry until a manual refresh or key save.
|
|
67
|
+
lockedOut: false,
|
|
68
|
+
// Consecutive management-key rejections; AUTH_FAILURE_LIMIT stops automatic refresh.
|
|
69
|
+
authFailures: saved?.authFailures ?? 0,
|
|
70
|
+
pausedCredentials: new Map(),
|
|
71
|
+
lastAttemptAt: undefined,
|
|
72
|
+
};
|
|
73
|
+
states.set(id, st);
|
|
74
|
+
}
|
|
75
|
+
return st;
|
|
76
|
+
};
|
|
77
|
+
const authPaused = (st) => st.authFailures >= AUTH_FAILURE_LIMIT;
|
|
78
|
+
/** Neither a rejected key past the limit nor a failed cycle is retried in the background. */
|
|
79
|
+
const autoPaused = (st) => st.lockedOut || authPaused(st);
|
|
80
|
+
/** Forget an account's failure count (a new key, a cleared key, a removed account). */
|
|
81
|
+
const resetAuth = (id, st = states.get(id)) => {
|
|
82
|
+
if (st !== undefined) st.authFailures = 0;
|
|
83
|
+
writeAuthEntry(id, undefined);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const log = (level, message) => {
|
|
87
|
+
try {
|
|
88
|
+
logger?.[level]?.(message);
|
|
89
|
+
} catch {
|
|
90
|
+
/* logging must never break a refresh */
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const listAccounts = () => {
|
|
95
|
+
try {
|
|
96
|
+
const list = deps.listAccounts();
|
|
97
|
+
return Array.isArray(list) ? list.filter((a) => isObj(a) && text(a.id) !== "") : [];
|
|
98
|
+
} catch {
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const findAccount = (accountId) => {
|
|
104
|
+
const account = listAccounts().find((a) => a.id === accountId);
|
|
105
|
+
if (account === undefined) throw new Error(`dsh-cliproxyapi: unknown account ${JSON.stringify(String(accountId))}`);
|
|
106
|
+
return account;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const keyConfigured = async (ref) => {
|
|
110
|
+
try {
|
|
111
|
+
return (await deps.describeKey(ref))?.configured === true;
|
|
112
|
+
} catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const { management, apiCall, loadModels } = createManagement({ fetchImpl, timeoutMs });
|
|
118
|
+
|
|
119
|
+
// --- Provider quota probes: each returns { windows, plan? } or throws QuotaError ---
|
|
120
|
+
const PROBES = {
|
|
121
|
+
...createOAuthProbes({ apiCall, now }),
|
|
122
|
+
...createGoogleProbes({ apiCall, now, agPreferred }),
|
|
123
|
+
...createBillingProbes({ apiCall, management, now }),
|
|
124
|
+
};
|
|
125
|
+
PROBES.gemini = PROBES["gemini-cli"];
|
|
126
|
+
const pluginProbe = createPluginProbe({ management });
|
|
127
|
+
|
|
128
|
+
async function loadCredential(ctx, entry, previous) {
|
|
129
|
+
const id = firstText(entry.name, entry.id);
|
|
130
|
+
const provider = normalizeProvider(firstText(entry.provider, entry.type)) || "unknown";
|
|
131
|
+
const prefix = text(firstText(entry.prefix, getPath(entry, ["attributes", "prefix"]), getPath(entry, ["metadata", "prefix"]))).replace(/^\/+|\/+$/g, "").toLowerCase();
|
|
132
|
+
const status = credentialStatus(entry);
|
|
133
|
+
const credential = {
|
|
134
|
+
id,
|
|
135
|
+
label: firstText(entry.label, entry.email, entry.account_email, typeof entry.account === "string" ? entry.account : ""),
|
|
136
|
+
provider,
|
|
137
|
+
};
|
|
138
|
+
const plan = extractPlan(entry) || extractPlan(...entryClaims(entry)) || previous?.plan || "";
|
|
139
|
+
credential.status = status;
|
|
140
|
+
const statusMessage = shortMessage(firstText(entry.status_message, entry.statusMessage));
|
|
141
|
+
if (statusMessage !== "") credential.statusMessage = statusMessage;
|
|
142
|
+
if (prefix !== "") credential.prefix = prefix;
|
|
143
|
+
const recent = parseRecent(entry);
|
|
144
|
+
const paused = ctx.pausedCredentials.get(id);
|
|
145
|
+
if (paused !== undefined) {
|
|
146
|
+
// Keep the failure sticky even if CPA temporarily removes/re-adds the file.
|
|
147
|
+
// No model read, token download or upstream probe for this credential.
|
|
148
|
+
return {
|
|
149
|
+
...credential,
|
|
150
|
+
...(plan === "" ? {} : { plan }),
|
|
151
|
+
models: paused.provider === provider && paused.prefix === prefix ? paused.models : null,
|
|
152
|
+
quotaState: "error",
|
|
153
|
+
quotaErrorCode: paused.quotaErrorCode,
|
|
154
|
+
autoRefreshPaused: true,
|
|
155
|
+
windows: [],
|
|
156
|
+
...(recent === undefined ? {} : { recent }),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const authIndex = firstText(entry.auth_index, entry.authIndex);
|
|
161
|
+
// Built-in probes win; any other credential CPA marks `supports_quota`
|
|
162
|
+
// (a CPA quota plugin or a declarative quota_probe) goes through CPA's
|
|
163
|
+
// own normalized route.
|
|
164
|
+
const probe = PROBES[provider] ?? (flagOf(entry.supports_quota ?? entry.supportsQuota) === true ? pluginProbe : undefined);
|
|
165
|
+
const [models, quota] = await Promise.all([
|
|
166
|
+
loadModels(ctx, id, prefix, status),
|
|
167
|
+
(async () => {
|
|
168
|
+
if (probe === undefined) return { quotaState: "unsupported", windows: [] };
|
|
169
|
+
if (authIndex === "") return { quotaState: "error", quotaErrorCode: "missing-auth-index", windows: [] };
|
|
170
|
+
try {
|
|
171
|
+
const result = await probe(ctx, entry, authIndex, plan);
|
|
172
|
+
return { quotaState: "ok", windows: sortWindows(result.windows), plan: result.plan };
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (error?.code === "aborted") throw error;
|
|
175
|
+
return { quotaState: "error", quotaErrorCode: error instanceof QuotaError ? error.code : "invalid-response", windows: [] };
|
|
176
|
+
}
|
|
177
|
+
})(),
|
|
178
|
+
]);
|
|
179
|
+
const finalPlan = quota.plan || plan;
|
|
180
|
+
if (quota.quotaState === "error") {
|
|
181
|
+
ctx.pausedCredentials.set(id, { models, provider, prefix, quotaErrorCode: quota.quotaErrorCode });
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
...credential,
|
|
185
|
+
autoRefreshPaused: quota.quotaState === "error",
|
|
186
|
+
...(finalPlan === "" ? {} : { plan: finalPlan }),
|
|
187
|
+
models,
|
|
188
|
+
quotaState: quota.quotaState,
|
|
189
|
+
...(quota.quotaErrorCode === undefined ? {} : { quotaErrorCode: quota.quotaErrorCode }),
|
|
190
|
+
windows: quota.windows,
|
|
191
|
+
...(recent === undefined ? {} : { recent }),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function runCycle(account, signal, retryPaused) {
|
|
196
|
+
let key;
|
|
197
|
+
try {
|
|
198
|
+
key = await deps.resolveKey(managementKeyRef(account.id));
|
|
199
|
+
} catch {
|
|
200
|
+
key = undefined;
|
|
201
|
+
}
|
|
202
|
+
if (typeof key !== "string" || key.trim() === "") return { kind: "nokey" };
|
|
203
|
+
const origin = managementOrigin(account.endpoint) ?? managementOrigin(account.baseURL);
|
|
204
|
+
if (origin === undefined) throw new QuotaError("no-endpoint");
|
|
205
|
+
// A cycle owns its copy: cancelled/obsolete work must not change lockouts.
|
|
206
|
+
const pausedCredentials = retryPaused ? new Map() : new Map(stateFor(account.id).pausedCredentials);
|
|
207
|
+
const ctx = { origin, key: key.trim(), signal, pausedCredentials };
|
|
208
|
+
const files = await management(ctx, "/v0/management/auth-files");
|
|
209
|
+
const entries = Array.isArray(files) ? files : Array.isArray(files?.files) ? files.files : null;
|
|
210
|
+
if (entries === null) throw new QuotaError("invalid-response");
|
|
211
|
+
const previous = new Map((stateFor(account.id).data?.credentials ?? []).map((c) => [c.id, c]));
|
|
212
|
+
const seen = new Set();
|
|
213
|
+
const unique = entries.filter((e) => {
|
|
214
|
+
if (!isObj(e)) return false;
|
|
215
|
+
const name = firstText(e.name, e.id);
|
|
216
|
+
if (name === "" || seen.has(name)) return false;
|
|
217
|
+
seen.add(name);
|
|
218
|
+
return true;
|
|
219
|
+
});
|
|
220
|
+
const credentials = await Promise.all(unique.map((entry) => pool(() => loadCredential(ctx, entry, previous.get(firstText(entry.name, entry.id))), signal)));
|
|
221
|
+
return { kind: "ok", credentials, pausedCredentials };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function startRefresh(account, retryPaused = false) {
|
|
225
|
+
const st = stateFor(account.id);
|
|
226
|
+
if (st.inflight !== null) {
|
|
227
|
+
const active = st.inflight;
|
|
228
|
+
// A manual recovery must not disappear into a background cycle that
|
|
229
|
+
// skips quarantined credentials. Queue at most one recovery, never overlap.
|
|
230
|
+
if (retryPaused && !active.retryPaused && st.pausedCredentials.size > 0) {
|
|
231
|
+
active.recovery ??= active.promise.then(() => {
|
|
232
|
+
if (disposed || st.gen !== active.gen) return;
|
|
233
|
+
return startRefresh(account, true);
|
|
234
|
+
});
|
|
235
|
+
return active.recovery;
|
|
236
|
+
}
|
|
237
|
+
return active.promise;
|
|
238
|
+
}
|
|
239
|
+
const controller = new AbortController();
|
|
240
|
+
const onRootAbort = () => controller.abort();
|
|
241
|
+
root.signal.addEventListener("abort", onRootAbort, { once: true });
|
|
242
|
+
const gen = ++st.gen;
|
|
243
|
+
const current = () => !disposed && st.gen === gen;
|
|
244
|
+
const promise = (async () => {
|
|
245
|
+
try {
|
|
246
|
+
const result = await runCycle(account, controller.signal, retryPaused);
|
|
247
|
+
if (!current()) return;
|
|
248
|
+
if (result.kind === "nokey") {
|
|
249
|
+
st.result = { state: "nokey" };
|
|
250
|
+
} else {
|
|
251
|
+
const fetchedAt = new Date(now()).toISOString();
|
|
252
|
+
st.data = { credentials: result.credentials, fetchedAt };
|
|
253
|
+
st.pausedCredentials = result.pausedCredentials;
|
|
254
|
+
st.result = { state: "ok" };
|
|
255
|
+
st.lockedOut = false;
|
|
256
|
+
if (st.authFailures > 0) resetAuth(account.id, st);
|
|
257
|
+
}
|
|
258
|
+
} catch (error) {
|
|
259
|
+
if (!current()) return;
|
|
260
|
+
const code = error instanceof QuotaError && error.code !== "aborted" ? error.code : error?.code === "aborted" ? null : "network";
|
|
261
|
+
if (code === null) return;
|
|
262
|
+
st.result = { state: "error", errorCode: code, ...(error?.status === undefined ? {} : { errorStatus: error.status }) };
|
|
263
|
+
if (AUTH_ERROR_CODES.includes(code)) {
|
|
264
|
+
// A rejected management key is retried in the background until
|
|
265
|
+
// AUTH_FAILURE_LIMIT consecutive rejections (persisted across reloads).
|
|
266
|
+
st.authFailures += 1;
|
|
267
|
+
writeAuthEntry(account.id, {
|
|
268
|
+
authFailures: st.authFailures,
|
|
269
|
+
errorCode: code,
|
|
270
|
+
...(error?.status === undefined ? {} : { errorStatus: error.status }),
|
|
271
|
+
failedAt: new Date(now()).toISOString(),
|
|
272
|
+
});
|
|
273
|
+
} else {
|
|
274
|
+
// Repeated quota probes can invalidate upstream sessions: fail closed
|
|
275
|
+
// for every other cycle error.
|
|
276
|
+
st.lockedOut = true;
|
|
277
|
+
}
|
|
278
|
+
log(
|
|
279
|
+
"warn",
|
|
280
|
+
`dsh-cliproxyapi: quota refresh failed for account ${account.id}: ${code}${error?.status === undefined ? "" : ` (${error.status})`}` +
|
|
281
|
+
(AUTH_ERROR_CODES.includes(code)
|
|
282
|
+
? ` — management key rejected ${st.authFailures}/${AUTH_FAILURE_LIMIT}${authPaused(st) ? "; automatic refresh stopped" : ""}`
|
|
283
|
+
: "")
|
|
284
|
+
);
|
|
285
|
+
} finally {
|
|
286
|
+
root.signal.removeEventListener("abort", onRootAbort);
|
|
287
|
+
if (st.gen === gen) {
|
|
288
|
+
st.inflight = null;
|
|
289
|
+
if (!disposed) st.lastAttemptAt = now();
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
})();
|
|
293
|
+
st.inflight = { gen, controller, promise, retryPaused, recovery: null };
|
|
294
|
+
return promise;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function cancelInflight(st) {
|
|
298
|
+
if (st.inflight === null) return;
|
|
299
|
+
st.inflight.controller.abort();
|
|
300
|
+
st.inflight = null;
|
|
301
|
+
st.gen += 1;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function buildSnapshot(prepared) {
|
|
305
|
+
const accounts = prepared ?? (await prepare());
|
|
306
|
+
const out = [];
|
|
307
|
+
for (const { account, keyRef, keyConfigured: configured } of accounts) {
|
|
308
|
+
const st = stateFor(account.id);
|
|
309
|
+
const refreshing = st.inflight !== null;
|
|
310
|
+
let state;
|
|
311
|
+
if (!configured) state = "nokey";
|
|
312
|
+
else if (st.result === null || (st.result.state === "nokey")) state = refreshing ? "loading" : "idle";
|
|
313
|
+
else state = st.result.state;
|
|
314
|
+
const pickerModels = (Array.isArray(account.pickerModels) ? account.pickerModels : [])
|
|
315
|
+
.filter((m) => isObj(m) && text(m.id) !== "")
|
|
316
|
+
.map((m) => ({ id: text(m.id), route: text(m.route), ...(text(m.ownedBy) === "" ? {} : { ownedBy: text(m.ownedBy) }) }));
|
|
317
|
+
const entry = {
|
|
318
|
+
accountId: account.id,
|
|
319
|
+
displayName: text(account.displayName) || account.id,
|
|
320
|
+
provider: text(account.provider),
|
|
321
|
+
routes: Array.isArray(account.routes) ? account.routes.filter((r) => typeof r === "string") : [],
|
|
322
|
+
enabled: account.enabled === true,
|
|
323
|
+
keyRef,
|
|
324
|
+
keyConfigured: configured,
|
|
325
|
+
state,
|
|
326
|
+
...(state === "error" ? { errorCode: st.result.errorCode, ...(st.result.errorStatus === undefined ? {} : { errorStatus: st.result.errorStatus }) } : {}),
|
|
327
|
+
...(configured && st.data !== null ? { fetchedAt: st.data.fetchedAt } : {}),
|
|
328
|
+
refreshing,
|
|
329
|
+
autoRefreshPaused: configured && st.lockedOut,
|
|
330
|
+
...(configured && st.authFailures > 0
|
|
331
|
+
? { authFailures: st.authFailures, authFailureLimit: AUTH_FAILURE_LIMIT, authPaused: authPaused(st) }
|
|
332
|
+
: {}),
|
|
333
|
+
credentials: configured && st.data !== null ? structuredClone(st.data.credentials) : [],
|
|
334
|
+
pickerModels,
|
|
335
|
+
};
|
|
336
|
+
Object.assign(entry, buildModelIndex(entry));
|
|
337
|
+
out.push(entry);
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
generatedAt: new Date(now()).toISOString(),
|
|
341
|
+
refreshing: out.some((a) => a.refreshing),
|
|
342
|
+
accounts: out,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function prepare() {
|
|
347
|
+
const accounts = listAccounts();
|
|
348
|
+
const known = new Set(accounts.map((a) => a.id));
|
|
349
|
+
for (const [id, st] of states) {
|
|
350
|
+
if (!known.has(id)) {
|
|
351
|
+
cancelInflight(st);
|
|
352
|
+
states.delete(id);
|
|
353
|
+
// An empty list may be a failed read; keep the stored count then.
|
|
354
|
+
if (accounts.length > 0) resetAuth(id);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return Promise.all(accounts.map(async (account) => {
|
|
358
|
+
const keyRef = managementKeyRef(account.id);
|
|
359
|
+
return { account, keyRef, keyConfigured: await keyConfigured(keyRef) };
|
|
360
|
+
}));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
async snapshot() {
|
|
365
|
+
const prepared = await prepare();
|
|
366
|
+
if (!disposed) {
|
|
367
|
+
const at = now();
|
|
368
|
+
for (const { account, keyConfigured: configured } of prepared) {
|
|
369
|
+
if (account.enabled !== true || !configured) continue;
|
|
370
|
+
const st = stateFor(account.id);
|
|
371
|
+
if (st.inflight !== null || autoPaused(st)) continue;
|
|
372
|
+
if (st.lastAttemptAt !== undefined && at - st.lastAttemptAt < ttlMs) continue;
|
|
373
|
+
startRefresh(account);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return buildSnapshot(prepared);
|
|
377
|
+
},
|
|
378
|
+
|
|
379
|
+
/** `options.wait === false` starts the refresh and returns at once (snapshot shows `refreshing`). */
|
|
380
|
+
async refresh(accountId, options = {}) {
|
|
381
|
+
const wait = options?.wait !== false;
|
|
382
|
+
if (accountId !== undefined && accountId !== null && accountId !== "") {
|
|
383
|
+
const account = findAccount(accountId);
|
|
384
|
+
if (!disposed) {
|
|
385
|
+
const st = stateFor(account.id);
|
|
386
|
+
if (await keyConfigured(managementKeyRef(account.id))) {
|
|
387
|
+
// A manual refresh tries once even when paused. The key-rejection
|
|
388
|
+
// count is kept, so another rejection past the limit pauses again
|
|
389
|
+
// at once (a success resets it).
|
|
390
|
+
st.lockedOut = false;
|
|
391
|
+
const running = startRefresh(account, true);
|
|
392
|
+
if (wait) await running;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return buildSnapshot();
|
|
396
|
+
}
|
|
397
|
+
const prepared = await prepare();
|
|
398
|
+
if (!disposed) {
|
|
399
|
+
// Refresh-all never retries a paused account; only refresh(id) tries it once, and saveKey resets it.
|
|
400
|
+
await Promise.all(prepared
|
|
401
|
+
.filter(({ account, keyConfigured: configured }) => account.enabled === true && configured && !autoPaused(stateFor(account.id)))
|
|
402
|
+
.map(({ account }) => (wait ? startRefresh(account) : (startRefresh(account), undefined))));
|
|
403
|
+
}
|
|
404
|
+
return buildSnapshot(prepared);
|
|
405
|
+
},
|
|
406
|
+
|
|
407
|
+
async saveKey(accountId, input = {}, options = {}) {
|
|
408
|
+
const wait = options?.wait !== false;
|
|
409
|
+
const account = findAccount(accountId);
|
|
410
|
+
const ref = managementKeyRef(account.id);
|
|
411
|
+
const st = stateFor(account.id);
|
|
412
|
+
if (input?.clear === true) {
|
|
413
|
+
cancelInflight(st);
|
|
414
|
+
await deps.unsetKey(ref);
|
|
415
|
+
st.data = null;
|
|
416
|
+
st.pausedCredentials.clear();
|
|
417
|
+
st.result = null;
|
|
418
|
+
st.lockedOut = false;
|
|
419
|
+
resetAuth(account.id, st);
|
|
420
|
+
st.lastAttemptAt = undefined;
|
|
421
|
+
return buildSnapshot();
|
|
422
|
+
}
|
|
423
|
+
const value = typeof input?.managementKey === "string" ? input.managementKey.trim() : "";
|
|
424
|
+
if (value !== "") {
|
|
425
|
+
if (/\s/.test(value)) throw new Error("dsh-cliproxyapi: management key must not contain whitespace");
|
|
426
|
+
cancelInflight(st);
|
|
427
|
+
await deps.setKey(ref, value);
|
|
428
|
+
st.result = null;
|
|
429
|
+
st.lockedOut = false;
|
|
430
|
+
resetAuth(account.id, st);
|
|
431
|
+
}
|
|
432
|
+
if (!disposed && (await keyConfigured(ref))) {
|
|
433
|
+
st.lockedOut = false;
|
|
434
|
+
const running = startRefresh(account, true);
|
|
435
|
+
if (wait) await running;
|
|
436
|
+
}
|
|
437
|
+
return buildSnapshot();
|
|
438
|
+
},
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* A credential reference changed outside saveKey (e.g. the DSH credentials
|
|
442
|
+
* page): when it is an account's management key, forget its failure count
|
|
443
|
+
* and lift its lockout, as saving the key would.
|
|
444
|
+
* @returns the account id, or undefined for any other reference.
|
|
445
|
+
*/
|
|
446
|
+
keyChanged(ref) {
|
|
447
|
+
const account = listAccounts().find((a) => managementKeyRef(a.id) === ref);
|
|
448
|
+
if (account === undefined) return undefined;
|
|
449
|
+
const st = states.get(account.id);
|
|
450
|
+
if (st !== undefined) st.lockedOut = false;
|
|
451
|
+
resetAuth(account.id);
|
|
452
|
+
return account.id;
|
|
453
|
+
},
|
|
454
|
+
|
|
455
|
+
dispose() {
|
|
456
|
+
if (disposed) return;
|
|
457
|
+
disposed = true;
|
|
458
|
+
root.abort();
|
|
459
|
+
for (const st of states.values()) {
|
|
460
|
+
st.inflight?.controller.abort();
|
|
461
|
+
st.inflight = null;
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
//#endregion
|