@coffre/ui 0.0.0 → 0.1.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 (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,1659 @@
1
+ import { CoffreError, planImport, type CoffreClient } from '@coffre/client';
2
+ import { parseDotenv } from '@coffre/core/dotenv';
3
+ import {
4
+ useEffect,
5
+ useRef,
6
+ useState,
7
+ type ComponentProps,
8
+ type InputHTMLAttributes,
9
+ } from 'react';
10
+ import { createFileRoute, Link, useLoaderData, useRouter } from '@tanstack/react-router';
11
+ import { DropdownMenu } from 'radix-ui';
12
+ import { toast } from 'sonner';
13
+ import { failureMessage, Refusal, uiResult, useCoffre } from '../lib/coffre';
14
+ import { useAction } from '../lib/use-action';
15
+ import type {
16
+ ImportPlanEntry,
17
+ ImportProblem,
18
+ Permission,
19
+ SecretKey,
20
+ SecretVersion,
21
+ } from '../shared/models';
22
+ import { canRevealSecrets } from '../lib/capabilities';
23
+ import {
24
+ applySecretEditBatch,
25
+ hasSecretEditConflict,
26
+ secretChangeFor,
27
+ type SecretChange,
28
+ type SecretDraft,
29
+ } from '../lib/secret-edit-batch';
30
+ import { revealIsCurrent, type Reveal } from '../lib/reveal';
31
+ import { secretKeyProblem } from '../lib/validation';
32
+ import {
33
+ breakAfterUnderscores,
34
+ ConfirmButton,
35
+ CopyButton,
36
+ EmptyState,
37
+ ErrorLine,
38
+ Modal,
39
+ Notice,
40
+ Spinner,
41
+ Timestamp,
42
+ Tip,
43
+ } from '../components/ui';
44
+ import { Card, ClosedDoor, PageHeader } from '../components/page';
45
+ import { SecretReadOnly } from '../components/affordances';
46
+ import { Syncs } from '../components/syncs';
47
+ import {
48
+ AlertCircle,
49
+ Archive,
50
+ Clock,
51
+ Eye,
52
+ EyeOff,
53
+ Hash,
54
+ History,
55
+ Key,
56
+ Lock,
57
+ MoreHorizontal,
58
+ Pencil,
59
+ Plus,
60
+ RotateBack,
61
+ Search,
62
+ Terminal,
63
+ Upload,
64
+ X,
65
+ } from '../components/icons';
66
+
67
+ /**
68
+ * How long a revealed value stays on screen.
69
+ *
70
+ * A revealed secret is live credential material sitting in a browser tab that
71
+ * may well be shared on a call. Hiding it again costs nothing -- the read is
72
+ * already logged, and re-revealing writes a second, honest audit row.
73
+ */
74
+ const REVEAL_TTL_SECONDS = 45;
75
+
76
+ export const Route = createFileRoute('/projects/$project/$environment')({
77
+ // `?filter=KEY` opens the ledger narrowed to matching keys, for links to one secret.
78
+ validateSearch: (search: Record<string, unknown>): { filter?: string } => ({
79
+ filter: typeof search.filter === 'string' && search.filter !== '' ? search.filter : undefined,
80
+ }),
81
+ loader: async ({ context: { client }, params }) => {
82
+ const path = `${params.project}/${params.environment}`;
83
+ const [keys, syncs] = await Promise.all([
84
+ uiResult(() => client.secrets.list(path)),
85
+ uiResult(() => client.syncs.list(path)),
86
+ ]);
87
+ return { keys, syncs };
88
+ },
89
+ component: EnvironmentPage,
90
+ });
91
+
92
+ function EnvironmentPage() {
93
+ const { keys: result, syncs } = Route.useLoaderData();
94
+ const { project, environment } = Route.useParams();
95
+
96
+ if (!result.ok) {
97
+ return (
98
+ <ClosedDoor
99
+ icon={<Lock size={18} />}
100
+ label={
101
+ <span className="mono">
102
+ {project}/{environment}
103
+ </span>
104
+ }
105
+ title="This environment is closed to you"
106
+ actions={
107
+ <Link className="btn" to="/projects/$project" params={{ project }}>
108
+ Back to {project}
109
+ </Link>
110
+ }
111
+ >
112
+ {result.error}
113
+ </ClosedDoor>
114
+ );
115
+ }
116
+
117
+ // Keyed by location: pending edits belong to the environment they were
118
+ // started in. The route component is reused across params, so without the
119
+ // key they would follow you into the next environment and be written there.
120
+ return (
121
+ <EnvironmentLedger
122
+ key={`${project}/${environment}`}
123
+ project={project}
124
+ environment={environment}
125
+ permissions={result.permissions}
126
+ keys={result.keys}
127
+ syncs={syncs}
128
+ />
129
+ );
130
+ }
131
+
132
+ type Pending = { key: string; what: string };
133
+
134
+ function EnvironmentLedger({
135
+ project,
136
+ environment,
137
+ permissions,
138
+ keys,
139
+ syncs,
140
+ }: {
141
+ project: string;
142
+ environment: string;
143
+ permissions: Permission[];
144
+ keys: SecretKey[];
145
+ syncs: ComponentProps<typeof Syncs>['result'];
146
+ }) {
147
+ const router = useRouter();
148
+ const coffre = useCoffre();
149
+ const place = `${project}/${environment}`;
150
+ const [drafts, setDrafts] = useState<SecretDraft[]>([]);
151
+ const [changes, setChanges] = useState<Record<string, SecretChange>>({});
152
+ // Rows opened for editing that may not have changed yet. A row with a
153
+ // pending change is in edit mode whether or not it is listed here.
154
+ const [editing, setEditing] = useState<ReadonlySet<string>>(() => new Set());
155
+ const [saving, setSaving] = useState(false);
156
+ const [saveError, setSaveError] = useState<string | null>(null);
157
+ const [query, setQuery] = useState(Route.useSearch().filter ?? '');
158
+ const nextDraftId = useRef(0);
159
+
160
+ const canWrite = permissions.includes('secret.write');
161
+ const canArchive = permissions.includes('secret.archive');
162
+ const canReveal = canRevealSecrets(permissions);
163
+
164
+ const active = keys.filter((entry) => !entry.archived);
165
+ const archived = keys.filter((entry) => entry.archived);
166
+ const existing = new Set(keys.map((entry) => entry.key));
167
+
168
+ const changedEntries = active.filter(
169
+ (entry) => secretChangeFor(changes, entry.key) !== undefined,
170
+ );
171
+ const hasConflict = hasSecretEditConflict(active, drafts, changes);
172
+ // Every name that will be written. Blank ones only hold the save back -- a
173
+ // row you just added is not an error yet -- while malformed ones say why.
174
+ const pendingNames = [
175
+ ...drafts.map((row) => row.key.trim()),
176
+ ...changedEntries.flatMap((entry) => {
177
+ const change = secretChangeFor(changes, entry.key);
178
+ return change === undefined || change.archived ? [] : [change.key.trim()];
179
+ }),
180
+ ];
181
+ const unnamed = pendingNames.some((name) => name === '');
182
+ const invalid = pendingNames.some((name) => name !== '' && secretKeyProblem(name) !== null);
183
+ const pendingCount = drafts.length + changedEntries.length;
184
+ const ready = pendingCount > 0 && !unnamed && !invalid && !hasConflict;
185
+
186
+ function patchChange(entry: SecretKey, patch: Partial<SecretChange>) {
187
+ setChanges((current) => {
188
+ const next = {
189
+ ...(secretChangeFor(current, entry.key) ?? {
190
+ key: entry.key,
191
+ value: null,
192
+ archived: false,
193
+ }),
194
+ ...patch,
195
+ };
196
+ const dirty = next.key !== entry.key || next.value !== null || next.archived;
197
+ if (dirty) return { ...current, [entry.key]: next };
198
+ const { [entry.key]: _, ...rest } = current;
199
+ return rest;
200
+ });
201
+ }
202
+
203
+ function dropChange(key: string) {
204
+ setChanges((current) => {
205
+ const { [key]: _, ...rest } = current;
206
+ return rest;
207
+ });
208
+ setEditing((current) => {
209
+ const next = new Set(current);
210
+ next.delete(key);
211
+ return next;
212
+ });
213
+ }
214
+
215
+ function addDraft() {
216
+ // New rows go to the top, where the button that made them is, rather than
217
+ // below a list that may be longer than the screen.
218
+ setDrafts((rows) => [{ id: nextDraftId.current++, key: '', value: '' }, ...rows]);
219
+ }
220
+
221
+ function discardAll() {
222
+ setDrafts([]);
223
+ setChanges({});
224
+ setEditing(new Set());
225
+ setSaveError(null);
226
+ }
227
+
228
+ /**
229
+ * Write every pending edit: renames one by one, then the rest as one patch
230
+ * that lands whole or not at all (see `applySecretEditBatch`). Whatever did
231
+ * not land stays pending, so pressing save again retries exactly that.
232
+ */
233
+ async function saveChanges() {
234
+ if (!ready || saving) return;
235
+ setSaving(true);
236
+ setSaveError(null);
237
+ const outcome = await applySecretEditBatch({
238
+ active,
239
+ drafts,
240
+ changes,
241
+ operations: {
242
+ rename: async (key, nextKey) => {
243
+ try {
244
+ await coffre.secrets.rename(`${place}/${key}`, nextKey);
245
+ } catch (error) {
246
+ // A refused rename names the key it stopped at.
247
+ throw new Refusal(`${key}: ${failureMessage(error)}`);
248
+ }
249
+ },
250
+ write: async (patch) => {
251
+ try {
252
+ await coffre.secrets.set(place, patch);
253
+ } catch (error) {
254
+ throw new Refusal(failureMessage(error));
255
+ }
256
+ },
257
+ },
258
+ });
259
+
260
+ setDrafts(outcome.drafts);
261
+ setChanges(outcome.changes);
262
+ setEditing(new Set());
263
+
264
+ if (outcome.applied > 0) {
265
+ try {
266
+ await router.invalidate();
267
+ } catch {
268
+ setSaveError('Saved, but the page could not refresh. Reload before you retry.');
269
+ setSaving(false);
270
+ return;
271
+ }
272
+ }
273
+
274
+ if (outcome.error === null) {
275
+ // Counted as the save button counted them: a rename with a new value is one change.
276
+ toast.success(`Saved ${pendingCount} change${pendingCount === 1 ? '' : 's'}`);
277
+ } else {
278
+ const message =
279
+ outcome.error instanceof Error ? outcome.error.message : 'The request could not be sent.';
280
+ // Only renames can have landed before a failure: the patch is all or nothing.
281
+ setSaveError(
282
+ outcome.applied === 0
283
+ ? message
284
+ : `${message} The renames before it were saved; nothing else was, and the rest is ready to retry.`,
285
+ );
286
+ }
287
+ setSaving(false);
288
+ }
289
+
290
+ // Cmd/Ctrl+Enter saves from anywhere on the page while edits are pending.
291
+ const saveRef = useRef(saveChanges);
292
+ saveRef.current = saveChanges;
293
+ useEffect(() => {
294
+ if (pendingCount === 0) return;
295
+ function onKeyDown(event: KeyboardEvent) {
296
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
297
+ event.preventDefault();
298
+ void saveRef.current();
299
+ }
300
+ }
301
+ document.addEventListener('keydown', onKeyDown);
302
+ return () => document.removeEventListener('keydown', onKeyDown);
303
+ }, [pendingCount]);
304
+
305
+ const pending: Pending[] = [
306
+ ...drafts.map((draft) => ({
307
+ key: draft.key.trim() || 'unnamed',
308
+ what: existing.has(draft.key.trim()) ? 'new version' : 'added',
309
+ })),
310
+ ...changedEntries.map((entry) => {
311
+ const change = secretChangeFor(changes, entry.key)!;
312
+ if (change.archived) return { key: entry.key, what: 'archived' };
313
+ const renamed = change.key.trim() !== entry.key;
314
+ if (renamed && change.value !== null) {
315
+ return { key: entry.key, what: `→ ${change.key.trim()}, new value` };
316
+ }
317
+ if (renamed) return { key: entry.key, what: `→ ${change.key.trim()}` };
318
+ return { key: entry.key, what: 'new value' };
319
+ }),
320
+ ];
321
+
322
+ // Two rows that are both still blank "conflict" too, so say nothing until
323
+ // every name is filled in; the blank row speaks for itself.
324
+ const problem = unnamed
325
+ ? null
326
+ : hasConflict
327
+ ? 'Two pending edits would end up with the same name. Secret names are unique in an environment.'
328
+ : invalid
329
+ ? 'Names are letters, digits and underscores, and cannot start with a digit.'
330
+ : null;
331
+
332
+ // Filtering narrows what is listed, never what is saved: a pending edit on
333
+ // a row the filter hides still counts, and still shows in the save bar.
334
+ const needle = query.trim().toLowerCase();
335
+ const listed =
336
+ needle === '' ? active : active.filter((entry) => entry.key.toLowerCase().includes(needle));
337
+ const columns = 6;
338
+
339
+ return (
340
+ <>
341
+ <PageHeader
342
+ tile={project}
343
+ title={environment}
344
+ aside={<EnvironmentName project={project} environment={environment} />}
345
+ actions={
346
+ <>
347
+ {canWrite && canReveal && <ImportEnv project={project} environment={environment} />}
348
+ {canWrite && (
349
+ <button className="btn btn-primary" onClick={addDraft} disabled={saving}>
350
+ <Plus size={14} />
351
+ New secret
352
+ </button>
353
+ )}
354
+ </>
355
+ }
356
+ />
357
+
358
+ {(active.length > 0 || drafts.length > 0) && (
359
+ <div className="toolbar">
360
+ <label className="filter input-group">
361
+ <span className="visually-hidden">Filter secrets by name</span>
362
+ <Search size={14} className="input-icon" />
363
+ <input
364
+ className="input"
365
+ type="search"
366
+ placeholder="Filter by name…"
367
+ spellCheck={false}
368
+ autoComplete="off"
369
+ value={query}
370
+ onChange={(event) => setQuery(event.target.value)}
371
+ />
372
+ </label>
373
+ <div className="toolbar-meta">
374
+ <span className="th" title="Run a process with these secrets in its environment">
375
+ <Terminal size={14} />
376
+ <code>
377
+ coffre run {project}/{environment} -- …
378
+ </code>
379
+ <CopyButton
380
+ value={`coffre run ${project}/${environment} -- `}
381
+ label="Copy command"
382
+ />
383
+ </span>
384
+ </div>
385
+ </div>
386
+ )}
387
+
388
+ <section className="card" aria-label="Secrets">
389
+ {active.length === 0 && drafts.length === 0 ? (
390
+ <EmptyState
391
+ title="No secrets yet"
392
+ actions={
393
+ canWrite ? (
394
+ <>
395
+ <button className="btn btn-primary" onClick={addDraft}>
396
+ <Plus size={14} />
397
+ New secret
398
+ </button>
399
+ {canReveal && <ImportEnv project={project} environment={environment} />}
400
+ </>
401
+ ) : undefined
402
+ }
403
+ >
404
+ {canWrite
405
+ ? 'Add them one by one, or import an existing .env file. Nothing is written until you save, or until you have seen the import plan.'
406
+ : 'Nothing has been written to this environment, and adding the first secret needs secret.write.'}
407
+ </EmptyState>
408
+ ) : (
409
+ <div className="dt-wrap">
410
+ <table className="dt secrets stacks">
411
+ <thead>
412
+ <tr>
413
+ <th className="n">#</th>
414
+ <th className="col-key">
415
+ <span className="th">
416
+ <Key size={14} />
417
+ Key
418
+ </span>
419
+ </th>
420
+ <th>
421
+ <span className="th">
422
+ <Lock size={14} />
423
+ Value
424
+ {!canReveal && <span className="th-note">hidden from you</span>}
425
+ </span>
426
+ </th>
427
+ <th className="col-version">
428
+ <span className="th">
429
+ <Hash size={14} />
430
+ Version
431
+ </span>
432
+ </th>
433
+ <th className="col-written col-hide-narrow">
434
+ <span className="th">
435
+ <Clock size={14} />
436
+ Last written
437
+ </span>
438
+ </th>
439
+ <th className="col-actions">
440
+ <span className="visually-hidden">Actions</span>
441
+ </th>
442
+ </tr>
443
+ </thead>
444
+ <tbody>
445
+ {drafts.map((draft) => (
446
+ <DraftRow
447
+ key={draft.id}
448
+ draft={draft}
449
+ existingVersion={
450
+ keys.find((entry) => entry.key === draft.key.trim())?.version ?? null
451
+ }
452
+ disabled={saving}
453
+ onChange={(patch) =>
454
+ setDrafts((rows) =>
455
+ rows.map((row) => (row.id === draft.id ? { ...row, ...patch } : row)),
456
+ )
457
+ }
458
+ onRemove={() => setDrafts((rows) => rows.filter((row) => row.id !== draft.id))}
459
+ />
460
+ ))}
461
+
462
+ {listed.map((entry) => {
463
+ const change = secretChangeFor(changes, entry.key);
464
+ return (
465
+ <SecretRow
466
+ key={entry.key}
467
+ number={active.indexOf(entry) + 1}
468
+ project={project}
469
+ environment={environment}
470
+ entry={entry}
471
+ change={change ?? { key: entry.key, value: null, archived: false }}
472
+ editing={
473
+ change?.archived !== true &&
474
+ (editing.has(entry.key) || change !== undefined)
475
+ }
476
+ canWrite={canWrite}
477
+ canArchive={canArchive}
478
+ canReveal={canReveal}
479
+ disabled={saving}
480
+ columns={columns}
481
+ onEdit={() => setEditing((current) => new Set(current).add(entry.key))}
482
+ onPatch={(patch) => patchChange(entry, patch)}
483
+ onUndo={() => dropChange(entry.key)}
484
+ onMarkArchive={() => {
485
+ setEditing((current) => {
486
+ const next = new Set(current);
487
+ next.delete(entry.key);
488
+ return next;
489
+ });
490
+ setChanges((current) => ({
491
+ ...current,
492
+ [entry.key]: { key: entry.key, value: null, archived: true },
493
+ }));
494
+ }}
495
+ />
496
+ );
497
+ })}
498
+
499
+ {listed.length === 0 && active.length > 0 && (
500
+ <tr>
501
+ <td colSpan={columns} className="cell-muted" style={{ padding: '1rem' }}>
502
+ No secret name contains “{query.trim()}”.
503
+ </td>
504
+ </tr>
505
+ )}
506
+ </tbody>
507
+ </table>
508
+ </div>
509
+ )}
510
+ </section>
511
+
512
+ <Syncs
513
+ project={project}
514
+ environment={environment}
515
+ result={syncs}
516
+ canRun={canWrite || permissions.includes('environment.manage')}
517
+ />
518
+
519
+ {archived.length > 0 && (
520
+ <Card
521
+ labelledBy="archived-secrets"
522
+ title="Archived"
523
+ description={
524
+ <>
525
+ Retired, so no longer served or injected by <code>coffre run</code>. Their history
526
+ and audit trail are intact, and restoring is immediate.
527
+ </>
528
+ }
529
+ >
530
+ <div className="dt-wrap">
531
+ <table className="dt secrets secrets-archived stacks">
532
+ <thead>
533
+ <tr>
534
+ <th className="n">#</th>
535
+ <th className="col-key">
536
+ <span className="th">
537
+ <Key size={14} />
538
+ Key
539
+ </span>
540
+ </th>
541
+ <th className="col-version">
542
+ <span className="th">
543
+ <Hash size={14} />
544
+ Version
545
+ </span>
546
+ </th>
547
+ <th className="col-written col-hide-narrow">
548
+ <span className="th">
549
+ <Clock size={14} />
550
+ Last written
551
+ </span>
552
+ </th>
553
+ <th className="col-actions">
554
+ <span className="visually-hidden">Actions</span>
555
+ </th>
556
+ </tr>
557
+ </thead>
558
+ <tbody>
559
+ {archived.map((entry, index) => (
560
+ <ArchivedRow
561
+ key={entry.key}
562
+ number={index + 1}
563
+ project={project}
564
+ environment={environment}
565
+ entry={entry}
566
+ canArchive={canArchive}
567
+ canReveal={canReveal}
568
+ />
569
+ ))}
570
+ </tbody>
571
+ </table>
572
+ </div>
573
+ </Card>
574
+ )}
575
+
576
+ {pendingCount > 0 && (
577
+ <div className="savebar" role="region" aria-label="Unsaved changes">
578
+ <div className="savebar-inner">
579
+ <span className="savebar-count">
580
+ <span className="dot" aria-hidden />
581
+ {pendingCount} unsaved change{pendingCount === 1 ? '' : 's'}
582
+ </span>
583
+ <span className="savebar-summary">
584
+ {pending.slice(0, 3).map((item, index) => (
585
+ <span key={`${item.key}:${index}`}>
586
+ {index > 0 && ' · '}
587
+ <span className="mono">{item.key}</span> {item.what}
588
+ </span>
589
+ ))}
590
+ {pending.length > 3 && ` · and ${pending.length - 3} more`}
591
+ </span>
592
+ <div className="savebar-actions">
593
+ <button className="btn btn-sm" onClick={discardAll} disabled={saving}>
594
+ Discard
595
+ </button>
596
+ <button
597
+ className="btn btn-sm btn-primary"
598
+ onClick={() => void saveChanges()}
599
+ disabled={saving || !ready}
600
+ title="Save (⌘ Enter or Ctrl Enter)"
601
+ aria-keyshortcuts="Meta+Enter Control+Enter"
602
+ >
603
+ {saving && <Spinner size={13} />}
604
+ Save {pendingCount === 1 ? 'change' : `${pendingCount} changes`}
605
+ </button>
606
+ </div>
607
+ {(saveError ?? problem) !== null && (
608
+ <p className="savebar-error" role="alert">
609
+ <AlertCircle size={14} />
610
+ <span>{saveError ?? problem}</span>
611
+ </p>
612
+ )}
613
+ </div>
614
+ </div>
615
+ )}
616
+ </>
617
+ );
618
+ }
619
+
620
+ /** The display name sits beside the slug; it comes from the shell's project tree. */
621
+ function EnvironmentName({ project, environment }: { project: string; environment: string }) {
622
+ const { projects } = useLoaderData({ from: '__root__' });
623
+ const name = projects
624
+ .find((entry) => entry.slug === project)
625
+ ?.environments.find((entry) => entry.slug === environment)?.name;
626
+ return name === undefined ? null : <>{name}</>;
627
+ }
628
+
629
+ /* -------------------------------------------------------------------------- */
630
+ /* Rows */
631
+ /* -------------------------------------------------------------------------- */
632
+
633
+ /**
634
+ * A text field whose contents are masked until asked, for secret values.
635
+ *
636
+ * Where the browser supports it, the mask is CSS on a text input rather than
637
+ * `type="password"`: password fields invite password managers to offer to
638
+ * save or fill them, and a secret being typed into coffre is neither.
639
+ */
640
+ function MaskedInput({
641
+ masked,
642
+ className = '',
643
+ ...props
644
+ }: Omit<InputHTMLAttributes<HTMLInputElement>, 'type'> & { masked: boolean }) {
645
+ const [cssMask, setCssMask] = useState(false);
646
+ useEffect(() => {
647
+ setCssMask(typeof CSS !== 'undefined' && CSS.supports('-webkit-text-security', 'disc'));
648
+ }, []);
649
+
650
+ return (
651
+ <input
652
+ {...props}
653
+ type={masked && !cssMask ? 'password' : 'text'}
654
+ className={`${className}${masked && cssMask ? ' is-masked' : ''}`}
655
+ autoComplete="off"
656
+ spellCheck={false}
657
+ data-1p-ignore
658
+ data-lpignore="true"
659
+ data-bwignore
660
+ />
661
+ );
662
+ }
663
+
664
+ function ValueField({
665
+ label,
666
+ value,
667
+ onChange,
668
+ placeholder,
669
+ disabled,
670
+ autoFocus,
671
+ onEscape,
672
+ }: {
673
+ label: string;
674
+ value: string;
675
+ onChange: (value: string) => void;
676
+ placeholder: string;
677
+ disabled: boolean;
678
+ autoFocus?: boolean;
679
+ onEscape?: () => void;
680
+ }) {
681
+ const [shown, setShown] = useState(false);
682
+ return (
683
+ <div className="input-group">
684
+ <MaskedInput
685
+ className="input input-mono"
686
+ masked={!shown}
687
+ aria-label={label}
688
+ placeholder={placeholder}
689
+ value={value}
690
+ disabled={disabled}
691
+ autoFocus={autoFocus}
692
+ onChange={(event) => onChange(event.target.value)}
693
+ onKeyDown={(event) => {
694
+ if (event.key === 'Escape' && onEscape !== undefined) onEscape();
695
+ }}
696
+ />
697
+ <button
698
+ type="button"
699
+ className="btn btn-quiet btn-sm btn-icon input-addon"
700
+ aria-label={shown ? 'Mask the value' : 'Show the value'}
701
+ aria-pressed={shown}
702
+ onClick={() => setShown((current) => !current)}
703
+ >
704
+ {shown ? <EyeOff size={14} /> : <Eye size={14} />}
705
+ </button>
706
+ </div>
707
+ );
708
+ }
709
+
710
+ function useSecondsLeft(reveal: Reveal | null): number {
711
+ const [now, setNow] = useState(() => Date.now());
712
+ useEffect(() => {
713
+ if (reveal === null) return;
714
+ setNow(Date.now());
715
+ const tick = setInterval(() => setNow(Date.now()), 1000);
716
+ return () => clearInterval(tick);
717
+ }, [reveal]);
718
+ if (reveal === null) return 0;
719
+ return Math.max(0, Math.ceil(REVEAL_TTL_SECONDS - (now - reveal.at) / 1000));
720
+ }
721
+
722
+ function SecretRow({
723
+ number,
724
+ project,
725
+ environment,
726
+ entry,
727
+ change,
728
+ editing,
729
+ canWrite,
730
+ canArchive,
731
+ canReveal,
732
+ disabled,
733
+ columns,
734
+ onEdit,
735
+ onPatch,
736
+ onUndo,
737
+ onMarkArchive,
738
+ }: {
739
+ number: number;
740
+ project: string;
741
+ environment: string;
742
+ entry: SecretKey;
743
+ change: SecretChange;
744
+ editing: boolean;
745
+ canWrite: boolean;
746
+ canArchive: boolean;
747
+ canReveal: boolean;
748
+ disabled: boolean;
749
+ columns: number;
750
+ onEdit: () => void;
751
+ onPatch: (patch: Partial<SecretChange>) => void;
752
+ onUndo: () => void;
753
+ onMarkArchive: () => void;
754
+ }) {
755
+ const [reveal, setReveal] = useState<Reveal | null>(null);
756
+ const coffre = useCoffre();
757
+ const [revealing, setRevealing] = useState(false);
758
+ const [historyOpen, setHistoryOpen] = useState(false);
759
+ const [error, setError] = useState<string | null>(null);
760
+ // The current value, loaded on request as the starting point for an edit.
761
+ // It is not a change until it is edited: saving it untouched would append a
762
+ // version identical to the one it came from.
763
+ const [base, setBase] = useState<Reveal | null>(null);
764
+
765
+ // A reveal belongs to the version it decrypted. The moment the row shows a
766
+ // different version -- saved here, rolled back, or written by someone else
767
+ // and picked up on refresh -- the old plaintext is not the value any more,
768
+ // and must not stay on screen pretending to be.
769
+ const shown = revealIsCurrent(reveal, entry.version) ? reveal : null;
770
+ useEffect(() => {
771
+ if (reveal !== null && !revealIsCurrent(reveal, entry.version)) setReveal(null);
772
+ }, [reveal, entry.version]);
773
+
774
+ useEffect(() => {
775
+ if (reveal === null) return;
776
+ const timer = setTimeout(() => setReveal(null), REVEAL_TTL_SECONDS * 1000);
777
+ return () => clearTimeout(timer);
778
+ }, [reveal]);
779
+
780
+ const secondsLeft = useSecondsLeft(shown);
781
+
782
+ const editBase = editing && revealIsCurrent(base, entry.version) ? base : null;
783
+ useEffect(() => {
784
+ if (!editing) setBase(null);
785
+ }, [editing]);
786
+
787
+ async function readValue(): Promise<string | null> {
788
+ if (shown !== null) return shown.value;
789
+ setRevealing(true);
790
+ try {
791
+ const { values } = await coffre.secrets.reveal(`${project}/${environment}/${entry.key}`);
792
+ const value = values[entry.key];
793
+ setError(null);
794
+ setReveal({ value, version: entry.version, at: Date.now() });
795
+ return value;
796
+ } catch (failure) {
797
+ setError(
798
+ failure instanceof CoffreError
799
+ ? failureMessage(failure)
800
+ : 'The request could not be sent. Nothing was read.',
801
+ );
802
+ return null;
803
+ } finally {
804
+ setRevealing(false);
805
+ }
806
+ }
807
+
808
+ function toggleReveal() {
809
+ if (shown !== null) setReveal(null);
810
+ else void readValue();
811
+ }
812
+
813
+ const leaving = change.archived;
814
+ const renamed = change.key !== entry.key;
815
+ const valueChanged = change.value !== null;
816
+ const keyProblem = editing ? secretKeyProblem(change.key.trim()) : null;
817
+ const state = leaving
818
+ ? ' is-leaving'
819
+ : editing && (renamed || valueChanged)
820
+ ? ' is-changed'
821
+ : shown !== null
822
+ ? ' is-revealed'
823
+ : '';
824
+ const version = entry.version ?? 0;
825
+
826
+ return (
827
+ <>
828
+ <tr className={`secret-row${state}`}>
829
+ <td className="n">{number}</td>
830
+ <td className="cell-key" data-label="Key">
831
+ {editing && canWrite ? (
832
+ <div className="edit-stack">
833
+ <input
834
+ className="input input-mono"
835
+ aria-label={`Name for ${entry.key}`}
836
+ aria-invalid={keyProblem !== null}
837
+ spellCheck={false}
838
+ autoComplete="off"
839
+ value={change.key}
840
+ disabled={disabled}
841
+ onChange={(event) => onPatch({ key: event.target.value })}
842
+ onKeyDown={(event) => {
843
+ if (event.key === 'Escape') onUndo();
844
+ }}
845
+ />
846
+ {(keyProblem !== null || renamed) && (
847
+ <span className={`edit-note${keyProblem !== null ? ' edit-note-error' : ''}`}>
848
+ {keyProblem ?? (
849
+ <>
850
+ Renamed from <span className="mono">{entry.key}</span>
851
+ </>
852
+ )}
853
+ </span>
854
+ )}
855
+ </div>
856
+ ) : (
857
+ <div className="key-cell">
858
+ <span>{breakAfterUnderscores(entry.key)}</span>
859
+ {leaving && <span className="tag tag-red">will be archived</span>}
860
+ </div>
861
+ )}
862
+ </td>
863
+
864
+ <td data-label="Value">
865
+ {editing && canWrite ? (
866
+ <div className="edit-stack">
867
+ <ValueField
868
+ label={`New value for ${entry.key}`}
869
+ value={change.value ?? editBase?.value ?? ''}
870
+ placeholder="New value"
871
+ disabled={disabled}
872
+ autoFocus
873
+ onChange={(value) =>
874
+ onPatch({ value: value === (editBase?.value ?? '') ? null : value })
875
+ }
876
+ onEscape={onUndo}
877
+ />
878
+ <span className="edit-note">
879
+ <span>
880
+ {valueChanged
881
+ ? `Saving appends v${version + 1}; v${version} stays restorable.`
882
+ : editBase !== null
883
+ ? `This is v${version}. Change it to append v${version + 1}.`
884
+ : `Nothing is decrypted to edit. Left empty, v${version} stays current.`}
885
+ </span>
886
+ {canReveal && !valueChanged && editBase === null && (
887
+ <button
888
+ type="button"
889
+ className="act"
890
+ disabled={revealing}
891
+ onClick={async () => {
892
+ const value = await readValue();
893
+ if (value !== null) {
894
+ setBase({ value, version: entry.version, at: Date.now() });
895
+ }
896
+ }}
897
+ >
898
+ {revealing && <Spinner size={12} />}
899
+ Start from current value
900
+ </button>
901
+ )}
902
+ </span>
903
+ </div>
904
+ ) : shown !== null && !leaving ? (
905
+ <div
906
+ className="revealed"
907
+ style={{ ['--reveal-ttl' as string]: `${REVEAL_TTL_SECONDS}s` }}
908
+ >
909
+ <span className="revealed-value">{shown.value === '' ? '(empty)' : shown.value}</span>
910
+ <span className="revealed-note">
911
+ Hides in {secondsLeft}s
912
+ </span>
913
+ <span className="revealed-meter" aria-hidden />
914
+ </div>
915
+ ) : (
916
+ <span className="mask" aria-label="Hidden">
917
+ ••••••••••••
918
+ </span>
919
+ )}
920
+ </td>
921
+
922
+ <td className="col-version" data-label="Version">
923
+ {editing && valueChanged ? (
924
+ <span className="version-shift">
925
+ v{version} → <b>v{version + 1}</b>
926
+ </span>
927
+ ) : (
928
+ <span className="version-shift">{entry.version === null ? '—' : `v${entry.version}`}</span>
929
+ )}
930
+ </td>
931
+
932
+ <td className="col-written col-hide-narrow" data-label="Last written">
933
+ <Written entry={entry} />
934
+ </td>
935
+
936
+ <td className="col-actions">
937
+ <div className="acts">
938
+ {leaving ? (
939
+ <Tip label="Keep">
940
+ <button
941
+ className="act act-icon act-quiet"
942
+ onClick={onUndo}
943
+ disabled={disabled}
944
+ aria-label={`Keep ${entry.key}`}
945
+ >
946
+ <RotateBack size={14} />
947
+ </button>
948
+ </Tip>
949
+ ) : editing ? (
950
+ <Tip label={renamed || valueChanged ? 'Undo changes' : 'Cancel'}>
951
+ <button
952
+ className="act act-icon act-quiet"
953
+ onClick={onUndo}
954
+ disabled={disabled}
955
+ aria-label={`${renamed || valueChanged ? 'Undo changes to' : 'Stop editing'} ${entry.key}`}
956
+ >
957
+ {renamed || valueChanged ? <RotateBack size={14} /> : <X size={15} />}
958
+ </button>
959
+ </Tip>
960
+ ) : (
961
+ <>
962
+ {/* Copy comes in to the left, so Hide stays where Reveal was clicked. */}
963
+ {shown !== null && (
964
+ <CopyButton variant="act" value={shown.value} label={`Copy ${entry.key}`} />
965
+ )}
966
+ <SecretReadOnly canReveal={canReveal}>
967
+ <Tip label={shown === null ? 'Reveal' : 'Hide'}>
968
+ <button
969
+ className="act act-icon act-accent"
970
+ onClick={toggleReveal}
971
+ disabled={revealing}
972
+ aria-label={`${shown === null ? 'Reveal' : 'Hide'} ${entry.key}`}
973
+ >
974
+ {revealing ? (
975
+ <Spinner size={13} />
976
+ ) : shown === null ? (
977
+ <Eye size={15} />
978
+ ) : (
979
+ <EyeOff size={15} />
980
+ )}
981
+ </button>
982
+ </Tip>
983
+ </SecretReadOnly>
984
+ {canWrite && (
985
+ <Tip label="Edit">
986
+ <button
987
+ className="act act-icon"
988
+ onClick={() => {
989
+ // A value already revealed is already on the record, so
990
+ // it becomes the starting point instead of being thrown
991
+ // away and read again.
992
+ if (shown !== null) setBase(shown);
993
+ setReveal(null);
994
+ onEdit();
995
+ }}
996
+ disabled={disabled}
997
+ aria-label={`Edit ${entry.key}`}
998
+ >
999
+ <Pencil size={14} />
1000
+ </button>
1001
+ </Tip>
1002
+ )}
1003
+ {(canReveal || canArchive) && (
1004
+ <DropdownMenu.Root>
1005
+ <DropdownMenu.Trigger asChild>
1006
+ <button
1007
+ className="act act-icon act-quiet"
1008
+ aria-label={`More for ${entry.key}`}
1009
+ disabled={disabled}
1010
+ >
1011
+ <MoreHorizontal size={16} />
1012
+ </button>
1013
+ </DropdownMenu.Trigger>
1014
+ <DropdownMenu.Portal>
1015
+ <DropdownMenu.Content className="menu" sideOffset={6} align="end">
1016
+ <SecretReadOnly canReveal={canReveal}>
1017
+ <DropdownMenu.Item
1018
+ className="menu-item"
1019
+ onSelect={() => setHistoryOpen((open) => !open)}
1020
+ >
1021
+ <History size={14} />
1022
+ {historyOpen ? 'Hide history' : 'Version history'}
1023
+ </DropdownMenu.Item>
1024
+ </SecretReadOnly>
1025
+ {canArchive && (
1026
+ <>
1027
+ {canReveal && <DropdownMenu.Separator className="menu-sep" />}
1028
+ <DropdownMenu.Item
1029
+ className="menu-item menu-item-danger"
1030
+ onSelect={() => {
1031
+ setReveal(null);
1032
+ onMarkArchive();
1033
+ }}
1034
+ >
1035
+ <Archive size={14} />
1036
+ Archive
1037
+ <span className="menu-hint">on save</span>
1038
+ </DropdownMenu.Item>
1039
+ </>
1040
+ )}
1041
+ </DropdownMenu.Content>
1042
+ </DropdownMenu.Portal>
1043
+ </DropdownMenu.Root>
1044
+ )}
1045
+ </>
1046
+ )}
1047
+ </div>
1048
+ </td>
1049
+ </tr>
1050
+
1051
+ {historyOpen && canReveal && (
1052
+ <tr className="detail-row">
1053
+ <td colSpan={columns}>
1054
+ <VersionHistory
1055
+ project={project}
1056
+ environment={environment}
1057
+ secretKey={entry.key}
1058
+ currentVersion={entry.version}
1059
+ canWrite={canWrite}
1060
+ onClose={() => setHistoryOpen(false)}
1061
+ onRolledBack={() => setReveal(null)}
1062
+ />
1063
+ </td>
1064
+ </tr>
1065
+ )}
1066
+
1067
+ {error !== null && (
1068
+ <tr className="row-error">
1069
+ <td colSpan={columns}>
1070
+ <ErrorLine error={error} />
1071
+ </td>
1072
+ </tr>
1073
+ )}
1074
+ </>
1075
+ );
1076
+ }
1077
+
1078
+ /**
1079
+ * Who wrote the current version and how long ago, on one line: the local part
1080
+ * of the email is enough to recognise a colleague, and the full address and
1081
+ * the exact time are a hover away.
1082
+ */
1083
+ function Written({ entry }: { entry: SecretKey }) {
1084
+ if (entry.updatedBy === null && entry.updatedAt === null) {
1085
+ return <span className="cell-muted">—</span>;
1086
+ }
1087
+ const by = entry.updatedBy ?? 'unknown';
1088
+ return (
1089
+ <span className="written">
1090
+ <span className="written-by" title={by}>
1091
+ {by.split('@')[0]}
1092
+ </span>
1093
+ {entry.updatedAt !== null && (
1094
+ <>
1095
+ <span className="cell-muted" aria-hidden>
1096
+ ·
1097
+ </span>
1098
+ <span className="cell-muted">
1099
+ <Timestamp iso={entry.updatedAt} display="relative" />
1100
+ </span>
1101
+ </>
1102
+ )}
1103
+ </span>
1104
+ );
1105
+ }
1106
+
1107
+ /**
1108
+ * A secret being typed, sitting in the table where it will end up.
1109
+ *
1110
+ * This replaced a separate "Add a secret" form. The form made you look away
1111
+ * from the list to add to it, and only ever accepted one key at a time; a row
1112
+ * in place accepts as many as you want to queue.
1113
+ */
1114
+ function DraftRow({
1115
+ draft,
1116
+ existingVersion,
1117
+ disabled,
1118
+ onChange,
1119
+ onRemove,
1120
+ }: {
1121
+ draft: SecretDraft;
1122
+ existingVersion: number | null;
1123
+ disabled: boolean;
1124
+ onChange: (patch: Partial<SecretDraft>) => void;
1125
+ onRemove: () => void;
1126
+ }) {
1127
+ const [touched, setTouched] = useState(false);
1128
+ const trimmed = draft.key.trim();
1129
+ const keyProblem = trimmed === '' ? (touched ? 'Give it a name.' : null) : secretKeyProblem(trimmed);
1130
+ const isNewVersion = trimmed !== '' && existingVersion !== null;
1131
+
1132
+ return (
1133
+ <tr className="secret-row is-draft">
1134
+ <td className="n" aria-label="New">
1135
+ +
1136
+ </td>
1137
+ <td className="cell-key" data-label="New secret">
1138
+ <div className="edit-stack">
1139
+ <input
1140
+ className="input input-mono"
1141
+ // Only the row that just mounted takes focus, which is the one the
1142
+ // New secret button created.
1143
+ autoFocus
1144
+ aria-label="Name of the new secret"
1145
+ aria-invalid={keyProblem !== null}
1146
+ placeholder="NAME_OF_SECRET"
1147
+ spellCheck={false}
1148
+ autoComplete="off"
1149
+ value={draft.key}
1150
+ disabled={disabled}
1151
+ onBlur={() => setTouched(true)}
1152
+ onChange={(event) => onChange({ key: event.target.value })}
1153
+ onKeyDown={(event) => {
1154
+ if (event.key === 'Escape') onRemove();
1155
+ }}
1156
+ />
1157
+ {(keyProblem !== null || isNewVersion) && (
1158
+ <span className={`edit-note${keyProblem !== null ? ' edit-note-error' : ''}`}>
1159
+ {keyProblem ??
1160
+ 'This name already exists here. Saving appends a new version to it rather than creating a second secret.'}
1161
+ </span>
1162
+ )}
1163
+ </div>
1164
+ </td>
1165
+ <td data-label="Value">
1166
+ <div className="edit-stack">
1167
+ <ValueField
1168
+ label={`Value for ${trimmed === '' ? 'the new secret' : trimmed}`}
1169
+ value={draft.value}
1170
+ placeholder="Value"
1171
+ disabled={disabled}
1172
+ onChange={(value) => onChange({ value })}
1173
+ onEscape={onRemove}
1174
+ />
1175
+ </div>
1176
+ </td>
1177
+ <td className="col-version" data-label="Version">
1178
+ <span className="version-shift">
1179
+ {isNewVersion ? (
1180
+ <>
1181
+ v{existingVersion} → <b>v{existingVersion + 1}</b>
1182
+ </>
1183
+ ) : (
1184
+ <b>new</b>
1185
+ )}
1186
+ </span>
1187
+ </td>
1188
+ <td className="col-written col-hide-narrow">
1189
+ <span className="cell-muted">—</span>
1190
+ </td>
1191
+ <td className="col-actions">
1192
+ <div className="acts">
1193
+ <Tip label="Remove">
1194
+ <button
1195
+ className="act act-icon act-quiet"
1196
+ onClick={onRemove}
1197
+ disabled={disabled}
1198
+ aria-label={trimmed === '' ? 'Remove this new secret' : `Remove new secret ${trimmed}`}
1199
+ >
1200
+ <X size={15} />
1201
+ </button>
1202
+ </Tip>
1203
+ </div>
1204
+ </td>
1205
+ </tr>
1206
+ );
1207
+ }
1208
+
1209
+ function ArchivedRow({
1210
+ number,
1211
+ project,
1212
+ environment,
1213
+ entry,
1214
+ canArchive,
1215
+ canReveal,
1216
+ }: {
1217
+ number: number;
1218
+ project: string;
1219
+ environment: string;
1220
+ entry: SecretKey;
1221
+ canArchive: boolean;
1222
+ canReveal: boolean;
1223
+ }) {
1224
+ const [historyOpen, setHistoryOpen] = useState(false);
1225
+ const coffre = useCoffre();
1226
+ const { pending, error, run } = useAction();
1227
+
1228
+ function setArchived(archived: boolean) {
1229
+ run(
1230
+ () => coffre.secrets.update(`${project}/${environment}/${entry.key}`, { archived }),
1231
+ () =>
1232
+ // Restoring is fully reversible, so it gets an undo rather than a
1233
+ // confirmation dialog in front of it.
1234
+ toast.success(archived ? `${entry.key} archived` : `${entry.key} restored`, {
1235
+ action: { label: 'Undo', onClick: () => setArchived(!archived) },
1236
+ }),
1237
+ );
1238
+ }
1239
+
1240
+ return (
1241
+ <>
1242
+ <tr className="secret-row is-archived">
1243
+ <td className="n">{number}</td>
1244
+ <td className="cell-key" data-label="Key">
1245
+ {breakAfterUnderscores(entry.key)}
1246
+ </td>
1247
+ <td className="col-version" data-label="Version">
1248
+ <span className="version-shift">{entry.version === null ? '—' : `v${entry.version}`}</span>
1249
+ </td>
1250
+ <td className="col-written col-hide-narrow" data-label="Last written">
1251
+ <Written entry={entry} />
1252
+ </td>
1253
+ <td className="col-actions">
1254
+ <div className="acts">
1255
+ <SecretReadOnly canReveal={canReveal}>
1256
+ <Tip label={historyOpen ? 'Hide history' : 'Version history'}>
1257
+ <button
1258
+ className="act act-icon act-quiet"
1259
+ onClick={() => setHistoryOpen((open) => !open)}
1260
+ aria-label={`${historyOpen ? 'Hide history of' : 'Version history of'} ${entry.key}`}
1261
+ aria-expanded={historyOpen}
1262
+ >
1263
+ <History size={15} />
1264
+ </button>
1265
+ </Tip>
1266
+ </SecretReadOnly>
1267
+ {canArchive && (
1268
+ <Tip label="Restore">
1269
+ <button
1270
+ className="act act-icon"
1271
+ onClick={() => setArchived(false)}
1272
+ disabled={pending}
1273
+ aria-label={`Restore ${entry.key}`}
1274
+ >
1275
+ {pending ? <Spinner size={13} /> : <RotateBack size={14} />}
1276
+ </button>
1277
+ </Tip>
1278
+ )}
1279
+ </div>
1280
+ </td>
1281
+ </tr>
1282
+ {historyOpen && (
1283
+ <tr className="detail-row">
1284
+ <td colSpan={5}>
1285
+ <VersionHistory
1286
+ project={project}
1287
+ environment={environment}
1288
+ secretKey={entry.key}
1289
+ currentVersion={entry.version}
1290
+ canWrite={false}
1291
+ onClose={() => setHistoryOpen(false)}
1292
+ onRolledBack={() => undefined}
1293
+ />
1294
+ </td>
1295
+ </tr>
1296
+ )}
1297
+ {error !== null && (
1298
+ <tr className="row-error">
1299
+ <td colSpan={5}>
1300
+ <ErrorLine error={error} />
1301
+ </td>
1302
+ </tr>
1303
+ )}
1304
+ </>
1305
+ );
1306
+ }
1307
+
1308
+ /* -------------------------------------------------------------------------- */
1309
+ /* History */
1310
+ /* -------------------------------------------------------------------------- */
1311
+
1312
+ function VersionHistory({
1313
+ project,
1314
+ environment,
1315
+ secretKey,
1316
+ currentVersion,
1317
+ canWrite,
1318
+ onClose,
1319
+ onRolledBack,
1320
+ }: {
1321
+ project: string;
1322
+ environment: string;
1323
+ secretKey: string;
1324
+ currentVersion: number | null;
1325
+ canWrite: boolean;
1326
+ onClose: () => void;
1327
+ onRolledBack: () => void;
1328
+ }) {
1329
+ const [versions, setVersions] = useState<SecretVersion[] | null>(null);
1330
+ const [loadError, setLoadError] = useState<string | null>(null);
1331
+ const coffre = useCoffre();
1332
+ const { pending, error, run } = useAction();
1333
+
1334
+ // Refetch whenever the current version moves, so a rollback -- here or by
1335
+ // anyone else -- is reflected in which row says "current".
1336
+ useEffect(() => {
1337
+ let cancelled = false;
1338
+ coffre.secrets
1339
+ .history(`${project}/${environment}/${secretKey}`)
1340
+ .then((result) => {
1341
+ if (cancelled) return;
1342
+ setVersions(result.versions);
1343
+ setLoadError(null);
1344
+ })
1345
+ .catch((failure: unknown) => {
1346
+ if (cancelled) return;
1347
+ setLoadError(
1348
+ failure instanceof CoffreError
1349
+ ? failureMessage(failure)
1350
+ : 'The version history could not be loaded.',
1351
+ );
1352
+ });
1353
+ return () => {
1354
+ cancelled = true;
1355
+ };
1356
+ }, [coffre, project, environment, secretKey, currentVersion]);
1357
+
1358
+ return (
1359
+ <div className="history">
1360
+ <div className="history-head">
1361
+ <span className="history-title th">
1362
+ <History size={14} />
1363
+ Versions of <span className="mono">{secretKey}</span>
1364
+ </span>
1365
+ <button className="act" onClick={onClose}>
1366
+ Close
1367
+ </button>
1368
+ </div>
1369
+
1370
+ {loadError !== null ? (
1371
+ <div className="history-body">
1372
+ <ErrorLine error={loadError} />
1373
+ </div>
1374
+ ) : versions === null ? (
1375
+ <p className="hint history-body">
1376
+ <Spinner size={13} /> Loading versions…
1377
+ </p>
1378
+ ) : (
1379
+ <div className="dt-wrap">
1380
+ <table className="dt">
1381
+ <thead>
1382
+ <tr>
1383
+ <th className="col-shrink">Version</th>
1384
+ <th className="col-shrink">Written (UTC)</th>
1385
+ <th>By</th>
1386
+ <th className="col-shrink">Key id</th>
1387
+ <th className="col-actions">
1388
+ <span className="visually-hidden">Actions</span>
1389
+ </th>
1390
+ </tr>
1391
+ </thead>
1392
+ <tbody>
1393
+ {versions.map((version) => (
1394
+ <tr key={version.version}>
1395
+ <td className="cell-mono nowrap">
1396
+ v{version.version}{' '}
1397
+ {version.current && <span className="tag tag-blue">current</span>}
1398
+ </td>
1399
+ <td className="nowrap">
1400
+ <Timestamp iso={version.createdAt} />
1401
+ </td>
1402
+ <td>{version.createdBy}</td>
1403
+ <td className="cell-mono cell-muted nowrap">{version.kek}</td>
1404
+ <td className="col-actions">
1405
+ {canWrite && !version.current && (
1406
+ <ConfirmButton
1407
+ trigger={
1408
+ <button className="act" disabled={pending}>
1409
+ <RotateBack size={13} />
1410
+ Roll back
1411
+ </button>
1412
+ }
1413
+ title={
1414
+ <>
1415
+ Roll <span className="mono">{secretKey}</span> back to v
1416
+ {version.version}?
1417
+ </>
1418
+ }
1419
+ body={
1420
+ <>
1421
+ The current pointer moves to v{version.version}. Nothing is copied
1422
+ or deleted, every version stays readable, and the next write
1423
+ continues the numbering forward. Anything reading{' '}
1424
+ <span className="mono">
1425
+ {project}/{environment}
1426
+ </span>{' '}
1427
+ picks up the change immediately.
1428
+ </>
1429
+ }
1430
+ confirmLabel={`Roll back to v${version.version}`}
1431
+ destructive={false}
1432
+ onConfirm={() =>
1433
+ run(
1434
+ () =>
1435
+ coffre.secrets.restore(
1436
+ `${project}/${environment}/${secretKey}`,
1437
+ version.version,
1438
+ ),
1439
+ () => {
1440
+ onRolledBack();
1441
+ toast.success(`${secretKey} rolled back to v${version.version}`);
1442
+ },
1443
+ )
1444
+ }
1445
+ />
1446
+ )}
1447
+ </td>
1448
+ </tr>
1449
+ ))}
1450
+ </tbody>
1451
+ </table>
1452
+ </div>
1453
+ )}
1454
+
1455
+ {error !== null && (
1456
+ <div className="history-body">
1457
+ <ErrorLine error={error} />
1458
+ </div>
1459
+ )}
1460
+ <p className="history-note">
1461
+ Metadata only. Listing versions decrypts nothing.
1462
+ </p>
1463
+ </div>
1464
+ );
1465
+ }
1466
+
1467
+ /* -------------------------------------------------------------------------- */
1468
+ /* Import */
1469
+ /* -------------------------------------------------------------------------- */
1470
+
1471
+ const PLAN_TAG: Record<ImportPlanEntry['action'], string> = {
1472
+ added: 'tag tag-green',
1473
+ changed: 'tag tag-blue',
1474
+ unchanged: 'tag',
1475
+ };
1476
+
1477
+ /** Plan a .env import against what is stored, with a dry run of the write. */
1478
+ async function planEnv(coffre: CoffreClient, path: string, content: string) {
1479
+ const parsed = parseDotenv(content);
1480
+ if (parsed.entries.length === 0) return { plan: [], changes: {}, problems: parsed.problems };
1481
+ return { ...(await planImport(coffre, path, parsed.entries)), problems: parsed.problems };
1482
+ }
1483
+
1484
+ /**
1485
+ * Bulk import from a .env file.
1486
+ *
1487
+ * Always previews first, with a dry run of the write: the server compares
1488
+ * the file against the current values and answers per key, so no value
1489
+ * reaches this page. Comparing is still reading -- it needs secret.read as
1490
+ * well as secret.write, and the values it opens are logged as reads. Writing
1491
+ * then sends exactly the changes the preview showed, in one patch.
1492
+ */
1493
+ function ImportEnv({ project, environment }: { project: string; environment: string }) {
1494
+ const [content, setContent] = useState('');
1495
+ const [plan, setPlan] = useState<{ entries: ImportPlanEntry[]; changes: Record<string, string> } | null>(
1496
+ null,
1497
+ );
1498
+ const [problems, setProblems] = useState<ImportProblem[]>([]);
1499
+ const [open, setOpen] = useState(false);
1500
+ const coffre = useCoffre();
1501
+ const { pending, error, setError, run } = useAction();
1502
+ const path = `${project}/${environment}`;
1503
+
1504
+ function preview() {
1505
+ run(
1506
+ () => planEnv(coffre, path, content),
1507
+ (result) => {
1508
+ setProblems(result.problems);
1509
+ setPlan({ entries: result.plan, changes: result.changes });
1510
+ },
1511
+ );
1512
+ }
1513
+
1514
+ function apply() {
1515
+ if (plan === null) return;
1516
+ const written = Object.keys(plan.changes).length;
1517
+ run(
1518
+ () => coffre.secrets.set(path, plan.changes),
1519
+ () => {
1520
+ toast.success(`Imported ${written} change${written === 1 ? '' : 's'}`);
1521
+ close();
1522
+ },
1523
+ );
1524
+ }
1525
+
1526
+ function close() {
1527
+ setOpen(false);
1528
+ setPlan(null);
1529
+ setContent('');
1530
+ setProblems([]);
1531
+ setError(null);
1532
+ }
1533
+
1534
+ const changes = plan?.entries.filter((entry) => entry.action !== 'unchanged') ?? [];
1535
+
1536
+ return (
1537
+ <>
1538
+ <button className="btn" onClick={() => setOpen(true)}>
1539
+ <Upload size={14} />
1540
+ Import .env
1541
+ </button>
1542
+
1543
+ <Modal
1544
+ open={open}
1545
+ onOpenChange={(next) => (next ? setOpen(true) : close())}
1546
+ title={
1547
+ <>
1548
+ Import into{' '}
1549
+ <span className="mono">
1550
+ {project}/{environment}
1551
+ </span>
1552
+ </>
1553
+ }
1554
+ wide
1555
+ description={
1556
+ <>
1557
+ Paste a .env file. It is read by the CLI’s own parser, so this page and the CLI
1558
+ cannot disagree about what it means, and malformed lines are reported rather
1559
+ than guessed at. coffre compares it with the current values without sending any
1560
+ to this page.
1561
+ </>
1562
+ }
1563
+ >
1564
+ <div className="form" style={{ marginTop: '1.25rem' }}>
1565
+ <label className="field">
1566
+ <span className="label">File contents</span>
1567
+ <textarea
1568
+ className="textarea"
1569
+ autoFocus
1570
+ spellCheck={false}
1571
+ placeholder={'DATABASE_URL=postgres://…\nSTRIPE_KEY="sk_live_…"'}
1572
+ value={content}
1573
+ onChange={(event) => {
1574
+ setContent(event.target.value);
1575
+ setPlan(null);
1576
+ setProblems([]);
1577
+ }}
1578
+ />
1579
+ </label>
1580
+
1581
+ {plan !== null && plan.entries.length > 0 && (
1582
+ <div className="card dt-wrap">
1583
+ <table className="dt">
1584
+ <thead>
1585
+ <tr>
1586
+ <th>Key</th>
1587
+ <th className="col-shrink">Plan</th>
1588
+ <th className="col-shrink">Current</th>
1589
+ </tr>
1590
+ </thead>
1591
+ <tbody>
1592
+ {plan.entries.map((entry) => (
1593
+ <tr key={entry.key}>
1594
+ <td className="cell-key">{breakAfterUnderscores(entry.key)}</td>
1595
+ <td className="col-shrink">
1596
+ <span className={PLAN_TAG[entry.action]}>{entry.action}</span>
1597
+ </td>
1598
+ <td className="col-shrink cell-mono cell-muted">
1599
+ {entry.version === null ? '—' : `v${entry.version}`}
1600
+ </td>
1601
+ </tr>
1602
+ ))}
1603
+ </tbody>
1604
+ </table>
1605
+ </div>
1606
+ )}
1607
+
1608
+ {plan !== null && plan.entries.length > 0 && changes.length === 0 && (
1609
+ <Notice tone="good">Every key already has this value. There is nothing to write.</Notice>
1610
+ )}
1611
+
1612
+ {problems.length > 0 && (
1613
+ <Notice tone="bad">
1614
+ <strong>
1615
+ {problems.length} line{problems.length === 1 ? '' : 's'} could not be parsed
1616
+ </strong>
1617
+ <ul style={{ margin: '0.375rem 0 0', paddingLeft: '1.1rem' }}>
1618
+ {problems.map((problem) => (
1619
+ <li key={problem.line}>
1620
+ Line {problem.line}: {problem.reason}{' '}
1621
+ <span className="mono">({problem.text})</span>
1622
+ </li>
1623
+ ))}
1624
+ </ul>
1625
+ </Notice>
1626
+ )}
1627
+
1628
+ <ErrorLine error={error} />
1629
+
1630
+ <div className="dialog-actions">
1631
+ <button className="btn" onClick={close}>
1632
+ Cancel
1633
+ </button>
1634
+ {plan === null ? (
1635
+ <button
1636
+ className="btn btn-primary"
1637
+ disabled={pending || content.trim() === ''}
1638
+ onClick={preview}
1639
+ >
1640
+ {pending && <Spinner />}
1641
+ Preview changes
1642
+ </button>
1643
+ ) : (
1644
+ <button
1645
+ className="btn btn-primary"
1646
+ disabled={pending || changes.length === 0}
1647
+ onClick={apply}
1648
+ >
1649
+ {pending && <Spinner />}
1650
+ Write {changes.length} change{changes.length === 1 ? '' : 's'}
1651
+ </button>
1652
+ )}
1653
+ </div>
1654
+ </div>
1655
+ </Modal>
1656
+ </>
1657
+ );
1658
+ }
1659
+