@magpie-community/opencode-factory-auth 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.
Files changed (3) hide show
  1. package/README.md +58 -0
  2. package/index.mjs +545 -0
  3. package/package.json +10 -0
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # @magpie-community/opencode-factory-auth
2
+
3
+ Signs in to a [Factory](https://factory.ai) (Droid) subscription and sends
4
+ model requests to Factory's API the way `droid` sends them. Provider id:
5
+ `factory`.
6
+
7
+ ## Sign-in
8
+
9
+ - **Sign in with Factory (device code).** This is WorkOS's device flow
10
+ under droid's own client. The browser opens Factory's page with the code
11
+ filled in. Confirm it there, and the plugin picks up the tokens.
12
+ - **Organization.** A token that isn't in an organization yet is put in
13
+ the first one your account belongs to.
14
+ - **Whoami.** The plugin asks `whoami` for your active organization, its
15
+ region (EU orgs go to `api.eu.factory.ai`) and any host of the org's
16
+ own. Every request then carries them, as droid's do.
17
+
18
+ ## Where the sign-in is kept
19
+
20
+ The sign-in is kept wherever the host keeps provider sign-ins:
21
+
22
+ - OpenCode: `~/.local/share/opencode/auth.json`
23
+ - magpie: `plugin-auth.json`
24
+
25
+ It holds WorkOS's access and refresh tokens, with the organization,
26
+ region and host.
27
+
28
+ **Refreshing.** The access token is renewed two minutes before it lapses.
29
+ WorkOS rotates the refresh token, so the plugin never runs two refreshes
30
+ at once.
31
+
32
+ **Refusals.** If Factory refuses the organization a request names, the
33
+ plugin asks `whoami` again and resends the request once. If the refusal
34
+ stands, the error says what to check.
35
+
36
+ ## Models
37
+
38
+ Each model is served on the one API droid uses for it:
39
+
40
+ | API | Models |
41
+ |---|---|
42
+ | Anthropic Messages (`/api/llm/a`) | Fable 5.1, Fable 5, Opus 5.5, Opus 5, Opus 4.8, Sonnet 5.5, Sonnet 5, Sonnet 4.6, Haiku 4.5, MiniMax M2.7 |
43
+ | OpenAI Responses (`/api/llm/o/v1`) | GPT-6 Sol/Astra/Luna, GPT-5.6 Sol/Terra/Luna, GPT-5.5, GPT-5.4, GPT-5.3-Codex, Grok 4.7, Grok 4.6 |
44
+ | Chat completions (`/api/llm/o/v1`) | GLM-5.3, GLM-5.3-Flash, GLM-5.2, Kimi K3, DeepSeek V4.1 Flash, Qwen3.8 Max, MiniMax M3, Mistral Medium 3.5, Nemotron 3 Ultra |
45
+
46
+ Reasoning efforts are the variants droid offers for each model.
47
+
48
+ The list is not included:
49
+
50
+ - Gemini, which Factory sends on a route of its own.
51
+ - auto, which droid picks on the client side.
52
+
53
+ ## Use
54
+
55
+ ```sh
56
+ magpie plugin add @magpie-community/opencode-factory-auth
57
+ magpie plugin login factory
58
+ ```
package/index.mjs ADDED
@@ -0,0 +1,545 @@
1
+ // Factory (Droid) subscriptions for OpenCode and magpie: WorkOS's device
2
+ // flow under droid's client, as `droid` signs in, and each model request
3
+ // sent to Factory's API with the headers droid sends. Ported from magpie's
4
+ // built-in Factory account (internal/provider/factory*.go).
5
+
6
+ const PROVIDER = "factory"
7
+
8
+ const WORKOS = "https://api.workos.com/user_management"
9
+ const API = "https://api.factory.ai"
10
+ const API_EU = "https://api.eu.factory.ai"
11
+ // droid's WorkOS client, production
12
+ const CLIENT_ID = "client_01HNM792M5G5G1A2THWPXKFMXB"
13
+ // the droid release the requests say they are
14
+ const VERSION = "0.229.0"
15
+ // how long before an access token lapses it is renewed (droid: a minute)
16
+ const REFRESH_LEAD = 2 * 60 * 1000
17
+ // how long an account whose whoami failed waits before asking again
18
+ const ASK_AGAIN = 10 * 60 * 1000
19
+
20
+ const ANTHROPIC = { npm: "@ai-sdk/anthropic", api: API + "/api/llm/a/v1" }
21
+ const RESPONSES = { npm: "@ai-sdk/openai", api: API + "/api/llm/o/v1" }
22
+ const CHAT = { npm: "@ai-sdk/openai-compatible", api: API + "/api/llm/o/v1" }
23
+
24
+ const E5 = ["low", "medium", "high", "xhigh", "max"]
25
+ const E6 = ["none", "low", "medium", "high", "xhigh", "max"]
26
+ const E4 = ["low", "medium", "high", "xhigh"]
27
+
28
+ // The models droid's /model picker offers, less Gemini's (sent on a route of
29
+ // Factory's own) and auto (droid picks it client side): id, name, the wire
30
+ // droid sends it on, the vendor it names in x-api-provider, context, output,
31
+ // reasoning efforts, images.
32
+ const MODELS = [
33
+ ["claude-fable-5.1", "Fable 5.1", ANTHROPIC, "anthropic", 867000, 128000, E5, true],
34
+ ["claude-fable-5", "Fable 5", ANTHROPIC, "anthropic", 867000, 128000, E5, true],
35
+ ["claude-opus-5-5", "Opus 5.5", ANTHROPIC, "anthropic", 872000, 128000, E5, true],
36
+ ["claude-opus-5", "Opus 5", ANTHROPIC, "anthropic", 867000, 128000, E5, true],
37
+ ["claude-opus-4-8", "Opus 4.8", ANTHROPIC, "anthropic", 867000, 128000, E5, true],
38
+ ["claude-sonnet-5-5", "Sonnet 5.5", ANTHROPIC, "anthropic", 872000, 128000, E5, true],
39
+ ["claude-sonnet-5", "Sonnet 5", ANTHROPIC, "anthropic", 872000, 128000, E5, true],
40
+ ["claude-sonnet-4-6", "Sonnet 4.6", ANTHROPIC, "anthropic", 931000, 64000, ["low", "medium", "high", "max"], true],
41
+ ["claude-haiku-4-5-20251001", "Haiku 4.5", ANTHROPIC, "anthropic", 0, 0, ["low", "medium", "high"], true],
42
+ ["gpt-6-sol", "GPT-6 Sol", RESPONSES, "openai", 1050000, 128000, E6, true],
43
+ ["gpt-6-astra", "GPT-6 Astra", RESPONSES, "openai", 1050000, 128000, E5, true],
44
+ ["gpt-6-luna", "GPT-6 Luna", RESPONSES, "openai", 1050000, 128000, E6, true],
45
+ ["gpt-5.6-sol", "GPT-5.6 Sol", RESPONSES, "openai", 1050000, 128000, E6, true],
46
+ ["gpt-5.6-terra", "GPT-5.6 Terra", RESPONSES, "openai", 1050000, 128000, E6, true],
47
+ ["gpt-5.6-luna", "GPT-5.6 Luna", RESPONSES, "openai", 1050000, 128000, E6, true],
48
+ ["gpt-5.5", "GPT-5.5", RESPONSES, "openai", 1050000, 128000, E4, true],
49
+ ["gpt-5.4", "GPT-5.4", RESPONSES, "openai", 1050000, 128000, E4, true],
50
+ ["gpt-5.3-codex", "GPT-5.3-Codex", RESPONSES, "openai", 400000, 128000, E4, true],
51
+ ["grok-4.7", "Grok 4.7", RESPONSES, "xai", 500000, 63356, E4, true],
52
+ ["grok-4.6", "Grok 4.6", RESPONSES, "xai", 200000, 63356, E4, true],
53
+ ["glm-5.3", "GLM-5.3", CHAT, "fireworks", 1040000, 131072, ["low", "high", "max"], false],
54
+ ["glm-5.3-flash", "GLM-5.3-Flash", CHAT, "fireworks", 1048576, 131072, ["low", "high", "max"], false],
55
+ ["glm-5.2", "GLM-5.2", CHAT, "baseten", 1040000, 131072, ["high", "max"], false],
56
+ ["kimi-k3", "Kimi K3", CHAT, "fireworks", 262144, 65536, ["low", "high", "max"], true],
57
+ ["deepseek-v4.1-flash", "DeepSeek V4.1 Flash", CHAT, "fireworks", 1040000, 131072, ["low", "high", "max"], true],
58
+ ["qwen3.8-max", "Qwen3.8 Max", CHAT, "fireworks", 262144, 131072, ["low", "medium", "xhigh"], false],
59
+ ["minimax-m3", "MiniMax M3", CHAT, "fireworks", 512000, 64000, ["high"], true],
60
+ ["minimax-m2.7", "MiniMax M2.7", ANTHROPIC, "fireworks", 196600, 64000, ["high"], false],
61
+ ["mistral-medium-3.5", "Mistral Medium 3.5", CHAT, "mistral", 256000, 64000, ["high"], true],
62
+ ["nemotron-3-ultra", "Nemotron 3 Ultra", CHAT, "baseten", 202000, 65536, ["high"], false],
63
+ ].map(([id, name, wire, upstream, context, output, efforts, images]) => ({ id, name, wire, upstream, context, output, efforts, images }))
64
+
65
+ const byId = new Map(MODELS.map((m) => [m.id, m]))
66
+
67
+ // variant is what the AI SDK package a model is on is given for an effort.
68
+ function variant(npm, effort) {
69
+ if (npm === ANTHROPIC.npm) return { effort }
70
+ return { reasoningEffort: effort }
71
+ }
72
+
73
+ function configModels() {
74
+ const out = {}
75
+ for (const m of MODELS) {
76
+ out[m.id] = {
77
+ id: m.id,
78
+ name: m.name,
79
+ provider: { npm: m.wire.npm, api: m.wire.api },
80
+ reasoning: m.efforts.length > 0,
81
+ attachment: m.images,
82
+ tool_call: true,
83
+ temperature: true,
84
+ modalities: { input: m.images ? ["text", "image"] : ["text"], output: ["text"] },
85
+ cost: { input: 0, output: 0 },
86
+ limit: { context: m.context, output: m.output },
87
+ variants: Object.fromEntries(m.efforts.map((e) => [e, variant(m.wire.npm, e)])),
88
+ }
89
+ }
90
+ return out
91
+ }
92
+
93
+ // ---- tokens -----------------------------------------------------------------
94
+
95
+ class FactoryStatus extends Error {
96
+ constructor(code, message) {
97
+ super(message)
98
+ this.code = code
99
+ }
100
+ }
101
+
102
+ // refused is WorkOS turning the refresh token away for good: any 4xx but a
103
+ // rate limit, as droid reads it.
104
+ const refused = (e) => e instanceof FactoryStatus && e.code >= 400 && e.code < 500 && e.code !== 429
105
+
106
+ function claims(jwt) {
107
+ try {
108
+ const part = String(jwt ?? "").split(".")[1]
109
+ return JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8")) ?? {}
110
+ } catch {
111
+ return {}
112
+ }
113
+ }
114
+
115
+ const claim = (c, k) => (typeof c[k] === "string" ? c[k] : "")
116
+
117
+ // expiry is when an access token lapses, from its exp; 0 when it doesn't say.
118
+ function expiry(access) {
119
+ const exp = claims(access).exp
120
+ return typeof exp === "number" && exp > 0 ? Math.floor(exp) * 1000 : 0
121
+ }
122
+
123
+ function apiError(text, fallback) {
124
+ try {
125
+ const j = JSON.parse(text)
126
+ const m = j?.error?.message ?? j?.error_description ?? j?.message ?? j?.detail ?? (typeof j?.error === "string" ? j.error : "")
127
+ if (m) return String(m)
128
+ } catch {}
129
+ return text.trim().slice(0, 300) || fallback
130
+ }
131
+
132
+ // workos posts a form to WorkOS: the answer and its status.
133
+ async function workos(path, form, signal) {
134
+ const res = await fetch(WORKOS + path, {
135
+ method: "POST",
136
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
137
+ body: new URLSearchParams(form).toString(),
138
+ signal: signal ?? AbortSignal.timeout(30_000),
139
+ })
140
+ return { text: await res.text(), status: res.status }
141
+ }
142
+
143
+ // authenticate asks WorkOS for tokens. A 400 carrying an OAuth error is an
144
+ // answer, not a failure: the device flow's polls are told to wait so.
145
+ async function authenticate(form, signal) {
146
+ const { text, status } = await workos("/authenticate", form, signal)
147
+ let t = {}
148
+ try {
149
+ t = JSON.parse(text) ?? {}
150
+ } catch {}
151
+ t.status = status
152
+ if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " + apiError(text, String(status)))
153
+ return t
154
+ }
155
+
156
+ // renew trades a refresh token for a new pair, in the WorkOS org when one is
157
+ // named (droid's way of putting a token that names no org in one); droid's
158
+ // routine refresh names none, and WorkOS keeps the org.
159
+ async function renew(refresh, org) {
160
+ const form = { grant_type: "refresh_token", refresh_token: refresh, client_id: CLIENT_ID }
161
+ if (org) form.organization_id = org
162
+ const t = await authenticate(form, AbortSignal.timeout(20_000))
163
+ if (t.error) throw new FactoryStatus(t.status, "Factory: " + `${t.error} ${t.error_description ?? ""}`.trim())
164
+ if (!t.access_token) throw new Error("Factory: the refresh gave no access token")
165
+ return t
166
+ }
167
+
168
+ // ---- Factory's API ------------------------------------------------------------
169
+
170
+ // base is the Factory API the account's org is served from.
171
+ const base = (c) => (c.region === "eu" ? API_EU : API)
172
+
173
+ // llmBase is where the account's model requests go: the org's own host when
174
+ // whoami named one, else its region's API.
175
+ function llmBase(c) {
176
+ if (c.premBaseHost) {
177
+ const p = c.premBaseHost.replace(/\/+$/, "")
178
+ return p.includes("://") ? p : "https://" + p
179
+ }
180
+ return base(c)
181
+ }
182
+
183
+ // factoryHeaders are what droid sends on every call to Factory's API.
184
+ function factoryHeaders(h, c) {
185
+ h.set("Authorization", "Bearer " + c.access)
186
+ h.set("X-Factory-Client", "cli")
187
+ h.set("X-Client-Version", VERSION)
188
+ h.set("User-Agent", "factory-cli/" + VERSION)
189
+ if (c.activeOrganizationId) h.set("X-Factory-Org-Id", c.activeOrganizationId)
190
+ else h.delete("X-Factory-Org-Id")
191
+ }
192
+
193
+ async function factoryGet(c, path) {
194
+ const h = new Headers({ Accept: "application/json" })
195
+ factoryHeaders(h, c)
196
+ const res = await fetch(base(c) + path, { headers: h, signal: AbortSignal.timeout(30_000) })
197
+ const text = await res.text()
198
+ if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + apiError(text, String(res.status)))
199
+ return JSON.parse(text)
200
+ }
201
+
202
+ // firstOrg is the first WorkOS org /api/cli/org says the account is in, ""
203
+ // for none. droid asks it with the bearer token alone.
204
+ async function firstOrg(c) {
205
+ const r = await factoryGet({ ...c, activeOrganizationId: "" }, "/api/cli/org")
206
+ return r?.workosOrgIds?.[0] ?? ""
207
+ }
208
+
209
+ // whoami asks Factory whose the token is with the headers droid's whoami
210
+ // sends: the token, X-Factory-Whoami-Extended, and the active org when there
211
+ // is one — nothing else.
212
+ async function whoami(c, signal) {
213
+ const h = { Authorization: "Bearer " + c.access, "X-Factory-Whoami-Extended": "true" }
214
+ if (c.activeOrganizationId) h["X-Factory-Org-Id"] = c.activeOrganizationId
215
+ const res = await fetch(base(c) + "/api/cli/whoami", { headers: h, signal: signal ?? AbortSignal.timeout(10_000) })
216
+ const text = await res.text()
217
+ if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + apiError(text, String(res.status)))
218
+ return JSON.parse(text) ?? {}
219
+ }
220
+
221
+ // reconcile asks whoami, as droid does for each token it holds, and keeps the
222
+ // org, region and host it names: true when any changed. An active org whoami
223
+ // refuses is left off and whoami asked again without it.
224
+ async function reconcile(c) {
225
+ const signal = AbortSignal.timeout(10_000)
226
+ let who
227
+ try {
228
+ who = await whoami(c, signal)
229
+ } catch (e) {
230
+ if (!(c.activeOrganizationId && e instanceof FactoryStatus && e.code === 403)) return false
231
+ try {
232
+ who = await whoami({ ...c, activeOrganizationId: "" }, signal)
233
+ } catch {
234
+ return false
235
+ }
236
+ }
237
+ if (!who?.orgId) return false
238
+ const changed = c.activeOrganizationId !== who.orgId || (c.region ?? "") !== (who.region ?? "") || (c.premBaseHost ?? "") !== (who.premBaseHostV2 ?? "")
239
+ c.activeOrganizationId = who.orgId
240
+ c.region = who.region ?? ""
241
+ c.premBaseHost = who.premBaseHostV2 ?? ""
242
+ return changed
243
+ }
244
+
245
+ // orgRefused is Factory's 403 for an X-Factory-Org-Id the user can't reach:
246
+ // "Requested active organization is not accessible by this user".
247
+ const orgRefused = (status, text) => status === 403 && text.toLowerCase().includes("active organization is not accessible")
248
+
249
+ // explain is what the user can do about a 403 Factory still answers once
250
+ // the request carries what droid sends.
251
+ function explain(status, text) {
252
+ if (status !== 403) return ""
253
+ if (orgRefused(status, text)) return "the Factory account's organization changed; sign in to it again"
254
+ return "Factory refused this account the request; check that `droid`, signed in to the same account and organization, can use this model (an organization's model policy or the plan may not allow it), and if it can, sign in to the Factory account again"
255
+ }
256
+
257
+ // ---- sign-in ----------------------------------------------------------------
258
+
259
+ // signedInWith is the account WorkOS just signed in, as droid keeps it: a
260
+ // token that names no org (the JWT's external_org_id or org_id) is put in
261
+ // the first org /api/cli/org lists, and whoami, asked without an org header,
262
+ // gives Factory's own id for the org the token is in (the active org droid
263
+ // then sends as X-Factory-Org-Id) and where Factory serves it from. droid
264
+ // carries on without either when they fail.
265
+ async function signedInWith(t) {
266
+ const cl = claims(t.access_token)
267
+ const c = {
268
+ access: t.access_token,
269
+ refresh: t.refresh_token ?? "",
270
+ expires: expiry(t.access_token),
271
+ orgId: t.organization_id || claim(cl, "org_id"),
272
+ email: t.user?.email || claim(cl, "email"),
273
+ userId: t.user?.id || claim(cl, "sub"),
274
+ activeOrganizationId: "",
275
+ region: "",
276
+ premBaseHost: "",
277
+ }
278
+ if (!c.orgId && !claim(cl, "external_org_id")) {
279
+ let org = ""
280
+ try {
281
+ org = await firstOrg(c)
282
+ } catch {}
283
+ if (org) {
284
+ const r = await renew(c.refresh, org)
285
+ c.access = r.access_token
286
+ c.expires = expiry(r.access_token)
287
+ c.orgId = org
288
+ if (r.refresh_token) c.refresh = r.refresh_token
289
+ }
290
+ }
291
+ try {
292
+ const who = await whoami(c)
293
+ c.activeOrganizationId = who.orgId ?? ""
294
+ c.region = who.region ?? ""
295
+ c.premBaseHost = who.premBaseHostV2 ?? ""
296
+ c.email ||= who.email ?? ""
297
+ c.userId ||= who.userId ?? ""
298
+ } catch (e) {
299
+ if (!c.email && !c.userId) throw e
300
+ }
301
+ const user = c.email || c.userId
302
+ if (!user) throw new Error("signed in, but Factory didn't say whose account it is; try again")
303
+ return { ...c, accountId: user }
304
+ }
305
+
306
+ async function deviceSignIn() {
307
+ const { text, status } = await workos("/authorize/device", { client_id: CLIENT_ID })
308
+ if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " + apiError(text, String(status)))
309
+ const dc = JSON.parse(text)
310
+ if (!dc.device_code || !dc.user_code) throw new Error("Factory's sign-in gave no device code")
311
+ let interval = Math.max(dc.interval ?? 0, 1) * 1000
312
+ // WorkOS answers expired_token once the code lapses; stop a little after
313
+ // that regardless, so a lost poll can't run forever
314
+ const until = Date.now() + (Math.max(dc.expires_in ?? 0, 300) + 30) * 1000
315
+ return {
316
+ url: dc.verification_uri_complete || dc.verification_uri,
317
+ instructions: `Confirm the code ${dc.user_code} on Factory's page`,
318
+ method: "auto",
319
+ async callback() {
320
+ for (;;) {
321
+ await new Promise((r) => setTimeout(r, interval))
322
+ if (Date.now() > until) throw new Error("the code expired; start again")
323
+ let t
324
+ try {
325
+ t = await authenticate({
326
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
327
+ device_code: dc.device_code,
328
+ client_id: CLIENT_ID,
329
+ })
330
+ } catch {
331
+ continue // a hiccup: ask again
332
+ }
333
+ if (t.error === "authorization_pending") continue
334
+ if (t.error === "slow_down") {
335
+ interval += 1000
336
+ continue
337
+ }
338
+ if (t.error === "expired_token") throw new Error("the code expired; start again")
339
+ if (t.error === "access_denied") throw new Error("the sign-in was declined")
340
+ if (t.error || !t.access_token) throw new Error("Factory: " + (`${t.error ?? ""} ${t.error_description ?? ""}`.trim() || "no token came back"))
341
+ const c = await signedInWith(t)
342
+ return { type: "success", ...c }
343
+ }
344
+ },
345
+ }
346
+ }
347
+
348
+ // ---- the plugin ---------------------------------------------------------------
349
+
350
+ function bodyModel(body) {
351
+ try {
352
+ if (body == null) return ""
353
+ const s = typeof body === "string" ? body : body instanceof ArrayBuffer || ArrayBuffer.isView(body) ? Buffer.from(body).toString("utf8") : ""
354
+ return JSON.parse(s)?.model ?? ""
355
+ } catch {
356
+ return ""
357
+ }
358
+ }
359
+
360
+ export const FactoryAuthPlugin = async ({ client }) => {
361
+ // the session id this process's requests carry
362
+ const session = crypto.randomUUID()
363
+ // serializes checking, rotating and saving tokens: WorkOS rotates the
364
+ // refresh token, so two refreshes would spend it twice
365
+ let lock = Promise.resolve()
366
+ const locked = (fn) => {
367
+ const run = lock.then(fn, fn)
368
+ lock = run.catch(() => {})
369
+ return run
370
+ }
371
+ // when the account last asked whoami for its org, so one whoami can't
372
+ // answer doesn't ask before every request
373
+ let asked = 0
374
+
375
+ return {
376
+ config: async (config) => {
377
+ config.provider ??= {}
378
+ const was = config.provider[PROVIDER] ?? {}
379
+ config.provider[PROVIDER] = {
380
+ name: "Factory",
381
+ npm: CHAT.npm,
382
+ api: CHAT.api,
383
+ ...was,
384
+ models: { ...configModels(), ...(was.models ?? {}) },
385
+ }
386
+ },
387
+ auth: {
388
+ provider: PROVIDER,
389
+ methods: [
390
+ {
391
+ type: "oauth",
392
+ label: "Sign in with Factory (device code)",
393
+ authorize: deviceSignIn,
394
+ },
395
+ ],
396
+ async loader(getAuth) {
397
+ const first = await getAuth()
398
+ if (first?.type !== "oauth") return {}
399
+
400
+ const save = async (c) => {
401
+ const { type: _t, ...rest } = c
402
+ await client.auth.set({ path: { id: PROVIDER }, body: { ...rest, type: "oauth" } })
403
+ }
404
+ const current = async () => {
405
+ const a = await getAuth()
406
+ if (a?.type !== "oauth" || !a.access) throw new Error("Factory: not signed in")
407
+ return { ...a }
408
+ }
409
+
410
+ // orgOf fills in the active org when there is none: droid asks
411
+ // whoami as soon as it holds a token and sends the orgId it answers
412
+ // as X-Factory-Org-Id on every request after.
413
+ const orgOf = async (c) => {
414
+ if (c.activeOrganizationId || Date.now() - asked < ASK_AGAIN) return c
415
+ asked = Date.now()
416
+ if (await reconcile(c)) await save(c)
417
+ return c
418
+ }
419
+
420
+ // fresh is a live token, renewed near its end.
421
+ const fresh = () =>
422
+ locked(async () => {
423
+ const c = await current()
424
+ if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
425
+ let t
426
+ try {
427
+ t = await renew(c.refresh, "")
428
+ } catch (e) {
429
+ // a hiccup while the token still runs: go on with it
430
+ if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
431
+ if (refused(e)) throw new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`)
432
+ throw e
433
+ }
434
+ c.access = t.access_token
435
+ c.expires = expiry(t.access_token)
436
+ if (t.refresh_token) c.refresh = t.refresh_token
437
+ // droid asks whoami again for each new token, keeping the org it names
438
+ await reconcile(c)
439
+ asked = Date.now()
440
+ await save(c)
441
+ return c
442
+ })
443
+
444
+ // mendOrg answers Factory refusing a request: an active org it
445
+ // can't reach is left off and whoami asked again without it; with
446
+ // no header sent, the token is put in the first org /api/cli/org
447
+ // lists. Any other 403 to an account that sent no org asks whoami
448
+ // for one. True when the request is worth sending again.
449
+ const mendOrg = (status, text) =>
450
+ locked(async () => {
451
+ if (status !== 403) return false
452
+ const isOrg = orgRefused(status, text)
453
+ const c = await current()
454
+ if (c.activeOrganizationId) {
455
+ if (!isOrg) return false // the org was sent: the refusal is about something else
456
+ const was = c.activeOrganizationId
457
+ c.activeOrganizationId = ""
458
+ if ((await reconcile(c)) && c.activeOrganizationId === was) c.activeOrganizationId = "" // whoami names the org refused: send none
459
+ asked = Date.now()
460
+ await save(c)
461
+ return true
462
+ }
463
+ if (!isOrg) {
464
+ asked = Date.now()
465
+ if ((await reconcile(c)) && c.activeOrganizationId) {
466
+ await save(c)
467
+ return true
468
+ }
469
+ return false
470
+ }
471
+ if (!c.refresh) return false
472
+ let org = ""
473
+ try {
474
+ org = await firstOrg(c)
475
+ } catch {}
476
+ if (!org) return false
477
+ let t
478
+ try {
479
+ t = await renew(c.refresh, org)
480
+ } catch {
481
+ return false
482
+ }
483
+ c.access = t.access_token
484
+ c.expires = expiry(t.access_token)
485
+ c.orgId = org
486
+ if (t.refresh_token) c.refresh = t.refresh_token
487
+ await save(c)
488
+ return true
489
+ })
490
+
491
+ const send = async (input, init, body) => {
492
+ const c = await fresh()
493
+ let url = input instanceof Request ? input.url : String(input)
494
+ // an EU org is served from Factory's EU region, an on-prem one
495
+ // from its own host: the request goes there
496
+ const to = llmBase(c)
497
+ if (to !== API && url.startsWith(API)) url = to + url.slice(API.length)
498
+ const h = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))
499
+ h.delete("x-api-key")
500
+ factoryHeaders(h, c)
501
+ const model = byId.get(bodyModel(body))
502
+ const path = new URL(url).pathname
503
+ const upstream = model ? model.upstream : path.includes("/llm/o/") ? "openai" : "anthropic"
504
+ h.set("x-api-provider", upstream)
505
+ h.set("x-session-id", session)
506
+ h.set("x-assistant-message-id", crypto.randomUUID())
507
+ h.set("x-provider-routing-source", "registry_default")
508
+ if (upstream === "openai") h.set("OpenAI-Platform", "org-bHuLtG1fGmYk5YaOihAAXFBw")
509
+ // droid's Anthropic client is made with the key "placeholder",
510
+ // which Anthropic's SDK sends beside the bearer token
511
+ if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
512
+ return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body })
513
+ }
514
+
515
+ return {
516
+ apiKey: "placeholder",
517
+ async fetch(input, init) {
518
+ let body = init?.body
519
+ if (body == null && input instanceof Request && input.body) body = new Uint8Array(await input.arrayBuffer())
520
+ if (body instanceof ReadableStream) body = new Uint8Array(await new Response(body).arrayBuffer())
521
+ let res = await send(input, init, body)
522
+ if (res.status !== 403) return res
523
+ let text = await res.text()
524
+ if (await mendOrg(res.status, text).catch(() => false)) {
525
+ res = await send(input, init, body)
526
+ if (res.status !== 403) return res
527
+ text = await res.text()
528
+ }
529
+ const why = explain(res.status, text)
530
+ const msg = `${apiError(text, "Forbidden")}: ${why}`
531
+ const headers = new Headers(res.headers)
532
+ headers.set("content-type", "application/json")
533
+ headers.delete("content-length")
534
+ headers.delete("content-encoding")
535
+ return new Response(JSON.stringify({ type: "error", error: { type: "permission_error", message: msg } }), {
536
+ status: res.status,
537
+ statusText: res.statusText,
538
+ headers,
539
+ })
540
+ },
541
+ }
542
+ },
543
+ },
544
+ }
545
+ }
package/package.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "@magpie-community/opencode-factory-auth",
3
+ "version": "0.1.0",
4
+ "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
+ "type": "module",
6
+ "main": "./index.mjs",
7
+ "files": ["index.mjs", "README.md"],
8
+ "keywords": ["opencode", "opencode-plugin", "magpie", "factory", "droid"],
9
+ "license": "MIT"
10
+ }