@coffre/ui 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/chunks/{audit-sentence-BVv_9_nq.js → audit-sentence-C_wMpAqr.js} +99 -26
  2. package/dist/chunks/audit-sentence-C_wMpAqr.js.map +1 -0
  3. package/dist/chunks/{connected-apps-rBF9XUob.js → connected-apps-Bn5rEoV2.js} +2 -2
  4. package/dist/chunks/{connected-apps-rBF9XUob.js.map → connected-apps-Bn5rEoV2.js.map} +1 -1
  5. package/dist/chunks/{delete-place-CkGezx5R.js → delete-place-CQCDHkne.js} +3 -3
  6. package/dist/chunks/{delete-place-CkGezx5R.js.map → delete-place-CQCDHkne.js.map} +1 -1
  7. package/dist/chunks/{directory-SRN01yP6.js → directory-BQNOdze_.js} +6 -5
  8. package/dist/chunks/{directory-SRN01yP6.js.map → directory-BQNOdze_.js.map} +1 -1
  9. package/dist/chunks/{grants-1E1vqkM0.js → grants-CJIBrkod.js} +3 -3
  10. package/dist/chunks/{grants-1E1vqkM0.js.map → grants-CJIBrkod.js.map} +1 -1
  11. package/dist/chunks/{offboarding-Bt7KSixm.js → offboarding-CrgwaetA.js} +3 -3
  12. package/dist/chunks/offboarding-CrgwaetA.js.map +1 -0
  13. package/dist/chunks/personal-tokens-B8rkT-DI.js +138 -0
  14. package/dist/chunks/personal-tokens-B8rkT-DI.js.map +1 -0
  15. package/dist/chunks/{principal-page-Cbx2l6XL.js → principal-page-Cv5PheS9.js} +25 -12
  16. package/dist/chunks/principal-page-Cv5PheS9.js.map +1 -0
  17. package/dist/chunks/{project-page-DKo2AFYg.js → project-page-BI--vjt3.js} +2 -2
  18. package/dist/chunks/{project-page-DKo2AFYg.js.map → project-page-BI--vjt3.js.map} +1 -1
  19. package/dist/chunks/{queries-BvSw1xBN.js → queries-epz4MIuW.js} +19 -5
  20. package/dist/chunks/queries-epz4MIuW.js.map +1 -0
  21. package/dist/chunks/{references-DCoSPtvw.js → references-DImfw0cz.js} +3 -3
  22. package/dist/chunks/{references-DCoSPtvw.js.map → references-DImfw0cz.js.map} +1 -1
  23. package/dist/chunks/{role-field-D98CvNEg.js → role-field-C1KhNaIR.js} +2 -2
  24. package/dist/chunks/{role-field-D98CvNEg.js.map → role-field-C1KhNaIR.js.map} +1 -1
  25. package/dist/chunks/{use-action-Bv7yQ0DW.js → use-action-BB-RcHo1.js} +2 -2
  26. package/dist/chunks/{use-action-Bv7yQ0DW.js.map → use-action-BB-RcHo1.js.map} +1 -1
  27. package/dist/chunks/{use-change-DIQTGXER.js → use-change-CQyDpCqw.js} +268 -17
  28. package/dist/chunks/use-change-CQyDpCqw.js.map +1 -0
  29. package/dist/chunks/{use-shell-DhFoHjDS.js → use-shell-C_NmvCt_.js} +2 -2
  30. package/dist/chunks/{use-shell-DhFoHjDS.js.map → use-shell-C_NmvCt_.js.map} +1 -1
  31. package/dist/index.d.ts +33 -0
  32. package/dist/index.js +4 -3
  33. package/dist/index.js.map +1 -1
  34. package/dist/pages/account.d.ts +1 -1
  35. package/dist/pages/account.js +26 -9
  36. package/dist/pages/account.js.map +1 -1
  37. package/dist/pages/audit.js +52 -32
  38. package/dist/pages/audit.js.map +1 -1
  39. package/dist/pages/environment.js +520 -192
  40. package/dist/pages/environment.js.map +1 -1
  41. package/dist/pages/login.js +1 -1
  42. package/dist/pages/project-access.js +8 -8
  43. package/dist/pages/project-access.js.map +1 -1
  44. package/dist/pages/project-environments.js +106 -19
  45. package/dist/pages/project-environments.js.map +1 -1
  46. package/dist/pages/project-settings.js +6 -6
  47. package/dist/pages/project.js +1 -1
  48. package/dist/pages/projects.js +4 -4
  49. package/dist/pages/service-account.js +278 -29
  50. package/dist/pages/service-account.js.map +1 -1
  51. package/dist/pages/service-accounts.js +4 -4
  52. package/dist/pages/settings.js +4 -4
  53. package/dist/pages/unregistered.js +1 -1
  54. package/dist/pages/user.js +5 -5
  55. package/dist/pages/users.js +4 -4
  56. package/package.json +3 -3
  57. package/src/components/actions-log.tsx +2 -1
  58. package/src/components/directory.tsx +1 -0
  59. package/src/components/generate-value.tsx +15 -7
  60. package/src/components/offboarding.tsx +1 -1
  61. package/src/components/personal-tokens.tsx +131 -0
  62. package/src/components/principal-page.tsx +20 -3
  63. package/src/components/regenerate.tsx +72 -0
  64. package/src/components/service-tokens.tsx +3 -3
  65. package/src/components/trusted-workloads.tsx +177 -8
  66. package/src/lib/audit-sentences.ts +110 -12
  67. package/src/lib/bindings.ts +41 -3
  68. package/src/lib/changes.ts +155 -20
  69. package/src/lib/generate.ts +3 -146
  70. package/src/lib/queries.ts +15 -4
  71. package/src/lib/recipes.ts +63 -0
  72. package/src/lib/reveal.ts +7 -1
  73. package/src/lib/secret-edit-batch.ts +64 -5
  74. package/src/options.ts +5 -1
  75. package/src/pages/account.tsx +27 -5
  76. package/src/pages/audit.tsx +23 -7
  77. package/src/pages/environment.tsx +357 -39
  78. package/src/pages/project-access.tsx +1 -1
  79. package/src/pages/project-environments.tsx +85 -12
  80. package/src/parity.ts +19 -2
  81. package/src/styles/globals.css +56 -3
  82. package/dist/chunks/audit-sentence-BVv_9_nq.js.map +0 -1
  83. package/dist/chunks/offboarding-Bt7KSixm.js.map +0 -1
  84. package/dist/chunks/principal-page-Cbx2l6XL.js.map +0 -1
  85. package/dist/chunks/queries-BvSw1xBN.js.map +0 -1
  86. package/dist/chunks/use-change-DIQTGXER.js.map +0 -1
@@ -26,6 +26,7 @@ export type AuditEntry = Pick<
26
26
  | 'environment'
27
27
  | 'key'
28
28
  | 'version'
29
+ | 'secrets'
29
30
  | 'operationId'
30
31
  | 'metadata'
31
32
  >;
@@ -42,7 +43,7 @@ export type Sentence = { parts: Part[]; refused: boolean };
42
43
  /** What one template needs: the line's leading entry, its batch, and how it was decided. */
43
44
  type Facts = {
44
45
  entry: AuditEntry;
45
- /** Every entry of the batch, the lead included. */
46
+ /** Every entry of the batch, the lead included, a read of several once per secret (`perSecret`). */
46
47
  batch: AuditEntry[];
47
48
  /** Secrets the batch was about. */
48
49
  count: number;
@@ -83,6 +84,17 @@ function subject(entry: AuditEntry): Part[] {
83
84
  return [{ member: `${entry.metadata.principalType === 'service' ? 'token' : 'user'}:${id}` }];
84
85
  }
85
86
 
87
+ /** Whether a token entry is about a personal token, which acts as its person, rather than a service account's. */
88
+ function personal(entry: AuditEntry): boolean {
89
+ return entry.metadata.kind === 'personal';
90
+ }
91
+
92
+ /** A personal token's label, as it was made: ` "cursor-agent"`. */
93
+ function labelled(entry: AuditEntry): Part[] {
94
+ const label = text(entry.metadata.label);
95
+ return label === null ? [] : [` “${label}”`];
96
+ }
97
+
86
98
  /** Why the vault made someone an Owner itself, said after it. */
87
99
  function owned(entry: AuditEntry): Part[] {
88
100
  return entry.metadata.reason === 'owners' ? [': the deployment names them one'] : [];
@@ -122,22 +134,34 @@ function plural(count: number, one: string, many = `${one}s`): string {
122
134
  * The secrets a read or write was about. A read through a reference is a
123
135
  * read of its source, "market/prod/DATABASE_URL through
124
136
  * billing/prod/DATABASE_URL"; a run that read some that way is a run of
125
- * the environment that holds them.
137
+ * the environment that holds them. A value a fork inherits is its parent's,
138
+ * read in the fork: "market/prod/STRIPE_KEY in market/prod-eu".
126
139
  */
127
140
  function secrets(facts: Facts): Part[] {
128
141
  const through = (entry: AuditEntry) => text((entry.metadata.via as { path?: unknown } | undefined)?.path);
142
+ // The fork a value was inherited in, by path: in its parent's project, which holds the reference a read went through.
143
+ const forkOf = (entry: AuditEntry) => {
144
+ const slug = text((entry.metadata.through as { slug?: unknown } | undefined)?.slug);
145
+ const project = through(entry)?.split('/')[0] ?? entry.project;
146
+ return slug === null || project === null ? null : `${project}/${slug}`;
147
+ };
129
148
  if (facts.batch.length === 1) {
130
- const held = through(facts.entry);
131
- return held === null ? place(facts.entry) : [...place(facts.entry), ' through ', { place: held }];
149
+ const [held, fork] = [through(facts.entry), forkOf(facts.entry)];
150
+ return [...place(facts.entry), ...(held === null ? [] : [' through ', { place: held }]), ...(fork === null ? [] : [' in ', { place: fork }])];
132
151
  }
133
- const own = facts.batch.find((entry) => through(entry) === null);
152
+ const fork = facts.batch.map(forkOf).find((path) => path !== null);
153
+ const own = facts.batch.find((entry) => through(entry) === null && forkOf(entry) === null);
134
154
  const held = facts.batch.map(through).filter((path): path is string => path !== null);
135
- const where = own !== undefined ? environmentOf(own) : [{ place: held[0]!.split('/').slice(0, 2).join('/') }];
155
+ const inherited = facts.batch.filter((entry) => forkOf(entry) !== null).length;
156
+ const where = fork !== undefined && fork !== null
157
+ ? [{ place: fork }]
158
+ : own !== undefined ? environmentOf(own) : [{ place: held[0]!.split('/').slice(0, 2).join('/') }];
136
159
  return [
137
160
  ...where,
138
161
  facts.refused ? ', ' : ': ',
139
162
  plural(facts.count, 'secret'),
140
163
  ...(held.length === 0 ? [] : [`, ${held.length} through ${held.length === 1 ? 'a reference' : 'references'}`]),
164
+ ...(inherited === 0 ? [] : [`, ${inherited} inherited`]),
141
165
  ];
142
166
  }
143
167
 
@@ -170,6 +194,9 @@ const READ_VERBS: Record<string, [did: string, tried: string]> = {
170
194
  run: ['ran', 'run'],
171
195
  compare: ['compared', 'compare'],
172
196
  copy: ['copied', 'copy'],
197
+ // The credential proxy's: a value injected into a request for its person, or one handed to their app.
198
+ use: ['used', 'use'],
199
+ expose: ['was given', 'be given'],
173
200
  };
174
201
 
175
202
  function readVerb({ entry }: Facts): [string, string] {
@@ -177,14 +204,29 @@ function readVerb({ entry }: Facts): [string, string] {
177
204
  }
178
205
 
179
206
  const placeTemplates = (kind: 'project' | 'environment'): Record<string, Template> => {
180
- const what = (facts: Facts): Part[] => [`${kind} `, ...(kind === 'project' ? place({ ...facts.entry, environment: null, key: null }) : environmentOf(facts.entry))];
207
+ // A personal config by what it is a config of, `market/dev`: its own slug is generated, and shown nowhere else.
208
+ const of = (entry: AuditEntry): string | null => {
209
+ const parent = text(entry.metadata.personal) ?? text(entry.metadata.with);
210
+ return parent === null || entry.project === null ? null : `${entry.project}/${parent}`;
211
+ };
212
+ const what = (facts: Facts): Part[] => {
213
+ const personal = kind === 'environment' ? of(facts.entry) : null;
214
+ if (personal !== null) return ['a personal config of ', { place: personal }];
215
+ if (kind === 'environment' && facts.entry.metadata.personal === true) return [`a personal config, ${text(facts.entry.metadata.path) ?? ''}`];
216
+ return [`${kind} `, ...(kind === 'project' ? place({ ...facts.entry, environment: null, key: null }) : environmentOf(facts.entry))];
217
+ };
181
218
  return {
182
219
  [`${kind}.create`]: {
183
220
  did: 'created',
184
221
  tried: 'create',
185
222
  what,
186
223
  // A fork names the environment it copied.
187
- then: ({ entry }) => (text(entry.metadata.from) === null ? [] : [`, a fork of ${text(entry.metadata.from)}`]),
224
+ then: ({ entry }) =>
225
+ text(entry.metadata.inherits) !== null
226
+ ? [`, inheriting from ${text(entry.metadata.inherits)}`]
227
+ : text(entry.metadata.from) === null
228
+ ? []
229
+ : [`, a fork of ${text(entry.metadata.from)}`],
188
230
  },
189
231
  [`${kind}.update`]: { did: 'changed', tried: 'change', what },
190
232
  [`${kind}.archive`]: { did: 'archived', tried: 'archive', what },
@@ -213,6 +255,12 @@ const TEMPLATES: Record<string, Template> = {
213
255
  then: ({ entry, batch }) =>
214
256
  batch.length > 1 || entry.version === null || entry.version === 1 ? [] : [`, now version ${entry.version}`],
215
257
  },
258
+ // The credential proxy's own entry beside the vault's read: which credential the keys went into, and where.
259
+ 'credential.use': {
260
+ did: ({ entry }) => (entry.metadata.purpose === 'expose' ? 'was given the values of' : 'used the credential'),
261
+ tried: ({ entry }) => (entry.metadata.purpose === 'expose' ? 'be given the values of' : 'use the credential'),
262
+ what: ({ entry }) => [text(entry.metadata.credential) ?? '', ...(text(entry.metadata.host) === null ? [] : [` on ${text(entry.metadata.host)}`])],
263
+ },
216
264
  'secret.restore': {
217
265
  did: 'restored',
218
266
  tried: 'restore',
@@ -223,8 +271,17 @@ const TEMPLATES: Record<string, Template> = {
223
271
  did: 'renamed',
224
272
  tried: 'rename',
225
273
  what: ({ entry }) => [...place(entry), ...(text(entry.metadata.nextKey) === null ? [] : [` to ${text(entry.metadata.nextKey)}`])],
274
+ // In a fork, carried down from a rename in its parent.
275
+ then: ({ entry }) => (text(entry.metadata.parent) === null ? [] : [`, as ${text(entry.metadata.parent)} did`]),
226
276
  },
227
277
  'secret.archive': { did: 'archived', tried: 'archive', what: ({ entry }) => archivedKeys(entry) },
278
+ // In a fork: its own value set aside, kept, for its parent's.
279
+ 'secret.reset': {
280
+ did: 'reset',
281
+ tried: 'reset',
282
+ what: ({ entry }) => place(entry),
283
+ then: ({ entry }) => (text(entry.metadata.from) === null ? [] : [` to ${text(entry.metadata.from)}'s value`]),
284
+ },
228
285
  'missing.dismiss': {
229
286
  did: 'dismissed',
230
287
  tried: 'dismiss',
@@ -388,8 +445,24 @@ const TEMPLATES: Record<string, Template> = {
388
445
  what: ({ entry }) => (text(entry.metadata.provider) === null ? [] : [`with ${text(entry.metadata.provider)}`]),
389
446
  },
390
447
  sign_out: { did: 'signed out', tried: 'sign out', what: () => [] },
391
- 'token.create': { did: 'issued a bearer token to', tried: 'issue a bearer token to', what: (facts) => subject(facts.entry), then: ({ entry }) => reaching(entry) },
392
- 'token.revoke': { did: 'revoked a bearer token of', tried: 'revoke a bearer token of', what: (facts) => subject(facts.entry) },
448
+ // A personal token is its person's own, and named by its label; a bearer token is a service account's.
449
+ 'token.create': {
450
+ did: ({ entry }) => (entry.metadata.kind === 'handle' ? 'made a handle' : personal(entry) ? 'made a personal token' : 'issued a bearer token to'),
451
+ tried: ({ entry }) => (entry.metadata.kind === 'handle' ? 'make a handle' : personal(entry) ? 'make a personal token' : 'issue a bearer token to'),
452
+ what: ({ entry }) => (personal(entry) ? labelled(entry) : subject(entry)),
453
+ then: ({ entry }) => reaching(entry),
454
+ },
455
+ 'token.revoke': {
456
+ did: ({ entry }) => (personal(entry) ? 'revoked a personal token of' : 'revoked a bearer token of'),
457
+ tried: ({ entry }) => (personal(entry) ? 'revoke a personal token of' : 'revoke a bearer token of'),
458
+ what: (facts) => subject(facts.entry),
459
+ },
460
+ // A personal token refused a route only its person reaches: the route, as the API names it.
461
+ 'token.use': {
462
+ did: 'used a personal token for',
463
+ tried: 'use a personal token for',
464
+ what: ({ entry }) => [text(entry.metadata.route) ?? 'something'],
465
+ },
393
466
  'device.approve': { did: 'approved a CLI sign-in', tried: 'approve a CLI sign-in', what: () => [] },
394
467
  'device.deny': { did: 'turned down a CLI sign-in', tried: 'turn down a CLI sign-in', what: () => [] },
395
468
  'mcp.read': { did: 'used', tried: 'use', what: ({ entry }) => tool(entry), then: ({ entry }) => via(entry) },
@@ -521,6 +594,7 @@ const TAMPERING: Record<string, string> = {
521
594
  const REASONS: Record<string, string> = {
522
595
  no_grant: 'no grant',
523
596
  bulk_limit: 'bulk limit',
597
+ stand_ins: 'people get stand-ins',
524
598
  expired: 'grant expired',
525
599
  removed: 'removed from coffre',
526
600
  not_a_member: 'not a member',
@@ -555,6 +629,8 @@ const REASONS: Record<string, string> = {
555
629
  replaced: 'what it replaces changed since it was shown',
556
630
  unconfirmed: 'what it replaces could not be read',
557
631
  disconnected: 'the app was disconnected',
632
+ personal_token: 'only its person can, signed in as themselves',
633
+ beyond_holder: 'more than they hold',
558
634
  };
559
635
 
560
636
  /** What a missing permission meant, from the app's `missing_<permission>`. */
@@ -587,10 +663,32 @@ export function leadOf(batch: AuditEntry[]): AuditEntry {
587
663
  return batch[0]!;
588
664
  }
589
665
 
666
+ /**
667
+ * A read of several secrets, logged once for its place, as the entries it
668
+ * would be about one secret each: its key and version, and what its own
669
+ * part of the metadata says, such as the reference it went through. Any
670
+ * other entry as it is.
671
+ */
672
+ export function perSecret<T extends AuditEntry>(entry: T): T[] {
673
+ const listed = entry.metadata.secrets;
674
+ // One whose list was emptied or mangled, which verification would flag, still reads as itself.
675
+ if (entry.secrets === null || entry.secrets.length === 0 || !Array.isArray(listed)) return [entry];
676
+ return entry.secrets.map(({ key, version }, i) => {
677
+ const own = listed[i];
678
+ return {
679
+ ...entry,
680
+ key,
681
+ version,
682
+ secrets: null,
683
+ metadata: { ...entry.metadata, secrets: undefined, ...(typeof own === 'object' && own !== null && !Array.isArray(own) ? own : {}) },
684
+ };
685
+ });
686
+ }
687
+
590
688
  /** What a line says: one entry, or a batch that shares an operation. */
591
689
  export function describe(batch: AuditEntry[]): Sentence {
592
- const entry = leadOf(batch);
593
- const same = batch.filter((other) => other.action === entry.action);
690
+ const entry = perSecret(leadOf(batch))[0]!;
691
+ const same = batch.filter((other) => other.action === entry.action).flatMap(perSecret);
594
692
  const denied = same.filter((other) => other.decision === 'deny');
595
693
  const refused = denied.length === same.length;
596
694
  const facts: Facts = {
@@ -27,7 +27,16 @@ export function summary(binding: Pick<BindingView, 'profile' | 'issuer' | 'claim
27
27
  if (binding.profile === 'gitlab') {
28
28
  return { title: `GitLab project ${claims.project_id}`, detail: `${claimValues(binding.claims.pipeline_source).join(', ')} at ${claims.ref_type} ${claims.ref}` };
29
29
  }
30
- return { title: new URL(binding.issuer).host, detail: `sub ${claims.sub}` };
30
+ return { title: issuerName(binding.issuer), detail: `sub ${claims.sub}` };
31
+ }
32
+
33
+ /** An issuer as a title: its host, when it is a URL; a binding that carries its keys may name any string. */
34
+ function issuerName(issuer: string): string {
35
+ try {
36
+ return new URL(issuer).host || issuer;
37
+ } catch {
38
+ return issuer;
39
+ }
31
40
  }
32
41
 
33
42
  /**
@@ -80,6 +89,8 @@ export const EMPTY_FORM = {
80
89
  issuer: '',
81
90
  sub: '',
82
91
  extra: '',
92
+ // Its keys, a JWKS pasted, for an issuer coffre cannot fetch them from; empty, they are fetched.
93
+ jwks: '',
83
94
  };
84
95
 
85
96
  export type Form = typeof EMPTY_FORM;
@@ -176,7 +187,10 @@ export function lookupFailure(name: string, failure: unknown): GitHubLookup {
176
187
  * server checks the rest. A GitHub binding takes its IDs, and its
177
188
  * repository's name as GitHub spells it, from `found`, unless typed in.
178
189
  */
179
- export function bindingOf(form: Form, found: GitHubIds | null = null): { profile: BindingPlan['profile']; issuer: string | null; claims: BindingClaims } {
190
+ export function bindingOf(
191
+ form: Form,
192
+ found: GitHubIds | null = null,
193
+ ): { profile: BindingPlan['profile']; issuer: string | null; claims: BindingClaims; jwks?: KeySet } {
180
194
  const needed = (value: string, what: string) => {
181
195
  if (value.trim() === '') throw new Error(`${what} is needed`);
182
196
  return value.trim();
@@ -240,6 +254,30 @@ export function bindingOf(form: Form, found: GitHubIds | null = null): { profile
240
254
  if (at <= 0) throw new Error(`"${line}" is not <claim>=<value>`);
241
255
  claims[line.slice(0, at).trim()] = line.slice(at + 1).trim();
242
256
  }
243
- return { profile: 'custom', issuer: needed(form.issuer, 'The issuer'), claims };
257
+ const jwks = keySetOf(form.jwks);
258
+ return { profile: 'custom', issuer: needed(form.issuer, 'The issuer'), claims, ...(jwks === undefined ? {} : { jwks }) };
259
+ }
260
+
261
+ /** A JWKS, as the API takes it: each key the server checks. */
262
+ export type KeySet = { keys: Record<string, unknown>[] };
263
+
264
+ /** The key set pasted in a field, or undefined for none; throws a sentence when it is not one. */
265
+ export function keySetOf(text: string): KeySet | undefined {
266
+ if (text.trim() === '') return undefined;
267
+ let value: unknown;
268
+ try {
269
+ value = JSON.parse(text);
270
+ } catch {
271
+ throw new Error('The keys are not JSON: paste the issuer\'s key set, { "keys": [ … ] }');
272
+ }
273
+ const keys = (value as { keys?: unknown } | null)?.keys;
274
+ if (!Array.isArray(keys)) throw new Error('The keys are a key set, { "keys": [ … ] }, as kubectl get --raw /openid/v1/jwks prints it');
275
+ return { keys: keys as Record<string, unknown>[] };
276
+ }
277
+
278
+ /** Where a binding's keys come from, in a line: the URL coffre fetches, or the keys uploaded with it, by `kid` or thumbprint. */
279
+ export function keysOf(binding: Pick<BindingPlan, 'jwksUri' | 'keys'>): string {
280
+ if (binding.keys === null) return binding.jwksUri;
281
+ return `Uploaded: ${binding.keys.map((key) => `${key.kid ?? key.thumbprint} (${key.alg})`).join(', ')}`;
244
282
  }
245
283
 
@@ -1,4 +1,4 @@
1
- import type { CoffreClient, ConnectedApp, IdentityRow, MissingKey, 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
  /**
@@ -35,6 +37,7 @@ const ARCHIVING: Words = { pending: 'Archiving…', done: 'archived', failed: 'N
35
37
  const REVOKING: Words = { pending: 'Revoking…', done: 'revoked', failed: 'Not revoked.' };
36
38
  const DISCONNECTING: Words = { pending: 'Disconnecting…', done: 'disconnected', failed: 'Not disconnected.' };
37
39
  const MOVING: Words = { pending: 'Moving…', done: 'moved', failed: 'Not moved.' };
40
+ const REGENERATING: Words = { pending: 'Regenerating…', done: 'regenerated', failed: 'Not regenerated.' };
38
41
 
39
42
  const saving = (id: string): Target => ({ id, kind: 'saving' });
40
43
  const removing = (id: string): Target => ({ id, kind: 'removing' });
@@ -201,13 +204,12 @@ export function removeMember(client: CoffreClient): Change<Directory, DirectoryP
201
204
 
202
205
  // --- credentials, sessions, linked accounts --------------------------------------
203
206
 
204
- type Credential = { id: string; hint: string };
205
- type Credentials = ({ ok: true; tokens: Credential[] } | Failure) | null;
207
+ type Credentials = ({ ok: true; tokens: TokenRow[] } | Failure) | null;
206
208
 
207
- export function revokeCredential(client: CoffreClient, serviceId: string): Change<Credentials, Credential, Credential, unknown> {
208
- 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> {
209
211
  return {
210
- 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),
211
213
  label: (token) => `token ${token.hint}`,
212
214
  targets: (token) => [removing(token.id)],
213
215
  removing: REVOKING,
@@ -260,6 +262,24 @@ export function disconnectApp(client: CoffreClient): Change<Apps, ConnectedApp,
260
262
 
261
263
  type Report = { ok: true; report: OffboardingReport | null } | Failure | null;
262
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
+
263
283
  /** An owner disconnecting someone's app, on their page: their report lists it, as the owner reads it. */
264
284
  export function disconnectMemberApp(client: CoffreClient, member: string): Change<Report, ConnectedApp, ConnectedApp, unknown> {
265
285
  return {
@@ -359,20 +379,21 @@ export function environmentId(project: string, environment: string): string {
359
379
  }
360
380
 
361
381
  /** A new environment, empty or, `from` a sibling, forked: each of its keys copied. */
362
- export function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: 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> {
363
383
  return {
364
384
  list: environmentsList(project),
365
385
  label: (vars) => `environment ${vars.slug}`,
366
386
  targets: (vars) => [saving(environmentId(project, vars.slug))],
367
387
  apply: (environments, vars) => [
368
388
  ...environments,
369
- { slug: vars.slug, name: vars.slug, 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 } },
370
390
  ],
371
391
  affects: () => affects.places(),
372
392
  run: async (vars) => {
373
393
  const { created } = await client.environments.create(`${project}/${vars.slug}`, {
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
  },
@@ -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);
@@ -569,6 +604,54 @@ export function moveSecret(
569
604
  };
570
605
  }
571
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
+
572
655
  /** Restore an archived secret, from the Archived list. */
573
656
  export function restoreSecret(
574
657
  client: CoffreClient,
@@ -601,6 +684,58 @@ export function archiveSecret(
601
684
  };
602
685
  }
603
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
+
604
739
  // --- missing keys ----------------------------------------------------------------
605
740
 
606
741
  type Missing = ({ ok: true; missing: MissingKey[] } | Failure);