@ptkl/toolkit 1.3.2 → 1.4.1
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 +37 -30
- package/dist/bin/toolkit.js +37 -3
- package/dist/commands/__tests__/apiUsers.test.js +16 -0
- package/dist/commands/__tests__/apps.test.js +52 -0
- package/dist/commands/__tests__/forge-requires.test.js +58 -0
- package/dist/commands/__tests__/profile.test.js +65 -0
- package/dist/commands/apiUsers.js +12 -0
- package/dist/commands/apps.js +47 -31
- package/dist/commands/forge.js +48 -0
- package/dist/commands/profile.js +84 -76
- package/dist/lib/oauth/CallbackPages.js +82 -0
- package/dist/lib/oauth/CallbackServer.js +84 -0
- package/dist/lib/oauth/OAuthClient.js +81 -0
- package/dist/lib/oauth/OAuthError.js +17 -0
- package/dist/lib/oauth/OAuthLogin.js +60 -0
- package/dist/lib/oauth/OAuthSession.js +103 -0
- package/dist/lib/oauth/Pkce.js +19 -0
- package/dist/lib/oauth/ProfileLogin.js +76 -0
- package/dist/lib/oauth/RefreshLock.js +61 -0
- package/dist/lib/oauth/ScopePreset.js +58 -0
- package/dist/lib/oauth/__tests__/mockServer.js +29 -0
- package/dist/lib/oauth/__tests__/oauth.test.js +364 -0
- package/dist/lib/util.js +9 -2
- package/package.json +1 -1
package/dist/commands/profile.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
2
|
import util from "../lib/util.js";
|
|
3
3
|
import cli from "../lib/cli.js";
|
|
4
|
-
import { APIUser, Users as User } from "@ptkl/sdk";
|
|
5
4
|
import password from '@inquirer/password';
|
|
5
|
+
import ProfileLogin from "../lib/oauth/ProfileLogin.js";
|
|
6
|
+
import OAuthSession from "../lib/oauth/OAuthSession.js";
|
|
6
7
|
class ProfileCommand {
|
|
7
8
|
register() {
|
|
8
9
|
return new Command('profile')
|
|
@@ -10,19 +11,37 @@ class ProfileCommand {
|
|
|
10
11
|
.version('0.1.0')
|
|
11
12
|
.action(this.action)
|
|
12
13
|
.addCommand(new Command('new')
|
|
13
|
-
.description('Create new profile')
|
|
14
|
+
.description('Create new profile (OAuth browser login by default; --legacy for an API user)')
|
|
14
15
|
.option("-n, --name <name>")
|
|
15
|
-
.option("-u, --username <username>")
|
|
16
|
-
.option("-p, --password [
|
|
16
|
+
.option("-u, --username <username>", "API-user username (with --legacy)")
|
|
17
|
+
.option("-p, --password [secret]", "API-user secret (with --legacy; prompted if omitted)")
|
|
17
18
|
.option("-P, --project <project>")
|
|
18
19
|
.option("-h, --host <host>")
|
|
20
|
+
.option("--legacy", "Use API-user credentials (username + secret) instead of OAuth (implied by -u, -p, -t)")
|
|
21
|
+
.option("--client-id <id>", "OAuth client id (default: stored, $PTKL_OAUTH_CLIENT_ID, or the built-in CLI client)")
|
|
22
|
+
.option("--scope <list>", "Comma-separated permissions (or pattern:<regex>) replacing the OAuth preset")
|
|
23
|
+
.option("--add-scope <list>", "Comma-separated permissions (or pattern:<regex>) added to the OAuth preset")
|
|
24
|
+
.option("--port <port>", "OAuth loopback callback port (default: random free port)")
|
|
25
|
+
.option("--no-browser", "Print the OAuth URL instead of opening a browser")
|
|
19
26
|
.action(this.new))
|
|
20
27
|
.addCommand(new Command('auth')
|
|
21
|
-
.description('Profile auth')
|
|
22
|
-
.
|
|
28
|
+
.description('Profile auth (OAuth browser login by default; --legacy for an API user or token)')
|
|
29
|
+
.argument('[name]', 'Profile name (default: active profile)')
|
|
30
|
+
.option("-u, --username <username>", "API-user username (with --legacy)")
|
|
31
|
+
.option("-p, --password [secret]", "API-user secret (with --legacy; prompted if omitted)")
|
|
23
32
|
.option("-t, --token <token>")
|
|
24
33
|
.option("-P, --project <project>")
|
|
34
|
+
.option("--legacy", "Use API-user credentials (username + secret) instead of OAuth (implied by -u, -p, -t)")
|
|
35
|
+
.option("--client-id <id>", "OAuth client id (default: stored, $PTKL_OAUTH_CLIENT_ID, or the built-in CLI client)")
|
|
36
|
+
.option("--scope <list>", "Comma-separated permissions (or pattern:<regex>) replacing the OAuth preset")
|
|
37
|
+
.option("--add-scope <list>", "Comma-separated permissions (or pattern:<regex>) added to the OAuth preset")
|
|
38
|
+
.option("--port <port>", "OAuth loopback callback port (default: random free port)")
|
|
39
|
+
.option("--no-browser", "Print the OAuth URL instead of opening a browser")
|
|
25
40
|
.action(this.auth))
|
|
41
|
+
.addCommand(new Command('logout')
|
|
42
|
+
.description('Revoke the OAuth refresh token and clear stored tokens')
|
|
43
|
+
.argument('[name]', 'Profile name (default: active profile)')
|
|
44
|
+
.action(this.logout))
|
|
26
45
|
.addCommand(new Command('list')
|
|
27
46
|
.description('List all available profiles')
|
|
28
47
|
.action(this.list))
|
|
@@ -39,6 +58,14 @@ class ProfileCommand {
|
|
|
39
58
|
.argument('<name>')
|
|
40
59
|
.action(this.inspect));
|
|
41
60
|
}
|
|
61
|
+
/** The API-user secret: the flag value (with a warning) or a secure prompt. */
|
|
62
|
+
static async secret(flag) {
|
|
63
|
+
if (typeof flag === 'string' && flag.length > 0) {
|
|
64
|
+
console.warn('WARNING: a secret passed on the command line may be visible in shell history; use -p without a value to be prompted.');
|
|
65
|
+
return flag;
|
|
66
|
+
}
|
|
67
|
+
return password({ message: 'Enter API-user secret:' });
|
|
68
|
+
}
|
|
42
69
|
action() {
|
|
43
70
|
const currentProfile = util.getCurrentProfile();
|
|
44
71
|
cli.write(currentProfile?.name ?? "profile not selected");
|
|
@@ -46,40 +73,22 @@ class ProfileCommand {
|
|
|
46
73
|
async new(options) {
|
|
47
74
|
// try to find profile with the name
|
|
48
75
|
const { name, username, project, host } = options;
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
console.warn('⚠️ WARNING: Providing password via CLI argument is insecure and may be visible in shell history.');
|
|
54
|
-
console.warn('⚠️ Consider using --password flag without a value to be prompted securely.\n');
|
|
55
|
-
}
|
|
56
|
-
else {
|
|
57
|
-
// Prompt for password securely (either --password flag was used without value, or not provided at all)
|
|
58
|
-
userPassword = await password({
|
|
59
|
-
message: 'Enter password:',
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
let token = "";
|
|
63
|
-
// if username is email then login to platform as user
|
|
64
|
-
if (username && username.includes('@')) {
|
|
65
|
-
const user = new User({
|
|
66
|
-
host,
|
|
67
|
-
});
|
|
68
|
-
try {
|
|
69
|
-
const { data } = await user.auth(username, userPassword, project);
|
|
70
|
-
token = "SESSION:" + data.token;
|
|
76
|
+
if (!ProfileLogin.useLegacy(options)) {
|
|
77
|
+
for (const [flag, v] of [["--name", name], ["--host", host], ["--project", project]]) {
|
|
78
|
+
if (!v)
|
|
79
|
+
throw new Error(`${flag} is required`);
|
|
71
80
|
}
|
|
72
|
-
|
|
73
|
-
throw
|
|
81
|
+
if ((util.getProfiles() ?? []).some((p) => p.name == name)) {
|
|
82
|
+
throw new Error(`Profile with ${name} already exist`);
|
|
74
83
|
}
|
|
84
|
+
await ProfileLogin.login({ name, host, project }, options, (l) => cli.write(l));
|
|
85
|
+
cli.write(`Logged in. Profile '${name}' saved.`);
|
|
86
|
+
return;
|
|
75
87
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const { data } = await user.auth(username, userPassword, project);
|
|
81
|
-
token = data.Token;
|
|
82
|
-
}
|
|
88
|
+
if (!username)
|
|
89
|
+
throw new Error("--username (API-user username) is required with --legacy");
|
|
90
|
+
const secret = await ProfileCommand.secret(options.password);
|
|
91
|
+
const token = await ProfileLogin.apiUserToken(host, username, secret, project);
|
|
83
92
|
const profiles = util.getProfiles() ?? [];
|
|
84
93
|
// try to find that the profile with the name already exist
|
|
85
94
|
const profile = profiles.find((p) => p.name == name);
|
|
@@ -95,47 +104,46 @@ class ProfileCommand {
|
|
|
95
104
|
});
|
|
96
105
|
util.updateProfiles(profiles);
|
|
97
106
|
}
|
|
98
|
-
async auth(options) {
|
|
99
|
-
|
|
107
|
+
async auth(name, options) {
|
|
108
|
+
const profile = name
|
|
109
|
+
? (util.getProfiles() ?? []).find((p) => p.name == name)
|
|
110
|
+
: util.getCurrentProfile();
|
|
111
|
+
if (!profile)
|
|
112
|
+
throw new Error(`Profile with ${name} doesn't exist`);
|
|
113
|
+
if (!ProfileLogin.useLegacy(options)) {
|
|
114
|
+
const project = options.project ?? profile.project;
|
|
115
|
+
if (!project)
|
|
116
|
+
throw new Error("--project is required");
|
|
117
|
+
await ProfileLogin.login({ name: profile.name, host: profile.host, project }, options, (l) => cli.write(l));
|
|
118
|
+
cli.write(`Logged in. Profile '${profile.name}' updated.`);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
100
121
|
let { token, project } = options;
|
|
101
|
-
|
|
102
|
-
const profile = util.getCurrentProfile();
|
|
122
|
+
const username = ProfileLogin.legacyUsername(profile, options.username);
|
|
103
123
|
if (!token) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
throw error;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
const user = new APIUser({
|
|
130
|
-
host: profile.host,
|
|
131
|
-
});
|
|
132
|
-
const { data } = await user.auth(profile.username, userPassword, project ?? profile.project);
|
|
133
|
-
token = data.Token;
|
|
134
|
-
}
|
|
124
|
+
if (!username)
|
|
125
|
+
throw new Error("No username for this profile; pass -u <API-user username>");
|
|
126
|
+
const secret = await ProfileCommand.secret(options.password);
|
|
127
|
+
token = await ProfileLogin.apiUserToken(profile.host, username, secret, project ?? profile.project);
|
|
128
|
+
}
|
|
129
|
+
util.updateProfile({
|
|
130
|
+
...ProfileLogin.toLegacy(profile, { username, token }),
|
|
131
|
+
project: project ?? profile.project,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
async logout(name) {
|
|
135
|
+
const profile = name
|
|
136
|
+
? (util.getProfiles() ?? []).find((p) => p.name == name)
|
|
137
|
+
: util.getCurrentProfile();
|
|
138
|
+
if (!profile)
|
|
139
|
+
throw new Error(`Profile with ${name} doesn't exist`);
|
|
140
|
+
if (OAuthSession.isOAuth(profile)) {
|
|
141
|
+
await new OAuthSession().logout(profile);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
util.updateProfile({ ...profile, token: "" });
|
|
135
145
|
}
|
|
136
|
-
|
|
137
|
-
profile.token = token;
|
|
138
|
-
util.updateProfile(profile);
|
|
146
|
+
cli.write(`Logged out of '${profile.name}'.`);
|
|
139
147
|
}
|
|
140
148
|
list() {
|
|
141
149
|
const profiles = util.getProfiles() ?? [];
|
|
@@ -171,7 +179,7 @@ class ProfileCommand {
|
|
|
171
179
|
let profiles = util.getProfiles() ?? [];
|
|
172
180
|
// try to find that the profile with the name already exist
|
|
173
181
|
const profile = profiles.find((p) => p.name == name);
|
|
174
|
-
console.log(profile);
|
|
182
|
+
console.log(profile && OAuthSession.masked(profile));
|
|
175
183
|
}
|
|
176
184
|
}
|
|
177
185
|
export default new ProfileCommand;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Headers for every callback page: nothing external may load, nothing is cached or leaked. */
|
|
2
|
+
export const PAGE_HEADERS = {
|
|
3
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
4
|
+
"Cache-Control": "no-store",
|
|
5
|
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
|
|
6
|
+
"Referrer-Policy": "no-referrer",
|
|
7
|
+
"X-Content-Type-Options": "nosniff",
|
|
8
|
+
};
|
|
9
|
+
/** Where the browser tab lands after a successful login. */
|
|
10
|
+
export const GUIDE_URL = "https://docs.protokol.io/platform/oauth/";
|
|
11
|
+
const MAX_DESCRIPTION = 200;
|
|
12
|
+
/** Self-contained HTML (inline CSS/SVG only) for the loopback login result. */
|
|
13
|
+
export default class CallbackPages {
|
|
14
|
+
static escape(s) {
|
|
15
|
+
return s.replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
16
|
+
}
|
|
17
|
+
static clip(s, max = MAX_DESCRIPTION) {
|
|
18
|
+
return s.length > max ? s.slice(0, max) + "..." : s;
|
|
19
|
+
}
|
|
20
|
+
static retryCommand(c) {
|
|
21
|
+
const name = c.name;
|
|
22
|
+
return c.isNew
|
|
23
|
+
? `ptkl profile new -n ${name} -h ${c.host} -P ${c.project}`
|
|
24
|
+
: `ptkl profile auth ${name}`;
|
|
25
|
+
}
|
|
26
|
+
static retry(c) {
|
|
27
|
+
return `<p class="retry">Try again:</p><pre>${CallbackPages.escape(CallbackPages.retryCommand(c))}</pre>`;
|
|
28
|
+
}
|
|
29
|
+
static denied(c) {
|
|
30
|
+
return CallbackPages.page(400, "You declined access", "No permissions were granted to the CLI.", CallbackPages.retry(c));
|
|
31
|
+
}
|
|
32
|
+
static invalidLink(c) {
|
|
33
|
+
return CallbackPages.page(400, "This login link is no longer valid", "The request does not match a login started from your terminal.", CallbackPages.retry(c));
|
|
34
|
+
}
|
|
35
|
+
static expired(c) {
|
|
36
|
+
return CallbackPages.page(408, "This login timed out", "The CLI stopped waiting for the browser.", CallbackPages.retry(c));
|
|
37
|
+
}
|
|
38
|
+
/** Server-reported OAuth error. Only the (escaped, capped) code and description are shown. */
|
|
39
|
+
static failed(c, code, description) {
|
|
40
|
+
const detail = `<p class="code">${CallbackPages.escape(CallbackPages.clip(code, 64))}</p>` +
|
|
41
|
+
(description ? `<p class="desc">${CallbackPages.escape(CallbackPages.clip(description))}</p>` : "");
|
|
42
|
+
return CallbackPages.page(400, "Login failed", "The authorization server returned an error.", detail + CallbackPages.retry(c));
|
|
43
|
+
}
|
|
44
|
+
static forError(c, code, description) {
|
|
45
|
+
if (code === "access_denied")
|
|
46
|
+
return CallbackPages.denied(c);
|
|
47
|
+
if (code === "state_mismatch" || code === "invalid_response")
|
|
48
|
+
return CallbackPages.invalidLink(c);
|
|
49
|
+
if (code === "timeout")
|
|
50
|
+
return CallbackPages.expired(c);
|
|
51
|
+
return CallbackPages.failed(c, code, description);
|
|
52
|
+
}
|
|
53
|
+
static page(status, title, lead, body) {
|
|
54
|
+
const icon = `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7L7 17" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round"/></svg>`;
|
|
55
|
+
const html = `<!doctype html>
|
|
56
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
57
|
+
<title>${CallbackPages.escape(title)} - Protokol</title>
|
|
58
|
+
<style>
|
|
59
|
+
:root{--bg:#f8f9fa;--card:#fff;--text:#1f2328;--muted:#656d76;--line:rgba(0,0,0,.08);--code:#f1f3f4;--err:#d64545;--p1:#6c80ff;--p2:#764ba2}
|
|
60
|
+
@media (prefers-color-scheme:dark){:root{--bg:#1e1f22;--card:#313338;--text:#f2f3f5;--muted:#b5bac1;--line:rgba(255,255,255,.08);--code:#2b2d31}}
|
|
61
|
+
*{box-sizing:border-box}
|
|
62
|
+
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:16px;background:var(--bg);color:var(--text);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
63
|
+
main{width:100%;max-width:440px;background:var(--card);border:1px solid var(--line);border-radius:16px;padding:40px 32px 28px;text-align:center;box-shadow:0 8px 32px rgba(0,0,0,.08)}
|
|
64
|
+
.brand{font-weight:700;letter-spacing:.04em;background:linear-gradient(90deg,var(--p1),var(--p2));-webkit-background-clip:text;background-clip:text;color:transparent;margin-bottom:28px}
|
|
65
|
+
.icon{width:56px;height:56px;border-radius:50%;margin:0 auto 20px;padding:13px;background:var(--err)}
|
|
66
|
+
h1{font-size:1.35rem;line-height:1.3;margin:0 0 8px}
|
|
67
|
+
.lead{color:var(--muted);margin:0 0 24px}
|
|
68
|
+
pre,code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
69
|
+
pre{margin:0 0 8px;padding:12px;background:var(--code);border-radius:10px;font-size:.85rem;text-align:left;white-space:pre-wrap;word-break:break-all}
|
|
70
|
+
.retry{color:var(--muted);margin:0 0 8px;text-align:left;font-size:.9rem}
|
|
71
|
+
.code{font-family:ui-monospace,Menlo,monospace;font-size:.85rem;margin:0 0 4px}.desc{color:var(--muted);font-size:.9rem;margin:0 0 20px;word-break:break-word}
|
|
72
|
+
</style></head>
|
|
73
|
+
<body><main>
|
|
74
|
+
<div class="brand">PROTOKOL</div>
|
|
75
|
+
<div class="icon">${icon}</div>
|
|
76
|
+
<h1>${CallbackPages.escape(title)}</h1>
|
|
77
|
+
<p class="lead">${CallbackPages.escape(lead)}</p>
|
|
78
|
+
${body}
|
|
79
|
+
</main></body></html>`;
|
|
80
|
+
return { status, html };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import OAuthError from "./OAuthError.js";
|
|
3
|
+
import CallbackPages, { GUIDE_URL, PAGE_HEADERS } from "./CallbackPages.js";
|
|
4
|
+
/** One-shot loopback redirect receiver (RFC 8252 §7.3). Binds 127.0.0.1 only and
|
|
5
|
+
* settles on the first request to /callback. */
|
|
6
|
+
export default class CallbackServer {
|
|
7
|
+
server;
|
|
8
|
+
redirectUri;
|
|
9
|
+
result;
|
|
10
|
+
pending;
|
|
11
|
+
ctx;
|
|
12
|
+
static path = "/callback";
|
|
13
|
+
constructor(server, redirectUri, result, pending, ctx) {
|
|
14
|
+
this.server = server;
|
|
15
|
+
this.redirectUri = redirectUri;
|
|
16
|
+
this.result = result;
|
|
17
|
+
this.pending = pending;
|
|
18
|
+
this.ctx = ctx;
|
|
19
|
+
}
|
|
20
|
+
static async start(expectedState, ctx, port = 0, timeoutMs = 120_000) {
|
|
21
|
+
let settle;
|
|
22
|
+
const result = new Promise((resolve, reject) => { settle = { resolve, reject }; });
|
|
23
|
+
result.catch(() => { });
|
|
24
|
+
let done = false;
|
|
25
|
+
const pending = {};
|
|
26
|
+
const send = (res, page) => res.writeHead(page.status, PAGE_HEADERS).end(page.html);
|
|
27
|
+
const finish = (fn) => { if (!done) {
|
|
28
|
+
done = true;
|
|
29
|
+
fn();
|
|
30
|
+
} };
|
|
31
|
+
const server = http.createServer((req, res) => {
|
|
32
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
33
|
+
if (req.method !== "GET" || url.pathname !== CallbackServer.path || done) {
|
|
34
|
+
res.writeHead(404).end();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const q = url.searchParams;
|
|
38
|
+
const fail = (e) => {
|
|
39
|
+
send(res, CallbackPages.forError(ctx, e.code, e.description));
|
|
40
|
+
finish(() => settle.reject(e));
|
|
41
|
+
};
|
|
42
|
+
if (q.get("state") !== expectedState)
|
|
43
|
+
return fail(new OAuthError("state_mismatch", "The authorization response state did not match."));
|
|
44
|
+
if (q.get("error"))
|
|
45
|
+
return fail(new OAuthError(q.get("error"), q.get("error_description") ?? undefined));
|
|
46
|
+
const code = q.get("code");
|
|
47
|
+
if (!code)
|
|
48
|
+
return fail(new OAuthError("invalid_response", "The authorization response had no code."));
|
|
49
|
+
pending.res = res; // answered by finish() once the code exchange has succeeded or failed
|
|
50
|
+
finish(() => settle.resolve({ code, iss: q.get("iss") ?? undefined }));
|
|
51
|
+
});
|
|
52
|
+
await new Promise((resolve, reject) => {
|
|
53
|
+
server.once("error", reject);
|
|
54
|
+
server.listen(port, "127.0.0.1", resolve);
|
|
55
|
+
});
|
|
56
|
+
const actual = server.address().port;
|
|
57
|
+
const timer = setTimeout(() => finish(() => settle.reject(new OAuthError("timeout", "Timed out waiting for the browser login."))), timeoutMs);
|
|
58
|
+
timer.unref();
|
|
59
|
+
result.finally(() => clearTimeout(timer)).catch(() => { });
|
|
60
|
+
return new CallbackServer(server, `http://127.0.0.1:${actual}${CallbackServer.path}`, result, pending, ctx);
|
|
61
|
+
}
|
|
62
|
+
wait() {
|
|
63
|
+
return this.result;
|
|
64
|
+
}
|
|
65
|
+
/** Answer the waiting browser tab with the final outcome. */
|
|
66
|
+
finish(error) {
|
|
67
|
+
const res = this.pending.res;
|
|
68
|
+
if (!res || res.writableEnded)
|
|
69
|
+
return;
|
|
70
|
+
if (!error) {
|
|
71
|
+
res.writeHead(302, { Location: GUIDE_URL, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }).end();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const page = CallbackPages.forError(this.ctx, error.code, error.description);
|
|
75
|
+
res.writeHead(page.status, PAGE_HEADERS).end(page.html);
|
|
76
|
+
}
|
|
77
|
+
close() {
|
|
78
|
+
this.finish(new OAuthError("server_error", "The login did not complete."));
|
|
79
|
+
return new Promise(resolve => {
|
|
80
|
+
this.server.close(() => resolve());
|
|
81
|
+
this.server.closeAllConnections();
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import OAuthError from "./OAuthError.js";
|
|
2
|
+
/** Protocol calls against the platform authorization server. Public client: no secret. */
|
|
3
|
+
export default class OAuthClient {
|
|
4
|
+
fetchImpl;
|
|
5
|
+
now;
|
|
6
|
+
constructor(fetchImpl = fetch, now = Date.now) {
|
|
7
|
+
this.fetchImpl = fetchImpl;
|
|
8
|
+
this.now = now;
|
|
9
|
+
}
|
|
10
|
+
async discover(host) {
|
|
11
|
+
const url = `${host.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`;
|
|
12
|
+
const res = await this.fetchImpl(url, { headers: { Accept: "application/json" } });
|
|
13
|
+
if (res.status === 404)
|
|
14
|
+
throw new OAuthError("not_enabled", `OAuth is not enabled on ${host}.`, 404);
|
|
15
|
+
if (!res.ok)
|
|
16
|
+
throw new OAuthError("discovery_failed", `Discovery returned HTTP ${res.status}.`, res.status);
|
|
17
|
+
const doc = await res.json();
|
|
18
|
+
if (!doc.authorization_endpoint || !doc.token_endpoint)
|
|
19
|
+
throw new OAuthError("discovery_failed", "Discovery document is incomplete.");
|
|
20
|
+
return doc;
|
|
21
|
+
}
|
|
22
|
+
authorizeUrl(d, p) {
|
|
23
|
+
const q = new URLSearchParams({
|
|
24
|
+
response_type: "code",
|
|
25
|
+
client_id: p.clientId,
|
|
26
|
+
redirect_uri: p.redirectUri,
|
|
27
|
+
project_id: p.project,
|
|
28
|
+
state: p.state,
|
|
29
|
+
code_challenge: p.challenge,
|
|
30
|
+
code_challenge_method: "S256",
|
|
31
|
+
scope: p.scope,
|
|
32
|
+
});
|
|
33
|
+
return `${d.authorization_endpoint}?${q}`;
|
|
34
|
+
}
|
|
35
|
+
exchangeCode(tokenEndpoint, p) {
|
|
36
|
+
return this.token(tokenEndpoint, {
|
|
37
|
+
grant_type: "authorization_code",
|
|
38
|
+
client_id: p.clientId,
|
|
39
|
+
code: p.code,
|
|
40
|
+
redirect_uri: p.redirectUri,
|
|
41
|
+
code_verifier: p.verifier,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
refresh(tokenEndpoint, p) {
|
|
45
|
+
return this.token(tokenEndpoint, {
|
|
46
|
+
grant_type: "refresh_token",
|
|
47
|
+
client_id: p.clientId,
|
|
48
|
+
refresh_token: p.refreshToken,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async revoke(revocationEndpoint, p) {
|
|
52
|
+
await this.post(revocationEndpoint, { token: p.token, token_type_hint: "refresh_token", client_id: p.clientId });
|
|
53
|
+
}
|
|
54
|
+
async token(endpoint, form) {
|
|
55
|
+
const res = await this.post(endpoint, form);
|
|
56
|
+
const body = await res.json();
|
|
57
|
+
if (!body?.access_token)
|
|
58
|
+
throw new OAuthError("invalid_response", "Token response had no access_token.");
|
|
59
|
+
return {
|
|
60
|
+
accessToken: body.access_token,
|
|
61
|
+
refreshToken: body.refresh_token,
|
|
62
|
+
expiresAt: this.now() + Number(body.expires_in ?? 0) * 1000,
|
|
63
|
+
scope: body.scope ?? "",
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
async post(endpoint, form) {
|
|
67
|
+
const res = await this.fetchImpl(endpoint, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
70
|
+
body: new URLSearchParams(form).toString(),
|
|
71
|
+
});
|
|
72
|
+
if (res.ok)
|
|
73
|
+
return res;
|
|
74
|
+
let body = {};
|
|
75
|
+
try {
|
|
76
|
+
body = await res.json();
|
|
77
|
+
}
|
|
78
|
+
catch { /* non-JSON error */ }
|
|
79
|
+
throw new OAuthError(body.error ?? "server_error", body.error_description ?? `HTTP ${res.status}`, res.status);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** An OAuth protocol error (RFC 6749 §5.2 body) or a local flow failure. */
|
|
2
|
+
export default class OAuthError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
description;
|
|
5
|
+
status;
|
|
6
|
+
constructor(code, description, status) {
|
|
7
|
+
super(description && code === "unavailable" ? description : description ? `${code}: ${description}` : code);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.description = description;
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.name = "OAuthError";
|
|
12
|
+
}
|
|
13
|
+
/** Refresh token rejected: the session is gone and needs a new login. */
|
|
14
|
+
get needsLogin() {
|
|
15
|
+
return this.code === "invalid_grant";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import open from "open";
|
|
2
|
+
import OAuthClient from "./OAuthClient.js";
|
|
3
|
+
import CallbackServer from "./CallbackServer.js";
|
|
4
|
+
import OAuthError from "./OAuthError.js";
|
|
5
|
+
import Pkce from "./Pkce.js";
|
|
6
|
+
/** Authorization code + PKCE for a native app (RFC 8252). */
|
|
7
|
+
export default class OAuthLogin {
|
|
8
|
+
client;
|
|
9
|
+
constructor(client = new OAuthClient()) {
|
|
10
|
+
this.client = client;
|
|
11
|
+
}
|
|
12
|
+
async run(o) {
|
|
13
|
+
let discovery;
|
|
14
|
+
try {
|
|
15
|
+
discovery = await this.client.discover(o.host);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new OAuthError("unavailable", `OAuth login isn't available on ${o.host}; use \`ptkl profile auth --legacy\``);
|
|
19
|
+
}
|
|
20
|
+
const pkce = Pkce.generate();
|
|
21
|
+
const server = await CallbackServer.start(pkce.state, { name: o.name, host: o.host, project: o.project, isNew: !!o.isNew }, o.port ?? 0, o.timeoutMs);
|
|
22
|
+
try {
|
|
23
|
+
const url = this.client.authorizeUrl(discovery, {
|
|
24
|
+
clientId: o.clientId,
|
|
25
|
+
redirectUri: server.redirectUri,
|
|
26
|
+
project: o.project,
|
|
27
|
+
state: pkce.state,
|
|
28
|
+
challenge: pkce.challenge,
|
|
29
|
+
scope: o.scope,
|
|
30
|
+
});
|
|
31
|
+
if (o.noBrowser) {
|
|
32
|
+
o.print("Open this URL in a browser to log in:");
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
o.print("Opening the browser to log in. If it does not open, visit:");
|
|
36
|
+
open(url).catch(() => { });
|
|
37
|
+
}
|
|
38
|
+
o.print(url);
|
|
39
|
+
const { code, iss } = await server.wait();
|
|
40
|
+
if (iss && iss !== discovery.issuer)
|
|
41
|
+
throw new OAuthError("issuer_mismatch", "The authorization response came from an unexpected issuer.");
|
|
42
|
+
const tokens = await this.client.exchangeCode(discovery.token_endpoint, {
|
|
43
|
+
clientId: o.clientId,
|
|
44
|
+
code,
|
|
45
|
+
redirectUri: server.redirectUri,
|
|
46
|
+
verifier: pkce.verifier,
|
|
47
|
+
});
|
|
48
|
+
server.finish();
|
|
49
|
+
return { discovery, tokens };
|
|
50
|
+
}
|
|
51
|
+
catch (e) {
|
|
52
|
+
if (e instanceof OAuthError)
|
|
53
|
+
server.finish(e);
|
|
54
|
+
throw e;
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
await server.close();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import OAuthClient from "./OAuthClient.js";
|
|
2
|
+
import RefreshLock from "./RefreshLock.js";
|
|
3
|
+
import OAuthError from "./OAuthError.js";
|
|
4
|
+
import Util from "../util.js";
|
|
5
|
+
/** Lifecycle of the tokens stored on an OAuth profile: refresh and logout. */
|
|
6
|
+
export default class OAuthSession {
|
|
7
|
+
client;
|
|
8
|
+
now;
|
|
9
|
+
static skewMs = 60_000;
|
|
10
|
+
constructor(client = new OAuthClient(), now = Date.now) {
|
|
11
|
+
this.client = client;
|
|
12
|
+
this.now = now;
|
|
13
|
+
}
|
|
14
|
+
static isOAuth(p) {
|
|
15
|
+
return p?.auth === "oauth";
|
|
16
|
+
}
|
|
17
|
+
static mask(value) {
|
|
18
|
+
if (!value)
|
|
19
|
+
return value;
|
|
20
|
+
return value.length <= 8 ? "****" : `${value.slice(0, 4)}...****`;
|
|
21
|
+
}
|
|
22
|
+
/** Copy of the profile that is safe to print. */
|
|
23
|
+
static masked(p) {
|
|
24
|
+
return { ...p, token: OAuthSession.mask(p.token), refresh_token: OAuthSession.mask(p.refresh_token) };
|
|
25
|
+
}
|
|
26
|
+
needsRefresh(p) {
|
|
27
|
+
return OAuthSession.isOAuth(p) && (p.expires_at ?? 0) - this.now() < OAuthSession.skewMs;
|
|
28
|
+
}
|
|
29
|
+
/** Refreshes an expired or near-expiry OAuth profile, persisting the rotated refresh token.
|
|
30
|
+
* Serialized per profile: a second caller finds the first one's fresh token and reuses it. */
|
|
31
|
+
async ensureFresh(profile) {
|
|
32
|
+
if (!this.needsRefresh(profile))
|
|
33
|
+
return profile;
|
|
34
|
+
const lock = await RefreshLock.acquire(`${Util.profileDir()}/${encodeURIComponent(profile.name)}.refresh.lock`);
|
|
35
|
+
try {
|
|
36
|
+
const current = (Util.getProfiles() ?? []).find(p => p.name === profile.name) ?? profile;
|
|
37
|
+
if (!this.needsRefresh(current))
|
|
38
|
+
return current;
|
|
39
|
+
return await this.refresh(current);
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
lock.release();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async refresh(current) {
|
|
46
|
+
if (!current.refresh_token || !current.token_endpoint || !current.client_id) {
|
|
47
|
+
throw new OAuthError("invalid_grant", "No refresh token stored.");
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const t = await this.client.refresh(current.token_endpoint, {
|
|
51
|
+
clientId: current.client_id,
|
|
52
|
+
refreshToken: current.refresh_token,
|
|
53
|
+
});
|
|
54
|
+
const next = {
|
|
55
|
+
...current,
|
|
56
|
+
token: t.accessToken,
|
|
57
|
+
// Strict rotation: the old refresh token is dead once this succeeds.
|
|
58
|
+
refresh_token: t.refreshToken ?? current.refresh_token,
|
|
59
|
+
expires_at: t.expiresAt,
|
|
60
|
+
scope: t.scope || current.scope,
|
|
61
|
+
};
|
|
62
|
+
Util.updateProfile(next);
|
|
63
|
+
return next;
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
if (e instanceof OAuthError && e.needsLogin) {
|
|
67
|
+
throw new OAuthError("invalid_grant", `Your OAuth session for profile '${current.name}' has expired or was revoked. Run \`ptkl profile oauth -n ${current.name} --client-id ${current.client_id} -P ${current.project} -h ${current.host}\` to log in again.`);
|
|
68
|
+
}
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Revokes the refresh token server-side and clears stored tokens. */
|
|
73
|
+
async logout(profile) {
|
|
74
|
+
if (!OAuthSession.isOAuth(profile))
|
|
75
|
+
throw new Error(`Profile '${profile.name}' is not an OAuth profile`);
|
|
76
|
+
try {
|
|
77
|
+
if (profile.refresh_token && profile.revocation_endpoint && profile.client_id) {
|
|
78
|
+
await this.client.revoke(profile.revocation_endpoint, { clientId: profile.client_id, token: profile.refresh_token });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
// Clear locally even if the server was unreachable.
|
|
83
|
+
Util.updateProfile({ ...profile, token: "", refresh_token: undefined, expires_at: 0 });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Human-readable explanation when an API call fails under an OAuth token. */
|
|
87
|
+
static describeApiError(err, profile) {
|
|
88
|
+
const res = err?.response;
|
|
89
|
+
if (!res)
|
|
90
|
+
return undefined;
|
|
91
|
+
const challenge = String(res.headers?.["www-authenticate"] ?? "");
|
|
92
|
+
if (res.status === 403 && (/insufficient_scope/.test(challenge) || OAuthSession.isOAuth(profile))) {
|
|
93
|
+
const named = /scope="([^"]+)"/.exec(challenge)?.[1] ?? res.data?.required_scope ?? res.data?.scope;
|
|
94
|
+
const missing = typeof named === "string" && named.trim() ? named.trim() : undefined;
|
|
95
|
+
return `This profile's token lacks ${missing ? `the permission "${missing}"` : "a permission this command needs"}. `
|
|
96
|
+
+ `Log in again with \`ptkl profile new --add-scope "${missing ?? "<permission>"}"\`, or use an API-user profile (\`--legacy\`) for CI.`;
|
|
97
|
+
}
|
|
98
|
+
if (res.status === 401 && OAuthSession.isOAuth(profile)) {
|
|
99
|
+
return `The OAuth token was rejected. Run \`ptkl profile oauth\` again to log in${profile ? ` (profile '${profile.name}')` : ""}.`;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
}
|