@huaqiu/dsh-auth 0.6.10 → 0.6.11

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/lib/index.d.mts CHANGED
@@ -226,67 +226,6 @@ declare const AUTH_ROUTE_PREFIX = "/api/v1/huaqiu/auth";
226
226
  type AuthHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;
227
227
  declare function createAuthHandler(service: HuaqiuAuthService): AuthHandler;
228
228
  //#endregion
229
- //#region src/apiKeySync.d.ts
230
- /** Credential reference the `huaqiu` provider resolves per request. */
231
- declare const HUAQIU_API_KEY_REF = "HUAQIU_API_KEY";
232
- /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
233
- declare const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5000;
234
- /** Minimal writable credential store (the DSH `ctx.credentials` seam). */
235
- interface CredentialStore {
236
- set(ref: string, value: string): Promise<void>;
237
- unset(ref: string): Promise<void>;
238
- }
239
- /**
240
- * Resolves the credential store lazily on every sync round.
241
- *
242
- * The DSH `credentials` service may not be activated yet when this plugin
243
- * boots (service activation order), and direct `ctx.credentials` property
244
- * access throws "cannot get property ... without inject" in that window.
245
- * Resolving through `ctx.get('credentials')` per round returns `undefined`
246
- * while the service is unavailable — the round is skipped and retried on the
247
- * next poll, so the sync self-heals once the service activates, without a
248
- * restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
249
- */
250
- type CredentialStoreProvider = () => CredentialStore | null;
251
- /** Logger surface used by the sync (kept small so tests can pass a spy). */
252
- interface SyncLogger {
253
- debug(msg: string, ctx?: Record<string, unknown>): void;
254
- info(msg: string, ctx?: Record<string, unknown>): void;
255
- warn(msg: string, ctx?: Record<string, unknown>): void;
256
- }
257
- declare class HuaqiuApiKeySync {
258
- /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
259
- readonly baseUrl: string;
260
- /** Token path on the host; default "/api/v1/auth/token". */
261
- readonly path: string;
262
- private readonly storeProvider;
263
- private readonly log;
264
- private readonly intervalMs;
265
- private readonly doFetch;
266
- private timer;
267
- /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
268
- private inFlight;
269
- /** Last token mirrored into the credential store (change detection). */
270
- private lastToken;
271
- constructor(
272
- /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
273
- baseUrl: string,
274
- /** Token path on the host; default "/api/v1/auth/token". */
275
- path: string, storeProvider: CredentialStoreProvider, log: SyncLogger, intervalMs?: number, doFetch?: typeof fetch);
276
- /** Host-mode sync is active iff a base URL was configured. */
277
- get enabled(): boolean;
278
- /** Kick off an immediate sync, then poll on a non-overlapping interval. */
279
- start(): void;
280
- /** Stop the poll timer. Safe to call more than once. */
281
- dispose(): void;
282
- /**
283
- * One sync round: fetch the host token endpoint and mirror the verdict into
284
- * the credential store. Exported separately from `start()` so tests can run
285
- * rounds deterministically without timers.
286
- */
287
- syncNow(): Promise<void>;
288
- }
289
- //#endregion
290
229
  //#region src/index.d.ts
291
230
  declare const name = "@huaqiu/dsh-auth";
292
231
  declare const inject: readonly ["webServer"];
@@ -305,4 +244,4 @@ declare module '@deepseek-ai/cordis' {
305
244
  */
306
245
  declare function apply(ctx: Context, config?: Partial<HuaqiuAuthConfig>): void;
307
246
  //#endregion
308
- export { AUTH_ROUTE_PREFIX, type AuthHandler, type CredentialStore, DEFAULT_HUAQIU_API_KEY_SYNC_MS, HUAQIU_API_KEY_REF, HuaqiuApiKeySync, type HuaqiuAuthApi, type HuaqiuAuthConfig, type HuaqiuAuthService, type HuaqiuUserInfo, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
247
+ export { AUTH_ROUTE_PREFIX, type AuthHandler, type HuaqiuAuthApi, type HuaqiuAuthConfig, type HuaqiuAuthService, type HuaqiuUserInfo, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
package/lib/index.mjs CHANGED
@@ -173,125 +173,6 @@ function normalizeHostUser(data) {
173
173
  ...expiresAt !== void 0 ? { expiresAt } : {}
174
174
  };
175
175
  }
176
- //#endregion
177
- //#region src/apiKeySync.ts
178
- /**
179
- * Huaqiu AI gateway credential sync (host mode).
180
- *
181
- * The bundled DSH's `huaqiu` provider resolves its api key through the
182
- * `HUAQIU_API_KEY` credential reference (overlay `apiKeyEnv`). In host mode the
183
- * authoritative credential lives in HQ Edge (mirroring the EDA/KiCad host), and
184
- * Workstream A strips `HUAQIU_API_KEY` from the child environment — so this
185
- * sync is the ONLY source of that credential (task huaqiu-ai-gateway §5.5).
186
- *
187
- * The sync watches the HQ Edge token endpoint directly with a per-call
188
- * loopback GET — deliberately NOT `hqEdge.auth.getAccessToken()`, whose
189
- * initial-null cache has no invalidation path — and mirrors the token into
190
- * `ctx.credentials` under the `HUAQIU_API_KEY` reference:
191
- *
192
- * - authenticated host session → `set` (only when the token value changed);
193
- * - explicit unauthenticated verdict (2xx + `authenticated: false`, or a 2xx
194
- * payload without a usable credential) → `unset`;
195
- * - transient network error / non-2xx host answer → warn and leave the
196
- * current value untouched (a blip must never log the operator out).
197
- *
198
- * The same path serves both the `hq-eda` and `kicad` hosts — host identity is
199
- * HQ Edge configuration, never this plugin's concern.
200
- */
201
- /** Credential reference the `huaqiu` provider resolves per request. */
202
- const HUAQIU_API_KEY_REF = "HUAQIU_API_KEY";
203
- /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
204
- const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5e3;
205
- var HuaqiuApiKeySync = class {
206
- baseUrl;
207
- path;
208
- storeProvider;
209
- log;
210
- intervalMs;
211
- doFetch;
212
- timer = null;
213
- /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
214
- inFlight = false;
215
- /** Last token mirrored into the credential store (change detection). */
216
- lastToken = null;
217
- constructor(baseUrl, path, storeProvider, log, intervalMs = DEFAULT_HUAQIU_API_KEY_SYNC_MS, doFetch = globalThis.fetch.bind(globalThis)) {
218
- this.baseUrl = baseUrl;
219
- this.path = path;
220
- this.storeProvider = storeProvider;
221
- this.log = log;
222
- this.intervalMs = intervalMs;
223
- this.doFetch = doFetch;
224
- }
225
- /** Host-mode sync is active iff a base URL was configured. */
226
- get enabled() {
227
- return this.baseUrl.length > 0;
228
- }
229
- /** Kick off an immediate sync, then poll on a non-overlapping interval. */
230
- start() {
231
- this.syncNow();
232
- this.timer = setInterval(() => {
233
- if (this.inFlight) return;
234
- this.inFlight = true;
235
- this.syncNow().finally(() => {
236
- this.inFlight = false;
237
- });
238
- }, this.intervalMs);
239
- if (typeof this.timer.unref === "function") this.timer.unref();
240
- }
241
- /** Stop the poll timer. Safe to call more than once. */
242
- dispose() {
243
- if (this.timer !== null) clearInterval(this.timer);
244
- this.timer = null;
245
- }
246
- /**
247
- * One sync round: fetch the host token endpoint and mirror the verdict into
248
- * the credential store. Exported separately from `start()` so tests can run
249
- * rounds deterministically without timers.
250
- */
251
- async syncNow() {
252
- const store = this.storeProvider();
253
- if (store === null) {
254
- this.log.debug("huaqiu api-key sync skipped: credentials service unavailable");
255
- return;
256
- }
257
- const url = `${this.baseUrl}${this.path}`;
258
- let res = null;
259
- let info = null;
260
- try {
261
- res = await this.doFetch(url, {
262
- method: "GET",
263
- headers: { accept: "application/json" }
264
- });
265
- if (res.ok) info = normalizeHostUser(await res.json());
266
- } catch (err) {
267
- this.log.warn("huaqiu api-key sync fetch failed", {
268
- url,
269
- error: String(err)
270
- });
271
- return;
272
- }
273
- if (info !== null && info.authenticated) {
274
- if (info.token !== this.lastToken) {
275
- this.lastToken = info.token;
276
- await store.set(HUAQIU_API_KEY_REF, info.token);
277
- this.log.info("huaqiu api-key credential synced", { userId: info.id });
278
- }
279
- return;
280
- }
281
- if (res !== null && res.ok) {
282
- if (this.lastToken !== null) {
283
- this.lastToken = null;
284
- await store.unset(HUAQIU_API_KEY_REF);
285
- this.log.info("huaqiu api-key credential cleared", { explicit: true });
286
- }
287
- return;
288
- }
289
- this.log.warn("huaqiu api-key sync rejected by host", {
290
- url,
291
- status: res?.status ?? null
292
- });
293
- }
294
- };
295
176
  /**
296
177
  * Classifies the HTTP status of the validation request.
297
178
  *
@@ -934,27 +815,10 @@ function apply(ctx, config) {
934
815
  path: AUTH_ROUTE_PREFIX,
935
816
  handler: createAuthHandler(service)
936
817
  }));
937
- if (service.hostMode) ctx.effect(() => {
938
- const resolved = resolveHostConfig(config);
939
- const sync = new HuaqiuApiKeySync(resolved.hqEdgeBaseUrl ?? "", resolved.hostAuthPath ?? "/api/v1/auth/token", () => {
940
- const credentials = ctx.get("credentials");
941
- if (credentials === void 0) return null;
942
- return {
943
- set: (ref, value) => credentials.set(ref, value),
944
- unset: (ref) => credentials.unset(ref)
945
- };
946
- }, {
947
- debug: (msg, ctx2) => log.debug(msg, ctx2),
948
- info: (msg, ctx2) => log.info(msg, ctx2),
949
- warn: (msg, ctx2) => log.warn(msg, ctx2)
950
- });
951
- sync.start();
952
- return () => sync.dispose();
953
- });
954
818
  log.info("dsh-auth node half ready", {
955
819
  routes: AUTH_ROUTE_PREFIX,
956
820
  hostMode: service.hostMode
957
821
  });
958
822
  }
959
823
  //#endregion
960
- export { AUTH_ROUTE_PREFIX, DEFAULT_HUAQIU_API_KEY_SYNC_MS, HUAQIU_API_KEY_REF, HuaqiuApiKeySync, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
824
+ export { AUTH_ROUTE_PREFIX, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-auth",
3
- "version": "0.6.10",
3
+ "version": "0.6.11",
4
4
  "type": "module",
5
5
  "main": "./lib/index.mjs",
6
6
  "types": "./lib/index.d.mts",
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@deepseek-ai/dsh-home-paths": "^0.1.0-rc.0",
36
- "@huaqiu/dsh-plugin-log": "0.6.10"
36
+ "@huaqiu/dsh-plugin-log": "0.6.11"
37
37
  },
38
38
  "files": [
39
39
  "lib",
package/src/index.ts CHANGED
@@ -5,15 +5,9 @@
5
5
  * mounts the browser→node credential routes on `ctx.webServer`.
6
6
  */
7
7
  import type { Context } from '@deepseek-ai/cordis'
8
- import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
9
8
  import type {} from '@deepseek-ai/dsh-host-webserver'
10
9
  import { getLogger } from '@huaqiu/dsh-plugin-log'
11
- import {
12
- DEFAULT_HOST_AUTH_PATH,
13
- resolveHostConfig,
14
- type HuaqiuAuthConfig,
15
- } from './host.js'
16
- import { HuaqiuApiKeySync, HUAQIU_API_KEY_REF } from './apiKeySync.js'
10
+ import type { HuaqiuAuthConfig } from './host.js'
17
11
  import { InMemoryHuaqiuAuthService, type HuaqiuAuthService } from './service.js'
18
12
  import { AUTH_ROUTE_PREFIX, createAuthHandler } from './routes.js'
19
13
 
@@ -22,12 +16,6 @@ const log = getLogger('dsh-auth')
22
16
  export type { HuaqiuAuthApi, HuaqiuAuthService, HuaqiuUserInfo } from './service.js'
23
17
  export { InMemoryHuaqiuAuthService } from './service.js'
24
18
  export { AUTH_ROUTE_PREFIX, createAuthHandler, type AuthHandler } from './routes.js'
25
- export {
26
- DEFAULT_HUAQIU_API_KEY_SYNC_MS,
27
- HuaqiuApiKeySync,
28
- HUAQIU_API_KEY_REF,
29
- type CredentialStore,
30
- } from './apiKeySync.js'
31
19
  export type { HuaqiuAuthConfig } from './host.js'
32
20
 
33
21
  export const name = '@huaqiu/dsh-auth'
@@ -67,45 +55,5 @@ export function apply(ctx: Context, config?: Partial<HuaqiuAuthConfig>): void {
67
55
  handler: createAuthHandler(service),
68
56
  }))
69
57
 
70
- // Host mode: mirror the operator token into the DSH credential reference
71
- // `HUAQIU_API_KEY` so the bundled `huaqiu` AI provider can resolve it per
72
- // request (task huaqiu-ai-gateway §5). The sync re-fetches the loopback
73
- // token endpoint on an immediate round plus a 5 s non-overlapping poll;
74
- // it is host-scoped only — standalone DSH keeps its browser-login flow and
75
- // the reference stays unset (missing credential → explicit
76
- // MISSING_CREDENTIAL, never a fallback key).
77
- if (service.hostMode) {
78
- ctx.effect(() => {
79
- const resolved = resolveHostConfig(config)
80
- const sync = new HuaqiuApiKeySync(
81
- resolved.hqEdgeBaseUrl ?? '',
82
- resolved.hostAuthPath ?? DEFAULT_HOST_AUTH_PATH,
83
- // Lazy per-round resolution: the `credentials` service may not be
84
- // activated yet while this plugin boots (activation order). Direct
85
- // `ctx.credentials` property access would throw "cannot get property
86
- // ... without inject" in that window; `ctx.get('credentials')`
87
- // returns undefined instead, so the round is skipped and the next
88
- // poll retries once the service is live (self-healing, no restart).
89
- () => {
90
- const credentials = ctx.get('credentials') as
91
- | { set(ref: string, value: string): Promise<void>; unset(ref: string): Promise<void> }
92
- | undefined
93
- if (credentials === undefined) return null
94
- return {
95
- set: (ref, value) => credentials.set(ref as CredentialRef, value),
96
- unset: (ref) => credentials.unset(ref as CredentialRef),
97
- }
98
- },
99
- {
100
- debug: (msg, ctx2) => log.debug(msg, ctx2),
101
- info: (msg, ctx2) => log.info(msg, ctx2),
102
- warn: (msg, ctx2) => log.warn(msg, ctx2),
103
- },
104
- )
105
- sync.start()
106
- return () => sync.dispose()
107
- })
108
- }
109
-
110
58
  log.info('dsh-auth node half ready', { routes: AUTH_ROUTE_PREFIX, hostMode: service.hostMode })
111
59
  }
package/src/apiKeySync.ts DELETED
@@ -1,157 +0,0 @@
1
- /**
2
- * Huaqiu AI gateway credential sync (host mode).
3
- *
4
- * The bundled DSH's `huaqiu` provider resolves its api key through the
5
- * `HUAQIU_API_KEY` credential reference (overlay `apiKeyEnv`). In host mode the
6
- * authoritative credential lives in HQ Edge (mirroring the EDA/KiCad host), and
7
- * Workstream A strips `HUAQIU_API_KEY` from the child environment — so this
8
- * sync is the ONLY source of that credential (task huaqiu-ai-gateway §5.5).
9
- *
10
- * The sync watches the HQ Edge token endpoint directly with a per-call
11
- * loopback GET — deliberately NOT `hqEdge.auth.getAccessToken()`, whose
12
- * initial-null cache has no invalidation path — and mirrors the token into
13
- * `ctx.credentials` under the `HUAQIU_API_KEY` reference:
14
- *
15
- * - authenticated host session → `set` (only when the token value changed);
16
- * - explicit unauthenticated verdict (2xx + `authenticated: false`, or a 2xx
17
- * payload without a usable credential) → `unset`;
18
- * - transient network error / non-2xx host answer → warn and leave the
19
- * current value untouched (a blip must never log the operator out).
20
- *
21
- * The same path serves both the `hq-eda` and `kicad` hosts — host identity is
22
- * HQ Edge configuration, never this plugin's concern.
23
- */
24
- import { normalizeHostUser, type ResolvedHostUser } from './host.js'
25
-
26
- /** Credential reference the `huaqiu` provider resolves per request. */
27
- export const HUAQIU_API_KEY_REF = 'HUAQIU_API_KEY'
28
-
29
- /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
30
- export const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5000
31
-
32
- /** Minimal writable credential store (the DSH `ctx.credentials` seam). */
33
- export interface CredentialStore {
34
- set(ref: string, value: string): Promise<void>
35
- unset(ref: string): Promise<void>
36
- }
37
-
38
- /**
39
- * Resolves the credential store lazily on every sync round.
40
- *
41
- * The DSH `credentials` service may not be activated yet when this plugin
42
- * boots (service activation order), and direct `ctx.credentials` property
43
- * access throws "cannot get property ... without inject" in that window.
44
- * Resolving through `ctx.get('credentials')` per round returns `undefined`
45
- * while the service is unavailable — the round is skipped and retried on the
46
- * next poll, so the sync self-heals once the service activates, without a
47
- * restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
48
- */
49
- export type CredentialStoreProvider = () => CredentialStore | null
50
-
51
- /** Logger surface used by the sync (kept small so tests can pass a spy). */
52
- export interface SyncLogger {
53
- debug(msg: string, ctx?: Record<string, unknown>): void
54
- info(msg: string, ctx?: Record<string, unknown>): void
55
- warn(msg: string, ctx?: Record<string, unknown>): void
56
- }
57
-
58
- export class HuaqiuApiKeySync {
59
- private timer: NodeJS.Timeout | null = null
60
- /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
61
- private inFlight = false
62
- /** Last token mirrored into the credential store (change detection). */
63
- private lastToken: string | null = null
64
-
65
- constructor(
66
- /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
67
- readonly baseUrl: string,
68
- /** Token path on the host; default "/api/v1/auth/token". */
69
- readonly path: string,
70
- private readonly storeProvider: CredentialStoreProvider,
71
- private readonly log: SyncLogger,
72
- private readonly intervalMs: number = DEFAULT_HUAQIU_API_KEY_SYNC_MS,
73
- private readonly doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
74
- ) {}
75
-
76
- /** Host-mode sync is active iff a base URL was configured. */
77
- get enabled(): boolean {
78
- return this.baseUrl.length > 0
79
- }
80
-
81
- /** Kick off an immediate sync, then poll on a non-overlapping interval. */
82
- start(): void {
83
- void this.syncNow()
84
- this.timer = setInterval(() => {
85
- if (this.inFlight) return
86
- this.inFlight = true
87
- void this.syncNow().finally(() => {
88
- this.inFlight = false
89
- })
90
- }, this.intervalMs)
91
- // Never keep the DSH process alive just for this timer.
92
- if (typeof this.timer.unref === 'function') this.timer.unref()
93
- }
94
-
95
- /** Stop the poll timer. Safe to call more than once. */
96
- dispose(): void {
97
- if (this.timer !== null) clearInterval(this.timer)
98
- this.timer = null
99
- }
100
-
101
- /**
102
- * One sync round: fetch the host token endpoint and mirror the verdict into
103
- * the credential store. Exported separately from `start()` so tests can run
104
- * rounds deterministically without timers.
105
- */
106
- async syncNow(): Promise<void> {
107
- // Resolve the credential store lazily: the `credentials` service may not
108
- // be activated yet while this plugin boots (activation order). Skipping
109
- // the round is safe — the next poll retries once the service is live.
110
- const store = this.storeProvider()
111
- if (store === null) {
112
- this.log.debug('huaqiu api-key sync skipped: credentials service unavailable')
113
- return
114
- }
115
- const url = `${this.baseUrl}${this.path}`
116
- let res: Response | null = null
117
- let info: ResolvedHostUser | null = null
118
- try {
119
- res = await this.doFetch(url, {
120
- method: 'GET',
121
- headers: { accept: 'application/json' },
122
- })
123
- if (res.ok) {
124
- info = normalizeHostUser(await res.json() as Record<string, unknown>)
125
- }
126
- } catch (err) {
127
- // Transient network error: never unset — a blip must not log the
128
- // operator out (task §5.4).
129
- this.log.warn('huaqiu api-key sync fetch failed', { url, error: String(err) })
130
- return
131
- }
132
- if (info !== null && info.authenticated) {
133
- if (info.token !== this.lastToken) {
134
- this.lastToken = info.token
135
- await store.set(HUAQIU_API_KEY_REF, info.token)
136
- this.log.info('huaqiu api-key credential synced', { userId: info.id })
137
- }
138
- return
139
- }
140
- // A 2xx answer without a usable authenticated credential is the HOST'S
141
- // explicit verdict (logout / not-yet-logged-in / cleared token) — mirror
142
- // the cleared state. Anything else (non-2xx) is a host-side error: warn
143
- // and keep the current value.
144
- if (res !== null && res.ok) {
145
- if (this.lastToken !== null) {
146
- this.lastToken = null
147
- await store.unset(HUAQIU_API_KEY_REF)
148
- this.log.info('huaqiu api-key credential cleared', { explicit: true })
149
- }
150
- return
151
- }
152
- this.log.warn('huaqiu api-key sync rejected by host', {
153
- url,
154
- status: res?.status ?? null,
155
- })
156
- }
157
- }