@coffre/ui 0.4.6 → 0.5.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 (113) hide show
  1. package/dist/chunks/{affordances-DAvsVz7u.js → affordances-Bqdevf7w.js} +10 -5
  2. package/dist/chunks/affordances-Bqdevf7w.js.map +1 -0
  3. package/dist/chunks/{audit-sentence-DIztXvbU.js → audit-sentence-Cm5nby5k.js} +105 -7
  4. package/dist/chunks/audit-sentence-Cm5nby5k.js.map +1 -0
  5. package/dist/chunks/{connected-apps-AZsX9Zvv.js → connected-apps-DTNS7YmY.js} +2 -2
  6. package/dist/chunks/{connected-apps-AZsX9Zvv.js.map → connected-apps-DTNS7YmY.js.map} +1 -1
  7. package/dist/chunks/{delete-place-D6LIZkg9.js → delete-place-CIaOq0mt.js} +3 -3
  8. package/dist/chunks/{delete-place-D6LIZkg9.js.map → delete-place-CIaOq0mt.js.map} +1 -1
  9. package/dist/chunks/{directory-B6FuiCir.js → directory-DSVt5Tya.js} +54 -60
  10. package/dist/chunks/directory-DSVt5Tya.js.map +1 -0
  11. package/dist/chunks/{folders-DvSqBhuu.js → folders-CoGK9oqg.js} +2 -2
  12. package/dist/chunks/{folders-DvSqBhuu.js.map → folders-CoGK9oqg.js.map} +1 -1
  13. package/dist/chunks/grants-CRU7yZhL.js +164 -0
  14. package/dist/chunks/grants-CRU7yZhL.js.map +1 -0
  15. package/dist/chunks/{offboarding-CLJaNTcD.js → offboarding-DVBSiJRZ.js} +7 -3
  16. package/dist/chunks/offboarding-DVBSiJRZ.js.map +1 -0
  17. package/dist/chunks/{principal-page-1yMztIcc.js → principal-page-BEBr_zW7.js} +350 -91
  18. package/dist/chunks/principal-page-BEBr_zW7.js.map +1 -0
  19. package/dist/chunks/{project-page-C4cEaRFa.js → project-page-B3TZ5_ig.js} +2 -2
  20. package/dist/chunks/{project-page-C4cEaRFa.js.map → project-page-B3TZ5_ig.js.map} +1 -1
  21. package/dist/chunks/{queries-Dew8mIeo.js → queries-DE5nK2y4.js} +132 -54
  22. package/dist/chunks/queries-DE5nK2y4.js.map +1 -0
  23. package/dist/chunks/{references-DWDnXNoW.js → references-uv4Mli9z.js} +4 -3
  24. package/dist/chunks/{references-DWDnXNoW.js.map → references-uv4Mli9z.js.map} +1 -1
  25. package/dist/chunks/role-field-DWhkRY6n.js +192 -0
  26. package/dist/chunks/role-field-DWhkRY6n.js.map +1 -0
  27. package/dist/chunks/use-action-BRgvbUWt.js +49 -0
  28. package/dist/chunks/use-action-BRgvbUWt.js.map +1 -0
  29. package/dist/chunks/{use-change-C4bGRhHY.js → use-change-BJ3dCFHb.js} +40 -14
  30. package/dist/chunks/use-change-BJ3dCFHb.js.map +1 -0
  31. package/dist/chunks/{use-shell-Dkv89nW1.js → use-shell-BO4ZTr1y.js} +2 -2
  32. package/dist/chunks/{use-shell-Dkv89nW1.js.map → use-shell-BO4ZTr1y.js.map} +1 -1
  33. package/dist/chunks/validation-DiHIwZRA.js +37 -0
  34. package/dist/chunks/validation-DiHIwZRA.js.map +1 -0
  35. package/dist/index.d.ts +111 -88
  36. package/dist/index.js +40 -21
  37. package/dist/index.js.map +1 -1
  38. package/dist/pages/account.js +8 -7
  39. package/dist/pages/account.js.map +1 -1
  40. package/dist/pages/audit.js +2 -2
  41. package/dist/pages/environment.js +8 -7
  42. package/dist/pages/environment.js.map +1 -1
  43. package/dist/pages/login.js +2 -2
  44. package/dist/pages/login.js.map +1 -1
  45. package/dist/pages/project-access.js +7 -7
  46. package/dist/pages/project-environments.js +26 -21
  47. package/dist/pages/project-environments.js.map +1 -1
  48. package/dist/pages/project-settings.js +9 -8
  49. package/dist/pages/project-settings.js.map +1 -1
  50. package/dist/pages/project.js +1 -1
  51. package/dist/pages/projects.js +8 -13
  52. package/dist/pages/projects.js.map +1 -1
  53. package/dist/pages/service-account.js +294 -88
  54. package/dist/pages/service-account.js.map +1 -1
  55. package/dist/pages/service-accounts.js +7 -7
  56. package/dist/pages/service-accounts.js.map +1 -1
  57. package/dist/pages/settings.js +91 -9
  58. package/dist/pages/settings.js.map +1 -1
  59. package/dist/pages/unregistered.d.ts +1 -1
  60. package/dist/pages/unregistered.js +4 -4
  61. package/dist/pages/unregistered.js.map +1 -1
  62. package/dist/pages/user.d.ts +2 -0
  63. package/dist/pages/user.js +21 -3
  64. package/dist/pages/user.js.map +1 -1
  65. package/dist/pages/users.js +4 -4
  66. package/package.json +3 -3
  67. package/src/components/affordances.ts +7 -3
  68. package/src/components/command-palette.tsx +2 -0
  69. package/src/components/directory.tsx +58 -63
  70. package/src/components/grants.tsx +9 -9
  71. package/src/components/offboarding.tsx +3 -1
  72. package/src/components/principal-page.tsx +124 -74
  73. package/src/components/role-field.tsx +183 -0
  74. package/src/components/scope-picker.tsx +73 -0
  75. package/src/components/service-tokens.tsx +20 -9
  76. package/src/components/shell.tsx +6 -10
  77. package/src/components/trusted-workloads.tsx +121 -42
  78. package/src/index.ts +1 -0
  79. package/src/lib/audit-sentences.ts +104 -3
  80. package/src/lib/bindings.ts +33 -10
  81. package/src/lib/capabilities.ts +28 -8
  82. package/src/lib/changes.ts +22 -13
  83. package/src/lib/project-access.ts +21 -0
  84. package/src/lib/queries.ts +121 -44
  85. package/src/lib/service-setup.ts +41 -0
  86. package/src/lib/validation.ts +7 -0
  87. package/src/options.ts +31 -11
  88. package/src/pages/account.tsx +3 -2
  89. package/src/pages/login.tsx +1 -1
  90. package/src/pages/project-environments.tsx +12 -15
  91. package/src/pages/project-settings.tsx +3 -3
  92. package/src/pages/projects.tsx +1 -5
  93. package/src/pages/service-account.tsx +7 -5
  94. package/src/pages/service-accounts.tsx +8 -4
  95. package/src/pages/settings.tsx +80 -4
  96. package/src/pages/unregistered.tsx +3 -3
  97. package/src/pages/user.tsx +24 -1
  98. package/src/parity.ts +5 -1
  99. package/src/register.ts +3 -1
  100. package/src/shared/models.ts +8 -4
  101. package/src/styles/globals.css +100 -27
  102. package/dist/chunks/affordances-DAvsVz7u.js.map +0 -1
  103. package/dist/chunks/audit-sentence-DIztXvbU.js.map +0 -1
  104. package/dist/chunks/directory-B6FuiCir.js.map +0 -1
  105. package/dist/chunks/grants-9kIV6uZ7.js +0 -669
  106. package/dist/chunks/grants-9kIV6uZ7.js.map +0 -1
  107. package/dist/chunks/offboarding-CLJaNTcD.js.map +0 -1
  108. package/dist/chunks/principal-page-1yMztIcc.js.map +0 -1
  109. package/dist/chunks/queries-Dew8mIeo.js.map +0 -1
  110. package/dist/chunks/use-change-C4bGRhHY.js.map +0 -1
  111. package/dist/chunks/validation-DvPinn8V.js +0 -87
  112. package/dist/chunks/validation-DvPinn8V.js.map +0 -1
  113. package/src/components/every-project.tsx +0 -287
@@ -1,17 +1,18 @@
1
1
  import { useState } from 'react';
2
- import { useSuspenseQueries, useSuspenseQuery } from '@tanstack/react-query';
2
+ import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query';
3
3
  import { Link, Outlet } from '@tanstack/react-router';
4
- import { ROLES } from '@coffre/core/access';
4
+ import { INSTANCE_ROLES, ROLE_NAMES, ROLES, scopeInWords, unscoped, type Role } from '@coffre/core/access';
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, disconnectMemberApp } from '../lib/changes';
9
- import { affects, managedProjects, queries, signInWays } from '../lib/queries';
8
+ import { directoryList } from '../lib/changes';
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';
12
12
  import { ItemFailure } from './row-state';
13
13
  import { useAction } from '../lib/use-action';
14
- import { projectAccessLabel } from '../lib/project-access';
14
+ import { accessRows, projectAccessLabel, type ProjectAccess } from '../lib/project-access';
15
+ import { givable, serviceProjects } from '../lib/service-setup';
15
16
  import {
16
17
  accessChanges,
17
18
  accessPatch,
@@ -24,15 +25,14 @@ import {
24
25
  type AccessChange,
25
26
  type AccessPlan,
26
27
  } from '../lib/access-plan';
27
- import type { DirectoryPrincipal, GrantRow, PrincipalReport, ProjectSummary } from '../shared/models';
28
+ import type { MemberAccess } from '@coffre/client';
29
+ import type { DirectoryPrincipal, ProjectSummary } from '../shared/models';
28
30
  import { ClosedDoor, PageHeader } from './page';
29
31
  import { EmptyState, ErrorLine, Modal, Notice, Spinner } from './ui';
30
32
  import { GrantRowView, GrantsTable } from './grants';
31
- import { EveryProjectGrants } from './every-project';
32
33
  import { ExpiryField } from './expiry-field';
33
34
  import { InstanceRole, KIND, PrincipalActions } from './directory';
34
35
  import { PrincipalReportCards, RemovedNotice } from './offboarding';
35
- import { ConnectedAppsCard } from './connected-apps';
36
36
  import { PrincipalAvatar } from './principal';
37
37
  import { Tile } from './tile';
38
38
  import { Activity, Archive, Clock, Folder, Key, Link as LinkIcon, Pencil, Users, X } from './icons';
@@ -40,40 +40,53 @@ import { PageTabs } from './tabs';
40
40
 
41
41
  type PrincipalType = DirectoryPrincipal['principalType'];
42
42
 
43
- type ProjectAccess = { project: ProjectSummary; grants: GrantRow[]; grantsError: string | null };
43
+ /** The roles you may give at a project, or one of its environments: any where you manage access (`givable`). */
44
+ type Offers = (project: ProjectSummary, environment: string | null) => readonly Role[];
44
45
 
45
46
  /** Who a user or service account is to the instance, as an owner reads it; null for anyone else. */
46
47
  function useReport(principalType: PrincipalType, principalId: string) {
47
48
  const { capabilities } = useShell();
48
- return useSuspenseQuery(queries.report(useCoffre(), memberRef(principalType, principalId), capabilities.canManageGrants)).data;
49
+ return useSuspenseQuery(queries.report(useCoffre(), memberRef(principalType, principalId), capabilities.runsInstance)).data;
49
50
  }
50
51
 
51
52
  /**
52
- * Its grants on every project where you manage access, which `loadAccess`
53
- * read: there is no call for one member's, so each project's are filtered.
53
+ * What `loadAccess` read in one request: their role and scope, and, for each
54
+ * project where you manage access, the grants they hold there. For a
55
+ * service account you manage, each project where you may give it
56
+ * something, and what (`offers`).
54
57
  */
55
- function useProjectAccess(principalType: PrincipalType, principalId: string): ProjectAccess[] {
56
- const client = useCoffre();
57
- const managed = managedProjects(useShell().projects);
58
- const grants = useSuspenseQueries({
59
- queries: managed.map((project) => queries.grants(client, project.slug)),
60
- });
61
- return managed.map((project, index) => {
62
- const result = grants[index]!.data;
63
- return {
58
+ function useMemberAccess(principalType: PrincipalType, principalId: string): {
59
+ access: MemberAccess | null;
60
+ error: string | null;
61
+ projects: ProjectAccess[];
62
+ offers: Offers;
63
+ } {
64
+ const shell = useShell();
65
+ const { data } = useSuspenseQuery(queries.memberAccess(useCoffre(), memberRef(principalType, principalId), listsAccess(shell)));
66
+ const error = data !== null && !data.ok ? data.error : null;
67
+ const access = data?.ok === true ? data : null;
68
+ const yours = principalType === 'service' && access?.managed === true;
69
+ const listed = yours ? serviceProjects(shell) : managedProjects(shell.projects);
70
+ return {
71
+ access,
72
+ error,
73
+ offers: yours ? (project, environment) => givable(shell, project, environment) : () => ROLE_NAMES,
74
+ projects: listed.map((project) => ({
64
75
  project,
65
- // Grants on every project show once, below: not again in each project they reach.
66
- grants: result.ok
67
- ? result.grants.filter(
68
- (grant) =>
69
- grant.principalType === principalType &&
70
- grant.principalId === principalId &&
71
- grant.scope !== 'every-project',
72
- )
73
- : [],
74
- grantsError: result.ok ? null : result.error,
75
- };
76
- });
76
+ grants: (access?.grants ?? []).filter((grant) => grant.project === project.slug).map((grant) => ({
77
+ id: grant.id,
78
+ principalType,
79
+ principalId,
80
+ role: grant.role,
81
+ roleName: grant.roleName,
82
+ permissions: grant.permissions,
83
+ scope: grant.environment === null ? 'project' : 'environment',
84
+ environmentSlug: grant.environment,
85
+ expiresAt: grant.expiresAt,
86
+ })),
87
+ grantsError: error,
88
+ })),
89
+ };
77
90
  }
78
91
 
79
92
  /**
@@ -87,6 +100,9 @@ export function PrincipalLayout({ principalType, principalId }: { principalType:
87
100
  const mounted = useMounted();
88
101
  const { capabilities } = shell;
89
102
  const report = useReport(principalType, principalId);
103
+ // A service account you manage, though you do not run the instance: what it holds, from its access.
104
+ const { data: held } = useSuspenseQuery(queries.memberAccess(useCoffre(), memberRef(principalType, principalId), listsAccess(shell)));
105
+ const yours = principalType === 'service' && held?.ok === true && held.managed;
90
106
  // A role change or removal made from this page's menu, refused.
91
107
  const { status, dismiss } = useChangeStatus(directoryList.queryKey);
92
108
  const change = status(memberRef(principalType, principalId));
@@ -100,16 +116,20 @@ export function PrincipalLayout({ principalType, principalId }: { principalType:
100
116
  principalType,
101
117
  principalId,
102
118
  instanceRole: found.instanceRole,
119
+ scope: found.scope,
103
120
  isRootAdmin: found.isRootAdmin,
104
121
  tampered: found.status === 'tampered',
122
+ managed: principalType === 'service',
105
123
  }
106
- : undefined;
124
+ : yours
125
+ ? { principalType, principalId, instanceRole: 'member' as const, scope: null, isRootAdmin: false, tampered: false, managed: true }
126
+ : undefined;
107
127
 
108
128
  // Owners get a report about anyone ever registered, removed or not, so a
109
129
  // miss there means there is no such user. Everyone else only reaches this
110
- // page through projects they manage.
130
+ // page through projects they manage, or a service account they manage.
111
131
  const unknown = report?.ok === true && found === null;
112
- if (unknown || (report === null && managedProjects(shell.projects).length === 0)) {
132
+ if (unknown || (report === null && managedProjects(shell.projects).length === 0 && !yours)) {
113
133
  return (
114
134
  <ClosedDoor
115
135
  icon={people ? <Users size={18} /> : <Key size={18} />}
@@ -145,6 +165,13 @@ export function PrincipalLayout({ principalType, principalId }: { principalType:
145
165
  <Link key="access" to="/users/$user" params={{ user: principalId }} activeOptions={{ exact: true, includeSearch: false }}>
146
166
  {access}
147
167
  </Link>,
168
+ // Only an owner reads the report that lists them; removal disconnects them.
169
+ hasAppsTab(shell, report) && mounted('/users/$user/apps') && (
170
+ <Link key="apps" to="/users/$user/apps" params={{ user: principalId }}>
171
+ <LinkIcon size={15} />
172
+ Connected apps
173
+ </Link>
174
+ ),
148
175
  capabilities.canReadAudit && mounted('/users/$user/activity') && (
149
176
  <Link key="activity" to="/users/$user/activity" params={{ user: principalId }}>
150
177
  {activity}
@@ -152,7 +179,7 @@ export function PrincipalLayout({ principalType, principalId }: { principalType:
152
179
  ),
153
180
  ]
154
181
  : [
155
- signInWays(shell, report) !== null && (
182
+ signInWays(shell, held) !== null && (
156
183
  <Link key="sign-in" to="/service-accounts/$account" params={{ account: principalId }} activeOptions={{ exact: true, includeSearch: false }}>
157
184
  <LinkIcon size={15} />
158
185
  Sign-in
@@ -213,18 +240,16 @@ export function PrincipalLayout({ principalType, principalId }: { principalType:
213
240
  * its offboarding did instead.
214
241
  */
215
242
  export function PrincipalAccess({ principalType, principalId }: { principalType: PrincipalType; principalId: string }) {
216
- const { instanceRole, features } = useShell();
243
+ const { instanceRole } = useShell();
217
244
  const report = useReport(principalType, principalId);
218
- const access = useProjectAccess(principalType, principalId);
245
+ const { access: held, error, projects: access, offers } = useMemberAccess(principalType, principalId);
219
246
  const kind = KIND[principalType];
220
247
  const people = principalType === 'user';
221
248
  const found = report?.ok === true ? report.report : null;
222
249
  const removed = found?.status === 'removed';
223
250
 
224
- const rows = access.flatMap(({ project, grants }) =>
225
- grants.map((grant) => ({ project, grant })),
226
- );
227
- const errors = access.filter((entry) => entry.grantsError !== null);
251
+ // One request, so one error, said once in place of the rows (`UnreadAccess`).
252
+ const rows = accessRows(access).flatMap((row) => (row.grant === null ? [] : [row]));
228
253
  // Grants to someone removed are refused until they are added back.
229
254
  const editable = removed
230
255
  ? []
@@ -239,16 +264,12 @@ export function PrincipalAccess({ principalType, principalId }: { principalType:
239
264
  {/* Removal ends every grant, so there is no access left to show. */}
240
265
  {!removed && (
241
266
  <>
242
- {errors.map(({ project, grantsError }) => (
243
- <div key={project.slug} style={{ marginBottom: '0.75rem' }}>
244
- <Notice tone="bad">
245
- <span className="mono">{project.slug}</span>: {grantsError}
246
- </Notice>
247
- </div>
248
- ))}
267
+ {people && held !== null && <InstanceRoleNote access={held} />}
249
268
 
250
269
  <section className="card" aria-label="Project access">
251
- {rows.length === 0 ? (
270
+ {error !== null ? (
271
+ <UnreadAccess member={memberRef(principalType, principalId)} error={error} />
272
+ ) : rows.length === 0 ? (
252
273
  <EmptyState title="No project access yet">
253
274
  {editable.length > 0
254
275
  ? `Edit access gives this ${kind} access to several projects at once.`
@@ -291,21 +312,19 @@ export function PrincipalAccess({ principalType, principalId }: { principalType:
291
312
 
292
313
  {editable.length > 0 && (
293
314
  <div className="table-actions">
294
- <EditAccess principalType={principalType} principalId={principalId} access={editable} />
315
+ <EditAccess principalType={principalType} principalId={principalId} access={editable} offers={offers} />
295
316
  </div>
296
317
  )}
297
318
 
298
319
  {/* A root admin manages every project, so nothing is out of view. */}
299
320
  {instanceRole !== 'root-admin' && (
300
321
  <p className="hint section-foot">
301
- Only projects where you manage access are listed.
322
+ {held?.managed === true && principalType === 'service'
323
+ ? 'Only projects where you may give it access are listed: what you hold there, where the instance lets you.'
324
+ : 'Only projects where you manage access are listed.'}
302
325
  </p>
303
326
  )}
304
327
 
305
- <EveryProjectGrants principalType={principalType} principalId={principalId} />
306
-
307
- {/* Only an owner reads the report that lists them; removal disconnects them. */}
308
- {features.mcp && people && found !== null && <MemberApps principalId={principalId} apps={found.apps} />}
309
328
  </>
310
329
  )}
311
330
 
@@ -314,15 +333,41 @@ export function PrincipalAccess({ principalType, principalId }: { principalType:
314
333
  );
315
334
  }
316
335
 
317
- /** A person's connected apps, for an owner, who may disconnect any of them. */
318
- function MemberApps({ principalId, apps }: { principalId: string; apps: PrincipalReport['apps'] }) {
336
+ /** What a person's instance role gives them, above the grants that add to it: nothing for a Member. */
337
+ function InstanceRoleNote({ access }: { access: MemberAccess }) {
338
+ if (access.instanceRole === 'member' || access.instanceRole === 'root-admin') return null;
339
+ const { name } = INSTANCE_ROLES[access.instanceRole];
340
+ return (
341
+ <div className="report-notice">
342
+ <Notice tone="info">
343
+ <strong>{name}</strong>
344
+ {access.scope === null ? '' : unscoped(access.scope) ? ' in every project' : `: ${scopeInWords(access.scope)}`}, from their instance role. The
345
+ grants below add to it.
346
+ </Notice>
347
+ </div>
348
+ );
349
+ }
350
+
351
+ /** Their access could not be read: why, and another try, never an empty list that reads as no access. */
352
+ function UnreadAccess({ member, error }: { member: string; error: string }) {
353
+ const queryClient = useQueryClient();
354
+ const [retrying, setRetrying] = useState(false);
319
355
  return (
320
- <ConnectedAppsCard
321
- apps={apps}
322
- change={disconnectMemberApp(useCoffre(), memberRef('user', principalId))}
323
- description="AI assistants and other MCP clients they connected. Removing them disconnects every one."
324
- empty="They have connected none."
325
- />
356
+ <div className="row-failure-line unread-access">
357
+ <ErrorLine error={`Their access could not be read. ${error}`} />
358
+ <button
359
+ type="button"
360
+ className="act"
361
+ disabled={retrying}
362
+ onClick={() => {
363
+ setRetrying(true);
364
+ void queryClient.refetchQueries({ queryKey: keys.memberAccess(member) }).finally(() => setRetrying(false));
365
+ }}
366
+ >
367
+ {retrying && <Spinner size={13} />}
368
+ Retry
369
+ </button>
370
+ </div>
326
371
  );
327
372
  }
328
373
 
@@ -338,10 +383,12 @@ function EditAccess({
338
383
  principalType,
339
384
  principalId,
340
385
  access,
386
+ offers,
341
387
  }: {
342
388
  principalType: PrincipalType;
343
389
  principalId: string;
344
390
  access: ProjectAccess[];
391
+ offers: Offers;
345
392
  }) {
346
393
  const coffre = useCoffre();
347
394
  const [open, setOpen] = useState(false);
@@ -357,7 +404,10 @@ function EditAccess({
357
404
  .map((environment) => environment.slug);
358
405
  const held = planFromGrants(grants, environments);
359
406
  const plan = Object.hasOwn(edits, project.slug) ? edits[project.slug] : held;
360
- return { project, grants, environments, held, plan, changes: accessChanges(grants, plan) };
407
+ // What you may give here: every role where you manage access; a service account you manage, what you hold.
408
+ const whole = offers(project, null);
409
+ const each = Object.fromEntries(environments.map((slug) => [slug, offers(project, slug)]));
410
+ return { project, grants, environments, held, plan, whole, each, changes: accessChanges(grants, plan) };
361
411
  });
362
412
  const changed = rows.filter((row) => row.changes.length > 0);
363
413
 
@@ -382,7 +432,7 @@ function EditAccess({
382
432
  Edit access for <span className="mono">{principalId}</span>
383
433
  </>
384
434
  }
385
- description={`Set what this ${kind} can reach on each project you manage, and until when.`}
435
+ description={`Set what this ${kind} can reach on each project you ${principalType === 'service' ? 'may give it access to' : 'manage'}, and until when.`}
386
436
  wide
387
437
  >
388
438
  <form
@@ -415,7 +465,7 @@ function EditAccess({
415
465
  <span>Access</span>
416
466
  <span>Expires</span>
417
467
  </li>
418
- {rows.map(({ project, grants, environments, held, plan, changes }) => {
468
+ {rows.map(({ project, grants, environments, held, plan, whole, each, changes }) => {
419
469
  const id = `plan-${project.slug}`;
420
470
  const edit = (next: AccessPlan) =>
421
471
  setEdits((current) => ({ ...current, [project.slug]: next }));
@@ -447,10 +497,10 @@ function EditAccess({
447
497
  >
448
498
  {held.level === 'custom' && <option value="custom">Keep as is</option>}
449
499
  <option value="none">No access</option>
450
- <option value="owner">{ROLES.owner.name}</option>
451
- <option value="viewer">{ROLES.viewer.name}: all</option>
452
- <option value="developer">{ROLES.developer.name}: all</option>
453
- {environments.length > 0 && <option value="env">Per environment…</option>}
500
+ {whole.includes('owner') && <option value="owner">{ROLES.owner.name}</option>}
501
+ {whole.includes('viewer') && <option value="viewer">{ROLES.viewer.name}: all</option>}
502
+ {whole.includes('developer') && <option value="developer">{ROLES.developer.name}: all</option>}
503
+ {environments.some((slug) => each[slug]!.length > 0) && <option value="env">Per environment…</option>}
454
504
  </select>
455
505
  {(plan.level === 'owner' ||
456
506
  plan.level === 'viewer' ||
@@ -489,8 +539,8 @@ function EditAccess({
489
539
  }}
490
540
  >
491
541
  <option value="">No access</option>
492
- <option value="viewer">{ROLES.viewer.name}</option>
493
- <option value="developer">{ROLES.developer.name}</option>
542
+ {each[slug]!.includes('viewer') && <option value="viewer">{ROLES.viewer.name}</option>}
543
+ {each[slug]!.includes('developer') && <option value="developer">{ROLES.developer.name}</option>}
494
544
  </select>
495
545
  {current !== null && (
496
546
  <ExpiryField
@@ -0,0 +1,183 @@
1
+ import { useId, useState } from 'react';
2
+ import { INSTANCE_ROLE_NAMES, INSTANCE_ROLES, type Filter, type InstanceRole, type Scope } from '@coffre/core/access';
3
+ import type { RoleVars } from '../lib/changes';
4
+ import { useShell } from '../lib/use-shell';
5
+ import { slugProblem } from '../lib/validation';
6
+ import { X } from './icons';
7
+
8
+ /**
9
+ * A person's instance role, one dropdown, and under it, for every role but
10
+ * Member, where it applies: projects and environments, each All, Only or
11
+ * All except. Projects are picked from those there are; environments are
12
+ * names, so any slug goes, the ones made later too.
13
+ */
14
+ export function RoleField({ value, onChange }: { value: RoleVars; onChange: (value: RoleVars) => void }) {
15
+ const { role, scope } = value;
16
+ return (
17
+ <>
18
+ <label className="field">
19
+ <span className="label">Instance role</span>
20
+ <select
21
+ className="select"
22
+ value={role}
23
+ onChange={(event) => onChange({ role: event.target.value as InstanceRole, scope })}
24
+ >
25
+ {INSTANCE_ROLE_NAMES.map((name) => (
26
+ <option key={name} value={name}>
27
+ {INSTANCE_ROLES[name].name}
28
+ </option>
29
+ ))}
30
+ </select>
31
+ <span className="hint">
32
+ {INSTANCE_ROLES[role].description}
33
+ {role === 'member' ? '' : ' Project grants add to it.'}
34
+ </span>
35
+ </label>
36
+ {role !== 'member' && <ScopeField scope={scope} onChange={(next) => onChange({ role, scope: next })} />}
37
+ </>
38
+ );
39
+ }
40
+
41
+ /**
42
+ * Where something applies: projects and environments, each All, Only or All
43
+ * except. A role's scope, and the instance's setting of where people set
44
+ * up service accounts, which has the same shape.
45
+ */
46
+ export function ScopeField({ scope, onChange, legend = 'Where' }: { scope: Scope; onChange: (scope: Scope) => void; legend?: string }) {
47
+ const { projects } = useShell();
48
+ const slugs = [...new Set(projects.flatMap((project) => project.environments.map((environment) => environment.slug)))].sort();
49
+ return (
50
+ <fieldset className="field scope-field">
51
+ <legend className="label">{legend}</legend>
52
+ <FilterRow
53
+ label="Projects"
54
+ filter={scope.projects}
55
+ options={projects.map((project) => project.slug)}
56
+ onChange={(filter) => onChange({ ...scope, projects: filter })}
57
+ />
58
+ <FilterRow
59
+ label="Environments"
60
+ filter={scope.environments}
61
+ options={slugs}
62
+ free
63
+ onChange={(filter) => onChange({ ...scope, environments: filter })}
64
+ />
65
+ {scope.environments !== 'all' && <span className="hint">Environments match by name in every project, new ones included.</span>}
66
+ </fieldset>
67
+ );
68
+ }
69
+
70
+ type Mode = 'all' | 'only' | 'except';
71
+
72
+ const namesOf = (filter: Filter): string[] => (filter === 'all' ? [] : 'only' in filter ? filter.only : filter.except);
73
+
74
+ function filterOf(mode: Mode, names: string[]): Filter {
75
+ return mode === 'all' ? 'all' : mode === 'only' ? { only: names } : { except: names };
76
+ }
77
+
78
+ /** One filter: All, Only or All except, and the names it lists. */
79
+ function FilterRow({
80
+ label,
81
+ filter,
82
+ options,
83
+ free = false,
84
+ onChange,
85
+ }: {
86
+ label: string;
87
+ filter: Filter;
88
+ options: string[];
89
+ /** Whether a name need not be among `options`: an environment's slug, which may come later. */
90
+ free?: boolean;
91
+ onChange: (filter: Filter) => void;
92
+ }) {
93
+ const mode: Mode = filter === 'all' ? 'all' : 'only' in filter ? 'only' : 'except';
94
+ const names = namesOf(filter);
95
+ return (
96
+ <div className="scope-row">
97
+ <span className="scope-label">{label}</span>
98
+ <select
99
+ className="select select-sm"
100
+ aria-label={`${label}: which`}
101
+ value={mode}
102
+ onChange={(event) => onChange(filterOf(event.target.value as Mode, names))}
103
+ >
104
+ <option value="all">All</option>
105
+ <option value="only">Only</option>
106
+ <option value="except">All except</option>
107
+ </select>
108
+ {mode !== 'all' && (
109
+ <NamePicker label={label} names={names} options={options} free={free} onChange={(next) => onChange(filterOf(mode, next))} />
110
+ )}
111
+ </div>
112
+ );
113
+ }
114
+
115
+ /** Names as chips, and a field to add one: picked from the list, or, where any name goes, typed and entered. */
116
+ function NamePicker({
117
+ label,
118
+ names,
119
+ options,
120
+ free,
121
+ onChange,
122
+ }: {
123
+ label: string;
124
+ names: string[];
125
+ options: string[];
126
+ free: boolean;
127
+ onChange: (names: string[]) => void;
128
+ }) {
129
+ const [draft, setDraft] = useState('');
130
+ const list = useId();
131
+ const add = (raw: string) => {
132
+ const name = raw.trim();
133
+ setDraft('');
134
+ if (name === '' || names.includes(name)) return;
135
+ if (free ? slugProblem(name) !== null : !options.includes(name)) return;
136
+ onChange([...names, name]);
137
+ };
138
+ const offered = options.filter((option) => !names.includes(option));
139
+ return (
140
+ <span className="scope-names">
141
+ {names.map((name) => (
142
+ <span key={name} className="tag scope-chip">
143
+ <span className="mono">{name}</span>
144
+ <button type="button" aria-label={`Remove ${name}`} onClick={() => onChange(names.filter((other) => other !== name))}>
145
+ <X size={11} />
146
+ </button>
147
+ </span>
148
+ ))}
149
+ <input
150
+ className="input input-mono scope-input"
151
+ list={list}
152
+ value={draft}
153
+ spellCheck={false}
154
+ autoComplete="off"
155
+ placeholder={names.length === 0 ? (free ? 'dev' : 'Pick a project') : 'Add'}
156
+ aria-label={`Add to ${label}`}
157
+ aria-invalid={draft !== '' && free && slugProblem(draft.trim()) !== null}
158
+ onChange={(event) => {
159
+ // A name picked from the list goes in at once; one typed, on Enter.
160
+ if ((event.nativeEvent as InputEvent).inputType === 'insertReplacementText' || (!free && options.includes(event.target.value))) {
161
+ add(event.target.value);
162
+ } else {
163
+ setDraft(event.target.value);
164
+ }
165
+ }}
166
+ onKeyDown={(event) => {
167
+ if (event.key === 'Enter' || event.key === ',') {
168
+ event.preventDefault();
169
+ add(draft);
170
+ } else if (event.key === 'Backspace' && draft === '' && names.length > 0) {
171
+ onChange(names.slice(0, -1));
172
+ }
173
+ }}
174
+ onBlur={() => add(draft)}
175
+ />
176
+ <datalist id={list}>
177
+ {offered.map((option) => (
178
+ <option key={option} value={option} />
179
+ ))}
180
+ </datalist>
181
+ </span>
182
+ );
183
+ }
@@ -0,0 +1,73 @@
1
+ import { assignableToEnvironment, credentialScopeInWords, ROLE_NAMES, ROLES, type Role } from '@coffre/core/access';
2
+
3
+ /** A grant of the account's, as its Access tab lists it. */
4
+ export type HeldGrant = { project: string; environment: string | null; role: Role };
5
+
6
+ /** A token's or a binding's scope, by path: what the API takes and lists. */
7
+ export type ScopeByPath = Record<string, Role>;
8
+
9
+ const pathOf = (grant: HeldGrant) => (grant.environment === null ? grant.project : `${grant.project}/${grant.environment}`);
10
+
11
+ /** Everything the account holds, each grant as it is: what a new token or binding reaches unless narrowed. */
12
+ export function wholeScope(grants: readonly HeldGrant[]): ScopeByPath {
13
+ return Object.fromEntries(grants.map((grant) => [pathOf(grant), grant.role]));
14
+ }
15
+
16
+ /** The roles a credential may hold where its account holds `grant`: those it holds all of, and that the place takes. */
17
+ function within(grant: HeldGrant): Role[] {
18
+ const held: readonly string[] = ROLES[grant.role].permissions;
19
+ return ROLE_NAMES.filter(
20
+ (role) => (grant.environment === null || assignableToEnvironment(role)) && ROLES[role].permissions.every((permission) => held.includes(permission)),
21
+ );
22
+ }
23
+
24
+ /**
25
+ * What a new token or trust binding reaches: each of its account's grants,
26
+ * kept or left out, at its role or a smaller one. Nothing the account is
27
+ * given later reaches it, and it never changes after.
28
+ */
29
+ export function ScopePicker({ grants, value, onChange }: { grants: readonly HeldGrant[]; value: ScopeByPath; onChange: (scope: ScopeByPath) => void }) {
30
+ if (grants.length === 0) {
31
+ return <p className="hint">The account holds nothing yet: give it a grant first, since nothing it is given later reaches a token or binding made before.</p>;
32
+ }
33
+ const set = (path: string, role: Role | null) => {
34
+ const { [path]: _, ...rest } = value;
35
+ // In the account's order, as its Access tab lists them.
36
+ const next: ScopeByPath = role === null ? rest : { ...rest, [path]: role };
37
+ onChange(Object.fromEntries(grants.map(pathOf).flatMap((each) => (next[each] === undefined ? [] : [[each, next[each]!]]))));
38
+ };
39
+ return (
40
+ <fieldset className="field checks">
41
+ <legend className="label">Reaches</legend>
42
+ {grants.map((grant) => {
43
+ const path = pathOf(grant);
44
+ const chosen = value[path];
45
+ return (
46
+ <div key={path} className="form-row">
47
+ <label className="check mono">
48
+ <input type="checkbox" checked={chosen !== undefined} onChange={(event) => set(path, event.target.checked ? grant.role : null)} />
49
+ {path}
50
+ </label>
51
+ <select
52
+ className="select"
53
+ aria-label={`Role on ${path}`}
54
+ value={chosen ?? grant.role}
55
+ disabled={chosen === undefined}
56
+ onChange={(event) => set(path, event.target.value as Role)}
57
+ >
58
+ {within(grant).map((role) => (
59
+ <option key={role} value={role}>
60
+ {ROLES[role].name}
61
+ </option>
62
+ ))}
63
+ </select>
64
+ </div>
65
+ );
66
+ })}
67
+ <span className="hint">
68
+ {Object.keys(value).length === 0 ? 'Choose at least one.' : `${credentialScopeInWords(value)}.`} At most what the account holds; nothing it is given
69
+ later reaches it, and to change it, make another and remove this one.
70
+ </span>
71
+ </fieldset>
72
+ );
73
+ }