@bevel-software/platform-core-backend 0.21.0 → 0.22.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 (177) hide show
  1. package/dist/core/create-core-server.d.ts.map +1 -1
  2. package/dist/core/create-core-server.js +32 -2
  3. package/dist/core/create-core-server.js.map +1 -1
  4. package/dist/core/create-core-services.d.ts +13 -1
  5. package/dist/core/create-core-services.d.ts.map +1 -1
  6. package/dist/core/create-core-services.js +51 -5
  7. package/dist/core/create-core-services.js.map +1 -1
  8. package/dist/modules/access/access-requests.contract.d.ts +75 -0
  9. package/dist/modules/access/access-requests.contract.d.ts.map +1 -0
  10. package/dist/modules/access/access-requests.contract.js +20 -0
  11. package/dist/modules/access/access-requests.contract.js.map +1 -0
  12. package/dist/modules/access/access-requests.routes.d.ts +35 -0
  13. package/dist/modules/access/access-requests.routes.d.ts.map +1 -0
  14. package/dist/modules/access/access-requests.routes.js +237 -0
  15. package/dist/modules/access/access-requests.routes.js.map +1 -0
  16. package/dist/modules/access/access-requests.service.d.ts +123 -0
  17. package/dist/modules/access/access-requests.service.d.ts.map +1 -0
  18. package/dist/modules/access/access-requests.service.js +337 -0
  19. package/dist/modules/access/access-requests.service.js.map +1 -0
  20. package/dist/modules/access-model/access-grammar.d.ts +12 -0
  21. package/dist/modules/access-model/access-grammar.d.ts.map +1 -1
  22. package/dist/modules/access-model/access-grammar.js +24 -0
  23. package/dist/modules/access-model/access-grammar.js.map +1 -1
  24. package/dist/modules/auth/auth.service.d.ts +26 -1
  25. package/dist/modules/auth/auth.service.d.ts.map +1 -1
  26. package/dist/modules/auth/auth.service.js +11 -2
  27. package/dist/modules/auth/auth.service.js.map +1 -1
  28. package/dist/modules/github-app/github-app.client.d.ts +101 -0
  29. package/dist/modules/github-app/github-app.client.d.ts.map +1 -0
  30. package/dist/modules/github-app/github-app.client.js +222 -0
  31. package/dist/modules/github-app/github-app.client.js.map +1 -0
  32. package/dist/modules/github-app/github-app.connection.d.ts +102 -0
  33. package/dist/modules/github-app/github-app.connection.d.ts.map +1 -0
  34. package/dist/modules/github-app/github-app.connection.js +185 -0
  35. package/dist/modules/github-app/github-app.connection.js.map +1 -0
  36. package/dist/modules/github-app/github-app.routes.d.ts +59 -0
  37. package/dist/modules/github-app/github-app.routes.d.ts.map +1 -0
  38. package/dist/modules/github-app/github-app.routes.js +323 -0
  39. package/dist/modules/github-app/github-app.routes.js.map +1 -0
  40. package/dist/modules/github-app/index.d.ts +4 -0
  41. package/dist/modules/github-app/index.d.ts.map +1 -0
  42. package/dist/modules/github-app/index.js +4 -0
  43. package/dist/modules/github-app/index.js.map +1 -0
  44. package/dist/modules/kb-fs/remote-url.d.ts +22 -0
  45. package/dist/modules/kb-fs/remote-url.d.ts.map +1 -0
  46. package/dist/modules/kb-fs/remote-url.js +35 -0
  47. package/dist/modules/kb-fs/remote-url.js.map +1 -0
  48. package/dist/modules/plugins/join-proposals.d.ts +17 -5
  49. package/dist/modules/plugins/join-proposals.d.ts.map +1 -1
  50. package/dist/modules/plugins/join-proposals.js +76 -22
  51. package/dist/modules/plugins/join-proposals.js.map +1 -1
  52. package/dist/modules/plugins/join-requests.service.d.ts +111 -18
  53. package/dist/modules/plugins/join-requests.service.d.ts.map +1 -1
  54. package/dist/modules/plugins/join-requests.service.js +173 -29
  55. package/dist/modules/plugins/join-requests.service.js.map +1 -1
  56. package/dist/modules/plugins/plugins.routes.d.ts.map +1 -1
  57. package/dist/modules/plugins/plugins.routes.js +3 -2
  58. package/dist/modules/plugins/plugins.routes.js.map +1 -1
  59. package/dist/modules/settings/deployment-settings.service.d.ts +22 -1
  60. package/dist/modules/settings/deployment-settings.service.d.ts.map +1 -1
  61. package/dist/modules/settings/deployment-settings.service.js +93 -4
  62. package/dist/modules/settings/deployment-settings.service.js.map +1 -1
  63. package/dist/modules/settings/managed-repository.d.ts +43 -0
  64. package/dist/modules/settings/managed-repository.d.ts.map +1 -0
  65. package/dist/modules/settings/managed-repository.js +60 -0
  66. package/dist/modules/settings/managed-repository.js.map +1 -0
  67. package/dist/modules/settings/repository-source.d.ts +128 -0
  68. package/dist/modules/settings/repository-source.d.ts.map +1 -0
  69. package/dist/modules/settings/repository-source.js +150 -0
  70. package/dist/modules/settings/repository-source.js.map +1 -0
  71. package/dist/modules/settings/setup.routes.d.ts +27 -4
  72. package/dist/modules/settings/setup.routes.d.ts.map +1 -1
  73. package/dist/modules/settings/setup.routes.js +187 -13
  74. package/dist/modules/settings/setup.routes.js.map +1 -1
  75. package/dist/modules/skills/skill-access-requests.routes.d.ts +6 -8
  76. package/dist/modules/skills/skill-access-requests.routes.d.ts.map +1 -1
  77. package/dist/modules/skills/skill-access-requests.routes.js +24 -63
  78. package/dist/modules/skills/skill-access-requests.routes.js.map +1 -1
  79. package/dist/modules/tool-helpers/tool-context.d.ts.map +1 -1
  80. package/dist/modules/tool-helpers/tool-context.js +15 -0
  81. package/dist/modules/tool-helpers/tool-context.js.map +1 -1
  82. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
  83. package/dist/modules/workflow/agent-tools/workflow.tools.js +38 -2
  84. package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
  85. package/dist/modules/workflow/git/git.service.d.ts +3 -1
  86. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  87. package/dist/modules/workflow/git/git.service.js +17 -4
  88. package/dist/modules/workflow/git/git.service.js.map +1 -1
  89. package/dist/modules/workflow/git/node-git-runner.d.ts.map +1 -1
  90. package/dist/modules/workflow/git/node-git-runner.js +5 -0
  91. package/dist/modules/workflow/git/node-git-runner.js.map +1 -1
  92. package/dist/modules/workflow/git/pull-request.service.d.ts +45 -0
  93. package/dist/modules/workflow/git/pull-request.service.d.ts.map +1 -1
  94. package/dist/modules/workflow/git/pull-request.service.js +99 -0
  95. package/dist/modules/workflow/git/pull-request.service.js.map +1 -1
  96. package/dist/modules/workflow/workflow.routes.d.ts.map +1 -1
  97. package/dist/modules/workflow/workflow.routes.js +3 -1
  98. package/dist/modules/workflow/workflow.routes.js.map +1 -1
  99. package/dist/modules/workflow/workflow.service.d.ts +34 -7
  100. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  101. package/dist/modules/workflow/workflow.service.js +148 -48
  102. package/dist/modules/workflow/workflow.service.js.map +1 -1
  103. package/dist/modules/workspace/startup/kb-startup-runner.d.ts +66 -0
  104. package/dist/modules/workspace/startup/kb-startup-runner.d.ts.map +1 -1
  105. package/dist/modules/workspace/startup/kb-startup-runner.js +148 -0
  106. package/dist/modules/workspace/startup/kb-startup-runner.js.map +1 -1
  107. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  108. package/dist/modules/workspace/workspace.service.js +17 -1
  109. package/dist/modules/workspace/workspace.service.js.map +1 -1
  110. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  111. package/dist/modules/workspace/workspace.tools.js +28 -2
  112. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  113. package/dist/shared/domain-errors.d.ts +39 -0
  114. package/dist/shared/domain-errors.d.ts.map +1 -1
  115. package/dist/shared/domain-errors.js +55 -0
  116. package/dist/shared/domain-errors.js.map +1 -1
  117. package/dist/shared/git.contract.d.ts +10 -0
  118. package/dist/shared/git.contract.d.ts.map +1 -1
  119. package/dist/shared/git.contract.js.map +1 -1
  120. package/package.json +3 -3
  121. package/src/core/create-core-server.ts +37 -1
  122. package/src/core/create-core-services.ts +65 -8
  123. package/src/modules/access/__tests__/access-requests.recut.test.ts +134 -0
  124. package/src/modules/access/__tests__/access-requests.routes.test.ts +610 -0
  125. package/src/modules/access/access-requests.contract.ts +93 -0
  126. package/src/modules/access/access-requests.routes.ts +286 -0
  127. package/src/modules/access/access-requests.service.ts +420 -0
  128. package/src/modules/access-model/access-grammar.ts +22 -0
  129. package/src/modules/auth/__tests__/auth.service.test.ts +38 -0
  130. package/src/modules/auth/auth.service.ts +28 -1
  131. package/src/modules/github-app/__tests__/github-app.test.ts +848 -0
  132. package/src/modules/github-app/github-app.client.ts +268 -0
  133. package/src/modules/github-app/github-app.connection.ts +204 -0
  134. package/src/modules/github-app/github-app.routes.ts +359 -0
  135. package/src/modules/github-app/index.ts +19 -0
  136. package/src/modules/kb-fs/__tests__/remote-url.test.ts +38 -0
  137. package/src/modules/kb-fs/remote-url.ts +35 -0
  138. package/src/modules/plugins/__tests__/join-proposals.test.ts +100 -19
  139. package/src/modules/plugins/__tests__/join-requests.service.test.ts +27 -11
  140. package/src/modules/plugins/__tests__/join-requests.settlement.test.ts +371 -0
  141. package/src/modules/plugins/__tests__/plugins.routes.test.ts +1 -1
  142. package/src/modules/plugins/join-proposals.ts +87 -19
  143. package/src/modules/plugins/join-requests.service.ts +199 -39
  144. package/src/modules/plugins/plugins.routes.ts +3 -2
  145. package/src/modules/settings/__tests__/repository-source.test.ts +191 -0
  146. package/src/modules/settings/__tests__/setup.routes.git-mode.test.ts +353 -0
  147. package/src/modules/settings/__tests__/setup.routes.github-app.test.ts +282 -0
  148. package/src/modules/settings/__tests__/setup.routes.managed-phase.test.ts +233 -0
  149. package/src/modules/settings/deployment-settings.service.ts +109 -3
  150. package/src/modules/settings/managed-repository.ts +68 -0
  151. package/src/modules/settings/repository-source.ts +197 -0
  152. package/src/modules/settings/setup.routes.ts +214 -10
  153. package/src/modules/skills/__tests__/skill-access-requests.routes.test.ts +5 -1
  154. package/src/modules/skills/skill-access-requests.routes.ts +25 -75
  155. package/src/modules/tool-helpers/tool-context.ts +15 -0
  156. package/src/modules/workflow/__tests__/apply-failure.test.ts +9 -1
  157. package/src/modules/workflow/__tests__/workflow.service.facade.test.ts +159 -8
  158. package/src/modules/workflow/__tests__/workflow.service.update-from-target.test.ts +146 -40
  159. package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +141 -1
  160. package/src/modules/workflow/agent-tools/workflow.tools.ts +49 -3
  161. package/src/modules/workflow/git/__tests__/git.service.pull.test.ts +121 -0
  162. package/src/modules/workflow/git/__tests__/pull-request.service.getPrDetail.test.ts +145 -2
  163. package/src/modules/workflow/git/__tests__/pull-request.service.viewer-can-delete.test.ts +166 -0
  164. package/src/modules/workflow/git/git.service.ts +25 -4
  165. package/src/modules/workflow/git/node-git-runner.ts +6 -0
  166. package/src/modules/workflow/git/pull-request.service.ts +119 -0
  167. package/src/modules/workflow/workflow.routes.ts +3 -1
  168. package/src/modules/workflow/workflow.service.ts +170 -52
  169. package/src/modules/workspace/__tests__/workspace.service.unknown-branch.test.ts +43 -0
  170. package/src/modules/workspace/__tests__/workspace.tools.branch-errors.test.ts +233 -7
  171. package/src/modules/workspace/__tests__/workspace.tools.test.ts +35 -3
  172. package/src/modules/workspace/startup/__tests__/kb-startup-runner.test.ts +211 -0
  173. package/src/modules/workspace/startup/kb-startup-runner.ts +159 -0
  174. package/src/modules/workspace/workspace.service.ts +17 -1
  175. package/src/modules/workspace/workspace.tools.ts +35 -0
  176. package/src/shared/domain-errors.ts +58 -0
  177. package/src/shared/git.contract.ts +10 -0
@@ -0,0 +1,420 @@
1
+ import path from 'node:path';
2
+ import {
3
+ joinBranchFor,
4
+ type AuthUser,
5
+ type IWorkflowService,
6
+ } from '@bevel-software/platform-shared';
7
+ import {
8
+ ChangeRequestConflictsError,
9
+ DuplicateChangeRequestError,
10
+ } from '../../shared/domain-errors.js';
11
+ import { isAbsence } from '../../shared/fs.contract.js';
12
+ import type { KbContext } from '../../shared/kb-context.js';
13
+ import { spliceGrant } from '../access-model/access-splice.js';
14
+ import type { WorkspaceService } from '../workspace/workspace.service.js';
15
+ import { logger } from '../../shared/logging.js';
16
+ import { AccessMutationError } from './access-mutation.service.js';
17
+ import {
18
+ rulesFileFor,
19
+ type AccessRequestTarget,
20
+ type IAccessRequestLifecycle,
21
+ type RequestLevel,
22
+ } from './access-requests.contract.js';
23
+
24
+ /** How the dialog spells each level — the same words the request is answered in. */
25
+ const log = logger('access.request');
26
+
27
+ export const LEVEL_LABEL: Record<RequestLevel, string> = {
28
+ write: 'Can edit',
29
+ owner: 'Owner',
30
+ };
31
+
32
+ /** What the requester's own dialog shows in place of the control. */
33
+ export interface AccessRequestStatus {
34
+ /**
35
+ * - `none` nothing outstanding; show the control.
36
+ * - `pending` a request is open and still asking for something.
37
+ * - `not-accepted` their last request closed without the access landing.
38
+ */
39
+ state: 'none' | 'pending' | 'not-accepted';
40
+ level?: RequestLevel;
41
+ number?: number;
42
+ }
43
+
44
+ /** The name an item is called by in a title — the last path segment. */
45
+ export function itemNameOf(repoRelPath: string): string {
46
+ if (!repoRelPath) return 'the workspace';
47
+ return path.posix.basename(repoRelPath) || repoRelPath;
48
+ }
49
+
50
+ /**
51
+ * Neutralise every character a markdown renderer would read as structure.
52
+ *
53
+ * The note is somebody's free text and it lands in a change request's
54
+ * description, which IS rendered. Escaping it is what makes "plain text" true:
55
+ * without this a note can carry a heading, a link, or an image pointing at a
56
+ * URL that logs whoever opens the request.
57
+ */
58
+ export function escapeMarkdown(text: string): string {
59
+ return text.replace(/[\\`*_{}[\]()#+\-.!|<>~]/g, (c) => `\\${c}`);
60
+ }
61
+
62
+ /** The exact inverse of {@link escapeMarkdown} — only our own backslashes go. */
63
+ function unescapeMarkdown(text: string): string {
64
+ return text.replace(/\\([\\`*_{}[\]()#+\-.!|<>~])/g, '$1');
65
+ }
66
+
67
+ /**
68
+ * The fence the note sits behind in a request's description.
69
+ *
70
+ * The description is the note's only home — there is no column for it — so the
71
+ * editors' banner has to read it back out of prose. Marking the block means
72
+ * that read is exact rather than a guess at which paragraph was the note, and
73
+ * an HTML comment is invisible in every surface that renders the description.
74
+ */
75
+ const NOTE_OPEN = '<!--hexis:access-request-note-->';
76
+ const NOTE_CLOSE = '<!--/hexis:access-request-note-->';
77
+
78
+ /**
79
+ * The level, recorded on the change request itself.
80
+ *
81
+ * The branch says what is proposed, but only while it can be read — and a
82
+ * clone whose refs are a few seconds stale cannot read a branch cut moments
83
+ * ago. The request's own row always can. "Requested: <level>" is a promise
84
+ * about a request, so it is answered from the request, not from a file at a
85
+ * ref that may not have arrived yet.
86
+ */
87
+ const LEVEL_MARK = /<!--hexis:access-request-level:(write|owner)-->/;
88
+
89
+ /**
90
+ * The requester's own words, back out of a request's description, or
91
+ * undefined when they wrote none. Unescaped exactly as they were escaped, so
92
+ * what the banner shows is what was typed.
93
+ */
94
+ /**
95
+ * The level a request asks for, off its own description. Undefined for a
96
+ * request opened before this marker existed — those are the skill route's,
97
+ * and the skill route only ever asked for `write`.
98
+ */
99
+ export function extractRequestLevel(body: string | null | undefined): RequestLevel | undefined {
100
+ const hit = body ? LEVEL_MARK.exec(body) : null;
101
+ return hit ? (hit[1] as RequestLevel) : undefined;
102
+ }
103
+
104
+ export function extractRequestNote(body: string | null | undefined): string | undefined {
105
+ if (!body) return undefined;
106
+ const start = body.indexOf(NOTE_OPEN);
107
+ if (start < 0) return undefined;
108
+ const end = body.indexOf(NOTE_CLOSE, start);
109
+ if (end < 0) return undefined;
110
+ const note = body
111
+ .slice(start + NOTE_OPEN.length, end)
112
+ .split(/\r?\n/)
113
+ .filter((line) => line.startsWith('>'))
114
+ .map((line) => unescapeMarkdown(line.replace(/^>\s?/, '')))
115
+ .join('\n')
116
+ .trim();
117
+ return note || undefined;
118
+ }
119
+
120
+ /**
121
+ * Asking for Can edit or Owner on ONE item, and reading back what came of it.
122
+ *
123
+ * A request is a change request whose branch proposes exactly one grant in the
124
+ * item's own rules — a folder's `access.md`, or a file's own frontmatter — and
125
+ * nothing else. There is no request table: the branch IS the request, named
126
+ * deterministically from (person, item), so a second click finds the first
127
+ * click's request instead of opening a rival. Editors answer it by granting
128
+ * through the ordinary access path, and it retires itself
129
+ * ({@link IAccessRequestLifecycle}) once the access has landed however it
130
+ * landed.
131
+ *
132
+ * Keyed on the ITEM'S PATH, which is what the skill page's "Request write
133
+ * access" keys on too — so a Can edit request on a skill's folder and that
134
+ * button open one request, shown on both surfaces.
135
+ */
136
+ export class AccessRequestsService {
137
+ constructor(
138
+ private readonly deps: {
139
+ workflow: IWorkflowService;
140
+ workspaceService: WorkspaceService;
141
+ lifecycle: IAccessRequestLifecycle;
142
+ kb: Pick<KbContext, 'defaultBranch' | 'defaultWorkspaceId' | 'kbDirName'>;
143
+ },
144
+ ) {}
145
+
146
+ /** The branch a request from `email` about `target` always lives on. */
147
+ branchFor(email: string, target: AccessRequestTarget): string {
148
+ return joinBranchFor(email, target.path);
149
+ }
150
+
151
+ /**
152
+ * Open `user`'s request for `level` on `target`, or answer with the one they
153
+ * already have open. Never opens a second request for the same pair.
154
+ */
155
+ async open(input: {
156
+ user: AuthUser;
157
+ target: AccessRequestTarget;
158
+ itemName: string;
159
+ level: RequestLevel;
160
+ note?: string;
161
+ }): Promise<{ number: number; level: RequestLevel }> {
162
+ const { user, target, itemName, level } = input;
163
+ const note = (input.note ?? '').trim();
164
+ const { workflow, workspaceService, kb } = this.deps;
165
+ const wsId = kb.defaultWorkspaceId();
166
+ const branch = this.branchFor(user.email, target);
167
+
168
+ // FRESH, and matched on the BRANCH rather than on the author: a repeated
169
+ // click must find the request the previous one opened (the cached listing
170
+ // can trail it), and the same lookup has to prove the branch free before
171
+ // it is recut below. The branch name already carries the person, so
172
+ // matching it is matching them.
173
+ const openOnBranch = async () =>
174
+ (await workflow.listChangeRequests({ fresh: true })).find(
175
+ (cr) => cr.state === 'open' && cr.branch === branch,
176
+ );
177
+ const existing = await openOnBranch();
178
+ if (existing) return { number: existing.number, level: await this.levelOf(existing.number) };
179
+
180
+ // Existence is PROBED, before and — if creation fails — after: the race
181
+ // shows up as "already exists" locally or as a rejected push when origin
182
+ // got there first, and a message is not a contract. STRICT: the list
183
+ // proves absence, and a listing that could not fetch proves nothing.
184
+ const branchExists = async () =>
185
+ (await workflow.listBranches(wsId, { freshFetch: true, strictFetch: true })).some(
186
+ (b) => b.name === branch,
187
+ );
188
+ // A branch still standing here belonged to an ANSWERED request: it holds a
189
+ // dead proposal on a base that may be months old. It cannot simply be
190
+ // written to. `openChangeRequest` merges live INTO the source branch, and
191
+ // that merge conflicts the moment live has touched the same rules file —
192
+ // which an editor granting anyone anything on this item does. The person
193
+ // asking would be shown "resolve the conflicts on <an internal branch>",
194
+ // about a branch they cannot reach, for good.
195
+ //
196
+ // So the branch is CUT AGAIN from live. Live's tip is then the merge base,
197
+ // the auto-merge is a no-op, and the diff is exactly the one grant this
198
+ // request proposes. Deleting it also retires its clone, so the old content
199
+ // cannot come back (`deleteBranch`), and `deleteBranch` refuses a branch
200
+ // with an open request — the guard against recutting one under a request
201
+ // that opened in the meantime.
202
+ let present = await branchExists();
203
+ if (present) {
204
+ try {
205
+ await workflow.deleteBranch(wsId, branch, user);
206
+ // A delete that RETURNED is proof enough; re-probing here would let a
207
+ // ref list that has not caught up talk us out of cutting the branch we
208
+ // just removed, and the proposal would have nowhere to go.
209
+ present = false;
210
+ } catch (err) {
211
+ // It raced into an open request, or could not be removed. Answer with
212
+ // the request if there is one; otherwise carry on against the branch
213
+ // as it stands, which is what this did before and still works whenever
214
+ // the live rules have not moved.
215
+ const raced = await openOnBranch();
216
+ if (raced) return { number: raced.number, level: await this.levelOf(raced.number) };
217
+ log.warn(
218
+ `could not recut the request branch "${branch}": ${
219
+ err instanceof Error ? err.message : String(err)
220
+ }`,
221
+ );
222
+ }
223
+ }
224
+ if (!present) {
225
+ try {
226
+ await workflow.createBranch(wsId, branch, kb.defaultBranch);
227
+ } catch (err) {
228
+ if (!(await branchExists())) throw err;
229
+ }
230
+ }
231
+
232
+ const rulesPath = rulesFileFor(target);
233
+ const wsRulesPath = `${kb.kbDirName}/${rulesPath}`;
234
+ // The proposal is spliced onto the LIVE copy, never onto whatever the
235
+ // branch holds. Belt and braces with the recut above: a branch that could
236
+ // not be recut still carries a declined proposal, and splicing onto it
237
+ // would ask for two levels at once. Starting from live means the request
238
+ // proposes exactly what was chosen this time.
239
+ const live = await this.readLive(target, wsRulesPath);
240
+ const spliced = spliceGrant(
241
+ live,
242
+ level,
243
+ { kind: 'user', email: user.email, displayName: user.name },
244
+ { allowScalar: target.kind === 'file', target: target.kind === 'folder' ? 'folder' : 'node' },
245
+ );
246
+
247
+ const ws = await workspaceService.getOrCreateForBranch(branch);
248
+ const onBranch = await workspaceService
249
+ .readFile(ws.id, wsRulesPath)
250
+ .catch((err: unknown) => {
251
+ if (!isAbsence(err)) throw err;
252
+ return null;
253
+ });
254
+ if (onBranch !== spliced.text) {
255
+ await workspaceService.writeFile(ws.id, wsRulesPath, spliced.text);
256
+ await workflow.commitChanges(
257
+ ws.id,
258
+ user,
259
+ `Request ${LEVEL_LABEL[level].toLowerCase()} access to ${itemName}`,
260
+ );
261
+ }
262
+
263
+ try {
264
+ const detail = await workflow.openChangeRequest(ws.id, user, {
265
+ sourceBranch: branch,
266
+ targetBranch: kb.defaultBranch,
267
+ title: `Access request: ${itemName}`,
268
+ description: this.describe({ user, target, level, note }),
269
+ });
270
+ return { number: detail.number, level };
271
+ } catch (err) {
272
+ // Two sends that raced past the listing above meet here, at the partial
273
+ // unique index on open (source, target). The loser answers with the
274
+ // winner's request rather than an error: the person asked once, and one
275
+ // request is what they get.
276
+ if (err instanceof DuplicateChangeRequestError) {
277
+ return { number: err.existingNumber, level: await this.levelOf(err.existingNumber) };
278
+ }
279
+ // The branch is recut from live above precisely so this cannot happen;
280
+ // reaching it means something raced. Whatever the cause, the person
281
+ // asking cannot act on "resolve the conflicts on
282
+ // reader2/join-artest3-04i7dr4" — they have never heard of that branch
283
+ // and could not reach it if they had. Say the one thing that IS theirs
284
+ // to do, and keep the detail where an operator will find it.
285
+ if (err instanceof ChangeRequestConflictsError) {
286
+ log.warn(
287
+ `request branch "${branch}" conflicted with live after being recut: ${err.message}`,
288
+ );
289
+ throw new AccessMutationError(
290
+ 'The rules changed while your request was being sent. Try again.',
291
+ 409,
292
+ { kind: 'request-raced' },
293
+ );
294
+ }
295
+ throw err;
296
+ }
297
+ }
298
+
299
+ /**
300
+ * What `user`'s dialog should say about `target`.
301
+ *
302
+ * The two states are answered from DIFFERENT sources, because different
303
+ * things prove them:
304
+ *
305
+ * pending an open request on this branch. That is the whole proof,
306
+ * and the level comes off the request itself — asking the
307
+ * branch would make "Requested: …" depend on whether this
308
+ * clone has fetched a ref that may be seconds old.
309
+ * not-accepted a closed request AND a branch that still carries an unmet
310
+ * proposal naming this person. A settled request has no
311
+ * branch left, so an accepted one can never read as
312
+ * declined; a branch that cannot be read proves nothing and
313
+ * reads as `none`, which shows the control rather than
314
+ * claiming a refusal nobody made.
315
+ */
316
+ async status(user: AuthUser, target: AccessRequestTarget): Promise<AccessRequestStatus> {
317
+ const { workflow } = this.deps;
318
+ const branch = this.branchFor(user.email, target);
319
+
320
+ const open = (await workflow.listChangeRequests({ fresh: true })).find(
321
+ (cr) => cr.state === 'open' && cr.branch === branch,
322
+ );
323
+ if (open) {
324
+ return { state: 'pending', level: await this.levelOf(open.number), number: open.number };
325
+ }
326
+
327
+ const level = await this.levelAskedOn(branch, target, user.email);
328
+ if (!level) return { state: 'none' };
329
+ const last = await workflow.latestClosedChangeRequest(user.email, branch);
330
+ return last ? { state: 'not-accepted', level, number: last.number } : { state: 'none' };
331
+ }
332
+
333
+ /**
334
+ * The level change request `number` asks for, off its own description.
335
+ *
336
+ * `write` when the description does not say: every request that predates the
337
+ * marker came from the skill page's "Request write access", which asks for
338
+ * exactly that. A detail that cannot be fetched falls there too — the line
339
+ * it feeds says which level was asked for, and Can edit is the lesser claim.
340
+ */
341
+ private async levelOf(number: number): Promise<RequestLevel> {
342
+ const detail = await this.deps.workflow
343
+ .getChangeRequestDetail(number, { patches: false })
344
+ .catch(() => null);
345
+ return extractRequestLevel(detail?.body) ?? 'write';
346
+ }
347
+
348
+ /**
349
+ * The level `email`'s branch still asks for on `target`, or null when it
350
+ * asks for nothing they do not already hold. Owner wins when a branch
351
+ * somehow carries both — it is the larger of the two, and it is the one the
352
+ * person is still waiting on.
353
+ */
354
+ private async levelAskedOn(
355
+ branch: string,
356
+ target: AccessRequestTarget,
357
+ email: string,
358
+ ): Promise<RequestLevel | null> {
359
+ const needle = email.trim().toLowerCase();
360
+ // null ⇒ the branch could not be read at all, which is not "asks for
361
+ // nothing". Saying nothing is outstanding shows the control, which is
362
+ // recoverable; claiming a refusal would not be.
363
+ const proposals = await this.deps.lifecycle.proposalsOn(branch, target);
364
+ if (proposals === null) return null;
365
+ const mine = proposals.filter(
366
+ (p) => p.principal.kind === 'user' && p.principal.email.trim().toLowerCase() === needle,
367
+ );
368
+ if (mine.some((p) => p.verb === 'owner')) return 'owner';
369
+ return mine.some((p) => p.verb === 'write') ? 'write' : null;
370
+ }
371
+
372
+ /**
373
+ * The live rules text to splice onto. A folder with no `access.md` yet is
374
+ * normal and reads as empty; a FILE that is not there is not — a request
375
+ * must not conjure the file it asks about.
376
+ */
377
+ private async readLive(target: AccessRequestTarget, wsRulesPath: string): Promise<string> {
378
+ const { workspaceService, kb } = this.deps;
379
+ await workspaceService.getOrCreateForBranch(kb.defaultBranch);
380
+ try {
381
+ return await workspaceService.readFile(kb.defaultWorkspaceId(), wsRulesPath);
382
+ } catch (err) {
383
+ if (target.kind === 'folder' && isAbsence(err)) return '';
384
+ if (isAbsence(err)) {
385
+ throw new AccessMutationError(`"${target.path}" is not there any more.`, 404, {
386
+ kind: 'unknown-target',
387
+ });
388
+ }
389
+ throw err;
390
+ }
391
+ }
392
+
393
+ /** The description an editor reads: who, what, where, the note, and how to answer. */
394
+ private describe(input: {
395
+ user: AuthUser;
396
+ target: AccessRequestTarget;
397
+ level: RequestLevel;
398
+ note: string;
399
+ }): string {
400
+ const { user, target, level, note } = input;
401
+ const who = escapeMarkdown(user.name || user.email);
402
+ const lines = [
403
+ `<!--hexis:access-request-level:${level}-->`,
404
+ `${who} (${escapeMarkdown(user.email)}) asked for **${LEVEL_LABEL[level]}** on ` +
405
+ `${escapeMarkdown(target.path || 'the workspace')}.`,
406
+ ];
407
+ if (note) {
408
+ lines.push('', `Note from ${who}:`, '', NOTE_OPEN);
409
+ for (const line of note.split(/\r?\n/)) lines.push(`> ${escapeMarkdown(line)}`);
410
+ lines.push(NOTE_CLOSE);
411
+ }
412
+ lines.push(
413
+ '',
414
+ `Anyone who can edit this ${target.kind}'s access answers it: Accept in the ` +
415
+ `${target.kind}'s Manage access dialog, or approve and merge this request. It closes ` +
416
+ `itself once ${who} holds that access, however it was given.`,
417
+ );
418
+ return lines.join('\n');
419
+ }
420
+ }
@@ -1042,3 +1042,25 @@ export function parseOwnAccessEntries(text: string): OwnEntries | null {
1042
1042
  }
1043
1043
  return sawVerb ? entries : null;
1044
1044
  }
1045
+
1046
+ /**
1047
+ * Whether a node file's frontmatter could be READ at all, which
1048
+ * {@link parseOwnAccessEntries} does not say: its null covers a file with no
1049
+ * frontmatter, one that names no access verb, and one whose frontmatter is
1050
+ * broken, and only the last of those is a failure to read.
1051
+ *
1052
+ * Readable: no frontmatter block at all (the file grants nothing), or a
1053
+ * block that parses to a mapping. Not readable: a block that is never
1054
+ * closed, or one that does not parse to a mapping. For a caller that must
1055
+ * not take "could not tell" for "grants nothing".
1056
+ */
1057
+ export function ownAccessReadable(text: string): boolean {
1058
+ const scan = scanFrontmatter(text);
1059
+ if (scan.kind === 'none') return true;
1060
+ if (scan.kind === 'unterminated') return false;
1061
+ const block = scan.fm.join('\n');
1062
+ // An empty block says nothing, and says it readably.
1063
+ if (!block.trim()) return true;
1064
+ const root = ownEntriesRoot(block);
1065
+ return root != null && typeof root === 'object' && !Array.isArray(root);
1066
+ }
@@ -574,6 +574,44 @@ describe('AuthService — the SSO domain allow-list', () => {
574
574
  ).rejects.toThrow(/domain is not allowed/i);
575
575
  });
576
576
 
577
+ /**
578
+ * One rule per sign-in. A provider that decided for itself who may enter
579
+ * (an invitation, a claimed domain) is not overruled by a list the admin
580
+ * set for the deployment's own provider; the plan still has its say.
581
+ */
582
+ it('is not laid on top of a provider that decided admission itself', async () => {
583
+ const { db } = makeFakeDb([[{ ...ROW, email: 'invited@gmail.com', name: 'Invited' }]]);
584
+ const out = await new AuthService(db, config).loginWithSso('invited@gmail.com', 'Invited', {
585
+ admittedByProvider: true,
586
+ });
587
+ expect(out.user.email).toBe('invited@gmail.com');
588
+ });
589
+
590
+ it('still asks the plan about someone the provider admitted', async () => {
591
+ const asked: Array<[string, string]> = [];
592
+ const plan: IAccountAdmission = {
593
+ canProvision: async (email, reason) => {
594
+ asked.push([email, reason]);
595
+ return { ok: false, message: 'No seat left on this plan' };
596
+ },
597
+ };
598
+ const { db } = makeFakeDb([[]]);
599
+ await expect(
600
+ new AuthService(db, config, plan).loginWithSso('invited@gmail.com', 'Invited', { admittedByProvider: true }),
601
+ ).rejects.toBeInstanceOf(AccountAdmissionRefusedError);
602
+ expect(asked).toEqual([['invited@gmail.com', 'sso']]);
603
+ expect(vi.mocked(db.insert)).not.toHaveBeenCalled();
604
+ });
605
+
606
+ it('governs a provider that says nothing, or says it did not decide', async () => {
607
+ for (const opts of [undefined, {}, { admittedByProvider: false }]) {
608
+ const { db } = makeFakeDb([[]]);
609
+ await expect(new AuthService(db, config).loginWithSso('someone@gmail.com', 'Someone', opts)).rejects.toThrow(
610
+ /domain is not allowed/i,
611
+ );
612
+ }
613
+ });
614
+
577
615
  it('admits a subdomain of an allowed domain', async () => {
578
616
  const { db } = makeFakeDb([[{ ...ROW, email: 'eu@eu.bevel.software', name: 'EU' }]]);
579
617
  const out = await new AuthService(db, config).loginWithSso('eu@eu.bevel.software', 'EU');
@@ -85,6 +85,24 @@ export interface AuthConfig {
85
85
  loginPasswordEnabled?: boolean;
86
86
  }
87
87
 
88
+ /** What a sign-in provider tells {@link AuthService.loginWithSso} about the sign-in it hands over. */
89
+ export interface SsoLoginOptions {
90
+ /**
91
+ * The provider has itself decided that this person may enter: they were
92
+ * invited, their address is on a domain the deployment claimed, whatever
93
+ * its rule is. The domain allow-list (`ALLOWED_EMAIL_DOMAINS`) is then
94
+ * not applied.
95
+ *
96
+ * The allow-list exists for a provider that decides nothing: it is what
97
+ * stands between "the issuer knows this person" and "this person has an
98
+ * account here". Applied on top of a provider's own decision it is a
99
+ * second rule the admin set somewhere else, and the person it refuses was
100
+ * let in by the first. Default false, so every provider that does not say
101
+ * otherwise is governed by the allow-list as before.
102
+ */
103
+ admittedByProvider?: boolean;
104
+ }
105
+
88
106
  export class AuthService {
89
107
  constructor(
90
108
  private readonly db: Database,
@@ -206,16 +224,25 @@ export class AuthService {
206
224
  * verified. Same upsert-by-email + JWT path as password login. Email is the
207
225
  * idempotency key, so a user who first used password login and later signs
208
226
  * in via SSO (same email) keeps the same account/id.
227
+ *
228
+ * WHO MAY ENTER is decided once per sign-in, by whoever is in a position
229
+ * to decide it. For the deployment's own provider that is the domain
230
+ * allow-list: the provider signs in whoever its issuer knows, and nobody
231
+ * has approved the person. A provider that HAS decided (see
232
+ * {@link SsoLoginOptions.admittedByProvider}) is governed by its own rule
233
+ * alone; the allow-list is not laid on top of it. The admission port is
234
+ * asked either way: that is the plan's answer, not a sign-in rule.
209
235
  */
210
236
  async loginWithSso(
211
237
  email: string,
212
238
  name: string,
239
+ opts: SsoLoginOptions = {},
213
240
  ): Promise<{ token: string; user: AuthUser }> {
214
241
  const normalizedEmail = canonicalEmail(email ?? '');
215
242
  if (!EMAIL_REGEX.test(normalizedEmail)) {
216
243
  throw new Error('Sign-in returned an invalid email');
217
244
  }
218
- this.assertAllowedDomain(normalizedEmail);
245
+ if (!opts.admittedByProvider) this.assertAllowedDomain(normalizedEmail);
219
246
  await this.assertAdmitted(normalizedEmail, 'sso');
220
247
  const displayName = (name ?? '').trim() || normalizedEmail.split('@')[0] || normalizedEmail;
221
248
  const user = await this.upsertUserByEmail(normalizedEmail, displayName);