@coffre/ui 0.5.1 → 0.6.1

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 (120) hide show
  1. package/dist/chunks/{affordances-Bqdevf7w.js → affordances-Dtyha68j.js} +11 -3
  2. package/dist/chunks/affordances-Dtyha68j.js.map +1 -0
  3. package/dist/chunks/{audit-sentence-Cm5nby5k.js → audit-sentence-CUUMshIp.js} +22 -6
  4. package/dist/chunks/audit-sentence-CUUMshIp.js.map +1 -0
  5. package/dist/chunks/{connected-apps-DTNS7YmY.js → connected-apps-DTpatjge.js} +5 -5
  6. package/dist/chunks/{connected-apps-DTNS7YmY.js.map → connected-apps-DTpatjge.js.map} +1 -1
  7. package/dist/chunks/{delete-place-CIaOq0mt.js → delete-place-SOOYVt6A.js} +5 -5
  8. package/dist/chunks/{delete-place-CIaOq0mt.js.map → delete-place-SOOYVt6A.js.map} +1 -1
  9. package/dist/chunks/{directory-DSVt5Tya.js → directory-DrtdKny2.js} +60 -37
  10. package/dist/chunks/directory-DrtdKny2.js.map +1 -0
  11. package/dist/chunks/{folders-CoGK9oqg.js → folders-hR2Lnk0k.js} +3 -3
  12. package/dist/chunks/{folders-CoGK9oqg.js.map → folders-hR2Lnk0k.js.map} +1 -1
  13. package/dist/chunks/{grants-CRU7yZhL.js → grants-DDBui9YD.js} +6 -6
  14. package/dist/chunks/{grants-CRU7yZhL.js.map → grants-DDBui9YD.js.map} +1 -1
  15. package/dist/chunks/{offboarding-DVBSiJRZ.js → offboarding-C7ECW5o0.js} +5 -5
  16. package/dist/chunks/{offboarding-DVBSiJRZ.js.map → offboarding-C7ECW5o0.js.map} +1 -1
  17. package/dist/chunks/{page-DvsgZ2Hd.js → page-JTORvh-N.js} +7 -3
  18. package/dist/chunks/page-JTORvh-N.js.map +1 -0
  19. package/dist/chunks/{principal-BIN-xwZw.js → principal-DFBswTBr.js} +2 -2
  20. package/dist/chunks/{principal-BIN-xwZw.js.map → principal-DFBswTBr.js.map} +1 -1
  21. package/dist/chunks/{principal-page-BEBr_zW7.js → principal-page-CB6dAABC.js} +17 -19
  22. package/dist/chunks/principal-page-CB6dAABC.js.map +1 -0
  23. package/dist/chunks/{project-page-B3TZ5_ig.js → project-page-BHNUvr2L.js} +3 -3
  24. package/dist/chunks/{project-page-B3TZ5_ig.js.map → project-page-BHNUvr2L.js.map} +1 -1
  25. package/dist/chunks/{queries-DE5nK2y4.js → queries-DgQo3mC-.js} +27 -12
  26. package/dist/chunks/queries-DgQo3mC-.js.map +1 -0
  27. package/dist/chunks/{references-uv4Mli9z.js → references-BQc35Q9g.js} +5 -5
  28. package/dist/chunks/{references-uv4Mli9z.js.map → references-BQc35Q9g.js.map} +1 -1
  29. package/dist/chunks/{role-field-DWhkRY6n.js → role-field-BfWRCqzl.js} +14 -7
  30. package/dist/chunks/role-field-BfWRCqzl.js.map +1 -0
  31. package/dist/chunks/{row-state-DOPUsjQK.js → row-state-Zf3kZVhd.js} +13 -5
  32. package/dist/chunks/row-state-Zf3kZVhd.js.map +1 -0
  33. package/dist/chunks/{signin-errors--ykMFuqN.js → signin-errors-TlQmQe0t.js} +2 -2
  34. package/dist/chunks/signin-errors-TlQmQe0t.js.map +1 -0
  35. package/dist/chunks/{theme-DJuz-xLM.js → theme-B6-V9JvY.js} +3 -3
  36. package/dist/chunks/{theme-DJuz-xLM.js.map → theme-B6-V9JvY.js.map} +1 -1
  37. package/dist/chunks/{ui-DJje3gST.js → ui-Br-dNUTc.js} +2 -2
  38. package/dist/chunks/{ui-DJje3gST.js.map → ui-Br-dNUTc.js.map} +1 -1
  39. package/dist/chunks/{use-action-BRgvbUWt.js → use-action-DthL5hL8.js} +3 -3
  40. package/dist/chunks/{use-action-BRgvbUWt.js.map → use-action-DthL5hL8.js.map} +1 -1
  41. package/dist/chunks/{use-change-BJ3dCFHb.js → use-change-By4cG8bT.js} +31 -19
  42. package/dist/chunks/use-change-By4cG8bT.js.map +1 -0
  43. package/dist/chunks/{use-shell-BO4ZTr1y.js → use-shell-D6kjSPls.js} +3 -3
  44. package/dist/chunks/{use-shell-BO4ZTr1y.js.map → use-shell-D6kjSPls.js.map} +1 -1
  45. package/dist/index.d.ts +6 -7
  46. package/dist/index.js +8 -9
  47. package/dist/index.js.map +1 -1
  48. package/dist/pages/account.js +12 -13
  49. package/dist/pages/account.js.map +1 -1
  50. package/dist/pages/approval.js +2 -2
  51. package/dist/pages/audit.js +5 -5
  52. package/dist/pages/audit.js.map +1 -1
  53. package/dist/pages/device-login.js +2 -2
  54. package/dist/pages/environment.js +837 -155
  55. package/dist/pages/environment.js.map +1 -1
  56. package/dist/pages/login.js +4 -4
  57. package/dist/pages/oauth-authorize.js +2 -2
  58. package/dist/pages/project-access.js +160 -80
  59. package/dist/pages/project-access.js.map +1 -1
  60. package/dist/pages/project-environments.js +10 -10
  61. package/dist/pages/project-settings.js +8 -8
  62. package/dist/pages/project.js +3 -3
  63. package/dist/pages/projects.js +10 -10
  64. package/dist/pages/projects.js.map +1 -1
  65. package/dist/pages/service-account.js +537 -109
  66. package/dist/pages/service-account.js.map +1 -1
  67. package/dist/pages/service-accounts.js +5 -5
  68. package/dist/pages/settings.js +8 -18
  69. package/dist/pages/settings.js.map +1 -1
  70. package/dist/pages/unregistered.js +3 -3
  71. package/dist/pages/unregistered.js.map +1 -1
  72. package/dist/pages/user.js +6 -6
  73. package/dist/pages/users.js +5 -5
  74. package/package.json +3 -3
  75. package/src/components/affordances.ts +13 -1
  76. package/src/components/directory.tsx +50 -36
  77. package/src/components/generate-value.tsx +362 -0
  78. package/src/components/github-picker.tsx +83 -0
  79. package/src/components/icons.tsx +4 -0
  80. package/src/components/masked.tsx +60 -0
  81. package/src/components/missing.tsx +3 -3
  82. package/src/components/multi-combobox.tsx +94 -0
  83. package/src/components/principal-page.tsx +8 -12
  84. package/src/components/principal-picker.tsx +68 -18
  85. package/src/components/role-field.tsx +7 -5
  86. package/src/components/row-state.tsx +7 -3
  87. package/src/components/shell.tsx +0 -1
  88. package/src/components/trusted-workloads.tsx +157 -62
  89. package/src/lib/audit-sentences.ts +25 -3
  90. package/src/lib/bindings.ts +125 -14
  91. package/src/lib/capabilities.ts +15 -9
  92. package/src/lib/changes.ts +15 -9
  93. package/src/lib/coffre.ts +2 -0
  94. package/src/lib/generate.ts +160 -0
  95. package/src/lib/queries.ts +19 -5
  96. package/src/lib/secret-edit-batch.ts +38 -5
  97. package/src/lib/secret-order.ts +23 -0
  98. package/src/lib/shortcuts.ts +9 -0
  99. package/src/lib/signin-errors.ts +1 -1
  100. package/src/lib/use-github-lookup.ts +70 -0
  101. package/src/pages/account.tsx +1 -2
  102. package/src/pages/audit.tsx +1 -1
  103. package/src/pages/environment.tsx +241 -119
  104. package/src/pages/project-access.tsx +19 -8
  105. package/src/pages/projects.tsx +3 -3
  106. package/src/pages/settings.tsx +0 -10
  107. package/src/pages/unregistered.tsx +1 -1
  108. package/src/parity.ts +3 -1
  109. package/src/shared/models.ts +2 -2
  110. package/src/styles/globals.css +303 -19
  111. package/dist/chunks/affordances-Bqdevf7w.js.map +0 -1
  112. package/dist/chunks/audit-sentence-Cm5nby5k.js.map +0 -1
  113. package/dist/chunks/directory-DSVt5Tya.js.map +0 -1
  114. package/dist/chunks/page-DvsgZ2Hd.js.map +0 -1
  115. package/dist/chunks/principal-page-BEBr_zW7.js.map +0 -1
  116. package/dist/chunks/queries-DE5nK2y4.js.map +0 -1
  117. package/dist/chunks/role-field-DWhkRY6n.js.map +0 -1
  118. package/dist/chunks/row-state-DOPUsjQK.js.map +0 -1
  119. package/dist/chunks/signin-errors--ykMFuqN.js.map +0 -1
  120. package/dist/chunks/use-change-BJ3dCFHb.js.map +0 -1
@@ -1,10 +1,10 @@
1
- import { s as memberRef, u as useCoffre } from "../chunks/page-DvsgZ2Hd.js";
2
- import { g as queries } from "../chunks/queries-DE5nK2y4.js";
3
- import { t as useShell } from "../chunks/use-shell-BO4ZTr1y.js";
4
- import { d as disconnectMemberApp } from "../chunks/use-change-BJ3dCFHb.js";
5
- import { t as ConnectedAppsCard } from "../chunks/connected-apps-DTNS7YmY.js";
1
+ import { s as memberRef, u as useCoffre } from "../chunks/page-JTORvh-N.js";
2
+ import { g as queries } from "../chunks/queries-DgQo3mC-.js";
3
+ import { t as useShell } from "../chunks/use-shell-D6kjSPls.js";
4
+ import { d as disconnectMemberApp } from "../chunks/use-change-By4cG8bT.js";
5
+ import { t as ConnectedAppsCard } from "../chunks/connected-apps-DTpatjge.js";
6
6
  import { t as pageRoute } from "../chunks/page-route-Drfw7lmn.js";
7
- import { n as PrincipalLayout, r as ActionsLog, t as PrincipalAccess } from "../chunks/principal-page-BEBr_zW7.js";
7
+ import { n as PrincipalLayout, r as ActionsLog, t as PrincipalAccess } from "../chunks/principal-page-CB6dAABC.js";
8
8
  import { jsx } from "react/jsx-runtime";
9
9
  import { useSuspenseQuery } from "@tanstack/react-query";
10
10
  //#region src/pages/user.tsx
@@ -1,8 +1,8 @@
1
- import { i as PageHeader, n as ClosedDoor, rt as Users, u as useCoffre } from "../chunks/page-DvsgZ2Hd.js";
2
- import { g as queries } from "../chunks/queries-DE5nK2y4.js";
3
- import { t as useShell } from "../chunks/use-shell-BO4ZTr1y.js";
4
- import { t as DirectoryTable } from "../chunks/directory-DSVt5Tya.js";
5
- import { n as RemovedList } from "../chunks/offboarding-DVBSiJRZ.js";
1
+ import { i as PageHeader, n as ClosedDoor, ot as Users, u as useCoffre } from "../chunks/page-JTORvh-N.js";
2
+ import { g as queries } from "../chunks/queries-DgQo3mC-.js";
3
+ import { t as useShell } from "../chunks/use-shell-D6kjSPls.js";
4
+ import { t as DirectoryTable } from "../chunks/directory-DrtdKny2.js";
5
+ import { n as RemovedList } from "../chunks/offboarding-C7ECW5o0.js";
6
6
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
7
  import { useSuspenseQuery } from "@tanstack/react-query";
8
8
  //#region src/pages/users.tsx
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/ui",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "description": "coffre's pages, for a deployment's own TanStack Start app: its router, and a Vite plugin for its build.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -44,8 +44,8 @@
44
44
  "@tanstack/router-core": "1.171.15",
45
45
  "lucide-react": "1.47.0",
46
46
  "sonner": "2.0.7",
47
- "@coffre/client": "0.5.1",
48
- "@coffre/core": "0.5.1"
47
+ "@coffre/client": "0.6.1",
48
+ "@coffre/core": "0.6.1"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@tanstack/react-query": "5.103.1",
@@ -41,7 +41,7 @@ export function administrationEntries<T>(
41
41
  }
42
42
 
43
43
  /** Project creation exists before a grantable resource, so it follows the instance role and its scope (`makesProjects`). */
44
- export function RootAdminOnly({
44
+ export function MakesProjectsOnly({
45
45
  capabilities,
46
46
  children,
47
47
  }: {
@@ -88,3 +88,15 @@ export function SecretReadOnly({
88
88
  }): ReactNode {
89
89
  return canReveal ? children : null;
90
90
  }
91
+
92
+ /**
93
+ * Whether an Owner's tag greys out with "Set by deployment": the deployment names
94
+ * this Owner, and the viewer is someone who could otherwise change Owners. Anyone
95
+ * else sees the plain Owner tag, as nothing is theirs to change.
96
+ */
97
+ export function setByDeployment(
98
+ principal: { instanceRole: string; declared?: boolean },
99
+ capabilities: Pick<UiCapabilities, 'ownsInstance'>,
100
+ ): boolean {
101
+ return principal.declared === true && principal.instanceRole === 'owner' && capabilities.ownsInstance;
102
+ }
@@ -9,6 +9,7 @@ import { queries, waysFor } from '../lib/queries';
9
9
  import { useShell } from '../lib/use-shell';
10
10
  import { useChange, useChangeStatus } from '../lib/use-change';
11
11
  import type { DirectoryPrincipal } from '../shared/models';
12
+ import { setByDeployment } from './affordances';
12
13
  import { RowFailure, RowPending, rowClass } from './row-state';
13
14
  import { ConfirmDialog, EmptyState, MenuPopup, Modal, Spinner, Timestamp, Toggletip } from './ui';
14
15
  import { PrincipalLink } from './principal';
@@ -29,17 +30,11 @@ type PrincipalType = DirectoryPrincipal['principalType'];
29
30
  export const memberOf = (principal: Pick<DirectoryPrincipal, 'principalType' | 'principalId'>) =>
30
31
  memberRef(principal.principalType, principal.principalId);
31
32
 
32
- export const ROLE_LABEL: Record<DirectoryPrincipal['instanceRole'], string> = {
33
- 'root-admin': 'Root admin',
34
- ...Object.fromEntries(Object.entries(INSTANCE_ROLES).map(([role, { name }]) => [role, name])),
35
- } as Record<DirectoryPrincipal['instanceRole'], string>;
36
-
37
33
  /** A new person's role: a Member, everywhere. */
38
34
  const MEMBER: RoleVars = { role: 'member', scope: EVERYWHERE };
39
35
 
40
36
  /** The role a principal holds, as the role field edits it. */
41
- const roleOf = (principal: DirectoryPrincipal): RoleVars =>
42
- principal.instanceRole === 'root-admin' ? MEMBER : { role: principal.instanceRole, scope: principal.scope ?? EVERYWHERE };
37
+ const roleOf = (principal: DirectoryPrincipal): RoleVars => ({ role: principal.instanceRole, scope: principal.scope ?? EVERYWHERE });
43
38
 
44
39
  /** What each kind of principal is called in the interface. */
45
40
  export const KIND: Record<PrincipalType, string> = {
@@ -96,7 +91,7 @@ export function DirectoryTable({
96
91
  <th className="col-role">
97
92
  <span className="th">
98
93
  <ShieldCheck size={14} />
99
- Instance role
94
+ Role
100
95
  </span>
101
96
  </th>
102
97
  ) : (
@@ -144,7 +139,7 @@ export function DirectoryTable({
144
139
  />
145
140
  </td>
146
141
  {users ? (
147
- <td className="col-role" data-label="Instance role">
142
+ <td className="col-role" data-label="Role">
148
143
  <InstanceRole principal={principal} />
149
144
  </td>
150
145
  ) : (
@@ -279,10 +274,10 @@ function ServiceCells({ principal }: { principal: DirectoryPrincipal }) {
279
274
 
280
275
  /**
281
276
  * A user's instance role. Service accounts have none worth showing: every one is a
282
- * plain member. A root admin's role comes from the deployment, so its tag says
283
- * so on hover or tap instead of offering a menu that could not work.
277
+ * plain member.
284
278
  */
285
279
  export function InstanceRole({ principal }: { principal: DirectoryPrincipal }) {
280
+ const { capabilities } = useShell();
286
281
  if (principal.tampered === true) {
287
282
  return (
288
283
  <Toggletip
@@ -300,27 +295,18 @@ export function InstanceRole({ principal }: { principal: DirectoryPrincipal }) {
300
295
  </Toggletip>
301
296
  );
302
297
  }
303
- if (principal.isRootAdmin) {
304
- return (
305
- <Toggletip
306
- label={
307
- <>
308
- Set by <code>rootAdmins</code> in the vault's configuration, not here.
309
- </>
310
- }
311
- >
312
- <button type="button" className="tag tag-violet tag-button">
313
- <Lock size={11} />
314
- Root admin
315
- </button>
316
- </Toggletip>
317
- );
318
- }
298
+ const name = INSTANCE_ROLES[principal.instanceRole].name;
319
299
  return (
320
300
  <>
321
- <span className={`tag${principal.instanceRole === 'member' ? '' : ' tag-violet'}`}>
322
- {ROLE_LABEL[principal.instanceRole]}
323
- </span>
301
+ {setByDeployment(principal, capabilities) ? (
302
+ <Toggletip label="Set by deployment">
303
+ <button type="button" className="tag tag-button" aria-label={`${name}, set by deployment`}>
304
+ {name}
305
+ </button>
306
+ </Toggletip>
307
+ ) : (
308
+ <span className={`tag${principal.instanceRole === 'member' ? '' : ' tag-violet'}`}>{name}</span>
309
+ )}
324
310
  {principal.instanceRole !== 'member' && principal.scope !== null && !unscoped(principal.scope) && (
325
311
  <span className="role-scope">{scopeInWords(principal.scope)}</span>
326
312
  )}
@@ -330,8 +316,10 @@ export function InstanceRole({ principal }: { principal: DirectoryPrincipal }) {
330
316
 
331
317
  /**
332
318
  * Change role and Remove, behind one menu, for those who run the instance;
333
- * Remove, for a service account you manage. Root admins get none: the
334
- * deployment's configuration owns them. Nobody changes their own role.
319
+ * Remove, for a service account you manage. Nobody changes their own role
320
+ * but an Owner of the whole instance, who alone changes or removes an
321
+ * Owner: to anyone else, an Owner's row says so instead. Nobody changes or
322
+ * removes an Owner the deployment names: their row says where they are named.
335
323
  */
336
324
  export function PrincipalActions({
337
325
  principal,
@@ -354,7 +342,33 @@ export function PrincipalActions({
354
342
 
355
343
  const self = me?.type === principal.principalType && me.id === principal.principalId;
356
344
  const yours = principal.principalType === 'service' && principal.managed === true;
357
- if (principal.isRootAdmin || !(capabilities.runsInstance || yours)) return null;
345
+ if (!(capabilities.runsInstance || yours)) return null;
346
+ if (principal.declared === true) {
347
+ return (
348
+ <Toggletip
349
+ label={
350
+ <>
351
+ The deployment names them an Owner: <span className="mono">owners</span> in the vault's configuration. To
352
+ change or remove them, take them off that list and deploy.
353
+ </>
354
+ }
355
+ align="end"
356
+ >
357
+ <button type="button" className={trigger} aria-label={`Why ${principal.principalId} can't be changed`}>
358
+ <Lock size={14} />
359
+ </button>
360
+ </Toggletip>
361
+ );
362
+ }
363
+ if (principal.instanceRole === 'owner' && !capabilities.ownsInstance) {
364
+ return (
365
+ <Toggletip label="Only an Owner of the whole instance changes or removes an Owner." align="end">
366
+ <button type="button" className={trigger} aria-label={`Why ${principal.principalId} can't be changed`}>
367
+ <Lock size={14} />
368
+ </button>
369
+ </Toggletip>
370
+ );
371
+ }
358
372
 
359
373
  return (
360
374
  <>
@@ -367,7 +381,7 @@ export function PrincipalActions({
367
381
  {pending ? <Spinner size={13} /> : <MoreHorizontal size={16} />}
368
382
  </Menu.Trigger>
369
383
  <MenuPopup align="end">
370
- {principal.principalType === 'user' && !self && capabilities.runsInstance && (
384
+ {principal.principalType === 'user' && (!self || capabilities.ownsInstance) && capabilities.runsInstance && (
371
385
  <>
372
386
  <Menu.Item
373
387
  className="menu-item"
@@ -518,7 +532,7 @@ export function AddPrincipal({ principalType }: { principalType: PrincipalType }
518
532
  title={`Add a ${kind}`}
519
533
  description={
520
534
  principalType === 'user'
521
- ? 'Their instance role reaches every project in its scope. Grant more afterwards, from their page or a project\'s.'
535
+ ? undefined
522
536
  : 'This gives the service account no project access. Grant it afterwards, from its page or a project\'s.'
523
537
  }
524
538
  >
@@ -533,7 +547,7 @@ export function AddPrincipal({ principalType }: { principalType: PrincipalType }
533
547
  >
534
548
  <label className="field">
535
549
  <span className="label">
536
- {principalType === 'user' ? 'Cloudflare Access email' : 'Service account name'}
550
+ {principalType === 'user' ? 'Email' : 'Service account name'}
537
551
  </span>
538
552
  <input
539
553
  className="input input-mono"
@@ -0,0 +1,362 @@
1
+ import { useEffect, useId, useState } from 'react';
2
+ import {
3
+ DEFAULT_RECIPE,
4
+ ENCODINGS,
5
+ encodedLength,
6
+ generate,
7
+ MAX_BYTES,
8
+ MIN_BYTES,
9
+ PAIRS,
10
+ pairNameProblem,
11
+ publicKeyName,
12
+ type AesSize,
13
+ type Encoding,
14
+ type Generated,
15
+ type Recipe,
16
+ } from '../lib/generate';
17
+ import type { Companion } from '../lib/secret-edit-batch';
18
+ import { secretKeyProblem } from '../lib/validation';
19
+ import { Eye, EyeOff, Shuffle } from './icons';
20
+ import { MaskedInput } from './masked';
21
+ import { ErrorLine, Modal } from './ui';
22
+
23
+ /**
24
+ * What Use hands the row: its value, its name as the dialog left it (only a
25
+ * new row's can change), and for a key pair the public key it saves with it.
26
+ */
27
+ export type GeneratedUse = { value: string; name: string; companion?: Companion };
28
+
29
+ type Kind = Recipe['kind'];
30
+
31
+ const KINDS: { id: Kind; name: string }[] = [
32
+ { id: 'random', name: 'Random value' },
33
+ { id: 'aes', name: 'AES-GCM key' },
34
+ { id: 'pair', name: 'Key pair' },
35
+ ];
36
+
37
+ /**
38
+ * Make a value for a secret's field, in the browser: Use fills the field, as
39
+ * typing would, and the row saves it with the rest.
40
+ *
41
+ * The dialog's content unmounts as it closes, so each opening draws a new
42
+ * value and nothing generated stays in memory behind a cancel.
43
+ */
44
+ export function GenerateValue({
45
+ open,
46
+ onOpenChange,
47
+ name,
48
+ renamable,
49
+ companion,
50
+ onUse,
51
+ }: {
52
+ open: boolean;
53
+ onOpenChange: (open: boolean) => void;
54
+ /** The row's name, which a key pair's private key keeps. */
55
+ name: string;
56
+ /** A new row's name can be set here; a saved secret's is renamed in its row. */
57
+ renamable: boolean;
58
+ /** The public key of a pair generated here before, which a new pair replaces. */
59
+ companion: Companion | undefined;
60
+ onUse: (use: GeneratedUse) => void;
61
+ }) {
62
+ return (
63
+ <Modal open={open} onOpenChange={onOpenChange} title="Generate a value" description="Made in this browser. It is sent only when you save the row.">
64
+ <GenerateForm
65
+ name={name}
66
+ renamable={renamable}
67
+ publicName={companion?.key}
68
+ onCancel={() => onOpenChange(false)}
69
+ onUse={(use) => {
70
+ onUse(use);
71
+ onOpenChange(false);
72
+ }}
73
+ />
74
+ </Modal>
75
+ );
76
+ }
77
+
78
+ function GenerateForm({
79
+ name,
80
+ renamable,
81
+ publicName: pendingPublicName,
82
+ onCancel,
83
+ onUse,
84
+ }: {
85
+ name: string;
86
+ renamable: boolean;
87
+ publicName?: string;
88
+ onCancel: () => void;
89
+ onUse: (use: GeneratedUse) => void;
90
+ }) {
91
+ const id = useId();
92
+ // Each kind keeps its own choices, so trying another and coming back finds them as left.
93
+ // A row that already holds a generated pair opens on Key pair, to make another.
94
+ const [kind, setKind] = useState<Kind>(pendingPublicName === undefined ? DEFAULT_RECIPE.kind : 'pair');
95
+ const [encoding, setEncoding] = useState<Encoding>('base62');
96
+ const [bytes, setBytes] = useState(32);
97
+ // What the number field shows while a length is being typed, "" or "3" on the way to "300".
98
+ const [bytesText, setBytesText] = useState('32');
99
+ const [size, setSize] = useState<AesSize>(256);
100
+ const [pair, setPair] = useState(0);
101
+ const [round, setRound] = useState(0);
102
+ const [generated, setGenerated] = useState<Generated | null>(null);
103
+ const [error, setError] = useState<string | null>(null);
104
+ const [privateName, setPrivateName] = useState(name);
105
+ // Follows the private key's name until it is typed in, or the row it replaces names it.
106
+ const [publicName, setPublicName] = useState<string | null>(pendingPublicName ?? null);
107
+
108
+ const recipe: Recipe =
109
+ kind === 'random'
110
+ ? { kind, encoding, bytes }
111
+ : kind === 'aes'
112
+ ? { kind, size }
113
+ : { kind, ...PAIRS[pair]! };
114
+ const recipeKey = JSON.stringify(recipe);
115
+
116
+ useEffect(() => {
117
+ let current = true;
118
+ setGenerated(null);
119
+ setError(null);
120
+ generate(recipe).then(
121
+ (made) => current && setGenerated(made),
122
+ (failure: unknown) =>
123
+ current && setError(failure instanceof Error ? failure.message : 'The browser made no value.'),
124
+ );
125
+ return () => {
126
+ current = false;
127
+ };
128
+ // The recipe is a new object each render; its content is what counts.
129
+ }, [recipeKey, round]);
130
+
131
+ const publicKey = publicName ?? publicKeyName(privateName);
132
+ const nameProblem = kind === 'pair' ? pairNameProblem(privateName, publicKey) : null;
133
+ const ready = generated !== null && nameProblem === null;
134
+
135
+ function use() {
136
+ if (!ready) return;
137
+ onUse(
138
+ kind === 'pair' && generated.publicKey !== undefined
139
+ ? {
140
+ value: generated.value,
141
+ name: privateName.trim(),
142
+ companion: { key: publicKey.trim(), value: generated.publicKey },
143
+ }
144
+ : { value: generated.value, name },
145
+ );
146
+ }
147
+
148
+ return (
149
+ <form
150
+ className="form generate"
151
+ onSubmit={(event) => {
152
+ event.preventDefault();
153
+ use();
154
+ }}
155
+ >
156
+ <div className="form-row">
157
+ <label className="field">
158
+ <span className="label">Type</span>
159
+ <select className="select" value={kind} onChange={(event) => setKind(event.target.value as Kind)}>
160
+ {KINDS.map((each) => (
161
+ <option key={each.id} value={each.id}>
162
+ {each.name}
163
+ </option>
164
+ ))}
165
+ </select>
166
+ </label>
167
+ {kind === 'random' ? (
168
+ <label className="field">
169
+ <span className="label">Characters</span>
170
+ <select
171
+ className="select"
172
+ value={encoding}
173
+ onChange={(event) => setEncoding(event.target.value as Encoding)}
174
+ >
175
+ {ENCODINGS.map((each) => (
176
+ <option key={each.id} value={each.id}>
177
+ {each.name}
178
+ </option>
179
+ ))}
180
+ </select>
181
+ </label>
182
+ ) : kind === 'aes' ? (
183
+ <label className="field">
184
+ <span className="label">Size</span>
185
+ <select
186
+ className="select"
187
+ value={size}
188
+ onChange={(event) => setSize(Number(event.target.value) as AesSize)}
189
+ >
190
+ <option value={256}>256-bit</option>
191
+ <option value={128}>128-bit</option>
192
+ </select>
193
+ </label>
194
+ ) : (
195
+ <label className="field">
196
+ <span className="label">Algorithm</span>
197
+ <select className="select" value={pair} onChange={(event) => setPair(Number(event.target.value))}>
198
+ {PAIRS.map((each, index) => (
199
+ <option key={index} value={index}>
200
+ {each.algorithm}, {each.curve}
201
+ </option>
202
+ ))}
203
+ </select>
204
+ </label>
205
+ )}
206
+ </div>
207
+
208
+ {kind === 'random' && (
209
+ <div className="field">
210
+ <label className="label" htmlFor={`${id}-bytes`}>
211
+ Length
212
+ </label>
213
+ <div className="generate-length">
214
+ <input
215
+ className="range"
216
+ type="range"
217
+ aria-label="Length in bytes"
218
+ aria-valuetext={`${bytes} bytes`}
219
+ min={MIN_BYTES}
220
+ max={MAX_BYTES}
221
+ value={bytes}
222
+ onChange={(event) => {
223
+ setBytes(Number(event.target.value));
224
+ setBytesText(event.target.value);
225
+ }}
226
+ />
227
+ <input
228
+ id={`${id}-bytes`}
229
+ className="input generate-bytes"
230
+ type="number"
231
+ inputMode="numeric"
232
+ min={MIN_BYTES}
233
+ max={MAX_BYTES}
234
+ value={bytesText}
235
+ aria-describedby={`${id}-entropy`}
236
+ onChange={(event) => {
237
+ setBytesText(event.target.value);
238
+ const typed = Number(event.target.value);
239
+ if (Number.isInteger(typed) && typed >= MIN_BYTES && typed <= MAX_BYTES) setBytes(typed);
240
+ }}
241
+ onBlur={() => setBytesText(String(bytes))}
242
+ />
243
+ <span className="generate-unit">bytes</span>
244
+ </div>
245
+ <p className="hint" id={`${id}-entropy`}>
246
+ {encodedLength(encoding, bytes)} characters{encoding === 'base62' ? ', A–Z, a–z and 0–9' : ''}, {bytes * 8} bits of entropy.
247
+ </p>
248
+ </div>
249
+ )}
250
+
251
+ {kind === 'pair' ? (
252
+ <>
253
+ <NamedValue
254
+ label="Private key"
255
+ format="PKCS #8, base64"
256
+ name={privateName}
257
+ onName={renamable ? setPrivateName : undefined}
258
+ value={generated?.value ?? null}
259
+ describedBy={`${id}-names`}
260
+ />
261
+ <NamedValue
262
+ label="Public key"
263
+ format="SPKI, base64"
264
+ name={publicKey}
265
+ onName={setPublicName}
266
+ value={generated?.publicKey ?? null}
267
+ describedBy={`${id}-names`}
268
+ />
269
+ <p className="hint" id={`${id}-names`}>
270
+ {nameProblem ?? 'The public key is saved with this row, as a secret of its own.'}
271
+ </p>
272
+ </>
273
+ ) : (
274
+ <NamedValue
275
+ label="Value"
276
+ format={kind === 'aes' ? `the raw key, base64, ${size === 256 ? 44 : 24} characters` : undefined}
277
+ value={generated?.value ?? null}
278
+ />
279
+ )}
280
+
281
+ <ErrorLine error={error} />
282
+
283
+ <div className="dialog-actions generate-actions">
284
+ <button className="btn btn-quiet" type="button" onClick={() => setRound((count) => count + 1)}>
285
+ <Shuffle size={14} />
286
+ Generate again
287
+ </button>
288
+ <button className="btn" type="button" onClick={onCancel}>
289
+ Cancel
290
+ </button>
291
+ <button className="btn btn-primary" type="submit" disabled={!ready}>
292
+ {kind === 'pair' ? 'Use keys' : 'Use value'}
293
+ </button>
294
+ </div>
295
+ </form>
296
+ );
297
+ }
298
+
299
+ /** A generated value, masked until shown, and for a key pair the name it is saved under. */
300
+ function NamedValue({
301
+ label,
302
+ format,
303
+ name,
304
+ onName,
305
+ value,
306
+ describedBy,
307
+ }: {
308
+ label: string;
309
+ format?: string;
310
+ /** Only a key pair's two values carry a name. */
311
+ name?: string;
312
+ /** Without it, the name is shown but fixed: the row's own. */
313
+ onName?: (name: string) => void;
314
+ value: string | null;
315
+ /** The line under both names that says what is wrong with them. */
316
+ describedBy?: string;
317
+ }) {
318
+ const id = useId();
319
+ const [shown, setShown] = useState(false);
320
+ const problem = name === undefined || name.trim() === '' ? null : secretKeyProblem(name.trim());
321
+ return (
322
+ <div className="field">
323
+ <label className="label" htmlFor={`${id}-value`}>
324
+ {label}
325
+ {format !== undefined && <span className="label-note"> · {format}</span>}
326
+ </label>
327
+ {name !== undefined && (
328
+ <input
329
+ className="input input-mono"
330
+ aria-label={`Name of the ${label.toLowerCase()}`}
331
+ aria-invalid={problem !== null}
332
+ aria-describedby={describedBy}
333
+ placeholder="NAME_OF_SECRET"
334
+ spellCheck={false}
335
+ autoComplete="off"
336
+ value={name}
337
+ disabled={onName === undefined}
338
+ onChange={(event) => onName?.(event.target.value)}
339
+ />
340
+ )}
341
+ <div className="input-group">
342
+ <MaskedInput
343
+ id={`${id}-value`}
344
+ className="input input-mono"
345
+ masked={!shown}
346
+ readOnly
347
+ value={value ?? ''}
348
+ placeholder={value === null ? 'Generating…' : undefined}
349
+ />
350
+ <button
351
+ type="button"
352
+ className="btn btn-quiet btn-sm btn-icon input-addon"
353
+ aria-label={shown ? `Mask the ${label.toLowerCase()}` : `Show the ${label.toLowerCase()}`}
354
+ aria-pressed={shown}
355
+ onClick={() => setShown((current) => !current)}
356
+ >
357
+ {shown ? <EyeOff size={14} /> : <Eye size={14} />}
358
+ </button>
359
+ </div>
360
+ </div>
361
+ );
362
+ }