@ptkl/toolkit 1.3.2 → 1.4.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,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 => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[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,100 @@
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
+ return "This command isn't available to OAuth tokens (insufficient scope). Use a profile created with `ptkl profile new`.";
94
+ }
95
+ if (res.status === 401 && OAuthSession.isOAuth(profile)) {
96
+ return `The OAuth token was rejected. Run \`ptkl profile oauth\` again to log in${profile ? ` (profile '${profile.name}')` : ""}.`;
97
+ }
98
+ return undefined;
99
+ }
100
+ }
@@ -0,0 +1,19 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ /** RFC 7636 S256 verifier/challenge pair plus the CSRF `state` value. */
3
+ export default class Pkce {
4
+ verifier;
5
+ challenge;
6
+ state;
7
+ constructor(verifier, challenge, state) {
8
+ this.verifier = verifier;
9
+ this.challenge = challenge;
10
+ this.state = state;
11
+ }
12
+ static challengeFor(verifier) {
13
+ return createHash("sha256").update(verifier).digest("base64url");
14
+ }
15
+ static generate() {
16
+ const verifier = randomBytes(48).toString("base64url");
17
+ return new Pkce(verifier, Pkce.challengeFor(verifier), randomBytes(24).toString("base64url"));
18
+ }
19
+ }
@@ -0,0 +1,76 @@
1
+ import OAuthLogin from "./OAuthLogin.js";
2
+ import OAuthSession from "./OAuthSession.js";
3
+ import ScopePreset from "./ScopePreset.js";
4
+ import Util from "../util.js";
5
+ import { APIUser } from "@ptkl/sdk";
6
+ /** Routing and persistence for `profile new` / `profile auth` OAuth logins. */
7
+ export default class ProfileLogin {
8
+ // First-party CLI client; the same id is provisioned in every environment.
9
+ static defaultClientId = "pk_cli_0c11c11c11c11c11c11c11c11c11c11c";
10
+ /** Explicit --legacy, or any legacy-only credential flag, selects password/token auth. */
11
+ static useLegacy(f) {
12
+ return !!f.legacy || !!f.token || (f.password !== undefined && f.password !== false) || !!f.username;
13
+ }
14
+ static resolveClientId(flag, profile, env = process.env) {
15
+ return flag || profile?.client_id || env.PTKL_OAUTH_CLIENT_ID || ProfileLogin.defaultClientId;
16
+ }
17
+ /** Browser login; creates or updates the named profile. */
18
+ static async login(base, f, print) {
19
+ const profiles = Util.getProfiles() ?? [];
20
+ const existing = profiles.find(p => p.name == base.name);
21
+ const clientId = ProfileLogin.resolveClientId(f.clientId, existing);
22
+ const { discovery, tokens } = await new OAuthLogin().run({
23
+ host: base.host,
24
+ name: base.name,
25
+ isNew: !existing,
26
+ clientId,
27
+ project: base.project,
28
+ scope: ScopePreset.toWire(ScopePreset.resolve(f)),
29
+ port: f.port ? Number(f.port) : undefined,
30
+ noBrowser: f.browser === false,
31
+ print,
32
+ });
33
+ // OAuth profiles carry no username; drop one left by a legacy login or the old "oauth" placeholder.
34
+ const { username: _dropped, ...kept } = existing ?? {};
35
+ const profile = {
36
+ ...kept,
37
+ name: base.name,
38
+ host: base.host,
39
+ project: base.project,
40
+ token: tokens.accessToken,
41
+ current: existing?.current ?? !profiles.some(p => p.current),
42
+ auth: "oauth",
43
+ refresh_token: tokens.refreshToken,
44
+ expires_at: tokens.expiresAt,
45
+ client_id: clientId,
46
+ token_endpoint: discovery.token_endpoint,
47
+ revocation_endpoint: discovery.revocation_endpoint,
48
+ scope: tokens.scope,
49
+ };
50
+ Util.updateProfiles(existing ? profiles.map(p => p.name == base.name ? profile : p) : [...profiles, profile]);
51
+ return profile;
52
+ }
53
+ /** API-user login (POST /v1/user/api/auth); returns the token. Never echoes the secret. */
54
+ static async apiUserToken(host, username, secret, project) {
55
+ try {
56
+ const { data } = await new APIUser({ host }).auth(username, secret, project);
57
+ if (!data?.Token)
58
+ throw new Error("no token in response");
59
+ return data.Token;
60
+ }
61
+ catch (e) {
62
+ const detail = e?.response?.data?.message ?? e?.response?.data?.error ?? e?.message ?? "unknown error";
63
+ throw new Error(`API-user authentication failed: ${detail}`);
64
+ }
65
+ }
66
+ /** Login name for a legacy password login: --username, else the stored one (never an OAuth profile's). */
67
+ static legacyUsername(profile, flag) {
68
+ return flag || (OAuthSession.isOAuth(profile) ? undefined : profile.username) || undefined;
69
+ }
70
+ /** Plain legacy profile: every OAuth field removed, so the next command doesn't refresh over the new token. */
71
+ static toLegacy(profile, { username, token }) {
72
+ const { auth, refresh_token, expires_at, client_id, token_endpoint, revocation_endpoint, scope, username: stored, ...rest } = profile;
73
+ const keep = username ?? (OAuthSession.isOAuth(profile) ? undefined : stored);
74
+ return { ...rest, token, ...(keep ? { username: keep } : {}) };
75
+ }
76
+ }
@@ -0,0 +1,61 @@
1
+ import { closeSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
2
+ import OAuthError from "./OAuthError.js";
3
+ /** Per-profile cross-process lock. Refresh-token reuse revokes the whole token
4
+ * family, so concurrent refreshes must be serialized. */
5
+ export default class RefreshLock {
6
+ path;
7
+ static staleMs = 30_000;
8
+ static waitMs = 10_000;
9
+ constructor(path) {
10
+ this.path = path;
11
+ }
12
+ static async acquire(path, waitMs = RefreshLock.waitMs, staleMs = RefreshLock.staleMs) {
13
+ const deadline = Date.now() + waitMs;
14
+ for (let delay = 20;; delay = Math.min(delay * 2, 250)) {
15
+ try {
16
+ const fd = openSync(path, "wx", 0o600);
17
+ writeSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
18
+ closeSync(fd);
19
+ return new RefreshLock(path);
20
+ }
21
+ catch (e) {
22
+ if (e.code !== "EEXIST")
23
+ throw e;
24
+ }
25
+ if (RefreshLock.isStale(path, staleMs)) {
26
+ try {
27
+ unlinkSync(path);
28
+ }
29
+ catch { /* lost the race to another taker */ }
30
+ continue;
31
+ }
32
+ if (Date.now() > deadline)
33
+ throw new OAuthError("lock_timeout", "Timed out waiting for another ptkl process to finish refreshing the OAuth token.");
34
+ await new Promise(r => setTimeout(r, delay));
35
+ }
36
+ }
37
+ static isStale(path, staleMs) {
38
+ try {
39
+ const { pid, at } = JSON.parse(readFileSync(path, "utf8"));
40
+ if (Date.now() - at > staleMs)
41
+ return true;
42
+ try {
43
+ process.kill(pid, 0);
44
+ }
45
+ catch (e) {
46
+ return e.code === "ESRCH";
47
+ }
48
+ return false;
49
+ }
50
+ catch (e) {
51
+ // Unreadable or half-written file: let it age out via the owner, or vanish.
52
+ return false;
53
+ }
54
+ }
55
+ release() {
56
+ try {
57
+ unlinkSync(this.path);
58
+ }
59
+ catch { /* already gone */ }
60
+ }
61
+ }
@@ -0,0 +1,38 @@
1
+ /** Default OAuth scope for `ptkl profile oauth`: least privilege for the toolkit
2
+ * commands whose platform routes OAuth admits (docs/oauth-route-inventory.json,
3
+ * policy SCOPED/SHARED and oauth_audited). The user's own authority still bounds
4
+ * what is granted, and scope never grows on its own: re-run the login after
5
+ * creating resources whose per-resource permissions you need. */
6
+ export const SCOPE_PRESET = [
7
+ { permission: "manage base_platform_apps", commands: "apps" },
8
+ { permission: "manage base_functions", commands: "functions" },
9
+ { permission: "manage base_components", commands: "component, generate-types, ratchet test connection" },
10
+ { permission: "manage base_templates", commands: "template" },
11
+ { permission: "manage base_thunder", commands: "thunder" },
12
+ { permission: "read base_ratchet", commands: "ratchet (list/get)" },
13
+ { permission: "inspect base_ratchet", commands: "ratchet (query inspect)" },
14
+ { permission: "read base_users", commands: "users (list)" },
15
+ { permission: "edit base_users", commands: "api-users (list/get/edit/revoke-secret)" },
16
+ { permission: "manage_secrets base_users", commands: "api-users (new/new-secret)" },
17
+ { permission: "read base_roles", commands: "role (list)" },
18
+ { permission: "get global_env", commands: "config (read)" },
19
+ // Non-live envs need "<env> env_access"; dev is the CLI's default env.
20
+ { permission: "dev env_access", commands: "every command on the dev env (the default)" },
21
+ ];
22
+ export default class ScopePreset {
23
+ static permissions = SCOPE_PRESET.map(p => p.permission);
24
+ /** `--scope` / `--add-scope` value -> entries. `pattern:<regex>` is a regex expression. */
25
+ static parse(list) {
26
+ return list.split(",").map(s => s.trim()).filter(Boolean);
27
+ }
28
+ /** Wire scope: `offline_access` (refresh token) plus typed `perm64:`/`pattern64:` entries. */
29
+ static toWire(entries) {
30
+ const enc = (s) => Buffer.from(s).toString("base64url");
31
+ const parts = entries.map(e => e.startsWith("pattern:") ? `pattern64:${enc(e.slice(8))}` : `perm64:${enc(e)}`);
32
+ return ["offline_access", ...parts].join(" ");
33
+ }
34
+ static resolve(o) {
35
+ const base = o.scope ? ScopePreset.parse(o.scope) : ScopePreset.permissions;
36
+ return [...new Set([...base, ...(o.addScope ? ScopePreset.parse(o.addScope) : [])])];
37
+ }
38
+ }
@@ -0,0 +1,29 @@
1
+ import http from "node:http";
2
+ /** Minimal OAuth authorization server for tests. */
3
+ export async function startMock(handlers = {}) {
4
+ const calls = [];
5
+ let tokenCalls = 0;
6
+ const server = http.createServer((req, res) => {
7
+ let body = "";
8
+ req.on("data", c => body += c);
9
+ req.on("end", () => {
10
+ const base = `http://127.0.0.1:${server.address().port}`;
11
+ const send = (status, json) => { res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(json)); };
12
+ if (req.url === "/.well-known/oauth-authorization-server") {
13
+ return send(200, { issuer: base, authorization_endpoint: `${base}/v1/oauth/authorize`, token_endpoint: `${base}/v1/oauth/token`, revocation_endpoint: `${base}/v1/oauth/revoke` });
14
+ }
15
+ const form = Object.fromEntries(new URLSearchParams(body));
16
+ calls.push({ path: req.url, form });
17
+ if (req.url === "/v1/oauth/token") {
18
+ const [status, json] = handlers.token?.(form, ++tokenCalls) ?? [200, { access_token: "at", token_type: "Bearer", expires_in: 900, refresh_token: "rt", scope: "offline_access" }];
19
+ return send(status, json);
20
+ }
21
+ if (req.url === "/v1/oauth/revoke")
22
+ return send(200, {});
23
+ send(404, {});
24
+ });
25
+ });
26
+ await new Promise(r => server.listen(0, "127.0.0.1", r));
27
+ const base = `http://127.0.0.1:${server.address().port}`;
28
+ return { base, calls, close: () => { server.closeAllConnections(); return new Promise(r => server.close(() => r())); } };
29
+ }