@coffre/ui 0.1.10 → 0.1.12

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 (172) hide show
  1. package/dist/client/_coffre/assets/account-CyJDFhek.js +2 -0
  2. package/dist/client/_coffre/assets/account-DHSs5h2f.js +1 -0
  3. package/dist/client/_coffre/assets/affordances-BQD5B421.js +1 -0
  4. package/dist/client/_coffre/assets/audit-Bcyp_dU1.js +2 -0
  5. package/dist/client/_coffre/assets/audit-rMy9mU9Q.js +1 -0
  6. package/dist/client/_coffre/assets/auth.device-DuvaComb.js +1 -0
  7. package/dist/client/_coffre/assets/auth.device-yBt_sLZW.js +2 -0
  8. package/dist/client/_coffre/assets/directory-C4BMGC7-.js +1 -0
  9. package/dist/client/_coffre/assets/dist-BNkBTkxj.js +1 -0
  10. package/dist/client/_coffre/assets/globals-BJkzu6T5.css +1 -0
  11. package/dist/client/_coffre/assets/grants-CyDW25eX.js +1 -0
  12. package/dist/client/_coffre/assets/icons-BRl8DlXW.js +1 -0
  13. package/dist/client/_coffre/assets/index-CA1mtrIx.js +12 -0
  14. package/dist/client/_coffre/assets/link-CqlAJWBd.js +1 -0
  15. package/dist/client/_coffre/assets/login-B73b6bsJ.js +1 -0
  16. package/dist/client/_coffre/assets/login-BO1KAGPU.js +2 -0
  17. package/dist/client/_coffre/assets/offboarding--5vSKNHv.js +1 -0
  18. package/dist/client/_coffre/assets/page-Dngv8FMr.js +1 -0
  19. package/dist/client/_coffre/assets/preload-helper-DBha3tys.js +1 -0
  20. package/dist/client/_coffre/assets/principal-page-C4qDD-d8.js +1 -0
  21. package/dist/client/_coffre/assets/projects._project._environment-eBKxOZ0_.js +2 -0
  22. package/dist/client/_coffre/assets/projects._project._environment-or_AX6o5.js +3 -0
  23. package/dist/client/_coffre/assets/projects._project.index-DHdXfEh-.js +2 -0
  24. package/dist/client/_coffre/assets/projects._project.index-iynQgenH.js +1 -0
  25. package/dist/client/_coffre/assets/projects.index-CGW8mRil.js +1 -0
  26. package/dist/client/_coffre/assets/row-state-BlarvG7E.js +1 -0
  27. package/dist/client/_coffre/assets/settings-D-7RJIDf.js +1 -0
  28. package/dist/client/_coffre/assets/suspense-q_eJaZ18.js +1 -0
  29. package/dist/client/_coffre/assets/tokens._token-0u7midqA.js +2 -0
  30. package/dist/client/_coffre/assets/tokens._token-C53NqScg.js +1 -0
  31. package/dist/client/_coffre/assets/tokens.index-DBZTLnbi.js +1 -0
  32. package/dist/client/_coffre/assets/ui-BPWFJNz7.js +46 -0
  33. package/dist/client/_coffre/assets/unregistered-CLhgtwUt.js +1 -0
  34. package/dist/client/_coffre/assets/use-action-LULgF26O.js +1 -0
  35. package/dist/client/_coffre/assets/use-change-Bd6NZJj9.js +1 -0
  36. package/dist/client/_coffre/assets/use-shell-Dx92Huhb.js +1 -0
  37. package/dist/client/_coffre/assets/useQuery-BIIZz1CB.js +1 -0
  38. package/dist/client/_coffre/assets/useSuspenseQuery-tP9HFZ8w.js +1 -0
  39. package/dist/client/_coffre/assets/users._user-BXtaL8Ee.js +2 -0
  40. package/dist/client/_coffre/assets/users._user-CNYVkXaY.js +1 -0
  41. package/dist/client/_coffre/assets/users.index-Cs9tibIv.js +1 -0
  42. package/dist/server/.vite/manifest.json +342 -246
  43. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-T9tMsCwo.js +162 -0
  44. package/dist/server/_coffre/assets/{account-CUQYGCYh.js → account-BUhhOS5-.js} +150 -117
  45. package/dist/server/_coffre/assets/{account-DMlUoBxQ.js → account-B_h55GCs.js} +10 -24
  46. package/dist/server/_coffre/assets/{affordances-BNaXjMOb.js → affordances-CKANXDTG.js} +2 -22
  47. package/dist/server/_coffre/assets/{async-local-storage-C0cwgkEr.js → async-local-storage-C10uQtMM.js} +3 -2
  48. package/dist/server/_coffre/assets/{audit-CCdSLmvK.js → audit-B8Ck358-.js} +46 -16
  49. package/dist/server/_coffre/assets/audit-DFsXfeAQ.js +31 -0
  50. package/dist/server/_coffre/assets/{auth.device-BoFM1jcf.js → auth.device-BXf_JjT7.js} +5 -5
  51. package/dist/server/_coffre/assets/{auth.device-C05u5ROO.js → auth.device-cqjWACvB.js} +7 -5
  52. package/dist/server/_coffre/assets/{directory-GsnYkse0.js → directory-C9SfNgpM.js} +87 -112
  53. package/dist/server/_coffre/assets/{use-action-DwEmf58L.js → dist-CnnV3t2g.js} +3 -48
  54. package/dist/server/_coffre/assets/globals-BJkzu6T5.css +1 -0
  55. package/dist/server/_coffre/assets/grants--315KmXu.js +158 -0
  56. package/dist/server/_coffre/assets/{page-BdnhpwvH.js → icons-CWsTEfpn.js} +125 -436
  57. package/dist/server/_coffre/assets/lazyRouteComponent-CqBNCGuZ.js +480 -0
  58. package/dist/server/_coffre/assets/link-42ZWdjzZ.js +422 -0
  59. package/dist/server/_coffre/assets/{login-DUtCQju5.js → login-CQSkYW_D.js} +7 -5
  60. package/dist/server/_coffre/assets/{login-B2njIq_o.js → login-LBpXXfsQ.js} +2 -2
  61. package/dist/server/_coffre/assets/matchContext-qLfYbC6_.js +56 -0
  62. package/dist/server/_coffre/assets/{offboarding-8yMa7ViM.js → offboarding-CykelNis.js} +11 -79
  63. package/dist/server/_coffre/assets/page-BGeDoQO5.js +3531 -0
  64. package/dist/server/_coffre/assets/{principal-page-B8zPcS2b.js → principal-page-CRdoAQOq.js} +51 -42
  65. package/dist/server/_coffre/assets/{projects._project._environment-DdIOc7wx.js → projects._project._environment-BXU1Mee5.js} +4 -11
  66. package/dist/server/_coffre/assets/{projects._project._environment-BZ5Z80V8.js → projects._project._environment-BrDqn8kW.js} +129 -748
  67. package/dist/server/_coffre/assets/{projects._project.index-CuEAUwGn.js → projects._project.index-CAxBU4tY.js} +134 -96
  68. package/dist/server/_coffre/assets/{projects._project.index-DvbcU1kh.js → projects._project.index-CYyUVTCl.js} +5 -4
  69. package/dist/server/_coffre/assets/{projects.index-5HI0wOuG.js → projects.index-D6ZoDE_0.js} +57 -55
  70. package/dist/server/_coffre/assets/{react-dom-qCTiwGGR.js → react-dom-bBoJXlK2.js} +417 -51
  71. package/dist/server/_coffre/assets/{router-CQDoql8s.js → router-Bu2qtyqw.js} +376 -92
  72. package/dist/server/_coffre/assets/row-state-CAItu3n_.js +117 -0
  73. package/dist/server/_coffre/assets/{settings-BVz78wjP.js → settings-ByeF6hBa.js} +8 -6
  74. package/dist/server/_coffre/assets/suspense-beD01bb8.js +602 -0
  75. package/dist/server/_coffre/assets/tokens._token-CM01QPCq.js +10 -0
  76. package/dist/server/_coffre/assets/{tokens._token-CWs3Mtki.js → tokens._token-D2E4P3Qc.js} +97 -79
  77. package/dist/server/_coffre/assets/{tokens.index-Ck0LN7aC.js → tokens.index-Cmrgn3mU.js} +9 -6
  78. package/dist/server/_coffre/assets/{ui-D_slKpSF.js → ui-DvlGkmaH.js} +7 -836
  79. package/dist/server/_coffre/assets/{unregistered-Z17da4Rc.js → unregistered-DSArejP9.js} +5 -3
  80. package/dist/server/_coffre/assets/use-action-C2wz34kq.js +47 -0
  81. package/dist/server/_coffre/assets/use-change-CJpGSNIq.js +1212 -0
  82. package/dist/server/_coffre/assets/use-shell-C3iYcyP1.js +462 -0
  83. package/dist/server/_coffre/assets/useQuery-ChxaQ4Cb.js +8 -0
  84. package/dist/server/_coffre/assets/{useStore-DWGPqzXR.js → useRouter-CaUSUNsw.js} +1 -420
  85. package/dist/server/_coffre/assets/useSuspenseQuery-BjAmlGZl.js +117 -0
  86. package/dist/server/_coffre/assets/users._user-BVeR9fZP.js +10 -0
  87. package/dist/server/_coffre/assets/{users._user-CMwj-VI9.js → users._user-Cih2Etf4.js} +4 -5
  88. package/dist/server/_coffre/assets/{users.index-fWHv6A30.js → users.index-Bo2_a95G.js} +9 -6
  89. package/dist/server/index.js +6 -5
  90. package/package.json +5 -3
  91. package/src/components/directory.tsx +75 -104
  92. package/src/components/grants.tsx +60 -112
  93. package/src/components/icons.tsx +0 -34
  94. package/src/components/offboarding.tsx +1 -52
  95. package/src/components/principal-page.tsx +54 -67
  96. package/src/components/principal-picker.tsx +7 -16
  97. package/src/components/row-state.tsx +95 -0
  98. package/src/components/service-tokens.tsx +75 -64
  99. package/src/components/shell.tsx +1 -1
  100. package/src/lib/announce.ts +36 -0
  101. package/src/lib/changes.ts +498 -0
  102. package/src/lib/coffre.ts +1 -1
  103. package/src/lib/optimistic.ts +233 -0
  104. package/src/lib/queries.ts +385 -0
  105. package/src/lib/use-action.ts +20 -15
  106. package/src/lib/use-change.ts +42 -0
  107. package/src/lib/use-shell.ts +17 -0
  108. package/src/router.tsx +17 -9
  109. package/src/routes/__root.tsx +8 -38
  110. package/src/routes/account.tsx +163 -154
  111. package/src/routes/audit.tsx +51 -72
  112. package/src/routes/auth.device.tsx +4 -2
  113. package/src/routes/login.tsx +3 -2
  114. package/src/routes/projects.$project.$environment.tsx +223 -238
  115. package/src/routes/projects.$project.index.tsx +136 -118
  116. package/src/routes/projects.index.tsx +117 -145
  117. package/src/routes/settings.tsx +7 -7
  118. package/src/routes/tokens.$token.tsx +14 -17
  119. package/src/routes/tokens.index.tsx +8 -4
  120. package/src/routes/unregistered.tsx +3 -2
  121. package/src/routes/users.$user.tsx +4 -4
  122. package/src/routes/users.index.tsx +8 -4
  123. package/src/shared/models.ts +1 -5
  124. package/src/styles/globals.css +80 -50
  125. package/dist/client/_coffre/assets/account-B48wuSF8.js +0 -1
  126. package/dist/client/_coffre/assets/account-BkNyIDT7.js +0 -2
  127. package/dist/client/_coffre/assets/affordances-CmoY-8Xf.js +0 -1
  128. package/dist/client/_coffre/assets/audit-BvwKYb-5.js +0 -2
  129. package/dist/client/_coffre/assets/audit-D02H-zxS.js +0 -1
  130. package/dist/client/_coffre/assets/auth.device-BP5FY0K1.js +0 -1
  131. package/dist/client/_coffre/assets/auth.device-DYOONgFF.js +0 -2
  132. package/dist/client/_coffre/assets/coffre-BBp7cKVa.js +0 -1
  133. package/dist/client/_coffre/assets/directory-Bu0EIxqI.js +0 -1
  134. package/dist/client/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  135. package/dist/client/_coffre/assets/grants-DavcwofW.js +0 -1
  136. package/dist/client/_coffre/assets/index-CDPlq5rM.js +0 -12
  137. package/dist/client/_coffre/assets/login-C-wTm_t1.js +0 -2
  138. package/dist/client/_coffre/assets/login-CLLv1om9.js +0 -1
  139. package/dist/client/_coffre/assets/offboarding-DWsE2FSa.js +0 -1
  140. package/dist/client/_coffre/assets/page-DbSS7pYH.js +0 -1
  141. package/dist/client/_coffre/assets/preload-helper-DduCCcmc.js +0 -46
  142. package/dist/client/_coffre/assets/principal-page-Bp_iwuSd.js +0 -1
  143. package/dist/client/_coffre/assets/projects._project._environment-BMeX_B8l.js +0 -2
  144. package/dist/client/_coffre/assets/projects._project._environment-CT0A-hIU.js +0 -3
  145. package/dist/client/_coffre/assets/projects._project.index-C_xYOGLT.js +0 -2
  146. package/dist/client/_coffre/assets/projects._project.index-Chcf-cUd.js +0 -1
  147. package/dist/client/_coffre/assets/projects.index-CfOtb1X5.js +0 -2
  148. package/dist/client/_coffre/assets/projects.index-DSjOhLDh.js +0 -1
  149. package/dist/client/_coffre/assets/settings-BC9cUJNK.js +0 -1
  150. package/dist/client/_coffre/assets/settings-Bkj_E21y.js +0 -2
  151. package/dist/client/_coffre/assets/tokens._token-BA0KqvaW.js +0 -1
  152. package/dist/client/_coffre/assets/tokens._token-Dh9jLOkm.js +0 -2
  153. package/dist/client/_coffre/assets/tokens.index-BgAMWkHT.js +0 -2
  154. package/dist/client/_coffre/assets/tokens.index-CHueIAv1.js +0 -1
  155. package/dist/client/_coffre/assets/unregistered-D5go1AfR.js +0 -1
  156. package/dist/client/_coffre/assets/use-action-l__xZDYY.js +0 -1
  157. package/dist/client/_coffre/assets/users._user-Dwqa0gv5.js +0 -1
  158. package/dist/client/_coffre/assets/users._user-xJAb3T6Y.js +0 -2
  159. package/dist/client/_coffre/assets/users.index-BJoF-L37.js +0 -2
  160. package/dist/client/_coffre/assets/users.index-YUjtbTGy.js +0 -1
  161. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-BKg2AlPu.js +0 -133
  162. package/dist/server/_coffre/assets/audit-CThXn2v7.js +0 -74
  163. package/dist/server/_coffre/assets/coffre-C2ANsTAz.js +0 -281
  164. package/dist/server/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  165. package/dist/server/_coffre/assets/grants-B6k4Fu9z.js +0 -243
  166. package/dist/server/_coffre/assets/projects.index-uiomWX_l.js +0 -54
  167. package/dist/server/_coffre/assets/settings-4oRyDizv.js +0 -18
  168. package/dist/server/_coffre/assets/tokens._token-CF_deAwq.js +0 -18
  169. package/dist/server/_coffre/assets/tokens.index-DF_07KEe.js +0 -10
  170. package/dist/server/_coffre/assets/users._user-DUzwkSKT.js +0 -10
  171. package/dist/server/_coffre/assets/users.index-BbuweTwH.js +0 -10
  172. package/src/components/syncs.tsx +0 -581
@@ -0,0 +1,498 @@
1
+ import type { CoffreClient, IdentityRow, SecretKey, SessionRow } from '@coffre/client';
2
+ import type { Role } from '@coffre/core/access';
3
+ import type { QueryKey } from '@tanstack/react-query';
4
+
5
+ import { failureMessage, memberRef, Refusal } from './coffre.ts';
6
+ import { projectAccessLabel } from './project-access.ts';
7
+ import type { Change, ListShape, Target, Words } from './optimistic.ts';
8
+ import { affects, keys } from './queries.ts';
9
+ import { applySecretEditBatch, type SecretChange, type SecretDraft, type SecretEditBatchResult } from './secret-edit-batch.ts';
10
+ import type { DirectoryPrincipal, GrantRow, ProjectSummary } from '../shared/models.ts';
11
+
12
+ /**
13
+ * Every change the pages make before the server answers, one per kind, each
14
+ * with the list it shows in (`lib/optimistic.ts`). Issuing a token is not
15
+ * here: only the server can show what it issued.
16
+ */
17
+
18
+ type Failure = { ok: false; error: string };
19
+
20
+ /** A list held in a read's `field`, when the read answered. */
21
+ function listOf<TItem, TData extends { ok: boolean } | null>(
22
+ queryKey: QueryKey,
23
+ field: string,
24
+ id: (item: TItem) => string,
25
+ ): ListShape<TData, TItem> {
26
+ return {
27
+ queryKey,
28
+ items: (data) => (data?.ok === true ? ((data as unknown as Record<string, TItem[]>)[field] ?? []) : []),
29
+ withItems: (data, items) => (data?.ok === true ? { ...data, [field]: items } : data),
30
+ id,
31
+ };
32
+ }
33
+
34
+ const ARCHIVING: Words = { pending: 'Archiving…', done: 'archived', failed: 'Not archived.' };
35
+ const REVOKING: Words = { pending: 'Revoking…', done: 'revoked', failed: 'Not revoked.' };
36
+
37
+ const saving = (id: string): Target => ({ id, kind: 'saving' });
38
+ const removing = (id: string): Target => ({ id, kind: 'removing' });
39
+
40
+ // --- access --------------------------------------------------------------------
41
+
42
+ type Grants = ({ ok: true; grants: GrantRow[] } | Failure);
43
+
44
+ /** A grant's identity, before the server has given it an id: who, and where. */
45
+ export function grantId(grant: Pick<GrantRow, 'principalType' | 'principalId' | 'environmentSlug'>): string {
46
+ return `${memberRef(grant.principalType, grant.principalId)}@${grant.environmentSlug ?? ''}`;
47
+ }
48
+
49
+ export function grantsList(project: string) {
50
+ return listOf<GrantRow, Grants>(keys.grants(project), 'grants', grantId);
51
+ }
52
+
53
+ /** Where a grant applies, as the API names it: `market`, or `market/prod`. */
54
+ export function grantPlace(project: string, environmentSlug: string | null): string {
55
+ return environmentSlug === null ? project : `${project}/${environmentSlug}`;
56
+ }
57
+
58
+ export type GrantVars = {
59
+ principalType: GrantRow['principalType'];
60
+ principalId: string;
61
+ role: string;
62
+ /** How the role is shown while it saves. */
63
+ roleName: string;
64
+ environmentSlug: string | null;
65
+ expiresAt: string | null;
66
+ };
67
+
68
+ /**
69
+ * Give someone a role at one place. Access is declarative, so asking for what
70
+ * they already hold is not an error, whoever asked first: `existed` says so.
71
+ */
72
+ export function grantAccess(client: CoffreClient, project: string): Change<Grants, GrantRow, GrantVars, { existed: boolean }> {
73
+ const list = grantsList(project);
74
+ return {
75
+ list,
76
+ label: (vars) => `${vars.roleName} for ${vars.principalId}`,
77
+ targets: (vars) => [saving(grantId(vars))],
78
+ apply: (grants, vars) => {
79
+ const row: GrantRow = {
80
+ id: `pending:${grantId(vars)}`,
81
+ principalType: vars.principalType,
82
+ principalId: vars.principalId,
83
+ role: vars.role,
84
+ roleName: vars.roleName,
85
+ permissions: [],
86
+ scope: vars.environmentSlug === null ? 'project' : 'environment',
87
+ environmentSlug: vars.environmentSlug,
88
+ expiresAt: vars.expiresAt,
89
+ };
90
+ const id = grantId(vars);
91
+ return grants.some((grant) => grantId(grant) === id)
92
+ ? grants.map((grant) => (grantId(grant) === id ? { ...row, id: grant.id } : grant))
93
+ : [...grants, row];
94
+ },
95
+ affects: (vars) => affects.access(project, memberRef(vars.principalType, vars.principalId)),
96
+ run: async (vars) => {
97
+ const place = grantPlace(project, vars.environmentSlug);
98
+ const role = vars.role as Role;
99
+ const { changes } = await client.access.set(memberRef(vars.principalType, vars.principalId), {
100
+ [place]: vars.expiresAt === null ? role : { role, until: vars.expiresAt },
101
+ });
102
+ return { existed: changes[place] === 'unchanged' };
103
+ },
104
+ };
105
+ }
106
+
107
+ export function revokeGrant(client: CoffreClient, project: string): Change<Grants, GrantRow, GrantRow, unknown> {
108
+ return {
109
+ list: grantsList(project),
110
+ label: (grant) => `${projectAccessLabel(grant)} for ${grant.principalId}`,
111
+ targets: (grant) => [removing(grantId(grant))],
112
+ removing: REVOKING,
113
+ affects: (grant) => affects.access(project, memberRef(grant.principalType, grant.principalId)),
114
+ run: (grant) =>
115
+ client.access.set(memberRef(grant.principalType, grant.principalId), {
116
+ [grantPlace(project, grant.environmentSlug)]: null,
117
+ }),
118
+ };
119
+ }
120
+
121
+ // --- the directory -------------------------------------------------------------
122
+
123
+ type Directory = ({ ok: true; principals: DirectoryPrincipal[] } | Failure);
124
+
125
+ const principalId = (principal: Pick<DirectoryPrincipal, 'principalType' | 'principalId'>) =>
126
+ memberRef(principal.principalType, principal.principalId);
127
+
128
+ /** The directory as owners read it: the only ones who change it. */
129
+ export const directoryList = listOf<DirectoryPrincipal, Directory>([...keys.directory, { owner: true }], 'principals', principalId);
130
+
131
+ export type InviteVars = { principalType: DirectoryPrincipal['principalType']; principalId: string; owner: boolean };
132
+
133
+ export function invite(client: CoffreClient): Change<Directory, DirectoryPrincipal, InviteVars, void> {
134
+ return {
135
+ list: directoryList,
136
+ label: (vars) => vars.principalId,
137
+ targets: (vars) => [saving(principalId(vars))],
138
+ // Someone already listed is not added twice: the server will say they exist.
139
+ apply: (principals, vars) =>
140
+ principals.some((principal) => principalId(principal) === principalId(vars)) ? principals : [
141
+ ...principals,
142
+ {
143
+ principalType: vars.principalType,
144
+ principalId: vars.principalId,
145
+ instanceRole: vars.owner ? 'owner' : 'user',
146
+ isRootAdmin: false,
147
+ },
148
+ ],
149
+ affects: () => affects.admission(),
150
+ run: async (vars) => {
151
+ // Adding is an idempotent PUT that would also set the role of someone
152
+ // already here; this is only for someone new.
153
+ const member = memberRef(vars.principalType, vars.principalId);
154
+ const { members } = await client.members.list();
155
+ if (members.some((entry) => entry.member === member)) throw new Refusal('That principal already exists.');
156
+ await client.members.add(member, { owner: vars.principalType === 'user' && vars.owner });
157
+ },
158
+ };
159
+ }
160
+
161
+ export function changeRole(client: CoffreClient): Change<Directory, DirectoryPrincipal, { principalId: string; owner: boolean }, unknown> {
162
+ const id = (vars: { principalId: string }) => memberRef('user', vars.principalId);
163
+ return {
164
+ list: directoryList,
165
+ label: (vars) => `the role of ${vars.principalId}`,
166
+ targets: (vars) => [saving(id(vars))],
167
+ apply: (principals, vars) =>
168
+ principals.map((principal) =>
169
+ principalId(principal) === id(vars) ? { ...principal, instanceRole: vars.owner ? 'owner' : 'user' } : principal,
170
+ ),
171
+ affects: (vars) => affects.role(id(vars)),
172
+ run: (vars) => client.members.add(id(vars), { owner: vars.owner }),
173
+ };
174
+ }
175
+
176
+ export function removeMember(client: CoffreClient): Change<Directory, DirectoryPrincipal, DirectoryPrincipal, unknown> {
177
+ return {
178
+ list: directoryList,
179
+ label: (principal) => principal.principalId,
180
+ targets: (principal) => [removing(principalId(principal))],
181
+ affects: (principal) => affects.removal(principalId(principal)),
182
+ run: (principal) => client.members.remove(principalId(principal)),
183
+ };
184
+ }
185
+
186
+ // --- credentials, sessions, linked accounts --------------------------------------
187
+
188
+ type Credential = { id: string; hint: string };
189
+ type Credentials = ({ ok: true; tokens: Credential[] } | Failure) | null;
190
+
191
+ export function revokeCredential(client: CoffreClient, serviceId: string): Change<Credentials, Credential, Credential, unknown> {
192
+ const member = memberRef('service', serviceId);
193
+ return {
194
+ list: listOf<Credential, Credentials>([...keys.credentials(member), { allowed: true }], 'tokens', (token) => token.id),
195
+ label: (token) => `token ${token.hint}`,
196
+ targets: (token) => [removing(token.id)],
197
+ removing: REVOKING,
198
+ affects: () => affects.credentials(member),
199
+ run: (token) => client.tokens.revoke(member, token.id),
200
+ };
201
+ }
202
+
203
+ type Sessions = ({ ok: true; sessions: SessionRow[] } | Failure);
204
+
205
+ export function endSession(client: CoffreClient): Change<Sessions, SessionRow, SessionRow, unknown> {
206
+ return {
207
+ list: listOf<SessionRow, Sessions>(keys.sessions, 'sessions', (session) => session.id),
208
+ label: () => 'the session',
209
+ targets: (session) => [removing(session.id)],
210
+ removing: { pending: 'Ending…', done: 'ended', failed: 'Not ended.' },
211
+ affects: () => affects.sessions(),
212
+ run: (session) => client.sessions.revoke(session.id),
213
+ };
214
+ }
215
+
216
+ type Identities = ({ ok: true; identities: IdentityRow[] } | Failure);
217
+
218
+ export function unlinkIdentity(client: CoffreClient): Change<Identities, IdentityRow, IdentityRow & { label: string }, unknown> {
219
+ return {
220
+ list: listOf<IdentityRow, Identities>(keys.identities, 'identities', (identity) => identity.id),
221
+ label: (identity) => `the ${identity.label} account`,
222
+ targets: (identity) => [removing(identity.id)],
223
+ removing: { pending: 'Unlinking…', done: 'unlinked', failed: 'Not unlinked.' },
224
+ affects: () => affects.identities(),
225
+ run: (identity) => client.identities.unlink(identity.id),
226
+ };
227
+ }
228
+
229
+ // --- projects and environments ---------------------------------------------------
230
+
231
+ type Projects = ({ ok: true; projects: ProjectSummary[] } | Failure);
232
+
233
+ export const projectsList = listOf<ProjectSummary, Projects>(keys.projects, 'projects', (project) => project.slug);
234
+
235
+ export function createProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string; name: string }, void> {
236
+ return {
237
+ list: projectsList,
238
+ label: (vars) => `project ${vars.slug}`,
239
+ targets: (vars) => [saving(vars.slug)],
240
+ apply: (projects, vars) => [
241
+ ...projects,
242
+ {
243
+ slug: vars.slug,
244
+ name: vars.name,
245
+ archivedAt: null,
246
+ // You become its owner.
247
+ permissions: ['project.manage', 'environment.manage', 'grant.manage'],
248
+ environments: [],
249
+ secretCount: null,
250
+ },
251
+ ],
252
+ affects: () => affects.places(),
253
+ run: async (vars) => {
254
+ // Creating is an idempotent PUT; a slug that is taken is refused here.
255
+ const { created } = await client.projects.create(vars.slug, { name: vars.name });
256
+ if (!created) throw new Refusal(`A project named "${vars.slug}" already exists.`);
257
+ },
258
+ };
259
+ }
260
+
261
+ type Environment = ProjectSummary['environments'][number];
262
+
263
+ /** One project's environments, held in the project list. */
264
+ export function environmentsList(project: string): ListShape<Projects, Environment> {
265
+ const environmentsOf = (data: Projects) =>
266
+ data.ok ? (data.projects.find((entry) => entry.slug === project)?.environments ?? []) : [];
267
+ return {
268
+ queryKey: keys.projects,
269
+ items: environmentsOf,
270
+ withItems: (data, environments) =>
271
+ data.ok
272
+ ? { ...data, projects: data.projects.map((entry) => (entry.slug === project ? { ...entry, environments } : entry)) }
273
+ : data,
274
+ // Under the project's name: the projects list, in the same read, uses bare slugs.
275
+ id: (environment) => environmentId(project, environment.slug),
276
+ };
277
+ }
278
+
279
+ export function environmentId(project: string, environment: string): string {
280
+ return `${project}/${environment}`;
281
+ }
282
+
283
+ export function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; name: string }, void> {
284
+ return {
285
+ list: environmentsList(project),
286
+ label: (vars) => `environment ${vars.slug}`,
287
+ targets: (vars) => [saving(environmentId(project, vars.slug))],
288
+ apply: (environments, vars) => [
289
+ ...environments,
290
+ { slug: vars.slug, name: vars.name, accessible: false, details: { archivedAt: null, secretCount: 0 } },
291
+ ],
292
+ affects: () => affects.places(),
293
+ run: async (vars) => {
294
+ const { created } = await client.environments.create(`${project}/${vars.slug}`, { name: vars.name });
295
+ if (!created) throw new Refusal(`An environment named "${vars.slug}" already exists.`);
296
+ },
297
+ };
298
+ }
299
+
300
+ export type RenameVars = { from: string; slug: string; name: string };
301
+
302
+ export function renameEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, RenameVars, unknown> {
303
+ return {
304
+ list: environmentsList(project),
305
+ label: (vars) => `environment ${vars.from}`,
306
+ targets: (vars) =>
307
+ vars.slug === vars.from
308
+ ? [saving(environmentId(project, vars.from))]
309
+ : [saving(environmentId(project, vars.from)), saving(environmentId(project, vars.slug))],
310
+ apply: (environments, vars) =>
311
+ environments.map((environment) =>
312
+ environment.slug === vars.from ? { ...environment, slug: vars.slug, name: vars.name } : environment,
313
+ ),
314
+ affects: () => affects.places(),
315
+ run: (vars) => client.environments.update(`${project}/${vars.from}`, { slug: vars.slug, name: vars.name }),
316
+ };
317
+ }
318
+
319
+ /**
320
+ * Archive an environment or bring it back. Archiving ends every read of it,
321
+ * so it waits for the server, as a removal does; restoring shows at once.
322
+ */
323
+ export function archiveEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; archived: boolean }, unknown> {
324
+ const archivedAt = (archived: boolean) => (archived ? new Date().toISOString() : null);
325
+ const withArchived = (environment: Environment, archived: boolean): Environment =>
326
+ environment.details === null
327
+ ? environment
328
+ : { ...environment, details: { ...environment.details, archivedAt: archivedAt(archived) } };
329
+ return {
330
+ list: environmentsList(project),
331
+ label: (vars) => `environment ${vars.slug}`,
332
+ targets: (vars) => [
333
+ vars.archived ? removing(environmentId(project, vars.slug)) : saving(environmentId(project, vars.slug)),
334
+ ],
335
+ removing: ARCHIVING,
336
+ apply: (environments, vars) =>
337
+ vars.archived
338
+ ? environments
339
+ : environments.map((environment) => (environment.slug === vars.slug ? withArchived(environment, false) : environment)),
340
+ confirmed: (environments, _vars, archived) =>
341
+ environments.map((environment) =>
342
+ archived.has(environmentId(project, environment.slug)) ? withArchived(environment, true) : environment,
343
+ ),
344
+ affects: () => affects.places(),
345
+ run: (vars) => client.environments.update(`${project}/${vars.slug}`, { archived: vars.archived }),
346
+ };
347
+ }
348
+
349
+ // --- secrets ---------------------------------------------------------------------
350
+
351
+ type Secrets = ({ ok: true; keys: SecretKey[] } | Failure);
352
+
353
+ export function secretsList(place: { project: string; environment: string }) {
354
+ return listOf<SecretKey, Secrets>(keys.secrets(place), 'keys', (entry) => entry.key);
355
+ }
356
+
357
+ /** A save that stopped partway: what is left to retry, as the ledger holds it. */
358
+ export class UnsavedEdits extends Refusal {
359
+ readonly outcome: SecretEditBatchResult;
360
+
361
+ constructor(outcome: SecretEditBatchResult) {
362
+ const message = outcome.error instanceof Error ? outcome.error.message : failureMessage(outcome.error);
363
+ // Only renames can have landed before a failure: the patch is all or nothing.
364
+ super(
365
+ outcome.applied === 0
366
+ ? message
367
+ : `${message} The renames before it were saved; nothing else was, and the rest is ready to retry.`,
368
+ );
369
+ this.outcome = outcome;
370
+ }
371
+ }
372
+
373
+ export type SaveSecretsVars = {
374
+ active: SecretKey[];
375
+ drafts: SecretDraft[];
376
+ changes: Record<string, SecretChange>;
377
+ };
378
+
379
+ /**
380
+ * Write the ledger's pending edits, as `applySecretEditBatch` does: renames
381
+ * one by one, then the rest as one patch that lands whole or not at all.
382
+ * New and edited secrets show at once; archived ones stay, struck through,
383
+ * until the server confirms.
384
+ */
385
+ export function saveSecrets(
386
+ client: CoffreClient,
387
+ place: { project: string; environment: string },
388
+ /** Who is saving, shown as the author until the list is read back. */
389
+ author: string | null,
390
+ ): Change<Secrets, SecretKey, SaveSecretsVars, number> {
391
+ const path = `${place.project}/${place.environment}`;
392
+ const edits = (vars: SaveSecretsVars) =>
393
+ vars.active.flatMap((entry) => {
394
+ const change = vars.changes[entry.key];
395
+ return change === undefined ? [] : [{ entry, change }];
396
+ });
397
+ return {
398
+ list: secretsList(place),
399
+ label: (vars) => {
400
+ const named = [...vars.drafts.map((draft) => draft.key.trim()), ...edits(vars).map(({ entry }) => entry.key)];
401
+ return named.length === 1 ? named[0]! : `${named.length} changes`;
402
+ },
403
+ targets: (vars) => [
404
+ ...vars.drafts.map((draft) => saving(draft.key.trim())),
405
+ ...edits(vars).flatMap(({ entry, change }) =>
406
+ change.archived
407
+ ? [removing(entry.key)]
408
+ : change.key.trim() === entry.key
409
+ ? [saving(entry.key)]
410
+ : [saving(entry.key), saving(change.key.trim())],
411
+ ),
412
+ ],
413
+ removing: ARCHIVING,
414
+ apply: (entries, vars) => {
415
+ const now = new Date().toISOString();
416
+ const bumped = (entry: SecretKey | undefined, key: string): SecretKey => ({
417
+ key,
418
+ archived: false,
419
+ version: (entry?.version ?? 0) + 1,
420
+ updatedAt: now,
421
+ updatedBy: author,
422
+ });
423
+ let next = entries.map((entry) => {
424
+ const change = vars.changes[entry.key];
425
+ if (change === undefined || change.archived) return entry;
426
+ const key = change.key.trim();
427
+ return change.value === null ? { ...entry, key } : bumped(entry, key);
428
+ });
429
+ for (const draft of vars.drafts) {
430
+ const key = draft.key.trim();
431
+ const existing = next.find((entry) => entry.key === key);
432
+ next = existing === undefined ? [bumped(undefined, key), ...next] : next.map((entry) => (entry.key === key ? bumped(entry, key) : entry));
433
+ }
434
+ return next;
435
+ },
436
+ confirmed: (entries, _vars, archived) =>
437
+ entries.map((entry) => (archived.has(entry.key) ? { ...entry, archived: true } : entry)),
438
+ affects: () => affects.secrets(place),
439
+ run: async (vars) => {
440
+ const outcome = await applySecretEditBatch({
441
+ active: vars.active,
442
+ drafts: vars.drafts,
443
+ changes: vars.changes,
444
+ operations: {
445
+ rename: async (key, nextKey) => {
446
+ try {
447
+ await client.secrets.rename(`${path}/${key}`, nextKey);
448
+ } catch (error) {
449
+ // A refused rename names the key it stopped at.
450
+ throw new Refusal(`${key}: ${failureMessage(error)}`);
451
+ }
452
+ },
453
+ write: async (patch) => {
454
+ try {
455
+ await client.secrets.set(path, patch);
456
+ } catch (error) {
457
+ throw new Refusal(failureMessage(error));
458
+ }
459
+ },
460
+ },
461
+ });
462
+ if (outcome.error !== null) throw new UnsavedEdits(outcome);
463
+ return outcome.applied;
464
+ },
465
+ };
466
+ }
467
+
468
+ /** Restore an archived secret, from the Archived list. */
469
+ export function restoreSecret(
470
+ client: CoffreClient,
471
+ place: { project: string; environment: string },
472
+ ): Change<Secrets, SecretKey, { key: string }, unknown> {
473
+ return {
474
+ list: secretsList(place),
475
+ label: (vars) => vars.key,
476
+ targets: (vars) => [saving(vars.key)],
477
+ apply: (entries, vars) => entries.map((entry) => (entry.key === vars.key ? { ...entry, archived: false } : entry)),
478
+ affects: () => affects.secrets(place),
479
+ run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: false }),
480
+ };
481
+ }
482
+
483
+ /** Archive one secret, as Undo after a restore does: it stays, struck through, until confirmed. */
484
+ export function archiveSecret(
485
+ client: CoffreClient,
486
+ place: { project: string; environment: string },
487
+ ): Change<Secrets, SecretKey, { key: string }, unknown> {
488
+ return {
489
+ list: secretsList(place),
490
+ label: (vars) => vars.key,
491
+ targets: (vars) => [removing(vars.key)],
492
+ removing: ARCHIVING,
493
+ confirmed: (entries, _vars, archived) =>
494
+ entries.map((entry) => (archived.has(entry.key) ? { ...entry, archived: true } : entry)),
495
+ affects: () => affects.secrets(place),
496
+ run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: true }),
497
+ };
498
+ }
package/src/lib/coffre.ts CHANGED
@@ -32,7 +32,7 @@ export function failureMessage(error: unknown): string {
32
32
  }
33
33
  if (error.status === 404) return 'Not found. It may have been renamed or archived.';
34
34
  // A 400 or 409 carries a sentence written for the person, such as which
35
- // field of a sync's destination is wrong. Anything unexpected stays generic.
35
+ // field of a request is wrong. Anything unexpected stays generic.
36
36
  if (error.status === 400 || error.status === 409) return error.message;
37
37
  return 'coffre is unavailable. Nothing was read or written.';
38
38
  }