@basementuniverse/jsonpad-cli 1.3.0 → 1.5.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.
@@ -1,8 +1,8 @@
1
1
  import { Option } from 'commander';
2
2
  import { apiError, apiErrorExitCode, CliError } from '../errors.js';
3
3
  import { canPrompt, confirm, promptSecret, readStdin } from '../input.js';
4
- import { addOutputOptions, formatTimestamp, printRecord, renderDetails, resolveOutputFormat, } from '../output.js';
5
- import { addAllOption, addPagingOptions, addTaggedOption, addTagsOption, nullable, removeUndefined, printPages, request, resolveIdentityId, } from '../resources.js';
4
+ import { addOutputOptions, formatTimestamp, printRecord, printRecords, renderDetails, resolveOutputFormat, } from '../output.js';
5
+ import { addAllOption, addPagingOptions, addTaggedOption, addTagsOption, nullable, removeUndefined, printPages, request, resolveIdentityId, UUID, } from '../resources.js';
6
6
  import { JSONPadError } from '../sdk.js';
7
7
  import { defineEventCommands, defineStatsCommand } from './history.js';
8
8
  const ORDER_FIELDS = [
@@ -14,6 +14,22 @@ const ORDER_FIELDS = [
14
14
  'activated',
15
15
  ];
16
16
  const IDENTITY_ARGUMENT_DESCRIPTION = 'The identity: its id, group/name, or the name of an identity without a group';
17
+ /**
18
+ * The sign-in providers identities can use, for showing a name rather than an
19
+ * id. An unknown provider (one added to the API since this release) is shown
20
+ * as it comes
21
+ */
22
+ const PROVIDER_NAMES = {
23
+ google: 'Google',
24
+ github: 'GitHub',
25
+ apple: 'Apple',
26
+ microsoft: 'Microsoft',
27
+ discord: 'Discord',
28
+ facebook: 'Facebook',
29
+ };
30
+ export function providerLabel(provider) {
31
+ return PROVIDER_NAMES[provider] ?? provider;
32
+ }
17
33
  export function identityLabel(identity) {
18
34
  return identity.group ? `${identity.group}/${identity.name}` : identity.name;
19
35
  }
@@ -26,6 +42,32 @@ function identityOutput(context) {
26
42
  ['Group', identity.group || dim('(none)')],
27
43
  ['Name', identity.name],
28
44
  ['Display name', identity.displayName ?? dim('(none)')],
45
+ ...(identity.email === undefined
46
+ ? []
47
+ : [
48
+ [
49
+ 'Email',
50
+ identity.email
51
+ ? `${identity.email}${identity.emailVerified ? '' : dim(' (not verified)')}`
52
+ : dim('(none)'),
53
+ ],
54
+ ]),
55
+ ...(identity.hasPassword === undefined
56
+ ? []
57
+ : [['Password', identity.hasPassword ? 'Set' : dim('not set')]]),
58
+ ...(identity.sessionCount === undefined
59
+ ? []
60
+ : [['Sessions', String(identity.sessionCount)]]),
61
+ ...(identity.providers?.length
62
+ ? [
63
+ [
64
+ 'Sign-in accounts',
65
+ identity.providers
66
+ .map(account => providerLabel(account.provider))
67
+ .join(', '),
68
+ ],
69
+ ]
70
+ : []),
29
71
  [
30
72
  'Tags',
31
73
  identity.tags?.length ? identity.tags.join(', ') : dim('(none)'),
@@ -74,15 +116,33 @@ async function readPassword(context, label) {
74
116
  }
75
117
  return password;
76
118
  }
119
+ /**
120
+ * Read an identity's current password, which the API needs before it changes
121
+ * a password or an email address
122
+ */
123
+ async function readCurrentPassword(context) {
124
+ const password = context.env.JSONPAD_IDENTITY_CURRENT_PASSWORD ??
125
+ (canPrompt(context)
126
+ ? await promptSecret(context, 'Current password: ')
127
+ : undefined);
128
+ if (!password) {
129
+ throw new CliError(canPrompt(context)
130
+ ? 'The current password is needed'
131
+ : 'The current password is needed. Set JSONPAD_IDENTITY_CURRENT_PASSWORD');
132
+ }
133
+ return password;
134
+ }
77
135
  function addIdentityFieldOptions(command, update) {
78
136
  command
79
137
  .option('--group <group>', 'The group, which separates identities with the same name')
80
138
  .option('--name <name>', 'The name, used to log in')
81
- .option('--display-name <name>', 'The name to show');
139
+ .option('--display-name <name>', 'The name to show')
140
+ .option('--email <email>', 'The email address, which can also be used to log in');
82
141
  addTagsOption(command);
83
142
  if (update) {
84
143
  command
85
144
  .option('--no-display-name', 'Remove the display name')
145
+ .option('--no-email', 'Remove the email address')
86
146
  .option('--password', 'Change the password: asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD');
87
147
  }
88
148
  return command;
@@ -135,6 +195,7 @@ export function defineIdentities(command, context) {
135
195
  group: options.group || undefined,
136
196
  name: options.name,
137
197
  displayName: options.displayName || undefined,
198
+ email: options.email || undefined,
138
199
  tags: options.tags,
139
200
  password,
140
201
  })));
@@ -154,6 +215,7 @@ export function defineIdentities(command, context) {
154
215
  group: options.group,
155
216
  name: options.name,
156
217
  displayName: nullable(options.displayName),
218
+ email: nullable(options.email),
157
219
  tags: options.tags,
158
220
  password,
159
221
  })));
@@ -181,6 +243,8 @@ export function defineIdentities(command, context) {
181
243
  context.error(`Deleted the identity ${context.colours.bold(reference)}`);
182
244
  });
183
245
  defineIdentityModeCommands(command, context);
246
+ defineTokenCommands(command, context);
247
+ defineProviderCommands(command, context);
184
248
  const target = {
185
249
  arguments: [['<identity>', IDENTITY_ARGUMENT_DESCRIPTION]],
186
250
  resolve: async (jsonpad, [reference]) => [
@@ -204,6 +268,13 @@ export function defineIdentities(command, context) {
204
268
  'identity-logged-out',
205
269
  'identity-updated-self',
206
270
  'identity-deleted-self',
271
+ 'identity-sessions-revoked',
272
+ 'identity-password-reset-requested',
273
+ 'identity-password-reset',
274
+ 'identity-email-verification-requested',
275
+ 'identity-email-verified',
276
+ 'identity-provider-linked',
277
+ 'identity-provider-unlinked',
207
278
  ],
208
279
  fetchEvents: (jsonpad, [id], parameters) => jsonpad.fetchIdentityEvents(id, parameters),
209
280
  fetchEvent: (jsonpad, [id], eventId, parameters) => jsonpad.fetchIdentityEvent(id, eventId, parameters),
@@ -234,7 +305,8 @@ function defineIdentityModeCommands(command, context) {
234
305
  .description("Register an identity, as an app would for a new user. Unlike create, this needs the token's register permission. The password is asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD")
235
306
  .option('--group <group>', 'The group')
236
307
  .option('--name <name>', 'The name, used to log in')
237
- .option('--display-name <name>', 'The name to show'))).action(async (options) => {
308
+ .option('--display-name <name>', 'The name to show')
309
+ .option('--email <email>', 'The email address, which can also be used to log in'))).action(async (options) => {
238
310
  const format = resolveOutputFormat(context, options);
239
311
  if (!options.name) {
240
312
  throw new CliError('An identity needs a name: pass --name');
@@ -245,6 +317,7 @@ function defineIdentityModeCommands(command, context) {
245
317
  group: options.group || undefined,
246
318
  name: options.name,
247
319
  displayName: options.displayName || undefined,
320
+ email: options.email || undefined,
248
321
  password,
249
322
  }), NO_IDENTITY));
250
323
  printRecord(context, format, identity, identityOutput(context));
@@ -255,22 +328,29 @@ function defineIdentityModeCommands(command, context) {
255
328
  .description('Log in as an identity, and output its identity token. Set JSONPAD_IDENTITY_TOKEN (and JSONPAD_IDENTITY_GROUP) to it to act as the identity when working with items, e.g. eval "$(jsonpad identities login --name ada -o env)". The password is asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD')
256
329
  .option('--group <group>', "The identity's group")
257
330
  .option('--name <name>', "The identity's name")
331
+ .option('--email <email>', "The identity's email address, instead of a name")
258
332
  .addOption(new Option('-o, --output <format>', 'Output format: table (the default in a terminal), json (the default otherwise), env (export commands for a POSIX shell), or token (just the token)').choices(['table', 'json', 'env', 'token']))
259
333
  .action(async (options) => {
260
- if (!options.name) {
261
- throw new CliError("Pass the identity's name with --name");
334
+ if (!options.name && !options.email) {
335
+ throw new CliError("Pass the identity's name with --name, or its email address with --email");
336
+ }
337
+ if (options.name && options.email) {
338
+ throw new CliError('Pass either --name or --email, not both');
262
339
  }
263
340
  const format = options.output ?? (context.stdout.isTTY ? 'table' : 'json');
341
+ const nameOrEmail = (options.name ?? options.email);
264
342
  const label = options.group
265
- ? `${options.group}/${options.name}`
266
- : options.name;
343
+ ? `${options.group}/${nameOrEmail}`
344
+ : nameOrEmail;
267
345
  const password = await readPassword(context, label);
268
346
  const jsonpad = context.createClient();
269
347
  const [identity, token] = await request(context, async () => {
270
348
  try {
271
349
  return await jsonpad.loginIdentity(removeUndefined({
272
350
  group: options.group || undefined,
273
- name: options.name,
351
+ ...(options.email
352
+ ? { email: options.email }
353
+ : { name: options.name }),
274
354
  password,
275
355
  }), NO_IDENTITY);
276
356
  }
@@ -303,18 +383,21 @@ function defineIdentityModeCommands(command, context) {
303
383
  break;
304
384
  case 'table':
305
385
  context.log(renderIdentityWithToken(context, identity, token));
306
- context.error(context.colours.dim(`To act as ${label}, set JSONPAD_IDENTITY_TOKEN${group ? ' and JSONPAD_IDENTITY_GROUP' : ''}, e.g. with: eval "$(jsonpad identities login ${group ? `--group ${shellQuote(group)} ` : ''}--name ${shellQuote(options.name)} -o env)"`));
386
+ context.error(context.colours.dim(`To act as ${label}, set JSONPAD_IDENTITY_TOKEN${group ? ' and JSONPAD_IDENTITY_GROUP' : ''}, e.g. with: eval "$(jsonpad identities login ${group ? `--group ${shellQuote(group)} ` : ''}${options.email
387
+ ? `--email ${shellQuote(options.email)}`
388
+ : `--name ${shellQuote(options.name)}`} -o env)"`));
307
389
  break;
308
390
  }
309
391
  });
310
392
  command
311
393
  .command('logout')
312
394
  .description('Log out the identity in JSONPAD_IDENTITY_TOKEN, so that its token stops working')
313
- .action(async () => {
395
+ .option('--all', 'Log the identity out everywhere, ending its sessions on every device')
396
+ .action(async (options) => {
314
397
  const jsonpad = context.createClient();
315
398
  requireIdentity(context);
316
- await request(context, () => jsonpad.logoutIdentity());
317
- context.error('Logged out. Unset JSONPAD_IDENTITY_TOKEN and JSONPAD_IDENTITY_GROUP');
399
+ await request(context, () => jsonpad.logoutIdentity(undefined, { all: options.all }));
400
+ context.error(`${options.all ? 'Logged out everywhere' : 'Logged out'}. Unset JSONPAD_IDENTITY_TOKEN and JSONPAD_IDENTITY_GROUP`);
318
401
  });
319
402
  const self = command
320
403
  .command('self')
@@ -334,20 +417,76 @@ function defineIdentityModeCommands(command, context) {
334
417
  .option('--name <name>', 'The name, used to log in')
335
418
  .option('--display-name <name>', 'The name to show')
336
419
  .option('--no-display-name', 'Remove the display name')
337
- .option('--password', 'Change the password: asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD')).action(async (options) => {
420
+ .option('--email <email>', 'The email address, which needs verifying again')
421
+ .option('--no-email', 'Remove the email address')
422
+ .option('--password', 'Change the password: asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD')
423
+ .option('--current-password', "The identity's current password, needed to change its password or email address. Asked for in a terminal, or read from JSONPAD_IDENTITY_CURRENT_PASSWORD")).action(async (options) => {
338
424
  const format = resolveOutputFormat(context, options);
339
425
  const jsonpad = context.createClient();
340
426
  requireIdentity(context);
427
+ // The API needs the current password to change a password or an email
428
+ // address, unless the identity has no password (e.g. it signed in with
429
+ // Google)
430
+ const currentPassword = options.currentPassword
431
+ ? await readCurrentPassword(context)
432
+ : undefined;
341
433
  const password = options.password
342
434
  ? await readPassword(context, 'this identity')
343
435
  : undefined;
344
436
  const identity = await request(context, () => jsonpad.updateSelfIdentity(removeUndefined({
345
437
  name: options.name,
346
438
  displayName: nullable(options.displayName),
439
+ email: nullable(options.email),
347
440
  password,
441
+ currentPassword,
348
442
  })));
349
443
  printRecord(context, format, identity, identityOutput(context));
350
444
  });
445
+ const providers = self
446
+ .command('providers')
447
+ .description('The provider accounts (e.g. Google) the identity in JSONPAD_IDENTITY_TOKEN can sign in with');
448
+ addOutputOptions(providers
449
+ .command('list', { isDefault: true })
450
+ .alias('ls')
451
+ .description('List the accounts the identity can sign in with (the default when no command is given)')).action(async (options) => {
452
+ const format = resolveOutputFormat(context, options);
453
+ const jsonpad = context.createClient();
454
+ requireIdentity(context);
455
+ const accounts = await request(context, () => jsonpad.fetchSelfIdentityProviders());
456
+ printRecords(context, format, accounts, {
457
+ id: account => account.provider,
458
+ columns: [
459
+ {
460
+ header: 'PROVIDER',
461
+ value: account => providerLabel(account.provider),
462
+ },
463
+ { header: 'EMAIL', value: account => account.email ?? '-' },
464
+ { header: 'NAME', value: account => account.name ?? '-' },
465
+ {
466
+ header: 'LAST SIGNED IN',
467
+ value: account => account.lastLoginAt ? formatTimestamp(account.lastLoginAt) : '-',
468
+ },
469
+ ],
470
+ empty: 'This identity has no provider accounts',
471
+ });
472
+ });
473
+ providers
474
+ .command('unlink')
475
+ .alias('rm')
476
+ .summary('Stop the identity signing in with a provider account')
477
+ .description("Stop the identity in JSONPAD_IDENTITY_TOKEN signing in with a provider account. An identity's last way of signing in can't be removed: set a password first, or link another account")
478
+ .argument('<provider>', 'The provider, e.g. google')
479
+ .option('-y, --yes', "Don't ask for confirmation")
480
+ .action(async (provider, options) => {
481
+ const jsonpad = context.createClient();
482
+ requireIdentity(context);
483
+ await confirm(context, {
484
+ question: `Stop signing in with ${providerLabel(provider)}?`,
485
+ yes: options.yes,
486
+ });
487
+ await request(context, () => jsonpad.unlinkSelfIdentityProvider(provider));
488
+ context.error(`Unlinked the ${context.colours.bold(providerLabel(provider))} account`);
489
+ });
351
490
  self
352
491
  .command('delete')
353
492
  .alias('rm')
@@ -366,6 +505,173 @@ function defineIdentityModeCommands(command, context) {
366
505
  context.error('Deleted the identity. Unset JSONPAD_IDENTITY_TOKEN and JSONPAD_IDENTITY_GROUP');
367
506
  });
368
507
  }
508
+ /**
509
+ * How an identity is chosen for a password reset or email verification token:
510
+ * by the same reference as elsewhere, or by email address
511
+ */
512
+ function identityTokenRequest(reference, options) {
513
+ if (reference && options.email) {
514
+ throw new CliError('Pass either an identity or --email, not both');
515
+ }
516
+ if (options.email) {
517
+ return removeUndefined({
518
+ group: options.group || undefined,
519
+ email: options.email,
520
+ });
521
+ }
522
+ if (!reference) {
523
+ throw new CliError('Pass the identity (its id, group/name, or name), or its email address with --email');
524
+ }
525
+ if (UUID.test(reference)) {
526
+ return { identityId: reference };
527
+ }
528
+ // Names can't contain a slash, but groups can
529
+ const slash = reference.lastIndexOf('/');
530
+ return removeUndefined({
531
+ group: slash === -1 ? options.group || undefined : reference.slice(0, slash),
532
+ name: reference.slice(slash + 1),
533
+ });
534
+ }
535
+ /**
536
+ * Print an issued password reset or email verification token
537
+ */
538
+ function printIssuedToken(context, format, issued, noun) {
539
+ const { dim } = context.colours;
540
+ if (issued.delivery === 'webhook') {
541
+ if (format === 'table') {
542
+ context.log(renderDetails([['Delivery', "sent to the identity group's webhook"]]));
543
+ context.error(dim(`The ${noun} was sent to the webhook, so it isn't returned here. The same response is given whether or not an identity matched.`));
544
+ }
545
+ else {
546
+ printRecord(context, format, issued, {
547
+ id: () => '',
548
+ details: () => [],
549
+ data: () => issued.response,
550
+ });
551
+ }
552
+ return;
553
+ }
554
+ if (!issued.token && format === 'table') {
555
+ context.error(`No activated, unlocked identity matched, so no ${noun} was issued`);
556
+ }
557
+ printRecord(context, format, issued, {
558
+ data: () => issued.response,
559
+ id: () => issued.identity?.id ?? '',
560
+ details: () => [
561
+ [
562
+ noun === 'reset token' ? 'Reset token' : 'Verification token',
563
+ issued.token ?? dim('(none)'),
564
+ ],
565
+ [
566
+ 'Expires',
567
+ issued.expiresAt ? formatTimestamp(issued.expiresAt) : dim('(none)'),
568
+ ],
569
+ [
570
+ 'Identity',
571
+ issued.identity
572
+ ? `${identityLabel(issued.identity)} (${issued.identity.id})`
573
+ : dim('(no match)'),
574
+ ],
575
+ ['Email', issued.identity?.email ?? dim('(none)')],
576
+ ],
577
+ });
578
+ }
579
+ /**
580
+ * Password reset and email verification tokens: JSONPad issues them, and your
581
+ * app sends them on
582
+ */
583
+ function defineTokenCommands(command, context) {
584
+ const kinds = [
585
+ {
586
+ name: 'password-reset',
587
+ summary: 'Issue and use password reset tokens',
588
+ noun: 'reset token',
589
+ requestSummary: 'Issue a password reset token for an identity',
590
+ requestDescription: "Issue a single-use password reset token for an identity, to send to whoever owns it. JSONPad never sends email itself. The token is returned unless the identity group delivers tokens to a webhook. This needs the token's reset-password permission",
591
+ confirmSummary: 'Set a new password with a reset token',
592
+ confirmDescription: 'Set a new password for the identity the reset token was issued for, which logs it out everywhere. The password is asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD',
593
+ request: (jsonpad, data) => jsonpad.requestIdentityPasswordReset(data),
594
+ },
595
+ {
596
+ name: 'email-verification',
597
+ summary: 'Issue and use email verification tokens',
598
+ noun: 'verification token',
599
+ requestSummary: 'Issue an email verification token for an identity',
600
+ requestDescription: "Issue a single-use email verification token for an identity, to send to the address being verified. This needs the token's verify-email permission",
601
+ confirmSummary: "Verify an identity's email address with a token",
602
+ confirmDescription: "Mark an identity's email address as verified, using a verification token",
603
+ request: (jsonpad, data) => jsonpad.requestIdentityEmailVerification(data),
604
+ },
605
+ ];
606
+ for (const kind of kinds) {
607
+ const group = command.command(kind.name).description(kind.summary);
608
+ addOutputOptions(group
609
+ .command('request')
610
+ .summary(kind.requestSummary)
611
+ .description(kind.requestDescription)
612
+ .argument('[identity]', IDENTITY_ARGUMENT_DESCRIPTION)
613
+ .option('--group <group>', "The identity's group")
614
+ .option('--email <email>', "The identity's email address, instead of a name")).action(async (reference, options) => {
615
+ const format = resolveOutputFormat(context, options);
616
+ const jsonpad = context.createClient();
617
+ const issued = (await request(context, () => kind.request(jsonpad, identityTokenRequest(reference, options))));
618
+ printIssuedToken(context, format, {
619
+ token: issued.resetToken ?? issued.verificationToken ?? null,
620
+ expiresAt: issued.expiresAt ?? null,
621
+ identity: issued.identity ?? null,
622
+ delivery: issued.delivery,
623
+ response: issued,
624
+ }, kind.noun);
625
+ });
626
+ const confirm = group
627
+ .command('confirm')
628
+ .summary(kind.confirmSummary)
629
+ .description(kind.confirmDescription)
630
+ .argument('<token>', `The ${kind.noun}, which can only be used once`);
631
+ addOutputOptions(confirm).action(async (token, options) => {
632
+ const format = resolveOutputFormat(context, options);
633
+ const jsonpad = context.createClient();
634
+ const identity = await request(context, async () => {
635
+ if (kind.name === 'password-reset') {
636
+ const password = await readPassword(context, 'the identity');
637
+ return jsonpad.confirmIdentityPasswordReset({
638
+ resetToken: token,
639
+ password,
640
+ });
641
+ }
642
+ return jsonpad.confirmIdentityEmailVerification({
643
+ verificationToken: token,
644
+ });
645
+ });
646
+ printRecord(context, format, identity, identityOutput(context));
647
+ if (kind.name === 'password-reset') {
648
+ context.error(context.colours.dim('The identity has been logged out everywhere, and can log in with its new password'));
649
+ }
650
+ });
651
+ }
652
+ }
653
+ /**
654
+ * Signing in with Google, GitHub and the rest
655
+ */
656
+ function defineProviderCommands(command, context) {
657
+ addOutputOptions(command
658
+ .command('providers')
659
+ .summary("List an identity group's sign-in providers")
660
+ .description("List the sign-in providers enabled for an identity group, e.g. to see what an app's sign-in page would show. Set them up in the dashboard")
661
+ .option('--group <group>', 'The identity group')).action(async (options) => {
662
+ const format = resolveOutputFormat(context, options);
663
+ const jsonpad = context.createClient();
664
+ const providers = await request(context, () => jsonpad.fetchIdentityOAuthProviders(options.group || undefined));
665
+ printRecords(context, format, providers, {
666
+ id: provider => provider.provider,
667
+ columns: [
668
+ { header: 'PROVIDER', value: provider => provider.provider },
669
+ { header: 'NAME', value: provider => provider.name },
670
+ ],
671
+ empty: 'No sign-in providers are enabled for this identity group',
672
+ });
673
+ });
674
+ }
369
675
  function renderIdentityWithToken(context, identity, token) {
370
676
  const rows = identityOutput(context).details(identity);
371
677
  return renderDetails([...rows, ['Token', token]]);
@@ -1,5 +1,8 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { CliError } from '../errors.js';
2
- import { canPrompt, confirm, readJsonInput } from '../input.js';
4
+ import { canPrompt, confirm, readJsonInput, readStdin } from '../input.js';
5
+ import { compileRules, readJsonFile, readTextFile, runRuleTests, } from '../rules.js';
3
6
  import { addOutputOptions, formatFlags, formatNumber, formatTimestamp, printRecord, printRecords, resolveOutputFormat, } from '../output.js';
4
7
  import { addBooleanOption, addAllOption, addPagingOptions, addTaggedOption, addTagsOption, nullable, readBody, removeUndefined, printPages, request, } from '../resources.js';
5
8
  import { defineEventCommands, defineStatsCommand } from './history.js';
@@ -43,6 +46,17 @@ export function listDetails(context, list) {
43
46
  ['Tags', list.tags?.length ? list.tags.join(', ') : dim('(none)')],
44
47
  ['Items', formatNumber(list.itemCount ?? 0)],
45
48
  ['Flags', formatFlags(list, [...FLAGS])],
49
+ // Only the account owner and tokens that can update the list see these
50
+ ...(list.rules !== undefined
51
+ ? [
52
+ [
53
+ 'Write rules',
54
+ list.rules
55
+ ? `${list.rules.split('\n').length} lines (jsonpad lists rules get ${list.pathName || list.id})`
56
+ : dim('(none)'),
57
+ ],
58
+ ]
59
+ : []),
46
60
  ];
47
61
  if (list.generative) {
48
62
  rows.push(['Prompt', list.generativePrompt || dim('(none)')]);
@@ -105,6 +119,105 @@ async function listBody(context, options) {
105
119
  ...Object.fromEntries(FLAGS.map(flag => [flag, options[flag]])),
106
120
  });
107
121
  }
122
+ /**
123
+ * jsonpad lists rules: read and write a list's write rules
124
+ */
125
+ function defineListRules(command, context) {
126
+ command.description("Read and write a list's write rules");
127
+ command
128
+ .command('get', { isDefault: true })
129
+ .description("Show a list's write rules")
130
+ .argument('<list>', 'The list (id or path name)')
131
+ .option('--tests', 'Show the rule tests instead of the rules')
132
+ .option('-o, --out <file>', 'Write to a file, not stdout')
133
+ .action(async (listId, options) => {
134
+ const jsonpad = context.createClient();
135
+ const list = await request(context, () => jsonpad.fetchList(listId));
136
+ if (list.rules === undefined) {
137
+ throw new CliError("This token can't see the list's write rules: it needs permission to update the list");
138
+ }
139
+ const text = options.tests
140
+ ? list.rulesTests
141
+ ? `${JSON.stringify(list.rulesTests, null, 2)}\n`
142
+ : ''
143
+ : list.rules
144
+ ? `${list.rules.replace(/\n?$/, '\n')}`
145
+ : '';
146
+ if (!text) {
147
+ context.error(`List ${listId} has no write rule${options.tests ? ' tests' : 's'}`);
148
+ return;
149
+ }
150
+ if (options.out) {
151
+ fs.writeFileSync(path.resolve(context.cwd, options.out), text);
152
+ context.error(`Wrote ${options.out}`);
153
+ return;
154
+ }
155
+ context.stdout.write(text);
156
+ });
157
+ command
158
+ .command('set')
159
+ .description("Set a list's write rules from a file")
160
+ .argument('<list>', 'The list (id or path name)')
161
+ .argument('[file]', 'The rule file, or - for stdin')
162
+ .option('--tests <file>', 'Also set the rule tests from this file')
163
+ .option('--remove', "Remove the list's rules")
164
+ .option('--skip-check', "Don't compile and test the rules here first (the API always checks them)")
165
+ .action(async (listId, file, options) => {
166
+ if (!file && !options.remove && !options.tests) {
167
+ throw new CliError('Give a rule file, --tests or --remove');
168
+ }
169
+ const rules = options.remove
170
+ ? null
171
+ : file
172
+ ? file === '-'
173
+ ? await readStdin(context)
174
+ : readTextFile(context, file, 'the rule file')
175
+ : undefined;
176
+ const tests = options.tests
177
+ ? readJsonFile(context, options.tests, 'the test file')
178
+ : undefined;
179
+ // Checked here first, so a mistake costs no requests
180
+ if (!options.skipCheck && rules) {
181
+ const ruleSet = compileRules(context, rules, file ?? 'the rules');
182
+ if (tests) {
183
+ runRuleTests(context, ruleSet, tests, options.tests);
184
+ }
185
+ }
186
+ const jsonpad = context.createClient();
187
+ const list = await request(context, () => jsonpad.updateList(listId, {
188
+ ...(rules === undefined ? {} : { rules }),
189
+ ...(tests === undefined ? {} : { rulesTests: tests }),
190
+ }));
191
+ context.error(rules === null
192
+ ? `Removed the write rules from ${list.pathName || list.id}`
193
+ : `Saved the write rules on ${list.pathName || list.id}`);
194
+ });
195
+ addOutputOptions(command
196
+ .command('denials')
197
+ .description("The most recent writes the list's rules refused, newest first")
198
+ .argument('<list>', 'The list (id or path name)')).action(async (listId, options) => {
199
+ const format = resolveOutputFormat(context, options);
200
+ const jsonpad = context.createClient();
201
+ const denials = await request(context, () => jsonpad.fetchListRuleDenials(listId));
202
+ printRecords(context, format, denials, {
203
+ columns: [
204
+ { header: 'When', value: denial => formatTimestamp(denial.createdAt) },
205
+ { header: 'Operation', value: denial => denial.operation },
206
+ {
207
+ header: 'Refused by',
208
+ value: denial => denial.stage === 'allow'
209
+ ? 'no allow statement'
210
+ : `require${denial.statementLabel ? ` "${denial.statementLabel}"` : ''} on line ${denial.statementLine}`,
211
+ },
212
+ { header: 'Identity', value: denial => denial.identityId ?? '' },
213
+ { header: 'Item', value: denial => denial.itemId ?? '' },
214
+ ],
215
+ empty: "The list's rules haven't refused any writes",
216
+ id: denial => denial.id,
217
+ });
218
+ });
219
+ return command;
220
+ }
108
221
  export function defineLists(command, context) {
109
222
  command.description('Create, view, change and delete lists');
110
223
  const list = command
@@ -218,6 +331,7 @@ export function defineLists(command, context) {
218
331
  empty: 'Nothing found',
219
332
  });
220
333
  });
334
+ defineListRules(command.command('rules'), context);
221
335
  const target = {
222
336
  arguments: [['<list>', 'The list (id or path name)']],
223
337
  };