@platforma-sdk/pl-cli 0.13.5 → 0.14.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.
- package/README.md +208 -0
- package/dist/address.d.ts +6 -0
- package/dist/base_command.d.ts +10 -3
- package/dist/cli.js +649 -230
- package/dist/cli.js.map +1 -1
- package/dist/cmd/login.d.ts +21 -0
- package/dist/cmd/logout.d.ts +7 -0
- package/dist/cmd/session/list.d.ts +6 -0
- package/dist/cmd/session/remove.d.ts +7 -0
- package/dist/cmd/session/select.d.ts +9 -0
- package/dist/cmd-opts.d.ts +8 -3
- package/dist/connection.d.ts +59 -3
- package/dist/index.js +1 -1
- package/dist/instance.d.ts +7 -0
- package/dist/jwt.d.ts +12 -0
- package/dist/lib.d.ts +2 -1
- package/dist/project_ops-CHhJu5k5.js +524 -0
- package/dist/project_ops-CHhJu5k5.js.map +1 -0
- package/dist/prompt.d.ts +5 -0
- package/dist/session_store.d.ts +112 -0
- package/dist/sso.d.ts +30 -0
- package/package.json +3 -3
- package/src/address.ts +15 -0
- package/src/base_command.ts +24 -6
- package/src/cli.ts +74 -3
- package/src/cmd/admin/delete-user.ts +7 -0
- package/src/cmd/login.ts +262 -0
- package/src/cmd/logout.ts +55 -0
- package/src/cmd/session/list.ts +71 -0
- package/src/cmd/session/remove.ts +29 -0
- package/src/cmd/session/select.ts +36 -0
- package/src/cmd-opts.ts +24 -15
- package/src/commands.test.ts +637 -0
- package/src/connection.ts +275 -15
- package/src/instance.ts +19 -0
- package/src/jwt.ts +36 -0
- package/src/lib.ts +12 -0
- package/src/prompt.ts +54 -0
- package/src/session_store.test.ts +237 -0
- package/src/session_store.ts +315 -0
- package/src/sso.test.ts +269 -0
- package/src/sso.ts +336 -0
- package/src/test_backend.ts +151 -0
- package/dist/output-D41Wn0wM.js +0 -229
- package/dist/output-D41Wn0wM.js.map +0 -1
package/src/sso.test.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createServer, type Server } from "node:http";
|
|
3
|
+
import type { AddressInfo } from "node:net";
|
|
4
|
+
import { afterEach, beforeEach, expect, test } from "vitest";
|
|
5
|
+
import type { SSOAuthMethod } from "@milaboratories/pl-client";
|
|
6
|
+
import { openInBrowser, requireSecureUrl, runOidcLogin } from "./sso";
|
|
7
|
+
|
|
8
|
+
let idp: Server;
|
|
9
|
+
let base: string;
|
|
10
|
+
/** With a trailing slash, as some issuers have: the flow must trim it. */
|
|
11
|
+
let issuer: string;
|
|
12
|
+
let tokenRequests: URLSearchParams[];
|
|
13
|
+
let challenge: string | null;
|
|
14
|
+
/** What the fake discovery document returns. */
|
|
15
|
+
let discovery: { status: number; authorization?: string; token?: string };
|
|
16
|
+
|
|
17
|
+
async function listen(server: Server): Promise<number> {
|
|
18
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
19
|
+
const addr: AddressInfo | string | null = server.address();
|
|
20
|
+
if (addr === null || typeof addr === "string") throw new Error("no port");
|
|
21
|
+
return addr.port;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function freePort(): Promise<number> {
|
|
25
|
+
const s = createServer();
|
|
26
|
+
const port = await listen(s);
|
|
27
|
+
await new Promise((r) => s.close(r));
|
|
28
|
+
return port;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
beforeEach(async () => {
|
|
32
|
+
tokenRequests = [];
|
|
33
|
+
challenge = null;
|
|
34
|
+
discovery = { status: 200 };
|
|
35
|
+
idp = createServer((req, res) => {
|
|
36
|
+
if (req.url === "/.well-known/openid-configuration") {
|
|
37
|
+
res.statusCode = discovery.status;
|
|
38
|
+
res.setHeader("content-type", "application/json");
|
|
39
|
+
res.end(
|
|
40
|
+
JSON.stringify({
|
|
41
|
+
authorization_endpoint: discovery.authorization ?? `${base}/authorize`,
|
|
42
|
+
token_endpoint: discovery.token ?? `${base}/token`,
|
|
43
|
+
}),
|
|
44
|
+
);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (req.url === "/token" && req.method === "POST") {
|
|
48
|
+
let body = "";
|
|
49
|
+
req.on("data", (c) => (body += c));
|
|
50
|
+
req.on("end", () => {
|
|
51
|
+
const params = new URLSearchParams(body);
|
|
52
|
+
tokenRequests.push(params);
|
|
53
|
+
const verifier = params.get("code_verifier") ?? "";
|
|
54
|
+
const ok =
|
|
55
|
+
createHash("sha256").update(verifier).digest("base64url") === challenge &&
|
|
56
|
+
params.get("code") === "the-code";
|
|
57
|
+
res.statusCode = ok ? 200 : 400;
|
|
58
|
+
res.end(ok ? '{"id_token":"x","access_token":"y"}' : '{"error":"invalid_grant"}');
|
|
59
|
+
});
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
res.statusCode = 404;
|
|
63
|
+
res.end();
|
|
64
|
+
});
|
|
65
|
+
base = `http://127.0.0.1:${await listen(idp)}`;
|
|
66
|
+
issuer = `${base}/`;
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
afterEach(async () => {
|
|
70
|
+
await new Promise((r) => idp.close(r));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
function method(redirectPorts: number[]): SSOAuthMethod {
|
|
74
|
+
return {
|
|
75
|
+
id: "corp-sso",
|
|
76
|
+
title: "SSO",
|
|
77
|
+
description: "",
|
|
78
|
+
issuer,
|
|
79
|
+
clientId: "pl-client-id",
|
|
80
|
+
scopes: "openid email",
|
|
81
|
+
resource: "",
|
|
82
|
+
prompt: "",
|
|
83
|
+
redirectPorts,
|
|
84
|
+
subjectTokenSource: "",
|
|
85
|
+
userIdClaim: "",
|
|
86
|
+
groupsClaim: "",
|
|
87
|
+
flowType: "public_pkce",
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Acts as the browser: reads the auth request and calls the redirect URI. */
|
|
92
|
+
function browser(opts: { state?: string } = {}) {
|
|
93
|
+
const seen: URL[] = [];
|
|
94
|
+
return {
|
|
95
|
+
seen,
|
|
96
|
+
openUrl: async (url: string) => {
|
|
97
|
+
const u = new URL(url);
|
|
98
|
+
seen.push(u);
|
|
99
|
+
challenge = u.searchParams.get("code_challenge");
|
|
100
|
+
const redirect = new URL(u.searchParams.get("redirect_uri") ?? "");
|
|
101
|
+
redirect.searchParams.set("code", "the-code");
|
|
102
|
+
redirect.searchParams.set("state", opts.state ?? u.searchParams.get("state") ?? "");
|
|
103
|
+
// Do not wait: the flow awaits the callback after openUrl returns.
|
|
104
|
+
void fetch(redirect).catch(() => {});
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
test("runs PKCE S256 on the loopback and returns the raw token response", async () => {
|
|
110
|
+
// The first advertised port is busy: the flow uses the next one.
|
|
111
|
+
const busy = createServer();
|
|
112
|
+
const busyPort = await listen(busy);
|
|
113
|
+
const freeOne = await freePort();
|
|
114
|
+
try {
|
|
115
|
+
const b = browser();
|
|
116
|
+
const raw = await runOidcLogin({
|
|
117
|
+
method: method([busyPort, freeOne]),
|
|
118
|
+
nonce: "nonce-1",
|
|
119
|
+
clientSecret: "secret-from-backend",
|
|
120
|
+
openUrl: b.openUrl,
|
|
121
|
+
});
|
|
122
|
+
expect(Buffer.from(raw).toString()).toBe('{"id_token":"x","access_token":"y"}');
|
|
123
|
+
|
|
124
|
+
const auth = b.seen[0];
|
|
125
|
+
expect(auth.pathname).toBe("/authorize");
|
|
126
|
+
expect(auth.searchParams.get("code_challenge_method")).toBe("S256");
|
|
127
|
+
expect(auth.searchParams.get("nonce")).toBe("nonce-1");
|
|
128
|
+
expect(auth.searchParams.get("client_id")).toBe("pl-client-id");
|
|
129
|
+
expect(auth.searchParams.get("redirect_uri")).toBe(`http://127.0.0.1:${freeOne}/callback`);
|
|
130
|
+
|
|
131
|
+
expect(tokenRequests).toHaveLength(1);
|
|
132
|
+
expect(tokenRequests[0].get("grant_type")).toBe("authorization_code");
|
|
133
|
+
expect(tokenRequests[0].get("client_secret")).toBe("secret-from-backend");
|
|
134
|
+
} finally {
|
|
135
|
+
await new Promise((r) => busy.close(r));
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("public client: no client secret is sent", async () => {
|
|
140
|
+
const b = browser();
|
|
141
|
+
await runOidcLogin({ method: method([await freePort()]), nonce: "n", openUrl: b.openUrl });
|
|
142
|
+
expect(tokenRequests[0].has("client_secret")).toBe(false);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("a callback with a wrong or missing state gets 400 and does not stop the sign-in", async () => {
|
|
146
|
+
const forged: number[] = [];
|
|
147
|
+
const raw = await runOidcLogin({
|
|
148
|
+
method: method([await freePort()]),
|
|
149
|
+
nonce: "n",
|
|
150
|
+
openUrl: async (url) => {
|
|
151
|
+
const u = new URL(url);
|
|
152
|
+
challenge = u.searchParams.get("code_challenge");
|
|
153
|
+
const redirect = new URL(u.searchParams.get("redirect_uri") ?? "");
|
|
154
|
+
// Another web page calls the callback first.
|
|
155
|
+
for (const state of ["forged", null]) {
|
|
156
|
+
const bad = new URL(redirect);
|
|
157
|
+
bad.searchParams.set("code", "evil");
|
|
158
|
+
if (state !== null) bad.searchParams.set("state", state);
|
|
159
|
+
forged.push((await fetch(bad)).status);
|
|
160
|
+
}
|
|
161
|
+
const good = new URL(redirect);
|
|
162
|
+
good.searchParams.set("code", "the-code");
|
|
163
|
+
good.searchParams.set("state", u.searchParams.get("state") ?? "");
|
|
164
|
+
void fetch(good).catch(() => {});
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
expect(forged).toEqual([400, 400]);
|
|
168
|
+
expect(Buffer.from(raw).toString()).toContain("id_token");
|
|
169
|
+
expect(tokenRequests.map((r) => r.get("code"))).toEqual(["the-code"]);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("an identity provider error with the right state stops the sign-in, without escapes", async () => {
|
|
173
|
+
await expect(
|
|
174
|
+
runOidcLogin({
|
|
175
|
+
method: method([await freePort()]),
|
|
176
|
+
nonce: "n",
|
|
177
|
+
openUrl: async (url) => {
|
|
178
|
+
const u = new URL(url);
|
|
179
|
+
const redirect = new URL(u.searchParams.get("redirect_uri") ?? "");
|
|
180
|
+
redirect.searchParams.set("state", u.searchParams.get("state") ?? "");
|
|
181
|
+
redirect.searchParams.set("error", "access_denied");
|
|
182
|
+
redirect.searchParams.set("error_description", "no\u001b[31m red");
|
|
183
|
+
void fetch(redirect).catch(() => {});
|
|
184
|
+
},
|
|
185
|
+
}),
|
|
186
|
+
).rejects.toThrow(/^Identity provider error: access_denied: no\[31m red$/);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
/** True when the port can be bound again, that is, the listener was closed. */
|
|
190
|
+
async function portIsFree(port: number): Promise<boolean> {
|
|
191
|
+
const s = createServer();
|
|
192
|
+
try {
|
|
193
|
+
await new Promise<void>((resolve, reject) => {
|
|
194
|
+
s.once("error", reject);
|
|
195
|
+
s.listen(port, "127.0.0.1", resolve);
|
|
196
|
+
});
|
|
197
|
+
return true;
|
|
198
|
+
} catch {
|
|
199
|
+
return false;
|
|
200
|
+
} finally {
|
|
201
|
+
s.close();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
test("a discovery failure closes the loopback listener at once", async () => {
|
|
206
|
+
discovery = { status: 500 };
|
|
207
|
+
const port = await freePort();
|
|
208
|
+
await expect(
|
|
209
|
+
runOidcLogin({ method: method([port]), nonce: "n", openUrl: () => {} }),
|
|
210
|
+
).rejects.toThrow(/discovery .* failed: 500/);
|
|
211
|
+
expect(await portIsFree(port)).toBe(true);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("an openUrl failure closes the loopback listener", async () => {
|
|
215
|
+
const port = await freePort();
|
|
216
|
+
await expect(
|
|
217
|
+
runOidcLogin({
|
|
218
|
+
method: method([port]),
|
|
219
|
+
nonce: "n",
|
|
220
|
+
openUrl: () => {
|
|
221
|
+
throw new Error("no browser");
|
|
222
|
+
},
|
|
223
|
+
}),
|
|
224
|
+
).rejects.toThrow(/no browser/);
|
|
225
|
+
expect(await portIsFree(port)).toBe(true);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("endpoints must use https (http only on loopback)", async () => {
|
|
229
|
+
discovery = { status: 200, token: "http://idp.example.com/token" };
|
|
230
|
+
const port = await freePort();
|
|
231
|
+
await expect(
|
|
232
|
+
runOidcLogin({ method: method([port]), nonce: "n", openUrl: () => {} }),
|
|
233
|
+
).rejects.toThrow(/SSO token endpoint must use https/);
|
|
234
|
+
expect(await portIsFree(port)).toBe(true);
|
|
235
|
+
|
|
236
|
+
discovery = { status: 200, authorization: "file:///etc/passwd" };
|
|
237
|
+
await expect(
|
|
238
|
+
runOidcLogin({ method: method([await freePort()]), nonce: "n", openUrl: () => {} }),
|
|
239
|
+
).rejects.toThrow(/SSO authorization endpoint must use https/);
|
|
240
|
+
|
|
241
|
+
await expect(
|
|
242
|
+
runOidcLogin({
|
|
243
|
+
method: { ...method([await freePort()]), issuer: "http://idp.example.com" },
|
|
244
|
+
nonce: "n",
|
|
245
|
+
openUrl: () => {},
|
|
246
|
+
}),
|
|
247
|
+
).rejects.toThrow(/SSO issuer must use https/);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test("requireSecureUrl and openInBrowser accept only web URLs", async () => {
|
|
251
|
+
expect(requireSecureUrl("https://idp.example.com/a", "x").host).toBe("idp.example.com");
|
|
252
|
+
expect(requireSecureUrl("http://localhost:8080/a", "x").port).toBe("8080");
|
|
253
|
+
expect(requireSecureUrl("http://[::1]:8080/a", "x").port).toBe("8080");
|
|
254
|
+
for (const bad of ["http://10.0.0.1/a", "file:///etc/passwd", "javascript:alert(1)", "x-app://y"])
|
|
255
|
+
expect(() => requireSecureUrl(bad, "x")).toThrow(/must use https/);
|
|
256
|
+
await expect(openInBrowser("file:///etc/passwd")).rejects.toThrow(/must use https/);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("abort stops waiting for the callback", async () => {
|
|
260
|
+
const controller = new AbortController();
|
|
261
|
+
await expect(
|
|
262
|
+
runOidcLogin({
|
|
263
|
+
method: method([await freePort()]),
|
|
264
|
+
nonce: "n",
|
|
265
|
+
signal: controller.signal,
|
|
266
|
+
openUrl: () => controller.abort(),
|
|
267
|
+
}),
|
|
268
|
+
).rejects.toThrow(/cancelled/);
|
|
269
|
+
});
|
package/src/sso.ts
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
// Ported from the Desktop App (packages/main/src/sso.ts). Keep the two flows the same.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
import { createServer, type Server } from "node:http";
|
|
5
|
+
import type { SSOAuthMethod } from "@milaboratories/pl-client";
|
|
6
|
+
|
|
7
|
+
export interface RunOidcLoginArgs {
|
|
8
|
+
method: SSOAuthMethod;
|
|
9
|
+
/** One-time nonce from the Backend's BeginSSOLogin. */
|
|
10
|
+
nonce: string;
|
|
11
|
+
/** Client secret from the Backend's BeginSSOLogin. Sent to the identity provider token
|
|
12
|
+
* endpoint when set (confidential clients, for example Google); absent for public clients. */
|
|
13
|
+
clientSecret?: string;
|
|
14
|
+
/** Called with the identity provider URL that the user must open. */
|
|
15
|
+
openUrl: (url: string) => void | Promise<void>;
|
|
16
|
+
/** Stops the flow: closes the loopback listener and cancels the token request. */
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Runs the authorization code flow with PKCE (RFC 7636, S256) for a public client, as the
|
|
22
|
+
* Desktop App does: listens on 127.0.0.1 on the first free redirect port that the Backend
|
|
23
|
+
* advertises, sends the user to the identity provider, receives the code and exchanges it for
|
|
24
|
+
* tokens. Returns the raw token response body. The caller gives this body to the Backend
|
|
25
|
+
* (Login with SSO credentials) and must not keep it: only the Backend reads these tokens.
|
|
26
|
+
*/
|
|
27
|
+
export async function runOidcLogin(args: RunOidcLoginArgs): Promise<Uint8Array> {
|
|
28
|
+
const { method, nonce } = args;
|
|
29
|
+
// Check before the listener starts, so that a refused issuer leaves nothing open.
|
|
30
|
+
requireSecureUrl(method.issuer, "SSO issuer");
|
|
31
|
+
|
|
32
|
+
const pkce = generatePkcePair();
|
|
33
|
+
const state = randomBytes(32).toString("base64url");
|
|
34
|
+
|
|
35
|
+
// Bind the listener first: the redirect URI must contain the port that is really bound.
|
|
36
|
+
const listener = await listenForCallback(method.redirectPorts, state, args.signal);
|
|
37
|
+
try {
|
|
38
|
+
const redirectUri = `http://127.0.0.1:${listener.port}/callback`;
|
|
39
|
+
|
|
40
|
+
const { authorizationEndpoint, tokenEndpoint } = await discoverEndpoints(
|
|
41
|
+
method.issuer,
|
|
42
|
+
args.signal,
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
const authUrl = new URL(authorizationEndpoint);
|
|
46
|
+
authUrl.searchParams.set("response_type", "code");
|
|
47
|
+
authUrl.searchParams.set("client_id", method.clientId);
|
|
48
|
+
authUrl.searchParams.set("redirect_uri", redirectUri);
|
|
49
|
+
authUrl.searchParams.set("scope", method.scopes);
|
|
50
|
+
authUrl.searchParams.set("state", state);
|
|
51
|
+
authUrl.searchParams.set("nonce", nonce);
|
|
52
|
+
authUrl.searchParams.set("code_challenge", pkce.codeChallenge);
|
|
53
|
+
authUrl.searchParams.set("code_challenge_method", pkce.codeChallengeMethod);
|
|
54
|
+
if (method.resource) authUrl.searchParams.set("resource", method.resource);
|
|
55
|
+
if (method.prompt) authUrl.searchParams.set("prompt", method.prompt);
|
|
56
|
+
// Google issues a refresh token only with access_type=offline. The Backend keeps that refresh
|
|
57
|
+
// token and uses it to renew the Platforma session; pl-cli never sees it.
|
|
58
|
+
if (method.accessType) authUrl.searchParams.set("access_type", method.accessType);
|
|
59
|
+
|
|
60
|
+
await args.openUrl(authUrl.toString());
|
|
61
|
+
const code = await listener.code;
|
|
62
|
+
|
|
63
|
+
return await exchangeAuthCode({
|
|
64
|
+
tokenEndpoint,
|
|
65
|
+
code,
|
|
66
|
+
redirectUri,
|
|
67
|
+
clientId: method.clientId,
|
|
68
|
+
codeVerifier: pkce.codeVerifier,
|
|
69
|
+
clientSecret: args.clientSecret,
|
|
70
|
+
resource: method.resource || undefined,
|
|
71
|
+
signal: args.signal,
|
|
72
|
+
});
|
|
73
|
+
} finally {
|
|
74
|
+
// Also on a failure before the callback (discovery, openUrl): an open listener keeps the
|
|
75
|
+
// process alive until the timeout.
|
|
76
|
+
listener.close();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Accepts only `https:` URLs, and `http:` URLs to a loopback host (local test identity
|
|
81
|
+
* providers). Other schemes (`file:`, application schemes) must not reach the browser launcher,
|
|
82
|
+
* and plain HTTP to a remote host would send the code and the PKCE verifier in clear text. */
|
|
83
|
+
export function requireSecureUrl(raw: string, what: string): URL {
|
|
84
|
+
let url: URL;
|
|
85
|
+
try {
|
|
86
|
+
url = new URL(raw);
|
|
87
|
+
} catch {
|
|
88
|
+
throw new Error(`${what} is not a valid URL: ${sanitizeForTerminal(raw)}`);
|
|
89
|
+
}
|
|
90
|
+
if (url.protocol === "https:") return url;
|
|
91
|
+
if (url.protocol === "http:" && isLoopbackHost(url.hostname)) return url;
|
|
92
|
+
throw new Error(
|
|
93
|
+
`${what} must use https (http is accepted only for localhost): ${sanitizeForTerminal(raw)}`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isLoopbackHost(hostname: string): boolean {
|
|
98
|
+
return (
|
|
99
|
+
hostname === "localhost" ||
|
|
100
|
+
hostname === "[::1]" ||
|
|
101
|
+
hostname === "::1" ||
|
|
102
|
+
/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Removes control characters (terminal escape sequences included) from text that comes from
|
|
107
|
+
* the identity provider, before pl-cli prints it. Keeps line feeds and tabs. */
|
|
108
|
+
export function sanitizeForTerminal(text: string): string {
|
|
109
|
+
// oxlint-disable-next-line no-control-regex
|
|
110
|
+
return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Opens the URL in the default browser. Returns false if no browser command could start. */
|
|
114
|
+
export async function openInBrowser(url: string): Promise<boolean> {
|
|
115
|
+
// The launchers start any registered handler, so allow web URLs only.
|
|
116
|
+
requireSecureUrl(url, "Sign-in URL");
|
|
117
|
+
const [command, cmdArgs] =
|
|
118
|
+
process.platform === "darwin"
|
|
119
|
+
? ["open", [url]]
|
|
120
|
+
: process.platform === "win32"
|
|
121
|
+
? // rundll32 takes the URL as one argument; "cmd /c start" would split it at "&".
|
|
122
|
+
["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
123
|
+
: ["xdg-open", [url]];
|
|
124
|
+
return await new Promise<boolean>((resolve) => {
|
|
125
|
+
try {
|
|
126
|
+
const child = spawn(command, cmdArgs, { stdio: "ignore", detached: true });
|
|
127
|
+
child.once("error", () => resolve(false));
|
|
128
|
+
child.once("spawn", () => {
|
|
129
|
+
child.unref();
|
|
130
|
+
resolve(true);
|
|
131
|
+
});
|
|
132
|
+
} catch {
|
|
133
|
+
resolve(false);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
interface PkcePair {
|
|
139
|
+
codeVerifier: string;
|
|
140
|
+
codeChallenge: string;
|
|
141
|
+
codeChallengeMethod: "S256";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function generatePkcePair(): PkcePair {
|
|
145
|
+
const codeVerifier = randomBytes(64).toString("base64url");
|
|
146
|
+
const codeChallenge = createHash("sha256").update(codeVerifier).digest().toString("base64url");
|
|
147
|
+
return { codeVerifier, codeChallenge, codeChallengeMethod: "S256" };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function callbackPage(message: string): string {
|
|
151
|
+
return (
|
|
152
|
+
"<!doctype html><meta charset=utf-8><title>Platforma</title>" +
|
|
153
|
+
`<p>${message}</p><script>window.close()</script>`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface CallbackListener {
|
|
158
|
+
port: number;
|
|
159
|
+
/** The authorization code. Rejects on an identity provider error or on abort. */
|
|
160
|
+
code: Promise<string>;
|
|
161
|
+
/** Stops the listener. Safe to call more than once. */
|
|
162
|
+
close: () => void;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Binds a loopback HTTP server to the first free port of `ports`. Waits for a callback with the
|
|
166
|
+
* expected state: a callback without it gets status 400 and the server keeps listening, so that
|
|
167
|
+
* another web page cannot stop the sign-in. */
|
|
168
|
+
async function listenForCallback(
|
|
169
|
+
ports: number[],
|
|
170
|
+
expectedState: string,
|
|
171
|
+
signal: AbortSignal | undefined,
|
|
172
|
+
): Promise<CallbackListener> {
|
|
173
|
+
if (signal?.aborted) throw abortError();
|
|
174
|
+
|
|
175
|
+
const { promise, resolve, reject } = Promise.withResolvers<string>();
|
|
176
|
+
// The caller may not await the code promise yet (for example, while discovery runs).
|
|
177
|
+
promise.catch(() => {});
|
|
178
|
+
|
|
179
|
+
let closed = false;
|
|
180
|
+
const close = () => {
|
|
181
|
+
if (closed) return;
|
|
182
|
+
closed = true;
|
|
183
|
+
server.close();
|
|
184
|
+
server.closeAllConnections();
|
|
185
|
+
reject(abortError());
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const server = createServer((request, response) => {
|
|
189
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
190
|
+
if (url.pathname !== "/callback") {
|
|
191
|
+
response.statusCode = 404;
|
|
192
|
+
response.end();
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
response.setHeader("content-type", "text/html; charset=utf-8");
|
|
196
|
+
const params = url.searchParams;
|
|
197
|
+
if (params.get("state") !== expectedState) {
|
|
198
|
+
response.statusCode = 400;
|
|
199
|
+
response.end(callbackPage("This sign-in request is not valid. Go back to the terminal."));
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const error = params.get("error");
|
|
204
|
+
const code = params.get("code");
|
|
205
|
+
if (error) {
|
|
206
|
+
response.end(callbackPage("Sign-in failed. Go back to the terminal for the details."));
|
|
207
|
+
reject(
|
|
208
|
+
new Error(
|
|
209
|
+
sanitizeForTerminal(
|
|
210
|
+
`Identity provider error: ${error}: ${params.get("error_description") ?? ""}`,
|
|
211
|
+
),
|
|
212
|
+
),
|
|
213
|
+
);
|
|
214
|
+
} else if (!code) {
|
|
215
|
+
response.end(callbackPage("Sign-in failed. Go back to the terminal for the details."));
|
|
216
|
+
reject(new Error("The SSO callback has no code."));
|
|
217
|
+
} else {
|
|
218
|
+
response.end(callbackPage("Sign-in is complete. You can close this tab."));
|
|
219
|
+
resolve(code);
|
|
220
|
+
}
|
|
221
|
+
close();
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
signal?.addEventListener("abort", close, { once: true });
|
|
225
|
+
|
|
226
|
+
const port = await bindToFirstAvailablePort(server, ports);
|
|
227
|
+
server.on("error", (err) => reject(new Error(`SSO loopback server error: ${err.message}`)));
|
|
228
|
+
return { port, code: promise, close };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function bindToFirstAvailablePort(server: Server, ports: number[]): Promise<number> {
|
|
232
|
+
const { promise, resolve, reject } = Promise.withResolvers<number>();
|
|
233
|
+
if (ports.length === 0) {
|
|
234
|
+
reject(new Error("The Backend advertises no SSO redirect ports."));
|
|
235
|
+
return promise;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
let portIndex = -1;
|
|
239
|
+
const onListening = () => {
|
|
240
|
+
cleanup();
|
|
241
|
+
resolve(ports[portIndex]);
|
|
242
|
+
};
|
|
243
|
+
const onError = (err: NodeJS.ErrnoException) => {
|
|
244
|
+
if (err.code === "EADDRINUSE") {
|
|
245
|
+
tryNextPort();
|
|
246
|
+
} else {
|
|
247
|
+
cleanup();
|
|
248
|
+
reject(new Error(`SSO loopback cannot bind port ${ports[portIndex]}: ${err.message}`));
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
const cleanup = () => {
|
|
252
|
+
server.removeListener("error", onError);
|
|
253
|
+
server.removeListener("listening", onListening);
|
|
254
|
+
};
|
|
255
|
+
const tryNextPort = () => {
|
|
256
|
+
portIndex += 1;
|
|
257
|
+
if (portIndex >= ports.length) {
|
|
258
|
+
cleanup();
|
|
259
|
+
reject(new Error(`All SSO redirect ports are in use: ${ports.join(", ")}`));
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
server.listen(ports[portIndex], "127.0.0.1");
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
server.on("listening", onListening);
|
|
266
|
+
server.on("error", onError);
|
|
267
|
+
tryNextPort();
|
|
268
|
+
return promise;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function abortError(): Error {
|
|
272
|
+
const error = new Error("SSO sign-in was cancelled.");
|
|
273
|
+
error.name = "AbortError";
|
|
274
|
+
return error;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Reads the authorization and token endpoints from the OpenID Connect discovery document. */
|
|
278
|
+
async function discoverEndpoints(
|
|
279
|
+
issuer: string,
|
|
280
|
+
signal: AbortSignal | undefined,
|
|
281
|
+
): Promise<{ authorizationEndpoint: string; tokenEndpoint: string }> {
|
|
282
|
+
const url = `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
|
|
283
|
+
const response = await fetch(url, { signal });
|
|
284
|
+
if (!response.ok) throw new Error(`OIDC discovery ${url} failed: ${response.status}`);
|
|
285
|
+
const doc: unknown = await response.json();
|
|
286
|
+
if (
|
|
287
|
+
typeof doc !== "object" ||
|
|
288
|
+
doc === null ||
|
|
289
|
+
!("authorization_endpoint" in doc) ||
|
|
290
|
+
!("token_endpoint" in doc) ||
|
|
291
|
+
typeof doc.authorization_endpoint !== "string" ||
|
|
292
|
+
typeof doc.token_endpoint !== "string"
|
|
293
|
+
)
|
|
294
|
+
throw new Error(`OIDC discovery ${url} has no authorization_endpoint or token_endpoint.`);
|
|
295
|
+
requireSecureUrl(doc.authorization_endpoint, "SSO authorization endpoint");
|
|
296
|
+
requireSecureUrl(doc.token_endpoint, "SSO token endpoint");
|
|
297
|
+
return {
|
|
298
|
+
authorizationEndpoint: doc.authorization_endpoint,
|
|
299
|
+
tokenEndpoint: doc.token_endpoint,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function exchangeAuthCode(args: {
|
|
304
|
+
tokenEndpoint: string;
|
|
305
|
+
code: string;
|
|
306
|
+
redirectUri: string;
|
|
307
|
+
clientId: string;
|
|
308
|
+
codeVerifier: string;
|
|
309
|
+
clientSecret?: string;
|
|
310
|
+
resource?: string;
|
|
311
|
+
signal?: AbortSignal;
|
|
312
|
+
}): Promise<Uint8Array> {
|
|
313
|
+
const body: Record<string, string> = {
|
|
314
|
+
grant_type: "authorization_code",
|
|
315
|
+
code: args.code,
|
|
316
|
+
redirect_uri: args.redirectUri,
|
|
317
|
+
client_id: args.clientId,
|
|
318
|
+
code_verifier: args.codeVerifier,
|
|
319
|
+
};
|
|
320
|
+
if (args.resource) body.resource = args.resource;
|
|
321
|
+
if (args.clientSecret) body.client_secret = args.clientSecret;
|
|
322
|
+
|
|
323
|
+
const response = await fetch(args.tokenEndpoint, {
|
|
324
|
+
method: "POST",
|
|
325
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
326
|
+
body: new URLSearchParams(body).toString(),
|
|
327
|
+
signal: args.signal,
|
|
328
|
+
});
|
|
329
|
+
const raw = new Uint8Array(await response.arrayBuffer());
|
|
330
|
+
if (!response.ok)
|
|
331
|
+
throw new Error(
|
|
332
|
+
`Identity provider token endpoint returned ${response.status}: ` +
|
|
333
|
+
sanitizeForTerminal(Buffer.from(raw).toString("utf8")),
|
|
334
|
+
);
|
|
335
|
+
return raw;
|
|
336
|
+
}
|