@ptkl/toolkit 1.4.4 → 1.6.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 +34 -1
- package/dist/commands/__tests__/capabilities.test.js +83 -0
- package/dist/commands/__tests__/componentRunAs.test.js +65 -0
- package/dist/commands/__tests__/forge-bundle-layout.test.js +58 -0
- package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
- package/dist/commands/__tests__/forge-tools.test.js +64 -0
- package/dist/commands/__tests__/forge-variables.test.js +16 -0
- package/dist/commands/__tests__/kortexPlaybook.test.js +328 -0
- package/dist/commands/__tests__/role.test.js +83 -0
- package/dist/commands/__tests__/runAs.test.js +63 -0
- package/dist/commands/__tests__/thunder.test.js +46 -0
- package/dist/commands/component.js +9 -3
- package/dist/commands/forge.js +262 -202
- package/dist/commands/functions.js +11 -5
- package/dist/commands/integrations/payments.js +11 -7
- package/dist/commands/kortex.js +8 -6
- package/dist/commands/kortexPlaybook.js +396 -0
- package/dist/commands/role.js +45 -54
- package/dist/commands/satellite.js +0 -5
- package/dist/commands/thunder.js +19 -12
- package/dist/commands/workflow.js +10 -4
- package/dist/lib/__tests__/apiError.test.js +18 -0
- package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
- package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
- package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
- package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
- package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
- package/dist/lib/__tests__/runIdentity.test.js +101 -0
- package/dist/lib/__tests__/thunder.test.js +101 -0
- package/dist/lib/apiError.js +94 -1
- package/dist/lib/forgeDevKernelPlugin.js +90 -4
- package/dist/lib/forgeDevServiceExec.js +49 -0
- package/dist/lib/forgeDevServiceServer.js +163 -0
- package/dist/lib/forgeDevToken.js +126 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +1 -1
- package/dist/lib/kortex/__tests__/playbookRules.test.js +120 -0
- package/dist/lib/kortex/__tests__/resultSchemaChecker.test.js +37 -0
- package/dist/lib/kortex/playbookValidator.js +297 -0
- package/dist/lib/kortex/providers/protokol.js +1 -1
- package/dist/lib/kortex/resultSchemaChecker.js +188 -0
- package/dist/lib/kortex/session.js +1 -3
- package/dist/lib/oauth/ScopePreset.js +4 -3
- package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
- package/dist/lib/runIdentity.js +51 -0
- package/dist/lib/thunder.js +98 -0
- package/package.json +2 -2
package/dist/commands/role.js
CHANGED
|
@@ -1,63 +1,54 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
|
|
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
|
-
|
|
8
|
-
|
|
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...>", "
|
|
14
|
-
.requiredOption("-w, --workspaces <workspaces...>", "
|
|
15
|
-
.option("-l --level <level>", "level of the role")
|
|
16
|
-
.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.
|
|
26
|
-
.
|
|
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...>", "
|
|
29
|
-
.requiredOption("-w, --workspaces <workspaces...>", "
|
|
30
|
-
.requiredOption("-l --level <level>", "level of the role")
|
|
31
|
-
.
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
return
|
|
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() {
|
package/dist/commands/thunder.js
CHANGED
|
@@ -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,
|
|
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
|
|
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)")
|
|
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
|
|
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)")
|
|
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
|
|
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")
|
|
@@ -29,6 +29,10 @@ describe("apiErrorMessage", () => {
|
|
|
29
29
|
expect(apiErrorMessage(http(400, { message: "plain" }))).toBe("plain");
|
|
30
30
|
expect(apiErrorMessage(http(500, "boom"))).toBe("boom");
|
|
31
31
|
});
|
|
32
|
+
it("prints the problems of a refused deploy", () => {
|
|
33
|
+
const body = { message: "workforce: playbook version has 1 problem(s)", problems: [{ code: "agent_disabled", node_id: "s1", message: "The agent on Step \"A\" is disabled." }] };
|
|
34
|
+
expect(apiErrorMessage(http(422, body))).toBe("workforce: playbook version has 1 problem(s)\n - The agent on Step \"A\" is disabled. (step: s1)");
|
|
35
|
+
});
|
|
32
36
|
it("falls back to the HTTP status", () => {
|
|
33
37
|
expect(apiErrorMessage(http(404, Buffer.from("")))).toBe("HTTP 404");
|
|
34
38
|
expect(apiErrorMessage(http(502, {}))).toBe("HTTP 502");
|
|
@@ -57,3 +61,17 @@ describe("withProfile", () => {
|
|
|
57
61
|
expect(exit).toHaveBeenCalledWith(1);
|
|
58
62
|
});
|
|
59
63
|
});
|
|
64
|
+
describe("permissions_not_held re-authorize hint", () => {
|
|
65
|
+
const body = { error: "permissions_not_held", message: "permissions not held", added: [], missing: ["secrets::read base_functions"] };
|
|
66
|
+
const enc64 = (s) => Buffer.from(s).toString("base64url");
|
|
67
|
+
it("names the profile command when the grant lacks the permission", () => {
|
|
68
|
+
const p = { ...oauth, scope: `offline_access perm64:${enc64("manage base_functions")}` };
|
|
69
|
+
const text = apiErrorMessage(http(403, body), p);
|
|
70
|
+
expect(text).toContain("Missing: secrets::read base_functions");
|
|
71
|
+
expect(text).toContain('ptkl profile auth o --add-scope "secrets::read base_functions"');
|
|
72
|
+
});
|
|
73
|
+
it("does not hint when the grant holds it", () => {
|
|
74
|
+
const p = { ...oauth, scope: `offline_access perm64:${enc64("secrets::read base_functions")}` };
|
|
75
|
+
expect(apiErrorMessage(http(403, body), p)).not.toContain("grant lacks");
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -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
|
+
});
|