@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.
package/CHANGELOG.md CHANGED
@@ -18,6 +18,175 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.0] - 2026-11-11
22
+
23
+ **Workspaces.** One identity can now hold a role in each of many workspaces inside a tenant,
24
+ and switch between them without signing in again. The feature is **off by default**: a host that
25
+ does not set `workspaces.enabled` registers nothing new and is asked for nothing. This is a minor
26
+ release that carries a large additive surface and a few behaviour changes, each listed below with
27
+ what to do about it.
28
+
29
+ ### Apply to a derived backend
30
+
31
+ - **Workspaces are opt-in; nothing changes until you enable them.** To use them, set
32
+ `workspaces: { enabled: true, roles: { hierarchy, ownerRole } }`, provide the two repositories
33
+ (`BYMAX_AUTH_WORKSPACE_REPOSITORY` and `BYMAX_AUTH_MEMBERSHIP_REPOSITORY`, implementing
34
+ `IWorkspaceRepository` and `IMembershipRepository`), and turn on `controllers.workspaces`
35
+ (and `controllers.workspaceInvitations`, which also needs an email provider that implements the new
36
+ optional `sendWorkspaceInvitation`). The module refuses to start with a flag on and a piece
37
+ missing. The README has a Workspaces section and the technical specification has §5.6 and §22.
38
+ - **The shared Redis contract is now at version 3.** The new key prefixes are `wsv`, `wmv`, `wm`
39
+ (membership cache and its version counters), `winv`, `winvidx`, `winvset`, `winvrl` (invitations,
40
+ their per-address index, the pending set and the per-inviter rate) and `wad`, `wads` (the
41
+ `access.denied` window and its suppressed count), each specified in
42
+ `conformance/wire-contract.json`. The contract's sha256 changes with it, so a copy
43
+ kept by another library is refreshed from that file.
44
+ - **`access.denied` now fires, only when workspaces are enabled.** A refused workspace access on a
45
+ route, in stream verification or on a socket message reaches `onWorkspaceEvent`, bounded per account
46
+ by `workspaces.accessDeniedEvents` (default 10 events per 60 s; the denials past the bound are
47
+ counted and the count is carried on the next event as `suppressedCount`). The event carries the
48
+ public `code`, a host-only `reason` (`not_member`, `pending_deletion` or `insufficient_role`) and
49
+ the `surface`. The access decision is never affected by the bound.
50
+ - **A host hook that throws synchronously no longer fails a completed flow.** `afterRegister`,
51
+ `afterLogin`, `afterEmailVerified`, `afterMfaEnabled`, `afterMfaDisabled`,
52
+ `afterMfaRecoveryCodesRegenerated`, `afterPasswordReset`, `onNewSession` and `onSessionEvicted`
53
+ now run detached, so a hook that throws after `register`, `login`, the password-less token path,
54
+ `verifyEmail`, an MFA enable or disable, a recovery-code regeneration or a password reset leaves the
55
+ flow's result alone. A throwing `onSessionEvicted` no longer fails `createSession`, and a throwing
56
+ `onNewSession` is logged as `onNewSession hook threw` rather than as a failed `findById`. The three
57
+ 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.
58
+ - **Accepting a workspace invitation through OAuth does not complete it for an account with a second
59
+ factor.** The callback answers the MFA challenge as for any OAuth sign-in, the invitation stays
60
+ pending and unspent, and it is not resumed after the challenge. The signed-in caller accepts it with
61
+ `POST /workspaces/invitations/accept` and the same token, so a host whose members use MFA should
62
+ send the token again from its accept page after sign-in. Binding the invitation to the MFA temp
63
+ token is not part of this release.
64
+ - **`registration: 'invitation-only'` is enforced.** It was refused at startup; it now closes
65
+ `POST /register` with `403 auth.registration_closed`, and does the same to the OAuth `create` action
66
+ unless the flow carries a vetted invitation. Startup refuses the mode only when workspaces and tenant
67
+ invitations are both disabled.
68
+ - **The frontend entries are tree-shakeable, and the workspace pieces are separate.** A bundler now
69
+ drops what a frontend does not import from `./shared`, `./client`, `./react` and `./nextjs`
70
+ (previously every import shipped the whole entry). Measured with a minified, tree-shaken minimal
71
+ import: `createAuthClient` went from 3.82 to 3.45 KiB brotli and `AuthProvider` plus `useSession`
72
+ from 1.26 to 1.13 KiB. `createWorkspaceClient`, `<WorkspaceProvider>` and `useWorkspaces()` add to a
73
+ bundle only when imported (+0.64 and +1.24 KiB over those two). No API change to what existed.
74
+ - **Length bounds on user text now count Unicode code points everywhere, as the validation pipe
75
+ already did.** The service-side checks counted UTF-16 units, so an emoji counted twice. Four
76
+ checks changed: the workspace name, the workspace id, the API key label, and the password floor
77
+ (`password.minLength`, default 15). Only the password floor can newly refuse an existing
78
+ caller: a password made of characters outside the Basic Multilingual Plane that met the floor by
79
+ units can now be refused, **when it is set or changed** (registration, reset, change, invitation
80
+ acceptance). Existing hashes and logins are unaffected, because the floor is never applied at
81
+ login. A workspace name of exactly its bound in emoji, which the pipe accepted and the service
82
+ refused, is now accepted. Tokens, one-time codes and the other checks that never hold user text
83
+ keep counting units.
84
+
85
+ ### Added
86
+
87
+ - **The workspace layer.** The ports a host implements, `IWorkspaceRepository` and
88
+ `IMembershipRepository`, name the whole key (tenant, workspace and member) on every method, and every
89
+ mutating method persists its audit event in the same transaction as the change. `createWithOwner`
90
+ receives the effective `workspaces.maxWorkspacesPerUser` and answers `limit_reached` (a host that
91
+ needs an exact cap enforces it inside the create transaction), and the membership port has
92
+ `countOwned` and `listSoleOwned`. The `workspaces` option group (`enabled`, `roles`, `permissions`,
93
+ `allowCreate`, `maxWorkspacesPerUser`, `invitationTtlSeconds`, `maxPendingInvitationsPerWorkspace`,
94
+ `membershipCacheTtlSeconds`, `deletionGraceDays`, `accessDeniedEvents`, `resolveRequestWorkspace`,
95
+ `resolveWsWorkspace`) is validated at startup, and so is the `registration` mode.
96
+ - **Workspace error codes and the membership cache.** Nine codes (`auth.workspace_required`,
97
+ `workspace_not_found`, `insufficient_workspace_role`, `last_owner`, `already_member`,
98
+ `invitation_email_mismatch`, `registration_closed`, `workspace_limit_reached`,
99
+ `workspace_pending_deletion`) in the server and shared catalogs. `WorkspaceAccessService` resolves an
100
+ active membership of an active workspace through a versioned Redis cache backed by the repositories;
101
+ a failed or unreachable Redis falls back to the repositories and never fails a request.
102
+ - **`WorkspaceGuard`, `@WorkspaceRoles(...)`, `@WorkspacePermission(...)`, `@AllowPendingWorkspace()`
103
+ and `@CurrentWorkspace()`.** A route authorizes in the workspace it names (a path parameter or the
104
+ host's resolver, never a body, query or header). A missing workspace, a non-member and an inactive
105
+ workspace answer an identical `404 auth.workspace_not_found`; a route that declares no roles is refused
106
+ `403`. A workspace pending deletion is reported to its owner only (`409
107
+ auth.workspace_pending_deletion`); everyone else gets the not-found. Mount the guard after
108
+ `JwtAuthGuard` and `UserStatusGuard`.
109
+ - **Workspace and membership services, and two hooks.** `WorkspaceService` (create, rename, schedule
110
+ deletion, restore, finalize deletion, switch), `MembershipService` (list, change role, remove,
111
+ leave, transfer ownership) and `WorkspaceEventsService`; `IAuthHooks.beforeWorkspaceCreate` (a refusal
112
+ is `403 auth.forbidden` with the reason) and `onWorkspaceEvent` (detached and best-effort; a throwing
113
+ hook never fails an operation, and the event is never logged). `finalizeDeletion` is for the host's
114
+ own job: the library does not schedule it.
115
+ - **The workspace routes, behind `controllers.workspaces: true`.** `GET /workspaces` and `POST
116
+ /workspaces`, `GET /workspaces/:workspaceId/access`, `POST .../switch`, `GET .../members`
117
+ (cursor-paginated where listing), `PATCH /workspaces/:workspaceId`, `POST .../schedule-deletion`
118
+ (the password is re-proved), `POST .../restore`, `PATCH` and `DELETE .../members/:userId`, `POST
119
+ .../leave` and `POST .../transfer-ownership` (the owner, re-proved). A caller who may not act is
120
+ refused before a password is checked or a lockout attempt is spent. The last owner cannot leave, be
121
+ removed or demote themselves (`409 auth.last_owner`). A switch records the caller's last active
122
+ workspace and changes no token.
123
+ - **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.
124
+
125
+ - **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`.
126
+
127
+ - **Accepting a workspace invitation through Google.** `GET /oauth/google?workspaceInvitation=<token>`
128
+ vets the invitation against the verified provider profile before the host's `onOAuthLogin` hook runs
129
+ (an account with a second factor gets the MFA challenge; see the note above).
130
+ - **Workspaces on sockets, streams and queued jobs.** `workspaceScopedName` and
131
+ `decodeWorkspaceScopedName` are an injective encoding for rooms, cache keys and storage prefixes (a
132
+ C0 control, DEL or an unpaired surrogate in a part is a `TypeError`).
133
+ `AuthTokenVerifierService.verifyAccessToken(token, { plane: 'dashboard', workspace: { workspaceId,
134
+ roles, allowPending } })` returns the caller's membership; `WsWorkspaceGuard` (with
135
+ `workspaces.resolveWsWorkspace`) guards a gateway handler per message; and
136
+ `WorkspaceAccessService.assertStillAuthorized`, `stampJobContext` and `WorkspaceJobContext` serve
137
+ queued jobs, whose check reads the account, the workspace and the membership live and costs three
138
+ repository reads. The server size budget is 169 KiB.
139
+ - **The browser half of workspaces.** `./shared`: the workspace types, which mirror the views the
140
+ server answers with key for key and type for type, and `fillRoute` / `pathSegment`, which build
141
+ request paths from caller-supplied values and refuse `.`, `..` and empty values (use them for
142
+ `sessions/:id` and `oauth/:provider` as well). `./client`: `createWorkspaceClient`, 19 typed workspace
143
+ calls (workspaces, members, ownership, invitations), separate from `createAuthClient`. `./react`:
144
+ `<WorkspaceProvider>` and `useWorkspaces()` with `onWorkspaceChanged`, `onWorkspaceAccessLost`, a role
145
+ hint and a cross-tab list sync; the provider stores the list, the chosen workspace and the last
146
+ active one with the account they were read for, and reads them only for that account.
147
+ `./nextjs`: `createWorkspaceAccessReader` for server components; `createAuthProxy` accepts
148
+ `lastWorkspaceCookie` and passes `getDefaultDashboard(role, { lastActiveWorkspaceId })`, and an inbound
149
+ `x-workspace-id` is stripped.
150
+ - **`conformance/openapi-operation-security.json`**, the per-operation security table, generated by
151
+ `pnpm gen:openapi-security` and checked on every test run. It is data for the sibling library's own
152
+ check, not behaviour; the wire contract and the OpenAPI request schemas cover the new routes.
153
+ - **Documentation:** the README and the technical specification describe workspaces, including the
154
+ decided limitation above.
155
+
156
+ ### Changed
157
+
158
+ - **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.
159
+
160
+ - **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.
161
+
162
+ - **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.
163
+
164
+ - **The server bundle budget is 169 KiB brotli.** It is checked in `scripts/check-size.mjs` and
165
+ affects no consumer; the frontend entries and the consumer surfaces have budgets of their own there.
166
+
167
+ ### Fixed
168
+
169
+ - **A refresh cookie over 2048 characters is refused with `400 auth.validation`.** The body value
170
+ already was; the cookie is now held to the same bound on the routes that read the refresh token,
171
+ in `cookie` and `both` delivery. The error names the field `refreshToken` and nothing is looked
172
+ up. Logout is the exception: it reads such a cookie as no token, answers 204 and clears the auth
173
+ cookies, so a browser holding one can sign out of it. No token this library mints is longer than
174
+ the bound, so only a forged or corrupted cookie is affected. An empty cookie is still treated as
175
+ no token.
176
+
177
+ - **A synchronous throw from `afterInvitationAccepted` no longer turns a completed signup into a server
178
+ error.**
179
+
180
+ ### Maintenance
181
+
182
+ Repository tooling and dependencies; nothing changes for a host. The 50-line limit on functions and
183
+ test bodies is gated against a shrink-only baseline (`pnpm check:function-length`), whose keys are
184
+ structured values; new double assertions through `unknown` are gated against a baseline; the API-key
185
+ option group moved out of the two largest option files; the contract-parity workflow compares the
186
+ request schemas and the operation security table with rust-auth, each under its own tracking issue;
187
+ `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
188
+ 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.
189
+
21
190
  ## [1.4.22] - 2026-11-08
22
191
 
23
192
  ### Apply to a derived backend
@@ -4662,7 +4831,8 @@ ever installable.
4662
4831
  - 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
4832
  - 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
4833
 
4665
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.22...HEAD
4834
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.0...HEAD
4835
+ [1.5.0]: https://github.com/bymaxone/nest-auth/compare/v1.4.22...v1.5.0
4666
4836
  [1.4.22]: https://github.com/bymaxone/nest-auth/compare/v1.4.21...v1.4.22
4667
4837
  [1.4.21]: https://github.com/bymaxone/nest-auth/compare/v1.4.20...v1.4.21
4668
4838
  [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,207 @@ 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`, `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). The token travels
1569
+ in a POST body, never in a query string; put it in the URL fragment on your accept page and set
1570
+ `Referrer-Policy: no-referrer` there.
1571
+
1572
+ ### Hooks and events
1573
+
1574
+ `beforeWorkspaceCreate(user, { name }, context)` can refuse a creation. `onWorkspaceEvent(event,
1575
+ context)` receives, after the change has committed, `workspace.created`, `.renamed`,
1576
+ `.deletion_scheduled`, `.restored` and `.deleted`; `member.invited`, `invitation.resent`,
1577
+ `.revoked` and `.accepted`; `member.role_changed`, `.removed` and `.left`; `ownership.transferred`;
1578
+ `workspace.switched`; and `access.denied` (with the `surface`, the public `code` and a host-only
1579
+ `reason`). It is best-effort and informational: the repository's persisted audit row is the record.
1580
+
1581
+ ### Accepting an invitation through OAuth, and MFA
1582
+
1583
+ An OAuth flow started with a workspace invitation vets the invitation against the provider's profile
1584
+ before your `onOAuthLogin` hook runs, and completes it for the account that results. **When that
1585
+ account has a second factor, the library does not complete the invitation:** the callback answers the
1586
+ MFA challenge as it does for any OAuth sign-in, the invitation stays pending and unspent, and it is
1587
+ not resumed after the challenge. The signed-in caller accepts it with `POST
1588
+ workspaces/invitations/accept` and the same token, so a host whose members use MFA should send the
1589
+ token again from its accept page after sign-in.
1590
+
1591
+ ### Frontend
1592
+
1593
+ ```typescript
1594
+ // client — a separate factory, so a frontend that does not use workspaces does not ship it
1595
+ import { createWorkspaceClient } from '@bymax-one/nest-auth/client'
1596
+ const workspaces = createWorkspaceClient({ baseUrl: '/api' })
1597
+ ```
1598
+
1599
+ ```tsx
1600
+ // react — inside <AuthProvider>
1601
+ <WorkspaceProvider client={workspaces} activeWorkspaceId={params.workspaceId} hierarchy={...}>
1602
+ <App />
1603
+ </WorkspaceProvider>
1604
+ // const { memberships, activeWorkspace, switchWorkspace, hasWorkspaceRole, status } = useWorkspaces()
1605
+ ```
1606
+
1607
+ The active workspace is the URL's, else the one chosen with `switchWorkspace`, else the server's
1608
+ `lastActiveWorkspaceId`; never `localStorage`. The provider stores what it loads with the account it
1609
+ was read for, so a different account never reads another's list. `hasWorkspaceRole` is a hint for
1610
+ what to render and carries no authority; the server decides. `onWorkspaceChanged` and
1611
+ `onWorkspaceAccessLost` are options; call `handleWorkspaceError(workspaceId, error)` from your own
1612
+ catch to feed the latter. Other tabs reload their lists through a `BroadcastChannel`, and a tab that
1613
+ is signed out makes no request.
1614
+
1615
+ ```typescript
1616
+ // nextjs — a server-only reader for a /w/[workspaceId] layout, cached per request
1617
+ import { createWorkspaceAccessReader } from '@bymax-one/nest-auth/nextjs'
1618
+ export const getWorkspaceAccess = createWorkspaceAccessReader({ apiBase })
1619
+ // { workspace, role } for a 200; null for 403, 404 and 409, so call notFound()
1620
+ ```
1621
+
1622
+ `createAuthProxy` accepts `lastWorkspaceCookie`: set a cookie yourself after `listWorkspaces()`
1623
+ (`HttpOnly; Secure; SameSite=Lax`) and `getDefaultDashboard(role, hint)` receives
1624
+ `{ lastActiveWorkspaceId }` only when the cookie holds a UUID, `{}` otherwise. The library never
1625
+ writes the cookie and the value carries no authority; the layout's reader decides. The proxy strips
1626
+ an inbound `x-workspace-id` and never sets one. Path values go through `fillRoute` and `pathSegment`
1627
+ (`./shared`), which refuse an empty value, `.` and `..` and percent-encode the rest.
1628
+
1629
+ ### Threat model
1630
+
1631
+ A workspace id is never trusted from the body, a header or a stored default; the guard resolves it
1632
+ from the route and the membership from the repository. Non-members and nonexistent workspaces are
1633
+ indistinguishable. A platform token has no implicit bypass. Memberships are cached for
1634
+ `membershipCacheTtlSeconds` and read under version counters, so a stale value is never served after a
1635
+ change the library made. The host's rate limiting on guarded routes is what bounds a caller probing
1636
+ workspace ids.
1637
+
1638
+ ---
1639
+
1438
1640
  ## 🏗️ Architecture
1439
1641
 
1440
1642
  The package runs **inside** your NestJS application as a dynamic module — not as a separate service:
@@ -2069,9 +2271,17 @@ which of the three proofs is eligible depends on `passwordReset.method`, and an
2069
2271
  is refused with the same code a structural violation gets. That narrowing is declared with its
2070
2272
  own probes and is deliberately not something a client can generate against.
2071
2273
 
2072
- All three are development artifacts — they are not in the published tarball, and nothing reads
2274
+ Another file,
2275
+ [`openapi-operation-security.json`](./conformance/openapi-operation-security.json), maps every
2276
+ operation this library mounts (`METHOD /path`, relative to your route prefix) to the **kind** of
2277
+ credential it requires, with the meaning of each kind alongside. It is generated from the table the
2278
+ OpenAPI fragment is built from and the controllers' route metadata, regenerated by
2279
+ `pnpm gen:openapi-security`, and a spec fails when it differs. How a kind becomes a security
2280
+ requirement depends on your `tokenDelivery` and is not in the file.
2281
+
2282
+ These are development artifacts — they are not in the published tarball, and nothing reads
2073
2283
  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`.
2284
+ second description maintained by hand.
2075
2285
 
2076
2286
  ### Administrative operations — methods, deliberately not routes
2077
2287