@entrinsik/vite-plugin-informer 2.13.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.
package/README.md CHANGED
@@ -5,14 +5,18 @@ Vite plugin and deploy tool for Informer App development: a local dev server wir
5
5
  ## Quick start
6
6
 
7
7
  ```bash
8
+ npm install -g @entrinsik/informer-cli
9
+ inf login <your-informer-url> # once: the sign-in dev and deploy use
8
10
  npm create vite@latest my-app -- --template react
9
11
  cd my-app
10
12
  npm install -D @entrinsik/vite-plugin-informer
11
- npx informer-init # wires vite config, informer.yaml, .env, deploy scripts
12
- npm run dev # local dev against the Informer in .env
13
- npm run deploy # assemble + upload + deploy
13
+ npx informer-init # wires vite config, informer.yaml, deploy scripts
14
+ npm run dev # local dev against the server you signed in to
15
+ npm run deploy # assemble + upload + deploy (or: inf deploy, which asks first)
14
16
  ```
15
17
 
18
+ No `.env` is needed: with no credential in the environment or `.env`, the plugin asks the Informer CLI (`inf auth token`) for the signed-in server and a current token, and a dev server renews it as it runs. `INFORMER_URL` with `INFORMER_API_KEY` (or `INFORMER_USER` and `INFORMER_PASS`) in `.env` still work, and win when set; `INFORMER_URL` alone picks which of your sign-ins to use.
19
+
16
20
  `informer-init` leaves an existing `@entrinsik/vite-plugin-informer` entry alone, and writes one only when the dependency is missing — in which case it uses its own version (2.12.0 and later; before that it wrote `^1.0.0`). A project scaffolded earlier still carries `^1.0.0`, which resolves to 1.0.5 and predates everything below: bump it by hand.
17
21
 
18
22
  ## What a deploy ships
package/bin/deploy.js CHANGED
@@ -4,9 +4,12 @@ import { readFile, writeFile } from 'node:fs/promises';
4
4
  import { resolve } from 'node:path';
5
5
  import { deploy } from '../src/deploy.js';
6
6
  import { loadEnv, parseModeArg } from '../src/env.js';
7
+ import { useSignedIn } from '../src/signed-in.js';
7
8
 
8
9
  const mode = parseModeArg(process.argv);
9
10
  loadEnv({ mode });
11
+ // No credential in the environment or .env: use the inf CLI's sign-in
12
+ await useSignedIn(process.env);
10
13
 
11
14
  const baseUrl = process.env.INFORMER_URL;
12
15
  const apiKey = process.env.INFORMER_API_KEY;
@@ -14,13 +17,10 @@ const user = process.env.INFORMER_USER;
14
17
  const pass = process.env.INFORMER_PASS;
15
18
 
16
19
  if (!baseUrl || (!apiKey && (!user || !pass))) {
17
- console.error('Missing required environment variables.');
18
- console.error('Create a .env file with:');
19
- console.error(' INFORMER_URL=http://localhost:3000');
20
- console.error(' INFORMER_API_KEY=your-api-key');
21
- console.error('Or use basic auth:');
22
- console.error(' INFORMER_USER=admin');
23
- console.error(' INFORMER_PASS=yourpassword');
20
+ console.error('Not signed in to an Informer server.');
21
+ console.error('Sign in once with the Informer CLI (npm install -g @entrinsik/informer-cli):');
22
+ console.error(' inf login <your-informer-url>');
23
+ console.error('Or set INFORMER_URL with INFORMER_API_KEY (or INFORMER_USER and INFORMER_PASS) in .env.');
24
24
  process.exit(1);
25
25
  }
26
26
 
package/bin/init.js CHANGED
@@ -208,14 +208,17 @@ async function init() {
208
208
  // 7. Update vite.config
209
209
  await updateViteConfig();
210
210
 
211
- // 8. Create .env.example
212
- const envExample = `# Informer connection settings
213
- INFORMER_URL=http://localhost:3000
214
-
215
- # Option 1: API Key (recommended)
216
- INFORMER_API_KEY=your-api-key
217
-
218
- # Option 2: Basic auth
211
+ // 8. Create .env.example. No .env: the Informer CLI's sign-in (inf login)
212
+ // is the credential, and a placeholder key would stand in its way
213
+ const envExample = `# Nothing here is required. Sign in once with the Informer CLI:
214
+ # npm install -g @entrinsik/informer-cli
215
+ # inf login <your-informer-url>
216
+ # and npm run dev / npm run deploy use that sign-in (inf deploy does too).
217
+ #
218
+ # To use another server or credential instead, copy this file to .env and set:
219
+ # INFORMER_URL=http://localhost:3000
220
+ # INFORMER_API_KEY=your-api-key
221
+ # or basic auth:
219
222
  # INFORMER_USER=admin
220
223
  # INFORMER_PASS=yourpassword
221
224
  `;
@@ -226,13 +229,6 @@ INFORMER_API_KEY=your-api-key
226
229
  console.log('Created .env.example');
227
230
  }
228
231
 
229
- // Also create .env if it doesn't exist
230
- const envPath = resolve(cwd, '.env');
231
- if (!await exists(envPath)) {
232
- await writeFile(envPath, envExample);
233
- console.log('Created .env (update with your credentials)');
234
- }
235
-
236
232
  // 9. Create informer.yaml if it doesn't exist
237
233
  const informerYamlPath = resolve(cwd, 'informer.yaml');
238
234
  if (!await exists(informerYamlPath)) {
@@ -283,7 +279,7 @@ export default defineConfig({
283
279
  }
284
280
 
285
281
  // Check if plugin is already added
286
- if (configContent.includes('vite-plugin-informer') || configContent.includes("informer()")) {
282
+ if (configContent.includes('vite-plugin-informer') || configContent.includes('informer()')) {
287
283
  console.log('Informer plugin already in vite config');
288
284
  return;
289
285
  }
package/bin/workspace.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { resolve, basename } from 'node:path';
5
5
  import { createClient } from '../src/client.js';
6
+ import { useSignedIn } from '../src/signed-in.js';
6
7
  import { loadEnv, envWritePath, localEnvValue, parseModeArg } from '../src/env.js';
7
8
  import { init, migrate, reset } from '../src/workspace.js';
8
9
 
@@ -26,14 +27,16 @@ if (!command || !['init', 'migrate', 'reset'].includes(command)) {
26
27
  process.exit(1);
27
28
  }
28
29
 
30
+ // No credential in the environment or .env: use the inf CLI's sign-in
31
+ await useSignedIn(process.env);
29
32
  const baseUrl = process.env.INFORMER_URL;
30
33
  const apiKey = process.env.INFORMER_API_KEY;
31
34
  const user = process.env.INFORMER_USER;
32
35
  const pass = process.env.INFORMER_PASS;
33
36
 
34
37
  if (!baseUrl || (!apiKey && (!user || !pass))) {
35
- console.error('Missing required environment variables.');
36
- console.error('Set INFORMER_URL and either INFORMER_API_KEY or INFORMER_USER/INFORMER_PASS in .env');
38
+ console.error('Not signed in to an Informer server. Run inf login <your-informer-url>,');
39
+ console.error('or set INFORMER_URL with INFORMER_API_KEY (or INFORMER_USER and INFORMER_PASS) in .env.');
37
40
  process.exit(1);
38
41
  }
39
42
 
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@entrinsik/vite-plugin-informer",
3
- "version": "2.13.0",
3
+ "version": "2.14.0-beta.0",
4
4
  "description": "Vite plugin and deploy tool for Informer App development",
5
5
  "scripts": {
6
- "test": "node --test"
6
+ "test": "node --test",
7
+ "lint": "eslint ."
7
8
  },
8
9
  "repository": {
9
10
  "type": "git",
10
11
  "url": "https://github.com/entrinsik-org/i5.git",
11
- "directory": "packages/vite-plugin-informer"
12
+ "directory": "packages-standalone/vite-plugin-informer"
12
13
  },
13
14
  "author": "Entrinsik Inc.",
14
15
  "license": "UNLICENSED",
@@ -46,5 +47,10 @@
46
47
  "dependencies": {
47
48
  "dotenv": "16.6.1",
48
49
  "yaml": "^2.7.0"
50
+ },
51
+ "devDependencies": {
52
+ "@eslint/js": "9.22.0",
53
+ "eslint": "9.22.0",
54
+ "globals": "15.15.0"
49
55
  }
50
56
  }
package/src/agent-dev.js CHANGED
@@ -157,6 +157,8 @@ async function readSSE(response) {
157
157
  * @returns {Function} Connect middleware
158
158
  */
159
159
  export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, devWorkspaceId, projectRoot, devBindings, appToken, channels = createDevChannels(), platform = devPlatform(), appId = null }) {
160
+ // a string, or a function answering the current header (renewed from the CLI's sign-in)
161
+ const header = () => (typeof authHeader === 'function' ? authHeader() : authHeader);
160
162
 
161
163
  // query() — proxies to the workspace _sql endpoint (same as server-routes.js)
162
164
  async function query(sql, params) {
@@ -166,7 +168,7 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
166
168
 
167
169
  const resp = await globalThis.fetch(`${serverOrigin}/api/datasources/${devWorkspaceId}/_sql`, {
168
170
  method: 'POST',
169
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
171
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
170
172
  body: JSON.stringify({ sql, params: params || [] })
171
173
  });
172
174
 
@@ -221,7 +223,7 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
221
223
  const embed = createDevEmbed({ platform, apiFetch, appId });
222
224
 
223
225
  async function apiFetch(path, opts = {}) {
224
- return await fetchAs(authHeader, path, opts);
226
+ return await fetchAs(header(), path, opts);
225
227
  }
226
228
 
227
229
  // Cross-app request() hits the target's /view/_/ dispatch, which accepts only
@@ -229,11 +231,11 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
229
231
  // INFORMER_API_KEY Bearer is reused; under basic auth INFORMER_APP_TOKEN is
230
232
  // required. appFetch stamps x-informer-app-depth:1 for the one-hop guard.
231
233
  // See server-routes.js.
232
- const appAuth = appToken
234
+ const appAuth = () => (appToken
233
235
  ? `Bearer ${appToken}`
234
- : (authHeader && authHeader.startsWith('Bearer ') ? authHeader : null);
235
- const appFetch = appAuth
236
- ? async (path, opts = {}) => await fetchAs(appAuth, path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
236
+ : (header() && header().startsWith('Bearer ') ? header() : null));
237
+ const appFetch = appAuth()
238
+ ? async (path, opts = {}) => await fetchAs(appAuth(), path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
237
239
  : null;
238
240
 
239
241
  // notify/email — delivery is a console-logged no-op in dev, but required-field
@@ -401,7 +403,7 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
401
403
  // Call the AI model
402
404
  const chatResp = await globalThis.fetch(`${serverOrigin}/api/models/${model}/_chat`, {
403
405
  method: 'POST',
404
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
406
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
405
407
  body: JSON.stringify({
406
408
  messages,
407
409
  system: instructions,
package/src/assemble.js CHANGED
@@ -25,8 +25,9 @@ const ROOT_CONFIG_FILES = ['informer.yaml', 'data-access.yaml', 'API.md', 'READM
25
25
  // channels/ holds live-channel join/leave handlers (App Channels); the server
26
26
  // scans and bundles it like server/ and webhooks/. `embeddings` holds the pump
27
27
  // use-case files: server-side like server/, so they ship with the library and
28
- // the platform can scan them.
29
- const SOURCE_DIRS = ['migrations', 'tools', 'mcp', 'server', 'webhooks', 'channels', 'embeddings', 'lib', 'shared'];
28
+ // the platform can scan them. `cli` holds the commands the installed Informer
29
+ // CLI runs, scanned and bundled like mcp/.
30
+ const SOURCE_DIRS = ['migrations', 'tools', 'mcp', 'cli', 'server', 'webhooks', 'channels', 'embeddings', 'lib', 'shared'];
30
31
 
31
32
  // Entries never worth shipping in an app's server-side library: OS/editor
32
33
  // dotfiles (.DS_Store, .env), nested dependency trees, and test files. Applied
package/src/compat.js CHANGED
@@ -22,6 +22,8 @@ export const FEATURE_FLOORS = Object.freeze({
22
22
  channels: '2026.1.3',
23
23
  // The embedding pump: embeddings/ use cases and embed() on the handler bag.
24
24
  embeddings: '2026.1.3',
25
+ // App CLI commands: cli/ handlers the installed Informer CLI runs.
26
+ cli: '2026.1.4',
25
27
  // Staged uploads/downloads: the uploads/downloads services, /view/_uploads
26
28
  // and /view/_downloads, and __INFORMER__.upload() in the page.
27
29
  streams: '2026.1.3',
@@ -50,7 +52,8 @@ export const FEATURE_FLOORS = Object.freeze({
50
52
  */
51
53
  export const GATED_SOURCE_DIRS = Object.freeze([
52
54
  Object.freeze({ dir: 'channels', feature: 'channels', holds: 'channel join/leave handlers' }),
53
- Object.freeze({ dir: 'embeddings', feature: 'embeddings', holds: 'embedding pump handlers (and the workspace SQL in them)' })
55
+ Object.freeze({ dir: 'embeddings', feature: 'embeddings', holds: 'embedding pump handlers (and the workspace SQL in them)' }),
56
+ Object.freeze({ dir: 'cli', feature: 'cli', holds: 'CLI command handlers' })
54
57
  ]);
55
58
 
56
59
  /**
@@ -179,10 +182,11 @@ export function planDeploy({ server, files, manifest }) {
179
182
  const where = server.version ? `Informer ${server.version}` : 'this Informer';
180
183
 
181
184
  if (server.unknown) {
185
+ const atRisk = GATED_SOURCE_DIRS.map(d => `${d.dir}/ (before ${FEATURE_FLOORS[d.feature]})`).join(', ');
182
186
  warnings.push(
183
187
  `Could not read a comparable version from ${server.version ? `"${server.version}"` : 'GET /api/about'}. `
184
- + 'Deploying everything on the assumption the server is current — if it is older than 2026.1.3, '
185
- + `${GATED_SOURCE_DIRS.map(d => `${d.dir}/`).join(' and ')} will be readable from the App's view URL.`
188
+ + 'Deploying everything on the assumption the server is current. On an older server these trees '
189
+ + `would be readable from the App's view URL: ${atRisk}.`
186
190
  );
187
191
  }
188
192
 
package/src/deploy.js CHANGED
@@ -122,7 +122,7 @@ export async function deploy({ baseUrl, apiKey, user, pass, distDir, name, descr
122
122
 
123
123
  // 6. Upload the app-library file set assembled in step 0: dist output at the
124
124
  // library root, plus informer.yaml / data-access.yaml and the
125
- // server/tools/mcp/migrations/webhooks/embeddings source trees, less any
125
+ // server/tools/mcp/cli/migrations/webhooks/embeddings source trees, less any
126
126
  // tree this server is too old to keep out of browsers (see compat.js).
127
127
  // Sourced from the shared collectAppFiles() so a deploy and a marketplace
128
128
  // publish package byte-identical contents.
package/src/dev-bag.js CHANGED
@@ -74,7 +74,9 @@ export function buildDevUser(user) {
74
74
  *
75
75
  * @param {Object} opts
76
76
  * @param {string} opts.serverOrigin - Informer server origin
77
- * @param {string} opts.authHeader - Basic or Bearer auth header for /api calls
77
+ * @param {string|Function} opts.authHeader - Basic or Bearer auth header for
78
+ * /api calls, or a function answering the current one (a header from the
79
+ * CLI's sign-in is renewed, signed-in.js)
78
80
  * @param {string|null} opts.devWorkspaceId - workspace datasource id for query()
79
81
  * @param {string} opts.projectRoot - app project root
80
82
  * @param {Object} [opts.devBindings] - dev bindings for `target: app` / `target: pack` deps
@@ -90,6 +92,8 @@ export function buildDevUser(user) {
90
92
  * @returns {{ query: Function, apiFetch: Function, build: (opts?: { forwarding?: Object|null }) => Promise<{ manifest: Object, bag: Object }> }}
91
93
  */
92
94
  export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId, projectRoot, devBindings = {}, appToken = null, channels = createDevChannels(), logPrefix = '[app]', platform = devPlatform(), appId = null }) {
95
+ const header = () => (typeof authHeader === 'function' ? authHeader() : authHeader);
96
+
93
97
  // query() implementation — proxies to the workspace _sql endpoint
94
98
  async function query(sql, params) {
95
99
  if (!devWorkspaceId) {
@@ -98,7 +102,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
98
102
 
99
103
  const resp = await globalThis.fetch(`${serverOrigin}/api/datasources/${devWorkspaceId}/_sql`, {
100
104
  method: 'POST',
101
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
105
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
102
106
  body: JSON.stringify({ sql, params: params || [] })
103
107
  });
104
108
 
@@ -178,7 +182,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
178
182
  }
179
183
 
180
184
  async function apiFetch(path, opts = {}) {
181
- return await fetchAs(authHeader, path, opts);
185
+ return await fetchAs(header(), path, opts);
182
186
  }
183
187
 
184
188
  // Cross-app request() targets /api/apps/<id>/view/_/<path>, whose auth accepts
@@ -188,11 +192,11 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
188
192
  // the app proxy's request() throws a pointed error instead of a bare 401.
189
193
  // appFetch also stamps x-informer-app-depth:1 so the target runs one hop deep
190
194
  // and enforces the same one-hop guard it does in production.
191
- const appAuth = appToken
195
+ const appAuth = () => (appToken
192
196
  ? `Bearer ${appToken}`
193
- : (authHeader && authHeader.startsWith('Bearer ') ? authHeader : null);
194
- const appFetch = appAuth
195
- ? async (path, opts = {}) => await fetchAs(appAuth, path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
197
+ : (header() && header().startsWith('Bearer ') ? header() : null));
198
+ const appFetch = appAuth()
199
+ ? async (path, opts = {}) => await fetchAs(appAuth(), path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
196
200
  : null;
197
201
 
198
202
  // notify/email — delivery is a console-logged no-op in dev, but the
@@ -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"
@@ -33,7 +34,9 @@ export const DEV_CAPABILITIES = Object.freeze({
33
34
  channels: true,
34
35
  // channels/ files with config.actor: one live instance per channel (dev-channel-actors.js)
35
36
  channelActors: true,
36
- embeddings: false
37
+ embeddings: false,
38
+ // cli/ commands run only on a deployed app; the dev server does not mirror them
39
+ cli: false
37
40
  });
38
41
 
39
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
  },
@@ -223,7 +223,8 @@ function isDescriptor(value) {
223
223
  * @param {Object} viteServer - Vite dev server instance
224
224
  * @param {Object} opts
225
225
  * @param {string} opts.serverOrigin - Informer server origin
226
- * @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)
227
228
  * @param {string|null} opts.devWorkspaceId - workspace datasource id for query()
228
229
  * @param {string} opts.projectRoot - app project root
229
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
+ }