dsh-sub2api 0.10.1 → 0.10.3

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 CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.3
4
+
5
+ - **A request can no longer go out with no key.** When the adapter could not
6
+ reach the host's credential service, the transport treated that as "no key"
7
+ and sent the request without an `Authorization` header; the gateway answered
8
+ `401 API key is required in Authorization header`, which reads as a bad key and
9
+ sends you hunting the wrong problem. The key now also comes from the plugin's
10
+ own session record, and when neither source has one the plugin says so in the
11
+ log instead of failing at the far end.
12
+ - The resolver is a named export so this path is testable: a keyless request and
13
+ a request with a wrong key are indistinguishable from the caller.
14
+
15
+ ## 0.10.2
16
+
17
+ - **One retry against the current host when the configured one cannot be
18
+ reached.** A profile that still points at a retired domain would otherwise
19
+ fail every call with a transport error the user cannot act on. The retry only
20
+ happens for an unreachable host, and only when that host is one this plugin
21
+ used to ship: a 401 or 404 is a real answer and is never re-sent elsewhere, and
22
+ a self-hosted gateway keeps its own result.
23
+ - Both request paths are covered: the account API and the `/v1` gateway used for
24
+ models and billing. An explicit base passed by a caller is respected and never
25
+ redirected.
26
+ - `scripts/measure-context.mjs` defaults to the current host; it still pointed at
27
+ the retired one and would have failed on a fresh clone.
28
+
3
29
  ## 0.10.1
4
30
 
5
31
  - **A key without a group is replaced instead of reused.** After the domain move
package/lib/adapter.js CHANGED
@@ -60,6 +60,7 @@ export class Sub2ApiAdapter extends LlmAdapter {
60
60
  * @param {import("./sub2api/catalog.js").ModelCatalog} deps.catalog
61
61
  * @param {() => string} deps.apiBase
62
62
  * @param {() => string} deps.apiKeyEnv credential reference holding the key
63
+ * @param {() => {apiKey: () => Promise<string | undefined>}} [deps.session] fallback key source
63
64
  * @param {() => number} deps.timeoutMs
64
65
  * @param {() => number} deps.idleTimeoutMs
65
66
  * @param {{warn: Function}} [deps.logger]
@@ -110,7 +111,7 @@ export class Sub2ApiAdapter extends LlmAdapter {
110
111
  this.service = new OpenAiLlmService({
111
112
  config,
112
113
  provider: PROVIDER,
113
- credentials: () => optionalService(deps.ctx, "credentials"),
114
+ credentials: () => resolveCredentials(deps),
114
115
  images: () => optionalService(deps.ctx, "attachments"),
115
116
  });
116
117
  return this.service;
@@ -392,6 +393,42 @@ export function selectedEffort(model, id) {
392
393
  }
393
394
 
394
395
  /** Read an optional host service without letting an absent one abort the call. */
396
+ /**
397
+ * The credential resolver handed to the transport.
398
+ *
399
+ * The host's `credentials` service is the right source, but it is not a hard
400
+ * requirement: the same key also lives in this plugin's own session record. The
401
+ * transport treats a missing resolver as "no key" and sends the request without
402
+ * an `Authorization` header, which the gateway answers with a 401 that reads
403
+ * exactly like a bad key — so falling back to the stored record, and saying so
404
+ * when neither source has anything, is what keeps that failure diagnosable.
405
+ *
406
+ * Exported because this path cannot be exercised from the outside: a request
407
+ * with no key and a request with a wrong key look identical to a caller.
408
+ * @param {object} deps adapter dependencies
409
+ * @returns {any} a resolver, or undefined when no key source exists
410
+ */
411
+ export function resolveCredentials(deps) {
412
+ const service = optionalService(deps.ctx, "credentials");
413
+ if (service !== undefined) return service;
414
+
415
+ const stored = deps.session?.();
416
+ if (stored !== undefined) {
417
+ return {
418
+ resolve: async () => {
419
+ const value = await stored.apiKey().catch(() => undefined);
420
+ return typeof value === "string" && value !== "" ? { value } : undefined;
421
+ },
422
+ set: async () => {},
423
+ };
424
+ }
425
+
426
+ deps.logger?.warn?.(
427
+ "[sub2api] 取不到凭据:ctx.get('credentials') 为空且会话里没有密钥,请求会不带密钥发出",
428
+ );
429
+ return undefined;
430
+ }
431
+
395
432
  function optionalService(ctx, name) {
396
433
  try {
397
434
  return ctx?.get?.(name);
package/lib/config.js CHANGED
@@ -66,7 +66,7 @@ export function field(config, key, fallback) {
66
66
  * completely alone.
67
67
  * @type {Record<string, string>}
68
68
  */
69
- const MOVED_HOSTS = {
69
+ export const MOVED_HOSTS = {
70
70
  "sub.pscly.cc": "sub.svpai.net",
71
71
  "pay.pscly.cc": "pay.svpai.net",
72
72
  };
package/lib/index.js CHANGED
@@ -127,6 +127,9 @@ export function apply(ctx, rawConfig = {}) {
127
127
  catalog,
128
128
  apiBase: () => cfg().apiBase,
129
129
  apiKeyEnv: () => cfg().apiKeyEnv,
130
+ // The transport prefers the host's credential service; this is the
131
+ // fallback when that service is not reachable from the adapter.
132
+ session: () => session,
130
133
  timeoutMs: () => cfg().requestTimeoutMs,
131
134
  idleTimeoutMs: () => cfg().streamIdleTimeoutMs,
132
135
  transportRetries: () => cfg().retries,
@@ -13,6 +13,27 @@
13
13
 
14
14
  import { KEY_PAGE_SIZE } from "../constants.js";
15
15
  import { Sub2ApiError, requestJson } from "../util.js";
16
+ import { MOVED_HOSTS } from "../config.js";
17
+
18
+ /**
19
+ * Whether a failure means "never reached the server", as opposed to a considered
20
+ * answer from it.
21
+ *
22
+ * Retrying a 401 or a 404 against another host would mask real problems; a
23
+ * connection that never opened is the only case where a different host can help.
24
+ * @param {unknown} error
25
+ * @returns {boolean}
26
+ */
27
+ function isTransportFailureLike(error) {
28
+ const code = String(error?.code ?? "");
29
+ if (code === "transport" || code === "TRANSPORT" || code === "TIMEOUT") return true;
30
+ const status = Number(error?.status);
31
+ if (Number.isFinite(status) && status > 0) return false;
32
+ const message = String(error?.message ?? "");
33
+ return /fetch failed|could not be reached|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EAI_AGAIN|socket hang up/i.test(
34
+ message,
35
+ );
36
+ }
16
37
 
17
38
  export class Sub2ApiApi {
18
39
  /**
@@ -41,8 +62,8 @@ export class Sub2ApiApi {
41
62
  async #call(path, options = {}) {
42
63
  const headers = {};
43
64
  if (options.token) headers.Authorization = `Bearer ${options.token}`;
44
- try {
45
- const { payload } = await requestJson(this.#url(path), {
65
+ const attempt = (base) =>
66
+ requestJson(`${base}${path}`, {
46
67
  method: options.method ?? "GET",
47
68
  headers,
48
69
  body: options.body,
@@ -50,12 +71,50 @@ export class Sub2ApiApi {
50
71
  signal: options.signal,
51
72
  fetchImpl: this.deps.fetchImpl,
52
73
  });
74
+
75
+ try {
76
+ const { payload } = await attempt(this.#base());
53
77
  return payload;
54
78
  } catch (error) {
79
+ // A moved host is not something the plugin can fix after the fact, but a
80
+ // stale profile pointing at a retired one is common enough to be worth one
81
+ // retry against the current default. Only a transport failure qualifies:
82
+ // a 4xx is a real answer and retrying it elsewhere would be wrong.
83
+ const fallback = this.#relocatedBase();
84
+ if (fallback !== undefined && isTransportFailureLike(error)) {
85
+ const { payload } = await attempt(fallback).catch((retryError) => {
86
+ throw annotate(retryError, path);
87
+ });
88
+ return payload;
89
+ }
55
90
  throw annotate(error, path);
56
91
  }
57
92
  }
58
93
 
94
+ /** The configured base, normalised. */
95
+ #base() {
96
+ return String(this.deps.apiBase()).replace(/\/+$/, "");
97
+ }
98
+
99
+ /**
100
+ * Where to try when the configured base cannot be reached at all.
101
+ *
102
+ * Only offered when the configured host is one this plugin used to ship: a
103
+ * self-hosted gateway keeps its own answer, failure included.
104
+ * @returns {string | undefined}
105
+ */
106
+ #relocatedBase() {
107
+ const current = this.#base();
108
+ let host;
109
+ try {
110
+ host = new URL(current).hostname.toLowerCase();
111
+ } catch {
112
+ return undefined;
113
+ }
114
+ const moved = MOVED_HOSTS[host];
115
+ return moved === undefined ? undefined : `https://${moved}`;
116
+ }
117
+
59
118
  // ---------------------------------------------------------------- auth
60
119
 
61
120
  /**
@@ -215,16 +274,30 @@ export class Sub2ApiApi {
215
274
  }
216
275
 
217
276
  async #gateway(path, apiKey, signal, baseUrl) {
218
- const root = baseUrl === undefined || baseUrl === "" ? this.deps.apiBase() : String(baseUrl).replace(/\/+$/, "");
219
- try {
220
- const { payload } = await requestJson(`${root}${path}`, {
277
+ const explicit =
278
+ baseUrl === undefined || baseUrl === "" ? undefined : String(baseUrl).replace(/\/+$/, "");
279
+ const attempt = (root) =>
280
+ requestJson(`${root}${path}`, {
221
281
  headers: { Authorization: `Bearer ${apiKey}` },
222
282
  timeoutMs: this.deps.timeoutMs(),
223
283
  signal,
224
284
  fetchImpl: this.deps.fetchImpl,
225
285
  });
286
+
287
+ try {
288
+ const { payload } = await attempt(explicit ?? this.#base());
226
289
  return payload;
227
290
  } catch (error) {
291
+ // Same rule as #call: only an unreachable host earns one retry, and only
292
+ // when the route came from configuration rather than a caller's explicit
293
+ // base (an explicit base is the caller's own choice to keep).
294
+ const fallback = explicit === undefined ? this.#relocatedBase() : undefined;
295
+ if (fallback !== undefined && isTransportFailureLike(error)) {
296
+ const { payload } = await attempt(fallback).catch((retryError) => {
297
+ throw annotate(retryError, path);
298
+ });
299
+ return payload;
300
+ }
228
301
  throw annotate(error, path);
229
302
  }
230
303
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
4
4
  "description": "Official Psapi provider for DeepSeek Harness: email sign-in or sign-up, automatic key and model provisioning, one panel for balance and recharge",
5
5
  "type": "module",
6
6
  "license": "GPL-3.0-only",