@bymax-one/nest-auth 1.4.22 → 1.5.1

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.
package/CHANGELOG.md CHANGED
@@ -18,6 +18,252 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.1] - 2026-11-11
22
+
23
+ A patch release for workspaces: it adds the way to remove an account's memberships before the host deletes
24
+ the account, fixes a wrong-account list in a tab that hears a broadcast, makes the shared contract valid for
25
+ a strict parser, and measures the frontend bundle. **One required port method is added: read the first
26
+ note below.**
27
+
28
+ ### Apply to a derived backend
29
+
30
+ - **`IMembershipRepository` gains a REQUIRED method, `removeAllForUser`: every implementer must add
31
+ it.** It removes every membership of an account, in every membership status (active or suspended)
32
+ and in every workspace status, in one transaction, persisting one `member.removed` audit row per
33
+ removal, and answers the removed `{ workspaceId, role }` list. In the same transaction it applies the
34
+ last-owner rule: when the account is the only active owner of a workspace that is not
35
+ `pending_deletion` or `deleted`, it removes nothing, writes no audit row and answers `{ result:
36
+ 'last_owner', workspaceIds }`. It is required, not optional, because `listForUser` lists only the
37
+ active memberships of active workspaces, so a fallback built on it would silently leave the suspended
38
+ memberships and the memberships in other workspaces behind. A host that does not enable workspaces
39
+ implements nothing.
40
+ - **Call `MembershipService.removeAllForUser(tenantId, userId, actorUserId, context)` before you
41
+ delete or anonymise a user.** The library never deletes a user, and until now the membership rows of
42
+ a deleted user stayed behind: they still showed in `listForWorkspace`, a deleted owner still counted,
43
+ and a workspace whose only owner was deleted was never seen as orphaned. The call refuses with `409 auth.last_owner` and
44
+ `details.workspaces` (`{ id, name, status }`, at most 100; `{ id }` alone for one the repository found
45
+ during the write) while the account is the only owner of an active or suspended workspace, so you can
46
+ transfer ownership or schedule the workspace's deletion first. A workspace pending deletion does not block, because no one can finalize
47
+ it before its grace period ends: the owner's membership there is removed, the workspace can no longer
48
+ be restored, and your finalize job deletes it when the grace period ends. If a cache bump fails after
49
+ the commit it throws `MembershipBumpFailedError` with `removed` and `failed`; repeating the call
50
+ removes nothing, so drop the access of each `failed` entry with
51
+ `WorkspaceAccessService.invalidateMembership`.
52
+ - **The shared wire contract is at version 4, and its bytes changed.** The new section
53
+ `workspaceAccountRemoval` holds the rules and the blocking vectors, and the `workspaceScopedName`
54
+ refusal vector for an unpaired surrogate now carries `unpairedSurrogateCodeUnits: [55296]` (one more
55
+ final part, built from those UTF-16 code units) instead of a lone surrogate escape, which a parser
56
+ that builds well-formed strings, `serde_json` among them, rejects, so the sibling library lost the
57
+ whole file. Every string in `conformance/` is now held to well-formed Unicode by a test. The
58
+ contract's sha256 is `1e4c38e1741c21e639e4099cd33ece9b04518cf69699fb39fd9d5b9d37352edd`; a copy kept
59
+ by another library is refreshed from `conformance/wire-contract.json`, and a library that reads the
60
+ vector builds the lone surrogate itself.
61
+ - **`AUTH_WORKSPACE_ROUTES` is exported from `./shared`,** as the README and the specification already
62
+ said it was; before, it was reachable only as `AUTH_ROUTES.workspaces`.
63
+ - **A frontend that uses no workspace ships less.** `createAuthClient` imports its own route groups
64
+ instead of the aggregate `AUTH_ROUTES`, which kept every route family, the 16 workspace routes among
65
+ them, in the bundle. Measured with the same minified, tree-shaken minimal import: `createAuthClient`
66
+ is **3.12 KiB** brotli, against 3.45 KiB in 1.5.0 and **3.57 KiB in 1.4.22**. The 1.5.0 note that
67
+ said "from 3.82 to 3.45" was wrong about the starting point: 1.4.22 measures 3.57, so the 1.4.22 to
68
+ 1.5.0 change is 3.57 to 3.45, and `AuthProvider` plus `useSession` 1.26 to 1.13 KiB stands.
69
+
70
+ ### Added
71
+
72
+ - **`MembershipService.removeAllForUser` and `MembershipBumpFailedError`,** described above, with the
73
+ port method `IMembershipRepository.removeAllForUser` and its types (`RemoveAllMembershipsParams`,
74
+ `RemoveAllMembershipsResult`, `RemovedMembership`, `AccountRemovalAudit`).
75
+ - **A "Deleting an account" section in the README** and §22.3a in the technical specification.
76
+
77
+ ### Fixed
78
+
79
+ - **A tab whose session still named the previous account no longer shows the new account's workspaces
80
+ after a broadcast.** After another tab changed the signed-in account, the tab reloaded the list with
81
+ the browser's cookie, which already belonged to the new account, and showed it under the old
82
+ identity until the session revalidated. A broadcast now revalidates the session first and reloads the
83
+ list only when the account is unchanged; when it changed, the account change loads the new account's
84
+ list. A signed-out tab still makes no request. A revalidation that fails with an error other than an
85
+ expired session ends the tab's session view, as every revalidation of the auth provider already does.
86
+ - **The shared contract can be read by a strict parser:** see the contract note above.
87
+ - **The README states where a workspace invitation token travels:** in a POST body on the API routes;
88
+ the one use of a query string is the OAuth sign-in start, `GET /oauth/:provider?workspaceInvitation=`,
89
+ which stores only the token's sha256 and answers with `Referrer-Policy: no-referrer`.
90
+
91
+ ### Maintenance
92
+
93
+ Repository tooling; nothing changes for a host. The weekly cold mutation job runs as four shards of two
94
+ workers each on the shared sharded workflow, after a run at four workers lost its runner twice; the
95
+ size budgets of the two auth surfaces are tightened to the measured size plus about 5% (client 3.3 KiB,
96
+ react 1.2 KiB) and the react workspace surface and entry are 2.5 and 3.6 KiB.
97
+
98
+ ## [1.5.0] - 2026-11-11
99
+
100
+ **Workspaces.** One identity can now hold a role in each of many workspaces inside a tenant,
101
+ and switch between them without signing in again. The feature is **off by default**: a host that
102
+ does not set `workspaces.enabled` registers nothing new and is asked for nothing. This is a minor
103
+ release that carries a large additive surface and a few behaviour changes, each listed below with
104
+ what to do about it.
105
+
106
+ ### Apply to a derived backend
107
+
108
+ - **Workspaces are opt-in; nothing changes until you enable them.** To use them, set
109
+ `workspaces: { enabled: true, roles: { hierarchy, ownerRole } }`, provide the two repositories
110
+ (`BYMAX_AUTH_WORKSPACE_REPOSITORY` and `BYMAX_AUTH_MEMBERSHIP_REPOSITORY`, implementing
111
+ `IWorkspaceRepository` and `IMembershipRepository`), and turn on `controllers.workspaces`
112
+ (and `controllers.workspaceInvitations`, which also needs an email provider that implements the new
113
+ optional `sendWorkspaceInvitation`). The module refuses to start with a flag on and a piece
114
+ missing. The README has a Workspaces section and the technical specification has §5.6 and §22.
115
+ - **The shared Redis contract is now at version 3.** The new key prefixes are `wsv`, `wmv`, `wm`
116
+ (membership cache and its version counters), `winv`, `winvidx`, `winvset`, `winvrl` (invitations,
117
+ their per-address index, the pending set and the per-inviter rate) and `wad`, `wads` (the
118
+ `access.denied` window and its suppressed count), each specified in
119
+ `conformance/wire-contract.json`. The contract's sha256 changes with it, so a copy
120
+ kept by another library is refreshed from that file.
121
+ - **`access.denied` now fires, only when workspaces are enabled.** A refused workspace access on a
122
+ route, in stream verification or on a socket message reaches `onWorkspaceEvent`, bounded per account
123
+ by `workspaces.accessDeniedEvents` (default 10 events per 60 s; the denials past the bound are
124
+ counted and the count is carried on the next event as `suppressedCount`). The event carries the
125
+ public `code`, a host-only `reason` (`not_member`, `pending_deletion` or `insufficient_role`) and
126
+ the `surface`. The access decision is never affected by the bound.
127
+ - **A host hook that throws synchronously no longer fails a completed flow.** `afterRegister`,
128
+ `afterLogin`, `afterEmailVerified`, `afterMfaEnabled`, `afterMfaDisabled`,
129
+ `afterMfaRecoveryCodesRegenerated`, `afterPasswordReset`, `onNewSession` and `onSessionEvicted`
130
+ now run detached, so a hook that throws after `register`, `login`, the password-less token path,
131
+ `verifyEmail`, an MFA enable or disable, a recovery-code regeneration or a password reset leaves the
132
+ flow's result alone. A throwing `onSessionEvicted` no longer fails `createSession`, and a throwing
133
+ `onNewSession` is logged as `onNewSession hook threw` rather than as a failed `findById`. The three
134
+ MFA hooks now log a failure, a rejection included, where they used to swallow it with no trace. A host that relied on a throwing one of these hooks to abort a flow can no longer do so.
135
+ - **Accepting a workspace invitation through OAuth does not complete it for an account with a second
136
+ factor.** The callback answers the MFA challenge as for any OAuth sign-in, the invitation stays
137
+ pending and unspent, and it is not resumed after the challenge. The signed-in caller accepts it with
138
+ `POST /workspaces/invitations/accept` and the same token, so a host whose members use MFA should
139
+ send the token again from its accept page after sign-in. Binding the invitation to the MFA temp
140
+ token is not part of this release.
141
+ - **`registration: 'invitation-only'` is enforced.** It was refused at startup; it now closes
142
+ `POST /register` with `403 auth.registration_closed`, and does the same to the OAuth `create` action
143
+ unless the flow carries a vetted invitation. Startup refuses the mode only when workspaces and tenant
144
+ invitations are both disabled.
145
+ - **The frontend entries are tree-shakeable, and the workspace pieces are separate.** A bundler now
146
+ drops what a frontend does not import from `./shared`, `./client`, `./react` and `./nextjs`
147
+ (previously every import shipped the whole entry). Measured with a minified, tree-shaken minimal
148
+ import: `createAuthClient` went from 3.82 to 3.45 KiB brotli and `AuthProvider` plus `useSession`
149
+ from 1.26 to 1.13 KiB. `createWorkspaceClient`, `<WorkspaceProvider>` and `useWorkspaces()` add to a
150
+ bundle only when imported (+0.64 and +1.24 KiB over those two). No API change to what existed.
151
+ - **Length bounds on user text now count Unicode code points everywhere, as the validation pipe
152
+ already did.** The service-side checks counted UTF-16 units, so an emoji counted twice. Four
153
+ checks changed: the workspace name, the workspace id, the API key label, and the password floor
154
+ (`password.minLength`, default 15). Only the password floor can newly refuse an existing
155
+ caller: a password made of characters outside the Basic Multilingual Plane that met the floor by
156
+ units can now be refused, **when it is set or changed** (registration, reset, change, invitation
157
+ acceptance). Existing hashes and logins are unaffected, because the floor is never applied at
158
+ login. A workspace name of exactly its bound in emoji, which the pipe accepted and the service
159
+ refused, is now accepted. Tokens, one-time codes and the other checks that never hold user text
160
+ keep counting units.
161
+
162
+ ### Added
163
+
164
+ - **The workspace layer.** The ports a host implements, `IWorkspaceRepository` and
165
+ `IMembershipRepository`, name the whole key (tenant, workspace and member) on every method, and every
166
+ mutating method persists its audit event in the same transaction as the change. `createWithOwner`
167
+ receives the effective `workspaces.maxWorkspacesPerUser` and answers `limit_reached` (a host that
168
+ needs an exact cap enforces it inside the create transaction), and the membership port has
169
+ `countOwned` and `listSoleOwned`. The `workspaces` option group (`enabled`, `roles`, `permissions`,
170
+ `allowCreate`, `maxWorkspacesPerUser`, `invitationTtlSeconds`, `maxPendingInvitationsPerWorkspace`,
171
+ `membershipCacheTtlSeconds`, `deletionGraceDays`, `accessDeniedEvents`, `resolveRequestWorkspace`,
172
+ `resolveWsWorkspace`) is validated at startup, and so is the `registration` mode.
173
+ - **Workspace error codes and the membership cache.** Nine codes (`auth.workspace_required`,
174
+ `workspace_not_found`, `insufficient_workspace_role`, `last_owner`, `already_member`,
175
+ `invitation_email_mismatch`, `registration_closed`, `workspace_limit_reached`,
176
+ `workspace_pending_deletion`) in the server and shared catalogs. `WorkspaceAccessService` resolves an
177
+ active membership of an active workspace through a versioned Redis cache backed by the repositories;
178
+ a failed or unreachable Redis falls back to the repositories and never fails a request.
179
+ - **`WorkspaceGuard`, `@WorkspaceRoles(...)`, `@WorkspacePermission(...)`, `@AllowPendingWorkspace()`
180
+ and `@CurrentWorkspace()`.** A route authorizes in the workspace it names (a path parameter or the
181
+ host's resolver, never a body, query or header). A missing workspace, a non-member and an inactive
182
+ workspace answer an identical `404 auth.workspace_not_found`; a route that declares no roles is refused
183
+ `403`. A workspace pending deletion is reported to its owner only (`409
184
+ auth.workspace_pending_deletion`); everyone else gets the not-found. Mount the guard after
185
+ `JwtAuthGuard` and `UserStatusGuard`.
186
+ - **Workspace and membership services, and two hooks.** `WorkspaceService` (create, rename, schedule
187
+ deletion, restore, finalize deletion, switch), `MembershipService` (list, change role, remove,
188
+ leave, transfer ownership) and `WorkspaceEventsService`; `IAuthHooks.beforeWorkspaceCreate` (a refusal
189
+ is `403 auth.forbidden` with the reason) and `onWorkspaceEvent` (detached and best-effort; a throwing
190
+ hook never fails an operation, and the event is never logged). `finalizeDeletion` is for the host's
191
+ own job: the library does not schedule it.
192
+ - **The workspace routes, behind `controllers.workspaces: true`.** `GET /workspaces` and `POST
193
+ /workspaces`, `GET /workspaces/:workspaceId/access`, `POST .../switch`, `GET .../members`
194
+ (cursor-paginated where listing), `PATCH /workspaces/:workspaceId`, `POST .../schedule-deletion`
195
+ (the password is re-proved), `POST .../restore`, `PATCH` and `DELETE .../members/:userId`, `POST
196
+ .../leave` and `POST .../transfer-ownership` (the owner, re-proved). A caller who may not act is
197
+ refused before a password is checked or a lockout attempt is spent. The last owner cannot leave, be
198
+ removed or demote themselves (`409 auth.last_owner`). A switch records the caller's last active
199
+ workspace and changes no token.
200
+ - **Workspace invitations.** With `controllers.workspaceInvitations: true` the library serves `POST /workspaces/:workspaceId/invitations` (invite), `GET` on the same path (list), `.../invitations/resend`, `.../invitations/revoke` and the public `POST /workspaces/invitations/preview`. The flag requires `workspaces.enabled`, both workspace repositories and an email provider that implements the new optional `sendWorkspaceInvitation`; the module refuses to start without the method. A token is 32 random bytes and only its digest is stored, so a resend mints a new one and retires the old. A member who is not the owner invites only to a role strictly below their own. An address has one live invitation per workspace; inviting it again is a resend, held to a 60-second cooldown and five resends. One member issues at most 20 invitations an hour, and a workspace holds at most `workspaces.maxPendingInvitationsPerWorkspace` pending ones. The preview answers every token it cannot honour with the same `auth.invalid_invitation_token`. The Redis keyspace gains the prefixes `winv`, `winvidx`, `winvset` and `winvrl`, specified in the wire contract with test vectors.
201
+
202
+ - **Accepting a workspace invitation.** `POST /workspaces/invitations/accept` takes the signed-in account the invitation names, and `POST /workspaces/invitations/accept-signup` creates the account it was addressed to and signs it in. Both answer `workspaceId` and the `role` the caller actually holds. Everything that can be decided without spending the token is decided first, the membership is written next, and the token is spent only after that; an address that is not the invited one answers `auth.invitation_email_mismatch` and an unverified one `auth.email_not_verified`, each leaving the token usable. The stored record is now a union with a required `kind`: `member`, or `bootstrap` for an invitation the platform issues, through the new `WorkspaceInvitationService.inviteAsPlatform`, for the invitee to own a workspace that is created when they accept (`revokeAsPlatform` withdraws it). The preview answer is a union on the same `kind`, and a bootstrap one has no `inviterName`.
203
+
204
+ - **Accepting a workspace invitation through Google.** `GET /oauth/google?workspaceInvitation=<token>`
205
+ vets the invitation against the verified provider profile before the host's `onOAuthLogin` hook runs
206
+ (an account with a second factor gets the MFA challenge; see the note above).
207
+ - **Workspaces on sockets, streams and queued jobs.** `workspaceScopedName` and
208
+ `decodeWorkspaceScopedName` are an injective encoding for rooms, cache keys and storage prefixes (a
209
+ C0 control, DEL or an unpaired surrogate in a part is a `TypeError`).
210
+ `AuthTokenVerifierService.verifyAccessToken(token, { plane: 'dashboard', workspace: { workspaceId,
211
+ roles, allowPending } })` returns the caller's membership; `WsWorkspaceGuard` (with
212
+ `workspaces.resolveWsWorkspace`) guards a gateway handler per message; and
213
+ `WorkspaceAccessService.assertStillAuthorized`, `stampJobContext` and `WorkspaceJobContext` serve
214
+ queued jobs, whose check reads the account, the workspace and the membership live and costs three
215
+ repository reads. The server size budget is 169 KiB.
216
+ - **The browser half of workspaces.** `./shared`: the workspace types, which mirror the views the
217
+ server answers with key for key and type for type, and `fillRoute` / `pathSegment`, which build
218
+ request paths from caller-supplied values and refuse `.`, `..` and empty values (use them for
219
+ `sessions/:id` and `oauth/:provider` as well). `./client`: `createWorkspaceClient`, 19 typed workspace
220
+ calls (workspaces, members, ownership, invitations), separate from `createAuthClient`. `./react`:
221
+ `<WorkspaceProvider>` and `useWorkspaces()` with `onWorkspaceChanged`, `onWorkspaceAccessLost`, a role
222
+ hint and a cross-tab list sync; the provider stores the list, the chosen workspace and the last
223
+ active one with the account they were read for, and reads them only for that account.
224
+ `./nextjs`: `createWorkspaceAccessReader` for server components; `createAuthProxy` accepts
225
+ `lastWorkspaceCookie` and passes `getDefaultDashboard(role, { lastActiveWorkspaceId })`, and an inbound
226
+ `x-workspace-id` is stripped.
227
+ - **`conformance/openapi-operation-security.json`**, the per-operation security table, generated by
228
+ `pnpm gen:openapi-security` and checked on every test run. It is data for the sibling library's own
229
+ check, not behaviour; the wire contract and the OpenAPI request schemas cover the new routes.
230
+ - **Documentation:** the README and the technical specification describe workspaces, including the
231
+ decided limitation above.
232
+
233
+ ### Changed
234
+
235
+ - **A validation error no longer repeats an unknown request property it cannot safely name, on every route.** The pipe every controller mounts answered a body with an unknown key by naming the key in `details[].field` and in the message, so a 1000-character key made the answer as long as the key, and a key holding a control character put that character in the answer. An unknown key over 128 code points, holding a control character, or empty is now reported once under the field `body`, however many there are; a short key is still named, and every other failure is still reported by its own name. The status, the code (`auth.validation`) and the top-level message are unchanged. **Apply to a derived backend:** a client that read the name of such a key from `details[].field` now reads `body`; the contract's `errorEnvelope` row states the rule.
236
+
237
+ - **The `shared` subpath bundle budget goes from 4.75 KiB to 5 KiB brotli.** The two accept routes' names no longer fit under the old limit. It is checked in `scripts/check-size.mjs` and affects no consumer.
238
+
239
+ - **A password reset with no usable proof is refused as an invalid token before its password is judged.** `POST password/reset-password` now classifies the proof first, without spending it: more than one proof, none, or one the configured `passwordReset.method` does not accept answers `auth.password_reset_token_invalid` whatever the new password is. Before, such a request with a password under the policy floor answered `auth.validation`. The password is then judged, and the proof is spent last, as before, so a refused password still does not burn a single-use proof. A caller who holds no usable proof can no longer reach the password policy, and with it the breach screen, which is an outbound query when the host wires the bundled HIBP provider.
240
+
241
+ - **The server bundle budget is 169 KiB brotli.** It is checked in `scripts/check-size.mjs` and
242
+ affects no consumer; the frontend entries and the consumer surfaces have budgets of their own there.
243
+
244
+ ### Fixed
245
+
246
+ - **A refresh cookie over 2048 characters is refused with `400 auth.validation`.** The body value
247
+ already was; the cookie is now held to the same bound on the routes that read the refresh token,
248
+ in `cookie` and `both` delivery. The error names the field `refreshToken` and nothing is looked
249
+ up. Logout is the exception: it reads such a cookie as no token, answers 204 and clears the auth
250
+ cookies, so a browser holding one can sign out of it. No token this library mints is longer than
251
+ the bound, so only a forged or corrupted cookie is affected. An empty cookie is still treated as
252
+ no token.
253
+
254
+ - **A synchronous throw from `afterInvitationAccepted` no longer turns a completed signup into a server
255
+ error.**
256
+
257
+ ### Maintenance
258
+
259
+ Repository tooling and dependencies; nothing changes for a host. The 50-line limit on functions and
260
+ test bodies is gated against a shrink-only baseline (`pnpm check:function-length`), whose keys are
261
+ structured values; new double assertions through `unknown` are gated against a baseline; the API-key
262
+ option group moved out of the two largest option files; the contract-parity workflow compares the
263
+ request schemas and the operation security table with rust-auth, each under its own tracking issue;
264
+ `minimatch` (GHSA-g3hv-75wg-m249) is resolved for the development tooling, with `glob` 10 mapped to 13; a platform-MFA e2e no longer depends on the wall-clock TOTP
265
+ window; a snapshot pins every `description` and `summary` the OpenAPI fragment publishes (the invite and preview descriptions were the only unpinned ones); the mutation inventory has an exempt list of the specs that execute no source; development and CI dependency bumps.
266
+
21
267
  ## [1.4.22] - 2026-11-08
22
268
 
23
269
  ### Apply to a derived backend
@@ -4662,7 +4908,9 @@ ever installable.
4662
4908
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
4663
4909
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
4664
4910
 
4665
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.22...HEAD
4911
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.1...HEAD
4912
+ [1.5.1]: https://github.com/bymaxone/nest-auth/compare/v1.5.0...v1.5.1
4913
+ [1.5.0]: https://github.com/bymaxone/nest-auth/compare/v1.4.22...v1.5.0
4666
4914
  [1.4.22]: https://github.com/bymaxone/nest-auth/compare/v1.4.21...v1.4.22
4667
4915
  [1.4.21]: https://github.com/bymaxone/nest-auth/compare/v1.4.20...v1.4.21
4668
4916
  [1.4.20]: https://github.com/bymaxone/nest-auth/compare/v1.4.19...v1.4.20
package/README.md CHANGED
@@ -83,6 +83,7 @@ pnpm add @bymax-one/nest-auth
83
83
  - ✅ **Platform Admin Auth** — Separate token context and role hierarchy for super-admins
84
84
  - ✅ **User Invitations** — Invite users with role assignment and configurable expiration
85
85
  - ✅ **Role-Based Access Control** — Hierarchical roles with `@Roles()` decorator
86
+ - ✅ **Workspaces** — One identity with a role in each of many workspaces, switched without a login (see _Workspaces_ below)
86
87
 
87
88
  ### 🧩 Developer Experience
88
89
 
@@ -1435,6 +1436,236 @@ written to your repository in one batch. With **N instances** a key is written u
1435
1436
  per window instead of once, and a crash loses at most one window of `lastUsedAt`. The field is
1436
1437
  advisory: authorization never reads it.
1437
1438
 
1439
+ ## 🗂️ Workspaces (one identity, many workspaces)
1440
+
1441
+ For a product where one person belongs to several teams, each with its own role. The identity, its
1442
+ sessions and its tokens do not change: a workspace role is resolved on each request, for the
1443
+ workspace that request names, so switching workspace never needs a login and two workspaces can be
1444
+ open in two tabs at once. Workspaces live inside a tenant. Nothing is registered until you opt in.
1445
+
1446
+ ### Enable it
1447
+
1448
+ ```typescript
1449
+ import {
1450
+ BYMAX_AUTH_MEMBERSHIP_REPOSITORY,
1451
+ BYMAX_AUTH_WORKSPACE_REPOSITORY,
1452
+ BymaxAuthModule
1453
+ } from '@bymax-one/nest-auth'
1454
+
1455
+ BymaxAuthModule.registerAsync({
1456
+ useFactory: () => ({
1457
+ jwt: { secret: process.env.JWT_SECRET ?? '' },
1458
+ roles: { hierarchy: { ADMIN: ['MEMBER'], MEMBER: [] } },
1459
+ rateLimit: { clientIpSource: 'peer' },
1460
+ workspaces: {
1461
+ enabled: true,
1462
+ roles: {
1463
+ // Denormalized, like `roles.hierarchy`: each role lists every role it includes.
1464
+ hierarchy: { owner: ['admin', 'member'], admin: ['member'], member: [] },
1465
+ ownerRole: 'owner'
1466
+ }
1467
+ },
1468
+ controllers: { workspaces: true, workspaceInvitations: true }
1469
+ }),
1470
+ extraProviders: [
1471
+ // …BYMAX_AUTH_USER_REPOSITORY and BYMAX_AUTH_REDIS_CLIENT as usual
1472
+ { provide: BYMAX_AUTH_WORKSPACE_REPOSITORY, useClass: PrismaWorkspaceRepository },
1473
+ { provide: BYMAX_AUTH_MEMBERSHIP_REPOSITORY, useClass: PrismaMembershipRepository }
1474
+ ]
1475
+ })
1476
+ ```
1477
+
1478
+ `controllers.workspaces` mounts the routes and needs `workspaces.enabled` and both repositories.
1479
+ `controllers.workspaceInvitations` also needs an email provider that implements
1480
+ `sendWorkspaceInvitation`. The module refuses to boot when a piece is missing. With
1481
+ `workspaces.enabled: false`, the default, nothing in this section exists in your application.
1482
+
1483
+ You implement two ports: `IWorkspaceRepository` (`createWithOwner`, `findById`, `rename`,
1484
+ `updateStatus`) and `IMembershipRepository` (`find`, `listForUser`, `listForWorkspace`, `create`,
1485
+ `changeRole`, `remove`, `removeAllForUser`, `transferOwnership`, `countOwned`, `listSoleOwned`). Every call carries the
1486
+ tenant and the workspace. The writes that must not race (a role change, a removal, an ownership
1487
+ transfer) are guarded writes the repository answers atomically, so two requests cannot both remove
1488
+ the last owner.
1489
+
1490
+ ### Options
1491
+
1492
+ | Option | Default | Meaning |
1493
+ | ------------------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1494
+ | `roles.hierarchy`, `roles.ownerRole` | — (required) | The workspace role hierarchy, separate from `roles.hierarchy`. It must name the owner role, and the owner must include every other role. |
1495
+ | `permissions` | owner only | Which roles may `manageWorkspace` (rename), `deleteWorkspace` and `manageMembers`; `viewMembers` defaults to every active member. |
1496
+ | `allowCreate` | `true` | Whether an identity may create a workspace: a flag, or a function of the user. |
1497
+ | `maxWorkspacesPerUser` | `0` | Most workspaces one identity may own; `0` is unlimited. The check is advisory under concurrency; the repository's create call receives the value for an exact cap. |
1498
+ | `invitationTtlSeconds` | `604800` | How long an invitation stays valid. Up to `2592000`. |
1499
+ | `maxPendingInvitationsPerWorkspace` | `100` | Most pending invitations one workspace may hold. |
1500
+ | `membershipCacheTtlSeconds` | `60` | How long a resolved membership is cached; `0` always reads the repository. Up to `3600`. A host that changes memberships outside the library must invalidate or set `0`. |
1501
+ | `deletionGraceDays` | `14` | Days a deleted workspace can be restored; `0` deletes at once. |
1502
+ | `accessDeniedEvents` | `{ max: 10, windowSeconds: 60 }` | Bounds the `access.denied` events one account can cause. The access decision is never affected. |
1503
+ | `resolveRequestWorkspace` | the route | Reads the workspace from a request when the host does not carry it in the route. Never from the body. |
1504
+ | `resolveWsWorkspace` | `data.workspaceId` | Reads the workspace a socket message names, from the message body and nothing else. |
1505
+
1506
+ `registration: 'invitation-only'` closes sign-up except through an invitation for that exact address
1507
+ (password registration and the OAuth `create` action answer `403 auth.registration_closed`; the
1508
+ invitation accept routes stay open; existing accounts keep signing in). Startup refuses the mode when
1509
+ workspaces and tenant invitations are both disabled.
1510
+
1511
+ ### Protect a route
1512
+
1513
+ ```typescript
1514
+ @UseGuards(JwtAuthGuard, UserStatusGuard, WorkspaceGuard)
1515
+ @Controller('workspaces/:workspaceId/projects')
1516
+ export class ProjectsController {
1517
+ @Get()
1518
+ @WorkspaceRoles(ANY_WORKSPACE_MEMBER)
1519
+ list(@CurrentWorkspace() workspace: CurrentWorkspaceContext) {
1520
+ // workspace.tenantId, workspace.workspaceId, workspace.userId, workspace.role
1521
+ }
1522
+
1523
+ @Delete(':id')
1524
+ @WorkspaceRoles('admin')
1525
+ remove(@CurrentWorkspace() workspace: CurrentWorkspaceContext) {}
1526
+ }
1527
+ ```
1528
+
1529
+ `WorkspaceGuard` is default-deny. In order it: refuses a route that declares neither
1530
+ `@WorkspaceRoles(...)` nor `@WorkspacePermission(...)` (`403 auth.forbidden`, so a forgotten
1531
+ decorator closes the route); accepts only a dashboard token, never a platform one; takes the
1532
+ workspace from the route or `resolveRequestWorkspace`, never the body and never a remembered
1533
+ default; resolves the caller's membership with the tenant from the token; and checks the role through
1534
+ the hierarchy. A workspace that does not exist, one that is not active and one the caller does not
1535
+ belong to all answer `404 auth.workspace_not_found`, so the answer reveals nothing about which
1536
+ workspaces exist. An insufficient role answers `403 auth.insufficient_workspace_role`. The owner of a
1537
+ workspace pending deletion gets `409 auth.workspace_pending_deletion`, except on a route marked
1538
+ `@AllowPendingWorkspace()`. A service takes its workspace from `@CurrentWorkspace()` and never from a
1539
+ DTO or a query.
1540
+
1541
+ A transport with no guard in front of it uses the same decision: `WsWorkspaceGuard` and
1542
+ `@CurrentWsWorkspace()` for a gateway, `AuthTokenVerifierService.verifyAccessToken(token, { plane:
1543
+ 'dashboard', workspace })` for a stream, and `stampJobContext` with
1544
+ `WorkspaceAccessService.assertStillAuthorized` for a job that must re-check the caller before it
1545
+ writes. `workspaceScopedName` builds cache keys and room names that two workspaces cannot share.
1546
+
1547
+ ### Routes
1548
+
1549
+ With `controllers.workspaces: true`; every `:workspaceId` is a path segment, never a body field or a
1550
+ header.
1551
+
1552
+ | Route | Method | Meaning |
1553
+ | -------------------------------------------- | -------------- | ------------------------------------------------------------------ |
1554
+ | `workspaces` | GET / POST | The caller's workspaces and the last one they switched to / create |
1555
+ | `workspaces/:workspaceId/access` | GET | The workspace and the caller's role in it |
1556
+ | `workspaces/:workspaceId/switch` | POST | Record it as the last active one; no token changes |
1557
+ | `workspaces/:workspaceId` | PATCH | Rename |
1558
+ | `workspaces/:workspaceId/schedule-deletion` | POST | Schedule deletion, re-proving the caller with the password |
1559
+ | `workspaces/:workspaceId/restore` | POST | Undo it within the grace period |
1560
+ | `workspaces/:workspaceId/members` | GET | List members |
1561
+ | `workspaces/:workspaceId/members/:userId` | PATCH / DELETE | Change a role / remove a member |
1562
+ | `workspaces/:workspaceId/leave` | POST | Leave |
1563
+ | `workspaces/:workspaceId/transfer-ownership` | POST | Hand ownership over, re-proving the caller |
1564
+
1565
+ With `controllers.workspaceInvitations: true`: `POST` and `GET workspaces/:workspaceId/invitations`
1566
+ (invite, list pending), `POST .../invitations/resend` and `.../invitations/revoke`, and the
1567
+ token-based `POST workspaces/invitations/preview` (public), `.../accept` (the signed-in account the
1568
+ invitation was addressed to) and `.../accept-signup` (public, creates the account). On these routes
1569
+ the token travels in a POST body, never in a query string. The one exception is the OAuth sign-in
1570
+ start, `GET /oauth/:provider?workspaceInvitation=<token>`: it stores only the token's sha256 in the
1571
+ state record and answers with `Referrer-Policy: no-referrer`. On your accept page, put the token in
1572
+ the URL fragment and set `Referrer-Policy: no-referrer` there.
1573
+
1574
+ ### Hooks and events
1575
+
1576
+ `beforeWorkspaceCreate(user, { name }, context)` can refuse a creation. `onWorkspaceEvent(event,
1577
+ context)` receives, after the change has committed, `workspace.created`, `.renamed`,
1578
+ `.deletion_scheduled`, `.restored` and `.deleted`; `member.invited`, `invitation.resent`,
1579
+ `.revoked` and `.accepted`; `member.role_changed`, `.removed` and `.left`; `ownership.transferred`;
1580
+ `workspace.switched`; and `access.denied` (with the `surface`, the public `code` and a host-only
1581
+ `reason`). It is best-effort and informational: the repository's persisted audit row is the record.
1582
+
1583
+ ### Deleting an account
1584
+
1585
+ The library never deletes a user: `IUserRepository` has no delete. A host that deletes or anonymises
1586
+ a user row must remove that user's memberships first, or the rows stay behind, still count as
1587
+ members of their workspaces, and a deleted owner keeps a workspace from ever being seen as
1588
+ orphaned. Call `MembershipService.removeAllForUser(tenantId, userId, actorUserId, context)` before
1589
+ the delete. `actorUserId` is the account itself, an administrator, or `null` for a job.
1590
+
1591
+ It removes every membership of the account, in every membership status and every workspace, with one
1592
+ `member.removed` event per removal and the cached access of each dropped, so access ends at the next
1593
+ request. Only the repository can find them all (`listForUser` lists active memberships of active
1594
+ workspaces only), so it is one call on the membership port, `removeAllForUser`, which you implement
1595
+ in one transaction together with the audit rows.
1596
+
1597
+ - **It refuses while the account is the only owner of an active or suspended workspace:** `409
1598
+ auth.last_owner` with `details.workspaces` (`{ id, name, status }`, at most 100; `{ id }` alone for one the repository found during the write), and nothing is
1599
+ removed. Transfer ownership or schedule the workspace's deletion first.
1600
+ - **A workspace pending deletion does not block.** No one can finalize a pending deletion before
1601
+ its grace period ends, so an owner who scheduled one would otherwise be unable to delete their own
1602
+ account for the whole period. Their membership there is removed with the rest, the workspace can no
1603
+ longer be restored (restoring is owner-only), and your finalize job deletes it when the grace period
1604
+ ends.
1605
+ - **If a cache bump fails after the commit,** the call throws `MembershipBumpFailedError` with
1606
+ `removed` and `failed`. The removal is already committed, so calling it again removes nothing: drop
1607
+ the access of each entry of `failed` with `WorkspaceAccessService.invalidateMembership`, or wait out
1608
+ `membershipCacheTtlSeconds`.
1609
+
1610
+ ### Accepting an invitation through OAuth, and MFA
1611
+
1612
+ An OAuth flow started with a workspace invitation vets the invitation against the provider's profile
1613
+ before your `onOAuthLogin` hook runs, and completes it for the account that results. **When that
1614
+ account has a second factor, the library does not complete the invitation:** the callback answers the
1615
+ MFA challenge as it does for any OAuth sign-in, the invitation stays pending and unspent, and it is
1616
+ not resumed after the challenge. The signed-in caller accepts it with `POST
1617
+ workspaces/invitations/accept` and the same token, so a host whose members use MFA should send the
1618
+ token again from its accept page after sign-in.
1619
+
1620
+ ### Frontend
1621
+
1622
+ ```typescript
1623
+ // client — a separate factory, so a frontend that does not use workspaces does not ship it
1624
+ import { createWorkspaceClient } from '@bymax-one/nest-auth/client'
1625
+ const workspaces = createWorkspaceClient({ baseUrl: '/api' })
1626
+ ```
1627
+
1628
+ ```tsx
1629
+ // react — inside <AuthProvider>
1630
+ <WorkspaceProvider client={workspaces} activeWorkspaceId={params.workspaceId} hierarchy={...}>
1631
+ <App />
1632
+ </WorkspaceProvider>
1633
+ // const { memberships, activeWorkspace, switchWorkspace, hasWorkspaceRole, status } = useWorkspaces()
1634
+ ```
1635
+
1636
+ The active workspace is the URL's, else the one chosen with `switchWorkspace`, else the server's
1637
+ `lastActiveWorkspaceId`; never `localStorage`. The provider stores what it loads with the account it
1638
+ was read for, so a different account never reads another's list. `hasWorkspaceRole` is a hint for
1639
+ what to render and carries no authority; the server decides. `onWorkspaceChanged` and
1640
+ `onWorkspaceAccessLost` are options; call `handleWorkspaceError(workspaceId, error)` from your own
1641
+ catch to feed the latter. Other tabs reload their lists through a `BroadcastChannel`, and a tab that
1642
+ is signed out makes no request.
1643
+
1644
+ ```typescript
1645
+ // nextjs — a server-only reader for a /w/[workspaceId] layout, cached per request
1646
+ import { createWorkspaceAccessReader } from '@bymax-one/nest-auth/nextjs'
1647
+ export const getWorkspaceAccess = createWorkspaceAccessReader({ apiBase })
1648
+ // { workspace, role } for a 200; null for 403, 404 and 409, so call notFound()
1649
+ ```
1650
+
1651
+ `createAuthProxy` accepts `lastWorkspaceCookie`: set a cookie yourself after `listWorkspaces()`
1652
+ (`HttpOnly; Secure; SameSite=Lax`) and `getDefaultDashboard(role, hint)` receives
1653
+ `{ lastActiveWorkspaceId }` only when the cookie holds a UUID, `{}` otherwise. The library never
1654
+ writes the cookie and the value carries no authority; the layout's reader decides. The proxy strips
1655
+ an inbound `x-workspace-id` and never sets one. Path values go through `fillRoute` and `pathSegment`
1656
+ (`./shared`), which refuse an empty value, `.` and `..` and percent-encode the rest.
1657
+
1658
+ ### Threat model
1659
+
1660
+ A workspace id is never trusted from the body, a header or a stored default; the guard resolves it
1661
+ from the route and the membership from the repository. Non-members and nonexistent workspaces are
1662
+ indistinguishable. A platform token has no implicit bypass. Memberships are cached for
1663
+ `membershipCacheTtlSeconds` and read under version counters, so a stale value is never served after a
1664
+ change the library made. The host's rate limiting on guarded routes is what bounds a caller probing
1665
+ workspace ids.
1666
+
1667
+ ---
1668
+
1438
1669
  ## 🏗️ Architecture
1439
1670
 
1440
1671
  The package runs **inside** your NestJS application as a dynamic module — not as a separate service:
@@ -2069,9 +2300,17 @@ which of the three proofs is eligible depends on `passwordReset.method`, and an
2069
2300
  is refused with the same code a structural violation gets. That narrowing is declared with its
2070
2301
  own probes and is deliberately not something a client can generate against.
2071
2302
 
2072
- All three are development artifacts — they are not in the published tarball, and nothing reads
2303
+ Another file,
2304
+ [`openapi-operation-security.json`](./conformance/openapi-operation-security.json), maps every
2305
+ operation this library mounts (`METHOD /path`, relative to your route prefix) to the **kind** of
2306
+ credential it requires, with the meaning of each kind alongside. It is generated from the table the
2307
+ OpenAPI fragment is built from and the controllers' route metadata, regenerated by
2308
+ `pnpm gen:openapi-security`, and a spec fails when it differs. How a kind becomes a security
2309
+ requirement depends on your `tokenDelivery` and is not in the file.
2310
+
2311
+ These are development artifacts — they are not in the published tarball, and nothing reads
2073
2312
  them at runtime yet. They exist so the schemas are a function of the decorators rather than a
2074
- second description maintained by hand, and so the same file can be asserted from `rust-auth`.
2313
+ second description maintained by hand.
2075
2314
 
2076
2315
  ### Administrative operations — methods, deliberately not routes
2077
2316