@coffre/ui 0.8.2 → 0.10.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 (92) hide show
  1. package/dist/chunks/{audit-sentence-C_wMpAqr.js → audit-sentence-Bjhg00cn.js} +73 -6
  2. package/dist/chunks/audit-sentence-Bjhg00cn.js.map +1 -0
  3. package/dist/chunks/{connected-apps-Bn5rEoV2.js → connected-apps-CZI7xxUq.js} +2 -2
  4. package/dist/chunks/{connected-apps-Bn5rEoV2.js.map → connected-apps-CZI7xxUq.js.map} +1 -1
  5. package/dist/chunks/{delete-place-CQCDHkne.js → delete-place-D3UQGl3b.js} +3 -3
  6. package/dist/chunks/{delete-place-CQCDHkne.js.map → delete-place-D3UQGl3b.js.map} +1 -1
  7. package/dist/chunks/{directory-BQNOdze_.js → directory-CyHmxYP-.js} +9 -7
  8. package/dist/chunks/directory-CyHmxYP-.js.map +1 -0
  9. package/dist/chunks/{grants-CJIBrkod.js → grants-CEIdNqJU.js} +4 -4
  10. package/dist/chunks/{grants-CJIBrkod.js.map → grants-CEIdNqJU.js.map} +1 -1
  11. package/dist/chunks/{offboarding-CrgwaetA.js → offboarding-CvGgTmHi.js} +2 -2
  12. package/dist/chunks/{offboarding-CrgwaetA.js.map → offboarding-CvGgTmHi.js.map} +1 -1
  13. package/dist/chunks/{personal-tokens-B8rkT-DI.js → personal-tokens-BX97oX4a.js} +2 -2
  14. package/dist/chunks/{personal-tokens-B8rkT-DI.js.map → personal-tokens-BX97oX4a.js.map} +1 -1
  15. package/dist/chunks/{principal-page-Cv5PheS9.js → principal-page-Bp2O8kIW.js} +92 -76
  16. package/dist/chunks/principal-page-Bp2O8kIW.js.map +1 -0
  17. package/dist/chunks/{project-page-BI--vjt3.js → project-page-CUXV4FDR.js} +2 -2
  18. package/dist/chunks/{project-page-BI--vjt3.js.map → project-page-CUXV4FDR.js.map} +1 -1
  19. package/dist/chunks/protected-YYW3U-Sq.js +22 -0
  20. package/dist/chunks/protected-YYW3U-Sq.js.map +1 -0
  21. package/dist/chunks/{queries-epz4MIuW.js → queries-DEOPOpsT.js} +27 -3
  22. package/dist/chunks/queries-DEOPOpsT.js.map +1 -0
  23. package/dist/chunks/{references-DImfw0cz.js → references-DsXkt064.js} +3 -3
  24. package/dist/chunks/{references-DImfw0cz.js.map → references-DsXkt064.js.map} +1 -1
  25. package/dist/chunks/{role-field-C1KhNaIR.js → role-field-CCUeZd1a.js} +8 -5
  26. package/dist/chunks/role-field-CCUeZd1a.js.map +1 -0
  27. package/dist/chunks/{use-action-BB-RcHo1.js → use-action-COW-XFw8.js} +2 -2
  28. package/dist/chunks/{use-action-BB-RcHo1.js.map → use-action-COW-XFw8.js.map} +1 -1
  29. package/dist/chunks/{use-change-CQyDpCqw.js → use-change-hfqE7baE.js} +231 -66
  30. package/dist/chunks/use-change-hfqE7baE.js.map +1 -0
  31. package/dist/chunks/use-roles-C_Tj5wBH.js +224 -0
  32. package/dist/chunks/use-roles-C_Tj5wBH.js.map +1 -0
  33. package/dist/chunks/{use-shell-C_NmvCt_.js → use-shell-DBLG80kk.js} +2 -2
  34. package/dist/chunks/{use-shell-C_NmvCt_.js.map → use-shell-DBLG80kk.js.map} +1 -1
  35. package/dist/index.d.ts +9 -3
  36. package/dist/index.js +25 -11
  37. package/dist/index.js.map +1 -1
  38. package/dist/pages/account.js +6 -6
  39. package/dist/pages/audit.js +2 -2
  40. package/dist/pages/environment.js +306 -96
  41. package/dist/pages/environment.js.map +1 -1
  42. package/dist/pages/login.js +1 -1
  43. package/dist/pages/project-access.js +78 -45
  44. package/dist/pages/project-access.js.map +1 -1
  45. package/dist/pages/project-environments.js +77 -28
  46. package/dist/pages/project-environments.js.map +1 -1
  47. package/dist/pages/project-settings.js +6 -6
  48. package/dist/pages/project.js +1 -1
  49. package/dist/pages/projects.js +23 -11
  50. package/dist/pages/projects.js.map +1 -1
  51. package/dist/pages/service-account.js +19 -12
  52. package/dist/pages/service-account.js.map +1 -1
  53. package/dist/pages/service-accounts.js +4 -4
  54. package/dist/pages/settings.js +580 -8
  55. package/dist/pages/settings.js.map +1 -1
  56. package/dist/pages/unregistered.js +1 -1
  57. package/dist/pages/user.js +5 -5
  58. package/dist/pages/users.js +4 -4
  59. package/package.json +3 -3
  60. package/src/components/directory.tsx +5 -2
  61. package/src/components/grants.tsx +1 -1
  62. package/src/components/principal-page.tsx +38 -23
  63. package/src/components/protected.tsx +17 -0
  64. package/src/components/role-editor.tsx +582 -0
  65. package/src/components/role-field.tsx +7 -3
  66. package/src/components/scope-picker.tsx +19 -9
  67. package/src/components/shell.tsx +7 -1
  68. package/src/lib/access-plan.ts +35 -36
  69. package/src/lib/audit-sentences.ts +75 -6
  70. package/src/lib/changes.ts +48 -6
  71. package/src/lib/project-access.ts +4 -78
  72. package/src/lib/queries.ts +16 -0
  73. package/src/lib/roles.ts +201 -0
  74. package/src/lib/row-reads.ts +12 -0
  75. package/src/lib/secret-edit-batch.ts +162 -26
  76. package/src/lib/sensitivity.ts +50 -0
  77. package/src/lib/service-setup.ts +20 -8
  78. package/src/lib/use-roles.ts +17 -0
  79. package/src/pages/environment.tsx +295 -61
  80. package/src/pages/project-access.tsx +49 -19
  81. package/src/pages/project-environments.tsx +62 -3
  82. package/src/pages/projects.tsx +3 -1
  83. package/src/pages/settings.tsx +2 -0
  84. package/src/parity.ts +41 -4
  85. package/src/shared/models.ts +2 -9
  86. package/src/styles/globals.css +329 -4
  87. package/dist/chunks/audit-sentence-C_wMpAqr.js.map +0 -1
  88. package/dist/chunks/directory-BQNOdze_.js.map +0 -1
  89. package/dist/chunks/principal-page-Cv5PheS9.js.map +0 -1
  90. package/dist/chunks/queries-epz4MIuW.js.map +0 -1
  91. package/dist/chunks/role-field-C1KhNaIR.js.map +0 -1
  92. package/dist/chunks/use-change-CQyDpCqw.js.map +0 -1
@@ -0,0 +1,201 @@
1
+ import type { ImpactLine, RolesView, RoleView } from '@coffre/client';
2
+ import {
3
+ assignableToEnvironment,
4
+ FIXED_ROLES,
5
+ INSTANCE_ROLES,
6
+ PERMISSIONS,
7
+ PROJECT_ONLY_PERMISSIONS,
8
+ ROLES,
9
+ type Permission,
10
+ type RoleDefinition,
11
+ } from '@coffre/core/access';
12
+
13
+ /**
14
+ * The instance's roles as the pages offer and name them (docs/design/roles.md):
15
+ * each in two columns, what it holds in an environment and what a person
16
+ * holds of it in a protected one. The policy is the vault's, read from
17
+ * `GET /api/roles`; until it is, the roles as they ship stand in.
18
+ */
19
+
20
+ /** Every permission in words, in the catalogue's order, and what a short label leaves out. */
21
+ export const PERMISSION_WORDS: Record<Permission, { label: string; note?: string; verb: string }> = {
22
+ 'secret.read': { label: 'Read values', verb: 'read values' },
23
+ 'secret.use': { label: 'Use values', note: 'placeholders, the proxy', verb: 'use values' },
24
+ 'secret.write': { label: 'Write values', verb: 'write values' },
25
+ 'secret.archive': { label: 'Retire values', verb: 'retire values' },
26
+ 'audit.read': { label: 'Read the log', verb: 'read the log' },
27
+ 'environment.manage': { label: 'Manage environments', verb: 'manage environments' },
28
+ 'grant.manage': { label: 'Manage access', verb: 'manage access' },
29
+ 'project.manage': { label: 'Manage the project', verb: 'manage the project' },
30
+ };
31
+
32
+ /** The rows of a role's grid: secrets first, as a role is read, then the log, then what only a project holds. */
33
+ export const GRID_PERMISSIONS: readonly Permission[] = [
34
+ 'secret.read',
35
+ 'secret.use',
36
+ 'secret.write',
37
+ 'secret.archive',
38
+ 'audit.read',
39
+ 'environment.manage',
40
+ 'grant.manage',
41
+ 'project.manage',
42
+ ];
43
+
44
+ export function projectWide(permission: Permission): boolean {
45
+ return PROJECT_ONLY_PERMISSIONS.includes(permission);
46
+ }
47
+
48
+ /** A role's two columns, as the grid edits them. */
49
+ export type Columns = { permissions: Permission[]; protected: Permission[] };
50
+ export type Column = 'normal' | 'protected';
51
+
52
+ /**
53
+ * One checkbox of the grid flipped, and the rules the vault holds a role to
54
+ * kept true by the boxes it takes along (`definitionProblem`):
55
+ *
56
+ * checking Read checks Use unchecking Use unchecks Read
57
+ * checking a protected box checks its unchecking a normal box unchecks
58
+ * normal one its protected one
59
+ *
60
+ * A project-wide permission has no protected box: flipping one is no change.
61
+ */
62
+ export function toggle(columns: Pick<RoleDefinition, 'permissions' | 'protected'>, permission: Permission, column: Column, on: boolean): Columns {
63
+ if (column === 'protected' && projectWide(permission)) return ordered(columns);
64
+ const normal = new Set(columns.permissions);
65
+ const guarded = new Set(columns.protected);
66
+ // Reading takes using; giving up using gives up reading.
67
+ const along: Permission[] = on ? (permission === 'secret.read' ? ['secret.use'] : []) : permission === 'secret.use' ? ['secret.read'] : [];
68
+ for (const each of [permission, ...along]) {
69
+ if (on) {
70
+ normal.add(each);
71
+ if (column === 'protected') guarded.add(each);
72
+ } else {
73
+ guarded.delete(each);
74
+ if (column === 'normal') normal.delete(each);
75
+ }
76
+ }
77
+ return ordered({ permissions: [...normal], protected: [...guarded] });
78
+ }
79
+
80
+ /** Each column in catalogue order, as the vault keeps it, so that comparing two says whether they differ. */
81
+ export function ordered(columns: Pick<RoleDefinition, 'permissions' | 'protected'>): Columns {
82
+ return {
83
+ permissions: PERMISSIONS.filter((permission) => columns.permissions.includes(permission)),
84
+ protected: PERMISSIONS.filter((permission) => columns.protected.includes(permission)),
85
+ };
86
+ }
87
+
88
+ /** Whether two definitions hold the same, named and described the same. */
89
+ export function sameDefinition(a: RoleDefinition, b: RoleDefinition): boolean {
90
+ const [x, y] = [ordered(a), ordered(b)];
91
+ return a.name.trim() === b.name.trim() && a.description === b.description
92
+ && x.permissions.join() === y.permissions.join() && x.protected.join() === y.protected.join();
93
+ }
94
+
95
+ /** A column in words, for a role's row: "read, use and write values", or "nothing". */
96
+ export function columnInWords(permissions: readonly Permission[]): string {
97
+ const values = ['secret.read', 'secret.use', 'secret.write', 'secret.archive'] as const;
98
+ const held = values.filter((permission) => permissions.includes(permission));
99
+ const verbs = { 'secret.read': 'read', 'secret.use': 'use', 'secret.write': 'write', 'secret.archive': 'retire' } as const;
100
+ const parts = [
101
+ ...(held.length === 0 ? [] : [`${list(held.map((permission) => verbs[permission]))} values`]),
102
+ ...GRID_PERMISSIONS.filter((permission) => !(values as readonly string[]).includes(permission) && permissions.includes(permission)).map((permission) => PERMISSION_WORDS[permission].verb),
103
+ ];
104
+ return parts.length === 0 ? 'nothing' : list(parts);
105
+ }
106
+
107
+ function list(words: readonly string[]): string {
108
+ return words.length <= 1 ? (words[0] ?? '') : `${words.slice(0, -1).join(', ')} and ${words.at(-1)}`;
109
+ }
110
+
111
+ /** A role's id, made from its name as it is typed: "Release manager" is `release-manager`. */
112
+ export function roleIdFrom(name: string): string {
113
+ return name
114
+ .toLowerCase()
115
+ .normalize('NFKD')
116
+ .replace(/[\u0300-\u036f]/g, '')
117
+ .replace(/[^a-z0-9]+/g, '-')
118
+ .replace(/^[^a-z]+/, '')
119
+ .replace(/-+$/, '')
120
+ .slice(0, 32)
121
+ .replace(/-+$/, '');
122
+ }
123
+
124
+ /** What is wrong with a new role's id, or null: its shape, and not one the instance has. */
125
+ export function roleIdProblem(id: string, taken: readonly string[]): string | null {
126
+ if (id === '') return 'A role needs an id.';
127
+ if (!/^[a-z0-9-]+$/.test(id)) return 'An id is lowercase letters, digits and dashes.';
128
+ if (!/^[a-z]/.test(id)) return 'An id starts with a letter.';
129
+ if (id.length < 2 || id.length > 32) return 'An id is 2 to 32 characters.';
130
+ if (taken.includes(id)) return `There is a role ${id} already.`;
131
+ return null;
132
+ }
133
+
134
+ /** The roles as they ship: what the pages offer and name until the instance's are read, or where they cannot be. */
135
+ export const SHIPPED_ROLES: RolesView = {
136
+ roles: Object.entries(ROLES).map(([id, definition]) => shippedView(id, definition, FIXED_ROLES.roles.includes(id), assignableToEnvironment(id))),
137
+ instanceRoles: Object.entries(INSTANCE_ROLES).map(([id, definition]) =>
138
+ shippedView(id, definition, (FIXED_ROLES.instanceRoles as readonly string[]).includes(id), false)),
139
+ editable: false,
140
+ };
141
+
142
+ function shippedView(id: string, definition: RoleDefinition, fixed: boolean, assignable: boolean): RoleView {
143
+ const shipped = { name: definition.name, description: definition.description, ...ordered(definition) };
144
+ return { id, ...shipped, builtin: true, edited: false, fixed, default: shipped, assignableToEnvironment: assignable, grants: 0 };
145
+ }
146
+
147
+ /** A role's name by its id, as the instance defines it; one it does not know, as itself. */
148
+ export function roleNameOf(roles: readonly Pick<RoleView, 'id' | 'name'>[], id: string): string {
149
+ return roles.find((role) => role.id === id)?.name ?? id;
150
+ }
151
+
152
+ /**
153
+ * One line of a change's impact, in words, from the dry run's count:
154
+ *
155
+ * widens secret.read, protected, 6 people, 4 environments
156
+ * 6 people can now read values in 4 protected environments
157
+ * narrows secret.write, 2 people, 1 environment, ["ada@… on market/dev", …]
158
+ * 2 people can no longer write values in market/dev
159
+ *
160
+ * One place is named, from its examples; more are counted.
161
+ */
162
+ export function impactInWords(line: ImpactLine): string {
163
+ const people = [
164
+ line.people > 0 ? (line.people === 1 ? '1 person' : `${line.people} people`) : null,
165
+ line.services > 0 ? (line.services === 1 ? '1 service account' : `${line.services} service accounts`) : null,
166
+ ].filter((part) => part !== null).join(' and ');
167
+ const can = line.change === 'widens' ? 'can now' : 'can no longer';
168
+ const wide = projectWide(line.permission);
169
+ const count = wide ? line.projects : line.environments;
170
+ const only = count === 1 ? placeOf(line.examples[0]) : null;
171
+ const where = only !== null
172
+ ? `${wide ? 'on' : 'in'} ${only}${line.protected ? ', protected' : ''}`
173
+ : `${wide ? 'on' : 'in'} ${count} ${line.protected ? 'protected ' : ''}${wide ? (count === 1 ? 'project' : 'projects') : count === 1 ? 'environment' : 'environments'}`;
174
+ return `${people} ${can} ${PERMISSION_WORDS[line.permission].verb} ${where}`;
175
+ }
176
+
177
+ /** The place of an impact's example, `ada@acme.example on market/prod`: `market/prod`. */
178
+ function placeOf(example: string | undefined): string | null {
179
+ const at = example?.lastIndexOf(' on ') ?? -1;
180
+ return example === undefined || at < 0 ? null : example.slice(at + ' on '.length);
181
+ }
182
+
183
+ /** Who an impact line reaches, for its note: `ada@acme.example on market/prod, bo@acme.example on market/prod`. */
184
+ export function impactExamples(line: ImpactLine): string | null {
185
+ return line.examples.length === 0 ? null : `${line.examples.join(', ')}${line.people + line.services > line.examples.length ? ', …' : ''}`;
186
+ }
187
+
188
+ /**
189
+ * What protecting an environment does, said by a role whose two columns
190
+ * differ, Developer first: "Developers use and write values, and read
191
+ * none". Null where no role's do, so protecting changes nothing.
192
+ */
193
+ export function protectionInWords(roles: readonly Pick<RoleView, 'id' | 'name' | 'permissions' | 'protected'>[]): string | null {
194
+ const differs = (role: Pick<RoleView, 'permissions' | 'protected'>) =>
195
+ role.permissions.some((permission) => !projectWide(permission) && !role.protected.includes(permission));
196
+ const role = roles.find((each) => each.id === 'developer' && differs(each)) ?? roles.find(differs);
197
+ if (role === undefined) return null;
198
+ const held = columnInWords(role.protected);
199
+ const loses = role.permissions.includes('secret.read') && !role.protected.includes('secret.read') && role.protected.length > 0;
200
+ return `${role.name}s ${held === 'nothing' ? 'hold nothing' : held}${loses ? ', and read none' : ''}`;
201
+ }
@@ -62,3 +62,15 @@ export function rowReads(state: RowReads, action: RowReadsAction): RowReads {
62
62
  export function revealToggleDisabled(state: RowReads, shown: Reveal | null): boolean {
63
63
  return shown === null && state.revealing;
64
64
  }
65
+
66
+ /**
67
+ * The value an edit starts from: a plain one as listed, one the caller reads
68
+ * as `read` opens it, or none, the editor opening empty to replace it: a
69
+ * sensitive value, a parent's they do not read, or a read refused or failed,
70
+ * whose reason the row says. It always opens: writing a value takes no read
71
+ * of the one it replaces.
72
+ */
73
+ export async function valueToEdit(row: { value: string | null; readable: boolean }, read: () => Promise<string | null>): Promise<string | null> {
74
+ if (row.value !== null) return row.value;
75
+ return row.readable ? read() : null;
76
+ }
@@ -1,11 +1,15 @@
1
1
  import type { Generation } from '@coffre/core/recipe';
2
+ import type { Sensitivity } from '../shared/models.ts';
3
+ import { stricter } from './sensitivity.ts';
2
4
 
3
5
  /**
4
6
  * A second secret a row writes with its own value, in the same patch: a
5
7
  * generated key pair's public key, beside its private key. It is part of
6
- * the row's edit, so saving, undoing or retrying the row takes both.
8
+ * the row's edit, so saving, undoing or retrying the row takes both. It is
9
+ * written at its own level, not its row's (`companionLevel`): `sensitivity`
10
+ * where the user chose one.
7
11
  */
8
- export type Companion = { key: string; value: string };
12
+ export type Companion = { key: string; value: string; sensitivity?: 'secret' | 'sensitive' };
9
13
 
10
14
  export type SecretDraft = {
11
15
  id: number;
@@ -14,6 +18,8 @@ export type SecretDraft = {
14
18
  companion?: Companion;
15
19
  /** The recipe a generated value was made by, saved with it; typing over the value drops it. */
16
20
  recipe?: string;
21
+ /** Who sees it (`lib/sensitivity.ts`). */
22
+ sensitivity: Sensitivity;
17
23
  };
18
24
 
19
25
  export type SecretChange = {
@@ -24,15 +30,52 @@ export type SecretChange = {
24
30
  companion?: Companion;
25
31
  /** Only beside a generated value. */
26
32
  recipe?: string;
33
+ /**
34
+ * Who sees the key's value once saved: beside a new value, that value's
35
+ * level; alone, a mark, the current value made stricter and kept (`valueEdit`).
36
+ */
37
+ sensitivity?: Sensitivity;
27
38
  };
28
39
 
29
- type ActiveSecret = { key: string };
40
+ /**
41
+ * What an edit of a row's value, and of who sees it, makes of its change,
42
+ * from where it started: `from.start`, the value the editor opened on (''
43
+ * when it could not be read), and `from.level`, who sees the row's value
44
+ * now (null for none of its own: a secret is written). A value left as it
45
+ * opened writes nothing; its level changed alone is then a mark. Looser
46
+ * than the row, the field opens empty, as that takes the value typed again:
47
+ * a stored value is never made more visible by a flip. Back where it
48
+ * started, it is no change.
49
+ *
50
+ * secret 'sk_1', opened on 'sk_1': Sensitive -> { value: null, sensitivity: 'sensitive' }, a mark
51
+ * secret 'sk_1', opened on 'sk_1': Plain -> { value: null, sensitivity: 'plain' }, waiting for a value
52
+ * then 'sk_2' typed -> { value: 'sk_2', sensitivity: 'plain' }
53
+ */
54
+ export function valueEdit(
55
+ from: { start: string; level: Sensitivity | null },
56
+ next: { value: string | null; sensitivity: Sensitivity },
57
+ ): Pick<SecretChange, 'value' | 'sensitivity'> {
58
+ const level = from.level ?? 'secret';
59
+ const opened = stricter(level, next.sensitivity) ? '' : from.start;
60
+ const value = next.value === opened ? null : next.value;
61
+ return { value, sensitivity: value === null && next.sensitivity === level ? undefined : next.sensitivity };
62
+ }
63
+
64
+ /** A listed key, and who sees its value now (null for none of its own). */
65
+ type ActiveSecret = { key: string; sensitivity?: Sensitivity | null };
30
66
 
31
67
  /**
32
- * A merge patch: a string sets a key, adding it if it is new; a value with
33
- * how it was generated sets it with its recipe; `null` archives it.
68
+ * A merge patch: a value sets a key with who sees it, adding it if it is
69
+ * new; a value with how it was generated sets it with its recipe; a level
70
+ * alone makes the key's value stricter, kept; `null` archives it.
34
71
  */
35
- export type SecretPatch = Record<string, string | { value: string; generated: Generation } | null>;
72
+ export type SecretPatch = Record<
73
+ string,
74
+ | { value: string; sensitivity: Sensitivity }
75
+ | { value: string; generated: Generation; sensitivity: 'secret' | 'sensitive' }
76
+ | { sensitivity: Sensitivity }
77
+ | null
78
+ >;
36
79
 
37
80
  /**
38
81
  * How a row's generated value was made, as its write says it: its recipe,
@@ -45,16 +88,101 @@ function generationOf(key: string, edit: { recipe?: string; companion?: Companio
45
88
  : { recipe: edit.recipe, pair: { private: key, public: edit.companion.key.trim() } };
46
89
  }
47
90
 
48
- /** What a row writes under each key: its value, and its companion's beside it. */
49
- function rowPatch(key: string, value: string, edit: { recipe?: string; companion?: Companion }): SecretPatch {
91
+ type ValueEdit = { recipe?: string; companion?: Companion; sensitivity?: Sensitivity };
92
+
93
+ /** Who sees the value a row writes: a secret unless it says, and a generated one never plain. */
94
+ function levelOf(edit: ValueEdit): 'secret' | 'sensitive' | 'plain' {
95
+ return edit.sensitivity === 'sensitive' || (edit.sensitivity === 'plain' && edit.recipe === undefined) ? edit.sensitivity : 'secret';
96
+ }
97
+
98
+ /**
99
+ * Who sees each listed key's value now, by its name after the save: a
100
+ * renamed key keeps its level under its new name; an archived one is gone.
101
+ */
102
+ function levelsNow(
103
+ active: readonly ActiveSecret[],
104
+ changes: Readonly<Record<string, SecretChange>>,
105
+ ): Map<string, Sensitivity | null> {
106
+ const out = new Map<string, Sensitivity | null>();
107
+ for (const entry of active) {
108
+ const change = secretChangeFor(changes, entry.key);
109
+ if (change?.archived) continue;
110
+ out.set(change?.key.trim() ?? entry.key, entry.sensitivity ?? null);
111
+ }
112
+ return out;
113
+ }
114
+
115
+ /**
116
+ * Who sees the public key a pair writes: who the user chose, else who sees
117
+ * the key it writes over now, or a secret, as a generated value is never
118
+ * plain. A public key need not be hidden, so a sensitive private key does
119
+ * not make it sensitive.
120
+ *
121
+ * PRIVATE_KEY sensitive, PUBLIC_KEY secret -> PUBLIC_KEY written secret
122
+ * PRIVATE_KEY secret, PUBLIC_KEY sensitive -> PUBLIC_KEY written sensitive
123
+ * PUBLIC_KEY new -> secret
124
+ */
125
+ function companionLevel(companion: Companion, now: ReadonlyMap<string, Sensitivity | null>): 'secret' | 'sensitive' {
126
+ return companion.sensitivity ?? (now.get(companion.key.trim()) === 'sensitive' ? 'sensitive' : 'secret');
127
+ }
128
+
129
+ /**
130
+ * What a row writes under each key: its value, and its companion's beside
131
+ * it, each saying who sees it, as every write does: over a sensitive key,
132
+ * one that said nothing would stay sensitive.
133
+ */
134
+ function rowPatch(key: string, value: string, edit: ValueEdit, now: ReadonlyMap<string, Sensitivity | null>): SecretPatch {
50
135
  const generated = generationOf(key, edit);
51
- const entry = (each: string) => (generated === undefined ? each : { value: each, generated });
136
+ const entry = (each: string, sensitivity: Sensitivity) => (generated === undefined || sensitivity === 'plain'
137
+ ? { value: each, sensitivity }
138
+ : { value: each, generated, sensitivity });
52
139
  const patch: SecretPatch = Object.create(null);
53
- patch[key] = entry(value);
54
- if (edit.companion !== undefined) patch[edit.companion.key.trim()] = entry(edit.companion.value);
140
+ patch[key] = entry(value, levelOf(edit));
141
+ if (edit.companion !== undefined) patch[edit.companion.key.trim()] = entry(edit.companion.value, companionLevel(edit.companion, now));
55
142
  return patch;
56
143
  }
57
144
 
145
+ /**
146
+ * The one merge patch a save writes, by each key's name after its renames:
147
+ * every value with its companion, every mark and every archive. An edit
148
+ * whose key went from the list writes nothing.
149
+ */
150
+ function patchOf(
151
+ active: readonly ActiveSecret[],
152
+ drafts: readonly SecretDraft[],
153
+ changes: Readonly<Record<string, SecretChange>>,
154
+ ): SecretPatch {
155
+ const now = levelsNow(active, changes);
156
+ // A key named `__proto__` is a key like any other.
157
+ const patch: SecretPatch = Object.create(null);
158
+ for (const entry of active) {
159
+ const change = secretChangeFor(changes, entry.key);
160
+ if (change === undefined) continue;
161
+ const key = change.key.trim();
162
+ if (change.archived) patch[entry.key] = null;
163
+ else if (change.value !== null) Object.assign(patch, rowPatch(key, change.value, change, now));
164
+ else if (change.sensitivity !== undefined) patch[key] = { sensitivity: change.sensitivity };
165
+ }
166
+ for (const draft of drafts) Object.assign(patch, rowPatch(draft.key.trim(), draft.value, draft, now));
167
+ return patch;
168
+ }
169
+
170
+ /**
171
+ * The keys a save makes sensitive, by their names after it: each it writes
172
+ * sensitive, a companion included, that was not sensitive before. Nobody
173
+ * sees them again, so the save asks first.
174
+ */
175
+ export function madeSensitive(
176
+ active: readonly ActiveSecret[],
177
+ drafts: readonly SecretDraft[],
178
+ changes: Readonly<Record<string, SecretChange>>,
179
+ ): string[] {
180
+ const now = levelsNow(active, changes);
181
+ return Object.entries(patchOf(active, drafts, changes))
182
+ .filter(([key, write]) => write !== null && write.sensitivity === 'sensitive' && now.get(key) !== 'sensitive')
183
+ .map(([key]) => key);
184
+ }
185
+
58
186
  /**
59
187
  * The recipe each key a save writes will hold, by its name after the save:
60
188
  * what the list shows of it until it is read back.
@@ -79,6 +207,22 @@ export function generationsOf(
79
207
  return out;
80
208
  }
81
209
 
210
+ /**
211
+ * Who sees each value a save writes, and a plain one's value, by its key's
212
+ * name after the save: what the list shows of it until it is read back.
213
+ */
214
+ export function levelsOf(
215
+ active: readonly ActiveSecret[],
216
+ drafts: readonly SecretDraft[],
217
+ changes: Readonly<Record<string, SecretChange>>,
218
+ ): Map<string, { sensitivity: Sensitivity; value: string | null }> {
219
+ const out = new Map<string, { sensitivity: Sensitivity; value: string | null }>();
220
+ for (const [key, write] of Object.entries(patchOf(active, drafts, changes))) {
221
+ if (write !== null && 'value' in write) out.set(key, { sensitivity: write.sensitivity, value: write.sensitivity === 'plain' ? write.value : null });
222
+ }
223
+ return out;
224
+ }
225
+
82
226
  type SecretEditOperations = {
83
227
  rename: (key: string, nextKey: string) => Promise<void>;
84
228
  /** One transaction: every key in it lands, or none does. */
@@ -140,7 +284,7 @@ export function hasSecretEditConflict(
140
284
  const valueEditTargets = new Set(
141
285
  active.flatMap((entry) => {
142
286
  const change = secretChangeFor(changes, entry.key);
143
- return change !== undefined && !change.archived && change.value !== null
287
+ return change !== undefined && !change.archived && (change.value !== null || change.sensitivity !== undefined)
144
288
  ? [change.key.trim()]
145
289
  : [];
146
290
  }),
@@ -183,24 +327,16 @@ export async function applySecretEditBatch({
183
327
  }
184
328
 
185
329
  let applied = 0;
186
- // A key named `__proto__` is a key like any other.
187
- const patch: SecretPatch = Object.create(null);
330
+ const patch = patchOf(active, drafts, changes);
188
331
  try {
189
332
  for (const { sourceKey, change } of plan) {
190
- if (change.archived) {
191
- patch[sourceKey] = null;
192
- continue;
193
- }
194
333
  const key = change.key.trim();
195
- if (key !== sourceKey) {
196
- await operations.rename(sourceKey, key);
197
- delete remainingChanges[sourceKey];
198
- applied += 1;
199
- if (change.value !== null) remainingChanges[key] = { ...change, key };
200
- }
201
- if (change.value !== null) Object.assign(patch, rowPatch(key, change.value, change));
334
+ if (change.archived || key === sourceKey) continue;
335
+ await operations.rename(sourceKey, key);
336
+ delete remainingChanges[sourceKey];
337
+ applied += 1;
338
+ if (change.value !== null || change.sensitivity !== undefined) remainingChanges[key] = { ...change, key };
202
339
  }
203
- for (const draft of drafts) Object.assign(patch, rowPatch(draft.key.trim(), draft.value, draft));
204
340
 
205
341
  const written = Object.keys(patch).length;
206
342
  if (written > 0) await operations.write({ ...patch });
@@ -0,0 +1,50 @@
1
+ import type { SecretKey, Sensitivity } from '../shared/models.ts';
2
+ import type { SecretChange } from './secret-edit-batch.ts';
3
+
4
+ /**
5
+ * Who sees a key's value, loosest first: `plain`, whoever lists its
6
+ * environment; `secret`, the default, people whose role reads secrets;
7
+ * `sensitive`, no person, Owners included, while their apps use it through
8
+ * the credential proxy and service accounts read it. A key is made
9
+ * stricter with its value kept; looser only with its value typed again, so
10
+ * nobody shows a value by flipping it.
11
+ */
12
+ export const SENSITIVITIES = ['plain', 'secret', 'sensitive'] as const satisfies readonly Sensitivity[];
13
+
14
+ /** Each level as the page names it, and who it lets see the value. */
15
+ export const LEVELS: Record<Sensitivity, { label: string; hint: string }> = {
16
+ plain: { label: 'Plain', hint: 'Visible to anyone who can see this environment' },
17
+ secret: { label: 'Secret', hint: 'Visible to people whose role can read secrets' },
18
+ sensitive: { label: 'Sensitive', hint: 'Never shown to anyone, Owners included. Used through the proxy or by services' },
19
+ };
20
+
21
+ /** The levels in your personal config, `dev@me`, whose values nobody else sees, whatever their level. */
22
+ const PERSONAL_LEVELS: Record<Sensitivity, { label: string; hint: string }> = {
23
+ plain: { label: 'Plain', hint: 'Visible to you alone, as it is' },
24
+ secret: { label: 'Secret', hint: 'Visible to you alone, when you reveal it' },
25
+ sensitive: { label: 'Sensitive', hint: 'Never shown, you included. Your app uses it through the proxy' },
26
+ };
27
+
28
+ /** Each level as a page names it, in your personal config or elsewhere. */
29
+ export function levelsIn(personal: boolean): Record<Sensitivity, { label: string; hint: string }> {
30
+ return personal ? PERSONAL_LEVELS : LEVELS;
31
+ }
32
+
33
+ /** Whether `a` lets fewer people see a value than `b`. */
34
+ export function stricter(a: Sensitivity, b: Sensitivity): boolean {
35
+ return SENSITIVITIES.indexOf(a) > SENSITIVITIES.indexOf(b);
36
+ }
37
+
38
+ /** A key's own value, which a mark makes stricter in place: not a reference's, nor one a fork inherits. */
39
+ export function markable(entry: SecretKey): boolean {
40
+ return entry.sensitivity !== null && entry.reference === null && (entry.parent === null || entry.parent.state === 'overridden');
41
+ }
42
+
43
+ /**
44
+ * Whether a change of who sees a key waits for its value typed: looser
45
+ * than the key is, or where it has no value of its own to mark.
46
+ */
47
+ export function waitsForValue(entry: SecretKey, change: SecretChange | undefined): boolean {
48
+ if (change === undefined || change.archived || change.value !== null || change.sensitivity === undefined) return false;
49
+ return !markable(entry) || stricter(entry.sensitivity!, change.sensitivity);
50
+ }
@@ -1,9 +1,12 @@
1
- import { inScope, ROLE_NAMES, ROLES, type Permission, type Role, type Scope } from '@coffre/core/access';
1
+ import { inScope, PROJECT_ONLY_PERMISSIONS, type Permission, type Role, type Scope } from '@coffre/core/access';
2
+ import type { RoleView } from '@coffre/client';
2
3
 
3
4
  import type { ProjectSummary } from '../shared/models';
4
5
 
5
6
  /** What `givable` reads of the shell: the projects, what you hold in each environment, and the setting. */
6
7
  type Holder = {
8
+ /** The instance's roles, as the policy defines them (`useRoles`). */
9
+ roles: readonly Pick<RoleView, 'id' | 'permissions' | 'assignableToEnvironment'>[];
7
10
  projects: readonly ProjectSummary[];
8
11
  environments: readonly { project: string; environment: string; permissions: Permission[] }[];
9
12
  /** The instance's setting as `/me` says it, projects by slug, those you see; null for a service account. */
@@ -14,23 +17,32 @@ type Holder = {
14
17
  * The roles you may give a service account at a project, or one of its
15
18
  * environments, as the server decides it (`givesService` in
16
19
  * @coffre/core/access): any, where you manage access; otherwise, inside the
17
- * instance's setting, those whose every permission you hold there.
20
+ * instance's setting, those whose every permission you hold there. An
21
+ * environment takes only the roles that hold nothing project-wide. A
22
+ * project's role reaches its protected environments too, where the service
23
+ * holds the role's normal column and you your protected one: you hold that
24
+ * normal column there as well, or give none.
18
25
  *
19
- * a Developer of every dev, at market/dev viewer, developer
26
+ * a Developer of every dev, at market/dev viewer, contributor, developer
20
27
  * the same, at market none: a project takes holding all of it
28
+ * a Developer of market, prod protected contributor: viewer and developer read prod, which you only use
21
29
  */
22
30
  export function givable(holder: Holder, project: ProjectSummary, environment: string | null): Role[] {
23
- const held = environment === null
24
- ? project.permissions
25
- : holder.environments.find((entry) => entry.project === project.slug && entry.environment === environment)?.permissions ?? [];
26
- if (held.includes('grant.manage')) return [...ROLE_NAMES];
31
+ const heldIn = (slug: string) => holder.environments.find((entry) => entry.project === project.slug && entry.environment === slug)?.permissions ?? [];
32
+ const held = environment === null ? project.permissions : heldIn(environment);
33
+ const roles = holder.roles.filter((role) => environment === null || role.assignableToEnvironment);
34
+ if (held.includes('grant.manage')) return roles.map((role) => role.id);
27
35
  const setting = holder.serviceSetup;
28
36
  // The setting names projects by slug here, so a place is matched by its slugs.
29
37
  const place = environment === null
30
38
  ? { projectId: project.slug }
31
39
  : { projectId: project.slug, environmentId: environment, environmentSlug: environment };
32
40
  if (setting === null || !inScope(setting, place)) return [];
33
- return ROLE_NAMES.filter((role) => ROLES[role].permissions.every((permission) => held.includes(permission)));
41
+ const reached = environment === null ? project.environments.filter((candidate) => candidate.protected && !candidate.personal).map((candidate) => heldIn(candidate.slug)) : [];
42
+ const gives = (permission: Permission) =>
43
+ held.includes(permission) && (PROJECT_ONLY_PERMISSIONS.includes(permission) || reached.every((there) => there.includes(permission)));
44
+ // A role that holds nothing is given where its giver manages access alone, as the server decides (`givesService`).
45
+ return roles.filter((role) => role.permissions.length > 0 && role.permissions.every(gives)).map((role) => role.id);
34
46
  }
35
47
 
36
48
  /** The projects where you may give a service account something: on the project, or on one of its environments. */
@@ -0,0 +1,17 @@
1
+ import type { RolesView } from '@coffre/client';
2
+ import { useQuery } from '@tanstack/react-query';
3
+
4
+ import { useCoffre } from './coffre';
5
+ import { queries } from './queries';
6
+ import { SHIPPED_ROLES } from './roles';
7
+
8
+ /**
9
+ * The instance's roles, for a picker or a name: as an Owner edited and made
10
+ * them once read, and as they ship until then, or where they cannot be read,
11
+ * so a picker never waits for them. The server decides every grant: a role
12
+ * shown here a moment stale is one it refuses, never one it gives.
13
+ */
14
+ export function useRoles(): RolesView {
15
+ const { data } = useQuery({ ...queries.roles(useCoffre()), placeholderData: { ok: true as const, ...SHIPPED_ROLES } });
16
+ return data?.ok === true ? data : SHIPPED_ROLES;
17
+ }