@coffre/ui 0.6.2 → 0.7.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.
Files changed (86) hide show
  1. package/dist/chunks/{audit-sentence-BVv_9_nq.js → audit-sentence-C1_gRxWW.js} +90 -25
  2. package/dist/chunks/audit-sentence-C1_gRxWW.js.map +1 -0
  3. package/dist/chunks/{connected-apps-rBF9XUob.js → connected-apps-Bn5rEoV2.js} +2 -2
  4. package/dist/chunks/{connected-apps-rBF9XUob.js.map → connected-apps-Bn5rEoV2.js.map} +1 -1
  5. package/dist/chunks/{delete-place-CkGezx5R.js → delete-place-CQCDHkne.js} +3 -3
  6. package/dist/chunks/{delete-place-CkGezx5R.js.map → delete-place-CQCDHkne.js.map} +1 -1
  7. package/dist/chunks/{directory-SRN01yP6.js → directory-BQNOdze_.js} +6 -5
  8. package/dist/chunks/{directory-SRN01yP6.js.map → directory-BQNOdze_.js.map} +1 -1
  9. package/dist/chunks/{grants-1E1vqkM0.js → grants-CJIBrkod.js} +3 -3
  10. package/dist/chunks/{grants-1E1vqkM0.js.map → grants-CJIBrkod.js.map} +1 -1
  11. package/dist/chunks/{offboarding-Bt7KSixm.js → offboarding-CrgwaetA.js} +3 -3
  12. package/dist/chunks/offboarding-CrgwaetA.js.map +1 -0
  13. package/dist/chunks/personal-tokens-B8rkT-DI.js +138 -0
  14. package/dist/chunks/personal-tokens-B8rkT-DI.js.map +1 -0
  15. package/dist/chunks/{principal-page-Cbx2l6XL.js → principal-page-DDmmV1KQ.js} +25 -12
  16. package/dist/chunks/principal-page-DDmmV1KQ.js.map +1 -0
  17. package/dist/chunks/{project-page-DKo2AFYg.js → project-page-BI--vjt3.js} +2 -2
  18. package/dist/chunks/{project-page-DKo2AFYg.js.map → project-page-BI--vjt3.js.map} +1 -1
  19. package/dist/chunks/{queries-BvSw1xBN.js → queries-epz4MIuW.js} +19 -5
  20. package/dist/chunks/queries-epz4MIuW.js.map +1 -0
  21. package/dist/chunks/{references-DCoSPtvw.js → references-DImfw0cz.js} +3 -3
  22. package/dist/chunks/{references-DCoSPtvw.js.map → references-DImfw0cz.js.map} +1 -1
  23. package/dist/chunks/{role-field-D98CvNEg.js → role-field-C1KhNaIR.js} +2 -2
  24. package/dist/chunks/{role-field-D98CvNEg.js.map → role-field-C1KhNaIR.js.map} +1 -1
  25. package/dist/chunks/{use-action-Bv7yQ0DW.js → use-action-BB-RcHo1.js} +2 -2
  26. package/dist/chunks/{use-action-Bv7yQ0DW.js.map → use-action-BB-RcHo1.js.map} +1 -1
  27. package/dist/chunks/{use-change-DIQTGXER.js → use-change-CQyDpCqw.js} +268 -17
  28. package/dist/chunks/use-change-CQyDpCqw.js.map +1 -0
  29. package/dist/chunks/{use-shell-DhFoHjDS.js → use-shell-C_NmvCt_.js} +2 -2
  30. package/dist/chunks/{use-shell-DhFoHjDS.js.map → use-shell-C_NmvCt_.js.map} +1 -1
  31. package/dist/index.d.ts +33 -0
  32. package/dist/index.js +4 -3
  33. package/dist/index.js.map +1 -1
  34. package/dist/pages/account.d.ts +1 -1
  35. package/dist/pages/account.js +26 -9
  36. package/dist/pages/account.js.map +1 -1
  37. package/dist/pages/audit.js +52 -32
  38. package/dist/pages/audit.js.map +1 -1
  39. package/dist/pages/environment.js +520 -192
  40. package/dist/pages/environment.js.map +1 -1
  41. package/dist/pages/login.js +1 -1
  42. package/dist/pages/project-access.js +8 -8
  43. package/dist/pages/project-access.js.map +1 -1
  44. package/dist/pages/project-environments.js +106 -19
  45. package/dist/pages/project-environments.js.map +1 -1
  46. package/dist/pages/project-settings.js +6 -6
  47. package/dist/pages/project.js +1 -1
  48. package/dist/pages/projects.js +4 -4
  49. package/dist/pages/service-account.js +278 -29
  50. package/dist/pages/service-account.js.map +1 -1
  51. package/dist/pages/service-accounts.js +4 -4
  52. package/dist/pages/settings.js +4 -4
  53. package/dist/pages/unregistered.js +1 -1
  54. package/dist/pages/user.js +5 -5
  55. package/dist/pages/users.js +4 -4
  56. package/package.json +3 -3
  57. package/src/components/actions-log.tsx +2 -1
  58. package/src/components/directory.tsx +1 -0
  59. package/src/components/generate-value.tsx +15 -7
  60. package/src/components/offboarding.tsx +1 -1
  61. package/src/components/personal-tokens.tsx +131 -0
  62. package/src/components/principal-page.tsx +20 -3
  63. package/src/components/regenerate.tsx +72 -0
  64. package/src/components/service-tokens.tsx +3 -3
  65. package/src/components/trusted-workloads.tsx +177 -8
  66. package/src/lib/audit-sentences.ts +100 -12
  67. package/src/lib/bindings.ts +41 -3
  68. package/src/lib/changes.ts +155 -20
  69. package/src/lib/generate.ts +3 -146
  70. package/src/lib/queries.ts +15 -4
  71. package/src/lib/recipes.ts +63 -0
  72. package/src/lib/reveal.ts +7 -1
  73. package/src/lib/secret-edit-batch.ts +64 -5
  74. package/src/options.ts +5 -1
  75. package/src/pages/account.tsx +27 -5
  76. package/src/pages/audit.tsx +23 -7
  77. package/src/pages/environment.tsx +357 -39
  78. package/src/pages/project-access.tsx +1 -1
  79. package/src/pages/project-environments.tsx +85 -12
  80. package/src/parity.ts +18 -2
  81. package/src/styles/globals.css +56 -3
  82. package/dist/chunks/audit-sentence-BVv_9_nq.js.map +0 -1
  83. package/dist/chunks/offboarding-Bt7KSixm.js.map +0 -1
  84. package/dist/chunks/principal-page-Cbx2l6XL.js.map +0 -1
  85. package/dist/chunks/queries-BvSw1xBN.js.map +0 -1
  86. package/dist/chunks/use-change-DIQTGXER.js.map +0 -1
@@ -21,8 +21,9 @@ export function ActionsLog({ member }: { member: string }) {
21
21
  initialPageParam: undefined as number | undefined,
22
22
  queryFn: ({ pageParam }) =>
23
23
  uiResult(() => client.audit.list({ actor: member, limit: PAGE_SIZE, before: pageParam })),
24
+ // A page lists fewer entries where they name many secrets: `more` says whether older ones follow.
24
25
  getNextPageParam: (page) =>
25
- page.ok && page.entries.length === PAGE_SIZE ? page.entries.at(-1)!.seq : undefined,
26
+ page.ok && page.more && page.entries.length > 0 ? page.entries.at(-1)!.seq : undefined,
26
27
  });
27
28
 
28
29
  if (log.isPending) {
@@ -480,6 +480,7 @@ function RemovalPreview({ principal, open }: { principal: DirectoryPrincipal; op
480
480
  ? [
481
481
  plural(live.grants, 'grant'),
482
482
  plural(live.sessions, 'session'),
483
+ ...(live.tokens > 0 ? [plural(live.tokens, 'personal token')] : []),
483
484
  plural(live.identities, 'linked sign-in account'),
484
485
  ...(features.mcp ? [apps] : []),
485
486
  ]
@@ -3,17 +3,18 @@ import {
3
3
  DEFAULT_RECIPE,
4
4
  ENCODINGS,
5
5
  encodedLength,
6
+ formatRecipe,
6
7
  generate,
7
8
  MAX_BYTES,
8
9
  MIN_BYTES,
9
10
  PAIRS,
10
- pairNameProblem,
11
11
  publicKeyName,
12
12
  type AesSize,
13
13
  type Encoding,
14
14
  type Generated,
15
15
  type Recipe,
16
- } from '../lib/generate';
16
+ } from '@coffre/core/recipe';
17
+ import { pairNameProblem } from '../lib/generate';
17
18
  import type { Companion } from '../lib/secret-edit-batch';
18
19
  import { secretKeyProblem } from '../lib/validation';
19
20
  import { Eye, EyeOff, Shuffle } from './icons';
@@ -22,9 +23,10 @@ import { ErrorLine, Modal } from './ui';
22
23
 
23
24
  /**
24
25
  * 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
+ * new row's can change), the recipe it was made by, which the row saves
27
+ * with it for Regenerate, and for a key pair the public key it saves too.
26
28
  */
27
- export type GeneratedUse = { value: string; name: string; companion?: Companion };
29
+ export type GeneratedUse = { value: string; name: string; recipe: string; companion?: Companion };
28
30
 
29
31
  type Kind = Recipe['kind'];
30
32
 
@@ -99,7 +101,8 @@ function GenerateForm({
99
101
  const [size, setSize] = useState<AesSize>(256);
100
102
  const [pair, setPair] = useState(0);
101
103
  const [round, setRound] = useState(0);
102
- const [generated, setGenerated] = useState<Generated | null>(null);
104
+ // With the recipe it was made by, which Use saves: never the one picked a moment later.
105
+ const [generated, setGenerated] = useState<(Generated & { recipe: string }) | null>(null);
103
106
  const [error, setError] = useState<string | null>(null);
104
107
  const [privateName, setPrivateName] = useState(name);
105
108
  // Follows the private key's name until it is typed in, or the row it replaces names it.
@@ -118,7 +121,7 @@ function GenerateForm({
118
121
  setGenerated(null);
119
122
  setError(null);
120
123
  generate(recipe).then(
121
- (made) => current && setGenerated(made),
124
+ (made) => current && setGenerated({ ...made, recipe: formatRecipe(recipe) }),
122
125
  (failure: unknown) =>
123
126
  current && setError(failure instanceof Error ? failure.message : 'The browser made no value.'),
124
127
  );
@@ -139,9 +142,10 @@ function GenerateForm({
139
142
  ? {
140
143
  value: generated.value,
141
144
  name: privateName.trim(),
145
+ recipe: generated.recipe,
142
146
  companion: { key: publicKey.trim(), value: generated.publicKey },
143
147
  }
144
- : { value: generated.value, name },
148
+ : { value: generated.value, name, recipe: generated.recipe },
145
149
  );
146
150
  }
147
151
 
@@ -278,6 +282,10 @@ function GenerateForm({
278
282
  />
279
283
  )}
280
284
 
285
+ <p className="hint">
286
+ Saved with its recipe, <span className="mono">{formatRecipe(recipe)}</span>, so Regenerate makes the next one alike.
287
+ </p>
288
+
281
289
  <ErrorLine error={error} />
282
290
 
283
291
  <div className="dialog-actions generate-actions">
@@ -42,7 +42,7 @@ export function RemovedNotice({ report }: { report: PrincipalReport }) {
42
42
  )}
43
43
  .{' '}
44
44
  {person
45
- ? 'Their project access, sessions, CLI logins, linked sign-in accounts and connected apps were revoked, so adding them again starts from nothing.'
45
+ ? 'Their project access, sessions, CLI logins, personal tokens, linked sign-in accounts and connected apps were revoked, so adding them again starts from nothing.'
46
46
  : 'Its project access and every token issued to it were revoked, so adding it again starts from nothing.'}
47
47
  </Notice>
48
48
  </div>
@@ -0,0 +1,131 @@
1
+ import type { TokenRow } from '@coffre/client';
2
+ import { credentialScopeInWords } from '@coffre/core/access';
3
+ import { Fragment, type ReactNode } from 'react';
4
+
5
+ import type { Change } from '../lib/optimistic';
6
+ import { useChange, useChangeStatus } from '../lib/use-change';
7
+ import { Key, X } from './icons';
8
+ import { Card } from './page';
9
+ import { RowFailure, RowPending, rowClass } from './row-state';
10
+ import { ConfirmButton, EmptyState, ErrorLine, Timestamp } from './ui';
11
+
12
+ /**
13
+ * Personal tokens, which act as their person within what each reaches:
14
+ * your own on your account page, or a person's on theirs, for whoever runs
15
+ * the instance. Each row says what it is called, what it reaches and when
16
+ * it ends; Revoke stops it at its next request.
17
+ */
18
+ export function PersonalTokensCard<TData>({
19
+ tokens,
20
+ change,
21
+ description,
22
+ empty,
23
+ emptyActions,
24
+ }: {
25
+ tokens: TokenRow[] | { error: string };
26
+ change: Change<TData, TokenRow, TokenRow, unknown>;
27
+ description: ReactNode;
28
+ /** Said when there is none: phrasing, inside the empty state's paragraph. */
29
+ empty?: ReactNode;
30
+ /** Beneath it, what to do about it. */
31
+ emptyActions?: ReactNode;
32
+ }) {
33
+ const revoke = useChange(change);
34
+ const { status, dismiss } = useChangeStatus(change.list.queryKey);
35
+ return (
36
+ <Card labelledBy="personal-tokens" title="Personal tokens" description={description}>
37
+ {'error' in tokens ? (
38
+ <div className="card-body">
39
+ <ErrorLine error={tokens.error} />
40
+ </div>
41
+ ) : tokens.length === 0 ? (
42
+ <EmptyState title="No personal tokens" actions={emptyActions}>
43
+ {empty}
44
+ </EmptyState>
45
+ ) : (
46
+ <div className="dt-wrap">
47
+ <table className="dt stacks stacks-inline">
48
+ <thead>
49
+ <tr>
50
+ <th>Token</th>
51
+ <th>Reaches</th>
52
+ <th className="col-shrink">Last used</th>
53
+ <th className="col-shrink">Expires</th>
54
+ <th className="col-actions">
55
+ <span className="visually-hidden">Actions</span>
56
+ </th>
57
+ </tr>
58
+ </thead>
59
+ <tbody>
60
+ {tokens.map((token) => {
61
+ const state = status(token.id);
62
+ return (
63
+ <Fragment key={token.id}>
64
+ <tr className={rowClass(state)}>
65
+ <td>
66
+ <span className="cell-account">
67
+ <Key size={15} />
68
+ <span className="cell-stack">
69
+ <span>{token.label}</span>
70
+ <small>
71
+ <span className="mono">{token.hint}</span>
72
+ {' · made '}
73
+ <Timestamp iso={token.createdAt} display="relative" />
74
+ </small>
75
+ </span>
76
+ </span>
77
+ </td>
78
+ <td data-label="Reaches">{credentialScopeInWords(token.scope ?? {})}</td>
79
+ <td className="nowrap cell-muted" data-label="Last used">
80
+ {token.lastUsedAt === null ? (
81
+ 'Never'
82
+ ) : (
83
+ <span className="cell-stack">
84
+ <Timestamp iso={token.lastUsedAt} display="relative" />
85
+ {token.lastUsedIp !== null && <small className="mono">{token.lastUsedIp}</small>}
86
+ </span>
87
+ )}
88
+ </td>
89
+ <td className="nowrap cell-muted" data-label="Expires">
90
+ <Timestamp iso={token.expiresAt} display="relative" />
91
+ </td>
92
+ <td className="col-actions">
93
+ {state.state === 'pending' ? (
94
+ <RowPending status={state} />
95
+ ) : (
96
+ <ConfirmButton
97
+ trigger={
98
+ <button className="act">
99
+ <X size={13} />
100
+ Revoke
101
+ </button>
102
+ }
103
+ title={`Revoke “${token.label}”?`}
104
+ body={
105
+ <>
106
+ <span className="mono">{token.hint}</span>, last used{' '}
107
+ {token.lastUsedAt === null ? 'never' : <Timestamp iso={token.lastUsedAt} display="relative" />}.
108
+ Whatever uses it is refused at once.
109
+ </>
110
+ }
111
+ confirmLabel="Revoke token"
112
+ onConfirm={() => revoke(token)}
113
+ />
114
+ )}
115
+ </td>
116
+ </tr>
117
+ <RowFailure
118
+ status={state}
119
+ columns={5}
120
+ onDismiss={() => state.state === 'failed' && dismiss(state.mutationId)}
121
+ />
122
+ </Fragment>
123
+ );
124
+ })}
125
+ </tbody>
126
+ </table>
127
+ </div>
128
+ )}
129
+ </Card>
130
+ );
131
+ }
@@ -5,7 +5,7 @@ import { INSTANCE_ROLES, ROLE_NAMES, ROLES, scopeInWords, unscoped, type Role }
5
5
  import { useShell } from '../lib/use-shell';
6
6
  import { toast } from 'sonner';
7
7
  import { memberRef, useCoffre } from '../lib/coffre';
8
- import { directoryList } from '../lib/changes';
8
+ import { directoryList, revokeMemberToken } from '../lib/changes';
9
9
  import { affects, hasAppsTab, keys, listsAccess, managedProjects, queries, signInWays } from '../lib/queries';
10
10
  import { useChangeStatus } from '../lib/use-change';
11
11
  import { useMounted } from '../lib/mounted';
@@ -25,7 +25,7 @@ import {
25
25
  type AccessChange,
26
26
  type AccessPlan,
27
27
  } from '../lib/access-plan';
28
- import type { MemberAccess } from '@coffre/client';
28
+ import type { MemberAccess, TokenRow } from '@coffre/client';
29
29
  import type { DirectoryPrincipal, ProjectSummary } from '../shared/models';
30
30
  import { ClosedDoor, PageHeader } from './page';
31
31
  import { EmptyState, ErrorLine, Modal, Notice, Spinner } from './ui';
@@ -33,6 +33,7 @@ import { GrantRowView, GrantsTable } from './grants';
33
33
  import { ExpiryField } from './expiry-field';
34
34
  import { InstanceRole, KIND, PrincipalActions } from './directory';
35
35
  import { PrincipalReportCards, RemovedNotice } from './offboarding';
36
+ import { PersonalTokensCard } from './personal-tokens';
36
37
  import { PrincipalAvatar } from './principal';
37
38
  import { Tile } from './tile';
38
39
  import { Activity, Archive, Clock, Folder, Key, Link as LinkIcon, Pencil, Users, X } from './icons';
@@ -321,10 +322,25 @@ export function PrincipalAccess({ principalType, principalId }: { principalType:
321
322
  )}
322
323
 
323
324
  {found !== null && <PrincipalReportCards report={found} />}
325
+ {/* A report from an instance before 0.7, mid-deploy or rolled back, lists none. */}
326
+ {found !== null && !removed && (found.personalTokens ?? []).length > 0 && (
327
+ <MemberPersonalTokens member={memberRef(principalType, principalId)} tokens={found.personalTokens} />
328
+ )}
324
329
  </>
325
330
  );
326
331
  }
327
332
 
333
+ /** A person's personal tokens, for whoever runs the instance, who reads their report and may revoke any of them. */
334
+ function MemberPersonalTokens({ member, tokens }: { member: string; tokens: TokenRow[] }) {
335
+ return (
336
+ <PersonalTokensCard
337
+ tokens={tokens}
338
+ change={revokeMemberToken(useCoffre(), member)}
339
+ description="Tokens they made, each acting as them within what it reaches. Removing them from coffre revokes every one."
340
+ />
341
+ );
342
+ }
343
+
328
344
  /** What a person's instance role gives them, above the grants that add to it: nothing for a Member. */
329
345
  function InstanceRoleNote({ access }: { access: MemberAccess }) {
330
346
  if (access.instanceRole === 'member') return null;
@@ -391,7 +407,8 @@ function EditAccess({
391
407
  const rows = access.map(({ project, grants }) => {
392
408
  const environments = project.environments
393
409
  .filter(
394
- (environment) => environment.details !== null && environment.details.archivedAt === null,
410
+ // Your personal config takes no grant: it is no place to give access to.
411
+ (environment) => environment.details !== null && environment.details.archivedAt === null && !environment.personal,
395
412
  )
396
413
  .map((environment) => environment.slug);
397
414
  const held = planFromGrants(grants, environments);
@@ -0,0 +1,72 @@
1
+ import type { SecretKey } from '@coffre/client';
2
+ import { describeRecipe, parseRecipe, recipeProblem, type Generation } from '@coffre/core/recipe';
3
+
4
+ import { Generate } from './icons';
5
+ import { ConfirmDialog, Tip } from './ui';
6
+
7
+ /** What a generated key's recipe makes, in words; null for one this page does not know. */
8
+ export function recipeInWords(generated: Generation): string | null {
9
+ return recipeProblem(generated.recipe) === null ? describeRecipe(parseRecipe(generated.recipe)) : null;
10
+ }
11
+
12
+ /** Beside a key whose value was generated: how, on hover or focus. */
13
+ export function RecipeMark({ generated }: { generated: Generation }) {
14
+ const label = `Generated: ${recipeInWords(generated) ?? generated.recipe}`;
15
+ return (
16
+ <Tip label={label}>
17
+ <span className="recipe-mark" tabIndex={0} role="img" aria-label={label}>
18
+ <Generate size={12} />
19
+ </span>
20
+ </Tip>
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Asks before regenerating a key by its recipe (`regenerateSecret`, which
26
+ * the row runs on confirm): a new value made in this browser, written as
27
+ * its next version, and never shown. A key pair's either half makes the
28
+ * pair again, both keys in one write, in the environment the page is on.
29
+ */
30
+ export function RegenerateSecret({
31
+ open,
32
+ onOpenChange,
33
+ place,
34
+ entry,
35
+ generated,
36
+ onConfirm,
37
+ }: {
38
+ open: boolean;
39
+ onOpenChange: (open: boolean) => void;
40
+ /** `project/environment`, where it is written. */
41
+ place: string;
42
+ entry: SecretKey;
43
+ generated: Generation;
44
+ onConfirm: () => void;
45
+ }) {
46
+ const made = recipeInWords(generated);
47
+ const body =
48
+ generated.pair === undefined
49
+ ? `A new value, ${made ?? generated.recipe}, is made in this browser and saved as v${(entry.version ?? 0) + 1}. Nobody sees it; whatever reads ${place} gets it from now on.`
50
+ : `A new key pair is made in this browser and saved as ${generated.pair.private} and ${generated.pair.public}, together. Nobody sees it; whatever reads ${place} gets both from now on.`;
51
+ return (
52
+ <ConfirmDialog
53
+ open={open}
54
+ onOpenChange={onOpenChange}
55
+ title={
56
+ <>
57
+ Regenerate <span className="mono">{entry.key}</span>
58
+ {generated.pair !== undefined && ' and its pair'}?
59
+ </>
60
+ }
61
+ body={body}
62
+ detail={
63
+ <p className="hint">
64
+ Recipe <span className="mono">{generated.recipe}</span>
65
+ {generated.pair !== undefined && made !== null && <>: {made}</>}
66
+ </p>
67
+ }
68
+ confirmLabel="Regenerate"
69
+ onConfirm={onConfirm}
70
+ />
71
+ );
72
+ }
@@ -1,4 +1,4 @@
1
- import type { ServiceTokenRow } from '@coffre/client';
1
+ import type { TokenRow } from '@coffre/client';
2
2
  import { credentialScopeInWords } from '@coffre/core/access';
3
3
  import { Fragment, useState } from 'react';
4
4
  import { revokeCredential } from '../lib/changes';
@@ -19,8 +19,8 @@ const LIFETIMES = [30, 90, 180, 365] as const;
19
19
  * OIDC. A value exists in exactly
20
20
  * one place, this dialog, for as long as it stays open: coffre keeps a hash.
21
21
  */
22
- export function ServiceTokens({ serviceId, tokens, grants }: { serviceId: string; tokens: ServiceTokenRow[]; grants: HeldGrant[] }) {
23
- const change = revokeCredential(useCoffre(), serviceId);
22
+ export function ServiceTokens({ serviceId, tokens, grants }: { serviceId: string; tokens: TokenRow[]; grants: HeldGrant[] }) {
23
+ const change = revokeCredential(useCoffre(), memberRef('service', serviceId));
24
24
  const revoke = useChange(change);
25
25
  const { status, dismiss } = useChangeStatus(change.list.queryKey);
26
26
 
@@ -1,9 +1,25 @@
1
- import type { BindingPlan, BindingView, CoffreClient } from '@coffre/client';
1
+ import type { BindingPlan, BindingView, CoffreClient, KeysPlan } from '@coffre/client';
2
2
  import { credentialScopeInWords } from '@coffre/core/access';
3
3
  import { claimValues, EVENT_EXPOSURE, githubEventsAt, GITLAB_PIPELINE_SOURCES } from '@coffre/core/workloads';
4
4
  import { useQuery } from '@tanstack/react-query';
5
5
  import { Fragment, useEffect, useState } from 'react';
6
- import { askedScope, bindingOf, EMPTY_FORM, githubTarget, listedIds, listingGap, planned, summary, type Form, type GitHubLookup, type RefKind, type ScopeChoice } from '../lib/bindings';
6
+ import {
7
+ askedScope,
8
+ bindingOf,
9
+ EMPTY_FORM,
10
+ githubTarget,
11
+ keySetOf,
12
+ keysOf,
13
+ listedIds,
14
+ listingGap,
15
+ planned,
16
+ summary,
17
+ type Form,
18
+ type GitHubLookup,
19
+ type KeySet,
20
+ type RefKind,
21
+ type ScopeChoice,
22
+ } from '../lib/bindings';
7
23
  import { removeBinding } from '../lib/changes';
8
24
  import { memberRef, statusOf, useCoffre } from '../lib/coffre';
9
25
  import { affects, queries } from '../lib/queries';
@@ -16,7 +32,7 @@ import { RowFailure, RowPending, rowClass } from './row-state';
16
32
  import { Card } from './page';
17
33
  import { ScopePicker, wholeScope, type HeldGrant } from './scope-picker';
18
34
  import { ConfirmButton, EmptyState, ErrorLine, Modal, Notice, Spinner, Timestamp } from './ui';
19
- import { CheckCircle, GitHub, Link, Plus, X } from './icons';
35
+ import { CheckCircle, GitHub, Key, Link, Plus, X } from './icons';
20
36
 
21
37
  /**
22
38
  * The CI runs that may sign in as a service, by the ID token their platform
@@ -64,6 +80,7 @@ export function TrustedWorkloads({ serviceId, bindings, grants }: { serviceId: s
64
80
  <details className="claims">
65
81
  <summary>Claims</summary>
66
82
  <Claims binding={binding} />
83
+ {binding.keys !== null && <ReplaceKeys serviceId={serviceId} issuer={binding.issuer} bindings={bindings} />}
67
84
  </details>
68
85
  </span>
69
86
  </span>
@@ -127,7 +144,7 @@ export function TrustedWorkloads({ serviceId, bindings, grants }: { serviceId: s
127
144
  );
128
145
  }
129
146
 
130
- function Claims({ binding }: { binding: Pick<BindingPlan, 'issuer' | 'jwksUri' | 'claims'> }) {
147
+ function Claims({ binding }: { binding: Pick<BindingPlan, 'issuer' | 'jwksUri' | 'keys' | 'claims'> }) {
131
148
  return (
132
149
  <table className="claims-table">
133
150
  <tbody>
@@ -143,13 +160,136 @@ function Claims({ binding }: { binding: Pick<BindingPlan, 'issuer' | 'jwksUri' |
143
160
  ))}
144
161
  <tr>
145
162
  <th>keys</th>
146
- <td className="mono">{binding.jwksUri}</td>
163
+ <td className="mono">{keysOf(binding)}</td>
147
164
  </tr>
148
165
  </tbody>
149
166
  </table>
150
167
  );
151
168
  }
152
169
 
170
+ /**
171
+ * New keys, pasted, for the service's bindings on an issuer whose keys they
172
+ * carry: when the issuer rotates its keys. Each binding is replaced by one
173
+ * the same but for them, as the review says before anything is saved.
174
+ */
175
+ function ReplaceKeys({ serviceId, issuer, bindings }: { serviceId: string; issuer: string; bindings: BindingView[] }) {
176
+ const [open, setOpen] = useState(false);
177
+ const [text, setText] = useState('');
178
+ // The plan, with the keys it was made for: Save sends those, whatever the field says by then.
179
+ const [preview, setPreview] = useState<{ plan: KeysPlan; jwks: KeySet } | null>(null);
180
+ const plan = preview?.plan ?? null;
181
+ const coffre = useCoffre();
182
+ const member = memberRef('service', serviceId);
183
+ const { pending, error, setError, run } = useAction();
184
+ const on = bindings.filter((binding) => binding.issuer === issuer).length;
185
+
186
+ function close() {
187
+ setOpen(false);
188
+ setText('');
189
+ setPreview(null);
190
+ setError(null);
191
+ }
192
+
193
+ function review() {
194
+ let jwks: KeySet;
195
+ try {
196
+ const pasted = keySetOf(text);
197
+ if (pasted === undefined) throw new Error("Paste the issuer's key set");
198
+ jwks = pasted;
199
+ } catch (problem) {
200
+ setError((problem as Error).message);
201
+ return;
202
+ }
203
+ void run(() => coffre.bindings.previewKeys(member, { issuer, jwks }), { affects: [], onSuccess: (next) => setPreview({ plan: next, jwks }) });
204
+ }
205
+
206
+ return (
207
+ <>
208
+ <button className="act" type="button" onClick={() => setOpen(true)}>
209
+ <Key size={13} />
210
+ Replace keys
211
+ </button>
212
+ <Modal open={open} onOpenChange={(next) => (next ? setOpen(true) : close())} title={preview === null ? 'Replace keys' : 'Review the keys'}>
213
+ {preview === null || plan === null ? (
214
+ <form
215
+ className="form"
216
+ onSubmit={(event) => {
217
+ event.preventDefault();
218
+ review();
219
+ }}
220
+ >
221
+ <p>
222
+ The {on === 1 ? 'binding' : `${on} bindings`} of <span className="mono">service:{serviceId}</span> on{' '}
223
+ <span className="mono">{issuer}</span> will verify tokens with these keys alone. While the issuer rotates, paste a set that
224
+ holds the old key and the new, and tokens signed with either sign in.
225
+ </p>
226
+ <label className="field">
227
+ <span className="label">Keys</span>
228
+ <textarea
229
+ className="input mono"
230
+ rows={6}
231
+ value={text}
232
+ spellCheck={false}
233
+ placeholder='{ "keys": [ … ] }'
234
+ onChange={(event) => {
235
+ setText(event.target.value);
236
+ setError(null);
237
+ }}
238
+ />
239
+ <span className="hint">
240
+ From a Kubernetes cluster: <span className="mono">kubectl get --raw /openid/v1/jwks</span>
241
+ </span>
242
+ </label>
243
+ <ErrorLine error={error} />
244
+ <div className="dialog-actions">
245
+ <button className="btn" type="button" onClick={close}>
246
+ Cancel
247
+ </button>
248
+ <button className="btn btn-primary" type="submit" disabled={pending}>
249
+ {pending && <Spinner />}
250
+ Review
251
+ </button>
252
+ </div>
253
+ </form>
254
+ ) : (
255
+ <div className="form">
256
+ <p>
257
+ {plan.replaces.length === 1 ? 'Its binding' : `Its ${plan.replaces.length} bindings`} on <span className="mono">{issuer}</span>{' '}
258
+ {plan.replaces.length === 1 ? 'is' : 'are'} replaced by {plan.replaces.length === 1 ? 'one' : 'ones'} the same but for these keys.
259
+ Credentials {plan.replaces.length === 1 ? 'it' : 'they'} issued, five minutes each at most, end at once.
260
+ </p>
261
+ <table className="claims-table">
262
+ <tbody>
263
+ {plan.keys.map((key) => (
264
+ <tr key={key.thumbprint}>
265
+ <th className="mono">{key.alg}</th>
266
+ <td className="mono">{key.kid ?? key.thumbprint}</td>
267
+ </tr>
268
+ ))}
269
+ </tbody>
270
+ </table>
271
+ <ErrorLine error={error} />
272
+ <div className="dialog-actions">
273
+ <button className="btn" type="button" onClick={() => setPreview(null)}>
274
+ Back
275
+ </button>
276
+ <button
277
+ className="btn btn-primary"
278
+ type="button"
279
+ disabled={pending}
280
+ onClick={() => void run(() => coffre.bindings.replaceKeys(member, { issuer, jwks: preview.jwks }), { affects: affects.bindings(member), onSuccess: close })}
281
+ >
282
+ {pending && <Spinner />}
283
+ Save keys
284
+ </button>
285
+ </div>
286
+ </div>
287
+ )}
288
+ </Modal>
289
+ </>
290
+ );
291
+ }
292
+
153
293
  /** Beside `pull_request` and `workflow_run` in the events' list: they run code nobody reviewed, said in full once chosen. */
154
294
  function exposureNote(event: string) {
155
295
  return EVENT_EXPOSURE[event] === undefined ? null : <span className="tag tag-amber">unreviewed code</span>;
@@ -250,6 +390,8 @@ function TrustWorkload({ serviceId, grants, bindings }: { serviceId: string; gra
250
390
  const whole = (): ScopeChoice => ({ scope: wholeScope(grants), chosen: false });
251
391
  const [choice, setChoice] = useState(whole);
252
392
  const [plan, setPlan] = useState<BindingPlan | null>(null);
393
+ // What the plan was made from: Save sends it, whatever the form says by then.
394
+ const [reviewed, setReviewed] = useState<ReturnType<typeof input> | null>(null);
253
395
  const coffre = useCoffre();
254
396
  const member = memberRef('service', serviceId);
255
397
  const { pending, error, setError, run } = useAction();
@@ -293,6 +435,7 @@ function TrustWorkload({ serviceId, grants, bindings }: { serviceId: string; gra
293
435
  // One that replaces bindings reaches what they did unless told: the picker says so, should the person go back.
294
436
  onSuccess: (next) => {
295
437
  setPlan(next);
438
+ setReviewed(request);
296
439
  setChoice((current) => planned(current, next));
297
440
  },
298
441
  });
@@ -494,11 +637,37 @@ function TrustWorkload({ serviceId, grants, bindings }: { serviceId: string; gra
494
637
 
495
638
  {form.platform === 'other' && (
496
639
  <>
497
- {field('Issuer', 'issuer', { placeholder: 'https://accounts.google.com' })}
640
+ {field('Issuer', 'issuer', {
641
+ placeholder: 'https://accounts.google.com',
642
+ hint: form.jwks.trim() === '' ? undefined : 'Exactly as its tokens name it in iss: with its keys pasted below, coffre asks it nothing.',
643
+ })}
498
644
  {field('Subject (sub)', 'sub', { mono: true, hint: "You vouch for what this issuer's subject means: a Google service account's unique ID, say." })}
499
645
  <label className="field">
500
646
  <span className="label">Other claims, one <span className="mono">name=value</span> a line</span>
501
- <textarea className="input mono" rows={3} value={form.extra} onChange={(event) => set({ extra: event.target.value })} />
647
+ <textarea
648
+ className="input mono"
649
+ rows={3}
650
+ value={form.extra}
651
+ spellCheck={false}
652
+ placeholder="kubernetes.io.serviceaccount.uid=…"
653
+ onChange={(event) => set({ extra: event.target.value })}
654
+ />
655
+ <span className="hint">A nested claim goes by its path, its names joined by dots.</span>
656
+ </label>
657
+ <label className="field">
658
+ <span className="label">Keys (optional)</span>
659
+ <textarea
660
+ className="input mono"
661
+ rows={3}
662
+ value={form.jwks}
663
+ spellCheck={false}
664
+ placeholder='{ "keys": [ … ] }'
665
+ onChange={(event) => set({ jwks: event.target.value })}
666
+ />
667
+ <span className="hint">
668
+ Left empty, coffre fetches the issuer's keys. Paste them for one it cannot reach, such as a private Kubernetes cluster:{' '}
669
+ <span className="mono">kubectl get --raw /openid/v1/jwks</span>
670
+ </span>
502
671
  </label>
503
672
  </>
504
673
  )}
@@ -548,7 +717,7 @@ function TrustWorkload({ serviceId, grants, bindings }: { serviceId: string; gra
548
717
  type="button"
549
718
  disabled={pending}
550
719
  // What the review said it reaches, whatever the account holds by now.
551
- onClick={() => void run(() => coffre.bindings.create(member, { ...input(), scope: plan.scope }), { affects: affects.bindings(member), onSuccess: close })}
720
+ onClick={() => void run(() => coffre.bindings.create(member, { ...reviewed!, scope: plan.scope }), { affects: affects.bindings(member), onSuccess: close })}
552
721
  >
553
722
  {pending && <Spinner />}
554
723
  Save binding