@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,139 +1,10 @@
1
1
  /**
2
- * Values the browser makes for a secret: random strings, AES keys and EC key
3
- * pairs, from Web Crypto alone.
4
- *
5
- * Nothing here talks to the server. A value made here goes into the row's
6
- * field like a typed one, and leaves the page only when that row is saved.
2
+ * What the Generate dialog checks of the names it saves a key pair under.
3
+ * The values themselves, and their recipes, are `@coffre/core/recipe`'s,
4
+ * which the CLI makes them by too.
7
5
  */
8
6
  import { secretKeyProblem } from './validation.ts';
9
7
 
10
- export type Encoding = 'base62' | 'hex' | 'base64' | 'base64url';
11
- export type AesSize = 128 | 256;
12
- export type Curve = 'P-256' | 'P-384' | 'P-521';
13
- export type PairAlgorithm = 'ECDSA' | 'ECDH';
14
-
15
- export type Recipe =
16
- | { kind: 'random'; encoding: Encoding; bytes: number }
17
- | { kind: 'aes'; size: AesSize }
18
- | { kind: 'pair'; algorithm: PairAlgorithm; curve: Curve };
19
-
20
- /** A value for the row, and for a key pair the public key, which takes a row of its own. */
21
- export type Generated = { value: string; publicKey?: string };
22
-
23
- export const MIN_BYTES = 1;
24
- export const MAX_BYTES = 256;
25
- export const DEFAULT_RECIPE: Recipe = { kind: 'random', encoding: 'base62', bytes: 32 };
26
-
27
- export const ENCODINGS: { id: Encoding; name: string }[] = [
28
- { id: 'base62', name: 'Letters and digits' },
29
- { id: 'hex', name: 'Hex' },
30
- { id: 'base64', name: 'Base64' },
31
- { id: 'base64url', name: 'Base64 URL' },
32
- ];
33
-
34
- /** Strongest first, as a new key should be. */
35
- export const PAIRS: { algorithm: PairAlgorithm; curve: Curve }[] = [
36
- { algorithm: 'ECDSA', curve: 'P-521' },
37
- { algorithm: 'ECDSA', curve: 'P-384' },
38
- { algorithm: 'ECDSA', curve: 'P-256' },
39
- { algorithm: 'ECDH', curve: 'P-521' },
40
- { algorithm: 'ECDH', curve: 'P-384' },
41
- { algorithm: 'ECDH', curve: 'P-256' },
42
- ];
43
-
44
- const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
45
- /**
46
- * The largest multiple of 62 a byte reaches: 248. A byte below it is taken
47
- * modulo 62, and each of the 62 characters has four bytes that make it. The
48
- * eight bytes from 248 up are thrown away, as taking them would make the
49
- * first eight characters a little likelier than the rest.
50
- */
51
- const BASE62_LIMIT = 256 - (256 % 62);
52
-
53
- type RandomBytes = (bytes: Uint8Array<ArrayBuffer>) => Uint8Array<ArrayBuffer>;
54
- const randomBytes: RandomBytes = (bytes) => crypto.getRandomValues(bytes);
55
-
56
- /**
57
- * How many characters carry `bytes` of entropy. Hex and base64 encode the
58
- * bytes themselves; base62 draws whole characters, each worth log2(62) bits,
59
- * so it takes as many as reach the same number of bits: 43 for 32 bytes.
60
- * Base64 pads to a multiple of four; base64 URL leaves the padding off.
61
- */
62
- export function encodedLength(encoding: Encoding, bytes: number): number {
63
- switch (encoding) {
64
- case 'hex':
65
- return bytes * 2;
66
- case 'base64':
67
- return Math.ceil(bytes / 3) * 4;
68
- case 'base64url':
69
- return Math.ceil((bytes * 8) / 6);
70
- case 'base62':
71
- return Math.ceil((bytes * 8) / Math.log2(62));
72
- }
73
- }
74
-
75
- /** `length` characters of base62, each drawn uniformly by rejecting the bytes 248 to 255. */
76
- export function base62(length: number, random: RandomBytes = randomBytes): string {
77
- let out = '';
78
- while (out.length < length) {
79
- // About 3% of bytes are rejected, so a few spare bytes almost always finish it in one draw.
80
- for (const byte of random(new Uint8Array(length - out.length + 8))) {
81
- if (byte >= BASE62_LIMIT) continue;
82
- out += BASE62[byte % 62];
83
- if (out.length === length) break;
84
- }
85
- }
86
- return out;
87
- }
88
-
89
- export function randomValue(encoding: Encoding, bytes: number, random: RandomBytes = randomBytes): string {
90
- if (encoding === 'base62') return base62(encodedLength('base62', bytes), random);
91
- const drawn = random(new Uint8Array(bytes));
92
- if (encoding === 'hex') return [...drawn].map((byte) => byte.toString(16).padStart(2, '0')).join('');
93
- const base64 = toBase64(drawn);
94
- return encoding === 'base64'
95
- ? base64
96
- : base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
97
- }
98
-
99
- export async function generate(recipe: Recipe): Promise<Generated> {
100
- switch (recipe.kind) {
101
- case 'random':
102
- return { value: randomValue(recipe.encoding, recipe.bytes) };
103
- case 'aes': {
104
- const key = await subtle().generateKey({ name: 'AES-GCM', length: recipe.size }, true, [
105
- 'encrypt',
106
- 'decrypt',
107
- ]);
108
- return { value: toBase64(await subtle().exportKey('raw', key)) };
109
- }
110
- case 'pair': {
111
- const usages: KeyUsage[] = recipe.algorithm === 'ECDSA' ? ['sign', 'verify'] : ['deriveBits'];
112
- const pair = await subtle().generateKey(
113
- { name: recipe.algorithm, namedCurve: recipe.curve },
114
- true,
115
- usages,
116
- );
117
- return {
118
- value: toBase64(await subtle().exportKey('pkcs8', pair.privateKey)),
119
- publicKey: toBase64(await subtle().exportKey('spki', pair.publicKey)),
120
- };
121
- }
122
- }
123
- }
124
-
125
- /**
126
- * The name a key pair's public key gets beside its private key's:
127
- * `JWT_PRIVATE_KEY` gives `JWT_PUBLIC_KEY`, any other name gains `_PUBLIC`.
128
- */
129
- export function publicKeyName(privateName: string): string {
130
- const name = privateName.trim();
131
- if (name === '') return '';
132
- if (/PRIVATE/.test(name)) return name.replace(/PRIVATE/g, 'PUBLIC');
133
- if (/private/.test(name)) return name.replace(/private/g, 'public');
134
- return `${name}_PUBLIC`;
135
- }
136
-
137
8
  /** What stops a key pair's two names from being saved, if anything. */
138
9
  export function pairNameProblem(privateName: string, publicName: string): string | null {
139
10
  const names = [privateName.trim(), publicName.trim()];
@@ -144,17 +15,3 @@ export function pairNameProblem(privateName: string, publicName: string): string
144
15
  }
145
16
  return names[0] === names[1] ? 'The two keys need different names.' : null;
146
17
  }
147
-
148
- /** Web Crypto's keys need a secure context: HTTPS, or the machine's own address. */
149
- function subtle(): SubtleCrypto {
150
- if (globalThis.crypto?.subtle === undefined) {
151
- throw new Error('This page is not served over HTTPS, so the browser makes no keys here.');
152
- }
153
- return globalThis.crypto.subtle;
154
- }
155
-
156
- function toBase64(bytes: ArrayBuffer | Uint8Array): string {
157
- let binary = '';
158
- for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);
159
- return btoa(binary);
160
- }
@@ -51,6 +51,8 @@ export type Change<TData, TItem, TVars, TResult> = {
51
51
  * removed ones as they are until confirmed. A rename touches both names.
52
52
  */
53
53
  targets: (vars: TVars) => Target[];
54
+ /** How saves are worded, when not as saves: dismissing. */
55
+ saving?: Words;
54
56
  /** How removals are worded, when not as removals: archiving, revoking. */
55
57
  removing?: Words;
56
58
  /** The items as they will be once the saves land; removals are left for the server. */
@@ -83,7 +85,7 @@ export function changeOptions<TData, TItem, TVars, TResult>(
83
85
  mutationFn: change.run,
84
86
  onMutate: async (vars) => {
85
87
  const targets = change.targets(vars);
86
- const words = { saving: WORDS.saving, removing: change.removing ?? WORDS.removing };
88
+ const words = { saving: change.saving ?? WORDS.saving, removing: change.removing ?? WORDS.removing };
87
89
  announce(`${change.label(vars)}: ${words[mainKind(targets)].pending}`);
88
90
  // A read already on its way would land over the change.
89
91
  await queryClient.cancelQueries({ queryKey: list.queryKey });
@@ -1,9 +1,10 @@
1
1
  import type { AuthInfo, CoffreClient, Member } from '@coffre/client';
2
2
  import { EVERYWHERE, INSTANCE_ROLES } from '@coffre/core/access';
3
- import { QueryClient, queryOptions, type QueryKey } from '@tanstack/react-query';
3
+ import { QueryClient, queryOptions, type FetchQueryOptions, type QueryKey } from '@tanstack/react-query';
4
4
 
5
5
  import { deriveUiCapabilities } from './capabilities.ts';
6
6
  import { memberRef, statusOf, uiResult } from './coffre.ts';
7
+ import { isActiveAccessibleEnvironment } from './project-environments.ts';
7
8
  import type { DirectoryPrincipal, GrantRow, Me, ProjectSummary } from '../shared/models';
8
9
 
9
10
  /**
@@ -50,6 +51,7 @@ export const keys = {
50
51
  secrets: ({ project, environment }: Place) => ['secrets', project, environment],
51
52
  references: (path: string) => ['references', path],
52
53
  missing: ({ project, environment }: Place) => ['missing', project, environment],
54
+ personal: (project: string) => ['personal', project],
53
55
  directory: ['directory'],
54
56
  report: (member: string) => ['report', member],
55
57
  memberAccess: (member: string) => ['member-access', member],
@@ -177,6 +179,13 @@ export const queries = {
177
179
  queryFn: () => uiResult(() => client.environments.missing(`${place.project}/${place.environment}`)),
178
180
  }),
179
181
 
182
+ /** A project's personal configs, for whoever manages its environments: whose, of what, and their key names. */
183
+ personal: (client: CoffreClient, project: string) =>
184
+ queryOptions({
185
+ queryKey: keys.personal(project),
186
+ queryFn: () => uiResult(() => client.environments.personal(project)),
187
+ }),
188
+
180
189
  /** The live references into and out of a place, and who reads through them, for whoever manages its access. */
181
190
  references: (client: CoffreClient, path: string) =>
182
191
  queryOptions({
@@ -393,15 +402,37 @@ export function shellOf(
393
402
 
394
403
  export type Shell = ReturnType<typeof shellOf>;
395
404
 
405
+ /**
406
+ * How a loader reads. `fresh`, a page's own reads: the cached answer within
407
+ * `FRESH_MS`, else the network's, waited for. `cached`, a tab's: its page's
408
+ * layout has read the same, so it takes the cached answer at once, however
409
+ * old, and refetches behind it, and switching tabs never waits on the
410
+ * network. A read the cache lacks is waited for either way.
411
+ */
412
+ export type Freshness = 'fresh' | 'cached';
413
+
414
+ function read<T, TKey extends QueryKey>(queryClient: QueryClient, options: FetchQueryOptions<T, Error, T, TKey>, freshness: Freshness): Promise<T> {
415
+ return freshness === 'fresh' ? queryClient.fetchQuery(options) : queryClient.ensureQueryData({ ...options, revalidateIfStale: true });
416
+ }
417
+
418
+ /**
419
+ * Whether a tab may open: from the cache, and where the cache says no, from
420
+ * the network, which a no needs before the tab sends anyone away. A stale
421
+ * no could be an account since added back, or a role since given.
422
+ */
423
+ export async function tabOpens(opens: (freshness: Freshness) => Promise<boolean>): Promise<boolean> {
424
+ return (await opens('cached')) || opens('fresh');
425
+ }
426
+
396
427
  /**
397
428
  * The shell, as every loader reads it: from the cache while fresh, so a
398
429
  * child route never asks again for what the root has.
399
430
  */
400
- export async function loadShell(queryClient: QueryClient, client: CoffreClient): Promise<Shell> {
431
+ export async function loadShell(queryClient: QueryClient, client: CoffreClient, freshness: Freshness = 'fresh'): Promise<Shell> {
401
432
  const [auth, me, projects] = await Promise.all([
402
- queryClient.fetchQuery(queries.auth(client)),
403
- queryClient.fetchQuery(queries.me(client)),
404
- queryClient.fetchQuery(queries.projects(client)),
433
+ read(queryClient, queries.auth(client), freshness),
434
+ read(queryClient, queries.me(client), freshness),
435
+ read(queryClient, queries.projects(client), freshness),
405
436
  ]);
406
437
  return shellOf(auth, me, projects);
407
438
  }
@@ -423,6 +454,33 @@ export async function loadProject(queryClient: QueryClient, client: CoffreClient
423
454
  if (found.ok && found.managesAccess) await queryClient.fetchQuery(queries.grants(client, slug));
424
455
  }
425
456
 
457
+ /**
458
+ * What an environment's page reads: its secrets and, for whoever reads them,
459
+ * the references that read them from elsewhere and the keys it lacks,
460
+ * rendered with them. Where the project tree the shell holds says you read
461
+ * it, all three are asked at once, one round trip; elsewhere the others wait
462
+ * for the secrets, so a refused visit is one refusal in the log, not three.
463
+ */
464
+ export async function loadEnvironment(queryClient: QueryClient, client: CoffreClient, place: Place) {
465
+ const others = () =>
466
+ Promise.all([
467
+ queryClient.fetchQuery(queries.references(client, `${place.project}/${place.environment}`)),
468
+ queryClient.fetchQuery(queries.missing(client, place)),
469
+ ]);
470
+ const found = projectOf(await queryClient.ensureQueryData(queries.projects(client)), place.project);
471
+ // Neither in an archived project nor archived itself: the API serves neither.
472
+ const here = found.ok && found.project.archivedAt === null
473
+ ? found.project.environments.find((environment) => environment.slug === place.environment)
474
+ : undefined;
475
+ if (here !== undefined && isActiveAccessibleEnvironment(here)) {
476
+ const [secrets] = await Promise.all([queryClient.fetchQuery(queries.secrets(client, place)), others()]);
477
+ return secrets;
478
+ }
479
+ const secrets = await queryClient.fetchQuery(queries.secrets(client, place));
480
+ if (secrets.ok) await others();
481
+ return secrets;
482
+ }
483
+
426
484
  /** The directory pages' read: the directory, for owners. */
427
485
  export async function loadDirectory(queryClient: QueryClient, client: CoffreClient) {
428
486
  const shell = await loadShell(queryClient, client);
@@ -480,9 +538,9 @@ export async function loadServiceDirectory(queryClient: QueryClient, client: Cof
480
538
  }
481
539
 
482
540
  /** Who a user or service account is to the instance, its pages' header: null to anyone who does not run it. */
483
- export async function loadMember(queryClient: QueryClient, client: CoffreClient, member: string) {
484
- const shell = await loadShell(queryClient, client);
485
- return queryClient.fetchQuery(queries.report(client, member, shell.capabilities.runsInstance));
541
+ export async function loadMember(queryClient: QueryClient, client: CoffreClient, member: string, freshness: Freshness = 'fresh') {
542
+ const shell = await loadShell(queryClient, client, freshness);
543
+ return read(queryClient, queries.report(client, member, shell.capabilities.runsInstance), freshness);
486
544
  }
487
545
 
488
546
  export type MemberReport = Awaited<ReturnType<typeof loadMember>>;
@@ -492,9 +550,42 @@ export type MemberReport = Awaited<ReturnType<typeof loadMember>>;
492
550
  * and the grants you manage, in one request, which the server answers in
493
551
  * one query, however many projects they hold grants in.
494
552
  */
495
- export async function loadAccess(queryClient: QueryClient, client: CoffreClient, member: string) {
496
- const shell = await loadShell(queryClient, client);
497
- return queryClient.fetchQuery(queries.memberAccess(client, member, listsAccess(shell)));
553
+ export async function loadAccess(queryClient: QueryClient, client: CoffreClient, member: string, freshness: Freshness = 'fresh') {
554
+ const shell = await loadShell(queryClient, client, freshness);
555
+ return read(queryClient, queries.memberAccess(client, member, listsAccess(shell)), freshness);
556
+ }
557
+
558
+ /**
559
+ * A user's or service account's page: what every tab but Activity shows,
560
+ * read once by its layout, so its tabs open at once. Who they are, what they
561
+ * hold and, for a service account, how it signs in.
562
+ */
563
+ export async function loadPrincipal(queryClient: QueryClient, client: CoffreClient, principalType: 'user' | 'service', principalId: string) {
564
+ const member = memberRef(principalType, principalId);
565
+ await Promise.all([
566
+ loadMember(queryClient, client, member),
567
+ principalType === 'service' ? loadSignIn(queryClient, client, member) : loadAccess(queryClient, client, member),
568
+ ]);
569
+ }
570
+
571
+ /**
572
+ * A service account's Sign-in tab: its bearer tokens and trust bindings, as
573
+ * far as its page shows them (`signInWays`), which it returns: null where it
574
+ * shows neither.
575
+ */
576
+ export async function loadSignIn(queryClient: QueryClient, client: CoffreClient, member: string, freshness: Freshness = 'fresh') {
577
+ const [shell, access] = await Promise.all([
578
+ loadShell(queryClient, client, freshness),
579
+ loadAccess(queryClient, client, member, freshness),
580
+ ]);
581
+ const ways = signInWays(shell, access);
582
+ if (ways !== null) {
583
+ await Promise.all([
584
+ read(queryClient, queries.credentials(client, member, ways.tokens), freshness),
585
+ read(queryClient, queries.bindings(client, member, ways.workloads), freshness),
586
+ ]);
587
+ }
588
+ return ways;
498
589
  }
499
590
 
500
591
  /**
@@ -541,10 +632,13 @@ export function managedProjects(projects: ProjectSummary[]): ProjectSummary[] {
541
632
  * change also lands in the audit log, which is always read fresh.
542
633
  */
543
634
  export const affects = {
544
- /** A project or environment made, renamed or archived: the tree, and where you hold access. */
545
- places: (): QueryKey[] => [keys.projects, keys.me],
546
- /** Secrets written, renamed, restored or archived: the environment and the counts. */
547
- secrets: (place: Place): QueryKey[] => [keys.secrets(place), keys.projects, ['references'], ['missing']],
635
+ /**
636
+ * A project or environment made, renamed or archived: the tree, where you
637
+ * hold access, and the personal configs listed of it, which go with it.
638
+ */
639
+ places: (): QueryKey[] => [keys.projects, keys.me, ['personal']],
640
+ /** Secrets written, renamed, restored or archived: the environment, the counts, and the personal configs' key names. */
641
+ secrets: (place: Place): QueryKey[] => [keys.secrets(place), keys.projects, ['references'], ['missing'], ['personal']],
548
642
  /**
549
643
  * Someone's access in a project changed: its grants, their report, and, as
550
644
  * it may be your own, what you can see.
@@ -556,8 +650,18 @@ export const affects = {
556
650
  keys.projects,
557
651
  keys.me,
558
652
  ],
559
- /** Someone let in: the directory. */
560
- admission: (): QueryKey[] => [keys.directory],
653
+ /**
654
+ * Someone let in: the directory, and whatever was read of them before
655
+ * they were there, which said there was no such member: a new service
656
+ * account's row asks how it signs in as soon as it shows.
657
+ */
658
+ admission: (member: string): QueryKey[] => [
659
+ keys.directory,
660
+ keys.report(member),
661
+ keys.memberAccess(member),
662
+ keys.credentials(member),
663
+ keys.bindings(member),
664
+ ],
561
665
  /**
562
666
  * An instance role changed: the directory, their report, and, as it may be
563
667
  * your own, what you can see and do.
@@ -0,0 +1,63 @@
1
+ import type { SecretKey } from '@coffre/client';
2
+ import type { Generation } from '@coffre/core/recipe';
3
+
4
+ /**
5
+ * A listed key's recipe, as far as the page may act on it: a key pair's
6
+ * only while the list holds both its halves, live, each saying the same of
7
+ * the pair. The server lists a pair by that rule; this holds the page to it
8
+ * between a change shown at once and the list read back, while a value
9
+ * typed over one half, or an archive, has not reached the other half yet.
10
+ */
11
+ export function liveGeneration(entry: SecretKey, entries: readonly SecretKey[]): Generation | null {
12
+ const { generated } = entry;
13
+ if (generated === null || generated.pair === undefined) return generated;
14
+ const { pair, recipe } = generated;
15
+ const holds = (key: string) =>
16
+ entries.some(
17
+ (each) =>
18
+ each.key === key &&
19
+ !each.archived &&
20
+ each.generated?.recipe === recipe &&
21
+ each.generated.pair?.private === pair.private &&
22
+ each.generated.pair.public === pair.public,
23
+ );
24
+ return holds(pair.private) && holds(pair.public) ? generated : null;
25
+ }
26
+
27
+ /**
28
+ * The list after keys were renamed, `from` to `to`: each pair names its
29
+ * halves as they are now, in both halves, as the server lists them.
30
+ */
31
+ export function renamePairs(entries: readonly SecretKey[], renames: ReadonlyMap<string, string>): SecretKey[] {
32
+ if (renames.size === 0) return [...entries];
33
+ const now = (key: string) => renames.get(key) ?? key;
34
+ return entries.map((entry) =>
35
+ entry.generated?.pair === undefined
36
+ ? entry
37
+ : {
38
+ ...entry,
39
+ generated: {
40
+ ...entry.generated,
41
+ pair: { private: now(entry.generated.pair.private), public: now(entry.generated.pair.public) },
42
+ },
43
+ },
44
+ );
45
+ }
46
+
47
+ /** The keys regenerating a key writes: itself, or a key pair's two halves. */
48
+ export function regeneratedKeys(key: string, generated: Generation): string[] {
49
+ return generated.pair === undefined ? [key] : [generated.pair.private, generated.pair.public];
50
+ }
51
+
52
+ /**
53
+ * Whether a key's Regenerate waits: while the key, or either half of its
54
+ * pair, is busy, being edited or with a save on its way. A regenerate
55
+ * addresses keys by name, so one sent beside a rename of a half could land
56
+ * on either side of it: before, and the rename fails with the old name
57
+ * holding the old private key beside a new public key; after, and it
58
+ * writes the old name again. Regenerate's own save marks every key it
59
+ * writes busy (`regenerateSecret`), so neither half is edited meanwhile.
60
+ */
61
+ export function regenerateWaits(key: string, generated: Generation, busy: (key: string) => boolean): boolean {
62
+ return [key, ...regeneratedKeys(key, generated)].some(busy);
63
+ }
package/src/lib/reveal.ts CHANGED
@@ -9,6 +9,11 @@
9
9
  export type Reveal = {
10
10
  value: string;
11
11
  version: number | null;
12
+ /**
13
+ * Where the value was held, when that can change under one version
14
+ * number: a fork's key reset to its parent's reads another secret's v1.
15
+ */
16
+ from?: string;
12
17
  /** When the read happened, in ms since the epoch; drives the auto-hide. */
13
18
  at: number;
14
19
  };
@@ -16,6 +21,7 @@ export type Reveal = {
16
21
  export function revealIsCurrent(
17
22
  reveal: Reveal | null,
18
23
  currentVersion: number | null,
24
+ currentFrom?: string,
19
25
  ): reveal is Reveal {
20
- return reveal !== null && reveal.version === currentVersion;
26
+ return reveal !== null && reveal.version === currentVersion && reveal.from === currentFrom;
21
27
  }
@@ -0,0 +1,64 @@
1
+ import type { Reveal } from './reveal';
2
+
3
+ /**
4
+ * What a secret's row knows about reading its value.
5
+ *
6
+ * Two things read it, and they must not share state. Reveal (and Edit, which
7
+ * opens on the current value) put the value on screen: `reveal` holds it,
8
+ * `revealing` says a read is out, `error` is its refusal. Copy hands the value
9
+ * to the clipboard and keeps nothing: `copyError` is all of it that the row
10
+ * holds, because Copy's in-flight state belongs to its button. So a Copy never
11
+ * changes whether a value is shown or whether Hide can be pressed, and a Reveal
12
+ * never touches Copy's error, whichever of the two finishes first.
13
+ */
14
+ export type RowReads = {
15
+ reveal: Reveal | null;
16
+ revealing: boolean;
17
+ error: string | null;
18
+ copyError: string | null;
19
+ };
20
+
21
+ export const noReads: RowReads = { reveal: null, revealing: false, error: null, copyError: null };
22
+
23
+ export type RowReadsAction =
24
+ | { type: 'set-reveal'; reveal: Reveal | null }
25
+ /** Reveal or Edit asked for the value. */
26
+ | { type: 'read-started' }
27
+ /** It arrived; `reveal` is null when it was only wanted to edit from. */
28
+ | { type: 'read-succeeded'; reveal: Reveal | null }
29
+ | { type: 'read-failed'; message: string }
30
+ | { type: 'copy-started' }
31
+ | { type: 'copy-succeeded' }
32
+ | { type: 'copy-failed'; message: string };
33
+
34
+ export function rowReads(state: RowReads, action: RowReadsAction): RowReads {
35
+ switch (action.type) {
36
+ case 'set-reveal':
37
+ return { ...state, reveal: action.reveal };
38
+ case 'read-started':
39
+ return { ...state, revealing: true };
40
+ case 'read-succeeded':
41
+ return {
42
+ ...state,
43
+ revealing: false,
44
+ error: null,
45
+ reveal: action.reveal ?? state.reveal,
46
+ };
47
+ case 'read-failed':
48
+ return { ...state, revealing: false, error: action.message };
49
+ case 'copy-started':
50
+ case 'copy-succeeded':
51
+ return { ...state, copyError: null };
52
+ case 'copy-failed':
53
+ return { ...state, copyError: action.message };
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Whether the eye button is out of reach: while a read is on its way and there
59
+ * is nothing on screen yet. Once a value is shown, Hide is always available,
60
+ * whatever else is being read.
61
+ */
62
+ export function revealToggleDisabled(state: RowReads, shown: Reveal | null): boolean {
63
+ return shown === null && state.revealing;
64
+ }
@@ -1,3 +1,5 @@
1
+ import type { Generation } from '@coffre/core/recipe';
2
+
1
3
  /**
2
4
  * A second secret a row writes with its own value, in the same patch: a
3
5
  * generated key pair's public key, beside its private key. It is part of
@@ -5,7 +7,14 @@
5
7
  */
6
8
  export type Companion = { key: string; value: string };
7
9
 
8
- export type SecretDraft = { id: number; key: string; value: string; companion?: Companion };
10
+ export type SecretDraft = {
11
+ id: number;
12
+ key: string;
13
+ value: string;
14
+ companion?: Companion;
15
+ /** The recipe a generated value was made by, saved with it; typing over the value drops it. */
16
+ recipe?: string;
17
+ };
9
18
 
10
19
  export type SecretChange = {
11
20
  key: string;
@@ -13,12 +22,62 @@ export type SecretChange = {
13
22
  archived: boolean;
14
23
  /** Only beside a new value. */
15
24
  companion?: Companion;
25
+ /** Only beside a generated value. */
26
+ recipe?: string;
16
27
  };
17
28
 
18
29
  type ActiveSecret = { key: string };
19
30
 
20
- /** A merge patch: a string sets a key, adding it if it is new; `null` archives it. */
21
- export type SecretPatch = Record<string, string | null>;
31
+ /**
32
+ * A merge patch: a string sets a key, adding it if it is new; a value with
33
+ * how it was generated sets it with its recipe; `null` archives it.
34
+ */
35
+ export type SecretPatch = Record<string, string | { value: string; generated: Generation } | null>;
36
+
37
+ /**
38
+ * How a row's generated value was made, as its write says it: its recipe,
39
+ * and for a key pair the names both halves are saved under.
40
+ */
41
+ function generationOf(key: string, edit: { recipe?: string; companion?: Companion }): Generation | undefined {
42
+ if (edit.recipe === undefined) return undefined;
43
+ return edit.companion === undefined
44
+ ? { recipe: edit.recipe }
45
+ : { recipe: edit.recipe, pair: { private: key, public: edit.companion.key.trim() } };
46
+ }
47
+
48
+ /** What a row writes under each key: its value, and its companion's beside it. */
49
+ function rowPatch(key: string, value: string, edit: { recipe?: string; companion?: Companion }): SecretPatch {
50
+ const generated = generationOf(key, edit);
51
+ const entry = (each: string) => (generated === undefined ? each : { value: each, generated });
52
+ const patch: SecretPatch = Object.create(null);
53
+ patch[key] = entry(value);
54
+ if (edit.companion !== undefined) patch[edit.companion.key.trim()] = entry(edit.companion.value);
55
+ return patch;
56
+ }
57
+
58
+ /**
59
+ * The recipe each key a save writes will hold, by its name after the save:
60
+ * what the list shows of it until it is read back.
61
+ */
62
+ export function generationsOf(
63
+ active: readonly ActiveSecret[],
64
+ drafts: readonly SecretDraft[],
65
+ changes: Readonly<Record<string, SecretChange>>,
66
+ ): Map<string, Generation> {
67
+ const out = new Map<string, Generation>();
68
+ const add = (key: string, edit: { recipe?: string; companion?: Companion }) => {
69
+ const generated = generationOf(key, edit);
70
+ if (generated === undefined) return;
71
+ out.set(key, generated);
72
+ if (edit.companion !== undefined) out.set(edit.companion.key.trim(), generated);
73
+ };
74
+ for (const draft of drafts) add(draft.key.trim(), draft);
75
+ for (const entry of active) {
76
+ const change = secretChangeFor(changes, entry.key);
77
+ if (change !== undefined && !change.archived && change.value !== null) add(change.key.trim(), change);
78
+ }
79
+ return out;
80
+ }
22
81
 
23
82
  type SecretEditOperations = {
24
83
  rename: (key: string, nextKey: string) => Promise<void>;
@@ -139,9 +198,9 @@ export async function applySecretEditBatch({
139
198
  applied += 1;
140
199
  if (change.value !== null) remainingChanges[key] = { ...change, key };
141
200
  }
142
- if (change.value !== null) patch[key] = change.value;
201
+ if (change.value !== null) Object.assign(patch, rowPatch(key, change.value, change));
143
202
  }
144
- for (const draft of [...drafts, ...companionsOf(active, drafts, changes)]) patch[draft.key.trim()] = draft.value;
203
+ for (const draft of drafts) Object.assign(patch, rowPatch(draft.key.trim(), draft.value, draft));
145
204
 
146
205
  const written = Object.keys(patch).length;
147
206
  if (written > 0) await operations.write({ ...patch });