@ptkl/toolkit 1.8.0 → 1.9.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 CHANGED
@@ -189,6 +189,13 @@ ptkl forge dev -p <path> [options]
189
189
  | `--platform-url <url>` | Platform UI URL for consent/permission flows |
190
190
  | `-m, --mode <mode>` | Vite mode (defaults to `development`) |
191
191
  | `--env <env>` | Target environment (`dev` or `live`) |
192
+ | `--public-host <host>` | Host name other machines use to reach this one (e.g. its Tailscale name). Off by default |
193
+
194
+ #### Opening the dev app from another machine
195
+
196
+ By default the dev page, the dev hub and the dev services only work from the machine running `ptkl forge dev`. If the app runs on machine A and you browse from machine B, pass `--public-host <host>` with the name B uses to reach A, then open `http://<host>:<port>`.
197
+
198
+ This exposes the dev page, the app token it carries and the dev services to the network, so use it only on a network you trust (for example a private Tailscale network).
192
199
 
193
200
  #### Multi-view development
194
201
 
@@ -11,6 +11,7 @@ import { dirname, extname, isAbsolute, join } from 'path';
11
11
  import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
12
12
  import { ForgeDevToken } from '../lib/forgeDevToken.js';
13
13
  import { ForgeDevServiceExec } from '../lib/forgeDevServiceExec.js';
14
+ import { ForgeDevPublicHost } from '../lib/forgeDevPublicHost.js';
14
15
  import { ForgeDevServiceServer } from '../lib/forgeDevServiceServer.js';
15
16
  import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
16
17
  import * as sdk from "../lib/sdk.js";
@@ -439,6 +440,7 @@ class ForgeCommand {
439
440
  .option("-m, --mode <mode>", "Vite mode (controls which .env.[mode] files are loaded). Defaults to 'development'.")
440
441
  .option("--env <env>", "Run for a specific env only (dev or live)")
441
442
  .option("--view <view>", "Which view to serve (defaults to 'main')")
443
+ .option("--public-host <host>", "Host name other machines use to reach this one (e.g. its Tailscale name). Off by default. With it, the dev page, the token it carries and the dev services are reachable from the network.")
442
444
  .action(this.runDev))
443
445
  .addCommand(new Command("setup")
444
446
  .description("Scaffold a new Forge app in a directory (ptkl.config.js, vite, index.html, entry, deps)")
@@ -927,6 +929,17 @@ class ForgeCommand {
927
929
  async runDev(options) {
928
930
  const { path: rawPath, platformUrl, mode, env, view: viewFlag } = options;
929
931
  const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
932
+ let publicHost;
933
+ try {
934
+ publicHost = new ForgeDevPublicHost(options.publicHost);
935
+ }
936
+ catch (err) {
937
+ console.error(`❌ ${err.message}`);
938
+ process.exit(1);
939
+ }
940
+ if (publicHost.enabled) {
941
+ console.warn(`⚠️ --public-host ${publicHost.name}: the dev page, its token and the dev services are reachable from the network.`);
942
+ }
930
943
  const host = Util.getCurrentProfile().host;
931
944
  // Load ptkl.config.js to discover views, services, and app name
932
945
  let appName;
@@ -953,8 +966,8 @@ class ForgeCommand {
953
966
  const { ensureHubRunning, pushBundle, DEV_HUB_PORT } = await import('../lib/devHub.js');
954
967
  const hubStatus = await ensureHubRunning();
955
968
  console.log(hubStatus === 'started'
956
- ? `🔌 Dev hub started on http://localhost:${DEV_HUB_PORT}`
957
- : `🔌 Reusing existing dev hub on http://localhost:${DEV_HUB_PORT}`);
969
+ ? `🔌 Dev hub started on ${publicHost.baseUrl(DEV_HUB_PORT)}`
970
+ : `🔌 Reusing existing dev hub on ${publicHost.baseUrl(DEV_HUB_PORT)}`);
958
971
  // Resolve the entry for the selected view
959
972
  const selectedView = viewFlag ?? 'main';
960
973
  let viewEntry;
@@ -997,6 +1010,7 @@ class ForgeCommand {
997
1010
  const server = await createServer({
998
1011
  root: path,
999
1012
  mode: mode ?? 'development',
1013
+ ...(publicHost.enabled ? { server: { host: true, allowedHosts: [publicHost.name] } } : {}),
1000
1014
  resolve: {
1001
1015
  // One React instance even when @ptkl/components is npm-linked (the
1002
1016
  // linked repo carries its own node_modules/react) — two copies break
@@ -1009,12 +1023,12 @@ class ForgeCommand {
1009
1023
  INTEGRATION_API: `${host}/luma/integrations`,
1010
1024
  PROJECT_API_TOKEN: Util.getCurrentProfile().token,
1011
1025
  PROJECT_ENV: env ?? "dev",
1012
- ...(servicePort ? { FORGE_DEV_SERVICE_URL: `http://localhost:${servicePort}` } : {}),
1026
+ ...(servicePort ? { FORGE_DEV_SERVICE_URL: publicHost.baseUrl(servicePort) } : {}),
1013
1027
  }),
1014
1028
  DEV_HUB_PORT
1015
1029
  },
1016
1030
  plugins: [
1017
- forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT, env ?? 'dev', host, pageToken),
1031
+ forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT, env ?? 'dev', host, pageToken, publicHost),
1018
1032
  kortexDevPlugin({
1019
1033
  host,
1020
1034
  token: Util.getCurrentProfile().token,
@@ -1080,7 +1094,9 @@ class ForgeCommand {
1080
1094
  });
1081
1095
  await server.listen();
1082
1096
  console.log('Current profile:', Util.getCurrentProfile().name);
1083
- console.log(`Dev server running at: ${server?.resolvedUrls?.local[0]}${viewFlag ? ` (view: ${selectedView})` : ''}`);
1097
+ const localUrl = server?.resolvedUrls?.local[0];
1098
+ const serverUrl = publicHost.enabled && localUrl ? publicHost.baseUrl(Number(new URL(localUrl).port)) + '/' : localUrl;
1099
+ console.log(`Dev server running at: ${serverUrl}${viewFlag ? ` (view: ${selectedView})` : ''}`);
1084
1100
  // Build every view declared in ptkl.config.js in watch mode.
1085
1101
  // On each successful rebuild the bundle is pushed to the dev hub so any
1086
1102
  // other locally-running app that embeds this view via AppView picks it up instantly.
@@ -1262,10 +1278,11 @@ class ForgeCommand {
1262
1278
  services: services,
1263
1279
  bundles: serviceBundles,
1264
1280
  exec: serviceExec,
1281
+ publicHost,
1265
1282
  }).listen(() => {
1266
- console.log(`\n⚡ Service dev server running at http://localhost:${SERVICE_PORT}`);
1283
+ console.log(`\n⚡ Service dev server running at ${publicHost.baseUrl(SERVICE_PORT)}`);
1267
1284
  for (const svc of services) {
1268
- console.log(` POST http://localhost:${SERVICE_PORT}/${svc.name}`);
1285
+ console.log(` POST ${publicHost.baseUrl(SERVICE_PORT)}/${svc.name}`);
1269
1286
  }
1270
1287
  console.log('');
1271
1288
  });
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
+ import { ForgeDevPublicHost } from '../forgeDevPublicHost.js';
2
3
  import { forgeDevKernelPlugin } from '../forgeDevKernelPlugin.js';
3
4
  const fake = (token, appUuid = '') => ({
4
5
  configured: true,
@@ -31,4 +32,15 @@ describe('forgeDevKernelPlugin', () => {
31
32
  expect(out[0].children).toContain("sessionStorage.removeItem('forge_app_uuid')");
32
33
  expect(out[0].children).not.toContain("setItem('forge_app_uuid'");
33
34
  });
35
+ it('points the hub at localhost by default', async () => {
36
+ const p = forgeDevKernelPlugin('app', 'https://p', 9229, 'dev', 'https://h', fake('tok'));
37
+ const out = await p.transformIndexHtml();
38
+ expect(out[0].children).toContain('window.__PTKL_DEV_HUB__="http://localhost:9229"');
39
+ });
40
+ it('points the hub at the public host when given', async () => {
41
+ const p = forgeDevKernelPlugin('app', 'https://p', 9229, 'dev', 'https://h', fake('tok'), new ForgeDevPublicHost('macbook-devbox'));
42
+ const out = await p.transformIndexHtml();
43
+ expect(out[0].children).toContain('window.__PTKL_DEV_HUB__="http://macbook-devbox:9229"');
44
+ expect(out[0].children).not.toContain('http://localhost:9229');
45
+ });
34
46
  });
@@ -0,0 +1,36 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { ForgeDevPublicHost } from '../forgeDevPublicHost.js';
3
+ describe('ForgeDevPublicHost', () => {
4
+ it.each([undefined, '', ' '])('is disabled for %j', (v) => {
5
+ const h = new ForgeDevPublicHost(v);
6
+ expect(h.enabled).toBe(false);
7
+ expect(h.baseUrl(5173)).toBe('http://localhost:5173');
8
+ expect(h.listenAddress()).toBe('127.0.0.1');
9
+ expect(h.allowsOrigin('http://localhost:5173')).toBe(false);
10
+ });
11
+ it.each(['macbook-devbox', 'devbox.tail1234.ts.net', '100.64.0.7', ' macbook-devbox '])('accepts %j', (v) => {
12
+ expect(new ForgeDevPublicHost(v).enabled).toBe(true);
13
+ });
14
+ it.each(['http://x', 'x:5173', 'a/b', 'a b', '*', '*.example.com', '-x', 'x-', 'a_b'])('rejects %j', (v) => {
15
+ expect(() => new ForgeDevPublicHost(v)).toThrow(/--public-host/);
16
+ });
17
+ it('builds the base url and listens on all interfaces', () => {
18
+ const h = new ForgeDevPublicHost(' macbook-devbox ');
19
+ expect(h.baseUrl(9229)).toBe('http://macbook-devbox:9229');
20
+ expect(h.listenAddress()).toBe('0.0.0.0');
21
+ });
22
+ it.each([
23
+ ['http://macbook-devbox:5201', true],
24
+ ['https://MacBook-Devbox', true],
25
+ ['http://macbook-devbox', true],
26
+ ['http://other-host:5201', false],
27
+ ['http://evil-macbook-devbox', false],
28
+ ['http://macbook-devbox.evil.com', false],
29
+ ['http://evil.com/macbook-devbox', false],
30
+ ['ftp://macbook-devbox', false],
31
+ ['not a url', false],
32
+ ['', false],
33
+ ])('allowsOrigin(%j) = %s', (origin, expected) => {
34
+ expect(new ForgeDevPublicHost('macbook-devbox').allowsOrigin(origin)).toBe(expected);
35
+ });
36
+ });
@@ -1,9 +1,10 @@
1
1
  import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
  import { ForgeDevServiceServer } from '../forgeDevServiceServer.js';
3
+ import { ForgeDevPublicHost } from '../forgeDevPublicHost.js';
3
4
  import { ForgeDevServiceExec } from '../forgeDevServiceExec.js';
4
5
  let server;
5
6
  afterEach(() => new Promise((r) => (server ? server.close(() => r()) : r())));
6
- async function start() {
7
+ async function start(publicHost) {
7
8
  const posts = [];
8
9
  const post = vi.fn(async (url, _p, c) => {
9
10
  posts.push({ url, bearer: c.headers.Authorization });
@@ -15,7 +16,7 @@ async function start() {
15
16
  const srv = new ForgeDevServiceServer({
16
17
  port: 0, appName: 'app', appType: 'app', env: 'dev',
17
18
  services: [{ name: 'gate' }], bundles: { gate: 'code' }, exec,
18
- log: quiet, warn: quiet, error: quiet,
19
+ log: quiet, warn: quiet, error: quiet, publicHost,
19
20
  });
20
21
  await new Promise((r) => { server = srv.listen(r); });
21
22
  const base = `http://127.0.0.1:${server.address().port}`;
@@ -110,4 +111,40 @@ describe('ForgeDevServiceServer', () => {
110
111
  const { address } = await start();
111
112
  expect(address.address).toBe('127.0.0.1');
112
113
  });
114
+ describe('with --public-host', () => {
115
+ const pub = () => new ForgeDevPublicHost('macbook-devbox');
116
+ const origin = 'http://macbook-devbox:5201';
117
+ it('without it, the same remote origin is refused', async () => {
118
+ const { base, post } = await start();
119
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: origin }, body: '{}' });
120
+ expect(res.status).toBe(403);
121
+ expect(post).not.toHaveBeenCalled();
122
+ });
123
+ it('accepts the public host origin and echoes it', async () => {
124
+ const { base } = await start(pub());
125
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: origin }, body: '{}' });
126
+ expect(res.status).toBe(200);
127
+ expect(res.headers.get('access-control-allow-origin')).toBe(origin);
128
+ expect(res.headers.get('access-control-allow-credentials')).toBe('true');
129
+ });
130
+ it('still refuses any other remote origin', async () => {
131
+ const { base, post } = await start(pub());
132
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: 'http://evil-macbook-devbox:5201' }, body: '{}' });
133
+ expect(res.status).toBe(403);
134
+ expect(res.headers.get('access-control-allow-origin')).toBeNull();
135
+ expect(post).not.toHaveBeenCalled();
136
+ });
137
+ it('still requires a bearer from the public origin', async () => {
138
+ const { base, post } = await start(pub());
139
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Origin: origin }, body: '{}' });
140
+ expect(res.status).toBe(401);
141
+ expect(post).not.toHaveBeenCalled();
142
+ });
143
+ it('lists services under the public host url and binds all interfaces', async () => {
144
+ const { base, address } = await start(pub());
145
+ const body = await (await fetch(`${base}/`)).json();
146
+ expect(body.services[0].url).toBe('http://macbook-devbox:0/gate');
147
+ expect(address.address).toBe('0.0.0.0');
148
+ });
149
+ });
113
150
  });
@@ -7,7 +7,7 @@
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, projectEnv, apiHost, devToken) {
10
+ export function forgeDevKernelPlugin(appName, platformUrl, devHubPort, projectEnv, apiHost, devToken, publicHost) {
11
11
  const appRef = appName ?? '';
12
12
  const platUrl = platformUrl ? platformUrl.replace(/\/$/, '') : '';
13
13
  // The consent page is a standalone load: without this it reads the dashboard's own env
@@ -20,7 +20,7 @@ export function forgeDevKernelPlugin(appName, platformUrl, devHubPort, projectEn
20
20
  var _env=${JSON.stringify(env)};
21
21
  var _apiHost=${JSON.stringify(host)};
22
22
  window.$forge=window.$forge||{};
23
- ${devHubPort ? ` window.__PTKL_DEV_HUB__="http://localhost:${devHubPort}";\n window.DEV_HUB_PORT=${devHubPort};` : ''}
23
+ ${devHubPort ? ` window.__PTKL_DEV_HUB__=${JSON.stringify(publicHost?.baseUrl(devHubPort) ?? `http://localhost:${devHubPort}`)};\n window.DEV_HUB_PORT=${devHubPort};` : ''}
24
24
  function openPlatformPopup(url){return window.open(url,'_blank');}
25
25
  function showWaitingOverlay(message){
26
26
  var overlay=document.createElement('div');
@@ -0,0 +1,39 @@
1
+ // Opt-in (`ptkl forge dev --public-host <host>`): the name other machines use to reach this
2
+ // one. Disabled by default, which keeps every dev listener on loopback.
3
+ const HOST_NAME = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/;
4
+ export class ForgeDevPublicHost {
5
+ host;
6
+ constructor(host) {
7
+ const trimmed = host?.trim();
8
+ if (!trimmed)
9
+ return;
10
+ if (!HOST_NAME.test(trimmed)) {
11
+ throw new Error(`--public-host must be a bare host name or IPv4 address (no scheme, port or path), got "${trimmed}"`);
12
+ }
13
+ this.host = trimmed;
14
+ }
15
+ get enabled() { return this.host !== undefined; }
16
+ /** The validated host name; undefined when disabled. */
17
+ get name() { return this.host; }
18
+ /** Where a browser reaches a dev listener on `port`. */
19
+ baseUrl(port) {
20
+ return `http://${this.host ?? 'localhost'}:${port}`;
21
+ }
22
+ /** True only for an http(s) origin on the public host, any port. */
23
+ allowsOrigin(origin) {
24
+ if (!this.host)
25
+ return false;
26
+ try {
27
+ const url = new URL(origin);
28
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
29
+ return false;
30
+ return url.hostname.toLowerCase() === this.host.toLowerCase();
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ listenAddress() {
37
+ return this.enabled ? '0.0.0.0' : '127.0.0.1';
38
+ }
39
+ }
@@ -3,7 +3,8 @@ import { randomUUID } from 'crypto';
3
3
  // This server runs the app's services as the app token (your credential if it cannot mint) and
4
4
  // has no `service::{name} forge::{uuid}` to enforce: dev services are unbuilt source with no
5
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).
6
+ // the local-origin check below, unless --public-host widens both to that one host) and the
7
+ // caller's identity (a bearer is required).
7
8
  const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
8
9
  const BEARER = /^Bearer\s+\S+/i;
9
10
  export class ForgeDevServiceServer {
@@ -20,23 +21,22 @@ export class ForgeDevServiceServer {
20
21
  error(m) { (this.opts.error ?? console.error)(m); }
21
22
  listen(onListening) {
22
23
  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);
24
+ // Loopback unless --public-host was given.
25
+ server.listen(this.port, this.opts.publicHost?.listenAddress() ?? '127.0.0.1', onListening);
26
26
  return server;
27
27
  }
28
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
29
+ // CORS, for the local dev page (or the --public-host page) only. A cross-origin POST of JSON
30
+ // is preflighted, so refusing unknown origins here keeps a page you happen to be visiting from driving
31
31
  // your services. Requests with no Origin at all are your own tools (curl, tests).
32
32
  const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
33
- const localOrigin = origin === undefined || LOCAL_ORIGIN.test(origin);
33
+ const localOrigin = origin === undefined || LOCAL_ORIGIN.test(origin) || (this.opts.publicHost?.allowsOrigin(origin) ?? false);
34
34
  res.setHeader('Vary', 'Origin');
35
35
  if (origin && localOrigin) {
36
36
  res.setHeader('Access-Control-Allow-Origin', origin);
37
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.
38
+ // credentialed and drops the response unless this says true. It is only ever sent back to an
39
+ // allowed origin, which was already checked above.
40
40
  res.setHeader('Access-Control-Allow-Credentials', 'true');
41
41
  }
42
42
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
@@ -69,7 +69,7 @@ export class ForgeDevServiceServer {
69
69
  services: this.opts.services.map((s) => ({
70
70
  name: s.name,
71
71
  access: s.access || 'public',
72
- url: `http://localhost:${this.port}/${s.name}`,
72
+ url: `${this.opts.publicHost?.baseUrl(this.port) ?? `http://localhost:${this.port}`}/${s.name}`,
73
73
  })),
74
74
  }, null, 2));
75
75
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",