@magpie-community/opencode-qoder-auth 0.2.49 → 0.2.50

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/README.md +19 -0
  2. package/index.mjs +112 -10
  3. package/package.json +20 -4
package/README.md CHANGED
@@ -302,6 +302,25 @@ paths, client id and protocol are the public ones:
302
302
  The hosts and reply shapes come from a real VPC account's report
303
303
  (yetone/magpie#312). This plugin has not been tried with a VPC account.
304
304
 
305
+ ## The card's name
306
+
307
+ An account signed in with a phone is shown by that phone — masked, `138****8000` — not by
308
+ its `accountId`, which is a uuid. Qoder CN's user info answers the number as `security_mobile`
309
+ (measured `13800138000`), so that is what the card takes.
310
+
311
+ QwenWork's phone accounts answer only the last four digits, as `name`, beside a synthetic
312
+ `phone_<uuid>@phone.local` email (measured): the card shows `****8000` and never that email.
313
+ An email sign-in keeps its email.
314
+
315
+ `accountId` stays the account's identity — what magpie keys the user's own name for
316
+ it, its proxy, model picks, caps and a gateway key's account list by — so it never
317
+ changes: it is what a sign-in and every renewal give back. The card's name is usage's
318
+ `user`, a field magpie shows and never keys by.
319
+
320
+ A sign-in reads the user info, and a renewal reads it again (outside the token lock),
321
+ so an account stored by an earlier version shows the phone on the card at its next
322
+ renewal. A failed read changes nothing and never costs a sign-in.
323
+
305
324
  ## QwenWork (千问办公)
306
325
 
307
326
  `QwenWork` and `QwenWork 企业版` serve Alibaba's own QwenWork (qwenwork.cn)
package/index.mjs CHANGED
@@ -375,10 +375,11 @@ async function deviceSignIn(site) {
375
375
  let email = ""
376
376
  let name = ""
377
377
  let uid = dt.user_id
378
+ let user = null
378
379
  try {
379
380
  const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token })
380
381
  if (ui.status >= 200 && ui.status < 300) {
381
- const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
382
+ user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
382
383
  ;[email, name] = [user?.email ?? "", user?.name ?? ""]
383
384
  if (site.deviceOnly) uid = String(user?.id ?? user?.user_id ?? user?.uid ?? uid ?? "") || undefined
384
385
  // a VPC poll may give the token alone: the user is then the one
@@ -393,7 +394,22 @@ async function deviceSignIn(site) {
393
394
  ...chat,
394
395
  // a VPC account is told apart from the same person's public one; a
395
396
  // device-only one is shown by name, falling back to its id
396
- accountId: site.vpc ? `${email || uid} (${site.vpc})` : site.deviceOnly ? email || uid || name || dt.user_id : email || dt.user_id,
397
+ // accountId is the account's identity in magpie (its name, proxy,
398
+ // model picks and caps all hang off it, and a gateway key keys its
399
+ // list by it), so it stays exactly what main computes: the phone is a
400
+ // separate field, shown by usage's `user`, never the identity.
401
+ accountId: site.vpc
402
+ ? `${email || uid} (${site.vpc})`
403
+ : site.deviceOnly
404
+ ? email || uid || name || dt.user_id
405
+ : email || dt.user_id,
406
+ // the card's names: the phone on its own, and what magpie shows (a
407
+ // real email first, then the phone) — never the accountId
408
+ ...(() => {
409
+ const label = phoneLabelOf(user, email, name)
410
+ const suffix = (v) => (v ? (site.vpc ? `${v} (${site.vpc})` : v) : "")
411
+ return { phoneLabel: suffix(label), cardName: suffix(realEmailOf(email) || label) }
412
+ })(),
397
413
  uid,
398
414
  email,
399
415
  name: name || dt.user_name || "",
@@ -430,9 +446,11 @@ async function patSignIn(site, pat) {
430
446
  let email = ""
431
447
  let name = ""
432
448
  let uid = ""
449
+ let user = null
433
450
  try {
434
451
  const ui = await openapi(site, "/api/v1/userinfo", { token })
435
452
  if (ui.status >= 200 && ui.status < 300) {
453
+ user = ui.json
436
454
  ;[email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""]
437
455
  uid = String(ui.json?.id ?? ui.json?.user_id ?? ui.json?.uid ?? "")
438
456
  }
@@ -446,6 +464,8 @@ async function patSignIn(site, pat) {
446
464
  // so a renewed PAT sign-in must keep naming the same account. A suffix
447
465
  // here would add a second row beside the lapsed one instead.
448
466
  accountId: email || uid,
467
+ phoneLabel: phoneLabelOf(user, email, name),
468
+ cardName: realEmailOf(email) || phoneLabelOf(user, email, name),
449
469
  uid,
450
470
  email,
451
471
  name: name || "",
@@ -1864,6 +1884,70 @@ function signed(res, renewed) {
1864
1884
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
1865
1885
  }
1866
1886
 
1887
+ // ---- the card's name ----------------------------------------------------------
1888
+ //
1889
+ // The card's name is not `accountId` (a uuid is not a name, and accountId is
1890
+ // the identity magpie keys settings by). Both phone
1891
+ // sign-ins here carry the phone somewhere in their user info: Qoder CN answers
1892
+ // `security_mobile` (measured `13800138000`), QwenWork's phone accounts answer
1893
+ // only the last four digits as `name` plus a synthetic
1894
+ // `phone_<uuid>@phone.local` email (measured).
1895
+ const PHONE_EMAIL = /^phone_[0-9a-f-]+@phone\.local$/i
1896
+
1897
+ /** A phone number as the cards show it: `0086-…`/`+86 …`/bare → `138****8000`. */
1898
+ function maskPhone(raw) {
1899
+ let digits = String(raw ?? "").replace(/\D/g, "")
1900
+ if (digits.startsWith("0086") && digits.length - 4 >= 7) digits = digits.slice(4)
1901
+ else if (digits.startsWith("86") && digits.length - 2 >= 7) digits = digits.slice(2)
1902
+ // a phone is 11 digits; a shorter run is not a number to mask
1903
+ if (digits.length < 11) return ""
1904
+ return `${digits.slice(0, 3)}****${digits.slice(-4)}`
1905
+ }
1906
+
1907
+ /**
1908
+ * What a renewal puts on the record for the card: `phoneLabel` (the phone the
1909
+ * account signs in with, `138****8000` / `****8000`) and `cardName` (a real
1910
+ * email first, then the phone) — both with the VPC suffix. It renames nothing:
1911
+ * `accountId` is the identity and never changes.
1912
+ *
1913
+ * Read from the renewed token's user info. No cache: each renewal has a new
1914
+ * token, so nothing is read twice (review #487, 6).
1915
+ */
1916
+ async function refreshedNames(site, token) {
1917
+ const key = String(token ?? "")
1918
+ if (!key) return {}
1919
+ try {
1920
+ const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: key })
1921
+ if (ui.status < 200 || ui.status >= 300) return {}
1922
+ const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
1923
+ const label = phoneLabelOf(user, user?.email, user?.name)
1924
+ const suffix = (v) => (v ? (site.vpc ? `${v} (${site.vpc})` : v) : "")
1925
+ // built as the sign-in builds it: a real email first, then the phone
1926
+ return { phoneLabel: suffix(label), cardName: suffix(realEmailOf(user?.email) || label) }
1927
+ } catch {
1928
+ return {}
1929
+ }
1930
+ }
1931
+
1932
+ /** The account's own email, when it is a real one (a synthetic phone email is not). */
1933
+ function realEmailOf(email) {
1934
+ const e = String(email ?? "").trim()
1935
+ if (!e || PHONE_EMAIL.test(e)) return ""
1936
+ return e
1937
+ }
1938
+
1939
+ /** The phone-derived part of a card's name, or "" when the account has none. */
1940
+ function phoneLabelOf(user, email, name) {
1941
+ const phone = maskPhone(user?.security_mobile ?? user?.phoneNumber ?? user?.phone ?? user?.mobile)
1942
+ if (phone) return phone
1943
+ // a synthetic phone email is never shown: its four digits are, or nothing
1944
+ if (PHONE_EMAIL.test(String(email ?? ""))) {
1945
+ const tail = String(name ?? "").trim()
1946
+ if (/^\d{4}$/.test(tail)) return `****${tail}`
1947
+ }
1948
+ return ""
1949
+ }
1950
+
1867
1951
  // changed is the fields of b that differ from a's: what auth.refresh gives.
1868
1952
  function changed(a, b) {
1869
1953
  const out = {}
@@ -2605,6 +2689,8 @@ const makePlugin = (site) => async ({ client }) => {
2605
2689
  try {
2606
2690
  const cred = await fresh(getAuth)
2607
2691
  if (renewed(cred)) signIn = "renewed"
2692
+ // the card's name: magpie takes usage's `user` for it and never as a key
2693
+ const who = cred?.cardName ? { user: cred.cardName } : {}
2608
2694
  // a site with its own usage path (QwenWork's account-context, signed
2609
2695
  // like any other call and answered with its own envelope) is read
2610
2696
  // there; a 401 rotates the device token once, as the qoder path does
@@ -2635,7 +2721,7 @@ const makePlugin = (site) => async ({ client }) => {
2635
2721
  if (site.walletsPath && ctxUser?.is_biz !== true && ctxUser?.isBiz !== true) {
2636
2722
  try { wallets = await read(token, site.walletsPath) } catch {}
2637
2723
  }
2638
- return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn }
2724
+ return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn, ...who }
2639
2725
  }
2640
2726
  // A PAT account has no device token: the usage endpoint takes the job
2641
2727
  // token the exchange gave — a live PAT account answered 200 with a
@@ -2643,7 +2729,7 @@ const makePlugin = (site) => async ({ client }) => {
2643
2729
  // no second token here to rotate and retry with.
2644
2730
  if (cred.patAuth && !cred.deviceToken) {
2645
2731
  const env = await fetchUsage(siteOf(site, cred), cred.access)
2646
- return { ...(await spareFree(cred, parseUsage(env))), signIn }
2732
+ return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who }
2647
2733
  }
2648
2734
  let env
2649
2735
  try {
@@ -2652,7 +2738,7 @@ const makePlugin = (site) => async ({ client }) => {
2652
2738
  if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
2653
2739
  env = await fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken))
2654
2740
  }
2655
- return { ...(await spareFree(cred, parseUsage(env))), signIn }
2741
+ return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who }
2656
2742
  } catch (e) {
2657
2743
  return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn }
2658
2744
  }
@@ -2904,19 +2990,35 @@ const makePlugin = (site) => async ({ client }) => {
2904
2990
  refreshLead: RENEW_LEAD,
2905
2991
  async refresh(auth) {
2906
2992
  if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined
2907
- return locked(async () => {
2993
+ const out = await locked(async () => {
2908
2994
  // a request renewed it meanwhile (or magpie hasn't saved this
2909
2995
  // hook's last answer): what that gave, not a second refresh
2910
2996
  const a = latest(auth)
2911
- if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return changed(auth, a)
2997
+ if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return { next: a, renewed: false }
2912
2998
  try {
2913
- // magpie saves what this gives
2914
- return changed(auth, { ...a, ...(await renew(a)) })
2999
+ return { next: { ...a, ...(await renew(a)) }, renewed: true }
2915
3000
  } catch (e) {
2916
3001
  if (e?.expired) throw Object.assign(new Error(e.message), { signIn: "expired" })
2917
3002
  throw e
2918
3003
  }
2919
3004
  })
3005
+ const fields = changed(auth, out.next)
3006
+ if (!out.renewed) return fields
3007
+ // The name is read outside the lock: this lock is the plugin's, shared
3008
+ // by every account, and a user-info call may take 20 seconds — a chat
3009
+ // from another account must not wait on it (review #487, C). The
3010
+ // account's own site, too: a public one would send an enterprise token
3011
+ // to the public hosts (1), and the suffix must match the sign-in (2).
3012
+ try {
3013
+ const s = siteOf(site, out.next)
3014
+ const { phoneLabel, cardName } = await refreshedNames(s, out.next.access)
3015
+ const extra = {}
3016
+ if (phoneLabel) extra.phoneLabel = phoneLabel
3017
+ if (cardName) extra.cardName = cardName
3018
+ return Object.keys(extra).length ? { ...fields, ...extra } : fields
3019
+ } catch {
3020
+ return fields
3021
+ }
2920
3022
  },
2921
3023
  async loader(getAuth) {
2922
3024
  const a = await getAuth()
@@ -3125,4 +3227,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
3125
3227
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
3126
3228
 
3127
3229
  // for tests
3128
- export const _internal = { chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
3230
+ export const _internal = { maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
package/package.json CHANGED
@@ -1,12 +1,28 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.49",
3
+ "version": "0.2.50",
4
4
  "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": "./index.mjs",
8
- "files": ["index.mjs", "README.md", "LICENSE-CLIProxyAPI"],
9
- "keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn", "qwenwork", "千问办公"],
8
+ "files": [
9
+ "index.mjs",
10
+ "README.md",
11
+ "LICENSE-CLIProxyAPI"
12
+ ],
13
+ "keywords": [
14
+ "opencode",
15
+ "opencode-plugin",
16
+ "magpie",
17
+ "qoder",
18
+ "qoder-cn",
19
+ "qwenwork",
20
+ "千问办公"
21
+ ],
10
22
  "license": "MIT",
11
- "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/qoder" }
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/magpie-community/plugins.git",
26
+ "directory": "packages/qoder"
27
+ }
12
28
  }