@magpie-community/opencode-factory-auth 0.1.2 → 0.1.4

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 (2) hide show
  1. package/index.mjs +57 -38
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -123,15 +123,6 @@ function expiry(access) {
123
123
  return typeof exp === "number" && exp > 0 ? Math.floor(exp) * 1000 : 0
124
124
  }
125
125
 
126
- function apiError(text, fallback) {
127
- try {
128
- const j = JSON.parse(text)
129
- const m = j?.error?.message ?? j?.error_description ?? j?.message ?? j?.detail ?? (typeof j?.error === "string" ? j.error : "")
130
- if (m) return String(m)
131
- } catch {}
132
- return text.trim().slice(0, 300) || fallback
133
- }
134
-
135
126
  // workos posts a form to WorkOS: the answer and its status.
136
127
  async function workos(path, form, signal) {
137
128
  const res = await fetch(WORKOS + path, {
@@ -152,7 +143,7 @@ async function authenticate(form, signal) {
152
143
  t = JSON.parse(text) ?? {}
153
144
  } catch {}
154
145
  t.status = status
155
- if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " + apiError(text, String(status)))
146
+ if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " + vendorError(text, STATUS_CODES[status] ?? ""))
156
147
  return t
157
148
  }
158
149
 
@@ -198,7 +189,7 @@ async function factoryGet(c, path) {
198
189
  factoryHeaders(h, c)
199
190
  const res = await fetch(base(c) + path, { headers: h, signal: AbortSignal.timeout(30_000) })
200
191
  const text = await res.text()
201
- if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + apiError(text, String(res.status)))
192
+ if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status)))
202
193
  return JSON.parse(text)
203
194
  }
204
195
 
@@ -217,7 +208,7 @@ async function whoami(c, signal) {
217
208
  if (c.activeOrganizationId) h["X-Factory-Org-Id"] = c.activeOrganizationId
218
209
  const res = await fetch(base(c) + "/api/cli/whoami", { headers: h, signal: signal ?? AbortSignal.timeout(10_000) })
219
210
  const text = await res.text()
220
- if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + apiError(text, String(res.status)))
211
+ if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status)))
221
212
  return JSON.parse(text) ?? {}
222
213
  }
223
214
 
@@ -268,6 +259,15 @@ function errorReply(url, status, type, message, headers = new Headers()) {
268
259
  return new Response(JSON.stringify(body), { status, headers })
269
260
  }
270
261
 
262
+ // said is an answer with magpie's X-Magpie-Sign-In, which tells what it
263
+ // means for the account's sign-in whatever its status: "expired" marks it
264
+ // lapsed, "kept" leaves it be. magpie takes it off before the agent sees it.
265
+ function said(res, v) {
266
+ const h = new Headers(res.headers)
267
+ h.set("X-Magpie-Sign-In", v)
268
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h })
269
+ }
270
+
271
271
  // ---- sign-in ----------------------------------------------------------------
272
272
 
273
273
  // signedInWith is the account WorkOS just signed in, as droid keeps it: a
@@ -319,7 +319,7 @@ async function signedInWith(t) {
319
319
 
320
320
  async function deviceSignIn() {
321
321
  const { text, status } = await workos("/authorize/device", { client_id: CLIENT_ID })
322
- if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " + apiError(text, String(status)))
322
+ if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " + vendorError(text, STATUS_CODES[status] ?? ""))
323
323
  const dc = JSON.parse(text)
324
324
  if (!dc.device_code || !dc.user_code) throw new Error("Factory's sign-in gave no device code")
325
325
  let interval = Math.max(dc.interval ?? 0, 1) * 1000
@@ -502,8 +502,9 @@ export const FactoryAuthPlugin = async ({ client }) => {
502
502
  return c
503
503
  }
504
504
 
505
- // fresh is a live token, renewed near its end.
506
- const fresh = () =>
505
+ // fresh is a live token, renewed near its end; renewed is told when
506
+ // it was, the built-in's clearing of the account's lapse.
507
+ const fresh = (renewed) =>
507
508
  locked(async () => {
508
509
  const c = await current()
509
510
  if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
@@ -523,6 +524,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
523
524
  await reconcile(c)
524
525
  ask(c)
525
526
  await save(c)
527
+ renewed?.()
526
528
  return c
527
529
  })
528
530
 
@@ -530,8 +532,9 @@ export const FactoryAuthPlugin = async ({ client }) => {
530
532
  // can't reach is left off and whoami asked again without it; with
531
533
  // no header sent, the token is put in the first org /api/cli/org
532
534
  // lists. Any other 403 to an account that sent no org asks whoami
533
- // for one. True when the request is worth sending again.
534
- const mendOrg = (status, text) =>
535
+ // for one. True when the request is worth sending again; renewed is
536
+ // told when the token was.
537
+ const mendOrg = (status, text, renewed) =>
535
538
  locked(async () => {
536
539
  if (status !== 403) return false
537
540
  const isOrg = orgRefused(status, text)
@@ -570,14 +573,20 @@ export const FactoryAuthPlugin = async ({ client }) => {
570
573
  c.orgId = org
571
574
  if (t.refresh_token) c.refresh = t.refresh_token
572
575
  await save(c)
576
+ renewed?.()
573
577
  return true
574
578
  })
575
579
 
576
580
  // usage is the account's limits, asked once more when Factory refused
577
- // an org that was put right
581
+ // an org that was put right. signIn is what the read did to the
582
+ // built-in's lapse mark: a renewal took it off whatever came after, a
583
+ // refused one put it on, a read that renewed nothing left it be (a
584
+ // clean read too)
578
585
  const usage = async () => {
586
+ let signIn = "kept"
587
+ const onRenew = () => (signIn = "renewed")
579
588
  const limits = async () => {
580
- const c = await fresh()
589
+ const c = await fresh(onRenew)
581
590
  const h = new Headers({ Accept: "application/json" })
582
591
  factoryHeaders(h, c)
583
592
  const res = await fetch(base(c) + "/api/billing/limits", { headers: h, signal: AbortSignal.timeout(15_000) })
@@ -590,13 +599,14 @@ export const FactoryAuthPlugin = async ({ client }) => {
590
599
  try {
591
600
  l = await limits()
592
601
  } catch (e) {
593
- if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body).catch(() => false)))) throw e
602
+ if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body, onRenew).catch(() => false)))) throw e
594
603
  l = await limits()
595
604
  }
596
- if (!l?.limits?.standard) return { error: "Factory: the account reported no limits" }
597
- return { windows: limitWindows(l) }
605
+ if (!l?.limits?.standard) return { error: "Factory: the account reported no limits", signIn }
606
+ return { windows: limitWindows(l), signIn }
598
607
  } catch (e) {
599
- return { error: e?.message ?? String(e) }
608
+ if (e?.lapsed) signIn = "expired"
609
+ return { error: e?.message ?? String(e), signIn }
600
610
  }
601
611
  }
602
612
 
@@ -634,8 +644,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
634
644
 
635
645
  const { fresh, mendOrg } = account(getAuth)
636
646
 
637
- const send = async (input, init, body) => {
638
- const c = await fresh()
647
+ const send = async (input, init, body, renewed) => {
648
+ const c = await fresh(renewed)
639
649
  let url = input instanceof Request ? input.url : String(input)
640
650
  // an EU org is served from Factory's EU region, an on-prem one
641
651
  // from its own host: the request goes there
@@ -665,24 +675,33 @@ export const FactoryAuthPlugin = async ({ client }) => {
665
675
  if (body == null && input instanceof Request && input.body) body = new Uint8Array(await input.arrayBuffer())
666
676
  if (body instanceof ReadableStream) body = new Uint8Array(await new Response(body).arrayBuffer())
667
677
  const url = input instanceof Request ? input.url : String(input)
678
+ // the built-in takes an account's lapse off when it renews the
679
+ // token, whatever the request then meets, and never for an
680
+ // answer: a 401 of Factory's leaves it be, and so does a success
681
+ // with no renewal on the way
682
+ let renewed = false
683
+ const onRenew = () => (renewed = true)
684
+ const answer = (res) => said(res, renewed ? "renewed" : "kept")
668
685
  let res
669
686
  try {
670
- res = await send(input, init, body)
687
+ res = await send(input, init, body, onRenew)
688
+ if (res.status !== 403) return answer(res)
689
+ let text = await res.text()
690
+ if (await mendOrg(res.status, text, onRenew).catch(() => false)) {
691
+ res = await send(input, init, body, onRenew)
692
+ if (res.status !== 403) return answer(res)
693
+ text = await res.text()
694
+ }
695
+ const why = explain(res.status, text)
696
+ // the refusal, then what to do about it, as provider.Explain joins them
697
+ const msg = `${vendorError(text, statusLine(res.status))} — ${why}`
698
+ return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers)))
671
699
  } catch (e) {
672
- // Factory refused to renew the sign-in: the account's own 401
673
- if (e?.lapsed) return errorReply(url, 401, "authentication_error", e.message)
700
+ // Factory refused to renew the sign-in: the built-in failed the
701
+ // request (magpie's 502) and marked the account lapsed
702
+ if (e?.lapsed) return said(errorReply(url, 502, "api_error", e.message), "expired")
674
703
  throw e
675
704
  }
676
- if (res.status !== 403) return res
677
- let text = await res.text()
678
- if (await mendOrg(res.status, text).catch(() => false)) {
679
- res = await send(input, init, body)
680
- if (res.status !== 403) return res
681
- text = await res.text()
682
- }
683
- const why = explain(res.status, text)
684
- const msg = `${apiError(text, "Forbidden")}: ${why}`
685
- return errorReply(url, res.status, "permission_error", msg, new Headers(res.headers))
686
705
  },
687
706
  }
688
707
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",