@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 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
- #### Secure Method (Recommended)
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
- You'll be prompted to enter your password securely (hidden input).
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
- ⚠️ **Security Warning**: This will show a warning as the password may be visible in shell history.
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
- - `-p, --password [password]` - Password (optional value for secure prompt)
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 --password
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
- - `-p, --password [password]` - Password (omit value for secure prompt)
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:
@@ -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
- if (response && response.data) {
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,52 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ const calls = {};
3
+ const client = {
4
+ get: vi.fn(), post: vi.fn(), put: vi.fn(),
5
+ };
6
+ const appApi = {
7
+ client,
8
+ download: vi.fn(async (ref, version) => { calls.download = [ref, version]; return {}; }),
9
+ updateSettings: vi.fn(async (v, ref) => ({ v, ref })),
10
+ };
11
+ vi.mock('@ptkl/sdk', () => ({ Platform: class {
12
+ app() { return appApi; }
13
+ } }));
14
+ vi.mock('../../lib/util.js', () => ({
15
+ default: {
16
+ getCurrentProfile: () => ({ token: 't', host: 'h', name: 'p' }),
17
+ getClientForProfile: () => ({ app: () => appApi }),
18
+ },
19
+ }));
20
+ vi.mock('vite', () => ({ build: vi.fn(), createServer: vi.fn() }));
21
+ vi.mock('../../playground.js', () => ({ default: class {
22
+ } }));
23
+ import apps from '../apps.js';
24
+ describe('apps', () => {
25
+ beforeEach(() => { vi.clearAllMocks(); });
26
+ it('download passes (ref, version) in SDK order', async () => {
27
+ await apps.download({ apptype: 'app', version: '1.2.3', ref: 'my-app', output: '' });
28
+ expect(appApi.download).toHaveBeenCalledWith('my-app', '1.2.3');
29
+ });
30
+ it('remove-version GETs settings then PUTs the filtered list', async () => {
31
+ client.get.mockResolvedValue({ data: { public_version: '2', settings: [{ version: '1' }, { version: '2' }, { version: '3' }] } });
32
+ await apps.removeVersion({ version: '3', ref: 'r' });
33
+ expect(client.get).toHaveBeenCalledWith('/v3/system/gateway/app-service/app/r/settings');
34
+ expect(appApi.updateSettings).toHaveBeenCalledWith({ settings: [{ version: '1' }, { version: '2' }] }, 'r');
35
+ });
36
+ it('remove-version refuses the public version', async () => {
37
+ client.get.mockResolvedValue({ data: { public_version: '2', settings: [] } });
38
+ await expect(apps.removeVersion({ version: '2', ref: 'r' })).rejects.toThrow(/public version/);
39
+ expect(appApi.updateSettings).not.toHaveBeenCalled();
40
+ });
41
+ it('bundle upload posts to the platform app upload route', async () => {
42
+ const { default: Cmd } = await import('../apps.js');
43
+ client.post.mockResolvedValue({});
44
+ await Cmd.constructor.postArchive(appApi, 'app', Buffer.from('x'));
45
+ expect(client.post.mock.calls[0][0]).toBe('/v3/system/gateway/app-service/app/upload');
46
+ });
47
+ it('public-app is refused under an OAuth profile', () => {
48
+ const cls = apps.constructor;
49
+ expect(() => cls.assertAllowed('public-app', { auth: 'oauth', client_id: 'x', refresh_token: 'r' })).toThrow(/OAuth/);
50
+ expect(() => cls.assertAllowed('app', { auth: 'oauth' })).not.toThrow();
51
+ });
52
+ });
@@ -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();
@@ -7,7 +7,8 @@ import { Writable } from "stream";
7
7
  import { writeFileSync } from "fs";
8
8
  import Util from "../lib/util.js";
9
9
  import Playground from "../playground.js";
10
- import { join } from 'path';
10
+ import { join, resolve } from 'path';
11
+ import OAuthSession from "../lib/oauth/OAuthSession.js";
11
12
  /**
12
13
  * Deprecation notice: Apps as such will be deprecated in favor for Protokol Forge and this will be removed in the future.
13
14
  */
@@ -71,11 +72,36 @@ class AppsCommand {
71
72
  const { apptype, version, ref, output } = options;
72
73
  const profile = util.getCurrentProfile();
73
74
  const client = new Api({ token: profile.token, host: profile.host }).app(apptype);
74
- return await client.download(version, ref, output);
75
+ AppsCommand.assertAllowed(apptype, profile);
76
+ const res = await client.download(ref, version);
77
+ if (output && res?.data) {
78
+ const file = resolve(output, `${ref}-${version}.tar.gz`);
79
+ writeFileSync(file, Buffer.from(res.data));
80
+ console.log(`Downloaded to ${file}`);
81
+ }
82
+ return res;
83
+ }
84
+ /** `public-app` routes are deprecated and denied to OAuth tokens. */
85
+ static assertAllowed(apptype, profile) {
86
+ if (apptype === "public-app" && OAuthSession.isOAuth(profile)) {
87
+ throw new Error("public-app routes are deprecated and not available to OAuth profiles. Use an API-user profile (`ptkl profile new --legacy`).");
88
+ }
89
+ }
90
+ /** POST a tar.gz to the app-service upload route (shared by `upload` and `bundle -u`). */
91
+ static async postArchive(api, apptype, buffer, build) {
92
+ const formData = new FormData();
93
+ formData.append('app', new Blob([buffer], { type: "application/gzip" }), "app.tar.gz");
94
+ if (build)
95
+ formData.append('build', 'true');
96
+ return await api.client.post(`/v3/system/gateway/app-service/${apptype}/upload`, formData, {
97
+ timeout: 60000,
98
+ headers: { 'Content-Type': 'multipart/form-data' }
99
+ });
75
100
  }
76
101
  async upload(options) {
77
102
  const { apptype, directory, build } = options;
78
103
  const profile = util.getCurrentProfile();
104
+ AppsCommand.assertAllowed(apptype, profile);
79
105
  const api = new Api({ token: profile.token, host: profile.host }).app(apptype);
80
106
  try {
81
107
  let buffer = Buffer.alloc(0);
@@ -93,19 +119,7 @@ class AppsCommand {
93
119
  .on('error', reject);
94
120
  });
95
121
  console.log('Archive created successfully');
96
- // Create FormData with buffer
97
- const formData = new FormData();
98
- const blob = new Blob([buffer], { type: 'application/gzip' });
99
- formData.append('app', blob, 'app.tar.gz');
100
- if (build) {
101
- formData.append('build', 'true');
102
- }
103
- return await api.client.post(`/v3/system/gateway/app-service/${apptype}/upload`, formData, {
104
- timeout: 60000,
105
- headers: {
106
- 'Content-Type': 'multipart/form-data'
107
- }
108
- });
122
+ return await AppsCommand.postArchive(api, apptype, buffer, build);
109
123
  }
110
124
  catch (error) {
111
125
  throw error;
@@ -200,17 +214,20 @@ class AppsCommand {
200
214
  callback();
201
215
  },
202
216
  });
203
- c({ gzip: true, cwd: distPath }, ['.']).pipe(bufferStream).on('finish', () => {
204
- const buffer = Buffer.concat(chunks);
205
- client.app().bundleUpload(buffer).then(() => {
206
- console.log('Bundle uploaded successfully');
217
+ await new Promise((done) => {
218
+ c({ gzip: true, cwd: distPath }, ['.']).pipe(bufferStream).on('finish', () => {
219
+ AppsCommand.postArchive(client.app("app"), "app", Buffer.concat(chunks)).then(() => {
220
+ console.log('Bundle uploaded successfully');
221
+ })
222
+ .catch((error) => {
223
+ console.error('Bundle error:', error.response?.data?.message ?? error.message);
224
+ })
225
+ .finally(done);
207
226
  })
208
- .catch((error) => {
209
- console.error('Bundle error:', error.response.data.message);
227
+ .on('error', (error) => {
228
+ console.error('Error creating the archive:', error.message);
229
+ done();
210
230
  });
211
- })
212
- .on('error', (error) => {
213
- console.error('Error creating the archive:', error.message);
214
231
  });
215
232
  }
216
233
  else {
@@ -233,16 +250,15 @@ class AppsCommand {
233
250
  }
234
251
  async removeVersion(options) {
235
252
  const { version, ref } = options;
236
- const profile = util.getClientForProfile();
237
- const client = profile.app();
238
- const { data } = await client.getApp(ref);
253
+ const api = util.getClientForProfile().app("app");
254
+ const url = `/v3/system/gateway/app-service/app/${ref}/settings`;
255
+ const res = await api.client.get(url);
256
+ const data = res.data?.data ?? res.data;
239
257
  if (data.public_version === version) {
240
258
  throw new Error("Cannot remove public version");
241
259
  }
242
- const settings = data.settings.filter((s) => s.version !== version);
243
- return await client.updateSettings({
244
- 'settings': settings
245
- }, ref);
260
+ const settings = (data.settings ?? []).filter((s) => s.version !== version);
261
+ return await api.updateSettings({ settings }, ref);
246
262
  }
247
263
  }
248
264
  export default new AppsCommand();
@@ -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) {