quick-acp 0.0.0-stage → 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.
@@ -0,0 +1,522 @@
1
+ /**
2
+ * Real login: obtain a Quick session on a machine that has never run the
3
+ * official client.
4
+ *
5
+ * WHY THIS EXISTS
6
+ * ---------------
7
+ * Everything else in this bridge assumes a stored login: read the credential
8
+ * from Windows Credential Manager, hand the refresh token to the outpost, done.
9
+ * That works only after the user installed and signed into the desktop app.
10
+ *
11
+ * The app's own client is a standard OAuth PKCE public client — the evidence is
12
+ * in its own stored `client_secret`, which is a plain JWT whose payload says:
13
+ *
14
+ * {"clientType":"PUBLIC",
15
+ * "enabledGrants":{"AUTH_CODE":{"redirectUris":["http://127.0.0.1:18080"]},
16
+ * "REFRESH_TOKEN":{...}}}
17
+ *
18
+ * So the login can be reproduced without the Electron shell:
19
+ *
20
+ * 1. POST /client/register -> clientId + clientSecret (dynamic reg)
21
+ * 2. GET /authorize (PKCE + S256) -> 302 to the AWS sign-in page
22
+ * 3. user signs in; AWS redirects to http://127.0.0.1:18080?code=...
23
+ * 4. POST /token (auth code) -> access_token + refresh_token
24
+ *
25
+ * VERIFIED END TO END on 2026-11-21 against us-east-1: every step returned 200
26
+ * and produced a usable token. See LOGIN-NOTES.md for the raw transcripts.
27
+ *
28
+ * WHAT THE CALLER GETS
29
+ * --------------------
30
+ * Exactly the fields `profiles.json` records, so the outpost can be pointed at
31
+ * a home directory containing it — no Quick install, no credential-manager
32
+ * entry, no 200 MB Electron shell.
33
+ */
34
+ import { createHash, randomBytes } from 'node:crypto';
35
+ import { createServer } from 'node:http';
36
+ import { mkdir, writeFile, readFile } from 'node:fs/promises';
37
+ import { existsSync } from 'node:fs';
38
+ import { homedir } from 'node:os';
39
+ import { join } from 'node:path';
40
+ /** The OIDC control plane. NOT `oidc.<region>.amazonaws.com` — that host 403s. */
41
+ const OIDC_HOST = 'https://oidc.us-east-1.api.aws';
42
+ /**
43
+ * Redirect URI must match the one Quick's own client registered, because the
44
+ * authorize request is checked against the client's registered grants.
45
+ */
46
+ const REDIRECT_PORT = 18080;
47
+ const REDIRECT_URI = `http://127.0.0.1:${REDIRECT_PORT}`;
48
+ const SCOPE = 'quicksight:read_write';
49
+ /**
50
+ * Derive the issuer from any of the forms a user might paste:
51
+ *
52
+ * https://ssoins-xxxx.awsapps.com/start (the access-portal URL)
53
+ * ssoins-xxxx.awsapps.com/start
54
+ * https://ssoins-xxxx.awsapps.com
55
+ * ssoins-xxxx (bare instance id)
56
+ * https://identitycenter.amazonaws.com/ssoins-xxxx (the issuer itself)
57
+ *
58
+ * All of them collapse to https://identitycenter.amazonaws.com/<instance>.
59
+ */
60
+ export function issuerFromStartUrl(input) {
61
+ const raw = input.trim();
62
+ if (!raw)
63
+ return null;
64
+ const idc = raw.match(/identitycenter\.amazonaws\.com\/(ssoins-[a-z0-9]+)/i);
65
+ if (idc?.[1])
66
+ return `https://identitycenter.amazonaws.com/${idc[1]}`;
67
+ const portal = raw.match(/(ssoins-[a-z0-9]+)\.awsapps\.com/i);
68
+ if (portal?.[1])
69
+ return `https://identitycenter.amazonaws.com/${portal[1]}`;
70
+ const bare = raw.match(/^(ssoins-[a-z0-9]+)$/i);
71
+ if (bare?.[1])
72
+ return `https://identitycenter.amazonaws.com/${bare[1]}`;
73
+ return null;
74
+ }
75
+ /** Pull the instance id back out of an issuer URL, for building portal links. */
76
+ export function instanceIdFromIssuer(issuerUrl) {
77
+ const m = issuerUrl.match(/identitycenter\.amazonaws\.com\/(ssoins-[a-z0-9]+)/i);
78
+ return m?.[1] ?? null;
79
+ }
80
+ async function postJson(path, body) {
81
+ const resp = await fetch(OIDC_HOST + path, {
82
+ method: 'POST',
83
+ headers: { 'content-type': 'application/json' },
84
+ body: JSON.stringify(body),
85
+ signal: AbortSignal.timeout(30_000),
86
+ });
87
+ const text = await resp.text();
88
+ let parsed = {};
89
+ try {
90
+ parsed = JSON.parse(text);
91
+ }
92
+ catch {
93
+ parsed = { raw: text };
94
+ }
95
+ return { status: resp.status, body: parsed };
96
+ }
97
+ /**
98
+ * Register a throwaway public client for this sign-in.
99
+ *
100
+ * Field names matter and were established by probing (each wrong one returns a
101
+ * different validation error, which is how they were found):
102
+ *
103
+ * startUrl -> "Start URL is required" (ignored; the API does not want it)
104
+ * issuerUrl -> accepted, returns clientId + clientSecret
105
+ * scopes as [] -> "Scopes are required for this grant"
106
+ * scopes:[str] -> accepted
107
+ */
108
+ export async function registerClient(issuerUrl) {
109
+ const r = await postJson('/client/register', {
110
+ clientName: 'quick-acp',
111
+ clientType: 'PUBLIC',
112
+ grantTypes: ['authorization_code', 'refresh_token'],
113
+ redirectUris: [REDIRECT_URI],
114
+ scopes: [SCOPE],
115
+ issuerUrl,
116
+ });
117
+ const clientId = typeof r.body['clientId'] === 'string' ? r.body['clientId'] : '';
118
+ const clientSecret = typeof r.body['clientSecret'] === 'string' ? r.body['clientSecret'] : '';
119
+ if (r.status !== 200 || !clientId || !clientSecret) {
120
+ throw new Error(`client registration failed (HTTP ${r.status}): ${JSON.stringify(r.body).slice(0, 300)}. ` +
121
+ 'Check that the issuer/start URL belongs to an IAM Identity Center instance.');
122
+ }
123
+ return { clientId, clientSecret };
124
+ }
125
+ /** Build the authorize URL and its PKCE verifier. */
126
+ export function buildAuthorizeUrl(opts) {
127
+ const verifier = randomBytes(32).toString('base64url');
128
+ const challenge = createHash('sha256').update(verifier).digest('base64url');
129
+ const state = randomBytes(16).toString('hex');
130
+ const url = new URL(OIDC_HOST + '/authorize');
131
+ url.searchParams.set('response_type', 'code');
132
+ url.searchParams.set('client_id', opts.clientId);
133
+ url.searchParams.set('redirect_uri', REDIRECT_URI);
134
+ url.searchParams.set('scope', SCOPE);
135
+ url.searchParams.set('state', state);
136
+ url.searchParams.set('code_challenge', challenge);
137
+ url.searchParams.set('code_challenge_method', 'S256');
138
+ return { url: url.toString(), verifier, state };
139
+ }
140
+ /**
141
+ * Start the loopback listener and wait for the browser callback.
142
+ *
143
+ * Resolves with the authorization code. Rejects on an error callback, a state
144
+ * mismatch (CSRF), or the timeout.
145
+ */
146
+ export function waitForCallback(opts) {
147
+ return new Promise((resolve, reject) => {
148
+ const server = createServer((req, res) => {
149
+ const u = new URL(req.url ?? '/', REDIRECT_URI);
150
+ const code = u.searchParams.get('code');
151
+ const error = u.searchParams.get('error');
152
+ const state = u.searchParams.get('state');
153
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
154
+ if (error) {
155
+ res.end(`<h2>quick-acp: sign-in failed</h2><pre>${error}</pre>`);
156
+ }
157
+ else if (code && state !== opts.expectedState) {
158
+ res.end('<h2>quick-acp: state mismatch — sign-in rejected</h2>');
159
+ }
160
+ else if (code) {
161
+ res.end('<h2>quick-acp: signed in</h2><p>You can close this tab.</p>');
162
+ }
163
+ else {
164
+ res.end('<h2>quick-acp: no code in callback</h2>');
165
+ }
166
+ server.close();
167
+ if (error)
168
+ reject(new Error(`the sign-in page returned "${error}"`));
169
+ else if (!code)
170
+ reject(new Error('the callback carried no authorization code'));
171
+ else if (state !== opts.expectedState)
172
+ reject(new Error('state mismatch (possible CSRF)'));
173
+ else
174
+ resolve({ code, close: () => server.close() });
175
+ });
176
+ server.on('error', (e) => {
177
+ reject(new Error(`cannot listen on ${REDIRECT_URI}: ${e.message}. The port is fixed by the ` +
178
+ "app's registered redirect URI, so another program using 18080 will block sign-in."));
179
+ });
180
+ server.listen(REDIRECT_PORT, '127.0.0.1');
181
+ setTimeout(() => {
182
+ server.close();
183
+ reject(new Error(`no browser callback within ${Math.round(opts.timeoutMs / 1000)}s`));
184
+ }, opts.timeoutMs);
185
+ });
186
+ }
187
+ /**
188
+ * Exchange the code for tokens.
189
+ *
190
+ * The body shape is the whole point, and the endpoint is picky in a way that is
191
+ * not documented anywhere:
192
+ *
193
+ * client_id/client_secret as FORM FIELDS -> 200 (what works)
194
+ * client_id/client_secret as Basic auth -> 400 "Invalid request"
195
+ * both places -> 400 "should not be provided in both"
196
+ *
197
+ * Verified live against us-east-1. Because a 400 here reports nothing useful
198
+ * ("Invalid request"), the shapes are tried in order and the first 200 wins;
199
+ * the failure of every shape is then reported with each status, so the next
200
+ * person sees what was attempted rather than a bare 400.
201
+ */
202
+ export async function exchangeCode(opts) {
203
+ const basic = Buffer.from(`${opts.clientId}:${opts.clientSecret}`).toString('base64');
204
+ const base = {
205
+ grant_type: 'authorization_code',
206
+ code: opts.code,
207
+ redirect_uri: REDIRECT_URI,
208
+ code_verifier: opts.verifier,
209
+ };
210
+ const shapes = [
211
+ {
212
+ // The confirmed-good shape: everything as form fields, no Basic auth.
213
+ label: 'form+client-fields',
214
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
215
+ body: new URLSearchParams({
216
+ ...base,
217
+ client_id: opts.clientId,
218
+ client_secret: opts.clientSecret,
219
+ }).toString(),
220
+ },
221
+ {
222
+ label: 'form+basic',
223
+ headers: {
224
+ 'content-type': 'application/x-www-form-urlencoded',
225
+ authorization: `Basic ${basic}`,
226
+ },
227
+ body: new URLSearchParams(base).toString(),
228
+ },
229
+ {
230
+ label: 'json+client-fields',
231
+ headers: { 'content-type': 'application/json' },
232
+ body: JSON.stringify({
233
+ ...base,
234
+ clientId: opts.clientId,
235
+ clientSecret: opts.clientSecret,
236
+ }),
237
+ },
238
+ ];
239
+ const attempts = [];
240
+ for (const shape of shapes) {
241
+ const resp = await fetch(OIDC_HOST + '/token', {
242
+ method: 'POST',
243
+ headers: shape.headers,
244
+ body: shape.body,
245
+ signal: AbortSignal.timeout(30_000),
246
+ });
247
+ const text = await resp.text();
248
+ if (resp.status === 200) {
249
+ const parsed = JSON.parse(text);
250
+ if (process.env.QUICK_ACP_DEBUG === '1') {
251
+ console.error(`[login] token exchange succeeded with shape "${shape.label}"`);
252
+ }
253
+ return parsed;
254
+ }
255
+ attempts.push(`${shape.label} -> HTTP ${resp.status} ${text.slice(0, 120)}`);
256
+ }
257
+ throw new Error(`token exchange failed:\n ${attempts.join('\n ')}`);
258
+ }
259
+ /**
260
+ * Refresh an access token.
261
+ *
262
+ * Refresh DOES work directly — the earlier note in this project claiming
263
+ * otherwise was wrong. The two mistakes were the host and the credential
264
+ * placement:
265
+ * host : oidc.<region>.amazonaws.com -> 403 / invalid_client
266
+ * oidc.<region>.api.aws -> works
267
+ * secret: in the body -> "Invalid request"
268
+ * via Basic auth -> works
269
+ */
270
+ export async function refreshAccessToken(opts) {
271
+ const basic = Buffer.from(`${opts.clientId}:${opts.clientSecret}`).toString('base64');
272
+ const resp = await fetch(OIDC_HOST + '/token', {
273
+ method: 'POST',
274
+ headers: {
275
+ 'content-type': 'application/x-www-form-urlencoded',
276
+ authorization: `Basic ${basic}`,
277
+ },
278
+ body: new URLSearchParams({
279
+ grant_type: 'refresh_token',
280
+ refresh_token: opts.refreshToken,
281
+ }).toString(),
282
+ signal: AbortSignal.timeout(30_000),
283
+ });
284
+ const text = await resp.text();
285
+ if (resp.status !== 200) {
286
+ throw new Error(`token refresh failed (HTTP ${resp.status}): ${text.slice(0, 300)}`);
287
+ }
288
+ const body = JSON.parse(text);
289
+ return {
290
+ accessToken: String(body['access_token'] ?? ''),
291
+ refreshToken: String(body['refresh_token'] ?? opts.refreshToken),
292
+ expiresIn: Number(body['expires_in'] ?? 3600),
293
+ };
294
+ }
295
+ /** Where profiles live. Mirrors what the desktop app uses. */
296
+ export function quickworkHome() {
297
+ return process.env.QUICK_ACP_QUICKWORK_HOME ?? join(homedir(), '.quickwork');
298
+ }
299
+ /** Profile id shape the app uses: "<provider>-<12 hex>". */
300
+ function newProfileId() {
301
+ return `social-${randomBytes(6).toString('hex')}`;
302
+ }
303
+ /**
304
+ * Write a `profiles.json` the outpost will accept.
305
+ *
306
+ * The outpost reads the issuer/tenant/client hints from here and obtains the
307
+ * actual tokens from the OS keychain — which we populate separately. Writing
308
+ * this file is what makes a machine with no Quick install look "signed in" to
309
+ * the outpost.
310
+ */
311
+ export async function persistProfile(opts) {
312
+ const home = opts.home ?? quickworkHome();
313
+ const profileId = opts.login.profileId ?? newProfileId();
314
+ const dir = join(home, 'profiles', profileId);
315
+ await mkdir(dir, { recursive: true });
316
+ const path = join(home, 'profiles.json');
317
+ let existing = {
318
+ version: 1,
319
+ entries: [],
320
+ };
321
+ if (existsSync(path)) {
322
+ try {
323
+ existing = JSON.parse(await readFile(path, 'utf8'));
324
+ }
325
+ catch {
326
+ /* start fresh rather than refuse to write */
327
+ }
328
+ }
329
+ const entry = {
330
+ id: profileId,
331
+ provider: 'social',
332
+ display_name: opts.displayName ?? 'quick-acp',
333
+ data_path: `profiles/${profileId}`,
334
+ login_metadata: {
335
+ issuer_url: opts.login.issuerUrl,
336
+ tenant_url: opts.login.tenantUrl,
337
+ client_id: opts.login.clientId,
338
+ },
339
+ created_at: new Date().toISOString(),
340
+ last_used_at: new Date().toISOString(),
341
+ refresh_failing_since: null,
342
+ };
343
+ const entries = Array.isArray(existing.entries) ? existing.entries : [];
344
+ const without = entries.filter((e) => e?.id !== profileId);
345
+ await writeFile(path, JSON.stringify({ version: 1, entries: [...without, entry], last_active: profileId }, null, 2) + '\n', 'utf8');
346
+ return path;
347
+ }
348
+ /**
349
+ * Write the bridge's own login file.
350
+ *
351
+ * Separate from `profiles.json` on purpose: this is OUR artifact, holding the
352
+ * tokens and client credentials the OAuth flow produced. `profiles.json` is the
353
+ * desktop app's file and only carries hints — writing secrets into a file the
354
+ * app owns would be rude and confusing.
355
+ *
356
+ * `tenant_url` is the gateway host. The token response does not include it, so
357
+ * the caller must supply it (see discoverTenantUrl) or the session cannot dial.
358
+ */
359
+ export async function persistBridgeLogin(opts) {
360
+ const dir = join(homedir(), '.quick-acp');
361
+ await mkdir(dir, { recursive: true, mode: 0o700 });
362
+ const path = join(dir, 'login.json');
363
+ await writeFile(path, JSON.stringify({
364
+ issuer_url: opts.login.issuerUrl,
365
+ tenant_url: opts.tenantUrl ?? null,
366
+ client_id: opts.login.clientId,
367
+ client_secret: opts.login.clientSecret,
368
+ access_token: opts.login.accessToken,
369
+ refresh_token: opts.login.refreshToken,
370
+ expires_at: opts.login.expiresAt,
371
+ role: opts.role ?? null,
372
+ signed_in_at: new Date().toISOString(),
373
+ }, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
374
+ return path;
375
+ }
376
+ /**
377
+ * Find the gateway host for an account.
378
+ *
379
+ * The tenant URL is not part of the OAuth response and there is no public
380
+ * discovery endpoint for it. Three sources, best first:
381
+ *
382
+ * 1. an existing Quick profile (the desktop app records it in profiles.json)
383
+ * 2. QUICK_ACP_TENANT_URL, for a user who was told theirs
384
+ * 3. a running outpost's /auth/status, when the app happens to be open
385
+ *
386
+ * Returns '' when none is available — calling code must treat that as "ask the
387
+ * user" rather than inventing a host.
388
+ */
389
+ export async function discoverTenantUrl() {
390
+ const env = process.env.QUICK_ACP_TENANT_URL;
391
+ if (env)
392
+ return env;
393
+ // 1. profiles.json
394
+ try {
395
+ const path = join(quickworkHome(), 'profiles.json');
396
+ if (existsSync(path)) {
397
+ const j = JSON.parse(await readFile(path, 'utf8'));
398
+ const entries = j.entries ?? [];
399
+ const active = entries.find((e) => e.login_metadata?.tenant_url);
400
+ const t = active?.login_metadata?.tenant_url;
401
+ if (typeof t === 'string' && t)
402
+ return t;
403
+ }
404
+ }
405
+ catch {
406
+ /* fall through */
407
+ }
408
+ // 2. the desktop app's outpost, if it is running
409
+ try {
410
+ const port = process.env.QUICKWORK_OUTPOST_PORT ?? '8780';
411
+ const r = await fetch(`http://127.0.0.1:${port}/auth/status`, {
412
+ signal: AbortSignal.timeout(2_000),
413
+ });
414
+ if (r.ok) {
415
+ const j = (await r.json());
416
+ const t = j['tenant_url'];
417
+ if (typeof t === 'string' && t)
418
+ return t;
419
+ }
420
+ }
421
+ catch {
422
+ /* outpost not running */
423
+ }
424
+ return '';
425
+ }
426
+ /** Where bridge logins live. */
427
+ export function bridgeLoginPath() {
428
+ return join(homedir(), '.quick-acp', 'login.json');
429
+ }
430
+ /**
431
+ * Full interactive sign-in.
432
+ *
433
+ * `onUrl` is called with the sign-in URL so a CLI can print it and an ACP client
434
+ * can surface it; the flow then blocks until the browser comes back.
435
+ */
436
+ export async function login(opts) {
437
+ const issuerUrl = issuerFromStartUrl(opts.startUrl);
438
+ if (!issuerUrl) {
439
+ return {
440
+ ok: false,
441
+ error: `could not read an IAM Identity Center instance from "${opts.startUrl}". ` +
442
+ 'Expected something like https://ssoins-xxxxx.awsapps.com/start — the address ' +
443
+ 'of your AWS access portal. Copy it from the browser after signing in there.',
444
+ };
445
+ }
446
+ const instanceId = instanceIdFromIssuer(issuerUrl);
447
+ let clientId;
448
+ let clientSecret;
449
+ try {
450
+ ({ clientId, clientSecret } = await registerClient(issuerUrl));
451
+ }
452
+ catch (e) {
453
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
454
+ }
455
+ const { url, verifier, state } = buildAuthorizeUrl({ clientId, issuerUrl });
456
+ // The authorize endpoint redirects to the sign-in host. Follow one hop so the
457
+ // URL we hand out is the one the user actually needs to open.
458
+ let signInUrl = url;
459
+ try {
460
+ const resp = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(30_000) });
461
+ const loc = resp.headers.get('location');
462
+ if (loc)
463
+ signInUrl = loc;
464
+ }
465
+ catch {
466
+ /* keep the original URL; the browser will follow the same redirect */
467
+ }
468
+ const waiter = waitForCallback({ expectedState: state, timeoutMs: opts.timeoutMs ?? 600_000 });
469
+ opts.onUrl?.(signInUrl);
470
+ let code;
471
+ try {
472
+ ({ code } = await waiter);
473
+ }
474
+ catch (e) {
475
+ return { ok: false, error: e instanceof Error ? e.message : String(e), issuerUrl, clientId };
476
+ }
477
+ let tokens;
478
+ try {
479
+ tokens = await exchangeCode({ clientId, clientSecret, code, verifier });
480
+ }
481
+ catch (e) {
482
+ return { ok: false, error: e instanceof Error ? e.message : String(e), issuerUrl, clientId };
483
+ }
484
+ const result = {
485
+ ok: true,
486
+ issuerUrl,
487
+ clientId,
488
+ clientSecret,
489
+ accessToken: String(tokens['access_token'] ?? ''),
490
+ refreshToken: String(tokens['refresh_token'] ?? ''),
491
+ expiresAt: Math.floor(Date.now() / 1000) + Number(tokens['expires_in'] ?? 3600),
492
+ profileId: newProfileId(),
493
+ };
494
+ // The gateway host is not in the token response and there is no public
495
+ // discovery endpoint for it, so it is looked up separately. Failing to find
496
+ // it is not a sign-in failure — the tokens are still good — but the caller
497
+ // must know the session cannot be dialled yet.
498
+ const tenantUrl = await discoverTenantUrl();
499
+ if (tenantUrl)
500
+ result.tenantUrl = tenantUrl;
501
+ if (opts.persist) {
502
+ try {
503
+ // Our own artifact: tokens + client credentials, mode 0600.
504
+ await persistBridgeLogin({ login: result, tenantUrl: tenantUrl || undefined });
505
+ // And the profile the outpost reads, in case the user wants that path.
506
+ // Only written when we know the tenant, because a profile without it is
507
+ // useless to the outpost.
508
+ if (tenantUrl) {
509
+ result.profilePath = await persistProfile({
510
+ login: result,
511
+ displayName: opts.displayName ?? (instanceId ? `quick-acp (${instanceId})` : undefined),
512
+ });
513
+ }
514
+ }
515
+ catch (e) {
516
+ result.ok = false;
517
+ result.error = `signed in, but could not write the login file: ${e instanceof Error ? e.message : String(e)}`;
518
+ }
519
+ }
520
+ return result;
521
+ }
522
+ //# sourceMappingURL=login.js.map
@@ -0,0 +1,152 @@
1
+ /**
2
+ * OIDC token refresh against AWS IAM Identity Center.
3
+ *
4
+ * STATUS: WORKS. The first version of this file said it did not, and the two
5
+ * reasons it failed are worth keeping written down because they are both easy
6
+ * to repeat:
7
+ *
8
+ * 1. WRONG HOST
9
+ * https://oidc.<region>.amazonaws.com -> 403 / 401 invalid_client
10
+ * https://oidc.<region>.api.aws -> works
11
+ * The `.amazonaws.com` form is the old SSO OIDC host; the newer control
12
+ * plane lives on `.api.aws`. A 401 there looks like "wrong client" but is
13
+ * really "wrong host".
14
+ *
15
+ * 2. WRONG CREDENTIAL PLACEMENT
16
+ * client_id + client_secret in the FORM BODY -> HTTP 400 "Invalid request"
17
+ * client_id:client_secret as BASIC AUTH -> HTTP 200
18
+ * The refresh grant wants HTTP Basic. The authorization-code grant is the
19
+ * opposite (form fields — see login.ts). Getting these two backwards
20
+ * produces a 400 that says nothing useful.
21
+ *
22
+ * Verified live on 2026-11-21 against us-east-1: the stored refresh token was
23
+ * exchanged for a fresh access token with HTTP 200.
24
+ *
25
+ * So this module is now the primary token source, and the outpost is needed
26
+ * only for what the token cannot tell us: `ws_host`, `actor_arn`, `tenant_url`.
27
+ */
28
+ export const OIDC_HOST = 'https://oidc.us-east-1.api.aws';
29
+ /**
30
+ * Refresh the access token.
31
+ *
32
+ * Returns null (rather than throwing) when the credentials are unusable, so the
33
+ * caller can fall back to the outpost without losing the reason — attach it to
34
+ * the log via `QUICK_ACP_DEBUG=1`.
35
+ */
36
+ export async function refreshIdToken(login) {
37
+ const refreshToken = login.refresh_token;
38
+ const clientId = login.client_id;
39
+ const clientSecret = login.client_secret;
40
+ if (!refreshToken || !clientId || !clientSecret)
41
+ return null;
42
+ for (const host of candidateHosts(login)) {
43
+ const basic = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
44
+ let resp;
45
+ try {
46
+ resp = await fetch(`${host}/token`, {
47
+ method: 'POST',
48
+ headers: {
49
+ 'content-type': 'application/x-www-form-urlencoded',
50
+ authorization: `Basic ${basic}`,
51
+ },
52
+ body: new URLSearchParams({
53
+ grant_type: 'refresh_token',
54
+ refresh_token: refreshToken,
55
+ }).toString(),
56
+ signal: AbortSignal.timeout(30_000),
57
+ });
58
+ }
59
+ catch {
60
+ continue;
61
+ }
62
+ const text = await resp.text();
63
+ if (resp.status !== 200) {
64
+ if (process.env.QUICK_ACP_DEBUG === '1') {
65
+ console.error(`[oidc] ${host} -> HTTP ${resp.status}: ${text.slice(0, 200)}`);
66
+ }
67
+ continue;
68
+ }
69
+ let body;
70
+ try {
71
+ body = JSON.parse(text);
72
+ }
73
+ catch {
74
+ continue;
75
+ }
76
+ const accessToken = body.access_token ?? body.id_token ?? '';
77
+ if (!accessToken)
78
+ continue;
79
+ return {
80
+ idToken: accessToken,
81
+ accessToken,
82
+ refreshToken: body.refresh_token ?? null,
83
+ expiresAt: Math.floor(Date.now() / 1000) + (body.expires_in ?? 3600),
84
+ };
85
+ }
86
+ return null;
87
+ }
88
+ /**
89
+ * Hosts to try, in order.
90
+ *
91
+ * `.api.aws` first because that is the confirmed-working one. The legacy
92
+ * `.amazonaws.com` form is kept as a fallback in case AWS moves back or a
93
+ * non-us-east-1 deployment behaves differently.
94
+ */
95
+ function candidateHosts(login) {
96
+ const hosts = [OIDC_HOST];
97
+ const region = regionFromIssuer(login.issuer_url);
98
+ if (region && region !== 'us-east-1') {
99
+ hosts.push(`https://oidc.${region}.api.aws`);
100
+ }
101
+ if (region) {
102
+ hosts.push(`https://oidc.${region}.amazonaws.com`);
103
+ }
104
+ return [...new Set(hosts)];
105
+ }
106
+ function regionFromIssuer(issuerUrl) {
107
+ if (typeof issuerUrl !== 'string')
108
+ return null;
109
+ const m = issuerUrl.match(/\.([a-z]{2}-[a-z]+-\d)\./);
110
+ return m?.[1] ?? 'us-east-1';
111
+ }
112
+ // ---------------------------------------------------------------------------
113
+ // JWT helpers
114
+ // ---------------------------------------------------------------------------
115
+ /**
116
+ * Decode a JWT payload without verifying it.
117
+ *
118
+ * Verification is pointless here: the token is used immediately as an opaque
119
+ * bearer, and the server is the only party that can judge it. We only read
120
+ * `exp` to refresh ahead of time and `sub`/`email` for diagnostics.
121
+ *
122
+ * Note: the AWS tokens this app receives are NOT three-part JWTs — they look
123
+ * like `aoaAAAA...:MGUCMQ...`, a proprietary envelope. So this returns null for
124
+ * them rather than pretending to parse.
125
+ */
126
+ export function decodeJwtClaims(token) {
127
+ const parts = token.split('.');
128
+ if (parts.length !== 3)
129
+ return null;
130
+ try {
131
+ const payload = Buffer.from(parts[1], 'base64url').toString('utf8');
132
+ const v = JSON.parse(payload);
133
+ return v && typeof v === 'object' ? v : null;
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ }
139
+ /**
140
+ * Expiry (seconds since epoch) of a token, or 0 when unknown.
141
+ *
142
+ * Falls back to "one hour from now" for the opaque AWS envelope, because that
143
+ * is what `expires_in` reports and it keeps the refresh timer sane.
144
+ */
145
+ export function jwtExpiry(token) {
146
+ const claims = decodeJwtClaims(token);
147
+ const exp = claims?.['exp'];
148
+ if (typeof exp === 'number')
149
+ return exp;
150
+ return Math.floor(Date.now() / 1000) + 3600;
151
+ }
152
+ //# sourceMappingURL=oidc.js.map