@gatemux/dsh-gatemux-login-core 1.0.0 → 1.0.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.
Files changed (3) hide show
  1. package/account.js +85 -17
  2. package/llm.js +4 -0
  3. package/package.json +6 -4
package/account.js CHANGED
@@ -25,11 +25,10 @@ import { promises as streamPromises } from 'node:stream'
25
25
 
26
26
  import { Service } from '@deepseek-ai/cordis'
27
27
  import { credentialKey } from '@deepseek-ai/dsh-credentials'
28
- import {
29
- DeepSeekAccount,
30
- installAccountTaskCancellation,
31
- } from '@deepseek-ai/dsh-deepseek-account'
28
+ import { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account'
29
+ import { LlmError } from '@deepseek-ai/dsh-llm'
32
30
  import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
31
+ import Schema from '@deepseek-ai/schemastery'
33
32
 
34
33
  /**
35
34
  * Deployment defaults. Every one of these is overridable through the row's
@@ -64,6 +63,22 @@ const REFRESH_MARGIN_MS = 60_000
64
63
  const ATTEMPT_TIMEOUT_MS = 600_000
65
64
  const REQUEST_TIMEOUT_MS = 30_000
66
65
  const DEFAULT_SCOPES = ['models:read', 'responses:create', 'media:create', 'account:read', 'openid', 'email']
66
+ /** Route this provider authenticates; the same id the model row registers. */
67
+ const PROVIDER = 'gatemux-account'
68
+
69
+ /**
70
+ * Row configuration surface, validated at activation rather than on first use.
71
+ *
72
+ * `clientId` stays optional because a launch environment may supply it; the
73
+ * constructor still rejects an empty value with the message that names both
74
+ * sources.
75
+ */
76
+ export const Config = Schema.object({
77
+ clientId: Schema.string().min(1),
78
+ authorizeOrigin: Schema.string().default(DEFAULT_ISSUER),
79
+ consoleOrigin: Schema.string().default(DEFAULT_CONSOLE_ORIGIN),
80
+ scopes: Schema.array(Schema.string()).default(DEFAULT_SCOPES),
81
+ })
67
82
 
68
83
  /** Local attempt failure taxonomy; the abstract contract renders these through locale copy. */
69
84
  class GateMuxAuthError extends Error {
@@ -134,9 +149,37 @@ function apiErrorCode(body) {
134
149
  return typeof error.code === 'string' ? error.code : undefined
135
150
  }
136
151
 
152
+ /**
153
+ * Cancel running work on this route when the account signs out.
154
+ *
155
+ * The shared `installAccountTaskCancellation` helper is keyed to the shipped
156
+ * `deepseek-account` route, so reusing it here would leave a `gatemux-account`
157
+ * stream running with a credential the person just removed. The sign-in
158
+ * guidance half is provider-agnostic and kept verbatim.
159
+ *
160
+ * @param ctx - the account provider's lifetime.
161
+ */
162
+ function installGateMuxTaskCancellation(ctx) {
163
+ ctx.inject(['agents'], (scope) => {
164
+ scope.on('agent/error', ({ error }) => {
165
+ if (error instanceof LlmError && error.code === 'ACCOUNT_SIGN_IN_REQUIRED') {
166
+ scope.emit('deepseek-account/model-sign-in-required')
167
+ }
168
+ })
169
+ scope.on('deepseek-account/signed-out', () => {
170
+ for (const agent of scope.agents.list()) {
171
+ if (agent.status === 'running' && agent.session.requestContext()?.provider === PROVIDER) {
172
+ agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true })
173
+ }
174
+ }
175
+ })
176
+ })
177
+ }
178
+
137
179
  /** GateMux login state, stored grant, and refresh rotation. */
138
180
  export class GateMuxAccount extends DeepSeekAccount {
139
181
  static inject = ['credentials', 'authorization']
182
+ static Config = Config
140
183
 
141
184
  clientId
142
185
  issuer
@@ -162,7 +205,7 @@ export class GateMuxAccount extends DeepSeekAccount {
162
205
  */
163
206
  constructor(ctx, config = {}) {
164
207
  super(ctx)
165
- installAccountTaskCancellation(ctx)
208
+ installGateMuxTaskCancellation(ctx)
166
209
  const clientId = config.clientId ?? launchEnvironmentOf(ctx).get(CLIENT_ID_ENV)?.value
167
210
  if (typeof clientId !== 'string' || clientId.length === 0) {
168
211
  throw new GateMuxAuthError(
@@ -265,7 +308,7 @@ export class GateMuxAccount extends DeepSeekAccount {
265
308
  if (grant === null || lifetime.signal.aborted) return null
266
309
  const body = await this.callApi(this.accountEndpoint, grant, lifetime, client)
267
310
  if (this.detailsLifetime !== lifetime) return null
268
- if (body === null) return { status: 'failed' }
311
+ if (body === null || typeof body !== 'object') return { status: 'failed' }
269
312
  const wallet = body.wallet
270
313
  if (typeof wallet !== 'object' || wallet === null) return { status: 'failed' }
271
314
  const { currency, balance } = wallet
@@ -313,9 +356,7 @@ export class GateMuxAccount extends DeepSeekAccount {
313
356
  interaction: { notify: () => undefined, prompt: () => Promise.reject(new GateMuxAuthError('no prompt', 'protocol')) },
314
357
  }).then((outcome) => {
315
358
  this.update(attempt, { phase: outcome.status === 'authorized' ? 'succeeded' : 'cancelled' })
316
- if (outcome.status === 'authorized' && attempt.completionUrl !== undefined) {
317
- attempt.callback?.writeHead(302, { location: attempt.completionUrl, 'cache-control': 'no-store' }).end()
318
- } else if (outcome.status === 'authorized') {
359
+ if (outcome.status === 'authorized') {
319
360
  // GateMux serves no hosted completion page, so this tab is the only place
320
361
  // the result is visible; answering 204 would leave it blank.
321
362
  this.writeCallbackPage(attempt, 'Signed in', attempt.loginSource === 'web'
@@ -363,10 +404,15 @@ export class GateMuxAccount extends DeepSeekAccount {
363
404
  const record = await this.ctx.credentials.readRecord(KEY)
364
405
  if (record !== undefined) {
365
406
  const grant = record.kind === 'grant' ? parseGrant(record.payload, this.issuer) : null
366
- if (grant === null) throw new GateMuxAuthError('stored grant is unreadable', 'storage')
407
+ // A record this deployment cannot read still has to be removable:
408
+ // refusing here would strand a corrupt grant with no way to clear it
409
+ // from the settings page.
410
+ if (grant === null) {
411
+ this.logger.warn('stored grant discarded on sign-out', { reason: 'unreadable-or-foreign-issuer' })
412
+ }
367
413
  await this.ctx.credentials.deleteRecord(KEY)
368
414
  // Revoking the refresh token cascades to every access token it issued.
369
- this.revoke(grant.refreshToken)
415
+ if (grant !== null) this.revoke(grant.refreshToken)
370
416
  }
371
417
  this.attempt = undefined
372
418
  this.ctx.emit('deepseek-account/signed-out')
@@ -553,6 +599,9 @@ export class GateMuxAccount extends DeepSeekAccount {
553
599
  try {
554
600
  return await this.refreshInFlight
555
601
  } catch {
602
+ // The seam can only report "no token", so a transient refresh failure
603
+ // reads as sign-in-required at the model route; the grant is kept so the
604
+ // next request can retry.
556
605
  return null
557
606
  }
558
607
  }
@@ -574,10 +623,18 @@ export class GateMuxAccount extends DeepSeekAccount {
574
623
  }, lifetime.signal)
575
624
  if (!response.ok) {
576
625
  const code = tokenErrorCode(response.body)
577
- // An unknown or expired refresh token means the authorization is gone.
578
- this.logger.warn('refresh rejected', { errorCode: code ?? 'unknown' })
579
- await this.expireCredential(grant.accessToken, lifetime)
580
- throw new GateMuxAuthError('refresh token rejected', 'expired')
626
+ // Only a rejected grant means this authorization is gone. A 5xx, a 429,
627
+ // or a client-configuration error leaves the stored grant in place:
628
+ // discarding it would sign the person out for an outage they cannot fix
629
+ // by signing in again.
630
+ if (code === 'invalid_grant' || code === 'invalid_token') {
631
+ this.logger.warn('refresh token rejected', { errorCode: code })
632
+ await this.expireCredential(grant.accessToken, lifetime)
633
+ throw new GateMuxAuthError('refresh token rejected', 'expired')
634
+ }
635
+ this.logger.warn('refresh temporarily failed', { status: response.status, errorCode: code ?? 'unknown' })
636
+ throw new GateMuxAuthError(
637
+ `token endpoint rejected refresh (${response.status} ${code ?? 'unknown'})`, 'network')
581
638
  }
582
639
  const next = this.grantFrom(response.body)
583
640
  // Persist the rotated token before any other request can read the old one.
@@ -599,7 +656,13 @@ export class GateMuxAccount extends DeepSeekAccount {
599
656
  return { version: 1, accessToken, refreshToken, expiresAt: Date.now() + seconds * 1000, issuer: this.issuer }
600
657
  }
601
658
 
602
- /** Post one token-endpoint request and decode its RFC 6749 §5.2 envelope. */
659
+ /**
660
+ * Post one token-endpoint request and decode its RFC 6749 §5.2 envelope.
661
+ *
662
+ * GateMux accepts the parameters as a JSON object; a stock RFC 6749 token
663
+ * endpoint expects `application/x-www-form-urlencoded`, so this is a
664
+ * GateMux-specific contract rather than a generic one.
665
+ */
603
666
  async postToken(fields, signal) {
604
667
  const response = await fetch(this.tokenEndpoint, {
605
668
  method: 'POST',
@@ -689,7 +752,12 @@ export class GateMuxAccount extends DeepSeekAccount {
689
752
  await this.removing
690
753
  }
691
754
 
692
- /** Revoke a refresh token, cascading to its access tokens; failures are not fatal. */
755
+ /**
756
+ * Revoke a refresh token, cascading to its access tokens; failures are not fatal.
757
+ *
758
+ * RFC 7009 normally expects form encoding; GateMux accepts JSON, like its
759
+ * token endpoint.
760
+ */
693
761
  revoke(refreshToken) {
694
762
  if (this.closed) return
695
763
  void fetch(this.revokeEndpoint, {
package/llm.js CHANGED
@@ -35,6 +35,9 @@ const MESSAGES_PROTOCOL = 'anthropic-messages'
35
35
  /** Protocol version this transport sends on every request, the model listing included. */
36
36
  const ANTHROPIC_VERSION = '2023-06-01'
37
37
 
38
+ /** Deadline for one model-listing read; discovery must not hang the selector. */
39
+ const LISTING_TIMEOUT_MS = 30_000
40
+
38
41
  /**
39
42
  * Anthropic's listing path, read from a Messages base URL.
40
43
  *
@@ -164,6 +167,7 @@ export function apply(ctx, config) {
164
167
  const response = await fetch(url, {
165
168
  method: 'GET',
166
169
  headers: { ...headers, 'accept': 'application/json', 'anthropic-version': ANTHROPIC_VERSION },
170
+ signal: AbortSignal.timeout(LISTING_TIMEOUT_MS),
167
171
  })
168
172
  if (!response.ok) throw new Error(`${url} answered ${response.status}`)
169
173
  const body = await response.json()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gatemux/dsh-gatemux-login-core",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "type": "module",
5
5
  "description": "GateMux account provider and model route for DeepSeek Harness. Shared code; install a region bundle instead of this package.",
6
6
  "publishConfig": {
@@ -28,7 +28,8 @@
28
28
  "@deepseek-ai/dsh-host-webserver": "^0.1.7-rc.2 || ^0.2.0-rc.2",
29
29
  "@deepseek-ai/dsh-launch-environment": "^0.1.7-rc.2 || ^0.2.0-rc.2",
30
30
  "@deepseek-ai/dsh-llm": "^0.1.7-rc.2 || ^0.2.0-rc.2",
31
- "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2"
31
+ "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2",
32
+ "@deepseek-ai/schemastery": "^3.18.4"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@deepseek-ai/cordis": "^4.0.4",
@@ -38,6 +39,7 @@
38
39
  "@deepseek-ai/dsh-host-webserver": "^0.1.7-rc.2 || ^0.2.0-rc.2",
39
40
  "@deepseek-ai/dsh-launch-environment": "^0.1.7-rc.2 || ^0.2.0-rc.2",
40
41
  "@deepseek-ai/dsh-llm": "^0.1.7-rc.2 || ^0.2.0-rc.2",
41
- "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2"
42
+ "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2",
43
+ "@deepseek-ai/schemastery": "^3.18.4"
42
44
  }
43
- }
45
+ }