@coffre/ui 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -3
  3. package/dist/client/.assetsignore +2 -0
  4. package/dist/client/_coffre/assets/account-C3Zo1l5A.js +1 -0
  5. package/dist/client/_coffre/assets/account-C4bNbeO7.js +2 -0
  6. package/dist/client/_coffre/assets/affordances-DiuJIiR2.js +1 -0
  7. package/dist/client/_coffre/assets/audit-1xLyuxGz.js +2 -0
  8. package/dist/client/_coffre/assets/audit-Dab2GuRj.js +1 -0
  9. package/dist/client/_coffre/assets/auth.device-BfCfeBWe.js +2 -0
  10. package/dist/client/_coffre/assets/auth.device-D2pCLF-X.js +1 -0
  11. package/dist/client/_coffre/assets/coffre-C7qL3HGR.js +1 -0
  12. package/dist/client/_coffre/assets/directory-C2Ou4SQv.js +1 -0
  13. package/dist/client/_coffre/assets/globals-Dgq4Jy0x.css +1 -0
  14. package/dist/client/_coffre/assets/grants-fqTtJ-aW.js +1 -0
  15. package/dist/client/_coffre/assets/index-BpGwbjmM.js +12 -0
  16. package/dist/client/_coffre/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
  17. package/dist/client/_coffre/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
  18. package/dist/client/_coffre/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
  19. package/dist/client/_coffre/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
  20. package/dist/client/_coffre/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
  21. package/dist/client/_coffre/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
  22. package/dist/client/_coffre/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
  23. package/dist/client/_coffre/assets/jetbrains-mono-cyrillic-ext-wght-normal-EocZY2iu.woff2 +0 -0
  24. package/dist/client/_coffre/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  25. package/dist/client/_coffre/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  26. package/dist/client/_coffre/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  27. package/dist/client/_coffre/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  28. package/dist/client/_coffre/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  29. package/dist/client/_coffre/assets/login-CR9CBXlw.js +2 -0
  30. package/dist/client/_coffre/assets/login-DZizFxa4.js +1 -0
  31. package/dist/client/_coffre/assets/offboarding-DOLJQcXU.js +1 -0
  32. package/dist/client/_coffre/assets/page-BxW2MwaX.js +1 -0
  33. package/dist/client/_coffre/assets/preload-helper-BHuP8_FL.js +46 -0
  34. package/dist/client/_coffre/assets/principal-page-xnBZVURr.js +1 -0
  35. package/dist/client/_coffre/assets/project-environments-CfIH5kFM.js +1 -0
  36. package/dist/client/_coffre/assets/projects._project._environment-CrWjQmIA.js +2 -0
  37. package/dist/client/_coffre/assets/projects._project._environment-CwRVG9Ne.js +3 -0
  38. package/dist/client/_coffre/assets/projects._project.index-CCDEuE-z.js +2 -0
  39. package/dist/client/_coffre/assets/projects._project.index-DCJsmnD7.js +1 -0
  40. package/dist/client/_coffre/assets/projects.index-B8eV8JIn.js +1 -0
  41. package/dist/client/_coffre/assets/projects.index-BNEC7Oz8.js +2 -0
  42. package/dist/client/_coffre/assets/settings-2BPsenNM.js +2 -0
  43. package/dist/client/_coffre/assets/settings-BrS0-wEt.js +1 -0
  44. package/dist/client/_coffre/assets/signin-errors-CroZWZgm.js +1 -0
  45. package/dist/client/_coffre/assets/tokens._token-B3-YwuKp.js +2 -0
  46. package/dist/client/_coffre/assets/tokens._token-D_hsbHx6.js +1 -0
  47. package/dist/client/_coffre/assets/tokens.index-BdKE2Jv8.js +2 -0
  48. package/dist/client/_coffre/assets/tokens.index-XvA4XRxh.js +1 -0
  49. package/dist/client/_coffre/assets/unregistered-CTRMtBIy.js +1 -0
  50. package/dist/client/_coffre/assets/use-action-DgAf-tiX.js +1 -0
  51. package/dist/client/_coffre/assets/users._user-BFPXcJ4y.js +2 -0
  52. package/dist/client/_coffre/assets/users._user-DEtMeSoh.js +1 -0
  53. package/dist/client/_coffre/assets/users.index-B03beUHq.js +1 -0
  54. package/dist/client/_coffre/assets/users.index-D8hwzM6P.js +2 -0
  55. package/dist/client/_coffre/assets/validation-9Cl_XS-l.js +1 -0
  56. package/dist/index.d.ts +19 -0
  57. package/dist/server/.vite/manifest.json +572 -0
  58. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-B6CZDfrB.js +133 -0
  59. package/dist/server/_coffre/assets/account-B71_b5xc.js +296 -0
  60. package/dist/server/_coffre/assets/account-BoO6ZqMc.js +176 -0
  61. package/dist/server/_coffre/assets/affordances-BNaXjMOb.js +46 -0
  62. package/dist/server/_coffre/assets/async-local-storage-C0cwgkEr.js +3107 -0
  63. package/dist/server/_coffre/assets/audit-CwRFnSAY.js +74 -0
  64. package/dist/server/_coffre/assets/audit-t1sYjtrf.js +964 -0
  65. package/dist/server/_coffre/assets/auth.device-1IcJ475s.js +208 -0
  66. package/dist/server/_coffre/assets/auth.device-CJwZYYtn.js +29 -0
  67. package/dist/server/_coffre/assets/coffre-1hxT2E_U.js +278 -0
  68. package/dist/server/_coffre/assets/directory-wm_JQUfk.js +396 -0
  69. package/dist/server/_coffre/assets/empty-plugin-adapters-Cq4--YW-.js +5 -0
  70. package/dist/server/_coffre/assets/globals-Dgq4Jy0x.css +1 -0
  71. package/dist/server/_coffre/assets/grants-BmhEY1vz.js +243 -0
  72. package/dist/server/_coffre/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
  73. package/dist/server/_coffre/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
  74. package/dist/server/_coffre/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
  75. package/dist/server/_coffre/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
  76. package/dist/server/_coffre/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
  77. package/dist/server/_coffre/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
  78. package/dist/server/_coffre/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
  79. package/dist/server/_coffre/assets/jetbrains-mono-cyrillic-ext-wght-normal-EocZY2iu.woff2 +0 -0
  80. package/dist/server/_coffre/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  81. package/dist/server/_coffre/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  82. package/dist/server/_coffre/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  83. package/dist/server/_coffre/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  84. package/dist/server/_coffre/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  85. package/dist/server/_coffre/assets/login-B5O5LPXV.js +100 -0
  86. package/dist/server/_coffre/assets/login-Bvc4gp0X.js +22 -0
  87. package/dist/server/_coffre/assets/offboarding-CvSilnSm.js +330 -0
  88. package/dist/server/_coffre/assets/page-BjXk0Ehu.js +2003 -0
  89. package/dist/server/_coffre/assets/principal-page-DkwNGzM2.js +617 -0
  90. package/dist/server/_coffre/assets/project-environments-lEzFHUt4.js +9 -0
  91. package/dist/server/_coffre/assets/projects._project._environment-7grhqlgq.js +2227 -0
  92. package/dist/server/_coffre/assets/projects._project._environment-ByEf6pmz.js +55 -0
  93. package/dist/server/_coffre/assets/projects._project.index-B1bjowP-.js +932 -0
  94. package/dist/server/_coffre/assets/projects._project.index-DU8wtoHD.js +22 -0
  95. package/dist/server/_coffre/assets/projects.index-B0DoHbCz.js +280 -0
  96. package/dist/server/_coffre/assets/projects.index-kMDA6pMy.js +54 -0
  97. package/dist/server/_coffre/assets/react-dom-qCTiwGGR.js +1352 -0
  98. package/dist/server/_coffre/assets/router-ChU_CwCX.js +2028 -0
  99. package/dist/server/_coffre/assets/settings-CM9-h7in.js +18 -0
  100. package/dist/server/_coffre/assets/settings-Cg5qOGij.js +60 -0
  101. package/dist/server/_coffre/assets/signin-errors-BEFlVDbQ.js +28 -0
  102. package/dist/server/_coffre/assets/start-DR3rN0St.js +4 -0
  103. package/dist/server/_coffre/assets/tokens._token-CCpaPMAk.js +268 -0
  104. package/dist/server/_coffre/assets/tokens._token-Di4OZdAA.js +18 -0
  105. package/dist/server/_coffre/assets/tokens.index-Do3OHR31.js +34 -0
  106. package/dist/server/_coffre/assets/tokens.index-tDKq4AFh.js +10 -0
  107. package/dist/server/_coffre/assets/ui-BNzhIAQP.js +15710 -0
  108. package/dist/server/_coffre/assets/unregistered-BqaWYFJK.js +51 -0
  109. package/dist/server/_coffre/assets/use-action-BkJXC5JM.js +953 -0
  110. package/dist/server/_coffre/assets/useStore-DWGPqzXR.js +892 -0
  111. package/dist/server/_coffre/assets/users._user-BenYva93.js +15 -0
  112. package/dist/server/_coffre/assets/users._user-Cp039Va-.js +10 -0
  113. package/dist/server/_coffre/assets/users.index-BrzG1Ecq.js +10 -0
  114. package/dist/server/_coffre/assets/users.index-DQ_45DQl.js +34 -0
  115. package/dist/server/_coffre/assets/validation-BQtqPe2V.js +27 -0
  116. package/dist/server/index.js +13910 -0
  117. package/package.json +58 -5
  118. package/src/components/affordances.ts +80 -0
  119. package/src/components/agentation.tsx +34 -0
  120. package/src/components/command-palette.tsx +271 -0
  121. package/src/components/directory.tsx +448 -0
  122. package/src/components/grants.tsx +204 -0
  123. package/src/components/icons.tsx +283 -0
  124. package/src/components/offboarding.tsx +286 -0
  125. package/src/components/page.tsx +128 -0
  126. package/src/components/principal-page.tsx +549 -0
  127. package/src/components/principal-picker.tsx +168 -0
  128. package/src/components/principal.tsx +53 -0
  129. package/src/components/route-states.tsx +60 -0
  130. package/src/components/service-tokens.tsx +212 -0
  131. package/src/components/shell.tsx +641 -0
  132. package/src/components/syncs.tsx +581 -0
  133. package/src/components/theme.tsx +141 -0
  134. package/src/components/tile.tsx +22 -0
  135. package/src/components/ui.tsx +440 -0
  136. package/src/entry.ts +19 -0
  137. package/src/lib/access-plan.ts +201 -0
  138. package/src/lib/audit-sentences.ts +468 -0
  139. package/src/lib/capabilities.ts +45 -0
  140. package/src/lib/coffre.ts +57 -0
  141. package/src/lib/project-access.ts +95 -0
  142. package/src/lib/project-environments.ts +23 -0
  143. package/src/lib/reveal.ts +21 -0
  144. package/src/lib/secret-edit-batch.ts +181 -0
  145. package/src/lib/signin-errors.ts +33 -0
  146. package/src/lib/use-action.ts +50 -0
  147. package/src/lib/validation.ts +27 -0
  148. package/src/routeTree.gen.ts +367 -0
  149. package/src/router.tsx +84 -0
  150. package/src/routes/__root.tsx +192 -0
  151. package/src/routes/access.tsx +11 -0
  152. package/src/routes/account.tsx +359 -0
  153. package/src/routes/audit.tsx +545 -0
  154. package/src/routes/auth.device.tsx +200 -0
  155. package/src/routes/index.tsx +15 -0
  156. package/src/routes/login.tsx +129 -0
  157. package/src/routes/projects.$project.$environment.tsx +1659 -0
  158. package/src/routes/projects.$project.index.tsx +917 -0
  159. package/src/routes/projects.index.tsx +353 -0
  160. package/src/routes/settings.tsx +72 -0
  161. package/src/routes/tokens.$token.tsx +35 -0
  162. package/src/routes/tokens.index.tsx +37 -0
  163. package/src/routes/unregistered.tsx +59 -0
  164. package/src/routes/users.$user.tsx +13 -0
  165. package/src/routes/users.index.tsx +37 -0
  166. package/src/shared/models.ts +55 -0
  167. package/src/styles/globals.css +4118 -0
  168. package/src/types.ts +21 -0
@@ -0,0 +1,201 @@
1
+ import type { AccessValue } from '@coffre/client';
2
+ import type { Role } from '@coffre/core/access';
3
+
4
+ import type { GrantRow } from '../shared/models';
5
+
6
+ /** Read or write on one environment, and when it ends: an ISO instant, or null for never. */
7
+ export type EnvironmentAccess = { role: 'viewer' | 'developer'; expiresAt: string | null };
8
+
9
+ /**
10
+ * What one project is set to in a principal's access editor: nothing, owner,
11
+ * read or write everywhere, or read or write per environment. Every grant the
12
+ * plan asks for carries its own expiry.
13
+ *
14
+ * `custom` is for grants that do not fit that shape -- an auditor grant, or
15
+ * read everywhere plus write on one environment. The editor shows them and
16
+ * leaves them alone unless another setting is picked.
17
+ */
18
+ export type AccessPlan = {
19
+ level: 'none' | 'owner' | 'viewer' | 'developer' | 'env' | 'custom';
20
+ /** When the project-wide level ends. */
21
+ expiresAt: string | null;
22
+ /** Environments without an entry get no access. */
23
+ environments: Record<string, EnvironmentAccess>;
24
+ };
25
+
26
+ export type HeldGrant = Pick<
27
+ GrantRow,
28
+ 'id' | 'role' | 'roleName' | 'environmentSlug' | 'expiresAt'
29
+ >;
30
+
31
+ export type AccessChange =
32
+ | { kind: 'create'; role: string; environmentSlug: string | null; expiresAt: string | null }
33
+ | { kind: 'expiry'; grant: HeldGrant; expiresAt: string | null }
34
+ | { kind: 'revoke'; grant: HeldGrant };
35
+
36
+ /** An environment's access in a plan; slugs like `constructor` are not inherited. */
37
+ export function environmentAccess(plan: AccessPlan, slug: string): EnvironmentAccess | null {
38
+ return Object.hasOwn(plan.environments, slug) ? plan.environments[slug] : null;
39
+ }
40
+
41
+ /**
42
+ * Read what a principal holds on a project back into the editor's terms.
43
+ * `environments` are the ones the editor can set: live, and not archived.
44
+ */
45
+ export function planFromGrants(
46
+ grants: readonly HeldGrant[],
47
+ environments: readonly string[],
48
+ ): AccessPlan {
49
+ if (grants.length === 0) return { level: 'none', expiresAt: null, environments: {} };
50
+
51
+ const [only] = grants;
52
+ if (
53
+ grants.length === 1 &&
54
+ only.environmentSlug === null &&
55
+ (only.role === 'owner' || only.role === 'viewer' || only.role === 'developer')
56
+ ) {
57
+ return { level: only.role, expiresAt: only.expiresAt, environments: {} };
58
+ }
59
+
60
+ const perEnvironment: Record<string, EnvironmentAccess> = {};
61
+ for (const grant of grants) {
62
+ const slug = grant.environmentSlug;
63
+ if (
64
+ slug === null ||
65
+ !environments.includes(slug) ||
66
+ Object.hasOwn(perEnvironment, slug) ||
67
+ (grant.role !== 'viewer' && grant.role !== 'developer')
68
+ ) {
69
+ return { level: 'custom', expiresAt: null, environments: {} };
70
+ }
71
+ perEnvironment[slug] = { role: grant.role, expiresAt: grant.expiresAt };
72
+ }
73
+ return { level: 'env', expiresAt: null, environments: perEnvironment };
74
+ }
75
+
76
+ /**
77
+ * Switch a plan's level. Going from read or write everywhere to per
78
+ * environment starts every environment at that level and expiry, so the
79
+ * switch alone keeps the same reach.
80
+ */
81
+ export function withLevel(
82
+ plan: AccessPlan,
83
+ level: AccessPlan['level'],
84
+ environments: readonly string[],
85
+ ): AccessPlan {
86
+ if (
87
+ level === 'env' &&
88
+ (plan.level === 'viewer' || plan.level === 'developer') &&
89
+ Object.keys(plan.environments).length === 0
90
+ ) {
91
+ const access = { role: plan.level, expiresAt: plan.expiresAt };
92
+ return {
93
+ ...plan,
94
+ level,
95
+ environments: Object.fromEntries(environments.map((slug) => [slug, access])),
96
+ };
97
+ }
98
+ return { ...plan, level };
99
+ }
100
+
101
+ /** Set one environment's access, or take it away with `null`. */
102
+ export function withEnvironment(
103
+ plan: AccessPlan,
104
+ slug: string,
105
+ access: EnvironmentAccess | null,
106
+ ): AccessPlan {
107
+ const environments = { ...plan.environments };
108
+ if (access === null) delete environments[slug];
109
+ else environments[slug] = access;
110
+ return { ...plan, environments };
111
+ }
112
+
113
+ function grantsFor(
114
+ plan: AccessPlan,
115
+ ): { role: string; environmentSlug: string | null; expiresAt: string | null }[] {
116
+ switch (plan.level) {
117
+ case 'none':
118
+ case 'custom':
119
+ return [];
120
+ case 'owner':
121
+ case 'viewer':
122
+ case 'developer':
123
+ return [{ role: plan.level, environmentSlug: null, expiresAt: plan.expiresAt }];
124
+ case 'env':
125
+ return Object.entries(plan.environments).map(([environmentSlug, access]) => ({
126
+ environmentSlug,
127
+ ...access,
128
+ }));
129
+ }
130
+ }
131
+
132
+ /** The server and the date field spell the same instant differently. */
133
+ function sameExpiry(a: string | null, b: string | null): boolean {
134
+ return a === b || (a !== null && b !== null && Date.parse(a) === Date.parse(b));
135
+ }
136
+
137
+ /**
138
+ * The changes that take what is held to the plan: grants to create, grants
139
+ * whose expiry moves, and grants to revoke, in that order. Asking for what is
140
+ * already held yields nothing, so applying the same plan twice is a no-op.
141
+ */
142
+ export function accessChanges(grants: readonly HeldGrant[], plan: AccessPlan): AccessChange[] {
143
+ if (plan.level === 'custom') return [];
144
+
145
+ const key = (grant: { role: string; environmentSlug: string | null }) =>
146
+ `${grant.role}@${grant.environmentSlug ?? ''}`;
147
+ const wanted = new Map(grantsFor(plan).map((grant) => [key(grant), grant]));
148
+ const held = new Map(grants.map((grant) => [key(grant), grant]));
149
+
150
+ const changes: AccessChange[] = [];
151
+ for (const [id, grant] of wanted) {
152
+ if (!held.has(id)) changes.push({ kind: 'create', ...grant });
153
+ }
154
+ for (const [id, grant] of held) {
155
+ const want = wanted.get(id);
156
+ if (want !== undefined && !sameExpiry(grant.expiresAt, want.expiresAt)) {
157
+ changes.push({ kind: 'expiry', grant, expiresAt: want.expiresAt });
158
+ }
159
+ }
160
+ for (const [id, grant] of held) {
161
+ if (!wanted.has(id)) changes.push({ kind: 'revoke', grant });
162
+ }
163
+ return changes;
164
+ }
165
+
166
+ /**
167
+ * The changes as the API's access patch for one project: each place it
168
+ * touches, and the role to hold there until when, or `null` for none.
169
+ *
170
+ * { "market": null, "market/dev": { "role": "developer", "until": "2026-12-31T23:59:59.000Z" } }
171
+ *
172
+ * A place holds one role, so where a level changes, the revoke of the old
173
+ * role and the create of the new land on the same place, and the new role
174
+ * wins: the server replaces one with the other, never passing through none.
175
+ */
176
+ export function accessPatch(project: string, changes: readonly AccessChange[]): Record<string, AccessValue> {
177
+ const place = (environmentSlug: string | null) =>
178
+ environmentSlug === null ? project : `${project}/${environmentSlug}`;
179
+ const holding = (role: string, expiresAt: string | null): AccessValue =>
180
+ expiresAt === null ? (role as Role) : { role: role as Role, until: expiresAt };
181
+
182
+ const patch: Record<string, AccessValue> = {};
183
+ for (const change of changes) {
184
+ if (change.kind === 'revoke') patch[place(change.grant.environmentSlug)] = null;
185
+ }
186
+ for (const change of changes) {
187
+ if (change.kind === 'expiry') patch[place(change.grant.environmentSlug)] = holding(change.grant.role, change.expiresAt);
188
+ if (change.kind === 'create') patch[place(change.environmentSlug)] = holding(change.role, change.expiresAt);
189
+ }
190
+ return patch;
191
+ }
192
+
193
+ /** A date field's value as the instant access ends: the close of that day, UTC. */
194
+ export function expiryFromDate(date: string): string | null {
195
+ return date === '' ? null : new Date(`${date}T23:59:59Z`).toISOString();
196
+ }
197
+
198
+ /** A date field's value for an expiry. Expiries are shown as UTC dates everywhere. */
199
+ export function dateFromExpiry(expiresAt: string | null): string {
200
+ return expiresAt === null ? '' : expiresAt.slice(0, 10);
201
+ }
@@ -0,0 +1,468 @@
1
+ /**
2
+ * The audit log in sentences: who did what, to what. One entry is one
3
+ * human action, named for it (`secret.read`, `access.grant`, …); a batch of
4
+ * them, one reveal of twelve secrets, shares an operation and reads as one
5
+ * line, "ran market/prod: 12 secrets".
6
+ *
7
+ * A sentence is parts rather than a string, so the page can make the people
8
+ * and places in it links. `plain` flattens it, for tests and titles.
9
+ */
10
+ import type { AuditEntryView } from '@coffre/client';
11
+
12
+ /** What a sentence is made from: an entry of the log, as `GET /api/audit` gives it. */
13
+ export type AuditEntry = Pick<
14
+ AuditEntryView,
15
+ | 'seq'
16
+ | 'author'
17
+ | 'actorType'
18
+ | 'actorId'
19
+ | 'action'
20
+ | 'decision'
21
+ | 'reason'
22
+ | 'detail'
23
+ | 'subject'
24
+ | 'project'
25
+ | 'environment'
26
+ | 'key'
27
+ | 'version'
28
+ | 'operationId'
29
+ | 'metadata'
30
+ >;
31
+
32
+ /** Text, a place (`market`, `market/prod`, `market/prod/KEY`), or a member (`user:…`, `token:…`). */
33
+ export type Part = string | { place: string } | { member: string };
34
+
35
+ export type Sentence = { parts: Part[]; refused: boolean };
36
+
37
+ /** What one template needs: the line's leading entry, its batch, and how it was decided. */
38
+ type Facts = {
39
+ entry: AuditEntry;
40
+ /** Every entry of the batch, the lead included. */
41
+ batch: AuditEntry[];
42
+ /** Secrets the batch was about. */
43
+ count: number;
44
+ refused: boolean;
45
+ };
46
+
47
+ type Template = {
48
+ /** What they did: "revealed". */
49
+ did: string | ((facts: Facts) => string);
50
+ /** What they tried, after "tried to": "reveal". */
51
+ tried: string | ((facts: Facts) => string);
52
+ /** To what: "market/prod/API_KEY". */
53
+ what: (facts: Facts) => Part[];
54
+ /** Said only of what happened: ", now version 5". */
55
+ then?: (facts: Facts) => Part[];
56
+ };
57
+
58
+ // --- the pieces of a sentence ---------------------------------------------------
59
+
60
+ const text = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null);
61
+ const number = (value: unknown): number | null => (typeof value === 'number' ? value : null);
62
+
63
+ /** The entry's place, as deep as it goes. */
64
+ function place({ project, environment, key }: AuditEntry): Part[] {
65
+ const path = [project, environment, key].filter((part): part is string => part !== null);
66
+ return path.length === 0 ? ['coffre'] : [{ place: path.join('/') }];
67
+ }
68
+
69
+ function environmentOf({ project, environment }: AuditEntry): Part[] {
70
+ return place({ project, environment, key: null } as AuditEntry);
71
+ }
72
+
73
+ /** The member an entry is about: its subject, or the principal a token entry names. */
74
+ function subject(entry: AuditEntry): Part[] {
75
+ if (entry.subject !== null) return [{ member: entry.subject }];
76
+ const id = text(entry.metadata.principalId);
77
+ if (id === null) return ['someone'];
78
+ return [{ member: `${entry.metadata.principalType === 'service' ? 'token' : 'user'}:${id}` }];
79
+ }
80
+
81
+ function plural(count: number, one: string, many = `${one}s`): string {
82
+ return `${count} ${count === 1 ? one : many}`;
83
+ }
84
+
85
+ /** A batch reads as its environment and a count; one entry as its secret. */
86
+ function secrets(facts: Facts): Part[] {
87
+ if (facts.batch.length === 1) return place(facts.entry);
88
+ return [...environmentOf(facts.entry), facts.refused ? ', ' : ': ', plural(facts.count, 'secret')];
89
+ }
90
+
91
+ /** " to acme/market", when the entry names where a sync pushes. */
92
+ function toDestination(entry: AuditEntry): string {
93
+ const where = text(entry.metadata.destination);
94
+ return where === null ? '' : ` to ${where}`;
95
+ }
96
+
97
+ function destination(entry: AuditEntry): string {
98
+ return text(entry.metadata.destination) ?? 'its destination';
99
+ }
100
+
101
+ const READ_VERBS: Record<string, [did: string, tried: string]> = {
102
+ reveal: ['revealed', 'reveal'],
103
+ run: ['ran', 'run'],
104
+ compare: ['compared', 'compare'],
105
+ sync: ['read', 'read'],
106
+ };
107
+
108
+ function readVerb({ entry }: Facts): [string, string] {
109
+ return READ_VERBS[text(entry.metadata.purpose) ?? 'reveal'] ?? READ_VERBS.reveal!;
110
+ }
111
+
112
+ const placeTemplates = (kind: 'project' | 'environment'): Record<string, Template> => {
113
+ const what = (facts: Facts): Part[] => [`${kind} `, ...(kind === 'project' ? place({ ...facts.entry, environment: null, key: null }) : environmentOf(facts.entry))];
114
+ return {
115
+ [`${kind}.create`]: { did: 'created', tried: 'create', what },
116
+ [`${kind}.update`]: { did: 'changed', tried: 'change', what },
117
+ [`${kind}.archive`]: { did: 'archived', tried: 'archive', what },
118
+ [`${kind}.restore`]: { did: 'restored', tried: 'restore', what },
119
+ };
120
+ };
121
+
122
+ // --- one template per action ----------------------------------------------------
123
+
124
+ const TEMPLATES: Record<string, Template> = {
125
+ 'secret.read': {
126
+ did: (facts) => readVerb(facts)[0],
127
+ tried: (facts) => readVerb(facts)[1],
128
+ what: secrets,
129
+ },
130
+ 'secret.write': {
131
+ // New secrets are added, others changed; a batch of both is written.
132
+ did: ({ batch }) => {
133
+ const firsts = batch.filter((entry) => entry.version === 1).length;
134
+ return firsts === batch.length ? 'added' : firsts === 0 ? 'changed' : 'wrote';
135
+ },
136
+ tried: 'change',
137
+ what: secrets,
138
+ then: ({ entry, batch }) =>
139
+ batch.length > 1 || entry.version === null || entry.version === 1 ? [] : [`, now version ${entry.version}`],
140
+ },
141
+ 'secret.restore': {
142
+ did: 'restored',
143
+ tried: 'restore',
144
+ what: ({ entry }) => [...place(entry), ...(number(entry.metadata.from) === null ? [] : [` to version ${number(entry.metadata.from)}`])],
145
+ then: ({ entry }) => (entry.version === null ? [] : [`, now ${entry.version}`]),
146
+ },
147
+ 'secret.rename': {
148
+ did: 'renamed',
149
+ tried: 'rename',
150
+ what: ({ entry }) => [...place(entry), ...(text(entry.metadata.nextKey) === null ? [] : [` to ${text(entry.metadata.nextKey)}`])],
151
+ },
152
+ 'secret.archive': { did: 'archived', tried: 'archive', what: (facts) => place(facts.entry) },
153
+ 'secret.unarchive': { did: 'brought back', tried: 'bring back', what: (facts) => place(facts.entry) },
154
+ ...placeTemplates('project'),
155
+ ...placeTemplates('environment'),
156
+ 'access.grant': {
157
+ did: 'gave',
158
+ tried: 'give',
159
+ what: ({ entry }) => [...subject(entry), ` ${text(entry.metadata.role) ?? 'a role'} on `, ...placeOnly(entry)],
160
+ then: ({ entry }) => [
161
+ ...(text(entry.metadata.previousRole) === null ? [] : [`, was ${text(entry.metadata.previousRole)}`]),
162
+ ...(text(entry.metadata.expiresAt) === null ? [] : [`, until ${text(entry.metadata.expiresAt)!.slice(0, 10)}`]),
163
+ ],
164
+ },
165
+ 'access.revoke': {
166
+ did: 'took',
167
+ tried: 'take',
168
+ what: ({ entry }) => [
169
+ ...(text(entry.metadata.previousRole ?? entry.metadata.role) === null ? ['access to '] : [`${text(entry.metadata.previousRole ?? entry.metadata.role)} on `]),
170
+ ...placeOnly(entry),
171
+ ' from ',
172
+ ...subject(entry),
173
+ ],
174
+ },
175
+ 'member.add': {
176
+ did: 'added',
177
+ tried: 'add',
178
+ what: ({ entry }) => [
179
+ ...subject(entry),
180
+ ...(entry.metadata.rootAdmin === true ? [' as a root admin'] : entry.metadata.owner === true ? [' as an owner'] : []),
181
+ ],
182
+ },
183
+ 'member.remove': {
184
+ did: 'removed',
185
+ tried: 'remove',
186
+ what: (facts) => subject(facts.entry),
187
+ then: ({ entry }) => (number(entry.metadata.revoked) === null ? [] : [`, who held ${plural(number(entry.metadata.revoked)!, 'grant')}`]),
188
+ },
189
+ 'member.restore': { did: 'brought back', tried: 'bring back', what: (facts) => subject(facts.entry) },
190
+ 'member.owner': {
191
+ did: ({ entry }) => (entry.metadata.owner === false ? 'took owner from' : 'made'),
192
+ tried: ({ entry }) => (entry.metadata.owner === false ? 'take owner from' : 'make'),
193
+ what: ({ entry }) => [...subject(entry), ...(entry.metadata.owner === false ? [] : [' an owner'])],
194
+ },
195
+ 'sync.create': {
196
+ did: 'set up a sync of',
197
+ tried: 'set up a sync of',
198
+ what: ({ entry }) => [...environmentOf(entry), toDestination(entry)],
199
+ },
200
+ 'sync.update': {
201
+ did: ({ entry }) => (entry.metadata.paused === true ? 'paused the sync of' : entry.metadata.paused === false ? 'resumed the sync of' : 'changed the sync of'),
202
+ tried: 'change the sync of',
203
+ what: ({ entry }) => [...environmentOf(entry), toDestination(entry)],
204
+ },
205
+ 'sync.delete': {
206
+ did: 'removed the sync of',
207
+ tried: 'remove the sync of',
208
+ what: ({ entry }) => [...environmentOf(entry), toDestination(entry)],
209
+ },
210
+ 'sync.push': {
211
+ did: 'pushed',
212
+ tried: 'push',
213
+ what: (facts) =>
214
+ facts.batch.length === 1
215
+ ? [...place(facts.entry), ` to ${destination(facts.entry)}`]
216
+ : [...environmentOf(facts.entry), ` to ${destination(facts.entry)}: ${plural(facts.count, 'secret')}`],
217
+ },
218
+ 'sync.remove': {
219
+ did: 'removed',
220
+ tried: 'remove',
221
+ what: (facts) =>
222
+ facts.batch.length === 1
223
+ ? [...place(facts.entry), ` from ${destination(facts.entry)}`]
224
+ : [plural(facts.count, 'secret'), ' of ', ...environmentOf(facts.entry), ` from ${destination(facts.entry)}`],
225
+ },
226
+ 'vault.tampered': {
227
+ did: 'found',
228
+ tried: 'check',
229
+ what: ({ entry }) => [
230
+ ...(entry.subject === null ? ['an entry'] : [...subject(entry), "'s record"]),
231
+ ` tampered with: ${TAMPERING[entry.reason ?? ''] ?? 'it fails its seal'}`,
232
+ ],
233
+ },
234
+
235
+ // Detail, hidden unless asked for.
236
+ sign_in: {
237
+ did: ({ entry }) => (entry.metadata.kind === 'cli' ? 'signed in to the CLI' : 'signed in'),
238
+ tried: 'sign in',
239
+ what: ({ entry }) => (text(entry.metadata.provider) === null ? [] : [`with ${text(entry.metadata.provider)}`]),
240
+ },
241
+ sign_out: { did: 'signed out', tried: 'sign out', what: () => [] },
242
+ 'token.create': { did: 'issued a token to', tried: 'issue a token to', what: (facts) => subject(facts.entry) },
243
+ 'token.revoke': { did: 'revoked a token of', tried: 'revoke a token of', what: (facts) => subject(facts.entry) },
244
+ 'device.approve': { did: 'approved a CLI sign-in', tried: 'approve a CLI sign-in', what: () => [] },
245
+ 'device.deny': { did: 'turned down a CLI sign-in', tried: 'turn down a CLI sign-in', what: () => [] },
246
+ 'account.link': {
247
+ did: 'linked',
248
+ tried: 'link',
249
+ what: ({ entry }) => [`a ${text(entry.metadata.provider) ?? 'sign-in'} account`],
250
+ },
251
+ 'account.unlink': {
252
+ did: 'unlinked',
253
+ tried: 'unlink',
254
+ what: ({ entry }) => [`a ${text(entry.metadata.provider) ?? 'sign-in'} account`],
255
+ },
256
+ 'key.wrap': { did: 'sealed the key of', tried: 'seal the key of', what: (facts) => versioned(facts.entry) },
257
+ 'key.rewrap': { did: 'resealed the key of', tried: 'reseal the key of', what: (facts) => versioned(facts.entry) },
258
+ 'key.intent': { did: 'asked KMS about', tried: 'ask KMS about', what: (facts) => secrets(facts) },
259
+ 'key.check': {
260
+ did: 'recorded the check value of',
261
+ tried: 'check',
262
+ what: ({ entry }) => [['the', text(entry.metadata.kekProvider), 'KEK', text(entry.metadata.kekId)].filter((word) => word !== null).join(' ')],
263
+ },
264
+ 'sync.run': {
265
+ did: 'ran the sync of',
266
+ tried: 'run the sync of',
267
+ what: ({ entry }) => [...environmentOf(entry), toDestination(entry)],
268
+ },
269
+ 'audit.heartbeat': { did: 'checked in', tried: 'check in', what: () => [] },
270
+ 'audit.checkpoint': {
271
+ did: 'signed the log',
272
+ tried: 'sign the log',
273
+ what: ({ entry }) => (number(entry.metadata.seq) === null ? [] : [`through entry ${number(entry.metadata.seq)}`]),
274
+ },
275
+
276
+ // Only ever refused: a read of a list, which is not logged when allowed.
277
+ 'secret.list': { did: 'listed', tried: 'list', what: ({ entry }) => environmentOf(entry) },
278
+ 'secret.history': { did: 'read the history of', tried: 'read the history of', what: (facts) => place(facts.entry) },
279
+ 'secret.update': { did: 'changed', tried: 'change', what: (facts) => place(facts.entry) },
280
+ 'sync.list': { did: 'listed the syncs of', tried: 'list the syncs of', what: ({ entry }) => environmentOf(entry) },
281
+ };
282
+
283
+ function placeOnly(entry: AuditEntry): Part[] {
284
+ return place({ ...entry, key: null });
285
+ }
286
+
287
+ function versioned(entry: AuditEntry): Part[] {
288
+ return [...place(entry), ...(entry.version === null ? [] : [`, version ${entry.version}`])];
289
+ }
290
+
291
+ const TAMPERING: Record<string, string> = {
292
+ mac: "it does not carry the vault's seal",
293
+ stale: 'an older copy was put back',
294
+ forged_entry: 'the vault did not write it',
295
+ };
296
+
297
+ /** Why something was refused, in words. Codes from the vault and the app. */
298
+ const REASONS: Record<string, string> = {
299
+ no_grant: 'no grant',
300
+ bulk_limit: 'bulk limit',
301
+ expired: 'grant expired',
302
+ removed: 'removed from coffre',
303
+ not_a_member: 'not a member',
304
+ not_registered: 'not invited',
305
+ tampered: 'their record was tampered with',
306
+ bad_claim: 'the key did not match the secret',
307
+ not_allowed: 'not allowed',
308
+ root_admin: 'root admins are set by the deployment',
309
+ unknown_environment: 'no such environment',
310
+ unknown_secret: 'no such secret',
311
+ unknown_project: 'no such project',
312
+ unusable_credential: 'its token is not a secret they can read',
313
+ duplicate_destination: 'already synced from elsewhere',
314
+ cannot_grant_sync: 'cannot grant the sync its reads',
315
+ kms_unavailable: 'KMS did not answer',
316
+ wrong_kek: "the vault's KEK is not the one that wrapped the data",
317
+ };
318
+
319
+ /** What a missing permission meant, from the app's `missing_<permission>`. */
320
+ const MISSING: Record<string, string> = {
321
+ secret_read: 'no grant to read it',
322
+ secret_write: 'no grant to write',
323
+ secret_archive: 'no grant to archive',
324
+ audit_read: 'no grant to read the audit log',
325
+ environment_manage: 'no grant to manage environments',
326
+ grant_manage: 'no grant to manage access',
327
+ project_manage: 'no grant to manage the project',
328
+ };
329
+
330
+ export function reasonInWords(reason: string | null): string {
331
+ if (reason === null) return 'refused';
332
+ if (reason.startsWith('missing_')) return MISSING[reason.slice('missing_'.length)] ?? 'no grant';
333
+ return REASONS[reason] ?? reason.replace(/_/g, ' ');
334
+ }
335
+
336
+ // --- lines ----------------------------------------------------------------------
337
+
338
+ /** In a batch of mixed actions, the one the line is named for: a sync's push, not its reads. */
339
+ const LEAD = ['sync.push', 'sync.remove', 'secret.write', 'secret.read'];
340
+
341
+ export function leadOf(batch: AuditEntry[]): AuditEntry {
342
+ for (const action of LEAD) {
343
+ const found = batch.find((entry) => entry.action === action);
344
+ if (found !== undefined) return found;
345
+ }
346
+ return batch[0]!;
347
+ }
348
+
349
+ /** What a line says: one entry, or a batch that shares an operation. */
350
+ export function describe(batch: AuditEntry[]): Sentence {
351
+ const entry = leadOf(batch);
352
+ const same = batch.filter((other) => other.action === entry.action);
353
+ const denied = same.filter((other) => other.decision === 'deny');
354
+ const refused = denied.length === same.length;
355
+ const facts: Facts = {
356
+ entry,
357
+ batch: same,
358
+ count: new Set(same.map((other) => `${other.project}/${other.environment}/${other.key}`)).size,
359
+ refused,
360
+ };
361
+ const template = TEMPLATES[entry.action];
362
+ if (template === undefined) return { parts: [entry.action, ' ', ...place(entry)], refused };
363
+ const say = (verb: Template['did']) => (typeof verb === 'string' ? verb : verb(facts));
364
+ const what = template.what(facts);
365
+ const gap = what.length === 0 ? [] : [' '];
366
+ if (refused) {
367
+ const reason = reasonInWords((denied[0] ?? entry).reason);
368
+ return { parts: ['tried to ', say(template.tried), ...gap, ...what, `: ${reason}`], refused };
369
+ }
370
+ const partly = denied.length === 0 ? [] : [`, ${denied.length} refused: ${reasonInWords(denied[0]!.reason)}`];
371
+ return { parts: [say(template.did), ...gap, ...what, ...(template.then?.(facts) ?? []), ...partly], refused };
372
+ }
373
+
374
+ /**
375
+ * Who acted, as a part: a member links to their page; a sync or coffre
376
+ * itself is text. A sync is named for where it pushes, which any entry of
377
+ * its batch may say.
378
+ */
379
+ export function who(batch: Pick<AuditEntry, 'actorType' | 'actorId' | 'metadata'>[]): string | { member: string } {
380
+ const entry = batch[0]!;
381
+ if (entry.actorType === 'user') return { member: `user:${entry.actorId}` };
382
+ if (entry.actorType === 'service') return { member: `token:${entry.actorId}` };
383
+ if (entry.actorId.startsWith('sync:')) {
384
+ const id = batch.map((other) => text(other.metadata.provider)).find((provider) => provider !== null);
385
+ const provider = id === undefined ? undefined : (PROVIDERS[id!] ?? id!);
386
+ return provider === undefined ? 'a sync' : `sync to ${provider}`;
387
+ }
388
+ return SYSTEM[entry.actorId] ?? entry.actorId;
389
+ }
390
+
391
+ const PROVIDERS: Record<string, string> = {
392
+ 'github-actions': 'GitHub',
393
+ vercel: 'Vercel',
394
+ railway: 'Railway',
395
+ 'cloudflare-workers': 'Cloudflare',
396
+ };
397
+
398
+ const SYSTEM: Record<string, string> = {
399
+ scheduler: 'the scheduler',
400
+ cron: 'the scheduler',
401
+ vault: 'the vault',
402
+ app: 'coffre',
403
+ };
404
+
405
+ /** Which components wrote the line, the vault first: "vault", "app", "vault, app". */
406
+ export function decidedBy(batch: Pick<AuditEntry, 'author'>[]): string {
407
+ return (['vault', 'app'] as const).filter((author) => batch.some((entry) => entry.author === author)).join(', ');
408
+ }
409
+
410
+ /**
411
+ * Entries in the order the page shows them, newest first, each batch as one
412
+ * line at its newest entry. The server leaves detail out unless asked.
413
+ */
414
+ export function lines<T extends AuditEntry>(entries: T[]): T[][] {
415
+ const shown: T[][] = [];
416
+ const batches = new Map<string, T[]>();
417
+ for (const entry of entries) {
418
+ const batch = entry.operationId === null ? undefined : batches.get(entry.operationId);
419
+ if (batch !== undefined) {
420
+ batch.push(entry);
421
+ continue;
422
+ }
423
+ const fresh = [entry];
424
+ if (entry.operationId !== null) batches.set(entry.operationId, fresh);
425
+ shown.push(fresh);
426
+ }
427
+ return shown;
428
+ }
429
+
430
+ /** What a kind of hidden entry is called, by action or its prefix. */
431
+ const HIDDEN_KINDS: [prefix: string, one: string, many: string][] = [
432
+ ['key.', 'key operation', 'key operations'],
433
+ ['sign_in', 'sign-in', 'sign-ins'],
434
+ ['sign_out', 'sign-out', 'sign-outs'],
435
+ ['token.', 'token change', 'token changes'],
436
+ ['device.', 'CLI sign-in approval', 'CLI sign-in approvals'],
437
+ ['account.', 'account link', 'account links'],
438
+ ['sync.run', 'sync run', 'sync runs'],
439
+ ['audit.heartbeat', 'heartbeat', 'heartbeats'],
440
+ ['audit.checkpoint', 'checkpoint', 'checkpoints'],
441
+ ];
442
+
443
+ /**
444
+ * "2 key operations, 3 sign-ins and 12 heartbeats": the detail the server
445
+ * left out of the page, as it counts it, by action.
446
+ */
447
+ export function hiddenInWords(hidden: { action: string; count: number }[]): string | null {
448
+ const counts = new Map<string, { one: string; many: string; count: number }>();
449
+ for (const { action, count } of hidden) {
450
+ if (count === 0) continue;
451
+ const [, one, many] = HIDDEN_KINDS.find(([prefix]) => action.startsWith(prefix)) ?? [action, action, action];
452
+ const kind = counts.get(one) ?? { one, many, count: 0 };
453
+ kind.count += count;
454
+ counts.set(one, kind);
455
+ }
456
+ const phrases = [...counts.values()].map(({ one, many, count }) => `${count} ${count === 1 ? one : many}`);
457
+ if (phrases.length === 0) return null;
458
+ return phrases.length === 1 ? phrases[0]! : `${phrases.slice(0, -1).join(', ')} and ${phrases.at(-1)}`;
459
+ }
460
+
461
+ /** A sentence as text. */
462
+ export function plain(parts: Part[]): string {
463
+ return parts
464
+ .map((part) =>
465
+ typeof part === 'string' ? part : 'place' in part ? part.place : part.member.startsWith('user:') ? part.member.slice(5) : part.member,
466
+ )
467
+ .join('');
468
+ }