@rfany/rf 0.20.3 → 0.20.4

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 (3) hide show
  1. package/README.md +9 -4
  2. package/package.json +1 -1
  3. package/rf.mjs +115 -18
package/README.md CHANGED
@@ -2,13 +2,18 @@
2
2
 
3
3
  People's command line for [rollforward](https://github.com/spoj/rollforward): what its page does, from a shell or a desktop agent, as you.
4
4
 
5
- npm i -g @rfany/rf
6
- rf login https://rollforward.example.com
5
+ Run with `npx` so you always stay on the latest version automatically:
6
+
7
+ npx @rfany/rf@latest login https://rollforward.example.com
8
+
9
+ Or use short-lived Entra ID tokens via Azure CLI (no static token saved to disk; requires HTTPS off loopback and an explicit `--resource api://<app-id>`, plus an initial browser sign-in to link your account and establish run-owner sign-in):
10
+
11
+ npx @rfany/rf@latest login https://rollforward.example.com --az --resource api://<app-id>
7
12
 
8
13
  rf opens the page, which asks you to allow it if it shows the same code as rf; or make a token on the page, under Tokens, and
9
- `rf login URL TOKEN`. `rf` alone lists the commands and `rf help COMMAND` gives one's usage; `rf help` is the guide for an agent, read before it first uses rf. Without saved config, help works offline; once signed in, it reads your current capabilities from the server.
14
+ `npx @rfany/rf@latest login URL TOKEN`. `rf` alone lists the commands and `rf help COMMAND` gives one's usage; `rf help` is the guide for an agent, read before it first uses rf. Without saved config, help works offline; once signed in, it reads your current capabilities from the server.
10
15
 
11
- `rf series owner WORKSPACE/SERIES EMAIL` explicitly transfers the whole series, not one instance; only its current owner or a workspace manager may do it. Old runs stop and execution consent is cleared. The incoming owner selects a series-wide ceiling with `rf series credentials WORKSPACE/SERIES --set OFFER,... --autonomous false`, or `--clear` for an explicit empty selection. The owner's acts and answers by whom the agent's ask named start runs under current consent. Other collaborators' words stay notes. Scheduled/autonomous execution needs `--autonomous true`. `rf new instance` never changes credentials; `rf new task` without `--creds` or `--clear` establishes no execution consent.
16
+ `rf series owner WORKSPACE/SERIES EMAIL` explicitly transfers the whole series, not one instance; only its current owner or a workspace manager may do it. Old runs stop and execution consent is cleared. The incoming owner selects series credentials with `rf series credentials WORKSPACE/SERIES --set OFFER,... --autonomous false`, or `--clear` for an explicit empty selection. The owner's acts and answers by whom the agent's ask named start runs under current consent. Other collaborators' words stay notes. Scheduled/autonomous execution needs `--autonomous true`. `rf new instance` never changes credentials; `rf new task` without `--creds` or `--clear` establishes no execution consent.
12
17
 
13
18
  `rf site ask NAME WORKSPACE REASON` asks its owners to use your login there, or approves it at once where you may. `rf grants` describes the system and what runs may do; general platforms and high-risk or failed checks need an admin. Only admins allow hosts, with `rf logins allow SITE HOST --person EMAIL`; you remove one with `rf logins disallow SITE HOST`.
14
19
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rfany/rf",
3
- "version": "0.20.3",
3
+ "version": "0.20.4",
4
4
  "description": "rollforward's command line for people: what its page does, from a shell or a desktop agent, as you",
5
5
  "license": "MIT",
6
6
  "repository": { "type": "git", "url": "git+https://github.com/spoj/rollforward.git", "directory": "cli" },
package/rf.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // Published to npm as @rfany/rf, from cli/. PATH is workspace/series/label, as `rf ls` prints it.
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync, } from 'node:fs';
6
- import { spawn } from 'node:child_process';
6
+ import { execFileSync, spawn } from 'node:child_process';
7
7
  import { homedir, hostname } from 'node:os';
8
8
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
9
9
  import { parseArgs } from 'node:util';
@@ -15,7 +15,7 @@ process.on('uncaughtException', e => {
15
15
  });
16
16
 
17
17
  const usage = (c , vpn = false, admin = false) => {
18
- const all = `rf login URL [TOKEN] without a TOKEN, through the browser: type rf's code on the page, and allow it
18
+ const all = `rf login URL [TOKEN] [--az [--resource URI]] without a TOKEN, through the browser; with --az, short-lived Entra tokens via Azure CLI (no token on disk); run via npx @rfany/rf@latest
19
19
  rf ls [--mine] [--json] every workspace, series and instance you see, with its status, owner, asks waiting and wakes;
20
20
  --mine, only open instances of series you own
21
21
  rf waiting [--json] what waits on you: asks, proposals, requests and expired logins; also note notices (FYI).
@@ -62,7 +62,7 @@ rf series owner SERIES [EMAIL] [--json] the whole series' owner; EMAIL transfe
62
62
  clearing consent; only its current owner or a workspace manager may transfer it
63
63
  rf series credentials SERIES [--set OFFER,...|--clear] [--autonomous true|false] [--json]
64
64
  credentials for every instance; only the owner saves consent, explicitly including [] with
65
- --clear; saving requires --autonomous true|false; no credentials or schedules transfer
65
+ --clear; saving requires --autonomous true|false; no credentials transfer (schedules pause until opted in)
66
66
  rf rename PATH NAME an instance, a series or a workspace, by its path
67
67
  rf new task WORKSPACE [LABEL] [--creds OFFER,...|--clear] [--autonomous true|false] [--comment TEXT [--wake]] a one-off task, Untitled until LABEL or its
68
68
  first comment names it; --wake starts its run on the comment; without --creds or --clear,
@@ -234,7 +234,7 @@ Usual work
234
234
  - Give an input or a corrected output: rf upload PATH FILE [--onto ITEM] [--output], with --wake on the last for a run on them
235
235
  all.
236
236
  - Start an instance: rf new instance SERIES LABEL --wake, only as the series owner. Scheduled wakes need that owner's
237
- autonomous opt-in and keep their authorized credential snapshot; collaborators' wakes become requests for the owner.
237
+ autonomous opt-in and use their current series credentials at fire time; collaborators' wakes become requests for the owner.
238
238
  A one-off: rf new task WORKSPACE --clear --comment TEXT --wake. Promotion with rf new series PATH NAME keeps its owner.
239
239
  - Tell a series something for its runs, or while no instance is open: rf comment SERIES TEXT, which starts no run.
240
240
  rf comment SERIES lists its notes; rf comment --mine lists your notes. Settle an informing note with
@@ -286,7 +286,7 @@ if (cmd === 'comment' || cmd === 'settle') {
286
286
  } else for (let i = 0; i < argv.length; i++) {
287
287
  const flag = argv[i] === '-n' ? 'dry-run' : argv[i] === '-d' ? 'delay' : argv[i].match(/^--(.+)$/)?.[1];
288
288
  if (!flag) args.push(argv[i]);
289
- else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount', 'yes', 'mine', 'daily', 'all'].includes(flag)) flags[flag] = true;
289
+ else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount', 'yes', 'mine', 'daily', 'all', 'az'].includes(flag)) flags[flag] = true;
290
290
  else if (argv[i + 1] === undefined) throw new Error(`--${flag} takes a value`);
291
291
  else if (flag === 'exclude') excludes.push(argv[++i]);
292
292
  else flags[flag] = argv[++i];
@@ -301,10 +301,69 @@ if ((!cmd || cmd === 'help') && !existsSync(config)) {
301
301
  process.exit();
302
302
  }
303
303
  if (cmd !== 'login' && !existsSync(config)) throw new Error('sign in first: rf login URL');
304
- let { url, token } = cmd === 'login' ? { url: args[0]?.replace(/\/$/, ''), token: args[1] } : JSON.parse(readFileSync(config, 'utf8'));
304
+ let { url, token, auth, resource } = cmd === 'login'
305
+ ? { url: args[0]?.replace(/\/$/, ''), token: args[1], auth: flags.az ? 'az' : (typeof flags.auth === 'string' ? flags.auth : undefined), resource: typeof flags.resource === 'string' ? flags.resource : undefined }
306
+ : JSON.parse(readFileSync(config, 'utf8'));
307
+
308
+ function assertSafeAzUrl(rawUrl ) {
309
+ let parsed ;
310
+ try {
311
+ parsed = new URL(rawUrl);
312
+ } catch {
313
+ throw new Error(`invalid server URL: ${rawUrl}`);
314
+ }
315
+ const host = parsed.hostname.toLowerCase();
316
+ const isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
317
+ if (parsed.protocol !== 'https:' && !isLoopback) {
318
+ throw new Error('--az requires https:// off loopback');
319
+ }
320
+ }
321
+
322
+ function assertValidAzResource(res ) {
323
+ if (!res || res.startsWith('-') || !/^[A-Za-z0-9:/._-]+$/.test(res)) {
324
+ throw new Error('invalid --resource for --az; pass an explicit Entra resource such as --resource api://<app-id>');
325
+ }
326
+ }
327
+
328
+ function jwtExpMs(tok ) {
329
+ try {
330
+ const parts = tok.split('.');
331
+ if (parts.length !== 3) return 0;
332
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
333
+ return typeof payload?.exp === 'number' ? payload.exp * 1000 : 0;
334
+ } catch {
335
+ return 0;
336
+ }
337
+ }
338
+
339
+ let cachedAzToken ;
340
+ function bearerToken() {
341
+ if (auth === 'az') {
342
+ if (cachedAzToken && (cachedAzToken.expMs === 0 || cachedAzToken.expMs - Date.now() > 300_000)) {
343
+ return cachedAzToken.token;
344
+ }
345
+ assertSafeAzUrl(url);
346
+ if (!resource) throw new Error('missing resource for --az auth; run rf login URL --az --resource api://<app-id>');
347
+ assertValidAzResource(resource);
348
+ const azBin = process.env.RF_AZ_BIN || 'az';
349
+ const azArgs = ['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'];
350
+ try {
351
+ const out = (process.platform === 'win32'
352
+ ? execFileSync('cmd.exe', ['/d', '/s', '/c', azBin, ...azArgs], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
353
+ : execFileSync(azBin, azArgs, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })).trim();
354
+ if (!out) throw new Error('empty access token returned by az');
355
+ cachedAzToken = { token: out, expMs: jwtExpMs(out) };
356
+ return out;
357
+ } catch (e ) {
358
+ const stderr = String(e?.stderr ?? '').trim();
359
+ throw new Error(`az account get-access-token failed: ${stderr || e.message}`);
360
+ }
361
+ }
362
+ return token;
363
+ }
305
364
 
306
365
  async function api(path , init = {}, accept = []) {
307
- const r = await fetch(url + path, { ...init, headers: { authorization: `Bearer ${token}` } });
366
+ const r = await fetch(url + path, { ...init, headers: { authorization: `Bearer ${bearerToken()}` } });
308
367
  if (!r.ok && !accept.includes(r.status)) throw new Error(`${init.method ?? 'GET'} ${path}: ${r.status} ${await r.text()}`);
309
368
  return r;
310
369
  }
@@ -347,7 +406,7 @@ async function workspaceNamed(name ) {
347
406
  const pathOf = async (id ) => (await get('/api')).flatMap(w => w.series.flatMap(s => s.instances.filter(i => i.id === id).map(i => `${w.name}/${s.name}/${i.label}`)))[0];
348
407
  // Explicit series-wide offer selection.
349
408
  const ticks = () => flags.clear ? [] : String(flags.creds ?? flags.set ?? '').split(',').map(o => o.trim()).filter(Boolean);
350
- const consent = (offers ) => `, series-wide ceiling: ${offers.join(', ') || 'no credentials'}; you explicitly consent to agents acting as you`;
409
+ const consent = (offers ) => `, series credentials: ${offers.join(', ') || 'no credentials'}; you explicitly consent to agents acting as you`;
351
410
 
352
411
  // Times as this machine's clock reads them, and lengths of time and costs, for the views.
353
412
  const when = (iso ) => new Date(iso).toLocaleString('sv-SE', { dateStyle: 'short', timeStyle: 'short' });
@@ -578,11 +637,22 @@ async function browserToken() {
578
637
  }
579
638
 
580
639
  if (cmd === 'login' && url) {
581
- token ??= await browserToken();
582
- const me = await get('/me');
583
- mkdirSync(dirname(config), { recursive: true });
584
- writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
585
- console.log(`signed in as ${me.email}`);
640
+ if (auth === 'az') {
641
+ assertSafeAzUrl(url);
642
+ resource ||= process.env.RF_AZ_RESOURCE;
643
+ if (!resource) throw new Error('--az requires an explicit trusted --resource api://<app-id> (or RF_AZ_RESOURCE)');
644
+ assertValidAzResource(resource);
645
+ const me = await get('/me');
646
+ mkdirSync(dirname(config), { recursive: true });
647
+ writeFileSync(config, JSON.stringify({ url, auth: 'az', resource }), { mode: 0o600 });
648
+ console.log(`signed in as ${me.email} (az)`);
649
+ } else {
650
+ token ??= await browserToken();
651
+ const me = await get('/me');
652
+ mkdirSync(dirname(config), { recursive: true });
653
+ writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
654
+ console.log(`signed in as ${me.email}`);
655
+ }
586
656
  } else if (cmd === 'ls' && !args.length) {
587
657
  // --mine: open instances of series you own.
588
658
  const me = flags.mine && await get('/me'), rows = (await get('/api')).flatMap(w => w.series.flatMap(s => [
@@ -757,16 +827,43 @@ else if (cmd === 'comment' && args.length < 2) {
757
827
  else console.log(`${args[1]}: series owner ${s.owner ?? 'not selected'}`);
758
828
  } else if (cmd === 'series' && args[0] === 'credentials' && args.length === 2) {
759
829
  const s = await seriesAt(args[1]);
830
+ const fmtSched = (k ) => ` ${k.id} ${k.targetLabel ?? k.target} ${k.at}${k.deadline ? ` (deadline ${k.deadline})` : ''}${k.days ? ` (${k.days.join(',')})` : ''}${k.label ? ` ${k.label}` : ''}${k.from ? ` by ${k.from}` : ''}${k.check ? ` check=${k.check}` : ''}${k.text ? ` ${k.text}` : ''}`;
760
831
  if (flags.set !== undefined || flags.clear) {
761
832
  if (!['true', 'false'].includes(String(flags.autonomous))) throw new Error('saving requires --autonomous true|false');
762
- await post(`/api/series/${s.id}/credentials`, { logins: ticks(), autonomous: flags.autonomous === 'true' }, 'PUT');
833
+ const previewRes = await api(`/api/series/${s.id}/credentials`, {}, flags.autonomous === 'true' ? [] : [404, 405]);
834
+ const preview = previewRes.ok ? await previewRes.json() : null;
835
+ if (flags.autonomous === 'true' && !preview) {
836
+ throw new Error('could not load pending schedules to review before enabling autonomous runs');
837
+ }
838
+ if (flags.autonomous === 'true' && Array.isArray(preview?.schedules) && preview.schedules.length) {
839
+ console.log(`pending schedules to be adopted (${preview.schedules.length}):`);
840
+ for (const k of preview.schedules) console.log(fmtSched(k));
841
+ }
842
+ const body = { logins: ticks(), autonomous: flags.autonomous === 'true' };
843
+ if (preview?.epoch !== undefined) body.expectedEpoch = preview.epoch;
844
+ if (preview?.scheduleRevision) body.expectedSchedules = preview.scheduleRevision;
845
+ const putRes = await post(`/api/series/${s.id}/credentials`, body, 'PUT');
846
+ const rawText = await putRes.text();
847
+ let saved = null;
848
+ try { saved = JSON.parse(rawText); } catch {}
763
849
  console.log(`saved ${args[1]}${consent(ticks())}; autonomous ${flags.autonomous}`);
850
+ if (!preview && flags.autonomous === 'true' && Array.isArray(saved?.schedules) && saved.schedules.length) {
851
+ console.log(`pending schedules that will run (${saved.schedules.length}):`);
852
+ for (const k of saved.schedules) console.log(fmtSched(k));
853
+ }
764
854
  } else {
765
855
  if (flags.autonomous !== undefined) throw new Error('select credentials with --set OFFER,... or --clear');
766
856
  const mine = await get('/logins');
767
- const out = { owner: s.owner, consent: s.consent, yours: mine.flatMap(l => l.offers.map(o => ({ ...o, ...(l.expired && { expired: true }) }))) };
857
+ const detail = await api(`/api/series/${s.id}/credentials`, {}, [404, 405]).then(async r => r.ok ? r.json() : null).catch(() => null);
858
+ const out = { owner: s.owner, consent: s.consent, schedules: detail?.schedules ?? [], yours: mine.flatMap((l ) => l.offers.map((o ) => ({ ...o, ...(l.expired && { expired: true }) }))) };
768
859
  if (flags.json) console.log(JSON.stringify(out, null, 1));
769
- else console.log([`Series owner: ${out.owner ?? 'not selected'}`, out.consent ? `Series-wide ceiling: ${out.consent.logins.join(', ') || 'no credentials'}; autonomous ${out.consent.autonomous}` : 'No execution consent', 'your offers:', ...out.yours.map(o => ` ${o.id} ${o.name}${o.expired ? ' expired' : ''}`)].join('\n'));
860
+ else console.log([
861
+ `Series owner: ${out.owner ?? 'not selected'}`,
862
+ out.consent ? `Series credentials: ${out.consent.logins.join(', ') || 'no credentials'}; autonomous ${out.consent.autonomous}` : 'No execution consent',
863
+ ...(out.schedules.length ? [`pending schedules (${out.schedules.length}):`, ...out.schedules.map(fmtSched)] : []),
864
+ 'your offers:',
865
+ ...out.yours.map((o ) => ` ${o.id} ${o.name}${o.expired ? ' expired' : ''}`),
866
+ ].join('\n'));
770
867
  }
771
868
  } else if (cmd === 'rename' && args.length === 2) {
772
869
  const [w, s, l] = args[0].replace(/\/+$/, '').split('/');
@@ -794,7 +891,7 @@ else if (cmd === 'comment' && args.length < 2) {
794
891
  if (flags.creds !== undefined || flags.clear || flags.autonomous !== undefined) throw new Error('instance credentials were removed: use rf series credentials SERIES');
795
892
  const series = await seriesAt(args[1]);
796
893
  const { id } = await (await post(`/api/series/${series.id}`, { label: args[2], quiet: !flags.wake })).json();
797
- console.log(`made ${await pathOf(id)}; series owner and ceiling unchanged${series.owner ? `; ${series.owner} starts its runs` : ''}`);
894
+ console.log(`made ${await pathOf(id)}; series owner and credentials unchanged${series.owner ? `; ${series.owner} starts its runs` : ''}`);
798
895
  } else if (cmd === 'new' && args[0] === 'series' && args.length === 3) {
799
896
  await post(`/api/series/${(await find(args[1])).series.id}/promote`, { name: args[2] });
800
897
  console.log(`made the series ${args[1].split('/')[0]}/${args[2]}`);
@@ -813,7 +910,7 @@ else if (cmd === 'comment' && args.length < 2) {
813
910
  if (flags.creds !== undefined || flags.clear) throw new Error('request credentials were removed: use rf series credentials SERIES');
814
911
  const r = await post(`/api/requests/${args[1]}`, { quiet: !flags.wake });
815
912
  const woke = r.headers.get('X-RF-Woke') === '1', { id } = await r.json();
816
- console.log(`${woke ? 'woke' : 'made'} ${await pathOf(id)}; series owner and ceiling unchanged`);
913
+ console.log(`${woke ? 'woke' : 'made'} ${await pathOf(id)}; series owner and credentials unchanged`);
817
914
  }
818
915
  } else if (cmd === 'logins' && !args.length) {
819
916
  const all = await get('/logins');