@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.
- 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__/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/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 +100 -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 +38 -0
- package/dist/lib/oauth/__tests__/mockServer.js +29 -0
- package/dist/lib/oauth/__tests__/oauth.test.js +347 -0
- package/dist/lib/util.js +9 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,41 +24,28 @@ This creates a `~/.ptkl` directory where profiles and settings are stored.
|
|
|
24
24
|
|
|
25
25
|
A profile stores your authentication credentials and connection settings for a Protokol instance.
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
Omit the password or use `--password` flag without a value to be prompted securely:
|
|
27
|
+
Log in with your browser (OAuth, the default):
|
|
30
28
|
|
|
31
29
|
```bash
|
|
32
|
-
ptkl profile new
|
|
33
|
-
-n production \
|
|
34
|
-
-u user@example.com \
|
|
35
|
-
-P my-project \
|
|
36
|
-
-h https://api.example.com \
|
|
37
|
-
--password
|
|
30
|
+
ptkl profile new -n production -h https://api.example.com -P <project-uuid>
|
|
38
31
|
```
|
|
39
32
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
#### With Password in CLI (Not Recommended)
|
|
33
|
+
For scripts and CI, log in as an **API user** with `--legacy`. API-user credentials come from `ptkl api-users new` or the dashboard. The secret is prompted securely unless you pass a value (not recommended: it lands in shell history).
|
|
43
34
|
|
|
44
35
|
```bash
|
|
45
|
-
ptkl profile new
|
|
46
|
-
-n production \
|
|
47
|
-
-u user@example.com \
|
|
48
|
-
-P my-project \
|
|
49
|
-
-h https://api.example.com \
|
|
50
|
-
--password "myPassword"
|
|
36
|
+
ptkl profile new --legacy -n ci -u <api-user> -P my-project -h https://api.example.com
|
|
51
37
|
```
|
|
52
38
|
|
|
53
|
-
|
|
39
|
+
Email/password login is no longer available in the CLI; use the OAuth login.
|
|
54
40
|
|
|
55
41
|
#### Options
|
|
56
42
|
|
|
57
43
|
- `-n, --name <name>` - Profile name (e.g., "production", "staging")
|
|
58
|
-
- `-u, --username <username>` - Email or API username
|
|
59
44
|
- `-P, --project <project>` - Project identifier
|
|
60
45
|
- `-h, --host <host>` - API host URL
|
|
61
|
-
-
|
|
46
|
+
- `--legacy` - Use API-user credentials (username + secret) instead of OAuth
|
|
47
|
+
- `-u, --username <username>` - API-user username (with `--legacy`)
|
|
48
|
+
- `-p, --password [secret]` - API-user secret (with `--legacy`; prompted if omitted)
|
|
62
49
|
|
|
63
50
|
## Profile Management
|
|
64
51
|
|
|
@@ -95,18 +82,14 @@ ptkl profile inspect production
|
|
|
95
82
|
If your token expires or you need to update credentials:
|
|
96
83
|
|
|
97
84
|
```bash
|
|
98
|
-
ptkl profile auth
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
Or for a specific profile:
|
|
102
|
-
|
|
103
|
-
```bash
|
|
104
|
-
ptkl profile auth --profile production --password
|
|
85
|
+
ptkl profile auth [name] # OAuth browser login
|
|
86
|
+
ptkl profile auth [name] --legacy -u <api-user> # API-user login (secret prompted)
|
|
105
87
|
```
|
|
106
88
|
|
|
107
|
-
#### Options
|
|
89
|
+
#### Options (legacy)
|
|
108
90
|
|
|
109
|
-
- `-
|
|
91
|
+
- `-u, --username <username>` - API-user username (defaults to the stored one)
|
|
92
|
+
- `-p, --password [secret]` - API-user secret (omit value for secure prompt)
|
|
110
93
|
- `-t, --token <token>` - Directly provide a token
|
|
111
94
|
- `-P, --project <project>` - Update the project
|
|
112
95
|
|
|
@@ -116,6 +99,30 @@ ptkl profile auth --profile production --password
|
|
|
116
99
|
ptkl profile delete staging
|
|
117
100
|
```
|
|
118
101
|
|
|
102
|
+
### OAuth login (default)
|
|
103
|
+
|
|
104
|
+
OAuth browser login is the default for `profile new` and `profile auth`:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
ptkl profile new -n dev -h https://api.example.com -P <project-uuid> # create + log in
|
|
108
|
+
ptkl profile auth [name] # log in again (default: active profile)
|
|
109
|
+
ptkl profile logout [name] # revoke + clear tokens
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
After a successful login the browser tab is redirected to the OAuth guide (https://docs.protokol.io/platform/oauth/); failures show an error page with the retry command.
|
|
113
|
+
|
|
114
|
+
The flow is authorization code + PKCE with a loopback redirect on `127.0.0.1`. `-P` must be a project UUID (one login covers one project). Options: `--no-browser` prints the URL instead of opening a browser, `--port` fixes the loopback port (default: random), `--client-id` overrides the client (default: the profile's stored client, `$PTKL_OAUTH_CLIENT_ID`, then the built-in first-party CLI client), `--scope <list>` replaces the default scope and `--add-scope <list>` extends it (comma-separated permission names; `pattern:<regex>` for a regex).
|
|
115
|
+
|
|
116
|
+
If OAuth is not enabled on the host the command fails with a pointer to `--legacy`; there is no silent fallback.
|
|
117
|
+
|
|
118
|
+
**Legacy and CI.** `--legacy` (implied by `-u`, `-p` or `-t`) logs in as an API user (`/v1/user/api/auth`) or takes a token directly, e.g. `ptkl profile auth -t $TOKEN`. For CI use API-user tokens with `--legacy -t`.
|
|
119
|
+
|
|
120
|
+
Default scope is a least-privilege toolkit preset (`src/lib/oauth/ScopePreset.ts`), further limited by your own permissions in the project: apps, functions, components, templates, thunder, ratchet (read/inspect), users and roles (list), API users (`edit base_users` for list/get/edit/revoke-secret, `manage_secrets base_users` for new/new-secret), global env (read), and `dev env_access` (non-live environments need `<env> env_access`; `dev` is the default — add others with `--add-scope "<env> env_access"`). Scope never grows by itself: re-run `ptkl profile auth` after creating resources whose per-resource permissions you need.
|
|
121
|
+
|
|
122
|
+
Access tokens (15 min) refresh transparently when a command starts, serialized across processes by a per-profile lock in `~/.ptkl` (the rotated refresh token is saved); long-running commands such as watch modes refresh only at start. If the session expired or was revoked you are asked to log in again. `profile inspect` masks tokens.
|
|
123
|
+
|
|
124
|
+
Not available with OAuth profiles (routes OAuth does not admit; the CLI says so on a 403): workflow, sandbox, kortex, integration(s), satellite, billing, logs, forge, project administration, and user and role changes unless you `--add-scope "edit base_users"`. Use a `--legacy` profile for these.
|
|
125
|
+
|
|
119
126
|
## Using the --profile Flag
|
|
120
127
|
|
|
121
128
|
You can override the active profile for any command using the global `--profile` flag:
|
package/dist/bin/toolkit.js
CHANGED
|
@@ -1,22 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { commands } from "../commands/index.js";
|
|
4
|
+
import Util from "../lib/util.js";
|
|
5
|
+
import OAuthError from "../lib/oauth/OAuthError.js";
|
|
6
|
+
import OAuthSession from "../lib/oauth/OAuthSession.js";
|
|
4
7
|
const program = new Command();
|
|
5
8
|
// Add global --profile option
|
|
6
9
|
program.option('--profile <profileName>', 'Use a specific profile for this command');
|
|
7
10
|
// Add a preAction hook to handle the global --profile flag
|
|
8
|
-
program.hook('preAction', (thisCommand, actionCommand) => {
|
|
11
|
+
program.hook('preAction', async (thisCommand, actionCommand) => {
|
|
9
12
|
const opts = thisCommand.opts();
|
|
10
13
|
if (opts.profile) {
|
|
11
14
|
// Store the profile name in a global variable or process.env so commands can access it
|
|
12
15
|
process.env.PTKL_ACTIVE_PROFILE = opts.profile;
|
|
13
16
|
}
|
|
17
|
+
// Refresh an expiring OAuth access token before any command builds an SDK client.
|
|
18
|
+
// Profile commands manage tokens themselves.
|
|
19
|
+
for (let c = actionCommand; c; c = c.parent) {
|
|
20
|
+
if (c.name() === 'profile')
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
let profile;
|
|
24
|
+
try {
|
|
25
|
+
profile = Util.getCurrentProfile();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (OAuthSession.isOAuth(profile)) {
|
|
31
|
+
await new OAuthSession().ensureFresh(profile);
|
|
32
|
+
}
|
|
14
33
|
});
|
|
15
34
|
commands.forEach(c => program.addCommand(c));
|
|
16
35
|
program.parseAsync(process.argv).catch((err) => {
|
|
17
|
-
console.log("An error occurred while executing the command.", err);
|
|
18
36
|
const { response } = err;
|
|
19
|
-
|
|
37
|
+
let active;
|
|
38
|
+
try {
|
|
39
|
+
active = Util.getCurrentProfile();
|
|
40
|
+
}
|
|
41
|
+
catch { /* none */ }
|
|
42
|
+
const oauthMessage = OAuthSession.describeApiError(err, active);
|
|
43
|
+
// Never dump the raw error for OAuth failures: axios errors carry the bearer token.
|
|
44
|
+
if (!oauthMessage && !(err instanceof OAuthError)) {
|
|
45
|
+
console.log("An error occurred while executing the command.", err);
|
|
46
|
+
}
|
|
47
|
+
if (err instanceof OAuthError) {
|
|
48
|
+
console.error(err.message);
|
|
49
|
+
}
|
|
50
|
+
else if (oauthMessage) {
|
|
51
|
+
console.error(oauthMessage);
|
|
52
|
+
}
|
|
53
|
+
else if (response && response.data) {
|
|
20
54
|
console.error(response.data.message || "An error occurred with the API request.");
|
|
21
55
|
}
|
|
22
56
|
else {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from "vitest";
|
|
2
|
+
const post = vi.fn(async (path, body) => ({ data: { uuid: "api-1", path, body, secrets: [{ secret: "s3cret" }] } }));
|
|
3
|
+
vi.mock("../../lib/sdk.js", () => ({ platform: () => ({ apiUser: () => ({ client: { post } }) }) }));
|
|
4
|
+
vi.mock("../../lib/util.js", () => ({ default: { getCurrentProfile: () => ({ name: "p", host: "http://h", project: "proj", token: "t" }) } }));
|
|
5
|
+
const { default: apiUsers } = await import("../apiUsers.js");
|
|
6
|
+
describe("api-users new", () => {
|
|
7
|
+
it("creates the API user with its roles and returns the response with the secret", async () => {
|
|
8
|
+
const out = await apiUsers.create({ name: "ci-bot", roles: ["role-1", "role-2"] });
|
|
9
|
+
expect(post).toHaveBeenCalledWith("/v1/user/api-user", { name: "ci-bot", roles: ["role-1", "role-2"] });
|
|
10
|
+
expect(out.secrets[0].secret).toBe("s3cret");
|
|
11
|
+
});
|
|
12
|
+
it("sends an empty role list when no roles are given", async () => {
|
|
13
|
+
await apiUsers.create({ name: "plain" });
|
|
14
|
+
expect(post).toHaveBeenLastCalledWith("/v1/user/api-user", { name: "plain", roles: [] });
|
|
15
|
+
});
|
|
16
|
+
});
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { assertRequiresIsValid } from '../forge.js';
|
|
3
|
+
const ok = (requires) => expect(() => assertRequiresIsValid(requires)).not.toThrow();
|
|
4
|
+
const bad = (requires, message) => expect(() => assertRequiresIsValid(requires)).toThrow(message);
|
|
5
|
+
describe('assertRequiresIsValid', () => {
|
|
6
|
+
it('accepts an absent block', () => {
|
|
7
|
+
ok(undefined);
|
|
8
|
+
ok(null);
|
|
9
|
+
});
|
|
10
|
+
it('accepts presence-only requirements', () => {
|
|
11
|
+
ok({ integrations: [{ id: 'protokol-mail' }] });
|
|
12
|
+
ok({ integrations: [{ id: 'protokol-mail', optional: true }] });
|
|
13
|
+
});
|
|
14
|
+
it('accepts an any-of option list', () => {
|
|
15
|
+
ok({ integrations: [{ id: 'protokol-mail', options: ['premium'] }] });
|
|
16
|
+
ok({ integrations: [{ id: 'protokol-mail', options: ['standard', 'premium'] }] });
|
|
17
|
+
});
|
|
18
|
+
it('accepts optional alongside options', () => {
|
|
19
|
+
ok({ integrations: [{ id: 'protokol-mail', optional: true, options: ['premium'] }] });
|
|
20
|
+
});
|
|
21
|
+
it('accepts a requires block with no integrations key', () => {
|
|
22
|
+
ok({});
|
|
23
|
+
});
|
|
24
|
+
it('rejects a non-object block', () => {
|
|
25
|
+
bad([], /requires must be an object/);
|
|
26
|
+
bad('mail', /requires must be an object/);
|
|
27
|
+
});
|
|
28
|
+
it('rejects a non-array integrations key', () => {
|
|
29
|
+
bad({ integrations: { id: 'protokol-mail' } }, /requires\.integrations must be an array/);
|
|
30
|
+
});
|
|
31
|
+
it('rejects a missing or blank id', () => {
|
|
32
|
+
bad({ integrations: [{}] }, /\[0\]\.id must be a non-empty string/);
|
|
33
|
+
bad({ integrations: [{ id: ' ' }] }, /\[0\]\.id must be a non-empty string/);
|
|
34
|
+
});
|
|
35
|
+
it('rejects keys that are not part of the shape', () => {
|
|
36
|
+
bad({ integrations: [{ id: 'm', option: 'premium' }] }, /unknown key "option"/);
|
|
37
|
+
bad({ integrations: [{ id: 'm', tier: 'premium' }] }, /unknown key "tier"/);
|
|
38
|
+
});
|
|
39
|
+
it('rejects a non-boolean optional', () => {
|
|
40
|
+
bad({ integrations: [{ id: 'm', optional: 'yes' }] }, /\.optional must be a boolean/);
|
|
41
|
+
});
|
|
42
|
+
it('rejects an empty or non-array options list', () => {
|
|
43
|
+
bad({ integrations: [{ id: 'm', options: [] }] }, /must be a non-empty array/);
|
|
44
|
+
bad({ integrations: [{ id: 'm', options: 'premium' }] }, /must be a non-empty array/);
|
|
45
|
+
});
|
|
46
|
+
it('rejects blank and duplicate option codes', () => {
|
|
47
|
+
bad({ integrations: [{ id: 'm', options: ['premium', ''] }] }, /must be non-empty strings/);
|
|
48
|
+
bad({ integrations: [{ id: 'm', options: ['premium', 1] }] }, /must be non-empty strings/);
|
|
49
|
+
bad({ integrations: [{ id: 'm', options: ['premium', 'premium'] }] }, /contains duplicates/);
|
|
50
|
+
});
|
|
51
|
+
it('reports which entry failed', () => {
|
|
52
|
+
bad({ integrations: [{ id: 'ok' }, { id: 'bad', options: [] }] }, /requires\.integrations\[1\]\.options/);
|
|
53
|
+
});
|
|
54
|
+
it('ignores requires.components entirely', () => {
|
|
55
|
+
ok({ components: [{ ref: 'shop::order' }] });
|
|
56
|
+
ok({ integrations: [{ id: 'm' }], components: 'anything' });
|
|
57
|
+
});
|
|
58
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
const auth = vi.fn();
|
|
3
|
+
const profiles = [];
|
|
4
|
+
const login = vi.fn(async () => ({}));
|
|
5
|
+
vi.mock("@ptkl/sdk", () => ({ APIUser: class {
|
|
6
|
+
auth = auth;
|
|
7
|
+
} }));
|
|
8
|
+
vi.mock("@inquirer/password", () => ({ default: vi.fn(async () => "prompted-secret") }));
|
|
9
|
+
vi.mock("../../lib/util.js", () => ({
|
|
10
|
+
default: {
|
|
11
|
+
getProfiles: () => profiles,
|
|
12
|
+
updateProfiles: (p) => { profiles.splice(0, profiles.length, ...p); },
|
|
13
|
+
updateProfile: (p) => { const i = profiles.findIndex(x => x.name == p.name); profiles[i] = p; },
|
|
14
|
+
getCurrentProfile: () => profiles.find(p => p.current),
|
|
15
|
+
},
|
|
16
|
+
}));
|
|
17
|
+
const { default: ProfileLogin } = await import("../../lib/oauth/ProfileLogin.js");
|
|
18
|
+
vi.spyOn(ProfileLogin, "login").mockImplementation(login);
|
|
19
|
+
const { default: profile } = await import("../profile.js");
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
profiles.length = 0;
|
|
22
|
+
auth.mockReset();
|
|
23
|
+
login.mockClear();
|
|
24
|
+
});
|
|
25
|
+
describe("profile --legacy (API user)", () => {
|
|
26
|
+
it("new: calls APIUser.auth with username/secret/project and stores username + token", async () => {
|
|
27
|
+
auth.mockResolvedValue({ data: { Token: "tok" } });
|
|
28
|
+
await profile.new({ name: "n", host: "http://h", project: "proj", username: "bot", password: "s3" });
|
|
29
|
+
expect(auth).toHaveBeenCalledWith("bot", "s3", "proj");
|
|
30
|
+
expect(profiles).toEqual([{ name: "n", username: "bot", token: "tok", host: "http://h", project: "proj" }]);
|
|
31
|
+
expect(login).not.toHaveBeenCalled();
|
|
32
|
+
});
|
|
33
|
+
it("new: prompts for the secret when -p has no value", async () => {
|
|
34
|
+
auth.mockResolvedValue({ data: { Token: "tok" } });
|
|
35
|
+
await profile.new({ name: "n", host: "http://h", project: "proj", username: "bot", password: true });
|
|
36
|
+
expect(auth).toHaveBeenCalledWith("bot", "prompted-secret", "proj");
|
|
37
|
+
});
|
|
38
|
+
it("new: auth failure is clear and never contains the secret", async () => {
|
|
39
|
+
auth.mockRejectedValue({ response: { data: { message: "bad credentials" } }, message: "Request failed" });
|
|
40
|
+
const err = await profile.new({ name: "n", host: "http://h", project: "p", username: "bot", password: "topsecret" }).catch((e) => e);
|
|
41
|
+
expect(err.message).toBe("API-user authentication failed: bad credentials");
|
|
42
|
+
expect(err.message).not.toContain("topsecret");
|
|
43
|
+
expect(profiles).toEqual([]);
|
|
44
|
+
});
|
|
45
|
+
it("auth -t stores the token directly without calling the API", async () => {
|
|
46
|
+
profiles.push({ name: "n", username: "bot", token: "old", host: "http://h", project: "proj", current: true });
|
|
47
|
+
await profile.auth(undefined, { token: "direct" });
|
|
48
|
+
expect(auth).not.toHaveBeenCalled();
|
|
49
|
+
expect(profiles[0]).toMatchObject({ name: "n", username: "bot", token: "direct" });
|
|
50
|
+
});
|
|
51
|
+
it("auth re-authenticates with the stored username", async () => {
|
|
52
|
+
auth.mockResolvedValue({ data: { Token: "fresh" } });
|
|
53
|
+
profiles.push({ name: "n", username: "bot", token: "old", host: "http://h", project: "proj", current: true });
|
|
54
|
+
await profile.auth(undefined, { legacy: true, password: "s3" });
|
|
55
|
+
expect(auth).toHaveBeenCalledWith("bot", "s3", "proj");
|
|
56
|
+
expect(profiles[0]).toMatchObject({ username: "bot", token: "fresh" });
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
describe("profile without --legacy", () => {
|
|
60
|
+
it("new goes to the OAuth login, not APIUser.auth", async () => {
|
|
61
|
+
await profile.new({ name: "n", host: "http://h", project: "proj" });
|
|
62
|
+
expect(login).toHaveBeenCalledTimes(1);
|
|
63
|
+
expect(auth).not.toHaveBeenCalled();
|
|
64
|
+
});
|
|
65
|
+
});
|
|
@@ -2,11 +2,16 @@ import { Command } from "commander";
|
|
|
2
2
|
import util from "../lib/util.js";
|
|
3
3
|
import { Platform as Api } from "@ptkl/sdk";
|
|
4
4
|
import OutputFormatCommand from "./outputCommand.js";
|
|
5
|
+
import * as sdk from "../lib/sdk.js";
|
|
5
6
|
class ApiUsersCommand {
|
|
6
7
|
register() {
|
|
7
8
|
return (new Command("api-users")
|
|
8
9
|
.description("Manage API users")
|
|
9
10
|
.version("0.1.0")
|
|
11
|
+
.addCommand(new OutputFormatCommand(new Command("new")
|
|
12
|
+
.description("Create an API user; its secret is printed once")
|
|
13
|
+
.requiredOption("-n, --name <name>", "Name of the API user")
|
|
14
|
+
.option("-r, --roles <roles...>", "list of role uuids")).action(this.create))
|
|
10
15
|
.addCommand(new OutputFormatCommand(new Command("new-secret")
|
|
11
16
|
.description("Create a new secret for a user")
|
|
12
17
|
.requiredOption("-u, --uuid <uuid>", "UUID of the user to create a new secret for")).action(this.newSecret))
|
|
@@ -26,6 +31,13 @@ class ApiUsersCommand {
|
|
|
26
31
|
.description("Retrieve an API user by UUID")
|
|
27
32
|
.requiredOption("-u, --uuid <uuid>", "UUID of the API user")).action(this.get)));
|
|
28
33
|
}
|
|
34
|
+
async create(opts) {
|
|
35
|
+
const { name, roles } = opts;
|
|
36
|
+
const profile = util.getCurrentProfile();
|
|
37
|
+
// The SDK has no API-user create call yet.
|
|
38
|
+
const res = await sdk.platform(profile).apiUser().client.post("/v1/user/api-user", { name, roles: roles ?? [] });
|
|
39
|
+
return res.data;
|
|
40
|
+
}
|
|
29
41
|
async newSecret(opts) {
|
|
30
42
|
const { uuid } = opts;
|
|
31
43
|
const profile = util.getCurrentProfile();
|
package/dist/commands/forge.js
CHANGED
|
@@ -41,6 +41,53 @@ function assertPermissionBytesWithinBudget(runtimePermissions = [], entitlements
|
|
|
41
41
|
throw new Error(`Declared permissions total ${bytes} bytes across ${all.length} entries, exceeding the ${MAX_PERMISSION_BYTES} byte limit`);
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Validates requires.integrations. Codes are not checked against the live option
|
|
46
|
+
* set — it can change after an app ships, and an unknown code is reported at
|
|
47
|
+
* preflight where it has project context.
|
|
48
|
+
*/
|
|
49
|
+
export function assertRequiresIsValid(requires) {
|
|
50
|
+
if (requires === undefined || requires === null)
|
|
51
|
+
return;
|
|
52
|
+
if (typeof requires !== "object" || Array.isArray(requires)) {
|
|
53
|
+
throw new Error("requires must be an object");
|
|
54
|
+
}
|
|
55
|
+
const integrations = requires.integrations;
|
|
56
|
+
if (integrations === undefined)
|
|
57
|
+
return;
|
|
58
|
+
if (!Array.isArray(integrations)) {
|
|
59
|
+
throw new Error("requires.integrations must be an array");
|
|
60
|
+
}
|
|
61
|
+
const allowed = new Set(["id", "optional", "options"]);
|
|
62
|
+
integrations.forEach((entry, i) => {
|
|
63
|
+
const at = `requires.integrations[${i}]`;
|
|
64
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
|
|
65
|
+
throw new Error(`${at} must be an object`);
|
|
66
|
+
}
|
|
67
|
+
for (const key of Object.keys(entry)) {
|
|
68
|
+
if (!allowed.has(key)) {
|
|
69
|
+
throw new Error(`${at} has unknown key "${key}" (allowed: ${[...allowed].join(", ")})`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (typeof entry.id !== "string" || entry.id.trim() === "") {
|
|
73
|
+
throw new Error(`${at}.id must be a non-empty string`);
|
|
74
|
+
}
|
|
75
|
+
if (entry.optional !== undefined && typeof entry.optional !== "boolean") {
|
|
76
|
+
throw new Error(`${at}.optional must be a boolean`);
|
|
77
|
+
}
|
|
78
|
+
if (entry.options === undefined)
|
|
79
|
+
return;
|
|
80
|
+
if (!Array.isArray(entry.options) || entry.options.length === 0) {
|
|
81
|
+
throw new Error(`${at}.options must be a non-empty array of option codes`);
|
|
82
|
+
}
|
|
83
|
+
if (entry.options.some((c) => typeof c !== "string" || c.trim() === "")) {
|
|
84
|
+
throw new Error(`${at}.options entries must be non-empty strings`);
|
|
85
|
+
}
|
|
86
|
+
if (new Set(entry.options).size !== entry.options.length) {
|
|
87
|
+
throw new Error(`${at}.options contains duplicates`);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
44
91
|
function parseJSON(label, raw) {
|
|
45
92
|
try {
|
|
46
93
|
return JSON.parse(raw);
|
|
@@ -348,6 +395,7 @@ class ForgeCommand {
|
|
|
348
395
|
// appservice and assertPermissionSetWithinBudget in platform-api — same 64 KB, so a build
|
|
349
396
|
// that passes here is not rejected at publish or at a user's app launch.
|
|
350
397
|
assertPermissionBytesWithinBudget(runtime_permissions ?? [], entitlements ?? []);
|
|
398
|
+
assertRequiresIsValid(requires);
|
|
351
399
|
// Normalize views: support both string entries and object entries with access/permissions
|
|
352
400
|
const normalizedViews = {};
|
|
353
401
|
if (views) {
|
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;
|