opencode-codebuddy-quota 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +81 -2
- package/config.default.json +38 -0
- package/dist/gui-experimental.cjs +1 -0
- package/package.json +46 -4
- package/rpc.ts +92 -0
- package/server.ts +136 -0
- package/src/gui/battery.tsx +81 -0
- package/src/gui/dialog-helpers.ts +30 -0
- package/src/gui/dialog.css +83 -0
- package/src/gui/dialog.tsx +262 -0
- package/src/gui/pace.ts +76 -0
- package/src/gui/quota.ts +198 -0
- package/src/gui/store.ts +181 -0
- package/src/gui.tsx +111 -0
- package/src/server/catalog.ts +264 -0
- package/src/server/config-writer.ts +621 -0
- package/src/server/config.ts +195 -0
- package/src/server/headers.ts +72 -0
- package/src/server/logger.ts +26 -0
- package/src/server/login-gate.ts +21 -0
- package/src/server/login.ts +206 -0
- package/src/server/model-info.ts +109 -0
- package/src/server/models-dev.ts +77 -0
- package/src/server/package-spec.ts +42 -0
- package/src/server/package-version.ts +51 -0
- package/src/server/pricing.ts +169 -0
- package/src/server/proxy.ts +236 -0
- package/src/server/quota-source.ts +129 -0
- package/src/server/rpc-handlers.ts +87 -0
- package/src/server/signal.ts +36 -0
- package/src/server/site-select.ts +24 -0
- package/src/server/site-state.ts +58 -0
- package/src/server/token-store.ts +263 -0
- package/src/server/upstream.ts +150 -0
- package/src/server/wire.ts +67 -0
- package/src/shared.ts +20 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { Site } from "../shared"
|
|
2
|
+
import type { UpstreamReading } from "./upstream"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A reading plus the freshness verdict. `fetchedAt` is null only when nothing
|
|
6
|
+
* has ever been read successfully — every numeric field is null then.
|
|
7
|
+
*/
|
|
8
|
+
export interface Reading {
|
|
9
|
+
remaining: number | null
|
|
10
|
+
used: number | null
|
|
11
|
+
total: number | null
|
|
12
|
+
cycleStart: string | null
|
|
13
|
+
cycleEnd: string | null
|
|
14
|
+
resetAt: string | null
|
|
15
|
+
fetchedAt: string | null
|
|
16
|
+
stale: boolean
|
|
17
|
+
error: string | null
|
|
18
|
+
/** This answer was served from the cache; the upstream was not called. */
|
|
19
|
+
cached: boolean
|
|
20
|
+
/** How old the numbers are, in whole seconds. Null when there are no numbers. */
|
|
21
|
+
ageSeconds: number | null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface QuotaSource {
|
|
25
|
+
read(site: Site, signal?: AbortSignal): Promise<Reading>
|
|
26
|
+
/**
|
|
27
|
+
* Called after a fresh login. Drops the failure cooldown *and* the cached
|
|
28
|
+
* reading, so the next read re-fetches with the new token instead of serving
|
|
29
|
+
* the old account's numbers from the 30-second cache.
|
|
30
|
+
*/
|
|
31
|
+
clearFailure(site: Site): void
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface QuotaSourceDeps {
|
|
35
|
+
/** Site-based fetch callback; the server wraps it over store.ensureFresh + fetchUpstream. */
|
|
36
|
+
readForSite: (site: Site, signal?: AbortSignal) => Promise<UpstreamReading>
|
|
37
|
+
now?: () => number
|
|
38
|
+
minRefreshMs?: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const MIN_REFRESH_MS = 30_000
|
|
42
|
+
|
|
43
|
+
const EMPTY: Reading = {
|
|
44
|
+
remaining: null, used: null, total: null,
|
|
45
|
+
cycleStart: null, cycleEnd: null, resetAt: null,
|
|
46
|
+
fetchedAt: null, stale: false, error: null, cached: false, ageSeconds: null,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface SiteState {
|
|
50
|
+
cached: { reading: UpstreamReading; at: number } | null
|
|
51
|
+
failedAt: number | null
|
|
52
|
+
lastError: string | null
|
|
53
|
+
inflight: Promise<Reading> | null
|
|
54
|
+
/** Bumped on clearFailure so a read that began with an old token cannot write
|
|
55
|
+
* its late result back into the cache after a new login. */
|
|
56
|
+
epoch: number
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const newState = (): SiteState => ({ cached: null, failedAt: null, lastError: null, inflight: null, epoch: 0 })
|
|
60
|
+
|
|
61
|
+
/** Per-site cache: one broken site cannot starve the other. */
|
|
62
|
+
export function createQuotaSource(deps: QuotaSourceDeps): QuotaSource {
|
|
63
|
+
const now = deps.now ?? Date.now
|
|
64
|
+
const minRefreshMs = deps.minRefreshMs ?? MIN_REFRESH_MS
|
|
65
|
+
const states: Record<Site, SiteState> = { cn: newState(), intl: newState() }
|
|
66
|
+
|
|
67
|
+
const ageOf = (at: number) => Math.max(0, Math.round((now() - at) / 1000))
|
|
68
|
+
const fresh = (r: UpstreamReading): Reading => ({ ...r, stale: false, error: null, cached: false, ageSeconds: 0 })
|
|
69
|
+
const fromCache = (e: { reading: UpstreamReading; at: number }): Reading => ({
|
|
70
|
+
...e.reading, stale: false, error: null, cached: true, ageSeconds: ageOf(e.at),
|
|
71
|
+
})
|
|
72
|
+
const fallback = (state: SiteState, error: string): Reading =>
|
|
73
|
+
state.cached
|
|
74
|
+
? { ...state.cached.reading, stale: true, error, cached: false, ageSeconds: ageOf(state.cached.at) }
|
|
75
|
+
: { ...EMPTY, stale: true, error }
|
|
76
|
+
|
|
77
|
+
const load = async (site: Site, state: SiteState, signal?: AbortSignal): Promise<Reading> => {
|
|
78
|
+
const epoch = state.epoch
|
|
79
|
+
try {
|
|
80
|
+
const reading = await deps.readForSite(site, signal)
|
|
81
|
+
// A clearFailure (new login) may have happened while this request was in
|
|
82
|
+
// flight. Its result belongs to the old token — return it to this caller
|
|
83
|
+
// but never cache it, so the next read fetches with the new token.
|
|
84
|
+
if (state.epoch !== epoch) return fresh(reading)
|
|
85
|
+
state.cached = { reading, at: now() }
|
|
86
|
+
state.failedAt = null
|
|
87
|
+
state.lastError = null
|
|
88
|
+
return fresh(reading)
|
|
89
|
+
} catch (error) {
|
|
90
|
+
const message = String((error as Error)?.message ?? error)
|
|
91
|
+
if (state.epoch !== epoch) return fallback(state, message)
|
|
92
|
+
state.failedAt = now()
|
|
93
|
+
state.lastError = message
|
|
94
|
+
return fallback(state, message)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
clearFailure(site) {
|
|
100
|
+
const state = states[site]
|
|
101
|
+
state.epoch += 1
|
|
102
|
+
state.failedAt = null
|
|
103
|
+
state.lastError = null
|
|
104
|
+
state.cached = null
|
|
105
|
+
// Release the single-flight slot so the next read starts a fresh request
|
|
106
|
+
// with the new token instead of awaiting the stale in-flight one.
|
|
107
|
+
state.inflight = null
|
|
108
|
+
},
|
|
109
|
+
async read(site, signal) {
|
|
110
|
+
const state = states[site]
|
|
111
|
+
if (signal?.aborted) return fallback(state, String(signal.reason ?? "aborted"))
|
|
112
|
+
if (state.cached && now() - state.cached.at < minRefreshMs) return fromCache(state.cached)
|
|
113
|
+
if (state.failedAt !== null && now() - state.failedAt < minRefreshMs) {
|
|
114
|
+
return fallback(state, state.lastError ?? "upstream unavailable")
|
|
115
|
+
}
|
|
116
|
+
if (!state.inflight) {
|
|
117
|
+
// Identity check: a clearFailure may have released the slot and a newer
|
|
118
|
+
// request taken it while this one was still in flight. Only the current
|
|
119
|
+
// owner may clear it — otherwise a late old request would drop the new
|
|
120
|
+
// one's slot and cause a redundant upstream call.
|
|
121
|
+
const pending = load(site, state, signal).finally(() => {
|
|
122
|
+
if (state.inflight === pending) state.inflight = null
|
|
123
|
+
})
|
|
124
|
+
state.inflight = pending
|
|
125
|
+
}
|
|
126
|
+
return state.inflight
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { Site } from "../shared"
|
|
2
|
+
import { createLoginGate, type LoginGate } from "./login-gate"
|
|
3
|
+
import { getAuthState, openBrowser, pollToken, type SiteAuth } from "./login"
|
|
4
|
+
import { resolveSite } from "./site-select"
|
|
5
|
+
import { siteInfo } from "./site-state"
|
|
6
|
+
import type { TokenStore } from "./token-store"
|
|
7
|
+
import type { QuotaSource, Reading } from "./quota-source"
|
|
8
|
+
import { toWireReading, type WireReading } from "./wire"
|
|
9
|
+
|
|
10
|
+
/** The `read`/`login` handlers the plugin registers over RPC. */
|
|
11
|
+
export interface RpcHandlers {
|
|
12
|
+
read(input: unknown, context: { signal: AbortSignal }): Promise<WireReading>
|
|
13
|
+
login(input: unknown): Promise<{ ok: boolean; error: string | null }>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface HandlerDeps {
|
|
17
|
+
store: TokenStore
|
|
18
|
+
source: QuotaSource
|
|
19
|
+
log: (message: string) => void
|
|
20
|
+
/** Injectable login step returning the new credential; defaults to browser flow. */
|
|
21
|
+
performLogin?: (site: Site) => Promise<SiteAuth>
|
|
22
|
+
/** Injectable gate; defaults to per-site single-flight. */
|
|
23
|
+
loginGate?: LoginGate
|
|
24
|
+
/**
|
|
25
|
+
* Best-effort hook run after a successful login so the freshly added account
|
|
26
|
+
* can re-import its provider models. A failure here never fails the login.
|
|
27
|
+
*/
|
|
28
|
+
afterLogin?: (site: Site) => Promise<void>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Build the RPC handlers. Kept free of Plugin/Context so the wiring —
|
|
33
|
+
* site selection persistence, post-refresh cache snapshot, login single-flight —
|
|
34
|
+
* can be asserted without starting a real proxy or touching the disk.
|
|
35
|
+
*/
|
|
36
|
+
export function makeRpcHandlers(deps: HandlerDeps): RpcHandlers {
|
|
37
|
+
const gate = deps.loginGate ?? createLoginGate()
|
|
38
|
+
// Returns the new credential; the handler archives it on success so the
|
|
39
|
+
// write is part of the tested assembly, not hidden in the login step.
|
|
40
|
+
const performLogin =
|
|
41
|
+
deps.performLogin ??
|
|
42
|
+
(async (site) => {
|
|
43
|
+
const { state, authUrl } = await getAuthState(site)
|
|
44
|
+
openBrowser(authUrl)
|
|
45
|
+
return pollToken(site, state)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
async read(input, context) {
|
|
50
|
+
const requested = (input as { site?: Site } | undefined)?.site
|
|
51
|
+
const site = resolveSite(deps.store, requested, (m) => deps.log(m))
|
|
52
|
+
const reading: Reading = await deps.source.read(site, context.signal)
|
|
53
|
+
// Read the cache AFTER the refresh so a rotated token cannot leave a
|
|
54
|
+
// stale "needs login" tag next to freshly returned numbers.
|
|
55
|
+
const state = deps.store.all()
|
|
56
|
+
return toWireReading(reading, { site, sites: siteInfo(state, (s) => deps.store.refreshFailed(s)).sites })
|
|
57
|
+
},
|
|
58
|
+
async login(input) {
|
|
59
|
+
const site = (input as { site: Site }).site
|
|
60
|
+
return gate.run(site, async () => {
|
|
61
|
+
try {
|
|
62
|
+
const auth = await performLogin(site)
|
|
63
|
+
deps.store.archive(auth)
|
|
64
|
+
// A read before login likely armed the 30s failure cooldown. Clear it
|
|
65
|
+
// so the GUI's post-login refresh retries upstream with the new token
|
|
66
|
+
// immediately instead of replaying the old "needs login" verdict.
|
|
67
|
+
deps.source.clearFailure(site)
|
|
68
|
+
deps.log(`${site} login complete`)
|
|
69
|
+
// Re-import this account's models: a login after startup is the moment
|
|
70
|
+
// a previously missing site becomes importable. Fire-and-forget — the
|
|
71
|
+
// registry/catalog fetch can take tens of seconds, and a best-effort
|
|
72
|
+
// re-import must neither block the login response nor fail it.
|
|
73
|
+
if (deps.afterLogin) {
|
|
74
|
+
void deps.afterLogin(site).catch((error) => {
|
|
75
|
+
deps.log(`${site} post-login model re-import failed: ${String((error as Error)?.message ?? error)}`)
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
return { ok: true, error: null }
|
|
79
|
+
} catch (error) {
|
|
80
|
+
const message = String((error as Error)?.message ?? error)
|
|
81
|
+
deps.log(`${site} login failed: ${message}`)
|
|
82
|
+
return { ok: false, error: message }
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AbortSignal.any is not guaranteed in every runtime OpenCode embeds, so keep a
|
|
3
|
+
* small compatible implementation shared by the server and the catalog fetch.
|
|
4
|
+
*/
|
|
5
|
+
export function anySignal(signals: AbortSignal[]): AbortSignal {
|
|
6
|
+
for (const signal of signals) {
|
|
7
|
+
if (signal.aborted) return AbortSignal.abort(signal.reason)
|
|
8
|
+
}
|
|
9
|
+
const controller = new AbortController()
|
|
10
|
+
const listeners = signals.map((signal) => {
|
|
11
|
+
const handler = () => controller.abort(signal.reason)
|
|
12
|
+
signal.addEventListener("abort", handler, { once: true })
|
|
13
|
+
return { signal, handler }
|
|
14
|
+
})
|
|
15
|
+
// When one signal wins, detach from the others so a long-lived parent does
|
|
16
|
+
// not accumulate listeners across many requests.
|
|
17
|
+
controller.signal.addEventListener("abort", () => {
|
|
18
|
+
for (const { signal, handler } of listeners) signal.removeEventListener("abort", handler)
|
|
19
|
+
}, { once: true })
|
|
20
|
+
return controller.signal
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* AbortSignal.timeout is also not guaranteed in every embedded runtime. Prefer
|
|
25
|
+
* the native implementation; fall back to a timer-driven AbortController.
|
|
26
|
+
*/
|
|
27
|
+
export function timeoutSignal(ms: number): AbortSignal {
|
|
28
|
+
if (typeof AbortSignal.timeout === "function") return AbortSignal.timeout(ms)
|
|
29
|
+
const controller = new AbortController()
|
|
30
|
+
const timer = setTimeout(() => controller.abort(), ms)
|
|
31
|
+
// On Node the timer would otherwise hold the process open until it fires.
|
|
32
|
+
// Browsers return a numeric id with no unref — optional call is safe there.
|
|
33
|
+
timer.unref?.()
|
|
34
|
+
controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true })
|
|
35
|
+
return controller.signal
|
|
36
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Site } from "../shared"
|
|
2
|
+
import type { TokenStore } from "./token-store"
|
|
3
|
+
import { currentSite } from "./site-state"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Decide which site a `read` should use. An explicit requested site becomes the
|
|
7
|
+
* persisted selection, so a tag switch survives restart. A failed persist must
|
|
8
|
+
* not fail the read — the caller still gets numbers for the requested site.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveSite(
|
|
11
|
+
store: Pick<TokenStore, "all" | "select">,
|
|
12
|
+
requested: Site | undefined,
|
|
13
|
+
onError?: (message: string) => void,
|
|
14
|
+
): Site {
|
|
15
|
+
if (requested === "cn" || requested === "intl") {
|
|
16
|
+
try {
|
|
17
|
+
store.select(requested)
|
|
18
|
+
} catch (error) {
|
|
19
|
+
onError?.(`could not persist selected site: ${String((error as Error)?.message ?? error)}`)
|
|
20
|
+
}
|
|
21
|
+
return requested
|
|
22
|
+
}
|
|
23
|
+
return currentSite(store.all())
|
|
24
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { AccountBrief, Site, SiteInfo } from "../shared"
|
|
2
|
+
import { activeAccount, type TokenCache } from "./token-store"
|
|
3
|
+
|
|
4
|
+
/** A site is available if it has a usable session and refresh has not just failed. */
|
|
5
|
+
const siteAvailable = (
|
|
6
|
+
cache: TokenCache,
|
|
7
|
+
site: Site,
|
|
8
|
+
refreshFailed?: (site: Site) => boolean,
|
|
9
|
+
): boolean => {
|
|
10
|
+
const auth = activeAccount(cache, site)
|
|
11
|
+
if (!auth) return false
|
|
12
|
+
const now = Date.now()
|
|
13
|
+
// Usable if the access token is still valid, or the refresh token has not expired.
|
|
14
|
+
if (!(now < auth.expiresAt || now < auth.refreshExpiresAt)) return false
|
|
15
|
+
// A recent refresh failure means "needs login" — surface the login button
|
|
16
|
+
// instead of looping on a session that keeps failing to refresh.
|
|
17
|
+
if (refreshFailed?.(site)) return false
|
|
18
|
+
return true
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function availableSites(
|
|
22
|
+
cache: TokenCache,
|
|
23
|
+
refreshFailed?: (site: Site) => boolean,
|
|
24
|
+
): Site[] {
|
|
25
|
+
const sites: Site[] = ["cn", "intl"]
|
|
26
|
+
return sites.filter((s) => siteAvailable(cache, s, refreshFailed))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function currentSite(
|
|
30
|
+
cache: TokenCache,
|
|
31
|
+
refreshFailed?: (site: Site) => boolean,
|
|
32
|
+
): Site {
|
|
33
|
+
const available = availableSites(cache, refreshFailed)
|
|
34
|
+
if (available.includes(cache.selected)) return cache.selected
|
|
35
|
+
if (available.length === 1) return available[0]
|
|
36
|
+
return cache.selected
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** SiteInfo for the GUI: availability + account briefs (never tokens). */
|
|
40
|
+
export function siteInfo(
|
|
41
|
+
cache: TokenCache,
|
|
42
|
+
refreshFailed?: (site: Site) => boolean,
|
|
43
|
+
): { sites: SiteInfo[]; selected: Site } {
|
|
44
|
+
const sites: SiteInfo[] = (["cn", "intl"] as Site[]).map((site) => {
|
|
45
|
+
const account = activeAccount(cache, site)
|
|
46
|
+
const accounts: AccountBrief[] = cache.accounts[site].map((a) => ({
|
|
47
|
+
id: a.id,
|
|
48
|
+
label: a.uid,
|
|
49
|
+
}))
|
|
50
|
+
return {
|
|
51
|
+
site,
|
|
52
|
+
available: siteAvailable(cache, site, refreshFailed),
|
|
53
|
+
accounts,
|
|
54
|
+
activeId: account?.id ?? null,
|
|
55
|
+
}
|
|
56
|
+
})
|
|
57
|
+
return { sites, selected: currentSite(cache, refreshFailed) }
|
|
58
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { chmodSync, readFileSync, writeFileSync } from "node:fs"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import type { Site } from "../shared"
|
|
5
|
+
import { refreshHeaders } from "./headers"
|
|
6
|
+
import type { SiteAuth } from "./login"
|
|
7
|
+
|
|
8
|
+
/** Two-site cache. `accounts`/`activeId` reserve room for future multi-account. */
|
|
9
|
+
export interface TokenCache {
|
|
10
|
+
accounts: Record<Site, SiteAuth[]>
|
|
11
|
+
activeId: Record<Site, string | null>
|
|
12
|
+
selected: Site
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const CACHE_FILENAME = "codebuddy-quota-auth.json"
|
|
16
|
+
|
|
17
|
+
export function cachePath(dir?: string): string {
|
|
18
|
+
const base = dir ?? join(homedir(), ".config", "opencode")
|
|
19
|
+
return join(base, CACHE_FILENAME)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const emptyCache = (): TokenCache => ({
|
|
23
|
+
accounts: { cn: [], intl: [] },
|
|
24
|
+
activeId: { cn: null, intl: null },
|
|
25
|
+
selected: "cn",
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
type ReadFile = () => string
|
|
29
|
+
type WriteFile = (path: string, data: string) => void
|
|
30
|
+
|
|
31
|
+
const defaultRead = (path: string): ReadFile => () => readFileSync(path, "utf8")
|
|
32
|
+
const defaultWrite = (_path: string): WriteFile => (p, data) => {
|
|
33
|
+
writeFileSync(p, data, { mode: 0o600 })
|
|
34
|
+
// `mode` only applies on create; tighten an existing (e.g. 0644) file too.
|
|
35
|
+
try { chmodSync(p, 0o600) } catch { /* no-op on platforms without POSIX modes */ }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const isSite = (v: unknown): v is Site => v === "cn" || v === "intl"
|
|
39
|
+
|
|
40
|
+
/** Guard against a hand-corrupted cache entry with missing/ill-typed fields. */
|
|
41
|
+
const isSiteAuth = (v: unknown): v is SiteAuth => {
|
|
42
|
+
if (typeof v !== "object" || v === null) return false
|
|
43
|
+
const a = v as Record<string, unknown>
|
|
44
|
+
return (
|
|
45
|
+
typeof a.id === "string" &&
|
|
46
|
+
typeof a.accessToken === "string" &&
|
|
47
|
+
typeof a.refreshToken === "string" &&
|
|
48
|
+
typeof a.expiresAt === "number" &&
|
|
49
|
+
typeof a.refreshExpiresAt === "number" &&
|
|
50
|
+
typeof a.uid === "string" &&
|
|
51
|
+
typeof a.endpoint === "string" &&
|
|
52
|
+
typeof a.usageHost === "string" &&
|
|
53
|
+
(a.enterpriseId === null || typeof a.enterpriseId === "string")
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
const filterAuths = (v: unknown): SiteAuth[] =>
|
|
57
|
+
Array.isArray(v) ? (v as unknown[]).filter(isSiteAuth) : []
|
|
58
|
+
|
|
59
|
+
/** Read the cache, migrating the old flat `{ cn, intl, selected }` format. */
|
|
60
|
+
export function readCache(readFile?: ReadFile): TokenCache {
|
|
61
|
+
const raw = readFile ? readFile() : (() => {
|
|
62
|
+
try {
|
|
63
|
+
return defaultRead(cachePath())()
|
|
64
|
+
} catch {
|
|
65
|
+
return ""
|
|
66
|
+
}
|
|
67
|
+
})()
|
|
68
|
+
if (!raw) return emptyCache()
|
|
69
|
+
let parsed: Record<string, unknown>
|
|
70
|
+
try {
|
|
71
|
+
parsed = JSON.parse(raw) as Record<string, unknown>
|
|
72
|
+
} catch {
|
|
73
|
+
return emptyCache()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// New format: { accounts, activeId, selected }
|
|
77
|
+
if (parsed.accounts && typeof parsed.accounts === "object") {
|
|
78
|
+
const accounts = parsed.accounts as Record<string, unknown>
|
|
79
|
+
const active = (parsed.activeId ?? {}) as Record<string, unknown>
|
|
80
|
+
const cn = filterAuths(accounts.cn)
|
|
81
|
+
const intl = filterAuths(accounts.intl)
|
|
82
|
+
const selectSite = isSite(parsed.selected) ? parsed.selected : "cn"
|
|
83
|
+
const pick = (listed: unknown, accounts: SiteAuth[]): string | null => {
|
|
84
|
+
const id = typeof listed === "string" ? listed : (accounts[0]?.id ?? null)
|
|
85
|
+
return id && accounts.some((a) => a.id === id) ? id : (accounts[0]?.id ?? null)
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
accounts: { cn, intl },
|
|
89
|
+
activeId: { cn: pick(active.cn, cn), intl: pick(active.intl, intl) },
|
|
90
|
+
selected: selectSite,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Old format: { cn: SiteAuth|null, intl: SiteAuth|null, selected }
|
|
95
|
+
const cn = isSiteAuth(parsed.cn) ? parsed.cn : null
|
|
96
|
+
const intl = isSiteAuth(parsed.intl) ? parsed.intl : null
|
|
97
|
+
const accounts: Record<Site, SiteAuth[]> = {
|
|
98
|
+
cn: cn ? [cn] : [],
|
|
99
|
+
intl: intl ? [intl] : [],
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
accounts,
|
|
103
|
+
activeId: { cn: cn?.id ?? null, intl: intl?.id ?? null },
|
|
104
|
+
selected: isSite(parsed.selected) ? parsed.selected : "cn",
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function writeCache(cache: TokenCache, writeFile?: WriteFile, dir?: string): void {
|
|
109
|
+
const path = cachePath(dir)
|
|
110
|
+
const target = writeFile ?? defaultWrite(path)
|
|
111
|
+
target(path, JSON.stringify(cache, null, 2))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The currently active account for a site; callers never handle 1 vs N. */
|
|
115
|
+
export function activeAccount(cache: TokenCache, site: Site): SiteAuth | null {
|
|
116
|
+
const id = cache.activeId[site]
|
|
117
|
+
if (!id) return null
|
|
118
|
+
return cache.accounts[site].find((a) => a.id === id) ?? null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Store/replace an account for its site and make it active there. */
|
|
122
|
+
export function archive(cache: TokenCache, incoming: SiteAuth): TokenCache {
|
|
123
|
+
const site: Site = incoming.id.startsWith("intl:") ? "intl" : "cn"
|
|
124
|
+
const list = cache.accounts[site].filter((a) => a.id !== incoming.id)
|
|
125
|
+
list.push(incoming)
|
|
126
|
+
return {
|
|
127
|
+
...cache,
|
|
128
|
+
accounts: { ...cache.accounts, [site]: list },
|
|
129
|
+
activeId: { ...cache.activeId, [site]: incoming.id },
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function needsRefresh(auth: SiteAuth, now: number): boolean {
|
|
134
|
+
return now >= auth.expiresAt - 5 * 60_000
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
interface RefreshDeps {
|
|
138
|
+
fetchImpl?: typeof fetch
|
|
139
|
+
now?: () => number
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Refresh via the proprietary REST endpoint; token pair rotates. */
|
|
143
|
+
export async function refreshSite(
|
|
144
|
+
auth: SiteAuth,
|
|
145
|
+
deps: RefreshDeps = {},
|
|
146
|
+
): Promise<SiteAuth> {
|
|
147
|
+
const doFetch = deps.fetchImpl ?? fetch
|
|
148
|
+
const now = deps.now ?? Date.now
|
|
149
|
+
const url = `${auth.endpoint}/v2/plugin/auth/token/refresh`
|
|
150
|
+
const res = await doFetch(url, {
|
|
151
|
+
method: "POST",
|
|
152
|
+
headers: refreshHeaders(auth),
|
|
153
|
+
body: "{}",
|
|
154
|
+
})
|
|
155
|
+
const json = (await res.json()) as {
|
|
156
|
+
code?: number
|
|
157
|
+
msg?: string
|
|
158
|
+
data?: {
|
|
159
|
+
accessToken?: string
|
|
160
|
+
refreshToken?: string
|
|
161
|
+
expiresIn?: number
|
|
162
|
+
refreshExpiresIn?: number
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (json.code !== 0 || !json.data?.accessToken || !json.data?.refreshToken) {
|
|
166
|
+
throw new Error(`refresh failed: code=${json.code ?? "?"} msg=${json.msg ?? "?"}`)
|
|
167
|
+
}
|
|
168
|
+
const t = now()
|
|
169
|
+
return {
|
|
170
|
+
...auth,
|
|
171
|
+
accessToken: json.data.accessToken,
|
|
172
|
+
refreshToken: json.data.refreshToken,
|
|
173
|
+
expiresAt: t + (json.data.expiresIn ?? 0) * 1000,
|
|
174
|
+
refreshExpiresAt: t + (json.data.refreshExpiresIn ?? 0) * 1000,
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export interface TokenStore {
|
|
179
|
+
get(site: Site): SiteAuth | null
|
|
180
|
+
activeAccount(site: Site): SiteAuth | null
|
|
181
|
+
ensureFresh(site: Site): Promise<SiteAuth>
|
|
182
|
+
archive(auth: SiteAuth): void
|
|
183
|
+
select(site: Site): void
|
|
184
|
+
all(): TokenCache
|
|
185
|
+
/** True when the last refresh for this site failed (in-memory only). */
|
|
186
|
+
refreshFailed(site: Site): boolean
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
interface StoreDeps extends RefreshDeps {
|
|
190
|
+
fetchImpl?: typeof fetch
|
|
191
|
+
now?: () => number
|
|
192
|
+
persist?: (cache: TokenCache) => void
|
|
193
|
+
load?: () => TokenCache
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** In-memory store backed by the cache file; per-site single-flight refresh. */
|
|
197
|
+
export function createTokenStore(deps: StoreDeps = {}): TokenStore {
|
|
198
|
+
let cache = deps.load ? deps.load() : readCache()
|
|
199
|
+
const persist = deps.persist ?? ((c: TokenCache) => writeCache(c))
|
|
200
|
+
const inFlight: Partial<Record<Site, Promise<SiteAuth>>> = {}
|
|
201
|
+
const refreshErrors: Record<Site, boolean> = { cn: false, intl: false }
|
|
202
|
+
const lastRefreshAt: Partial<Record<Site, number>> = {}
|
|
203
|
+
const nowOf = deps.now ?? Date.now
|
|
204
|
+
|
|
205
|
+
const save = () => persist(cache)
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
get: (site) => activeAccount(cache, site),
|
|
209
|
+
activeAccount: (site) => activeAccount(cache, site),
|
|
210
|
+
all: () => cache,
|
|
211
|
+
archive: (auth) => {
|
|
212
|
+
cache = archive(cache, auth)
|
|
213
|
+
// A freshly stored credential (login or a successful refresh) makes any
|
|
214
|
+
// prior refresh failure stale. Clear it so the site reads as available
|
|
215
|
+
// again and the amber "needs login" dot disappears.
|
|
216
|
+
const site: Site = auth.id.startsWith("intl:") ? "intl" : "cn"
|
|
217
|
+
refreshErrors[site] = false
|
|
218
|
+
delete lastRefreshAt[site]
|
|
219
|
+
save()
|
|
220
|
+
},
|
|
221
|
+
select: (site) => {
|
|
222
|
+
if (cache.selected !== site) {
|
|
223
|
+
cache = { ...cache, selected: site }
|
|
224
|
+
save()
|
|
225
|
+
}
|
|
226
|
+
},
|
|
227
|
+
refreshFailed: (site) => refreshErrors[site],
|
|
228
|
+
ensureFresh: (site) => {
|
|
229
|
+
const current = activeAccount(cache, site)
|
|
230
|
+
if (!current) return Promise.reject(new Error(`no account for ${site}`))
|
|
231
|
+
if (!needsRefresh(current, nowOf())) return Promise.resolve(current)
|
|
232
|
+
// Cooldown: a short-TTL token that is already inside the 5-minute window
|
|
233
|
+
// must not be refreshed again on every request right after a refresh —
|
|
234
|
+
// but never hand back a token that has actually expired.
|
|
235
|
+
if (
|
|
236
|
+
lastRefreshAt[site] !== undefined &&
|
|
237
|
+
nowOf() - lastRefreshAt[site]! < 60_000 &&
|
|
238
|
+
nowOf() < current.expiresAt
|
|
239
|
+
) {
|
|
240
|
+
return Promise.resolve(current)
|
|
241
|
+
}
|
|
242
|
+
const existing = inFlight[site]
|
|
243
|
+
if (existing) return existing
|
|
244
|
+
const task = refreshSite(current, deps)
|
|
245
|
+
.then((next) => {
|
|
246
|
+
cache = archive(cache, next)
|
|
247
|
+
refreshErrors[site] = false
|
|
248
|
+
lastRefreshAt[site] = nowOf()
|
|
249
|
+
save()
|
|
250
|
+
return next
|
|
251
|
+
})
|
|
252
|
+
.catch((error) => {
|
|
253
|
+
refreshErrors[site] = true
|
|
254
|
+
throw error
|
|
255
|
+
})
|
|
256
|
+
.finally(() => {
|
|
257
|
+
delete inFlight[site]
|
|
258
|
+
})
|
|
259
|
+
inFlight[site] = task
|
|
260
|
+
return task
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|