@ptkl/toolkit 1.4.3 → 1.5.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.
Files changed (37) hide show
  1. package/README.md +14 -1
  2. package/dist/commands/__tests__/capabilities.test.js +83 -0
  3. package/dist/commands/__tests__/componentRunAs.test.js +65 -0
  4. package/dist/commands/__tests__/forge-bundle-layout.test.js +46 -0
  5. package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
  6. package/dist/commands/__tests__/forge-variables.test.js +16 -0
  7. package/dist/commands/__tests__/role.test.js +83 -0
  8. package/dist/commands/__tests__/runAs.test.js +63 -0
  9. package/dist/commands/__tests__/thunder.test.js +46 -0
  10. package/dist/commands/component.js +9 -3
  11. package/dist/commands/forge.js +106 -135
  12. package/dist/commands/functions.js +11 -5
  13. package/dist/commands/integrations/payments.js +11 -7
  14. package/dist/commands/project.js +0 -8
  15. package/dist/commands/role.js +45 -54
  16. package/dist/commands/satellite.js +0 -5
  17. package/dist/commands/template.js +7 -13
  18. package/dist/commands/thunder.js +19 -12
  19. package/dist/commands/workflow.js +10 -4
  20. package/dist/lib/__tests__/apiError.test.js +14 -0
  21. package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
  22. package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
  23. package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
  24. package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
  25. package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
  26. package/dist/lib/__tests__/runIdentity.test.js +101 -0
  27. package/dist/lib/__tests__/thunder.test.js +101 -0
  28. package/dist/lib/apiError.js +83 -1
  29. package/dist/lib/forgeDevKernelPlugin.js +90 -4
  30. package/dist/lib/forgeDevServiceExec.js +49 -0
  31. package/dist/lib/forgeDevServiceServer.js +163 -0
  32. package/dist/lib/forgeDevToken.js +126 -0
  33. package/dist/lib/oauth/ScopePreset.js +4 -3
  34. package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
  35. package/dist/lib/runIdentity.js +51 -0
  36. package/dist/lib/thunder.js +98 -0
  37. package/package.json +2 -2
@@ -1,63 +1,54 @@
1
1
  import { Command } from "commander";
2
- import util from "../lib/util.js";
3
- import { Platform as Api } from "@ptkl/sdk";
4
- import OutputFormatCommand from "./outputCommand.js";
2
+ import * as sdk from "../lib/sdk.js";
3
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
4
+ /** `ptkl role` — project role management. Maps onto the SDK `Users` client (@ptkl/sdk/beta), which
5
+ * owns the `/v1/user/role/*` and `/v1/user/permissions/list` routes; the standalone `Roles`
6
+ * client is gone (only a stale deprecated typing remains) and is not exported. */
5
7
  class RoleCommand {
6
8
  register() {
7
- return new Command("role")
8
- .description("Manage roles")
9
- .version("0.1.0")
10
- .addCommand(new Command("create")
9
+ const cmd = new Command("role").description("Manage roles");
10
+ cmd.addCommand(registerCommand(new Command("create")
11
11
  .description("Create role")
12
12
  .requiredOption("-n, --name <name>", "name for the new role")
13
- .requiredOption("-p, --permissions <permissions...>", "Permissions's array ")
14
- .requiredOption("-w, --workspaces <workspaces...>", "Workspaces array ")
15
- .option("-l --level <level>", "level of the role")
16
- .action(this.create))
17
- .addCommand(new Command("delete")
18
- .description("Delete role")
19
- .requiredOption("-u, --uuid <uuid>", "uuid of the role to delete")
20
- .action(this.delete))
21
- .addCommand(new OutputFormatCommand(new Command("list")
22
- .description("list roles")).action(this.list))
23
- .addCommand(new OutputFormatCommand(new Command("permissions-list")
24
- .description("list permissions")).action(this.list))
25
- .addCommand(new Command("edit")
26
- .description("edit role")
13
+ .requiredOption("-p, --permissions <permissions...>", "permissions granted by the role")
14
+ .requiredOption("-w, --workspaces <workspaces...>", "UUIDs of the workspaces the role applies to")
15
+ .option("-l, --level <level>", "level of the role", "0")).action(withProfile(async (profile, opts) => {
16
+ const res = await sdk.platform(profile).user().createRole({
17
+ name: opts.name,
18
+ permissions: opts.permissions,
19
+ workspaces: opts.workspaces,
20
+ level: Number(opts.level),
21
+ });
22
+ return res.data;
23
+ })));
24
+ cmd.addCommand(registerCommand(new Command("list").description("List roles")).action(withProfile(async (profile) => {
25
+ const res = await sdk.platform(profile).user().listRoles();
26
+ return res.data;
27
+ })));
28
+ cmd.addCommand(registerCommand(new Command("permissions-list").description("List available permissions")).action(withProfile(async (profile) => {
29
+ const res = await sdk.platform(profile).user().listPermissions();
30
+ return res.data;
31
+ })));
32
+ cmd.addCommand(registerCommand(new Command("edit")
33
+ .description("Edit role")
27
34
  .requiredOption("-u, --uuid <uuid>", "uuid of the role to edit")
28
- .requiredOption("-p, --permissions <permissions...>", "Permissions's array ")
29
- .requiredOption("-w, --workspaces <workspaces...>", "Workspaces array ")
30
- .requiredOption("-l --level <level>", "level of the role")
31
- .action(this.edit));
32
- }
33
- async create(options) {
34
- let { name, permissions, workspaces, level } = options;
35
- level = level ? Number(level) : 0;
36
- const profile = util.getCurrentProfile();
37
- const client = new Api({ token: profile.token, host: profile.host }).role();
38
- return await client.create({ name, workspaces, permissions, level });
39
- }
40
- async delete(opts) {
41
- const { uuid } = opts;
42
- const profile = util.getCurrentProfile();
43
- const client = new Api({ token: profile.token, host: profile.host }).role();
44
- return await client.delete(uuid);
45
- }
46
- async list() {
47
- const profile = util.getCurrentProfile();
48
- const client = new Api({ token: profile.token, host: profile.host }).role();
49
- return await client.list();
50
- }
51
- async listPermissions() {
52
- const profile = util.getCurrentProfile();
53
- const client = new Api({ token: profile.token, host: profile.host }).role();
54
- return await client.list();
55
- }
56
- async edit(opts) {
57
- let { uuid, permissions, workspaces, level } = opts;
58
- const profile = util.getCurrentProfile();
59
- const client = new Api({ token: profile.token, host: profile.host }).role();
60
- return await client.edit(permissions, workspaces, Number(level), uuid);
35
+ .requiredOption("-p, --permissions <permissions...>", "permissions granted by the role")
36
+ .requiredOption("-w, --workspaces <workspaces...>", "UUIDs of the workspaces the role applies to")
37
+ .requiredOption("-l, --level <level>", "level of the role")).action(withProfile(async (profile, opts) => {
38
+ const res = await sdk.platform(profile).user().editRole(opts.uuid, {
39
+ permissions: opts.permissions,
40
+ workspaces: opts.workspaces,
41
+ level: Number(opts.level),
42
+ });
43
+ return res.data;
44
+ })));
45
+ cmd.addCommand(registerCommand(new Command("delete")
46
+ .description("Delete role")
47
+ .requiredOption("-u, --uuid <uuid>", "uuid of the role to delete")).action(withProfile(async (profile, opts) => {
48
+ const res = await sdk.platform(profile).user().deleteRole(opts.uuid);
49
+ return res.data;
50
+ })));
51
+ return cmd;
61
52
  }
62
53
  }
63
54
  export default new RoleCommand();
@@ -84,11 +84,6 @@ class SatelliteCommand {
84
84
  templates.addCommand(registerCommand(new Command("get").description("Get a satellite template by id").argument("<id>", "Satellite template id")).action(withProfile(async (profile, id) => {
85
85
  return await satellites(profile).get(id);
86
86
  })));
87
- templates.addCommand(registerCommand(new Command("delete")
88
- .description("Delete a satellite template")
89
- .argument("<id>", "Satellite template id")).action(withProfile(async (profile, id) => {
90
- return await satellites(profile).delete(id);
91
- })));
92
87
  return templates;
93
88
  }
94
89
  registerVersions() {
@@ -5,17 +5,16 @@ import { registerCommand, withProfile } from "../lib/scaffold.js";
5
5
  * `search`/`available`/`install`/`upgrade`/`uninstall` map 1:1 onto the SDK `Project` client's
6
6
  * template methods (@ptkl/sdk/beta).
7
7
  *
8
- * `activation-code redeem|list` do NOT map onto `Project.getTemplateByCode` — that method wraps
8
+ * `activation-code redeem` does NOT map onto `Project.getTemplateByCode` — that method wraps
9
9
  * `GET /v1/project/template/activationCode/{code}` (platform-api
10
10
  * internal/project/controllers/template_activation_code.go), a public read-only lookup that
11
11
  * resolves a code to its template's install instructions without redeeming anything. The actual
12
12
  * redemption is a *different* platform subsystem — activation codes with `product_type: template`
13
- * (also `account`/`app`/`integration`) redeemed via `POST /v1/project/codes/{code}/redeem` and
14
- * listed via `GET /v1/project/codes/redeemed` (internal/project/controllers/code_redeem.go,
15
- * internal/project/domain/code/service.go). The v0.10 `Project` client has no typed method for
16
- * either route yet, so these two subcommands go through the authenticated client instance's public
17
- * `.client` (an AxiosInstance, see @ptkl/sdk/beta BaseClient) rather than a named method, pending
18
- * a follow-up SDK WP to give `Project` `redeemCode()`/`listRedeemedCodes()`. */
13
+ * (also `account`/`app`/`integration`) redeemed via `POST /v1/project/codes/{code}/redeem`
14
+ * (internal/project/controllers/code_redeem.go, internal/project/domain/code/service.go). The v0.10
15
+ * `Project` client has no typed method for that route yet, so the subcommand goes through the
16
+ * authenticated client instance's public `.client` (an AxiosInstance, see @ptkl/sdk/beta
17
+ * BaseClient), pending a follow-up SDK WP to give `Project` a `redeemCode()`. */
19
18
  function parseJSON(label, raw) {
20
19
  try {
21
20
  return JSON.parse(raw);
@@ -76,7 +75,7 @@ class TemplateCommand {
76
75
  return cmd;
77
76
  }
78
77
  registerActivationCode() {
79
- const activationCode = new Command("activation-code").description("Redeem and list activation codes (account/app/integration/template benefits)");
78
+ const activationCode = new Command("activation-code").description("Redeem activation codes (account/app/integration/template benefits)");
80
79
  activationCode.addCommand(registerCommand(new Command("redeem")
81
80
  .description("Redeem an activation code for the current user and project")
82
81
  .argument("<code>", "Activation code")).action(withProfile(async (profile, code, opts) => {
@@ -84,11 +83,6 @@ class TemplateCommand {
84
83
  const res = await client.client.post(`/v1/project/codes/${encodeURIComponent(code)}/redeem`);
85
84
  return res.data;
86
85
  })));
87
- activationCode.addCommand(registerCommand(new Command("list").description("List activation codes redeemed by the current user")).action(withProfile(async (profile) => {
88
- const client = sdk.project(profile);
89
- const res = await client.client.get("/v1/project/codes/redeemed");
90
- return res.data;
91
- })));
92
86
  return activationCode;
93
87
  }
94
88
  }
@@ -3,6 +3,7 @@ import { readFileSync } from "fs";
3
3
  import { Command } from "commander";
4
4
  import * as sdk from "../lib/sdk.js";
5
5
  import { registerCommand, withProfile } from "../lib/scaffold.js";
6
+ import { DEFAULT_PAGE_SIZE, paginateOptions, readFlagOptions, readOptions } from "../lib/thunder.js";
6
7
  /** `ptkl thunder` — Thunder generic entity engine (RFC §4.1 "Thunder (generic entity + realtime
7
8
  * cfg)": `system/thunder` read/write). Maps onto the SDK `Thunder` client (@ptkl/sdk/beta), which
8
9
  * wraps the two underlying HTTP verbs (`read`/`write`) plus the typed convenience methods layered
@@ -27,13 +28,6 @@ function loadJSON(label, raw, file, fallback) {
27
28
  }
28
29
  return fallback;
29
30
  }
30
- function readOptions(opts) {
31
- const only = opts.only ? String(opts.only).split(",").map((s) => s.trim()).filter(Boolean) : undefined;
32
- const cacheTTL = opts.cacheTtl !== undefined ? Number(opts.cacheTtl) : undefined;
33
- if (only === undefined && cacheTTL === undefined)
34
- return undefined;
35
- return { ...(only ? { only } : {}), ...(cacheTTL !== undefined ? { cacheTTL } : {}) };
36
- }
37
31
  function withFilterAndReadOptions(cmd) {
38
32
  return cmd
39
33
  .requiredOption("-t, --type <type>", "Thunder entity type name")
@@ -41,6 +35,17 @@ function withFilterAndReadOptions(cmd) {
41
35
  .option("--only <fields>", "Comma-separated list of fields to project")
42
36
  .option("--cache-ttl <seconds>", "Cache TTL in seconds");
43
37
  }
38
+ /** Page size, offset and sort for a `Paginate` read. `read --flag Paginate` takes them too and rejects
39
+ * them on the other flags, see `readFlagOptions`; `scope` says so in that command's help. */
40
+ function withPageOptions(cmd, scope = "") {
41
+ const suffix = scope ? ` ${scope}` : "";
42
+ return cmd
43
+ .option("-l, --limit <n>", `Page size (default: ${DEFAULT_PAGE_SIZE})${suffix}`)
44
+ .option("--skip <n>", `Documents to skip before the page (default: 0)${suffix}`)
45
+ .option("--sort <json>", 'Sort as JSON on stored field paths: user fields are under data., e.g. \'{"data.n":-1}\' or ' +
46
+ '\'[{"data.n":-1},{"updated_at":1}]\' (1 ascending, -1 descending)' +
47
+ suffix);
48
+ }
44
49
  class ThunderCommand {
45
50
  register() {
46
51
  const cmd = new Command("thunder").description("Query and mutate Thunder generic entities (system/thunder)");
@@ -54,16 +59,18 @@ class ThunderCommand {
54
59
  const res = await sdk.thunder(profile).findOne(opts.type, filters, readOptions(opts));
55
60
  return res.data;
56
61
  })));
57
- cmd.addCommand(registerCommand(withFilterAndReadOptions(new Command("paginate")).description("Paginate entities matching filters")).action(withProfile(async (profile, opts) => {
62
+ cmd.addCommand(registerCommand(withPageOptions(withFilterAndReadOptions(new Command("paginate")).description("Paginate entities matching filters"))).action(withProfile(async (profile, opts) => {
58
63
  const filters = parseJSON("--filters", opts.filters);
59
- const res = await sdk.thunder(profile).paginate(opts.type, filters, readOptions(opts));
64
+ const res = await sdk.thunder(profile).paginate(opts.type, filters, paginateOptions(opts));
60
65
  return res.data;
61
66
  })));
62
- cmd.addCommand(registerCommand(withFilterAndReadOptions(new Command("read"))
67
+ cmd.addCommand(registerCommand(withPageOptions(withFilterAndReadOptions(new Command("read"))
63
68
  .description("Low-level read: send a raw Thunder read flag (Find | FindOne | Paginate)")
64
- .requiredOption("--flag <flag>", "Thunder read flag: Find | FindOne | Paginate")).action(withProfile(async (profile, opts) => {
69
+ .requiredOption("--flag <flag>", "Thunder read flag: Find | FindOne | Paginate"), "(--flag Paginate only)")).action(withProfile(async (profile, opts) => {
65
70
  const filters = parseJSON("--filters", opts.filters);
66
- const res = await sdk.thunder(profile).read(opts.type, filters, opts.flag, readOptions(opts));
71
+ const res = await sdk
72
+ .thunder(profile)
73
+ .read(opts.type, filters, opts.flag, readFlagOptions(opts.flag, opts));
67
74
  return res.data;
68
75
  })));
69
76
  cmd.addCommand(registerCommand(new Command("write")
@@ -1,4 +1,5 @@
1
1
  import { Command } from "commander";
2
+ import RunIdentityService from "../lib/runIdentity.js";
2
3
  import * as sdk from "../lib/sdk.js";
3
4
  import { registerCommand, withProfile } from "../lib/scaffold.js";
4
5
  /** `ptkl workflow` — Workflow engine (RFC §4.2 "Workflow", `workflow/…` gateway prefix).
@@ -52,17 +53,22 @@ class WorkflowCommand {
52
53
  })));
53
54
  cmd.addCommand(registerCommand(new Command("create")
54
55
  .description("Create a new workflow")
55
- .requiredOption("-d, --data <json>", "Workflow payload as a JSON string (name, dev_version, public_version, integrator, roles, settings)")).action(withProfile(async (profile, opts) => {
56
+ .requiredOption("-d, --data <json>", "Workflow payload as a JSON string (name, dev_version, public_version, integrator, roles, settings)")
57
+ .option("--run-as <prn>", "Identity the workflow runs as (prompted for when interactive)")).action(withProfile(async (profile, opts) => {
56
58
  const data = parseJSON("--data", opts.data);
57
- const res = await sdk.workflow(profile).create(data);
59
+ const identity = new RunIdentityService(sdk.platform(profile).getPlatformClient());
60
+ const runAs = await identity.forCreate(opts.runAs);
61
+ const res = await sdk.workflow(profile).create(identity.withRunAs(data, runAs));
58
62
  return res.data;
59
63
  })));
60
64
  cmd.addCommand(registerCommand(new Command("update")
61
65
  .description("Update an existing workflow")
62
66
  .argument("<id>", "Workflow UUID")
63
- .requiredOption("-d, --data <json>", "Workflow payload as a JSON string (name, dev_version, public_version, integrator, roles, settings)")).action(withProfile(async (profile, id, opts) => {
67
+ .requiredOption("-d, --data <json>", "Workflow payload as a JSON string (name, dev_version, public_version, integrator, roles, settings)")
68
+ .option("--run-as <prn>", "Change the identity the workflow runs as")).action(withProfile(async (profile, id, opts) => {
64
69
  const data = parseJSON("--data", opts.data);
65
- const res = await sdk.workflow(profile).update(id, data);
70
+ const identity = new RunIdentityService();
71
+ const res = await sdk.workflow(profile).update(id, identity.withRunAs(data, opts.runAs));
66
72
  return res.data;
67
73
  })));
68
74
  cmd.addCommand(registerCommand(new Command("delete")
@@ -57,3 +57,17 @@ describe("withProfile", () => {
57
57
  expect(exit).toHaveBeenCalledWith(1);
58
58
  });
59
59
  });
60
+ describe("permissions_not_held re-authorize hint", () => {
61
+ const body = { error: "permissions_not_held", message: "permissions not held", added: [], missing: ["secrets::read base_functions"] };
62
+ const enc64 = (s) => Buffer.from(s).toString("base64url");
63
+ it("names the profile command when the grant lacks the permission", () => {
64
+ const p = { ...oauth, scope: `offline_access perm64:${enc64("manage base_functions")}` };
65
+ const text = apiErrorMessage(http(403, body), p);
66
+ expect(text).toContain("Missing: secrets::read base_functions");
67
+ expect(text).toContain('ptkl profile auth o --add-scope "secrets::read base_functions"');
68
+ });
69
+ it("does not hint when the grant holds it", () => {
70
+ const p = { ...oauth, scope: `offline_access perm64:${enc64("secrets::read base_functions")}` };
71
+ expect(apiErrorMessage(http(403, body), p)).not.toContain("grant lacks");
72
+ });
73
+ });
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { apiErrorMessage } from '../apiError.js';
3
+ const refusal = (status, data) => apiErrorMessage({ response: { status, data } });
4
+ describe('capability refusals', () => {
5
+ it('capability_invalid names the entry', () => {
6
+ const out = refusal(400, { error: 'capability_invalid', unit: 'function:f', capability: 's2s::x', message: 'not allowed' });
7
+ expect(out).toContain('not allowed');
8
+ expect(out).toContain('unit: function:f');
9
+ expect(out).toContain('capability: s2s::x');
10
+ });
11
+ it('capability_not_held_by_identity names the capability and identity', () => {
12
+ const out = refusal(403, { error: 'capability_not_held_by_identity', unit: 'node:n1', capability: 'a::b c', run_as: 'prn:role:1', message: 'm' });
13
+ expect(out).toContain('capability: a::b c');
14
+ expect(out).toContain('unit: node:n1');
15
+ expect(out).toContain('run as: prn:role:1');
16
+ });
17
+ it('capability_not_held names the capability', () => {
18
+ const out = refusal(403, { error: 'capability_not_held', unit: 'function:f', capability: 'a::b c', message: 'm' });
19
+ expect(out).toContain('m');
20
+ expect(out).toContain('unit: function:f');
21
+ expect(out).toContain('capability: a::b c');
22
+ });
23
+ });
@@ -0,0 +1,34 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { forgeDevKernelPlugin } from '../forgeDevKernelPlugin.js';
3
+ const fake = (token, appUuid = '') => ({
4
+ configured: true,
5
+ current: async () => token,
6
+ revision: 'r1',
7
+ permissions: ['p'],
8
+ appUuid,
9
+ lastError: 'x',
10
+ failureMessage: () => 'Could not mint the app token ... will not start.',
11
+ });
12
+ describe('forgeDevKernelPlugin', () => {
13
+ it('refuses to serve a page when the app token cannot be minted', async () => {
14
+ const p = forgeDevKernelPlugin('app', 'https://p', undefined, 'dev', 'https://h', fake(null));
15
+ await expect(p.transformIndexHtml()).rejects.toThrow(/will not start/);
16
+ });
17
+ it('seeds the session when minted', async () => {
18
+ const p = forgeDevKernelPlugin('app', 'https://p', undefined, 'dev', 'https://h', fake('tok'));
19
+ const out = await p.transformIndexHtml();
20
+ expect(out[0].children).toContain('forge_actor_token');
21
+ expect(out[0].children).toContain('"tok"');
22
+ });
23
+ it('seeds forge_app_uuid, which the SDK and app permission checks read', async () => {
24
+ const p = forgeDevKernelPlugin('app', 'https://p', undefined, 'dev', 'https://h', fake('tok', 'b1f6c2de-034e-40ff-a5c5-1f256c7449c4'));
25
+ const out = await p.transformIndexHtml();
26
+ expect(out[0].children).toContain("sessionStorage.setItem('forge_app_uuid',\"b1f6c2de-034e-40ff-a5c5-1f256c7449c4\")");
27
+ });
28
+ it('clears a stale forge_app_uuid when preflight reports none', async () => {
29
+ const p = forgeDevKernelPlugin('app', 'https://p', undefined, 'dev', 'https://h', fake('tok'));
30
+ const out = await p.transformIndexHtml();
31
+ expect(out[0].children).toContain("sessionStorage.removeItem('forge_app_uuid')");
32
+ expect(out[0].children).not.toContain("setItem('forge_app_uuid'");
33
+ });
34
+ });
@@ -0,0 +1,61 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { ForgeDevServiceExec } from '../forgeDevServiceExec.js';
3
+ function setup(statuses, tokens) {
4
+ const bearers = [];
5
+ const post = vi.fn(async (_u, _p, c) => {
6
+ bearers.push(c.headers.Authorization);
7
+ return { status: statuses[bearers.length - 1] ?? 200, data: {} };
8
+ });
9
+ let i = 0;
10
+ const token = {
11
+ current: vi.fn(async () => tokens[0]),
12
+ renew: vi.fn(async () => tokens[++i] ?? null),
13
+ lastError: 'boom',
14
+ };
15
+ const warn = vi.fn();
16
+ return { ex: new ForgeDevServiceExec('u', token, post, warn), bearers, post, warn, token };
17
+ }
18
+ describe('ForgeDevServiceExec', () => {
19
+ it('401 renews and retries once with the new app token', async () => {
20
+ const { ex, bearers, token } = setup([401, 200], ['app1', 'app2']);
21
+ expect((await ex.exec({})).status).toBe(200);
22
+ expect(bearers).toEqual(['Bearer app1', 'Bearer app2']);
23
+ expect(token.renew).toHaveBeenCalledTimes(1);
24
+ });
25
+ it('403 fails with no second attempt and never renews', async () => {
26
+ const { ex, bearers, token } = setup([403, 200], ['app1']);
27
+ const res = await ex.exec({});
28
+ expect(res.status).toBe(403);
29
+ expect(res.data.error).toBeTruthy();
30
+ expect(bearers).toEqual(['Bearer app1']);
31
+ expect(token.renew).not.toHaveBeenCalled();
32
+ });
33
+ it('no app token: exec is never called, request fails with the cause, warns once', async () => {
34
+ const { ex, post, warn } = setup([200], [null]);
35
+ const a = await ex.exec({});
36
+ await ex.exec({});
37
+ expect(post).not.toHaveBeenCalled();
38
+ expect(a.status).toBe(503);
39
+ expect(a.data.error).toContain('boom');
40
+ expect(warn).toHaveBeenCalledTimes(1);
41
+ expect(warn.mock.calls[0][0]).toContain('cannot run');
42
+ });
43
+ it('a 403 carrying the service result passes through: the service ran and refused, not the admission', async () => {
44
+ const post = vi.fn(async () => ({
45
+ status: 403,
46
+ data: { response: { statusCode: 403, contentType: 'application/json', body: { code: 1000, message: 'Access to env not allowed.' } }, logs: [] },
47
+ }));
48
+ const token = { current: async () => 'SRC', renew: async () => null, lastError: '' };
49
+ const res = await new ForgeDevServiceExec('http://exec', token, post, () => { }).exec({});
50
+ expect(res.status).toBe(403);
51
+ expect(res.data.response.body.message).toBe('Access to env not allowed.');
52
+ expect(JSON.stringify(res.data)).not.toContain('refused the app identity');
53
+ });
54
+ it('a 403 with an empty body is the admission refusing the app identity', async () => {
55
+ const post = vi.fn(async () => ({ status: 403, data: {} }));
56
+ const token = { current: async () => 'SRC', renew: async () => null, lastError: '' };
57
+ const res = await new ForgeDevServiceExec('http://exec', token, post, () => { }).exec({});
58
+ expect(res.status).toBe(403);
59
+ expect(res.data.error).toMatch(/refused the app identity/);
60
+ });
61
+ });
@@ -0,0 +1,113 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { ForgeDevServiceServer } from '../forgeDevServiceServer.js';
3
+ import { ForgeDevServiceExec } from '../forgeDevServiceExec.js';
4
+ let server;
5
+ afterEach(() => new Promise((r) => (server ? server.close(() => r()) : r())));
6
+ async function start() {
7
+ const posts = [];
8
+ const post = vi.fn(async (url, _p, c) => {
9
+ posts.push({ url, bearer: c.headers.Authorization });
10
+ return { status: 200, data: { response: { statusCode: 200, body: { ok: true } } } };
11
+ });
12
+ const token = { current: async () => 'SOURCE-TOKEN', renew: async () => null, lastError: '' };
13
+ const exec = new ForgeDevServiceExec('http://exec', token, post, () => { });
14
+ const quiet = () => { };
15
+ const srv = new ForgeDevServiceServer({
16
+ port: 0, appName: 'app', appType: 'app', env: 'dev',
17
+ services: [{ name: 'gate' }], bundles: { gate: 'code' }, exec,
18
+ log: quiet, warn: quiet, error: quiet,
19
+ });
20
+ await new Promise((r) => { server = srv.listen(r); });
21
+ const base = `http://127.0.0.1:${server.address().port}`;
22
+ return { base, post, posts, address: server.address() };
23
+ }
24
+ const json = { 'Content-Type': 'application/json' };
25
+ describe('ForgeDevServiceServer', () => {
26
+ it('rejects a service call with no bearer: 401 and never executes', async () => {
27
+ const { base, post } = await start();
28
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Origin: 'http://localhost:5173' }, body: '{}' });
29
+ expect(res.status).toBe(401);
30
+ expect((await res.json()).error).toMatch(/Authorization/);
31
+ expect(post).not.toHaveBeenCalled();
32
+ });
33
+ it('rejects a non-bearer Authorization scheme', async () => {
34
+ const { base, post } = await start();
35
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Basic abc' }, body: '{}' });
36
+ expect(res.status).toBe(401);
37
+ expect(post).not.toHaveBeenCalled();
38
+ });
39
+ it('with a bearer, executes as the SOURCE token, not the caller token', async () => {
40
+ const { base, posts } = await start();
41
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer VIEW-ACTOR', Origin: 'http://localhost:5173' }, body: '{}' });
42
+ expect(res.status).toBe(200);
43
+ expect(posts).toHaveLength(1);
44
+ expect(posts[0].bearer).toBe('Bearer SOURCE-TOKEN');
45
+ expect(posts[0].bearer).not.toContain('VIEW-ACTOR');
46
+ });
47
+ it('preflight allows authorization and content-type', async () => {
48
+ const { base, post } = await start();
49
+ const res = await fetch(`${base}/gate`, {
50
+ method: 'OPTIONS',
51
+ headers: { Origin: 'http://localhost:5173', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'authorization,content-type' },
52
+ });
53
+ expect(res.status).toBe(204);
54
+ const allowed = (res.headers.get('access-control-allow-headers') ?? '').toLowerCase();
55
+ expect(allowed).toContain('authorization');
56
+ expect(allowed).toContain('content-type');
57
+ expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5173');
58
+ expect(post).not.toHaveBeenCalled();
59
+ });
60
+ it('preflight allows the SDK project headers it asks for, not just a fixed pair', async () => {
61
+ const { base, post } = await start();
62
+ const res = await fetch(`${base}/gate`, {
63
+ method: 'OPTIONS',
64
+ headers: {
65
+ Origin: 'http://localhost:5173',
66
+ 'Access-Control-Request-Method': 'POST',
67
+ 'Access-Control-Request-Headers': 'authorization,content-type,x-project-env,x-project-uuid',
68
+ },
69
+ });
70
+ expect(res.status).toBe(204);
71
+ const allowed = (res.headers.get('access-control-allow-headers') ?? '').toLowerCase();
72
+ expect(allowed).toContain('x-project-env');
73
+ expect(allowed).toContain('x-project-uuid');
74
+ expect(allowed).toContain('authorization');
75
+ expect(post).not.toHaveBeenCalled();
76
+ });
77
+ it('preflight allows credentials: the SDK client sets withCredentials', async () => {
78
+ const { base } = await start();
79
+ const res = await fetch(`${base}/gate`, {
80
+ method: 'OPTIONS',
81
+ headers: {
82
+ Origin: 'http://localhost:5173',
83
+ 'Access-Control-Request-Method': 'POST',
84
+ 'Access-Control-Request-Headers': 'authorization,content-type,x-project-env',
85
+ },
86
+ });
87
+ expect(res.status).toBe(204);
88
+ expect(res.headers.get('access-control-allow-credentials')).toBe('true');
89
+ });
90
+ it('the service response itself allows credentials too, or the browser drops it', async () => {
91
+ const { base } = await start();
92
+ const res = await fetch(`${base}/gate`, {
93
+ method: 'POST',
94
+ headers: { ...json, Authorization: 'Bearer VIEW-ACTOR', Origin: 'http://localhost:5173' },
95
+ body: '{}',
96
+ });
97
+ expect(res.status).toBe(200);
98
+ expect(res.headers.get('access-control-allow-credentials')).toBe('true');
99
+ expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5173');
100
+ });
101
+ it('still refuses a non-local origin, even with a bearer', async () => {
102
+ const { base, post } = await start();
103
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: 'https://evil.example' }, body: '{}' });
104
+ expect(res.status).toBe(403);
105
+ expect(res.headers.get('access-control-allow-origin')).toBeNull();
106
+ expect(res.headers.get('access-control-allow-credentials')).toBeNull();
107
+ expect(post).not.toHaveBeenCalled();
108
+ });
109
+ it('binds loopback only', async () => {
110
+ const { address } = await start();
111
+ expect(address.address).toBe('127.0.0.1');
112
+ });
113
+ });
@@ -0,0 +1,85 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { ForgeDevToken } from '../forgeDevToken.js';
3
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { status });
4
+ function stub(revision, mintStatus = 200, uuid) {
5
+ const f = vi.fn(async (url) => {
6
+ if (String(url).includes('/preflight'))
7
+ return json(revision === undefined ? {} : { revision, ...(uuid ? { uuid } : {}) });
8
+ return mintStatus === 200 ? json({ token: 'app-tok', permissions: ['a'] }) : json({ message: 'denied' }, mintStatus);
9
+ });
10
+ vi.stubGlobal('fetch', f);
11
+ return f;
12
+ }
13
+ describe('ForgeDevToken', () => {
14
+ afterEach(() => vi.unstubAllGlobals());
15
+ const mk = (src = true) => new ForgeDevToken('https://h/', 'app', 'dev', 'user', src);
16
+ it('mints once and caches', async () => {
17
+ const f = stub('r1');
18
+ const t = mk();
19
+ expect(await t.current()).toBe('app-tok');
20
+ expect(await t.current()).toBe('app-tok');
21
+ expect(f).toHaveBeenCalledTimes(2); // preflight + mint
22
+ const body = JSON.parse(f.mock.calls[1][1].body);
23
+ expect(body).toEqual({ app_ref: 'app', revision: 'r1', submitted_source: true });
24
+ });
25
+ it('page token does not send submitted_source', async () => {
26
+ const f = stub('r1');
27
+ await mk(false).current();
28
+ const body = JSON.parse(f.mock.calls[1][1].body);
29
+ expect(body).toEqual({ app_ref: 'app', revision: 'r1' });
30
+ expect('submitted_source' in body).toBe(false);
31
+ });
32
+ it('renew forces a new mint', async () => {
33
+ const f = stub('r1');
34
+ const t = mk();
35
+ await t.current();
36
+ await t.renew();
37
+ expect(f).toHaveBeenCalledTimes(4);
38
+ });
39
+ it('reports nothing deployed', async () => {
40
+ stub(undefined);
41
+ const t = mk();
42
+ expect(await t.current()).toBeNull();
43
+ expect(t.lastError).toMatch(/nothing is deployed/);
44
+ });
45
+ it('returns null on a failed mint', async () => {
46
+ stub('r1', 403);
47
+ const t = mk();
48
+ expect(await t.current()).toBeNull();
49
+ expect(t.lastError).toBe('denied');
50
+ });
51
+ it('transport failure names the host and the underlying cause', async () => {
52
+ vi.stubGlobal('fetch', vi.fn(async () => {
53
+ throw Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('getaddrinfo ENOTFOUND h'), { code: 'ENOTFOUND' }) });
54
+ }));
55
+ const t = mk();
56
+ expect(await t.current()).toBeNull();
57
+ expect(t.lastError).toContain('https://h');
58
+ expect(t.lastError).toContain('ENOTFOUND');
59
+ expect(t.lastError).toContain('getaddrinfo');
60
+ });
61
+ it('carries the app uuid preflight reports, for the page to scope its own permissions by', async () => {
62
+ stub('r1', 200, 'b1f6c2de-034e-40ff-a5c5-1f256c7449c4');
63
+ const t = mk();
64
+ await t.current();
65
+ expect(t.appUuid).toBe('b1f6c2de-034e-40ff-a5c5-1f256c7449c4');
66
+ });
67
+ it('leaves the app uuid empty when preflight sends none', async () => {
68
+ stub('r1');
69
+ const t = mk();
70
+ await t.current();
71
+ expect(t.appUuid).toBe('');
72
+ });
73
+ it('failureMessage suggests ptkl init only after a 401', async () => {
74
+ stub('r1', 401);
75
+ const t = mk();
76
+ await t.current();
77
+ expect(t.failureMessage()).toContain('ptkl init');
78
+ expect(t.failureMessage()).toContain('will not start');
79
+ stub('r1', 500);
80
+ const u = mk();
81
+ await u.current();
82
+ expect(u.failureMessage()).not.toContain('ptkl init');
83
+ expect(u.failureMessage()).not.toContain('expired');
84
+ });
85
+ });