@bymax-one/nest-auth 1.4.22 → 1.5.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.
@@ -5,6 +5,257 @@ import { Reflector } from '@nestjs/core';
5
5
  import { JwtService } from '@nestjs/jwt';
6
6
  import { Redis } from 'ioredis';
7
7
 
8
+ /**
9
+ * @fileoverview The `apiKeys` group of the module options: scoped service keys for machine
10
+ * callers.
11
+ *
12
+ * @layer Interface
13
+ */
14
+ /** Options for scoped service API keys. See {@link BymaxAuthModuleOptions.apiKeys}. */
15
+ interface ApiKeyOptions {
16
+ /** Enables the feature. Default: `false`. */
17
+ enabled?: boolean;
18
+ /**
19
+ * The HMAC key every digest is computed under. Held to the same strength bar as
20
+ * `jwt.secret`, and refused when it equals `jwt.secret`, `identifierKey` or a retired JWT
21
+ * secret: a key shared across purposes is one leak away from all of them.
22
+ *
23
+ * Keep it in a secrets manager, apart from the database that stores the digests.
24
+ */
25
+ pepper: string;
26
+ /**
27
+ * The closed vocabulary of scopes. `issue()` refuses any scope outside it, and the
28
+ * bootstrap scan refuses a route that declares one. Letters, digits and `: . _ -`.
29
+ */
30
+ scopes: readonly string[];
31
+ /** Header the key is read from, lowercase. Never the query string. Default: `x-api-key`. */
32
+ header?: string;
33
+ /**
34
+ * Prefix of every issued key: lowercase letters and digits, no underscore (the underscore
35
+ * separates the parts). A literal prefix lets secret scanners find leaked keys.
36
+ * Default: `bak`.
37
+ */
38
+ prefix?: string;
39
+ /**
40
+ * How often, in seconds, the last-used timestamps coalesced in memory are flushed to the
41
+ * store in one batch. With N instances a key is written up to N times per window, and a crash
42
+ * loses at most one window of `lastUsedAt`. Default: `60`. Range: 1 to 3600.
43
+ */
44
+ lastUsedFlushSeconds?: number;
45
+ /**
46
+ * What a failing audit hook does to the request it audits.
47
+ *
48
+ * - `'best-effort'`: the hook is fired without being awaited and its failure is logged. An
49
+ * audit outage never changes an answer.
50
+ * - `'required'`: the hook is awaited, and if it throws the request is DENIED. For hosts whose
51
+ * audit row is a record they must have.
52
+ *
53
+ * Default: `'best-effort'`.
54
+ */
55
+ auditMode?: 'best-effort' | 'required';
56
+ }
57
+
58
+ /**
59
+ * @fileoverview The registration switches of the controllers a deployment mounts.
60
+ *
61
+ * @layer Interface
62
+ */
63
+ /**
64
+ * Granular control over which controllers are registered.
65
+ * Allows disabling endpoints that are not needed for a specific application.
66
+ */
67
+ interface ControllerFlags {
68
+ /** Enables `AuthController` (register, login, logout, refresh, me). Default: `true` */
69
+ auth?: boolean;
70
+ /**
71
+ * Enables `MfaController`, `MfaService`, and `MfaRequiredGuard`.
72
+ *
73
+ * **Opt-in** — must be set to `true` explicitly **on the `registerAsync()` call**,
74
+ * not inside `useFactory`. The factory is evaluated asynchronously after the module
75
+ * is built; this field is the synchronous activation switch.
76
+ *
77
+ * When set to `true`, the `mfa` group (`encryptionKey`, `issuer`) **must** also be
78
+ * present in the `useFactory` return value — omitting it causes a startup error.
79
+ *
80
+ * Default: `false`
81
+ */
82
+ mfa?: boolean;
83
+ /** Enables `PasswordResetController`. Default: `true` */
84
+ passwordReset?: boolean;
85
+ /**
86
+ * Enables `SessionController`. **Opt-in** — `Default: false`. Also requires
87
+ * `sessions.enabled: true`; setting one without the other is a startup error.
88
+ */
89
+ sessions?: boolean;
90
+ /**
91
+ * Enables `PlatformAuthController`. **Opt-in** — `Default: false`. Also requires
92
+ * `platform.enabled: true`; setting one without the other is a startup error.
93
+ */
94
+ platform?: boolean;
95
+ /**
96
+ * Enables `OAuthController` and `OAuthService`.
97
+ *
98
+ * **Opt-in** — requires the `oauth` group to be configured in the `useFactory` return
99
+ * value. Omitting the `oauth` group causes a startup error when this flag is `true`.
100
+ *
101
+ * Default: `false`
102
+ */
103
+ oauth?: boolean;
104
+ /**
105
+ * Enables `InvitationController`. **Opt-in** — `Default: false`. Also requires
106
+ * `invitations.enabled: true`; setting one without the other is a startup error.
107
+ */
108
+ invitations?: boolean;
109
+ /**
110
+ * Enables `EmailChangeController` and `EmailChangeService`. **Opt-in** — `Default: false`.
111
+ *
112
+ * Requires the configured `IEmailProvider` to implement
113
+ * `sendEmailChangeVerification`: the flow cannot deliver its token without it, and the
114
+ * module refuses to boot rather than mint tokens nobody receives.
115
+ */
116
+ emailChange?: boolean;
117
+ /**
118
+ * Enables `WorkspaceController`: the workspace routes. **Opt-in** — `Default: false`.
119
+ *
120
+ * Requires `workspaces.enabled: true` and both workspace repository providers in
121
+ * `extraProviders`; the module refuses to boot without them.
122
+ */
123
+ workspaces?: boolean;
124
+ /**
125
+ * Enables `WorkspaceInvitationController`: invite, list, resend, revoke and preview.
126
+ * **Opt-in** — `Default: false`.
127
+ *
128
+ * Requires `workspaces.enabled: true`, both workspace repository providers, and an email
129
+ * provider that implements `sendWorkspaceInvitation`; the module refuses to boot without them.
130
+ */
131
+ workspaceInvitations?: boolean;
132
+ }
133
+
134
+ /**
135
+ * @fileoverview The `oauth` group of the module options: provider configuration and the redirects
136
+ * that follow a callback.
137
+ *
138
+ * @layer Interface
139
+ */
140
+ /** Options for OAuth sign-in. See {@link BymaxAuthModuleOptions.oauth}. */
141
+ interface OAuthOptions {
142
+ /**
143
+ * URL the browser is redirected to after a successful OAuth callback.
144
+ *
145
+ * When set, the OAuth callback endpoint issues a `302` to this URL after
146
+ * delivering tokens (cookies are still set via the same response). When
147
+ * omitted, the callback returns a JSON body — appropriate for API/SPA
148
+ * consumers that XHR/fetch the callback URL, but it leaves browser users
149
+ * staring at a JSON page. Set this for any consumer where the OAuth flow
150
+ * is initiated by a full-page browser navigation.
151
+ *
152
+ * Requires `tokenDelivery: 'cookie'` or `'both'` — bearer-only delivery is
153
+ * incompatible with a redirect because the access token would be discarded
154
+ * in the redirect response body. The module throws at startup if the
155
+ * combination is misconfigured.
156
+ *
157
+ * In production (`NODE_ENV === 'production'`), the URL must use HTTPS or
158
+ * be a relative path (starts with `/`) — same posture as `callbackUrl`.
159
+ *
160
+ * @throws {Error} When the value fails validation at module initialisation.
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * successRedirectUrl: 'https://app.example.com/dashboard'
165
+ * // or, for same-origin deployments:
166
+ * successRedirectUrl: '/dashboard'
167
+ * ```
168
+ */
169
+ successRedirectUrl?: string;
170
+ /**
171
+ * URL the browser is redirected to when an OAuth callback completes for
172
+ * an MFA-enabled user — BEFORE any session tokens are issued.
173
+ *
174
+ * Resolves a critical UX gap for the OAuth + MFA combination: today, an
175
+ * MFA-enabled user who signs in via OAuth would receive session cookies
176
+ * with `mfaVerified: false`, which the global `MfaRequiredGuard` rejects
177
+ * on every subsequent request — leaving the user locked out with no
178
+ * surfaced path forward. With this option set, the lib instead plants a
179
+ * short-lived `mfa_temp_token` HttpOnly cookie (Path scoped to the MFA
180
+ * challenge endpoint, 5-minute TTL matching the underlying JWT) and
181
+ * redirects the browser to the
182
+ * configured URL where the consumer collects the TOTP/recovery code and
183
+ * POSTs to `/auth/mfa/challenge` to complete the flow.
184
+ *
185
+ * When omitted, the callback returns a JSON body
186
+ * `{ mfaRequired: true, mfaTempToken }` instead — appropriate for SPA
187
+ * consumers that drive the redirect client-side.
188
+ *
189
+ * Same security posture as `successRedirectUrl`: must be a non-empty
190
+ * string, and in production it must use HTTPS or be a same-origin path
191
+ * (`/...`). Independent of `tokenDelivery` because the MFA temp token
192
+ * always travels via the dedicated cookie/JSON channel — bearer mode is
193
+ * accepted here.
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * mfaRedirectUrl: 'https://app.example.com/auth/mfa-challenge'
198
+ * // or, for same-origin deployments:
199
+ * mfaRedirectUrl: '/auth/mfa-challenge'
200
+ * ```
201
+ */
202
+ mfaRedirectUrl?: string;
203
+ /**
204
+ * URL the browser is redirected to when an OAuth callback fails with an
205
+ * `AuthException` (e.g. invalid state, plugin error, hook rejected).
206
+ *
207
+ * Symmetric polish for `successRedirectUrl`: today, an OAuth failure
208
+ * propagates as a raw JSON 401/500 response, which leaves browser users
209
+ * looking at machine-readable output instead of a friendly error page.
210
+ * When set, the controller redirects to the configured URL and appends
211
+ * `?error=<code>` (e.g. `?error=oauth_failed`) so the destination page
212
+ * can branch on the failure reason. Existing query parameters on the URL
213
+ * are preserved (uses the `URL` constructor).
214
+ *
215
+ * Only `AuthException` errors trigger the redirect — unexpected
216
+ * exceptions (programmer errors, infrastructure failures) propagate so
217
+ * they are surfaced to monitoring instead of silently swallowed.
218
+ *
219
+ * Same security posture as `successRedirectUrl`: must be a non-empty
220
+ * string, and in production it must use HTTPS or be a same-origin path.
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * errorRedirectUrl: 'https://app.example.com/auth/error'
225
+ * // or, for same-origin deployments:
226
+ * errorRedirectUrl: '/auth/error'
227
+ * ```
228
+ */
229
+ errorRedirectUrl?: string;
230
+ /**
231
+ * Google OAuth 2.0 configuration.
232
+ * All three fields are required to enable Google login.
233
+ */
234
+ google?: {
235
+ /** Google OAuth client ID from Google Cloud Console. */
236
+ clientId: string;
237
+ /**
238
+ * Google OAuth client secret from Google Cloud Console.
239
+ * @remarks Never log this value. Treat with the same care as `jwt.secret`.
240
+ * The consuming `resolveOptions()` implementation must redact this field
241
+ * before any diagnostic logging.
242
+ */
243
+ clientSecret: string;
244
+ /** Absolute URL for the OAuth callback (must match Google Console configuration). */
245
+ callbackUrl: string;
246
+ /**
247
+ * OAuth scopes to request from Google.
248
+ * Defaults to `['openid', 'email', 'profile']` when not specified.
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * scope: ['openid', 'email', 'profile', 'https://www.googleapis.com/auth/calendar.readonly']
253
+ * ```
254
+ */
255
+ scope?: string[];
256
+ };
257
+ }
258
+
8
259
  /**
9
260
  * AuthUser type and IUserRepository interface for @bymax-one/nest-auth.
10
261
  *
@@ -428,6 +679,126 @@ interface IUserRepository {
428
679
  createWithOAuth(data: CreateWithOAuthData): Promise<AuthUser>;
429
680
  }
430
681
 
682
+ /**
683
+ * @fileoverview The marker a workspace permission list uses for "every active member".
684
+ *
685
+ * @layer Constants
686
+ */
687
+ /**
688
+ * Stands in a role list for "any active member of the workspace, whatever the role".
689
+ *
690
+ * A unique symbol rather than a string such as `'*'`, so it can never equal a role name a host
691
+ * defines, and so a role list that contains it is visibly different in the types.
692
+ */
693
+ declare const ANY_WORKSPACE_MEMBER: unique symbol;
694
+
695
+ /**
696
+ * @fileoverview The `workspaces` group of the module options, and the `registration` mode that
697
+ * pairs with it.
698
+ *
699
+ * @layer Interface
700
+ */
701
+
702
+ /**
703
+ * Who may create an account on their own.
704
+ *
705
+ * - `'open'`: anyone may register, by password or through an OAuth provider.
706
+ * - `'invitation-only'`: sign-up is closed except through a valid invitation for that exact
707
+ * address. `POST /auth/register` and the OAuth `create` action answer `403
708
+ * auth.registration_closed`, the invitation accept routes stay open, and an OAuth flow started
709
+ * with a workspace invitation may create the account it was addressed to. Existing accounts
710
+ * keep signing in. Startup refuses the mode when workspaces and tenant invitations are both
711
+ * disabled, since no account could ever be created.
712
+ */
713
+ type RegistrationMode = 'open' | 'invitation-only';
714
+ /** A role list in which `ANY_WORKSPACE_MEMBER` stands for every active member. */
715
+ type WorkspaceRoleList = ReadonlyArray<string | typeof ANY_WORKSPACE_MEMBER>;
716
+ /** Which workspace roles may perform each workspace-level action. */
717
+ interface WorkspacePermissionOptions {
718
+ /** May rename the workspace. Default: the owner role. */
719
+ manageWorkspace?: readonly string[];
720
+ /** May schedule the workspace's deletion. Default: the owner role. */
721
+ deleteWorkspace?: readonly string[];
722
+ /** May invite, remove and change the role of members. Default: the owner role. */
723
+ manageMembers?: readonly string[];
724
+ /** May list the workspace's members. Default: every active member. */
725
+ viewMembers?: WorkspaceRoleList;
726
+ }
727
+ /**
728
+ * Options for the opt-in workspace layer: one identity with a role in each of many workspaces.
729
+ *
730
+ * Workspaces live inside a tenant. The identity, its sessions and its tokens are unchanged; a
731
+ * workspace role is resolved on each request for the workspace that request names.
732
+ */
733
+ interface WorkspaceOptions {
734
+ /** Switches the feature on. Everything else here is ignored while it is `false`. */
735
+ enabled: boolean;
736
+ /**
737
+ * The workspace role hierarchy, denormalized like `roles.hierarchy`: each role lists every role
738
+ * it includes. A separate hierarchy from the account-level one, read only by the workspace
739
+ * guards.
740
+ */
741
+ roles: {
742
+ /** Role to the roles it includes. Must name the owner role. */
743
+ hierarchy: Record<string, string[]>;
744
+ /** The role that owns a workspace; it must include every other role. */
745
+ ownerRole: string;
746
+ };
747
+ /** Which roles may do what. */
748
+ permissions?: WorkspacePermissionOptions;
749
+ /**
750
+ * Whether an identity may create a workspace, as a flag or a per-user decision.
751
+ * Default: `true`.
752
+ */
753
+ allowCreate?: boolean | ((user: SafeAuthUser) => boolean | Promise<boolean>);
754
+ /**
755
+ * Most workspaces one identity may own at a time; `0` is unlimited. Default: `0`.
756
+ *
757
+ * A workspace pending deletion still counts until it is finalized or restored, so an identity at
758
+ * the limit cannot create another while one of its workspaces waits out the grace period. The
759
+ * library checks the count before creating, which is advisory under concurrency; a host that
760
+ * needs an exact cap enforces it inside the repository's create call, which receives this value.
761
+ */
762
+ maxWorkspacesPerUser?: number;
763
+ /** How long a workspace invitation stays valid, in seconds. Default: 604800 (7 days). Max: 2592000. */
764
+ invitationTtlSeconds?: number;
765
+ /** Most pending invitations one workspace may hold. Default: `100`. */
766
+ maxPendingInvitationsPerWorkspace?: number;
767
+ /**
768
+ * How long a resolved membership is cached, in seconds; `0` always reads the repository.
769
+ * Default: `60`. Max: `3600`. A host that changes memberships outside the library must call the
770
+ * invalidation methods, or set this to `0`.
771
+ */
772
+ membershipCacheTtlSeconds?: number;
773
+ /** Days a deleted workspace can be restored; `0` deletes at once. Default: `14`. */
774
+ deletionGraceDays?: number;
775
+ /**
776
+ * Bounds the `access.denied` events one account can cause, so a client probing workspace ids
777
+ * cannot flood `onWorkspaceEvent`. Per account, at most `max` events are emitted in a window of
778
+ * `windowSeconds`; the denials past that are counted, and the next event that is emitted carries
779
+ * the count as `suppressedCount`. The access decision is never affected.
780
+ *
781
+ * `max`: a positive integer up to `10000`. Default: `10`. `windowSeconds`: a positive integer up
782
+ * to `3600`. Default: `60`.
783
+ */
784
+ accessDeniedEvents?: {
785
+ max?: number;
786
+ windowSeconds?: number;
787
+ };
788
+ /**
789
+ * Reads the target workspace from a request, for hosts that do not carry it in the route.
790
+ * Return `undefined` when the request names none. Never read it from the body.
791
+ */
792
+ resolveRequestWorkspace?: (req: TenantResolverRequest) => string | undefined;
793
+ /**
794
+ * Reads the workspace a socket message names, for `WsWorkspaceGuard`. Receives the message body
795
+ * and nothing else: never the URL, a header or the handshake, so the workspace cannot come from
796
+ * where a confused deputy could be steered. Without it the guard reads `data.workspaceId`.
797
+ * A value that is not a well-formed workspace id is refused as a validation error.
798
+ */
799
+ resolveWsWorkspace?: (message: unknown) => unknown;
800
+ }
801
+
431
802
  /**
432
803
  * @fileoverview Main configuration contract for {@link BymaxAuthModule}.
433
804
  *
@@ -1097,48 +1468,7 @@ interface BymaxAuthModuleOptions {
1097
1468
  * Keys are stored only as an HMAC-SHA-256 digest under `pepper`. Changing the pepper makes
1098
1469
  * every issued key unverifiable, so it means re-issuing all of them.
1099
1470
  */
1100
- apiKeys?: {
1101
- /** Enables the feature. Default: `false`. */
1102
- enabled?: boolean;
1103
- /**
1104
- * The HMAC key every digest is computed under. Held to the same strength bar as
1105
- * `jwt.secret`, and refused when it equals `jwt.secret`, `identifierKey` or a retired JWT
1106
- * secret: a key shared across purposes is one leak away from all of them.
1107
- *
1108
- * Keep it in a secrets manager, apart from the database that stores the digests.
1109
- */
1110
- pepper: string;
1111
- /**
1112
- * The closed vocabulary of scopes. `issue()` refuses any scope outside it, and the
1113
- * bootstrap scan refuses a route that declares one. Letters, digits and `: . _ -`.
1114
- */
1115
- scopes: readonly string[];
1116
- /** Header the key is read from, lowercase. Never the query string. Default: `x-api-key`. */
1117
- header?: string;
1118
- /**
1119
- * Prefix of every issued key: lowercase letters and digits, no underscore (the underscore
1120
- * separates the parts). A literal prefix lets secret scanners find leaked keys.
1121
- * Default: `bak`.
1122
- */
1123
- prefix?: string;
1124
- /**
1125
- * How often, in seconds, the last-used timestamps coalesced in memory are flushed to the
1126
- * store in one batch. With N instances a key is written up to N times per window, and a crash
1127
- * loses at most one window of `lastUsedAt`. Default: `60`. Range: 1 to 3600.
1128
- */
1129
- lastUsedFlushSeconds?: number;
1130
- /**
1131
- * What a failing audit hook does to the request it audits.
1132
- *
1133
- * - `'best-effort'`: the hook is fired without being awaited and its failure is logged. An
1134
- * audit outage never changes an answer.
1135
- * - `'required'`: the hook is awaited, and if it throws the request is DENIED. For hosts whose
1136
- * audit row is a record they must have.
1137
- *
1138
- * Default: `'best-effort'`.
1139
- */
1140
- auditMode?: 'best-effort' | 'required';
1141
- };
1471
+ apiKeys?: ApiKeyOptions;
1142
1472
  /**
1143
1473
  * Role hierarchy configuration. **Required.**
1144
1474
  *
@@ -1186,123 +1516,18 @@ interface BymaxAuthModuleOptions {
1186
1516
  * OAuth provider configurations.
1187
1517
  * Each provider block is optional — only configured providers are registered.
1188
1518
  */
1189
- oauth?: {
1190
- /**
1191
- * URL the browser is redirected to after a successful OAuth callback.
1192
- *
1193
- * When set, the OAuth callback endpoint issues a `302` to this URL after
1194
- * delivering tokens (cookies are still set via the same response). When
1195
- * omitted, the callback returns a JSON body — appropriate for API/SPA
1196
- * consumers that XHR/fetch the callback URL, but it leaves browser users
1197
- * staring at a JSON page. Set this for any consumer where the OAuth flow
1198
- * is initiated by a full-page browser navigation.
1199
- *
1200
- * Requires `tokenDelivery: 'cookie'` or `'both'` — bearer-only delivery is
1201
- * incompatible with a redirect because the access token would be discarded
1202
- * in the redirect response body. The module throws at startup if the
1203
- * combination is misconfigured.
1204
- *
1205
- * In production (`NODE_ENV === 'production'`), the URL must use HTTPS or
1206
- * be a relative path (starts with `/`) — same posture as `callbackUrl`.
1207
- *
1208
- * @throws {Error} When the value fails validation at module initialisation.
1209
- *
1210
- * @example
1211
- * ```typescript
1212
- * successRedirectUrl: 'https://app.example.com/dashboard'
1213
- * // or, for same-origin deployments:
1214
- * successRedirectUrl: '/dashboard'
1215
- * ```
1216
- */
1217
- successRedirectUrl?: string;
1218
- /**
1219
- * URL the browser is redirected to when an OAuth callback completes for
1220
- * an MFA-enabled user — BEFORE any session tokens are issued.
1221
- *
1222
- * Resolves a critical UX gap for the OAuth + MFA combination: today, an
1223
- * MFA-enabled user who signs in via OAuth would receive session cookies
1224
- * with `mfaVerified: false`, which the global `MfaRequiredGuard` rejects
1225
- * on every subsequent request — leaving the user locked out with no
1226
- * surfaced path forward. With this option set, the lib instead plants a
1227
- * short-lived `mfa_temp_token` HttpOnly cookie (Path scoped to the MFA
1228
- * challenge endpoint, 5-minute TTL matching the underlying JWT) and
1229
- * redirects the browser to the
1230
- * configured URL where the consumer collects the TOTP/recovery code and
1231
- * POSTs to `/auth/mfa/challenge` to complete the flow.
1232
- *
1233
- * When omitted, the callback returns a JSON body
1234
- * `{ mfaRequired: true, mfaTempToken }` instead — appropriate for SPA
1235
- * consumers that drive the redirect client-side.
1236
- *
1237
- * Same security posture as `successRedirectUrl`: must be a non-empty
1238
- * string, and in production it must use HTTPS or be a same-origin path
1239
- * (`/...`). Independent of `tokenDelivery` because the MFA temp token
1240
- * always travels via the dedicated cookie/JSON channel — bearer mode is
1241
- * accepted here.
1242
- *
1243
- * @example
1244
- * ```typescript
1245
- * mfaRedirectUrl: 'https://app.example.com/auth/mfa-challenge'
1246
- * // or, for same-origin deployments:
1247
- * mfaRedirectUrl: '/auth/mfa-challenge'
1248
- * ```
1249
- */
1250
- mfaRedirectUrl?: string;
1251
- /**
1252
- * URL the browser is redirected to when an OAuth callback fails with an
1253
- * `AuthException` (e.g. invalid state, plugin error, hook rejected).
1254
- *
1255
- * Symmetric polish for `successRedirectUrl`: today, an OAuth failure
1256
- * propagates as a raw JSON 401/500 response, which leaves browser users
1257
- * looking at machine-readable output instead of a friendly error page.
1258
- * When set, the controller redirects to the configured URL and appends
1259
- * `?error=<code>` (e.g. `?error=oauth_failed`) so the destination page
1260
- * can branch on the failure reason. Existing query parameters on the URL
1261
- * are preserved (uses the `URL` constructor).
1262
- *
1263
- * Only `AuthException` errors trigger the redirect — unexpected
1264
- * exceptions (programmer errors, infrastructure failures) propagate so
1265
- * they are surfaced to monitoring instead of silently swallowed.
1266
- *
1267
- * Same security posture as `successRedirectUrl`: must be a non-empty
1268
- * string, and in production it must use HTTPS or be a same-origin path.
1269
- *
1270
- * @example
1271
- * ```typescript
1272
- * errorRedirectUrl: 'https://app.example.com/auth/error'
1273
- * // or, for same-origin deployments:
1274
- * errorRedirectUrl: '/auth/error'
1275
- * ```
1276
- */
1277
- errorRedirectUrl?: string;
1278
- /**
1279
- * Google OAuth 2.0 configuration.
1280
- * All three fields are required to enable Google login.
1281
- */
1282
- google?: {
1283
- /** Google OAuth client ID from Google Cloud Console. */
1284
- clientId: string;
1285
- /**
1286
- * Google OAuth client secret from Google Cloud Console.
1287
- * @remarks Never log this value. Treat with the same care as `jwt.secret`.
1288
- * The consuming `resolveOptions()` implementation must redact this field
1289
- * before any diagnostic logging.
1290
- */
1291
- clientSecret: string;
1292
- /** Absolute URL for the OAuth callback (must match Google Console configuration). */
1293
- callbackUrl: string;
1294
- /**
1295
- * OAuth scopes to request from Google.
1296
- * Defaults to `['openid', 'email', 'profile']` when not specified.
1297
- *
1298
- * @example
1299
- * ```typescript
1300
- * scope: ['openid', 'email', 'profile', 'https://www.googleapis.com/auth/calendar.readonly']
1301
- * ```
1302
- */
1303
- scope?: string[];
1304
- };
1305
- };
1519
+ oauth?: OAuthOptions;
1520
+ /**
1521
+ * Opt-in workspaces: one identity with a role in each of many workspaces inside a tenant. See
1522
+ * {@link WorkspaceOptions}. Enabling it also needs `BYMAX_AUTH_WORKSPACE_REPOSITORY` and
1523
+ * `BYMAX_AUTH_MEMBERSHIP_REPOSITORY` in `extraProviders`.
1524
+ */
1525
+ workspaces?: WorkspaceOptions;
1526
+ /**
1527
+ * Who may create an account on their own: `'open'` (default) or `'invitation-only'`; see
1528
+ * {@link RegistrationMode}.
1529
+ */
1530
+ registration?: RegistrationMode;
1306
1531
  /**
1307
1532
  * Route prefix applied to all endpoints registered by this module.
1308
1533
  * Default: `'auth'`
@@ -1412,57 +1637,7 @@ interface BymaxAuthModuleOptions {
1412
1637
  * Granular control over which controllers are registered.
1413
1638
  * Allows disabling endpoints that are not needed for a specific application.
1414
1639
  */
1415
- controllers?: {
1416
- /** Enables `AuthController` (register, login, logout, refresh, me). Default: `true` */
1417
- auth?: boolean;
1418
- /**
1419
- * Enables `MfaController`, `MfaService`, and `MfaRequiredGuard`.
1420
- *
1421
- * **Opt-in** — must be set to `true` explicitly **on the `registerAsync()` call**,
1422
- * not inside `useFactory`. The factory is evaluated asynchronously after the module
1423
- * is built; this field is the synchronous activation switch.
1424
- *
1425
- * When set to `true`, the `mfa` group (`encryptionKey`, `issuer`) **must** also be
1426
- * present in the `useFactory` return value — omitting it causes a startup error.
1427
- *
1428
- * Default: `false`
1429
- */
1430
- mfa?: boolean;
1431
- /** Enables `PasswordResetController`. Default: `true` */
1432
- passwordReset?: boolean;
1433
- /**
1434
- * Enables `SessionController`. **Opt-in** — `Default: false`. Also requires
1435
- * `sessions.enabled: true`; setting one without the other is a startup error.
1436
- */
1437
- sessions?: boolean;
1438
- /**
1439
- * Enables `PlatformAuthController`. **Opt-in** — `Default: false`. Also requires
1440
- * `platform.enabled: true`; setting one without the other is a startup error.
1441
- */
1442
- platform?: boolean;
1443
- /**
1444
- * Enables `OAuthController` and `OAuthService`.
1445
- *
1446
- * **Opt-in** — requires the `oauth` group to be configured in the `useFactory` return
1447
- * value. Omitting the `oauth` group causes a startup error when this flag is `true`.
1448
- *
1449
- * Default: `false`
1450
- */
1451
- oauth?: boolean;
1452
- /**
1453
- * Enables `InvitationController`. **Opt-in** — `Default: false`. Also requires
1454
- * `invitations.enabled: true`; setting one without the other is a startup error.
1455
- */
1456
- invitations?: boolean;
1457
- /**
1458
- * Enables `EmailChangeController` and `EmailChangeService`. **Opt-in** — `Default: false`.
1459
- *
1460
- * Requires the configured {@link IEmailProvider} to implement
1461
- * `sendEmailChangeVerification`: the flow cannot deliver its token without it, and the
1462
- * module refuses to boot rather than mint tokens nobody receives.
1463
- */
1464
- emailChange?: boolean;
1465
- };
1640
+ controllers?: ControllerFlags;
1466
1641
  /**
1467
1642
  * TTL in seconds for the user status Redis cache.
1468
1643
  * Status is cached per user to avoid a database query on every authenticated request.
@@ -1668,6 +1843,63 @@ declare const BYMAX_AUTH_API_KEY_REPOSITORY: unique symbol;
1668
1843
  * that expiry and revocation can be tested at the exact boundary instant.
1669
1844
  */
1670
1845
  declare const BYMAX_AUTH_API_KEY_CLOCK: unique symbol;
1846
+ /**
1847
+ * Injection token for the host's {@link IWorkspaceRepository} implementation.
1848
+ *
1849
+ * Provide it in `extraProviders` together with {@link BYMAX_AUTH_MEMBERSHIP_REPOSITORY}: the
1850
+ * workspace feature reads and writes workspaces through this port.
1851
+ */
1852
+ declare const BYMAX_AUTH_WORKSPACE_REPOSITORY: unique symbol;
1853
+ /**
1854
+ * Injection token for the host's {@link IMembershipRepository} implementation.
1855
+ *
1856
+ * Provide it in `extraProviders` together with {@link BYMAX_AUTH_WORKSPACE_REPOSITORY}: the
1857
+ * workspace feature reads and writes memberships through this port.
1858
+ */
1859
+ declare const BYMAX_AUTH_MEMBERSHIP_REPOSITORY: unique symbol;
1860
+
1861
+ /**
1862
+ * @fileoverview Resolution and startup validation of the `workspaces` option group and the
1863
+ * `registration` mode.
1864
+ *
1865
+ * @layer Config
1866
+ */
1867
+
1868
+ /** The workspace group with every default applied. Present only while the feature is enabled. */
1869
+ interface ResolvedWorkspaceOptions {
1870
+ /** Always `true`: a disabled group resolves to nothing. */
1871
+ enabled: true;
1872
+ /** The workspace role hierarchy. */
1873
+ roles: WorkspaceOptions['roles'];
1874
+ /** Which roles may perform each action. */
1875
+ permissions: {
1876
+ manageWorkspace: readonly string[];
1877
+ deleteWorkspace: readonly string[];
1878
+ manageMembers: readonly string[];
1879
+ viewMembers: WorkspaceRoleList;
1880
+ };
1881
+ /** Whether an identity may create a workspace. */
1882
+ allowCreate: NonNullable<WorkspaceOptions['allowCreate']>;
1883
+ /** Most workspaces one identity may own; `0` is unlimited. */
1884
+ maxWorkspacesPerUser: number;
1885
+ /** Seconds an invitation stays valid. */
1886
+ invitationTtlSeconds: number;
1887
+ /** Most pending invitations per workspace. */
1888
+ maxPendingInvitationsPerWorkspace: number;
1889
+ /** Seconds a resolved membership is cached; `0` disables the cache. */
1890
+ membershipCacheTtlSeconds: number;
1891
+ /** Days a deleted workspace can be restored; `0` deletes at once. */
1892
+ deletionGraceDays: number;
1893
+ /** How many `access.denied` events one account may cause per window, and how long a window is. */
1894
+ accessDeniedEvents: {
1895
+ readonly max: number;
1896
+ readonly windowSeconds: number;
1897
+ };
1898
+ /** Reads the target workspace from a request, when the host supplied one. */
1899
+ resolveRequestWorkspace?: WorkspaceOptions['resolveRequestWorkspace'];
1900
+ /** Reads the target workspace from a socket message, when the host supplied one. */
1901
+ resolveWsWorkspace?: WorkspaceOptions['resolveWsWorkspace'];
1902
+ }
1671
1903
 
1672
1904
  /**
1673
1905
  * resolveOptions — merge consumer options with defaults and validate security invariants.
@@ -1691,7 +1923,7 @@ declare const BYMAX_AUTH_API_KEY_CLOCK: unique symbol;
1691
1923
  * interface-extension compatibility check with `exactOptionalPropertyTypes`,
1692
1924
  * which rejects intersection widening of optional function properties.
1693
1925
  */
1694
- type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'apiKeys' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'environment' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
1926
+ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'apiKeys' | 'workspaces' | 'registration' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'environment' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
1695
1927
  jwt: Required<Omit<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>> & Pick<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>;
1696
1928
  password: Required<NonNullable<BymaxAuthModuleOptions['password']>>;
1697
1929
  tokenDelivery: NonNullable<BymaxAuthModuleOptions['tokenDelivery']>;
@@ -1703,6 +1935,10 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
1703
1935
  platform: Required<NonNullable<BymaxAuthModuleOptions['platform']>>;
1704
1936
  invitations: Required<NonNullable<BymaxAuthModuleOptions['invitations']>>;
1705
1937
  apiKeys: Required<NonNullable<BymaxAuthModuleOptions['apiKeys']>>;
1938
+ /** The workspace group with defaults applied; absent while the feature is off. */
1939
+ workspaces?: ResolvedWorkspaceOptions;
1940
+ /** Who may create an account on their own. */
1941
+ registration: RegistrationMode;
1706
1942
  emailChange: Required<NonNullable<BymaxAuthModuleOptions['emailChange']>>;
1707
1943
  rateLimit: {
1708
1944
  enabled: boolean;
@@ -2012,31 +2248,173 @@ declare const AUTH_THROTTLE_CONFIGS: {
2012
2248
  readonly ttl: 60000;
2013
2249
  };
2014
2250
  };
2015
- };
2016
-
2017
- /**
2018
- * Encrypts a plaintext string using AES-256-GCM.
2019
- *
2020
- * @param plaintext - The string to encrypt (UTF-8 encoded). May be empty.
2021
- * @param keyBase64 - A base64-encoded 32-byte AES-256 key.
2022
- * @returns Encoded as `base64(iv):base64(authTag):base64(ciphertext)`.
2023
- * @throws If the key does not decode to exactly 32 bytes.
2024
- */
2025
- declare function encrypt(plaintext: string, keyBase64: string): string;
2026
- /**
2027
- * Decrypts an AES-256-GCM ciphertext produced by `encrypt`.
2028
- *
2029
- * @param ciphertext - Encoded as `base64(iv):base64(authTag):base64(ciphertext)`.
2030
- * @param keyBase64 - The same base64-encoded 32-byte key used for encryption.
2031
- * @returns The original plaintext string.
2032
- * @throws If the ciphertext format is invalid, segment lengths are wrong, the
2033
- * key is incorrect, or the GCM auth tag verification fails (indicating
2034
- * tampering or corruption).
2035
- *
2036
- * @remarks
2037
- * This function may throw errors with different messages depending on the failure
2038
- * mode. Callers should catch all errors and re-throw a single opaque error to
2039
- * clients to avoid leaking information about the failure type.
2251
+ /** GET /workspaces — 30 requests per minute per IP. A workspace switcher reads it on load. */
2252
+ readonly workspaceList: {
2253
+ readonly default: {
2254
+ readonly limit: 30;
2255
+ readonly ttl: 60000;
2256
+ };
2257
+ };
2258
+ /** GET /workspaces/:workspaceId/access — 60 requests per minute per IP. SSR calls it per page. */
2259
+ readonly workspaceAccess: {
2260
+ readonly default: {
2261
+ readonly limit: 60;
2262
+ readonly ttl: 60000;
2263
+ };
2264
+ };
2265
+ /** POST /workspaces/:workspaceId/switch — 20 requests per minute per IP. */
2266
+ readonly workspaceSwitch: {
2267
+ readonly default: {
2268
+ readonly limit: 20;
2269
+ readonly ttl: 60000;
2270
+ };
2271
+ };
2272
+ /** GET /workspaces/:workspaceId/members — 30 requests per minute per IP. */
2273
+ readonly workspaceMembers: {
2274
+ readonly default: {
2275
+ readonly limit: 30;
2276
+ readonly ttl: 60000;
2277
+ };
2278
+ };
2279
+ /** POST /workspaces — 10 requests per hour per IP. Each one can create a workspace and its owner. */
2280
+ readonly workspaceCreate: {
2281
+ readonly default: {
2282
+ readonly limit: 10;
2283
+ readonly ttl: 3600000;
2284
+ };
2285
+ };
2286
+ /** PATCH /workspaces/:workspaceId — 20 requests per minute per IP. */
2287
+ readonly workspaceRename: {
2288
+ readonly default: {
2289
+ readonly limit: 20;
2290
+ readonly ttl: 60000;
2291
+ };
2292
+ };
2293
+ /**
2294
+ * POST /workspaces/:workspaceId/schedule-deletion — 5 requests per 5 minutes per IP. The route
2295
+ * checks a password, so it is limited like the other routes that do.
2296
+ */
2297
+ readonly workspaceScheduleDeletion: {
2298
+ readonly default: {
2299
+ readonly limit: 5;
2300
+ readonly ttl: 300000;
2301
+ };
2302
+ };
2303
+ /** POST /workspaces/:workspaceId/restore — 5 requests per 5 minutes per IP. */
2304
+ readonly workspaceRestore: {
2305
+ readonly default: {
2306
+ readonly limit: 5;
2307
+ readonly ttl: 300000;
2308
+ };
2309
+ };
2310
+ /** PATCH /workspaces/:workspaceId/members/:userId — 20 requests per minute per IP. */
2311
+ readonly workspaceChangeRole: {
2312
+ readonly default: {
2313
+ readonly limit: 20;
2314
+ readonly ttl: 60000;
2315
+ };
2316
+ };
2317
+ /** DELETE /workspaces/:workspaceId/members/:userId — 20 requests per minute per IP. */
2318
+ readonly workspaceRemoveMember: {
2319
+ readonly default: {
2320
+ readonly limit: 20;
2321
+ readonly ttl: 60000;
2322
+ };
2323
+ };
2324
+ /** POST /workspaces/:workspaceId/leave — 10 requests per minute per IP. */
2325
+ readonly workspaceLeave: {
2326
+ readonly default: {
2327
+ readonly limit: 10;
2328
+ readonly ttl: 60000;
2329
+ };
2330
+ };
2331
+ /**
2332
+ * POST /workspaces/:workspaceId/transfer-ownership — 3 requests per 5 minutes per IP. The route
2333
+ * checks a password, and a hand-over is rare.
2334
+ */
2335
+ readonly workspaceTransferOwnership: {
2336
+ readonly default: {
2337
+ readonly limit: 3;
2338
+ readonly ttl: 300000;
2339
+ };
2340
+ };
2341
+ /** POST /workspaces/:workspaceId/invitations — 30 requests per hour per IP. Each one mails a token. */
2342
+ readonly workspaceInvite: {
2343
+ readonly default: {
2344
+ readonly limit: 30;
2345
+ readonly ttl: 3600000;
2346
+ };
2347
+ };
2348
+ /** GET /workspaces/:workspaceId/invitations — 30 requests per minute per IP. */
2349
+ readonly workspaceInvitations: {
2350
+ readonly default: {
2351
+ readonly limit: 30;
2352
+ readonly ttl: 60000;
2353
+ };
2354
+ };
2355
+ /** POST /workspaces/:workspaceId/invitations/resend — 10 requests per 5 minutes per IP. */
2356
+ readonly workspaceInvitationResend: {
2357
+ readonly default: {
2358
+ readonly limit: 10;
2359
+ readonly ttl: 300000;
2360
+ };
2361
+ };
2362
+ /** POST /workspaces/:workspaceId/invitations/revoke — 20 requests per minute per IP. */
2363
+ readonly workspaceInvitationRevoke: {
2364
+ readonly default: {
2365
+ readonly limit: 20;
2366
+ readonly ttl: 60000;
2367
+ };
2368
+ };
2369
+ /** POST /workspaces/invitations/preview — 20 requests per minute per IP. Public, so it is metered tightly. */
2370
+ readonly workspaceInvitationPreview: {
2371
+ readonly default: {
2372
+ readonly limit: 20;
2373
+ readonly ttl: 60000;
2374
+ };
2375
+ };
2376
+ /** POST /workspaces/invitations/accept — 10 requests per minute per IP. */
2377
+ readonly workspaceInvitationAccept: {
2378
+ readonly default: {
2379
+ readonly limit: 10;
2380
+ readonly ttl: 60000;
2381
+ };
2382
+ };
2383
+ /**
2384
+ * POST /workspaces/invitations/accept-signup — 5 requests per minute per IP. Public, and each
2385
+ * request can drive a password key derivation and a breach lookup.
2386
+ */
2387
+ readonly workspaceInvitationAcceptSignup: {
2388
+ readonly default: {
2389
+ readonly limit: 5;
2390
+ readonly ttl: 60000;
2391
+ };
2392
+ };
2393
+ };
2394
+
2395
+ /**
2396
+ * Encrypts a plaintext string using AES-256-GCM.
2397
+ *
2398
+ * @param plaintext - The string to encrypt (UTF-8 encoded). May be empty.
2399
+ * @param keyBase64 - A base64-encoded 32-byte AES-256 key.
2400
+ * @returns Encoded as `base64(iv):base64(authTag):base64(ciphertext)`.
2401
+ * @throws If the key does not decode to exactly 32 bytes.
2402
+ */
2403
+ declare function encrypt(plaintext: string, keyBase64: string): string;
2404
+ /**
2405
+ * Decrypts an AES-256-GCM ciphertext produced by `encrypt`.
2406
+ *
2407
+ * @param ciphertext - Encoded as `base64(iv):base64(authTag):base64(ciphertext)`.
2408
+ * @param keyBase64 - The same base64-encoded 32-byte key used for encryption.
2409
+ * @returns The original plaintext string.
2410
+ * @throws If the ciphertext format is invalid, segment lengths are wrong, the
2411
+ * key is incorrect, or the GCM auth tag verification fails (indicating
2412
+ * tampering or corruption).
2413
+ *
2414
+ * @remarks
2415
+ * This function may throw errors with different messages depending on the failure
2416
+ * mode. Callers should catch all errors and re-throw a single opaque error to
2417
+ * clients to avoid leaking information about the failure type.
2040
2418
  */
2041
2419
  declare function decrypt(ciphertext: string, keyBase64: string): string;
2042
2420
 
@@ -2340,6 +2718,27 @@ declare const AUTH_ERROR_CODES: {
2340
2718
  readonly API_KEY_SCOPE_INSUFFICIENT: "auth.api_key_scope_insufficient";
2341
2719
  /** A key operation named an id that does not exist. Raised by revoke and rotate only. */
2342
2720
  readonly API_KEY_NOT_FOUND: "auth.api_key_not_found";
2721
+ /** The request named no target workspace. */
2722
+ readonly WORKSPACE_REQUIRED: "auth.workspace_required";
2723
+ /** The workspace does not exist, is not active, or the caller is not an active member. The three cases are indistinguishable on purpose, so the answer reveals nothing about which workspaces exist. */
2724
+ readonly WORKSPACE_NOT_FOUND: "auth.workspace_not_found";
2725
+ /** The caller is a member, but the role is below what the route requires. */
2726
+ readonly INSUFFICIENT_WORKSPACE_ROLE: "auth.insufficient_workspace_role";
2727
+ /** The change would leave the workspace with no active owner. */
2728
+ readonly LAST_OWNER: "auth.last_owner";
2729
+ /** An invitation or add named someone who already belongs to the workspace. */
2730
+ readonly ALREADY_MEMBER: "auth.already_member";
2731
+ /** The signed-in account does not match the invited address. */
2732
+ readonly INVITATION_EMAIL_MISMATCH: "auth.invitation_email_mismatch";
2733
+ /** The registration mode refused a sign-up that carried no valid invitation. */
2734
+ readonly REGISTRATION_CLOSED: "auth.registration_closed";
2735
+ /**
2736
+ * The account already owns the most workspaces `workspaces.maxWorkspacesPerUser` allows,
2737
+ * counting any that are pending deletion until they are finalized or restored.
2738
+ */
2739
+ readonly WORKSPACE_LIMIT_REACHED: "auth.workspace_limit_reached";
2740
+ /** Answered to an owner only; every other caller gets `auth.workspace_not_found`. */
2741
+ readonly WORKSPACE_PENDING_DELETION: "auth.workspace_pending_deletion";
2343
2742
  /**
2344
2743
  * An unexpected internal failure. The cause is logged and never serialized.
2345
2744
  *
@@ -2583,6 +2982,26 @@ interface SessionAlertInfo {
2583
2982
  */
2584
2983
  sessionHash: string;
2585
2984
  }
2985
+ /**
2986
+ * Data required to render and send a workspace invitation email.
2987
+ */
2988
+ interface WorkspaceInviteData {
2989
+ /** Display name of the member who sent the invitation. */
2990
+ inviterName: string;
2991
+ /** Name of the workspace the invitee is joining. */
2992
+ workspaceName: string;
2993
+ /** The role the invitation grants. */
2994
+ role: string;
2995
+ /**
2996
+ * Raw invitation token (64 hex chars). The provider builds the accept URL; only its digest is
2997
+ * stored, so a resend carries a new token.
2998
+ */
2999
+ inviteToken: string;
3000
+ /** UTC timestamp after which the invitation is no longer valid. */
3001
+ expiresAt: Date;
3002
+ /** Whether an account already exists for the address: sign-in wording versus sign-up wording. */
3003
+ accountExists: boolean;
3004
+ }
2586
3005
  /**
2587
3006
  * Data required to render and send a tenant invitation email.
2588
3007
  */
@@ -2799,6 +3218,18 @@ interface IEmailProvider {
2799
3218
  * @param locale - BCP 47 locale tag for email language (e.g. `'en'`, `'pt-BR'`).
2800
3219
  */
2801
3220
  sendInvitation(tenantId: string, email: string, inviteData: InviteData, locale?: string): Promise<void>;
3221
+ /**
3222
+ * Sends a workspace invitation to a prospective member.
3223
+ *
3224
+ * **Optional.** `controllers.workspaceInvitations` refuses to boot when it is absent, because the
3225
+ * flow would mint tokens nobody receives.
3226
+ *
3227
+ * @param tenantId - The tenant the workspace lives in, so a multi-tenant provider can route it.
3228
+ * @param email - The invitee.
3229
+ * @param data - What the message states, and the raw token the provider embeds in its accept link.
3230
+ * @param locale - BCP 47 locale tag for email language.
3231
+ */
3232
+ sendWorkspaceInvitation?(tenantId: string, email: string, data: WorkspaceInviteData, locale?: string): Promise<void>;
2802
3233
  }
2803
3234
 
2804
3235
  /**
@@ -2939,6 +3370,109 @@ interface OAuthProviderPlugin {
2939
3370
  fetchProfile(accessToken: string): Promise<OAuthProfile>;
2940
3371
  }
2941
3372
 
3373
+ /**
3374
+ * @fileoverview The audit event every workspace or membership change hands to its repository, and
3375
+ * to the `onWorkspaceEvent` hook after the change commits.
3376
+ *
3377
+ * @layer Interface
3378
+ */
3379
+ /**
3380
+ * The fields every workspace audit event carries.
3381
+ *
3382
+ * `actorUserId` is `null` for a change no signed-in user made: a scheduled purge, or the platform
3383
+ * bootstrap that creates the first workspace. It is never a placeholder id, so a consumer reading
3384
+ * the audit trail cannot mistake the system for a user.
3385
+ */
3386
+ interface WorkspaceAuditBase {
3387
+ /** The tenant the workspace lives in. */
3388
+ tenantId: string;
3389
+ /** The workspace the event is about. */
3390
+ workspaceId: string;
3391
+ /** The user who made the change, or `null` when none did. */
3392
+ actorUserId: string | null;
3393
+ /** When the change was decided, as an ISO-8601 instant. */
3394
+ at: string;
3395
+ }
3396
+ /**
3397
+ * One audited change to a workspace or one of its memberships.
3398
+ *
3399
+ * Every mutating repository method receives the event for its own change in an `audit` field and
3400
+ * must persist it in the SAME transaction as the change, so the audit row cannot be missing for a
3401
+ * change that happened or present for one that did not. After the write commits, the library fans
3402
+ * the event out to a hook; that fan-out is best-effort and can be lost if the process dies between
3403
+ * the commit and the call, which is why the persisted row is the record.
3404
+ *
3405
+ * `access.denied` and `workspace.switched` are the exceptions: neither rides on a repository write
3406
+ * that takes an `audit` field (a refused request writes nothing, and switching only remembers the
3407
+ * last workspace), so they go to the hook only.
3408
+ */
3409
+ type WorkspaceAuditEvent = (WorkspaceAuditBase & {
3410
+ type: 'workspace.created' | 'workspace.renamed' | 'workspace.deletion_scheduled' | 'workspace.restored' | 'workspace.deleted';
3411
+ }) | (WorkspaceAuditBase & {
3412
+ type: 'member.invited' | 'invitation.resent' | 'invitation.revoked';
3413
+ /** The invited address, trimmed and lowercased. */
3414
+ email: string;
3415
+ /** The role the invitation carries. */
3416
+ role: string;
3417
+ }) | (WorkspaceAuditBase & {
3418
+ type: 'invitation.accepted';
3419
+ /** The invited address, trimmed and lowercased. */
3420
+ email: string;
3421
+ /** The role the invitation carries. */
3422
+ role: string;
3423
+ /** The user the acceptance added to the workspace. */
3424
+ userId: string;
3425
+ /**
3426
+ * Set, on the hook event only, when the invitation record could not be spent as expected
3427
+ * because a revoke or a resend had already moved it. The membership exists either way.
3428
+ */
3429
+ lostConsumeRace?: true;
3430
+ }) | (WorkspaceAuditBase & {
3431
+ type: 'member.role_changed';
3432
+ /** The member whose role changed. */
3433
+ userId: string;
3434
+ /** The role before the change. */
3435
+ from: string;
3436
+ /** The role after the change. */
3437
+ to: string;
3438
+ }) | (WorkspaceAuditBase & {
3439
+ type: 'member.removed' | 'member.left' | 'workspace.switched';
3440
+ /** The member the event is about. */
3441
+ userId: string;
3442
+ }) | (WorkspaceAuditBase & {
3443
+ type: 'ownership.transferred';
3444
+ /** The owner who handed ownership over. */
3445
+ fromUserId: string;
3446
+ /** The member who took it. */
3447
+ toUserId: string;
3448
+ }) | (WorkspaceAuditBase & {
3449
+ type: 'access.denied';
3450
+ /** The account that was refused; the same value as `actorUserId`. */
3451
+ userId: string;
3452
+ /** The surface that refused: a route, a stream's verification or a socket message. */
3453
+ surface: 'http' | 'verifier' | 'ws';
3454
+ /**
3455
+ * The code the caller was answered with. The host receives the event and the caller never
3456
+ * does, so it also gets {@link reason}, which the answer deliberately does not carry.
3457
+ */
3458
+ code: 'auth.workspace_not_found' | 'auth.workspace_pending_deletion' | 'auth.insufficient_workspace_role';
3459
+ /**
3460
+ * Why the decision refused, for the host to tell two incidents apart: an account probing
3461
+ * workspaces it does not belong to (`not_member`) and a member reaching above its role
3462
+ * (`insufficient_role`). `not_member` also covers a workspace that does not exist, because
3463
+ * the resolution does not tell the two apart. `pending_deletion` is any active member of a
3464
+ * workspace pending deletion on a surface that does not admit it: the owner, and also a
3465
+ * non-owner, who is answered `auth.workspace_not_found` like a stranger, so `code` and
3466
+ * `reason` differ exactly where the caller is not told.
3467
+ */
3468
+ reason: 'not_member' | 'insufficient_role' | 'pending_deletion';
3469
+ /**
3470
+ * Denials since the last event for this account that were counted and not emitted, because
3471
+ * the account exceeded `workspaces.accessDeniedEvents.max` inside a window. Zero when none.
3472
+ */
3473
+ suppressedCount: number;
3474
+ });
3475
+
2942
3476
  /**
2943
3477
  * Authentication lifecycle hooks contract for @bymax-one/nest-auth.
2944
3478
  *
@@ -3368,6 +3902,40 @@ interface IAuthHooks {
3368
3902
  * @param context - Request metadata (IP, user agent, sanitized headers).
3369
3903
  */
3370
3904
  onApiKeyRequest?(event: ApiKeyAccessEvent, context: HookContext): Promise<void> | void;
3905
+ /**
3906
+ * Called before a workspace is created, and able to refuse it (a plan, a quota, an approval).
3907
+ *
3908
+ * Runs after `workspaces.allowCreate` and the per-user limit have passed, and before anything is
3909
+ * written. A refusal answers `403 auth.forbidden`; `reason` is returned to the caller, so keep
3910
+ * it free of anything sensitive. A hook that throws refuses the creation too.
3911
+ *
3912
+ * @param user - The identity creating the workspace.
3913
+ * @param data - What it asked for: the trimmed name.
3914
+ * @param context - Request metadata (IP, user agent, sanitized headers).
3915
+ * @returns Whether to proceed.
3916
+ */
3917
+ beforeWorkspaceCreate?(user: SafeAuthUser, data: {
3918
+ name: string;
3919
+ }, context: HookContext): Promise<BeforeWorkspaceCreateResult> | BeforeWorkspaceCreateResult;
3920
+ /**
3921
+ * Called after a workspace or membership change has committed, with the event that was handed to
3922
+ * the repository for persistence.
3923
+ *
3924
+ * Informational and best-effort: it never delays or fails the operation, and it can be lost if
3925
+ * the process dies between the commit and the call, which is why the repository's persisted audit
3926
+ * row is the record. `access.denied` and `workspace.switched` reach only this hook.
3927
+ *
3928
+ * @param event - What changed, and who did it.
3929
+ * @param context - Request metadata (IP, user agent, sanitized headers).
3930
+ */
3931
+ onWorkspaceEvent?(event: WorkspaceAuditEvent, context: HookContext): Promise<void> | void;
3932
+ }
3933
+ /** Return value of the {@link IAuthHooks.beforeWorkspaceCreate} hook. */
3934
+ interface BeforeWorkspaceCreateResult {
3935
+ /** When `false`, the workspace is not created and `reason` is returned to the caller. */
3936
+ allowed: boolean;
3937
+ /** Human-readable explanation surfaced when `allowed` is `false`; keep it non-sensitive. */
3938
+ reason?: string;
3371
3939
  }
3372
3940
  /** Why a service-key request was refused. Absent on an admitted request. */
3373
3941
  type ApiKeyDenyReason = 'missing' | 'malformed' | 'unknown' | 'wrong_secret' | 'revoked' | 'expired' | 'scope_insufficient' | 'route_undeclared' | 'store_error';
@@ -4012,79 +4580,600 @@ interface OAuthMfaChallengeResult {
4012
4580
  }
4013
4581
 
4014
4582
  /**
4015
- * No-operation email provider for development and testing environments.
4016
- *
4017
- * Implements {@link IEmailProvider} by logging each call via NestJS `Logger`
4018
- * and resolving immediately without sending any real email. Inject this
4019
- * provider via `BymaxAuthModule.forRoot({ emailProvider: NoOpEmailProvider })`
4020
- * when email delivery is not required (local development, integration tests).
4021
- *
4022
- * @remarks
4023
- * **Never use this provider in production.** Replace it with a concrete
4024
- * adapter (e.g. Resend, SendGrid, Nodemailer) that implements `IEmailProvider`.
4583
+ * @fileoverview The member whose role authorized a workspace or membership write, in the two forms
4584
+ * the services and the repositories use.
4025
4585
  *
4026
- * Logged messages include the method name and a MASKED recipient — never the full address,
4027
- * and never tokens, OTPs, or passwords.
4586
+ * @layer Interface
4587
+ */
4588
+ /**
4589
+ * The member whose role authorized a write, and the role the library read for them.
4028
4590
  *
4029
- * The mask matters because this is the DEFAULT provider: a deployment that ships without
4030
- * wiring `BYMAX_AUTH_EMAIL_PROVIDER` gets it, and it would otherwise write every user's
4031
- * address to stdout on every reset, verification, MFA notification and invitation — a PII
4032
- * disclosure to whatever collects the logs, produced by an omission rather than a decision.
4591
+ * The library decides what an actor may do from a role it read BEFORE the write. Handing it back
4592
+ * lets the repository check, in the write's own transaction, that the actor still holds it.
4033
4593
  */
4034
- declare class NoOpEmailProvider implements IEmailProvider {
4035
- private readonly logger;
4036
- /** @inheritdoc */
4037
- sendPasswordResetToken(_tenantId: string, email: string, _token: string, _locale?: string): Promise<void>;
4038
- /** @inheritdoc */
4039
- sendPasswordResetOtp(_tenantId: string, email: string, _otp: string, _locale?: string): Promise<void>;
4040
- /** @inheritdoc */
4041
- sendEmailVerificationOtp(_tenantId: string, email: string, _otp: string, _locale?: string): Promise<void>;
4042
- /** @inheritdoc */
4043
- sendMfaEnabledNotification(_tenantId: string, email: string, _locale?: string): Promise<void>;
4044
- /** @inheritdoc */
4045
- sendMfaDisabledNotification(_tenantId: string, email: string, _locale?: string): Promise<void>;
4046
- /** @inheritdoc */
4047
- sendNewSessionAlert(_tenantId: string, email: string, _sessionInfo: SessionAlertInfo, _locale?: string): Promise<void>;
4048
- /** @inheritdoc */
4049
- sendInvitation(_tenantId: string, email: string, _inviteData: InviteData, _locale?: string): Promise<void>;
4594
+ interface ActingMember {
4595
+ /** The actor, a member of the same workspace and tenant as the write. */
4596
+ userId: string;
4597
+ /** The role the library read for the actor and judged the action against. */
4598
+ expectedRole: string;
4599
+ }
4600
+ /** Who is making a change: their id, and the role they hold in the workspace. */
4601
+ interface WorkspaceActor {
4602
+ /** The actor. */
4603
+ userId: string;
4604
+ /** The role the actor holds in the workspace, as the guard resolved it. */
4605
+ role: string;
4050
4606
  }
4051
4607
 
4052
4608
  /**
4053
- * The delivery channel {@link DefaultAuthEmailProvider} sends through.
4054
- *
4055
- * Narrow by design: it names only the one call the provider makes, so the provider couples to no
4056
- * concrete mailer. Any adapter exposing this shape satisfies it.
4057
- *
4058
- * **Structural fit is not enough, and a channel that merely fits will drop the one field that
4059
- * matters.** `containsCredential` is this interface's own name for "publish none of this
4060
- * message's content". A channel that has never heard of this library reads every other field —
4061
- * `to`, `subject`, `html`, `text` — and ignores that one, because nothing tells it to look. The
4062
- * result is not a missing feature: it is a relay answering `550` with the offending body quoted,
4063
- * a reset code reaching an audit record, and a `send` call that looked correctly wired.
4064
- *
4065
- * So an implementation owes a TRANSLATION, not just a matching shape. Whatever the channel calls
4066
- * "do not publish this payload", set it from `containsCredential` on every call.
4067
- *
4068
- * `@bymax-one/nest-notification`'s `EmailService.send` is the worked example, and it is also the
4069
- * trap. It satisfies this interface structurally — its input carries these fields and more, all
4070
- * the extras optional — so it can be passed in directly and will compile. Do not. Its own switch
4071
- * is spelled `publishProviderText`, so a direct pass hands it a `containsCredential` it does not
4072
- * read while its own flag stays at the default. Wire an adapter instead:
4609
+ * @fileoverview The workspace port: the record of a workspace inside a tenant, and the writes that
4610
+ * create it, rename it and move it through its lifecycle.
4073
4611
  *
4074
- * ```ts
4075
- * const sink: AuthEmailSink = {
4076
- * send: ({ containsCredential, ...message }) =>
4077
- * mailer.send({ ...message, publishProviderText: !containsCredential })
4078
- * }
4079
- * ```
4612
+ * @layer Interface
4613
+ */
4614
+
4615
+ /**
4616
+ * Names a workspace. BOTH halves are always required: a workspace id is unique only inside its
4617
+ * tenant, so an id on its own can name a homonym in another tenant. A method that takes anything
4618
+ * less than this cannot scope the row it reads or writes.
4619
+ */
4620
+ interface WorkspaceRef {
4621
+ /** The tenant the workspace lives in. */
4622
+ tenantId: string;
4623
+ /** The workspace, unique within `tenantId`. */
4624
+ workspaceId: string;
4625
+ }
4626
+ /**
4627
+ * Where a workspace is in its life. Only `'active'` grants access: any other value reads as "not a
4628
+ * member" to every caller, so a workspace nobody can reach and one that does not exist look alike.
4080
4629
  *
4081
- * Named rather than left general because the direct pass is what a reader reaches for once they
4082
- * know the shapes line up, and this paragraph is the only thing standing between that instinct
4083
- * and a published credential. The field name is that library's to change; the obligation is not.
4630
+ * - `'pending_deletion'`: scheduled for removal; only the owner can restore it, within the grace.
4631
+ * - `'suspended'`: held by the host (a billing or abuse decision); the library never sets it.
4632
+ * - `'deleted'`: finalized. The row may remain for audit; the host purges the data.
4084
4633
  */
4085
- interface AuthEmailSink {
4086
- /**
4087
- * Delivers one rendered message.
4634
+ type WorkspaceStatus = 'active' | 'pending_deletion' | 'suspended' | 'deleted';
4635
+ /** A workspace as the port returns it. */
4636
+ interface AuthWorkspace {
4637
+ /** Unique within `tenantId`. */
4638
+ id: string;
4639
+ /** The tenant the workspace lives in. */
4640
+ tenantId: string;
4641
+ /** Display name. */
4642
+ name: string;
4643
+ /** Lifecycle state. */
4644
+ status: WorkspaceStatus;
4645
+ /** When the workspace was created. */
4646
+ createdAt: Date;
4647
+ /** When a scheduled deletion becomes final, or `null` when none is scheduled. */
4648
+ deletionScheduledAt: Date | null;
4649
+ }
4650
+ /** Input to {@link IWorkspaceRepository.createWithOwner}. */
4651
+ interface CreateWorkspaceWithOwnerParams extends WorkspaceRef {
4652
+ /** Display name. */
4653
+ name: string;
4654
+ /** The creator, who becomes a member holding `ownerRole`. */
4655
+ ownerUserId: string;
4656
+ /** The role that makes the creator the owner. */
4657
+ ownerRole: string;
4658
+ /**
4659
+ * The most workspaces the creator may own, `0` for no limit.
4660
+ *
4661
+ * The library checks it before calling, which is advisory under concurrency: two creates can pass
4662
+ * the check together. A host that needs an exact cap counts the creator's owned workspaces under
4663
+ * a lock inside this call's transaction and answers `limit_reached`; a host that ignores the
4664
+ * value keeps the advisory behaviour.
4665
+ */
4666
+ maxWorkspacesPerUser: number;
4667
+ /**
4668
+ * The `workspace.created` event, to persist in the same transaction. Its `tenantId` and
4669
+ * `workspaceId` equal the key in this same object; the library fills the event in completely.
4670
+ */
4671
+ audit: WorkspaceAuditEvent;
4672
+ }
4673
+ /** Outcome of {@link IWorkspaceRepository.createWithOwner}. */
4674
+ type CreateWorkspaceResult = {
4675
+ status: 'created';
4676
+ workspace: AuthWorkspace;
4677
+ } | {
4678
+ status: 'limit_reached';
4679
+ };
4680
+ /** Input to {@link IWorkspaceRepository.rename}. */
4681
+ interface RenameWorkspaceParams extends WorkspaceRef {
4682
+ /** The new display name. */
4683
+ name: string;
4684
+ /** The member whose role authorized the rename; see {@link IWorkspaceRepository.rename}. */
4685
+ actor: ActingMember;
4686
+ /** The `workspace.renamed` event, to persist in the same transaction. */
4687
+ audit: WorkspaceAuditEvent;
4688
+ }
4689
+ /** Outcome of {@link IWorkspaceRepository.rename}. */
4690
+ type RenameWorkspaceResult = 'ok' | 'not_found' | 'actor_changed';
4691
+ /** Input to {@link IWorkspaceRepository.updateStatus}. */
4692
+ interface UpdateWorkspaceStatusParams extends WorkspaceRef {
4693
+ /**
4694
+ * The member whose role authorized the change; see {@link IWorkspaceRepository.updateStatus}.
4695
+ * Absent for a change no member made, such as the host job that finalizes a deletion.
4696
+ */
4697
+ actor?: ActingMember;
4698
+ /** The state to move to. */
4699
+ status: WorkspaceStatus;
4700
+ /**
4701
+ * The state the caller read. The write applies only while the workspace is still in it, so a
4702
+ * restore cannot overwrite a finalize that landed first.
4703
+ */
4704
+ expectedStatus: WorkspaceStatus;
4705
+ /**
4706
+ * The scheduled-deletion instant the caller read, `null` for none. When present, the write also
4707
+ * applies only while the stored instant equals it, so a finalizer that read one schedule cannot
4708
+ * delete a workspace whose deletion was restored and scheduled again. Absent means the instant is
4709
+ * not compared.
4710
+ */
4711
+ expectedDeletionScheduledAt?: Date | null;
4712
+ /** The scheduled-deletion instant to store, or `null` to clear it. */
4713
+ deletionScheduledAt: Date | null;
4714
+ /** The event for this transition, to persist in the same transaction. */
4715
+ audit: WorkspaceAuditEvent;
4716
+ }
4717
+ /** Outcome of {@link IWorkspaceRepository.updateStatus}. */
4718
+ type UpdateWorkspaceStatusResult = 'ok' | 'not_found' | 'status_conflict' | 'actor_changed';
4719
+ /**
4720
+ * The workspace port a host implements.
4721
+ *
4722
+ * Every method carries both halves of the workspace key. Every mutating method receives the audit
4723
+ * event for its change and persists it in the same transaction; a result other than success means
4724
+ * nothing was written, the audit row included. The audit event a call receives names the same
4725
+ * tenant and workspace as the key of that call, and is stored as given.
4726
+ */
4727
+ interface IWorkspaceRepository {
4728
+ /**
4729
+ * Creates the workspace and the creator's owner membership atomically, persisting `audit` in the
4730
+ * same transaction. The library generates the workspace id and passes it in the key, so the
4731
+ * audit event is complete before the write; store it as given.
4732
+ *
4733
+ * @param params - The workspace key, name, creator, cap and audit event.
4734
+ * @returns `created` with the workspace, `active`; or `limit_reached` when the creator already
4735
+ * owns `maxWorkspacesPerUser` workspaces and the host enforces the cap here. Nothing is written
4736
+ * for `limit_reached`, the audit row included.
4737
+ */
4738
+ createWithOwner(params: CreateWorkspaceWithOwnerParams): Promise<CreateWorkspaceResult>;
4739
+ /**
4740
+ * Reads one workspace. Return a workspace in any status: the library decides access.
4741
+ *
4742
+ * @param ref - The workspace's tenant and id.
4743
+ * @returns The workspace, or `null` when none matches BOTH halves of the key.
4744
+ */
4745
+ findById(ref: WorkspaceRef): Promise<AuthWorkspace | null>;
4746
+ /**
4747
+ * Renames a workspace, persisting `audit` in the same transaction.
4748
+ *
4749
+ * The same transaction MUST check that the actor still holds `actor.expectedRole` as an active
4750
+ * member of this workspace, because the library judged the rename from a role it read before the
4751
+ * write; answer `'actor_changed'` otherwise and write nothing.
4752
+ *
4753
+ * ```sql
4754
+ * BEGIN;
4755
+ * SELECT 1 FROM memberships
4756
+ * WHERE tenant_id = $tenant AND workspace_id = $workspace AND user_id = $actor
4757
+ * AND role = $actorRole AND status = 'active'
4758
+ * FOR UPDATE; -- no row: ROLLBACK and answer 'actor_changed'
4759
+ * UPDATE workspaces SET name = $name
4760
+ * WHERE tenant_id = $tenant AND id = $workspace; -- 0 rows: ROLLBACK, answer 'not_found'
4761
+ * -- the audit insert, then COMMIT
4762
+ * ```
4763
+ *
4764
+ * A host that ignores the actor keeps the check-then-write window.
4765
+ *
4766
+ * @param params - The workspace key, the new name, the actor and the audit event.
4767
+ * @returns `'not_found'` when no such workspace exists, `'actor_changed'` as above; nothing is
4768
+ * written then.
4769
+ */
4770
+ rename(params: RenameWorkspaceParams): Promise<RenameWorkspaceResult>;
4771
+ /**
4772
+ * Moves a workspace to another status, persisting `audit` in the same transaction.
4773
+ *
4774
+ * Compare-and-set: it applies only while the stored status equals `expectedStatus`, and, when
4775
+ * `expectedDeletionScheduledAt` is given, while the stored instant equals it too (two dates are
4776
+ * equal when they are the same instant), decided in the same statement as the write.
4777
+ *
4778
+ * When `actor` is given, the same transaction MUST also check that the actor still holds
4779
+ * `actor.expectedRole` as an active member of this workspace and answer `'actor_changed'`
4780
+ * otherwise, with the same lock as {@link rename}. A change no member made carries no actor.
4781
+ *
4782
+ * @param params - The workspace key, the target and expected statuses, the deletion instant and
4783
+ * the audit event.
4784
+ * @returns `'ok'` when applied, `'not_found'` for no such workspace, `'status_conflict'` when the
4785
+ * stored status or, when compared, the stored instant differs, `'actor_changed'` as above. Nothing is written
4786
+ * for any refusal.
4787
+ */
4788
+ updateStatus(params: UpdateWorkspaceStatusParams): Promise<UpdateWorkspaceStatusResult>;
4789
+ }
4790
+
4791
+ /**
4792
+ * @fileoverview The membership port: who belongs to which workspace with which role, and the
4793
+ * writes that change it, including the owner-protecting ones the library cannot make atomic itself.
4794
+ *
4795
+ * @layer Interface
4796
+ */
4797
+
4798
+ /**
4799
+ * Names one member of a workspace. ALL THREE parts are always required: the tenant and workspace
4800
+ * halves scope the workspace, and the user id is unique only within the tenant.
4801
+ */
4802
+ interface MembershipRef extends WorkspaceRef {
4803
+ /** The member. */
4804
+ userId: string;
4805
+ }
4806
+ /** Whether a membership grants access. Only `'active'` does; any other value reads as "not a member". */
4807
+ type MembershipStatus = 'active' | 'suspended';
4808
+ /** A membership as the port returns it. */
4809
+ interface AuthMembership {
4810
+ /** The tenant of the workspace. */
4811
+ tenantId: string;
4812
+ /** The workspace the member belongs to. */
4813
+ workspaceId: string;
4814
+ /** The member. */
4815
+ userId: string;
4816
+ /** The member's role in this workspace, one of the configured hierarchy's roles. */
4817
+ role: string;
4818
+ /** Whether the membership grants access. */
4819
+ status: MembershipStatus;
4820
+ /** The user who invited the member, or `null` for a creator or a system-made membership. */
4821
+ invitedByUserId: string | null;
4822
+ /** When the membership was created. */
4823
+ createdAt: Date;
4824
+ /** When it last changed. */
4825
+ updatedAt: Date;
4826
+ }
4827
+ /** A membership with its workspace, as listed for the member. */
4828
+ interface MembershipWithWorkspace extends AuthMembership {
4829
+ /** The workspace the membership is in. */
4830
+ workspace: AuthWorkspace;
4831
+ }
4832
+ /** One page of a keyset-paginated list. */
4833
+ interface MembershipPage<T> {
4834
+ /** The rows of this page. */
4835
+ items: T[];
4836
+ /** The cursor for the next page, or `null` on the last one. */
4837
+ nextCursor: string | null;
4838
+ }
4839
+ /** Input to {@link IMembershipRepository.listForUser}. */
4840
+ interface ListMembershipsForUserParams {
4841
+ /** The tenant the member belongs to. */
4842
+ tenantId: string;
4843
+ /** The member whose memberships are listed. */
4844
+ userId: string;
4845
+ /** The `nextCursor` of the previous page, or absent for the first. */
4846
+ cursor?: string;
4847
+ /** Page size. */
4848
+ limit: number;
4849
+ }
4850
+ /** Input to {@link IMembershipRepository.listForWorkspace}. */
4851
+ interface ListMembershipsForWorkspaceParams extends WorkspaceRef {
4852
+ /** The `nextCursor` of the previous page, or absent for the first. */
4853
+ cursor?: string;
4854
+ /** Page size. */
4855
+ limit: number;
4856
+ }
4857
+ /** Input to {@link IMembershipRepository.create}. */
4858
+ interface CreateMembershipParams extends MembershipRef {
4859
+ /** The role to grant. */
4860
+ role: string;
4861
+ /** The inviter, or `null` when none. */
4862
+ invitedByUserId: string | null;
4863
+ /** The event for this change, to persist in the same transaction. */
4864
+ audit: WorkspaceAuditEvent;
4865
+ }
4866
+ /** Outcome of {@link IMembershipRepository.create}. */
4867
+ type CreateMembershipResult = 'ok' | 'already_member' | 'workspace_not_found';
4868
+ /** Input to {@link IMembershipRepository.changeRole}. */
4869
+ interface ChangeMembershipRoleParams extends MembershipRef {
4870
+ /** The role to set. */
4871
+ role: string;
4872
+ /** The role the member held when the library judged the change; the write applies only while it still does. */
4873
+ expectedRole: string;
4874
+ /** The actor whose role authorized the change; see {@link IMembershipRepository.changeRole}. */
4875
+ actor: ActingMember;
4876
+ /** The role that owns a workspace, so the last-owner rule can be decided with the write. */
4877
+ ownerRole: string;
4878
+ /** The `member.role_changed` event, to persist in the same transaction. */
4879
+ audit: WorkspaceAuditEvent;
4880
+ }
4881
+ /** Input to {@link IMembershipRepository.remove}. */
4882
+ interface RemoveMembershipParams extends MembershipRef {
4883
+ /**
4884
+ * The role the member held when the library judged the removal; the write applies only while it
4885
+ * still does. Absent when a member leaves, since nobody's role authorized it.
4886
+ */
4887
+ expectedRole?: string;
4888
+ /** The actor whose role authorized the removal; absent when a member leaves. */
4889
+ actor?: ActingMember;
4890
+ /** The role that owns a workspace, so the last-owner rule can be decided with the write. */
4891
+ ownerRole: string;
4892
+ /** The `member.removed` or `member.left` event, to persist in the same transaction. */
4893
+ audit: WorkspaceAuditEvent;
4894
+ }
4895
+ /** Input to {@link IMembershipRepository.transferOwnership}. */
4896
+ interface TransferOwnershipParams extends WorkspaceRef {
4897
+ /** The current owner handing over. */
4898
+ fromUserId: string;
4899
+ /** The member who becomes an owner; must already be an active member. */
4900
+ toUserId: string;
4901
+ /** The role that owns a workspace. */
4902
+ ownerRole: string;
4903
+ /** The role `fromUserId` takes afterwards, or `null` to keep them an owner alongside the new one. */
4904
+ demoteFromTo: string | null;
4905
+ /** The `ownership.transferred` event, to persist in the same transaction. */
4906
+ audit: WorkspaceAuditEvent;
4907
+ }
4908
+ /** Input to {@link IMembershipRepository.countOwned}. */
4909
+ interface CountOwnedParams {
4910
+ /** The tenant the member belongs to. */
4911
+ tenantId: string;
4912
+ /** The member. */
4913
+ userId: string;
4914
+ /** The role that owns a workspace. */
4915
+ ownerRole: string;
4916
+ }
4917
+ /** Input to {@link IMembershipRepository.listSoleOwned}. */
4918
+ interface ListSoleOwnedParams extends CountOwnedParams {
4919
+ /** The `nextCursor` of the previous page, or absent for the first. */
4920
+ cursor?: string;
4921
+ /** Page size. */
4922
+ limit: number;
4923
+ }
4924
+ /** Input to {@link IMembershipRepository.getLastActiveWorkspaceId}. */
4925
+ interface LastActiveWorkspaceRef {
4926
+ /** The tenant the member belongs to. */
4927
+ tenantId: string;
4928
+ /** The member. */
4929
+ userId: string;
4930
+ }
4931
+ /** Input to {@link IMembershipRepository.setLastActiveWorkspaceId}. */
4932
+ interface SetLastActiveWorkspaceParams extends LastActiveWorkspaceRef {
4933
+ /** The workspace to remember. */
4934
+ workspaceId: string;
4935
+ }
4936
+ /**
4937
+ * Outcome of a write that must keep at least one active owner.
4938
+ *
4939
+ * - `'ok'`: applied.
4940
+ * - `'not_found'`: no such membership (`transferOwnership` states what it means there).
4941
+ * - `'last_owner'`: the change would leave the workspace with no active member holding `ownerRole`.
4942
+ */
4943
+ type GuardedWriteResult = 'ok' | 'not_found' | 'last_owner';
4944
+ /**
4945
+ * Outcome of a write that an actor's role authorized: {@link GuardedWriteResult} plus
4946
+ * `'actor_changed'`, answered when the actor no longer holds the role the call was judged against.
4947
+ */
4948
+ type MemberChangeResult = GuardedWriteResult | 'actor_changed';
4949
+ /** Outcome of {@link IMembershipRepository.transferOwnership}. */
4950
+ type TransferOwnershipResult = GuardedWriteResult | 'target_not_member';
4951
+ /**
4952
+ * The membership port a host implements.
4953
+ *
4954
+ * Every method carries the full key of what it names, and every mutating one receives the audit
4955
+ * event for its change and persists it in the same transaction. A result other than `'ok'` means
4956
+ * nothing was written: no change and no audit row, so a refused write leaves no trace of an event
4957
+ * that did not happen. The audit event a call receives names the same tenant, workspace and member
4958
+ * as the key of that call, and is stored as given. Reads the library uses to decide
4959
+ * access must come from the primary or be read-your-writes: a replica that lags a removal would
4960
+ * cache the removed member as present under the new cache version.
4961
+ */
4962
+ interface IMembershipRepository {
4963
+ /**
4964
+ * Reads one membership. Return it in any status: the library decides access.
4965
+ *
4966
+ * @param ref - The workspace's tenant and id and the member.
4967
+ * @returns The membership, or `null` when none matches ALL parts of the key.
4968
+ */
4969
+ find(ref: MembershipRef): Promise<AuthMembership | null>;
4970
+ /**
4971
+ * Lists a member's memberships with their workspaces, for the workspace picker.
4972
+ *
4973
+ * Returns only ACTIVE memberships of ACTIVE workspaces, ordered by membership creation instant
4974
+ * and then workspace id, ascending. The cursor is opaque to the library and valid only for the
4975
+ * same tenant and member; a malformed cursor, or one issued for another query, restarts from the
4976
+ * first page and never widens the scope. The library bounds `limit` to 1 through 100.
4977
+ *
4978
+ * @param params - The tenant, member and page.
4979
+ * @returns One page.
4980
+ */
4981
+ listForUser(params: ListMembershipsForUserParams): Promise<MembershipPage<MembershipWithWorkspace>>;
4982
+ /**
4983
+ * Lists the members of a workspace, in every membership status so an administrator can see a
4984
+ * suspended member.
4985
+ *
4986
+ * Ordered by membership creation instant and then user id, ascending. The cursor is opaque to
4987
+ * the library and valid only for the same workspace; a malformed cursor, or one issued for
4988
+ * another query, restarts from the first page and never widens the scope. The library bounds
4989
+ * `limit` to 1 through 100.
4990
+ *
4991
+ * @param params - The workspace key and page.
4992
+ * @returns One page.
4993
+ */
4994
+ listForWorkspace(params: ListMembershipsForWorkspaceParams): Promise<MembershipPage<AuthMembership>>;
4995
+ /**
4996
+ * Adds a member, persisting `audit` in the same transaction.
4997
+ *
4998
+ * @param params - The membership key, role, inviter and audit event.
4999
+ * @returns `'already_member'` when the user already belongs to the workspace in any status,
5000
+ * `'workspace_not_found'` when the workspace does not exist.
5001
+ */
5002
+ create(params: CreateMembershipParams): Promise<CreateMembershipResult>;
5003
+ /**
5004
+ * Changes a member's role, persisting `audit` in the same transaction.
5005
+ *
5006
+ * MUST refuse with `'last_owner'` when the change would leave the workspace with no active member
5007
+ * holding `ownerRole`. The check and the write happen in ONE transaction (for example
5008
+ * `SELECT ... FOR UPDATE` on the workspace's owner rows): two owners demoting each other at the
5009
+ * same moment is the race this rule exists for, and the library cannot hold a database
5010
+ * transaction. The library pre-checks only to return a friendlier error; this result decides.
5011
+ *
5012
+ * The same transaction MUST also hold the two roles the library judged the change against, because
5013
+ * it read them before the write and either may have changed since:
5014
+ *
5015
+ * - the actor still holds `actor.expectedRole` as an active member, else answer `'actor_changed'`;
5016
+ * - the member still holds `expectedRole`, else answer `'not_found'`.
5017
+ *
5018
+ * ```sql
5019
+ * BEGIN;
5020
+ * -- 1. lock the actor's row and the member's row together, in one fixed order, so two members
5021
+ * -- acting on each other cannot deadlock and neither role can change before the commit
5022
+ * SELECT user_id, role, status FROM memberships
5023
+ * WHERE tenant_id = $tenant AND workspace_id = $workspace AND user_id IN ($actor, $member)
5024
+ * ORDER BY user_id
5025
+ * FOR UPDATE;
5026
+ * -- 2. the actor row missing, inactive or not holding $actorRole: ROLLBACK, answer 'actor_changed'
5027
+ * -- the member row missing, inactive or not holding $expectedRole: ROLLBACK, answer 'not_found'
5028
+ * UPDATE memberships SET role = $role, updated_at = now()
5029
+ * WHERE tenant_id = $tenant AND workspace_id = $workspace AND user_id = $member
5030
+ * AND role = $expectedRole AND status = 'active';
5031
+ * -- 3. the last-owner check, the audit insert, then COMMIT
5032
+ * ```
5033
+ *
5034
+ * A host that ignores both keeps the check-then-write window: a role changed between the library's
5035
+ * read and this call goes unseen. Nothing is written for any result other than `'ok'`.
5036
+ *
5037
+ * @param params - The membership key, new role, the roles judged, owner role and audit event.
5038
+ */
5039
+ changeRole(params: ChangeMembershipRoleParams): Promise<MemberChangeResult>;
5040
+ /**
5041
+ * Removes a member, persisting `audit` in the same transaction. The same atomic last-owner rule
5042
+ * as {@link changeRole} applies, and so does its pair of role conditions when `expectedRole` and
5043
+ * `actor` are given: the actor must still hold `actor.expectedRole` (`'actor_changed'` otherwise)
5044
+ * and the member must still hold `expectedRole` (`'not_found'` otherwise), both in this
5045
+ * transaction. A member leaving passes neither, since no role authorized it.
5046
+ *
5047
+ * @param params - The membership key, the roles judged, owner role and audit event.
5048
+ */
5049
+ remove(params: RemoveMembershipParams): Promise<MemberChangeResult>;
5050
+ /**
5051
+ * Hands ownership from one member to another in one transaction, persisting `audit` with it.
5052
+ *
5053
+ * `fromUserId` must be an active member holding `ownerRole`, and `toUserId` an active member; the
5054
+ * target takes `ownerRole`, and the previous owner takes `demoteFromTo` when it is set.
5055
+ *
5056
+ * @param params - The workspace key, both members, owner role, the previous owner's new role and
5057
+ * the audit event.
5058
+ * @returns `'not_found'` when the workspace or the `fromUserId` membership does not exist or is
5059
+ * not an active owner, `'target_not_member'` when `toUserId` is not an active member.
5060
+ */
5061
+ transferOwnership(params: TransferOwnershipParams): Promise<TransferOwnershipResult>;
5062
+ /**
5063
+ * Counts the workspaces a member owns, for the per-user cap.
5064
+ *
5065
+ * Counts the workspaces in which the member is an ACTIVE `ownerRole` holder and that are not
5066
+ * `deleted`, so one pending deletion still counts. Read from the primary, like every read the
5067
+ * library decides on.
5068
+ *
5069
+ * @param params - The tenant, member and owner role.
5070
+ * @returns How many.
5071
+ */
5072
+ countOwned(params: CountOwnedParams): Promise<number>;
5073
+ /**
5074
+ * Lists the workspaces whose ONLY active `ownerRole` holder is this member, so a host can block or
5075
+ * route an account deletion that would orphan them.
5076
+ *
5077
+ * Excludes `deleted` workspaces. Ordered by workspace creation instant and then workspace id,
5078
+ * ascending. The cursor is opaque to the library and valid only for the same tenant and member; a
5079
+ * malformed cursor, or one issued for another query, restarts from the first page and never widens
5080
+ * the scope. The library bounds `limit` to 1 through 100.
5081
+ *
5082
+ * @param params - The tenant, member, owner role and page.
5083
+ * @returns One page of workspaces.
5084
+ */
5085
+ listSoleOwned(params: ListSoleOwnedParams): Promise<MembershipPage<AuthWorkspace>>;
5086
+ /**
5087
+ * Optional: the workspace this member last switched to, for the post-sign-in landing.
5088
+ *
5089
+ * @param ref - The tenant and member.
5090
+ * @returns The workspace id, or `null` when none was recorded.
5091
+ */
5092
+ getLastActiveWorkspaceId?(ref: LastActiveWorkspaceRef): Promise<string | null>;
5093
+ /**
5094
+ * Optional: remembers the workspace this member last switched to.
5095
+ *
5096
+ * @param params - The tenant, member and workspace.
5097
+ */
5098
+ setLastActiveWorkspaceId?(params: SetLastActiveWorkspaceParams): Promise<void>;
5099
+ }
5100
+
5101
+ /**
5102
+ * No-operation email provider for development and testing environments.
5103
+ *
5104
+ * Implements {@link IEmailProvider} by logging each call via NestJS `Logger`
5105
+ * and resolving immediately without sending any real email. Inject this
5106
+ * provider via `BymaxAuthModule.forRoot({ emailProvider: NoOpEmailProvider })`
5107
+ * when email delivery is not required (local development, integration tests).
5108
+ *
5109
+ * @remarks
5110
+ * **Never use this provider in production.** Replace it with a concrete
5111
+ * adapter (e.g. Resend, SendGrid, Nodemailer) that implements `IEmailProvider`.
5112
+ *
5113
+ * Logged messages include the method name and a MASKED recipient — never the full address,
5114
+ * and never tokens, OTPs, or passwords.
5115
+ *
5116
+ * The mask matters because this is the DEFAULT provider: a deployment that ships without
5117
+ * wiring `BYMAX_AUTH_EMAIL_PROVIDER` gets it, and it would otherwise write every user's
5118
+ * address to stdout on every reset, verification, MFA notification and invitation — a PII
5119
+ * disclosure to whatever collects the logs, produced by an omission rather than a decision.
5120
+ */
5121
+ declare class NoOpEmailProvider implements IEmailProvider {
5122
+ private readonly logger;
5123
+ /** @inheritdoc */
5124
+ sendPasswordResetToken(_tenantId: string, email: string, _token: string, _locale?: string): Promise<void>;
5125
+ /** @inheritdoc */
5126
+ sendPasswordResetOtp(_tenantId: string, email: string, _otp: string, _locale?: string): Promise<void>;
5127
+ /** @inheritdoc */
5128
+ sendEmailVerificationOtp(_tenantId: string, email: string, _otp: string, _locale?: string): Promise<void>;
5129
+ /** @inheritdoc */
5130
+ sendMfaEnabledNotification(_tenantId: string, email: string, _locale?: string): Promise<void>;
5131
+ /** @inheritdoc */
5132
+ sendMfaDisabledNotification(_tenantId: string, email: string, _locale?: string): Promise<void>;
5133
+ /** @inheritdoc */
5134
+ sendNewSessionAlert(_tenantId: string, email: string, _sessionInfo: SessionAlertInfo, _locale?: string): Promise<void>;
5135
+ /** @inheritdoc */
5136
+ sendInvitation(_tenantId: string, email: string, _inviteData: InviteData, _locale?: string): Promise<void>;
5137
+ /** @inheritdoc */
5138
+ sendWorkspaceInvitation(_tenantId: string, email: string, _data: WorkspaceInviteData, _locale?: string): Promise<void>;
5139
+ }
5140
+
5141
+ /**
5142
+ * The delivery channel {@link DefaultAuthEmailProvider} sends through.
5143
+ *
5144
+ * Narrow by design: it names only the one call the provider makes, so the provider couples to no
5145
+ * concrete mailer. Any adapter exposing this shape satisfies it.
5146
+ *
5147
+ * **Structural fit is not enough, and a channel that merely fits will drop the one field that
5148
+ * matters.** `containsCredential` is this interface's own name for "publish none of this
5149
+ * message's content". A channel that has never heard of this library reads every other field —
5150
+ * `to`, `subject`, `html`, `text` — and ignores that one, because nothing tells it to look. The
5151
+ * result is not a missing feature: it is a relay answering `550` with the offending body quoted,
5152
+ * a reset code reaching an audit record, and a `send` call that looked correctly wired.
5153
+ *
5154
+ * So an implementation owes a TRANSLATION, not just a matching shape. Whatever the channel calls
5155
+ * "do not publish this payload", set it from `containsCredential` on every call.
5156
+ *
5157
+ * `@bymax-one/nest-notification`'s `EmailService.send` is the worked example, and it is also the
5158
+ * trap. It satisfies this interface structurally — its input carries these fields and more, all
5159
+ * the extras optional — so it can be passed in directly and will compile. Do not. Its own switch
5160
+ * is spelled `publishProviderText`, so a direct pass hands it a `containsCredential` it does not
5161
+ * read while its own flag stays at the default. Wire an adapter instead:
5162
+ *
5163
+ * ```ts
5164
+ * const sink: AuthEmailSink = {
5165
+ * send: ({ containsCredential, ...message }) =>
5166
+ * mailer.send({ ...message, publishProviderText: !containsCredential })
5167
+ * }
5168
+ * ```
5169
+ *
5170
+ * Named rather than left general because the direct pass is what a reader reaches for once they
5171
+ * know the shapes line up, and this paragraph is the only thing standing between that instinct
5172
+ * and a published credential. The field name is that library's to change; the obligation is not.
5173
+ */
5174
+ interface AuthEmailSink {
5175
+ /**
5176
+ * Delivers one rendered message.
4088
5177
  *
4089
5178
  * @param input - Tenant, recipient, and the rendered subject and bodies.
4090
5179
  * @returns Anything; the provider ignores the result and never surfaces a rejection.
@@ -5338,6 +6427,17 @@ declare class TokenDeliveryService {
5338
6427
  * @returns The raw refresh token string, or `undefined` if not found.
5339
6428
  */
5340
6429
  extractRefreshToken(req: Request): string | undefined;
6430
+ /**
6431
+ * Extracts the refresh token for a logout. It reads as {@link extractRefreshToken} does, except
6432
+ * that a cookie over the bound is no token: logout is the way out of a browser holding such a
6433
+ * cookie, so it must answer as it does for any unusable token and clear the auth cookies, not
6434
+ * refuse. A body value over the bound is still refused.
6435
+ *
6436
+ * @param req - Incoming Express request.
6437
+ * @returns The raw refresh token string, or `undefined` if not found.
6438
+ */
6439
+ extractLogoutRefreshToken(req: Request): string | undefined;
6440
+ private readRefreshToken;
5341
6441
  /**
5342
6442
  * Clears all auth cookies on the resolved domains.
5343
6443
  *
@@ -5401,6 +6501,13 @@ declare class TokenDeliveryService {
5401
6501
  * @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
5402
6502
  */
5403
6503
  private readBodyRefresh;
6504
+ /**
6505
+ * Reads the refresh cookie. A value over the bound is refused like a body value over it: no
6506
+ * token this library mints is longer, so it can only be junk, and it must not reach the store.
6507
+ * `discardOversize` reads it as absent instead. An empty cookie is returned unchanged; callers
6508
+ * treat it as no token.
6509
+ */
6510
+ private readRefreshCookie;
5404
6511
  }
5405
6512
 
5406
6513
  /**
@@ -5916,6 +7023,22 @@ declare class AccountStatusService {
5916
7023
  readonly userId: string;
5917
7024
  readonly tenantId: string;
5918
7025
  }): Promise<void>;
7026
+ /**
7027
+ * The same decision as {@link assertDashboardAccountUsable}, read from the repository now.
7028
+ *
7029
+ * Neither reads nor writes the status cache, so the answer is as current as the repository:
7030
+ * for a caller whose contract is "authorized at this moment", such as a queued job that may run
7031
+ * long after the request that enqueued it, and for which a ban inside the cache window is exactly
7032
+ * the case that must not slip through. It costs one repository read per call.
7033
+ *
7034
+ * @param ref - The account and its tenant.
7035
+ * @throws {AuthException} `TOKEN_INVALID` for an account that no longer exists, the blocked
7036
+ * status's own code, or `EMAIL_NOT_VERIFIED` when verification is required and missing.
7037
+ */
7038
+ assertDashboardAccountUsableNow(ref: {
7039
+ readonly userId: string;
7040
+ readonly tenantId: string;
7041
+ }): Promise<void>;
5919
7042
  /**
5920
7043
  * Refuses a platform administrator whose account is blocked or gone.
5921
7044
  *
@@ -5981,29 +7104,361 @@ declare class UserStatusGuard implements CanActivate {
5981
7104
  }
5982
7105
 
5983
7106
  /**
5984
- * @fileoverview Single-use WebSocket upgrade tickets.
7107
+ * @fileoverview What a queued job carries so its worker can ask whether it is still authorized.
5985
7108
  *
5986
- * The browser `WebSocket` API cannot set handshake headers, so a browser client has no way to
5987
- * present `Authorization: Bearer <token>` at the upgrade. The usual workaround — the access
5988
- * token in the query string — writes a long-lived credential into access logs, browser history
5989
- * and proxy caches. {@link WsJwtGuard} refuses it for exactly that reason, which left browser
5990
- * clients with no supported path at all.
7109
+ * @layer Interface
7110
+ */
7111
+ /**
7112
+ * The workspace a job acts in and the account that enqueued it, stamped at enqueue time from the
7113
+ * request's `@CurrentWorkspace()`.
5991
7114
  *
5992
- * A ticket is the other answer: opaque, single-use, ~30 seconds, and worth nothing once
5993
- * redeemed. It is minted only from a session that is already authenticated, in good standing
5994
- * and MFA-satisfied, so the ticket can never carry more authority than the session that asked
5995
- * for it.
7115
+ * It is a claim, not a proof: a worker must call `WorkspaceAccessService.assertStillAuthorized`
7116
+ * with it before any side effect, because a job can run long after the request that enqueued it and
7117
+ * the member may have been removed, demoted or banned in between. A `workspaceId` read from a job
7118
+ * payload is never to be trusted without that call.
7119
+ */
7120
+ interface WorkspaceJobContext {
7121
+ /** The tenant the job belongs to. */
7122
+ readonly tenantId: string;
7123
+ /** The workspace the job acts in. */
7124
+ readonly workspaceId: string;
7125
+ /** The account the job acts for. */
7126
+ readonly actorUserId: string;
7127
+ }
7128
+
7129
+ /**
7130
+ * @fileoverview Resolves whether a user is an active member of a workspace, and with which role,
7131
+ * from a versioned Redis cache backed by the membership and workspace repositories.
5996
7132
  *
5997
7133
  * @layer Service
5998
7134
  */
5999
7135
 
6000
- declare class WsTicketService {
7136
+ /** An active member of an active workspace, as the access check resolves it. */
7137
+ interface ResolvedWorkspaceMember extends MembershipRef {
7138
+ /** The member's role in the workspace. */
7139
+ role: string;
7140
+ }
7141
+ /**
7142
+ * What the rows say about a caller's access to a workspace.
7143
+ *
7144
+ * - `member`: an active member of an active workspace.
7145
+ * - `pending_deletion`: an active OWNER of a workspace pending deletion. Only an owner is told, so
7146
+ * the answer lets a client offer to restore it; every other caller reads as `denied`.
7147
+ * - `denied`: anything else, a missing workspace, an inactive one and a non-member alike.
7148
+ * `pendingDeletion` is set when the workspace is pending deletion and the caller is an active
7149
+ * member who does not own it: still `denied` to the caller, but the host is told why.
7150
+ */
7151
+ type WorkspaceAccess = {
7152
+ kind: 'member';
7153
+ member: ResolvedWorkspaceMember;
7154
+ } | {
7155
+ kind: 'pending_deletion';
7156
+ member: ResolvedWorkspaceMember;
7157
+ } | {
7158
+ kind: 'denied';
7159
+ pendingDeletion?: true;
7160
+ };
7161
+ /**
7162
+ * Decides workspace access for one request.
7163
+ *
7164
+ * A request is allowed only for an ACTIVE membership of an ACTIVE workspace; every other state
7165
+ * reads as "not a member", so a caller cannot tell a workspace it may not enter from one that does
7166
+ * not exist.
7167
+ *
7168
+ * The cache is advisory. Redis being unreachable never fails a request: the answer then comes from
7169
+ * the repositories, which are authoritative, and nothing is written back.
7170
+ *
7171
+ * The repository reads that fill the cache must come from the primary or be read-your-writes: a
7172
+ * lagging replica would cache a removed member as present under the new version. A counter evicted
7173
+ * under memory pressure restarts at 0 and can make an entry written under 0:0 readable again for
7174
+ * up to its lifetime, the exposure the token-epoch counters have, so run the store with a
7175
+ * no-eviction policy for the auth keyspace.
7176
+ */
7177
+ declare class WorkspaceAccessService {
6001
7178
  private readonly redis;
7179
+ private readonly workspaceRepo;
7180
+ private readonly membershipRepo;
6002
7181
  private readonly options;
6003
- private readonly userRepo;
6004
- private readonly revocation;
7182
+ private readonly accountStatus;
6005
7183
  private readonly logger;
6006
- constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository, revocation: AuthRevocationService);
7184
+ private readonly group;
7185
+ constructor(redis: AuthRedisService, workspaceRepo: IWorkspaceRepository, membershipRepo: IMembershipRepository, options: ResolvedOptions, accountStatus?: AccountStatusService | null);
7186
+ /**
7187
+ * Resolves a user's access to a workspace.
7188
+ *
7189
+ * @param ref - The tenant, workspace and user.
7190
+ * @returns The member and role when the membership AND the workspace are active, else `null`.
7191
+ * @throws {TypeError} When any part of the key is blank.
7192
+ */
7193
+ resolveMembership(ref: MembershipRef): Promise<ResolvedWorkspaceMember | null>;
7194
+ /**
7195
+ * Resolves what the rows say about a caller's access to a workspace, without reading anything the
7196
+ * refusal needs beyond the two rows every refusal already reads.
7197
+ *
7198
+ * @param ref - The tenant, workspace and user.
7199
+ * @returns The access: `member`, `pending_deletion` for the owner of a workspace pending
7200
+ * deletion, or `denied`.
7201
+ * @throws {TypeError} When any part of the key is blank.
7202
+ */
7203
+ resolveAccess(ref: MembershipRef): Promise<WorkspaceAccess>;
7204
+ /**
7205
+ * Answers whether an account may act in a workspace NOW, for work that runs apart from a request.
7206
+ *
7207
+ * A queued job can run long after the request that enqueued it, so its contract is "authorized at
7208
+ * this moment" and nothing cached may answer it. The workspace, the membership and the account
7209
+ * are all read from the repositories, never from the access cache or the status cache, and the
7210
+ * decision is the one a route's guard makes: the same refusals in the same order, with
7211
+ * `workspace_not_found` for anyone who is not an active member (and for every non-owner of a
7212
+ * workspace pending deletion). The account is judged first: a banned or deleted actor is refused
7213
+ * with that status's own code, which is the incident case where a queued job must not act. The
7214
+ * cost is three repository reads per call. The repositories must read from the primary.
7215
+ *
7216
+ * @param context - What was stamped at enqueue time.
7217
+ * @param roles - The roles that may perform the job's work.
7218
+ * @param options - `allowPending` admits the owner of a workspace pending deletion.
7219
+ * @returns The member, with the role they hold now.
7220
+ * @throws {AuthException} `auth.validation` naming the field for a malformed context, the
7221
+ * status's own code or `auth.token_invalid` for an account that is blocked or gone, then
7222
+ * `auth.workspace_not_found`, `auth.workspace_pending_deletion` or
7223
+ * `auth.insufficient_workspace_role`.
7224
+ * @throws {TypeError} When the service was built without the account status service.
7225
+ */
7226
+ assertStillAuthorized(context: WorkspaceJobContext, roles: WorkspaceRoleList, options?: {
7227
+ allowPending?: boolean;
7228
+ }): Promise<ResolvedWorkspaceMember>;
7229
+ /**
7230
+ * Drops the cached access of one membership. Call it after changing a membership outside this
7231
+ * library; a host that cannot guarantee that sets `membershipCacheTtlSeconds: 0`.
7232
+ *
7233
+ * @param ref - The tenant, workspace and user.
7234
+ * @throws {TypeError} When any part of the key is blank.
7235
+ * @throws The Redis error when the bump fails: a change is never reported as invalidated.
7236
+ */
7237
+ invalidateMembership(ref: MembershipRef): Promise<void>;
7238
+ /**
7239
+ * Drops the cached access of EVERY member of a workspace, for an event that changes the whole
7240
+ * workspace such as scheduling its deletion.
7241
+ *
7242
+ * @param ref - The tenant and workspace.
7243
+ * @throws {TypeError} When any part of the key is blank.
7244
+ * @throws The Redis error when the bump fails: a change is never reported as invalidated.
7245
+ */
7246
+ invalidateWorkspace(ref: WorkspaceRef): Promise<void>;
7247
+ private bump;
7248
+ private readCache;
7249
+ private fillCache;
7250
+ /**
7251
+ * Reads the workspace and the membership together, whatever the first one says.
7252
+ *
7253
+ * A missing workspace, an inactive one and a non-member then cost the same repository work, so
7254
+ * the time an answer takes does not tell a caller which of the three it was. The pending-deletion
7255
+ * answer for an owner is decided from these same two rows.
7256
+ */
7257
+ private readRepositories;
7258
+ }
7259
+
7260
+ /**
7261
+ * @fileoverview Fans a workspace audit event out to the host's `onWorkspaceEvent` hook after the
7262
+ * change it describes has committed.
7263
+ *
7264
+ * @layer Service
7265
+ */
7266
+
7267
+ /**
7268
+ * Delivers workspace events to the host.
7269
+ *
7270
+ * Delivery is best-effort and detached: a hook that is slow, throws or rejects never delays or
7271
+ * fails the operation that produced the event. A failure is logged through the module logger with
7272
+ * the hook name and the event type only: the event itself can carry an email address, so it is never
7273
+ * written to the log. The persisted audit row, written by the repository
7274
+ * in the same transaction as the change, is the record; this is a notification.
7275
+ */
7276
+ declare class WorkspaceEventsService {
7277
+ private readonly hooks;
7278
+ private readonly logger;
7279
+ constructor(hooks: IAuthHooks);
7280
+ /**
7281
+ * Hands an event to the `onWorkspaceEvent` hook, if the host defined one.
7282
+ *
7283
+ * @param event - The event that was persisted with the change.
7284
+ * @param context - Request metadata for the hook.
7285
+ */
7286
+ emit(event: WorkspaceAuditEvent, context: HookContext): void;
7287
+ }
7288
+
7289
+ /**
7290
+ * @fileoverview The single emitter of `access.denied`: tells the host's `onWorkspaceEvent` hook
7291
+ * that an account was refused a workspace, bounded per account so a probe cannot flood the hook.
7292
+ *
7293
+ * @layer Service
7294
+ */
7295
+
7296
+ type DeniedEvent = Extract<WorkspaceAuditEvent, {
7297
+ type: 'access.denied';
7298
+ }>;
7299
+ /** Who was refused, where, and in which workspace. */
7300
+ interface DeniedAccess {
7301
+ /** The tenant, from the verified token. */
7302
+ readonly tenantId: string;
7303
+ /** The account, from the verified token. */
7304
+ readonly userId: string;
7305
+ /** The workspace that was named, after it has been validated. */
7306
+ readonly workspaceId: string;
7307
+ /** The surface that refused. */
7308
+ readonly surface: DeniedEvent['surface'];
7309
+ }
7310
+ /**
7311
+ * Runs a workspace access decision and reports its refusal.
7312
+ *
7313
+ * The decision is never affected: a refusal is rethrown unchanged and at once, and the report is
7314
+ * made afterwards, detached, so a slow or failing Redis or hook cannot delay or change the answer.
7315
+ *
7316
+ * Per account (the tenant and the user together) at most `max` events are emitted in a fixed window
7317
+ * of `windowSeconds`, counted in one key whose expiry is set by its first denial. A denial past the
7318
+ * limit is not emitted but counted in a second key that outlives the window by a long way, and the
7319
+ * next event that is emitted reads and clears it with one atomic step and carries it as
7320
+ * `suppressedCount`, so a client that probes past the limit and then stops is still visible. The
7321
+ * two keys are two slots, which is fine: the order of the steps is what matters, and a lost
7322
+ * increment can only under-count. When Redis fails nothing is emitted, never an unlimited stream,
7323
+ * and one warning per window per process says so.
7324
+ */
7325
+ declare class WorkspaceDeniedEventsService {
7326
+ private readonly events;
7327
+ private readonly redis;
7328
+ private readonly logger;
7329
+ private lastWarningAt;
7330
+ private readonly limits;
7331
+ private readonly hmacKey;
7332
+ constructor(events: WorkspaceEventsService, redis: AuthRedisService, options: ResolvedOptions);
7333
+ /**
7334
+ * Runs `decide` and reports the access refusal it raises, if any.
7335
+ *
7336
+ * @param denied - Who is asking, and where.
7337
+ * @param decide - The access decision.
7338
+ * @returns What `decide` returns.
7339
+ * @throws Whatever `decide` throws, unchanged.
7340
+ */
7341
+ admit<T>(denied: DeniedAccess, decide: () => T): T;
7342
+ private report;
7343
+ private warnOncePerWindow;
7344
+ }
7345
+
7346
+ /**
7347
+ * @fileoverview `WorkspaceGuard`: lets a request through only for a workspace it names explicitly,
7348
+ * in which the caller is an active member holding an accepted role.
7349
+ *
7350
+ * @layer Guard
7351
+ */
7352
+
7353
+ /**
7354
+ * Authorizes a request in the workspace it names.
7355
+ *
7356
+ * Run it after `JwtAuthGuard` and `UserStatusGuard`: it reads the verified user they attach. Without
7357
+ * them, or with no `request.user`, a route that declares its roles answers `401 auth.token_invalid`
7358
+ * and the guard never reads further. A route that declares none is refused with `403
7359
+ * auth.forbidden` before anything else, including for an anonymous caller, so a misconfigured
7360
+ * route fails closed whatever the token. In order it:
7361
+ *
7362
+ * 1. refuses a route that declares neither `@WorkspaceRoles(...)` nor `@WorkspacePermission(...)`,
7363
+ * with `403 auth.forbidden`, before any lookup, so a forgotten decorator closes the route
7364
+ * rather than opening it;
7365
+ * 2. refuses anything but a verified dashboard token. A platform token is refused outright: there
7366
+ * is no implicit bypass for platform operators;
7367
+ * 3. resolves the workspace from the route or the host's resolver (never the body, never a
7368
+ * remembered default);
7369
+ * 4. resolves the caller's membership with the tenant taken from the token. A workspace that does
7370
+ * not exist, one that is not active and one the caller does not belong to all answer
7371
+ * `404 auth.workspace_not_found`, so the answer reveals nothing about which workspaces exist.
7372
+ * The one exception is the OWNER of a workspace pending deletion, who gets
7373
+ * `409 auth.workspace_pending_deletion` unless the route carries `@AllowPendingWorkspace()`;
7374
+ * 5. checks the role through `workspaces.roles.hierarchy`, answering `403
7375
+ * auth.insufficient_workspace_role` when it is below what the route declares;
7376
+ * 6. attaches the access to `request.workspace` for `@CurrentWorkspace()`.
7377
+ *
7378
+ * Two limits on step 4. The repositories are read together for every refusal, so a missing
7379
+ * workspace, an inactive one and a non-member cost the same work, but the time a host's database
7380
+ * takes for each row is outside this library. And a missing workspace costs two repository reads,
7381
+ * so the host's rate limiting on guarded routes is what bounds a caller probing ids.
7382
+ */
7383
+ declare class WorkspaceGuard implements CanActivate {
7384
+ private readonly reflector;
7385
+ private readonly access;
7386
+ private readonly denied;
7387
+ private readonly group;
7388
+ constructor(reflector: Reflector, access: WorkspaceAccessService, options: ResolvedOptions, denied: WorkspaceDeniedEventsService);
7389
+ canActivate(context: ExecutionContext): Promise<boolean>;
7390
+ }
7391
+
7392
+ /**
7393
+ * @fileoverview `WsWorkspaceGuard`: lets a socket message through only for a workspace it names, in
7394
+ * which the connected account is an active member holding an accepted role.
7395
+ *
7396
+ * @layer Guard
7397
+ */
7398
+
7399
+ /**
7400
+ * Authorizes a socket message in the workspace it names.
7401
+ *
7402
+ * Run it after `WsJwtGuard`, which authenticates the connection and leaves the verified identity on
7403
+ * `client.data.user`; the identity of a ticket carries no workspace, so the workspace is judged per
7404
+ * message and never at the handshake. It is `WorkspaceGuard` for a gateway handler, with the same
7405
+ * declarations (`@WorkspaceRoles`, `@WorkspacePermission`, `@AllowPendingWorkspace`), the same
7406
+ * access resolution and the same refusals in the same order:
7407
+ *
7408
+ * 1. a handler that declares no roles is refused `403 auth.forbidden` before anything else;
7409
+ * 2. a connection with no verified dashboard identity is refused `401 auth.token_invalid`, and a
7410
+ * message that is not an object, which cannot carry a membership, `400 auth.validation`;
7411
+ * 3. the workspace is read from the message body (`data.workspaceId`, or `workspaces.resolveWsWorkspace`
7412
+ * given the body), never from the URL, a header or the ticket, and a value that is blank,
7413
+ * over-long or holds a control character is `400 auth.validation` naming `workspaceId`, before
7414
+ * any lookup;
7415
+ * 4. a workspace that does not exist, one the account does not belong to, and one pending deletion
7416
+ * that the account does not own all answer the identical `404 auth.workspace_not_found`; the
7417
+ * owner of a pending workspace gets `409 auth.workspace_pending_deletion` unless the handler
7418
+ * carries `@AllowPendingWorkspace()`;
7419
+ * 5. the role is checked through `workspaces.roles.hierarchy`;
7420
+ * 6. the membership is kept with the message for `@CurrentWsWorkspace()`, never on the connection:
7421
+ * overlapping messages on one socket would overwrite a slot on the client, and a handler that
7422
+ * awaited something would act in a workspace another message was admitted to.
7423
+ *
7424
+ * Every message is judged again, through the access cache, so a member removed between two messages
7425
+ * is refused on the next one.
7426
+ */
7427
+ declare class WsWorkspaceGuard implements CanActivate {
7428
+ private readonly reflector;
7429
+ private readonly access;
7430
+ private readonly denied;
7431
+ private readonly group;
7432
+ constructor(reflector: Reflector, access: WorkspaceAccessService, options: ResolvedOptions, denied: WorkspaceDeniedEventsService);
7433
+ canActivate(context: ExecutionContext): Promise<boolean>;
7434
+ /** The workspace the message names, as the host's resolver or the default field reads it. */
7435
+ private named;
7436
+ }
7437
+
7438
+ /**
7439
+ * @fileoverview Single-use WebSocket upgrade tickets.
7440
+ *
7441
+ * The browser `WebSocket` API cannot set handshake headers, so a browser client has no way to
7442
+ * present `Authorization: Bearer <token>` at the upgrade. The usual workaround — the access
7443
+ * token in the query string — writes a long-lived credential into access logs, browser history
7444
+ * and proxy caches. {@link WsJwtGuard} refuses it for exactly that reason, which left browser
7445
+ * clients with no supported path at all.
7446
+ *
7447
+ * A ticket is the other answer: opaque, single-use, ~30 seconds, and worth nothing once
7448
+ * redeemed. It is minted only from a session that is already authenticated, in good standing
7449
+ * and MFA-satisfied, so the ticket can never carry more authority than the session that asked
7450
+ * for it.
7451
+ *
7452
+ * @layer Service
7453
+ */
7454
+
7455
+ declare class WsTicketService {
7456
+ private readonly redis;
7457
+ private readonly options;
7458
+ private readonly userRepo;
7459
+ private readonly revocation;
7460
+ private readonly logger;
7461
+ constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository, revocation: AuthRevocationService);
6007
7462
  /**
6008
7463
  * Mints a ticket from an already-verified access-token payload.
6009
7464
  *
@@ -10036,6 +11491,11 @@ declare class PasswordResetService {
10036
11491
  * - `otp` — verified by {@link OtpService} and consumed on success.
10037
11492
  * - `verifiedToken` — consumed atomically from Redis (`pw_vtok:{sha256(verifiedToken)}`).
10038
11493
  *
11494
+ * The proof is classified before anything else is judged, so a request with none, with more than
11495
+ * one, or with one the configured method does not accept is an invalid token whatever password it
11496
+ * carries and never reaches the password policy. Then the password is judged, then the proof is
11497
+ * spent.
11498
+ *
10039
11499
  * On success the user's password is updated and all sessions are invalidated.
10040
11500
  * The method throws an {@link AuthException} on any failure — no timing
10041
11501
  * normalization is applied here since the error reveals only that the proof
@@ -10386,6 +11846,36 @@ declare class PlatformAuthService {
10386
11846
  revokeAllPlatformSessions(userId: string): Promise<void>;
10387
11847
  }
10388
11848
 
11849
+ /**
11850
+ * @fileoverview `@CurrentWorkspace()`: the workspace and role `WorkspaceGuard` resolved for the
11851
+ * request.
11852
+ *
11853
+ * @layer Decorator
11854
+ */
11855
+ /** The access `WorkspaceGuard` resolved for a request. */
11856
+ interface CurrentWorkspaceContext {
11857
+ /** The tenant, taken from the verified token. */
11858
+ tenantId: string;
11859
+ /** The workspace the request named, checked against the caller's active membership. */
11860
+ workspaceId: string;
11861
+ /** The caller. */
11862
+ userId: string;
11863
+ /** The caller's role in that workspace. */
11864
+ role: string;
11865
+ }
11866
+ /** A request after `WorkspaceGuard` ran. */
11867
+ interface WorkspaceRequest {
11868
+ workspace?: CurrentWorkspaceContext;
11869
+ }
11870
+ /**
11871
+ * Injects the workspace access the guard resolved.
11872
+ *
11873
+ * A service takes its workspace from here and never from a DTO or a query: the guard is the only
11874
+ * place that checked the caller may act in it. Throws when the route runs without
11875
+ * `WorkspaceGuard`, since an id read from anywhere else would be unchecked.
11876
+ */
11877
+ declare const CurrentWorkspace: (...dataOrPipes: unknown[]) => ParameterDecorator;
11878
+
10389
11879
  /**
10390
11880
  * @fileoverview The request a `tenantIdResolver` sees when the caller arrived by WebSocket upgrade.
10391
11881
  *
@@ -10435,6 +11925,32 @@ type VerifiedAccessToken = {
10435
11925
  readonly plane: 'platform';
10436
11926
  readonly payload: PlatformJwtPayload;
10437
11927
  };
11928
+ /**
11929
+ * The workspace a verification also admits the caller to.
11930
+ *
11931
+ * Judged exactly as `WorkspaceGuard` judges a route: the same access resolution, the same cache, the
11932
+ * same refusals in the same order, so a stream and a route can never disagree about a member.
11933
+ */
11934
+ interface WorkspaceCheck {
11935
+ /** The workspace the caller names, from the message and never from the token or the URL. */
11936
+ readonly workspaceId: string;
11937
+ /** The roles that admit the caller; `ANY_WORKSPACE_MEMBER` admits every active member. */
11938
+ readonly roles: WorkspaceRoleList;
11939
+ /**
11940
+ * Admit the owner of a workspace pending deletion, for a read-only stream. Everyone else is still
11941
+ * answered `workspace_not_found`.
11942
+ *
11943
+ * @defaultValue false
11944
+ */
11945
+ readonly allowPending?: boolean;
11946
+ }
11947
+ /** A dashboard verification that also admitted the caller to a workspace. */
11948
+ interface VerifiedWorkspaceAccessToken {
11949
+ readonly plane: 'dashboard';
11950
+ readonly payload: DashboardJwtPayload;
11951
+ /** The caller's membership of the workspace they were admitted to. */
11952
+ readonly workspace: CurrentWorkspaceContext;
11953
+ }
10438
11954
  /**
10439
11955
  * What a verification checks beyond the signature.
10440
11956
  *
@@ -10497,6 +12013,19 @@ interface VerifyAccessTokenOptions {
10497
12013
  * binding the HTTP guards enforce and this surface does not.
10498
12014
  */
10499
12015
  readonly request?: HandshakeLike;
12016
+ /**
12017
+ * Also admit the caller to one workspace, resolved through the access cache the routes use, and
12018
+ * return their membership as `workspace`. A refusal is the guard's own: `workspace_not_found`
12019
+ * for a caller who is not an active member (and for every non-owner of a workspace pending
12020
+ * deletion, identically), `workspace_pending_deletion` for its owner, `insufficient_workspace_role`
12021
+ * for a role no accepted one covers, and `auth.validation` naming `workspaceId` for an id that is
12022
+ * blank, over-long or holds a control character, ahead of any lookup.
12023
+ *
12024
+ * Dashboard plane only, and only with `workspaces.enabled`: anything else is a `TypeError`,
12025
+ * because a platform token has no workspace and the feature is absent otherwise. A stream calls
12026
+ * it at subscribe time and again on its cadence or per message; a refusal means disconnect.
12027
+ */
12028
+ readonly workspace?: WorkspaceCheck;
10500
12029
  }
10501
12030
  /**
10502
12031
  * Performs, in one call, every identity check a guarded HTTP route performs before a handler runs.
@@ -10534,8 +12063,9 @@ interface VerifyAccessTokenOptions {
10534
12063
  * account is usable, and the definitive refusal is the one it must see first.
10535
12064
  *
10536
12065
  * **What it still does not do, and cannot.** Route authorization is the consumer's — this answers
10537
- * who the caller is, never what they may do, so a `@Roles()` equivalent stays yours to apply on
10538
- * every message a stream carries, not only at the handshake. Tenant binding
12066
+ * who the caller is, and with {@link VerifyAccessTokenOptions.workspace} which workspace they belong
12067
+ * to and in what role, never what they may do beyond that, so a `@Roles()` equivalent stays yours to
12068
+ * apply on every message a stream carries, not only at the handshake. Tenant binding
10539
12069
  * (`enforceTenantBinding`) needs the request the resolver reads, which a token does not carry:
10540
12070
  * pass the handshake as {@link VerifyAccessTokenOptions.request}, or the binding is not applied. And nothing here holds a subscription: it answers at the moment it is called, so a stream
10541
12071
  * that calls it once at connect is authorized for the lifetime of the token, not of the session.
@@ -10554,6 +12084,8 @@ declare class AuthTokenVerifierService {
10554
12084
  private readonly options;
10555
12085
  private readonly revocation;
10556
12086
  private readonly accountStatus;
12087
+ private readonly workspaceAccess;
12088
+ private readonly deniedEvents;
10557
12089
  private readonly logger;
10558
12090
  /** Whether the "binding not applied" warning has been logged by this instance. */
10559
12091
  private warnedUnbound;
@@ -10564,7 +12096,7 @@ declare class AuthTokenVerifierService {
10564
12096
  * @param revocation - The two revocation channels, shared with the mounted guards.
10565
12097
  * @param accountStatus - The account lifecycle gate, shared with {@link UserStatusGuard}.
10566
12098
  */
10567
- constructor(jwtService: JwtService, options: ResolvedOptions, revocation: AuthRevocationService, accountStatus: AccountStatusService);
12099
+ constructor(jwtService: JwtService, options: ResolvedOptions, revocation: AuthRevocationService, accountStatus: AccountStatusService, workspaceAccess?: WorkspaceAccessService | null, deniedEvents?: WorkspaceDeniedEventsService | null);
10568
12100
  /**
10569
12101
  * Verifies an access token and returns its payload, or throws.
10570
12102
  *
@@ -10593,6 +12125,10 @@ declare class AuthTokenVerifierService {
10593
12125
  * @throws {TypeError} When `options.plane` is neither `'dashboard'` nor `'platform'` — a caller
10594
12126
  * error rather than an authentication outcome, so it is deliberately not an `AuthException`.
10595
12127
  */
12128
+ verifyAccessToken(token: string, options: VerifyAccessTokenOptions & {
12129
+ plane: 'dashboard';
12130
+ workspace: WorkspaceCheck;
12131
+ }): Promise<VerifiedWorkspaceAccessToken>;
10596
12132
  verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<VerifiedAccessToken>;
10597
12133
  /**
10598
12134
  * The dashboard arm: the full chain plus the tenant claim and the tenant-scoped status gate.
@@ -10605,6 +12141,14 @@ declare class AuthTokenVerifierService {
10605
12141
  * @throws {@link AuthException} as {@link verifyAccessToken} documents.
10606
12142
  */
10607
12143
  private verifyDashboard;
12144
+ /**
12145
+ * The function that admits a caller to a workspace, or a `TypeError` when none can: on a plane
12146
+ * with no workspaces, or on a deployment that has not enabled them. A programmer's error.
12147
+ *
12148
+ * The returned function admits the caller as `WorkspaceGuard` would a route, with `auth.validation`
12149
+ * for a malformed id and then the guard's refusals.
12150
+ */
12151
+ private workspaceResolver;
10608
12152
  /**
10609
12153
  * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
10610
12154
  *
@@ -10657,126 +12201,834 @@ declare class AuthTokenVerifierService {
10657
12201
  }
10658
12202
 
10659
12203
  /**
10660
- * @fileoverview OAuth 2.0 Authorization Code flow service for @bymax-one/nest-auth.
10661
- *
10662
- * Handles the two-leg OAuth flow:
10663
- * 1. `initiateOAuth()` — generates a CSRF-protection state, stores it in Redis,
10664
- * and redirects the user to the provider's authorization URL.
10665
- * 2. `handleCallback()` — validates the state, exchanges the authorization code,
10666
- * fetches the profile, runs the `onOAuthLogin` hook, and issues auth tokens.
10667
- *
10668
- * @remarks
10669
- * **Tenant spoofing warning:** `initiateOAuth()` stores the `tenantId` provided
10670
- * by the caller without verifying that the tenant exists. The `onOAuthLogin` hook
10671
- * is the appropriate validation point. Without an `onOAuthLogin` implementation,
10672
- * any caller triggers `OAUTH_FAILED` — OAuth sign-in is fully disabled by default.
10673
- * Implement `onOAuthLogin` to enable it and enforce tenant membership.
12204
+ * @fileoverview The membership side of the workspace lifecycle: listings, role changes, removal,
12205
+ * leaving and ownership transfer.
10674
12206
  *
10675
12207
  * @layer Service
10676
12208
  */
10677
12209
 
12210
+ /** A member's workspaces, and the one they last switched to. */
12211
+ interface MyWorkspaces extends MembershipPage<MembershipWithWorkspace> {
12212
+ lastActiveWorkspaceId: string | null;
12213
+ }
10678
12214
  /**
10679
- * Core OAuth 2.0 service — provider-agnostic flow orchestration.
12215
+ * Changes who belongs to a workspace and what they may do there.
10680
12216
  *
10681
- * Each OAuth provider is abstracted by an {@link OAuthProviderPlugin}. The
10682
- * service resolves the correct plugin by name and delegates the provider-specific
10683
- * operations (authorize URL, code exchange, profile fetch) to the plugin.
12217
+ * Every write is made by the repository together with its audit event, and the last-owner rule is
12218
+ * decided there, in the same transaction as the write. A successful write bumps the affected
12219
+ * members' cache versions, so a change takes effect on their next request, and a bump that fails
12220
+ * surfaces as an error. The hook is told afterwards.
12221
+ *
12222
+ * The role ceiling. The owner role may grant, change and remove any role, other owners included
12223
+ * (the repository still refuses to leave a workspace with none). Every other role acts only
12224
+ * STRICTLY below itself: it may grant a role it includes, never its own, and may change or remove a
12225
+ * member whose role it includes, never a peer holding the same role and never anyone above. A member
12226
+ * therefore cannot change their own role (leaving is its own action), and an editor cannot make
12227
+ * another editor or remove one.
12228
+ *
12229
+ * The ceiling is judged from roles read before the write, so the write carries them: the member's
12230
+ * `expectedRole` and the actor's role, which the repository checks in the write's own transaction. A
12231
+ * member promoted, or an actor demoted, between the read and the write is answered `not_found` or
12232
+ * `actor_changed` and nothing changes. A repository that ignores both keeps that window open.
12233
+ *
12234
+ * A write whose cache bump failed throws, and retrying a role change repeats the bump. A removal is
12235
+ * different: once the member is gone the retry answers `auth.workspace_not_found`, so the stale
12236
+ * access ends when `workspaces.membershipCacheTtlSeconds` elapses, or at once through
12237
+ * `WorkspaceAccessService.invalidateMembership`.
10684
12238
  */
10685
- declare class OAuthService {
10686
- private readonly plugins;
10687
- private readonly userRepo;
10688
- private readonly hooks;
10689
- private readonly redis;
10690
- private readonly tokenManager;
10691
- private readonly sessionService;
10692
- private readonly options;
10693
- private readonly logger;
10694
- constructor(plugins: OAuthProviderPlugin[], userRepo: IUserRepository, hooks: IAuthHooks | null, redis: AuthRedisService, tokenManager: TokenManagerService, sessionService: SessionService, options: ResolvedOptions);
12239
+ declare class MembershipService {
12240
+ private readonly memberships;
12241
+ private readonly access;
12242
+ private readonly events;
12243
+ private readonly group;
12244
+ constructor(memberships: IMembershipRepository, access: WorkspaceAccessService, events: WorkspaceEventsService, options: ResolvedOptions);
10695
12245
  /**
10696
- * Initiates the OAuth 2.0 Authorization Code flow.
12246
+ * Lists the caller's own active memberships with their workspaces, and the workspace they last
12247
+ * switched to.
10697
12248
  *
10698
- * Sequence:
10699
- * 1. Validates the `provider` format and resolves the named plugin.
10700
- * 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
10701
- * 3. Stores `os:{sha256(state)} → { provider, tenantId, codeVerifier }` in Redis with a
10702
- * 10-minute TTL. `provider` is what the callback checks itself against (RFC 9700
10703
- * mix-up defence).
10704
- * 4. Constructs the provider's authorization URL via `plugin.authorizeUrl(state)`.
10705
- * 5. Issues a 302 redirect via the Express `res` object.
12249
+ * @param tenantId - The caller's tenant.
12250
+ * @param userId - The caller; only their own memberships are ever listed.
12251
+ * @param page - The cursor and size.
12252
+ * @returns One page and the last-used workspace id, `null` when none is recorded.
12253
+ */
12254
+ listMine(tenantId: string, userId: string, page?: {
12255
+ cursor?: string;
12256
+ limit?: number;
12257
+ }): Promise<MyWorkspaces>;
12258
+ /**
12259
+ * Lists a workspace's members, in every membership status.
10706
12260
  *
10707
- * @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
10708
- * @param tenantId - Tenant the user will join on successful login, as named by the caller in
10709
- * the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
10710
- * configured, since the deployment decides the tenant and a value it discards would only
10711
- * mislead the caller. Never validated against the database — implement `onOAuthLogin` to
10712
- * enforce tenant membership. Without the hook, OAuth sign-in is disabled.
10713
- * @param req - Incoming Express request, read by the configured `tenantIdResolver`.
10714
- * @param res - Express response in passthrough mode (used for the 302 redirect).
10715
- * @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
12261
+ * @param ref - The workspace.
12262
+ * @param page - The cursor and size.
12263
+ * @returns One page.
10716
12264
  */
10717
- initiateOAuth(provider: string, tenantId: string | undefined, req: Request, res: Response): Promise<void>;
12265
+ listMembers(ref: WorkspaceRef, page?: {
12266
+ cursor?: string;
12267
+ limit?: number;
12268
+ }): Promise<MembershipPage<AuthMembership>>;
10718
12269
  /**
10719
- * Processes the OAuth provider callback and issues auth tokens.
12270
+ * Lists the workspaces a member alone owns, so a host can block or route an account deletion
12271
+ * that would orphan them.
10720
12272
  *
10721
- * Sequence:
10722
- * 1. Validates the `provider` format before touching Redis.
10723
- * 2. Validates the `state` nonce — atomically reads and deletes `os:{sha256(state)}`.
10724
- * Missing key → `OAUTH_FAILED` (expired, forged, or already consumed).
10725
- * 3. Extracts `tenantId` from the stored state payload.
10726
- * 4. Exchanges `code` for an access token via the plugin.
10727
- * 5. Fetches the normalized user profile from the provider.
10728
- * 6. Looks up any existing user linked to the OAuth identity.
10729
- * 7. Calls `hooks.onOAuthLogin(profile, existingUser, context)` to determine
10730
- * the account resolution strategy (`create`, `link`, or `reject`).
10731
- * If no hook is configured (null hooks or missing method), throws `OAUTH_FAILED`.
10732
- * 8. Executes the strategy:
10733
- * - `'create'` — creates a new user via `userRepo.createWithOAuth()`.
10734
- * - `'link'` — links the OAuth identity to an existing user via `userRepo.linkOAuth()`.
10735
- * Re-fetches the user by primary key after linking.
10736
- * - `'reject'` — throws `AuthException(OAUTH_FAILED)`.
10737
- * 9. Issues dashboard tokens with a safe (credential-stripped) user projection.
10738
- * 10. Creates a session if session tracking is enabled.
12273
+ * @param tenantId - The member's tenant.
12274
+ * @param userId - The member.
12275
+ * @param page - The cursor and size.
12276
+ * @returns One page of workspaces.
12277
+ */
12278
+ listSoleOwnedWorkspaces(tenantId: string, userId: string, page?: {
12279
+ cursor?: string;
12280
+ limit?: number;
12281
+ }): Promise<MembershipPage<AuthWorkspace>>;
12282
+ /**
12283
+ * Changes a member's role.
10739
12284
  *
10740
- * @param provider - Provider name matching a registered plugin.
10741
- * @param code - Authorization code received on the callback URL.
10742
- * @param state - CSRF nonce received on the callback URL (must match the stored value).
10743
- * @param stateCookie - Value of the `oauth_state` cookie planted by `initiateOAuth()`, or
10744
- * `undefined` when the browser sent none. Must equal `state`; see the binding check below.
10745
- * @param ip - Client IP for session audit (truncated to 64 chars).
10746
- * @param userAgent - User-Agent string for session audit.
10747
- * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
10748
- * @returns Full `AuthResult` with access token, refresh token, and safe user record,
10749
- * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
10750
- * temp token when the resolved user has MFA enabled. The caller routes the two
10751
- * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
10752
- * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
12285
+ * @param ref - The workspace.
12286
+ * @param userId - The member whose role changes.
12287
+ * @param role - The role to give.
12288
+ * @param actor - Who changes it, with the role they hold.
12289
+ * @param context - Request metadata for the hook.
12290
+ * @throws {AuthException} `auth.validation` for a role outside the hierarchy,
12291
+ * `auth.insufficient_workspace_role` when the actor would grant or change above their own role,
12292
+ * `auth.workspace_not_found` for a member who is not active, `auth.last_owner` when it would
12293
+ * leave the workspace without an owner.
10753
12294
  */
10754
- handleCallback(provider: string, code: string, state: string, stateCookie: string | undefined, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
12295
+ changeRole(ref: WorkspaceRef, userId: string, role: string, actor: WorkspaceActor, context: HookContext): Promise<void>;
10755
12296
  /**
10756
- * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
12297
+ * Removes a member from a workspace.
10757
12298
  *
10758
- * Validates the `provider` format against `/^[a-z0-9-]{1,64}$/` before the
10759
- * registry lookup. This ensures that a malformed or oversized provider name
10760
- * (e.g. path traversal characters, null bytes) is explicitly rejected rather
10761
- * than silently failing the `find()` with a format-dependent miss.
12299
+ * @param ref - The workspace.
12300
+ * @param userId - The member to remove.
12301
+ * @param actor - Who removes them, with the role they hold.
12302
+ * @param context - Request metadata for the hook.
12303
+ * @throws {AuthException} `auth.insufficient_workspace_role` when the member holds a role above
12304
+ * the actor's, `auth.workspace_not_found` for a member who is not active, `auth.last_owner`
12305
+ * when it would leave the workspace without an owner.
12306
+ */
12307
+ remove(ref: WorkspaceRef, userId: string, actor: WorkspaceActor, context: HookContext): Promise<void>;
12308
+ /**
12309
+ * Lets a member leave a workspace.
10762
12310
  *
10763
- * @param provider - Plugin name to look up.
10764
- * @returns The matching plugin.
10765
- * @throws `AuthException(OAUTH_FAILED)` when the name is invalid or no plugin matches.
12311
+ * @param ref - The workspace.
12312
+ * @param userId - The member leaving.
12313
+ * @param context - Request metadata for the hook.
12314
+ * @throws {AuthException} `auth.last_owner` when they are the last owner: they must transfer
12315
+ * ownership or delete the workspace first.
10766
12316
  */
10767
- private resolvePlugin;
12317
+ leave(ref: WorkspaceRef, userId: string, context: HookContext): Promise<void>;
12318
+ /**
12319
+ * Hands ownership to another active member in one atomic step.
12320
+ *
12321
+ * Only an owner can hand it over. The repository decides the rest in one transaction: the giver
12322
+ * must still be an active owner, the receiver must be an active member of THIS workspace in this
12323
+ * tenant, and the giver's demotion is part of the same write, so there is never a moment with no
12324
+ * owner or with the giver demoted and the receiver not yet promoted.
12325
+ *
12326
+ * @param ref - The workspace.
12327
+ * @param actor - The owner handing it over, with the role they hold.
12328
+ * @param toUserId - The active member who becomes an owner.
12329
+ * @param demoteFromTo - The role the previous owner takes, or `null` to keep both as owners.
12330
+ * @param context - Request metadata for the hook.
12331
+ * @throws {AuthException} `auth.insufficient_workspace_role` when the actor is not an owner,
12332
+ * `auth.validation` for a role outside the hierarchy, the owner role, a transfer to oneself or
12333
+ * to a member who is not active in this workspace, `auth.workspace_not_found` when the giver is
12334
+ * no longer an active owner.
12335
+ */
12336
+ transferOwnership(ref: WorkspaceRef, actor: WorkspaceActor, toUserId: string, demoteFromTo: string | null, context: HookContext): Promise<void>;
12337
+ /**
12338
+ * Refuses a hand-over to a member who is not ACTIVE in this workspace: a suspended member is a
12339
+ * member, but ownership is not theirs to receive.
12340
+ *
12341
+ * It is a read, so a caller can run it before a costly step; the repository still decides the same
12342
+ * thing in the write's own transaction.
12343
+ *
12344
+ * @param ref - The workspace.
12345
+ * @param toUserId - The member who would become an owner.
12346
+ * @throws {AuthException} `auth.validation` naming `userId` for a member who is absent or not active.
12347
+ */
12348
+ assertTransferTarget(ref: WorkspaceRef, toUserId: string): Promise<void>;
12349
+ /**
12350
+ * Refuses, from the request alone, a hand-over that cannot succeed.
12351
+ *
12352
+ * Everything here is decided locally and spends nothing, so a caller can run it before a costly
12353
+ * step such as a password check: only an owner may hand ownership over, not to themselves, and
12354
+ * the role the giver keeps must be a workspace role other than the owner role.
12355
+ *
12356
+ * @param actor - The member handing ownership over, with the role they hold.
12357
+ * @param toUserId - The member who would become an owner.
12358
+ * @param demoteFromTo - The role the giver would take, or `null` to keep both as owners.
12359
+ * @throws {AuthException} `auth.insufficient_workspace_role` when the actor is not an owner,
12360
+ * `auth.validation` for a hand-over to oneself or a role the giver cannot take.
12361
+ */
12362
+ assertMayTransfer(actor: WorkspaceActor, toUserId: string, demoteFromTo: string | null): void;
12363
+ /**
12364
+ * Refuses a role the actor may not grant: the owner role may grant any role, every other role only
12365
+ * a role it includes and does not itself hold.
12366
+ *
12367
+ * @param actorRole - The role the actor holds.
12368
+ * @param role - The role to grant.
12369
+ * @throws {AuthException} `auth.validation` for a role outside the hierarchy,
12370
+ * `auth.insufficient_workspace_role` when the actor may not grant it.
12371
+ */
12372
+ assertMayGrant(actorRole: string, role: string): void;
12373
+ /**
12374
+ * Whether the actor's role stands above another role, so they may act on an invitation or a member
12375
+ * holding it. The same rule {@link assertMayGrant} applies, as an answer rather than a refusal.
12376
+ *
12377
+ * @param actorRole - The role the actor holds.
12378
+ * @param otherRole - The role acted on.
12379
+ */
12380
+ mayActOn(actorRole: string, otherRole: string): boolean;
12381
+ /**
12382
+ * Reads one member of a workspace.
12383
+ *
12384
+ * @param ref - The workspace.
12385
+ * @param userId - The member.
12386
+ * @returns The membership as it now stands.
12387
+ * @throws {AuthException} `auth.workspace_not_found` when the member does not exist.
12388
+ */
12389
+ getMember(ref: WorkspaceRef, userId: string): Promise<AuthMembership>;
12390
+ /** Reads an active member and refuses an actor who would act on a role above their own. */
12391
+ private activeMember;
12392
+ /**
12393
+ * Whether an actor's role may act on another role: the owner role on any role, every other role
12394
+ * only on a role it includes and does not itself hold.
12395
+ */
12396
+ private outranks;
12397
+ private removeWith;
12398
+ /**
12399
+ * Turns a guarded write's outcome into an error, or ends the affected members' cached access.
12400
+ * A bump that fails throws, so the change is never reported as done.
12401
+ */
12402
+ private settle;
10768
12403
  }
10769
12404
 
10770
12405
  /**
10771
- * Describes a thrown value in one line, with known values stripped out of the channel's own words.
10772
- *
10773
- * For failures where **nothing that must be withheld was rendered into the message**. There the
10774
- * relay's explanation is the diagnosis, and the values worth naming — a recipient address, say —
10775
- * appear the way this library wrote them, where redaction reaches them. Each piece is redacted,
10776
- * joined, length-capped and passed through {@link logSafe}, because text that came back from a
10777
- * remote is untrusted input and a CR/LF in it would forge a second log record.
12406
+ * @fileoverview The stored record of a workspace invitation and the shapes the invitation routes
12407
+ * answer with.
10778
12408
  *
10779
- * **When the message DID render something to withhold, use {@link describeChannelStatus} instead.**
12409
+ * @layer Interface
12410
+ */
12411
+ /** The fields both kinds of stored invitation carry. */
12412
+ interface InvitationRecordBase {
12413
+ /** The invited address, trimmed and lowercased. */
12414
+ email: string;
12415
+ /** The workspace role the invitation grants. */
12416
+ role: string;
12417
+ /** The tenant the workspace lives in. */
12418
+ tenantId: string;
12419
+ /** The workspace the invitee joins, or the id the workspace will be created with. */
12420
+ workspaceId: string;
12421
+ /** When the current token was issued, as an ISO-8601 instant. */
12422
+ createdAt: string;
12423
+ /** How many times the invitation has been resent. */
12424
+ resendCount: number;
12425
+ }
12426
+ /** An invitation a workspace member issued, to join a workspace that exists. */
12427
+ interface MemberInvitationRecord extends InvitationRecordBase {
12428
+ /** Discriminator. */
12429
+ kind: 'member';
12430
+ /** The member who issued the current token. */
12431
+ inviterUserId: string;
12432
+ }
12433
+ /**
12434
+ * An invitation the platform issued, for the invitee to own a workspace that does not exist until
12435
+ * they accept. It carries no inviter, and its role is the owner role.
12436
+ */
12437
+ interface BootstrapInvitationRecord extends InvitationRecordBase {
12438
+ /** Discriminator. */
12439
+ kind: 'bootstrap';
12440
+ /** The name the workspace is created with, in the form the create route stores it. */
12441
+ workspaceName: string;
12442
+ }
12443
+ /**
12444
+ * What Redis holds under `winv:{sha256(token)}`. The record is shared with rust-auth through
12445
+ * `conformance/wire-contract.json`; any other combination of fields is not a record.
12446
+ */
12447
+ type StoredWorkspaceInvitation = MemberInvitationRecord | BootstrapInvitationRecord;
12448
+ /** One pending invitation as the list route shows it. The token is never part of it. */
12449
+ interface WorkspaceInvitationView {
12450
+ /** The invited address. */
12451
+ email: string;
12452
+ /** The role the invitation grants. */
12453
+ role: string;
12454
+ /** The member who issued the current token. */
12455
+ inviterUserId: string;
12456
+ /** When the current token was issued. */
12457
+ createdAt: string;
12458
+ /** When the current token stops being valid. */
12459
+ expiresAt: string;
12460
+ /** How many times it has been resent. */
12461
+ resendCount: number;
12462
+ }
12463
+ /** The fields of a preview that every kind of invitation shows. */
12464
+ interface InvitationPreviewBase {
12465
+ /** The workspace the invitation is for. */
12466
+ workspaceName: string;
12467
+ /** The role the invitation grants. */
12468
+ role: string;
12469
+ /** The invited address with its local part masked. */
12470
+ maskedEmail: string;
12471
+ /** Whether an account already exists for the address. */
12472
+ accountExists: boolean;
12473
+ }
12474
+ /** What a holder of a member invitation may learn about it before signing in. */
12475
+ interface MemberInvitationPreview extends InvitationPreviewBase {
12476
+ /** Discriminator, the same as the record's. */
12477
+ kind: 'member';
12478
+ /** The display name of the member who invited. */
12479
+ inviterName: string;
12480
+ }
12481
+ /** What a holder of a platform bootstrap invitation may learn about it: it has no inviter. */
12482
+ interface BootstrapInvitationPreview extends InvitationPreviewBase {
12483
+ /** Discriminator, the same as the record's. */
12484
+ kind: 'bootstrap';
12485
+ }
12486
+ /** What a holder of a token may learn about it before signing in. */
12487
+ type WorkspaceInvitationPreview = MemberInvitationPreview | BootstrapInvitationPreview;
12488
+
12489
+ /**
12490
+ * @fileoverview Where workspace invitations live in Redis: the record, the index that names an
12491
+ * address's live invitation, and the set a workspace lists its pending ones from.
12492
+ *
12493
+ * @layer Service
12494
+ */
12495
+
12496
+ /** A pending invitation with the key it is stored under and the seconds it has left. */
12497
+ interface PendingInvitation {
12498
+ /** The record key, `winv:{hash}`. */
12499
+ key: string;
12500
+ /** The stored record. */
12501
+ record: StoredWorkspaceInvitation;
12502
+ /** Seconds until the record expires. */
12503
+ ttlSeconds: number;
12504
+ }
12505
+ /** Reads and writes workspace invitation records; it makes no authorization decision. */
12506
+ declare class WorkspaceInvitationStore {
12507
+ private readonly redis;
12508
+ private readonly hmacKey;
12509
+ constructor(redis: AuthRedisService, options: ResolvedOptions);
12510
+ /**
12511
+ * Reads the record under a token's digest.
12512
+ *
12513
+ * @param tokenHash - `sha256(token)`.
12514
+ * @returns The record, or `null` when absent, expired, or not a record this library wrote.
12515
+ */
12516
+ readByHash(tokenHash: string): Promise<StoredWorkspaceInvitation | null>;
12517
+ /**
12518
+ * Reads what an address's index names in a workspace.
12519
+ *
12520
+ * @param ref - The workspace.
12521
+ * @param email - The invitee, normalized.
12522
+ * @returns `null` when the address has no index; otherwise the record key the index names and its
12523
+ * record, which is `null` when the record has expired or been deleted under a live index.
12524
+ */
12525
+ readByEmail(ref: WorkspaceRef, email: string): Promise<{
12526
+ key: string;
12527
+ record: StoredWorkspaceInvitation | null;
12528
+ } | null>;
12529
+ /**
12530
+ * Writes a record, points the address's index at it and lists it as pending, retiring the record
12531
+ * the index named when it was read, all in one step.
12532
+ *
12533
+ * It writes only while the index still holds `expectedKey`, and, when `limit` is not `0`, only
12534
+ * while the workspace holds fewer than `limit` pending invitations.
12535
+ *
12536
+ * @param ref - The workspace.
12537
+ * @param email - The invitee, normalized.
12538
+ * @param key - The new record key, `winv:{hash}`.
12539
+ * @param record - What to store.
12540
+ * @param ttlSeconds - How long the record and the index live; the set lives as long as its
12541
+ * longest member.
12542
+ * @param limit - The most pending invitations the workspace may hold, or `0` for no limit.
12543
+ * @param expectedKey - The record key the index held when the caller read it, or `null` for no
12544
+ * index. A key whose record is already gone is retired all the same.
12545
+ * @returns `published`; `lost` when the index no longer holds `expectedKey`; or `full` when the
12546
+ * workspace holds `limit`. Nothing is written unless `published`.
12547
+ */
12548
+ publish(ref: WorkspaceRef, email: string, key: string, record: StoredWorkspaceInvitation, ttlSeconds: number, limit: number, expectedKey: string | null): Promise<'published' | 'lost' | 'full'>;
12549
+ /**
12550
+ * Deletes a record, its place in the pending set, and the index when it still names the record.
12551
+ *
12552
+ * @param ref - The workspace.
12553
+ * @param email - The invitee, normalized.
12554
+ * @param key - The record key.
12555
+ * @returns Whether the index still named this record. `false` means another writer had already
12556
+ * moved or deleted it; the record's own key is gone either way.
12557
+ */
12558
+ remove(ref: WorkspaceRef, email: string, key: string): Promise<boolean>;
12559
+ /**
12560
+ * Lists a workspace's pending invitations, dropping set members whose record is gone.
12561
+ *
12562
+ * @param ref - The workspace.
12563
+ * @returns Each live record with its remaining lifetime.
12564
+ */
12565
+ pending(ref: WorkspaceRef): Promise<PendingInvitation[]>;
12566
+ private indexKey;
12567
+ private setKey;
12568
+ private readKey;
12569
+ }
12570
+
12571
+ /**
12572
+ * @fileoverview The body of `POST /workspaces/invitations/accept-signup`.
12573
+ *
12574
+ * @layer DTO
12575
+ */
12576
+ /**
12577
+ * A workspace invitation token and the account to create with it.
12578
+ *
12579
+ * The bounds are those of the tenant invitation's accept body. The 8-character password floor is
12580
+ * structural; the deployment's policy floor is enforced by `PasswordService`, and answers the same
12581
+ * `auth.validation` code.
12582
+ */
12583
+ declare class AcceptWorkspaceInvitationSignupDto {
12584
+ /** The raw token from the invitation message, exactly 64 characters. */
12585
+ token: string;
12586
+ /** Display name of the new account, 2 to 100 characters. */
12587
+ name: string;
12588
+ /** Password of the new account, 8 to 128 characters; hashed at once and never stored in clear. */
12589
+ password: string;
12590
+ }
12591
+
12592
+ /**
12593
+ * @fileoverview Accepting a workspace invitation: by a signed-in account whose address it names,
12594
+ * or by a holder with no account yet, who creates one.
12595
+ *
12596
+ * @layer Service
12597
+ */
12598
+
12599
+ /** What a signed-in acceptance answers: where the caller now belongs, and as what. */
12600
+ interface AcceptedInvitation {
12601
+ /** The workspace the caller joined. */
12602
+ workspaceId: string;
12603
+ /** The role they hold there. */
12604
+ role: string;
12605
+ }
12606
+ /** What a signup acceptance answers: the new account's session and where it now belongs. */
12607
+ interface AcceptedSignup {
12608
+ /** The session, issued as a sign-in would. */
12609
+ result: AuthResult;
12610
+ /** The workspace joined and the role held there. */
12611
+ accepted: AcceptedInvitation;
12612
+ }
12613
+ /** The request facts a signup acceptance needs for its session and its hook. */
12614
+ interface SignupRequest {
12615
+ /** The client address. */
12616
+ ip: string;
12617
+ /** The `User-Agent` header. */
12618
+ userAgent: string;
12619
+ /** The raw request headers, for the hook. */
12620
+ headers: Record<string, string | string[] | undefined>;
12621
+ }
12622
+ /** A record read by its token, with the key it is stored under. */
12623
+ interface LoadedInvitation {
12624
+ /** The sha256 of the token, which names the record. */
12625
+ tokenHash: string;
12626
+ /** The key the record is stored under. */
12627
+ key: string;
12628
+ /** The record. */
12629
+ record: StoredWorkspaceInvitation;
12630
+ }
12631
+ /**
12632
+ * Accepts workspace invitations.
12633
+ *
12634
+ * The order is the contract: everything that can be decided without spending the token is decided
12635
+ * first, the membership is written next, and the token is consumed only after that. A failure
12636
+ * before the write leaves the invitation usable; a failure after it retries into an existing
12637
+ * membership, which counts as success, so the invitee is never left without the invitation they
12638
+ * were promised and the token cannot be used twice by anyone but the one address it names.
12639
+ */
12640
+ declare class WorkspaceInvitationAcceptService {
12641
+ private readonly store;
12642
+ private readonly ceiling;
12643
+ private readonly access;
12644
+ private readonly events;
12645
+ private readonly passwords;
12646
+ private readonly tokens;
12647
+ private readonly sessions;
12648
+ private readonly users;
12649
+ private readonly workspaces;
12650
+ private readonly memberships;
12651
+ private readonly hooks;
12652
+ private readonly options;
12653
+ private readonly logger;
12654
+ private readonly group;
12655
+ constructor(store: WorkspaceInvitationStore, ceiling: MembershipService, access: WorkspaceAccessService, events: WorkspaceEventsService, passwords: PasswordService, tokens: TokenManagerService, sessions: SessionService, users: IUserRepository, workspaces: IWorkspaceRepository, memberships: IMembershipRepository, hooks: IAuthHooks, options: ResolvedOptions);
12656
+ /**
12657
+ * Accepts an invitation as a signed-in account.
12658
+ *
12659
+ * @param caller - The verified token's subject and tenant.
12660
+ * @param token - The raw invitation token.
12661
+ * @param context - Request metadata for the hook.
12662
+ * @returns The workspace the caller joined and the role they hold there, which is the role they
12663
+ * already held when they were a member before.
12664
+ * @throws {AuthException} `auth.invalid_invitation_token` for a token that cannot be honoured,
12665
+ * whatever the reason; `auth.invitation_email_mismatch` when the caller's address is not the
12666
+ * invited one and `auth.email_not_verified` when it is but is not verified, each with the
12667
+ * token left unspent; `auth.workspace_limit_reached` for a bootstrap invitation the caller may
12668
+ * not own another workspace of.
12669
+ */
12670
+ accept(caller: {
12671
+ sub: string;
12672
+ tenantId: string;
12673
+ }, token: string, context: HookContext): Promise<AcceptedInvitation>;
12674
+ /**
12675
+ * Vets an invitation against the profile an OAuth provider returned, before the account it is
12676
+ * for exists or is known. Nothing is written and the token is not spent.
12677
+ *
12678
+ * @param tokenHash - The sha256 the OAuth state record carries, never the raw token.
12679
+ * @param tenantId - The tenant the OAuth flow resolved to.
12680
+ * @param profile - The provider's address for the person and whether the provider verified it.
12681
+ * @returns The record, to be handed to {@link completeOAuth}.
12682
+ * @throws {AuthException} `auth.invalid_invitation_token` for a record that cannot be honoured
12683
+ * or is another tenant's; `auth.invitation_email_mismatch` when the address is not the invited
12684
+ * one and `auth.email_not_verified` when it is but the provider did not verify it.
12685
+ */
12686
+ prepareOAuth(tokenHash: string, tenantId: string, profile: {
12687
+ email: string;
12688
+ emailVerified: boolean;
12689
+ }): Promise<LoadedInvitation>;
12690
+ /**
12691
+ * Completes an invitation vetted by {@link prepareOAuth} for the account the OAuth flow signs in.
12692
+ *
12693
+ * The record is read again and the account must be the invited address in its tenant, and the
12694
+ * inviter's standing and the workspace are judged again here, because the host's hook and the
12695
+ * account write ran since {@link prepareOAuth}: an invitation revoked, replaced or expired in
12696
+ * that time is refused. The membership is written first and the token spent after, as for
12697
+ * every acceptance, and a bootstrap invitation applies
12698
+ * the owner cap and the host's `beforeWorkspaceCreate` before it creates the workspace.
12699
+ *
12700
+ * @param loaded - What {@link prepareOAuth} returned.
12701
+ * @param user - The account the flow signed in.
12702
+ * @param created - Whether the flow created the account, which is when the host's
12703
+ * after-acceptance hook runs.
12704
+ * @param context - Request metadata for the hooks.
12705
+ * @returns The workspace joined and the role held there.
12706
+ * @throws {AuthException} The refusals of {@link accept} for the account, and
12707
+ * `auth.workspace_limit_reached` or `auth.forbidden` for a bootstrap invitation the account may
12708
+ * not own another workspace of; none of them spends the token.
12709
+ */
12710
+ completeOAuth(loaded: LoadedInvitation, user: AuthUser, created: boolean, context: HookContext): Promise<AcceptedInvitation>;
12711
+ /**
12712
+ * Accepts an invitation by creating the account it was addressed to.
12713
+ *
12714
+ * @param dto - The token and the new account's name and password.
12715
+ * @param request - The request facts for the session and the hook.
12716
+ * @returns The new account's session, issued as a sign-in would.
12717
+ * @throws {AuthException} `auth.invalid_invitation_token`; `auth.email_already_exists` when the
12718
+ * address already has an account, whose holder signs in and uses {@link accept}; and whatever
12719
+ * the password policy refuses.
12720
+ */
12721
+ acceptSignup(dto: AcceptWorkspaceInvitationSignupDto, request: SignupRequest): Promise<AcceptedSignup>;
12722
+ /**
12723
+ * Creates the account, answering a concurrent creation of the same address as the account that
12724
+ * already exists, whatever error the repository raised for it.
12725
+ */
12726
+ private createAccount;
12727
+ /** Reads the record a token names, or refuses a token that names nothing usable. */
12728
+ private load;
12729
+ /** Reads the record a token's hash names, or refuses a hash that names nothing usable. */
12730
+ private loadByHash;
12731
+ /** A member record grants a role of the hierarchy; a bootstrap record grants the owner role. */
12732
+ private grantsAKnownRole;
12733
+ /**
12734
+ * Re-checks what was true of the inviter and the workspace when the invitation was minted.
12735
+ *
12736
+ * An invitation delegates authority, and authority is revocable, so it is judged again at
12737
+ * redemption. Every failure answers as an invalid token: the redeemer did not lose the
12738
+ * authority, and the reason would describe someone else's account.
12739
+ */
12740
+ private assertStillGrantable;
12741
+ /**
12742
+ * Writes the membership, then spends the token, then tells the cache and the hook.
12743
+ *
12744
+ * The acceptance takes effect when the membership is written. A revoke or a resend that lands
12745
+ * between the write and the spend therefore cannot undo it: the token's own record is deleted
12746
+ * regardless, the index and the set entry only while they still name it, and the hook event says
12747
+ * the spend lost the race.
12748
+ */
12749
+ private finish;
12750
+ /**
12751
+ * Makes the account a member of the workspace it was invited to, or of the one it will own.
12752
+ *
12753
+ * @returns The role the account holds there.
12754
+ */
12755
+ private join;
12756
+ /** Creates the workspace a bootstrap invitation was for, owned by the accepting account. */
12757
+ private createOwned;
12758
+ /**
12759
+ * Applies to a bootstrap acceptance what the create route applies to a workspace the account
12760
+ * creates itself, except the self-serve switch: the owner cap, then the host's
12761
+ * `beforeWorkspaceCreate`. The platform has already decided that this account may own a
12762
+ * workspace, but the host's plan or quota may have changed since, and the acceptance can land
12763
+ * days after the invitation. A refusal does not spend the token.
12764
+ *
12765
+ * @throws {AuthException} `auth.workspace_limit_reached` at the cap, `auth.forbidden` naming
12766
+ * `name` with the hook's reason when the hook refuses.
12767
+ */
12768
+ private assertMayOwnAnother;
12769
+ /** Issues the new account's session as a sign-in does, and fires the host's hook. */
12770
+ private signIn;
12771
+ }
12772
+
12773
+ /**
12774
+ * @fileoverview OAuth 2.0 Authorization Code flow service for @bymax-one/nest-auth.
12775
+ *
12776
+ * Handles the two-leg OAuth flow:
12777
+ * 1. `initiateOAuth()` — generates a CSRF-protection state, stores it in Redis,
12778
+ * and redirects the user to the provider's authorization URL.
12779
+ * 2. `handleCallback()` — validates the state, exchanges the authorization code,
12780
+ * fetches the profile, runs the `onOAuthLogin` hook, and issues auth tokens.
12781
+ *
12782
+ * @remarks
12783
+ * **Tenant spoofing warning:** `initiateOAuth()` stores the `tenantId` provided
12784
+ * by the caller without verifying that the tenant exists. The `onOAuthLogin` hook
12785
+ * is the appropriate validation point. Without an `onOAuthLogin` implementation,
12786
+ * any caller triggers `OAUTH_FAILED` — OAuth sign-in is fully disabled by default.
12787
+ * Implement `onOAuthLogin` to enable it and enforce tenant membership.
12788
+ *
12789
+ * @layer Service
12790
+ */
12791
+
12792
+ /**
12793
+ * Core OAuth 2.0 service — provider-agnostic flow orchestration.
12794
+ *
12795
+ * Each OAuth provider is abstracted by an {@link OAuthProviderPlugin}. The
12796
+ * service resolves the correct plugin by name and delegates the provider-specific
12797
+ * operations (authorize URL, code exchange, profile fetch) to the plugin.
12798
+ */
12799
+ declare class OAuthService {
12800
+ private readonly plugins;
12801
+ private readonly userRepo;
12802
+ private readonly hooks;
12803
+ private readonly redis;
12804
+ private readonly tokenManager;
12805
+ private readonly sessionService;
12806
+ private readonly options;
12807
+ private readonly invitations;
12808
+ private readonly logger;
12809
+ constructor(plugins: OAuthProviderPlugin[], userRepo: IUserRepository, hooks: IAuthHooks | null, redis: AuthRedisService, tokenManager: TokenManagerService, sessionService: SessionService, options: ResolvedOptions, invitations?: WorkspaceInvitationAcceptService | null);
12810
+ /**
12811
+ * Initiates the OAuth 2.0 Authorization Code flow.
12812
+ *
12813
+ * Sequence:
12814
+ * 1. Validates the `provider` format and resolves the named plugin.
12815
+ * 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
12816
+ * 3. Stores `os:{sha256(state)} → { provider, tenantId, codeVerifier }` in Redis with a
12817
+ * 10-minute TTL. `provider` is what the callback checks itself against (RFC 9700
12818
+ * mix-up defence).
12819
+ * 4. Constructs the provider's authorization URL via `plugin.authorizeUrl(state)`.
12820
+ * 5. Issues a 302 redirect via the Express `res` object.
12821
+ *
12822
+ * @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
12823
+ * @param tenantId - Tenant the user will join on successful login, as named by the caller in
12824
+ * the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
12825
+ * configured, since the deployment decides the tenant and a value it discards would only
12826
+ * mislead the caller. Never validated against the database — implement `onOAuthLogin` to
12827
+ * enforce tenant membership. Without the hook, OAuth sign-in is disabled.
12828
+ * @param req - Incoming Express request, read by the configured `tenantIdResolver`.
12829
+ * @param res - Express response in passthrough mode (used for the 302 redirect).
12830
+ * @param workspaceInvitation - The raw workspace invitation token the flow accepts, when it
12831
+ * does. Only its sha256 is stored, and the response carries `Referrer-Policy: no-referrer`
12832
+ * because the request URL held the token.
12833
+ * @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`, and
12834
+ * `AuthException(INVALID_INVITATION_TOKEN)` for a token when workspaces are not enabled.
12835
+ */
12836
+ initiateOAuth(provider: string, tenantId: string | undefined, req: Request, res: Response, workspaceInvitation?: string): Promise<void>;
12837
+ /**
12838
+ * Hashes the invitation token a flow carries, so Redis never holds the raw token.
12839
+ *
12840
+ * @param carried - The raw invitation value from the query string, if any.
12841
+ * @returns Its sha256, or `undefined` when the flow carries none.
12842
+ * @throws `AuthException(INVALID_INVITATION_TOKEN)` when workspaces are not enabled.
12843
+ */
12844
+ private hashInvitation;
12845
+ /**
12846
+ * Plants the cookie that binds a flow to the browser that started it.
12847
+ *
12848
+ * The `state` parameter alone proves only that somebody started a flow: an attacker can begin
12849
+ * their own authorization, complete consent at the provider, capture the resulting callback URL
12850
+ * without visiting it, and lure the victim there — the victim's browser then receives the
12851
+ * attacker's session. PKCE does not help, because the verifier lives server-side and is replayed
12852
+ * for whoever presents the state. RFC 6749 §10.12 requires this binding, and it is what keeps a
12853
+ * flow started with someone else's invitation from being finished in another browser.
12854
+ * `SameSite` is forced to `lax`: the callback is a cross-site top-level GET and `strict` would
12855
+ * withhold the cookie on exactly that hop.
12856
+ *
12857
+ * @param res - The response to set the cookie on.
12858
+ * @param state - The raw state nonce.
12859
+ */
12860
+ private bindToBrowser;
12861
+ /**
12862
+ * Processes the OAuth provider callback and issues auth tokens.
12863
+ *
12864
+ * Sequence:
12865
+ * 1. Validates the `provider` format before touching Redis.
12866
+ * 2. Validates the `state` nonce — atomically reads and deletes `os:{sha256(state)}`.
12867
+ * Missing key → `OAUTH_FAILED` (expired, forged, or already consumed).
12868
+ * 3. Extracts `tenantId` from the stored state payload.
12869
+ * 4. Exchanges `code` for an access token via the plugin.
12870
+ * 5. Fetches the normalized user profile from the provider.
12871
+ * 6. Looks up any existing user linked to the OAuth identity.
12872
+ * 7. Calls `hooks.onOAuthLogin(profile, existingUser, context)` to determine
12873
+ * the account resolution strategy (`create`, `link`, or `reject`).
12874
+ * If no hook is configured (null hooks or missing method), throws `OAUTH_FAILED`.
12875
+ * 8. Executes the strategy:
12876
+ * - `'create'` — creates a new user via `userRepo.createWithOAuth()`.
12877
+ * - `'link'` — links the OAuth identity to an existing user via `userRepo.linkOAuth()`.
12878
+ * Re-fetches the user by primary key after linking.
12879
+ * - `'reject'` — throws `AuthException(OAUTH_FAILED)`.
12880
+ * 9. Issues dashboard tokens with a safe (credential-stripped) user projection.
12881
+ * 10. Creates a session if session tracking is enabled.
12882
+ *
12883
+ * @param provider - Provider name matching a registered plugin.
12884
+ * @param code - Authorization code received on the callback URL.
12885
+ * @param state - CSRF nonce received on the callback URL (must match the stored value).
12886
+ * @param stateCookie - Value of the `oauth_state` cookie planted by `initiateOAuth()`, or
12887
+ * `undefined` when the browser sent none. Must equal `state`; see the binding check below.
12888
+ * @param ip - Client IP for session audit (truncated to 64 chars).
12889
+ * @param userAgent - User-Agent string for session audit.
12890
+ * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
12891
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
12892
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
12893
+ * temp token when the resolved user has MFA enabled. The caller routes the two
12894
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
12895
+ * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
12896
+ */
12897
+ handleCallback(provider: string, code: string, state: string, stateCookie: string | undefined, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
12898
+ /**
12899
+ * Refuses an account that may not sign in: a blocked status, or an unverified address where the
12900
+ * deployment requires one.
12901
+ *
12902
+ * @param authUser - The account the flow resolved to.
12903
+ * @throws `AuthException` for a blocked status or an unverified address.
12904
+ */
12905
+ private assertMaySignIn;
12906
+ /**
12907
+ * Issues the MFA temp token for an account that has a second factor.
12908
+ *
12909
+ * @param authUser - The account the flow resolved to.
12910
+ * @param provider - The provider name, for the log line.
12911
+ * @param hookResult - The hook's decision, whose action goes in the log line.
12912
+ * @returns The challenge the controller plants in a cookie or surfaces in the body.
12913
+ */
12914
+ private issueMfaChallenge;
12915
+ /**
12916
+ * Issues the tokens and the tracked session of a completed sign-in, then runs the non-blocking
12917
+ * side effects of a login.
12918
+ *
12919
+ * @param authUser - The account the flow resolved to.
12920
+ * @param provider - The provider name, for the log line.
12921
+ * @param hookResult - The hook's decision, whose action goes in the log line.
12922
+ * @param hookContext - The context the hooks were given.
12923
+ * @param ip - The client address.
12924
+ * @param userAgent - The `User-Agent` header.
12925
+ * @returns The auth result.
12926
+ */
12927
+ private openSession;
12928
+ /**
12929
+ * Validates and spends the `state` of a callback.
12930
+ *
12931
+ * The state must be bound to this browser by the `oauth_state` cookie, must exist (and is
12932
+ * deleted as it is read), must parse, and must name the provider the callback names.
12933
+ *
12934
+ * @param provider - The provider named by the callback path.
12935
+ * @param state - The `state` query value.
12936
+ * @param stateCookie - The `oauth_state` cookie value, or `undefined` when none was sent.
12937
+ * @returns The stored record of the flow.
12938
+ * @throws `AuthException(OAUTH_FAILED)` for a state that is unbound, missing, unparseable,
12939
+ * malformed or minted for another provider.
12940
+ */
12941
+ private consumeState;
12942
+ /**
12943
+ * Reads and deletes the state record of a flow, in one step so it can be used once.
12944
+ *
12945
+ * @param provider - The provider named by the callback path, for the log lines.
12946
+ * @param state - The `state` query value.
12947
+ * @returns The stored record.
12948
+ * @throws `AuthException(OAUTH_FAILED)` for a state that is missing, unparseable or malformed.
12949
+ */
12950
+ private readState;
12951
+ /**
12952
+ * Exchanges the authorization code and fetches the provider's profile.
12953
+ *
12954
+ * @param plugin - The provider plugin.
12955
+ * @param provider - Its name, for the log line.
12956
+ * @param code - The authorization code.
12957
+ * @param codeVerifier - The PKCE verifier stored with the state.
12958
+ * @returns The normalized profile.
12959
+ * @throws `AuthException(OAUTH_FAILED)` when the exchange or the fetch fails.
12960
+ */
12961
+ private fetchProfile;
12962
+ /**
12963
+ * Provisions a new account from a verified OAuth profile.
12964
+ *
12965
+ * @param provider - The provider name.
12966
+ * @param tenantId - The tenant the flow resolved to.
12967
+ * @param profile - The provider's profile.
12968
+ * @returns The created account.
12969
+ * @throws `AuthException(OAUTH_EMAIL_MISMATCH)` when the address already belongs to an account.
12970
+ */
12971
+ private createAccount;
12972
+ /**
12973
+ * Links the OAuth identity to the account the flow already found.
12974
+ *
12975
+ * @param provider - The provider name.
12976
+ * @param profile - The provider's profile.
12977
+ * @param existingAuthUser - The account to link, or `null` when there is none.
12978
+ * @returns The account re-read after linking.
12979
+ * @throws `AuthException(OAUTH_FAILED)` when there is no account to link or it cannot be re-read.
12980
+ */
12981
+ private linkAccount;
12982
+ /**
12983
+ * Carries out the account strategy the `onOAuthLogin` hook chose.
12984
+ *
12985
+ * Under `registration: 'invitation-only'` a `create` is allowed only for a flow that carries a
12986
+ * vetted invitation; linking and signing in an existing account are not sign-ups.
12987
+ *
12988
+ * @param flow - What the callback resolved: the provider, the tenant, the verified profile, the
12989
+ * hook's decision and the account already linked to this identity, or `null`.
12990
+ * @param invitation - The invitation the flow carries, or `null`.
12991
+ * @returns The account the flow signs in.
12992
+ * @throws `AuthException` for a rejected flow, a closed registration, a `link` with no account
12993
+ * to link, or a create that collides with an existing address.
12994
+ */
12995
+ private resolveAccount;
12996
+ /**
12997
+ * Vets the invitation a flow was started with against the provider's profile.
12998
+ *
12999
+ * @param record - The consumed state record.
13000
+ * @param profile - The provider's profile.
13001
+ * @returns What completes the invitation once the account is known, or `null` for a flow that
13002
+ * carries none.
13003
+ * @throws `AuthException(INVALID_INVITATION_TOKEN)` when workspaces are not enabled, and the
13004
+ * refusals of `WorkspaceInvitationAcceptService.prepareOAuth` otherwise.
13005
+ */
13006
+ private vetInvitation;
13007
+ /**
13008
+ * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
13009
+ *
13010
+ * Validates the `provider` format against `/^[a-z0-9-]{1,64}$/` before the
13011
+ * registry lookup. This ensures that a malformed or oversized provider name
13012
+ * (e.g. path traversal characters, null bytes) is explicitly rejected rather
13013
+ * than silently failing the `find()` with a format-dependent miss.
13014
+ *
13015
+ * @param provider - Plugin name to look up.
13016
+ * @returns The matching plugin.
13017
+ * @throws `AuthException(OAUTH_FAILED)` when the name is invalid or no plugin matches.
13018
+ */
13019
+ private resolvePlugin;
13020
+ }
13021
+
13022
+ /**
13023
+ * Describes a thrown value in one line, with known values stripped out of the channel's own words.
13024
+ *
13025
+ * For failures where **nothing that must be withheld was rendered into the message**. There the
13026
+ * relay's explanation is the diagnosis, and the values worth naming — a recipient address, say —
13027
+ * appear the way this library wrote them, where redaction reaches them. Each piece is redacted,
13028
+ * joined, length-capped and passed through {@link logSafe}, because text that came back from a
13029
+ * remote is untrusted input and a CR/LF in it would forge a second log record.
13030
+ *
13031
+ * **When the message DID render something to withhold, use {@link describeChannelStatus} instead.**
10780
13032
  * Redaction cannot save that case: a relay may quote the body it rejected in transfer encoding
10781
13033
  * rather than verbatim, and base64 defeats substring matching outright.
10782
13034
  *
@@ -11455,5 +13707,571 @@ declare class ApiKeyService {
11455
13707
  private validatedExpiry;
11456
13708
  }
11457
13709
 
11458
- export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11459
- export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, RequestEncodingPolicy, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };
13710
+ /**
13711
+ * @fileoverview `@WorkspaceRoles(...)`: the workspace roles a route accepts.
13712
+ *
13713
+ * @layer Decorator
13714
+ */
13715
+
13716
+ /** Metadata key under which {@link WorkspaceRoles} stores the accepted roles. */
13717
+ declare const WORKSPACE_ROLES_KEY = "workspaceRoles";
13718
+ /**
13719
+ * Declares which roles may call a route, judged in the workspace the request names.
13720
+ *
13721
+ * A role is matched through `workspaces.roles.hierarchy`, so a role that includes another passes
13722
+ * wherever the included one does. `ANY_WORKSPACE_MEMBER` accepts every active member.
13723
+ *
13724
+ * `WorkspaceGuard` refuses a route that carries no declaration, and an empty list counts as none:
13725
+ * a guard that waved an undeclared route through would turn a forgotten decorator into open access.
13726
+ *
13727
+ * @param roles - The accepted roles, or the any-member marker.
13728
+ * @returns A method and class decorator.
13729
+ */
13730
+ declare const WorkspaceRoles: (...roles: Array<string | typeof ANY_WORKSPACE_MEMBER>) => MethodDecorator & ClassDecorator;
13731
+
13732
+ /**
13733
+ * @fileoverview `@WorkspacePermission(action)`: a route accepts the roles `workspaces.permissions`
13734
+ * names for an action.
13735
+ *
13736
+ * @layer Decorator
13737
+ */
13738
+
13739
+ /** Metadata key under which {@link WorkspacePermission} stores the action. */
13740
+ declare const WORKSPACE_PERMISSION_KEY = "workspacePermission";
13741
+ /** A workspace-level action whose roles the host configures in `workspaces.permissions`. */
13742
+ type WorkspaceAction = keyof WorkspacePermissionOptions;
13743
+ /**
13744
+ * Declares that a route accepts the roles configured for an action, judged in the workspace the
13745
+ * request names.
13746
+ *
13747
+ * The roles are read from `workspaces.permissions` when the request arrives, so a host that
13748
+ * changes who may manage members changes every route that declares that action. It is the
13749
+ * alternative to `@WorkspaceRoles(...)`: one target declares one of the two, and a target that
13750
+ * declares both is refused as undeclared, because the guard cannot know which one was meant.
13751
+ *
13752
+ * @param action - The action the route performs.
13753
+ * @returns A method and class decorator.
13754
+ */
13755
+ declare const WorkspacePermission: (action: WorkspaceAction) => MethodDecorator & ClassDecorator;
13756
+
13757
+ /**
13758
+ * @fileoverview `@AllowPendingWorkspace()`: lets a route run for the owner of a workspace that is
13759
+ * pending deletion.
13760
+ *
13761
+ * @layer Decorator
13762
+ */
13763
+ /** Metadata key under which {@link AllowPendingWorkspace} marks a route. */
13764
+ declare const ALLOW_PENDING_WORKSPACE_KEY = "allowPendingWorkspace";
13765
+ /**
13766
+ * Admits the owner of a workspace pending deletion to this route.
13767
+ *
13768
+ * Every other route refuses that owner with `409 auth.workspace_pending_deletion`, so a client can
13769
+ * offer to restore the workspace, and refuses everyone else with the `404` any other refusal gets.
13770
+ * Put this on the restore route and nowhere else: a route that runs while a workspace is waiting
13771
+ * to be deleted can act on data that is about to go. The route-inventory spec lists the routes that
13772
+ * carry it, so adding it elsewhere is a red test and not a quiet change.
13773
+ *
13774
+ * @returns A method and class decorator.
13775
+ */
13776
+ declare const AllowPendingWorkspace: () => MethodDecorator & ClassDecorator;
13777
+
13778
+ /**
13779
+ * @fileoverview `@CurrentWsWorkspace()`: the workspace a socket message was admitted to.
13780
+ *
13781
+ * @layer Decorator
13782
+ */
13783
+ /**
13784
+ * Injects the workspace `WsWorkspaceGuard` admitted THIS message to.
13785
+ *
13786
+ * A gateway handler takes its workspace from here and never from the message body: the guard is the
13787
+ * only place that checked the caller may act in it. It is per message, not per connection, so two
13788
+ * messages in flight on one socket each see their own. Throws when the handler runs without
13789
+ * `WsWorkspaceGuard`, since an id read from anywhere else would be unchecked.
13790
+ */
13791
+ declare const CurrentWsWorkspace: (...dataOrPipes: unknown[]) => ParameterDecorator;
13792
+
13793
+ /**
13794
+ * @fileoverview Names scoped to a workspace: the keys, rooms and prefixes a host builds for
13795
+ * storage, cache, sockets and queues, encoded so two workspaces can never share one.
13796
+ *
13797
+ * @layer Utility
13798
+ */
13799
+ /**
13800
+ * Builds the name of something that belongs to one workspace.
13801
+ *
13802
+ * Each of the tenant, the workspace and the parts is written as its length in UTF-8 bytes, a colon
13803
+ * and the text, and the pieces are concatenated: `workspaceScopedName('t1', 'w1', 'room')` is
13804
+ * `2:t12:w14:room`. A length-prefixed piece is self-delimiting, so no text a part holds, a colon, a
13805
+ * slash, digits or the shape of another name, can move the boundary between two pieces: two
13806
+ * different arguments never produce one name, by construction. {@link decodeWorkspaceScopedName}
13807
+ * is its inverse.
13808
+ *
13809
+ * A part may be empty and may hold any character except a C0 control, DEL or an unpaired
13810
+ * surrogate; those are refused because the name ends up in Redis keys, socket rooms and object
13811
+ * keys, several storage backends reject or mangle controls, and an unpaired surrogate has no UTF-8
13812
+ * form of its own, so two different strings would write the same bytes. The tenant and the workspace must be non-empty.
13813
+ *
13814
+ * @param tenantId - The tenant, from the verified token.
13815
+ * @param workspaceId - The workspace, checked against the caller's membership.
13816
+ * @param parts - What follows, such as a resource kind and an id.
13817
+ * @returns The name.
13818
+ * @throws {TypeError} For a part that is not a string, an empty tenant or workspace, or a part
13819
+ * holding a C0 control, DEL or an unpaired surrogate.
13820
+ */
13821
+ declare function workspaceScopedName(tenantId: string, workspaceId: string, ...parts: string[]): string;
13822
+ /**
13823
+ * Reads a name built by {@link workspaceScopedName} back into the tenant, the workspace and the
13824
+ * parts it was built from.
13825
+ *
13826
+ * @param name - A name.
13827
+ * @returns The tenant, the workspace and the parts, in order.
13828
+ * @throws {TypeError} For anything {@link workspaceScopedName} cannot have produced: a length that
13829
+ * is not canonical, one that runs past the end or inside a character, text after the last piece,
13830
+ * or fewer than two pieces.
13831
+ */
13832
+ declare function decodeWorkspaceScopedName(name: string): {
13833
+ tenantId: string;
13834
+ workspaceId: string;
13835
+ parts: string[];
13836
+ };
13837
+
13838
+ /**
13839
+ * @fileoverview Stamps the context a queued job carries.
13840
+ *
13841
+ * @layer Utility
13842
+ */
13843
+
13844
+ /**
13845
+ * Builds the context to put on a job from the workspace a guarded request resolved.
13846
+ *
13847
+ * @param workspace - What `@CurrentWorkspace()` returned.
13848
+ * @returns The tenant, the workspace and the account, and nothing else: the role is deliberately
13849
+ * not carried, because the worker asks again what the account may do now.
13850
+ */
13851
+ declare function stampJobContext(workspace: CurrentWorkspaceContext): WorkspaceJobContext;
13852
+
13853
+ /**
13854
+ * @fileoverview The signed-in caller of a workspace route: loading the account behind the token and
13855
+ * re-proving who is at the keyboard before a destructive change.
13856
+ *
13857
+ * @layer Service
13858
+ */
13859
+
13860
+ /** Loads the account behind a verified dashboard token, and re-proves it before a destructive change. */
13861
+ declare class WorkspaceCallerService {
13862
+ private readonly users;
13863
+ private readonly reauthentication;
13864
+ constructor(users: IUserRepository, reauthentication: ReauthenticationService);
13865
+ /**
13866
+ * Loads the account the token names, without its credentials.
13867
+ *
13868
+ * @param caller - The verified token's subject and tenant.
13869
+ * @returns The account.
13870
+ * @throws {AuthException} `auth.token_invalid` when the account no longer exists.
13871
+ */
13872
+ load(caller: Pick<DashboardJwtPayload, 'sub' | 'tenantId'>): Promise<SafeAuthUser>;
13873
+ /**
13874
+ * Re-proves the caller by their password, or by a recent sign-in when the account has none.
13875
+ *
13876
+ * Counted by the same lockout as a login, so a stolen token cannot guess the password here
13877
+ * without limit. Run it AFTER the checks that decide whether the caller may act at all: a caller
13878
+ * who may not must be refused before they can spend a key derivation or a lockout attempt.
13879
+ *
13880
+ * @param caller - The verified token's subject and tenant.
13881
+ * @param password - The password the caller submitted, if any.
13882
+ * @throws {AuthException} `auth.token_invalid` when the account no longer exists,
13883
+ * `auth.invalid_credentials` for a missing or wrong password, `auth.account_locked` at the
13884
+ * lockout ceiling, `auth.reauthentication_required` for a passwordless account with no recent
13885
+ * sign-in.
13886
+ */
13887
+ reauthenticate(caller: Pick<DashboardJwtPayload, 'sub' | 'tenantId'>, password: string | undefined): Promise<void>;
13888
+ private find;
13889
+ }
13890
+
13891
+ /**
13892
+ * @fileoverview The workspace lifecycle: create, rename, schedule and finalize deletion, restore,
13893
+ * switch and read the caller's access.
13894
+ *
13895
+ * @layer Service
13896
+ */
13897
+
13898
+ /** What scheduling a deletion produced. */
13899
+ interface ScheduledDeletion {
13900
+ /** `deleted` when the grace period is `0` and the workspace was finalized at once. */
13901
+ status: 'pending_deletion' | 'deleted';
13902
+ /** When the deletion becomes final, or `null` when it already is. */
13903
+ deletionScheduledAt: Date | null;
13904
+ }
13905
+ /** Why {@link WorkspaceService.finalizeDeletion} did not finalize. */
13906
+ type FinalizeResult = 'deleted' | 'not_found' | 'not_pending' | 'not_due';
13907
+ /** A workspace and the caller's role in it. */
13908
+ interface WorkspaceAccessView {
13909
+ workspace: AuthWorkspace;
13910
+ role: string;
13911
+ }
13912
+ /**
13913
+ * Owns the life of a workspace.
13914
+ *
13915
+ * Every change is written by the repository together with its audit event, in one transaction. The
13916
+ * service then ends the access the change affects by bumping the cache version, and only after that
13917
+ * hands the event to the host's hook, so a failed bump surfaces as an error and a change is never
13918
+ * reported as done while stale access could still be served.
13919
+ *
13920
+ * The writes a member's role authorized (rename, scheduling a deletion, restore) hand the repository
13921
+ * the role the guard resolved for the actor, and the repository checks it in the write's own
13922
+ * transaction; an actor demoted between the guard and the write is answered
13923
+ * `auth.insufficient_workspace_role` and nothing changes. The writes no role authorized are creation
13924
+ * (any identity may create its own workspace), finalizing a deletion (a host job) and switching (it
13925
+ * records a preference, and a stale pointer is harmless because the guard re-checks membership on
13926
+ * every request).
13927
+ */
13928
+ declare class WorkspaceService {
13929
+ private readonly workspaces;
13930
+ private readonly memberships;
13931
+ private readonly access;
13932
+ private readonly events;
13933
+ private readonly hooks;
13934
+ private readonly group;
13935
+ constructor(workspaces: IWorkspaceRepository, memberships: IMembershipRepository, access: WorkspaceAccessService, events: WorkspaceEventsService, hooks: IAuthHooks, options: ResolvedOptions);
13936
+ /**
13937
+ * Creates a workspace owned by the caller.
13938
+ *
13939
+ * Checks, in order, `workspaces.allowCreate`, the per-user limit and `beforeWorkspaceCreate`,
13940
+ * then writes the workspace and the owner membership atomically. The limit check here is
13941
+ * advisory under concurrency; the repository receives the limit and may enforce it exactly.
13942
+ *
13943
+ * @param user - The identity creating it; the workspace lives in its tenant.
13944
+ * @param data - The requested name.
13945
+ * @param context - Request metadata for the hooks.
13946
+ * @returns The created workspace.
13947
+ * @throws {AuthException} `auth.validation` for a bad name, `auth.forbidden` when creation is
13948
+ * not allowed, `auth.workspace_limit_reached` at the limit.
13949
+ */
13950
+ create(user: SafeAuthUser, data: {
13951
+ name: unknown;
13952
+ }, context: HookContext): Promise<AuthWorkspace>;
13953
+ /**
13954
+ * Renames a workspace.
13955
+ *
13956
+ * @param ref - The workspace.
13957
+ * @param rawName - The new name.
13958
+ * @param actor - Who renames it, with the role the guard resolved for them; the repository checks
13959
+ * in the write's own transaction that they still hold it.
13960
+ * @param context - Request metadata for the hook.
13961
+ * @throws {AuthException} `auth.validation` for a bad name, `auth.workspace_not_found` when the
13962
+ * workspace does not exist, `auth.insufficient_workspace_role` when the actor's role changed.
13963
+ */
13964
+ rename(ref: WorkspaceRef, rawName: unknown, actor: WorkspaceActor, context: HookContext): Promise<void>;
13965
+ /**
13966
+ * Schedules a workspace for deletion, ending every member's access at once.
13967
+ *
13968
+ * With `workspaces.deletionGraceDays` of `0` the workspace is deleted immediately instead.
13969
+ *
13970
+ * @param ref - The workspace.
13971
+ * @param actor - Who deletes it, with the role the guard resolved for them.
13972
+ * @param context - Request metadata for the hook.
13973
+ * @returns The resulting status and when the deletion becomes final.
13974
+ * @throws {AuthException} `auth.workspace_not_found`, or `auth.workspace_pending_deletion` when
13975
+ * it was already scheduled.
13976
+ */
13977
+ scheduleDeletion(ref: WorkspaceRef, actor: WorkspaceActor, context: HookContext): Promise<ScheduledDeletion>;
13978
+ /**
13979
+ * Undoes a scheduled deletion while the grace period has not elapsed.
13980
+ *
13981
+ * @param ref - The workspace.
13982
+ * @param actor - Who restores it, with the role the guard resolved for them.
13983
+ * @param context - Request metadata for the hook.
13984
+ * @throws {AuthException} `auth.workspace_not_found` when the workspace is not pending deletion
13985
+ * or its grace period is over.
13986
+ */
13987
+ restore(ref: WorkspaceRef, actor: WorkspaceActor, context: HookContext): Promise<void>;
13988
+ /**
13989
+ * Marks a workspace deleted once its grace period is over. A host job calls it; purging the
13990
+ * workspace's data is the host's work.
13991
+ *
13992
+ * @param ref - The workspace.
13993
+ * @param context - Request metadata for the hook; the job has none, so a minimal one is used.
13994
+ * @returns `deleted`, or why nothing changed.
13995
+ */
13996
+ finalizeDeletion(ref: WorkspaceRef, context?: HookContext): Promise<FinalizeResult>;
13997
+ /**
13998
+ * Records the workspace a member switched to and reports the switch.
13999
+ *
14000
+ * Nothing about the session changes: the token carries no workspace.
14001
+ *
14002
+ * @param ref - The workspace.
14003
+ * @param userId - The member.
14004
+ * @param context - Request metadata for the hook.
14005
+ * @returns The member's access.
14006
+ * @throws {AuthException} `auth.workspace_not_found` when the caller is not an active member.
14007
+ */
14008
+ switchTo(ref: WorkspaceRef, userId: string, context: HookContext): Promise<ResolvedWorkspaceMember>;
14009
+ /**
14010
+ * Reads a workspace and the caller's role in it.
14011
+ *
14012
+ * @param ref - The workspace.
14013
+ * @param userId - The caller.
14014
+ * @returns The workspace and the caller's role.
14015
+ * @throws {AuthException} `auth.workspace_not_found` when the caller is not an active member.
14016
+ */
14017
+ getAccess(ref: WorkspaceRef, userId: string): Promise<WorkspaceAccessView>;
14018
+ private assertMayCreate;
14019
+ /**
14020
+ * Turns a status write's outcome into an error, or ends every member's access to the workspace.
14021
+ *
14022
+ * A refused write throws; a successful one bumps the workspace version so no cached answer
14023
+ * outlives the change. A bump that fails throws too: the change is never reported as done.
14024
+ */
14025
+ private settle;
14026
+ }
14027
+
14028
+ /**
14029
+ * @fileoverview The workspace operations a route runs as a sequence: each one orders its checks and
14030
+ * its write, so the controller only delegates.
14031
+ *
14032
+ * @layer Service
14033
+ */
14034
+
14035
+ /** The verified token of the caller: who they are and the tenant they belong to. */
14036
+ type Caller = Pick<DashboardJwtPayload, 'sub' | 'tenantId'>;
14037
+ /** What a hand-over of ownership names: the receiver, the role the giver keeps, and the giver's proof. */
14038
+ interface HandOver {
14039
+ /** The member who becomes an owner. */
14040
+ toUserId: string;
14041
+ /** The role the giver keeps, or `null` to keep both as owners. */
14042
+ keeps: string | null;
14043
+ /** The giver's password, if they submitted one. */
14044
+ password: string | undefined;
14045
+ }
14046
+ /**
14047
+ * Runs the workspace operations that need more than one step.
14048
+ *
14049
+ * Each method fixes the order of its steps, which is part of what it guarantees: a caller is
14050
+ * re-proved only after the guard has decided they may act, and before the write.
14051
+ */
14052
+ declare class WorkspaceActionsService {
14053
+ private readonly workspaces;
14054
+ private readonly memberships;
14055
+ private readonly callers;
14056
+ constructor(workspaces: WorkspaceService, memberships: MembershipService, callers: WorkspaceCallerService);
14057
+ /**
14058
+ * Creates a workspace owned by the caller.
14059
+ *
14060
+ * @param caller - The verified token's subject and tenant.
14061
+ * @param name - The requested name.
14062
+ * @param context - Request metadata for the hooks.
14063
+ * @returns The created workspace.
14064
+ * @throws {AuthException} `auth.token_invalid` when the account no longer exists, then whatever
14065
+ * {@link WorkspaceService.create} refuses.
14066
+ */
14067
+ create(caller: Caller, name: string, context: HookContext): Promise<AuthWorkspace>;
14068
+ /**
14069
+ * Renames a workspace and reads it back.
14070
+ *
14071
+ * @param ref - The workspace.
14072
+ * @param actor - Who renames it, with the role the guard resolved for them.
14073
+ * @param name - The new name.
14074
+ * @param context - Request metadata for the hook.
14075
+ * @returns The workspace as it now reads.
14076
+ */
14077
+ rename(ref: WorkspaceRef, actor: WorkspaceActor, name: string, context: HookContext): Promise<AuthWorkspace>;
14078
+ /**
14079
+ * Re-proves the caller, then schedules the workspace's deletion.
14080
+ *
14081
+ * Nothing is looked up or spent for a caller the guard has not admitted: this runs after it. An
14082
+ * account that fails the proof schedules nothing.
14083
+ *
14084
+ * @param ref - The workspace.
14085
+ * @param actor - Who deletes it, with the role the guard resolved for them.
14086
+ * @param caller - The verified token's subject and tenant, whose proof is checked.
14087
+ * @param password - The password the caller submitted, if any.
14088
+ * @param context - Request metadata for the hook.
14089
+ * @throws {AuthException} The re-proof's refusals, then whatever
14090
+ * {@link WorkspaceService.scheduleDeletion} refuses.
14091
+ */
14092
+ scheduleDeletion(ref: WorkspaceRef, actor: WorkspaceActor, caller: Caller, password: string | undefined, context: HookContext): Promise<void>;
14093
+ /**
14094
+ * Changes a member's role and reads the membership back.
14095
+ *
14096
+ * @param ref - The workspace.
14097
+ * @param userId - The member whose role changes.
14098
+ * @param role - The role to give.
14099
+ * @param actor - Who changes it, with the role the guard resolved for them.
14100
+ * @param context - Request metadata for the hook.
14101
+ * @returns The membership as it now stands.
14102
+ */
14103
+ changeRole(ref: WorkspaceRef, userId: string, role: string, actor: WorkspaceActor, context: HookContext): Promise<AuthMembership>;
14104
+ /**
14105
+ * Hands ownership to another member, running the checks from cheapest to costliest.
14106
+ *
14107
+ * Everything the request alone decides (only an owner may hand it over, not to oneself, the role
14108
+ * the giver keeps must exist), then that the receiver is an active member, is checked first, so a caller who cannot succeed cannot spend a key
14109
+ * derivation or a lockout attempt. Then the caller is re-proved, then the write is made.
14110
+ *
14111
+ * @param ref - The workspace.
14112
+ * @param actor - The member handing ownership over, with the role the guard resolved for them.
14113
+ * @param caller - The verified token's subject and tenant, whose proof is checked.
14114
+ * @param handOver - The receiver, the role the giver keeps and the giver's password.
14115
+ * @param context - Request metadata for the hook.
14116
+ * @throws {AuthException} The local checks' refusals, the re-proof's refusals, then whatever
14117
+ * {@link MembershipService.transferOwnership} refuses.
14118
+ */
14119
+ transferOwnership(ref: WorkspaceRef, actor: WorkspaceActor, caller: Caller, handOver: HandOver, context: HookContext): Promise<void>;
14120
+ }
14121
+
14122
+ /**
14123
+ * @fileoverview Orders and pages a workspace's pending invitations.
14124
+ *
14125
+ * @layer Utility
14126
+ */
14127
+
14128
+ /** One page of invitations and where the next one starts. */
14129
+ interface InvitationPage {
14130
+ /** The invitations of this page, oldest first. */
14131
+ items: WorkspaceInvitationView[];
14132
+ /** Pass it back as the cursor for the next page; `null` on the last one. */
14133
+ nextCursor: string | null;
14134
+ }
14135
+
14136
+ /**
14137
+ * @fileoverview Workspace invitations: invite an address, list the pending ones, resend, revoke,
14138
+ * and let a token holder preview what it is for.
14139
+ *
14140
+ * @layer Service
14141
+ */
14142
+
14143
+ /**
14144
+ * Issues and withdraws workspace invitations.
14145
+ *
14146
+ * A token is 32 random bytes and only its SHA-256 is stored, so a resend mints a new token and
14147
+ * retires the old one. One address has one live invitation per workspace; inviting it again is a
14148
+ * resend and is held to the resend limits. The role ceiling is the member ceiling: a member who is
14149
+ * not the owner invites only to a role strictly below their own, and acts only on invitations to
14150
+ * such roles. An invitation the actor may not act on reads as absent, so the routes confirm
14151
+ * nothing about it.
14152
+ */
14153
+ declare class WorkspaceInvitationService {
14154
+ private readonly store;
14155
+ private readonly redis;
14156
+ private readonly members;
14157
+ private readonly events;
14158
+ private readonly users;
14159
+ private readonly workspaces;
14160
+ private readonly memberships;
14161
+ private readonly email;
14162
+ private readonly group;
14163
+ private readonly hmacKey;
14164
+ constructor(store: WorkspaceInvitationStore, redis: AuthRedisService, members: MembershipService, events: WorkspaceEventsService, users: IUserRepository, workspaces: IWorkspaceRepository, memberships: IMembershipRepository, email: IEmailProvider, options: ResolvedOptions);
14165
+ /**
14166
+ * Refuses to boot when the configured email provider cannot deliver a workspace invitation.
14167
+ *
14168
+ * @throws When the provider implements no `sendWorkspaceInvitation`.
14169
+ */
14170
+ onModuleInit(): void;
14171
+ /**
14172
+ * Invites an address to a workspace, or resends to one already invited.
14173
+ *
14174
+ * @param ref - The workspace.
14175
+ * @param actor - Who invites, with the role the guard resolved for them.
14176
+ * @param rawEmail - The invitee.
14177
+ * @param role - The role the invitation grants.
14178
+ * @param context - Request metadata for the hook.
14179
+ * @throws {AuthException} `auth.validation` for a role outside the hierarchy,
14180
+ * `auth.insufficient_workspace_role` above the actor's ceiling, `auth.already_member` for an
14181
+ * address that already has a membership, in any status, `auth.too_many_requests` at a limit or when the address changed under the
14182
+ * call, `auth.workspace_not_found` when the workspace is gone.
14183
+ */
14184
+ invite(ref: WorkspaceRef, actor: WorkspaceActor, rawEmail: string, role: string, context: HookContext): Promise<void>;
14185
+ /**
14186
+ * Sends a pending invitation again under a new token.
14187
+ *
14188
+ * An address with no pending invitation, or one the actor may not act on, is answered like a
14189
+ * success and changes nothing.
14190
+ *
14191
+ * @param ref - The workspace.
14192
+ * @param actor - Who resends.
14193
+ * @param rawEmail - The invitee.
14194
+ * @param context - Request metadata for the hook.
14195
+ * @throws {AuthException} `auth.too_many_requests` inside the cooldown, past the resend limit, or
14196
+ * when the address changed under the call.
14197
+ */
14198
+ resend(ref: WorkspaceRef, actor: WorkspaceActor, rawEmail: string, context: HookContext): Promise<void>;
14199
+ /**
14200
+ * Withdraws a pending invitation. An address with none, or one the actor may not act on, is
14201
+ * answered like a success and changes nothing.
14202
+ *
14203
+ * @param ref - The workspace.
14204
+ * @param actor - Who revokes.
14205
+ * @param rawEmail - The invitee.
14206
+ * @param context - Request metadata for the hook.
14207
+ */
14208
+ revoke(ref: WorkspaceRef, actor: WorkspaceActor, rawEmail: string, context: HookContext): Promise<void>;
14209
+ /**
14210
+ * Lists the workspace's pending invitations, oldest first.
14211
+ *
14212
+ * @param ref - The workspace.
14213
+ * @param page - The cursor and size.
14214
+ * @returns One page.
14215
+ */
14216
+ list(ref: WorkspaceRef, page: {
14217
+ cursor?: string;
14218
+ limit?: number;
14219
+ }): Promise<InvitationPage>;
14220
+ /**
14221
+ * Tells a token holder what the token is for, without signing in.
14222
+ *
14223
+ * Every token that cannot be previewed, whether it never existed, expired, was consumed, or names
14224
+ * a workspace or inviter that is gone, is answered with the same error after the same repository
14225
+ * reads: a stand-in lookup runs where the real one is missing, so neither the body nor the work
14226
+ * done separates one case from another.
14227
+ *
14228
+ * @param token - The raw token.
14229
+ * @returns What the invitation is for.
14230
+ * @throws {AuthException} `auth.invalid_invitation_token` for any token that cannot be previewed.
14231
+ */
14232
+ preview(token: string): Promise<WorkspaceInvitationPreview>;
14233
+ /**
14234
+ * Invites an address to own a workspace that does not exist yet, on behalf of the platform.
14235
+ *
14236
+ * There is no route for it: the platform plane's authorization is the host's. The workspace and
14237
+ * its owner membership are created when the invitation is accepted, under the id returned here.
14238
+ * Each call is its own invitation to its own workspace; nothing is replaced.
14239
+ *
14240
+ * @param params - The tenant, the invitee, the workspace's name, and the inviter's display name
14241
+ * for the message (it is not stored).
14242
+ * @param context - Request metadata for the hook.
14243
+ * @returns The id the workspace will be created with.
14244
+ * @throws {AuthException} `auth.validation` for an unusable workspace name.
14245
+ */
14246
+ inviteAsPlatform(params: {
14247
+ tenantId: string;
14248
+ email: string;
14249
+ workspaceName: string;
14250
+ inviterName: string;
14251
+ }, context: HookContext): Promise<{
14252
+ workspaceId: string;
14253
+ }>;
14254
+ /**
14255
+ * Withdraws a platform bootstrap invitation. An address with none, or with an ordinary member
14256
+ * invitation, is answered like a success and changes nothing.
14257
+ *
14258
+ * @param ref - The workspace id `inviteAsPlatform` returned.
14259
+ * @param rawEmail - The invitee.
14260
+ * @param context - Request metadata for the hook.
14261
+ */
14262
+ revokeAsPlatform(ref: WorkspaceRef, rawEmail: string, context: HookContext): Promise<void>;
14263
+ /** Counts one invitation against the inviter's hour, refusing the twenty-first. */
14264
+ private takeInviterSlot;
14265
+ /** Refuses to replace an invitation the actor may not act on, or one sent too recently or often. */
14266
+ private assertMayReissue;
14267
+ /** Refuses an address that already has a membership of the workspace; returns its account. */
14268
+ private assertNotMember;
14269
+ /** Mints a token, stores its record, retires the one it replaces, and mails it. */
14270
+ private issue;
14271
+ /** Mails the token. A failure is re-thrown without its text, which can quote the token. */
14272
+ private deliver;
14273
+ private activeWorkspace;
14274
+ }
14275
+
14276
+ export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspaceScopedName };
14277
+ export type { AcceptedInvitation, AcceptedSignup, ActingMember, ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthMembership, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthWorkspace, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BeforeWorkspaceCreateResult, BootstrapInvitationRecord, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ChangeMembershipRoleParams, ClientIpSource, CookieAuthResponse, CountOwnedParams, CreateMembershipParams, CreateMembershipResult, CreateSessionParams, CreateUserData, CreateWithOAuthData, CreateWorkspaceResult, CreateWorkspaceWithOwnerParams, CurrentWorkspaceContext, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FinalizeResult, FindUserByEmailParams, FindUserByOAuthIdParams, GuardedWriteResult, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IMembershipRepository, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, IWorkspaceRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LastActiveWorkspaceRef, LinkOAuthParams, ListMembershipsForUserParams, ListMembershipsForWorkspaceParams, ListSessionsParams, ListSoleOwnedParams, LiveSessionParams, MemberChangeResult, MemberInvitationRecord, MembershipPage, MembershipRef, MembershipStatus, MembershipWithWorkspace, MfaChallengeResult, MfaSetupResult, MfaTempPayload, MyWorkspaces, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, RegistrationMode, RemoveMembershipParams, RenameWorkspaceParams, RenameWorkspaceResult, RequestEncodingPolicy, ResolvedOptions, ResolvedWorkspaceMember, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, ScheduledDeletion, SessionAlertInfo, SessionInfo, SetLastActiveWorkspaceParams, SignupRequest, StoredWorkspaceInvitation, TenantResolverRequest, TenantScopedUserRef, TransferOwnershipParams, TransferOwnershipResult, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, UpdateWorkspaceStatusParams, UpdateWorkspaceStatusResult, VerifiedAccessToken, VerifiedWorkspaceAccessToken, VerifyAccessTokenOptions, WorkspaceAccess, WorkspaceAccessView, WorkspaceAction, WorkspaceActor, WorkspaceAuditEvent, WorkspaceCheck, WorkspaceInvitationPreview, WorkspaceInvitationView, WorkspaceInviteData, WorkspaceJobContext, WorkspaceOptions, WorkspacePermissionOptions, WorkspaceRef, WorkspaceRequest, WorkspaceRoleList, WorkspaceStatus, WsTicketSnapshot };