@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,45 @@
1
+ import type { Me, Permission, ProjectSummary } from '../shared/models';
2
+
3
+ /**
4
+ * The small set of instance-wide decisions the shell has to make.
5
+ *
6
+ * Resource-specific controls still use the permissions returned for that
7
+ * project or environment. These are only the capabilities whose affordances
8
+ * live outside one resource page.
9
+ */
10
+ export type UiCapabilities = {
11
+ canManageGrants: boolean;
12
+ canReadAudit: boolean;
13
+ canCreateProject: boolean;
14
+ };
15
+
16
+ const NONE: UiCapabilities = {
17
+ canManageGrants: false,
18
+ canReadAudit: false,
19
+ canCreateProject: false,
20
+ };
21
+
22
+ export function deriveUiCapabilities(
23
+ me: Me | null,
24
+ projects: readonly ProjectSummary[],
25
+ ): UiCapabilities {
26
+ if (me === null) return NONE;
27
+
28
+ const canManageInstance =
29
+ me.instanceRole === 'owner' || me.instanceRole === 'root-admin';
30
+
31
+ return {
32
+ // Users and Tokens manage the instance directory, not project grants.
33
+ // Project access managers keep their grant controls on each project page.
34
+ canManageGrants: canManageInstance,
35
+ canReadAudit: me.canReadAudit,
36
+ // Project creation has no resource on which to hold a grant, so it follows
37
+ // the instance-wide owner role (including configured root admins).
38
+ canCreateProject: canManageInstance,
39
+ };
40
+ }
41
+
42
+ /** Secret values are available only where the API reports secret.read. */
43
+ export function canRevealSecrets(permissions: readonly Permission[]): boolean {
44
+ return permissions.includes('secret.read');
45
+ }
@@ -0,0 +1,57 @@
1
+ import { CoffreError, type CoffreClient } from '@coffre/client';
2
+ import { useRouter } from '@tanstack/react-router';
3
+
4
+ /**
5
+ * The API as whoever is looking at the page. In the browser this is plain
6
+ * `fetch` to `/api`, carrying the session cookie; mutations call it straight
7
+ * from event handlers, and loaders read through `context.client`.
8
+ */
9
+ export function useCoffre(): CoffreClient {
10
+ return useRouter().options.context.client;
11
+ }
12
+
13
+ /** A refusal the page words itself, shown as it is. */
14
+ export class Refusal extends Error {}
15
+
16
+ type Failure = { ok: false; error: string };
17
+
18
+ /** The HTTP status of an API error; undefined when the request never got an answer. */
19
+ export function statusOf(error: unknown): number | undefined {
20
+ return error instanceof CoffreError ? error.status : undefined;
21
+ }
22
+
23
+ /** What to tell the person when a call fails. */
24
+ export function failureMessage(error: unknown): string {
25
+ if (error instanceof Refusal) return error.message;
26
+ if (!(error instanceof CoffreError)) return 'The request could not be sent. Nothing was changed.';
27
+ if (error.status === 401) return 'Your session has ended. Sign in again, then retry.';
28
+ if (error.code === 'cross_origin') return 'coffre refused a change that did not come from this page. Reload, then retry.';
29
+ if (error.status === 403) {
30
+ return 'You hold no grant that covers this. Someone with grant.manage on the project can add one.';
31
+ }
32
+ if (error.status === 404) return 'Not found. It may have been renamed or archived.';
33
+ // A 400 or 409 carries a sentence written for the person, such as which
34
+ // field of a sync's destination is wrong. Anything unexpected stays generic.
35
+ if (error.status === 400 || error.status === 409) return error.message;
36
+ return 'coffre is unavailable. Nothing was read or written.';
37
+ }
38
+
39
+ export function uiFailure(error: unknown): Failure {
40
+ return { ok: false, error: failureMessage(error) };
41
+ }
42
+
43
+ /** A loader's answer: what it read, or what to say instead. */
44
+ export async function uiResult<T extends object>(
45
+ operation: () => Promise<T>,
46
+ ): Promise<({ ok: true } & T) | Failure> {
47
+ try {
48
+ return { ok: true, ...(await operation()) };
49
+ } catch (error) {
50
+ return uiFailure(error);
51
+ }
52
+ }
53
+
54
+ /** How the API names a member: `user:ada@acme.example`, `token:ci-deploy`. */
55
+ export function memberRef(principalType: 'user' | 'service', principalId: string): string {
56
+ return `${principalType === 'user' ? 'user' : 'token'}:${principalId}`;
57
+ }
@@ -0,0 +1,95 @@
1
+ import type { GrantRow, ProjectSummary, RoleRow } from '../shared/models';
2
+
3
+ export type ProjectAccessRole = 'owner' | 'viewer' | 'developer';
4
+
5
+ export type ProjectAccessOption = {
6
+ value: string;
7
+ role: ProjectAccessRole;
8
+ environmentSlug: string | null;
9
+ label: string;
10
+ };
11
+
12
+ const LEVEL_LABELS: Record<ProjectAccessRole, string> = {
13
+ owner: 'Owner',
14
+ viewer: 'Read',
15
+ developer: 'Write',
16
+ };
17
+
18
+ export function projectAccessOptions(
19
+ environments: ProjectSummary['environments'],
20
+ ): ProjectAccessOption[] {
21
+ const options: ProjectAccessOption[] = [
22
+ {
23
+ value: 'owner:',
24
+ role: 'owner',
25
+ environmentSlug: null,
26
+ label: 'Owner',
27
+ },
28
+ ];
29
+
30
+ for (const role of ['viewer', 'developer'] as const) {
31
+ options.push({
32
+ value: `${role}:`,
33
+ role,
34
+ environmentSlug: null,
35
+ label: `${LEVEL_LABELS[role]}: all`,
36
+ });
37
+ }
38
+
39
+ for (const environment of environments) {
40
+ if (environment.details === null || environment.details.archivedAt !== null) continue;
41
+ for (const role of ['viewer', 'developer'] as const) {
42
+ options.push({
43
+ value: `${role}:${environment.slug}`,
44
+ role,
45
+ environmentSlug: environment.slug,
46
+ label: `${LEVEL_LABELS[role]}: ${environment.slug}`,
47
+ });
48
+ }
49
+ }
50
+
51
+ return options;
52
+ }
53
+
54
+ export function parseProjectAccess(value: string): {
55
+ role: ProjectAccessRole;
56
+ environmentSlug: string | null;
57
+ } {
58
+ const [role, environmentSlug = ''] = value.split(':', 2);
59
+ if (role !== 'owner' && role !== 'viewer' && role !== 'developer') {
60
+ throw new Error('unknown project access level');
61
+ }
62
+ return { role, environmentSlug: environmentSlug || null };
63
+ }
64
+
65
+ export function projectAccessLabel(
66
+ grant: Pick<GrantRow, 'role' | 'roleName' | 'environmentSlug'>,
67
+ ): string {
68
+ const scope =
69
+ grant.environmentSlug === null ? 'all environments' : grant.environmentSlug;
70
+
71
+ if (grant.role === 'owner') return 'Owner';
72
+ if (grant.role === 'viewer') {
73
+ return grant.environmentSlug === null ? 'Read: all' : `Read: ${scope}`;
74
+ }
75
+ if (grant.role === 'developer') {
76
+ return grant.environmentSlug === null ? 'Write: all' : `Write: ${scope}`;
77
+ }
78
+ // Specialised grants remain legible even though the common access controls
79
+ // use owner/read/write.
80
+ return `${grant.roleName}: ${scope}`;
81
+ }
82
+
83
+ export function projectAccessRoles(
84
+ roles: RoleRow[],
85
+ environmentSlug: string | null,
86
+ currentRole?: string,
87
+ ): RoleRow[] {
88
+ const allowed = new Set(
89
+ environmentSlug === null
90
+ ? ['owner', 'viewer', 'developer']
91
+ : ['viewer', 'developer'],
92
+ );
93
+ if (currentRole) allowed.add(currentRole);
94
+ return roles.filter((role) => allowed.has(role.slug));
95
+ }
@@ -0,0 +1,23 @@
1
+ import type { ProjectSummary } from '../shared/models';
2
+
3
+ export type ProjectEnvironment = ProjectSummary['environments'][number];
4
+ export type DetailedProjectEnvironment = ProjectEnvironment & {
5
+ details: NonNullable<ProjectEnvironment['details']>;
6
+ };
7
+
8
+ export function hasEnvironmentDetails(
9
+ environment: ProjectEnvironment,
10
+ ): environment is DetailedProjectEnvironment {
11
+ return environment.details !== null;
12
+ }
13
+
14
+ export function isActiveAccessibleEnvironment(
15
+ environment: ProjectEnvironment,
16
+ ): environment is ProjectEnvironment & {
17
+ accessible: true;
18
+ details: { archivedAt: null; secretCount: number };
19
+ } {
20
+ return environment.accessible
21
+ && environment.details !== null
22
+ && environment.details.archivedAt === null;
23
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A decrypted value on screen, and which version it was decrypted from.
3
+ *
4
+ * `version` is what makes it safe to keep around at all: the list of keys
5
+ * reports each secret's current version, and a reveal is only shown while the
6
+ * two agree. After a save, a rollback, or someone else's write, the plaintext
7
+ * on screen would be an old value presented as the current one.
8
+ */
9
+ export type Reveal = {
10
+ value: string;
11
+ version: number | null;
12
+ /** When the read happened, in ms since the epoch; drives the auto-hide. */
13
+ at: number;
14
+ };
15
+
16
+ export function revealIsCurrent(
17
+ reveal: Reveal | null,
18
+ currentVersion: number | null,
19
+ ): reveal is Reveal {
20
+ return reveal !== null && reveal.version === currentVersion;
21
+ }
@@ -0,0 +1,181 @@
1
+ export type SecretDraft = { id: number; key: string; value: string };
2
+
3
+ export type SecretChange = {
4
+ key: string;
5
+ value: string | null;
6
+ archived: boolean;
7
+ };
8
+
9
+ type ActiveSecret = { key: string };
10
+
11
+ /** A merge patch: a string sets a key, adding it if it is new; `null` archives it. */
12
+ export type SecretPatch = Record<string, string | null>;
13
+
14
+ type SecretEditOperations = {
15
+ rename: (key: string, nextKey: string) => Promise<void>;
16
+ /** One transaction: every key in it lands, or none does. */
17
+ write: (patch: SecretPatch) => Promise<void>;
18
+ };
19
+
20
+ type PlannedEdit = { sourceKey: string; change: SecretChange };
21
+
22
+ export function secretChangeFor(
23
+ changes: Readonly<Record<string, SecretChange>>,
24
+ key: string,
25
+ ): SecretChange | undefined {
26
+ return Object.hasOwn(changes, key) ? changes[key] : undefined;
27
+ }
28
+
29
+ export type SecretEditBatchResult = {
30
+ applied: number;
31
+ drafts: SecretDraft[];
32
+ changes: Record<string, SecretChange>;
33
+ error: unknown | null;
34
+ };
35
+
36
+ /** Return true when one save would give two pending edits the same target. */
37
+ export function hasSecretEditConflict(
38
+ active: readonly ActiveSecret[],
39
+ drafts: readonly SecretDraft[],
40
+ changes: Readonly<Record<string, SecretChange>>,
41
+ ): boolean {
42
+ const finalActiveKeys = active
43
+ .filter((entry) => !secretChangeFor(changes, entry.key)?.archived)
44
+ .map((entry) => secretChangeFor(changes, entry.key)?.key.trim() ?? entry.key);
45
+ if (new Set(finalActiveKeys).size !== finalActiveKeys.length) return true;
46
+
47
+ const draftKeys = drafts.map((draft) => draft.key.trim());
48
+ if (new Set(draftKeys).size !== draftKeys.length) return true;
49
+
50
+ const valueEditTargets = new Set(
51
+ active.flatMap((entry) => {
52
+ const change = secretChangeFor(changes, entry.key);
53
+ return change !== undefined && !change.archived && change.value !== null
54
+ ? [change.key.trim()]
55
+ : [];
56
+ }),
57
+ );
58
+ if (draftKeys.some((key) => valueEditTargets.has(key))) return true;
59
+
60
+ const archivedKeys = new Set(
61
+ active
62
+ .filter((entry) => secretChangeFor(changes, entry.key)?.archived)
63
+ .map((entry) => entry.key),
64
+ );
65
+ return draftKeys.some((key) => archivedKeys.has(key));
66
+ }
67
+
68
+ /**
69
+ * Save every pending edit: renames first, one call each, then everything else
70
+ * as one merge patch.
71
+ *
72
+ * The patch is a single transaction, so values, new keys and archives land
73
+ * together or not at all. Renames cannot join it: a merge patch names keys and
74
+ * has no way to move one with its history. A failed rename therefore stops the
75
+ * save before the patch. The renames before it stay done, and every other edit
76
+ * is kept for the retry, a value following its key to the new name.
77
+ */
78
+ export async function applySecretEditBatch({
79
+ active,
80
+ drafts,
81
+ changes,
82
+ operations,
83
+ }: {
84
+ active: readonly ActiveSecret[];
85
+ drafts: readonly SecretDraft[];
86
+ changes: Readonly<Record<string, SecretChange>>;
87
+ operations: SecretEditOperations;
88
+ }): Promise<SecretEditBatchResult> {
89
+ const remainingChanges = { ...changes };
90
+ const plan = planEdits(active, drafts, changes);
91
+ if (plan instanceof Error) {
92
+ return { applied: 0, drafts: [...drafts], changes: remainingChanges, error: plan };
93
+ }
94
+
95
+ let applied = 0;
96
+ // A key named `__proto__` is a key like any other.
97
+ const patch: SecretPatch = Object.create(null);
98
+ try {
99
+ for (const { sourceKey, change } of plan) {
100
+ if (change.archived) {
101
+ patch[sourceKey] = null;
102
+ continue;
103
+ }
104
+ const key = change.key.trim();
105
+ if (key !== sourceKey) {
106
+ await operations.rename(sourceKey, key);
107
+ delete remainingChanges[sourceKey];
108
+ applied += 1;
109
+ if (change.value !== null) remainingChanges[key] = { key, value: change.value, archived: false };
110
+ }
111
+ if (change.value !== null) patch[key] = change.value;
112
+ }
113
+ for (const draft of drafts) patch[draft.key.trim()] = draft.value;
114
+
115
+ const written = Object.keys(patch).length;
116
+ if (written > 0) await operations.write({ ...patch });
117
+ return { applied: applied + written, drafts: [], changes: {}, error: null };
118
+ } catch (error) {
119
+ return { applied, drafts: [...drafts], changes: remainingChanges, error };
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Put dependent renames in an order that frees each destination first.
125
+ * Cycles and archive-then-restore plans fail before the first mutation.
126
+ */
127
+ function planEdits(
128
+ active: readonly ActiveSecret[],
129
+ drafts: readonly SecretDraft[],
130
+ changes: Readonly<Record<string, SecretChange>>,
131
+ ): PlannedEdit[] | Error {
132
+ const activeKeys = new Set(active.map((entry) => entry.key));
133
+ const archivedKeys = new Set(
134
+ active
135
+ .filter((entry) => secretChangeFor(changes, entry.key)?.archived)
136
+ .map((entry) => entry.key),
137
+ );
138
+ const restoredByDraft = drafts.find((draft) => archivedKeys.has(draft.key.trim()));
139
+ if (restoredByDraft) {
140
+ return new Error(
141
+ `${restoredByDraft.key.trim()}: cannot archive and write the same key in one save`,
142
+ );
143
+ }
144
+
145
+ const renames = new Map<string, SecretChange>();
146
+ const otherEdits: PlannedEdit[] = [];
147
+ for (const entry of active) {
148
+ const change = secretChangeFor(changes, entry.key);
149
+ if (change === undefined) continue;
150
+ if (!change.archived && change.key.trim() !== entry.key) {
151
+ renames.set(entry.key, change);
152
+ } else {
153
+ otherEdits.push({ sourceKey: entry.key, change });
154
+ }
155
+ }
156
+
157
+ for (const [sourceKey, change] of renames) {
158
+ const destination = change.key.trim();
159
+ if (activeKeys.has(destination) && !renames.has(destination)) {
160
+ return new Error(`${sourceKey}: ${destination} is already in use`);
161
+ }
162
+ }
163
+
164
+ const orderedRenames: PlannedEdit[] = [];
165
+ const freedKeys = new Set<string>();
166
+ while (renames.size > 0) {
167
+ const ready = [...renames].find(([, change]) => {
168
+ const destination = change.key.trim();
169
+ return !activeKeys.has(destination) || freedKeys.has(destination);
170
+ });
171
+ if (!ready) {
172
+ return new Error('Secret renames contain a cycle. Save them in separate steps.');
173
+ }
174
+ const [sourceKey, change] = ready;
175
+ renames.delete(sourceKey);
176
+ freedKeys.add(sourceKey);
177
+ orderedRenames.push({ sourceKey, change });
178
+ }
179
+
180
+ return [...orderedRenames, ...otherEdits];
181
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What went wrong with a sign-in, in words. The callback redirects with a
3
+ * code rather than a sentence so the URL stays short and nothing the provider
4
+ * said is reflected into the page.
5
+ */
6
+ const MESSAGES: Record<string, string> = {
7
+ provider_denied: 'The sign-in was cancelled, or the provider refused it.',
8
+ state_mismatch:
9
+ 'This sign-in expired or was started in another tab. Start again from this page.',
10
+ invalid_response:
11
+ 'The provider answered in a way coffre could not verify. Try again; if it keeps happening, tell whoever runs coffre.',
12
+ provider_unavailable: 'The provider could not be reached. Try again in a moment.',
13
+ no_verified_email:
14
+ 'That account has no verified email address, so coffre cannot match it to an invitation.',
15
+ wrong_domain: 'That account is outside the organization this instance belongs to.',
16
+ not_in_organization:
17
+ 'That GitHub account is not a member of the required organization. If it is, grant coffre access to the organization when GitHub asks.',
18
+ not_registered:
19
+ 'Nobody has invited that account’s email address. Ask an owner to add you under Users, then sign in again.',
20
+ deactivated: 'Your access to this coffre was removed. Ask an owner if that is a mistake.',
21
+ account_mismatch:
22
+ 'Your email already signs in with a different account. Use that one, then link this account from your account page.',
23
+ already_linked: 'That account is already linked to someone else.',
24
+ tampered:
25
+ 'Your access record failed coffre’s integrity check: it was changed outside coffre. An owner must remove you and add you again.',
26
+ unknown_provider: 'That sign-in option is not configured here.',
27
+ link_session: 'Your session changed while linking. Sign in again, then retry.',
28
+ };
29
+
30
+ export function signinErrorMessage(code: string | undefined): string | null {
31
+ if (code === undefined) return null;
32
+ return MESSAGES[code] ?? 'The sign-in did not complete. Try again.';
33
+ }
@@ -0,0 +1,50 @@
1
+ import { useState } from 'react';
2
+ import { useRouter } from '@tanstack/react-router';
3
+
4
+ import { failureMessage } from './coffre';
5
+
6
+ /**
7
+ * Run a change against the API, then refresh what is on screen. A failed
8
+ * call leaves the page as it was and says why, in `error`.
9
+ *
10
+ * `router.invalidate()` is this app's replacement for Next's
11
+ * `revalidatePath`. The difference worth knowing: `revalidatePath` named the
12
+ * routes to refresh and got it wrong quietly when a mutation touched more than
13
+ * the page it was called from -- renaming a project had to remember to
14
+ * revalidate both `/` and `/:project`. Invalidating refetches every mounted
15
+ * loader instead, so the sidebar's project tree stays honest without anyone
16
+ * having to remember it exists.
17
+ */
18
+ export function useAction() {
19
+ const router = useRouter();
20
+ const [pending, setPending] = useState(false);
21
+ const [error, setError] = useState<string | null>(null);
22
+
23
+ async function run<T>(
24
+ fn: () => Promise<T>,
25
+ // `unknown` rather than `void`, so a one-expression callback can end in
26
+ // `toast.success(...)` -- which returns an id -- without a block body.
27
+ onSuccess?: (result: T) => unknown,
28
+ ): Promise<void> {
29
+ setPending(true);
30
+ let result: T;
31
+ try {
32
+ result = await fn();
33
+ } catch (failure) {
34
+ setError(failureMessage(failure));
35
+ setPending(false);
36
+ return;
37
+ }
38
+
39
+ setError(null);
40
+ try {
41
+ await router.invalidate();
42
+ await onSuccess?.(result);
43
+ } catch {
44
+ setError('The change was saved, but the page could not refresh. Reload before you retry.');
45
+ }
46
+ setPending(false);
47
+ }
48
+
49
+ return { pending, error, setError, run };
50
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Client-side hints for the two identifier shapes people type.
3
+ *
4
+ * The server validates with the zod schemas in `@coffre/core/schemas` and stays
5
+ * the authority; these only let a form say what is wrong before a round trip.
6
+ * They are plain patterns rather than imports of those schemas so the browser
7
+ * bundle does not carry zod, and `test/validation.test.ts` holds the two in
8
+ * agreement.
9
+ */
10
+
11
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
12
+ const SECRET_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
13
+
14
+ export function slugProblem(value: string): string | null {
15
+ if (SLUG.test(value)) return null;
16
+ if (value.length > 63) return 'At most 63 characters.';
17
+ if (/[A-Z]/.test(value)) return 'Lowercase only.';
18
+ if (value.startsWith('-')) return 'Start with a letter or digit.';
19
+ return 'Lowercase letters, digits and dashes only.';
20
+ }
21
+
22
+ export function secretKeyProblem(value: string): string | null {
23
+ if (SECRET_KEY.test(value)) return null;
24
+ if (value.length > 128) return 'At most 128 characters.';
25
+ if (/^[0-9]/.test(value)) return 'Cannot start with a digit.';
26
+ return 'Letters, digits and underscores only.';
27
+ }