-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathloginFlow.ts
More file actions
254 lines (226 loc) · 9.79 KB
/
loginFlow.ts
File metadata and controls
254 lines (226 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
* Copyright (c) 2024 Provar Limited.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.md file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-disable camelcase */
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
import { spawn, type ChildProcess } from 'node:child_process';
import { URL } from 'node:url';
// All three ports must be pre-registered in the Cognito App Client.
// Cognito requires redirect_uri to exactly match a registered callback URL — no wildcards.
export const CALLBACK_PORTS = [1717, 7890, 8080];
// ── PKCE ─────────────────────────────────────────────────────────────────────
/**
* Generate a PKCE code_verifier / code_challenge pair (S256 method, as required by Cognito).
*/
export function generatePkce(): { verifier: string; challenge: string } {
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
return { verifier, challenge };
}
/**
* Generate a random nonce for OIDC replay-attack prevention.
* Required by the OpenID Connect spec when requesting an id_token.
*/
export function generateNonce(): string {
return crypto.randomBytes(16).toString('base64url');
}
/**
* Generate a random state value for CSRF protection.
* Required by Cognito Managed Login even though it is optional per the OAuth 2.0 spec.
*/
export function generateState(): string {
return crypto.randomBytes(16).toString('base64url');
}
// ── Port selection ────────────────────────────────────────────────────────────
/**
* Try each registered callback port in order; return the first that is free.
*/
export async function findAvailablePort(): Promise<number> {
for (const port of CALLBACK_PORTS) {
// Sequential by design — we need the first free registered port, not all of them.
// eslint-disable-next-line no-await-in-loop
if (await isPortFree(port)) return port;
}
throw new Error(
'Could not bind to any registered callback port (1717, 7890, 8080). ' +
'Check that no other process is using these ports and try again.'
);
}
function isPortFree(port: number): Promise<boolean> {
return new Promise((resolve) => {
const probe = http.createServer();
probe.once('error', () => resolve(false));
probe.listen(port, '127.0.0.1', () => {
probe.close(() => resolve(true));
});
});
}
// ── Browser open ──────────────────────────────────────────────────────────────
/**
* Open a URL in the system browser. The URL is passed as an argument — not
* interpolated into a shell string — to avoid command injection.
*/
/**
* Return the platform-specific command and argument list for opening a URL
* in the system browser. Exported so tests can assert the correct command is
* chosen for each platform without actually spawning a process.
*/
export function getBrowserCommand(url: string, platform: NodeJS.Platform = process.platform): { cmd: string; args: string[] } {
switch (platform) {
case 'darwin':
return { cmd: 'open', args: [url] };
case 'win32':
// Pass the URL via $args[0] so it is never interpolated into the -Command
// string — avoids quote-breaking and injection risk from special characters.
return { cmd: 'powershell.exe', args: ['-NoProfile', '-Command', 'Start-Process $args[0]', '-args', url] };
default:
return { cmd: 'xdg-open', args: [url] };
}
}
export function openBrowser(url: string): void {
// detached:true + stdio:'ignore' + unref() is the standard Node.js pattern for
// fire-and-forget child processes — the event loop will not wait for them to exit.
const { cmd, args } = getBrowserCommand(url);
const child: ChildProcess = spawn(cmd, args, { detached: true, stdio: 'ignore' });
// Suppress unhandled-error crashes if the browser executable is not found.
// The login URL is already printed to the terminal so the user can open it manually.
child.on('error', () => { /* intentional no-op */ });
child.unref();
}
// ── Localhost callback server ─────────────────────────────────────────────────
/**
* Spin up a temporary localhost HTTP server that accepts exactly one callback
* from Cognito's Hosted UI, extracts the auth code, and shuts down.
*/
export function listenForCallback(port: number, expectedState?: string): Promise<string> {
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
const parsed = new URL(req.url ?? '/', `http://localhost:${port}`);
const code = parsed.searchParams.get('code');
const error = parsed.searchParams.get('error');
const description = parsed.searchParams.get('error_description');
const callbackState = parsed.searchParams.get('state');
if (expectedState && callbackState !== expectedState) {
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' });
res.end(
'<html><body style="font-family:sans-serif;padding:2rem;max-width:480px">' +
'<h2 style="color:#c23934">Authentication failed</h2>' +
'<p>Invalid state parameter — possible CSRF attack. Please try again.</p>' +
'</body></html>'
);
server.close();
server.closeAllConnections?.();
reject(new Error('OAuth callback state mismatch — possible CSRF. Try again.'));
return;
}
// 'Connection: close' tells the browser to close the TCP connection after
// this response so server.close() has no lingering keep-alive sockets to
// wait for, allowing the Node.js event loop to exit promptly.
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' });
res.end(
'<html><body style="font-family:sans-serif;padding:2rem;max-width:480px">' +
'<h2 style="color:#0070d2">Authentication complete</h2>' +
'<p>You can close this tab and return to the terminal.</p>' +
'</body></html>'
);
server.close();
// Destroy any sockets that are still open (e.g. a browser that ignores
// the Connection:close header). Requires Node 18.2+.
server.closeAllConnections?.();
if (code) {
resolve(code);
} else {
reject(new Error(description ?? error ?? 'No authorisation code received from Cognito'));
}
});
server.listen(port, '127.0.0.1');
server.on('error', (err: Error) => reject(err));
});
}
// ── Cognito token exchange ────────────────────────────────────────────────────
export interface CognitoTokens {
access_token: string;
id_token: string;
token_type: string;
expires_in: number;
}
/**
* Exchange a PKCE auth code for Cognito tokens via the standard token endpoint.
* Uses the Authorization Code + PKCE grant — no client secret required.
*/
export async function exchangeCodeForTokens(opts: {
code: string;
redirectUri: string;
clientId: string;
verifier: string;
tokenEndpoint: string;
}): Promise<CognitoTokens> {
const body = new URLSearchParams({
grant_type: 'authorization_code',
code: opts.code,
redirect_uri: opts.redirectUri,
client_id: opts.clientId,
code_verifier: opts.verifier,
}).toString();
const { status, responseBody } = await httpsPost(opts.tokenEndpoint, body, {
'Content-Type': 'application/x-www-form-urlencoded',
});
if (status !== 200) {
throw new Error(`Cognito token exchange failed (${status}): ${responseBody}`);
}
return JSON.parse(responseBody) as CognitoTokens;
}
// ── Internal HTTPS helper ─────────────────────────────────────────────────────
const REQUEST_TIMEOUT_MS = 30_000;
function httpsPost(
url: string,
body: string,
headers: Record<string, string>
): Promise<{ status: number; responseBody: string }> {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const req = https.request(
{
hostname: parsed.hostname,
port: parsed.port || undefined,
path: parsed.pathname + parsed.search,
method: 'POST',
headers: {
...headers,
'Content-Length': Buffer.byteLength(body).toString(),
},
},
(res) => {
let data = '';
res.on('data', (chunk: Buffer) => {
data += chunk.toString('utf-8');
});
res.on('end', () => resolve({ status: res.statusCode ?? 0, responseBody: data }));
}
);
req.setTimeout(REQUEST_TIMEOUT_MS, () => {
req.destroy(new Error(`Cognito token exchange timed out after ${REQUEST_TIMEOUT_MS / 1000}s`));
});
req.on('error', reject);
req.write(body);
req.end();
});
}
// ── Indirection object (sinon-stubbable) ──────────────────────────────────────
/**
* The login command calls loginFlowClient.X() so tests can replace properties with stubs.
*/
export const loginFlowClient = {
generatePkce,
generateNonce,
generateState,
findAvailablePort,
openBrowser,
listenForCallback: listenForCallback as (port: number, expectedState?: string) => Promise<string>,
exchangeCodeForTokens,
};