@entrinsik/vite-plugin-informer 2.12.0 → 2.14.0-beta.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.
@@ -165,8 +165,8 @@ const METHOD_SURFACE = {
165
165
  query: ['execute'],
166
166
  datasource: ['query'],
167
167
  integration: ['request'],
168
- app: ['request'],
169
- pack: ['request']
168
+ app: ['request', 'url'],
169
+ pack: ['request', 'url']
170
170
  };
171
171
 
172
172
  // Cross-app request() method allow-list — mirrors REQUEST_METHODS in
@@ -395,7 +395,7 @@ export function resolveAppBinding(binding) {
395
395
  // to the server constant by test/streams-parity.test.js.
396
396
  export const DEV_FORWARD_MAX_BYTES = Math.floor(52428800 * 3 / 4);
397
397
 
398
- export function buildDevContext({ deps, apiFetch, devBindings = {}, appFetch = null, forwarding = null }) {
398
+ export function buildDevContext({ deps, apiFetch, devBindings = {}, appFetch = null, forwarding = null, serverOrigin = null }) {
399
399
  const context = {};
400
400
  for (const [name, decl] of Object.entries(deps || {})) {
401
401
  if (!decl || typeof decl !== 'object') continue;
@@ -403,11 +403,10 @@ export function buildDevContext({ deps, apiFetch, devBindings = {}, appFetch = n
403
403
  if (!VALID_TARGETS.has(target)) continue;
404
404
 
405
405
  // App and pack slots bind from the plugin's `devBindings` (a human
406
- // `owner:slug` pointing request() at the target app). App slots fall
407
- // back to the manifest `defaultBinding` UUID; pack slots have no
408
- // fallback — the pin resolves via marketplace installs, which dev
409
- // doesn't have, so the devBinding names the locally-installed app.
410
- // request() is the only surface either way.
406
+ // `owner:slug` pointing request() and url() at the target app). App
407
+ // slots fall back to the manifest `defaultBinding` UUID; pack slots
408
+ // have no fallback — the pin resolves via marketplace installs, which
409
+ // dev doesn't have, so the devBinding names the locally-installed app.
411
410
  if (target === 'app' || target === 'pack') {
412
411
  const fallback = (target === 'app'
413
412
  && typeof decl.defaultBinding === 'string' && UUID_PATTERN.test(decl.defaultBinding))
@@ -415,7 +414,7 @@ export function buildDevContext({ deps, apiFetch, devBindings = {}, appFetch = n
415
414
  : null;
416
415
  const binding = devBindings[name] != null ? devBindings[name] : fallback;
417
416
  context[name] = binding
418
- ? makeAppDevProxy({ name, binding, appFetch, kind: target })
417
+ ? makeAppDevProxy({ name, binding, appFetch, serverOrigin, kind: target })
419
418
  : makeUnboundDevProxy({ name, target });
420
419
  continue;
421
420
  }
@@ -432,12 +431,31 @@ export function buildDevContext({ deps, apiFetch, devBindings = {}, appFetch = n
432
431
  }
433
432
 
434
433
  /**
435
- * Dev proxy for a `target: app` or `target: pack` slot. `request()` is the
436
- * only surface. Pack slots reuse this wholesale — in production the pack
437
- * driver resolves its marketplace pin and then delegates the runtime to the
438
- * app driver, and the devBinding IS that resolution done by hand. The prod
439
- * version gate (pack_dependency_out_of_range) is not emulated: dev has no
440
- * pack_install to read a version from.
434
+ * Append an app-relative path, query string, or fragment to a view URL, or
435
+ * null when the result would leave the view. Mirrors joinViewPath in
436
+ * informer-server's modules/app/lib/app-launch.js so dev refuses the same
437
+ * paths prod 400s; exported so test/streams-parity.test.js can hold the two
438
+ * copies to the same input table.
439
+ *
440
+ * Unguarded, as the server copy is: no `path` makes the parse throw, so the
441
+ * one thing that can is a malformed INFORMER_URL, and that deserves to read
442
+ * as the config error it is rather than as a claim about '..' segments.
443
+ */
444
+ export function joinViewPath(viewUrl, path) {
445
+ if (!path) return viewUrl;
446
+ const joined = /^[?#]/.test(path) ? `${viewUrl}${path}` : `${viewUrl}/${path.replace(/^\/+/, '')}`;
447
+ const base = new URL(viewUrl, 'http://localhost').pathname;
448
+ const resolved = new URL(joined, 'http://localhost').pathname;
449
+ return resolved === base || resolved.startsWith(`${base}/`) ? joined : null;
450
+ }
451
+
452
+ /**
453
+ * Dev proxy for a `target: app` or `target: pack` slot, with prod's
454
+ * `request()` and `url()` surface. Pack slots reuse this wholesale — in
455
+ * production the pack driver resolves its marketplace pin and then delegates
456
+ * the runtime to the app driver, and the devBinding IS that resolution done
457
+ * by hand. The prod version gate (pack_dependency_out_of_range) is not
458
+ * emulated: dev has no pack_install to read a version from.
441
459
  *
442
460
  * Production runs `request()` through the target's own /view/_/ dispatch, and
443
461
  * dev injects into the same route:
@@ -452,16 +470,21 @@ export function buildDevContext({ deps, apiFetch, devBindings = {}, appFetch = n
452
470
  * Non-JSON success responses follow the prod envelope contract: text/HTML
453
471
  * returns a text envelope; binary is rejected (dev can't emulate it yet).
454
472
  *
473
+ * url(path) -> <INFORMER_URL>/api/apps/<app>/view[/path | ?query | #fragment]
474
+ * The target's view URL on the configured server, for a page to open.
475
+ *
455
476
  * @param {Object} args
456
477
  * @param {string} args.name - dependency slot name
457
478
  * @param {string|{app?: string}} args.binding - devBindings entry (or the
458
479
  * manifest defaultBinding UUID). A bare string is shorthand for `{ app }`.
459
480
  * @param {Function|null} args.appFetch - token-authed fetch, or null when
460
481
  * INFORMER_APP_TOKEN is unset.
482
+ * @param {string|null} [args.serverOrigin] - INFORMER_URL, the server url()
483
+ * links point at.
461
484
  * @param {'app'|'pack'} [args.kind] - slot flavor, for error labels and the
462
485
  * structured resourceType guest code branches on.
463
486
  */
464
- function makeAppDevProxy({ name, binding, appFetch, kind = 'app' }) {
487
+ function makeAppDevProxy({ name, binding, appFetch, serverOrigin = null, kind = 'app' }) {
465
488
  const { app } = resolveAppBinding(binding);
466
489
 
467
490
  return {
@@ -522,6 +545,25 @@ function makeAppDevProxy({ name, binding, appFetch, kind = 'app' }) {
522
545
  return { status, body, contentType: contentType || '', headers: { 'content-type': contentType || '' } };
523
546
  }
524
547
  return body;
548
+ },
549
+
550
+ async url(path) {
551
+ if (!app) {
552
+ throw new Error(
553
+ `Dependency "${name}" (${kind}): dev url() needs the target app — set devBindings.${name}.app (e.g. 'admin:kanban')`
554
+ );
555
+ }
556
+ if (!serverOrigin) {
557
+ throw new Error(`Dependency "${name}" (${kind}): dev url() needs INFORMER_URL, the server its links point at`);
558
+ }
559
+ if (path !== undefined && path !== null && typeof path !== 'string') {
560
+ throw new Error(`Dependency "${name}" (${kind}): url(path) takes a string`);
561
+ }
562
+ const href = joinViewPath(`${serverOrigin}/api/apps/${encodeURIComponent(app)}/view`, path);
563
+ if (!href) {
564
+ throw new Error(`Dependency "${name}" (${kind}): url(path) must not escape the target app with ".." path segments`);
565
+ }
566
+ return href;
525
567
  }
526
568
  };
527
569
  }
@@ -6,6 +6,7 @@
6
6
  * Every capability the dev server mirrors is on. `embeddings` is off by
7
7
  * default: the pump needs a real Informer, so an app that feature-detects on
8
8
  * it sees locally exactly what it sees on an install without the feature.
9
+ * `cli` is off for the same reason: cli/ commands run only once deployed.
9
10
  * Turning it on binds query-time `embed()` to a deployed app's `_embed` route
10
11
  * (see createDevEmbed); the pump itself is still not mirrored. `version` is
11
12
  * `'dev'` (not semver) so a floor check treats the dev mirror as "unknown"
@@ -31,7 +32,11 @@ export const DEV_CAPABILITIES = Object.freeze({
31
32
  // live channels: broadcast() in the sandbox, the `channels:` relay block,
32
33
  // and channels/ join/leave handlers — the dev server mirrors all three.
33
34
  channels: true,
34
- embeddings: false
35
+ // channels/ files with config.actor: one live instance per channel (dev-channel-actors.js)
36
+ channelActors: true,
37
+ embeddings: false,
38
+ // cli/ commands run only on a deployed app; the dev server does not mirror them
39
+ cli: false
35
40
  });
36
41
 
37
42
  export function devPlatform(overrides = {}) {
@@ -216,6 +216,8 @@ export function isStreamRef(value, type) {
216
216
 
217
217
  export function createUpload(store, { filename, contentType, size, chunkSize, fingerprint }) {
218
218
  const { limits } = store;
219
+ // The control-character range is the point of this check.
220
+ // eslint-disable-next-line no-control-regex
219
221
  if (typeof filename !== 'string' || !filename || /[\\/\x00-\x1F]/.test(filename)) {
220
222
  throw httpError(400, 'filename is required and may not contain path separators or control characters');
221
223
  }
package/src/index.js CHANGED
@@ -15,6 +15,7 @@ import { createStreamStore, createUploadsMiddleware, createDownloadsMiddleware }
15
15
  import { streamsClientSource } from './streams-client.js';
16
16
  import { init, migrate } from './workspace.js';
17
17
  import { devPlatform } from './dev-platform.js';
18
+ import { refreshingHeader, useSignedIn } from './signed-in.js';
18
19
 
19
20
  /**
20
21
  * The dev `window.__INFORMER__` context: defaults overlaid with the plugin's
@@ -159,7 +160,7 @@ export default function informer(options = {}) {
159
160
  return {
160
161
  name: 'vite-plugin-informer',
161
162
 
162
- config(_, { command, mode }) {
163
+ async config(_, { command, mode }) {
163
164
  activeMode = mode;
164
165
  loadEnv({ mode });
165
166
 
@@ -170,6 +171,8 @@ export default function informer(options = {}) {
170
171
  };
171
172
 
172
173
  if (isDev) {
174
+ // No credential in the environment or .env: use the inf CLI's sign-in (signed-in.js)
175
+ const signedIn = await useSignedIn(process.env);
173
176
  const baseUrl = process.env.INFORMER_URL;
174
177
  const apiKey = process.env.INFORMER_API_KEY;
175
178
  const user = process.env.INFORMER_USER;
@@ -178,19 +181,28 @@ export default function informer(options = {}) {
178
181
  devWorkspaceId = process.env.INFORMER_DEV_WORKSPACE || null;
179
182
  appToken = process.env.INFORMER_APP_TOKEN || null;
180
183
 
184
+ if (baseUrl && !apiKey && !(user && pass)) {
185
+ console.warn('[informer] INFORMER_URL is set but there is no credential. Run inf login, or set INFORMER_API_KEY in .env.');
186
+ }
181
187
  if (baseUrl) {
182
188
  serverOrigin = baseUrl.replace(/\/+$/, '');
183
- authHeader = apiKey
189
+ const header = apiKey
184
190
  ? 'Bearer ' + apiKey
185
191
  : 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64');
192
+ // the CLI's access token lasts 15 minutes, so a dev server renews it
193
+ const renewed = signedIn.source === 'inf' ? refreshingHeader(header, { expiresAt: signedIn.expiresAt, url: serverOrigin }) : null;
194
+ authHeader = renewed ? renewed.get : header;
186
195
 
187
196
  cfg.server = {
188
197
  proxy: {
189
198
  '/api': {
190
199
  target: baseUrl,
191
200
  changeOrigin: true,
192
- headers: {
193
- Authorization: authHeader
201
+ // set per request, so a renewed header reaches the proxy
202
+ configure: (proxy) => {
203
+ proxy.on('proxyReq', (proxyReq) => {
204
+ proxyReq.setHeader('Authorization', typeof authHeader === 'function' ? authHeader() : authHeader);
205
+ });
194
206
  },
195
207
  ...options.proxy
196
208
  },
@@ -109,6 +109,10 @@ function slotInterface (iface, spec) {
109
109
  return [
110
110
  `export interface ${iface} {`,
111
111
  overloads.join('\n'),
112
+ ` /** Link into the target app's UI: its view root, or a path, query or`,
113
+ ` * fragment under it. Absolute wherever the deployment names an`,
114
+ ` * external address — always, when apps serve from their own origins. */`,
115
+ ' url(path?: string): Promise<string>;',
112
116
  '}'
113
117
  ].join('\n');
114
118
  }
@@ -164,8 +164,8 @@ async function walkJsFiles(dir, basePath) {
164
164
  * descriptor (mirrors app-sandbox.js buildInvokeScript / respondCallback).
165
165
  * The encoding allow-list and contract checks are enforced inside the ivm in
166
166
  * production; replicated here so handlers see the same errors in dev (where
167
- * there's no isolate to attribute the throw to). If you change this, mirror
168
- * it in modules/app/routes/view-api.js.
167
+ * there's no isolate to attribute the throw to). The header rule is shared
168
+ * with prod's modules/app/lib/handler-headers.js — change both.
169
169
  */
170
170
  function sendDescriptor(res, result) {
171
171
  const encoding = typeof result.encoding === 'string' ? result.encoding : null;
@@ -177,28 +177,38 @@ function sendDescriptor(res, result) {
177
177
  }
178
178
  const responseBody = result.body !== undefined ? result.body : null;
179
179
 
180
+ // Validate before writing anything: prod rejects a malformed body while
181
+ // building the response, so nothing of the handler's reaches the client. Left
182
+ // below the header loop, a 500 here still carried the handler's
183
+ // Content-Disposition and the browser saved a .pdf full of JSON.
184
+ if (encoding === 'base64' && !isBase64(responseBody)) {
185
+ throw new Error('Handler returned malformed base64 body');
186
+ }
187
+
180
188
  res.statusCode = result.status || 200;
189
+ // Lowercased for wire parity with Hapi. Node's header lookup is
190
+ // case-insensitive either way, which is why dev never reproduced I5-12972.
181
191
  for (const [key, value] of Object.entries(result.headers || {})) {
182
- res.setHeader(key, value);
192
+ res.setHeader(key.toLowerCase(), value);
193
+ }
194
+
195
+ // Same rule as prod's applyHandlerHeaders, and applied before the body is
196
+ // branched on so it covers base64 too. Dev used to leave a binary response
197
+ // unlabelled, which the browser sniffed happily while prod shipped it as
198
+ // application/json — the I5-12972 failure, arrived at from the other side.
199
+ const declaredType = res.getHeader('content-type');
200
+ if (typeof declaredType !== 'string' || !declaredType.trim()) {
201
+ res.setHeader('content-type', 'application/json');
183
202
  }
184
203
 
185
204
  if (responseBody === null) {
186
205
  res.end();
187
206
  } else if (encoding === 'base64') {
188
- if (!isBase64(responseBody)) {
189
- throw new Error('Handler returned malformed base64 body');
190
- }
191
207
  res.end(Buffer.from(responseBody, 'base64'));
192
208
  } else if (typeof responseBody === 'string') {
193
209
  // Strings go out verbatim, as prod passes them.
194
- if (!res.getHeader('content-type')) {
195
- res.setHeader('Content-Type', 'application/json');
196
- }
197
210
  res.end(responseBody);
198
211
  } else {
199
- if (!res.getHeader('content-type')) {
200
- res.setHeader('Content-Type', 'application/json');
201
- }
202
212
  res.end(JSON.stringify(responseBody));
203
213
  }
204
214
  }
@@ -213,7 +223,8 @@ function isDescriptor(value) {
213
223
  * @param {Object} viteServer - Vite dev server instance
214
224
  * @param {Object} opts
215
225
  * @param {string} opts.serverOrigin - Informer server origin
216
- * @param {string} opts.authHeader - Basic or Bearer auth header for /api calls
226
+ * @param {string|Function} opts.authHeader - Basic or Bearer auth header for
227
+ * /api calls, or a function answering the current one (dev-bag.js)
217
228
  * @param {string|null} opts.devWorkspaceId - workspace datasource id for query()
218
229
  * @param {string} opts.projectRoot - app project root
219
230
  * @param {string[]} [opts.roles] - dev user roles surfaced on request.roles
@@ -0,0 +1,104 @@
1
+ import { execFile as execFileCb } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ /**
5
+ * Credentials from the Informer CLI's sign-in, so an app folder needs no
6
+ * secrets in `.env`.
7
+ *
8
+ * When neither the environment nor `.env` gives a credential
9
+ * (INFORMER_API_KEY, or INFORMER_USER with INFORMER_PASS), the plugin asks
10
+ * the CLI: `inf auth token --json [--url $INFORMER_URL]` prints the signed-in
11
+ * server and a current access token, refreshed by the CLI as needed. The
12
+ * plugin then fills INFORMER_URL (when unset) and INFORMER_API_KEY in its own
13
+ * process, so the deploy, workspace and dev-server code paths read them as
14
+ * they always have. Running the CLI, rather than reading its files, keeps the
15
+ * two packages' versions independent.
16
+ *
17
+ * Access tokens from the CLI last 15 minutes; a dev server asks again before
18
+ * one runs out (refreshingHeader). Credentials set by hand are never
19
+ * replaced, so an existing `.env` keeps working unchanged.
20
+ */
21
+
22
+ const INF = process.platform === 'win32' ? 'inf.cmd' : 'inf';
23
+
24
+ // Ask again this long before the token's stated expiry
25
+ const RENEW_MARGIN_MS = 3 * 60 * 1000;
26
+ const CHECK_EVERY_MS = 60 * 1000;
27
+
28
+ export function hasOwnCredentials(env = process.env) {
29
+ return Boolean(env.INFORMER_API_KEY || (env.INFORMER_USER && env.INFORMER_PASS));
30
+ }
31
+
32
+ /**
33
+ * The CLI's sign-in for `url` (or its current one), or null when the CLI is
34
+ * not installed, nobody is signed in, or the sign-in has run out.
35
+ *
36
+ * @param {Object} [opts]
37
+ * @param {string} [opts.url] - the server to find the sign-in for
38
+ * @param {Function} [opts.execFile] - promisified child_process.execFile, for tests
39
+ * @returns {Promise<{ url: string, token: string, expiresAt: number|null, scope: string|null }|null>}
40
+ */
41
+ export async function signedInCredentials({ url, execFile = promisify(execFileCb), timeoutMs = 15000 } = {}) {
42
+ const args = ['auth', 'token', '--json', ...(url ? ['--url', url] : [])];
43
+ try {
44
+ const { stdout } = await execFile(INF, args, { timeout: timeoutMs, shell: process.platform === 'win32' });
45
+ const parsed = JSON.parse(String(stdout).trim());
46
+ return parsed && parsed.token && parsed.url ? parsed : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Fill INFORMER_URL and INFORMER_API_KEY from the CLI's sign-in when the
54
+ * environment has no credential of its own.
55
+ *
56
+ * @param {Object} [env] - process.env, or a stand-in
57
+ * @param {Object} [opts] - for signedInCredentials
58
+ * @returns {Promise<{ source: 'env'|'inf'|null, expiresAt?: number|null }>}
59
+ * `inf` when the CLI's sign-in filled them, `env` when they were already
60
+ * set, null when there is neither
61
+ */
62
+ export async function useSignedIn(env = process.env, opts = {}) {
63
+ if (env.INFORMER_URL && hasOwnCredentials(env)) return { source: 'env' };
64
+ const signedIn = await signedInCredentials({ url: env.INFORMER_URL, ...opts });
65
+ if (!signedIn) return { source: null };
66
+ if (!env.INFORMER_URL) env.INFORMER_URL = signedIn.url;
67
+ env.INFORMER_API_KEY = signedIn.token;
68
+ return { source: 'inf', expiresAt: signedIn.expiresAt || null };
69
+ }
70
+
71
+ /**
72
+ * The dev server's Authorization header as a function, renewed from the CLI
73
+ * before its token runs out. `stop()` ends the renewal.
74
+ *
75
+ * @param {string} header - the header to start with
76
+ * @param {Object} opts
77
+ * @param {number|null} opts.expiresAt - when the current token expires
78
+ * @param {string} opts.url - the server, to ask the CLI about
79
+ * @returns {{ get: () => string, stop: () => void }}
80
+ */
81
+ export function refreshingHeader(header, { expiresAt, url, now = Date.now, ...opts }) {
82
+ let current = header;
83
+ let expiry = expiresAt;
84
+ let renewing = false;
85
+ const timer = setInterval(async () => {
86
+ if (renewing || !expiry || expiry - now() > RENEW_MARGIN_MS) return;
87
+ renewing = true;
88
+ try {
89
+ const signedIn = await signedInCredentials({ url, ...opts });
90
+ if (signedIn) {
91
+ current = `Bearer ${signedIn.token}`;
92
+ expiry = signedIn.expiresAt || null;
93
+ process.env.INFORMER_API_KEY = signedIn.token;
94
+ } else {
95
+ console.warn('[informer] Your inf sign-in has run out. Run inf login, then restart the dev server.');
96
+ expiry = null;
97
+ }
98
+ } finally {
99
+ renewing = false;
100
+ }
101
+ }, CHECK_EVERY_MS);
102
+ if (timer.unref) timer.unref();
103
+ return { get: () => current, stop: () => clearInterval(timer) };
104
+ }