@magpie-community/opencode-kiro-auth 0.1.39 → 0.1.41
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/README.md +61 -4
- package/index.mjs +214 -30
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -75,6 +75,55 @@ them, are under "Other ways to sign in…".
|
|
|
75
75
|
us-east-1, as kiro-cli uses it. Its models are listed with the control
|
|
76
76
|
plane's `ListAvailableModels` and its credits with `GetUsageLimits`, and
|
|
77
77
|
no profile is named in its calls, as kiro-cli names none.
|
|
78
|
+
- **Import accounts from a file** (magpie only, `auth.import`): a JSON file,
|
|
79
|
+
or JSON pasted in, of sign-ins made elsewhere, one account or a list:
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
[
|
|
83
|
+
{ "email": "user@gmail.com", "refreshToken": "…", "provider": "Google" },
|
|
84
|
+
{ "refreshToken": "…", "provider": "Github" },
|
|
85
|
+
{ "refreshToken": "…", "clientId": "…", "clientSecret": "…", "provider": "BuilderId" },
|
|
86
|
+
{ "refreshToken": "…", "clientId": "…", "clientSecret": "…", "provider": "Enterprise", "region": "eu-central-1" }
|
|
87
|
+
]
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `provider` is the way it was signed in to: `Google` and `Github` are
|
|
91
|
+
renewed through Kiro's auth service in us-east-1; `BuilderId` and
|
|
92
|
+
`Enterprise` (IAM Identity Center) through AWS's OIDC in `region`
|
|
93
|
+
(blank: us-east-1), with the `clientId` and `clientSecret` registered
|
|
94
|
+
for it. With no `provider`, `authMethod` (`social`, `IdC`) or `auth`
|
|
95
|
+
(`Social`, `IdC`) says it, and else a sign-in with a client is AWS's.
|
|
96
|
+
- Also read: Kiro Account Manager's export (`{ accounts: [{ email,
|
|
97
|
+
provider, credentials: { refreshToken, … } }] }`), kiro2api's
|
|
98
|
+
`KIRO_AUTH_TOKEN` list, the Kiro IDE's `kiro-auth-token.json` (choose its
|
|
99
|
+
`<clientIdHash>.json` with it for a Builder ID or Identity Center
|
|
100
|
+
sign-in), kiro-cli's tokens (`access_token`, `refresh_token`, …; one with
|
|
101
|
+
a `start_url` or `scopes` is AWS's, renewed with the
|
|
102
|
+
`kirocli:odic:device-registration` client chosen with it) and this
|
|
103
|
+
plugin's own entries in `plugin-auth.json` or OpenCode's `auth.json`.
|
|
104
|
+
Other providers' entries there (keys not `kiro` or `kiro#…`) are passed
|
|
105
|
+
over, so none of their tokens is sent to Kiro.
|
|
106
|
+
- Each sign-in is renewed first unless its access token has more than 2
|
|
107
|
+
minutes left (`accessToken` with `expiresAt`), as the Kiro IDE renews
|
|
108
|
+
it. Kiro may give a new refresh token and stop taking the old one, so
|
|
109
|
+
the tool the file came from may have to sign in again.
|
|
110
|
+
- It is named by the email Kiro has for it (the file's `email` when Kiro
|
|
111
|
+
names none) and kept exactly as a browser sign-in of that way: `email
|
|
112
|
+
(Google)`, with its `uid`, region, profile ARN and plan. One with no
|
|
113
|
+
email either is `Kiro account <8 hex>`, from its file's token, so two
|
|
114
|
+
such stay two accounts. Importing an account signed in already replaces
|
|
115
|
+
it.
|
|
116
|
+
- A file's `profileArn` is kept only in the shape Kiro gives one
|
|
117
|
+
(`arn:aws:codewhisperer:<region>:<12 digits>:profile/<id>`); any other
|
|
118
|
+
is dropped and Kiro is asked for the profile. As for every sign-in
|
|
119
|
+
(the IDE's file, kiro-cli's, a saved one), the API's region is taken
|
|
120
|
+
from the profile only when it is one of Kiro's (us-east-1,
|
|
121
|
+
eu-central-1), and a region that isn't an AWS region's shape is refused
|
|
122
|
+
before anything is sent, so no file decides where a token goes.
|
|
123
|
+
- A sign-in Kiro refuses, one of an unknown `provider`, an AWS one without
|
|
124
|
+
its client, and a company's own identity provider (`ExternalIdp`) are
|
|
125
|
+
listed as not imported, with why; the others are imported. One sign-in
|
|
126
|
+
twice is renewed once. At most 100 are taken at a time.
|
|
78
127
|
|
|
79
128
|
A browser sign-in is kept where OpenCode keeps sign-ins (`auth.json`; in
|
|
80
129
|
magpie, `plugin-auth.json`) as an `oauth` entry. The entry holds the
|
|
@@ -241,10 +290,18 @@ beside the model. Claude models and Auto have thinking budget variants. Models w
|
|
|
241
290
|
|
|
242
291
|
`auth.usage` reads `Get-Usage-Limits`: the month's credits, the Free trial
|
|
243
292
|
while it is active, and each bonus (`bonuses`: a first upgrade's trial
|
|
244
|
-
credits, a promotion's) while it is `ACTIVE`
|
|
245
|
-
its own with its count and when it lapses.
|
|
246
|
-
Kiro spends the plan's credits first,
|
|
247
|
-
|
|
293
|
+
credits, a promotion's) while it is `ACTIVE` or `EXHAUSTED` (used up) and
|
|
294
|
+
not expired, as a window of its own with its count and when it lapses.
|
|
295
|
+
Bonus windows are shown only. Kiro spends the plan's credits first, then
|
|
296
|
+
the bonus, so a month used up while a bonus has credits left goes on on
|
|
297
|
+
credits (`credits: true`): magpie asks that account after the provider's
|
|
298
|
+
accounts that still have plan credits, since the plan's credits are lost at
|
|
299
|
+
the month's reset and a trial's last a year. The window is also set aside
|
|
300
|
+
(`aside: true`), so a magpie that doesn't read `credits` doesn't take the
|
|
301
|
+
account for spent. Only an `ACTIVE` bonus counts as credits left (an
|
|
302
|
+
`EXHAUSTED` one is shown only), and when a bonus left lapses before the
|
|
303
|
+
month's reset the month is only set aside, so that bonus isn't asked last
|
|
304
|
+
and lost.
|
|
248
305
|
|
|
249
306
|
With overage on (`overageConfiguration.overageStatus` `ENABLED`), the month
|
|
250
307
|
is two windows, as the Kiro IDE shows it: the plan's credits, shown only
|
package/index.mjs
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
// kiro-cli's or the IDE's own sign-in can be used instead: it is read where
|
|
10
10
|
// they keep it each time, refreshed by kiro-cli first, and a token
|
|
11
11
|
// refreshed here is written back, so they go on with it. A Kiro API key
|
|
12
|
-
// (ksk_…) signs in too
|
|
12
|
+
// (ksk_…) signs in too, and in magpie sign-ins made elsewhere are imported
|
|
13
|
+
// from a file by their refresh token (auth.import).
|
|
13
14
|
//
|
|
14
15
|
// Kiro has no API OpenCode speaks: the models are declared on Anthropic's
|
|
15
16
|
// Messages, and the fetch here sends each request whole to Kiro's own API
|
|
@@ -44,15 +45,30 @@ const WORDS = {
|
|
|
44
45
|
own: { zh: "Kiro CLI 或 Kiro IDE 已登录的账号", "zh-TW": "Kiro CLI 或 Kiro IDE 已登入的帳號", ja: "Kiro CLI または Kiro IDE のサインイン", de: "Anmeldung von Kiro CLI oder Kiro IDE" },
|
|
45
46
|
key: { zh: "Kiro API Key(ksk_…)", "zh-TW": "Kiro API Key(ksk_…)", ja: "Kiro API キー(ksk_…)", de: "Kiro-API-Schlüssel (ksk_…)" },
|
|
46
47
|
}
|
|
48
|
+
// IMPORT_FROM says what magpie's "Import accounts from a file…" takes
|
|
49
|
+
const IMPORT_FROM = {
|
|
50
|
+
en: "Choose a JSON file of Kiro sign-ins, or paste it: one account or a list, each with its refreshToken and the way it signed in (provider: Google, Github, BuilderId or Enterprise; Builder ID and Identity Center also need clientId, clientSecret and region), such as the Kiro IDE's kiro-auth-token.json. Each is renewed with Kiro before it is added, so the tool it came from may have to sign in again.",
|
|
51
|
+
froms: {
|
|
52
|
+
zh: "选择 Kiro 登录凭证的 JSON 文件,或直接粘贴:一个账号或一组账号,每个含 refreshToken 和登录方式(provider:Google、Github、BuilderId 或 Enterprise;Builder ID 和 IAM Identity Center 还需要 clientId、clientSecret 和 region),例如 Kiro IDE 的 kiro-auth-token.json。每个账号先向 Kiro 续期再添加,来源工具可能需要重新登录。",
|
|
53
|
+
"zh-TW": "選擇 Kiro 登入憑證的 JSON 檔,或直接貼上:一個帳號或一組帳號,每個含 refreshToken 和登入方式(provider:Google、Github、BuilderId 或 Enterprise;Builder ID 和 IAM Identity Center 還需要 clientId、clientSecret 和 region),例如 Kiro IDE 的 kiro-auth-token.json。每個帳號先向 Kiro 續期再加入,來源工具可能需要重新登入。",
|
|
54
|
+
ja: "Kiro のサインイン情報の JSON ファイルを選ぶか貼り付けてください。1 アカウントまたはリストで、各アカウントに refreshToken とサインイン方法(provider:Google、Github、BuilderId、Enterprise。Builder ID と IAM Identity Center は clientId、clientSecret、region も必要)を含めます。Kiro IDE の kiro-auth-token.json もそのまま使えます。各アカウントは追加前に Kiro で更新されるため、元のツールは再サインインが必要になることがあります。",
|
|
55
|
+
de: "Wähle eine JSON-Datei mit Kiro-Anmeldungen oder füge sie ein: ein Konto oder eine Liste, jedes mit refreshToken und Anmeldeart (provider: Google, Github, BuilderId oder Enterprise; Builder ID und IAM Identity Center brauchen außerdem clientId, clientSecret und region), etwa die kiro-auth-token.json der Kiro IDE. Jedes Konto wird vor dem Hinzufügen bei Kiro erneuert, daher muss sich das Tool, aus dem es stammt, eventuell neu anmelden.",
|
|
56
|
+
},
|
|
57
|
+
}
|
|
47
58
|
const MESSAGES = "@ai-sdk/anthropic"
|
|
48
59
|
const BASE = "https://runtime.us-east-1.kiro.dev" // what OpenCode is given; the fetch sends each request to the account's region
|
|
49
60
|
|
|
50
61
|
const PORTAL = "https://app.kiro.dev"
|
|
51
62
|
const AUTH_SERVICE = "https://prod.us-east-1.auth.desktop.kiro.dev"
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
63
|
+
// a region read from a file goes into these host names: one that isn't a region's shape is refused
|
|
64
|
+
const inHost = (region) => {
|
|
65
|
+
if (!AWS_REGION.test(String(region))) throw new Error(`${JSON.stringify(region)} isn't an AWS region`)
|
|
66
|
+
return region
|
|
67
|
+
}
|
|
68
|
+
const oidc = (region) => `https://oidc.${inHost(region)}.amazonaws.com`
|
|
69
|
+
const runtime = (region) => `https://runtime.${inHost(region)}.kiro.dev`
|
|
70
|
+
const management = (region) => `https://management.${inHost(region)}.kiro.dev`
|
|
71
|
+
const refreshURL = (region) => `https://prod.${inHost(region)}.auth.desktop.kiro.dev/refreshToken`
|
|
56
72
|
// the ports Kiro's sign-in page sends the browser back to, the IDE's
|
|
57
73
|
const CALLBACK_PORTS = [3128, 4649, 6588, 8008, 9091, 49153, 50153, 51153, 52153, 53153]
|
|
58
74
|
// what the IDE asks AWS for
|
|
@@ -165,7 +181,7 @@ async function readCLI() {
|
|
|
165
181
|
const m = get(key)
|
|
166
182
|
if (!m?.access_token) continue
|
|
167
183
|
const c = { access: m.access_token, refresh: m.refresh_token ?? "", expires: time(m.expires_at), region: m.region || "us-east-1",
|
|
168
|
-
profile: m.profile_arn
|
|
184
|
+
profile: arnOf(m.profile_arn), dbKey: key }
|
|
169
185
|
if (kind === "social") c.method = "social"
|
|
170
186
|
else if (kind === "odic") {
|
|
171
187
|
c.method = "idc"
|
|
@@ -198,7 +214,7 @@ async function readIDE() {
|
|
|
198
214
|
}
|
|
199
215
|
if (!t?.accessToken) return null
|
|
200
216
|
const c = { access: t.accessToken, refresh: t.refreshToken ?? "", expires: time(t.expiresAt), region: t.region || "us-east-1",
|
|
201
|
-
profile: t.profileArn
|
|
217
|
+
profile: arnOf(t.profileArn), method: "idc", idePath: path, builderID: isBuilderID(t.provider) }
|
|
202
218
|
if (t.clientIdHash) {
|
|
203
219
|
try {
|
|
204
220
|
const reg = JSON.parse(await readFile(join(ideDir(), t.clientIdHash + ".json"), "utf8"))
|
|
@@ -334,12 +350,17 @@ function authHeaders(a) {
|
|
|
334
350
|
const tokenType = (c) => (c.method === "apikey" ? "API_KEY" : c.method === "external-idp" ? "EXTERNAL_IDP" : "")
|
|
335
351
|
|
|
336
352
|
// region is where the account's API is: the region its profile is in, else
|
|
337
|
-
// the nearer of Kiro's two to where it signed in.
|
|
353
|
+
// the nearer of Kiro's two to where it signed in. It goes into the API's host
|
|
354
|
+
// name, so only Kiro's own regions are taken from a profile.
|
|
338
355
|
function regionOf(profile, signedIn) {
|
|
339
356
|
const parts = String(profile ?? "").split(":")
|
|
340
|
-
if (parts.length > 4 && parts[3]) return parts[3]
|
|
357
|
+
if (parts.length > 4 && CREDIT_REGIONS.includes(parts[3])) return parts[3]
|
|
341
358
|
return String(signedIn ?? "").startsWith("eu-") ? "eu-central-1" : "us-east-1"
|
|
342
359
|
}
|
|
360
|
+
// arnOf is a profile ARN as Kiro gives one, else "": one read from a file
|
|
361
|
+
// that isn't is left for profileOf to ask Kiro for
|
|
362
|
+
const PROFILE_ARN = /^arn:aws:codewhisperer:[a-z]{2}(?:-[a-z]+)+-\d{1,2}:\d{12}:profile\/[A-Za-z0-9_-]+$/
|
|
363
|
+
const arnOf = (s) => (PROFILE_ARN.test(String(s ?? "").trim()) ? String(s).trim() : "")
|
|
343
364
|
|
|
344
365
|
// STATUS_TEXT is Go's http.StatusText for the answers Kiro gives.
|
|
345
366
|
const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 408: "Request Timeout",
|
|
@@ -521,11 +542,16 @@ function goG(x) {
|
|
|
521
542
|
// round.
|
|
522
543
|
//
|
|
523
544
|
// Bonus credits (each allowance's bonuses: a first upgrade's trial credits,
|
|
524
|
-
// a promotion's) are a window each while ACTIVE
|
|
525
|
-
// month's: their count, and when they lapse
|
|
526
|
-
// reset. They are shown only (aside). Kiro
|
|
527
|
-
// first, then these, so a month used up while a
|
|
528
|
-
//
|
|
545
|
+
// a promotion's) are a window each while ACTIVE or EXHAUSTED (used up) and
|
|
546
|
+
// not expired, after the month's: their count, and when they lapse
|
|
547
|
+
// (runsOutAt), as they don't reset. They are shown only (aside). Kiro
|
|
548
|
+
// spends the plan's credits first, then these, so a month used up while a
|
|
549
|
+
// bonus has credits left goes on on them (credits): magpie asks the
|
|
550
|
+
// account after those with plan credits left, as the plan's end at the
|
|
551
|
+
// month's reset and a trial's run a year. It is set aside too, for a
|
|
552
|
+
// magpie that doesn't know credits, so the account isn't taken for spent.
|
|
553
|
+
// Only an ACTIVE bonus counts as credits left, and a bonus left that
|
|
554
|
+
// lapses before the month's reset keeps the month set aside only.
|
|
529
555
|
//
|
|
530
556
|
// With overage on, Kiro goes on past the plan's credits, billed as post-paid
|
|
531
557
|
// credits, until those reach the overage cap. The cap counts the overage
|
|
@@ -538,6 +564,8 @@ function goG(x) {
|
|
|
538
564
|
// still sends means nothing, and the plan's credits are the month.
|
|
539
565
|
const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit)
|
|
540
566
|
const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : 0)
|
|
567
|
+
const BONUS_SHOWN = new Set(["ACTIVE", "EXHAUSTED"])
|
|
568
|
+
const ON_BONUS = { aside: true, credits: true }
|
|
541
569
|
const overageOn = (l) =>
|
|
542
570
|
String(l?.overageConfiguration?.overageStatus ?? "").toUpperCase() === "ENABLED" || l?.overageConfiguration?.overageEnabled === true
|
|
543
571
|
|
|
@@ -556,20 +584,28 @@ function readUsage(l, now = Date.now()) {
|
|
|
556
584
|
windows.push({ name: "Free trial", used: (100 * used) / limit, resetsAt: at(num(t.freeTrialExpiry)), display: count(used, limit),
|
|
557
585
|
amount: used, limit, unit: "credits" })
|
|
558
586
|
}
|
|
559
|
-
const bonuses = []
|
|
587
|
+
const bonuses = [], spendable = []
|
|
560
588
|
for (const b of Array.isArray(u?.bonuses) ? u.bonuses : []) {
|
|
561
589
|
const used = num(b?.currentUsage), limit = num(b?.usageLimit), expires = num(b?.expiresAt)
|
|
562
|
-
if (String(b?.status ?? "").toUpperCase()
|
|
590
|
+
if (!BONUS_SHOWN.has(String(b?.status ?? "").toUpperCase()) || limit <= 0 || (expires > 0 && expires * 1000 <= now)) continue
|
|
563
591
|
const left = Math.max(0, limit - used)
|
|
564
592
|
bonuses.push({ name: b?.displayName || "Bonus credits", used: (100 * used) / limit, display: count(used, limit),
|
|
565
593
|
amount: used, limit, unit: "credits", ...(expires > 0 && left > 0 ? { runsOutAt: at(expires), runsOut: left } : {}), aside: true })
|
|
594
|
+
// only an ACTIVE bonus is spent: one Kiro marks EXHAUSTED has nothing
|
|
595
|
+
// to go on with, whatever its count says
|
|
596
|
+
if (left > 0 && String(b?.status ?? "").toUpperCase() === "ACTIVE") spendable.push(expires)
|
|
566
597
|
}
|
|
567
598
|
const used = num(u?.currentUsageWithPrecision), limit = num(u?.usageLimitWithPrecision)
|
|
568
599
|
const cap = overage ? num(u?.overageCapWithPrecision) || num(u?.overageCap) : 0
|
|
569
600
|
const reset = at(num(u?.nextDateReset) || num(l?.nextDateReset))
|
|
570
601
|
const month = { resetsAt: reset, unit: "credits", span: 30 * 24 * 3600 }
|
|
571
602
|
const name = u?.displayNamePlural || u?.displayName || "Credits"
|
|
572
|
-
const left =
|
|
603
|
+
const left = spendable.length > 0
|
|
604
|
+
// credits only when what is left outlasts the month: a bonus that
|
|
605
|
+
// lapses before the reset would be lost if asked last, so then the
|
|
606
|
+
// month is only set aside and the account keeps its listed place
|
|
607
|
+
const resetMs = Date.parse(reset ?? "")
|
|
608
|
+
const onBonus = spendable.some((e) => e > 0 && resetMs > 0 && e * 1000 < resetMs) ? { aside: true } : ON_BONUS
|
|
573
609
|
if (cap > 0) {
|
|
574
610
|
// what Kiro says of the overage, else what is past the plan
|
|
575
611
|
const said = typeof u?.currentOveragesWithPrecision === "number" ? u.currentOveragesWithPrecision : u?.currentOverages
|
|
@@ -577,12 +613,12 @@ function readUsage(l, now = Date.now()) {
|
|
|
577
613
|
const inPlan = Math.min(used, limit)
|
|
578
614
|
plan = limit > 0 ? { name, used: (100 * inPlan) / limit, display: count(inPlan, limit), amount: inPlan, limit, ...month, aside: true } : undefined
|
|
579
615
|
stop = { name: "Overage", used: (100 * over) / cap, display: count(over, cap), amount: over, limit: cap, ...month,
|
|
580
|
-
...(over >= cap && left ?
|
|
616
|
+
...(over >= cap && left ? onBonus : {}) }
|
|
581
617
|
windows.push(...(plan ? [plan] : []), stop)
|
|
582
618
|
plan ??= stop
|
|
583
619
|
} else if (limit > 0) {
|
|
584
620
|
plan = stop = { name, used: (100 * used) / limit, display: count(used, limit), amount: used, limit, ...month,
|
|
585
|
-
...(used >= limit && left ?
|
|
621
|
+
...(used >= limit && left ? onBonus : {}) }
|
|
586
622
|
windows.push(plan)
|
|
587
623
|
}
|
|
588
624
|
windows.push(...bonuses)
|
|
@@ -634,9 +670,11 @@ function regionsUsage(reads, now = Date.now(), only = "") {
|
|
|
634
670
|
allOver &&= over
|
|
635
671
|
}
|
|
636
672
|
monthName ??= plan.name
|
|
673
|
+
// a region's own windows are shown only: the sum below is weighed
|
|
674
|
+
const own = ({ credits, ...w }, n) => ({ ...w, name: `${n} (${r.region})`, aside: true })
|
|
637
675
|
if (!counted) {
|
|
638
|
-
shown.push(
|
|
639
|
-
if (over) shown.push(
|
|
676
|
+
shown.push(own(plan, plan.name))
|
|
677
|
+
if (over) shown.push(own(stop, stop.name))
|
|
640
678
|
regions.push({ region: r.region, full: stop.amount >= stop.limit, resetsAt: Date.parse(stop.resetsAt ?? "") > 0 ? Date.parse(stop.resetsAt) : 0 })
|
|
641
679
|
continue
|
|
642
680
|
}
|
|
@@ -646,8 +684,8 @@ function regionsUsage(reads, now = Date.now(), only = "") {
|
|
|
646
684
|
ofPlan += plan.limit
|
|
647
685
|
const at = Date.parse(stop.resetsAt ?? "")
|
|
648
686
|
if (at > 0 && (!resets || at < resets)) resets = at
|
|
649
|
-
shown.push(
|
|
650
|
-
if (over) shown.push(
|
|
687
|
+
shown.push(own(plan, plan.name))
|
|
688
|
+
if (over) shown.push(own(stop, stop.name))
|
|
651
689
|
regions.push({ region: r.region, full: stop.amount >= stop.limit, resetsAt: at > 0 ? at : 0 })
|
|
652
690
|
}
|
|
653
691
|
const windows = []
|
|
@@ -688,7 +726,7 @@ async function credOf(auth) {
|
|
|
688
726
|
if (auth.source === "kiro") return (await readCLI()) ?? (await readIDE())
|
|
689
727
|
if (!auth.access) return null
|
|
690
728
|
return { access: auth.access, refresh: auth.refresh ?? "", expires: auth.expires ?? 0, method: auth.method || "social",
|
|
691
|
-
region: auth.region || "us-east-1", profile: auth.profileArn
|
|
729
|
+
region: auth.region || "us-east-1", profile: arnOf(auth.profileArn), clientId: auth.clientId ?? "", clientSecret: auth.clientSecret ?? "",
|
|
692
730
|
builderID: isBuilderID(auth.loginProvider), own: true,
|
|
693
731
|
...(auth.profiles && typeof auth.profiles === "object" && !Array.isArray(auth.profiles) ? { profiles: { ...auth.profiles } } : {}) }
|
|
694
732
|
}
|
|
@@ -2978,6 +3016,17 @@ function httpsURL(s) {
|
|
|
2978
3016
|
}
|
|
2979
3017
|
}
|
|
2980
3018
|
|
|
3019
|
+
// signedIn is the account a sign-in keeps, whether made in the browser or
|
|
3020
|
+
// brought in from a file: named by the email Kiro has for it (else the one
|
|
3021
|
+
// given), with the way it was signed in to.
|
|
3022
|
+
function signedIn(c, who, email = who.email, nameless = "Kiro account") {
|
|
3023
|
+
return { type: "success", provider: ID, refresh: c.refresh, access: c.access, expires: c.expires,
|
|
3024
|
+
accountId: email ? nameOf(email, c.loginProvider) : nameless,
|
|
3025
|
+
...(uidOf(c.loginProvider) ? { uid: uidOf(c.loginProvider) } : {}),
|
|
3026
|
+
method: c.method, loginProvider: c.loginProvider, region: c.region, profileArn: who.profile,
|
|
3027
|
+
...(c.clientId ? { clientId: c.clientId, clientSecret: c.clientSecret } : {}), ...(who.plan ? { plan: who.plan } : {}) }
|
|
3028
|
+
}
|
|
3029
|
+
|
|
2981
3030
|
// whoIs names a new sign-in with the email Kiro has for it, and its plan.
|
|
2982
3031
|
async function whoIs(c) {
|
|
2983
3032
|
try {
|
|
@@ -3152,13 +3201,10 @@ async function browserSignIn(inputs = {}) {
|
|
|
3152
3201
|
// still busy while it is named: a second paste is told it is finishing
|
|
3153
3202
|
const who = await whoIs(c)
|
|
3154
3203
|
if (stage === "over") return over()
|
|
3155
|
-
const
|
|
3204
|
+
const done = signedIn(c, who)
|
|
3156
3205
|
stage = "over"
|
|
3157
|
-
finish(
|
|
3158
|
-
|
|
3159
|
-
method: c.method, loginProvider: c.loginProvider, region: c.region, profileArn: who.profile,
|
|
3160
|
-
...(c.clientId ? { clientId: c.clientId, clientSecret: c.clientSecret } : {}), ...(who.plan ? { plan: who.plan } : {}) })
|
|
3161
|
-
html(200, page(true, "You're signed in", `${user} is signed in. You can close this tab.`))
|
|
3206
|
+
finish(done)
|
|
3207
|
+
html(200, page(true, "You're signed in", `${done.accountId} is signed in. You can close this tab.`))
|
|
3162
3208
|
})
|
|
3163
3209
|
|
|
3164
3210
|
const timer = setTimeout(() => {
|
|
@@ -3226,6 +3272,140 @@ async function ownSignIn() {
|
|
|
3226
3272
|
}
|
|
3227
3273
|
}
|
|
3228
3274
|
|
|
3275
|
+
// ---- accounts from a file (magpie's auth.import) ------------------------------------
|
|
3276
|
+
//
|
|
3277
|
+
// A file of sign-ins made elsewhere: Kiro Account Manager's ([{ email,
|
|
3278
|
+
// refreshToken, provider }], or its export with the tokens under
|
|
3279
|
+
// credentials), kiro2api's ({ auth: "Social" | "IdC", refreshToken }), the
|
|
3280
|
+
// Kiro IDE's kiro-auth-token.json (with its <clientIdHash>.json client),
|
|
3281
|
+
// kiro-cli's tokens, or this plugin's own entry. Each is kept as the browser
|
|
3282
|
+
// sign-in keeps it (signedIn), renewed first the way its kind is renewed.
|
|
3283
|
+
|
|
3284
|
+
const IMPORT_MOST = 100 // what magpie keeps of one import
|
|
3285
|
+
const IMPORT_AT_ONCE = 6
|
|
3286
|
+
// the ways a sign-in is named in those files, as loginProvider says them
|
|
3287
|
+
const IMPORT_WAYS = { google: "Google", github: "Github", builderid: "BuilderId", awsbuilderid: "BuilderId", enterprise: "Enterprise",
|
|
3288
|
+
idc: "Enterprise", awsidc: "Enterprise", identitycenter: "Enterprise", iamidentitycenter: "Enterprise", internal: "Internal" }
|
|
3289
|
+
const squash = (s) => s.toLowerCase().replace(/[^a-z]/g, "")
|
|
3290
|
+
const word = (v) => (typeof v === "string" ? v.trim() : "")
|
|
3291
|
+
const pick = (o, ...keys) => keys.map((k) => word(o[k])).find(Boolean) ?? ""
|
|
3292
|
+
// an expiry as ISO time, local "YYYY/MM/DD HH:MM:SS", Unix seconds or ms
|
|
3293
|
+
const whenOf = (v) => (typeof v === "number" ? (v <= 0 ? 0 : v < 1e11 ? v * 1000 : v) : time(v))
|
|
3294
|
+
const emailIn = (s) => /^([^\s()]+@[^\s()]+)(?: \([^()]*\))?$/.exec(s)?.[1] ?? ""
|
|
3295
|
+
const EXTERNAL_IDP = "A company's own identity provider can't be signed in to here yet; sign in with `kiro-cli login`, and use Kiro CLI's sign-in"
|
|
3296
|
+
const NO_CLIENT = "an AWS Builder ID or IAM Identity Center sign-in is renewed with the client it was registered with: add its clientId and clientSecret, or choose the Kiro IDE's registration file (~/.aws/sso/cache/<clientIdHash>.json) with it"
|
|
3297
|
+
const REFUSED = "Kiro refused its refresh token: it has expired, been revoked, or been replaced by a newer one where it came from; sign in there again and export it once more"
|
|
3298
|
+
const REFUSED_IDC = "AWS refused its refresh token or its client: one has expired or been revoked; sign in again where it came from and export it once more"
|
|
3299
|
+
|
|
3300
|
+
// entryOf reads one sign-in of a file: { c, email } as refresh() takes it,
|
|
3301
|
+
// or { error, email }.
|
|
3302
|
+
function entryOf(o) {
|
|
3303
|
+
const said = pick(o, "provider", "loginProvider", "idp", "loginMethod", "login_option")
|
|
3304
|
+
const how = squash(pick(o, "authMethod", "auth_method", "auth", "method"))
|
|
3305
|
+
const email = emailIn(pick(o, "email", "accountId"))
|
|
3306
|
+
if (squash(said) === "externalidp" || how === "externalidp") return { error: EXTERNAL_IDP, email }
|
|
3307
|
+
let loginProvider = IMPORT_WAYS[squash(said)] ?? ""
|
|
3308
|
+
if (said && !loginProvider) return { error: `Kiro has no sign-in with ${JSON.stringify(said)}; provider is Google, Github, BuilderId or Enterprise`, email }
|
|
3309
|
+
const clientId = pick(o, "clientId", "client_id")
|
|
3310
|
+
const clientSecret = pick(o, "clientSecret", "client_secret")
|
|
3311
|
+
const start = pick(o, "startUrl", "start_url", "issuerUrl", "issuer_url")
|
|
3312
|
+
// kiro-cli's AWS sign-in names no provider and keeps its client apart, but has a start URL or scopes
|
|
3313
|
+
const aws = how === "idc" || how === "builderid" || !!clientId || !!start || Array.isArray(o.scopes)
|
|
3314
|
+
const social = loginProvider ? loginProvider === "Google" || loginProvider === "Github" : how === "social" || !aws
|
|
3315
|
+
if (!social && !loginProvider) {
|
|
3316
|
+
loginProvider = how === "builderid" || start === BUILDER_ID_START ? "BuilderId" : start ? "Enterprise" : ""
|
|
3317
|
+
}
|
|
3318
|
+
// Kiro's auth service renews every Google and GitHub sign-in in us-east-1
|
|
3319
|
+
const region = social ? "us-east-1" : pick(o, "idcRegion", "idc_region", "authRegion", "region") || "us-east-1"
|
|
3320
|
+
if (!AWS_REGION.test(region)) return { error: `${JSON.stringify(region)} isn't an AWS region`, email }
|
|
3321
|
+
return { email, c: { access: pick(o, "accessToken", "access_token", "access"), refresh: pick(o, "refreshToken", "refresh_token", "refresh"),
|
|
3322
|
+
expires: whenOf(o.expiresAt ?? o.expires_at ?? o.expires), method: social ? "social" : "idc", loginProvider, region,
|
|
3323
|
+
profile: arnOf(pick(o, "profileArn", "profile_arn")), clientId, clientSecret, builderID: isBuilderID(loginProvider) } }
|
|
3324
|
+
}
|
|
3325
|
+
|
|
3326
|
+
// signInsIn are the sign-ins a file's text holds; the clients registered
|
|
3327
|
+
// with AWS it holds (the Kiro IDE's <clientIdHash>.json) go into regs.
|
|
3328
|
+
function signInsIn(text, regs) {
|
|
3329
|
+
let v
|
|
3330
|
+
try {
|
|
3331
|
+
v = JSON.parse(text)
|
|
3332
|
+
} catch {
|
|
3333
|
+
return [{ error: "not JSON" }]
|
|
3334
|
+
}
|
|
3335
|
+
const out = []
|
|
3336
|
+
const seen = new Set()
|
|
3337
|
+
const walk = (o, depth) => {
|
|
3338
|
+
if (!o || typeof o !== "object" || depth > 4 || seen.has(o)) return
|
|
3339
|
+
seen.add(o)
|
|
3340
|
+
if (Array.isArray(o)) return o.forEach((x) => walk(x, depth + 1))
|
|
3341
|
+
const t = o.credentials && typeof o.credentials === "object" && !Array.isArray(o.credentials) ? { ...o, ...o.credentials } : o
|
|
3342
|
+
if (pick(t, "refreshToken", "refresh_token", "refresh", "accessToken", "access_token", "access")) return out.push(entryOf(t))
|
|
3343
|
+
const clientId = pick(t, "clientId", "client_id")
|
|
3344
|
+
const clientSecret = pick(t, "clientSecret", "client_secret")
|
|
3345
|
+
if (clientId && clientSecret) return regs.push({ clientId, clientSecret })
|
|
3346
|
+
// a sign-in store (magpie's plugin-auth.json, OpenCode's auth.json) keeps other providers' too: only Kiro's are taken
|
|
3347
|
+
for (const [k, x] of Object.entries(o)) if (!(x && (x.type === "oauth" || x.type === "api") && !/^kiro(#|$)/i.test(k))) walk(x, depth + 1)
|
|
3348
|
+
}
|
|
3349
|
+
walk(v, 0)
|
|
3350
|
+
return out.length || regs.length ? out : [{ error: "no Kiro sign-in in it (no refreshToken)" }]
|
|
3351
|
+
}
|
|
3352
|
+
|
|
3353
|
+
// importOne checks a sign-in with Kiro as signing in does: renewed unless
|
|
3354
|
+
// its access token still has time (as the Kiro IDE renews it), then named
|
|
3355
|
+
// by the email Kiro has for it.
|
|
3356
|
+
async function importOne(e) {
|
|
3357
|
+
const failed = (error) => ({ type: "failed", error, ...(e.email ? { accountId: nameOf(e.email, e.c?.loginProvider) } : {}) })
|
|
3358
|
+
if (e.error) return failed(e.error)
|
|
3359
|
+
let c = e.c
|
|
3360
|
+
if (c.method === "idc" && !(c.clientId && c.clientSecret)) return failed(NO_CLIENT)
|
|
3361
|
+
try {
|
|
3362
|
+
let renewed = false
|
|
3363
|
+
if (!c.access || !(c.expires - Date.now() > EARLY_MS)) {
|
|
3364
|
+
if (!c.refresh) return failed("its access token has ended, and it has no refreshToken to renew it with")
|
|
3365
|
+
c = await refresh(c)
|
|
3366
|
+
renewed = true
|
|
3367
|
+
}
|
|
3368
|
+
let who = await whoIs(c)
|
|
3369
|
+
// an access token Kiro didn't answer to: renewed, and asked again
|
|
3370
|
+
if (!who.email && !renewed && c.refresh) {
|
|
3371
|
+
c = await refresh(c)
|
|
3372
|
+
who = await whoIs(c)
|
|
3373
|
+
}
|
|
3374
|
+
// one Kiro names no one is still its own account: called by its file's token, so two such aren't kept as one
|
|
3375
|
+
const tag = createHash("sha256").update(e.c.refresh || e.c.access).digest("hex").slice(0, 8)
|
|
3376
|
+
return signedIn(c, who, who.email || e.email, `Kiro account ${tag}`)
|
|
3377
|
+
} catch (err) {
|
|
3378
|
+
return failed(err?.gone ? (c.method === "idc" ? REFUSED_IDC : REFUSED) : err?.message ?? String(err))
|
|
3379
|
+
}
|
|
3380
|
+
}
|
|
3381
|
+
|
|
3382
|
+
async function importSignIns(texts, signal) {
|
|
3383
|
+
const regs = []
|
|
3384
|
+
const found = texts.flatMap((t) => signInsIn(t, regs))
|
|
3385
|
+
if (regs.length === 1) for (const e of found) if (e.c?.method === "idc" && !e.c.clientId) Object.assign(e.c, regs[0])
|
|
3386
|
+
// one sign-in twice: renewing it twice would spend its refresh token
|
|
3387
|
+
const tokens = new Set()
|
|
3388
|
+
const list = found.filter((e) => {
|
|
3389
|
+
const k = e.c?.refresh || e.c?.access
|
|
3390
|
+
if (!k) return true
|
|
3391
|
+
if (tokens.has(k)) return false
|
|
3392
|
+
tokens.add(k)
|
|
3393
|
+
return true
|
|
3394
|
+
})
|
|
3395
|
+
const left = list.length > IMPORT_MOST ? list.splice(IMPORT_MOST - 1).length : 0
|
|
3396
|
+
const results = []
|
|
3397
|
+
let next = 0
|
|
3398
|
+
const work = async () => {
|
|
3399
|
+
while (next < list.length && !signal?.aborted) {
|
|
3400
|
+
const i = next++
|
|
3401
|
+
results[i] = await importOne(list[i])
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
await Promise.all(Array.from({ length: Math.min(IMPORT_AT_ONCE, list.length) }, work))
|
|
3405
|
+
if (left) results.push({ type: "failed", error: `${left} more sign-ins weren't imported: at most ${IMPORT_MOST} are taken at a time; import the rest on their own` })
|
|
3406
|
+
return results.filter(Boolean)
|
|
3407
|
+
}
|
|
3408
|
+
|
|
3229
3409
|
// ---- the plugin ------------------------------------------------------------------------
|
|
3230
3410
|
|
|
3231
3411
|
async function bodyOf(input, init) {
|
|
@@ -3306,6 +3486,10 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
|
|
|
3306
3486
|
return { error: e.message, signIn: e.gone ? "expired" : "kept" }
|
|
3307
3487
|
}
|
|
3308
3488
|
},
|
|
3489
|
+
// magpie's "Import accounts from a file…" (OpenCode ignores it)
|
|
3490
|
+
importFrom: IMPORT_FROM.en,
|
|
3491
|
+
importFroms: IMPORT_FROM.froms,
|
|
3492
|
+
import: (texts, { signal } = {}) => importSignIns(Array.isArray(texts) ? texts : [texts], signal),
|
|
3309
3493
|
// labels, messages and hints are magpie's own fields: the same words
|
|
3310
3494
|
// by the window's language (OpenCode shows the English)
|
|
3311
3495
|
// magpie's switches for the provider (#2038): shown in its editor, read
|