@songsid/agend 2.4.0-alpha.1 → 2.4.0-alpha.2

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 (235) hide show
  1. package/README.md +1 -1
  2. package/README.zh-TW.md +1 -1
  3. package/dist/agent-whats-new.js +2 -0
  4. package/dist/agent-whats-new.js.map +1 -1
  5. package/dist/auth-api.js +3 -1
  6. package/dist/auth-api.js.map +1 -1
  7. package/dist/backend/claude-code.js +4 -0
  8. package/dist/backend/claude-code.js.map +1 -1
  9. package/dist/backend/types.d.ts +6 -0
  10. package/dist/backend/types.js.map +1 -1
  11. package/dist/backend-availability.d.ts +1 -1
  12. package/dist/backend-availability.js +28 -1
  13. package/dist/backend-availability.js.map +1 -1
  14. package/dist/browser-backend-signins.d.ts +7 -1
  15. package/dist/browser-backend-signins.js +8 -4
  16. package/dist/browser-backend-signins.js.map +1 -1
  17. package/dist/build-provenance.json +1 -1
  18. package/dist/channel/mcp-tools.js +1 -1
  19. package/dist/channel/mcp-tools.js.map +1 -1
  20. package/dist/config-validator.js +47 -7
  21. package/dist/config-validator.js.map +1 -1
  22. package/dist/daemon.d.ts +3 -0
  23. package/dist/daemon.js +4 -0
  24. package/dist/daemon.js.map +1 -1
  25. package/dist/fleet-manager.d.ts +33 -4
  26. package/dist/fleet-manager.js +143 -61
  27. package/dist/fleet-manager.js.map +1 -1
  28. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +19 -0
  29. package/dist/hub/audit/index.js +12 -5
  30. package/dist/hub/audit/index.js.map +1 -1
  31. package/dist/hub/catalog.d.ts +6 -0
  32. package/dist/hub/catalog.js +14 -4
  33. package/dist/hub/catalog.js.map +1 -1
  34. package/dist/hub/client.js +2 -0
  35. package/dist/hub/client.js.map +1 -1
  36. package/dist/hub/compose/member.d.ts +2 -0
  37. package/dist/hub/compose/member.js +11 -2
  38. package/dist/hub/compose/member.js.map +1 -1
  39. package/dist/hub/compose/server.js +2 -1
  40. package/dist/hub/compose/server.js.map +1 -1
  41. package/dist/hub/enrolment-code.d.ts +126 -0
  42. package/dist/hub/enrolment-code.js +266 -0
  43. package/dist/hub/enrolment-code.js.map +1 -0
  44. package/dist/hub/group-policy/admin-impact.js +4 -2
  45. package/dist/hub/group-policy/admin-impact.js.map +1 -1
  46. package/dist/hub/group-policy/admin-inventory.js +6 -6
  47. package/dist/hub/group-policy/admin-inventory.js.map +1 -1
  48. package/dist/hub/group-policy/authorization.d.ts +16 -2
  49. package/dist/hub/group-policy/authorization.js +69 -5
  50. package/dist/hub/group-policy/authorization.js.map +1 -1
  51. package/dist/hub/group-policy/impact-inventory.js +3 -3
  52. package/dist/hub/group-policy/impact-inventory.js.map +1 -1
  53. package/dist/hub/group-policy/resources.d.ts +40 -1
  54. package/dist/hub/group-policy/resources.js +51 -13
  55. package/dist/hub/group-policy/resources.js.map +1 -1
  56. package/dist/hub/group-policy/store.d.ts +6 -0
  57. package/dist/hub/group-policy/store.js +49 -4
  58. package/dist/hub/group-policy/store.js.map +1 -1
  59. package/dist/hub/http/compose.js +30 -6
  60. package/dist/hub/http/compose.js.map +1 -1
  61. package/dist/hub/init/text.js +2 -2
  62. package/dist/hub/init/text.js.map +1 -1
  63. package/dist/hub/init/web.d.ts +7 -0
  64. package/dist/hub/init/web.js +6 -1
  65. package/dist/hub/init/web.js.map +1 -1
  66. package/dist/hub/join/local.d.ts +27 -0
  67. package/dist/hub/join/local.js +70 -5
  68. package/dist/hub/join/local.js.map +1 -1
  69. package/dist/hub/join/receipt.d.ts +1 -0
  70. package/dist/hub/join/receipt.js +1 -1
  71. package/dist/hub/join/receipt.js.map +1 -1
  72. package/dist/hub/join/service.d.ts +92 -6
  73. package/dist/hub/join/service.js +199 -28
  74. package/dist/hub/join/service.js.map +1 -1
  75. package/dist/hub/join/store.d.ts +2 -1
  76. package/dist/hub/join/store.js +7 -7
  77. package/dist/hub/join/store.js.map +1 -1
  78. package/dist/hub/member/exposure-api.d.ts +2 -0
  79. package/dist/hub/member/exposure-api.js +3 -2
  80. package/dist/hub/member/exposure-api.js.map +1 -1
  81. package/dist/hub/member/exposures.d.ts +4 -0
  82. package/dist/hub/member/exposures.js +12 -2
  83. package/dist/hub/member/exposures.js.map +1 -1
  84. package/dist/hub/member/pairing-notices.js +8 -6
  85. package/dist/hub/member/pairing-notices.js.map +1 -1
  86. package/dist/hub/pairing-notices.d.ts +5 -2
  87. package/dist/hub/pairing-notices.js +38 -13
  88. package/dist/hub/pairing-notices.js.map +1 -1
  89. package/dist/hub/pairing.d.ts +7 -2
  90. package/dist/hub/protocol.d.ts +47 -0
  91. package/dist/hub/protocol.js +3 -1
  92. package/dist/hub/protocol.js.map +1 -1
  93. package/dist/hub/server.js +15 -1
  94. package/dist/hub/server.js.map +1 -1
  95. package/dist/hub/types.d.ts +12 -4
  96. package/dist/hub-pairing-summary.js +1 -1
  97. package/dist/hub-pairing-summary.js.map +1 -1
  98. package/dist/instance-config-impact.js +4 -0
  99. package/dist/instance-config-impact.js.map +1 -1
  100. package/dist/instance-lifecycle.js +4 -0
  101. package/dist/instance-lifecycle.js.map +1 -1
  102. package/dist/locale.js +6 -2
  103. package/dist/locale.js.map +1 -1
  104. package/dist/log-service.d.ts +62 -6
  105. package/dist/log-service.js +135 -28
  106. package/dist/log-service.js.map +1 -1
  107. package/dist/log-steps-agy-grok.d.ts +74 -0
  108. package/dist/log-steps-agy-grok.js +440 -0
  109. package/dist/log-steps-agy-grok.js.map +1 -0
  110. package/dist/log-steps.d.ts +62 -3
  111. package/dist/log-steps.js +188 -22
  112. package/dist/log-steps.js.map +1 -1
  113. package/dist/log-transcript-paths.d.ts +29 -0
  114. package/dist/log-transcript-paths.js +109 -0
  115. package/dist/log-transcript-paths.js.map +1 -0
  116. package/dist/login-controller.d.ts +17 -3
  117. package/dist/login-controller.js +57 -5
  118. package/dist/login-controller.js.map +1 -1
  119. package/dist/login-window-lock.d.ts +20 -8
  120. package/dist/login-window-lock.js +35 -16
  121. package/dist/login-window-lock.js.map +1 -1
  122. package/dist/outbound-handlers.d.ts +14 -0
  123. package/dist/outbound-handlers.js +49 -1
  124. package/dist/outbound-handlers.js.map +1 -1
  125. package/dist/profile-signins.d.ts +2 -0
  126. package/dist/profile-signins.js +1 -1
  127. package/dist/profile-signins.js.map +1 -1
  128. package/dist/settings-api.d.ts +34 -0
  129. package/dist/settings-api.js +184 -6
  130. package/dist/settings-api.js.map +1 -1
  131. package/dist/settings-change.js +38 -1
  132. package/dist/settings-change.js.map +1 -1
  133. package/dist/settings-effect.js +14 -0
  134. package/dist/settings-effect.js.map +1 -1
  135. package/dist/tool-progress.d.ts +7 -0
  136. package/dist/tool-progress.js +21 -9
  137. package/dist/tool-progress.js.map +1 -1
  138. package/dist/types.d.ts +13 -0
  139. package/dist/ui/accounts-view.js +14 -4
  140. package/dist/ui/agent-details-settings.js +2 -2
  141. package/dist/ui/agent-page-strings.js +2 -2
  142. package/dist/ui/backend-signin.js +47 -14
  143. package/dist/ui/chat-activity-groups.js +225 -0
  144. package/dist/ui/chat-activity.js +355 -0
  145. package/dist/ui/chat-popout-header.js +35 -0
  146. package/dist/ui/chat-popout-transport.js +80 -0
  147. package/dist/ui/chat-popout.js +63 -0
  148. package/dist/ui/chat-quote.js +3 -1
  149. package/dist/ui/chat-store.js +45 -4
  150. package/dist/ui/chat-workspace-gestures.js +177 -0
  151. package/dist/ui/chat-workspace-navigation.js +34 -10
  152. package/dist/ui/chat-workspace.js +96 -32
  153. package/dist/ui/host-install.js +2 -2
  154. package/dist/ui/hub-agent-copy.js +7 -7
  155. package/dist/ui/hub-chat-strings.js +3 -3
  156. package/dist/ui/hub-client.js +77 -17
  157. package/dist/ui/hub-company-join-strings.js +12 -10
  158. package/dist/ui/hub-company-join.js +52 -39
  159. package/dist/ui/hub-confirm-place.js +44 -0
  160. package/dist/ui/hub-directory-editor-strings.js +3 -3
  161. package/dist/ui/hub-directory-notice-strings.js +1 -1
  162. package/dist/ui/hub-enrolment-code-strings.js +44 -0
  163. package/dist/ui/hub-enrolment-code.js +159 -0
  164. package/dist/ui/hub-group-search.js +82 -0
  165. package/dist/ui/hub-group-strings.js +8 -8
  166. package/dist/ui/hub-join-approval.js +31 -0
  167. package/dist/ui/hub-join-code-input.js +66 -0
  168. package/dist/ui/hub-join-queue.js +62 -0
  169. package/dist/ui/hub-join-steps.js +231 -0
  170. package/dist/ui/hub-joincode-flow-strings.js +22 -0
  171. package/dist/ui/hub-owner-strings.js +9 -9
  172. package/dist/ui/hub-pairing-progress-strings.js +1 -1
  173. package/dist/ui/hub-quick-pairing.js +8 -4
  174. package/dist/ui/hub-quick-strings.js +11 -11
  175. package/dist/ui/hub-share-refused.js +17 -0
  176. package/dist/ui/hub-strings.js +61 -61
  177. package/dist/ui/hub-this-hub.js +2 -2
  178. package/dist/ui/hub-welcome.js +26 -5
  179. package/dist/ui/image-annotate.js +283 -0
  180. package/dist/ui/image-lightbox.js +26 -6
  181. package/dist/ui/log-row.js +327 -0
  182. package/dist/ui/panel-chat.js +151 -12
  183. package/dist/ui/panel-details.js +14 -6
  184. package/dist/ui/panel-hub.js +42 -13
  185. package/dist/ui/panel-log.js +9 -154
  186. package/dist/ui/panel-settings.js +48 -11
  187. package/dist/ui/search-dialog.js +1 -0
  188. package/dist/ui/settings-access-overview.js +1 -1
  189. package/dist/ui/settings-hub-browser-certificate.js +3 -3
  190. package/dist/ui/settings-hub-company-join.js +41 -30
  191. package/dist/ui/settings-hub-connection.js +8 -5
  192. package/dist/ui/settings-hub-membership.js +3 -3
  193. package/dist/ui/settings-hub-section.js +1 -1
  194. package/dist/ui/settings-hub-setup-strings.js +6 -6
  195. package/dist/ui/settings-hub-setup.js +44 -6
  196. package/dist/ui/settings-hub.js +35 -10
  197. package/dist/ui/settings-layout.js +6 -4
  198. package/dist/ui/settings-public-session-strings.js +37 -0
  199. package/dist/ui/settings-registry.js +4 -0
  200. package/dist/ui/settings-strings.js +2 -2
  201. package/dist/ui/shared/app-shell.js +16 -10
  202. package/dist/ui/shared/app.css +195 -30
  203. package/dist/ui/shared/app.js +8 -1
  204. package/dist/ui/shared/chat-render.js +11 -2
  205. package/dist/ui/shared/chat-thread.js +20 -3
  206. package/dist/ui/shared/chat-work-bar.css +7 -0
  207. package/dist/ui/shared/chat-workspace-model.js +39 -9
  208. package/dist/ui/shared/hub-owner.css +8 -0
  209. package/dist/ui/shared/identity-color.js +9 -3
  210. package/dist/ui/shared/image-annotate.css +45 -0
  211. package/dist/ui/shared/instance-nav.js +59 -22
  212. package/dist/ui/shared/pane-geometry.js +29 -0
  213. package/dist/ui/shared/signin.js +2 -2
  214. package/dist/ui/shared/tokens.css +14 -0
  215. package/dist/ui/shared/ui-menu.js +22 -7
  216. package/dist/ui/signin.html +1 -1
  217. package/dist/ui/structured-signin.js +11 -4
  218. package/dist/web-api.d.ts +1 -0
  219. package/dist/web-api.js +34 -4
  220. package/dist/web-api.js.map +1 -1
  221. package/dist/web-backend-login.d.ts +9 -3
  222. package/dist/web-backend-login.js +7 -4
  223. package/dist/web-backend-login.js.map +1 -1
  224. package/dist/web-chat-history.d.ts +11 -0
  225. package/dist/web-chat-history.js +9 -1
  226. package/dist/web-chat-history.js.map +1 -1
  227. package/dist/web-guest-access.js +2 -2
  228. package/dist/web-guest-access.js.map +1 -1
  229. package/dist/web-session.d.ts +31 -3
  230. package/dist/web-session.js +25 -4
  231. package/dist/web-session.js.map +1 -1
  232. package/dist/web-settings-patch.d.ts +8 -2
  233. package/dist/web-settings-patch.js +22 -10
  234. package/dist/web-settings-patch.js.map +1 -1
  235. package/package.json +1 -1
@@ -9,6 +9,7 @@ import type { HubGroupAuthorization } from "../group-policy/authorization.js";
9
9
  import { CompanyJoinRecords } from "./store.js";
10
10
  import { type JoinIdentity } from "./protocol.js";
11
11
  import { type CompanyInvitationClaims } from "./invitation.js";
12
+ import { HubEnrolmentCodes } from "../enrolment-code.js";
12
13
  export declare class CompanyJoinLimit extends HubProtocolError {
13
14
  constructor();
14
15
  }
@@ -16,6 +17,10 @@ export declare class CompanyJoinLimit extends HubProtocolError {
16
17
  export declare class CompanyJoinOfferPending extends HubProtocolError {
17
18
  constructor();
18
19
  }
20
+ export declare class CompanyJoinCodeRefusal extends HubProtocolError {
21
+ readonly reason: "code-scope" | "code-ended";
22
+ constructor(reason: "code-scope" | "code-ended");
23
+ }
19
24
  export interface CompanyJoinOptions {
20
25
  home: string;
21
26
  db: Database.Database;
@@ -38,6 +43,7 @@ export interface CompanyJoinOptions {
38
43
  export declare class HubCompanyJoin {
39
44
  private readonly options;
40
45
  readonly records: CompanyJoinRecords;
46
+ readonly codes: HubEnrolmentCodes;
41
47
  private readonly directoryEpoch;
42
48
  private sealer?;
43
49
  constructor(options: CompanyJoinOptions);
@@ -57,7 +63,7 @@ export declare class HubCompanyJoin {
57
63
  };
58
64
  /** Display facts from this composed Hub's own provenance/audit; retention never becomes an invented date. */
59
65
  fleetDisplay(id: string): {
60
- source: "group" | "manual" | null;
66
+ source: "code" | "group" | "manual" | null;
61
67
  createdAt: number | null;
62
68
  };
63
69
  metadata(): {
@@ -87,6 +93,85 @@ export declare class HubCompanyJoin {
87
93
  url: string;
88
94
  expiresAt: number;
89
95
  }>;
96
+ private codeAdmin;
97
+ createCode(ctx: HubRequestContext, input: unknown): Promise<{
98
+ id: string;
99
+ code: string;
100
+ expiresAt: number;
101
+ maxUses: number;
102
+ perPersonFleets: number;
103
+ scope: {
104
+ kind: "directory";
105
+ } | {
106
+ kind: "group";
107
+ realm: string;
108
+ objectId: string;
109
+ dn: string;
110
+ };
111
+ freeFleetRows: number;
112
+ }>;
113
+ listCodes(ctx: HubRequestContext): Promise<{
114
+ codes: {
115
+ id: string;
116
+ code: string | null;
117
+ state: "exhausted" | "expired" | "live" | "revoked";
118
+ createdAt: number;
119
+ expiresAt: number;
120
+ maxUses: number;
121
+ uses: number;
122
+ perPersonFleets: number;
123
+ scope: {
124
+ kind: "directory";
125
+ } | {
126
+ kind: "group";
127
+ realm: string;
128
+ objectId: string;
129
+ dn: string;
130
+ };
131
+ inFlight: number;
132
+ inFlightLabels: string[];
133
+ recent: {
134
+ label: string;
135
+ owner: {
136
+ name: string;
137
+ login: string;
138
+ };
139
+ at: number;
140
+ }[];
141
+ }[];
142
+ }>;
143
+ revokeCode(ctx: HubRequestContext, id: string): Promise<{
144
+ id: string;
145
+ code: string | null;
146
+ state: "exhausted" | "expired" | "live" | "revoked";
147
+ createdAt: number;
148
+ expiresAt: number;
149
+ maxUses: number;
150
+ uses: number;
151
+ perPersonFleets: number;
152
+ scope: {
153
+ kind: "directory";
154
+ } | {
155
+ kind: "group";
156
+ realm: string;
157
+ objectId: string;
158
+ dn: string;
159
+ };
160
+ inFlight: number;
161
+ inFlightLabels: string[];
162
+ recent: {
163
+ label: string;
164
+ owner: {
165
+ name: string;
166
+ login: string;
167
+ };
168
+ at: number;
169
+ }[];
170
+ }>;
171
+ private maintainCodes;
172
+ private codeReservations;
173
+ private codeGrant;
174
+ private source;
90
175
  private enabled;
91
176
  /** Called only inside the group-policy update's owning transaction; never reads the directory. */
92
177
  policyUpdated(policy: import("../group-policy/model.js").HubGroupPolicy): void;
@@ -111,7 +196,7 @@ export declare class HubCompanyJoin {
111
196
  returnPath: string;
112
197
  connected: boolean;
113
198
  state: "acknowledged" | "ended" | "identity-approved" | "issued" | "pending" | "revoked" | "undeliverable";
114
- reason: "authority" | "backpressure" | "cancelled" | "denied" | "disabled" | "expired" | "limit-reached" | "offer-pending" | "revoked" | null;
199
+ reason: string | null;
115
200
  issued: boolean;
116
201
  fleetId: string | null;
117
202
  generation: number | null;
@@ -129,11 +214,12 @@ export declare class HubCompanyJoin {
129
214
  }>;
130
215
  private admit;
131
216
  private end;
217
+ private endCode;
132
218
  private expire;
133
219
  private view;
134
220
  status(binding: unknown, proof: unknown, payload: unknown, purpose?: "status" | "tombstone"): {
135
221
  state: "acknowledged" | "ended" | "identity-approved" | "issued" | "pending" | "revoked" | "undeliverable";
136
- reason: "authority" | "backpressure" | "cancelled" | "denied" | "disabled" | "expired" | "limit-reached" | "offer-pending" | "revoked" | null;
222
+ reason: string | null;
137
223
  issued: boolean;
138
224
  fleetId: string | null;
139
225
  generation: number | null;
@@ -143,7 +229,7 @@ export declare class HubCompanyJoin {
143
229
  };
144
230
  cancel(binding: unknown, proof: unknown, payload: unknown): {
145
231
  state: "acknowledged" | "ended" | "identity-approved" | "issued" | "pending" | "revoked" | "undeliverable";
146
- reason: "authority" | "backpressure" | "cancelled" | "denied" | "disabled" | "expired" | "limit-reached" | "offer-pending" | "revoked" | null;
232
+ reason: string | null;
147
233
  issued: boolean;
148
234
  fleetId: string | null;
149
235
  generation: number | null;
@@ -158,7 +244,7 @@ export declare class HubCompanyJoin {
158
244
  private reveal;
159
245
  redeem(binding: unknown, proof: unknown, payload: unknown): Promise<{
160
246
  state: "acknowledged" | "ended" | "identity-approved" | "issued" | "pending" | "revoked" | "undeliverable";
161
- reason: "authority" | "backpressure" | "cancelled" | "denied" | "disabled" | "expired" | "limit-reached" | "offer-pending" | "revoked" | null;
247
+ reason: string | null;
162
248
  issued: boolean;
163
249
  fleetId: string | null;
164
250
  generation: number | null;
@@ -183,7 +269,7 @@ export declare class HubCompanyJoin {
183
269
  }>;
184
270
  acknowledge(binding: unknown, proof: unknown, payload: unknown): Promise<{
185
271
  state: "acknowledged" | "ended" | "identity-approved" | "issued" | "pending" | "revoked" | "undeliverable";
186
- reason: "authority" | "backpressure" | "cancelled" | "denied" | "disabled" | "expired" | "limit-reached" | "offer-pending" | "revoked" | null;
272
+ reason: string | null;
187
273
  issued: boolean;
188
274
  fleetId: string | null;
189
275
  generation: number | null;
@@ -2,9 +2,9 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { z } from "zod";
3
3
  import { HubProtocolError, hash, plain, uuid, person, token, validated, parseStrictJson } from "../validation.js";
4
4
  import { canonicalArguments, personKeyString, sha256 } from "../identity.js";
5
- import { HubGroupAuthorizationError } from "../group-policy/authorization.js";
5
+ import { HubCodeScopeRefusal, HubGroupAuthorizationError } from "../group-policy/authorization.js";
6
6
  import { HubGroupEnrollmentRefusal } from "../group-policy/resources.js";
7
- import { HubGroupPolicyError } from "../group-policy/store.js";
7
+ import { HubGroupPolicyError, HubGroupReadOverload } from "../group-policy/store.js";
8
8
  import { HUB_SESSION_IDLE } from "../sessions.js";
9
9
  import { readHubSessionEpoch } from "../session-epoch.js";
10
10
  import { automaticFleetSlots, enrollmentThrottled, spendEnrollmentBudget } from "../enrollment-budget.js";
@@ -12,6 +12,8 @@ import { CompanyJoinRecords, companyInvitationRecord as invitationRecord } from
12
12
  import { browserOriginProof, companyIdentityDigest, joinKeyThumbprint, joinPurpose, pkceChallenge, validateJoinBinding, verifierSchema, verifyJoinProof } from "./protocol.js";
13
13
  import { createJoinSealer } from "./receipt.js";
14
14
  import { verifyCompanyInvitation } from "./invitation.js";
15
+ import { HubEnrolmentCodes, enrolmentCreate } from "../enrolment-code.js";
16
+ import { parseStoredHubGroupResource } from "../group-policy/resources.js";
15
17
  import { revokeHubFleet } from "../fleet-revocation.js";
16
18
  export class CompanyJoinLimit extends HubProtocolError {
17
19
  constructor() { super("backpressure"); }
@@ -20,28 +22,38 @@ export class CompanyJoinLimit extends HubProtocolError {
20
22
  export class CompanyJoinOfferPending extends HubProtocolError {
21
23
  constructor() { super("conflict"); }
22
24
  }
25
+ export class CompanyJoinCodeRefusal extends HubProtocolError {
26
+ reason;
27
+ constructor(reason) {
28
+ super("denied");
29
+ this.reason = reason;
30
+ }
31
+ }
23
32
  const pushPayload = z.strictObject({ label: plain(120).refine(s => s.trim().length > 0), stateHash: hash,
24
- invitation: z.string().max(8192).nullable(), supersedes: z.strictObject({ fleetId: uuid, credential: token }).optional() });
33
+ invitation: z.string().max(8192).nullable(), code: z.string().max(16).nullable().optional(), supersedes: z.strictObject({ fleetId: uuid, credential: token }).optional() });
25
34
  const redeemPayload = z.strictObject({ verifier: verifierSchema });
26
35
  const ackPayload = redeemPayload.extend({ credentialHash: hash, profileDigest: hash, journalCommitId: uuid });
27
36
  export class HubCompanyJoin {
28
37
  options;
29
38
  records;
39
+ codes;
30
40
  directoryEpoch;
31
41
  sealer;
32
42
  constructor(options) {
33
43
  this.options = options;
34
44
  this.directoryEpoch = readHubSessionEpoch(options.db);
35
45
  this.records = new CompanyJoinRecords(options.db, () => this.now());
46
+ this.codes = new HubEnrolmentCodes({ db: options.db, home: options.home, hubId: options.identity.hubId, now: () => this.now(),
47
+ audit: (action, codeId, use) => this.audit(action, use?.requestId ?? codeId, use?.owner ?? this.options.administrator, use?.fleetId, codeId) });
36
48
  }
37
49
  now() { return this.options.now?.() ?? Date.now(); }
38
50
  check() { if (!this.options.current() || readHubSessionEpoch(this.options.db) !== this.directoryEpoch)
39
51
  throw new HubProtocolError("unavailable"); }
40
52
  atomic(work) { this.check(); return this.options.db.transaction(() => { this.check(); const result = work(); this.check(); return result; }).immediate(); }
41
- audit(action, requestId, owner, fleetId) {
53
+ audit(action, requestId, owner, fleetId, codeId) {
42
54
  const result = this.options.audit.appendInTransaction({ id: randomUUID(), sequence: 0, policyVersion: this.options.store.read().revocationVersion,
43
55
  at: this.now(), requestId, actor: owner ? { kind: "person", person: owner } : { kind: "local-host" },
44
- action, result: "completed", ...(fleetId ? { fleetId } : {}) }, this.options.db);
56
+ action, result: "completed", ...(fleetId ? { fleetId } : {}), ...(codeId ? { codeId, reasonCode: "code" } : {}) }, this.options.db);
45
57
  if (result && typeof result.then === "function") {
46
58
  void Promise.resolve(result).catch(() => { });
47
59
  throw new HubProtocolError("uncertain");
@@ -65,7 +77,7 @@ export class HubCompanyJoin {
65
77
  this.check();
66
78
  validated(uuid, id);
67
79
  const row = this.options.db.prepare("SELECT source FROM hub_group_resources WHERE resource_key=?").get(JSON.stringify(["fleet", id, 1]));
68
- const issued = this.options.db.prepare("SELECT at FROM hub_audit WHERE fleet_id=? AND action IN('pairing.claimed','company-join.group-approved','company-join.admin-approved') AND result='allowed' ORDER BY sequence LIMIT 1")
80
+ const issued = this.options.db.prepare("SELECT at FROM hub_audit WHERE fleet_id=? AND action IN('pairing.claimed','company-join.group-approved','company-join.admin-approved','company-join.code-approved') AND result='allowed' ORDER BY sequence LIMIT 1")
69
81
  .get(id);
70
82
  return { source: row?.source ?? null, createdAt: issued?.at ?? null };
71
83
  }
@@ -73,7 +85,7 @@ export class HubCompanyJoin {
73
85
  const control = this.control();
74
86
  return { v: 1, hub: this.options.identity, identityDigest: companyIdentityDigest(this.options.identity),
75
87
  certificatePem: this.options.certificatePem, ...(this.options.name ? { name: this.options.name } : {}),
76
- features: control.enabled ? ["company-join-v1", "join-supersedes-v1", "member-leave-v1"] : [] };
88
+ features: control.enabled ? ["company-join-v1", "join-supersedes-v1", "member-leave-v1", "enrolment-code-v1"] : [] };
77
89
  }
78
90
  async configure(ctx, input) {
79
91
  const body = validated(z.strictObject({ enabled: z.boolean(), expectedRevision: z.number().int().min(1) }), input);
@@ -152,6 +164,88 @@ export class HubCompanyJoin {
152
164
  });
153
165
  return { invitation, url: this.options.identity.webOrigin + "/join-info#invite=" + invitation, expiresAt: claims.expiresAt };
154
166
  }
167
+ async codeAdmin(ctx, creating = false) {
168
+ this.check();
169
+ if (creating)
170
+ this.enabled();
171
+ const actor = await ctx.requireAdmin();
172
+ if (actor.kind !== "directory" || personKeyString(actor.person) !== personKeyString(this.options.administrator) || ctx.isCurrent?.() !== true)
173
+ throw new HubProtocolError("denied");
174
+ return Object.freeze({ ...actor, person: Object.freeze({ ...actor.person }) });
175
+ }
176
+ async createCode(ctx, input) {
177
+ const actor = await this.codeAdmin(ctx, true), body = validated(enrolmentCreate, input), revision = this.control().revision;
178
+ const scopeProof = await this.options.groups.validateCodeScope(body.scope, { requestId: ctx.requestId, current: () => ctx.isCurrent?.() === true });
179
+ const again = await this.codeAdmin(ctx, true);
180
+ if (again.sessionId !== actor.sessionId || personKeyString(again.person) !== personKeyString(actor.person))
181
+ throw new HubProtocolError("denied");
182
+ return this.atomic(() => {
183
+ scopeProof.assertCurrent();
184
+ if (ctx.isCurrent?.() !== true || !this.control().enabled || this.control().revision !== revision)
185
+ throw new HubProtocolError("revoked");
186
+ const result = { ...this.codes.create(actor.person, body), freeFleetRows: Math.max(0, 256 - this.options.store.read().fleets.length) };
187
+ scopeProof.assertCurrent();
188
+ if (ctx.isCurrent?.() !== true || !this.control().enabled || this.control().revision !== revision)
189
+ throw new HubProtocolError("revoked");
190
+ return result;
191
+ });
192
+ }
193
+ async listCodes(ctx) {
194
+ await this.codeAdmin(ctx);
195
+ return this.atomic(() => {
196
+ if (ctx.isCurrent?.() !== true)
197
+ throw new HubProtocolError("revoked");
198
+ this.maintainCodes();
199
+ const codes = this.codes.list().map(code => {
200
+ // Display all unissued joins, including people who have not signed in yet. Quota reservations stay separate.
201
+ const inFlight = this.options.db.prepare("SELECT id FROM hub_company_join_requests WHERE json_extract(body,'$.enrolmentCodeId')=? AND stage IN('pending','identity-approved') AND outer_deadline>?")
202
+ .all(code.id, this.now()).map(row => this.records.get(row.id)).filter(r => !r.issuedHash);
203
+ return { ...code, inFlight: inFlight.length, inFlightLabels: inFlight.slice(0, 3).map(r => r.label),
204
+ recent: this.options.db.prepare("SELECT u.fleet_id,u.owner,u.at FROM hub_enrolment_code_uses u WHERE code_id=? ORDER BY at DESC,rowid DESC LIMIT 50").all(code.id).map(use => {
205
+ const person = this.options.db.prepare("SELECT display_name,login_label FROM hub_people WHERE person=?").get(use.owner);
206
+ const fleet = this.options.store.read().fleets.find(f => f.id === use.fleet_id);
207
+ return { label: fleet?.label ?? "", owner: { name: person?.display_name ?? "", login: person?.login_label ?? "" }, at: use.at };
208
+ }) };
209
+ });
210
+ if (ctx.isCurrent?.() !== true)
211
+ throw new HubProtocolError("revoked");
212
+ return { codes };
213
+ });
214
+ }
215
+ async revokeCode(ctx, id) {
216
+ const actor = await this.codeAdmin(ctx);
217
+ this.atomic(() => {
218
+ if (ctx.isCurrent?.() !== true)
219
+ throw new HubProtocolError("revoked");
220
+ this.codes.revoke(id, actor.person);
221
+ const rows = this.options.db.prepare("SELECT id FROM hub_company_join_requests WHERE json_extract(body,'$.enrolmentCodeId')=? AND stage IN('pending','identity-approved')").all(id);
222
+ for (const row of rows)
223
+ this.endCode(this.records.get(row.id));
224
+ if (ctx.isCurrent?.() !== true)
225
+ throw new HubProtocolError("revoked");
226
+ });
227
+ return (await this.listCodes(ctx)).codes.find(code => code.id === id);
228
+ }
229
+ maintainCodes() {
230
+ this.atomic(() => {
231
+ this.codes.maintain();
232
+ const rows = this.options.db.prepare("SELECT id FROM hub_company_join_requests WHERE stage IN('pending','identity-approved') AND json_extract(body,'$.enrolmentCodeId') IS NOT NULL").all();
233
+ for (const { id } of rows) {
234
+ const r = this.records.get(id);
235
+ const row = this.options.db.prepare("SELECT id FROM hub_enrolment_codes WHERE id=?").get(r.enrolmentCodeId);
236
+ if (r.outerDeadline <= this.now() || r.stage === "identity-approved" && (r.redeemDeadline === null || r.redeemDeadline <= this.now()))
237
+ this.end(r, "expired");
238
+ else if (!row || this.codes.state(this.codes.get(r.enrolmentCodeId)) !== "live")
239
+ this.endCode(r);
240
+ }
241
+ });
242
+ }
243
+ codeReservations(id, except) {
244
+ return this.options.db.prepare("SELECT count(*) n FROM hub_company_join_requests r WHERE json_extract(body,'$.enrolmentCodeId')=? AND stage='identity-approved' AND outer_deadline>? AND json_extract(body,'$.redeemDeadline')>? AND id<>? AND NOT EXISTS(SELECT 1 FROM hub_enrolment_code_uses u WHERE u.request_id=r.id)")
245
+ .get(id, this.now(), this.now(), except ?? "").n;
246
+ }
247
+ codeGrant(c) { return { codeId: c.id, approvedBy: c.createdBy, scope: c.scope, perPersonFleets: c.perPersonFleets }; }
248
+ source(r) { return r.enrolmentCodeId ? "code" : r.invitationId ? "manual" : "group"; }
155
249
  enabled() { if (!this.control().enabled)
156
250
  throw new HubProtocolError("denied"); }
157
251
  /** Called only inside the group-policy update's owning transaction; never reads the directory. */
@@ -162,7 +256,7 @@ export class HubCompanyJoin {
162
256
  const rows = this.options.db.prepare("SELECT id FROM hub_company_join_requests WHERE stage IN('identity-approved','issued')").all();
163
257
  for (const { id } of rows) {
164
258
  const r = this.records.get(id);
165
- if (r.owner && (denied.has(personKeyString(r.owner)) || !r.invitationId && policy.state !== "enabled")) {
259
+ if (r.owner && (denied.has(personKeyString(r.owner)) || !r.invitationId && !r.enrolmentCodeId && policy.state !== "enabled")) {
166
260
  this.end(r, "authority");
167
261
  this.audit("company-join.policy-cancelled", id, r.owner);
168
262
  }
@@ -203,7 +297,25 @@ export class HubCompanyJoin {
203
297
  push(binding, input, proof) {
204
298
  this.enabled();
205
299
  const b = this.bound(binding), p = validated(pushPayload, input);
300
+ if (p.code != null && p.invitation !== null)
301
+ throw new HubProtocolError("invalid");
206
302
  this.consume(b, "push", proof, p);
303
+ let code = null;
304
+ if (p.code != null) {
305
+ const now = this.now();
306
+ if (enrollmentThrottled(this.options.store.read(), "code:invalid", 11, now))
307
+ throw new HubProtocolError("denied");
308
+ this.maintainCodes();
309
+ try {
310
+ code = this.codes.lookup(p.code);
311
+ }
312
+ catch (error) {
313
+ if (!(error instanceof HubProtocolError) || error.code !== "denied")
314
+ throw new HubProtocolError("unavailable");
315
+ this.atomic(() => this.options.store.mutate({ at: now, requestId: b.requestId, actor: { kind: "member", fleetId: b.fleetId }, action: "enrolment-code.refused", result: "denied" }, state => { spendEnrollmentBudget(state, "code:invalid", 11, now); }));
316
+ throw new HubProtocolError("denied");
317
+ }
318
+ }
207
319
  const invite = p.invitation ? verifyCompanyInvitation(p.invitation, this.now()) : null;
208
320
  if (invite && (companyIdentityDigest(invite.hub) !== companyIdentityDigest(b.hub)
209
321
  || personKeyString(invite.approvedBy) !== personKeyString(this.options.administrator)))
@@ -212,8 +324,10 @@ export class HubCompanyJoin {
212
324
  const record = { v: 1, binding: b, version: 1, label: p.label, stateHash: p.stateHash, stage: "pending", createdAt: now,
213
325
  outerDeadline, retainUntil: Math.max(outerDeadline, now + this.options.eventDays * 86_400_000), browserHash: null, browserOrigin: null,
214
326
  owner: null, sessionId: null, approvedAt: null, redeemDeadline: null, deliveryDeadline: null, issuedHash: null,
215
- reason: null, delivery: null, receipt: null, invitationId: invite?.id ?? null, approvedBy: invite?.approvedBy ?? null, supersedesFleetId: null };
327
+ reason: null, delivery: null, receipt: null, invitationId: invite?.id ?? null, approvedBy: code?.createdBy ?? invite?.approvedBy ?? null, supersedesFleetId: null, enrolmentCodeId: code?.id ?? null };
216
328
  this.atomic(() => {
329
+ if (code)
330
+ this.codes.live(code.id);
217
331
  if (p.supersedes) {
218
332
  const old = this.options.store.read().fleets.find(f => f.id === p.supersedes.fleetId);
219
333
  if (old?.status === "active" && old.credentialHash === sha256(p.supersedes.credential)
@@ -281,6 +395,10 @@ export class HubCompanyJoin {
281
395
  return this.options.current() && this.control().enabled && this.records.current(r) && this.session(r) && this.now() < r.outerDeadline;
282
396
  }
283
397
  groupError(error) {
398
+ if (error instanceof HubGroupReadOverload)
399
+ throw new HubProtocolError("backpressure");
400
+ if (error instanceof HubCodeScopeRefusal)
401
+ throw new CompanyJoinCodeRefusal("code-scope");
284
402
  if (error instanceof HubGroupAuthorizationError && error.reason === "denied"
285
403
  || error instanceof HubGroupEnrollmentRefusal && error.outcome === "denied")
286
404
  throw new HubProtocolError("denied");
@@ -297,9 +415,23 @@ export class HubCompanyJoin {
297
415
  }
298
416
  async approve(ctx, cookie, requestId) {
299
417
  this.enabled();
300
- const r = this.browser(cookie, requestId), actor = await ctx.current();
301
- if (actor.kind !== "directory" || ctx.isCurrent?.() !== true || !this.records.current(r) || r.stage !== "pending")
418
+ let r = this.browser(cookie, requestId);
419
+ const actor = await ctx.current();
420
+ if (actor.kind !== "directory" || ctx.isCurrent?.() !== true || !this.records.current(r))
421
+ throw new HubProtocolError("conflict");
422
+ if (r.stage !== "pending") {
423
+ // An authenticated browser may have been open before normal revocation/expiry retired its unissued request.
424
+ // This is feedback only: issued results and unrelated retirement keep the ordinary conflict/recovery path.
425
+ if (r.enrolmentCodeId && !r.issuedHash && r.stage === "ended" && this.codes.state(this.codes.get(r.enrolmentCodeId)) !== "live")
426
+ throw new CompanyJoinCodeRefusal("code-ended");
302
427
  throw new HubProtocolError("conflict");
428
+ }
429
+ if (r.enrolmentCodeId) {
430
+ this.maintainCodes();
431
+ r = this.browser(cookie, requestId);
432
+ if (r.stage !== "pending")
433
+ throw new CompanyJoinCodeRefusal("code-ended");
434
+ }
303
435
  try {
304
436
  return await this.admit(ctx, r, actor);
305
437
  }
@@ -320,44 +452,51 @@ export class HubCompanyJoin {
320
452
  }
321
453
  }
322
454
  async admit(ctx, r, actor) {
455
+ this.maintainCodes();
323
456
  const owner = validated(person, actor.person), key = personKeyString(owner), now = this.now(), invitation = this.invitation(r);
324
457
  if (invitation && personKeyString(invitation.claims.owner) !== key)
325
458
  throw new HubProtocolError("denied");
326
459
  let expected = r;
327
460
  const live = () => ctx.isCurrent?.() === true && this.options.current() && this.control().enabled && this.records.current(expected) && this.now() < r.outerDeadline;
328
- const initial = this.options.store.read();
329
- if (enrollmentThrottled(initial, `quick:${key}`, 5, now) || enrollmentThrottled(initial, "quick:all", 48, now))
461
+ const initial = this.options.store.read(), code = r.enrolmentCodeId ? this.codes.live(r.enrolmentCodeId) : null;
462
+ const buckets = code ? [[`code:${code.id}`, 120], ["code:all", 120]] : [["quick:all", 48]];
463
+ if (enrollmentThrottled(initial, `quick:${key}`, 5, now) || buckets.some(([key, max]) => enrollmentThrottled(initial, key, max, now)))
330
464
  throw new HubProtocolError("backpressure");
331
465
  this.atomic(() => this.options.store.mutate({ at: now, requestId: ctx.requestId, actor: { kind: "person", person: owner }, action: "company-join.admission", result: "allowed" }, state => {
332
466
  if (!live())
333
467
  throw new HubProtocolError("revoked");
334
- if (!spendEnrollmentBudget(state, `quick:${key}`, 5, now) || !spendEnrollmentBudget(state, "quick:all", 48, now))
468
+ if (!spendEnrollmentBudget(state, `quick:${key}`, 5, now) || buckets.some(([key, max]) => !spendEnrollmentBudget(state, key, max, now)))
335
469
  throw new HubProtocolError("backpressure");
336
470
  }));
337
471
  let permit, eligibility;
338
472
  try {
339
473
  const resource = { kind: "fleet", id: r.binding.fleetId, revision: 1, owner }, context = { requestId: ctx.requestId, current: live };
340
474
  eligibility = await this.options.groups.prepareOwnerEligibility(owner, context);
341
- permit = invitation ? await this.options.groups.prepareManualEnrollment(resource, invitation.claims.approvedBy, context) : await this.options.groups.prepareEnrollment(resource, context);
475
+ permit = code ? await this.options.groups.prepareCodeEnrollment(resource, this.codeGrant(code), context) : invitation ? await this.options.groups.prepareManualEnrollment(resource, invitation.claims.approvedBy, context) : await this.options.groups.prepareEnrollment(resource, context);
342
476
  }
343
477
  catch (error) {
344
478
  if (!live())
345
479
  throw new HubProtocolError("revoked");
346
480
  return this.groupError(error);
347
481
  }
348
- if (permit.source !== (r.invitationId ? "manual" : "group") || !r.invitationId && permit.maxFleets < 1)
482
+ if (permit.source !== this.source(r) || !r.invitationId && permit.maxFleets < 1)
349
483
  throw new HubProtocolError("denied");
350
484
  this.atomic(() => {
351
485
  eligibility.assertCurrent();
352
486
  permit.assertCurrent();
353
487
  if (!live())
354
488
  throw new HubProtocolError("revoked");
489
+ if (code) {
490
+ const current = this.codes.assertDefinition(code);
491
+ if (current.uses + this.codeReservations(code.id, r.binding.requestId) >= current.maxUses)
492
+ throw new HubProtocolError("denied");
493
+ }
355
494
  const transport = this.options.store.read();
356
495
  const old = this.superseded(r, transport, owner);
357
496
  if (!invitation && (transport.pairings.some(p => p.expiresAt > this.now() && personKeyString(p.owner) === key && ["offered", "pending"].includes(p.state))
358
497
  || this.records.reservations(owner) > 0))
359
498
  throw new CompanyJoinOfferPending();
360
- if (!invitation && transport.pairings.filter(p => p.expiresAt > this.now()).length + this.retained() >= 48)
499
+ if (!invitation && (code ? this.records.retained(true) >= 256 : transport.pairings.filter(p => p.expiresAt > this.now()).length + this.retained() >= 48))
361
500
  throw new HubProtocolError("backpressure");
362
501
  if (!invitation && automaticFleetSlots(transport, owner, this.now(), this.records.reservations(owner)) - Number(!!old) >= permit.maxFleets)
363
502
  throw new CompanyJoinLimit();
@@ -365,7 +504,12 @@ export class HubCompanyJoin {
365
504
  expected = { ...r, owner, sessionId: actor.sessionId, approvedAt: at, redeemDeadline: Math.min(at + 60_000, r.outerDeadline),
366
505
  stage: "identity-approved", reason: null, version: r.version + 1 };
367
506
  this.records.save(expected, r.version);
368
- this.audit("company-join.identity-approved", ctx.requestId, owner);
507
+ this.audit("company-join.identity-approved", ctx.requestId, owner, undefined, r.enrolmentCodeId ?? undefined);
508
+ if (code) {
509
+ const current = this.codes.assertDefinition(code);
510
+ if (current.uses + this.codeReservations(code.id) > current.maxUses)
511
+ throw new HubProtocolError("revoked");
512
+ }
369
513
  eligibility.assertCurrent();
370
514
  permit.assertCurrent();
371
515
  if (ctx.isCurrent?.() !== true)
@@ -378,6 +522,13 @@ export class HubCompanyJoin {
378
522
  this.records.save(next, r.version);
379
523
  return next;
380
524
  }
525
+ endCode(r) {
526
+ if (!r.enrolmentCodeId || r.issuedHash || !["pending", "identity-approved"].includes(r.stage))
527
+ throw new HubProtocolError("uncertain");
528
+ // Keep the durable v3 vocabulary readable by older servers. The exact ended/unissued/code tuple projects
529
+ // this denied approval as code-ended; ordinary authority loss and already-issued recovery are untouched.
530
+ this.end(r, "denied");
531
+ }
381
532
  expire(input) {
382
533
  if (input.issuedHash && input.stage !== "revoked") {
383
534
  const fleet = this.options.store.read().fleets.find(f => f.id === input.binding.fleetId);
@@ -408,7 +559,8 @@ export class HubCompanyJoin {
408
559
  });
409
560
  }
410
561
  view(r) {
411
- return { state: r.stage, reason: r.reason, issued: r.issuedHash !== null, fleetId: r.issuedHash ? r.binding.fleetId : null,
562
+ const reason = r.stage === "ended" && r.enrolmentCodeId && !r.issuedHash && r.reason === "denied" ? "code-ended" : r.reason;
563
+ return { state: r.stage, reason, issued: r.issuedHash !== null, fleetId: r.issuedHash ? r.binding.fleetId : null,
412
564
  generation: r.issuedHash ? 1 : null, outerDeadline: r.outerDeadline, redeemDeadline: r.redeemDeadline, deliveryDeadline: r.deliveryDeadline };
413
565
  }
414
566
  status(binding, proof, payload, purpose = "status") {
@@ -439,9 +591,17 @@ export class HubCompanyJoin {
439
591
  provenance(r) {
440
592
  const resource = this.resource(r), raw = this.options.db.prepare("SELECT body,source,state,revision FROM hub_group_resources WHERE resource_key=?")
441
593
  .get(JSON.stringify(["fleet", resource.id, 1]));
442
- if (!raw || raw.state !== "active" || raw.source !== (r.invitationId ? "manual" : "group") || raw.revision < 1
443
- || canonicalArguments(parseStrictJson(raw.body)) !== canonicalArguments(resource))
594
+ if (!raw || raw.state !== "active" || raw.source !== this.source(r) || raw.revision < 1
595
+ || canonicalArguments(parseStoredHubGroupResource(parseStrictJson(raw.body), raw.source).resource) !== canonicalArguments(resource))
444
596
  throw new HubProtocolError("denied");
597
+ if (r.enrolmentCodeId) {
598
+ const code = parseStoredHubGroupResource(parseStrictJson(raw.body), raw.source).code;
599
+ if (!code || code.codeId !== r.enrolmentCodeId || !r.approvedBy || personKeyString(code.approvedBy) !== personKeyString(r.approvedBy))
600
+ throw new HubProtocolError("denied");
601
+ const use = this.options.db.prepare("SELECT code_id,fleet_id,owner FROM hub_enrolment_code_uses WHERE request_id=?").get(r.binding.requestId);
602
+ if (!use || use.code_id !== r.enrolmentCodeId || use.fleet_id !== r.binding.fleetId || use.owner !== personKeyString(r.owner))
603
+ throw new HubProtocolError("denied");
604
+ }
445
605
  const events = this.options.db.prepare("SELECT body FROM hub_group_resource_events WHERE json_extract(body,'$.resource.kind')='fleet' AND json_extract(body,'$.resource.id')=? AND json_extract(body,'$.resource.revision')=1 ORDER BY rowid LIMIT 257")
446
606
  .all(resource.id);
447
607
  if (!events.length || events.length > 256)
@@ -484,7 +644,7 @@ export class HubCompanyJoin {
484
644
  }
485
645
  return this.groupError(error);
486
646
  }
487
- if (permit.source !== (r.invitationId ? "manual" : "group"))
647
+ if (permit.source !== this.source(r))
488
648
  throw new HubProtocolError("denied");
489
649
  permit.assertCurrent();
490
650
  this.assertIssued(r);
@@ -508,6 +668,8 @@ export class HubCompanyJoin {
508
668
  this.consume(b, "redeem", proof, p);
509
669
  if (pkceChallenge(p.verifier) !== b.verifierS256)
510
670
  throw new HubProtocolError("denied");
671
+ if (this.exact(b).enrolmentCodeId)
672
+ this.maintainCodes();
511
673
  let expected = this.expire(this.exact(b));
512
674
  if (expected.stage === "issued")
513
675
  return this.reveal(expected); // SAME result, never enrollment
@@ -519,10 +681,11 @@ export class HubCompanyJoin {
519
681
  throw new HubProtocolError("revoked");
520
682
  const sealer = this.seal();
521
683
  let permit, eligibility;
684
+ const code = expected.enrolmentCodeId ? this.codes.live(expected.enrolmentCodeId) : null;
522
685
  try {
523
686
  const invitation = this.invitation(expected), context = { requestId: b.requestId, current: live };
524
687
  eligibility = await this.options.groups.prepareOwnerEligibility(owner, context);
525
- permit = invitation ? await this.options.groups.prepareManualEnrollment(this.resource(expected), invitation.claims.approvedBy, context)
688
+ permit = code ? await this.options.groups.prepareCodeEnrollment(this.resource(expected), this.codeGrant(code), context) : invitation ? await this.options.groups.prepareManualEnrollment(this.resource(expected), invitation.claims.approvedBy, context)
526
689
  : await this.options.groups.prepareEnrollment(this.resource(expected), context);
527
690
  }
528
691
  catch (error) {
@@ -530,17 +693,24 @@ export class HubCompanyJoin {
530
693
  throw new HubProtocolError("revoked");
531
694
  return this.groupError(error);
532
695
  }
533
- if (permit.source !== (expected.invitationId ? "manual" : "group") || !expected.invitationId && permit.maxFleets < 1)
696
+ if (permit.source !== this.source(expected) || !expected.invitationId && permit.maxFleets < 1)
534
697
  throw new HubProtocolError("denied");
535
698
  const credential = randomBytes(32).toString("hex"), issuedHash = sha256(credential);
536
- let replaced = false;
699
+ let replaced = false, consumedCode = null;
700
+ const finalCode = () => { if (consumedCode)
701
+ this.codes.assertConsumed(consumedCode, { requestId: b.requestId, fleetId: b.fleetId, owner }); };
537
702
  this.atomic(() => {
538
703
  eligibility.assertCurrent();
539
704
  permit.assertCurrent();
540
705
  if (!live())
541
706
  throw new HubProtocolError("revoked");
707
+ // A last-use/revoke refusal occurs before the transport's independent floor advances.
708
+ if (code) {
709
+ consumedCode = this.codes.assertDefinition(code);
710
+ this.codes.consume(consumedCode, { requestId: b.requestId, fleetId: b.fleetId, owner });
711
+ }
542
712
  this.options.store.mutate({ at: this.now(), requestId: b.requestId, actor: { kind: "person", person: owner },
543
- fleetId: b.fleetId, action: expected.invitationId ? "company-join.admin-approved" : "company-join.group-approved", result: "allowed" }, state => {
713
+ fleetId: b.fleetId, action: expected.enrolmentCodeId ? "company-join.code-approved" : expected.invitationId ? "company-join.admin-approved" : "company-join.group-approved", result: "allowed", ...(expected.enrolmentCodeId ? { codeId: expected.enrolmentCodeId, reasonCode: "code" } : {}) }, state => {
544
714
  if (!live())
545
715
  throw new HubProtocolError("revoked");
546
716
  const old = this.superseded(expected, state, owner);
@@ -560,7 +730,7 @@ export class HubCompanyJoin {
560
730
  const receipt = sealer.seal(delivery, credential);
561
731
  this.options.db.prepare("INSERT INTO hub_company_join_cipher_nonces VALUES(?,?)").run(receipt.keyId, receipt.nonce);
562
732
  this.options.notices.enqueue(this.options.db, { fleetId: b.fleetId, generation: 1, owner, label: expected.label,
563
- at: issuedAt, initiatingSessionId: expected.sessionId, source: source.source }, { ...this.options.store.read(),
733
+ at: issuedAt, initiatingSessionId: expected.sessionId, ...(source.source === "code" ? { source: "code", codeId: expected.enrolmentCodeId } : { source: source.source }) }, { ...this.options.store.read(),
564
734
  fleets: this.options.store.read().fleets.filter(f => f.id !== expected.supersedesFleetId) });
565
735
  const next = { ...expected, stage: "issued", delivery, receipt, issuedHash, deliveryDeadline, version: expected.version + 1 };
566
736
  if (expected.invitationId) {
@@ -575,6 +745,7 @@ export class HubCompanyJoin {
575
745
  eligibility.assertCurrent();
576
746
  permit.assertCurrent();
577
747
  this.assertIssued(expected);
748
+ finalCode();
578
749
  // The permit binds the previous global version. Finish it before advancing revocation, in this SAME root transaction.
579
750
  const old = this.superseded(expected, this.options.store.read(), owner);
580
751
  if (old) {
@@ -584,7 +755,7 @@ export class HubCompanyJoin {
584
755
  if (!current || current.generation !== old.generation || current.credentialHash !== old.credentialHash)
585
756
  throw new HubProtocolError("revoked");
586
757
  revokeHubFleet(state, current);
587
- }, () => { eligibility.assertCurrent(); permit.assertCurrent(); this.assertIssued(expected); });
758
+ }, () => { eligibility.assertCurrent(); permit.assertCurrent(); this.assertIssued(expected); finalCode(); });
588
759
  replaced = true;
589
760
  }
590
761
  });