@coffre/ui 0.6.1 → 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 (119) hide show
  1. package/dist/chunks/{audit-sentence-CUUMshIp.js → audit-sentence-C1_gRxWW.js} +91 -26
  2. package/dist/chunks/audit-sentence-C1_gRxWW.js.map +1 -0
  3. package/dist/chunks/{connected-apps-DTpatjge.js → connected-apps-Bn5rEoV2.js} +4 -4
  4. package/dist/chunks/{connected-apps-DTpatjge.js.map → connected-apps-Bn5rEoV2.js.map} +1 -1
  5. package/dist/chunks/{delete-place-SOOYVt6A.js → delete-place-CQCDHkne.js} +4 -4
  6. package/dist/chunks/{delete-place-SOOYVt6A.js.map → delete-place-CQCDHkne.js.map} +1 -1
  7. package/dist/chunks/{directory-DrtdKny2.js → directory-BQNOdze_.js} +22 -19
  8. package/dist/chunks/directory-BQNOdze_.js.map +1 -0
  9. package/dist/chunks/{folders-hR2Lnk0k.js → folders-Dw240WMJ.js} +2 -2
  10. package/dist/chunks/{folders-hR2Lnk0k.js.map → folders-Dw240WMJ.js.map} +1 -1
  11. package/dist/chunks/{grants-DDBui9YD.js → grants-CJIBrkod.js} +5 -5
  12. package/dist/chunks/{grants-DDBui9YD.js.map → grants-CJIBrkod.js.map} +1 -1
  13. package/dist/chunks/multi-combobox-CsIXihuc.js +99 -0
  14. package/dist/chunks/multi-combobox-CsIXihuc.js.map +1 -0
  15. package/dist/chunks/{offboarding-C7ECW5o0.js → offboarding-CrgwaetA.js} +4 -4
  16. package/dist/chunks/offboarding-CrgwaetA.js.map +1 -0
  17. package/dist/chunks/personal-tokens-B8rkT-DI.js +138 -0
  18. package/dist/chunks/personal-tokens-B8rkT-DI.js.map +1 -0
  19. package/dist/chunks/{principal-page-CB6dAABC.js → principal-page-DDmmV1KQ.js} +37 -27
  20. package/dist/chunks/principal-page-DDmmV1KQ.js.map +1 -0
  21. package/dist/chunks/{project-page-BHNUvr2L.js → project-page-BI--vjt3.js} +2 -2
  22. package/dist/chunks/{project-page-BHNUvr2L.js.map → project-page-BI--vjt3.js.map} +1 -1
  23. package/dist/chunks/{queries-DgQo3mC-.js → queries-epz4MIuW.js} +103 -18
  24. package/dist/chunks/queries-epz4MIuW.js.map +1 -0
  25. package/dist/chunks/{references-BQc35Q9g.js → references-DImfw0cz.js} +4 -4
  26. package/dist/chunks/{references-BQc35Q9g.js.map → references-DImfw0cz.js.map} +1 -1
  27. package/dist/chunks/{role-field-BfWRCqzl.js → role-field-C1KhNaIR.js} +2 -2
  28. package/dist/chunks/{role-field-BfWRCqzl.js.map → role-field-C1KhNaIR.js.map} +1 -1
  29. package/dist/chunks/{row-state-Zf3kZVhd.js → row-state-BsIHspy4.js} +2 -2
  30. package/dist/chunks/{row-state-Zf3kZVhd.js.map → row-state-BsIHspy4.js.map} +1 -1
  31. package/dist/chunks/{theme-B6-V9JvY.js → theme-3b4DnCow.js} +2 -2
  32. package/dist/chunks/{theme-B6-V9JvY.js.map → theme-3b4DnCow.js.map} +1 -1
  33. package/dist/chunks/{ui-Br-dNUTc.js → ui-2kwXXfrX.js} +95 -22
  34. package/dist/chunks/ui-2kwXXfrX.js.map +1 -0
  35. package/dist/chunks/{use-action-DthL5hL8.js → use-action-BB-RcHo1.js} +2 -2
  36. package/dist/chunks/{use-action-DthL5hL8.js.map → use-action-BB-RcHo1.js.map} +1 -1
  37. package/dist/chunks/{use-change-By4cG8bT.js → use-change-CQyDpCqw.js} +323 -31
  38. package/dist/chunks/use-change-CQyDpCqw.js.map +1 -0
  39. package/dist/chunks/{use-shell-D6kjSPls.js → use-shell-C_NmvCt_.js} +2 -2
  40. package/dist/chunks/{use-shell-D6kjSPls.js.map → use-shell-C_NmvCt_.js.map} +1 -1
  41. package/dist/index.d.ts +46 -164
  42. package/dist/index.js +143 -129
  43. package/dist/index.js.map +1 -1
  44. package/dist/pages/account.d.ts +1 -1
  45. package/dist/pages/account.js +29 -12
  46. package/dist/pages/account.js.map +1 -1
  47. package/dist/pages/approval.js +1 -1
  48. package/dist/pages/audit.js +96 -90
  49. package/dist/pages/audit.js.map +1 -1
  50. package/dist/pages/device-login.js +1 -1
  51. package/dist/pages/environment.js +949 -412
  52. package/dist/pages/environment.js.map +1 -1
  53. package/dist/pages/login.js +2 -2
  54. package/dist/pages/oauth-authorize.js +1 -1
  55. package/dist/pages/project-access.js +9 -9
  56. package/dist/pages/project-access.js.map +1 -1
  57. package/dist/pages/project-environments.js +112 -64
  58. package/dist/pages/project-environments.js.map +1 -1
  59. package/dist/pages/project-settings.d.ts +1 -1
  60. package/dist/pages/project-settings.js +54 -75
  61. package/dist/pages/project-settings.js.map +1 -1
  62. package/dist/pages/project.js +3 -7
  63. package/dist/pages/project.js.map +1 -1
  64. package/dist/pages/projects.js +50 -77
  65. package/dist/pages/projects.js.map +1 -1
  66. package/dist/pages/service-account.js +284 -160
  67. package/dist/pages/service-account.js.map +1 -1
  68. package/dist/pages/service-accounts.js +4 -4
  69. package/dist/pages/settings.js +5 -5
  70. package/dist/pages/unregistered.js +1 -1
  71. package/dist/pages/user.js +5 -5
  72. package/dist/pages/users.js +4 -4
  73. package/package.json +3 -3
  74. package/src/components/actions-log.tsx +3 -2
  75. package/src/components/command-palette.tsx +4 -5
  76. package/src/components/directory.tsx +7 -14
  77. package/src/components/generate-value.tsx +15 -7
  78. package/src/components/missing.tsx +63 -67
  79. package/src/components/offboarding.tsx +1 -1
  80. package/src/components/personal-tokens.tsx +131 -0
  81. package/src/components/principal-page.tsx +30 -17
  82. package/src/components/regenerate.tsx +72 -0
  83. package/src/components/service-tokens.tsx +5 -14
  84. package/src/components/shell.tsx +79 -75
  85. package/src/components/trusted-workloads.tsx +179 -19
  86. package/src/components/ui.tsx +35 -25
  87. package/src/lib/audit-sentences.ts +100 -12
  88. package/src/lib/bindings.ts +41 -3
  89. package/src/lib/changes.ts +215 -29
  90. package/src/lib/clipboard.ts +40 -0
  91. package/src/lib/copy-attempts.ts +103 -0
  92. package/src/lib/dismissal.ts +24 -0
  93. package/src/lib/generate.ts +3 -146
  94. package/src/lib/optimistic.ts +3 -1
  95. package/src/lib/queries.ts +121 -17
  96. package/src/lib/recipes.ts +63 -0
  97. package/src/lib/reveal.ts +7 -1
  98. package/src/lib/row-reads.ts +64 -0
  99. package/src/lib/secret-edit-batch.ts +64 -5
  100. package/src/options.ts +43 -51
  101. package/src/pages/account.tsx +27 -5
  102. package/src/pages/audit.tsx +38 -31
  103. package/src/pages/environment.tsx +655 -121
  104. package/src/pages/project-access.tsx +1 -1
  105. package/src/pages/project-environments.tsx +92 -45
  106. package/src/pages/project-settings.tsx +9 -20
  107. package/src/pages/project.tsx +1 -5
  108. package/src/pages/projects.tsx +13 -28
  109. package/src/parity.ts +20 -4
  110. package/src/styles/globals.css +143 -131
  111. package/dist/chunks/audit-sentence-CUUMshIp.js.map +0 -1
  112. package/dist/chunks/directory-DrtdKny2.js.map +0 -1
  113. package/dist/chunks/offboarding-C7ECW5o0.js.map +0 -1
  114. package/dist/chunks/principal-page-CB6dAABC.js.map +0 -1
  115. package/dist/chunks/project-environments-lEzFHUt4.js +0 -11
  116. package/dist/chunks/project-environments-lEzFHUt4.js.map +0 -1
  117. package/dist/chunks/queries-DgQo3mC-.js.map +0 -1
  118. package/dist/chunks/ui-Br-dNUTc.js.map +0 -1
  119. package/dist/chunks/use-change-By4cG8bT.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import type { CoffreClient, ConnectedApp, IdentityRow, OffboardingReport, SecretKey, SessionRow } from '@coffre/client';
1
+ import type { CoffreClient, ConnectedApp, IdentityRow, MissingKey, OffboardingReport, SecretKey, SessionRow, TokenRow } from '@coffre/client';
2
2
  import { EVERYWHERE, unscoped, type InstanceRole, type Role, type Scope } from '@coffre/core/access';
3
3
  import type { QueryKey } from '@tanstack/react-query';
4
4
 
@@ -6,7 +6,9 @@ import { failureMessage, memberRef, Refusal } from './coffre.ts';
6
6
  import { projectAccessLabel } from './project-access.ts';
7
7
  import type { Change, ListShape, Target, Words } from './optimistic.ts';
8
8
  import { affects, keys } from './queries.ts';
9
- import { applySecretEditBatch, companionsOf, type SecretChange, type SecretDraft, type SecretEditBatchResult } from './secret-edit-batch.ts';
9
+ import { regenerateWrite, type Generation } from '@coffre/core/recipe';
10
+ import { regeneratedKeys, renamePairs } from './recipes.ts';
11
+ import { applySecretEditBatch, companionsOf, generationsOf, type SecretChange, type SecretDraft, type SecretEditBatchResult } from './secret-edit-batch.ts';
10
12
  import type { DirectoryPrincipal, GrantRow, ProjectSummary } from '../shared/models.ts';
11
13
 
12
14
  /**
@@ -34,6 +36,8 @@ function listOf<TItem, TData extends { ok: boolean } | null>(
34
36
  const ARCHIVING: Words = { pending: 'Archiving…', done: 'archived', failed: 'Not archived.' };
35
37
  const REVOKING: Words = { pending: 'Revoking…', done: 'revoked', failed: 'Not revoked.' };
36
38
  const DISCONNECTING: Words = { pending: 'Disconnecting…', done: 'disconnected', failed: 'Not disconnected.' };
39
+ const MOVING: Words = { pending: 'Moving…', done: 'moved', failed: 'Not moved.' };
40
+ const REGENERATING: Words = { pending: 'Regenerating…', done: 'regenerated', failed: 'Not regenerated.' };
37
41
 
38
42
  const saving = (id: string): Target => ({ id, kind: 'saving' });
39
43
  const removing = (id: string): Target => ({ id, kind: 'removing' });
@@ -98,7 +102,7 @@ export function grantAccess(client: CoffreClient, project: string): Change<Grant
98
102
  },
99
103
  affects: (vars) => [
100
104
  ...affects.access(project, memberRef(vars.principalType, vars.principalId)),
101
- ...(vars.admit === true ? affects.admission() : []),
105
+ ...(vars.admit === true ? affects.admission(memberRef(vars.principalType, vars.principalId)) : []),
102
106
  ],
103
107
  run: async (vars) => {
104
108
  const place = grantPlace(project, vars.environmentSlug);
@@ -161,7 +165,7 @@ export function invite(client: CoffreClient): Change<Directory, DirectoryPrincip
161
165
  scope: vars.principalType === 'user' ? vars.scope : EVERYWHERE,
162
166
  },
163
167
  ],
164
- affects: () => affects.admission(),
168
+ affects: (vars) => affects.admission(principalId(vars)),
165
169
  run: async (vars) => {
166
170
  // Adding is an idempotent PUT that would also set the role of someone
167
171
  // already here; this is only for someone new.
@@ -200,13 +204,12 @@ export function removeMember(client: CoffreClient): Change<Directory, DirectoryP
200
204
 
201
205
  // --- credentials, sessions, linked accounts --------------------------------------
202
206
 
203
- type Credential = { id: string; hint: string };
204
- type Credentials = ({ ok: true; tokens: Credential[] } | Failure) | null;
207
+ type Credentials = ({ ok: true; tokens: TokenRow[] } | Failure) | null;
205
208
 
206
- export function revokeCredential(client: CoffreClient, serviceId: string): Change<Credentials, Credential, Credential, unknown> {
207
- const member = memberRef('service', serviceId);
209
+ /** Revoking a member's token: a service account's bearer token, on its page, or a personal token of your own, on your account. */
210
+ export function revokeCredential(client: CoffreClient, member: string): Change<Credentials, TokenRow, TokenRow, unknown> {
208
211
  return {
209
- list: listOf<Credential, Credentials>([...keys.credentials(member), { allowed: true }], 'tokens', (token) => token.id),
212
+ list: listOf<TokenRow, Credentials>([...keys.credentials(member), { allowed: true }], 'tokens', (token) => token.id),
210
213
  label: (token) => `token ${token.hint}`,
211
214
  targets: (token) => [removing(token.id)],
212
215
  removing: REVOKING,
@@ -259,6 +262,24 @@ export function disconnectApp(client: CoffreClient): Change<Apps, ConnectedApp,
259
262
 
260
263
  type Report = { ok: true; report: OffboardingReport | null } | Failure | null;
261
264
 
265
+ /** Whoever runs the instance revoking someone's personal token, on their page: their report lists it, as they read it. */
266
+ export function revokeMemberToken(client: CoffreClient, member: string): Change<Report, TokenRow, TokenRow, unknown> {
267
+ return {
268
+ list: {
269
+ queryKey: [...keys.report(member), { owner: true }],
270
+ items: (data) => (data?.ok === true ? (data.report?.personalTokens ?? []) : []),
271
+ withItems: (data, personalTokens) => (data?.ok === true && data.report !== null ? { ...data, report: { ...data.report, personalTokens } } : data),
272
+ id: (token) => token.id,
273
+ },
274
+ label: (token) => `token ${token.hint}`,
275
+ targets: (token) => [removing(token.id)],
276
+ removing: REVOKING,
277
+ // Their report counts what removing them would end; the list on their account is theirs to read again.
278
+ affects: () => [keys.report(member), keys.credentials(member)],
279
+ run: (token) => client.tokens.revoke(member, token.id),
280
+ };
281
+ }
282
+
262
283
  /** An owner disconnecting someone's app, on their page: their report lists it, as the owner reads it. */
263
284
  export function disconnectMemberApp(client: CoffreClient, member: string): Change<Report, ConnectedApp, ConnectedApp, unknown> {
264
285
  return {
@@ -296,7 +317,7 @@ type Projects = ({ ok: true; projects: ProjectSummary[] } | Failure);
296
317
 
297
318
  export const projectsList = listOf<ProjectSummary, Projects>(keys.projects, 'projects', (project) => project.slug);
298
319
 
299
- export function createProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string; name: string }, void> {
320
+ export function createProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string }, void> {
300
321
  return {
301
322
  list: projectsList,
302
323
  label: (vars) => `project ${vars.slug}`,
@@ -305,7 +326,7 @@ export function createProject(client: CoffreClient): Change<Projects, ProjectSum
305
326
  ...projects,
306
327
  {
307
328
  slug: vars.slug,
308
- name: vars.name,
329
+ name: vars.slug,
309
330
  archivedAt: null,
310
331
  folder: null,
311
332
  // Its maker manages it by their instance role, an Admin's or an Owner's.
@@ -317,7 +338,7 @@ export function createProject(client: CoffreClient): Change<Projects, ProjectSum
317
338
  affects: () => affects.places(),
318
339
  run: async (vars) => {
319
340
  // Creating is an idempotent PUT; a slug that is taken is refused here.
320
- const { created } = await client.projects.create(vars.slug, { name: vars.name });
341
+ const { created } = await client.projects.create(vars.slug);
321
342
  if (!created) throw new Refusal(`A project named "${vars.slug}" already exists.`);
322
343
  },
323
344
  };
@@ -358,28 +379,28 @@ export function environmentId(project: string, environment: string): string {
358
379
  }
359
380
 
360
381
  /** A new environment, empty or, `from` a sibling, forked: each of its keys copied. */
361
- export function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; name: string; from?: string; references?: boolean }, void> {
382
+ export function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; from?: string; references?: boolean; inherit?: boolean }, void> {
362
383
  return {
363
384
  list: environmentsList(project),
364
385
  label: (vars) => `environment ${vars.slug}`,
365
386
  targets: (vars) => [saving(environmentId(project, vars.slug))],
366
387
  apply: (environments, vars) => [
367
388
  ...environments,
368
- { slug: vars.slug, name: vars.name, accessible: false, details: { archivedAt: null, secretCount: 0 } },
389
+ { slug: vars.slug, name: vars.slug, accessible: false, parent: vars.inherit === true ? (vars.from ?? null) : null, personal: false, details: { archivedAt: null, secretCount: 0 } },
369
390
  ],
370
391
  affects: () => affects.places(),
371
392
  run: async (vars) => {
372
393
  const { created } = await client.environments.create(`${project}/${vars.slug}`, {
373
- name: vars.name,
374
394
  ...(vars.from === undefined ? {} : { from: vars.from }),
375
395
  ...(vars.references === true ? { references: true } : {}),
396
+ ...(vars.inherit === true ? { inherit: true } : {}),
376
397
  });
377
398
  if (!created) throw new Refusal(`An environment named "${vars.slug}" already exists.`);
378
399
  },
379
400
  };
380
401
  }
381
402
 
382
- export type RenameVars = { from: string; slug: string; name: string };
403
+ export type RenameVars = { from: string; slug: string };
383
404
 
384
405
  export function renameEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, RenameVars, unknown> {
385
406
  return {
@@ -391,10 +412,10 @@ export function renameEnvironment(client: CoffreClient, project: string): Change
391
412
  : [saving(environmentId(project, vars.from)), saving(environmentId(project, vars.slug))],
392
413
  apply: (environments, vars) =>
393
414
  environments.map((environment) =>
394
- environment.slug === vars.from ? { ...environment, slug: vars.slug, name: vars.name } : environment,
415
+ environment.slug === vars.from ? { ...environment, slug: vars.slug } : environment,
395
416
  ),
396
417
  affects: () => affects.places(),
397
- run: (vars) => client.environments.update(`${project}/${vars.from}`, { slug: vars.slug, name: vars.name }),
418
+ run: (vars) => client.environments.update(`${project}/${vars.from}`, { slug: vars.slug }),
398
419
  };
399
420
  }
400
421
 
@@ -497,23 +518,37 @@ export function saveSecrets(
497
518
  removing: ARCHIVING,
498
519
  apply: (entries, vars) => {
499
520
  const now = new Date().toISOString();
500
- const bumped = (entry: SecretKey | undefined, key: string): SecretKey => ({
501
- key,
502
- // A rename keeps its folder; a new secret is in none.
503
- folder: entry?.folder ?? null,
504
- // A value of its own: no longer a reference.
505
- reference: null,
506
- archived: false,
507
- version: (entry?.version ?? 0) + 1,
508
- updatedAt: now,
509
- updatedBy: author,
510
- });
521
+ // A value typed by hand has no recipe; a generated one has the one it was made by.
522
+ const generations = generationsOf(vars.active, vars.drafts, vars.changes);
523
+ const bumped = (entry: SecretKey | undefined, key: string): SecretKey => {
524
+ // In a fork, a value written over the parent's is an override, whose own version the list read back says.
525
+ const inherited = entry?.parent != null && entry.parent.state !== 'overridden' && entry.key === key;
526
+ return {
527
+ key,
528
+ // A rename keeps its folder; a new secret is in none.
529
+ folder: entry?.folder ?? null,
530
+ // A value of its own: no longer a reference.
531
+ reference: null,
532
+ archived: false,
533
+ version: inherited ? null : (entry?.version ?? 0) + 1,
534
+ // Known once the list is read back: until then, nothing regenerates it.
535
+ versionId: null,
536
+ updatedAt: now,
537
+ updatedBy: author,
538
+ generated: generations.get(key) ?? null,
539
+ parent: entry?.parent == null || entry.key !== key ? null : { ...entry.parent, state: 'overridden', changed: false, reset: false },
540
+ };
541
+ };
542
+ const renames = new Map<string, string>();
511
543
  let next = entries.map((entry) => {
512
544
  const change = vars.changes[entry.key];
513
545
  if (change === undefined || change.archived) return entry;
514
546
  const key = change.key.trim();
547
+ if (key !== entry.key) renames.set(entry.key, key);
515
548
  return change.value === null ? { ...entry, key } : bumped(entry, key);
516
549
  });
550
+ // A rename moves no value: a pair it touches names the new key, in both halves.
551
+ next = renamePairs(next, renames);
517
552
  for (const draft of written(vars)) {
518
553
  const key = draft.key.trim();
519
554
  const existing = next.find((entry) => entry.key === key);
@@ -560,6 +595,7 @@ export function moveSecret(
560
595
  ): Change<Secrets, SecretKey, { key: string; folder: string | null }, unknown> {
561
596
  return {
562
597
  list: secretsList(place),
598
+ saving: MOVING,
563
599
  label: (vars) => vars.key,
564
600
  targets: (vars) => [saving(vars.key)],
565
601
  apply: (entries, vars) => entries.map((entry) => (entry.key === vars.key ? { ...entry, folder: vars.folder } : entry)),
@@ -568,6 +604,54 @@ export function moveSecret(
568
604
  };
569
605
  }
570
606
 
607
+ /** What Regenerate is asked: the key, its recipe, and the version id of each key it writes, as listed. */
608
+ export type RegenerateVars = { key: string; generated: Generation; versions: Readonly<Record<string, string>> };
609
+
610
+ /**
611
+ * Regenerate a key by its recipe: the value made in this browser as the
612
+ * change runs, and sent at once, never on the page. Each key it writes, a
613
+ * key pair's two halves, shows it pending, so neither is edited, renamed
614
+ * or regenerated again until it lands. The server holds it to the versions
615
+ * listed, which settles a race with any other write.
616
+ */
617
+ export function regenerateSecret(
618
+ client: CoffreClient,
619
+ place: { project: string; environment: string },
620
+ /** Who is regenerating, shown as the author until the list is read back. */
621
+ author: string | null,
622
+ ): Change<Secrets, SecretKey, RegenerateVars, unknown> {
623
+ const path = `${place.project}/${place.environment}`;
624
+ return {
625
+ list: secretsList(place),
626
+ saving: REGENERATING,
627
+ label: (vars) => regeneratedKeys(vars.key, vars.generated).join(' and '),
628
+ targets: (vars) => regeneratedKeys(vars.key, vars.generated).map(saving),
629
+ apply: (entries, vars) => {
630
+ const keys = new Set(regeneratedKeys(vars.key, vars.generated));
631
+ const now = new Date().toISOString();
632
+ return entries.map((entry) => {
633
+ if (!keys.has(entry.key)) return entry;
634
+ // In a fork, regenerating a key it inherits writes an override here, never the parent:
635
+ // its own version is the one the list read back says.
636
+ const inherited = entry.parent != null && entry.parent.state !== 'overridden';
637
+ return {
638
+ ...entry,
639
+ reference: null,
640
+ version: inherited ? null : (entry.version ?? 0) + 1,
641
+ versionId: null,
642
+ updatedAt: now,
643
+ updatedBy: author,
644
+ generated: vars.generated,
645
+ parent: entry.parent == null ? null : { ...entry.parent, state: 'overridden', changed: false, reset: false },
646
+ };
647
+ });
648
+ },
649
+ affects: () => affects.secrets(place),
650
+ // Each key replaces the version the page listed, or the server refuses the write.
651
+ run: async (vars) => client.secrets.set(path, await regenerateWrite(vars.key, vars.generated, (key) => (Object.hasOwn(vars.versions, key) ? vars.versions[key]! : null))),
652
+ };
653
+ }
654
+
571
655
  /** Restore an archived secret, from the Archived list. */
572
656
  export function restoreSecret(
573
657
  client: CoffreClient,
@@ -599,3 +683,105 @@ export function archiveSecret(
599
683
  run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: true }),
600
684
  };
601
685
  }
686
+
687
+ /**
688
+ * In a fork, a key's standing to its parent's (docs/design/forking.md):
689
+ * `remove` does without the parent's key and `restore` inherits it again,
690
+ * a dismissal and its end; `reset` drops an override for the parent's
691
+ * value, its own kept, and `override` serves its own again. Each shows at
692
+ * once, and is undone by its opposite.
693
+ */
694
+ export type ForkAction = 'remove' | 'restore' | 'reset' | 'override';
695
+
696
+ const FORK_WORDS: Record<ForkAction, Words> = {
697
+ remove: { pending: 'Removing…', done: 'removed', failed: 'Not removed.' },
698
+ restore: { pending: 'Restoring…', done: 'restored', failed: 'Not restored.' },
699
+ reset: { pending: 'Resetting…', done: 'reset', failed: 'Not reset.' },
700
+ override: { pending: 'Overriding…', done: 'overridden', failed: 'Not overridden.' },
701
+ };
702
+
703
+ export function forkKey(
704
+ client: CoffreClient,
705
+ place: { project: string; environment: string },
706
+ action: ForkAction,
707
+ ): Change<Secrets, SecretKey, { key: string }, unknown> {
708
+ const path = `${place.project}/${place.environment}`;
709
+ const standing = (entry: SecretKey): SecretKey => {
710
+ if (entry.parent === null) return entry;
711
+ switch (action) {
712
+ // Not served: nothing of the parent's value is shown for it.
713
+ case 'remove':
714
+ return { ...entry, reference: null, version: null, updatedAt: null, updatedBy: null, parent: { ...entry.parent, state: 'removed' } };
715
+ // The parent's value, which the list read back brings.
716
+ case 'restore':
717
+ case 'reset':
718
+ return { ...entry, parent: { ...entry.parent, state: 'inherited', changed: false, reset: action === 'reset' || entry.parent.reset } };
719
+ case 'override':
720
+ return { ...entry, parent: { ...entry.parent, state: 'overridden', changed: false, reset: false } };
721
+ }
722
+ };
723
+ return {
724
+ list: secretsList(place),
725
+ saving: FORK_WORDS[action],
726
+ label: (vars) => vars.key,
727
+ targets: (vars) => [saving(vars.key)],
728
+ // A removal of a key the parent archived since, restored, leaves nothing to list.
729
+ apply: (entries, vars) => entries.flatMap((entry) =>
730
+ entry.key !== vars.key ? [entry] : action === 'restore' && entry.parent?.held === false ? [] : [standing(entry)]),
731
+ affects: () => affects.secrets(place),
732
+ run: (vars) =>
733
+ action === 'remove' || action === 'restore'
734
+ ? client.environments.dismiss(path, { [vars.key]: action === 'remove' ? true : null })
735
+ : client.secrets.inherit(`${path}/${vars.key}`, action === 'reset'),
736
+ };
737
+ }
738
+
739
+ // --- missing keys ----------------------------------------------------------------
740
+
741
+ type Missing = ({ ok: true; missing: MissingKey[] } | Failure);
742
+
743
+ export function missingList(place: { project: string; environment: string }) {
744
+ return listOf<MissingKey, Missing>(keys.missing(place), 'missing', (entry) => entry.key);
745
+ }
746
+
747
+ const DISMISSING: Words = { pending: 'Dismissing…', done: 'dismissed', failed: 'Not dismissed.' };
748
+ const RESTORING: Words = { pending: 'Restoring…', done: 'restored', failed: 'Not restored.' };
749
+
750
+ /**
751
+ * Dismiss missing keys for the whole team. It shows at once: a dismissal
752
+ * hides nothing anyone may read, so it need not wait for the server, and a
753
+ * refusal puts the keys back.
754
+ */
755
+ export function dismissMissing(client: CoffreClient, place: { project: string; environment: string }) {
756
+ return missingChange(client, place, true);
757
+ }
758
+
759
+ /** Bring dismissed keys back, as Undo after a dismissal does: listed again at once. */
760
+ export function restoreMissing(client: CoffreClient, place: { project: string; environment: string }) {
761
+ return missingChange(client, place, false);
762
+ }
763
+
764
+ function missingChange(
765
+ client: CoffreClient,
766
+ place: { project: string; environment: string },
767
+ dismissed: boolean,
768
+ ): Change<Missing, MissingKey, MissingKey[], unknown> {
769
+ return {
770
+ list: missingList(place),
771
+ saving: dismissed ? DISMISSING : RESTORING,
772
+ label: (entries) => (entries.length === 1 ? entries[0]!.key : `${entries.length} missing keys`),
773
+ targets: (entries) => entries.map((entry) => saving(entry.key)),
774
+ apply: (entries, named) => {
775
+ const names = new Set(named.map((entry) => entry.key));
776
+ const others = entries.filter((entry) => !names.has(entry.key));
777
+ // Listed by name, as the server lists them.
778
+ return dismissed ? others : [...others, ...named].sort((a, b) => (a.key < b.key ? -1 : 1));
779
+ },
780
+ affects: () => [],
781
+ run: (entries) =>
782
+ client.environments.dismiss(
783
+ `${place.project}/${place.environment}`,
784
+ Object.fromEntries(entries.map((entry) => [entry.key, dismissed ? true : null])),
785
+ ),
786
+ };
787
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Writing to the clipboard, from text that may still be on its way.
3
+ *
4
+ * A browser lets a page write to the clipboard only inside a click's user
5
+ * gesture, and Safari drops the gesture across an `await`. So a value that has
6
+ * to be fetched first (Copy on a hidden secret) is handed over as a promise:
7
+ * `clipboard.write` is called at once, with the promise inside a
8
+ * `ClipboardItem`, and the browser waits for it. Where that is not supported,
9
+ * the text is awaited, then written with `writeText`, which is what every
10
+ * browser but Safari allows.
11
+ *
12
+ * The text goes through byte for byte: no trimming, no newline changes.
13
+ */
14
+
15
+ /** What of the clipboard `copyText` uses; the browser's `navigator.clipboard` fits. */
16
+ export type ClipboardLike = {
17
+ writeText(text: string): Promise<void>;
18
+ write?(items: unknown[]): Promise<void>;
19
+ };
20
+
21
+ type ClipboardItemConstructor = new (items: Record<string, Promise<string>>) => unknown;
22
+
23
+ export async function copyText(
24
+ text: string | Promise<string>,
25
+ {
26
+ clipboard = globalThis.navigator?.clipboard as ClipboardLike | undefined,
27
+ item = (globalThis as { ClipboardItem?: ClipboardItemConstructor }).ClipboardItem,
28
+ }: { clipboard?: ClipboardLike; item?: ClipboardItemConstructor } = {},
29
+ ): Promise<void> {
30
+ // A read that fails after the copy has ended is nobody's to hear: not an unhandled rejection.
31
+ if (typeof text !== 'string') text.catch(() => {});
32
+ if (clipboard === undefined) throw new Error('The clipboard is not available here.');
33
+ if (typeof text !== 'string' && item !== undefined && clipboard.write !== undefined) {
34
+ // Called before anything is awaited: this is what keeps the user gesture.
35
+ // The text goes in as a string, not a Blob: decoding a Blob drops a leading U+FEFF.
36
+ await clipboard.write([new item({ 'text/plain': text })]);
37
+ return;
38
+ }
39
+ await clipboard.writeText(await text);
40
+ }
@@ -0,0 +1,103 @@
1
+ import { copyText } from './clipboard.ts';
2
+
3
+ /**
4
+ * How a copy ended, as far as anyone still cares.
5
+ *
6
+ * `superseded`: a newer copy began before this one ended, so this one reports
7
+ * nothing and writes nothing. Its result, good or bad, is not what the person
8
+ * asked for last.
9
+ */
10
+ export type CopyResult = { outcome: 'copied' } | { outcome: 'failed'; failure: unknown } | { outcome: 'superseded' };
11
+
12
+ /** What a copy button shows: a copy under way, or how the last one ended, for a moment. */
13
+ export type CopyFeedback = 'idle' | 'pending' | 'copied' | 'failed';
14
+
15
+ /**
16
+ * Copies where the latest one wins, and what they look like while they run.
17
+ *
18
+ * The clipboard is one resource per page, so "latest" is decided per page: every
19
+ * copy, from any row, takes a number from one counter before it awaits anything,
20
+ * and only the newest reports, shows feedback, or writes. A copy may start while
21
+ * an earlier one is still reading or waiting on the clipboard: a retry after a
22
+ * refusal, a click on another row, a row filtered out and back, a button replaced
23
+ * by a remount. When a copy from another copier takes over, the older one drops
24
+ * its pending or "Copied" feedback and goes back to idle. A copier belongs to
25
+ * whoever outlives the button (a row); the button only subscribes to it, so a
26
+ * remount picks up where it was.
27
+ */
28
+ export type Copier = {
29
+ run(text: string | Promise<string>): Promise<CopyResult>;
30
+ feedback(): CopyFeedback;
31
+ subscribe(listener: () => void): () => void;
32
+ };
33
+
34
+ const SUPERSEDED = new Error('A newer copy began.');
35
+
36
+ /** The page's newest copy, and the copier that made it. */
37
+ let latest = 0;
38
+ let owner: { drop(): void } | null = null;
39
+
40
+ export function createCopier({
41
+ copy = copyText,
42
+ copiedMs = 1400,
43
+ failedMs = 3000,
44
+ }: { copy?: typeof copyText; copiedMs?: number; failedMs?: number } = {}): Copier {
45
+ let feedback: CopyFeedback = 'idle';
46
+ let timer: ReturnType<typeof setTimeout> | null = null;
47
+ const listeners = new Set<() => void>();
48
+
49
+ function show(next: CopyFeedback) {
50
+ if (feedback === next) return;
51
+ feedback = next;
52
+ for (const listener of listeners) listener();
53
+ }
54
+
55
+ function stopTimer() {
56
+ if (timer !== null) clearTimeout(timer);
57
+ timer = null;
58
+ }
59
+
60
+ const self = {
61
+ /** Another copier's copy took over: nothing of this one's is left showing. */
62
+ drop() {
63
+ stopTimer();
64
+ show('idle');
65
+ },
66
+ };
67
+
68
+ return {
69
+ feedback: () => feedback,
70
+ subscribe(listener) {
71
+ listeners.add(listener);
72
+ return () => void listeners.delete(listener);
73
+ },
74
+ async run(text) {
75
+ const attempt = ++latest;
76
+ if (owner !== null && owner !== self) owner.drop();
77
+ owner = self;
78
+ stopTimer();
79
+ show('pending');
80
+ // A read that finishes after a newer copy began, anywhere on the page, is
81
+ // refused here, so it never reaches the clipboard: the fallback does not
82
+ // write it, and a ClipboardItem whose payload rejects writes nothing.
83
+ const gated =
84
+ typeof text === 'string'
85
+ ? text
86
+ : text.then((value) => {
87
+ if (attempt !== latest) throw SUPERSEDED;
88
+ return value;
89
+ });
90
+ let result: CopyResult = { outcome: 'copied' };
91
+ try {
92
+ // Called before anything is awaited: the click's gesture is still live.
93
+ await copy(gated);
94
+ } catch (failure) {
95
+ result = { outcome: 'failed', failure };
96
+ }
97
+ if (attempt !== latest) return { outcome: 'superseded' };
98
+ show(result.outcome === 'copied' ? 'copied' : 'failed');
99
+ timer = setTimeout(() => show('idle'), result.outcome === 'copied' ? copiedMs : failedMs);
100
+ return result;
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,24 @@
1
+ import type { MissingKey } from '@coffre/client';
2
+ import { toast } from 'sonner';
3
+
4
+ import { failureMessage } from './coffre.ts';
5
+
6
+ /**
7
+ * Dismiss missing keys, and say so at once in a toast with Undo. A refused
8
+ * dismissal turns that toast into why it was refused, so the reason shows
9
+ * whatever the list does next: when reading it again fails too, the panel
10
+ * has no rows left to say it beneath.
11
+ */
12
+ export function dismissWithUndo(
13
+ entries: MissingKey[],
14
+ { dismiss, restore }: { dismiss: (entries: MissingKey[]) => Promise<unknown>; restore: (entries: MissingKey[]) => Promise<unknown> },
15
+ ): string | number {
16
+ const said = toast.success(entries.length === 1 ? `${entries[0]!.key} dismissed` : `${entries.length} keys dismissed`, {
17
+ action: {
18
+ label: 'Undo',
19
+ onClick: () => void restore(entries).catch((error: unknown) => toast.error(`Not restored. ${failureMessage(error)}`)),
20
+ },
21
+ });
22
+ dismiss(entries).catch((error: unknown) => toast.error(`Not dismissed. ${failureMessage(error)}`, { id: said, action: undefined }));
23
+ return said;
24
+ }