@lenne.tech/nest-server 11.42.1 → 11.42.3
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/.claude/rules/configurable-features.md +3 -2
- package/.claude/rules/role-system.md +31 -3
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +5 -0
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +43 -0
- package/dist/core/common/helpers/graphql-ws-connection.helper.js +219 -0
- package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -0
- package/dist/core/common/helpers/graphql-ws-context.helper.d.ts +2 -1
- package/dist/core/common/helpers/graphql-ws-context.helper.js +54 -18
- package/dist/core/common/helpers/graphql-ws-context.helper.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/modules/auth/services/core-auth.service.d.ts +1 -0
- package/dist/core/modules/auth/services/core-auth.service.js +19 -0
- package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.d.ts +2 -1
- package/dist/core/modules/better-auth/better-auth.config.js +27 -1
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.js +4 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.d.ts +2 -0
- package/dist/core/modules/tenant/core-tenant.guard.js +20 -8
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core/modules/tus/core-tus.controller.js +2 -2
- package/dist/core/modules/tus/core-tus.controller.js.map +1 -1
- package/dist/core/modules/tus/core-tus.service.d.ts +1 -0
- package/dist/core/modules/tus/core-tus.service.js +39 -0
- package/dist/core/modules/tus/core-tus.service.js.map +1 -1
- package/dist/core/modules/user/core-user.service.js +11 -6
- package/dist/core/modules/user/core-user.service.js.map +1 -1
- package/dist/core.module.d.ts +3 -0
- package/dist/core.module.js +100 -42
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/docs/REQUEST-LIFECYCLE.md +1 -0
- package/migration-guides/11.42.1-to-11.42.2.md +53 -0
- package/migration-guides/11.42.2-to-11.42.3.md +145 -0
- package/package.json +1 -1
- package/src/core/common/helpers/graphql-ws-connection.helper.ts +382 -0
- package/src/core/common/helpers/graphql-ws-context.helper.ts +91 -18
- package/src/core/common/interfaces/server-options.interface.ts +32 -2
- package/src/core/modules/auth/services/core-auth.service.ts +37 -0
- package/src/core/modules/better-auth/better-auth.config.ts +46 -1
- package/src/core/modules/better-auth/core-better-auth.service.ts +9 -1
- package/src/core/modules/tenant/README.md +8 -8
- package/src/core/modules/tenant/core-tenant.guard.ts +41 -12
- package/src/core/modules/tus/README.md +15 -0
- package/src/core/modules/tus/core-tus.controller.ts +4 -2
- package/src/core/modules/tus/core-tus.service.ts +60 -0
- package/src/core/modules/user/core-user.service.ts +19 -6
- package/src/core.module.ts +166 -55
- package/src/index.ts +1 -0
|
@@ -320,7 +320,8 @@ This pattern is currently applied to:
|
|
|
320
320
|
| Response Model Interceptor | `security.responseModelInterceptor` | Boolean Shorthand | `true` (enabled), `debug: false` |
|
|
321
321
|
| Translate Response Interceptor | `security.translateResponseInterceptor` | Boolean Shorthand | `true` (enabled) |
|
|
322
322
|
| Secret Fields Removal | `security.secretFields` | Array | `['password', 'verificationToken', ...]` |
|
|
323
|
-
| Multi-Tenancy | `multiTenancy` | Presence Implies Enabled | **`excludeSchemas` is an OFF SWITCH for isolation, per model** — a listed schema gets no tenant filter at all; since 11.35.0 the plugin WARNS once per model when the excluded schema declares `tenantId` (i.e. was built for isolation). The framework's own docs recommended `['User', 'Session']` until then; that is withdrawn — it is only right for the global-user model. Since 11.35.0 GraphQL operations over the WEBSOCKET also run inside a `RequestContext` (`CoreModule` installs a context-aware `execute`/`subscribe` pair inside `subscriptions`, where `ApolloDriver` forwards it): the tenant comes from the handshake header validated against an active membership, else from the subscriber's memberships, and an unresolvable tenant leaves the safety net to refuse the read rather than returning everything. `headerName: 'x-tenant-id'`, `membershipModel: 'TenantMember'`, `adminBypass: true`, `excludeSchemas: []`, `roleHierarchy: { member: 1, manager: 2, owner: 3 }`, `cacheTtlMs: 30000` (0 disables, process-local). System roles (`S_EVERYONE`, `S_USER`, `S_VERIFIED`) are checked as OR alternatives before real roles; method-level system roles take precedence; membership validated for context when system role grants access + header present. Hierarchy roles use level comparison, normal roles use exact match. Use `DefaultHR` or `createHierarchyRoles()` for type-safe role constants. Bypass: `RequestContext.runWithBypassTenantGuard()`. Cache invalidation: `invalidateUser(userId)` / `invalidateAll()` are **instance** methods on the singleton `CoreTenantGuard` — inject it and call `this.tenantGuard?.invalidateUser(userId)`, never `CoreTenantGuard.invalidateUser(...)` (there is no static). With `redis` configured, both additionally BROADCAST the invalidation to every replica (`<keyPrefix>:tenant-cache:invalidate` pub/sub); without Redis they clear the local process only, so other replicas stay stale until `cacheTtlMs`. A received broadcast clears locally without re-publishing. **`isTenantActive` (11.42.0)**: optional hook `(tenantId, { connection }) => boolean \| Promise<boolean>`, absent = every tenant active (no change). Asked AFTER the membership check on every path that establishes a tenant: 403 on header paths and for tenant API tokens, no enrichment on `S_EVERYONE`, dropped from the header-less tenant list, no tenant for a NEW WebSocket subscription
|
|
323
|
+
| Multi-Tenancy | `multiTenancy` | Presence Implies Enabled | **`excludeSchemas` is an OFF SWITCH for isolation, per model** — a listed schema gets no tenant filter at all; since 11.35.0 the plugin WARNS once per model when the excluded schema declares `tenantId` (i.e. was built for isolation). The framework's own docs recommended `['User', 'Session']` until then; that is withdrawn — it is only right for the global-user model. Since 11.35.0 GraphQL operations over the WEBSOCKET also run inside a `RequestContext` (`CoreModule` installs a context-aware `execute`/`subscribe` pair inside `subscriptions`, where `ApolloDriver` forwards it): the tenant comes from the handshake header validated against an active membership, else from the subscriber's memberships, and an unresolvable tenant leaves the safety net to refuse the read rather than returning everything. `headerName: 'x-tenant-id'`, `membershipModel: 'TenantMember'`, `adminBypass: true`, `excludeSchemas: []`, `roleHierarchy: { member: 1, manager: 2, owner: 3 }`, `cacheTtlMs: 30000` (0 disables, process-local). System roles (`S_EVERYONE`, `S_USER`, `S_VERIFIED`) are checked as OR alternatives before real roles; method-level system roles take precedence; membership validated for context when system role grants access + header present. Hierarchy roles use level comparison, normal roles use exact match. Use `DefaultHR` or `createHierarchyRoles()` for type-safe role constants. Bypass: `RequestContext.runWithBypassTenantGuard()`. Cache invalidation: `invalidateUser(userId)` / `invalidateAll()` are **instance** methods on the singleton `CoreTenantGuard` — inject it and call `this.tenantGuard?.invalidateUser(userId)`, never `CoreTenantGuard.invalidateUser(...)` (there is no static). With `redis` configured, both additionally BROADCAST the invalidation to every replica (`<keyPrefix>:tenant-cache:invalidate` pub/sub); without Redis they clear the local process only, so other replicas stay stale until `cacheTtlMs`. A received broadcast clears locally without re-publishing. **`isTenantActive` (11.42.0)**: optional hook `(tenantId, { connection }) => boolean \| Promise<boolean>`, absent = every tenant active (no change). Asked AFTER the membership check on every path that establishes a tenant: 403 on header paths and for tenant API tokens, no enrichment on `S_EVERYONE`, dropped from the header-less tenant list, no tenant for a NEW WebSocket subscription, and since 11.42.3 an OPEN one is closed with 4403 on `invalidateTenant()` (or at its next event once `graphQl.subscriptionRevalidationMs` has passed — see the GraphQL Subscription Re-check row); an admin under `adminBypass` is exempt (someone must be able to switch it back on). Only `false` deactivates. Cached for `cacheTtlMs`; `invalidateTenant(tenantId)` clears and broadcasts (`{ scope: 'tenant' }`). A function, so `config.env.ts` only — not reachable through `NSC__*`. **`adminBypass: false` (11.42.0)** additionally withholds two things that went around it: `CoreUserService.update()` refuses changing another account's e-mail or password (`assertCredentialChangeAllowed()`, administrator targets included — promote-then-change — system work without a current user exempt), and the AI tool registry grants no ADMIN bypass |
|
|
324
|
+
| GraphQL Subscription Re-check | `graphQl.subscriptionRevalidationMs` | Numeric — `0` = STRICTEST, `false` = off, invalid → default (a fifth shape: Family C's "invalid never means unbounded", but `0` asks for MORE checking, not less) | **30000 since 11.42.3.** Before, a WebSocket was authorized once, at the handshake, and every event and operation on it ran on that snapshot until the client reconnected. Every connection a `CoreModule` `onConnect` accepts is now registered (`registerWsConnection()`) and re-checked — at once when an invalidation names it (`CoreTenantGuard.invalidateUser()` / `invalidateTenant()` / `invalidateAll()`, `CoreUserService.setRoles()` and role/verification `update()`s, the legacy password reset, and Better-Auth deleting a session through `wsSessionRevocationPlugin()`), and otherwise before the next event or operation once the last check is older than this value. The check re-runs the handshake's own authentication (session store, Better-Auth JWT signature/expiry, or for legacy tokens `CoreAuthService.verifyJwt()` — signature/expiry, verified on the WebSocket since 11.42.3 — plus the device binding) and the tenant resolution; any difference in user id, roles, verification state or tenant scope closes the socket with **4403**, which the graphql-ws client retries — the user continues with current rights or is refused at the handshake. `0` re-checks on every event and operation (one session lookup each); `false` switches only the TIME-based check off, invalidations still apply. Process-local registry: an invalidation reaches other replicas only where the tenant guard's Redis broadcast carries it; everything else is bounded by the interval. A project that replaces `onConnect` through `graphQl.driver.subscriptions` must call `registerWsConnection()` itself to keep this. Implementation: `common/helpers/graphql-ws-connection.helper.ts` |
|
|
324
325
|
| API Tokens | `apiTokens` | Boolean Shorthand + Presence Implies Enabled — absent = off | `prefix: 'ltt'`, `scopes: []` (vocabulary; empty = no token creatable, boot warning), `manageRole`: highest hierarchy role, `maxAssertionLifetimeSeconds: 900` (invalid → default, never unbounded — Family C), `rateLimit: { max: 600, windowSeconds: 60 }` per token (**on by default**, `false` disables; Redis-shared when configured), `userTokens: true`, `tenantTokens: true` (effective only with `multiTenancy`), `encryptionKey` → `SECRETS_ENCRYPTION_KEY` → dev default (boot FAILS in production/staging). Top-level, NOT under `multiTenancy`: user tokens must work without it. **Deny by default**: every guard refuses a token on a route without `@ApiTokenScopes()`, public routes included, via ONE shared function (`enforceApiTokenRoute`) called BEFORE each guard's public-route shortcut. USER tokens act as their user with global roles REMOVED (no admin bypass); TENANT tokens act with the lowest hierarchy role in their own tenant, and a route guarded ONLY by `S_SELF` / `S_CREATOR` refuses them (a tenant token is nobody's self — skipping those roles would grant for any target). A tenant token depends on no member, so it outlives an off-boarded or deleted tenant until the project calls `deleteAllForTenant()`. The boot refuses a hierarchy in which that lowest role reaches `manageRole`. A prefixed credential that fails answers 401 on every route (not anonymous); `CoreBetterAuthMiddleware` skips prefixed credentials entirely, cookie fallback included. A password reset that ends the user's sessions ends their USER tokens too (legacy reset always; IAM reset while `betterAuth.emailAndPassword.revokeSessionsOnPasswordReset` is on), wired through `core-api-token.registry.ts` so neither reset path imports the optional module. Implementation: `src/core/modules/api-token/` |
|
|
325
326
|
| BetterAuth Tenant Skip | `betterAuth.skipTenantCheck` | Explicit Boolean | `true` (default). When `true` and no `X-Tenant-Id` header is sent, IAM endpoints (controller + resolver) skip `CoreTenantGuard` tenant validation. When header IS present, normal membership validation runs regardless. Set `false` for tenant-aware auth scenarios (subdomain-based, invite links, SSO per tenant) |
|
|
326
327
|
| Debug Process Input | `debugProcessInput` | Explicit Boolean | `false` (default). When `true`, logs a debug message when `prepareInput()` changes the input type during `process()`. Has performance cost due to `JSON.stringify` on every `process()` call — enable only for debugging |
|
|
@@ -329,7 +330,7 @@ This pattern is currently applied to:
|
|
|
329
330
|
| CORS | `cors` | Boolean Shorthand | `enabled: true`, `allowAll: false`, `deriveAppUrl: true`. Origins come from `appUrl`/`baseUrl`, resolved by the shared `resolveServerUrls()` helper (`cookies.helper.ts`) that ALL three CORS layers use (GraphQL, REST, BetterAuth `trustedOrigins`) — they can no longer drift. `appUrl` resolution: explicit → derived from a **host-split** localhost `baseUrl` (its `api.` label strips to a sibling host: `https://api.crm.localhost` → `https://crm.localhost`, as served by `lt dev up`; the port is preserved) → localhost default (`http://localhost:3001`, only for `env: local`/`ci`/`e2e` with a **port-split** localhost `baseUrl` — one host, API `:3000`, app `:3001`; `https://api.localhost` strips to the bare `localhost` the API already answers on and is therefore a port split, not a host split) → derived from `baseUrl` by stripping a leading `api.` label (`https://api.example.com` → `https://example.com`). **Security:** the derived origin receives credentialed CORS; set `deriveAppUrl: false` when the apex domain is not trusted, then list the frontend origin via `appUrl`/`allowedOrigins` (a host-split localhost `baseUrl` then falls back to the localhost default). The derivation never yields a bare TLD (`https://api.dev` unchanged) and never emits the opaque `null` origin (non-http(s) `baseUrl` passes through verbatim). `allowAll: true` mirrors the request origin for REST/GraphQL, but BetterAuth's `trustedOrigins` still resolve to `[appUrl]` (+ passkey origins) — an origin check has no "allow everything" mode, so a separately hosted frontend must appear in `appUrl`/`allowedOrigins` (or set `betterAuth.trustedOrigins` explicitly). `enabled: false` disables CORS on all layers including BetterAuth (`trustedOrigins: []`, which still trusts BetterAuth's own `baseURL`). Explicit `betterAuth.trustedOrigins` always takes precedence |
|
|
330
331
|
| Central Redis | `redis` | Boolean Shorthand + Presence Implies Enabled | `host: 'localhost'`, `port: 6379`, `db: 0`, `keyPrefix: <package.json name, slugified>` (per APPLICATION, not per framework — a constant default silently collides when two apps share one Redis; set it explicitly when sharing IS intended); `url` (takes precedence over host/port/db/credentials), `username`/`password`, `options` (passed to the ioredis constructor). `true` / `{}` enables with defaults; `{ enabled: false }` pre-configures without enabling; **absent = every consumer keeps its process-local fallback** (that fallback is the whole backward-compatibility story of 11.33.0). Requires the OPTIONAL peer `ioredis` — configured-but-missing **fails the boot** with a named error rather than crashing on first use. `keyPrefix` is applied by the framework per key, NOT as ioredis `keyPrefix` (that would collide with BullMQ's own prefix). One `CoreRedisService` serves all features: shared client (`getClient()`), one cached subscriber (`getSubscriber()` — a subscribing client cannot run commands), dedicated connections (`createClient(label)`); all are tracked and quit on shutdown. Switches on automatically: exact cross-replica rate limits via `RedisRateLimitStore` (see the Legacy Auth / BetterAuth / AI rate-limit rows), cron dedup (see Cron Job Deduplication row), `CoreRedisPubSub` as `PUB_SUB` for cluster-wide GraphQL subscriptions (**payloads must be JSON-serializable — `Date`, class instances, `Map`/`Set`, `undefined` do not survive**), tenant-cache invalidation broadcast, Hub collector mirroring, MCP session registry (turns a wrong-replica request from a misleading `404` into a `409` — `/ai/mcp` still REQUIRES sticky sessions, sessions are not portable) |
|
|
331
332
|
| File Access Roles | `file.downloadRoles`, `file.uploadRoles`, `file.deleteRoles` | Config-Driven Role List | `[RoleEnum.ADMIN]` each. **These are the only breaking change a single-replica project gets in 11.33.0** — six members moved from `@Roles(S_EVERYONE)` to these knobs: `GET /files/id/:id`, `GET /files/:filename` and `getFileInfo` (`downloadRoles`), `uploadFile` / `uploadFiles` (`uploadRoles`), `deleteFile` (`deleteRoles`). Plain role STRINGS, not `RoleEnum` members, so project roles work (`['company-admin', 'editor']`). Applied at boot by `applyFileRoles()` via `Reflect.defineMetadata('roles', …)` on the base-class methods — the same runtime mechanism `CorePermissionsModule` uses, because the value is only known from config. **`[]`, a non-array, or an array holding a non-string is REJECTED with a warning and the default applies** — an all-empty role set reads to the guards as "no roles required" and would OPEN the route, the exact opposite of the intent. **ADMIN is always unioned in**: both `CoreFileController` and `CoreFileResolver` carry a class-level `@Roles(RoleEnum.ADMIN)` and the guards UNION class + handler metadata, so these knobs can grant but never exclude admins. Both classes also carry `@SkipTenantCheck()` — GridFS and the S3 metadata collection are reached outside Mongoose, so `mongooseTenantPlugin` never scopes them and a role name alone cannot express a per-tenant rule; roles resolve against `user.roles`, never `membership.role`. **A subclass that OVERRIDES a member opts out permanently** (decorator metadata lives on the function object, and an override is a different function) — inherit the member instead. **Since 11.35.1 that opt-out is REPORTED**: `CoreFileAccessAuditInitializer` reads the roles off the class the project actually registered at `onApplicationBootstrap` (the earliest point at which the route table exists, which is why it is a provider and not part of `applyFileRoles()`) and warns when a member is open beyond ADMIN for a reason the configuration cannot explain — the case the construction-time warning below is structurally blind to. It only REPORTS: overwriting an override's metadata, the way `TusModule.applyRoles()` does, would silently relax a route a project pinned on purpose. Roles are the coarse filter only; per-file rules belong in `CoreFileService.checkRights()`, which now receives `currentUser` and can read raw metadata via `getRawFileInfo()`. **Since 11.35.0 a reused FILENAME resolves to the most recent file** in all three stores (`uploadDate` desc, `_id` tie-break) and every by-name read path resolves a document and then reads by ID — under GridFS the by-name metadata lookup answered the oldest document while `openDownloadStreamByName()` served the newest, so a per-file rule approved one file and the bytes of another came back. Consequence: `duplicateById()` keeps the source's filename and the copy carries no metadata, so the copy now wins the name and an `ownerId` rule refuses it — give the copy its own metadata or its own name. **Since 11.35.0 `CoreFileService` WARNS at construction** when `multiTenancy` is active AND a knob names a role other than ADMIN AND `checkRights()` is not overridden — the file stores are reached outside Mongoose, so these role names resolve against `user.roles` (global) and every holder reaches every tenant's files; only `checkRights()` can narrow that. Silent on the admin-only default and silent when a per-file rule exists. Implementation: `src/core/modules/file/file-roles.config.ts` (`FILE_ROLE_DEFAULTS`, `FILE_ROLE_MEMBERS`, the three warnings, the shared `hasDeclaredFilePolicy()` silencer) + `file-roles.helper.ts` (`applyFileRoles`) + `core-file-access-audit.initializer.ts` (the registered-class audit) |
|
|
332
|
-
| TUS Roles | `tus.roles` | Config-Driven Role List | `[RoleEnum.S_USER]` (was `S_EVERYONE` — breaking). A TUS upload writes into the SAME store the download routes guard, and the termination extension (on by default) can delete from it, so anonymous writes into a store only privileged callers may read is the wrong way round. Applied by `TusModule.applyRoles()` onto the registered controller class **and** onto `handleTus` / `handleTusWithId`. Same rejection rule as the file roles: `[]` / non-array / non-string → warning + `DEFAULT_TUS_CONFIG.roles`. **`OPTIONS` is deliberately exempt**: `handleTusOptions` / `handleTusOptionsWithId` keep their own handler-level `@Roles(RoleEnum.S_EVERYONE)`, because that is the CORS preflight — browsers send it WITHOUT credentials, and it returns server capabilities only. Gating it would make every browser upload fail before the first byte. `CoreTusController` also carries `@SkipTenantCheck()`. A custom controller is covered as long as it INHERITS the handlers; one that re-declares `@All()` / `@Roles()` carries its own metadata and thereby opts out — the documented way to hard-code a policy config must not be able to change. **Set `roles: [RoleEnum.S_EVERYONE]` explicitly if you accept attachments on a public form.** **Since 11.35.0 `tus.roles` is no longer the only gate**: `onUploadCreate` records the authenticated creator under `TUS_OWNER_METADATA_KEY` (`ltOwnerId`, always OVERWRITING any client-supplied value) and `onIncomingRequest` refuses HEAD/PATCH/DELETE naming an upload the caller does not own — with **404**, the file module's refusal policy. Before that, any authenticated caller who learned an upload id could APPEND BYTES to somebody else's upload, which are then migrated into the file store under the victim's filename. The finished file also gains `metadata.ownerId`, without which the documented per-file ownership rule could never authorize a tus-uploaded file (admin-only in practice). An OWNER-LESS upload stays reachable — uploads predating 11.35.0 have none, and neither does a deliberately public form. `readRequestUserId()` / `assertUploadOwnership()` are `protected`. **Since 11.41.9 the tenant is recorded too, but ONLY with `multiTenancy` configured** (not `enabled: false`) and a tenant guard registered: `onUploadCreate` validates the tenant header against the caller's active memberships through `core-tenant-context.registry.ts` (the routes carry `@SkipTenantCheck()`, so the guard did not), refuses a non-member with **403**, writes it under `TUS_TENANT_METADATA_KEY` (`ltTenantId`, always overwritten like the owner key) and the finished file gains `metadata.tenantId`. No header → tenant-less, as before; without `multiTenancy` nothing is read or written. A project hooks in through `TusModule.forRoot({ service })` (a `CoreTusService` subclass, constructed by the module as `(connection, options)` — project providers come from `options.moduleRef` at call time) and the `protected onUploadCreate(req, upload)`, the one point where `Upload-Length` is known and nothing is stored yet; an override must return `super.onUploadCreate()`. Note that `@tus/server` v2 hands its hooks a WHATWG `ServerRequest`, so a guard's `req.user` is reachable only via `runtime.node.req`. **CORS (11.42.1)**: the tus handler's `Access-Control-Allow-Origin` comes from `buildCorsConfig()` (or `tus.allowedOrigins`), plus `allowedCredentials` — without it `@tus/server` answered `*`, which browsers refuse on a credentialed request, so cookie-authenticated uploads across split app/API origins failed in every browser while the server answered 201; no credentialed CORS configured → the `*` default stays. Implementation: `src/core/modules/tus/tus.module.ts`, `src/core/modules/tus/core-tus.service.ts`, `src/core/modules/tus/tus.constants.ts` |
|
|
333
|
+
| TUS Roles | `tus.roles` | Config-Driven Role List | `[RoleEnum.S_USER]` (was `S_EVERYONE` — breaking). A TUS upload writes into the SAME store the download routes guard, and the termination extension (on by default) can delete from it, so anonymous writes into a store only privileged callers may read is the wrong way round. Applied by `TusModule.applyRoles()` onto the registered controller class **and** onto `handleTus` / `handleTusWithId`. Same rejection rule as the file roles: `[]` / non-array / non-string → warning + `DEFAULT_TUS_CONFIG.roles`. **`OPTIONS` is deliberately exempt**: `handleTusOptions` / `handleTusOptionsWithId` keep their own handler-level `@Roles(RoleEnum.S_EVERYONE)`, because that is the CORS preflight — browsers send it WITHOUT credentials, and it returns server capabilities only. Gating it would make every browser upload fail before the first byte. `CoreTusController` also carries `@SkipTenantCheck()`. A custom controller is covered as long as it INHERITS the handlers; one that re-declares `@All()` / `@Roles()` carries its own metadata and thereby opts out — the documented way to hard-code a policy config must not be able to change. **Set `roles: [RoleEnum.S_EVERYONE]` explicitly if you accept attachments on a public form.** **Since 11.35.0 `tus.roles` is no longer the only gate**: `onUploadCreate` records the authenticated creator under `TUS_OWNER_METADATA_KEY` (`ltOwnerId`, always OVERWRITING any client-supplied value) and `onIncomingRequest` refuses HEAD/PATCH/DELETE naming an upload the caller does not own — with **404**, the file module's refusal policy. Before that, any authenticated caller who learned an upload id could APPEND BYTES to somebody else's upload, which are then migrated into the file store under the victim's filename. The finished file also gains `metadata.ownerId`, without which the documented per-file ownership rule could never authorize a tus-uploaded file (admin-only in practice). An OWNER-LESS upload stays reachable — uploads predating 11.35.0 have none, and neither does a deliberately public form. `readRequestUserId()` / `assertUploadOwnership()` are `protected`. **Since 11.41.9 the tenant is recorded too, but ONLY with `multiTenancy` configured** (not `enabled: false`) and a tenant guard registered: `onUploadCreate` validates the tenant header against the caller's active memberships through `core-tenant-context.registry.ts` (the routes carry `@SkipTenantCheck()`, so the guard did not), refuses a non-member with **403**, writes it under `TUS_TENANT_METADATA_KEY` (`ltTenantId`, always overwritten like the owner key) and the finished file gains `metadata.tenantId`. No header → tenant-less, as before; without `multiTenancy` nothing is read or written. A project hooks in through `TusModule.forRoot({ service })` (a `CoreTusService` subclass, constructed by the module as `(connection, options)` — project providers come from `options.moduleRef` at call time) and the `protected onUploadCreate(req, upload)`, the one point where `Upload-Length` is known and nothing is stored yet; an override must return `super.onUploadCreate()`. Note that `@tus/server` v2 hands its hooks a WHATWG `ServerRequest`, so a guard's `req.user` is reachable only via `runtime.node.req`. **CORS (11.42.1)**: the tus handler's `Access-Control-Allow-Origin` comes from `buildCorsConfig()` (or `tus.allowedOrigins`), plus `allowedCredentials` — without it `@tus/server` answered `*`, which browsers refuse on a credentialed request, so cookie-authenticated uploads across split app/API origins failed in every browser while the server answered 201; no credentialed CORS configured → the `*` default stays. **compression (11.42.2)**: `@tus/server` finishes responses with `res.end(callback)`, which `compression`'s two-argument `res.end(chunk, encoding)` patch reads as a chunk (`ERR_INVALID_ARG_TYPE … Received function`); with the starter's `filter: () => true, threshold: 0` every finished upload HUNG without an answer AFTER the file was stored (headers already sent, so no error response could follow). `CoreTusService` wraps `server.handle()` and normalises `res.end` per response (`normalizeEndCallback()`, callback on `finish`/`close`), so no `main.ts` change is needed. Implementation: `src/core/modules/tus/tus.module.ts`, `src/core/modules/tus/core-tus.service.ts`, `src/core/modules/tus/tus.constants.ts` |
|
|
333
334
|
| File Storage | `file.storage` + `file.storageDir` + `s3` | Explicit Enum with DERIVED default | `'filesystem' \| 'gridfs' \| 's3'`. **Unset → derived**, most capable first: `'s3'` when `s3.bucket` is set, else `'gridfs'` when `mongoose.uri` is set, else `'filesystem'`. **Set → enforced**: an unavailable store FAILS THE BOOT (`assertFileStorageAvailable()`), it never falls back — a silent fallback puts files in a store the operator does not believe they are in, unrecoverably. A DERIVED driver is enforced too (`s3.bucket` set but `s3Service` not forwarded to `super()` → boot error). Metadata always lives in MongoDB whichever driver holds the bytes (`fs.files` / `s3-files` / `filesystem-files`) — it has to stay queryable for `findFileInfo()` and `checkRights()`. Reads consult ALL stores so switching drivers is forward-only with no migration; writes go to the active driver only. `'filesystem'` is pod-local: not shared between replicas, lost on restart unless `storageDir` is a mounted volume. `s3`: `bucket` (required — the one thing S3 cannot default, hence the eligibility test), `region: 'us-east-1'`, `forcePathStyle: false`, `autoCreateBucket: false` (off by design: production buckets come from infrastructure code, whose credentials usually cannot CreateBucket), `stagingBucket: bucket`, `presignedDownloads: false` (`true`/`{}` → `expiresInSeconds: 300`), `endpoint` (MinIO/RustFS), `accessKeyId`/`secretAccessKey` (omit → AWS default credential chain), `enabled: false` to pre-configure. Requires the OPTIONAL peer `@aws-sdk/client-s3`, plus `@aws-sdk/s3-request-presigner` for presigned downloads. **Uploads are never buffered on the S3 path** (11.41.7): a known length (`FileUploadSource.size`, TUS, a buffer) goes up as one streamed PutObject up to `CoreS3Service.MAX_SINGLE_PUT_BYTES` (5 GiB — AWS S3 refuses more in one request, `EntityTooLarge`) and as a multipart upload above it, an unknown one — every GraphQL and streamed REST upload — as a multipart upload via the OPTIONAL peer `@aws-sdk/lib-storage`. Missing peer → one boot warning and the old in-memory buffering, NOT a boot failure (multipart optimises a path that works without it). `size` must be the file's EXACT length — never a multipart request's `Content-Length`; anything but a positive integer counts as unknown (`isKnownUploadSize()`), and the recorded length of an unknown-length upload comes from a HEAD of the stored object. `presignedDownloads` makes `GET /files/id/:id` answer `302` to a time-limited S3 URL instead of streaming — the URL is a bearer capability, authorized once at issue time. The resolved driver is logged at boot (`[CoreFileStorage] File storage: …`) |
|
|
334
335
|
| TUS S3 Staging | `tus.s3Staging` | Explicit Boolean (default ON when S3 configured) | `true` when `s3` is configured, otherwise inert. Stages in-progress uploads in `s3.stagingBucket` via `@tus/s3-store` instead of `tus.uploadDir` on local disk, so resumable uploads survive replica restarts and need no sticky sessions. Set `false` to force local disk. Missing OPTIONAL peer `@tus/s3-store` → warning + fall back to local disk (NOT a boot failure). **Give the staging bucket a lifecycle rule expiring incomplete multipart uploads** — the framework's own expiration cleanup is skipped in S3 mode (S3 is the right place for that policy), so aborted uploads otherwise accumulate parts nothing removes |
|
|
335
336
|
| Cron Job Deduplication | per job: `distributed` in `CronJobConfig` | Explicit Boolean | **`true` when `redis` is configured, otherwise `false`** — a single-replica project that upgrades must not silently gain a `cron-locks` collection, a lease write per tick, and a new way for a tick to be skipped. A Redis-less multi-replica fleet opts in per job with `distributed: true` (MongoDB lease). Mechanism: BullMQ job scheduler when Redis + the OPTIONAL peer `bullmq` are present AND `cronTime` is a string without `utcOffset`; otherwise local timer + lease (Redis `SET NX`, else a TTL-indexed `cron-locks` document). Tick lease TTL 3600 s. **Leases fail open** — an unreachable lease store runs the tick everywhere rather than stopping all scheduled work fleet-wide. **`runOnInit` (default `true`) deduplicates over a FIXED per-job key with a 300 s TTL**, because replicas do not share a boot instant: replicas booting within 5 min run the startup tick once between them, and a replica restarting inside that window SKIPS its startup tick — set `distributed: false` on jobs whose `runOnInit` work is per-process (warming a process-local cache). No constructor change needed: `CoreModule` fills `core-cron-jobs.registry.ts` via `CoreCronJobsInitializer` and `CoreCronJobs` reads it lazily; explicit `{ connection, redisService }` in `CoreCronJobsOptions` wins. With neither source it warns once and every replica runs every tick |
|
|
@@ -444,9 +444,37 @@ account over with an address change and a reset, which is precisely the access `
|
|
|
444
444
|
withholds.
|
|
445
445
|
|
|
446
446
|
**Deactivated tenants.** `multiTenancy.isTenantActive` is asked after the membership on every path that
|
|
447
|
-
establishes a tenant (see `.claude/rules/configurable-features.md`, Multi-Tenancy row).
|
|
448
|
-
|
|
449
|
-
|
|
447
|
+
establishes a tenant (see `.claude/rules/configurable-features.md`, Multi-Tenancy row).
|
|
448
|
+
|
|
449
|
+
**Open WebSockets (11.42.3).** A WebSocket is authorized at the handshake, and until 11.42.3 that was
|
|
450
|
+
the only check: a removed membership, a deactivated tenant, a withdrawn role or a revoked session took
|
|
451
|
+
effect on every new request and on none of the sockets already open. Now every connection
|
|
452
|
+
`CoreModule`'s `onConnect` accepts is registered (`registerWsConnection()`,
|
|
453
|
+
`common/helpers/graphql-ws-connection.helper.ts`) with the rights it was authorized with, and is
|
|
454
|
+
checked again
|
|
455
|
+
|
|
456
|
+
| Trigger | When |
|
|
457
|
+
|---------|------|
|
|
458
|
+
| `CoreTenantGuard.invalidateUser()` / `invalidateTenant()` / `invalidateAll()` (also when received from another replica), `CoreUserService.setRoles()`, an `update()` touching `roles` / `verified` / `emailVerified`, the legacy password reset | at once |
|
|
459
|
+
| Better-Auth deleting a session (sign-out, revoked session, reset with `revokeSessionsOnPasswordReset`) — through `wsSessionRevocationPlugin()`, a plugin so a project's own `options.databaseHooks` cannot displace it | at once |
|
|
460
|
+
| anything nobody invalidated (a membership edited in the database, an expired session) | before the next event or operation once the last check is older than `graphQl.subscriptionRevalidationMs` (30 s) |
|
|
461
|
+
|
|
462
|
+
A connection whose rights CHANGED — in either direction — is closed with **4403**, which the
|
|
463
|
+
graphql-ws client retries: it reconnects and resubscribes with its current rights, or is refused at the
|
|
464
|
+
handshake. It is closed rather than patched because a subscription may have picked its topic or filter
|
|
465
|
+
from the tenant at subscribe time. An event is checked after graphql-js executed it and before it is
|
|
466
|
+
sent, so a dropped event's reads happened but none of it reaches the client. Pinned by
|
|
467
|
+
`tests/subscription-revalidation.e2e-spec.ts` (mechanism), `tests/subscription-session-iam.e2e-spec.ts`
|
|
468
|
+
and `tests/subscription-session-legacy.e2e-spec.ts` (assembled stack).
|
|
469
|
+
|
|
470
|
+
The check re-runs the HANDSHAKE'S authentication, which on the legacy builder means
|
|
471
|
+
`CoreAuthService.verifyJwt()` — signature and expiry, in passport-jwt's key order — before
|
|
472
|
+
`validateUser()`'s device binding. The handshake used `decodeJwt()` until 11.42.3, so an expired or
|
|
473
|
+
re-signed legacy token opened sockets that HTTP refused (mutation `legacy-ws-jwt-unverified`). A legacy
|
|
474
|
+
socket therefore ends with its token: at expiry or at the next token refresh.
|
|
475
|
+
|
|
476
|
+
**A guard that asks "is this request allowed?" once is not enough for a connection that outlives the
|
|
477
|
+
answer.** When you add a long-lived channel (SSE, a WebSocket of your own), register it the same way.
|
|
450
478
|
|
|
451
479
|
## Role Check Implementation
|
|
452
480
|
|
package/.claude/rules/testing.md
CHANGED
|
@@ -266,7 +266,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
|
|
|
266
266
|
pnpm run check:mutations -- --list # the registry, without running anything
|
|
267
267
|
pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
|
|
268
268
|
pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
|
|
269
|
-
pnpm run check:mutations -- --no-infra # only the
|
|
269
|
+
pnpm run check:mutations -- --no-infra # only the 94 that need no MongoDB
|
|
270
270
|
pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
|
|
271
271
|
```
|
|
272
272
|
|
|
@@ -285,7 +285,7 @@ when the registry, a vitest config or a setup file changed, since those can move
|
|
|
285
285
|
commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
|
|
286
286
|
has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
|
|
287
287
|
PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
|
|
288
|
-
at
|
|
288
|
+
at 156 mutations.
|
|
289
289
|
|
|
290
290
|
**Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
|
|
291
291
|
11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
|
|
@@ -330,9 +330,9 @@ exactly the environment where the answer matters.
|
|
|
330
330
|
|
|
331
331
|
### The cost is vitest's cold start, not the tests
|
|
332
332
|
|
|
333
|
-
Worth knowing before optimising the wrong thing: the specs behind all
|
|
333
|
+
Worth knowing before optimising the wrong thing: the specs behind all 62 e2e mutations add up to
|
|
334
334
|
**~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
|
|
335
|
-
spawn, transform, module graph, mongod connect, DB create and drop — once per mutation,
|
|
335
|
+
spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 156 times.
|
|
336
336
|
That work is largely single-threaded I/O and barely scales with cores: the full registry measures
|
|
337
337
|
**744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
|
|
338
338
|
|
package/CLAUDE.md
CHANGED
|
@@ -233,6 +233,11 @@ in services (MCP/AI tools call services directly), tenant-aware tool roles in th
|
|
|
233
233
|
boundary under `adminBypass: false`. User-entered URLs (webhooks, export targets) go through
|
|
234
234
|
`outboundFetch()` (SSRF guard) — configured targets do not.
|
|
235
235
|
|
|
236
|
+
Since 11.42.3 an **open GraphQL WebSocket** is re-checked, not trusted for its lifetime: at once on an
|
|
237
|
+
invalidation (tenant guard, role change, password reset, sign-out), otherwise every
|
|
238
|
+
`graphQl.subscriptionRevalidationMs` (30 s); changed rights close it with 4403 and the client
|
|
239
|
+
reconnects. A custom `onConnect` must call `registerWsConnection()` to keep that.
|
|
240
|
+
|
|
236
241
|
See `.claude/rules/role-system.md` for complete documentation.
|
|
237
242
|
|
|
238
243
|
### Versioning
|
package/FRAMEWORK-API.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @lenne.tech/nest-server — Framework API Reference
|
|
2
2
|
|
|
3
|
-
> Auto-generated from source code as of 2026-10-04 (v11.42.
|
|
3
|
+
> Auto-generated from source code as of 2026-10-04 (v11.42.3)
|
|
4
4
|
> File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
|
|
5
5
|
|
|
6
6
|
## CoreModule.forRoot()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { ResolvedTenantContext } from '../services/core-tenant-context.registry';
|
|
2
|
+
export declare const WS_AUTHORIZATION_CHANGED_CLOSE_CODE = 4403;
|
|
3
|
+
export declare const DEFAULT_SUBSCRIPTION_REVALIDATION_MS = 30000;
|
|
4
|
+
export interface IWsConnectionSocket {
|
|
5
|
+
close(code: number, reason?: string): void;
|
|
6
|
+
once?(event: 'close', listener: (...args: any[]) => void): unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface IWsConnectionRegistration {
|
|
9
|
+
carrier: object;
|
|
10
|
+
reauthenticate?: () => any;
|
|
11
|
+
socket?: IWsConnectionSocket;
|
|
12
|
+
user: any;
|
|
13
|
+
}
|
|
14
|
+
export interface IWsConnectionIdentity {
|
|
15
|
+
email?: string;
|
|
16
|
+
iamId?: string;
|
|
17
|
+
userId?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface WsConnection {
|
|
20
|
+
readonly email?: string;
|
|
21
|
+
readonly iamId?: string;
|
|
22
|
+
readonly reauthenticate?: () => any;
|
|
23
|
+
readonly socket?: IWsConnectionSocket;
|
|
24
|
+
tenant?: ResolvedTenantContext;
|
|
25
|
+
readonly tenantHeader?: string;
|
|
26
|
+
terminated: boolean;
|
|
27
|
+
readonly user: any;
|
|
28
|
+
readonly userFingerprint: string;
|
|
29
|
+
readonly userId?: string;
|
|
30
|
+
inflight?: Promise<boolean>;
|
|
31
|
+
stale: boolean;
|
|
32
|
+
tenantFingerprint?: string;
|
|
33
|
+
validatedAt: number;
|
|
34
|
+
}
|
|
35
|
+
export declare function resolveSubscriptionRevalidationMs(value: unknown): false | number;
|
|
36
|
+
export declare function readWsTenantHeader(contextValue: any): string | undefined;
|
|
37
|
+
export declare function registerWsConnection(registration: IWsConnectionRegistration): void;
|
|
38
|
+
export declare function getWsConnection(contextValue: any): undefined | WsConnection;
|
|
39
|
+
export declare function ensureWsConnectionCurrent(connection: WsConnection): Promise<boolean>;
|
|
40
|
+
export declare function noteWsConnectionTenant(connection: WsConnection, tenant: ResolvedTenantContext | undefined): boolean;
|
|
41
|
+
export declare function revalidateWsConnectionsOf(identity: IWsConnectionIdentity): number;
|
|
42
|
+
export declare function revalidateWsConnectionsForTenant(tenantId: string): number;
|
|
43
|
+
export declare function revalidateAllWsConnections(): number;
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_SUBSCRIPTION_REVALIDATION_MS = exports.WS_AUTHORIZATION_CHANGED_CLOSE_CODE = void 0;
|
|
4
|
+
exports.resolveSubscriptionRevalidationMs = resolveSubscriptionRevalidationMs;
|
|
5
|
+
exports.readWsTenantHeader = readWsTenantHeader;
|
|
6
|
+
exports.registerWsConnection = registerWsConnection;
|
|
7
|
+
exports.getWsConnection = getWsConnection;
|
|
8
|
+
exports.ensureWsConnectionCurrent = ensureWsConnectionCurrent;
|
|
9
|
+
exports.noteWsConnectionTenant = noteWsConnectionTenant;
|
|
10
|
+
exports.revalidateWsConnectionsOf = revalidateWsConnectionsOf;
|
|
11
|
+
exports.revalidateWsConnectionsForTenant = revalidateWsConnectionsForTenant;
|
|
12
|
+
exports.revalidateAllWsConnections = revalidateAllWsConnections;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const config_service_1 = require("../services/config.service");
|
|
15
|
+
const core_tenant_context_registry_1 = require("../services/core-tenant-context.registry");
|
|
16
|
+
exports.WS_AUTHORIZATION_CHANGED_CLOSE_CODE = 4403;
|
|
17
|
+
exports.DEFAULT_SUBSCRIPTION_REVALIDATION_MS = 30_000;
|
|
18
|
+
const WS_CONNECTION = Symbol('ltWsConnection');
|
|
19
|
+
const liveConnections = new Set();
|
|
20
|
+
const logger = new common_1.Logger('GraphQlWsConnection');
|
|
21
|
+
function resolveSubscriptionRevalidationMs(value) {
|
|
22
|
+
if (value === false || value === 'false') {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
const numeric = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
|
|
26
|
+
if (typeof numeric === 'number' && Number.isFinite(numeric) && numeric >= 0) {
|
|
27
|
+
return numeric;
|
|
28
|
+
}
|
|
29
|
+
return exports.DEFAULT_SUBSCRIPTION_REVALIDATION_MS;
|
|
30
|
+
}
|
|
31
|
+
function configuredRevalidationMs() {
|
|
32
|
+
const graphQl = config_service_1.ConfigService.configFastButReadOnly?.graphQl;
|
|
33
|
+
return resolveSubscriptionRevalidationMs(graphQl ? graphQl.subscriptionRevalidationMs : undefined);
|
|
34
|
+
}
|
|
35
|
+
function fingerprintUser(user) {
|
|
36
|
+
if (!user) {
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
const roles = Array.isArray(user.roles) ? user.roles.map((role) => String(role)).sort() : [];
|
|
40
|
+
const verified = !!(user.verified || user.verifiedAt || user.emailVerified);
|
|
41
|
+
return JSON.stringify([String(user.id ?? user._id ?? ''), roles, verified]);
|
|
42
|
+
}
|
|
43
|
+
function fingerprintTenant(tenant) {
|
|
44
|
+
const tenantIds = Array.isArray(tenant?.tenantIds) ? tenant.tenantIds.map((id) => String(id)).sort() : null;
|
|
45
|
+
return JSON.stringify([tenant?.tenantId ?? null, tenantIds, tenant?.tenantRole ?? null, !!tenant?.isAdminBypass]);
|
|
46
|
+
}
|
|
47
|
+
function readWsTenantHeader(contextValue) {
|
|
48
|
+
const headerName = (config_service_1.ConfigService.configFastButReadOnly?.multiTenancy?.headerName ?? 'x-tenant-id').toLowerCase();
|
|
49
|
+
const sources = [contextValue?.headers, contextValue?.connectionParams, contextValue?.request?.headers];
|
|
50
|
+
for (const source of sources) {
|
|
51
|
+
if (!source || typeof source !== 'object') {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
for (const [key, value] of Object.entries(source)) {
|
|
55
|
+
if (key.toLowerCase() === headerName && typeof value === 'string' && value) {
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
function registerWsConnection(registration) {
|
|
63
|
+
const { carrier, reauthenticate, socket, user } = registration;
|
|
64
|
+
if (!carrier || typeof carrier !== 'object') {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const userId = user?.id ?? user?._id;
|
|
68
|
+
const connection = {
|
|
69
|
+
email: typeof user?.email === 'string' ? user.email.toLowerCase() : undefined,
|
|
70
|
+
iamId: typeof user?.iamId === 'string' ? user.iamId : undefined,
|
|
71
|
+
reauthenticate,
|
|
72
|
+
socket,
|
|
73
|
+
stale: false,
|
|
74
|
+
tenantHeader: readWsTenantHeader(carrier),
|
|
75
|
+
terminated: false,
|
|
76
|
+
user,
|
|
77
|
+
userFingerprint: fingerprintUser(user),
|
|
78
|
+
userId: userId !== undefined && userId !== null ? String(userId) : undefined,
|
|
79
|
+
validatedAt: Date.now(),
|
|
80
|
+
};
|
|
81
|
+
Object.defineProperty(carrier, WS_CONNECTION, { configurable: true, enumerable: true, value: connection });
|
|
82
|
+
if (socket && typeof socket.once === 'function') {
|
|
83
|
+
liveConnections.add(connection);
|
|
84
|
+
socket.once('close', () => {
|
|
85
|
+
connection.terminated = true;
|
|
86
|
+
liveConnections.delete(connection);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function getWsConnection(contextValue) {
|
|
91
|
+
if (!contextValue || typeof contextValue !== 'object') {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
const connection = contextValue[WS_CONNECTION];
|
|
95
|
+
return connection && typeof connection === 'object' ? connection : undefined;
|
|
96
|
+
}
|
|
97
|
+
function terminate(connection, reason) {
|
|
98
|
+
if (connection.terminated) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
connection.terminated = true;
|
|
102
|
+
liveConnections.delete(connection);
|
|
103
|
+
logger.log(`Closing GraphQL WebSocket of user ${connection.userId ?? '(unknown)'}: ${reason}`);
|
|
104
|
+
try {
|
|
105
|
+
connection.socket?.close(exports.WS_AUTHORIZATION_CHANGED_CLOSE_CODE, reason);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
async function revalidate(connection) {
|
|
112
|
+
connection.stale = false;
|
|
113
|
+
try {
|
|
114
|
+
let user = connection.user;
|
|
115
|
+
if (connection.reauthenticate) {
|
|
116
|
+
user = await connection.reauthenticate();
|
|
117
|
+
if (!user) {
|
|
118
|
+
return terminate(connection, 'Session no longer valid');
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (fingerprintUser(user) !== connection.userFingerprint) {
|
|
122
|
+
return terminate(connection, 'User authorization changed');
|
|
123
|
+
}
|
|
124
|
+
if (connection.tenantFingerprint !== undefined) {
|
|
125
|
+
const resolver = (0, core_tenant_context_registry_1.getTenantContextResolver)();
|
|
126
|
+
const tenant = resolver ? await resolver.resolve(user, connection.tenantHeader) : {};
|
|
127
|
+
if (fingerprintTenant(tenant) !== connection.tenantFingerprint) {
|
|
128
|
+
return terminate(connection, 'Tenant access changed');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (connection.terminated) {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
connection.validatedAt = Date.now();
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return terminate(connection, 'Authorization check failed');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function ensureWsConnectionCurrent(connection) {
|
|
142
|
+
if (connection.terminated) {
|
|
143
|
+
return Promise.resolve(false);
|
|
144
|
+
}
|
|
145
|
+
const interval = configuredRevalidationMs();
|
|
146
|
+
if (!connection.stale && (interval === false || Date.now() - connection.validatedAt < interval)) {
|
|
147
|
+
return Promise.resolve(true);
|
|
148
|
+
}
|
|
149
|
+
if (!connection.inflight) {
|
|
150
|
+
connection.inflight = revalidate(connection).finally(() => {
|
|
151
|
+
connection.inflight = undefined;
|
|
152
|
+
if (connection.stale && !connection.terminated) {
|
|
153
|
+
void ensureWsConnectionCurrent(connection);
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return connection.inflight;
|
|
158
|
+
}
|
|
159
|
+
function noteWsConnectionTenant(connection, tenant) {
|
|
160
|
+
if (connection.terminated) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
const fingerprint = fingerprintTenant(tenant);
|
|
164
|
+
if (connection.tenantFingerprint === undefined) {
|
|
165
|
+
connection.tenant = tenant ? { ...tenant } : {};
|
|
166
|
+
connection.tenantFingerprint = fingerprint;
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
if (fingerprint !== connection.tenantFingerprint) {
|
|
170
|
+
return terminate(connection, 'Tenant access changed');
|
|
171
|
+
}
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
function markStale(connection) {
|
|
175
|
+
connection.stale = true;
|
|
176
|
+
void ensureWsConnectionCurrent(connection);
|
|
177
|
+
}
|
|
178
|
+
function revalidateWsConnectionsOf(identity) {
|
|
179
|
+
const userId = identity?.userId !== undefined && identity?.userId !== null ? String(identity.userId) : undefined;
|
|
180
|
+
const iamId = identity?.iamId || undefined;
|
|
181
|
+
const email = typeof identity?.email === 'string' ? identity.email.toLowerCase() : undefined;
|
|
182
|
+
if (!userId && !iamId && !email) {
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
185
|
+
let count = 0;
|
|
186
|
+
for (const connection of liveConnections) {
|
|
187
|
+
if ((userId && connection.userId === userId) ||
|
|
188
|
+
(iamId && connection.iamId === iamId) ||
|
|
189
|
+
(email && connection.email === email)) {
|
|
190
|
+
markStale(connection);
|
|
191
|
+
count++;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return count;
|
|
195
|
+
}
|
|
196
|
+
function revalidateWsConnectionsForTenant(tenantId) {
|
|
197
|
+
if (!tenantId) {
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
const id = String(tenantId);
|
|
201
|
+
let count = 0;
|
|
202
|
+
for (const connection of liveConnections) {
|
|
203
|
+
const tenant = connection.tenant;
|
|
204
|
+
if (tenant && (tenant.tenantId === id || (Array.isArray(tenant.tenantIds) && tenant.tenantIds.includes(id)))) {
|
|
205
|
+
markStale(connection);
|
|
206
|
+
count++;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return count;
|
|
210
|
+
}
|
|
211
|
+
function revalidateAllWsConnections() {
|
|
212
|
+
let count = 0;
|
|
213
|
+
for (const connection of liveConnections) {
|
|
214
|
+
markStale(connection);
|
|
215
|
+
count++;
|
|
216
|
+
}
|
|
217
|
+
return count;
|
|
218
|
+
}
|
|
219
|
+
//# sourceMappingURL=graphql-ws-connection.helper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graphql-ws-connection.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/graphql-ws-connection.helper.ts"],"names":[],"mappings":";;;AAkIA,8EASC;AAuBD,gDAcC;AAMD,oDA4BC;AAGD,0CAMC;AA6DD,8DAmBC;AASD,wDAcC;AAaD,8DAmBC;AAGD,4EAcC;AAGD,gEAOC;AA7XD,2CAAwC;AAExC,+DAA2D;AAC3D,2FAA2G;AAsC9F,QAAA,mCAAmC,GAAG,IAAI,CAAC;AAG3C,QAAA,oCAAoC,GAAG,MAAM,CAAC;AAmE3D,MAAM,aAAa,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAO/C,MAAM,eAAe,GAAG,IAAI,GAAG,EAAgB,CAAC;AAEhD,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,qBAAqB,CAAC,CAAC;AAUjD,SAAgB,iCAAiC,CAAC,KAAc;IAC9D,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,OAAO,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,OAAO,GAAG,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACzF,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,IAAI,CAAC,EAAE,CAAC;QAC5E,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,4CAAoC,CAAC;AAC9C,CAAC;AAED,SAAS,wBAAwB;IAC/B,MAAM,OAAO,GAAG,8BAAa,CAAC,qBAAqB,EAAE,OAAO,CAAC;IAC7D,OAAO,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CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,KAAK,MAAM,CAAC;YACxC,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,KAAK,KAAK,CAAC;YACrC,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,KAAK,KAAK,CAAC,EACrC,CAAC;YACD,SAAS,CAAC,UAAU,CAAC,CAAC;YACtB,KAAK,EAAE,CAAC;QACV,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAGD,SAAgB,gCAAgC,CAAC,QAAgB;IAC/D,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,CAAC,CAAC;IACX,CAAC;IACD,MAAM,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC5B,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,UAAU,IAAI,eAAe,EAAE,CAAC;QACzC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;QACjC,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7G,SAAS,CAAC,UAAU,CAAC,CAAC;YACtB,KAAK,EAAE,CAAC;QACV,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAGD,SAAgB,0BAA0B;IACxC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,UAAU,IAAI,eAAe,EAAE,CAAC;QACzC,SAAS,CAAC,UAAU,CAAC,CAAC;QACtB,KAAK,EAAE,CAAC;IACV,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { IRequestContext } from '../services/request-context.service';
|
|
2
|
+
import { WsConnection } from './graphql-ws-connection.helper';
|
|
2
3
|
interface GraphQlArgs {
|
|
3
4
|
contextValue?: any;
|
|
4
5
|
[key: string]: any;
|
|
@@ -7,7 +8,7 @@ type ExecuteFn = (args: GraphQlArgs) => any;
|
|
|
7
8
|
export declare function buildWsRequestContext(contextValue: any): Promise<IRequestContext | undefined>;
|
|
8
9
|
export declare function withRequestContextAsyncIterator<T>(iterator: AsyncIterator<T> & {
|
|
9
10
|
[Symbol.asyncIterator]?: () => AsyncIterator<T>;
|
|
10
|
-
}, context: IRequestContext): AsyncIterableIterator<T>;
|
|
11
|
+
}, context: IRequestContext, connection?: WsConnection): AsyncIterableIterator<T>;
|
|
11
12
|
export declare function createRequestContextAwareExecute(execute: ExecuteFn): ExecuteFn;
|
|
12
13
|
export declare function createRequestContextAwareSubscribe(subscribe: ExecuteFn): ExecuteFn;
|
|
13
14
|
export declare function buildRequestContextAwareExecute(): (args: GraphQlArgs) => any;
|
|
@@ -8,22 +8,10 @@ exports.buildRequestContextAwareExecute = buildRequestContextAwareExecute;
|
|
|
8
8
|
exports.buildRequestContextAwareSubscribe = buildRequestContextAwareSubscribe;
|
|
9
9
|
const graphql = require("graphql");
|
|
10
10
|
const core_tenant_context_registry_1 = require("../services/core-tenant-context.registry");
|
|
11
|
-
const config_service_1 = require("../services/config.service");
|
|
12
11
|
const request_context_service_1 = require("../services/request-context.service");
|
|
12
|
+
const graphql_ws_connection_helper_1 = require("./graphql-ws-connection.helper");
|
|
13
13
|
function readTenantHeader(contextValue) {
|
|
14
|
-
|
|
15
|
-
const sources = [contextValue?.headers, contextValue?.connectionParams, contextValue?.request?.headers];
|
|
16
|
-
for (const source of sources) {
|
|
17
|
-
if (!source || typeof source !== 'object') {
|
|
18
|
-
continue;
|
|
19
|
-
}
|
|
20
|
-
for (const [key, value] of Object.entries(source)) {
|
|
21
|
-
if (key.toLowerCase() === headerName && typeof value === 'string' && value) {
|
|
22
|
-
return value;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
return undefined;
|
|
14
|
+
return (0, graphql_ws_connection_helper_1.readWsTenantHeader)(contextValue);
|
|
27
15
|
}
|
|
28
16
|
function readUser(contextValue) {
|
|
29
17
|
return contextValue?.user ?? contextValue?.extra?.user ?? undefined;
|
|
@@ -42,17 +30,50 @@ async function buildWsRequestContext(contextValue) {
|
|
|
42
30
|
}
|
|
43
31
|
const resolver = (0, core_tenant_context_registry_1.getTenantContextResolver)();
|
|
44
32
|
if (resolver) {
|
|
33
|
+
let resolved = {};
|
|
45
34
|
try {
|
|
46
|
-
|
|
35
|
+
resolved = (await resolver.resolve(user, readTenantHeader(contextValue))) ?? {};
|
|
36
|
+
Object.assign(context, resolved);
|
|
47
37
|
}
|
|
48
38
|
catch {
|
|
49
39
|
}
|
|
40
|
+
const connection = (0, graphql_ws_connection_helper_1.getWsConnection)(contextValue);
|
|
41
|
+
if (connection) {
|
|
42
|
+
(0, graphql_ws_connection_helper_1.noteWsConnectionTenant)(connection, resolved);
|
|
43
|
+
}
|
|
50
44
|
}
|
|
51
45
|
return context;
|
|
52
46
|
}
|
|
53
|
-
function
|
|
47
|
+
function refusedResult() {
|
|
48
|
+
return {
|
|
49
|
+
errors: [
|
|
50
|
+
new graphql.GraphQLError('The authorization of this connection changed — reconnect.', {
|
|
51
|
+
extensions: { code: 'FORBIDDEN' },
|
|
52
|
+
}),
|
|
53
|
+
],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
async function connectionStillAuthorized(contextValue) {
|
|
57
|
+
const connection = (0, graphql_ws_connection_helper_1.getWsConnection)(contextValue);
|
|
58
|
+
return connection ? (0, graphql_ws_connection_helper_1.ensureWsConnectionCurrent)(connection) : true;
|
|
59
|
+
}
|
|
60
|
+
function withRequestContextAsyncIterator(iterator, context, connection) {
|
|
61
|
+
const next = (...args) => request_context_service_1.RequestContext.run(context, () => iterator.next(...args));
|
|
54
62
|
const wrapped = {
|
|
55
|
-
next:
|
|
63
|
+
next: connection
|
|
64
|
+
? async (...args) => {
|
|
65
|
+
const result = await next(...args);
|
|
66
|
+
if (result.done || (await (0, graphql_ws_connection_helper_1.ensureWsConnectionCurrent)(connection))) {
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
await request_context_service_1.RequestContext.run(context, () => iterator.return?.());
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
}
|
|
74
|
+
return { done: true, value: undefined };
|
|
75
|
+
}
|
|
76
|
+
: next,
|
|
56
77
|
[Symbol.asyncIterator]() {
|
|
57
78
|
return wrapped;
|
|
58
79
|
},
|
|
@@ -70,21 +91,36 @@ function isAsyncIterable(value) {
|
|
|
70
91
|
}
|
|
71
92
|
function createRequestContextAwareExecute(execute) {
|
|
72
93
|
return async (args) => {
|
|
94
|
+
if (!(await connectionStillAuthorized(args?.contextValue))) {
|
|
95
|
+
return refusedResult();
|
|
96
|
+
}
|
|
73
97
|
const context = await buildWsRequestContext(args?.contextValue);
|
|
74
98
|
if (!context) {
|
|
75
99
|
return execute(args);
|
|
76
100
|
}
|
|
101
|
+
if ((0, graphql_ws_connection_helper_1.getWsConnection)(args?.contextValue)?.terminated) {
|
|
102
|
+
return refusedResult();
|
|
103
|
+
}
|
|
77
104
|
return request_context_service_1.RequestContext.run(context, () => execute(args));
|
|
78
105
|
};
|
|
79
106
|
}
|
|
80
107
|
function createRequestContextAwareSubscribe(subscribe) {
|
|
81
108
|
return async (args) => {
|
|
109
|
+
if (!(await connectionStillAuthorized(args?.contextValue))) {
|
|
110
|
+
return refusedResult();
|
|
111
|
+
}
|
|
82
112
|
const context = await buildWsRequestContext(args?.contextValue);
|
|
83
113
|
if (!context) {
|
|
84
114
|
return subscribe(args);
|
|
85
115
|
}
|
|
116
|
+
const connection = (0, graphql_ws_connection_helper_1.getWsConnection)(args?.contextValue);
|
|
117
|
+
if (connection?.terminated) {
|
|
118
|
+
return refusedResult();
|
|
119
|
+
}
|
|
86
120
|
const result = await request_context_service_1.RequestContext.run(context, () => subscribe(args));
|
|
87
|
-
return isAsyncIterable(result)
|
|
121
|
+
return isAsyncIterable(result)
|
|
122
|
+
? withRequestContextAsyncIterator(result, context, connection)
|
|
123
|
+
: result;
|
|
88
124
|
};
|
|
89
125
|
}
|
|
90
126
|
function buildRequestContextAwareExecute() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql-ws-context.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/graphql-ws-context.helper.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"graphql-ws-context.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/graphql-ws-context.helper.ts"],"names":[],"mappings":";;AA4FA,sDAwCC;AAsCD,0EAgCC;AAYD,4EAcC;AAGD,gFAkBC;AASD,0EAEC;AAED,8EAEC;AAnQD,mCAAoC;AAEpC,2FAA2G;AAC3G,iFAAsF;AACtF,iFAMwC;AA6DxC,SAAS,gBAAgB,CAAC,YAAiB;IACzC,OAAO,IAAA,iDAAkB,EAAC,YAAY,CAAC,CAAC;AAC1C,CAAC;AAGD,SAAS,QAAQ,CAAC,YAAiB;IACjC,OAAO,YAAY,EAAE,IAAI,IAAI,YAAY,EAAE,KAAK,EAAE,IAAI,IAAI,SAAS,CAAC;AACtE,CAAC;AASM,KAAK,UAAU,qBAAqB,CAAC,YAAiB;IAC3D,IAAI,CAAC,YAAY,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,YAAY,CAAC,GAAG,EAAE,CAAC;QAC1E,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,IAAI,GAAG,QAAQ,CAAC,YAAY,CAAC,CAAC;IACpC,MAAM,OAAO,GAAoB,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;IAG1E,MAAM,cAAc,GAClB,YAAY,CAAC,OAAO,EAAE,CAAC,iBAAiB,CAAC;QACzC,YAAY,CAAC,gBAAgB,EAAE,CAAC,iBAAiB,CAAC;QAClD,YAAY,CAAC,OAAO,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AA,8CAAe,EAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QACvD,IAAI,UAAU,EAAE,UAAU,EAAE,CAAC;YAC3B,OAAO,aAAa,EAAE,CAAC;QACzB,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,wCAAc,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;QACxE,OAAO,eAAe,CAAC,MAAM,CAAC;YAC5B,CAAC,CAAC,+BAA+B,CAAC,MAA4B,EAAE,OAAO,EAAE,UAAU,CAAC;YACpF,CAAC,CAAC,MAAM,CAAC;IACb,CAAC,CAAC;AACJ,CAAC;AASD,SAAgB,+BAA+B;IAC7C,OAAO,gCAAgC,CAAC,OAAO,CAAC,OAAc,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,iCAAiC;IAC/C,OAAO,kCAAkC,CAAC,OAAO,CAAC,SAAgB,CAAC,CAAC;AACtE,CAAC"}
|
|
@@ -26,6 +26,7 @@ export declare class CoreAuthService {
|
|
|
26
26
|
private readonly logger;
|
|
27
27
|
constructor(userService: CoreAuthUserService, jwtService: JwtService, configService: ConfigService, betterAuthService?: CoreBetterAuthService, betterAuthUserMapper?: CoreBetterAuthUserMapper);
|
|
28
28
|
decodeJwt(token: string): JwtPayload;
|
|
29
|
+
verifyJwt(token: string): Promise<JwtPayload | null>;
|
|
29
30
|
logout(tokenOrRefreshToken: string, serviceOptions: ServiceOptions & {
|
|
30
31
|
allDevices?: boolean;
|
|
31
32
|
}): Promise<boolean>;
|