@ptkl/toolkit 1.3.0 → 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 +82 -6
- package/dist/commands/profile.js +84 -76
- package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
- package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
- package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
- package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
- package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
- package/dist/lib/kortex/config/loader.js +129 -0
- package/dist/lib/kortex/config/schema.js +60 -0
- package/dist/lib/kortex/controller.js +60 -0
- package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
- package/dist/lib/kortex/conversation/types.js +13 -0
- package/dist/lib/kortex/events/index.js +1 -0
- package/dist/lib/kortex/events/reducer.js +86 -0
- package/dist/lib/kortex/events/types.js +7 -0
- package/dist/lib/kortex/events/writer.js +76 -0
- package/dist/lib/kortex/mcp/index.js +1 -0
- package/dist/lib/kortex/orchestration/index.js +1 -0
- package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
- package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
- package/dist/lib/kortex/orchestration/plan.js +133 -0
- package/dist/lib/kortex/orchestration/scheduler.js +124 -0
- package/dist/lib/kortex/persistence/index.js +1 -0
- package/dist/lib/kortex/persistence/run-journal.js +94 -0
- package/dist/lib/kortex/providers/anthropic.js +34 -0
- package/dist/lib/kortex/providers/index.js +1 -0
- package/dist/lib/kortex/providers/openai-compatible.js +190 -0
- package/dist/lib/kortex/providers/protokol.js +204 -0
- package/dist/lib/kortex/providers/registry.js +61 -0
- package/dist/lib/kortex/providers/types.js +13 -0
- package/dist/lib/kortex/runtime/agent-runner.js +241 -0
- package/dist/lib/kortex/runtime/approval-queue.js +95 -0
- package/dist/lib/kortex/runtime/budget-controller.js +105 -0
- package/dist/lib/kortex/runtime/index.js +1 -0
- package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
- package/dist/lib/kortex/runtime/workspace.js +52 -0
- package/dist/lib/kortex/tools/index.js +1 -0
- package/dist/lib/kortex/tools.js +226 -34
- package/dist/lib/kortex/types.js +7 -0
- package/dist/lib/kortex/ui/index.js +1 -0
- 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 +6 -4
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
|
@@ -11,6 +11,83 @@ import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
|
|
|
11
11
|
import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
|
|
12
12
|
import * as sdk from "../lib/sdk.js";
|
|
13
13
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
14
|
+
// Total byte budget for an app's declared permissions, matching MaxForgePermissionBytes in
|
|
15
|
+
// appservice and maxPermissionSetBytes in platform-api. All three must move together: whichever is
|
|
16
|
+
// lowest becomes the real limit, and a developer would hit it at a different, more confusing point.
|
|
17
|
+
//
|
|
18
|
+
// It replaces a cap of 100 entries. That cap existed to keep the permission list inside HTTP header
|
|
19
|
+
// limits, and the list no longer travels in the token — platform-api stores the scoped set in Redis
|
|
20
|
+
// and re-attaches it when claims are parsed. The budget stays as a backstop: permission strings
|
|
21
|
+
// embed user-supplied resource and function names, so the declared set is unbounded and
|
|
22
|
+
// user-controlled even though it is no longer fatal at that size.
|
|
23
|
+
//
|
|
24
|
+
// Bytes rather than count because count was the wrong measure — 100 long permissions and 100 short
|
|
25
|
+
// ones are not the same thing, and the old check summed only runtime_permissions and entitlements,
|
|
26
|
+
// missing the grants and the permissions appended during the mint. That is how an app nominally
|
|
27
|
+
// capped at ~8 KB shipped a ~12 KB token and broke launch. It is sized to be unreachable for real
|
|
28
|
+
// apps (the largest today declares ~8 KB) rather than to act as a product limit.
|
|
29
|
+
const MAX_PERMISSION_BYTES = 64 * 1024;
|
|
30
|
+
/**
|
|
31
|
+
* Throws when an app's declared permissions exceed MAX_PERMISSION_BYTES.
|
|
32
|
+
*
|
|
33
|
+
* Takes grants as an optional third argument for the same reason its appservice counterpart does:
|
|
34
|
+
* request grants (FORGE_REQUEST_GRANTS_RFC.md) are still unimplemented, and when they land they
|
|
35
|
+
* belong in this sum rather than in a second, separate check.
|
|
36
|
+
*/
|
|
37
|
+
function assertPermissionBytesWithinBudget(runtimePermissions = [], entitlements = [], grants = []) {
|
|
38
|
+
const all = [...runtimePermissions, ...entitlements, ...grants];
|
|
39
|
+
const bytes = all.reduce((total, permission) => total + Buffer.byteLength(permission, "utf8"), 0);
|
|
40
|
+
if (bytes > MAX_PERMISSION_BYTES) {
|
|
41
|
+
throw new Error(`Declared permissions total ${bytes} bytes across ${all.length} entries, exceeding the ${MAX_PERMISSION_BYTES} byte limit`);
|
|
42
|
+
}
|
|
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
|
+
}
|
|
14
91
|
function parseJSON(label, raw) {
|
|
15
92
|
try {
|
|
16
93
|
return JSON.parse(raw);
|
|
@@ -314,12 +391,11 @@ class ForgeCommand {
|
|
|
314
391
|
if (existsSync(distPath)) {
|
|
315
392
|
rmSync(distPath, { recursive: true, force: true });
|
|
316
393
|
}
|
|
317
|
-
// Validate
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
394
|
+
// Validate the declared permission budget. Mirrors assertPermissionBytesWithinBudget in
|
|
395
|
+
// appservice and assertPermissionSetWithinBudget in platform-api — same 64 KB, so a build
|
|
396
|
+
// that passes here is not rejected at publish or at a user's app launch.
|
|
397
|
+
assertPermissionBytesWithinBudget(runtime_permissions ?? [], entitlements ?? []);
|
|
398
|
+
assertRequiresIsValid(requires);
|
|
323
399
|
// Normalize views: support both string entries and object entries with access/permissions
|
|
324
400
|
const normalizedViews = {};
|
|
325
401
|
if (views) {
|