@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
|
@@ -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,58 @@
|
|
|
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: "list forge", commands: "forge list" },
|
|
13
|
+
{ permission: "read thunder", commands: "thunder (data read)" },
|
|
14
|
+
{ permission: "write thunder", commands: "thunder (data write)" },
|
|
15
|
+
{ permission: "manage base_workflows", commands: "workflow" },
|
|
16
|
+
{ permission: "create base_users", commands: "project invite, invites" },
|
|
17
|
+
{ permission: "manage integrations", commands: "integration list/install" },
|
|
18
|
+
{ permission: "view_transactions protokol-payments", commands: "integration payments (transactions)" },
|
|
19
|
+
{ permission: "refund_transaction protokol-payments", commands: "integration payments refund" },
|
|
20
|
+
{ permission: "void_transaction protokol-payments", commands: "integration payments void/deactivate" },
|
|
21
|
+
{ permission: "read protokol-mail", commands: "integration mail (list/get/attachments)" },
|
|
22
|
+
{ permission: "send protokol-mail", commands: "integration mail (send/resend)" },
|
|
23
|
+
{ permission: "manage timber", commands: "integration timber query/usage, logs" },
|
|
24
|
+
{ permission: "write timber", commands: "integration timber write" },
|
|
25
|
+
{ permission: "use protokol-media", commands: "integration dms (dirs, backup, policies, reminders, download)" },
|
|
26
|
+
{ permission: "utilities protokol-media", commands: "integration dms (libraries, convert, ocr)" },
|
|
27
|
+
{ permission: "upload protokol-media", commands: "integration dms upload" },
|
|
28
|
+
{ permission: "read_documents protokol-media", commands: "integration dms document (read/list/revisions/generate)" },
|
|
29
|
+
{ permission: "create_document protokol-media", commands: "integration dms document create" },
|
|
30
|
+
{ permission: "edit_document protokol-media", commands: "integration dms document (update/comment)" },
|
|
31
|
+
{ permission: "delete_document protokol-media", commands: "integration dms document (delete/restore)" },
|
|
32
|
+
{ permission: "read base_ratchet", commands: "ratchet (list/get)" },
|
|
33
|
+
{ permission: "inspect base_ratchet", commands: "ratchet (query inspect)" },
|
|
34
|
+
{ permission: "read base_users", commands: "users (list)" },
|
|
35
|
+
{ permission: "edit base_users", commands: "api-users (list/get/edit/revoke-secret)" },
|
|
36
|
+
{ permission: "manage_secrets base_users", commands: "api-users (new/new-secret)" },
|
|
37
|
+
{ permission: "read base_roles", commands: "role (list)" },
|
|
38
|
+
{ permission: "get global_env", commands: "config (read)" },
|
|
39
|
+
// Non-live envs need "<env> env_access"; dev is the CLI's default env.
|
|
40
|
+
{ permission: "dev env_access", commands: "every command on the dev env (the default)" },
|
|
41
|
+
];
|
|
42
|
+
export default class ScopePreset {
|
|
43
|
+
static permissions = SCOPE_PRESET.map(p => p.permission);
|
|
44
|
+
/** `--scope` / `--add-scope` value -> entries. `pattern:<regex>` is a regex expression. */
|
|
45
|
+
static parse(list) {
|
|
46
|
+
return list.split(",").map(s => s.trim()).filter(Boolean);
|
|
47
|
+
}
|
|
48
|
+
/** Wire scope: `offline_access` (refresh token) plus typed `perm64:`/`pattern64:` entries. */
|
|
49
|
+
static toWire(entries) {
|
|
50
|
+
const enc = (s) => Buffer.from(s).toString("base64url");
|
|
51
|
+
const parts = entries.map(e => e.startsWith("pattern:") ? `pattern64:${enc(e.slice(8))}` : `perm64:${enc(e)}`);
|
|
52
|
+
return ["offline_access", ...parts].join(" ");
|
|
53
|
+
}
|
|
54
|
+
static resolve(o) {
|
|
55
|
+
const base = o.scope ? ScopePreset.parse(o.scope) : ScopePreset.permissions;
|
|
56
|
+
return [...new Set([...base, ...(o.addScope ? ScopePreset.parse(o.addScope) : [])])];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
5
|
+
import { startMock } from "./mockServer.js";
|
|
6
|
+
const home = mkdtempSync(join(tmpdir(), "ptkl-oauth-"));
|
|
7
|
+
process.env.HOME = home;
|
|
8
|
+
mkdirSync(join(home, ".ptkl"));
|
|
9
|
+
const profilesFile = join(home, ".ptkl", "profiles.json");
|
|
10
|
+
const { default: Pkce } = await import("../Pkce.js");
|
|
11
|
+
const { default: CallbackServer } = await import("../CallbackServer.js");
|
|
12
|
+
const { default: OAuthClient } = await import("../OAuthClient.js");
|
|
13
|
+
const { default: ScopePreset } = await import("../ScopePreset.js");
|
|
14
|
+
const { default: OAuthLogin } = await import("../OAuthLogin.js");
|
|
15
|
+
const { default: OAuthSession } = await import("../OAuthSession.js");
|
|
16
|
+
const { default: RefreshLock } = await import("../RefreshLock.js");
|
|
17
|
+
const { default: ProfileLogin } = await import("../ProfileLogin.js");
|
|
18
|
+
const { default: CallbackPages, PAGE_HEADERS, GUIDE_URL } = await import("../CallbackPages.js");
|
|
19
|
+
const { default: OAuthError } = await import("../OAuthError.js");
|
|
20
|
+
const { default: Util } = await import("../../util.js");
|
|
21
|
+
const ctx = { name: "dev", host: "http://h", project: "proj-uuid", isNew: false };
|
|
22
|
+
const seed = (p) => writeFileSync(profilesFile, JSON.stringify([p]));
|
|
23
|
+
const stored = () => JSON.parse(readFileSync(profilesFile, "utf8"))[0];
|
|
24
|
+
const oauthProfile = (base, over = {}) => ({
|
|
25
|
+
name: "o", host: base, project: "p", current: true, auth: "oauth",
|
|
26
|
+
token: "old-access", refresh_token: "old-refresh", expires_at: Date.now() + 3_600_000,
|
|
27
|
+
client_id: "pk_cli_x", token_endpoint: `${base}/v1/oauth/token`, revocation_endpoint: `${base}/v1/oauth/revoke`, ...over,
|
|
28
|
+
});
|
|
29
|
+
describe("Pkce", () => {
|
|
30
|
+
it("derives an S256 challenge (RFC 7636 appendix B)", () => {
|
|
31
|
+
expect(Pkce.challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
|
|
32
|
+
});
|
|
33
|
+
it("generates distinct verifier/state values within spec length", () => {
|
|
34
|
+
const a = Pkce.generate(), b = Pkce.generate();
|
|
35
|
+
expect(a.verifier.length).toBeGreaterThanOrEqual(43);
|
|
36
|
+
expect(a.verifier).not.toBe(b.verifier);
|
|
37
|
+
expect(a.state).not.toBe(b.state);
|
|
38
|
+
expect(a.challenge).toBe(Pkce.challengeFor(a.verifier));
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
describe("ScopePreset", () => {
|
|
42
|
+
it("encodes offline_access and typed entries", () => {
|
|
43
|
+
expect(ScopePreset.toWire(["read base_users", "pattern:read .*"])).toBe(`offline_access perm64:${Buffer.from("read base_users").toString("base64url")} pattern64:${Buffer.from("read .*").toString("base64url")}`);
|
|
44
|
+
});
|
|
45
|
+
it("defaults to the preset, --scope replaces, --add-scope extends", () => {
|
|
46
|
+
expect(ScopePreset.resolve({})).toEqual(ScopePreset.permissions);
|
|
47
|
+
expect(ScopePreset.resolve({ scope: "a b, c" })).toEqual(["a b", "c"]);
|
|
48
|
+
expect(ScopePreset.resolve({ scope: "x", addScope: "y,x" })).toEqual(["x", "y"]);
|
|
49
|
+
expect(ScopePreset.resolve({ addScope: "edit base_users" })).toContain("edit base_users");
|
|
50
|
+
});
|
|
51
|
+
it("covers thunder data, workflows, invites, forge list and integrations", () => {
|
|
52
|
+
expect(ScopePreset.permissions).toEqual(expect.arrayContaining([
|
|
53
|
+
"read thunder", "write thunder", "manage base_workflows", "create base_users", "list forge", "manage integrations",
|
|
54
|
+
"view_transactions protokol-payments", "refund_transaction protokol-payments", "void_transaction protokol-payments",
|
|
55
|
+
"read protokol-mail", "send protokol-mail", "manage timber", "write timber",
|
|
56
|
+
"use protokol-media", "utilities protokol-media", "upload protokol-media",
|
|
57
|
+
"read_documents protokol-media", "create_document protokol-media", "edit_document protokol-media", "delete_document protokol-media"
|
|
58
|
+
]));
|
|
59
|
+
for (const bad of ["admin", "manage forge"])
|
|
60
|
+
expect(ScopePreset.permissions).not.toContain(bad);
|
|
61
|
+
const wire = ScopePreset.toWire(ScopePreset.permissions);
|
|
62
|
+
expect(wire).toContain(`perm64:${Buffer.from("write thunder").toString("base64url")}`);
|
|
63
|
+
});
|
|
64
|
+
it("asks for API-user management and secrets by default", () => {
|
|
65
|
+
expect(ScopePreset.permissions).toEqual(expect.arrayContaining(["edit base_users", "manage_secrets base_users", "dev env_access"]));
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
describe("authorize URL", () => {
|
|
69
|
+
it("carries every required parameter", () => {
|
|
70
|
+
const u = new URL(new OAuthClient().authorizeUrl({ issuer: "i", authorization_endpoint: "http://h/v1/oauth/authorize", token_endpoint: "t" }, { clientId: "c", redirectUri: "http://127.0.0.1:1/callback", project: "proj", state: "s", challenge: "ch", scope: "offline_access" }));
|
|
71
|
+
const q = u.searchParams;
|
|
72
|
+
expect(u.pathname).toBe("/v1/oauth/authorize");
|
|
73
|
+
expect(Object.fromEntries(q)).toEqual({
|
|
74
|
+
response_type: "code", client_id: "c", redirect_uri: "http://127.0.0.1:1/callback", project_id: "proj",
|
|
75
|
+
state: "s", code_challenge: "ch", code_challenge_method: "S256", scope: "offline_access",
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
describe("CallbackServer", () => {
|
|
80
|
+
it("binds loopback and resolves on a matching state", async () => {
|
|
81
|
+
const s = await CallbackServer.start("st", ctx);
|
|
82
|
+
expect(s.redirectUri).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/);
|
|
83
|
+
const r = fetch(`${s.redirectUri}?code=abc&state=st&iss=x`);
|
|
84
|
+
expect(await s.wait()).toEqual({ code: "abc", iss: "x" });
|
|
85
|
+
s.finish();
|
|
86
|
+
await r;
|
|
87
|
+
await s.close();
|
|
88
|
+
});
|
|
89
|
+
it("rejects a state mismatch", async () => {
|
|
90
|
+
const s = await CallbackServer.start("st", ctx);
|
|
91
|
+
const r = await fetch(`${s.redirectUri}?code=abc&state=evil`);
|
|
92
|
+
expect(r.status).toBe(400);
|
|
93
|
+
await expect(s.wait()).rejects.toMatchObject({ code: "state_mismatch" });
|
|
94
|
+
await s.close();
|
|
95
|
+
});
|
|
96
|
+
it("surfaces an error parameter", async () => {
|
|
97
|
+
const s = await CallbackServer.start("st", ctx);
|
|
98
|
+
await fetch(`${s.redirectUri}?error=access_denied&error_description=nope&state=st`);
|
|
99
|
+
await expect(s.wait()).rejects.toMatchObject({ code: "access_denied", description: "nope" });
|
|
100
|
+
await s.close();
|
|
101
|
+
});
|
|
102
|
+
it("times out", async () => {
|
|
103
|
+
const s = await CallbackServer.start("st", ctx, 0, 50);
|
|
104
|
+
await expect(s.wait()).rejects.toMatchObject({ code: "timeout" });
|
|
105
|
+
await s.close();
|
|
106
|
+
});
|
|
107
|
+
it("answers 404 to other paths and settles only once", async () => {
|
|
108
|
+
const s = await CallbackServer.start("st", ctx);
|
|
109
|
+
expect((await fetch(s.redirectUri.replace("/callback", "/other"))).status).toBe(404);
|
|
110
|
+
const r1 = fetch(`${s.redirectUri}?code=1&state=st`);
|
|
111
|
+
expect((await s.wait()).code).toBe("1");
|
|
112
|
+
expect((await fetch(`${s.redirectUri}?code=2&state=st`)).status).toBe(404);
|
|
113
|
+
s.finish();
|
|
114
|
+
await r1;
|
|
115
|
+
await s.close();
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
describe("OAuthLogin.run", () => {
|
|
119
|
+
it("completes the code flow against a mock server (no browser)", async () => {
|
|
120
|
+
const mock = await startMock();
|
|
121
|
+
const printed = [];
|
|
122
|
+
const login = new OAuthLogin().run({
|
|
123
|
+
host: mock.base, name: "n", clientId: "pk_cli_x", project: "proj", scope: "offline_access", noBrowser: true,
|
|
124
|
+
print: l => printed.push(l),
|
|
125
|
+
});
|
|
126
|
+
// wait for the URL, then play the browser
|
|
127
|
+
while (!printed.some(l => l.includes("/authorize")))
|
|
128
|
+
await new Promise(r => setTimeout(r, 10));
|
|
129
|
+
const url = new URL(printed.find(l => l.includes("/authorize")));
|
|
130
|
+
const redirect = new URL(url.searchParams.get("redirect_uri"));
|
|
131
|
+
redirect.searchParams.set("code", "the-code");
|
|
132
|
+
redirect.searchParams.set("state", url.searchParams.get("state"));
|
|
133
|
+
redirect.searchParams.set("iss", mock.base);
|
|
134
|
+
await fetch(redirect);
|
|
135
|
+
const { tokens } = await login;
|
|
136
|
+
expect(tokens.accessToken).toBe("at");
|
|
137
|
+
expect(tokens.refreshToken).toBe("rt");
|
|
138
|
+
const exchange = mock.calls.find(c => c.path === "/v1/oauth/token").form;
|
|
139
|
+
expect(exchange).toMatchObject({ grant_type: "authorization_code", client_id: "pk_cli_x", code: "the-code", redirect_uri: redirect.origin + "/callback" });
|
|
140
|
+
expect(Pkce.challengeFor(exchange.code_verifier)).toBe(url.searchParams.get("code_challenge"));
|
|
141
|
+
expect(exchange).not.toHaveProperty("client_secret");
|
|
142
|
+
await mock.close();
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
describe("OAuthClient errors", () => {
|
|
146
|
+
it("exposes the platform error body", async () => {
|
|
147
|
+
const mock = await startMock({ token: () => [400, { error: "invalid_grant", error_description: "bad code" }] });
|
|
148
|
+
await expect(new OAuthClient().exchangeCode(`${mock.base}/v1/oauth/token`, { clientId: "c", code: "x", redirectUri: "r", verifier: "v" }))
|
|
149
|
+
.rejects.toMatchObject({ code: "invalid_grant", description: "bad code", status: 400 });
|
|
150
|
+
await mock.close();
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
describe("OAuthSession", () => {
|
|
154
|
+
let mock;
|
|
155
|
+
beforeAll(async () => { mock = await startMock({ token: (f, n) => f.refresh_token === "old-refresh" ? [200, { access_token: `new-access-${n}`, expires_in: 900, refresh_token: "rotated", scope: "s" }] : [400, { error: "invalid_grant" }] }); });
|
|
156
|
+
afterAll(() => mock.close());
|
|
157
|
+
it("leaves a fresh token alone", async () => {
|
|
158
|
+
const p = oauthProfile(mock.base);
|
|
159
|
+
seed(p);
|
|
160
|
+
const out = await new OAuthSession().ensureFresh(p);
|
|
161
|
+
expect(out.token).toBe("old-access");
|
|
162
|
+
expect(mock.calls.filter(c => c.path === "/v1/oauth/token")).toHaveLength(0);
|
|
163
|
+
});
|
|
164
|
+
it("refreshes an expired token and persists the rotated refresh token", async () => {
|
|
165
|
+
const p = oauthProfile(mock.base, { expires_at: Date.now() - 1000 });
|
|
166
|
+
seed(p);
|
|
167
|
+
const out = await new OAuthSession().ensureFresh(p);
|
|
168
|
+
expect(out.token).toMatch(/^new-access/);
|
|
169
|
+
expect(stored()).toMatchObject({ token: out.token, refresh_token: "rotated" });
|
|
170
|
+
expect(stored().expires_at).toBeGreaterThan(Date.now());
|
|
171
|
+
});
|
|
172
|
+
it("refreshes inside the 60s skew window", async () => {
|
|
173
|
+
const p = oauthProfile(mock.base, { expires_at: Date.now() + 30_000 });
|
|
174
|
+
seed(p);
|
|
175
|
+
expect((await new OAuthSession().ensureFresh(p)).refresh_token).toBe("rotated");
|
|
176
|
+
});
|
|
177
|
+
it("reuses a copy another process already refreshed", async () => {
|
|
178
|
+
const before = mock.calls.length;
|
|
179
|
+
seed(oauthProfile(mock.base, { token: "other-process" }));
|
|
180
|
+
const stale = oauthProfile(mock.base, { expires_at: 1 });
|
|
181
|
+
expect((await new OAuthSession().ensureFresh(stale)).token).toBe("other-process");
|
|
182
|
+
expect(mock.calls.length).toBe(before);
|
|
183
|
+
});
|
|
184
|
+
it("tells the user to log in again on invalid_grant", async () => {
|
|
185
|
+
const p = oauthProfile(mock.base, { expires_at: 1, refresh_token: "dead" });
|
|
186
|
+
seed(p);
|
|
187
|
+
await expect(new OAuthSession().ensureFresh(p)).rejects.toThrow(/ptkl profile oauth/);
|
|
188
|
+
});
|
|
189
|
+
it("logout revokes the refresh token and clears stored tokens", async () => {
|
|
190
|
+
const p = oauthProfile(mock.base);
|
|
191
|
+
seed(p);
|
|
192
|
+
await new OAuthSession().logout(p);
|
|
193
|
+
const call = mock.calls.filter(c => c.path === "/v1/oauth/revoke").pop();
|
|
194
|
+
expect(call.form).toMatchObject({ token: "old-refresh", token_type_hint: "refresh_token", client_id: "pk_cli_x" });
|
|
195
|
+
expect(stored().token).toBe("");
|
|
196
|
+
expect(stored().refresh_token).toBeUndefined();
|
|
197
|
+
});
|
|
198
|
+
it("masks tokens", () => {
|
|
199
|
+
const m = OAuthSession.masked(oauthProfile("http://x"));
|
|
200
|
+
expect(JSON.stringify(m)).not.toContain("old-access");
|
|
201
|
+
expect(JSON.stringify(m)).not.toContain("old-refresh");
|
|
202
|
+
});
|
|
203
|
+
it("maps 403 insufficient_scope to an unavailable-to-OAuth message", () => {
|
|
204
|
+
const err = { response: { status: 403, headers: { "www-authenticate": 'Bearer error="insufficient_scope"' } } };
|
|
205
|
+
expect(OAuthSession.describeApiError(err)).toMatch(/lacks a permission this command needs/);
|
|
206
|
+
expect(OAuthSession.describeApiError(err)).toMatch(/--add-scope "<permission>"/);
|
|
207
|
+
expect(OAuthSession.describeApiError(err)).toMatch(/--legacy/);
|
|
208
|
+
const named = { response: { status: 403, headers: { "www-authenticate": 'Bearer error="insufficient_scope", scope="read thunder"' } } };
|
|
209
|
+
expect(OAuthSession.describeApiError(named)).toMatch(/lacks the permission "read thunder"[\s\S]*--add-scope "read thunder"/);
|
|
210
|
+
expect(OAuthSession.describeApiError({ response: { status: 403, headers: {} } })).toBeUndefined();
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
describe("refresh serialization", () => {
|
|
214
|
+
const lockPath = join(home, ".ptkl", "o.refresh.lock");
|
|
215
|
+
it("two concurrent refreshes send one request and share the new token", async () => {
|
|
216
|
+
const mock = await startMock({ token: (f, n) => [200, { access_token: `a${n}`, expires_in: 900, refresh_token: `r${n}` }] });
|
|
217
|
+
const p = oauthProfile(mock.base, { expires_at: 1 });
|
|
218
|
+
seed(p);
|
|
219
|
+
const [a, b] = await Promise.all([new OAuthSession().ensureFresh(p), new OAuthSession().ensureFresh(p)]);
|
|
220
|
+
expect(mock.calls.filter(c => c.path === "/v1/oauth/token")).toHaveLength(1);
|
|
221
|
+
expect(a.token).toBe("a1");
|
|
222
|
+
expect(b.token).toBe("a1");
|
|
223
|
+
expect(existsSync(lockPath)).toBe(false);
|
|
224
|
+
await mock.close();
|
|
225
|
+
});
|
|
226
|
+
it("takes over a stale lock (dead pid or old)", async () => {
|
|
227
|
+
writeFileSync(lockPath, JSON.stringify({ pid: 2 ** 22 + 12345, at: Date.now() }));
|
|
228
|
+
(await RefreshLock.acquire(lockPath, 500)).release();
|
|
229
|
+
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, at: Date.now() - 60_000 }));
|
|
230
|
+
(await RefreshLock.acquire(lockPath, 500)).release();
|
|
231
|
+
expect(existsSync(lockPath)).toBe(false);
|
|
232
|
+
});
|
|
233
|
+
it("times out on a live lock", async () => {
|
|
234
|
+
const l = await RefreshLock.acquire(lockPath);
|
|
235
|
+
await expect(RefreshLock.acquire(lockPath, 100)).rejects.toMatchObject({ code: "lock_timeout" });
|
|
236
|
+
l.release();
|
|
237
|
+
});
|
|
238
|
+
it("releases the lock when the refresh fails", async () => {
|
|
239
|
+
const mock = await startMock({ token: () => [500, { error: "server_error" }] });
|
|
240
|
+
const p = oauthProfile(mock.base, { expires_at: 1 });
|
|
241
|
+
seed(p);
|
|
242
|
+
await expect(new OAuthSession().ensureFresh(p)).rejects.toThrow();
|
|
243
|
+
expect(existsSync(lockPath)).toBe(false);
|
|
244
|
+
await mock.close();
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
describe("ProfileLogin routing", () => {
|
|
248
|
+
it("defaults to OAuth", () => {
|
|
249
|
+
expect(ProfileLogin.useLegacy({})).toBe(false);
|
|
250
|
+
expect(ProfileLogin.useLegacy({ browser: false, scope: "x" })).toBe(false);
|
|
251
|
+
});
|
|
252
|
+
it("--legacy, -t, -p (flag with or without value) and -u select legacy", () => {
|
|
253
|
+
expect(ProfileLogin.useLegacy({ legacy: true })).toBe(true);
|
|
254
|
+
expect(ProfileLogin.useLegacy({ token: "t" })).toBe(true);
|
|
255
|
+
expect(ProfileLogin.useLegacy({ password: true })).toBe(true);
|
|
256
|
+
expect(ProfileLogin.useLegacy({ password: "pw" })).toBe(true);
|
|
257
|
+
expect(ProfileLogin.useLegacy({ username: "u@x" })).toBe(true);
|
|
258
|
+
});
|
|
259
|
+
it("resolves client id: flag > profile > env > built-in", () => {
|
|
260
|
+
const prof = { client_id: "stored" };
|
|
261
|
+
expect(ProfileLogin.resolveClientId("flag", prof, { PTKL_OAUTH_CLIENT_ID: "env" })).toBe("flag");
|
|
262
|
+
expect(ProfileLogin.resolveClientId(undefined, prof, { PTKL_OAUTH_CLIENT_ID: "env" })).toBe("stored");
|
|
263
|
+
expect(ProfileLogin.resolveClientId(undefined, undefined, { PTKL_OAUTH_CLIENT_ID: "env" })).toBe("env");
|
|
264
|
+
expect(ProfileLogin.resolveClientId(undefined, undefined, {})).toBe(ProfileLogin.defaultClientId);
|
|
265
|
+
});
|
|
266
|
+
it("OAuth login stores no username, dropping a legacy or placeholder one", async () => {
|
|
267
|
+
const run = vi.spyOn(OAuthLogin.prototype, "run").mockResolvedValue({
|
|
268
|
+
discovery: { issuer: "i", authorization_endpoint: "a", token_endpoint: "t", revocation_endpoint: "r" },
|
|
269
|
+
tokens: { accessToken: "at", refreshToken: "rt", expiresAt: 1, scope: "s" },
|
|
270
|
+
});
|
|
271
|
+
const base = { name: "o", host: "http://h", project: "p" };
|
|
272
|
+
for (const old of [{ username: "me@x.io" }, { username: "oauth" }, {}]) {
|
|
273
|
+
seed({ name: "o", host: "http://h", project: "p", current: true, token: "legacy", ...old });
|
|
274
|
+
const out = await ProfileLogin.login(base, {}, () => { });
|
|
275
|
+
expect(out).not.toHaveProperty("username");
|
|
276
|
+
expect(stored()).not.toHaveProperty("username");
|
|
277
|
+
expect(stored()).toMatchObject({ auth: "oauth", token: "at", current: true });
|
|
278
|
+
}
|
|
279
|
+
run.mockRestore();
|
|
280
|
+
});
|
|
281
|
+
it("toLegacy strips every OAuth field and sets token/username", () => {
|
|
282
|
+
const out = ProfileLogin.toLegacy(oauthProfile("http://h", { scope: "s", username: "oauth" }), { username: "me@x.io", token: "SESSION:t" });
|
|
283
|
+
expect(out).toEqual({ name: "o", host: "http://h", project: "p", current: true, token: "SESSION:t", username: "me@x.io" });
|
|
284
|
+
});
|
|
285
|
+
it("toLegacy with a token only keeps a real stored username, never the OAuth placeholder", () => {
|
|
286
|
+
expect(ProfileLogin.toLegacy(oauthProfile("http://h", { username: "oauth" }), { token: "t" })).not.toHaveProperty("username");
|
|
287
|
+
const legacy = { name: "l", host: "h", project: "p", current: false, token: "old", username: "me@x.io" };
|
|
288
|
+
expect(ProfileLogin.toLegacy(legacy, { token: "t" })).toEqual({ ...legacy, token: "t" });
|
|
289
|
+
});
|
|
290
|
+
it("legacyUsername: -u wins, OAuth profile's stored name ignored, legacy's used", () => {
|
|
291
|
+
const oauth = oauthProfile("http://h", { username: "oauth" });
|
|
292
|
+
const legacy = { name: "l", username: "stored@x.io" };
|
|
293
|
+
expect(ProfileLogin.legacyUsername(oauth, "me@x.io")).toBe("me@x.io");
|
|
294
|
+
expect(ProfileLogin.legacyUsername(oauth)).toBeUndefined();
|
|
295
|
+
expect(ProfileLogin.legacyUsername(legacy)).toBe("stored@x.io");
|
|
296
|
+
expect(ProfileLogin.legacyUsername(legacy, "other")).toBe("other");
|
|
297
|
+
});
|
|
298
|
+
it("fails with a --legacy hint when discovery is unavailable", async () => {
|
|
299
|
+
const mock = await startMock();
|
|
300
|
+
await mock.close(); // nothing listening: connection refused
|
|
301
|
+
await expect(new OAuthLogin().run({ host: mock.base, name: "n", clientId: "c", project: "p", scope: "offline_access", noBrowser: true, print: () => { } }))
|
|
302
|
+
.rejects.toThrow(`OAuth login isn't available on ${mock.base}; use \`ptkl profile auth --legacy\``);
|
|
303
|
+
});
|
|
304
|
+
it("fails the same way on a 404 (OAuth disabled)", async () => {
|
|
305
|
+
const http = await import("node:http");
|
|
306
|
+
const srv = http.createServer((_, res) => res.writeHead(404).end());
|
|
307
|
+
await new Promise(r => srv.listen(0, "127.0.0.1", r));
|
|
308
|
+
const host = `http://127.0.0.1:${srv.address().port}`;
|
|
309
|
+
await expect(new OAuthLogin().run({ host, name: "n", clientId: "c", project: "p", scope: "s", noBrowser: true, print: () => { } })).rejects.toThrow(/use `ptkl profile auth --legacy`/);
|
|
310
|
+
srv.close();
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
describe("CallbackPages", () => {
|
|
314
|
+
const c = { name: "dev", host: "https://api.x", project: "11111111-2222", isNew: false };
|
|
315
|
+
it("each error variant has its title and retry command", () => {
|
|
316
|
+
expect(CallbackPages.forError(c, "access_denied").html).toContain("You declined access");
|
|
317
|
+
expect(CallbackPages.forError(c, "access_denied").html).toContain("ptkl profile auth dev");
|
|
318
|
+
expect(CallbackPages.forError(c, "state_mismatch").html).toContain("This login link is no longer valid");
|
|
319
|
+
expect(CallbackPages.forError(c, "timeout").html).toContain("This login timed out");
|
|
320
|
+
const f = CallbackPages.forError({ ...c, isNew: true }, "server_error", "boom").html;
|
|
321
|
+
expect(f).toContain("server_error");
|
|
322
|
+
expect(f).toContain("ptkl profile new -n dev -h https://api.x -P 11111111-2222");
|
|
323
|
+
});
|
|
324
|
+
it("renders hostile error text inert and caps its length", () => {
|
|
325
|
+
const h = CallbackPages.forError(c, "<script>x()</script>", `<script>alert(1)</script>${"a".repeat(500)}`).html;
|
|
326
|
+
expect(h).not.toContain("<script");
|
|
327
|
+
expect(h).toContain("<script>alert(1)");
|
|
328
|
+
expect(h.length).toBeLessThan(CallbackPages.forError(c, "x", "a".repeat(100)).html.length + 800);
|
|
329
|
+
});
|
|
330
|
+
it("loads nothing external", () => {
|
|
331
|
+
const h = CallbackPages.forError(c, "access_denied").html;
|
|
332
|
+
expect(h).not.toMatch(/(src|href)=|url\(|@import|<script/i);
|
|
333
|
+
});
|
|
334
|
+
it("success answers the tab with a 302 to the guide", async () => {
|
|
335
|
+
const s = await CallbackServer.start("st", c);
|
|
336
|
+
const pendingRes = fetch(`${s.redirectUri}?code=SECRETCODE&state=st`, { redirect: "manual" });
|
|
337
|
+
await s.wait();
|
|
338
|
+
s.finish();
|
|
339
|
+
const r = await pendingRes;
|
|
340
|
+
expect(r.status).toBe(302);
|
|
341
|
+
expect(r.headers.get("location")).toBe(GUIDE_URL);
|
|
342
|
+
expect(r.headers.get("referrer-policy")).toBe("no-referrer");
|
|
343
|
+
expect(r.headers.get("cache-control")).toBe("no-store");
|
|
344
|
+
expect(await r.text()).toBe("");
|
|
345
|
+
await s.close();
|
|
346
|
+
});
|
|
347
|
+
it("error responses carry the headers and no raw query values", async () => {
|
|
348
|
+
const s = await CallbackServer.start("st", c);
|
|
349
|
+
const r = await fetch(`${s.redirectUri}?error=access_denied&error_description=%3Cb%3Ehi&state=st&code=LEAK`);
|
|
350
|
+
const body = await r.text();
|
|
351
|
+
expect(r.status).toBe(400);
|
|
352
|
+
expect(r.headers.get("content-security-policy")).toContain("default-src 'none'");
|
|
353
|
+
expect(body).toContain("You declined access");
|
|
354
|
+
expect(body).not.toContain("LEAK");
|
|
355
|
+
await s.wait().catch(() => { });
|
|
356
|
+
await s.close();
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
describe("Util profile writes", () => {
|
|
360
|
+
it("is atomic: no temp file left behind", () => {
|
|
361
|
+
Util.updateProfiles([{ name: "a" }]);
|
|
362
|
+
expect(readFileSync(profilesFile, "utf8")).toContain('"a"');
|
|
363
|
+
});
|
|
364
|
+
});
|
package/dist/lib/util.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
|
|
2
2
|
import { Platform } from '@ptkl/sdk';
|
|
3
3
|
export default class Util {
|
|
4
4
|
static profilePath = `${process.env.HOME}/.ptkl`;
|
|
5
5
|
static fileName = "profiles.json";
|
|
6
|
+
static profileDir() {
|
|
7
|
+
return Util.profilePath;
|
|
8
|
+
}
|
|
6
9
|
static getProfiles() {
|
|
7
10
|
try {
|
|
8
11
|
const contents = JSON.parse(readFileSync(`${Util.profilePath}/${Util.fileName}`).toString());
|
|
@@ -15,7 +18,11 @@ export default class Util {
|
|
|
15
18
|
static updateProfiles(profiles) {
|
|
16
19
|
try {
|
|
17
20
|
const contents = JSON.stringify(profiles);
|
|
18
|
-
|
|
21
|
+
// temp + rename so a crash or parallel run never leaves a torn file
|
|
22
|
+
const target = `${Util.profilePath}/${Util.fileName}`;
|
|
23
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
24
|
+
writeFileSync(tmp, contents, { mode: 0o600 });
|
|
25
|
+
renameSync(tmp, target);
|
|
19
26
|
return profiles;
|
|
20
27
|
}
|
|
21
28
|
catch (err) {
|