@magpie-community/opencode-zcode-auth 0.1.51 → 0.1.52

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 +11 -0
  2. package/index.mjs +101 -8
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -323,6 +323,17 @@ the body's code, not the HTTP status:
323
323
  first: six accounts all answered 1004 under 3.16.3's header, and four
324
324
  of them claimed with code 0 under 3.17.2's, one night, with nothing
325
325
  else changed;
326
+ - HTTP 429 "Too Many Requests", or a body code 3002 "请求过于频繁": *failed*,
327
+ and the account is then **held in the plugin**: until the wait is over, a
328
+ check-in answers that same failed (`until` and all) and asks ZCode nothing.
329
+ magpie asks a failed again after 30 minutes of its own whatever `until`
330
+ says, so the hold has to live here (magpie from v0.1.3165 honors a failed's
331
+ `until` itself; older versions lean on this hold). A `Retry-After` ZCode
332
+ sent is honored up to six hours; without one the account's own wait doubles
333
+ from half an hour, and a read that comes through forgets it. The hold
334
+ belongs to one account and lives in memory — a magpie restart forgets it.
335
+ (11-04, #503: one owner read 180 of them over four days at magpie's
336
+ 30-minute retry, across several accounts.);
326
337
  - anything else, an HTTP error without a code, or a reply that isn't
327
338
  JSON: *failed*, which magpie asks again later that day. It is never
328
339
  taken as claimed, and a failed claim leaves the account's sign-in
package/index.mjs CHANGED
@@ -96,8 +96,11 @@ async function call(method, url, { auth, body, headers, device, signal } = {}) {
96
96
  } catch {}
97
97
  const code = env?.code == null ? "" : String(env.code)
98
98
  if (!res.ok) {
99
- if (env?.msg) throw new ZError(code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`, res.status)
100
- throw new ZError(STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim(), res.status)
99
+ const said = env?.msg ? (code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`) : (STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim())
100
+ const err = new ZError(said, res.status)
101
+ err.code = Number(code) || 0 // 3002 and the like: so a caller can tell a rate limit from a failure
102
+ err.retryAfterMs = retryAfterMs(res) // 0 unless the reply carried a Retry-After
103
+ throw err
101
104
  }
102
105
  if (!env || typeof env !== "object") throw new ZError("not JSON", res.status)
103
106
  if (code && code !== "0" && code !== "200") throw new ZError(env.msg || `error ${code}`, res.status)
@@ -715,6 +718,62 @@ const CAPTCHA = 3007
715
718
  // 1004 under 3.16.3's header, and four of them claimed with code 0 under
716
719
  // 3.17.2's, one night, with nothing else changed).
717
720
  const NOT_ELIGIBLE = 1004
721
+ // RATE_LIMITED is Z.ai's "请求过于频繁" body code, its answer (with HTTP
722
+ // 429) to a client that asked too often. #503 (MiniFullC, 11-04) read 180
723
+ // "gift plans to claim: Too Many Requests" over four days at magpie's
724
+ // 30-minute retry, so asking again the same half hour keeps the limit on.
725
+ // magpie asks a failed again once retryAfter() has passed, whatever the
726
+ // answer's `until` says (the contract reads `until` as when an answer
727
+ // stops standing, not as the earliest time to ask again), so the account
728
+ // is held here instead: while the wait lasts, claimDaily answers the same
729
+ // failed again, `until` and all, and asks ZCode nothing. A Retry-After
730
+ // ZCode sent is honored up to RATE_LIMIT_MAX_MS; without one the
731
+ // account's own wait doubles from RECHECK_MS, and a read that comes
732
+ // through forgets it.
733
+ const RATE_LIMITED = 3002
734
+ const RATE_LIMIT_MAX_MS = 6 * 60 * 60_000
735
+ const rateWait = new Map() // s.key -> { ms, until, message }: the hold this account is under
736
+ // resetRateWait is for tests: it forgets the holds, and with `expire` it
737
+ // back-dates them, standing where the wait has passed. The plugin itself
738
+ // forgets a hold by reading through or by waiting it out, never by calling
739
+ // this.
740
+ export function resetRateWait(expire = false) {
741
+ if (!expire) {
742
+ rateWait.clear()
743
+ return
744
+ }
745
+ for (const [k, h] of rateWait) rateWait.set(k, { ...h, until: new Date(Date.now() - 1).toISOString() })
746
+ }
747
+ // holdKey names the account a wait belongs to. stateOf gives key: "" to a
748
+ // sign-in that has a jwt and no API key — the Start-Plan-only sign-ins
749
+ // that claim gift plans, #503's case — so the key alone would put every
750
+ // one of them under a single hold, and one account's 429 would answer for
751
+ // all of them. The jwt tells them apart; a renewed token starting its own
752
+ // wait is fine.
753
+ const holdKey = (s) => s.key || s.jwt
754
+ // retryAfterMs is a Retry-After header, in seconds or as an HTTP date, in
755
+ // ms; 0 when there is none or it doesn't read.
756
+ function retryAfterMs(res) {
757
+ const v = first(res?.headers?.get?.("retry-after"))
758
+ if (!v) return 0
759
+ const secs = Number(v)
760
+ if (Number.isFinite(secs) && secs > 0) return secs * 1000
761
+ const at = Date.parse(v)
762
+ return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 0
763
+ }
764
+ // noteRateLimit remembers the wait this account is under, with the failed
765
+ // that wait answers with, and says when it ends: a Retry-After ZCode sent
766
+ // is taken as it is, up to the cap; without one the wait doubles from
767
+ // RECHECK_MS (and never falls below it), so a client ZCode keeps turning
768
+ // away asks less and less.
769
+ function noteRateLimit(key, saidMs, message) {
770
+ const last = rateWait.get(key)?.ms ?? 0
771
+ const want = saidMs > 0 ? saidMs : Math.max(RECHECK_MS, last * 2)
772
+ const ms = Math.min(RATE_LIMIT_MAX_MS, want)
773
+ const until = new Date(Date.now() + ms).toISOString()
774
+ rateWait.set(key, { ms, until, message })
775
+ return until
776
+ }
718
777
  const CAPTCHA_WORDS = /captcha/i
719
778
 
720
779
  // The marketing feed and the claim are gated on the client's version:
@@ -747,6 +806,8 @@ async function claimOne(s, planID) {
747
806
  } catch {}
748
807
  const code = env && typeof env === "object" && env.code != null && String(env.code).trim() !== "" ? Number(env.code) : NaN
749
808
  const msg = typeof env?.msg === "string" ? env.msg : ""
809
+ // a rate limit is no claim: it is said as one, and carries how long to wait
810
+ if (res.status === 429 || code === RATE_LIMITED) return { outcome: "failed", why: `${msg || STATUS_TEXT[429]} (HTTP ${res.status}${Number.isFinite(code) ? `, code ${code}` : ""})`, rate: retryAfterMs(res) }
750
811
  if (code === CAPTCHA || CAPTCHA_WORDS.test(msg)) return { outcome: "captcha", why: msg || `code ${code}` }
751
812
  if (code === CLAIMED_ALREADY) return { outcome: "done" }
752
813
  if (code === NOT_ELIGIBLE) return { outcome: "ineligible", why: msg || `code ${code}` }
@@ -829,12 +890,14 @@ async function toClaim(s) {
829
890
  d = await call("GET", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { auth: "Bearer " + s.jwt, device: s.device, headers: marketingHeaders() })
830
891
  } catch (e) {
831
892
  unread.push(`gift plans to claim: ${e?.message ?? String(e)}`)
832
- return { plans, unread }
893
+ // rate is the ms ZCode asked to wait (0 when it sent no Retry-After),
894
+ // null when this was not a rate limit at all
895
+ return { plans, unread, rate: e?.status === 429 || e?.code === RATE_LIMITED ? (e.retryAfterMs || 0) : null }
833
896
  }
834
897
  const got = touchPlans(d)
835
898
  if (!got) unread.push("gift plans to claim: the plan list doesn't read")
836
899
  else got.forEach(add)
837
- return { plans, unread }
900
+ return { plans, unread, rate: null }
838
901
  }
839
902
 
840
903
  // RECHECK is how long an "nothing to claim" stands before magpie's loop
@@ -863,7 +926,16 @@ const recheck = () => new Date(Date.now() + RECHECK_MS).toISOString()
863
926
  // captcha for one (it is claimed in the ZCode app), ineligible when
864
927
  // ZCode is not offering one at that moment (code 1004, read again later
865
928
  // in the day), failed when a list
866
- // or a claim can't be read. A failed one is asked again later in the
929
+ // or a claim can't be read. A rate-limited read (HTTP 429, or code 3002)
930
+ // is not asked again either: the account is held here until the wait ends
931
+ // (a Retry-After ZCode sent, else the account's own wait doubling from
932
+ // RECHECK_MS, out to RATE_LIMIT_MAX_MS — see RATE_LIMITED), and every ask
933
+ // inside the wait answers the failed it already gave, without a request.
934
+ // The hold belongs to one account (`s.key || s.jwt`) and lives in this
935
+ // process's memory alone: a magpie restart forgets it. magpie from
936
+ // v0.1.3165 honors a failed's `until` itself; older versions wait for
937
+ // this hold, which is why it stays.
938
+ // A failed one is asked again later in the
867
939
  // day, when a plan claimed now answers 1003. An inactive stands only
868
940
  // until RECHECK_MS from now, so a plan dropped into the feed later in
869
941
  // the day is still claimed; the other settled answers stand for the day
@@ -872,9 +944,26 @@ const recheck = () => new Date(Date.now() + RECHECK_MS).toISOString()
872
944
  async function claimDaily(s) {
873
945
  if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" }
874
946
  if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED }
875
- const { plans, unread } = await toClaim(s)
876
- if (!plans.length && unread.length) return { outcome: "failed", message: unread.join("; ") }
877
- if (!plans.length) return { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() }
947
+ // a rate limit this account is still under: the same failed again, and
948
+ // not one request (magpie asks a failed again after 30 minutes of its
949
+ // own, so holding it is the plugin's job — see RATE_LIMITED)
950
+ const held = rateWait.get(holdKey(s))
951
+ if (held && Date.now() < Date.parse(held.until)) return { outcome: "failed", message: held.message, until: held.until }
952
+ const { plans, unread, rate = null } = await toClaim(s)
953
+ // a rate-limited read: held here until the wait is over
954
+ if (rate !== null) {
955
+ const message = unread.join("; ") || "ZCode rate limited this account"
956
+ return { outcome: "failed", message, until: noteRateLimit(holdKey(s), rate, message) }
957
+ }
958
+ // the feed answered and no claim is read: the wait is over. It is not
959
+ // forgotten before the claims below, so a claim ZCode keeps limiting
960
+ // waits longer each time (see noteRateLimit)
961
+ if (!plans.length) {
962
+ rateWait.delete(holdKey(s))
963
+ return unread.length
964
+ ? { outcome: "failed", message: unread.join("; ") }
965
+ : { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() }
966
+ }
878
967
  const got = []
879
968
  for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) })
880
969
  const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name)
@@ -888,6 +977,10 @@ async function claimDaily(s) {
888
977
  ].filter(Boolean).join("; ")
889
978
  // a plan claimed now is used by the next request, not ten minutes on
890
979
  if (claimed.length) routes.delete(s.key + "\0" + s.jwt)
980
+ // a claim ZCode rate limited: the plan may still be there, later
981
+ const limitedClaim = got.find((g) => g.rate !== undefined)
982
+ if (limitedClaim) return { outcome: "failed", message: said, until: noteRateLimit(holdKey(s), limitedClaim.rate, said) }
983
+ rateWait.delete(holdKey(s)) // nothing in this check-in was rate limited: the wait is over
891
984
  // a list that didn't read may hold a plan not claimed: asked again
892
985
  if (unread.length || got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
893
986
  if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.51",
3
+ "version": "0.1.52",
4
4
  "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan, and claims its gift plans daily",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",