@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.
Files changed (46) hide show
  1. package/README.md +34 -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 +58 -0
  5. package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
  6. package/dist/commands/__tests__/forge-tools.test.js +64 -0
  7. package/dist/commands/__tests__/forge-variables.test.js +16 -0
  8. package/dist/commands/__tests__/kortexPlaybook.test.js +328 -0
  9. package/dist/commands/__tests__/role.test.js +83 -0
  10. package/dist/commands/__tests__/runAs.test.js +63 -0
  11. package/dist/commands/__tests__/thunder.test.js +46 -0
  12. package/dist/commands/component.js +9 -3
  13. package/dist/commands/forge.js +262 -202
  14. package/dist/commands/functions.js +11 -5
  15. package/dist/commands/integrations/payments.js +11 -7
  16. package/dist/commands/kortex.js +8 -6
  17. package/dist/commands/kortexPlaybook.js +396 -0
  18. package/dist/commands/role.js +45 -54
  19. package/dist/commands/satellite.js +0 -5
  20. package/dist/commands/thunder.js +19 -12
  21. package/dist/commands/workflow.js +10 -4
  22. package/dist/lib/__tests__/apiError.test.js +18 -0
  23. package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
  24. package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
  25. package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
  26. package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
  27. package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
  28. package/dist/lib/__tests__/runIdentity.test.js +101 -0
  29. package/dist/lib/__tests__/thunder.test.js +101 -0
  30. package/dist/lib/apiError.js +94 -1
  31. package/dist/lib/forgeDevKernelPlugin.js +90 -4
  32. package/dist/lib/forgeDevServiceExec.js +49 -0
  33. package/dist/lib/forgeDevServiceServer.js +163 -0
  34. package/dist/lib/forgeDevToken.js +126 -0
  35. package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +1 -1
  36. package/dist/lib/kortex/__tests__/playbookRules.test.js +120 -0
  37. package/dist/lib/kortex/__tests__/resultSchemaChecker.test.js +37 -0
  38. package/dist/lib/kortex/playbookValidator.js +297 -0
  39. package/dist/lib/kortex/providers/protokol.js +1 -1
  40. package/dist/lib/kortex/resultSchemaChecker.js +188 -0
  41. package/dist/lib/kortex/session.js +1 -3
  42. package/dist/lib/oauth/ScopePreset.js +4 -3
  43. package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
  44. package/dist/lib/runIdentity.js +51 -0
  45. package/dist/lib/thunder.js +98 -0
  46. package/package.json +2 -2
@@ -0,0 +1,101 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import RunIdentityService from '../runIdentity.js';
3
+ import { apiErrorMessage, forbiddenDetails } from '../apiError.js';
4
+ const identities = [
5
+ { prn: 'prn:role:1', kind: 'role', name: 'Editors' },
6
+ { prn: 'prn:role:maintainer', kind: 'maintainer', name: 'Maintainer' },
7
+ ];
8
+ const choices = (data = { identities }) => ({ get: vi.fn(async () => ({ data })) });
9
+ describe('RunIdentityService.forCreate', () => {
10
+ it('prompts with a tty and returns the pick', async () => {
11
+ const http = choices();
12
+ const ask = vi.fn(async () => 'prn:role:1');
13
+ const run = await new RunIdentityService(http, true, ask).forCreate();
14
+ expect(http.get).toHaveBeenCalledWith('/v1/system/run-identity/choices');
15
+ expect(ask).toHaveBeenCalledWith(identities);
16
+ expect(run).toBe('prn:role:1');
17
+ });
18
+ it('does not prompt or fetch without a tty', async () => {
19
+ const http = choices();
20
+ const ask = vi.fn();
21
+ expect(await new RunIdentityService(http, false, ask).forCreate()).toBeUndefined();
22
+ expect(http.get).not.toHaveBeenCalled();
23
+ expect(ask).not.toHaveBeenCalled();
24
+ });
25
+ it('does not prompt when --run-as is given', async () => {
26
+ const http = choices();
27
+ expect(await new RunIdentityService(http, true, vi.fn()).forCreate('prn:role:9')).toBe('prn:role:9');
28
+ expect(http.get).not.toHaveBeenCalled();
29
+ });
30
+ it('sends no run_as on an older server (404)', async () => {
31
+ const http = { get: vi.fn(async () => { throw { response: { status: 404 } }; }) };
32
+ const ask = vi.fn();
33
+ expect(await new RunIdentityService(http, true, ask).forCreate()).toBeUndefined();
34
+ expect(ask).not.toHaveBeenCalled();
35
+ });
36
+ it('does not prompt on an empty list', async () => {
37
+ const ask = vi.fn();
38
+ expect(await new RunIdentityService(choices({ identities: [] }), true, ask).forCreate()).toBeUndefined();
39
+ expect(ask).not.toHaveBeenCalled();
40
+ });
41
+ it('surfaces other choices errors', async () => {
42
+ const http = { get: vi.fn(async () => { throw { response: { status: 500 } }; }) };
43
+ await expect(new RunIdentityService(http, true, vi.fn()).forCreate()).rejects.toBeTruthy();
44
+ });
45
+ });
46
+ describe('RunIdentityService.withRunAs', () => {
47
+ const svc = new RunIdentityService();
48
+ it('adds run_as when given', () => {
49
+ expect(svc.withRunAs({ name: 'f' }, 'prn:role:1')).toEqual({ name: 'f', run_as: 'prn:role:1' });
50
+ });
51
+ it('omits run_as on an update without the flag', () => {
52
+ const out = svc.withRunAs({ name: 'f' }, undefined);
53
+ expect(out).toEqual({ name: 'f' });
54
+ expect('run_as' in out).toBe(false);
55
+ });
56
+ });
57
+ describe('403 printing', () => {
58
+ it('lists identities and the flag for identity_required', () => {
59
+ const text = apiErrorMessage({
60
+ response: {
61
+ status: 403,
62
+ data: { status: false, code: 403, message: 'identity required: pass run_as', error: 'identity_required', identities },
63
+ },
64
+ });
65
+ expect(text).toContain('identity required: pass run_as');
66
+ expect(text).toContain('prn:role:1 role Editors');
67
+ expect(text).toContain('prn:role:maintainer maintainer Maintainer');
68
+ expect(text).toContain('--run-as <prn>');
69
+ });
70
+ it('prints the identity for identity_not_held', () => {
71
+ const text = forbiddenDetails({ message: 'identity not held: prn:role:9', error: 'identity_not_held', identity: 'prn:role:9' });
72
+ expect(text).toBe('identity not held: prn:role:9\n prn:role:9');
73
+ });
74
+ it('prints added and missing for permissions_not_held', () => {
75
+ const text = forbiddenDetails({
76
+ message: 'permissions not held',
77
+ error: 'permissions_not_held',
78
+ added: ['read a', 'write b'],
79
+ missing: ['write b'],
80
+ });
81
+ expect(text).toContain('Added: read a, write b');
82
+ expect(text).toContain('Missing: write b');
83
+ });
84
+ it('prints added and missing for the Forge upload 403 from appservice', () => {
85
+ const text = apiErrorMessage({
86
+ response: {
87
+ status: 403,
88
+ data: { missing: ['write b'], added: ['read a', 'write b'], status: 'error', statusCode: 403, message: 'Missing permissions' },
89
+ },
90
+ });
91
+ expect(text).toBe('Missing permissions\nAdded: read a, write b\nMissing: write b');
92
+ });
93
+ it('prints only missing when appservice sends no added list', () => {
94
+ const text = forbiddenDetails({ missing: ['manage forge'], status: 'error', statusCode: 403, message: 'Missing permissions' });
95
+ expect(text).toBe('Missing permissions\nMissing: manage forge');
96
+ });
97
+ it('leaves other bodies to the generic message', () => {
98
+ expect(forbiddenDetails({ message: 'nope', error: 'forbidden' })).toBeUndefined();
99
+ expect(apiErrorMessage({ response: { status: 403, data: { message: 'nope' } } })).toBe('nope');
100
+ });
101
+ });
@@ -0,0 +1,101 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { DEFAULT_PAGE_SIZE, paginateOptions, parseSort, readFlagOptions, readOptions } from '../thunder.js';
3
+ describe('readOptions', () => {
4
+ it('omits options when the caller set none', () => {
5
+ expect(readOptions({})).toBeUndefined();
6
+ });
7
+ it('splits --only and keeps --cache-ttl', () => {
8
+ expect(readOptions({ only: ' n , name , ', cacheTtl: '30' })).toEqual({ only: ['n', 'name'], cacheTTL: 30 });
9
+ });
10
+ it('accepts an explicit cache TTL of 0', () => {
11
+ expect(readOptions({ cacheTtl: '0' })).toEqual({ cacheTTL: 0 });
12
+ });
13
+ it('rejects a cache TTL that is not a non-negative integer', () => {
14
+ expect(() => readOptions({ cacheTtl: '-1' })).toThrow(/--cache-ttl must be an integer >= 0/);
15
+ expect(() => readOptions({ cacheTtl: '1.5' })).toThrow(/--cache-ttl/);
16
+ });
17
+ });
18
+ describe('parseSort', () => {
19
+ it('converts a single-field object to the platform sort list', () => {
20
+ expect(parseSort('{"data.n":-1}')).toEqual([{ Key: 'data.n', Value: -1 }]);
21
+ });
22
+ it('converts an array of single-field objects, preserving order', () => {
23
+ expect(parseSort('[{"data.n":-1},{"updated_at":1}]')).toEqual([
24
+ { Key: 'data.n', Value: -1 },
25
+ { Key: 'updated_at', Value: 1 },
26
+ ]);
27
+ });
28
+ it('converts a multi-field object, preserving key order', () => {
29
+ expect(parseSort('{"data.n":-1,"data.name":1}')).toEqual([
30
+ { Key: 'data.n', Value: -1 },
31
+ { Key: 'data.name', Value: 1 },
32
+ ]);
33
+ });
34
+ it('keeps dot-delimited top-level and nested field paths untouched', () => {
35
+ expect(parseSort('{"updated_at":-1,"data.score":1}')).toEqual([
36
+ { Key: 'updated_at', Value: -1 },
37
+ { Key: 'data.score', Value: 1 },
38
+ ]);
39
+ });
40
+ it('rejects invalid JSON and names the option', () => {
41
+ expect(() => parseSort('not-json')).toThrow(/--sort must be valid JSON/);
42
+ });
43
+ it('rejects an empty sort list', () => {
44
+ expect(() => parseSort('[]')).toThrow(/at least one field/);
45
+ });
46
+ it('rejects entries that are not objects or that name no field', () => {
47
+ expect(() => parseSort('[[1]]')).toThrow(/entry 0 must be an object/);
48
+ expect(() => parseSort('{}')).toThrow(/entry 0 must name at least one field/);
49
+ expect(() => parseSort('[{"data.n":1},{}]')).toThrow(/entry 1 must name at least one field/);
50
+ expect(() => parseSort('{"":1}')).toThrow(/must name a field/);
51
+ });
52
+ it('rejects directions other than 1 and -1', () => {
53
+ expect(() => parseSort('{"data.n":2}')).toThrow(/--sort data.n must be 1 \(ascending\) or -1 \(descending\)/);
54
+ expect(() => parseSort('{"data.n":"asc"}')).toThrow(/--sort data.n/);
55
+ });
56
+ });
57
+ describe('paginateOptions', () => {
58
+ it('always sends a page size, even when the caller set none', () => {
59
+ expect(paginateOptions({})).toEqual({ limit: DEFAULT_PAGE_SIZE, skip: 0 });
60
+ });
61
+ it('carries --limit, --skip and --sort', () => {
62
+ expect(paginateOptions({ limit: '5', skip: '10', sort: '{"data.n":1}' })).toEqual({
63
+ limit: 5,
64
+ skip: 10,
65
+ sort: [{ Key: 'data.n', Value: 1 }],
66
+ });
67
+ });
68
+ it('keeps the shared read options on the same request', () => {
69
+ expect(paginateOptions({ only: 'n', cacheTtl: '0', limit: '2' })).toEqual({
70
+ only: ['n'],
71
+ cacheTTL: 0,
72
+ limit: 2,
73
+ skip: 0,
74
+ });
75
+ });
76
+ it('rejects a page size below 1 and a negative offset', () => {
77
+ expect(() => paginateOptions({ limit: '0' })).toThrow(/--limit must be an integer >= 1/);
78
+ expect(() => paginateOptions({ limit: 'many' })).toThrow(/--limit/);
79
+ expect(() => paginateOptions({ skip: '-1' })).toThrow(/--skip must be an integer >= 0/);
80
+ });
81
+ it('accepts only plain decimal integers', () => {
82
+ expect(paginateOptions({ limit: '5' }).limit).toBe(5);
83
+ for (const bad of ['1e3', '0x10', '1.0', '+5', ' 5', '9007199254740992']) {
84
+ expect(() => paginateOptions({ limit: bad })).toThrow(/--limit must be an integer >= 1/);
85
+ }
86
+ });
87
+ });
88
+ describe('readFlagOptions', () => {
89
+ it('gives --flag Paginate the page defaults', () => {
90
+ expect(readFlagOptions('Paginate', {})).toEqual({ limit: DEFAULT_PAGE_SIZE, skip: 0 });
91
+ });
92
+ it('leaves the other flags on the shared read options', () => {
93
+ expect(readFlagOptions('Find', { only: 'n' })).toEqual({ only: ['n'] });
94
+ expect(readFlagOptions('FindOne', {})).toBeUndefined();
95
+ });
96
+ it('rejects page options on a flag that does not paginate', () => {
97
+ expect(() => readFlagOptions('Find', { limit: '5' })).toThrow(/only apply to --flag Paginate/);
98
+ expect(() => readFlagOptions('FindOne', { sort: '{"data.n":1}' })).toThrow(/only apply to --flag Paginate/);
99
+ expect(() => readFlagOptions('Find', { skip: '1' })).toThrow(/only apply to --flag Paginate/);
100
+ });
101
+ });
@@ -24,14 +24,107 @@ function bodyMessage(data) {
24
24
  }
25
25
  return undefined;
26
26
  }
27
+ function parseBody(data) {
28
+ let body = data;
29
+ if (body instanceof ArrayBuffer)
30
+ body = Buffer.from(body);
31
+ else if (ArrayBuffer.isView(body))
32
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
33
+ if (Buffer.isBuffer(body))
34
+ body = body.toString("utf8");
35
+ if (typeof body === "string") {
36
+ try {
37
+ body = JSON.parse(body);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ return body && typeof body === "object" ? body : undefined;
44
+ }
45
+ /** platform-api sends `error: permissions_not_held`; appservice's Forge 403 has no `error`, just `missing` (and `added`). */
46
+ function isPermissionsNotHeld(body) {
47
+ return body?.error === "permissions_not_held" || (!body?.error && Array.isArray(body?.missing));
48
+ }
49
+ /** Text for the run-identity and Forge permission 403s; undefined for anything else. */
50
+ export function forbiddenDetails(data) {
51
+ const body = parseBody(data);
52
+ if (!body)
53
+ return undefined;
54
+ const lines = [];
55
+ if (body.error === "identity_required") {
56
+ lines.push(body.message ?? "identity required");
57
+ for (const i of body.identities ?? [])
58
+ lines.push(` ${i.prn} ${i.kind} ${i.name}`);
59
+ lines.push("Pass one with --run-as <prn>.");
60
+ }
61
+ else if (body.error === "identity_not_held") {
62
+ lines.push(body.message ?? "identity not held");
63
+ if (body.identity)
64
+ lines.push(` ${body.identity}`);
65
+ }
66
+ else if (body.error === "capability_invalid" || body.error === "capability_not_held_by_identity" || body.error === "capability_not_held") {
67
+ lines.push(body.message ?? String(body.error).replace(/_/g, " "));
68
+ if (body.unit)
69
+ lines.push(` unit: ${body.unit}`);
70
+ if (body.capability)
71
+ lines.push(` capability: ${body.capability}`);
72
+ if (body.run_as)
73
+ lines.push(` run as: ${body.run_as}`);
74
+ if (body.error === "capability_not_held")
75
+ lines.push("You can only change a unit whose capabilities you hold yourself.");
76
+ else if (body.error === "capability_not_held_by_identity")
77
+ lines.push("The run identity does not hold this capability; drop it from the unit or choose another identity with --run-as.");
78
+ }
79
+ else if (isPermissionsNotHeld(body)) {
80
+ lines.push(body.message ?? "permissions not held");
81
+ if (Array.isArray(body.added))
82
+ lines.push(`Added: ${body.added.join(", ")}`);
83
+ lines.push(`Missing: ${(body.missing ?? []).join(", ")}`);
84
+ }
85
+ else {
86
+ return undefined;
87
+ }
88
+ return lines.join("\n");
89
+ }
90
+ /** Permissions in a stored OAuth scope: typed `perm64:` entries are decoded, plain text is kept whole. */
91
+ function grantHolds(scope, permission) {
92
+ const decoded = scope.split(/\s+/).filter(t => t.startsWith("perm64:")).map(t => Buffer.from(t.slice(7), "base64url").toString("utf8"));
93
+ return decoded.includes(permission) || scope.includes(permission);
94
+ }
95
+ /** permissions_not_held where the profile's OAuth grant itself lacks a missing permission: re-authorize. */
96
+ function reauthorizeHint(data, profile) {
97
+ const body = parseBody(data);
98
+ if (!isPermissionsNotHeld(body) || !OAuthSession.isOAuth(profile) || !profile?.scope)
99
+ return undefined;
100
+ const lacking = (body.missing ?? []).filter((m) => typeof m === "string" && !grantHolds(profile.scope, m));
101
+ if (!lacking.length)
102
+ return undefined;
103
+ return `${forbiddenDetails(body)}\nThis profile's OAuth grant lacks ${lacking.join(", ")}. `
104
+ + `Re-authorize it once with \`ptkl profile auth ${profile.name} --add-scope "${lacking.join(",")}"\` (or create a new one with \`ptkl profile new\`).`;
105
+ }
106
+ /** A refused deploy or rollback answers 422 with the list of problems; print each one after the message. */
107
+ function withProblems(message, data) {
108
+ const body = parseBody(data);
109
+ if (!message || !Array.isArray(body?.problems) || body.problems.length === 0)
110
+ return message;
111
+ const lines = body.problems.map((p) => {
112
+ const where = [p?.node_id ? `step: ${p.node_id}` : "", p?.field ? `field: ${p.field}` : ""].filter(Boolean).join(", ");
113
+ return ` - ${p?.message ?? p?.code ?? "problem"}${where ? ` (${where})` : ""}`;
114
+ });
115
+ return `${message}\n${lines.join("\n")}`;
116
+ }
27
117
  /** One-line, user-facing text for a failed command. Never includes headers, request config or tokens. */
28
118
  export function apiErrorMessage(err, profile) {
119
+ const reauth = err?.response?.status === 403 ? reauthorizeHint(err.response.data, profile) : undefined;
120
+ if (reauth)
121
+ return reauth;
29
122
  const hint = OAuthSession.describeApiError(err, profile);
30
123
  if (typeof hint === "string")
31
124
  return hint;
32
125
  const response = err?.response;
33
126
  if (response) {
34
- return bodyMessage(response.data) ?? `HTTP ${response.status}`;
127
+ return forbiddenDetails(response.data) ?? withProblems(bodyMessage(response.data), response.data) ?? `HTTP ${response.status}`;
35
128
  }
36
129
  return err?.message || String(err);
37
130
  }
@@ -7,13 +7,19 @@
7
7
  * in platform-forge/src/lib/dynamicImport.ts — uses a DOM overlay with an iframe
8
8
  * instead of a popup window to avoid popup blockers.
9
9
  */
10
- export function forgeDevKernelPlugin(appName, platformUrl, devHubPort) {
10
+ export function forgeDevKernelPlugin(appName, platformUrl, devHubPort, projectEnv, apiHost, devToken) {
11
11
  const appRef = appName ?? '';
12
12
  const platUrl = platformUrl ? platformUrl.replace(/\/$/, '') : '';
13
+ // The consent page is a standalone load: without this it reads the dashboard's own env
14
+ // (default 'live') and preflights a version a dev app has never published.
15
+ const env = projectEnv === 'live' ? 'live' : 'dev';
16
+ const host = apiHost ? apiHost.replace(/\/$/, '') : '';
13
17
  const scriptContent = `(function(){
14
18
  var _appRef=${JSON.stringify(appRef)};
15
19
  var _platformUrl=${JSON.stringify(platUrl)};
16
- window.$forge=window.forge||{};
20
+ var _env=${JSON.stringify(env)};
21
+ var _apiHost=${JSON.stringify(host)};
22
+ window.$forge=window.$forge||{};
17
23
  ${devHubPort ? ` window.__PTKL_DEV_HUB__="http://localhost:${devHubPort}";\n window.DEV_HUB_PORT=${devHubPort};` : ''}
18
24
  function openPlatformPopup(url){return window.open(url,'_blank');}
19
25
  function showWaitingOverlay(message){
@@ -34,10 +40,51 @@ ${devHubPort ? ` window.__PTKL_DEV_HUB__="http://localhost:${devHubPort}";\n w
34
40
  document.body.appendChild(overlay);
35
41
  return{close:function(){overlay.remove();}};
36
42
  }
43
+ // The session (forge context marker, app token) is written by the prelude the dev server
44
+ // prepends to this script — see mintSession(). It is absent when the mint failed, and then
45
+ // nothing below runs: the SDK keeps using the developer's token, exactly as dev did before
46
+ // the handshake existed. Claiming forge context without an app token would be worse than
47
+ // not claiming it, because the SDK reads the marker and the token separately.
48
+ var _revision=window.__PTKL_FORGE_REVISION__||null;
49
+ var _granted=window.__PTKL_FORGE_PERMISSIONS__||[];
50
+ var _lastRefresh=Date.now();
51
+ var _refreshMs=15*60*1000;
52
+ function _refresh(){
53
+ var held=sessionStorage.getItem('forge_actor_token')||'';
54
+ if(!held||!_revision)return Promise.resolve();
55
+ return fetch(_apiHost+'/v1/system/platform/forge/token',{
56
+ method:'POST',credentials:'include',
57
+ headers:{'Content-Type':'application/json','X-Project-Env':_env,'Authorization':'Bearer '+held},
58
+ body:JSON.stringify({app_ref:_appRef,revision:_revision})
59
+ }).then(function(res){
60
+ return res.json().catch(function(){return{};}).then(function(body){
61
+ if(!res.ok)throw new Error((body&&body.message)||('HTTP '+res.status));
62
+ if(body&&body.token){sessionStorage.setItem('forge_actor_token',body.token);_lastRefresh=Date.now();}
63
+ });
64
+ }).catch(function(err){
65
+ console.warn('[ptkl forge dev] Forge token refresh failed, will retry. Restart ptkl forge dev if it keeps failing:',err.message);
66
+ });
67
+ }
68
+ // A browser can throttle a background tab's timers by minutes, so the interval alone lets a
69
+ // 30-minute token expire and every call 401. These are the same resume triggers the platform
70
+ // runtime uses (platform-forge forgeToken.ts).
71
+ function _refreshIfStale(){
72
+ if(Date.now()-_lastRefresh<_refreshMs)return;
73
+ _refresh();
74
+ }
75
+ if(sessionStorage.getItem('protokol_context')==='forge'&&sessionStorage.getItem('forge_actor_token')){
76
+ setInterval(_refresh,_refreshMs);
77
+ document.addEventListener('visibilitychange',function(){if(document.visibilityState==='visible')_refreshIfStale();});
78
+ window.addEventListener('focus',_refreshIfStale);
79
+ window.addEventListener('pageshow',_refreshIfStale);
80
+ window.addEventListener('online',_refreshIfStale);
81
+ }
82
+ window.$forge.ready=Promise.resolve(_granted);
37
83
  window.$forge.requestPermissions=function(permissions,reason){
38
84
  var appName=_appRef||sessionStorage.getItem('forge_app_name')||'';
39
85
  var params=new URLSearchParams();
40
86
  params.set('app_ref',appName);
87
+ params.set('env',_env);
41
88
  if(reason)params.set('reason',reason);
42
89
  permissions.forEach(function(p){params.append('permissions[]',p);});
43
90
  var consentUrl=_platformUrl+'/forge/consent?'+params.toString();
@@ -150,14 +197,53 @@ ${devHubPort ? ` window.__PTKL_DEV_HUB__="http://localhost:${devHubPort}";\n w
150
197
  window.$forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};
151
198
  console.log('[ptkl forge dev] window.forge ready (platform: '+_platformUrl+')');
152
199
  })();`;
200
+ /**
201
+ * The launch handshake, run here rather than in the browser so the app token exists before any
202
+ * app module does — the ordering a real launch has, where platform-forge awaits the token
203
+ * before it renders. Minted per page load: the SDK reads the marker and the token when it
204
+ * constructs a client, so a token that arrives later would never reach clients built at import
205
+ * time. Returns the prelude that seeds the session; throws when nothing could be minted.
206
+ */
207
+ async function mintSession() {
208
+ // Never serve a page that would run as the developer: no token, no page. runDev checks this
209
+ // at startup and exits, so reaching the throw means the token was lost mid-session.
210
+ const token = devToken ? await devToken.current() : null;
211
+ if (!devToken || !token) {
212
+ throw new Error(devToken ? devToken.failureMessage() : 'No app token source configured; `ptkl forge dev` cannot run the app as itself.');
213
+ }
214
+ {
215
+ const revision = devToken.revision;
216
+ const permissions = devToken.permissions;
217
+ const appUuid = devToken.appUuid;
218
+ console.log(`⚡ Running as ${appRef} in ${env} (${permissions.length} permissions)`);
219
+ // forge_app_uuid is what the deployed runtime seeds from the launch URL (platform-forge
220
+ // Init.tsx). The SDK resolves the current app from it, and an app's own permissions are
221
+ // scoped by it (`<perm> forge::<uuid>`), so without it a dev page cannot name itself or
222
+ // test what it holds — the two things it could do when it still ran as the developer.
223
+ return `(function(){
224
+ window.__PTKL_FORGE_REVISION__=${JSON.stringify(revision)};
225
+ window.__PTKL_FORGE_PERMISSIONS__=${JSON.stringify(permissions)};
226
+ try{
227
+ sessionStorage.setItem('protokol_context','forge');
228
+ sessionStorage.setItem('forge_app_name',${JSON.stringify(appRef)});
229
+ ${appUuid ? `sessionStorage.setItem('forge_app_uuid',${JSON.stringify(appUuid)});` : `sessionStorage.removeItem('forge_app_uuid');`}
230
+ sessionStorage.setItem('forge_app_env',${JSON.stringify(env)});
231
+ if(!sessionStorage.getItem('forge_app_lang'))sessionStorage.setItem('forge_app_lang','en_US');
232
+ sessionStorage.setItem('forge_actor_token',${JSON.stringify(token)});
233
+ }catch(e){}
234
+ })();
235
+ `;
236
+ }
237
+ }
153
238
  return {
154
239
  name: 'ptkl-forge-dev-kernel',
155
- transformIndexHtml() {
240
+ async transformIndexHtml() {
241
+ const prelude = await mintSession();
156
242
  return [
157
243
  {
158
244
  tag: 'script',
159
245
  attrs: { type: 'text/javascript' },
160
- children: scriptContent,
246
+ children: prelude + scriptContent,
161
247
  injectTo: 'head-prepend',
162
248
  },
163
249
  ];
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Runs a dev service on platform-forge as the app, and only as the app. The developer's token is
3
+ * used solely to mint the app token (ForgeDevToken); it never runs a service, so there is no
4
+ * fallback when the app identity is unavailable or refused.
5
+ */
6
+ export class ForgeDevServiceExec {
7
+ execUrl;
8
+ serviceToken;
9
+ post;
10
+ warn;
11
+ warnedNoToken = false;
12
+ constructor(execUrl, serviceToken, post, warn = (m) => console.warn(m)) {
13
+ this.execUrl = execUrl;
14
+ this.serviceToken = serviceToken;
15
+ this.post = post;
16
+ this.warn = warn;
17
+ }
18
+ async exec(payload) {
19
+ const send = (bearer) => this.post(this.execUrl, payload, {
20
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${bearer}` },
21
+ timeout: 310000,
22
+ validateStatus: () => true,
23
+ });
24
+ const appToken = await this.serviceToken.current();
25
+ if (!appToken) {
26
+ const msg = `Dev services cannot run: the app token could not be minted (${this.serviceToken.lastError}).`;
27
+ if (!this.warnedNoToken) {
28
+ this.warnedNoToken = true;
29
+ this.warn(` ❌ ${msg} Fix this and call the service again; nothing was executed.`);
30
+ }
31
+ return { status: 503, data: { error: msg } };
32
+ }
33
+ let res = await send(appToken);
34
+ if (res.status === 401) {
35
+ // Expired: source actors cannot refresh, so mint again (same identity) and retry once.
36
+ const renewed = await this.serviceToken.renew();
37
+ if (renewed)
38
+ res = await send(renewed);
39
+ }
40
+ // A 403 from exec is two different things. If the body carries the service's own result or
41
+ // error, the service RAN and the refusal came from inside it (a platform call it made) — pass
42
+ // that through untouched, or the real cause is lost. Only a 403 with nothing in it is the
43
+ // admission check refusing the app identity before any code ran.
44
+ if (res.status === 403 && !res.data?.error && !res.data?.response) {
45
+ res = { status: 403, data: { error: 'platform-forge refused the app identity for this dev service before the code ran (403, empty body).' } };
46
+ }
47
+ return res;
48
+ }
49
+ }
@@ -0,0 +1,163 @@
1
+ import http from 'http';
2
+ import { randomUUID } from 'crypto';
3
+ // This server runs the app's services as the app token (your credential if it cannot mint) and
4
+ // has no `service::{name} forge::{uuid}` to enforce: dev services are unbuilt source with no
5
+ // revision and no app uuid. Two things bound who can call it: reachability (loopback bind and
6
+ // the local-origin check below) and the caller's identity (a bearer is required).
7
+ const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
8
+ const BEARER = /^Bearer\s+\S+/i;
9
+ export class ForgeDevServiceServer {
10
+ opts;
11
+ services = {};
12
+ constructor(opts) {
13
+ this.opts = opts;
14
+ for (const svc of opts.services)
15
+ this.services[svc.name] = svc;
16
+ }
17
+ get port() { return this.opts.port; }
18
+ log(m) { (this.opts.log ?? console.log)(m); }
19
+ warn(m) { (this.opts.warn ?? console.warn)(m); }
20
+ error(m) { (this.opts.error ?? console.error)(m); }
21
+ listen(onListening) {
22
+ const server = http.createServer((req, res) => { void this.handle(req, res); });
23
+ // Loopback only. FORGE_DEV_SERVICE_URL is http://localhost:<port>, so nothing that works
24
+ // today reaches this from another host anyway.
25
+ server.listen(this.port, '127.0.0.1', onListening);
26
+ return server;
27
+ }
28
+ async handle(req, res) {
29
+ // CORS, for the local dev page only. A cross-origin POST of JSON is preflighted, so
30
+ // refusing unknown origins here keeps a page you happen to be visiting from driving
31
+ // your services. Requests with no Origin at all are your own tools (curl, tests).
32
+ const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
33
+ const localOrigin = origin === undefined || LOCAL_ORIGIN.test(origin);
34
+ res.setHeader('Vary', 'Origin');
35
+ if (origin && localOrigin) {
36
+ res.setHeader('Access-Control-Allow-Origin', origin);
37
+ // The SDK's axios client sets withCredentials, so the browser treats every call here as
38
+ // credentialed and drops the response unless this says true. It is only ever sent back to a
39
+ // local origin, which was already checked above.
40
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
41
+ }
42
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
43
+ // The SDK sends Authorization, X-Project-Env and X-Project-Uuid, so the browser preflights and
44
+ // every one of them must be allowed or the call fails before it is sent. Echo whatever the
45
+ // preflight asks for instead of naming them: the origin is already restricted above, and a
46
+ // fixed list silently breaks again the next time the SDK adds a header.
47
+ const asked = req.headers['access-control-request-headers'];
48
+ res.setHeader('Access-Control-Allow-Headers', typeof asked === 'string' && asked ? asked : 'Content-Type, Authorization');
49
+ if (!localOrigin) {
50
+ this.warn(` ⚠️ refused a service call from ${origin}`);
51
+ res.writeHead(403, { 'Content-Type': 'application/json' });
52
+ res.end(JSON.stringify({ error: 'This dev service server only answers the local dev page.' }));
53
+ return;
54
+ }
55
+ // Preflights carry no credentials by design, so they are answered before the auth check.
56
+ if (req.method === 'OPTIONS') {
57
+ res.writeHead(204);
58
+ res.end();
59
+ return;
60
+ }
61
+ const url = new URL(req.url || '/', `http://localhost:${this.port}`);
62
+ const serviceName = url.pathname.replace(/^\//, '').replace(/\/$/, '');
63
+ if (!serviceName) {
64
+ // List available services
65
+ res.writeHead(200, { 'Content-Type': 'application/json' });
66
+ res.end(JSON.stringify({
67
+ app: this.opts.appName,
68
+ type: this.opts.appType,
69
+ services: this.opts.services.map((s) => ({
70
+ name: s.name,
71
+ access: s.access || 'public',
72
+ url: `http://localhost:${this.port}/${s.name}`,
73
+ })),
74
+ }, null, 2));
75
+ return;
76
+ }
77
+ // The caller must identify itself. We cannot verify the token here (it is the page's view
78
+ // actor, signed by the platform), so this only requires that the page is a signed-in forge
79
+ // app and not a bare request.
80
+ if (!BEARER.test(req.headers.authorization ?? '')) {
81
+ res.writeHead(401, { 'Content-Type': 'application/json' });
82
+ res.end(JSON.stringify({ error: 'Missing Authorization bearer. Call dev services through the SDK from a signed-in forge dev page.' }));
83
+ return;
84
+ }
85
+ const code = this.opts.bundles[serviceName];
86
+ if (!code) {
87
+ res.writeHead(404, { 'Content-Type': 'application/json' });
88
+ res.end(JSON.stringify({ error: `Service "${serviceName}" not found` }));
89
+ return;
90
+ }
91
+ const chunks = [];
92
+ for await (const chunk of req)
93
+ chunks.push(chunk);
94
+ const rawBody = Buffer.concat(chunks).toString();
95
+ let parsedBody = {};
96
+ try {
97
+ parsedBody = rawBody ? JSON.parse(rawBody) : {};
98
+ }
99
+ catch {
100
+ parsedBody = rawBody;
101
+ }
102
+ const query = {};
103
+ url.searchParams.forEach((v, k) => { query[k] = v; });
104
+ const reqHeaders = {};
105
+ for (const [k, v] of Object.entries(req.headers)) {
106
+ if (typeof v === 'string')
107
+ reqHeaders[k] = v;
108
+ }
109
+ const svcConf = this.services[serviceName];
110
+ const executionId = randomUUID();
111
+ this.log(`→ ${req.method} /${serviceName} (${executionId.slice(0, 8)})`);
112
+ try {
113
+ const payload = {
114
+ expression: code,
115
+ env: this.opts.env,
116
+ context: {
117
+ appUuid: `dev-${this.opts.appName}`,
118
+ appName: this.opts.appName,
119
+ serviceName,
120
+ executionId,
121
+ access: svcConf?.access || 'public',
122
+ },
123
+ input: parsedBody,
124
+ body: parsedBody,
125
+ query,
126
+ headers: reqHeaders,
127
+ };
128
+ // Execute with the exec client's own source-minted token, never the caller's. The page holds a
129
+ // normal view actor, but platform-forge's authorizeDevExec admits only a submitted-source
130
+ // actor (source=1 + app), so forwarding the caller's token would be a 403. The caller's
131
+ // bearer above only authenticates the caller; do not "fix" this by passing it on.
132
+ const evalResponse = await this.opts.exec.exec(payload);
133
+ const data = evalResponse.data;
134
+ if (data.logs?.length) {
135
+ data.logs.forEach((log) => this.log(` 📋 [${serviceName}] ${log}`));
136
+ }
137
+ if (data.error) {
138
+ res.writeHead(evalResponse.status || 500, { 'Content-Type': 'application/json' });
139
+ res.end(JSON.stringify({ error: data.error, logs: data.logs }));
140
+ this.log(` ❌ [${serviceName}] ${data.error}`);
141
+ }
142
+ else if (data.response) {
143
+ const resp = data.response;
144
+ const status = resp.statusCode || 200;
145
+ const contentType = resp.contentType || 'application/json';
146
+ res.writeHead(status, { 'Content-Type': contentType });
147
+ res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body));
148
+ this.log(` ✅ [${serviceName}] ${status} ${contentType}`);
149
+ }
150
+ else {
151
+ res.writeHead(200, { 'Content-Type': 'application/json' });
152
+ res.end(JSON.stringify(data));
153
+ this.log(` ✅ [${serviceName}] 200`);
154
+ }
155
+ }
156
+ catch (err) {
157
+ const msg = err.response?.data?.message || err.message;
158
+ res.writeHead(502, { 'Content-Type': 'application/json' });
159
+ res.end(JSON.stringify({ error: `Eval server error: ${msg}` }));
160
+ this.error(` ❌ [${serviceName}] ${msg}`);
161
+ }
162
+ }
163
+ }