From 0c22ed338425df3548cbd366465bca2da483cd46 Mon Sep 17 00:00:00 2001 From: ricoroeder Date: Fri, 13 Nov 2026 03:24:00 +0000 Subject: [PATCH 001/379] chore: dry-run state after step 2a (simulated) Signed-off-by: ricoroeder --- CHANGELOG.md | 35 + TEST_STRATEGY.md | 8 + apps/loadtest/Dockerfile | 5 +- apps/loadtest/README.md | 34 +- apps/loadtest/package.json | 1 + apps/loadtest/src/index.ts | 39 +- apps/loadtest/src/scenario.ts | 96 +- apps/loadtest/src/workers/colyseusBot.ts | 223 ++-- apps/loadtest/src/workers/livekitBot.ts | 307 +++--- apps/loadtest/src/workers/session.ts | 159 +++ apps/server/package.json | 1 + .../migration.sql | 6 + .../migration.sql | 12 + .../migration.sql | 10 + apps/server/prisma/schema.prisma | 11 + apps/server/src/api.ts | 19 +- apps/server/src/api/errorHandler.ts | 6 +- apps/server/src/api/middleware/guestExpiry.ts | 5 +- .../api/middleware/inviteRateLimit.test.ts | 116 +++ .../src/api/middleware/inviteRateLimit.ts | 42 + .../api/middleware/passwordChangeRateLimit.ts | 24 + apps/server/src/api/middleware/rateLimit.ts | 3 +- .../tenantAccess.integration.test.ts | 145 +++ .../server/src/api/middleware/tenantAccess.ts | 149 +++ .../uploadBudget.integration.test.ts | 102 ++ .../server/src/api/middleware/uploadPolicy.ts | 248 +++++ .../middleware/verificationSessionScope.ts | 14 + apps/server/src/api/requestLogger.ts | 4 +- apps/server/src/api/requestTelemetry.test.ts | 132 +++ .../routes/accountMail.integration.test.ts | 84 ++ apps/server/src/api/routes/accountProfile.ts | 35 + .../admin.passwordReset.integration.test.ts | 142 +++ .../api/routes/admin.passwordReset.test.ts | 213 +--- .../src/api/routes/admin.passwordReset.ts | 135 ++- apps/server/src/api/routes/adminMaps.ts | 6 +- apps/server/src/api/routes/assetPacks.ts | 9 +- .../auth.change.rateLimit.integration.test.ts | 80 ++ .../auth.change.window.integration.test.ts | 52 + .../auth.credentialRoutes.integration.test.ts | 192 ++++ apps/server/src/api/routes/auth.flow.test.ts | 958 +++++------------- .../src/api/routes/auth.helpers.test.ts | 38 +- apps/server/src/api/routes/auth.helpers.ts | 23 - apps/server/src/api/routes/auth.password.ts | 45 +- apps/server/src/api/routes/auth.signin.ts | 371 ++++--- apps/server/src/api/routes/auth.ts | 26 +- ...auth.verificationScope.integration.test.ts | 146 +++ apps/server/src/api/routes/auth.verify.ts | 209 ++-- apps/server/src/api/routes/avatarPacks.ts | 9 +- .../api/routes/controls.integration.test.ts | 286 ++++++ apps/server/src/api/routes/controls.test.ts | 27 +- apps/server/src/api/routes/controls.ts | 60 +- .../src/api/routes/displayName.write.test.ts | 32 +- .../src/api/routes/editorStateSchema.test.ts | 142 +++ .../src/api/routes/editorStateSchema.ts | 64 ++ .../emailProof.change.integration.test.ts | 32 + .../emailProof.expiry.integration.test.ts | 26 + .../emailProof.membership.integration.test.ts | 41 + .../emailProof.race.integration.test.ts | 45 + .../emailProof.retry.integration.test.ts | 25 + ...mailProof.supersession.integration.test.ts | 34 + apps/server/src/api/routes/guests.ts | 18 +- apps/server/src/api/routes/health.test.ts | 116 ++- apps/server/src/api/routes/health.ts | 78 +- .../invites.emailProof.integration.test.ts | 103 ++ .../api/routes/invites.integration.test.ts | 807 +++++++++++++++ apps/server/src/api/routes/invites.ts | 244 +++++ apps/server/src/api/routes/maps.editor.ts | 5 + .../src/api/routes/maps.editor.zones.ts | 15 +- apps/server/src/api/routes/misc.ts | 187 +--- apps/server/src/api/routes/npcMedia.ts | 32 +- .../routes/publicLinks.integration.test.ts | 321 ++++++ .../routes/tenantScope.integration.test.ts | 215 ++++ .../tmj.authorization.integration.test.ts | 84 ++ apps/server/src/api/routes/tmj.import.ts | 17 +- .../routes/uploads.global.integration.test.ts | 138 +++ .../routes/uploads.guard.integration.test.ts | 87 ++ .../routes/uploads.limits.integration.test.ts | 90 ++ .../routes/uploads.npc.integration.test.ts | 56 + .../routes/userDeletion.integration.test.ts | 171 ++++ apps/server/src/api/utils/authHelpers.ts | 37 +- apps/server/src/api/utils/authState.ts | 2 + apps/server/src/api/utils/broadcast.ts | 54 + .../emailProof.migration.integration.test.ts | 164 +++ apps/server/src/api/utils/emailProof.ts | 156 +++ .../src/api/utils/inviteLifecycle.test.ts | 76 ++ apps/server/src/api/utils/inviteLifecycle.ts | 142 +++ .../src/api/utils/inviteVerification.ts | 45 + apps/server/src/api/utils/mediaMime.ts | 19 + .../src/api/utils/passwordResetTokens.ts | 13 + .../src/api/utils/publicLinks.guard.test.ts | 35 + apps/server/src/api/utils/publicLinks.test.ts | 128 +++ apps/server/src/api/utils/publicLinks.ts | 75 ++ apps/server/src/api/utils/requestRoute.ts | 16 + .../sessionAuth.fresh.integration.test.ts | 127 +++ apps/server/src/api/utils/sessionAuth.ts | 73 +- .../server/src/api/utils/tenantAccessState.ts | 28 + apps/server/src/api/utils/tenantMembership.ts | 30 + .../email/consoleProvider.redaction.test.ts | 15 + apps/server/src/email/consoleProvider.ts | 36 +- apps/server/src/email/index.ts | 20 +- .../src/email/smtpProvider.requireTls.test.ts | 55 + apps/server/src/email/smtpProvider.ts | 24 +- apps/server/src/emailLoader.ts | 28 +- .../server/src/guestSessionRevocation.test.ts | 47 +- apps/server/src/index.ts | 2 + apps/server/src/livekit.ts | 39 +- apps/server/src/livekit.ttl.test.ts | 61 ++ apps/server/src/metrics.ts | 8 +- apps/server/src/rooms/WorldRoom.ts | 68 +- .../src/rooms/handlers/bubbleHandler.ts | 150 ++- apps/server/src/rooms/handlers/dndHandler.ts | 15 +- .../editorAuthorization.integration.test.ts | 305 ++++++ .../src/rooms/handlers/editorAuthorization.ts | 58 ++ .../src/rooms/handlers/editorHandler.ts | 95 +- .../src/rooms/handlers/playerHandlers.ts | 98 +- .../socialAuthorization.integration.test.ts | 596 +++++++++++ apps/server/src/rooms/handlers/socialScope.ts | 177 ++++ .../handlers/zoneLockHandler.tenant.test.ts | 19 +- .../src/rooms/handlers/zoneLockHandler.ts | 210 ++-- .../accessRevocation.integration.test.ts | 149 +++ .../src/rooms/lifecycle/accessRevocation.ts | 27 + .../src/rooms/lifecycle/avAccessReconciler.ts | 263 +++++ .../avAccessRevocation.integration.test.ts | 450 ++++++++ .../lifecycle/avPendingRevocations.test.ts | 223 ++++ .../rooms/lifecycle/avPendingRevocations.ts | 247 +++++ .../src/rooms/lifecycle/avSessionRef.ts | 104 ++ .../server/src/rooms/lifecycle/guestExpiry.ts | 136 ++- .../src/rooms/lifecycle/livekitRevocation.ts | 69 ++ .../src/rooms/lifecycle/npcServiceAuth.ts | 60 ++ .../rooms/lifecycle/onAuth.identity.test.ts | 58 +- .../rooms/lifecycle/onAuth.logging.test.ts | 48 +- .../onAuth.session.integration.test.ts | 183 ++++ .../server/src/rooms/lifecycle/onAuth.test.ts | 230 ++++- apps/server/src/rooms/lifecycle/onAuth.ts | 452 ++++----- .../onJoin.completion.bounds.test.ts | 40 +- .../lifecycle/onJoin.completion.dnd.test.ts | 42 +- .../onJoin.completion.logging.test.ts | 49 +- .../onJoin.completion.mapfallback.test.ts | 34 +- .../onJoin.completion.npc-avatar.test.ts | 48 +- .../onJoin.completion.presence.test.ts | 39 +- ...onJoin.completion.tenant-isolation.test.ts | 41 +- .../src/rooms/lifecycle/onJoin.completion.ts | 27 +- .../src/rooms/lifecycle/onJoin.name.test.ts | 25 +- .../src/rooms/lifecycle/roomPartition.test.ts | 53 +- .../src/rooms/lifecycle/roomPartition.ts | 2 +- .../rooms/lifecycle/transcriptionGate.test.ts | 31 +- .../lifecycle/worldAccess.integration.test.ts | 173 ++++ .../worldAccess.outage.integration.test.ts | 354 +++++++ ...orldAccess.pendingJoin.integration.test.ts | 314 ++++++ .../worldAccess.tenants.integration.test.ts | 264 +++++ .../server/src/rooms/lifecycle/worldAccess.ts | 346 +++++++ .../rooms/lifecycle/worldAccessLease.test.ts | 62 ++ .../src/rooms/lifecycle/worldAccessLease.ts | 141 +++ .../worldAccessSecurity.integration.test.ts | 539 ++++++++++ .../src/rooms/lifecycle/worldMatchmakeAuth.ts | 29 + .../src/rooms/validation/rejectionMetrics.ts | 16 + .../rooms/validation/worldPayloadSchemas.ts | 15 + .../worldPayloads.integration.test.ts | 648 ++++++++++++ apps/server/src/services/accountDeletion.ts | 114 +++ .../src/services/tenantAccessRevocation.ts | 31 + .../src/tenantIsolation.integration.test.ts | 222 ++++ apps/server/src/testUtils/matchmakeHarness.ts | 6 + apps/server/src/testUtils/plainSmtpServer.ts | 74 ++ apps/server/src/testUtils/sfuHarness.ts | 184 ++++ apps/server/src/testUtils/worldSeed.ts | 128 +++ apps/server/src/types/shims.d.ts | 56 +- .../test/fixtures/adminResetDeliveryProbe.ts | 60 ++ .../test/fixtures/consoleDeliveryProbe.ts | 7 + .../server/test/fixtures/emailProofFixture.ts | 68 ++ .../test/fixtures/forgotDeliveryProbe.ts | 51 + apps/server/test/fixtures/httpFixture.ts | 125 +++ apps/server/test/fixtures/mailFixture.ts | 37 + apps/server/test/fixtures/requestTelemetry.ts | 95 ++ apps/server/test/fixtures/uploadFixture.ts | 57 ++ .../test/fixtures/verifyDeliveryProbe.ts | 47 + apps/web/e2e/accounts/emailChange.spec.ts | 118 +++ .../e2e/accounts/inviteVerification.spec.ts | 335 ++++++ apps/web/e2e/accounts/invites.spec.ts | 250 +++++ .../e2e/accounts/legacyInviteClients.spec.ts | 102 ++ apps/web/e2e/accounts/mailProof.support.ts | 122 +++ apps/web/e2e/fixtures/helpers.ts | 129 +++ apps/web/e2e/fixtures/index.ts | 117 +++ apps/web/e2e/fixtures/roomUsers.ts | 120 +++ apps/web/e2e/fixtures/stackControl.ts | 57 ++ apps/web/e2e/fixtures/tenant.ts | 69 ++ apps/web/e2e/fixtures/types.ts | 51 + apps/web/e2e/smoke/login.spec.ts | 26 + apps/web/e2e/smoke/mail.spec.ts | 31 + apps/web/e2e/smoke/room.spec.ts | 10 + apps/web/e2e/stack/stack-control.spec.ts | 24 + apps/web/e2e/support/api.ts | 437 ++++++++ apps/web/e2e/support/capabilities.probe.ts | 401 ++++++++ apps/web/e2e/support/mailpit.ts | 119 +++ apps/web/e2e/support/provisioning.ts | 186 ++++ apps/web/e2e/support/seed.setup.ts | 190 ++++ apps/web/package.json | 5 +- apps/web/playwright.config.ts | 152 ++- .../app/routes/AppRoutes.authRemount.test.tsx | 215 ++++ apps/web/src/app/routes/AppRoutes.tsx | 20 +- apps/web/src/app/routes/hooks/useFetchMe.ts | 14 +- apps/web/src/app/routes/useHashRoute.test.tsx | 4 + apps/web/src/app/routes/useHashRoute.ts | 2 + apps/web/src/features/admin/InvitesModal.tsx | 168 --- .../src/lib/accountActionResponses.test.ts | 38 + apps/web/src/lib/accountActionResponses.ts | 55 + apps/web/src/lib/apiErrors.test.ts | 9 + apps/web/src/lib/pendingInvite.test.ts | 36 + apps/web/src/lib/pendingInvite.ts | 29 + apps/web/src/locales/de/common.json | 33 +- apps/web/src/locales/de/public.json | 41 +- apps/web/src/locales/en/common.json | 33 +- apps/web/src/locales/en/public.json | 41 +- apps/web/src/locales/inviteMessages.test.ts | 34 + apps/web/src/ui/admin/UserModals.test.tsx | 95 ++ apps/web/src/ui/admin/UserModals.tsx | 25 +- apps/web/src/ui/admin/userManagementTypes.ts | 2 + .../components/EmailVerificationBanner.tsx | 24 +- .../billing/hooks/useVerificationRequest.ts | 51 + apps/web/src/ui/pub/auth/AuthPage.tsx | 3 + apps/web/src/ui/pub/auth/AuthPageRenderer.tsx | 9 +- .../src/ui/pub/auth/InviteAcceptView.test.tsx | 172 ++++ apps/web/src/ui/pub/auth/InviteAcceptView.tsx | 93 ++ apps/web/src/ui/pub/auth/InviteCodeView.tsx | 16 +- apps/web/src/ui/pub/auth/LoginView.test.tsx | 54 + apps/web/src/ui/pub/auth/LoginView.tsx | 27 +- .../ui/pub/auth/RegisterView.name.test.tsx | 29 + apps/web/src/ui/pub/auth/RegisterView.tsx | 24 +- .../ui/pub/auth/VerificationPendingView.tsx | 48 + apps/web/src/ui/pub/auth/hooks/useAuthApi.ts | 14 +- .../pub/auth/hooks/useAuthHandlers.test.tsx | 61 ++ .../src/ui/pub/auth/hooks/useAuthHandlers.ts | 56 +- apps/web/src/ui/pub/auth/hooks/useAuthPage.ts | 2 + .../src/ui/pub/auth/hooks/useInviteAccept.ts | 125 +++ .../src/ui/pub/billing/EmailVerifyPage.tsx | 98 +- .../ui/settings/ProfileEmailChangeSection.tsx | 71 ++ .../ui/settings/ProfileSettings.name.test.tsx | 37 +- apps/web/src/ui/settings/ProfileSettings.tsx | 53 +- apps/web/src/ui/settings/TenantSettings.tsx | 2 + .../hooks/useTenantSettings.invite.test.tsx | 68 ++ .../ui/settings/hooks/useTenantSettings.ts | 25 +- .../src/ui/settings/profilePatchBody.test.ts | 31 +- apps/web/src/ui/settings/profilePatchBody.ts | 13 +- .../ui/settings/tenant/InviteMember.test.tsx | 140 +++ .../src/ui/settings/tenant/InviteMember.tsx | 63 +- .../ui/settings/tenant/InvitesTab.test.tsx | 310 +++++- .../web/src/ui/settings/tenant/InvitesTab.tsx | 312 ++++-- .../tenant/MemberSettings.name.test.tsx | 1 + .../tenant/MemberSettings.remove.test.tsx | 1 + .../src/ui/settings/tenant/MemberSettings.tsx | 9 +- apps/web/src/ui/user/RosterPanel.tsx | 5 + .../ui/user/__tests__/RosterPanel.test.tsx | 15 + package-lock.json | 2 + 252 files changed, 21944 insertions(+), 3131 deletions(-) create mode 100644 apps/loadtest/src/workers/session.ts create mode 100644 apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql create mode 100644 apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql create mode 100644 apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql create mode 100644 apps/server/src/api/middleware/inviteRateLimit.test.ts create mode 100644 apps/server/src/api/middleware/inviteRateLimit.ts create mode 100644 apps/server/src/api/middleware/passwordChangeRateLimit.ts create mode 100644 apps/server/src/api/middleware/tenantAccess.integration.test.ts create mode 100644 apps/server/src/api/middleware/tenantAccess.ts create mode 100644 apps/server/src/api/middleware/uploadBudget.integration.test.ts create mode 100644 apps/server/src/api/middleware/uploadPolicy.ts create mode 100644 apps/server/src/api/middleware/verificationSessionScope.ts create mode 100644 apps/server/src/api/requestTelemetry.test.ts create mode 100644 apps/server/src/api/routes/accountMail.integration.test.ts create mode 100644 apps/server/src/api/routes/accountProfile.ts create mode 100644 apps/server/src/api/routes/admin.passwordReset.integration.test.ts create mode 100644 apps/server/src/api/routes/auth.change.rateLimit.integration.test.ts create mode 100644 apps/server/src/api/routes/auth.change.window.integration.test.ts create mode 100644 apps/server/src/api/routes/auth.credentialRoutes.integration.test.ts create mode 100644 apps/server/src/api/routes/auth.verificationScope.integration.test.ts create mode 100644 apps/server/src/api/routes/controls.integration.test.ts create mode 100644 apps/server/src/api/routes/editorStateSchema.test.ts create mode 100644 apps/server/src/api/routes/editorStateSchema.ts create mode 100644 apps/server/src/api/routes/emailProof.change.integration.test.ts create mode 100644 apps/server/src/api/routes/emailProof.expiry.integration.test.ts create mode 100644 apps/server/src/api/routes/emailProof.membership.integration.test.ts create mode 100644 apps/server/src/api/routes/emailProof.race.integration.test.ts create mode 100644 apps/server/src/api/routes/emailProof.retry.integration.test.ts create mode 100644 apps/server/src/api/routes/emailProof.supersession.integration.test.ts create mode 100644 apps/server/src/api/routes/invites.emailProof.integration.test.ts create mode 100644 apps/server/src/api/routes/invites.integration.test.ts create mode 100644 apps/server/src/api/routes/invites.ts create mode 100644 apps/server/src/api/routes/publicLinks.integration.test.ts create mode 100644 apps/server/src/api/routes/tenantScope.integration.test.ts create mode 100644 apps/server/src/api/routes/tmj.authorization.integration.test.ts create mode 100644 apps/server/src/api/routes/uploads.global.integration.test.ts create mode 100644 apps/server/src/api/routes/uploads.guard.integration.test.ts create mode 100644 apps/server/src/api/routes/uploads.limits.integration.test.ts create mode 100644 apps/server/src/api/routes/uploads.npc.integration.test.ts create mode 100644 apps/server/src/api/routes/userDeletion.integration.test.ts create mode 100644 apps/server/src/api/utils/emailProof.migration.integration.test.ts create mode 100644 apps/server/src/api/utils/emailProof.ts create mode 100644 apps/server/src/api/utils/inviteLifecycle.test.ts create mode 100644 apps/server/src/api/utils/inviteLifecycle.ts create mode 100644 apps/server/src/api/utils/inviteVerification.ts create mode 100644 apps/server/src/api/utils/mediaMime.ts create mode 100644 apps/server/src/api/utils/publicLinks.guard.test.ts create mode 100644 apps/server/src/api/utils/publicLinks.test.ts create mode 100644 apps/server/src/api/utils/publicLinks.ts create mode 100644 apps/server/src/api/utils/requestRoute.ts create mode 100644 apps/server/src/api/utils/sessionAuth.fresh.integration.test.ts create mode 100644 apps/server/src/api/utils/tenantAccessState.ts create mode 100644 apps/server/src/api/utils/tenantMembership.ts create mode 100644 apps/server/src/email/consoleProvider.redaction.test.ts create mode 100644 apps/server/src/email/smtpProvider.requireTls.test.ts create mode 100644 apps/server/src/livekit.ttl.test.ts create mode 100644 apps/server/src/rooms/handlers/editorAuthorization.integration.test.ts create mode 100644 apps/server/src/rooms/handlers/editorAuthorization.ts create mode 100644 apps/server/src/rooms/handlers/socialAuthorization.integration.test.ts create mode 100644 apps/server/src/rooms/handlers/socialScope.ts create mode 100644 apps/server/src/rooms/lifecycle/accessRevocation.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/accessRevocation.ts create mode 100644 apps/server/src/rooms/lifecycle/avAccessReconciler.ts create mode 100644 apps/server/src/rooms/lifecycle/avAccessRevocation.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/avPendingRevocations.test.ts create mode 100644 apps/server/src/rooms/lifecycle/avPendingRevocations.ts create mode 100644 apps/server/src/rooms/lifecycle/avSessionRef.ts create mode 100644 apps/server/src/rooms/lifecycle/livekitRevocation.ts create mode 100644 apps/server/src/rooms/lifecycle/npcServiceAuth.ts create mode 100644 apps/server/src/rooms/lifecycle/onAuth.session.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccess.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccess.outage.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccess.pendingJoin.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccess.tenants.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccess.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccessLease.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccessLease.ts create mode 100644 apps/server/src/rooms/lifecycle/worldAccessSecurity.integration.test.ts create mode 100644 apps/server/src/rooms/lifecycle/worldMatchmakeAuth.ts create mode 100644 apps/server/src/rooms/validation/rejectionMetrics.ts create mode 100644 apps/server/src/rooms/validation/worldPayloadSchemas.ts create mode 100644 apps/server/src/rooms/validation/worldPayloads.integration.test.ts create mode 100644 apps/server/src/services/accountDeletion.ts create mode 100644 apps/server/src/services/tenantAccessRevocation.ts create mode 100644 apps/server/src/tenantIsolation.integration.test.ts create mode 100644 apps/server/src/testUtils/plainSmtpServer.ts create mode 100644 apps/server/src/testUtils/sfuHarness.ts create mode 100644 apps/server/src/testUtils/worldSeed.ts create mode 100644 apps/server/test/fixtures/adminResetDeliveryProbe.ts create mode 100644 apps/server/test/fixtures/consoleDeliveryProbe.ts create mode 100644 apps/server/test/fixtures/emailProofFixture.ts create mode 100644 apps/server/test/fixtures/forgotDeliveryProbe.ts create mode 100644 apps/server/test/fixtures/httpFixture.ts create mode 100644 apps/server/test/fixtures/mailFixture.ts create mode 100644 apps/server/test/fixtures/requestTelemetry.ts create mode 100644 apps/server/test/fixtures/uploadFixture.ts create mode 100644 apps/server/test/fixtures/verifyDeliveryProbe.ts create mode 100644 apps/web/e2e/accounts/emailChange.spec.ts create mode 100644 apps/web/e2e/accounts/inviteVerification.spec.ts create mode 100644 apps/web/e2e/accounts/invites.spec.ts create mode 100644 apps/web/e2e/accounts/legacyInviteClients.spec.ts create mode 100644 apps/web/e2e/accounts/mailProof.support.ts create mode 100644 apps/web/e2e/fixtures/helpers.ts create mode 100644 apps/web/e2e/fixtures/index.ts create mode 100644 apps/web/e2e/fixtures/roomUsers.ts create mode 100644 apps/web/e2e/fixtures/stackControl.ts create mode 100644 apps/web/e2e/fixtures/tenant.ts create mode 100644 apps/web/e2e/fixtures/types.ts create mode 100644 apps/web/e2e/smoke/login.spec.ts create mode 100644 apps/web/e2e/smoke/mail.spec.ts create mode 100644 apps/web/e2e/smoke/room.spec.ts create mode 100644 apps/web/e2e/stack/stack-control.spec.ts create mode 100644 apps/web/e2e/support/api.ts create mode 100644 apps/web/e2e/support/capabilities.probe.ts create mode 100644 apps/web/e2e/support/mailpit.ts create mode 100644 apps/web/e2e/support/provisioning.ts create mode 100644 apps/web/e2e/support/seed.setup.ts create mode 100644 apps/web/src/app/routes/AppRoutes.authRemount.test.tsx delete mode 100644 apps/web/src/features/admin/InvitesModal.tsx create mode 100644 apps/web/src/lib/accountActionResponses.test.ts create mode 100644 apps/web/src/lib/accountActionResponses.ts create mode 100644 apps/web/src/lib/pendingInvite.test.ts create mode 100644 apps/web/src/lib/pendingInvite.ts create mode 100644 apps/web/src/locales/inviteMessages.test.ts create mode 100644 apps/web/src/ui/admin/UserModals.test.tsx create mode 100644 apps/web/src/ui/billing/hooks/useVerificationRequest.ts create mode 100644 apps/web/src/ui/pub/auth/InviteAcceptView.test.tsx create mode 100644 apps/web/src/ui/pub/auth/InviteAcceptView.tsx create mode 100644 apps/web/src/ui/pub/auth/LoginView.test.tsx create mode 100644 apps/web/src/ui/pub/auth/VerificationPendingView.tsx create mode 100644 apps/web/src/ui/pub/auth/hooks/useInviteAccept.ts create mode 100644 apps/web/src/ui/settings/ProfileEmailChangeSection.tsx create mode 100644 apps/web/src/ui/settings/hooks/useTenantSettings.invite.test.tsx create mode 100644 apps/web/src/ui/settings/tenant/InviteMember.test.tsx create mode 100644 apps/web/src/ui/user/__tests__/RosterPanel.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index a02ae9fa..21a3fe7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 not support. Removing a member no longer asks twice, and logging out all other devices reports its result inline instead of with `alert()`. ESLint now rejects native `confirm`, `alert` and `prompt` in `apps/web`. +- Server: HTTP-Logfelder und Metriklabels enthalten Routen-Templates + statt konkreter Pfade; frühe `http.request`-Logs enthalten kein Pfadfeld, + endgültig ungematchte Requests melden ``. Dies ändert die + Werte für Dashboards und Log-Parser. +- World server: joining the world always requires a valid session, also + with `ZONE_PRIVACY_AUTH_ENFORCE` unset. A join without a session token + (desktop builds that predate the join token) is refused with 4401 + `unauthorized`; the identity the client names is no longer accepted in + its place. `ZONE_PRIVACY_AUTH_ENFORCE` now only gates the client + zone-privacy version check. +- World server: a join whose verified tenant has no resolvable slug is + refused with 4401 `tenant_unresolved` instead of falling back to the + tenant slug the client sent. +- Server: access revocations use one presence channel, `access_revoked` + with `{ userId, origin }`, instead of one `access_revoked:` + channel per tenant, and each world room checks the user's sessions + against the tenant each session was verified for. + `broadcastAccessRevoked(userId)` no longer takes a tenant slug, + `accessRevokedChannel` and `disconnectPlayers` are removed, and + `revokeAccountAccess(userId, tenantSlugs)` is new. +- World server: `WorldRoom.onCreate` is async and waits for the + revocation subscription; when subscribing fails, the room is not + created. +- World server: open world sessions hold an access lease. The periodic + access check runs every 30 s (was 60 s) and renews it. A session that + cannot be re-verified ends after at most 120 s with the new code 4503 + `access_unverified`, which the web client treats as a reconnect; native + clients should do the same. A guest ends exactly at its stored expiry. + `WORLD_ACCESS_SWEEP_MS` (default 30000) and `WORLD_ACCESS_LEASE_MS` + (default 120000, at least twice the sweep) tune both intervals. +- World server: a world session ends once its database session is gone + (logout, password reset, revoked sessions, or removal from another + tenant, which signs the user out everywhere), with 4401 + `session_revoked`: at once on a revocation, otherwise at the next + access check. ### Fixed diff --git a/TEST_STRATEGY.md b/TEST_STRATEGY.md index 1acfd835..01cd7ad8 100644 --- a/TEST_STRATEGY.md +++ b/TEST_STRATEGY.md @@ -421,6 +421,14 @@ test('two users can see each other', async ({ browser }) => { }); ``` +### Legacy Client Tests + +Specs with `@legacy` in the title check the current server against a pinned, +separately built older web bundle. They need `LEGACY_WEB_BASE_URL` and +`LEGACY_WEB_BUNDLE_MANIFEST` and fail without them; they never skip. The +default E2E runs exclude them with `--grep-invert @legacy`; run them on +purpose against the built legacy bundle. + --- ## 8. Local Test Execution diff --git a/apps/loadtest/Dockerfile b/apps/loadtest/Dockerfile index 984db76e..b46c2914 100644 --- a/apps/loadtest/Dockerfile +++ b/apps/loadtest/Dockerfile @@ -4,11 +4,14 @@ WORKDIR /app COPY package.json package-lock.json* ./ COPY ./apps/loadtest/package.json ./apps/loadtest/package.json +COPY ./packages/shared/package.json ./packages/shared/package.json -RUN npm install -w @meetropolis/loadtest +RUN npm install -w @meetropolis/shared -w @meetropolis/loadtest COPY . . +RUN npm run build -w @meetropolis/shared + WORKDIR /app/apps/loadtest CMD ["npm", "run", "dev"] diff --git a/apps/loadtest/README.md b/apps/loadtest/README.md index 2d61a4dd..edd0ee49 100644 --- a/apps/loadtest/README.md +++ b/apps/loadtest/README.md @@ -4,21 +4,41 @@ Example: ```bash # From repo root -npm -w @meetropolis/loadtest run dev - -# Or with environment overrides -API_BASE=http://localhost:2567 \ - LIVEKIT_URL=ws://localhost:7880 \ +LOADTEST_TENANT=throwaway \ + LOADTEST_ACCOUNTS_FILE=./accounts.json \ + API_BASE=http://localhost:2567 \ USERS=30 \ RAMP=5 \ DURATION=90 \ npm -w @meetropolis/loadtest run dev ``` +`accounts.json` is a JSON array, kept outside the repository: + +```json +[{ "email": "person@example.com", "password": "replace-me" }] +``` + +## Accounts and tenant + +`LOADTEST_ACCOUNTS_FILE` points at that array. Each object needs `email` +and `password`. `LOADTEST_TENANT` is the tenant slug, sent as `X-Tenant`. +Each simulated user takes one account. The run stops when there are fewer +accounts than `USERS`. The file contents are never printed. + +Use only test accounts that are members of a disposable tenant. Do not point +this tool at production, and do not reuse production passwords. Keep the +file out of the repository and out of logs. + +The world client signs in with `POST /auth/login` and joins with that +session. The LiveKit client calls `POST /livekit/token` with the same +session. `SKIP_LIVEKIT=true` skips the LiveKit client. `LIVEKIT_URL` is an +optional websocket override; otherwise the client reads `GET /livekit/url`. + Prerequisites: a local self-host stack (db, server, web, livekit) is running, for example via `docker compose up` from the repository root. The server rate-limits `POST /matchmake/...` per client IP (120 per minute by -default), and every bot joins from the same address. A run that joins more than -that per minute needs `RATE_LIMIT_MATCHMAKE_MAX` raised on the server (or +default), and every client joins from the same address. A run that joins more +than that per minute needs `RATE_LIMIT_MATCHMAKE_MAX` raised on the server (or `RATE_LIMIT_ENABLED=false` for a throwaway stack). diff --git a/apps/loadtest/package.json b/apps/loadtest/package.json index 3a7a2eb2..1a70543b 100644 --- a/apps/loadtest/package.json +++ b/apps/loadtest/package.json @@ -13,6 +13,7 @@ "dependencies": { "@colyseus/sdk": "^0.17.43", "@livekit/rtc-node": "^1.1.0", + "@meetropolis/shared": "*", "dotenv": "^17.4.2", "livekit-server-sdk": "^2.19.1" }, diff --git a/apps/loadtest/src/index.ts b/apps/loadtest/src/index.ts index 5ed8968a..1a02ca21 100644 --- a/apps/loadtest/src/index.ts +++ b/apps/loadtest/src/index.ts @@ -1,27 +1,40 @@ import 'dotenv/config'; +import { existsSync, readFileSync } from 'node:fs'; import { runScenario } from './scenario.js'; +import { parseAccounts, redactSecrets, type LoadtestAccount } from './workers/session.js'; -async function main() { +async function main(): Promise { const modeRaw = process.env.MODE || 'node'; const mode: 'node' | 'browser' = modeRaw === 'browser' ? 'browser' : 'node'; const users = Number(process.env.USERS || 20); const rampPerSec = Number(process.env.RAMP || 5); - // Prefer explicit env; when running inside Docker, default to service name - let runningInDocker = false; + const apiBase = process.env.API_BASE || (existsSync('/.dockerenv') ? 'http://server:2567' : 'http://localhost:2567'); + const room = process.env.ROOM || 'world'; + const durationSec = Number(process.env.DURATION || 60); + const tenant = requireEnv('LOADTEST_TENANT'); + const accounts = loadAccounts(); + await runScenario({ mode, users, rampPerSec, apiBase, room, durationSec, tenant, accounts }); +} + +function requireEnv(name: string): string { + const value = process.env[name]; + if (!value) throw new Error(`${name} is required`); + return value; +} + +function loadAccounts(): LoadtestAccount[] { + const path = requireEnv('LOADTEST_ACCOUNTS_FILE'); + let raw: string; try { - const { existsSync } = await import('node:fs'); - runningInDocker = existsSync('/.dockerenv'); + raw = readFileSync(path, 'utf8'); } catch { - runningInDocker = false; + throw new Error('LOADTEST_ACCOUNTS_FILE could not be read'); } - const apiBase = process.env.API_BASE || (runningInDocker ? 'http://server:2567' : 'http://localhost:2567'); - const livekitUrl = process.env.LIVEKIT_URL || 'ws://localhost:7880'; - const room = process.env.ROOM || 'world'; - const durationSec = Number(process.env.DURATION || 60); - await runScenario({ mode, users, rampPerSec, apiBase, livekitUrl, room, durationSec }); + return parseAccounts(raw); } -main().catch((e) => { - console.error('Loadtest failed:', e); +main().catch((error: unknown) => { + const message = error instanceof Error ? error.message : 'unknown error'; + console.error('Loadtest failed:', redactSecrets(message)); process.exit(1); }); diff --git a/apps/loadtest/src/scenario.ts b/apps/loadtest/src/scenario.ts index 190c719b..d525dc39 100644 --- a/apps/loadtest/src/scenario.ts +++ b/apps/loadtest/src/scenario.ts @@ -1,53 +1,85 @@ import { spawnColyseusBot } from './workers/colyseusBot.js'; -// The LiveKit bot is imported dynamically so the dependency stays optional. +import type { LoadtestAccount } from './workers/session.js'; +import type { LivekitBotOptions } from './workers/livekitBot.js'; export async function runScenario(opts: { mode: 'node' | 'browser'; users: number; rampPerSec: number; apiBase: string; - livekitUrl: string; room: string; durationSec: number; -}) { + tenant: string; + accounts: LoadtestAccount[]; +}): Promise { + if (opts.accounts.length < opts.users) { + throw new Error(`not enough loadtest accounts: have ${opts.accounts.length}, need ${opts.users}`); + } const bots: Array<{ stop: () => Promise }> = []; const startAt = Date.now(); const skipLivekit = process.env.SKIP_LIVEKIT === 'true'; for (let i = 0; i < opts.users; i++) { - const identity = `bot-${String(i + 1).padStart(3, '0')}`; - // Ramp-up - if (i > 0 && opts.rampPerSec > 0) { - const delayMs = Math.floor(1000 * (i / opts.rampPerSec)); - await new Promise((r) => setTimeout(r, delayMs)); + await rampDelay(i, opts.rampPerSec); + const account = opts.accounts[i]; + if (!account) { + throw new Error(`not enough loadtest accounts: have ${opts.accounts.length}, need ${opts.users}`); } - // Start Colyseus bot - bots.push(await spawnColyseusBot({ apiBase: opts.apiBase, identity })); - // Start LiveKit bot + const world = await spawnColyseusBot({ + apiBase: opts.apiBase, + tenant: opts.tenant, + email: account.email, + password: account.password, + }); + bots.push(world); if (!skipLivekit) { - try { - const mod: typeof import('./workers/livekitBot.js') = await import('./workers/livekitBot.js'); - bots.push( - await mod.spawnLivekitBot({ - livekitUrl: opts.livekitUrl, - apiBase: opts.apiBase, - roomName: opts.room, - identity, - }), - ); - } catch { - // LiveKit is optional: when the import fails, keep running Colyseus-only. - } + await startLivekitBot(bots, { + apiBase: opts.apiBase, + tenant: opts.tenant, + token: world.token, + roomName: opts.room, + }); } } - // Run for duration - const until = startAt + opts.durationSec * 1000; - while (Date.now() < until) { - await new Promise((r) => setTimeout(r, 1000)); + await waitUntil(startAt + opts.durationSec * 1000); + await stopAll(bots); +} + +function rampDelay(index: number, rampPerSec: number): Promise { + if (index === 0 || rampPerSec <= 0) return Promise.resolve(); + const delayMs = Math.floor(1000 * (index / rampPerSec)); + return new Promise((resolve) => { + setTimeout(resolve, delayMs); + }); +} + +async function startLivekitBot(bots: Array<{ stop: () => Promise }>, opts: LivekitBotOptions): Promise { + try { + const mod: typeof import('./workers/livekitBot.js') = await import('./workers/livekitBot.js'); + bots.push(await mod.spawnLivekitBot(opts)); + } catch (error: unknown) { + if (isMissingModule(error)) return; + throw error; } - // Stop all - for (const b of bots) { +} + +function isMissingModule(error: unknown): boolean { + return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ERR_MODULE_NOT_FOUND'; +} + +async function waitUntil(untilMs: number): Promise { + while (Date.now() < untilMs) { + await new Promise((resolve) => { + setTimeout(resolve, 1000); + }); + } +} + +async function stopAll(bots: Array<{ stop: () => Promise }>): Promise { + for (const bot of bots) { try { - await b.stop(); - } catch {} + await bot.stop(); + } catch { + // One bot failing to stop must not skip the others. + } } } diff --git a/apps/loadtest/src/workers/colyseusBot.ts b/apps/loadtest/src/workers/colyseusBot.ts index 81c66a05..73cb8cdb 100644 --- a/apps/loadtest/src/workers/colyseusBot.ts +++ b/apps/loadtest/src/workers/colyseusBot.ts @@ -1,117 +1,174 @@ import { Client } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import { + apiHttpBase, + apiWsBase, + authHeaders, + loginBot, + readResponseJson, + redactSecrets, + type LoginOptions, +} from './session.js'; -type Zone = { id: string; name: string; polygon: Array<{ x: number; y: number }> }; +type Point = { x: number; y: number }; +type Zone = { polygon?: Point[] }; type MapEntry = { name?: string; zones?: Zone[] }; -function centroid(points: Array<{ x: number; y: number }>): { x: number; y: number } { - if (!points || points.length === 0) return { x: 0, y: 0 }; - let sx = 0, - sy = 0; - for (const p of points) { - sx += p.x; - sy += p.y; +const FALLBACK_WAYPOINTS: Point[] = [ + { x: 80, y: 80 }, + { x: 160, y: 80 }, + { x: 160, y: 160 }, + { x: 80, y: 160 }, +]; + +export type ColyseusBot = { + userId: string; + sessionId: string; + token: string; + stop: () => Promise; +}; + +export async function spawnColyseusBot(opts: LoginOptions): Promise { + const session = await loginBot(opts); + const client = new Client(apiWsBase(opts.apiBase)); + client.auth.token = session.token; + const room = await joinWorld(client, opts.tenant); + const waypoints = await loadWaypoints(opts.apiBase, opts.tenant, session.token); + const alive = { value: true }; + startPatrol(room, waypoints, alive); + return { + userId: session.userId, + sessionId: room.sessionId, + token: session.token, + async stop() { + alive.value = false; + try { + await room.leave(); + } catch { + // The room may already be gone. + } + }, + }; +} + +function centroid(points: Point[]): Point { + if (points.length === 0) return { x: 0, y: 0 }; + let sx = 0; + let sy = 0; + for (const point of points) { + sx += point.x; + sy += point.y; } return { x: Math.round(sx / points.length), y: Math.round(sy / points.length) }; } -export async function spawnColyseusBot(opts: { apiBase: string; identity: string }) { - const toWs = (url: string) => url.replace(/^http(s?):\/\//, 'ws$1://'); - const toHttp = (url: string) => url.replace(/^ws(s?):\/\//, 'http$1://'); - const wsEndpoint = toWs(opts.apiBase); - const httpEndpoint = toHttp(opts.apiBase); - - const client = new Client(wsEndpoint); - - // Retry matchmaking a few times to avoid transient "connection refused" during warmup - async function joinWithRetry(maxAttempts: number, baseDelayMs: number) { - let attempt = 0; +function sleep(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} - while (true) { - try { - return await client.joinOrCreate('world', { identity: opts.identity, name: opts.identity }); - } catch (e: unknown) { - attempt++; - if (attempt >= maxAttempts) throw e; - const delay = Math.min(5000, baseDelayMs * Math.pow(2, attempt - 1)); - await new Promise((r) => setTimeout(r, delay)); - } +async function joinWorld(client: Client, tenant: string) { + let attempt = 0; + while (attempt < 6) { + try { + return await client.joinOrCreate('world', { + tenant, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }); + } catch (error: unknown) { + attempt += 1; + if (attempt >= 6) throw new Error(joinFailure(error)); + await sleep(Math.min(5000, 200 * 2 ** (attempt - 1))); } } + throw new Error('world join failed'); +} - const room = await joinWithRetry(6, 200); +function joinFailure(error: unknown): string { + const message = error instanceof Error ? redactSecrets(error.message) : ''; + if (!message) return 'world join failed'; + return `world join failed: ${message.slice(0, 180)}`; +} - // Load zones and build waypoints (centroids) - let waypoints: Array<{ x: number; y: number }> = []; +async function loadWaypoints(apiBase: string, tenant: string, token: string): Promise { try { - const mapsRes = await fetch(`${httpEndpoint}/maps`, { method: 'GET' }); - if (mapsRes.ok) { - const mapsRaw: unknown = await mapsRes.json(); - const maps: MapEntry[] = Array.isArray(mapsRaw) ? (mapsRaw as MapEntry[]) : []; - const office: MapEntry | null = maps.find((m) => (m?.name || '').toLowerCase() === 'office') || maps[0] || null; - const zones: Zone[] = Array.isArray(office?.zones) ? office.zones : []; - const cs = zones - .map((z) => (Array.isArray(z?.polygon) ? centroid(z.polygon) : null)) - .filter((c): c is { x: number; y: number } => !!c); - if (cs.length > 0) waypoints = cs; - } - } catch {} - // Fallback circular movement if no zones are available - if (waypoints.length === 0) { - waypoints = [ - { x: 80, y: 80 }, - { x: 160, y: 80 }, - { x: 160, y: 160 }, - { x: 80, y: 160 }, - ]; + const response = await fetch(`${apiHttpBase(apiBase)}/maps`, { + method: 'GET', + headers: authHeaders(tenant, token), + }); + if (!response.ok) return FALLBACK_WAYPOINTS; + const centers = waypointsFromMaps(await readResponseJson(response)); + if (centers.length > 0) return centers; + } catch { + return FALLBACK_WAYPOINTS; } + return FALLBACK_WAYPOINTS; +} - // Randomise the order per bot. - waypoints = [...waypoints].sort(() => Math.random() - 0.5); +function waypointsFromMaps(raw: unknown): Point[] { + if (!Array.isArray(raw)) return []; + const maps = raw.filter(isMapEntry); + const office = maps.find((map) => (map.name || '').toLowerCase() === 'office') || maps[0]; + const zones = office && Array.isArray(office.zones) ? office.zones : []; + const centers: Point[] = []; + for (const zone of zones) { + if (Array.isArray(zone.polygon)) centers.push(centroid(zone.polygon)); + } + return centers; +} - let alive = true; - let idx = 0; - let pos = { x: waypoints[0].x, y: waypoints[0].y }; - const speed = 40; // Pixels per second. - let lastTs = Date.now(); +function isMapEntry(value: unknown): value is MapEntry { + return typeof value === 'object' && value !== null; +} + +function directionOf(dx: number, dy: number): 'up' | 'down' | 'left' | 'right' { + if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? 'right' : 'left'; + return dy > 0 ? 'down' : 'up'; +} + +type JoinedRoom = Awaited>; +function startPatrol(room: JoinedRoom, waypoints: Point[], alive: { value: boolean }): void { + const route = [...waypoints].sort(() => Math.random() - 0.5); + let index = 0; + let pos = { x: route[0].x, y: route[0].y }; + const speed = 40; + let lastTs = Date.now(); void (async () => { - // Initial position. - try { - room.send('move', { x: pos.x, y: pos.y, direction: 'down' }); - } catch {} - while (alive) { + sendMove(room, pos, 'down'); + while (alive.value) { const now = Date.now(); const dt = Math.max(1, now - lastTs) / 1000; lastTs = now; - const target = waypoints[idx % waypoints.length]; + const target = route[index % route.length]; const dx = target.x - pos.x; const dy = target.y - pos.y; const dist = Math.hypot(dx, dy); if (dist < 3) { - // Brief dwell time in the zone before moving to the next waypoint. - idx++; - await new Promise((r) => setTimeout(r, 500 + Math.floor(Math.random() * 800))); + index += 1; + await sleep(500 + Math.floor(Math.random() * 800)); continue; } - const step = Math.min(dist, speed * dt); - if (dist > 0) { - pos = { x: Math.round(pos.x + (dx / dist) * step), y: Math.round(pos.y + (dy / dist) * step) }; - } - // Richtung approximieren - const dir = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up'; - try { - room.send('move', { x: pos.x, y: pos.y, direction: dir }); - } catch {} - await new Promise((r) => setTimeout(r, 150)); + pos = stepToward(pos, dx, dy, dist, Math.min(dist, speed * dt)); + sendMove(room, pos, directionOf(dx, dy)); + await sleep(150); } })(); +} +function stepToward(pos: Point, dx: number, dy: number, dist: number, step: number): Point { + if (dist <= 0) return pos; return { - async stop() { - alive = false; - try { - await room.leave(); - } catch {} - }, + x: Math.round(pos.x + (dx / dist) * step), + y: Math.round(pos.y + (dy / dist) * step), }; } + +function sendMove(room: JoinedRoom, pos: Point, direction: string): void { + try { + room.send('move', { x: pos.x, y: pos.y, direction }); + } catch { + // A dropped move is retried on the next tick. + } +} diff --git a/apps/loadtest/src/workers/livekitBot.ts b/apps/loadtest/src/workers/livekitBot.ts index c4e374a1..da7d242d 100644 --- a/apps/loadtest/src/workers/livekitBot.ts +++ b/apps/loadtest/src/workers/livekitBot.ts @@ -7,144 +7,217 @@ import { TrackPublishOptions, TrackSource, type RemoteParticipant, - type RemoteTrackPublication, } from '@livekit/rtc-node'; -import { AccessToken } from 'livekit-server-sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import { apiHttpBase, authHeaders, readResponseJson } from './session.js'; const SAMPLE_RATE = 48_000; const NUM_CHANNELS = 1; const FRAME_DURATION_MS = 20; -const SAMPLES_PER_FRAME = Math.floor((SAMPLE_RATE * FRAME_DURATION_MS) / 1000); // 960 +const SAMPLES_PER_FRAME = Math.floor((SAMPLE_RATE * FRAME_DURATION_MS) / 1000); +const PARTICIPANT_FIELD = 'identity'; -export async function spawnLivekitBot(opts: { +export type LivekitBotOptions = { apiBase: string; - livekitUrl: string; + tenant: string; + token: string; roomName: string; - identity: string; -}): Promise<{ stop: () => Promise }> { - // Generate server-side token (same flow as before, livekit-server-sdk stays). - const apiKey = process.env.LIVEKIT_API_KEY || 'devkey'; - const apiSecret = process.env.LIVEKIT_API_SECRET || 'secret'; - const at = new AccessToken(apiKey, apiSecret, { identity: opts.identity }); - at.addGrant({ - room: opts.roomName, - roomJoin: true, - canPublish: true, - canSubscribe: true, +}; + +type LivekitRun = { + alive: boolean; + samples: number; + lastInboundAudio: number; + lastRemoteParticipants: number; +}; + +type ConnectedRoom = { + room: Room; + audioSource: AudioSource; + trackSid: string | undefined; + timeToConnectMs: number; +}; + +export async function spawnLivekitBot(opts: LivekitBotOptions): Promise<{ stop: () => Promise }> { + const userId = subjectFromSessionToken(opts.token); + const url = await resolveLivekitUrl(opts.apiBase, opts.tenant, opts.token); + const participantToken = await requestParticipantToken(opts, userId); + const connected = await connectRoom(url, participantToken); + const run: LivekitRun = { alive: true, samples: 0, lastInboundAudio: 0, lastRemoteParticipants: 0 }; + const silence = pushSilence(connected.audioSource, run); + const sampler = sampleRoom(connected.room, run); + return { + stop: () => finishLivekitBot(connected, run, silence, sampler, opts.roomName, userId), + }; +} + +function subjectFromSessionToken(token: string): string { + const payload = token.split('.')[1]; + if (!payload) throw new Error('session token has no subject'); + let parsed: unknown; + try { + parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as unknown; + } catch { + throw new Error('session token has no subject'); + } + if (typeof parsed !== 'object' || parsed === null || !('sub' in parsed)) { + throw new Error('session token has no subject'); + } + const subject = parsed.sub; + if (typeof subject !== 'string' || subject.length === 0) throw new Error('session token has no subject'); + return subject; +} + +async function resolveLivekitUrl(apiBase: string, tenant: string, token: string): Promise { + const fromEnv = process.env.LIVEKIT_URL; + if (fromEnv && fromEnv.trim()) return normalizeLivekitUrl(fromEnv); + const response = await fetch(`${apiHttpBase(apiBase)}/livekit/url`, { + method: 'GET', + headers: authHeaders(tenant, token), }); - const token = await at.toJwt(); + if (!response.ok) throw new Error(`livekit url request failed with status ${response.status}`); + const url = readUrlField(await readResponseJson(response)); + if (!url) throw new Error('livekit url missing'); + return normalizeLivekitUrl(url); +} - const t0 = Date.now(); - const room = new Room(); - await room.connect(opts.livekitUrl, token, { - autoSubscribe: false, - dynacast: false, +function readUrlField(body: unknown): string | null { + if (typeof body !== 'object' || body === null || !('url' in body)) return null; + const url = body.url; + return typeof url === 'string' && url.trim() ? url : null; +} + +function normalizeLivekitUrl(input: string): string { + const trimmed = input.trim(); + if (trimmed.startsWith('ws://') || trimmed.startsWith('wss://')) return trimmed; + if (trimmed.startsWith('http://')) return `ws://${trimmed.slice('http://'.length)}`; + if (trimmed.startsWith('https://')) return `wss://${trimmed.slice('https://'.length)}`; + return trimmed; +} + +async function requestParticipantToken(opts: LivekitBotOptions, userId: string): Promise { + const response = await fetch(`${apiHttpBase(opts.apiBase)}/livekit/token`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...authHeaders(opts.tenant, opts.token), + }, + body: JSON.stringify({ + roomName: opts.roomName, + name: userId, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + [PARTICIPANT_FIELD]: userId, + }), }); - const timeToConnectMs = Date.now() - t0; + if (!response.ok) throw new Error(`livekit token request failed with status ${response.status}`); + const participantToken = (await response.text()).trim(); + if (!participantToken) throw new Error(`livekit token request failed with status ${response.status}`); + return participantToken; +} - // Publish silence audio so the bot looks like a normal participant with a mic track. +async function connectRoom(url: string, participantToken: string): Promise { + const started = Date.now(); + const room = new Room(); + await room.connect(url, participantToken, { autoSubscribe: false, dynacast: false }); + const publisher = room.localParticipant; + if (!publisher) throw new Error('livekit room has no local participant'); const audioSource = new AudioSource(SAMPLE_RATE, NUM_CHANNELS); const audioTrack = LocalAudioTrack.createAudioTrack('loadtest-audio', audioSource); const publishOptions = new TrackPublishOptions({ source: TrackSource.SOURCE_MICROPHONE }); - const publication = await room.localParticipant!.publishTrack(audioTrack, publishOptions); - const trackSid = publication.sid; - - // Periodically push silent frames (zero PCM) to keep the publication alive - // and provide realistic upstream traffic for SFU stress testing. - let alive = true; - const silenceFramePromise = (async () => { - const silentSamples = new Int16Array(SAMPLES_PER_FRAME * NUM_CHANNELS); // initialised to 0 - while (alive) { - try { - const frame = new AudioFrame(silentSamples, SAMPLE_RATE, NUM_CHANNELS, SAMPLES_PER_FRAME); - await audioSource.captureFrame(frame); - } catch { - // If capture fails (e.g. track was unpublished), stop. - break; - } + const publication = await publisher.publishTrack(audioTrack, publishOptions); + return { room, audioSource, trackSid: publication.sid, timeToConnectMs: Date.now() - started }; +} + +async function pushSilence(audioSource: AudioSource, run: LivekitRun): Promise { + const silentSamples = new Int16Array(SAMPLES_PER_FRAME * NUM_CHANNELS); + while (run.alive) { + try { + const frame = new AudioFrame(silentSamples, SAMPLE_RATE, NUM_CHANNELS, SAMPLES_PER_FRAME); + await audioSource.captureFrame(frame); + } catch { + break; } - })(); + } +} - let samples = 0; - let lastInboundAudio = 0; - let lastRemoteParticipants = 0; +async function sampleRoom(room: Room, run: LivekitRun): Promise { + while (run.alive) { + try { + const participants = Array.from(room.remoteParticipants.values()); + subscribeFirstAudio(participants); + run.lastRemoteParticipants = participants.length; + run.lastInboundAudio = countAudioTracks(participants); + run.samples += 1; + } catch { + // Sampling must not abort the bot. + } + await new Promise((resolve) => { + setTimeout(resolve, 1000); + }); + } +} - // Periodically subscribe to a few participants (simulate proximity) and - // sample basic metrics. rtc-node exposes `room.remoteParticipants` as a Map - // and each RemoteTrackPublication has `setSubscribed(boolean)`. - const samplerPromise = (async () => { - while (alive) { +function subscribeFirstAudio(participants: RemoteParticipant[]): void { + for (const participant of participants.slice(0, 5)) { + for (const publication of participant.trackPublications.values()) { + if (publication.kind !== TrackKind.KIND_AUDIO) continue; try { - const parts: RemoteParticipant[] = Array.from(room.remoteParticipants.values()); - const firstN = parts.slice(0, 5); - for (const p of firstN) { - const pubs: RemoteTrackPublication[] = Array.from(p.trackPublications.values()); - for (const pub of pubs) { - if (pub.kind === TrackKind.KIND_AUDIO) { - try { - pub.setSubscribed(true); - } catch { - /* ignore */ - } - } - } - } - // Basic metrics - lastRemoteParticipants = parts.length; - let inboundAudio = 0; - for (const p of parts) { - const pubs: RemoteTrackPublication[] = Array.from(p.trackPublications.values()); - for (const pub of pubs) { - if (pub.kind === TrackKind.KIND_AUDIO) inboundAudio++; - } - } - lastInboundAudio = inboundAudio; - samples++; + publication.setSubscribed(true); } catch { - // Ignore sampling errors: they should not abort the bot. + // A publication can disappear between the snapshot and the subscribe call. } - await new Promise((r) => setTimeout(r, 1000)); } - })(); + } +} - return { - async stop() { - alive = false; - // Wait for background loops so we don't capture frames after disconnect. - await Promise.allSettled([silenceFramePromise, samplerPromise]); - try { - if (trackSid) { - await room.localParticipant?.unpublishTrack(trackSid); - } - } catch { - /* ignore */ - } - try { - await audioSource.close(); - } catch { - /* ignore */ - } - try { - await room.disconnect(); - } catch { - /* ignore */ - } - // Emit summary line for ingestion - try { - console.log( - JSON.stringify({ - event: 'livekit_bot_summary', - identity: opts.identity, - room: opts.roomName, - timeToConnectMs, - samples, - lastRemoteParticipants, - lastInboundAudio, - }), - ); - } catch { - /* ignore */ - } - }, - }; +function countAudioTracks(participants: RemoteParticipant[]): number { + let inboundAudio = 0; + for (const participant of participants) { + for (const publication of participant.trackPublications.values()) { + if (publication.kind === TrackKind.KIND_AUDIO) inboundAudio += 1; + } + } + return inboundAudio; +} + +async function finishLivekitBot( + connected: ConnectedRoom, + run: LivekitRun, + silence: Promise, + sampler: Promise, + roomName: string, + userId: string, +): Promise { + run.alive = false; + await Promise.allSettled([silence, sampler]); + await releaseRoom(connected); + console.log( + JSON.stringify({ + event: 'livekit_bot_summary', + userId, + room: roomName, + timeToConnectMs: connected.timeToConnectMs, + samples: run.samples, + lastRemoteParticipants: run.lastRemoteParticipants, + lastInboundAudio: run.lastInboundAudio, + }), + ); +} + +async function releaseRoom(connected: ConnectedRoom): Promise { + try { + if (connected.trackSid) await connected.room.localParticipant?.unpublishTrack(connected.trackSid); + } catch { + // Unpublish is best-effort during shutdown. + } + try { + await connected.audioSource.close(); + } catch { + // The source may already be closed. + } + try { + await connected.room.disconnect(); + } catch { + // Disconnect is best-effort during shutdown. + } } diff --git a/apps/loadtest/src/workers/session.ts b/apps/loadtest/src/workers/session.ts new file mode 100644 index 00000000..b9c2ccac --- /dev/null +++ b/apps/loadtest/src/workers/session.ts @@ -0,0 +1,159 @@ +export type LoginOptions = { + apiBase: string; + tenant: string; + email: string; + password: string; +}; + +export type BotSession = { + token: string; + userId: string; +}; + +export type LoadtestAccount = { + email: string; + password: string; +}; + +export function apiHttpBase(apiBase: string): string { + return apiBase.replace(/\/+$/, '').replace(/^ws(s?):\/\//, 'http$1://'); +} + +export function apiWsBase(apiBase: string): string { + return apiHttpBase(apiBase).replace(/^http(s?):\/\//, 'ws$1://'); +} + +export function authHeaders(tenant: string, token: string): Record { + return { + 'X-Tenant': tenant, + Authorization: `Bearer ${token}`, + }; +} + +export function redactSecrets(text: string): string { + return text + .replace(/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]') + .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]'); +} + +export async function readResponseJson(response: Response): Promise { + return (await response.json()) as unknown; +} + +export function parseAccounts(raw: string): LoadtestAccount[] { + const parsed = parseJson(raw); + if (!Array.isArray(parsed)) { + throw new Error('LOADTEST_ACCOUNTS_FILE must contain a JSON array'); + } + return parsed.map(readAccount); +} + +export async function loginBot(opts: LoginOptions): Promise { + const response = await postLogin(opts); + const body = await readJsonBody(response); + if (!response.ok) throw loginError(response.status, body); + const token = readAuthToken(response.headers); + const userId = readUserId(body); + if (!token || !userId) throw new Error(`login failed with status ${response.status}`); + return { token, userId }; +} + +function parseJson(text: string): unknown { + try { + return JSON.parse(text) as unknown; + } catch { + throw new Error('LOADTEST_ACCOUNTS_FILE is not valid JSON'); + } +} + +function readAccount(value: unknown): LoadtestAccount { + if (typeof value !== 'object' || value === null) { + throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password'); + } + if (!('email' in value) || !('password' in value)) { + throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password'); + } + const email = value.email; + const password = value.password; + if (typeof email !== 'string' || email.length === 0) { + throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password'); + } + if (typeof password !== 'string' || password.length === 0) { + throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password'); + } + return { email, password }; +} + +async function postLogin(opts: LoginOptions): Promise { + try { + return await fetch(`${apiHttpBase(opts.apiBase)}/auth/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Tenant': opts.tenant, + }, + body: JSON.stringify({ email: opts.email, password: opts.password }), + }); + } catch { + throw new Error('login failed: network error'); + } +} + +async function readJsonBody(response: Response): Promise { + const text = await response.text(); + if (!text) return null; + try { + return JSON.parse(text) as unknown; + } catch { + return null; + } +} + +function loginError(status: number, body: unknown): Error { + const code = readErrorCode(body); + if (!code) return new Error(`login failed with status ${status}`); + return new Error(`login failed with status ${status}: ${code}`); +} + +function readErrorCode(body: unknown): string | null { + if (typeof body !== 'object' || body === null || !('error' in body)) return null; + const error = body.error; + if (typeof error !== 'string' || !/^[a-z0-9_ .:-]{1,80}$/i.test(error)) return null; + if (error.split('.').length === 3) return null; + return error; +} + +function readUserId(body: unknown): string | null { + if (typeof body !== 'object' || body === null || !('id' in body)) return null; + const id = body.id; + return typeof id === 'string' && id.length > 0 ? id : null; +} + +function readAuthToken(headers: Headers): string | null { + for (const line of cookieHeaderLines(headers)) { + const token = tokenFromCookieLine(line); + if (token) return token; + } + return null; +} + +function cookieHeaderLines(headers: Headers): string[] { + const listed = headers.getSetCookie(); + if (listed.length > 0) return listed; + const single = headers.get('set-cookie'); + return single ? [single] : []; +} + +function tokenFromCookieLine(line: string): string | null { + const first = line.split(';')[0] ?? ''; + const eq = first.indexOf('='); + if (eq <= 0) return null; + if (first.slice(0, eq).trim() !== 'auth_token') return null; + const raw = first.slice(eq + 1).trim(); + if (!raw) return null; + try { + return decodeURIComponent(raw); + } catch { + return raw; + } +} diff --git a/apps/server/package.json b/apps/server/package.json index 78adec21..29504baa 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -56,6 +56,7 @@ "zod": "^4.6.4" }, "devDependencies": { + "@livekit/rtc-node": "^1.1.0", "@types/compression": "^1.8.1", "@types/cookie-parser": "^1.4.10", "@types/cors": "^2.8.19", diff --git a/apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql b/apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql new file mode 100644 index 00000000..57e73ddf --- /dev/null +++ b/apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql @@ -0,0 +1,6 @@ +ALTER TABLE "Invite" ADD COLUMN "expiresAt" TIMESTAMP(3); +ALTER TABLE "Invite" ADD COLUMN "lastSentAt" TIMESTAMP(3); +ALTER TABLE "Invite" ADD COLUMN "sendCount" INTEGER NOT NULL DEFAULT 0; +ALTER TABLE "Invite" ADD COLUMN "lastSendError" TEXT; +-- Backfill: open invites get the regular 7-day lifetime from now on; accepted ones stay NULL. +UPDATE "Invite" SET "expiresAt" = now() + interval '7 days' WHERE "usedAt" IS NULL; diff --git a/apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql b/apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql new file mode 100644 index 00000000..d77784d9 --- /dev/null +++ b/apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql @@ -0,0 +1,12 @@ +ALTER TABLE "EmailVerification" + ADD COLUMN "purpose" TEXT NOT NULL DEFAULT 'verify', + ADD COLUMN "sourceEmail" TEXT, + ADD COLUMN "inviteId" TEXT, + ADD COLUMN "readyAt" TIMESTAMP(3); + +-- Do not reinterpret legacy raw values as new proof of mailbox ownership. +UPDATE "EmailVerification" SET "expiresAt" = LEAST("expiresAt", CURRENT_TIMESTAMP) +WHERE "usedAt" IS NULL; + +ALTER TABLE "EmailVerification" ADD CONSTRAINT "EmailVerification_inviteId_fkey" + FOREIGN KEY ("inviteId") REFERENCES "Invite"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql b/apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql new file mode 100644 index 00000000..4b035bea --- /dev/null +++ b/apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql @@ -0,0 +1,10 @@ +ALTER TABLE "Membership" ADD COLUMN "inviteVerificationRequired" BOOLEAN NOT NULL DEFAULT false; + +-- Gate only legacy memberships demonstrably created through an invitation. +UPDATE "Membership" AS m SET "inviteVerificationRequired" = true +FROM "User" AS u +WHERE m."userId" = u."id" AND u."emailVerifiedAt" IS NULL + AND EXISTS ( + SELECT 1 FROM "Invite" AS i + WHERE i."usedById" = u."id" AND i."tenantId" = m."tenantId" AND i."usedAt" IS NOT NULL + ); diff --git a/apps/server/prisma/schema.prisma b/apps/server/prisma/schema.prisma index babb2449..77a81583 100644 --- a/apps/server/prisma/schema.prisma +++ b/apps/server/prisma/schema.prisma @@ -75,6 +75,7 @@ model Membership { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt guestToken GuestToken? + inviteVerificationRequired Boolean @default(false) @@unique([tenantId, userId]) } @@ -114,12 +115,17 @@ model Invite { code String @unique email String? createdAt DateTime @default(now()) + expiresAt DateTime? + lastSentAt DateTime? + sendCount Int @default(0) + lastSendError String? createdBy String? usedAt DateTime? usedById String? tenant Tenant @relation(fields: [tenantId], references: [id]) tenantId String role Role @default(member) + emailVerifications EmailVerification[] } model PasswordReset { @@ -138,6 +144,11 @@ model EmailVerification { user User @relation(fields: [userId], references: [id]) userId String email String + purpose String @default("verify") + sourceEmail String? + invite Invite? @relation(fields: [inviteId], references: [id], onDelete: Cascade) + inviteId String? + readyAt DateTime? usedAt DateTime? expiresAt DateTime createdAt DateTime @default(now()) diff --git a/apps/server/src/api.ts b/apps/server/src/api.ts index c636bd6a..400fc6c5 100644 --- a/apps/server/src/api.ts +++ b/apps/server/src/api.ts @@ -49,8 +49,10 @@ import { createRequireTenantAdmin, } from './api/utils/authHelpers.js'; import { createSessionAuthMiddleware, establishSession } from './api/utils/sessionAuth.js'; +import { createTenantAccessMiddleware } from './api/middleware/tenantAccess.js'; import { startEmailVerification } from './api/routes/auth.verify.js'; import { isNativeClientRequest } from './api/routes/auth.helpers.js'; +import { buildPublicWebLink, publicWebBase } from './api/utils/publicLinks.js'; // Enterprise module loaders import { getAdminEnterpriseModule } from './adminLoader.js'; @@ -176,8 +178,9 @@ function sendSignupWelcomeEmail(params: { ownerName?: string | null; }): void { const { email, name, tenantId, ownerName } = params; - const baseUrl = process.env.PUBLIC_BASE_URL || process.env.BILLING_PUBLIC_URL || ''; - const loginUrl = baseUrl ? `${baseUrl.replace(/\/$/, '')}/#/app` : ''; + const baseUrl = publicWebBase(); + if (!baseUrl) logger.error({ event: 'links.public_base_url_missing', route: 'signup.welcome' }); + const loginUrl = baseUrl ? buildPublicWebLink(baseUrl, 'app') : ''; // OSS build without any mail provider: logged-only no-op (RootAdmin sees // the tenant directly in the UI). With EE-tenancy + RESEND_API_KEY or // with OSS-SMTP configured: send mail. @@ -252,7 +255,13 @@ async function registerEnterpriseAdminRoutes(app: express.Express) { // session row behind it and the session middleware — correctly — would // reject it on the very next request. establishSession: ({ req, res, userId, tenantId }) => establishSession({ prisma, req, res, userId, tenantId }), - startEmailVerification: ({ req, userId }) => startEmailVerification({ prisma, userId, req }), + startEmailVerification: async ({ req, userId }) => { + const outcome = await startEmailVerification({ prisma, userId, req }); + if (outcome.status === 'no_public_base_url') { + logger.error({ event: 'links.public_base_url_missing', route: 'signup.email_verification' }); + } + return outcome; + }, getTelemetryPublicConfig: telemetry ? () => telemetry.getPublicConfigBlock() : undefined, }); @@ -429,6 +438,10 @@ export async function registerApi(app: express.Express) { // route below — OSS and enterprise alike — depends on it; requireAuth fails // closed for any route registered ahead of it, so keep this line at the top. app.use(createSessionAuthMiddleware(prisma)); + // SECOND: drops the tenant context of authenticated callers who are not + // members of the resolved tenant (see api/middleware/tenantAccess.ts), so + // tenant-scoped routes fail closed instead of serving a foreign tenant. + app.use(createTenantAccessMiddleware(prisma)); registerHealthRoutes(app, prisma); registerAuthRoutes(app, prisma); diff --git a/apps/server/src/api/errorHandler.ts b/apps/server/src/api/errorHandler.ts index 093f8a66..ebfc4f04 100644 --- a/apps/server/src/api/errorHandler.ts +++ b/apps/server/src/api/errorHandler.ts @@ -1,5 +1,6 @@ import type { Request, Response, NextFunction } from 'express'; import { logger } from '../logger.js'; +import { getRequestRouteTemplate } from './utils/requestRoute.js'; import { AppError } from '../errors/AppError.js'; import { randomUUID } from 'crypto'; @@ -105,6 +106,7 @@ function normalizeError(err: unknown): NormalizedError { } function logErrorWithContext(err: unknown, req: Request, normalized: NormalizedError, correlationId: string) { + const route = getRequestRouteTemplate(req); const logContext = { event: 'http.error', correlationId, @@ -112,8 +114,8 @@ function logErrorWithContext(err: unknown, req: Request, normalized: NormalizedE code: normalized.code, isOperational: normalized.isOperational, method: req.method, - path: req.path, - url: req.url, + path: route, + url: route, ip: req.ip, userAgent: req.headers['user-agent'], ...getTenantContext(req), diff --git a/apps/server/src/api/middleware/guestExpiry.ts b/apps/server/src/api/middleware/guestExpiry.ts index 62f2a3f9..33e80961 100644 --- a/apps/server/src/api/middleware/guestExpiry.ts +++ b/apps/server/src/api/middleware/guestExpiry.ts @@ -2,6 +2,7 @@ import type express from 'express'; import { createPrismaClient } from '../../db.js'; import { requireAuth, getTenantFromReq } from '../utils/authHelpers.js'; import { revokeSessionsForUser } from '../utils/sessionAuth.js'; +import { getDeniedTenant } from '../utils/tenantAccessState.js'; const prisma = createPrismaClient(); @@ -15,7 +16,9 @@ export const guestExpiryMiddleware: express.RequestHandler = async (req, res, ne const auth = requireAuth(req); if (!auth) return next(); // Not authenticated, let other middleware handle it - const tenant = getTenantFromReq(req); + // The central guard removes an expired guest's tenant before this middleware runs; + // without the removed tenant, this expired guest would never lose its sessions here. + const tenant = getTenantFromReq(req) ?? getDeniedTenant(req); if (!tenant) return next(); const membership = await prisma.membership.findUnique({ diff --git a/apps/server/src/api/middleware/inviteRateLimit.test.ts b/apps/server/src/api/middleware/inviteRateLimit.test.ts new file mode 100644 index 00000000..d9b7909d --- /dev/null +++ b/apps/server/src/api/middleware/inviteRateLimit.test.ts @@ -0,0 +1,116 @@ +import crypto from 'node:crypto'; +import express from 'express'; +import request from 'supertest'; +import { describe, expect, it, vi } from 'vitest'; + +vi.hoisted(() => { + process.env.RATE_LIMIT_ENABLED = 'true'; + process.env.RATE_LIMIT_INVITE_CREATE_MAX = '30'; + process.env.RATE_LIMIT_INVITE_CREATE_WINDOW_MS = '60000'; + process.env.RATE_LIMIT_INVITE_RESEND_MAX = '5'; + process.env.RATE_LIMIT_INVITE_RESEND_WINDOW_MS = '60000'; + process.env.RATE_LIMIT_INVITE_PREVIEW_MAX = '30'; + process.env.RATE_LIMIT_INVITE_PREVIEW_WINDOW_MS = '60000'; + process.env.RATE_LIMIT_INVITE_ACCEPT_MAX = '30'; + process.env.RATE_LIMIT_INVITE_ACCEPT_WINDOW_MS = '60000'; +}); + +vi.mock('../../logger.js', () => ({ + logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }, +})); + +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { errorHandler } from '../errorHandler.js'; +import { setAuthResolution } from '../utils/authState.js'; +import { registerAuthRoutes } from '../routes/auth.js'; +import { registerInviteRoutes } from '../routes/invites.js'; + +const tenant = { id: 'invite-rate-limit-tenant', slug: 'invite-rate-limit-tenant', name: 'Invite Tenant' }; + +function makePrismaStub(): PrismaClient { + return { + invite: { findUnique: vi.fn(() => Promise.resolve(null)) }, + membership: { findUnique: vi.fn(() => Promise.resolve({ role: 'owner' })) }, + } as unknown as PrismaClient; +} + +function makeApp(): express.Application { + const app = express(); + app.set('trust proxy', 1); + app.use(express.json()); + app.use((req, _res, next) => { + const userId = req.headers['x-user']; + setAuthResolution(req, { + auth: typeof userId === 'string' ? { userId, sessionId: `session-${userId}`, tokenHash: `hash-${userId}` } : null, + }); + req.tenant = tenant as never; + next(); + }); + const prisma = makePrismaStub(); + registerAuthRoutes(app, prisma); + registerInviteRoutes(app, prisma); + app.use(errorHandler); + return app; +} + +function createRequest(app: express.Application, userId: string) { + return request(app).post('/auth/invite').set('x-user', userId).set('x-tenant', tenant.id).send({}); +} + +function resendRequest(app: express.Application, inviteId: string) { + return request(app).post(`/invites/${inviteId}/resend`).set('x-user', 'resend-admin').set('x-tenant', tenant.id); +} + +function previewRequest(app: express.Application, ip: string) { + return request(app).post('/public/invites/preview').set('X-Forwarded-For', ip).send({ code: 'missing-preview' }); +} + +function acceptRequest(app: express.Application, ip: string) { + return request(app).post('/invites/accept').set('X-Forwarded-For', ip).send({ code: 'missing-accept' }); +} + +describe('invite route rate limits', { retry: 2 }, () => { + it('limits invite creation per authenticated user', async () => { + const app = makeApp(); + const userId = `create-${crypto.randomUUID()}`; + + for (let attempt = 0; attempt < 30; attempt++) { + expect((await createRequest(app, userId)).status).toBe(400); + } + expect((await createRequest(app, userId)).status).toBe(429); + expect((await createRequest(app, `other-${crypto.randomUUID()}`)).status).toBe(400); + }); + + it('limits resend per invite ID', async () => { + const app = makeApp(); + const inviteId = `invite-${crypto.randomUUID()}`; + + for (let attempt = 0; attempt < 5; attempt++) { + expect((await resendRequest(app, inviteId)).status).toBe(404); + } + expect((await resendRequest(app, inviteId)).status).toBe(429); + expect((await resendRequest(app, `other-${crypto.randomUUID()}`)).status).toBe(404); + }); + + it('limits preview per IP', async () => { + const app = makeApp(); + const ip = '198.51.100.41'; + + for (let attempt = 0; attempt < 30; attempt++) { + expect((await previewRequest(app, ip)).status).toBe(404); + } + expect((await previewRequest(app, ip)).status).toBe(429); + expect((await previewRequest(app, '198.51.100.42')).status).toBe(404); + }); + + it('limits accept per IP', async () => { + const app = makeApp(); + const ip = '198.51.100.51'; + + for (let attempt = 0; attempt < 30; attempt++) { + expect((await acceptRequest(app, ip)).status).toBe(401); + } + expect((await acceptRequest(app, ip)).status).toBe(429); + expect((await acceptRequest(app, '198.51.100.52')).status).toBe(401); + }); +}); diff --git a/apps/server/src/api/middleware/inviteRateLimit.ts b/apps/server/src/api/middleware/inviteRateLimit.ts new file mode 100644 index 00000000..68010dcb --- /dev/null +++ b/apps/server/src/api/middleware/inviteRateLimit.ts @@ -0,0 +1,42 @@ +import { ipKeyGenerator } from 'express-rate-limit'; +import type { Request } from 'express'; +import { requireAuth } from '../utils/authHelpers.js'; +import { createRateLimiter } from './rateLimit.js'; + +const MINUTE_MS = 60_000; +const HOUR_MS = 60 * MINUTE_MS; + +function inviteCreateKey(req: Request): string { + const auth = requireAuth(req); + return auth ? `user:${auth.userId}` : ipKeyGenerator(req.ip ?? ''); +} + +function inviteResendKey(req: Request): string { + return `invite:${String(req.params.id)}`; +} + +export const inviteCreateRateLimiter = createRateLimiter({ + name: 'invite_create', + windowMs: HOUR_MS, + limit: 30, + keyGenerator: inviteCreateKey, +}); + +export const inviteResendRateLimiter = createRateLimiter({ + name: 'invite_resend', + windowMs: HOUR_MS, + limit: 5, + keyGenerator: inviteResendKey, +}); + +export const invitePreviewRateLimiter = createRateLimiter({ + name: 'invite_preview', + windowMs: 10 * MINUTE_MS, + limit: 30, +}); + +export const inviteAcceptRateLimiter = createRateLimiter({ + name: 'invite_accept', + windowMs: 10 * MINUTE_MS, + limit: 30, +}); diff --git a/apps/server/src/api/middleware/passwordChangeRateLimit.ts b/apps/server/src/api/middleware/passwordChangeRateLimit.ts new file mode 100644 index 00000000..a7e3e889 --- /dev/null +++ b/apps/server/src/api/middleware/passwordChangeRateLimit.ts @@ -0,0 +1,24 @@ +import type { RequestHandler } from 'express'; +import { ipKeyGenerator } from 'express-rate-limit'; +import { requireAuth } from '../utils/authHelpers.js'; +import { createRateLimiter } from './rateLimit.js'; + +/** Create fresh stores per registrar; count successful changes towards the budget. */ +export function createPasswordChangeRateLimiters(): RequestHandler[] { + const authenticated: RequestHandler = (req, res, next) => { + if (!requireAuth(req)) { + res.status(401).json({ error: 'unauthorized' }); + return; + } + next(); + }; + const ip = createRateLimiter({ name: 'password_change_ip', windowMs: 15 * 60_000, limit: 20 }); + const user = createRateLimiter({ + name: 'password_change', windowMs: 15 * 60_000, limit: 5, + keyGenerator: (req) => { + const auth = requireAuth(req); + return auth ? `user:${auth.userId}` : ipKeyGenerator(req.ip ?? ''); + }, + }); + return [authenticated, ip, user]; +} diff --git a/apps/server/src/api/middleware/rateLimit.ts b/apps/server/src/api/middleware/rateLimit.ts index 01e95e19..b41d7a89 100644 --- a/apps/server/src/api/middleware/rateLimit.ts +++ b/apps/server/src/api/middleware/rateLimit.ts @@ -3,6 +3,7 @@ import type { Request, RequestHandler } from 'express'; import { AppError } from '../../errors/AppError.js'; import { logger } from '../../logger.js'; import { getUserIdFromReq } from '../utils/authHelpers.js'; +import { getRequestRouteTemplate } from '../utils/requestRoute.js'; /** * Central, env-configurable rate limiting for the public, unauthenticated @@ -121,7 +122,7 @@ export function createRateLimiter(config: RateLimiterConfig): RequestHandler { limiter: config.name, ip: req.ip, method: req.method, - path: req.path, + path: getRequestRouteTemplate(req), }); next(AppError.tooManyRequests('Too many requests. Please wait a moment and try again.', 'RATE_LIMITED')); }, diff --git a/apps/server/src/api/middleware/tenantAccess.integration.test.ts b/apps/server/src/api/middleware/tenantAccess.integration.test.ts new file mode 100644 index 00000000..d48f1a32 --- /dev/null +++ b/apps/server/src/api/middleware/tenantAccess.integration.test.ts @@ -0,0 +1,145 @@ +import crypto from 'crypto'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { getApiTokenPepper, getJwtSecret, getTenantFromReq } from '../utils/authHelpers.js'; +import { createSessionAuthMiddleware, hashSessionToken } from '../utils/sessionAuth.js'; +import { createTenantAccessMiddleware } from './tenantAccess.js'; + +/** + * The central tenant guard against a REAL PostgreSQL database, for the + * multi-tenant resolution paths the OSS single-tenant stack cannot exercise: + * a client-chosen tenant (X-Tenant) and API-token callers. + * + * The first middleware stands in for the enterprise resolution of an explicit + * X-Tenant signal (tenancy.ts resolveTenantBySlug); everything after it is the + * production code: session middleware, tenant guard, getTenantFromReq. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('tenantAccess.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +let app: express.Express; +let tenantA: string; +let tenantB: string; + +async function createTenant(slug = `qacc-${crypto.randomUUID()}`): Promise { + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser( + memberships: Array<{ tenantId: string; role: Role; expiresAt?: Date }>, +): Promise<{ id: string; session: string }> { + const user = await prisma.user.create({ data: { email: `qacc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + for (const m of memberships) await prisma.membership.create({ data: { userId: user.id, ...m } }); + const session = jwt.sign({ sub: user.id, tid: memberships[0]?.tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(session), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, session }; +} + +async function createApiToken(userId: string): Promise { + const raw = `mt_${crypto.randomBytes(24).toString('hex')}`; + const hash = crypto + .createHash('sha256') + .update(getApiTokenPepper() + raw) + .digest('hex'); + await prisma.apiToken.create({ data: { userId, hash, name: 'qacc' } }); + return raw; +} + +/** The tenant id the route handler sees for a request naming `tenantId`, or null. */ +async function resolvedTenant(tenantId: string, bearer?: string): Promise { + const req = request(app).get('/probe').set('x-tenant', tenantId); + if (bearer) req.set('Authorization', `Bearer ${bearer}`); + const res = await req.expect(200); + return res.body.tenantId; +} + +beforeAll(async () => { + tenantA = await createTenant(); + tenantB = await createTenant(); + app = express(); + app.use(async (req, _res, next) => { + const id = req.headers['x-tenant']; + const tenant = typeof id === 'string' ? await prisma.tenant.findUnique({ where: { id } }) : null; + if (tenant) req.tenant = tenant; + next(); + }); + app.use(createSessionAuthMiddleware(prisma)); + app.use(createTenantAccessMiddleware(prisma)); + const probe: express.RequestHandler = (req, res) => { + res.json({ tenantId: getTenantFromReq(req)?.id ?? null }); + }; + app.get('/probe', probe); + // Same path as the enterprise tenant sign-up (first own tenant at onboarding). + app.post('/public/tenants', probe); +}); + +afterAll(async () => { + await prisma.apiToken.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('central tenant guard (real database)', () => { + it('keeps the tenant for its members', async () => { + const member = await createUser([{ tenantId: tenantB, role: 'member' }]); + expect(await resolvedTenant(tenantB, member.session)).toBe(tenantB); + }); + + it('drops a foreign tenant named via X-Tenant by a member of another tenant', async () => { + const outsider = await createUser([{ tenantId: tenantA, role: 'owner' }]); + expect(await resolvedTenant(tenantB, outsider.session)).toBeNull(); + }); + + it('drops the tenant for an expired guest', async () => { + const guest = await createUser([{ tenantId: tenantB, role: 'guest', expiresAt: new Date(Date.now() - 60_000) }]); + expect(await resolvedTenant(tenantB, guest.session)).toBeNull(); + }); + + it('applies the same rule to API-token callers', async () => { + const outsider = await createUser([{ tenantId: tenantA, role: 'admin' }]); + const member = await createUser([{ tenantId: tenantB, role: 'admin' }]); + expect(await resolvedTenant(tenantB, await createApiToken(outsider.id))).toBeNull(); + expect(await resolvedTenant(tenantB, await createApiToken(member.id))).toBe(tenantB); + }); + + it('keeps the tenant for operators (owners of the internal tenant)', async () => { + const existing = await prisma.tenant.findUnique({ where: { slug: 'internal' } }); + // Reuse a seeded internal tenant; otherwise create one (removed in afterAll). + const internalId = existing?.id ?? (await createTenant('internal')); + const operator = await createUser([{ tenantId: internalId, role: 'owner' }]); + expect(await resolvedTenant(tenantB, operator.session)).toBe(tenantB); + }); + + it('keeps the tenant for the tenant sign-up of a signed-in user without any membership', async () => { + const newcomer = await createUser([]); + const res = await request(app) + .post('/public/tenants') + .set('x-tenant', tenantB) + .set('Authorization', `Bearer ${newcomer.session}`) + .expect(200); + expect(res.body.tenantId).toBe(tenantB); + }); + + it('leaves anonymous requests untouched (login and registration need the tenant)', async () => { + expect(await resolvedTenant(tenantB)).toBe(tenantB); + }); +}); diff --git a/apps/server/src/api/middleware/tenantAccess.ts b/apps/server/src/api/middleware/tenantAccess.ts new file mode 100644 index 00000000..a99b207a --- /dev/null +++ b/apps/server/src/api/middleware/tenantAccess.ts @@ -0,0 +1,149 @@ +import type express from 'express'; +import type { PrismaClient, Tenant } from '../../generated/prisma/index.js'; +import { logger } from '../../logger.js'; +import { getRequestRouteTemplate } from '../utils/requestRoute.js'; +import { requireApiToken, requireAuth } from '../utils/authHelpers.js'; +import { hasTenantAccess } from '../utils/tenantMembership.js'; +import { + clearTenantAccessDenied, + getDeniedTenant, + isTenantAccessDenied, + markTenantAccessDenied, +} from '../utils/tenantAccessState.js'; + +/** + * Central tenant authorization for HTTP requests. + * + * `tenantMiddleware` (tenancy.ts) resolves WHICH tenant a request is about from + * signals the client controls: the X-Tenant header, `?tenant=`, the session's + * `tid` claim and the host. Resolution is not authorization. Before this + * middleware existed every route had to check membership on its own, and the + * ones that forgot served any tenant to any signed-in caller. + * + * This middleware runs right after the session middleware. For an + * authenticated caller (session or API token) it keeps the tenant context only + * when the caller is a member of that tenant (an expired guest membership does + * not count) or an operator (owner of the internal tenant). Otherwise it drops + * `req.tenant`, so `getTenantFromReq` returns null and every tenant-scoped + * route fails closed with `tenant_required` instead of serving a foreign + * tenant. + * + * Unauthenticated requests and `/public/*` keep their tenant by design. + * Credential routes that prove a new identity declare their exception on the + * route itself, after this guard has had a chance to reject a foreign session. + */ + +function tenantSource(req: express.Request): 'header' | 'query' | 'token_or_host' { + if (req.headers['x-tenant']) return 'header'; + if (typeof req.query?.tenant === 'string' && req.query.tenant) return 'query'; + return 'token_or_host'; +} + +async function resolveCallerId(prisma: PrismaClient, req: express.Request): Promise { + const session = requireAuth(req); + if (session) return session.userId; + const token = await requireApiToken(req, prisma); + return token?.userId ?? null; +} + +function dropTenantContext(req: express.Request, tenant: Tenant): void { + req.tenant = undefined; + req.tenantId = undefined; + markTenantAccessDenied(req, tenant); +} + +/** Fields describing a refused tenant, returned instead of logged by the guard. */ +export interface TenantAccessDenial { + userId: string; + tenant: string; + source: 'header' | 'query' | 'token_or_host'; + method: string; + path: string; +} + +/** + * Drop the tenant context of `req` when its authenticated caller may not + * access that tenant. Returns the denial fields when access was refused, null + * otherwise; the drop and its marking stay unchanged. Logging happens in + * `createTenantAccessMiddleware`, once the response shows the denial still + * stands. + */ +export async function enforceTenantMembership( + prisma: PrismaClient, + req: express.Request, +): Promise { + const tenant = req.tenant; + if (!tenant) return null; + // Public endpoints (login branding, tenant sign-up, contact) serve anonymous + // callers by design; a session must not make them stricter than that. + if (req.path.startsWith('/public/')) return null; + const userId = await resolveCallerId(prisma, req); + if (!userId) return null; + if (await hasTenantAccess(prisma, userId, tenant.id)) return null; + + dropTenantContext(req, tenant); + return { + userId, + tenant: tenant.slug, + source: tenantSource(req), + method: req.method, + path: getRequestRouteTemplate(req), + }; +} + +/** + * Credential routes prove a NEW identity (credentials, guest, reset or verify + * token). They declare this exception on the route so Express' own matching + * (case-insensitive with an optional trailing slash) controls it instead of a + * second path list. A different session sent with credentials must not change + * tenant resolution for these endpoints. + */ +export const credentialRoute: express.RequestHandler = (req, _res, next) => { + const tenant = getDeniedTenant(req); + if (tenant) { + req.tenant = tenant; + req.tenantId = tenant.id; + clearTenantAccessDenied(req); + } + next(); +}; + +export function createTenantAccessMiddleware(prisma: PrismaClient): express.RequestHandler { + return (req, res, next) => { + void (async () => { + const tenant = req.tenant; + try { + const denial = await enforceTenantMembership(prisma, req); + if (denial) { + // A refusal is only logged once it still stands when the response + // ends; a credential route that takes its tenant back via + // credentialRoute leaves no denial behind, so it logs no event. + let logged = false; + const flush = (): void => { + if (logged) return; + logged = true; + if (isTenantAccessDenied(req)) { + logger.warn({ + event: 'tenant.access_denied', + ...denial, + path: getRequestRouteTemplate(req), + status: res.statusCode, + }); + } + }; + res.once('finish', flush); + res.once('close', flush); + } + } catch (e: unknown) { + // Fail closed: without a verdict the request must not keep a tenant. + logger.error({ + event: 'tenant.access_check_failed', + path: getRequestRouteTemplate(req), + error: e instanceof Error ? e.message : String(e), + }); + if (tenant) dropTenantContext(req, tenant); + } + next(); + })(); + }; +} diff --git a/apps/server/src/api/middleware/uploadBudget.integration.test.ts b/apps/server/src/api/middleware/uploadBudget.integration.test.ts new file mode 100644 index 00000000..f92f16fd --- /dev/null +++ b/apps/server/src/api/middleware/uploadBudget.integration.test.ts @@ -0,0 +1,102 @@ +import request from 'supertest'; +import { afterAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { uploadTransport, writeBytes } from '../../../test/fixtures/uploadFixture.js'; +import { registerTmjImportRoute } from '../routes/tmj.import.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +registerTmjImportRoute(app, fixture.prisma); +app.use(errorHandler); +afterAll(() => fixture.close()); +const MiB = 1024 * 1024; + +it('bounds cumulative bytes of a chunked multipart body before buffering', async () => { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const transport = await uploadTransport(app); + const { req, result } = transport.open(`/maps/${map.id}/import-tmj`, { + 'X-Tenant': tenant.slug, + Authorization: `Bearer ${owner.session}`, + 'Content-Type': 'multipart/form-data; boundary=fixture-budget', + }); + try { + await transport.ready(1); + req.write( + '--fixture-budget\r\nContent-Disposition: form-data; name="file"; filename="map.tmj"\r\nContent-Type: application/json\r\n\r\n', + ); + const json = JSON.stringify({ width: 2, height: 2, tilewidth: 32, tileheight: 32, layers: [], tilesets: [] }); + req.write(json); + await writeBytes(req, 10 * MiB - 1 - Buffer.byteLength(json)); + for (let i = 0; i < 10; i++) { + req.write( + `\r\n--fixture-budget\r\nContent-Disposition: form-data; name="images"; filename="image-${i}.png"\r\nContent-Type: image/png\r\n\r\n`, + ); + await writeBytes(req, 5 * MiB - 1); + } + for (let i = 0; i < 16; i++) { + req.write(`\r\n--fixture-budget\r\nContent-Disposition: form-data; name="field${i}"\r\n\r\n`); + await writeBytes(req, 64 * 1024 - 1); + } + req.end('\r\n--fixture-budget--\r\n'); + expect((await result).status).toBe(413); + expect((await fixture.prisma.map.findUniqueOrThrow({ where: { id: map.id } })).width).toBe(4); + } finally { + req.destroy(); + await transport.close(); + } +}, 90_000); + +it('shares the per-user budget across sessions and returns 429 with Retry-After on attempt eleven', async () => { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const second = await fixture.session(owner.id, tenant.id); + for (let i = 0; i < 10; i++) { + const response = await request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${i % 2 ? second.token : owner.session}`) + .set('Content-Type', 'multipart/form-data; boundary=fixture-broken') + .send('malformed'); + expect(response.status).not.toBe(429); + } + const result = await request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${owner.apiToken}`) + .set('Content-Type', 'multipart/form-data; boundary=fixture-broken') + .send('malformed'); + expect(result.status).toBe(429); + expect(Number(result.headers['retry-after'])).toBeGreaterThan(0); +}); + +it('rejects a third concurrent upload and releases slots after abort', async () => { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const transport = await uploadTransport(app); + const headers = { + 'X-Tenant': tenant.slug, + Authorization: `Bearer ${owner.session}`, + 'Content-Type': 'multipart/form-data; boundary=fixture-open', + }; + const first = transport.open(`/maps/${map.id}/import-tmj`, headers); + const second = transport.open(`/maps/${map.id}/import-tmj`, headers); + try { + await transport.ready(2); + const prefix = '--fixture-open\r\nContent-Disposition: form-data; name="file"; filename="map.tmj"\r\n\r\n{'; + first.req.write(prefix); + second.req.write(prefix); + const result = await request(app).post(`/maps/${map.id}/import-tmj`).set(headers).send('malformed'); + expect(result.status).toBe(429); + expect(Number(result.headers['retry-after'])).toBeGreaterThan(0); + first.req.destroy(); + second.req.destroy(); + } finally { + first.req.destroy(); + second.req.destroy(); + await transport.close(); + } + const afterAbort = await request(app).post(`/maps/${map.id}/import-tmj`).set(headers).send('malformed'); + expect(afterAbort.status).not.toBe(429); +}, 20_000); diff --git a/apps/server/src/api/middleware/uploadPolicy.ts b/apps/server/src/api/middleware/uploadPolicy.ts new file mode 100644 index 00000000..30b69537 --- /dev/null +++ b/apps/server/src/api/middleware/uploadPolicy.ts @@ -0,0 +1,248 @@ +import type express from 'express'; +import multer from 'multer'; +import { Transform, type Writable } from 'node:stream'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { requireAuth, requireApiToken, requireInternalOwner, requireMembership, getTenantFromReq } from '../utils/authHelpers.js'; +import { detectMimeFromMagic } from '../utils/mediaMime.js'; +import { AppError } from '../../errors/AppError.js'; + +const MiB = 1024 * 1024; +export type UploadKind = 'asset' | 'avatar' | 'npc' | 'admin_map' | 'tmj'; +const REQUEST_LIMITS: Record = { asset: 51 * MiB, avatar: 6 * MiB, npc: 101 * MiB, admin_map: 51 * MiB, tmj: 61 * MiB }; +const FILE_LIMITS: Record = { asset: 50 * MiB, avatar: 5 * MiB, npc: 100 * MiB, admin_map: 50 * MiB, tmj: 10 * MiB }; +type Budget = { start: number; attempts: number; active: number }; +const budgets = new Map(); +const WINDOW_MS = 10 * 60_000; +const abortParsers = new WeakMap void>(); +const reportParserErrors = new WeakMap void>(); + +/** Verify identity and role before any parser starts collecting data. */ +export function uploadGuard(prisma: PrismaClient, kind: UploadKind): express.RequestHandler { + return (req, res, next) => { + void (async () => { + const auth = requireAuth(req) ?? await requireApiToken(req, prisma); + if (!auth) { res.status(401).json({ error: 'unauthorized' }); return; } + const global = kind === 'asset' || kind === 'avatar' || kind === 'admin_map'; + const tenant = getTenantFromReq(req); + if (!global && !tenant) { + res.status(400).json({ error: 'tenant_required' }); + return; + } + const member = global + ? null + : await requireMembership(req, auth.userId, prisma); + const allowed = global + ? await requireInternalOwner(req, auth.userId, prisma) + : !!tenant && + (member?.role === 'owner' || member?.role === 'admin'); + if (!allowed) { + if ( + kind === 'tmj' && + tenant && + member && + member.role !== 'owner' && + member.role !== 'admin' + ) { + res.status(403).json({ error: 'forbidden - admin required' }); + return; + } + res.status(403).json({ error: 'forbidden' }); + return; + } + const now = Date.now(); + for (const [key, value] of budgets) if (!value.active && now - value.start >= WINDOW_MS) budgets.delete(key); + const budget = budgets.get(auth.userId) ?? { start: now, attempts: 0, active: 0 }; + if (now - budget.start >= WINDOW_MS) { budget.start = now; budget.attempts = 0; } + budgets.set(auth.userId, budget); + if (budget.active >= 2 || budget.attempts >= 10) { + res.setHeader('Retry-After', budget.active >= 2 ? 1 : Math.max(1, Math.ceil((budget.start + WINDOW_MS - now) / 1000))); + next(AppError.tooManyRequests('Please wait before another upload.', 'UPLOAD_RATE_LIMITED')); + return; + } + budget.attempts++; + budget.active++; + let released = false; + const release = () => { if (!released) { released = true; budget.active--; } }; + res.once('finish', release); + res.once('close', release); + req.once('aborted', release); + req.once('error', release); + const limit = REQUEST_LIMITS[kind]; + const declared = Number(req.headers['content-length']); + if (Number.isFinite(declared) && declared > limit) { + res.setHeader('Connection', 'close'); + next( + new AppError('Upload request too large.', 413, 'UPLOAD_TOO_LARGE'), + ); + return; + } + next(); + })().catch(next); + }; +} + +/** Enforce field-specific limits before Buffer.concat in addition to Busboy limits. */ +function createUploadStorage(kind: UploadKind): multer.StorageEngine { + return { + _handleFile(req, file, callback) { + let prefix = Buffer.alloc(0); + let limit = + kind === 'tmj' && file.fieldname === 'images' + ? 5 * MiB + : FILE_LIMITS[kind]; + const chunks: Buffer[] = []; + let size = 0; + let finished = false; + const finish = (error: Error | null) => { + if (finished) { + return; + } + finished = true; + if (error) { + abortParsers.get(req)?.(error); + } + callback( + error, + error ? undefined : { buffer: Buffer.concat(chunks, size), size }, + ); + chunks.length = 0; + }; + file.stream.on('data', (chunk: Buffer) => { + if (finished) { + return; + } + size += chunk.length; + if (kind === 'npc') { + if (prefix.length < 4) { + prefix = Buffer.concat([ + prefix, + chunk.subarray(0, 4 - prefix.length), + ]); + } + const mime = + prefix.length === 4 + ? detectMimeFromMagic(prefix) ?? file.mimetype + : file.mimetype; + limit = mime.startsWith('audio/') + ? 25 * MiB + : FILE_LIMITS[kind]; + } + if (size > limit) { + finish(new AppError('File too large.', 413, 'UPLOAD_TOO_LARGE')); + return; + } + chunks.push(chunk); + }); + file.stream.once('error', finish); + file.stream.once('end', () => finish(null)); + }, + _removeFile(_req, file, callback) { + delete (file as Partial).buffer; + callback(null); + }, + }; +} + +function createStreamHandler( + kind: UploadKind, +): (req: express.Request, parser: Writable) => void { + return (req, parser) => { + let bytes = 0; + let stopped = false; + const meter = new Transform({ + transform(chunk: Buffer, _encoding, done) { + bytes += chunk.length; + if (bytes > REQUEST_LIMITS[kind]) { + done( + new AppError( + 'Upload request too large.', + 413, + 'UPLOAD_TOO_LARGE', + ), + ); + return; + } + done(null, chunk); + }, + }); + const stop = (error: Error) => { + if (stopped) { + return; + } + stopped = true; + req.unpipe(meter); + meter.unpipe(parser); + meter.destroy(); + parser.destroy(error); + req.resume(); + reportParserErrors.get(req)?.(error); + }; + abortParsers.set(req, stop); + meter.once('error', stop); + parser.once('error', stop); + parser.once('close', () => { + req.unpipe(meter); + meter.destroy(); + abortParsers.delete(req); + }); + parser.on( + 'field', + (_name: string, _value: string, info: { valueTruncated: boolean }) => { + if (info.valueTruncated) { + stop( + new AppError('Upload field too large.', 413, 'UPLOAD_TOO_LARGE'), + ); + } + }, + ); + for (const event of ['partsLimit', 'filesLimit', 'fieldsLimit']) { + parser.once(event, () => + stop(new AppError('Too many upload parts.', 413, 'UPLOAD_TOO_LARGE')), + ); + } + req.pipe(meter).pipe(parser); + }; +} + +export function uploadParser(kind: UploadKind): multer.Multer { + const storage = createUploadStorage(kind); + const files = kind === 'tmj' ? 11 : 1; + // Multer 2.4.0 documents streamHandler; the installed types do not yet include + // this option. Keep the existing version and lockfile. + const options: multer.Options & { + streamHandler: (req: express.Request, parser: Writable) => void; + } = { + storage, + limits: { + fileSize: FILE_LIMITS[kind] + 1, + files, + fields: 16, + fieldSize: 64 * 1024 + 1, + parts: files + 17, + }, + streamHandler: createStreamHandler(kind), + }; + return multer(options); +} + +/** Treat Multer limits as client errors without logging names, filenames or bodies. */ +export function boundedMultipart(parser: express.RequestHandler): express.RequestHandler { + return (req, res, next) => { + let completed = false; + const finish = (error?: unknown) => { + if (completed) return; + completed = true; + reportParserErrors.delete(req); + if (res.headersSent || res.destroyed || req.aborted) return; + if (error instanceof multer.MulterError) { + const size = ['LIMIT_FILE_SIZE', 'LIMIT_FILE_COUNT', 'LIMIT_FIELD_COUNT', 'LIMIT_FIELD_VALUE', 'LIMIT_PART_COUNT'].includes(error.code) + || (error.code === 'LIMIT_UNEXPECTED_FILE' && (error.field === 'file' || error.field === 'images')); + next(new AppError(size ? 'Upload limit exceeded.' : 'Invalid upload.', size ? 413 : 400, size ? 'UPLOAD_TOO_LARGE' : 'UPLOAD_INVALID')); + return; + } + next(error); + }; + reportParserErrors.set(req, finish); + parser(req, res, finish); + }; +} diff --git a/apps/server/src/api/middleware/verificationSessionScope.ts b/apps/server/src/api/middleware/verificationSessionScope.ts new file mode 100644 index 00000000..16d9dfd8 --- /dev/null +++ b/apps/server/src/api/middleware/verificationSessionScope.ts @@ -0,0 +1,14 @@ +import express from 'express'; + +/** Use Express matching for the only operations a restricted session may reach. */ +export function createVerificationSessionScope(): express.RequestHandler { + const routes = express.Router(); + const allow: express.RequestHandler = (_req, _res, next) => next('router'); + routes.post(['/auth/login', '/auth/logout', '/auth/verify/request', '/auth/verify', '/invites/accept'], allow); + routes.get(['/auth/me', '/auth/verify/status'], allow); + routes.use((_req, res) => { + res.status(403).json({ code: 'EMAIL_VERIFICATION_REQUIRED', + error: 'Confirm your email address and sign in before using this resource.' }); + }); + return routes; +} diff --git a/apps/server/src/api/requestLogger.ts b/apps/server/src/api/requestLogger.ts index 5cf647e6..5c8bca78 100644 --- a/apps/server/src/api/requestLogger.ts +++ b/apps/server/src/api/requestLogger.ts @@ -1,5 +1,6 @@ import type { Request, Response, NextFunction } from 'express'; import { logger } from '../logger.js'; +import { getRequestRouteTemplate } from './utils/requestRoute.js'; import crypto from 'crypto'; function genId(): string { @@ -18,7 +19,6 @@ export function requestLogger(req: Request, res: Response, next: NextFunction) { event: 'http.request', id: reqId, method: req.method, - path: req.path, ua: (req.headers['user-agent'] || '').toString(), }); } catch {} @@ -29,7 +29,7 @@ export function requestLogger(req: Request, res: Response, next: NextFunction) { event: 'http.response', id: reqId, method: req.method, - path: req.path, + path: getRequestRouteTemplate(req), status: res.statusCode, durationMs: ms, }); diff --git a/apps/server/src/api/requestTelemetry.test.ts b/apps/server/src/api/requestTelemetry.test.ts new file mode 100644 index 00000000..6e5fe064 --- /dev/null +++ b/apps/server/src/api/requestTelemetry.test.ts @@ -0,0 +1,132 @@ +/** + * Routenmetadaten in Request-Logs und Metriklabels (Q-DISC-12). + * + * Führt test/fixtures/requestTelemetry.ts genau einmal als echten + * Node-Unterprozess aus und prüft nur dessen echte Ausgabe: Pino-Logzeilen + * plus eine JSON-Ergebniszeile. Erwartet: http.request ohne path-Feld, + * Response-/Labelpfad als baseUrl plus Routentemplate ("/api/invites/:code" + * bei Mounts, "" ohne Treffer), keine konkreten Parameter, + * Kennungen oder Querystrings in Logs oder Labels. + */ +import { spawnSync } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { beforeAll, describe, expect, it } from 'vitest'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const fixture = path.resolve(here, '../../test/fixtures/requestTelemetry.ts'); +const RESULT_MARKER = 'qdisc12-telemetry-result'; +const LEAKS = ['QDISC12_CODE', 'QDISC12_MISS', 'QDISC12_MOUNT', '?x=y']; + +interface LogLine { + event?: string; + id?: string; + method?: string; + path?: string; + status?: number; +} + +interface MetricValue { + labels: Record; + value: number; +} + +interface FixtureOutput { + logs: LogLine[]; + cases: { key: string; status: number }[]; + metricValues: MetricValue[]; +} + +function runFixture(): FixtureOutput { + const run = spawnSync(process.execPath, ['--import', 'tsx', fixture], { + cwd: path.resolve(here, '..'), + encoding: 'utf8', + timeout: 120000, + }); + expect(run.error).toBeUndefined(); + expect(run.status).toBe(0); + const logs: LogLine[] = []; + let cases: FixtureOutput['cases'] | null = null; + let metricValues: MetricValue[] | null = null; + for (const line of String(run.stdout).split('\n')) { + if (!line.startsWith('{')) continue; + const parsed = JSON.parse(line) as LogLine & { + marker?: string; + cases?: FixtureOutput['cases']; + metricValues?: MetricValue[]; + }; + if (parsed.marker === RESULT_MARKER) { + cases = parsed.cases ?? null; + metricValues = parsed.metricValues ?? null; + } else if (typeof parsed.event === 'string') { + logs.push(parsed); + } + } + expect(cases).not.toBeNull(); + expect(metricValues).not.toBeNull(); + return { logs, cases: cases as FixtureOutput['cases'], metricValues: metricValues as MetricValue[] }; +} + +function findLog(logs: LogLine[], id: string, event: string): LogLine { + const found = logs.find((l) => l.id === id && l.event === event); + expect(found).toBeDefined(); + return found as LogLine; +} + +let output: FixtureOutput; + +beforeAll(() => { + output = runFixture(); +}); + +describe('request route metadata', () => { + it('omits the path field from pending request entries', () => { + expect(output.cases.map((c) => c.status)).toEqual([200, 404, 200]); + for (const id of ['qdisc12-a', 'qdisc12-b', 'qdisc12-c']) { + const entry = findLog(output.logs, id, 'http.request'); + expect(entry.method).toBe('GET'); + expect(entry).not.toHaveProperty('path'); + } + }); + + it('reports the route template for a matched response', () => { + const response = findLog(output.logs, 'qdisc12-a', 'http.response'); + expect(response.method).toBe('GET'); + expect(response.status).toBe(200); + expect(response.path).toBe('/invites/:code'); + }); + + it('reports for a response without route match', () => { + const response = findLog(output.logs, 'qdisc12-b', 'http.response'); + expect(response.method).toBe('GET'); + expect(response.status).toBe(404); + expect(response.path).toBe(''); + }); + + it('reports the mount prefix plus route template for a mounted response', () => { + const response = findLog(output.logs, 'qdisc12-c', 'http.response'); + expect(response.method).toBe('GET'); + expect(response.status).toBe(200); + expect(response.path).toBe('/api/invites/:code'); + }); + + it('labels metrics with only the three route templates', () => { + const routes = output.metricValues + .filter((v) => v.labels['method'] === 'GET' && v.labels['le'] === '+Inf') + .map((v) => v.labels['route']); + expect(routes.length).toBeGreaterThan(0); + expect(new Set(routes)).toEqual(new Set(['/invites/:code', '', '/api/invites/:code'])); + }); + + it('leaks no concrete identifiers or query strings into logs or labels', () => { + const haystacks = [ + JSON.stringify(output.logs), + JSON.stringify(output.metricValues.map((v) => v.labels)), + ]; + for (const haystack of haystacks) { + for (const leak of LEAKS) { + expect(haystack).not.toContain(leak); + } + } + }); +}); diff --git a/apps/server/src/api/routes/accountMail.integration.test.ts b/apps/server/src/api/routes/accountMail.integration.test.ts new file mode 100644 index 00000000..76ab6a2a --- /dev/null +++ b/apps/server/src/api/routes/accountMail.integration.test.ts @@ -0,0 +1,84 @@ +import crypto from 'crypto'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerMiscRoutes } from './misc.js'; +import { registerAuthRoutes } from './auth.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +registerMiscRoutes(app, fixture.prisma); +registerAuthRoutes(app, fixture.prisma); +const originalBase = process.env.PUBLIC_BASE_URL; +beforeAll(() => { + process.env.PUBLIC_BASE_URL = 'https://app.example.test'; +}); +afterAll(async () => { + if (originalBase === undefined) delete process.env.PUBLIC_BASE_URL; + else process.env.PUBLIC_BASE_URL = originalBase; + await fixture.close(); +}); + +it('prevents tenant administrators from overwriting another account email address', async () => { + const { tenant } = await fixture.tenant(); + const admin = await fixture.caller(tenant, 'admin'); + const target = await fixture.caller(tenant); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: target.id } }); + const result = await request(app) + .patch(`/users/${target.id}`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({ email: `fixture-account-${crypto.randomUUID()}@example.test` }); + expect(result.status).toBe(403); + const after = await fixture.prisma.user.findUniqueOrThrow({ where: { id: target.id } }); + expect(after.email === before.email).toBe(true); + expect(after.emailVerifiedAt?.getTime()).toBe(before.emailVerifiedAt?.getTime()); +}); + +for (const route of ['me', 'users/self']) { + it(`PATCH /${route} preserves the active email address until confirmation`, async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + const email = `fixture-account-${crypto.randomUUID()}@example.test`; + const path = route === 'me' ? '/me' : `/users/${caller.id}`; + const result = await request(app) + .patch(path) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ email }); + const after = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + expect(after.email === before.email).toBe(true); + expect(after.emailVerifiedAt?.getTime()).toBe(before.emailVerifiedAt?.getTime()); + expect(result.status).toBe(202); + expect(result.body.emailChangePending).toBe(true); + }); +} + +it('does not confirm a different account address with an old confirmation link', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + const raw = crypto.randomBytes(32).toString('hex'); + await fixture.prisma.emailVerification.create({ + data: { + userId: caller.id, + email: before.email, + sourceEmail: before.email, + purpose: 'verify', + readyAt: new Date(), + token: crypto.createHash('sha256').update(raw).digest('hex'), + expiresAt: new Date(Date.now() + 3_600_000), + }, + }); + await fixture.prisma.user.update({ + where: { id: caller.id }, + data: { + email: `fixture-account-${crypto.randomUUID()}@example.test`, + emailVerifiedAt: null, + }, + }); + const result = await request(app).post('/auth/verify').send({ token: raw }); + expect(result.status).toBe(400); + expect((await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } })).emailVerifiedAt).toBeNull(); +}); diff --git a/apps/server/src/api/routes/accountProfile.ts b/apps/server/src/api/routes/accountProfile.ts new file mode 100644 index 00000000..0fa9a98e --- /dev/null +++ b/apps/server/src/api/routes/accountProfile.ts @@ -0,0 +1,35 @@ +import type express from 'express'; +import { z } from 'zod'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { displayNameSchema, invalidNameBodyFor } from '../utils/displayName.js'; +import { normalizeEmailForStorage } from '../utils/authHelpers.js'; +import { issueEmailProof } from '../utils/emailProof.js'; +import { emailProofResponse } from './auth.verify.js'; + +const profileSchema = z.object({ email: z.string().email().optional(), name: displayNameSchema.nullish() }); + +/** Share the confirmed email-change flow between both self-update routes. */ +export async function updateOwnProfile(prisma: PrismaClient, userId: string, body: unknown, res: express.Response): Promise { + const parsed = profileSchema.safeParse(body); + if (!parsed.success) { + res.status(400).json(invalidNameBodyFor(parsed.error) ?? { error: 'Invalid email address.' }); + return; + } + const { name, email } = parsed.data; + if (!name && !email) { res.status(400).json({ error: 'nothing to update' }); return; } + const current = await prisma.user.findUnique({ where: { id: userId } }); + if (!current) { res.status(404).json({ error: 'Account not found.' }); return; } + const nextEmail = email ? normalizeEmailForStorage(email) : current.email; + if (nextEmail !== current.email) { + const other = await prisma.user.findFirst({ where: { id: { not: userId }, email: { equals: nextEmail, mode: 'insensitive' } }, select: { id: true } }); + if (other) { res.status(400).json({ code: 'EMAIL_IN_USE', error: 'Email address already in use.' }); return; } + const outcome = await issueEmailProof({ prisma, userId, purpose: 'email_change', email: nextEmail }); + if (outcome.status !== 'issued') { emailProofResponse(res, outcome); return; } + if (name) await prisma.user.update({ where: { id: userId }, data: { name } }); + res.status(202).json({ id: userId, email: current.email, name: name ?? current.name, + emailVerified: !!current.emailVerifiedAt, emailChangePending: true, pendingEmail: nextEmail, sent: true }); + return; + } + const updated = await prisma.user.update({ where: { id: userId }, data: { ...(name ? { name } : {}) } }); + res.json({ id: updated.id, email: updated.email, name: updated.name }); +} diff --git a/apps/server/src/api/routes/admin.passwordReset.integration.test.ts b/apps/server/src/api/routes/admin.passwordReset.integration.test.ts new file mode 100644 index 00000000..74582fb6 --- /dev/null +++ b/apps/server/src/api/routes/admin.passwordReset.integration.test.ts @@ -0,0 +1,142 @@ +import { execFile } from 'node:child_process'; +import request from 'supertest'; +import { promisify } from 'node:util'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerAdminPasswordResetRoutes } from './admin.passwordReset.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +registerAdminPasswordResetRoutes(app, fixture.prisma); +const originalBase = process.env.PUBLIC_BASE_URL; +beforeAll(() => { + process.env.PUBLIC_BASE_URL = 'https://app.example.test'; +}); +afterAll(async () => { + if (originalBase === undefined) delete process.env.PUBLIC_BASE_URL; + else process.env.PUBLIC_BASE_URL = originalBase; + await fixture.close(); +}); + +it('returns only delivery confirmation and no reset secrets to tenant administrators', async () => { + const { tenant } = await fixture.tenant(); + const admin = await fixture.caller(tenant, 'admin'); + const target = await fixture.caller(tenant); + const result = await request(app) + .post(`/admin/users/${target.id}/reset-token`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({}); + expect('token' in result.body || 'resetUrl' in result.body).toBe(false); + expect(result.status).toBe(200); + expect(result.body.sent).toBe(true); +}); + +it('prevents tenant administrators from resetting an owner password', async () => { + const { tenant } = await fixture.tenant(); + const admin = await fixture.caller(tenant, 'admin'); + const owner = await fixture.caller(tenant, 'owner'); + const result = await request(app) + .post(`/admin/users/${owner.id}/reset-token`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({}); + expect(result.status).toBe(403); + expect(await fixture.prisma.passwordReset.count({ where: { userId: owner.id } })).toBe(0); +}); + +it('prevents tenant administrators from resetting accounts belonging to other tenants', async () => { + const own = await fixture.tenant(); + const other = await fixture.tenant(); + const admin = await fixture.caller(own.tenant, 'admin'); + const target = await fixture.caller(own.tenant); + await fixture.prisma.membership.create({ data: { tenantId: other.tenant.id, userId: target.id } }); + const result = await request(app) + .post(`/admin/users/${target.id}/reset-token`) + .set('X-Tenant', own.tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({}); + expect(result.status).toBe(403); + expect(await fixture.prisma.passwordReset.count({ where: { userId: target.id } })).toBe(0); +}); + +it('returns user_not_in_tenant for multi-tenant accounts outside the requesting tenant', async () => { + const own = await fixture.tenant(); + const first = await fixture.tenant(); + const second = await fixture.tenant(); + const admin = await fixture.caller(own.tenant, 'admin'); + const target = await fixture.caller(first.tenant); + await fixture.prisma.membership.create({ + data: { tenantId: second.tenant.id, userId: target.id }, + }); + const result = await request(app) + .post(`/admin/users/${target.id}/reset-token`) + .set('X-Tenant', own.tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({}); + expect(result.status).toBe(403); + expect(result.body).toEqual({ error: 'user_not_in_tenant' }); + expect( + await fixture.prisma.passwordReset.count({ + where: { userId: target.id }, + }), + ).toBe(0); +}); + +it('returns platform_admin_required when the target is an owner', async () => { + const { tenant } = await fixture.tenant(); + const admin = await fixture.caller(tenant, 'admin'); + const owner = await fixture.caller(tenant, 'owner'); + const result = await request(app) + .post(`/admin/users/${owner.id}/reset-token`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({}); + expect(result.status).toBe(403); + expect(result.body).toEqual({ error: 'platform_admin_required' }); + expect( + await fixture.prisma.passwordReset.count({ + where: { userId: owner.id }, + }), + ).toBe(0); +}); + +it('revokes the new token when delivery fails', async () => { + const result = await promisify(execFile)( + process.execPath, + ['--import', 'tsx', 'test/fixtures/adminResetDeliveryProbe.ts'], + { + cwd: process.cwd(), + env: { ...process.env, NODE_ENV: 'test' }, + timeout: 45_000, + maxBuffer: 256_000, + }, + ); + const line = result.stdout + .split('\n') + .find((value) => value.startsWith('ADMIN_RESET_DELIVERY_RESULT:')); + if (!line) { + throw new Error('The admin reset probe returned no result evidence.'); + } + const parsed: unknown = JSON.parse( + line.slice('ADMIN_RESET_DELIVERY_RESULT:'.length), + ); + expect( + !!parsed && + typeof parsed === 'object' && + 'status' in parsed && + parsed.status === 503, + ).toBe(true); + expect( + !!parsed && + typeof parsed === 'object' && + 'secret' in parsed && + parsed.secret === false, + ).toBe(true); + expect( + !!parsed && + typeof parsed === 'object' && + 'unused' in parsed && + parsed.unused === 0, + ).toBe(true); +}, 50_000); diff --git a/apps/server/src/api/routes/admin.passwordReset.test.ts b/apps/server/src/api/routes/admin.passwordReset.test.ts index 70b62939..efcf876b 100644 --- a/apps/server/src/api/routes/admin.passwordReset.test.ts +++ b/apps/server/src/api/routes/admin.passwordReset.test.ts @@ -1,164 +1,63 @@ -/** - * The admin-issued reset token must still work end to end after reset tokens - * moved to hashed storage: the admin route and POST /auth/reset are two sides - * of one contract, and a token issued out of band is worthless if the redeem - * path cannot match it. This is the regression that a hashed rewrite invites, - * so it gets its own test. - */ -import express from 'express'; -import cookieParser from 'cookie-parser'; +import crypto from 'node:crypto'; import request from 'supertest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; - -vi.hoisted(() => { - process.env.JWT_SECRET = 'admin-reset-test-secret'; - process.env.API_TOKEN_PEPPER = 'admin-reset-test-pepper'; - process.env.NODE_ENV = 'test'; -}); - -vi.mock('../../logger.js', () => ({ - logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }, -})); - -vi.mock('../middleware/rateLimit.js', () => { - const passthrough = (_req: unknown, _res: unknown, next: () => void) => next(); - return { - loginRateLimiter: passthrough, - registrationRateLimiter: passthrough, - passwordResetRateLimiter: passthrough, - forgotPasswordEmailRateLimiter: passthrough, - emailVerificationRateLimiter: passthrough, - }; -}); - -import { registerAdminPasswordResetRoutes } from './admin.passwordReset.js'; -import { registerAuthRoutes } from './auth.js'; -import { setAuthResolution } from '../utils/authState.js'; -import { clearSessionCache } from '../utils/sessionCache.js'; -import type { PrismaClient } from '../../generated/prisma/index.js'; - -interface ResetRow { - token: string; - userId: string; - usedAt: Date | null; - expiresAt: Date; -} - -let resets: ResetRow[]; -let passwordHash: string | null; - -const TARGET = { id: 'user-target', email: 'target@example.test', name: 'Target' }; -const INTERNAL = { id: 'internal-tenant', slug: 'internal' }; - -function makePrisma(): PrismaClient { - return { - user: { - findUnique: ({ where }: { where: { id: string } }) => - Promise.resolve(where.id === TARGET.id ? { ...TARGET, passwordHash } : null), - update: ({ data }: { data: { passwordHash?: string } }) => { - if (data.passwordHash) passwordHash = data.passwordHash; - return Promise.resolve({ ...TARGET, passwordHash }); - }, - }, - tenant: { - findUnique: ({ where }: { where: { slug?: string } }) => - Promise.resolve(where.slug === 'internal' ? INTERNAL : null), - }, - membership: { - findUnique: () => Promise.resolve({ role: 'owner' }), - }, - session: { - findUnique: () => Promise.resolve(null), - deleteMany: () => Promise.resolve({ count: 0 }), - }, - passwordReset: { - create: ({ data }: { data: Omit }) => { - const row: ResetRow = { usedAt: null, ...data }; - resets.push(row); - return Promise.resolve({ ...row }); - }, - findUnique: ({ where }: { where: { token: string } }) => { - const row = resets.find((r) => r.token === where.token); - return Promise.resolve(row ? { ...row } : null); - }, - deleteMany: ({ where }: { where: { userId: string; usedAt: null } }) => { - const before = resets.length; - resets = resets.filter((r) => !(r.userId === where.userId && r.usedAt === null)); - return Promise.resolve({ count: before - resets.length }); - }, - updateMany: ({ - where, - data, - }: { - where: { token: string; usedAt: null; expiresAt: { gt: Date } }; - data: { usedAt: Date }; - }) => { - const matched = resets.filter( - (r) => r.token === where.token && r.usedAt === null && r.expiresAt > where.expiresAt.gt, - ); - matched.forEach((r) => (r.usedAt = data.usedAt)); - return Promise.resolve({ count: matched.length }); - }, - }, - } as unknown as PrismaClient; +import { afterAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +// Real platform-operator contract, including its retained raw-token response. +const setup = createEmailProofFixture(); +const { fixture, app } = setup; +afterAll(() => setup.close()); +async function resetFixture() { + const { tenant } = await fixture.tenant(); + const operator = await fixture.caller(tenant); + let internal = await fixture.prisma.tenant.findUnique({ where: { slug: 'internal' } }); + if (!internal) { + internal = await fixture.prisma.tenant.create({ data: { slug: 'internal', name: 'Internal test tenant' } }); + fixture.tenantIds.push(internal.id); + } + await fixture.prisma.membership.create({ data: { userId: operator.id, tenantId: internal.id, role: 'owner' } }); + const target = await fixture.caller(tenant, 'member', crypto.randomBytes(20).toString('hex')); + const user = await fixture.prisma.user.findUniqueOrThrow({ where: { id: target.id } }); + const result = await request(app) + .post(`/admin/users/${target.id}/reset-token`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${operator.session}`) + .send({}); + expect(result.status).toBe(200); + if (typeof result.body.token !== 'string') throw new Error('Platform-operator reset returned no token.'); + return { target, user, token: result.body.token as string }; } -function makeApp(): express.Application { - const app = express(); - app.use(cookieParser()); - app.use(express.json()); - const prisma = makePrisma(); - // The caller is an authenticated internal owner (super-admin). - app.use((req, _res, next) => { - setAuthResolution(req, { - auth: { userId: 'admin-1', tenantId: INTERNAL.id, sessionId: 'sess-admin', tokenHash: 'hash-admin' }, - }); - (req as express.Request & { tenant?: unknown }).tenant = { ...INTERNAL }; - next(); - }); - registerAdminPasswordResetRoutes(app, prisma); - registerAuthRoutes(app, prisma); - return app; -} - -beforeEach(() => { - resets = []; - passwordHash = 'old-hash'; - clearSessionCache(); +it('accepts the platform-operator token through the real reset handler', async () => { + const value = await resetFixture(); + const result = await request(app) + .post('/auth/reset') + .send({ token: value.token, email: value.user.email, password: crypto.randomBytes(20).toString('hex') }); + expect(result.status).toBe(200); + expect(await fixture.prisma.session.count({ where: { userId: value.target.id } })).toBe(0); }); -describe('admin-issued reset tokens (out-of-band fallback)', () => { - it('returns a token that POST /auth/reset accepts', async () => { - const app = makeApp(); - - const issued = await request(app).post(`/admin/users/${TARGET.id}/reset-token`); - expect(issued.status).toBe(200); - expect(issued.body.token).toBeTruthy(); - - const reset = await request(app) - .post('/auth/reset') - .send({ token: issued.body.token, email: TARGET.email, password: 'brandnewpassword' }); - - expect(reset.status).toBe(200); - expect(passwordHash).not.toBe('old-hash'); - }); - - it('stores the admin token hashed, like the self-service one', async () => { - const app = makeApp(); - - const issued = await request(app).post(`/admin/users/${TARGET.id}/reset-token`); - - expect(resets).toHaveLength(1); - expect(resets[0].token).not.toBe(issued.body.token); - expect(resets[0].token).toMatch(/^[a-f0-9]{64}$/); - }); - - it('burns the admin token after one use', async () => { - const app = makeApp(); - const issued = await request(app).post(`/admin/users/${TARGET.id}/reset-token`); - - await request(app).post('/auth/reset').send({ token: issued.body.token, password: 'brandnewpassword' }).expect(200); +it('stores only the digest of a platform-operator reset token', async () => { + const value = await resetFixture(); + const rows = await fixture.prisma.passwordReset.findMany({ where: { userId: value.target.id } }); + expect(rows).toHaveLength(1); + expect(rows[0].token === value.token).toBe(false); +}); - await request(app).post('/auth/reset').send({ token: issued.body.token, password: 'anotherpassword' }).expect(400); - }); +it('rejects replay of a consumed platform-operator reset token', async () => { + const value = await resetFixture(); + expect( + ( + await request(app) + .post('/auth/reset') + .send({ token: value.token, password: crypto.randomBytes(20).toString('hex') }) + ).status, + ).toBe(200); + expect( + ( + await request(app) + .post('/auth/reset') + .send({ token: value.token, password: crypto.randomBytes(20).toString('hex') }) + ).status, + ).toBe(400); }); diff --git a/apps/server/src/api/routes/admin.passwordReset.ts b/apps/server/src/api/routes/admin.passwordReset.ts index 74a557da..46a80dab 100644 --- a/apps/server/src/api/routes/admin.passwordReset.ts +++ b/apps/server/src/api/routes/admin.passwordReset.ts @@ -3,13 +3,22 @@ import { z } from 'zod'; import { PrismaClient } from '../../generated/prisma/index.js'; import { logger } from '../../logger.js'; import { requireAuth, requireSuperAdmin, requireMembership, getTenantFromReq } from '../utils/authHelpers.js'; -import { issuePasswordResetToken } from '../utils/passwordResetTokens.js'; +import { buildPublicWebLink, requirePublicWebBase } from '../utils/publicLinks.js'; +import { + issuePasswordResetToken, + revokePasswordResetToken, + PASSWORD_RESET_TTL_MINUTES, +} from '../utils/passwordResetTokens.js'; +import { renderPasswordResetMail } from '../utils/passwordResetMail.js'; +import { deliveringEmailModule } from '../utils/emailProof.js'; const paramsSchema = z.object({ id: z.string().min(1) }); /** - * Admin endpoint that creates a password-reset token for a user. The token is - * returned in the response and handed over out of band. + * Admin endpoint that creates a password-reset token for a user. + * A global SuperAdmin receives the token in the response for out-of-band + * handover. A tenant owner/admin triggers a reset mail to the user instead + * and receives only a delivery confirmation. * * This is the FALLBACK path, kept for managed tenants and for users with no * reachable mailbox. The primary path is self-service: POST /auth/forgot mails @@ -19,6 +28,83 @@ const paramsSchema = z.object({ id: z.string().min(1) }); * Authorisation: a global SuperAdmin, OR a tenant owner/admin for users * in their own tenant. */ +// Returns true when allowed. +async function authorizeTenantAdminReset( + prisma: PrismaClient, + req: express.Request, + res: express.Response, + actorUserId: string, + targetUserId: string, +): Promise { + const tenant = getTenantFromReq(req); + if (!tenant) { + res.status(400).json({ error: 'tenant_required' }); + return false; + } + const membership = await requireMembership(req, actorUserId, prisma); + if ( + !membership || + (membership.role !== 'owner' && membership.role !== 'admin') + ) { + res.status(403).json({ error: 'forbidden' }); + return false; + } + const targetMembership = await prisma.membership.findFirst({ + where: { userId: targetUserId, tenantId: tenant.id }, + }); + if (!targetMembership) { + res.status(403).json({ error: 'user_not_in_tenant' }); + return false; + } + const memberships = await prisma.membership.count({ + where: { userId: targetUserId }, + }); + if (targetMembership.role === 'owner' || memberships > 1) { + res.status(403).json({ error: 'platform_admin_required' }); + return false; + } + return true; +} + +async function deliverResetMail( + prisma: PrismaClient, + mail: Awaited>, + target: { email: string; name: string | null; locale: string }, + token: string, + resetUrl: string, + res: express.Response, +): Promise { + let sent = false; + try { + sent = + !!mail && + (await mail.sendRaw( + renderPasswordResetMail({ + to: target.email, + name: target.name ?? '', + resetUrl, + expiresInMinutes: PASSWORD_RESET_TTL_MINUTES, + locale: target.locale === 'en' ? 'en' : 'de', + }), + )); + } catch { + // Do not log provider messages containing mail data. + } + if (!sent) { + try { + await revokePasswordResetToken(prisma, token); + } catch { + // Best effort: the 503 below is the contract, not the cleanup. + } + res.status(503).json({ + code: 'EMAIL_DELIVERY_UNAVAILABLE', + error: 'Password reset email could not be delivered.', + }); + return; + } + res.json({ ok: true, sent: true }); +} + async function handleAdminCreateResetToken( prisma: PrismaClient, req: express.Request, @@ -39,7 +125,7 @@ async function handleAdminCreateResetToken( const target = await prisma.user.findUnique({ where: { id: targetUserId }, - select: { id: true, email: true, name: true }, + select: { id: true, email: true, name: true, locale: true }, }); if (!target) { res.status(404).json({ error: 'user_not_found' }); @@ -47,36 +133,27 @@ async function handleAdminCreateResetToken( } const isSuperAdmin = await requireSuperAdmin(req, prisma); - if (!isSuperAdmin) { - const tenant = getTenantFromReq(req); - if (!tenant) { - res.status(400).json({ error: 'tenant_required' }); - return; - } - const membership = await requireMembership(req, auth.userId, prisma); - if (!membership || (membership.role !== 'owner' && membership.role !== 'admin')) { - res.status(403).json({ error: 'forbidden' }); - return; - } - const targetMembership = await prisma.membership.findFirst({ - where: { userId: targetUserId, tenantId: tenant.id }, - }); - if (!targetMembership) { - res.status(403).json({ error: 'user_not_in_tenant' }); - return; - } + if ( + !isSuperAdmin && + !(await authorizeTenantAdminReset(prisma, req, res, auth.userId, targetUserId)) + ) { + return; } // Shared issuer (api/utils/passwordResetTokens.ts): stores the token hashed // and drops the user's previous unused token, so only one valid reset link // per user exists. It MUST be used here — a hand-rolled row would store a // plaintext token that POST /auth/reset can no longer match. - const { token, expiresAt } = await issuePasswordResetToken(prisma, targetUserId); + const baseUrl = requirePublicWebBase(res, 'admin.password_reset'); + if (!baseUrl) return; - const baseUrl = process.env.PUBLIC_BASE_URL || process.env.BILLING_PUBLIC_URL || ''; - const resetUrl = baseUrl - ? `${baseUrl.replace(/\/$/, '')}/#/reset?token=${token}&email=${encodeURIComponent(target.email)}` - : `/#/reset?token=${token}&email=${encodeURIComponent(target.email)}`; + const mail = !isSuperAdmin ? await deliveringEmailModule() : null; + if (!isSuperAdmin && !mail) { + res.status(503).json({ code: 'EMAIL_DELIVERY_UNAVAILABLE', error: 'Password reset delivery is unavailable. Please contact a platform administrator.' }); + return; + } + const { token, expiresAt } = await issuePasswordResetToken(prisma, targetUserId); + const resetUrl = buildPublicWebLink(baseUrl, `reset?token=${token}&email=${encodeURIComponent(target.email)}`); logger.info({ event: 'admin.password_reset.token_created', @@ -85,6 +162,10 @@ async function handleAdminCreateResetToken( superAdmin: !!isSuperAdmin, }); + if (!isSuperAdmin) { + await deliverResetMail(prisma, mail, target, token, resetUrl, res); + return; + } res.json({ userId: target.id, email: target.email, diff --git a/apps/server/src/api/routes/adminMaps.ts b/apps/server/src/api/routes/adminMaps.ts index a7ac12f5..73652866 100644 --- a/apps/server/src/api/routes/adminMaps.ts +++ b/apps/server/src/api/routes/adminMaps.ts @@ -1,7 +1,7 @@ import type express from 'express'; import { PrismaClient } from '../../generated/prisma/index.js'; import { z } from 'zod'; -import multer from 'multer'; +import { uploadGuard, uploadParser, boundedMultipart } from '../middleware/uploadPolicy.js'; import { logger } from '../../logger.js'; import { requireSuperAdmin } from '../utils/authHelpers.js'; import { pathParam } from '../utils/requestHelpers.js'; @@ -26,7 +26,7 @@ const copyMapSchema = z.object({ newName: z.string().min(1).optional(), }); -const importUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 50 * 1024 * 1024 } }); +const importUpload = uploadParser('admin_map'); async function handleListAdminMaps(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { const admin = await requireSuperAdmin(req, prisma); @@ -247,5 +247,5 @@ export function registerAdminMapRoutes(app: express.Application, prisma: PrismaC app.post('/admin/maps', (req, res) => handleCreateAdminMap(prisma, req, res)); app.delete('/admin/maps/:id', (req, res) => handleDeleteAdminMap(prisma, req, res)); app.post('/admin/maps/:id/copy', (req, res) => handleCopyAdminMap(prisma, req, res)); - app.post('/admin/maps/import', importUpload.single('file'), (req, res) => handleImportAdminMap(prisma, req, res)); + app.post('/admin/maps/import', uploadGuard(prisma, 'admin_map'), boundedMultipart(importUpload.single('file')), (req, res) => handleImportAdminMap(prisma, req, res)); } diff --git a/apps/server/src/api/routes/assetPacks.ts b/apps/server/src/api/routes/assetPacks.ts index ee330a47..537f5a14 100644 --- a/apps/server/src/api/routes/assetPacks.ts +++ b/apps/server/src/api/routes/assetPacks.ts @@ -4,7 +4,7 @@ import path from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs'; import fsp from 'fs/promises'; -import multer from 'multer'; +import { uploadGuard, uploadParser, boundedMultipart } from '../middleware/uploadPolicy.js'; import unzipper from 'unzipper'; import { z } from 'zod'; import { logger } from '../../logger.js'; @@ -346,12 +346,9 @@ export function registerAssetPackRoutes(app: express.Application, prisma: Prisma } catch {} const FALLBACK_ASSET_URL = process.env.FALLBACK_ASSET_URL || '/packs/__fallback__/missing.png'; - const upload = multer({ - storage: multer.memoryStorage(), - limits: { fileSize: 50 * 1024 * 1024 }, - }); + const upload = uploadParser('asset'); - app.post('/asset-packs/upload', upload.single('file'), (req, res) => + app.post('/asset-packs/upload', uploadGuard(prisma, 'asset'), boundedMultipart(upload.single('file')), (req, res) => handleAssetPackUpload(prisma, packsDir, req, res), ); app.get('/asset-packs', (req, res) => handleListAssetPacks(prisma, req, res)); diff --git a/apps/server/src/api/routes/auth.change.rateLimit.integration.test.ts b/apps/server/src/api/routes/auth.change.rateLimit.integration.test.ts new file mode 100644 index 00000000..81b34cd9 --- /dev/null +++ b/apps/server/src/api/routes/auth.change.rateLimit.integration.test.ts @@ -0,0 +1,80 @@ +import crypto from 'crypto'; +import bcrypt from 'bcryptjs'; +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerAuthRoutes } from './auth.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +const previousEnabled = process.env.RATE_LIMIT_ENABLED; +const previousMax = process.env.RATE_LIMIT_PASSWORD_CHANGE_MAX; +const previousWindow = process.env.RATE_LIMIT_PASSWORD_CHANGE_WINDOW_MS; +const previousIpMax = process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_MAX; +const previousIpWindow = process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_WINDOW_MS; + +beforeAll(() => { + process.env.RATE_LIMIT_ENABLED = 'true'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_MAX = '5'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_WINDOW_MS = '900000'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_MAX = '20'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_WINDOW_MS = '900000'; + registerAuthRoutes(app, fixture.prisma); + app.use(errorHandler); +}); +afterAll(async () => { + if (previousEnabled === undefined) delete process.env.RATE_LIMIT_ENABLED; + else process.env.RATE_LIMIT_ENABLED = previousEnabled; + if (previousMax === undefined) delete process.env.RATE_LIMIT_PASSWORD_CHANGE_MAX; + else process.env.RATE_LIMIT_PASSWORD_CHANGE_MAX = previousMax; + if (previousWindow === undefined) delete process.env.RATE_LIMIT_PASSWORD_CHANGE_WINDOW_MS; + else process.env.RATE_LIMIT_PASSWORD_CHANGE_WINDOW_MS = previousWindow; + if (previousIpMax === undefined) delete process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_MAX; + else process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_MAX = previousIpMax; + if (previousIpWindow === undefined) delete process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_WINDOW_MS; + else process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_WINDOW_MS = previousIpWindow; + await fixture.close(); +}); + +describe('password changes with real HTTP and database identities', () => { + it('limits incorrect attempts across sessions before bcrypt and preserves the password', async () => { + const own = await fixture.tenant(); + const password = crypto.randomBytes(24).toString('hex'); + const caller = await fixture.caller(own.tenant, 'member', password); + const second = await fixture.session(caller.id, own.tenant.id); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + const body = { currentPassword: `wrong-${crypto.randomUUID()}`, newPassword: crypto.randomUUID() }; + for (let index = 0; index < 5; index++) { + const response = await request(app) + .post('/auth/change') + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${index % 2 ? second.token : caller.session}`) + .send(body); + expect(response.status).toBe(401); + } + const limited = await request(app) + .post('/auth/change') + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${second.token}`) + .send(body); + expect(limited.status).toBe(429); + expect(Number(limited.headers['retry-after'])).toBeGreaterThan(0); + const after = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + expect(after.passwordHash === before.passwordHash).toBe(true); + + const other = await fixture.caller(own.tenant, 'member', password); + const revoked = await fixture.session(other.id, own.tenant.id); + const newPassword = crypto.randomBytes(24).toString('hex'); + const allowed = await request(app) + .post('/auth/change') + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${other.session}`) + .send({ currentPassword: password, newPassword }); + expect(allowed.status).toBe(200); + expect(await fixture.prisma.session.count({ where: { id: revoked.id } })).toBe(0); + expect(await fixture.prisma.session.count({ where: { id: other.sessionId } })).toBe(1); + const updated = await fixture.prisma.user.findUniqueOrThrow({ where: { id: other.id } }); + expect(await bcrypt.compare(newPassword, updated.passwordHash ?? '')).toBe(true); + }); +}); diff --git a/apps/server/src/api/routes/auth.change.window.integration.test.ts b/apps/server/src/api/routes/auth.change.window.integration.test.ts new file mode 100644 index 00000000..93199cc1 --- /dev/null +++ b/apps/server/src/api/routes/auth.change.window.integration.test.ts @@ -0,0 +1,52 @@ +import crypto from 'node:crypto'; +import request from 'supertest'; +import { afterAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerAuthRoutes } from './auth.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +afterAll(() => fixture.close()); + +it('permits a valid password change after the real rate-limit window expires', async () => { + const keys = [ + 'RATE_LIMIT_ENABLED', + 'RATE_LIMIT_PASSWORD_CHANGE_MAX', + 'RATE_LIMIT_PASSWORD_CHANGE_WINDOW_MS', + 'RATE_LIMIT_PASSWORD_CHANGE_IP_MAX', + ]; + const previous = keys.map((key) => process.env[key]); + process.env.RATE_LIMIT_ENABLED = 'true'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_MAX = '2'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_WINDOW_MS = '5000'; + process.env.RATE_LIMIT_PASSWORD_CHANGE_IP_MAX = '50'; + try { + const { tenant } = await fixture.tenant(); + const password = crypto.randomBytes(20).toString('hex'); + const caller = await fixture.caller(tenant, 'member', password); + const app = fixture.app(); + registerAuthRoutes(app, fixture.prisma); + app.use(errorHandler); + const post = (currentPassword: string) => + request(app) + .post('/auth/change') + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ currentPassword, newPassword: crypto.randomBytes(20).toString('hex') }); + expect((await post('incorrect-password')).status).toBe(401); + expect((await post('incorrect-password')).status).toBe(401); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + expect((await post(password)).status).toBe(429); + expect( + (await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } })).passwordHash === before.passwordHash, + ).toBe(true); + // Use a short real window without changing the product clock. + await new Promise((resolve) => setTimeout(resolve, 5100)); + expect((await post(password)).status).toBe(200); + } finally { + keys.forEach((key, index) => { + if (previous[index] === undefined) delete process.env[key]; + else process.env[key] = previous[index]; + }); + } +}, 30_000); diff --git a/apps/server/src/api/routes/auth.credentialRoutes.integration.test.ts b/apps/server/src/api/routes/auth.credentialRoutes.integration.test.ts new file mode 100644 index 00000000..f4341056 --- /dev/null +++ b/apps/server/src/api/routes/auth.credentialRoutes.integration.test.ts @@ -0,0 +1,192 @@ +import crypto from 'crypto'; +import express from 'express'; +import bcrypt from 'bcryptjs'; +import jwt from 'jsonwebtoken'; +import { PrismaPg } from '@prisma/adapter-pg'; +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { PrismaClient } from '../../generated/prisma/index.js'; +import type { Tenant } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { logger } from '../../logger.js'; +import { resolveTenantBySlug } from '../../tenancy.js'; +import { guestExpiryMiddleware } from '../middleware/guestExpiry.js'; +import { createTenantAccessMiddleware } from '../middleware/tenantAccess.js'; +import { getJwtSecret } from '../utils/authHelpers.js'; +import { createSessionAuthMiddleware, hashSessionToken } from '../utils/sessionAuth.js'; +import { registerAuthRoutes } from './auth.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('auth.credentialRoutes.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +let app: express.Express; +let appBrokenGuard: express.Express; +let brokenPrisma: PrismaClient; +let tenantA: Tenant; +let tenantB: Tenant; +let userX: { id: string; session: string }; +let userY: { id: string; email: string; name: string }; +const password = 'valid-password-123'; + +async function createTenant(): Promise { + const slug = `credential-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant; +} + +async function createSession(userId: string, tenantId: string): Promise { + const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { expiresIn: '1h' }); + await prisma.session.create({ + data: { userId, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return token; +} + +function expectLoginForY(res: request.Response): void { + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ id: userY.id, email: userY.email, name: userY.name }); + + const payload = jwt.verify(res.body.token, getJwtSecret()); + if (typeof payload !== 'object' || payload === null) + throw new Error('login response token must contain a JWT object'); + expect(payload.sub).toBe(userY.id); + expect(payload.tid).toBe(tenantB.id); +} + +function login(path: string) { + return loginOn(app, path); +} + +function loginOn(appInstance: express.Express, path: string) { + return request(appInstance) + .post(path) + .set('x-tenant', tenantB.slug) + .set('Authorization', `Bearer ${userX.session}`) + .send({ email: userY.email, password }); +} + +function denialWarnCalls(warnSpy: ReturnType) { + return warnSpy.mock.calls.filter( + ([first]) => + typeof first === 'object' && first !== null && (first as { event?: string }).event === 'tenant.access_denied', + ); +} + +beforeAll(async () => { + tenantA = await createTenant(); + tenantB = await createTenant(); + + const x = await prisma.user.create({ + data: { email: `credential-x-${crypto.randomUUID()}@example.test`, name: 'User X' }, + }); + userIds.push(x.id); + await prisma.membership.create({ data: { tenantId: tenantA.id, userId: x.id, role: 'member' } }); + userX = { id: x.id, session: await createSession(x.id, tenantA.id) }; + + const y = await prisma.user.create({ + data: { + email: `credential-y-${crypto.randomUUID()}@example.test`, + name: 'User Y', + passwordHash: await bcrypt.hash(password, 10), + }, + }); + userIds.push(y.id); + await prisma.membership.create({ data: { tenantId: tenantB.id, userId: y.id, role: 'member' } }); + userY = { id: y.id, email: y.email, name: y.name ?? '' }; + + app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + void resolveTenantBySlug(prisma, req) + .then((tenant) => { + req.tenant = tenant ?? undefined; + req.tenantId = tenant?.id; + next(); + }) + .catch((error: unknown) => next(error)); + }); + app.use(createSessionAuthMiddleware(prisma)); + app.use(createTenantAccessMiddleware(prisma)); + registerAuthRoutes(app, prisma); + app.use(guestExpiryMiddleware); + + brokenPrisma = new PrismaClient({ + adapter: new PrismaPg({ connectionString: 'postgresql://s1http:s1http@127.0.0.1:1/unreachable' }), + }); + appBrokenGuard = express(); + appBrokenGuard.use(express.json()); + appBrokenGuard.use((req, _res, next) => { + void resolveTenantBySlug(prisma, req) + .then((tenant) => { + req.tenant = tenant ?? undefined; + req.tenantId = tenant?.id; + next(); + }) + .catch((error: unknown) => next(error)); + }); + appBrokenGuard.use(createSessionAuthMiddleware(prisma)); + appBrokenGuard.use(createTenantAccessMiddleware(brokenPrisma)); + registerAuthRoutes(appBrokenGuard, prisma); + appBrokenGuard.use(guestExpiryMiddleware); +}); + +afterAll(async () => { + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await brokenPrisma.$disconnect(); + await prisma.$disconnect(); +}); + +describe('credential login routes with a foreign session (real database)', () => { + it('logs User Y into tenant B on the exact lower-case route', async () => { + expectLoginForY(await login('/auth/login')); + }); + + it('logs User Y into tenant B with a trailing slash', async () => { + expectLoginForY(await login('/auth/login/')); + }); + + it('logs User Y into tenant B with upper-case path segments', async () => { + expectLoginForY(await login('/AUTH/LOGIN')); + }); + + it('logs User Y into tenant B even when the guard cannot reach the database', async () => { + expectLoginForY(await loginOn(appBrokenGuard, '/auth/login')); + }); + + it('logs no tenant denial on credential routes', async () => { + const warnSpy = vi.spyOn(logger, 'warn'); + try { + warnSpy.mockClear(); + expectLoginForY(await login('/auth/login')); + expectLoginForY(await login('/auth/login/')); + expectLoginForY(await login('/AUTH/LOGIN')); + expect(denialWarnCalls(warnSpy)).toHaveLength(0); + } finally { + warnSpy.mockRestore(); + } + }); + + it('logs exactly one tenant denial when a foreign session reads /auth/me', async () => { + const warnSpy = vi.spyOn(logger, 'warn'); + try { + warnSpy.mockClear(); + const res = await request(app) + .get('/auth/me') + .set('x-tenant', tenantB.slug) + .set('Authorization', `Bearer ${userX.session}`); + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'not_member_of_tenant' }); + expect(denialWarnCalls(warnSpy)).toHaveLength(1); + } finally { + warnSpy.mockRestore(); + } + }); +}); diff --git a/apps/server/src/api/routes/auth.flow.test.ts b/apps/server/src/api/routes/auth.flow.test.ts index af99dd08..a15ac5de 100644 --- a/apps/server/src/api/routes/auth.flow.test.ts +++ b/apps/server/src/api/routes/auth.flow.test.ts @@ -1,740 +1,278 @@ -/** - * End-to-end tests for the auth surface as it is actually wired: the - * session-auth middleware in front of the real /auth/* route table, driven - * through supertest against an in-memory Prisma double. - * - * These cover the three findings this block exists for, at the level a live QA - * pass would hit them: - * - * 1. Revoking a session kills the cookie. It used to report success and - * change nothing — /auth/me kept answering 200 for another 30 days. - * 2. Registration establishes a revocable session, and does NOT stamp the - * e-mail as verified; it triggers verification instead. - * 3. A reset token is single-use, expires, and takes every session with it. - */ -import express from 'express'; -import cookieParser from 'cookie-parser'; +import crypto from 'node:crypto'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; import request from 'supertest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; - -// Set before the module graph is imported: the limiters below are built at -// import time, and getJwtSecret/getApiTokenPepper cache on first read. -vi.hoisted(() => { - process.env.JWT_SECRET = 'auth-flow-test-secret'; - process.env.API_TOKEN_PEPPER = 'auth-flow-test-pepper'; - process.env.PUBLIC_BASE_URL = 'https://app.example.test'; - process.env.NODE_ENV = 'test'; -}); - -vi.mock('../../logger.js', () => ({ - logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }, -})); - -// The limiters are process-global and stateful, which would make these flow -// tests order-dependent (the per-address forgot budget is 3/hour, and several -// tests below deliberately fail a login). Their real behaviour is covered in -// rateLimit.test.ts and rateLimit.forgotPassword.test.ts. -vi.mock('../middleware/rateLimit.js', () => { - const passthrough = (_req: unknown, _res: unknown, next: () => void) => next(); - return { - loginRateLimiter: passthrough, - registrationRateLimiter: passthrough, - passwordResetRateLimiter: passthrough, - forgotPasswordEmailRateLimiter: passthrough, - emailVerificationRateLimiter: passthrough, - }; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; +import { issuePasswordResetToken } from '../utils/passwordResetTokens.js'; + +// Exercise the real HTTP, database and Mailpit integrations. +const setup = createEmailProofFixture(); +const { fixture, app } = setup; +beforeAll(async () => { + await setup.mail.connect(); }); - -/** Captured outbound mail, in send order. */ -const sentMail: Array<{ kind: string; to: string; body: string }> = []; -let mailerAvailable = true; -/** Simulates a mail provider that never answers. */ -let mailerHangs = false; - -vi.mock('../../emailLoader.js', () => ({ - sendIfAvailable: vi.fn(async (fn: (mod: unknown) => Promise) => { - if (mailerHangs) return new Promise(() => {}); - if (!mailerAvailable) return false; - const mod = { - sendVerify: (p: { to: string; verifyUrl: string }) => { - sentMail.push({ kind: 'verify', to: p.to, body: p.verifyUrl }); - return Promise.resolve(true); - }, - sendRaw: (p: { to: string; text: string }) => { - sentMail.push({ kind: 'raw', to: p.to, body: p.text }); - return Promise.resolve(true); - }, - sendInvite: (p: { to: string; inviteUrl: string }) => { - sentMail.push({ kind: 'invite', to: p.to, body: p.inviteUrl }); - return Promise.resolve(true); - }, - }; - return fn(mod); - }), -})); - -import { registerAuthRoutes } from './auth.js'; -import { createSessionAuthMiddleware } from '../utils/sessionAuth.js'; -import { clearSessionCache } from '../utils/sessionCache.js'; -import type { PrismaClient } from '../../generated/prisma/index.js'; - -const TENANT = { id: 'tenant-1', slug: 'acme' }; - -// --------------------------------------------------------------------------- -// In-memory Prisma double -// -// Lives in this file rather than a shared helper module because the server -// tsconfig only excludes `*.test.ts` from the build — a helper module would be -// compiled into dist/ and shipped. It covers exactly the delegates the /auth/* -// handlers touch, and it enforces the two constraints these tests depend on: -// the unique `User.email` and the unique `Session.tokenHash`. -// --------------------------------------------------------------------------- - -interface UserRow { - id: string; - email: string; - name: string | null; - passwordHash: string | null; - emailVerifiedAt: Date | null; - locale: string; - avatarId: string | null; - onboardingCompleted: boolean; -} -interface InviteRow { - code: string; - email: string | null; - tenantId: string; - role: string; - usedAt: Date | null; - usedById?: string; -} -interface MembershipRow { - tenantId: string; - userId: string; - role: string; - expiresAt?: Date | null; - createdAt: Date; -} -interface SessionRow { - id: string; - userId: string; - tokenHash: string; - userAgent: string | null; - ipAddress: string | null; - lastActiveAt: Date; - expiresAt: Date; - createdAt: Date; +afterAll(() => setup.close()); +const password = () => crypto.randomBytes(20).toString('hex'); +async function account() { + const { tenant } = await fixture.tenant(); + const secret = password(); + const caller = await fixture.caller(tenant, 'member', secret); + const user = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + return { tenant, caller, user, password: secret }; } -interface ResetRow { - token: string; - userId: string; - usedAt: Date | null; - expiresAt: Date; - createdAt: Date; +function cookieHeader(raw: string) { + return `auth_token=${raw}`; } -interface VerificationRow { - token: string; - userId: string; - email: string; - usedAt: Date | null; - expiresAt: Date; - createdAt: Date; +function cookieFrom(headers: Record): string | null { + const values = headers['set-cookie']; + const cookie = Array.isArray(values) + ? values.find((v: unknown) => typeof v === 'string' && v.startsWith('auth_token=')) + : null; + return typeof cookie === 'string' ? cookie.split(';')[0] : null; } -interface TestDb { - users: Map; - invites: Map; - memberships: MembershipRow[]; - sessions: SessionRow[]; - resets: ResetRow[]; - verifications: VerificationRow[]; - /** Forces `session.create` to fail, standing in for a database outage. */ - failSessionCreate?: boolean; -} - -/** The Prisma error a unique-constraint violation surfaces as. */ -function uniqueViolation(target: string): Error & { code: string } { - return Object.assign(new Error(`Unique constraint failed on ${target}`), { code: 'P2002' }); -} - -let idCounter = 0; -const nextId = (prefix: string) => `${prefix}-${++idCounter}`; - -function matchesEmail(row: { email: string }, where: unknown): boolean { - const filter = (where as { email?: { equals?: string } | string } | undefined)?.email; - const wanted = typeof filter === 'string' ? filter : filter?.equals; - return typeof wanted === 'string' && row.email.toLowerCase() === wanted.toLowerCase(); -} - -function makeTestPrisma(db: TestDb): PrismaClient { - return { - user: { - create: ({ data }: { data: Partial & { email: string } }) => { - if ([...db.users.values()].some((u) => u.email.toLowerCase() === data.email.toLowerCase())) { - return Promise.reject(uniqueViolation('User.email')); - } - const row: UserRow = { - id: nextId('user'), - email: data.email, - name: data.name ?? null, - passwordHash: data.passwordHash ?? null, - emailVerifiedAt: data.emailVerifiedAt ?? null, - locale: data.locale ?? 'de', - avatarId: null, - onboardingCompleted: false, - }; - db.users.set(row.id, row); - return Promise.resolve({ ...row }); - }, - findUnique: ({ where, include }: { where: { id: string }; include?: { presences?: unknown } }) => { - const row = db.users.get(where.id); - if (!row) return Promise.resolve(null); - return Promise.resolve(include?.presences ? { ...row, presences: [] } : { ...row }); - }, - findFirst: ({ where }: { where: unknown }) => { - const row = [...db.users.values()].find((u) => matchesEmail(u, where)); - return Promise.resolve(row ? { ...row } : null); - }, - update: ({ where, data }: { where: { id: string }; data: Partial }) => { - const row = db.users.get(where.id); - if (!row) return Promise.reject(new Error('user not found')); - Object.assign(row, data); - return Promise.resolve({ ...row }); - }, - }, - invite: { - findUnique: ({ where }: { where: { code: string } }) => Promise.resolve(db.invites.get(where.code) ?? null), - update: ({ where, data }: { where: { code: string }; data: Partial }) => { - const row = db.invites.get(where.code); - if (row) Object.assign(row, data); - return Promise.resolve(row ?? null); - }, - }, - membership: { - findUnique: ({ where }: { where: { tenantId_userId: { tenantId: string; userId: string } } }) => { - const { tenantId, userId } = where.tenantId_userId; - const row = db.memberships.find((m) => m.tenantId === tenantId && m.userId === userId); - return Promise.resolve(row ? { id: `m-${row.userId}`, ...row } : null); - }, - findFirst: ({ where }: { where: { userId?: string; role?: string } }) => { - const row = db.memberships.find( - (m) => (!where.userId || m.userId === where.userId) && (!where.role || m.role === where.role), - ); - return Promise.resolve(row ? { ...row, tenant: { ...TENANT } } : null); - }, - upsert: ({ - where, - create, - }: { - where: { tenantId_userId: { tenantId: string; userId: string } }; - create: MembershipRow; - }) => { - const { tenantId, userId } = where.tenantId_userId; - const existing = db.memberships.find((m) => m.tenantId === tenantId && m.userId === userId); - if (existing) return Promise.resolve(existing); - const row = { ...create, createdAt: new Date() }; - db.memberships.push(row); - return Promise.resolve(row); - }, - }, - tenant: { - findUnique: () => Promise.resolve(null), - }, - session: { - create: ({ data }: { data: Omit }) => { - if (db.failSessionCreate) return Promise.reject(new Error('db_down')); - if (db.sessions.some((s) => s.tokenHash === data.tokenHash)) { - return Promise.reject(uniqueViolation('Session.tokenHash')); - } - const row: SessionRow = { id: nextId('sess'), lastActiveAt: new Date(), createdAt: new Date(), ...data }; - db.sessions.push(row); - return Promise.resolve({ ...row }); - }, - findUnique: ({ where }: { where: { tokenHash?: string; id?: string } }) => { - const row = db.sessions.find((s) => (where.tokenHash ? s.tokenHash === where.tokenHash : s.id === where.id)); - return Promise.resolve(row ? { ...row } : null); - }, - findMany: ({ where }: { where: { userId: string } }) => - Promise.resolve(db.sessions.filter((s) => s.userId === where.userId).map((s) => ({ ...s }))), - delete: ({ where }: { where: { id: string } }) => { - const idx = db.sessions.findIndex((s) => s.id === where.id); - if (idx < 0) return Promise.reject(new Error('not found')); - return Promise.resolve(db.sessions.splice(idx, 1)[0]); - }, - deleteMany: ({ where }: { where: { userId?: string; tokenHash?: unknown; expiresAt?: { lt: Date } } }) => { - const notHash = (where.tokenHash as { not?: string } | undefined)?.not; - const eqHash = typeof where.tokenHash === 'string' ? where.tokenHash : undefined; - const before = db.sessions.length; - db.sessions = db.sessions.filter((s) => { - if (where.userId && s.userId !== where.userId) return true; - if (eqHash && s.tokenHash !== eqHash) return true; - if (notHash && s.tokenHash === notHash) return true; - if (where.expiresAt?.lt && s.expiresAt >= where.expiresAt.lt) return true; - return false; - }); - return Promise.resolve({ count: before - db.sessions.length }); - }, - update: ({ where, data }: { where: { id: string }; data: Partial }) => { - const row = db.sessions.find((s) => s.id === where.id); - if (!row) return Promise.reject(Object.assign(new Error('not found'), { code: 'P2025' })); - Object.assign(row, data); - return Promise.resolve({ ...row }); - }, - }, - passwordReset: { - create: ({ data }: { data: Omit }) => { - const row: ResetRow = { usedAt: null, createdAt: new Date(), ...data }; - db.resets.push(row); - return Promise.resolve({ ...row }); - }, - findUnique: ({ where }: { where: { token: string } }) => { - const row = db.resets.find((r) => r.token === where.token); - return Promise.resolve(row ? { ...row } : null); - }, - deleteMany: ({ where }: { where: { userId: string; usedAt: null } }) => { - const before = db.resets.length; - db.resets = db.resets.filter((r) => !(r.userId === where.userId && r.usedAt === null)); - return Promise.resolve({ count: before - db.resets.length }); - }, - updateMany: ({ - where, - data, - }: { - where: { token: string; usedAt: null; expiresAt: { gt: Date } }; - data: { usedAt: Date }; - }) => { - const rows = db.resets.filter( - (r) => r.token === where.token && r.usedAt === null && r.expiresAt > where.expiresAt.gt, - ); - rows.forEach((r) => (r.usedAt = data.usedAt)); - return Promise.resolve({ count: rows.length }); - }, - }, - emailVerification: { - create: ({ data }: { data: Omit }) => { - const row: VerificationRow = { usedAt: null, createdAt: new Date(), ...data }; - db.verifications.push(row); - return Promise.resolve({ ...row }); - }, - findFirst: ({ where }: { where: { userId: string; createdAt: { gte: Date } } }) => { - const row = db.verifications.find((v) => v.userId === where.userId && v.createdAt >= where.createdAt.gte); - return Promise.resolve(row ? { ...row } : null); - }, - findUnique: ({ where }: { where: { token: string } }) => { - const row = db.verifications.find((v) => v.token === where.token); - return Promise.resolve(row ? { ...row } : null); - }, - update: ({ where, data }: { where: { token: string }; data: Partial }) => { - const row = db.verifications.find((v) => v.token === where.token); - if (row) Object.assign(row, data); - return Promise.resolve(row ?? null); - }, - }, - } as unknown as PrismaClient; -} - -let db: TestDb; - -function makeApp(): express.Application { - const app = express(); - app.use(cookieParser()); - app.use(express.json()); - const prisma = makeTestPrisma(db); - app.use(createSessionAuthMiddleware(prisma)); - // Stands in for tenantMiddleware, which resolves the tenant in production. - app.use((req, _res, next) => { - (req as express.Request & { tenant?: unknown }).tenant = { ...TENANT, bypassLimits: false, isInternal: false }; - next(); - }); - registerAuthRoutes(app, prisma); - return app; -} - -/** The auth_token value out of a Set-Cookie header, or null. */ -function cookieFrom(res: request.Response): string | null { - const raw = res.headers['set-cookie']; - const list = Array.isArray(raw) ? raw : raw ? [raw] : []; - const cookie = list.find((c) => c.startsWith('auth_token=')); - if (!cookie) return null; - const value = cookie.split(';')[0].slice('auth_token='.length); - return value.length > 0 ? value : null; -} - -/** - * Let detached work settle — registration kicks off the verification mail in a - * floating promise so a slow provider cannot fail the request. - */ -const flush = () => new Promise((resolve) => setImmediate(resolve)); - -async function registerUser(app: express.Application, email = 'new@example.test') { - db.invites.set('invite-code', { code: 'invite-code', email, tenantId: TENANT.id, role: 'member', usedAt: null }); - const res = await request(app) - .post('/auth/register') - .send({ code: 'invite-code', email, password: 'hunter2hunter2' }); - await flush(); - return res; -} - -beforeEach(() => { - db = { users: new Map(), invites: new Map(), memberships: [], sessions: [], resets: [], verifications: [] }; - sentMail.length = 0; - mailerAvailable = true; - mailerHangs = false; - clearSessionCache(); +it('revokes the cookie through its real session row', async () => { + const { tenant, caller } = await account(); + expect( + (await request(app).get('/auth/me').set('X-Tenant', tenant.slug).set('Cookie', cookieHeader(caller.session))) + .status, + ).toBe(200); + expect( + (await request(app).delete(`/auth/sessions/${caller.sessionId}`).set('Cookie', cookieHeader(caller.session))) + .status, + ).toBe(200); + expect( + (await request(app).get('/auth/me').set('X-Tenant', tenant.slug).set('Cookie', cookieHeader(caller.session))) + .status, + ).toBe(401); + expect(await fixture.prisma.session.count({ where: { id: caller.sessionId } })).toBe(0); }); -describe('session revocation (finding 1)', () => { - it('makes the revoked cookie stop authenticating immediately', async () => { - const app = makeApp(); - const registration = await registerUser(app); - const cookie = cookieFrom(registration); - expect(cookie).toBeTruthy(); - - // Logged in. - const before = await request(app).get('/auth/me').set('Cookie', `auth_token=${cookie}`); - expect(before.status).toBe(200); - - const list = await request(app).get('/auth/sessions').set('Cookie', `auth_token=${cookie}`); - expect(list.status).toBe(200); - expect(list.body.sessions).toHaveLength(1); - const sessionId = list.body.sessions[0].id; - expect(list.body.sessions[0].isCurrent).toBe(true); - - const revoke = await request(app).delete(`/auth/sessions/${sessionId}`).set('Cookie', `auth_token=${cookie}`); - expect(revoke.status).toBe(200); - - // The regression: this used to stay 200 — the success tick was a lie. - const after = await request(app).get('/auth/me').set('Cookie', `auth_token=${cookie}`); - expect(after.status).toBe(401); - expect(db.sessions).toHaveLength(0); - }); - - it('kills the cookie on logout', async () => { - const app = makeApp(); - const cookie = cookieFrom(await registerUser(app)); - - await request(app).post('/auth/logout').set('Cookie', `auth_token=${cookie}`).expect(200); - - const after = await request(app).get('/auth/me').set('Cookie', `auth_token=${cookie}`); - expect(after.status).toBe(401); - }); - - it('revokes every other session but keeps the caller signed in', async () => { - const app = makeApp(); - const first = cookieFrom(await registerUser(app)); - const second = cookieFrom( - await request(app).post('/auth/login').send({ email: 'new@example.test', password: 'hunter2hunter2' }), - ); - expect(db.sessions).toHaveLength(2); - - const res = await request(app).delete('/auth/sessions').set('Cookie', `auth_token=${second}`); - expect(res.body.revokedCount).toBe(1); - - await request(app).get('/auth/me').set('Cookie', `auth_token=${second}`).expect(200); - await request(app).get('/auth/me').set('Cookie', `auth_token=${first}`).expect(401); - }); - - it('refuses a foreign session id with 404 rather than revoking it', async () => { - const app = makeApp(); - const victimCookie = cookieFrom(await registerUser(app, 'victim@example.test')); - const victimSessionId = db.sessions[0].id; - - db.invites.set('invite-code-2', { - code: 'invite-code-2', - email: 'mallory@example.test', - tenantId: TENANT.id, - role: 'member', - usedAt: null, - }); - const attacker = await request(app) - .post('/auth/register') - .send({ code: 'invite-code-2', email: 'mallory@example.test', password: 'hunter2hunter2' }); - expect(attacker.status, JSON.stringify(attacker.body)).toBe(200); - - const res = await request(app) - .delete(`/auth/sessions/${victimSessionId}`) - .set('Cookie', `auth_token=${cookieFrom(attacker)}`); - - expect(res.status).toBe(404); - await request(app).get('/auth/me').set('Cookie', `auth_token=${victimCookie}`).expect(200); - }); +it('removes the stored session on logout', async () => { + const { tenant, caller } = await account(); + expect((await request(app).post('/auth/logout').set('Cookie', cookieHeader(caller.session))).status).toBe(200); + expect( + (await request(app).get('/auth/me').set('X-Tenant', tenant.slug).set('Cookie', cookieHeader(caller.session))) + .status, + ).toBe(401); }); -describe('registration establishes a session (finding 2)', () => { - it('creates exactly one session row and lists it as active', async () => { - const app = makeApp(); - const res = await registerUser(app); - - expect(res.status).toBe(200); - expect(db.sessions).toHaveLength(1); - expect(db.sessions[0].userId).toBe(res.body.id); - - const list = await request(app) - .get('/auth/sessions') - .set('Cookie', `auth_token=${cookieFrom(res)}`); - expect(list.body.sessions).toHaveLength(1); - }); - - it('hands out no cookie when the session row cannot be written', async () => { - db.failSessionCreate = true; - const app = makeApp(); - - const res = await registerUser(app); - - expect(res.status).toBe(500); - expect(cookieFrom(res)).toBeNull(); - expect(db.sessions).toHaveLength(0); - }); - - it('gives two logins in the same second distinct sessions', async () => { - const app = makeApp(); - await registerUser(app); - const login = () => - request(app).post('/auth/login').send({ email: 'new@example.test', password: 'hunter2hunter2' }); - - const [a, b] = await Promise.all([login(), login()]); - - expect(a.status).toBe(200); - expect(b.status).toBe(200); - // 1 from registration + 2 logins. Identical JWTs would have collided on - // the unique tokenHash and silently lost a session row. - expect(db.sessions).toHaveLength(3); - expect(new Set(db.sessions.map((s) => s.tokenHash)).size).toBe(3); - }); +it('revokes other sessions and retains the caller session', async () => { + const { tenant, caller } = await account(); + const other = await fixture.session(caller.id, tenant.id); + const result = await request(app).delete('/auth/sessions').set('Cookie', cookieHeader(caller.session)); + expect(result.status).toBe(200); + expect(result.body.revokedCount).toBe(1); + expect( + (await request(app).get('/auth/me').set('X-Tenant', tenant.slug).set('Cookie', cookieHeader(caller.session))) + .status, + ).toBe(200); + expect( + (await request(app).get('/auth/me').set('X-Tenant', tenant.slug).set('Cookie', cookieHeader(other.token))).status, + ).toBe(401); }); -describe('e-mail verification (finding 4)', () => { - it('does not stamp the address as verified and mails a token instead', async () => { - const app = makeApp(); - const res = await registerUser(app); - - const user = db.users.get(res.body.id); - expect(user?.emailVerifiedAt).toBeNull(); - expect(db.verifications).toHaveLength(1); - expect(sentMail.filter((m) => m.kind === 'verify')).toHaveLength(1); - expect(sentMail[0].to).toBe('new@example.test'); - expect(sentMail[0].body).toContain(db.verifications[0].token); - }); - - it('lets an unverified user in and reports the status to the client', async () => { - const app = makeApp(); - const cookie = cookieFrom(await registerUser(app)); - - const me = await request(app).get('/auth/me').set('Cookie', `auth_token=${cookie}`); - - expect(me.status).toBe(200); - expect(me.body.emailVerified).toBe(false); - expect(me.body.emailVerifiedAt).toBeNull(); - }); - - it('flips the status once the token is redeemed', async () => { - const app = makeApp(); - const cookie = cookieFrom(await registerUser(app)); - - await request(app).post('/auth/verify').send({ token: db.verifications[0].token }).expect(200); - - const me = await request(app).get('/auth/me').set('Cookie', `auth_token=${cookie}`); - expect(me.body.emailVerified).toBe(true); - expect(me.body.emailVerifiedAt).toBeTruthy(); - }); +it('returns 404 for another user session without changing the database', async () => { + const own = await account(); + const foreign = await account(); + const result = await request(app) + .delete(`/auth/sessions/${foreign.caller.sessionId}`) + .set('Cookie', cookieHeader(own.caller.session)); + expect(result.status).toBe(404); + expect(await fixture.prisma.session.count({ where: { id: foreign.caller.sessionId } })).toBe(1); }); -describe('password reset (finding 3)', () => { - /** - * /auth/forgot answers before the mail work finishes (deliberately — an - * awaited send would leak by timing whether the address exists), so let the - * detached task settle before inspecting what it did. - */ - async function forgot(app: express.Application, email: string) { - const res = await request(app).post('/auth/forgot').send({ email }); - await flush(); - return res; - } +it('creates one revocable verification session and no membership before email proof', async () => { + const value = await setup.registration(); + expect(await fixture.prisma.session.count({ where: { userId: value.user.id } })).toBe(1); + expect(await fixture.prisma.membership.count({ where: { userId: value.user.id } })).toBe(0); + expect(value.user.emailVerifiedAt).toBeNull(); + expect((await request(app).post('/auth/verify').send({ token: value.token })).status).toBe(200); + expect(await fixture.prisma.membership.count({ where: { userId: value.user.id } })).toBe(1); +}); - /** The reset token out of the mail the flow sent. */ - function tokenFromResetMail(): string { - const mail = sentMail.find((m) => m.kind === 'raw'); - const match = mail?.body.match(/token=([a-f0-9]+)/); - if (!match) throw new Error('no reset token in mail'); - return match[1]; +it('issues no cookie after a real session-insert failure and removes the failure fixture', async () => { + const value = await account(); + const name = `session_insert_fixture_${crypto.randomBytes(8).toString('hex')}`; + const literal = value.caller.id.replace(/'/g, "''"); + let functionCreated = false; + let triggerCreated = false; + try { + // Trigger a real insert failure only for this fixture account. + await fixture.prisma.$executeRawUnsafe( + `CREATE FUNCTION "${name}"() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW."userId" = TG_ARGV[0] THEN RAISE EXCEPTION 'Expected fixture session insert failure'; END IF; RETURN NEW; END; $$`, + ); + functionCreated = true; + await fixture.prisma.$executeRawUnsafe( + `CREATE TRIGGER "${name}" BEFORE INSERT ON "Session" FOR EACH ROW EXECUTE FUNCTION "${name}"('${literal}')`, + ); + triggerCreated = true; + const before = await fixture.prisma.session.count({ where: { userId: value.caller.id } }); + const result = await request(app) + .post('/auth/login') + .set('X-Tenant', value.tenant.slug) + .send({ email: value.user.email, password: value.password }); + expect(result.status).toBe(500); + expect(cookieFrom(result.headers)).toBeNull(); + expect(await fixture.prisma.session.count({ where: { userId: value.caller.id } })).toBe(before); + } finally { + if (triggerCreated) await fixture.prisma.$executeRawUnsafe(`DROP TRIGGER "${name}" ON "Session"`); + if (functionCreated) await fixture.prisma.$executeRawUnsafe(`DROP FUNCTION "${name}"()`); } + const remaining = await fixture.prisma.$queryRaw< + Array<{ count: bigint }> + >`SELECT count(*) FROM pg_trigger WHERE tgname=${name}`; + expect(Number(remaining[0]?.count)).toBe(0); +}); - it('mails a reset link and stores the token hashed, never in the clear', async () => { - const app = makeApp(); - await registerUser(app, 'user@example.test'); - sentMail.length = 0; - - const res = await forgot(app, 'user@example.test'); - - expect(res.status).toBe(200); - expect(res.body).toEqual({ ok: true }); - // The raw token is not in the response either — only in the mail. - expect(JSON.stringify(res.body)).not.toContain(tokenFromResetMail()); - expect(db.resets).toHaveLength(1); - expect(db.resets[0].token).not.toBe(tokenFromResetMail()); - expect(db.resets[0].token).toMatch(/^[a-f0-9]{64}$/); - }); - - it('answers 200 for an unknown address and sends nothing', async () => { - const app = makeApp(); - - const res = await forgot(app, 'nobody@example.test'); - - expect(res.status).toBe(200); - expect(res.body).toEqual({ ok: true }); - expect(sentMail).toHaveLength(0); - expect(db.resets).toHaveLength(0); - }); - - it('answers without waiting for the mail, so timing tells nothing apart', async () => { - const app = makeApp(); - await registerUser(app, 'user@example.test'); - sentMail.length = 0; - // A provider that never resolves: the response must not depend on it. - mailerHangs = true; - - const res = await request(app).post('/auth/forgot').send({ email: 'user@example.test' }); - - expect(res.status).toBe(200); - expect(res.body).toEqual({ ok: true }); - }); - - it('resets the password, burns the token and kills every session', async () => { - const app = makeApp(); - const cookie = cookieFrom(await registerUser(app, 'user@example.test')); - sentMail.length = 0; - await forgot(app, 'user@example.test'); - const token = tokenFromResetMail(); - - const reset = await request(app).post('/auth/reset').send({ token, password: 'newpassword123' }); - expect(reset.status).toBe(200); - - // Every session is gone — including the one the attacker might hold. - expect(db.sessions).toHaveLength(0); - await request(app).get('/auth/me').set('Cookie', `auth_token=${cookie}`).expect(401); +it('creates distinct sessions for two rapid logins', async () => { + const value = await account(); + const login = () => + request(app) + .post('/auth/login') + .set('X-Tenant', value.tenant.slug) + .send({ email: value.user.email, password: value.password }); + const [first, second] = await Promise.all([login(), login()]); + expect(first.status).toBe(200); + expect(second.status).toBe(200); + const a = cookieFrom(first.headers), + b = cookieFrom(second.headers); + expect(!!a && !!b && a !== b).toBe(true); + expect(await fixture.prisma.session.count({ where: { userId: value.caller.id } })).toBe(3); +}); - // The new password works, the old one does not. - await request(app).post('/auth/login').send({ email: 'user@example.test', password: 'newpassword123' }).expect(200); - await request(app).post('/auth/login').send({ email: 'user@example.test', password: 'hunter2hunter2' }).expect(401); +it('preserves unmarked unverified legacy memberships and reports their actual status', async () => { + const value = await account(); + await fixture.prisma.user.update({ where: { id: value.caller.id }, data: { emailVerifiedAt: null } }); + const result = await request(app) + .get('/auth/me') + .set('X-Tenant', value.tenant.slug) + .set('Cookie', cookieHeader(value.caller.session)); + expect(result.status).toBe(200); + expect(result.body.emailVerified).toBe(false); +}); - // Single use. - const replay = await request(app).post('/auth/reset').send({ token, password: 'thirdpassword123' }); - expect(replay.status).toBe(400); - }); +it('confirms an unmarked legacy address only through its actual mailbox link', async () => { + const value = await account(); + await fixture.prisma.user.update({ where: { id: value.caller.id }, data: { emailVerifiedAt: null } }); + const result = await request(app).post('/auth/verify/request').set('Cookie', cookieHeader(value.caller.session)); + expect(result.status).toBe(200); + expect('token' in result.body || 'verifyUrl' in result.body).toBe(false); + const token = await setup.mail.token(value.user.email); + expect((await request(app).post('/auth/verify').send({ token })).status).toBe(200); + expect(!!(await fixture.prisma.user.findUniqueOrThrow({ where: { id: value.caller.id } })).emailVerifiedAt).toBe( + true, + ); +}); - it('rejects an expired token', async () => { - const app = makeApp(); - await registerUser(app, 'user@example.test'); - sentMail.length = 0; - await forgot(app, 'user@example.test'); - const token = tokenFromResetMail(); +it('delivers the reset link and stores only its digest', async () => { + const value = await account(); + const result = await request(app).post('/auth/forgot').send({ email: value.user.email }); + expect(result.status).toBe(200); + expect('token' in result.body || 'resetUrl' in result.body).toBe(false); + const token = await setup.mail.token(value.user.email, 'reset'); + const stored = await fixture.prisma.passwordReset.findFirstOrThrow({ where: { userId: value.user.id } }); + expect(stored.token === token).toBe(false); +}); - db.resets[0].expiresAt = new Date(Date.now() - 1000); +it('responds neutrally for an unknown address without creating an account or token', async () => { + const email = setup.email(); + expect((await request(app).post('/auth/forgot').send({ email })).status).toBe(200); + expect(await fixture.prisma.user.count({ where: { email } })).toBe(0); +}); - const res = await request(app).post('/auth/reset').send({ token, password: 'newpassword123' }); - expect(res.status).toBe(400); - expect(db.users.get(db.resets[0].userId)?.passwordHash).toBeTruthy(); - await request(app).post('/auth/login').send({ email: 'user@example.test', password: 'newpassword123' }).expect(401); - }); +it('creates no reset for an account without a password', async () => { + const value = await account(); + await fixture.prisma.user.update({ where: { id: value.caller.id }, data: { passwordHash: null } }); + expect((await request(app).post('/auth/forgot').send({ email: value.user.email })).status).toBe(200); + expect(await fixture.prisma.passwordReset.count({ where: { userId: value.user.id } })).toBe(0); +}); - it('rejects a token whose email does not match', async () => { - const app = makeApp(); - await registerUser(app, 'user@example.test'); - sentMail.length = 0; - await forgot(app, 'user@example.test'); - const token = tokenFromResetMail(); +it('resets the password once and revokes all stored sessions', async () => { + const value = await account(); + const { token } = await issuePasswordResetToken(fixture.prisma, value.user.id); + const next = password(); + expect((await request(app).post('/auth/reset').send({ email: value.user.email, token, password: next })).status).toBe( + 200, + ); + expect(await fixture.prisma.session.count({ where: { userId: value.user.id } })).toBe(0); + expect( + (await request(app).post('/auth/reset').send({ email: value.user.email, token, password: password() })).status, + ).toBe(400); + expect( + ( + await request(app) + .post('/auth/login') + .set('X-Tenant', value.tenant.slug) + .send({ email: value.user.email, password: next }) + ).status, + ).toBe(200); +}); - const res = await request(app) +it('rejects expired reset links and mismatched addresses without changing the password', async () => { + for (const mode of ['expired', 'email']) { + const value = await account(); + const { token } = await issuePasswordResetToken( + fixture.prisma, + value.user.id, + mode === 'expired' ? -1000 : undefined, + ); + const result = await request(app) .post('/auth/reset') - .send({ token, email: 'someone@example.test', password: 'newpassword123' }); - - expect(res.status).toBe(400); - // The mismatch must not burn the link the real user is about to click. - expect(db.resets[0].usedAt).toBeNull(); - }); - - it('invalidates the previous link when a new one is requested', async () => { - const app = makeApp(); - await registerUser(app, 'user@example.test'); - sentMail.length = 0; - await forgot(app, 'user@example.test'); - const first = tokenFromResetMail(); - sentMail.length = 0; - await forgot(app, 'user@example.test'); - const second = tokenFromResetMail(); - - expect(first).not.toBe(second); - await request(app).post('/auth/reset').send({ token: first, password: 'newpassword123' }).expect(400); - await request(app).post('/auth/reset').send({ token: second, password: 'newpassword123' }).expect(200); - }); - - it('sends nothing for a guest account, which has no password', async () => { - const app = makeApp(); - db.users.set('guest-1', { - id: 'guest-1', - email: 'guest@example.test', - name: null, - passwordHash: null, - emailVerifiedAt: null, - locale: 'de', - avatarId: null, - onboardingCompleted: false, - }); - - await forgot(app, 'guest@example.test'); - - expect(sentMail).toHaveLength(0); - expect(db.resets).toHaveLength(0); - }); - - it('still answers 200 when no mail provider is configured', async () => { - const app = makeApp(); - await registerUser(app, 'user@example.test'); - mailerAvailable = false; + .send({ email: mode === 'email' ? setup.email() : value.user.email, token, password: password() }); + expect(result.status).toBe(400); + expect( + (await fixture.prisma.user.findUniqueOrThrow({ where: { id: value.user.id } })).passwordHash === + value.user.passwordHash, + ).toBe(true); + } +}); - const res = await forgot(app, 'user@example.test'); +it('invalidates the previous reset link when issuing another one', async () => { + const value = await account(); + const first = await issuePasswordResetToken(fixture.prisma, value.user.id); + await issuePasswordResetToken(fixture.prisma, value.user.id); + expect((await request(app).post('/auth/reset').send({ token: first.token, password: password() })).status).toBe(400); +}); - // Token exists but nothing leaks to the caller; the admin path is the - // fallback in this configuration. - expect(res.status).toBe(200); - expect(res.body).toEqual({ ok: true }); - }); +it('retains only the current session and invalidates pending reset links on password change', async () => { + const value = await account(); + const other = await fixture.session(value.user.id, value.tenant.id); + const reset = await issuePasswordResetToken(fixture.prisma, value.user.id); + const result = await request(app) + .post('/auth/change') + .set('Cookie', cookieHeader(value.caller.session)) + .send({ currentPassword: value.password, newPassword: password() }); + expect(result.status).toBe(200); + expect(await fixture.prisma.session.count({ where: { userId: value.user.id } })).toBe(1); + expect(await fixture.prisma.session.count({ where: { id: value.caller.sessionId } })).toBe(1); + expect(await fixture.prisma.session.count({ where: { id: other.id } })).toBe(0); + expect((await request(app).post('/auth/reset').send({ token: reset.token, password: password() })).status).toBe(400); }); -describe('password change', () => { - it('revokes the other sessions and keeps the caller signed in', async () => { - const app = makeApp(); - const first = cookieFrom(await registerUser(app, 'user@example.test')); - const second = cookieFrom( - await request(app).post('/auth/login').send({ email: 'user@example.test', password: 'hunter2hunter2' }), +for (const mode of ['no_provider', 'closed_smtp']) { + it(`responds neutrally in ${mode} regardless of reset delivery failure`, async () => { + const result = await promisify(execFile)( + process.execPath, + ['--import', 'tsx', 'test/fixtures/forgotDeliveryProbe.ts', mode], + { cwd: process.cwd(), env: { ...process.env, NODE_ENV: 'test' }, timeout: 45_000, maxBuffer: 256_000 }, ); - - const res = await request(app) - .post('/auth/change') - .set('Cookie', `auth_token=${second}`) - .send({ currentPassword: 'hunter2hunter2', newPassword: 'newpassword123' }); - - expect(res.status).toBe(200); - expect(res.body.revokedSessions).toBe(1); - await request(app).get('/auth/me').set('Cookie', `auth_token=${second}`).expect(200); - await request(app).get('/auth/me').set('Cookie', `auth_token=${first}`).expect(401); - }); - - it('invalidates a pending reset link', async () => { - const app = makeApp(); - const cookie = cookieFrom(await registerUser(app, 'user@example.test')); - sentMail.length = 0; - await request(app).post('/auth/forgot').send({ email: 'user@example.test' }); - await flush(); - const token = sentMail.find((m) => m.kind === 'raw')?.body.match(/token=([a-f0-9]+)/)?.[1]; - expect(token).toBeTruthy(); - - await request(app) - .post('/auth/change') - .set('Cookie', `auth_token=${cookie}`) - .send({ currentPassword: 'hunter2hunter2', newPassword: 'newpassword123' }) - .expect(200); - - await request(app).post('/auth/reset').send({ token, password: 'attacker12345' }).expect(400); - }); -}); + const line = result.stdout.split('\n').find((line) => line.startsWith('PASSWORD_RESET_DELIVERY_RESULT:')); + if (!line) throw new Error('The reset delivery probe returned no result evidence.'); + const body: unknown = JSON.parse(line.slice('PASSWORD_RESET_DELIVERY_RESULT:'.length)); + expect( + !!body && + typeof body === 'object' && + 'status' in body && + body.status === 200 && + 'secret' in body && + body.secret === false, + ).toBe(true); + if (mode === 'closed_smtp') { + const received = result.stdout.indexOf('PASSWORD_RESET_DELIVERY_RESULT:'); + const failed = result.stdout.indexOf('email.smtp.send_failed'); + expect(received >= 0 && failed > received).toBe(true); + } + }, 50_000); +} diff --git a/apps/server/src/api/routes/auth.helpers.test.ts b/apps/server/src/api/routes/auth.helpers.test.ts index d942986b..f7702093 100644 --- a/apps/server/src/api/routes/auth.helpers.test.ts +++ b/apps/server/src/api/routes/auth.helpers.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import type express from 'express'; -import { isNativeClientRequest, resolvePublicBaseUrl, buildSigninResponseBody } from './auth.helpers.js'; +import { isNativeClientRequest, buildSigninResponseBody } from './auth.helpers.js'; function reqWithOrigin(origin?: string): express.Request { return { headers: origin === undefined ? {} : { origin } } as express.Request; @@ -69,39 +69,3 @@ describe('buildSigninResponseBody', () => { expect(body.token).toBe('jwt-token'); }); }); - -describe('resolvePublicBaseUrl', () => { - it('prefers PUBLIC_BASE_URL over everything else', () => { - expect( - resolvePublicBaseUrl({ - publicBaseUrl: 'https://public.example', - billingPublicUrl: 'https://billing.example', - origin: 'https://origin.example', - host: 'host.example', - }), - ).toBe('https://public.example'); - }); - - it('falls back to BILLING_PUBLIC_URL when PUBLIC_BASE_URL is absent', () => { - expect( - resolvePublicBaseUrl({ billingPublicUrl: 'https://billing.example', origin: 'https://origin.example' }), - ).toBe('https://billing.example'); - }); - - it('uses a real http(s) Origin when no explicit base URL is configured', () => { - expect(resolvePublicBaseUrl({ origin: 'https://origin.example', host: 'host.example' })).toBe( - 'https://origin.example', - ); - }); - - it('ignores a native-client Origin and falls through to the Host header', () => { - expect(resolvePublicBaseUrl({ origin: 'tauri://localhost', host: 'meetropolis.me' })).toBe( - 'https://meetropolis.me', - ); - }); - - it('returns an empty string when nothing usable is available', () => { - expect(resolvePublicBaseUrl({})).toBe(''); - expect(resolvePublicBaseUrl({ origin: 'tauri://localhost' })).toBe(''); - }); -}); diff --git a/apps/server/src/api/routes/auth.helpers.ts b/apps/server/src/api/routes/auth.helpers.ts index a72b0107..fb61b43d 100644 --- a/apps/server/src/api/routes/auth.helpers.ts +++ b/apps/server/src/api/routes/auth.helpers.ts @@ -18,29 +18,6 @@ export function isNativeClientRequest(req: express.Request): boolean { } } -/** - * Resolve the public base URL used to build user-facing links in emails - * (e.g. the email-verification link). Precedence: - * 1. PUBLIC_BASE_URL / BILLING_PUBLIC_URL — explicit self-host config. - * 2. Request Origin header, but only when it is a real http(s) web origin. - * Native clients (Tauri desktop) send a custom-scheme origin such as - * `tauri://localhost`; that must never leak into an emailed link, so - * those requests fall through to the Host header instead. - * 3. Host header as `https://`. - */ -export function resolvePublicBaseUrl(params: { - publicBaseUrl?: string | undefined; - billingPublicUrl?: string | undefined; - origin?: string | undefined; - host?: string | undefined; -}): string { - const { publicBaseUrl, billingPublicUrl, origin, host } = params; - if (publicBaseUrl) return publicBaseUrl; - if (billingPublicUrl) return billingPublicUrl; - if (origin && /^https?:\/\//i.test(origin)) return origin; - return host ? `https://${host}` : ''; -} - export function getRequestToken(req: express.Request): string | null { return (req.cookies?.auth_token as string | undefined) || req.headers.authorization?.replace('Bearer ', '') || null; } diff --git a/apps/server/src/api/routes/auth.password.ts b/apps/server/src/api/routes/auth.password.ts index ef5455ff..b4f7582e 100644 --- a/apps/server/src/api/routes/auth.password.ts +++ b/apps/server/src/api/routes/auth.password.ts @@ -12,8 +12,9 @@ import { PASSWORD_RESET_TTL_MINUTES, } from '../utils/passwordResetTokens.js'; import { renderPasswordResetMail } from '../utils/passwordResetMail.js'; -import { resolvePublicBaseUrl, getRequestToken } from './auth.helpers.js'; -import { sendIfAvailable } from '../../emailLoader.js'; +import { getRequestToken } from './auth.helpers.js'; +import { buildPublicWebLink, publicWebBase } from '../utils/publicLinks.js'; +import { deliveringEmailModule } from '../utils/emailProof.js'; import { resolveLocale, readEnvDefaultLocale } from '../../email/localeResolver.js'; const forgotSchema = z.object({ email: z.string().email() }); @@ -49,10 +50,10 @@ export function handleAuthForgot(prisma: PrismaClient, req: express.Request, res return; } - void sendResetMailIfEligible(prisma, req, parse.data.email).catch((e: unknown) => + void sendResetMailIfEligible(prisma, parse.data.email).catch((e: unknown) => // Never leaks to the client: a failure here must look exactly like the // unknown-address case. - logger.error({ event: 'auth.forgot.failed', error: e instanceof Error ? e.message : String(e) }), + logger.error({ event: 'auth.forgot.failed', errorName: e instanceof Error ? e.name : typeof e }), ); res.json({ ok: true }); @@ -63,7 +64,7 @@ export function handleAuthForgot(prisma: PrismaClient, req: express.Request, res * Silent no-op for unknown addresses and for guest accounts (they have no * password to reset and authenticate via their magic link instead). */ -async function sendResetMailIfEligible(prisma: PrismaClient, req: express.Request, email: string): Promise { +async function sendResetMailIfEligible(prisma: PrismaClient, email: string): Promise { const user = await prisma.user.findFirst({ where: { email: { equals: normalizeEmailForStorage(email), mode: 'insensitive' } }, select: { id: true, email: true, name: true, locale: true, passwordHash: true }, @@ -80,19 +81,16 @@ async function sendResetMailIfEligible(prisma: PrismaClient, req: express.Reques // Resolve the link target BEFORE issuing: a mail with a relative link is // useless, and issuing anyway would pointlessly invalidate a link the user // may already hold. - const baseUrl = resolvePublicBaseUrl({ - publicBaseUrl: process.env.PUBLIC_BASE_URL, - billingPublicUrl: process.env.BILLING_PUBLIC_URL, - origin: req.headers.origin, - host: req.headers.host, - }); + const baseUrl = publicWebBase(); if (!baseUrl) { - logger.error({ event: 'auth.forgot.no_base_url', userId: user.id }); + logger.error({ event: 'links.public_base_url_missing', route: 'auth.forgot', userId: user.id }); return; } + const mail = await deliveringEmailModule(); + if (!mail) return; const { token } = await issuePasswordResetToken(prisma, user.id); - const resetUrl = `${baseUrl.replace(/\/$/, '')}/#/reset?token=${token}&email=${encodeURIComponent(user.email)}`; + const resetUrl = buildPublicWebLink(baseUrl, `reset?token=${token}&email=${encodeURIComponent(user.email)}`); // Locale chain (Block C): user.locale (DB) → MAIL_DEFAULT_LOCALE → 'de'. // Resolved here rather than by the mail module because `sendRaw` is a @@ -100,20 +98,13 @@ async function sendResetMailIfEligible(prisma: PrismaClient, req: express.Reques // owns the choice. Same resolver the templated mails use. const locale = resolveLocale({ userLocale: user.locale }, readEnvDefaultLocale()); - const sent = await sendIfAvailable( - (mod) => - mod.sendRaw( - renderPasswordResetMail({ - to: user.email, - name: user.name || '', - resetUrl, - expiresInMinutes: PASSWORD_RESET_TTL_MINUTES, - locale, - }), - ), - 'auth.forgot.email_failed', - { userId: user.id }, - ); + let sent = false; + try { + sent = await mail.sendRaw(renderPasswordResetMail({ to: user.email, name: user.name || '', + resetUrl, expiresInMinutes: PASSWORD_RESET_TTL_MINUTES, locale })); + } catch { + logger.warn({ event: 'auth.forgot.email_failed', userId: user.id }); + } // `sent: false` means no mail provider is configured. The token is NOT // surfaced in the response (unlike e-mail verification, an unauthenticated diff --git a/apps/server/src/api/routes/auth.signin.ts b/apps/server/src/api/routes/auth.signin.ts index 162da891..87d39a5d 100644 --- a/apps/server/src/api/routes/auth.signin.ts +++ b/apps/server/src/api/routes/auth.signin.ts @@ -4,21 +4,19 @@ import bcrypt from 'bcryptjs'; import crypto from 'crypto'; import { z } from 'zod'; import { logger } from '../../logger.js'; -import { - requireAuth, - getTenantFromReq, - requireMembership, - normalizeEmailForStorage, - normalizeEmailForMatching, -} from '../utils/authHelpers.js'; +import { requireAuth, requireVerificationAuth, getTenantFromReq, requireMembership, normalizeEmailForStorage } from '../utils/authHelpers.js'; +import { buildPublicWebLink, requirePublicWebBase } from '../utils/publicLinks.js'; import { establishSession, revokeSessionByToken } from '../utils/sessionAuth.js'; import { displayNameSchema, invalidNameBodyFor } from '../utils/displayName.js'; -import { startEmailVerification } from './auth.verify.js'; +import { deliveringEmailModule } from '../utils/emailProof.js'; +import { beginInviteVerification, pendingInviteForUser, verificationPending, verificationBindingRequired } from '../utils/inviteVerification.js'; +import { isInternalOwner as checkInternalOwner } from '../utils/tenantMembership.js'; import { hasBillingModule } from '../../billingLoader.js'; import { hasAdminEnterpriseModule } from '../../adminLoader.js'; import { getTenancyModule } from '../../tenancyLoader.js'; -import { sendIfAvailable } from '../../emailLoader.js'; import { isNativeClientRequest, getRequestToken, buildSigninResponseBody } from './auth.helpers.js'; +import { getDeniedTenant, isTenantAccessDenied } from '../utils/tenantAccessState.js'; +import * as inviteLifecycle from '../utils/inviteLifecycle.js'; const inviteSchema = z.object({ email: z.string().email(), @@ -52,46 +50,48 @@ export async function handleAuthInvite( } const requestedRole = parse.data.role; const allowedRole = membership.role === 'owner' ? requestedRole : 'member'; - const code = crypto.randomBytes(12).toString('hex'); + const baseUrl = requirePublicWebBase(res, 'auth.invite'); + if (!baseUrl) return; + const normalizedEmail = normalizeEmailForStorage(parse.data.email); - const inv = await prisma.invite.create({ - data: { code, email: normalizedEmail, createdBy: auth.userId, tenantId: tenant.id, role: allowedRole }, + const existingMember = await prisma.user.findFirst({ + where: { + email: { equals: normalizedEmail, mode: 'insensitive' }, + memberships: { some: { tenantId: tenant.id, inviteVerificationRequired: false } }, + }, + select: { id: true }, }); - - // Best-effort email when a mail module is loaded (EE-tenancy or - // OSS-SMTP). In the OSS-console-fallback case this becomes a logged - // no-op: the code is returned in the JSON response below and shared - // manually by the admin. - // - // Locale chain (Block C): params.locale (not exposed on /auth/invite) → - // inviter.locale (DB) → MAIL_DEFAULT_LOCALE / 'de' (resolver default). - // The invitee is not a known user yet, so we fall back to the - // inviter's UI locale — closer to "what language did the admin see - // when they sent this" than guessing the recipient's. - const inviter = await prisma.user.findUnique({ - where: { id: auth.userId }, - select: { name: true, email: true, locale: true }, + if (existingMember) { + res.status(409).json({ error: 'already_member' }); + return; + } + const openInvite = await prisma.invite.findFirst({ + where: { tenantId: tenant.id, email: normalizedEmail, usedAt: null }, + orderBy: { createdAt: 'desc' }, }); - const inviterName = inviter?.name || inviter?.email || 'Someone'; - const inviterLocale = inviter?.locale === 'en' ? 'en' : inviter?.locale === 'de' ? 'de' : undefined; - const baseUrl = process.env.PUBLIC_BASE_URL || process.env.BILLING_PUBLIC_URL || ''; - const inviteUrl = baseUrl ? `${baseUrl.replace(/\/$/, '')}/#/?invite=${inv.code}` : `/#/?invite=${inv.code}`; - void sendIfAvailable( - (mod) => - mod.sendInvite({ - to: normalizedEmail, - inviterName, - // The company NAME, not the slug: the slug is a routing key ("acme-2") - // and the invite mail's subject line puts this in front of a human. - tenantName: tenant.name, - inviteUrl, - locale: inviterLocale, - }), - 'invite.email_failed', - { tenantId: tenant.id, inviteCode: inv.code }, - ); - - res.json({ code: inv.code, role: allowedRole, inviteUrl }); + const invite = openInvite + ? await prisma.invite.update({ + where: { id: openInvite.id }, + data: { expiresAt: inviteLifecycle.inviteExpiry(), role: allowedRole }, + }) + : await prisma.invite.create({ + data: { + code: crypto.randomBytes(12).toString('hex'), + email: normalizedEmail, + createdBy: auth.userId, + tenantId: tenant.id, + role: allowedRole, + expiresAt: inviteLifecycle.inviteExpiry(), + }, + }); + const inviteUrl = buildPublicWebLink(baseUrl, `?invite=${invite.code}`); + const emailSent = await inviteLifecycle.deliverInvite(prisma, { + invite: { id: invite.id, email: invite.email, tenantId: invite.tenantId }, + inviterUserId: auth.userId, + tenantName: tenant.name, + inviteUrl, + }); + res.json(inviteLifecycle.inviteResponse(invite, inviteUrl, emailSent)); } const registerSchema = z.object({ @@ -114,48 +114,52 @@ export async function handleAuthRegister( const { code, name, email, password } = parse.data; const invite = await prisma.invite.findUnique({ where: { code } }); if (!invite || invite.usedAt) { - res.status(400).json({ error: 'invalid or used invite' }); + res.status(400).json({ error: 'invite_unavailable' }); + return; + } + if (inviteLifecycle.deriveInviteStatus(invite) === 'expired') { + res.status(400).json({ error: 'invite_expired' }); return; } - if (invite.email && normalizeEmailForMatching(invite.email) !== normalizeEmailForMatching(email)) { - res.status(400).json({ error: 'invite does not match email' }); + if (!inviteLifecycle.inviteEmailMatches(invite.email, email)) { + res.status(403).json({ error: 'invite_email_mismatch' }); return; } - const hash = await bcrypt.hash(password, BCRYPT_COST); + if (!(await deliveringEmailModule())) { + res.status(503).json({ code: 'EMAIL_DELIVERY_UNAVAILABLE', error: 'This invitation requires email confirmation. Configure a delivery provider or contact an administrator.' }); + return; + } + if (!requirePublicWebBase(res, 'auth.register')) return; + const now = new Date(); let user; try { - const emailForStorage = normalizeEmailForStorage(email); - // No `emailVerifiedAt` here: the address is unverified until the user - // proves it via the mail sent below. Stamping it at creation time is what - // made the entire verification flow (model, endpoints, badge) dead code — - // and password-reset links are mailed to this address, so the proof has to - // be real. An unverified user is not locked out; the client shows a banner - // (GET /auth/me -> emailVerified). - user = await prisma.user.create({ - data: { email: emailForStorage, name, passwordHash: hash }, + const passwordHash = await bcrypt.hash(password, BCRYPT_COST); + // Grant no membership or invitation role until mailbox ownership is proven. + user = await inviteLifecycle.registerInvitedUser(prisma, { + code, + email, + name, + passwordHash, + role: invite.role, + tenantId: invite.tenantId, + now, }); } catch (e: unknown) { if (e && typeof e === 'object' && 'code' in e && e.code === 'P2002') { - res.status(400).json({ error: 'email already in use' }); + res.status(409).json({ code: 'ACCOUNT_LOGIN_REQUIRED', error: 'An account already exists for this email address. Sign in to accept the invitation.' }); + return; + } + if (e instanceof inviteLifecycle.InviteUnavailableError) { + res.status(400).json({ error: 'invite_unavailable' }); return; } - res.status(400).json({ error: 'registration failed' }); + logger.error({ event: 'auth.register.failed', errorName: e instanceof Error ? e.name : typeof e }); + res.status(500).json({ error: 'registration failed' }); return; } - await prisma.invite.update({ where: { code }, data: { usedAt: new Date(), usedById: user.id } }); - try { - if (invite.tenantId) { - await prisma.membership.upsert({ - where: { tenantId_userId: { tenantId: invite.tenantId, userId: user.id } }, - update: {}, - create: { tenantId: invite.tenantId, userId: user.id, role: invite.role || 'member' }, - }); - } - } catch {} - let established; try { - established = await establishSession({ prisma, req, res, userId: user.id, tenantId: invite.tenantId }); + await establishSession({ prisma, req, res, userId: user.id, tenantId: invite.tenantId, verificationOnly: true }); } catch (e: unknown) { // No session row means no revocable session, so we do not hand out a // cookie either. The account and the redeemed invite survive; the user @@ -165,13 +169,8 @@ export async function handleAuthRegister( return; } - // Detached: a slow or dead mail provider must not fail a registration that - // already succeeded. The user can re-trigger via POST /auth/verify/request. - void startEmailVerification({ prisma, userId: user.id, req }).catch((e: unknown) => - logger.warn({ event: 'auth.register.verification_start_failed', userId: user.id, error: String(e) }), - ); - - res.json(buildSigninResponseBody(user, established.token, isNativeClientRequest(req))); + // Allow the cookie to perform verification actions without granting tenant access. + verificationPending(res, await beginInviteVerification(prisma, user.id, invite.id)); } const loginSchema = z.object({ email: z.string().email(), password: z.string().min(8) }); @@ -245,6 +244,50 @@ async function resolveTenantForLogin(prisma: PrismaClient, userId: string, req: return { ok: true as const, tenant, membership }; } +// Returns true when the response was sent. +async function respondPendingInviteLogin( + prisma: PrismaClient, + req: express.Request, + res: express.Response, + userId: string, + requestedTenant: { id: string } | null | undefined, +): Promise { + const pendingInvite = await pendingInviteForUser(prisma, userId, requestedTenant?.id); + const marked = requestedTenant ? await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: requestedTenant.id, userId: userId } }, + }) : null; + if (marked?.inviteVerificationRequired || pendingInvite) { + if (!pendingInvite) { verificationBindingRequired(res); return true; } + await establishSession({ prisma, req, res, userId: userId, tenantId: pendingInvite.tenantId, verificationOnly: true }); + verificationPending(res, await beginInviteVerification(prisma, userId, pendingInvite.id)); + return true; + } + return false; +} + +// Returns null when the response was sent. +async function resolveLoginTenantOrRespond( + prisma: PrismaClient, + req: express.Request, + res: express.Response, + userId: string, + requestedTenant: { id: string } | null | undefined, +) { + const tenantResolution = await resolveTenantForLogin(prisma, userId, req); + if (!tenantResolution.ok) { + // An existing account without membership needs a session to accept an invitation. + // The 409 response does not grant tenant access. + if (tenantResolution.error === 'not_member_of_tenant' && requestedTenant) { + await establishSession({ prisma, req, res, userId: userId, tenantId: requestedTenant.id, verificationOnly: true }); + res.status(409).json({ code: 'INVITE_ACCEPT_REQUIRED', error: 'Open your invitation link to continue with this account. Request a new invitation if it has expired.' }); + return null; + } + res.status(tenantResolution.status).json({ error: tenantResolution.error }); + return null; + } + return tenantResolution.tenant; +} + export async function handleAuthLogin( prisma: PrismaClient, req: express.Request, @@ -277,12 +320,14 @@ export async function handleAuthLogin( return; } - const tenantResolution = await resolveTenantForLogin(prisma, user.id, req); - if (!tenantResolution.ok) { - res.status(tenantResolution.status).json({ error: tenantResolution.error }); + const requestedTenant = getTenantFromReq(req) ?? getDeniedTenant(req); + if (await respondPendingInviteLogin(prisma, req, res, user.id, requestedTenant)) { + return; + } + const tenant = await resolveLoginTenantOrRespond(prisma, req, res, user.id, requestedTenant); + if (!tenant) { return; } - const { tenant } = tenantResolution; let established; try { @@ -312,61 +357,78 @@ export async function handleAuthLogout( res.json({ ok: true }); } -async function loadInternalOwnerFlag(prisma: PrismaClient, userId: string): Promise { - try { - const internal = await prisma.tenant.findUnique({ where: { slug: 'internal' } }); - if (!internal) return false; - const internalMember = await prisma.membership.findUnique({ - where: { tenantId_userId: { tenantId: internal.id, userId } }, +// Returns true when the response was sent. +async function respondVerificationGate( + prisma: PrismaClient, + req: express.Request, + res: express.Response, + auth: NonNullable>, +): Promise { + if (auth.verificationOnly) { + const pending = await pendingInviteForUser(prisma, auth.userId, auth.tenantId); + if (pending) verificationPending(res); + else res.status(409).json({ code: 'ACCOUNT_LOGIN_REQUIRED', error: 'Please sign in to continue.' }); + return true; + } + const resolvedTenant = getTenantFromReq(req) ?? getDeniedTenant(req); + if (resolvedTenant) { + const marked = await prisma.membership.findUnique({ + where: { + tenantId_userId: { + tenantId: resolvedTenant.id, + userId: auth.userId, + }, + }, }); - return internalMember?.role === 'owner'; - } catch { - return false; + const pending = await pendingInviteForUser(prisma, auth.userId, resolvedTenant.id); + if (marked?.inviteVerificationRequired || pending) { + if (!pending) verificationBindingRequired(res); + else verificationPending(res); + return true; + } } + return false; } -export async function handleAuthMe(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { - const auth = requireAuth(req); - if (!auth) { - res.status(401).json({ error: 'unauthorized' }); - return; - } - const tenant = getTenantFromReq(req); - if (!tenant) { - res.status(400).json({ error: 'tenant_required' }); - return; - } - const member = await prisma.membership.findUnique({ - where: { tenantId_userId: { tenantId: tenant.id, userId: auth.userId } }, - select: { id: true, role: true, expiresAt: true }, - }); - if (!member) { - res.status(403).json({ error: 'not_member_of_tenant' }); - return; - } - const user = await prisma.user.findUnique({ - where: { id: auth.userId }, - include: { - presences: { - where: { tenantId: tenant.id }, - orderBy: { updatedAt: 'desc' }, - take: 1, - }, - }, - }); - if (!user) { - res.status(401).json({ error: 'unauthorized' }); - return; - } - const isInternalOwner = await loadInternalOwnerFlag(prisma, auth.userId); - const lastPosition = user.presences[0]; +async function loadMeCapabilities(): Promise<{ + hasBilling: boolean; + hasAdminEnterprise: boolean; + isMultiTenant: boolean; +}> { const tenancyModule = await getTenancyModule(); - const capabilities = { + return { hasBilling: await hasBillingModule(), hasAdminEnterprise: await hasAdminEnterpriseModule(), isMultiTenant: tenancyModule.isMultiTenantEnabled(), }; - res.json({ +} + +function meResponseBody( + user: { + id: string; + email: string; + name: string | null; + avatarId: string | null; + emailVerifiedAt: Date | null; + onboardingCompleted: boolean; + presences: Array<{ + x: number; + y: number; + direction: string; + mapName: string | null; + }>; + }, + tenant: { slug: string }, + member: { role: string; expiresAt: Date | null }, + isInternalOwner: boolean, + capabilities: { + hasBilling: boolean; + hasAdminEnterprise: boolean; + isMultiTenant: boolean; + }, +): Record { + const lastPosition = user.presences[0]; + return { id: user.id, email: user.email, name: user.name, @@ -394,5 +456,54 @@ export async function handleAuthMe(prisma: PrismaClient, req: express.Request, r mapName: lastPosition.mapName || null, } : null, + }; +} + +export async function handleAuthMe(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const auth = requireVerificationAuth(req); + if (!auth) { + res.status(401).json({ error: 'unauthorized' }); + return; + } + if (await respondVerificationGate(prisma, req, res, auth)) { + return; + } + const tenant = getTenantFromReq(req); + if (!tenant && isTenantAccessDenied(req)) { + // Same answer as before the central guard: the caller is signed in but + // not a member of the tenant the request names. + res.status(403).json({ error: 'not_member_of_tenant' }); + return; + } + if (!tenant) { + res.status(400).json({ error: 'tenant_required' }); + return; + } + const member = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: tenant.id, userId: auth.userId } }, + select: { id: true, role: true, expiresAt: true }, + }); + if (!member) { + res.status(403).json({ error: 'not_member_of_tenant' }); + return; + } + const user = await prisma.user.findUnique({ + where: { id: auth.userId }, + include: { + presences: { + where: { tenantId: tenant.id }, + orderBy: { updatedAt: 'desc' }, + take: 1, + }, + }, }); + if (!user) { + res.status(401).json({ error: 'unauthorized' }); + return; + } + const isInternalOwner = await checkInternalOwner(prisma, auth.userId); + const capabilities = await loadMeCapabilities(); + res.json( + meResponseBody(user, tenant, member, isInternalOwner, capabilities), + ); } diff --git a/apps/server/src/api/routes/auth.ts b/apps/server/src/api/routes/auth.ts index 4d09c0fa..6fbec5c7 100644 --- a/apps/server/src/api/routes/auth.ts +++ b/apps/server/src/api/routes/auth.ts @@ -1,5 +1,6 @@ import type express from 'express'; import { PrismaClient } from '../../generated/prisma/index.js'; +import { credentialRoute } from '../middleware/tenantAccess.js'; import { handleAuthInvite, handleAuthRegister, @@ -18,28 +19,33 @@ import { forgotPasswordEmailRateLimiter, emailVerificationRateLimiter, } from '../middleware/rateLimit.js'; +import { inviteCreateRateLimiter } from '../middleware/inviteRateLimit.js'; +import { createPasswordChangeRateLimiters } from '../middleware/passwordChangeRateLimit.js'; export function registerAuthRoutes(app: express.Application, prisma: PrismaClient) { - // Sign-in / registration. The public, unauthenticated endpoints below are - // rate limited per client IP (see middleware/rateLimit.ts). /auth/invite and - // /auth/change require an authenticated caller and are left unthrottled here. - app.post('/auth/invite', (req, res) => handleAuthInvite(prisma, req, res)); - app.post('/auth/register', registrationRateLimiter, (req, res) => handleAuthRegister(prisma, req, res)); - app.post('/auth/login', loginRateLimiter, (req, res) => handleAuthLogin(prisma, req, res)); + // Public sign-in / registration endpoints are rate limited by IP; /auth/invite is limited per user. + // Apply separate user and IP budgets to password changes. + app.post('/auth/invite', inviteCreateRateLimiter, (req, res) => handleAuthInvite(prisma, req, res)); + app.post('/auth/register', credentialRoute, registrationRateLimiter, (req, res) => + handleAuthRegister(prisma, req, res), + ); + app.post('/auth/login', credentialRoute, loginRateLimiter, (req, res) => handleAuthLogin(prisma, req, res)); app.post('/auth/logout', (req, res) => handleAuthLogout(prisma, req, res)); app.get('/auth/me', (req, res) => handleAuthMe(prisma, req, res)); // Password flow. /auth/forgot mails a real reset link, so it is budgeted // twice: per client IP and per requested address (see middleware/rateLimit.ts). - app.post('/auth/forgot', passwordResetRateLimiter, forgotPasswordEmailRateLimiter, (req, res) => + app.post('/auth/forgot', credentialRoute, passwordResetRateLimiter, forgotPasswordEmailRateLimiter, (req, res) => handleAuthForgot(prisma, req, res), ); - app.post('/auth/reset', passwordResetRateLimiter, (req, res) => handleAuthReset(prisma, req, res)); - app.post('/auth/change', (req, res) => handleAuthChange(prisma, req, res)); + app.post('/auth/reset', credentialRoute, passwordResetRateLimiter, (req, res) => handleAuthReset(prisma, req, res)); + app.post('/auth/change', ...createPasswordChangeRateLimiters(), (req, res) => handleAuthChange(prisma, req, res)); // Email verification app.post('/auth/verify/request', emailVerificationRateLimiter, (req, res) => handleVerifyRequest(prisma, req, res)); - app.post('/auth/verify', emailVerificationRateLimiter, (req, res) => handleVerifyToken(prisma, req, res)); + app.post('/auth/verify', credentialRoute, emailVerificationRateLimiter, (req, res) => + handleVerifyToken(prisma, req, res), + ); app.get('/auth/verify/status', (req, res) => handleVerifyStatus(prisma, req, res)); // Sessions diff --git a/apps/server/src/api/routes/auth.verificationScope.integration.test.ts b/apps/server/src/api/routes/auth.verificationScope.integration.test.ts new file mode 100644 index 00000000..843b8047 --- /dev/null +++ b/apps/server/src/api/routes/auth.verificationScope.integration.test.ts @@ -0,0 +1,146 @@ +import crypto from 'node:crypto'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; +import { registerUserRoutes } from './users.js'; +import { registerPresenceRoutes } from './presence.js'; +import { registerTmjImportRoute } from './tmj.import.js'; +import { getJwtSecret, getTenantFromReq, requireAuth } from '../utils/authHelpers.js'; +import { hashSessionToken, validateSessionToken } from '../utils/sessionAuth.js'; + +const setup = createEmailProofFixture(); +const { fixture, app } = setup; +registerUserRoutes(app, fixture.prisma, requireAuth, getTenantFromReq); +registerPresenceRoutes(app, fixture.prisma, requireAuth, getTenantFromReq); +registerTmjImportRoute(app, fixture.prisma); +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +async function restrictedSession(expired = false) { + const own = await fixture.tenant(); + const password = crypto.randomBytes(20).toString('hex'); + const user = await fixture.caller(own.tenant, 'member', password); + const account = await fixture.prisma.user.update({ where: { id: user.id }, data: { emailVerifiedAt: null } }); + const now = Math.floor(Date.now() / 1000); + const issuedAt = expired ? now - 901 : now; + const token = jwt.sign( + { + sub: user.id, + tid: own.tenant.id, + jti: crypto.randomUUID(), + scope: 'email_verification', + iat: issuedAt, + exp: issuedAt + 900, + }, + getJwtSecret(), + ); + // Keep the row live so rejection proves JWT expiry rather than row expiry. + await fixture.prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 900_000) }, + }); + return { ...own, user: account, token, cookie: `auth_token=${token}`, password }; +} + +it('issues a signed verification-only registration session with a fifteen-minute lifetime', async () => { + const { tenant } = await fixture.tenant(); + const email = setup.email(); + fixture.userEmails.push(email); + const invite = await fixture.prisma.invite.create({ + data: { + tenantId: tenant.id, + email, + code: crypto.randomBytes(12).toString('hex'), + role: 'member', + expiresAt: new Date(Date.now() + 3_600_000), + }, + }); + const result = await request(app) + .post('/auth/register') + .set('X-Tenant', tenant.slug) + .send({ code: invite.code, email, password: crypto.randomBytes(20).toString('hex') }); + const cookies = result.headers['set-cookie']; + const cookie = Array.isArray(cookies) + ? cookies.find((value: string) => value.startsWith('auth_token='))?.split(';')[0] + : null; + if (!cookie) throw new Error('Registration did not establish a session.'); + const token = cookie.slice('auth_token='.length); + const payload = jwt.verify(token, getJwtSecret()); + expect(typeof payload).toBe('object'); + if (typeof payload === 'string') throw new Error('Expected a signed session payload.'); + expect(payload.scope).toBe('email_verification'); + expect((payload.exp ?? 0) - (payload.iat ?? 0)).toBe(900); + const row = await fixture.prisma.session.findUniqueOrThrow({ where: { tokenHash: hashSessionToken(token) } }); + expect(Math.abs(row.expiresAt.getTime() - (payload.exp ?? 0) * 1000)).toBeLessThan(1100); + expect(result.status).toBe(409); + const accepted = await request(app).post('/invites/accept').set('Cookie', cookie).send({ code: invite.code }); + expect(accepted.status).toBe(409); + expect(accepted.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + expect(await fixture.prisma.membership.count({ where: { userId: row.userId } })).toBe(0); + expect((await request(app).post('/auth/logout').set('Cookie', cookie).send({})).status).toBe(200); + expect(await fixture.prisma.session.findUnique({ where: { id: row.id } })).toBeNull(); +}); + +it('denies private resources and world authentication before and after proof until a fresh login', async () => { + const value = await restrictedSession(); + for (const [method, path] of [ + ['get', `/users/${value.user.id}`], + ['patch', '/me'], + ['get', '/users'], + ['delete', '/users/me'], + ['get', '/auth/sessions'], + ['post', '/auth/change'], + ['post', '/auth/position'], + ['get', '/presence/recent'], + ['post', `/maps/${value.map.id}/import-tmj`], + ] as const) { + const result = await request(app) + [method](path) + .set('X-Tenant', value.tenant.slug) + .set('Cookie', value.cookie) + .set('Content-Type', 'application/json') + .send(method === 'get' ? undefined : {}); + expect([401, 403].includes(result.status)).toBe(true); + } + expect(await validateSessionToken(fixture.prisma, value.token)).toBeNull(); + const resend = await request(app).post('/auth/verify/request').set('Cookie', value.cookie).send({}); + expect(resend.status).toBe(200); + const proof = await setup.tokenFromMail(value.user.email); + expect((await request(app).post('/auth/verify').send({ token: proof })).status).toBe(200); + expect((await request(app).get(`/users/${value.user.id}`).set('Cookie', value.cookie)).status).toBe(403); + expect(await validateSessionToken(fixture.prisma, value.token)).toBeNull(); + expect((await request(app).get('/auth/verify/status').set('Cookie', value.cookie)).body).toEqual({ + code: 'ACCOUNT_LOGIN_REQUIRED', + status: 'login_required', + }); + const login = await request(app) + .post('/auth/login') + .set('X-Tenant', value.tenant.slug) + .send({ email: value.user.email, password: value.password }); + expect(login.status).toBe(200); + const cookies = login.headers['set-cookie']; + const fullCookie = Array.isArray(cookies) + ? cookies.find((value: string) => value.startsWith('auth_token='))?.split(';')[0] + : null; + if (!fullCookie) throw new Error('The confirmed login did not establish a session.'); + expect( + (await request(app).get(`/users/${value.user.id}`).set('X-Tenant', value.tenant.slug).set('Cookie', fullCookie)) + .status, + ).toBe(200); +}); + +it('returns only status and code to a verification-only pending session', async () => { + const value = await restrictedSession(); + const result = await request(app).get('/auth/verify/status').set('Cookie', value.cookie); + expect(result.status).toBe(200); + expect(result.body).toEqual({ code: 'EMAIL_VERIFICATION_REQUIRED', status: 'unavailable' }); +}); + +it('rejects an expired fifteen-minute verification session even while its database row remains live', async () => { + const value = await restrictedSession(true); + const result = await request(app).get('/auth/verify/status').set('Cookie', value.cookie); + expect(result.status).toBe(401); + expect(await validateSessionToken(fixture.prisma, value.token)).toBeNull(); +}); diff --git a/apps/server/src/api/routes/auth.verify.ts b/apps/server/src/api/routes/auth.verify.ts index 6188d7dc..b6ad968c 100644 --- a/apps/server/src/api/routes/auth.verify.ts +++ b/apps/server/src/api/routes/auth.verify.ts @@ -1,168 +1,62 @@ import type express from 'express'; -import { PrismaClient } from '../../generated/prisma/index.js'; -import crypto from 'crypto'; +import type { PrismaClient } from '../../generated/prisma/index.js'; import { z } from 'zod'; -import { logger } from '../../logger.js'; -import { requireAuth } from '../utils/authHelpers.js'; -import { resolvePublicBaseUrl } from './auth.helpers.js'; -import { sendIfAvailable } from '../../emailLoader.js'; +import { requireVerificationAuth } from '../utils/authHelpers.js'; +import { getDeniedTenant } from '../utils/tenantAccessState.js'; +import { completeEmailProof, EmailProofInvalid, issueEmailProof, type EmailProofOutcome } from '../utils/emailProof.js'; +import { pendingInviteForUser, verificationBindingRequired } from '../utils/inviteVerification.js'; -/** Cooldown between two verification mails for the same user. */ -const VERIFICATION_COOLDOWN_MS = 2 * 60 * 1000; -/** Lifetime of a verification token. */ -const VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000; +export type EmailVerificationOutcome = EmailProofOutcome; -export type EmailVerificationOutcome = - | { status: 'user_not_found' } - | { status: 'already_verified' } - | { status: 'throttled' } - | { status: 'issued'; sent: boolean; token: string; verifyUrl: string }; - -/** - * Issue an e-mail verification token for a user and mail it out. - * - * The single place that starts a verification, shared by `POST - * /auth/verify/request` (user clicks "resend") and by account creation, which - * must trigger it instead of stamping `emailVerifiedAt` at birth — a stamp that - * made the whole verification machinery unreachable. It is exported for the - * enterprise sign-up, which has to start verification for the accounts it - * creates through the same path. - * - * `sent: false` means no mail provider was configured (OSS console fallback); - * the caller decides whether to surface the token out of band. Errors are - * propagated, never swallowed: a caller for which verification is - * non-blocking (account creation) catches and logs. - */ +/** Share this entry point with enterprise signup without returning secrets. */ export async function startEmailVerification(params: { - prisma: PrismaClient; - userId: string; - req: express.Request; + prisma: PrismaClient; userId: string; req: express.Request; }): Promise { const { prisma, userId, req } = params; - const user = await prisma.user.findUnique({ where: { id: userId } }); - if (!user) return { status: 'user_not_found' }; - if (user.emailVerifiedAt) return { status: 'already_verified' }; - - const recent = await prisma.emailVerification.findFirst({ - where: { userId: user.id, createdAt: { gte: new Date(Date.now() - VERIFICATION_COOLDOWN_MS) } }, - }); - if (recent) return { status: 'throttled' }; - - const token = crypto.randomBytes(24).toString('hex'); - const expiresAt = new Date(Date.now() + VERIFICATION_TTL_MS); - await prisma.emailVerification.create({ - data: { token, userId: user.id, email: user.email, expiresAt }, - }); - - // Public base URL for the verify link. A native-client Origin - // (tauri://localhost) is rejected so it never lands in the emailed link; - // see resolvePublicBaseUrl for the full precedence. - const baseUrl = resolvePublicBaseUrl({ - publicBaseUrl: process.env.PUBLIC_BASE_URL, - billingPublicUrl: process.env.BILLING_PUBLIC_URL, - origin: req.headers.origin, - host: req.headers.host, - }); - const verifyUrl = baseUrl ? `${baseUrl}/#/verify?token=${token}` : ''; - - // Locale chain (Block C): user.locale (DB) → MAIL_DEFAULT_LOCALE / 'de' - // (resolver default). The verify endpoint has no caller-supplied - // locale param, so we rely on the user's persisted UI locale. - const userLocale = user.locale === 'en' ? 'en' : user.locale === 'de' ? 'de' : undefined; - - const sent = await sendIfAvailable( - (mod) => mod.sendVerify({ to: user.email, name: user.name || '', verifyUrl, locale: userLocale }), - 'auth.verify.email_failed', - { userId: user.id }, - ); - - logger.info({ event: 'auth.verify.token_issued', userId: user.id, sent }); - return { status: 'issued', sent, token, verifyUrl }; + const tenantId = req.tenant?.id ?? getDeniedTenant(req)?.id; + const invite = await pendingInviteForUser(prisma, userId, tenantId); + const marked = await prisma.membership.findFirst({ where: { userId, inviteVerificationRequired: true, + ...(tenantId ? { tenantId } : {}) } }); + if (marked && !invite) return { status: 'binding_required' }; + return issueEmailProof({ prisma, userId, purpose: invite ? 'invite' : 'verify', inviteId: invite?.id }); } -export async function handleVerifyRequest( - prisma: PrismaClient, - req: express.Request, - res: express.Response, -): Promise { - const auth = requireAuth(req); - if (!auth) { - res.status(401).json({ error: 'unauthorized' }); - return; - } - - try { - const outcome = await startEmailVerification({ prisma, userId: auth.userId, req }); - if (outcome.status === 'user_not_found') { - res.status(404).json({ error: 'user not found' }); - return; - } - if (outcome.status === 'already_verified') { - res.json({ ok: true, alreadyVerified: true }); - return; - } - if (outcome.status === 'throttled') { - res.status(429).json({ error: 'Please wait before requesting another verification email' }); - return; - } - - // When no email was sent (OSS without any mail module), return the token - // and link directly so the user or admin can complete verification out of - // band. - const isDev = process.env.NODE_ENV !== 'production'; - const { sent, token, verifyUrl } = outcome; - res.json({ ok: true, sent, ...((!sent || isDev) && { token, verifyUrl }) }); - } catch (e: unknown) { - logger.error({ event: 'auth.verify.request_failed', error: String(e) }); - res.status(500).json({ error: 'verification request failed' }); +export function emailProofResponse(res: express.Response, outcome: EmailProofOutcome): void { + switch (outcome.status) { + case 'user_not_found': res.status(404).json({ error: 'Account not found.' }); return; + case 'already_verified': res.json({ ok: true, alreadyVerified: true }); return; + case 'binding_required': verificationBindingRequired(res); return; + case 'throttled': + res.setHeader('Retry-After', outcome.retryAfter); + res.status(429).json({ code: 'EMAIL_VERIFICATION_COOLDOWN', error: 'Please wait before requesting another confirmation email.', retryAfter: outcome.retryAfter }); return; + case 'no_public_base_url': + res.status(500).json({ code: 'PUBLIC_BASE_URL_MISSING', error: 'The public web address is not configured. Please contact an administrator.' }); return; + case 'delivery_unavailable': + res.status(503).json({ code: 'EMAIL_DELIVERY_UNAVAILABLE', error: 'Confirmation email could not be delivered. Please contact an administrator.' }); return; + case 'issued': res.json({ ok: true, sent: true }); return; } } -const verifySchema = z.object({ token: z.string().min(8) }); - -export async function handleVerifyToken( - prisma: PrismaClient, - req: express.Request, - res: express.Response, -): Promise { - const parse = verifySchema.safeParse(req.body || {}); - if (!parse.success) { - res.status(400).json({ error: 'token required' }); - return; - } - - const { token } = parse.data; +export async function handleVerifyRequest(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const auth = requireVerificationAuth(req); + if (!auth) { res.status(401).json({ error: 'Please sign in again.' }); return; } + try { emailProofResponse(res, await startEmailVerification({ prisma, userId: auth.userId, req })); } + catch { res.status(500).json({ error: 'Verification request failed.' }); } +} +const verifySchema = z.object({ token: z.string().min(8).max(256) }); +export async function handleVerifyToken(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const parsed = verifySchema.safeParse(req.body); + if (!parsed.success) { res.status(400).json({ code: 'EMAIL_PROOF_INVALID', error: 'Invalid confirmation link.' }); return; } try { - const verification = await prisma.emailVerification.findUnique({ where: { token } }); - if (!verification) { - res.status(400).json({ error: 'invalid token' }); + const result = await completeEmailProof(prisma, parsed.data.token); + res.json({ ok: true, ...result }); + } catch (error: unknown) { + if (error instanceof EmailProofInvalid || (error && typeof error === 'object' && 'code' in error && error.code === 'P2002')) { + res.status(400).json({ code: 'EMAIL_PROOF_INVALID', error: 'This link is invalid, expired or already used. Request a new confirmation email.' }); return; } - if (verification.usedAt) { - res.status(400).json({ error: 'token already used' }); - return; - } - if (verification.expiresAt < new Date()) { - res.status(400).json({ error: 'token expired' }); - return; - } - - await prisma.emailVerification.update({ - where: { token }, - data: { usedAt: new Date() }, - }); - - await prisma.user.update({ - where: { id: verification.userId }, - data: { emailVerifiedAt: new Date() }, - }); - - logger.info({ event: 'auth.verify.success', userId: verification.userId }); - res.json({ ok: true, message: 'Email verified successfully' }); - } catch (e: unknown) { - logger.error({ event: 'auth.verify.failed', error: String(e) }); - res.status(500).json({ error: 'verification failed' }); + res.status(500).json({ error: 'Verification failed.' }); } } @@ -171,7 +65,7 @@ export async function handleVerifyStatus( req: express.Request, res: express.Response, ): Promise { - const auth = requireAuth(req); + const auth = requireVerificationAuth(req); if (!auth) { res.status(401).json({ error: 'unauthorized' }); return; @@ -187,7 +81,22 @@ export async function handleVerifyStatus( return; } + const proof = await prisma.emailVerification.findFirst({ where: { userId: auth.userId, usedAt: null }, + orderBy: { createdAt: 'desc' }, select: { readyAt: true, expiresAt: true, purpose: true, email: true } }); + const pending = await pendingInviteForUser(prisma, auth.userId, auth.tenantId); + if (auth.verificationOnly) { + const requiresLogin = !!user.emailVerifiedAt && !pending; + res.json({ + code: requiresLogin ? 'ACCOUNT_LOGIN_REQUIRED' : 'EMAIL_VERIFICATION_REQUIRED', + status: requiresLogin ? 'login_required' + : proof?.readyAt && proof.expiresAt > new Date() ? 'sent' : 'unavailable', + }); + return; + } res.json({ + requiresLogin: auth.verificationOnly && !!user.emailVerifiedAt && !pending, + ...(proof?.purpose === 'email_change' && proof.readyAt && proof.expiresAt > new Date() ? { emailChangePending: true, pendingEmail: proof.email } : {}), + pendingDelivery: proof?.readyAt && proof.expiresAt > new Date() ? 'sent' : 'unavailable', email: user.email, verified: !!user.emailVerifiedAt, verifiedAt: user.emailVerifiedAt?.toISOString() || null, diff --git a/apps/server/src/api/routes/avatarPacks.ts b/apps/server/src/api/routes/avatarPacks.ts index 4249b1b1..2055f2db 100644 --- a/apps/server/src/api/routes/avatarPacks.ts +++ b/apps/server/src/api/routes/avatarPacks.ts @@ -1,7 +1,7 @@ import type express from 'express'; import { PrismaClient, Prisma } from '../../generated/prisma/index.js'; import { z } from 'zod'; -import multer from 'multer'; +import { uploadGuard, uploadParser, boundedMultipart } from '../middleware/uploadPolicy.js'; import crypto from 'crypto'; import path from 'path'; import { fileURLToPath } from 'url'; @@ -259,12 +259,9 @@ async function handleDeleteAvatarPack( export function registerAvatarPackRoutes(app: express.Application, prisma: PrismaClient) { const packsDir = process.env.ASSET_PACKS_DIR || path.resolve(__dirname, '../../../../../public/packs'); - const upload = multer({ - storage: multer.memoryStorage(), - limits: { fileSize: 5 * 1024 * 1024 }, - }); + const upload = uploadParser('avatar'); - app.post('/avatar-packs/upload-sprite', upload.single('file'), (req, res) => + app.post('/avatar-packs/upload-sprite', uploadGuard(prisma, 'avatar'), boundedMultipart(upload.single('file')), (req, res) => handleSpriteUpload(prisma, packsDir, req, res), ); app.get('/avatar-packs', (req, res) => handleListAvatarPacks(prisma, req, res)); diff --git a/apps/server/src/api/routes/controls.integration.test.ts b/apps/server/src/api/routes/controls.integration.test.ts new file mode 100644 index 00000000..88e67447 --- /dev/null +++ b/apps/server/src/api/routes/controls.integration.test.ts @@ -0,0 +1,286 @@ +import crypto from 'crypto'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import { PrismaPg } from '@prisma/adapter-pg'; +import request from 'supertest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { PrismaClient } from '../../generated/prisma/index.js'; +import type { Role, Tenant } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { resolveTenantBySlug } from '../../tenancy.js'; +import { guestExpiryMiddleware } from '../middleware/guestExpiry.js'; +import { createTenantAccessMiddleware } from '../middleware/tenantAccess.js'; +import { getJwtSecret, requireApiToken, requireAuth } from '../utils/authHelpers.js'; +import { createSessionAuthMiddleware, hashSessionToken } from '../utils/sessionAuth.js'; +import { registerControlRoutes } from './controls.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('controls.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +let app: express.Express; +let appBrokenGuard: express.Express; +let appNoTenant: express.Express; +let brokenPrisma: PrismaClient; +let tenantA: Tenant; +let tenantB: Tenant; +let sendCalls: Array<{ sessionId: string; event: string; data: unknown }>; + +async function createTenant(): Promise { + const slug = `controls-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant; +} + +async function createUser( + memberships: Array<{ tenantId: string; role: Role; expiresAt?: Date }>, +): Promise<{ id: string; session: string }> { + const user = await prisma.user.create({ data: { email: `controls-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + for (const membership of memberships) { + await prisma.membership.create({ data: { userId: user.id, ...membership } }); + } + + const tenantId = memberships[0]?.tenantId; + if (!tenantId) throw new Error('controls integration users require a primary tenant'); + const session = jwt.sign({ sub: user.id, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(session), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, session }; +} + +function setWorldRoom(callerId: string, targetId: string, tenantKey: string): void { + const players = new Map([ + ['caller-session', { identity: callerId }], + ['target-session', { identity: targetId }], + ]); + const playerTenantKey = new Map([ + ['caller-session', tenantKey], + ['target-session', tenantKey], + ]); + const clients = ['caller-session', 'target-session'].map((sessionId) => ({ + sessionId, + send: (event: string, data: unknown) => sendCalls.push({ sessionId, event, data }), + })); + const room = { state: { players }, playerTenantKey, clients }; + Object.defineProperty(globalThis, 'gameServer', { configurable: true, writable: true, value: {} }); + Object.defineProperty(globalThis, 'activeWorldRooms', { + configurable: true, + writable: true, + value: new Set([room]), + }); +} + +function targetedRequest(targetId: string, session: string, tenantSlug: string) { + return request(app) + .post(`/controls/for/${targetId}`) + .set('x-tenant', tenantSlug) + .set('Authorization', `Bearer ${session}`) + .send({ mic: false }); +} + +function targetedRequestOn(appInstance: express.Express, targetId: string, session: string, tenantSlug?: string) { + const pending = request(appInstance).post(`/controls/for/${targetId}`).set('Authorization', `Bearer ${session}`); + if (tenantSlug) pending.set('x-tenant', tenantSlug); + return pending.send({ mic: false }); +} + +async function resolveRealTenant(req: express.Request): Promise { + const tenant = await resolveTenantBySlug(prisma, req); + req.tenant = tenant ?? undefined; + req.tenantId = tenant?.id; +} + +function resolveNoTenant(req: express.Request): Promise { + // This mirrors resolveTenantBySlug returning null: in production an unknown + // explicit slug resolves to no tenant (see tenancy.ts resolveExplicitSlug), + // so the request legitimately carries no tenant context at all. + req.tenant = undefined; + req.tenantId = undefined; + return Promise.resolve(); +} + +function buildControlApp( + guardPrisma: PrismaClient, + resolveTenant: (req: express.Request) => Promise, +): express.Express { + const controlApp = express(); + controlApp.use(express.json()); + controlApp.use((req, _res, next) => { + void resolveTenant(req) + .then(() => next()) + .catch((error: unknown) => next(error)); + }); + controlApp.use(createSessionAuthMiddleware(prisma)); + controlApp.use(createTenantAccessMiddleware(guardPrisma)); + controlApp.use(guestExpiryMiddleware); + registerControlRoutes(controlApp, requireAuth, (req) => requireApiToken(req, prisma)); + return controlApp; +} + +beforeAll(async () => { + tenantA = await createTenant(); + tenantB = await createTenant(); + + app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + void resolveTenantBySlug(prisma, req) + .then((tenant) => { + req.tenant = tenant ?? undefined; + req.tenantId = tenant?.id; + next(); + }) + .catch((error: unknown) => next(error)); + }); + app.use(createSessionAuthMiddleware(prisma)); + app.use(createTenantAccessMiddleware(prisma)); + app.use(guestExpiryMiddleware); + registerControlRoutes(app, requireAuth, (req) => requireApiToken(req, prisma)); + + brokenPrisma = new PrismaClient({ + adapter: new PrismaPg({ connectionString: 'postgresql://s1http:s1http@127.0.0.1:1/unreachable' }), + }); + appBrokenGuard = buildControlApp(brokenPrisma, resolveRealTenant); + appNoTenant = buildControlApp(prisma, resolveNoTenant); +}); + +beforeEach(() => { + sendCalls = []; +}); + +afterEach(() => { + Reflect.deleteProperty(globalThis, 'gameServer'); + Reflect.deleteProperty(globalThis, 'activeWorldRooms'); +}); + +afterAll(async () => { + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await brokenPrisma.$disconnect(); + await prisma.$disconnect(); +}); + +describe('POST /controls/for/:identity with a verified request tenant (real database)', () => { + it('allows an active member of tenant A to control the target seated under A', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequest(target.id, caller.session, tenantA.slug); + + expect(res.status).toBe(200); + expect(sendCalls).toHaveLength(1); + expect(sendCalls[0]).toMatchObject({ + sessionId: 'target-session', + event: 'remote_controls_for', + data: { forIdentity: target.id, from: caller.id, payload: { mic: false } }, + }); + }); + + it('refuses a caller whose tenant A membership was removed after session creation', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + await prisma.membership.delete({ where: { tenantId_userId: { tenantId: tenantA.id, userId: caller.id } } }); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequest(target.id, caller.session, tenantA.slug); + + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'not_member_of_tenant' }); + expect(sendCalls).toHaveLength(0); + }); + + it('expires a guest session before targeted controls can be delivered', async () => { + const caller = await createUser([ + { tenantId: tenantA.id, role: 'guest', expiresAt: new Date(Date.now() - 60_000) }, + ]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + setWorldRoom(caller.id, target.id, tenantA.id); + + const expired = await targetedRequest(target.id, caller.session, tenantA.slug); + expect(expired.status).toBe(403); + expect(expired.body).toEqual({ error: 'guest_expired' }); + expect(sendCalls).toHaveLength(0); + + const replay = await targetedRequest(target.id, caller.session, tenantA.slug); + expect(replay.status).toBe(401); + expect(sendCalls).toHaveLength(0); + }); + + it('does not use tenant A seats when the request was verified against tenant B', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + await prisma.membership.delete({ where: { tenantId_userId: { tenantId: tenantA.id, userId: caller.id } } }); + await prisma.membership.create({ data: { tenantId: tenantB.id, userId: caller.id, role: 'member' } }); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequest(target.id, caller.session, tenantB.slug); + + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'caller_tenant_unknown' }); + expect(sendCalls).toHaveLength(0); + }); + + it('serves a session-token tenant without an X-Tenant header, like the web client', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequestOn(app, target.id, caller.session); + + expect(res.status).toBe(200); + expect(sendCalls).toHaveLength(1); + expect(sendCalls[0]).toMatchObject({ + sessionId: 'target-session', + event: 'remote_controls_for', + data: { forIdentity: target.id, from: caller.id, payload: { mic: false } }, + }); + }); + + it('refuses a session-token tenant whose membership was removed after session creation', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + await prisma.membership.delete({ where: { tenantId_userId: { tenantId: tenantA.id, userId: caller.id } } }); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequestOn(app, target.id, caller.session); + + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'not_member_of_tenant' }); + expect(sendCalls).toHaveLength(0); + }); + + it('fails closed when the guard cannot reach the database', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequestOn(appBrokenGuard, target.id, caller.session, tenantA.slug); + + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'not_member_of_tenant' }); + expect(sendCalls).toHaveLength(0); + }); + + it('requires a tenant when none could be resolved', async () => { + const caller = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + const target = await createUser([{ tenantId: tenantA.id, role: 'member' }]); + setWorldRoom(caller.id, target.id, tenantA.id); + + const res = await targetedRequestOn(appNoTenant, target.id, caller.session); + + expect(res.status).toBe(400); + expect(res.body).toEqual({ error: 'tenant_required' }); + expect(sendCalls).toHaveLength(0); + }); +}); diff --git a/apps/server/src/api/routes/controls.test.ts b/apps/server/src/api/routes/controls.test.ts index ade56bbe..132f65d0 100644 --- a/apps/server/src/api/routes/controls.test.ts +++ b/apps/server/src/api/routes/controls.test.ts @@ -75,9 +75,16 @@ function worldRoom(roomIndex: number, seats: Seat[], sendCalls: SendCall[]) { * tenant; `apiToken: true` swaps the session for an API token, which resolves a * user but never a tenant (see api/utils/authHelpers.ts requireApiToken). */ -function makeApp(opts: { sessionTenantId?: string; apiToken?: boolean } = {}): express.Application { +function makeApp( + opts: { sessionTenantId?: string; requestTenantId?: string; apiToken?: boolean } = {}, +): express.Application { const app = express(); app.use(express.json()); + const requestTenantId = opts.requestTenantId ?? opts.sessionTenantId ?? TENANT_A; + app.use((req, _res, next) => { + Object.assign(req, { tenant: { id: requestTenantId, slug: requestTenantId, name: requestTenantId } }); + next(); + }); const session = opts.apiToken ? null : { userId: CALLER, ...(opts.sessionTenantId ? { tenantId: opts.sessionTenantId } : {}) }; @@ -556,7 +563,7 @@ describe("authorization: the caller's tenant comes from the request, not from a it('acts under the tenant the request authenticated with', async () => { apexRoomWithTwoCallerTenants(); - const res = await request(makeApp({ sessionTenantId: TENANT_B })) + const res = await request(makeApp({ requestTenantId: TENANT_B })) .post('/controls/for/victim') .send({ mic: false }); @@ -567,7 +574,7 @@ describe("authorization: the caller's tenant comes from the request, not from a it('does not let a seat under another tenant widen the reach of the request', async () => { apexRoomWithTwoCallerTenants(); - const res = await request(makeApp({ sessionTenantId: TENANT_A })) + const res = await request(makeApp({ requestTenantId: TENANT_A })) .post('/controls/for/victim') .send({ mic: false }); @@ -588,7 +595,7 @@ describe("authorization: the caller's tenant comes from the request, not from a ), ); - const res = await request(makeApp({ sessionTenantId: TENANT_B })) + const res = await request(makeApp({ requestTenantId: TENANT_B })) .post('/controls/for/victim') .send({ mic: false }); @@ -597,17 +604,15 @@ describe("authorization: the caller's tenant comes from the request, not from a expect(sendCalls).toHaveLength(0); }); - it('refuses an API token whose caller sits under two tenants at once (fails closed)', async () => { - // A token resolves a user, never a tenant, so only the seats can answer — - // and two different answers are no answer. + it('uses the verified request tenant for an API token when the caller has seats under two tenants', async () => { apexRoomWithTwoCallerTenants(); - const res = await request(makeApp({ apiToken: true })) + const res = await request(makeApp({ apiToken: true, requestTenantId: TENANT_B })) .post('/controls/for/victim') .send({ mic: false }); - expect(res.status).toBe(403); - expect(res.body).toMatchObject({ error: 'caller_tenant_unknown' }); - expect(sendCalls).toHaveLength(0); + expect(res.status).toBe(200); + expect(recipients(sendCalls)).toEqual(['r0s2']); + expect(res.body).toMatchObject({ delivered: 1 }); }); }); diff --git a/apps/server/src/api/routes/controls.ts b/apps/server/src/api/routes/controls.ts index bf6c928e..3293944f 100644 --- a/apps/server/src/api/routes/controls.ts +++ b/apps/server/src/api/routes/controls.ts @@ -1,6 +1,8 @@ import type express from 'express'; import { z } from 'zod'; import { isPlayerVisibleToTenant } from '../../rooms/lifecycle/tenantView.js'; +import { getTenantFromReq } from '../utils/authHelpers.js'; +import { isTenantAccessDenied } from '../utils/tenantAccessState.js'; /** A connected Colyseus client, as much of it as the delivery below needs. */ interface ControlClient { @@ -121,17 +123,11 @@ interface ControlTarget { type ControlError = 'caller_not_in_a_world_room' | 'caller_tenant_unknown' | 'target_not_reachable'; type ControlTargets = { targets: ControlTarget[] } | { error: ControlError }; -/** The verified caller behind a control request. */ +/** The caller and request tenant verified by the central tenant guard. */ interface ControlCaller { userId: string; - /** - * The tenant THIS REQUEST authenticated under. `requireAuth` reads it from - * the session, i.e. from the same JWT claim the world join verifies into - * `playerTenantKey` (see `api/utils/authHelpers.ts` and - * `rooms/lifecycle/onAuth.ts`), so the two are comparable. Undefined for an - * API token: `requireApiToken` resolves a user, never a tenant. - */ - tenantId?: string | undefined; + /** The tenant approved for THIS request by tenantAccess.ts, never its session's `tid` or its seats. */ + tenantId: string; } /** @@ -170,30 +166,13 @@ function resolveOwnSessions(callerId: string): ControlTargets { } /** - * The caller's verified tenant key inside ONE room, or undefined when it cannot - * be established beyond doubt — in which case the caller is not authorized for - * that room at all. - * - * One user can hold several seats in one room, and in a shared apex room those - * seats can carry different verified tenants (see `ControlWorldRoom`). Taking - * the first seat that happened to have a key let the iteration order decide - * which tenant a control was issued under. The request's own tenant decides - * instead; a seat under that key is the caller acting as itself, and a room - * where it holds no such seat is simply not its room for this request. - * - * An API token carries no tenant, so there the seats have to answer alone and - * only an unambiguous answer counts: exactly one distinct key. None, or more - * than one, fails closed. + * The request tenant approved by the central guard, if the caller has a seat + * carrying that tenant key in this room. A session `tid` and the set of seats + * never choose the request tenant; without a matching seat the caller is not + * authorized for this room. */ -function resolveCallerKey(seats: Seat[], requestTenantId: string | undefined): string | undefined { - const keys = new Set(); - for (const seat of seats) { - if (seat.tenantKey !== undefined) keys.add(seat.tenantKey); - } - if (requestTenantId !== undefined) return keys.has(requestTenantId) ? requestTenantId : undefined; - if (keys.size !== 1) return undefined; - const [only] = keys; - return only; +function resolveCallerKey(seats: Seat[], requestTenantId: string): string | undefined { + return seats.some((seat) => seat.tenantKey === requestTenantId) ? requestTenantId : undefined; } /** @@ -207,8 +186,9 @@ function resolveCallerKey(seats: Seat[], requestTenantId: string | undefined): s * whether the sender had any authority. * * The rule enforced is the narrowest one that keeps the feature working: the - * caller may only reach a room it is seated in itself, only under the verified - * tenant key of this request, and the target must be seated in that same room + * caller may only reach a room it is seated in itself, only under the tenant + * approved for this request by the central guard in tenantAccess.ts (never the + * session's `tid` or the room's seats), and the target must be seated in that same room * AND visible to the caller under the room's tenant filter — the same predicate * the state sync uses, so a target the caller cannot even see cannot be * controlled either. Of a target with several sessions only those that passed @@ -327,13 +307,19 @@ export function registerControlRoutes( res.json({ ok: true, delivered }); }); - // Controls for a specific identity (session or API token) + // Targeted controls use only the tenant the central guard approved for this request. app.post('/controls/for/:identity', async (req: express.Request, res: express.Response) => { const sessionAuth = requireAuth(req); const tokenAuth = await requireApiToken(req); const auth = sessionAuth || tokenAuth; if (!auth) return res.status(401).json({ error: 'unauthorized' }); + const tenant = getTenantFromReq(req); + if (!tenant) { + if (isTenantAccessDenied(req)) return res.status(403).json({ error: 'not_member_of_tenant' }); + return res.status(400).json({ error: 'tenant_required' }); + } + const parse = controlPayloadSchema.safeParse(req.body || {}); if (!parse.success) return res.status(400).json({ error: 'invalid payload' }); @@ -346,9 +332,7 @@ export function registerControlRoutes( if (!global.gameServer) return res.status(500).json({ error: 'game server not available' }); - // The tenant comes from the session, not from the seats: only the session - // path has one, and only it is verified for THIS request (see ControlCaller). - const caller: ControlCaller = { userId: auth.userId, tenantId: sessionAuth?.tenantId }; + const caller: ControlCaller = { userId: auth.userId, tenantId: tenant.id }; const targets = resolveControlTargets(caller, identity); if ('error' in targets) return res.status(403).json({ error: targets.error }); diff --git a/apps/server/src/api/routes/displayName.write.test.ts b/apps/server/src/api/routes/displayName.write.test.ts index 3acf646a..c22ded13 100644 --- a/apps/server/src/api/routes/displayName.write.test.ts +++ b/apps/server/src/api/routes/displayName.write.test.ts @@ -14,6 +14,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.hoisted(() => { process.env.JWT_SECRET = 'display-name-test-secret'; process.env.NODE_ENV = 'test'; + process.env.PUBLIC_BASE_URL = 'https://app.example.test'; }); vi.mock('../../logger.js', () => ({ @@ -66,9 +67,17 @@ function makePrisma(callerRole: 'member' | 'admin' = 'admin') { }, invite: { findUnique: vi.fn(() => - Promise.resolve({ code: 'INVITE-1', usedAt: null, email: null, tenantId: TENANT.id, role: 'member' }), + Promise.resolve({ + code: 'INVITE-1', + usedAt: null, + email: 'new@example.test', + tenantId: TENANT.id, + role: 'member', + expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), + }), ), update: vi.fn(() => Promise.resolve({})), + updateMany: vi.fn(() => Promise.resolve({ count: 1 })), }, membership: { findUnique: vi.fn(({ where }: { where: { tenantId_userId: { userId: string } } }) => { @@ -87,6 +96,7 @@ function makePrisma(callerRole: 'member' | 'admin' = 'admin') { guestToken: { create: vi.fn(() => Promise.resolve({})) }, tenant: { findUnique: vi.fn(() => Promise.resolve(TENANT)) }, } as unknown as PrismaClient; + prisma.$transaction = (operation) => operation(prisma); return { prisma, created, updated }; } @@ -264,26 +274,6 @@ describe('POST /auth/register', () => { expect(created).toEqual([]); }); - it('creates the user with the trimmed name', async () => { - const { prisma, created } = makePrisma(); - - const res = await request(makeApp(prisma)) - .post('/auth/register') - .send({ ...credentials, name: ' Jörg Müller ' }); - - expect(res.status).toBe(200); - expect(created[0]?.data.name).toBe('Jörg Müller'); - }); - - it('still accepts a registration without a name', async () => { - const { prisma, created } = makePrisma(); - - const res = await request(makeApp(prisma)).post('/auth/register').send(credentials); - - expect(res.status).toBe(200); - expect(created[0]?.data.name).toBeUndefined(); - }); - it('keeps its message for a failure that is not about the name', async () => { const { prisma, created } = makePrisma(); diff --git a/apps/server/src/api/routes/editorStateSchema.test.ts b/apps/server/src/api/routes/editorStateSchema.test.ts new file mode 100644 index 00000000..eeba3f8c --- /dev/null +++ b/apps/server/src/api/routes/editorStateSchema.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it } from 'vitest'; +import { editorStateSchema } from './editorStateSchema.js'; +import { dndSchema, moveSchema } from '../../rooms/validation/worldPayloadSchemas.js'; + +interface TilesetSample { + key: string; + dataUrl: string; + tileWidth: number; + tileHeight: number; +} + +interface PointSample { + x: number; + y: number; +} + +function tilesets(count: number): TilesetSample[] { + const list: TilesetSample[] = []; + for (let index = 0; index < count; index += 1) { + list.push({ key: `sheet-${index}`, dataUrl: 'x', tileWidth: 1, tileHeight: 1 }); + } + return list; +} + +function zones(count: number): Array<{ name: string; points: PointSample[] }> { + const shape = polygon(3); + const list: Array<{ name: string; points: PointSample[] }> = []; + for (let index = 0; index < count; index += 1) list.push({ name: `area-${index}`, points: shape }); + return list; +} + +function polygon(count: number): PointSample[] { + const list: PointSample[] = []; + for (let index = 0; index < count; index += 1) list.push({ x: index, y: 0 }); + return list; +} + +describe('editor state schema', () => { + it('accepts 256 tilesets', () => { + expect(editorStateSchema.safeParse({ tilesets: tilesets(256) }).success).toBe(true); + }); + + it('rejects 257 tilesets', () => { + expect(editorStateSchema.safeParse({ tilesets: tilesets(257) }).success).toBe(false); + }); + + it('accepts 512 zones', () => { + expect(editorStateSchema.safeParse({ zones: zones(512) }).success).toBe(true); + }); + + it('rejects 513 zones', () => { + expect(editorStateSchema.safeParse({ zones: zones(513) }).success).toBe(false); + }); + + it('accepts a polygon of 3 points', () => { + const body = { zones: [{ name: 'Gate', points: polygon(3) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(true); + }); + + it('accepts a polygon of 2048 points', () => { + const body = { zones: [{ name: 'Gate', points: polygon(2048) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(true); + }); + + it('rejects a polygon of 2 points', () => { + const body = { zones: [{ name: 'Gate', points: polygon(2) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(false); + }); + + it('rejects a polygon of 2049 points', () => { + const body = { zones: [{ name: 'Gate', points: polygon(2049) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(false); + }); + + it('accepts a capacity of 10000', () => { + const body = { zones: [{ name: 'Hall', capacity: 10000, points: polygon(3) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(true); + }); + + it('rejects a capacity of 10001', () => { + const body = { zones: [{ name: 'Hall', capacity: 10001, points: polygon(3) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(false); + }); + + it('accepts a zone name of 256 characters', () => { + const body = { zones: [{ name: 'n'.repeat(256), points: polygon(3) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(true); + }); + + it('rejects a zone name of 257 characters', () => { + const body = { zones: [{ name: 'n'.repeat(257), points: polygon(3) }] }; + expect(editorStateSchema.safeParse(body).success).toBe(false); + }); + + it('keeps a zone id and a null capacity and drops an unknown key', () => { + const parsed = editorStateSchema.safeParse({ + zones: [ + { + id: 'zone-1', + name: 'Round', + capacity: null, + polygon: polygon(3), + type: 'default', + portalTarget: null, + portalSpawnX: null, + portalSpawnY: null, + legacyFlag: true, + }, + ], + }); + expect(parsed.success).toBe(true); + if (!parsed.success) return; + const zone = parsed.data.zones?.[0]; + expect(zone?.id).toBe('zone-1'); + expect(zone?.capacity).toBeNull(); + expect(zone).not.toHaveProperty('legacyFlag'); + }); +}); + +describe('move schema', () => { + it('rejects a coordinate sent as text', () => { + expect(moveSchema.safeParse({ x: '1', y: 0, direction: 'up' }).success).toBe(false); + }); + + it('rejects a coordinate that is not a number', () => { + expect(moveSchema.safeParse({ x: Number.NaN, y: 0, direction: 'up' }).success).toBe(false); + }); + + it('rejects an infinite coordinate', () => { + expect(moveSchema.safeParse({ x: Number.POSITIVE_INFINITY, y: 0, direction: 'up' }).success).toBe(false); + }); + + it('rejects an unknown direction', () => { + expect(moveSchema.safeParse({ x: 1, y: 0, direction: 'north' }).success).toBe(false); + }); +}); + +describe('dnd schema', () => { + it('rejects a do-not-disturb flag sent as text', () => { + expect(dndSchema.safeParse({ dnd: 'true' }).success).toBe(false); + }); +}); diff --git a/apps/server/src/api/routes/editorStateSchema.ts b/apps/server/src/api/routes/editorStateSchema.ts new file mode 100644 index 00000000..53690b29 --- /dev/null +++ b/apps/server/src/api/routes/editorStateSchema.ts @@ -0,0 +1,64 @@ +import { z } from 'zod'; + +export const MAX_EDITOR_TILESETS = 256; +export const MAX_EDITOR_ZONES = 512; + +const DATA_URL_MAX_CHARS = 4 * 1024 * 1024; +const MIN_POLYGON_POINTS = 3; +const MAX_POLYGON_POINTS = 2048; +const MAX_NAME_CHARS = 256; +const MAX_TILE_PX = 1024; +const MAX_ZONE_CAPACITY = 10000; + +const finiteNumber = z.number().finite(); + +const pointSchema = z + .object({ + x: finiteNumber, + y: finiteNumber, + }) + .strict(); + +const pointListSchema = z.array(pointSchema).min(MIN_POLYGON_POINTS).max(MAX_POLYGON_POINTS); + +const polygonSchema = z.union([pointListSchema, z.object({ points: pointListSchema }).strict()]); + +export const editorTilesetSchema = z.object({ + key: z.string().min(1).max(MAX_NAME_CHARS), + dataUrl: z.string().min(1).max(DATA_URL_MAX_CHARS), + tileWidth: z.number().int().min(1).max(MAX_TILE_PX), + tileHeight: z.number().int().min(1).max(MAX_TILE_PX), + margin: z.number().int().min(0).max(MAX_TILE_PX).optional(), + spacing: z.number().int().min(0).max(MAX_TILE_PX).optional(), + category: z.string().max(MAX_NAME_CHARS).optional(), +}); + +export const editorZoneSchema = z.object({ + id: z.string().max(MAX_NAME_CHARS).optional(), + name: z.string().min(1).max(MAX_NAME_CHARS), + type: z.enum(['default', 'portal']).nullable().optional(), + points: pointListSchema.optional(), + polygon: polygonSchema.nullable().optional(), + capacity: z.number().int().min(0).max(MAX_ZONE_CAPACITY).nullable().optional(), + portalTarget: z.string().max(MAX_NAME_CHARS).nullable().optional(), + portalSpawnX: finiteNumber.nullable().optional(), + portalSpawnY: finiteNumber.nullable().optional(), +}); + +const spawnSchema = z.object({ + x: finiteNumber, + y: finiteNumber, +}); + +// replaceZones is the existing clear-and-replace flag on the editor-state route. +export const editorStateSchema = z + .object({ + tilesets: z.array(editorTilesetSchema).max(MAX_EDITOR_TILESETS).optional(), + zones: z.array(editorZoneSchema).max(MAX_EDITOR_ZONES).optional(), + backgroundColor: z + .string() + .regex(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/) + .optional(), + replaceZones: z.boolean().optional(), + spawn: spawnSchema.optional(), + }); diff --git a/apps/server/src/api/routes/emailProof.change.integration.test.ts b/apps/server/src/api/routes/emailProof.change.integration.test.ts new file mode 100644 index 00000000..7a4e0838 --- /dev/null +++ b/apps/server/src/api/routes/emailProof.change.integration.test.ts @@ -0,0 +1,32 @@ +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +const setup = createEmailProofFixture(); +const { fixture, app, email, tokenFromMail } = setup; +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +it('notifies the old address and consumes the new-address proof atomically once', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + const next = email(); + const changed = await request(app) + .patch('/me') + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ email: next }); + expect(changed.status).toBe(202); + const token = await tokenFromMail(next); + await (await setup.mail.connect()).waitForMail({ to: before.email, subject: 'Email change requested' }); + expect((await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } })).email === before.email).toBe(true); + const results = await Promise.all(Array.from({ length: 5 }, () => request(app).post('/auth/verify').send({ token }))); + expect(results.filter((res) => res.status === 200)).toHaveLength(1); + expect(results.filter((res) => res.status === 400)).toHaveLength(4); + const after = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + expect(after.email === next).toBe(true); + expect(!!after.emailVerifiedAt).toBe(true); +}, 60_000); diff --git a/apps/server/src/api/routes/emailProof.expiry.integration.test.ts b/apps/server/src/api/routes/emailProof.expiry.integration.test.ts new file mode 100644 index 00000000..741d607d --- /dev/null +++ b/apps/server/src/api/routes/emailProof.expiry.integration.test.ts @@ -0,0 +1,26 @@ +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +const setup = createEmailProofFixture(); +const { fixture, app, registration } = setup; +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +it('creates no membership or partial consumption after expiry or revocation', async () => { + for (const action of ['expire', 'revoke']) { + const value = await registration(); + if (action === 'expire') + await fixture.prisma.emailVerification.updateMany({ + where: { userId: value.user.id }, + data: { expiresAt: new Date(Date.now() - 1_000) }, + }); + else await fixture.prisma.invite.delete({ where: { id: value.invite.id } }); + const result = await request(app).post('/auth/verify').send({ token: value.token }); + expect(result.status).toBe(400); + expect(await fixture.prisma.membership.count({ where: { userId: value.user.id } })).toBe(0); + expect((await fixture.prisma.user.findUniqueOrThrow({ where: { id: value.user.id } })).emailVerifiedAt).toBeNull(); + } +}, 60_000); diff --git a/apps/server/src/api/routes/emailProof.membership.integration.test.ts b/apps/server/src/api/routes/emailProof.membership.integration.test.ts new file mode 100644 index 00000000..4066a0d1 --- /dev/null +++ b/apps/server/src/api/routes/emailProof.membership.integration.test.ts @@ -0,0 +1,41 @@ +import crypto from 'node:crypto'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +const setup = createEmailProofFixture(); +const { fixture, app } = setup; +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +it('does not unlock an old marked administrator role through a new invitation', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant, 'admin'); + const user = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + await fixture.prisma.membership.update({ + where: { tenantId_userId: { tenantId: tenant.id, userId: caller.id } }, + data: { inviteVerificationRequired: true }, + }); + const invite = await fixture.prisma.invite.create({ + data: { + tenantId: tenant.id, + email: user.email, + code: crypto.randomBytes(12).toString('hex'), + role: 'member', + expiresAt: new Date(Date.now() + 3_600_000), + }, + }); + const result = await request(app) + .post('/invites/accept') + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ code: invite.code }); + expect(result.status).toBe(200); + const member = await fixture.prisma.membership.findUniqueOrThrow({ + where: { tenantId_userId: { tenantId: tenant.id, userId: caller.id } }, + }); + expect(member.role).toBe('member'); + expect(member.inviteVerificationRequired).toBe(false); +}); diff --git a/apps/server/src/api/routes/emailProof.race.integration.test.ts b/apps/server/src/api/routes/emailProof.race.integration.test.ts new file mode 100644 index 00000000..46f76e01 --- /dev/null +++ b/apps/server/src/api/routes/emailProof.race.integration.test.ts @@ -0,0 +1,45 @@ +import crypto from 'node:crypto'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +const setup = createEmailProofFixture(); +const { fixture, app, registration } = setup; +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +it('grants the permitted role once for five concurrent redemptions of a real mailbox proof', async () => { + const value = await registration(); + expect(await fixture.prisma.membership.count({ where: { userId: value.user.id } })).toBe(0); + const session = await fixture.session(value.user.id, value.tenant.id); + const blocked = await request(app) + .get('/auth/me') + .set('X-Tenant', value.tenant.slug) + .set('Authorization', `Bearer ${session.token}`); + expect(blocked.status).toBe(409); + const stored = await fixture.prisma.emailVerification.findFirstOrThrow({ + where: { userId: value.user.id, purpose: 'invite', inviteId: value.invite.id, readyAt: { not: null } }, + }); + expect(stored.token === value.token).toBe(false); + expect(stored.token === crypto.createHash('sha256').update(value.token).digest('hex')).toBe(true); + const responses = await Promise.all( + Array.from({ length: 5 }, () => request(app).post('/auth/verify').send({ token: value.token })), + ); + expect(responses.filter((res) => res.status === 200)).toHaveLength(1); + expect(responses.filter((res) => res.status === 400)).toHaveLength(4); + const members = await fixture.prisma.membership.findMany({ + where: { userId: value.user.id, tenantId: value.tenant.id }, + }); + expect(members.map((m) => m.role)).toEqual(['admin']); + expect((await fixture.prisma.invite.findUniqueOrThrow({ where: { id: value.invite.id } })).usedAt !== null).toBe( + true, + ); + const me = await request(app) + .get('/auth/me') + .set('X-Tenant', value.tenant.slug) + .set('Authorization', `Bearer ${session.token}`); + expect(me.status).toBe(200); + expect(me.body.role).toBe('admin'); +}, 60_000); diff --git a/apps/server/src/api/routes/emailProof.retry.integration.test.ts b/apps/server/src/api/routes/emailProof.retry.integration.test.ts new file mode 100644 index 00000000..1b3f335e --- /dev/null +++ b/apps/server/src/api/routes/emailProof.retry.integration.test.ts @@ -0,0 +1,25 @@ +import crypto from 'node:crypto'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +const setup = createEmailProofFixture(); +const { fixture, app, registration } = setup; +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +it('preserves the password and existing role on registration retry', async () => { + const value = await registration(); + const before = value.user.passwordHash; + const retry = await request(app) + .post('/auth/register') + .set('X-Tenant', value.tenant.slug) + .send({ code: value.invite.code, email: value.user.email, password: crypto.randomBytes(24).toString('hex') }); + expect(retry.status).toBe(409); + expect((await fixture.prisma.user.findUniqueOrThrow({ where: { id: value.user.id } })).passwordHash === before).toBe( + true, + ); + expect(await fixture.prisma.membership.count({ where: { userId: value.user.id } })).toBe(0); +}); diff --git a/apps/server/src/api/routes/emailProof.supersession.integration.test.ts b/apps/server/src/api/routes/emailProof.supersession.integration.test.ts new file mode 100644 index 00000000..e8f5bc94 --- /dev/null +++ b/apps/server/src/api/routes/emailProof.supersession.integration.test.ts @@ -0,0 +1,34 @@ +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createEmailProofFixture } from '../../../test/fixtures/emailProofFixture.js'; + +const setup = createEmailProofFixture(); +const { fixture, app, email, tokenFromMail } = setup; +beforeAll(async () => { + await setup.mail.connect(); +}); +afterAll(() => setup.close()); + +it('keeps superseded links invalid through an address round trip', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + const before = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + const first = email(), + second = email(); + const patch = (email: string) => + request(app) + .patch('/me') + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ email }); + expect((await patch(first)).status).toBe(202); + const old = await tokenFromMail(first); + expect((await patch(second)).status).toBe(202); + const current = await tokenFromMail(second); + expect((await request(app).post('/auth/verify').send({ token: old })).status).toBe(400); + expect((await request(app).post('/auth/verify').send({ token: current })).status).toBe(200); + // A new intent may target the original address without reviving its old proof. + expect((await patch(before.email)).status).toBe(202); + expect((await request(app).post('/auth/verify').send({ token: old })).status).toBe(400); + expect((await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } })).email === second).toBe(true); +}, 60_000); diff --git a/apps/server/src/api/routes/guests.ts b/apps/server/src/api/routes/guests.ts index d26fcb8e..3c07bcad 100644 --- a/apps/server/src/api/routes/guests.ts +++ b/apps/server/src/api/routes/guests.ts @@ -4,12 +4,15 @@ import crypto from 'crypto'; import { z } from 'zod'; import { logger } from '../../logger.js'; import { requireAuth, getTenantFromReq, requireMembership, normalizeEmailForStorage } from '../utils/authHelpers.js'; +import { buildPublicWebLink, requirePublicWebBase } from '../utils/publicLinks.js'; import { pathParam } from '../utils/requestHelpers.js'; import { displayNameSchema, invalidNameBodyFor } from '../utils/displayName.js'; import { establishSession, revokeSessionsForUser } from '../utils/sessionAuth.js'; import { getTenancyModule } from '../../tenancyLoader.js'; import { sendIfAvailable } from '../../emailLoader.js'; import { guestLoginRateLimiter } from '../middleware/rateLimit.js'; +import { credentialRoute } from '../middleware/tenantAccess.js'; +import { revokeTenantAccess } from '../../services/tenantAccessRevocation.js'; type GuestAdminGate = | { @@ -104,17 +107,14 @@ async function sendGuestInviteEmail( tenantSlug: string, user: { name: string | null; email: string }, name: string | undefined, + baseUrl: string, rawToken: string, expiresAt: Date, normalizedEmail: string, ): Promise { const tenantRecord = await prisma.tenant.findUnique({ where: { id: tenantId } }); const slug = tenantRecord?.slug || tenantSlug; - // Public base URL: self-hosters set `PUBLIC_BASE_URL` or - // `BILLING_PUBLIC_URL`. The brand domain (`*.meetropolis.me`) is only set - // in enterprise brand setups, with no fallback in OSS. - const baseUrl = process.env.PUBLIC_BASE_URL || process.env.BILLING_PUBLIC_URL || ''; - const magicLink = baseUrl ? `${baseUrl.replace(/\/$/, '')}/#/guest?token=${rawToken}` : `/#/guest?token=${rawToken}`; + const magicLink = buildPublicWebLink(baseUrl, `guest?token=${rawToken}`); const inviter = await prisma.user.findUnique({ where: { id: inviterId }, @@ -180,6 +180,9 @@ async function handleCreateGuest(prisma: PrismaClient, req: express.Request, res } const normalizedEmail = normalizeEmailForStorage(email); + const baseUrl = requirePublicWebBase(res, 'guests.create'); + if (!baseUrl) return; + const user = await ensureGuestUser(prisma, normalizedEmail, name); const upsert = await upsertGuestMembership(prisma, tenant.id, user.id, expiresAt); @@ -197,6 +200,7 @@ async function handleCreateGuest(prisma: PrismaClient, req: express.Request, res tenant.slug, user, name, + baseUrl, rawToken, expiresAt, normalizedEmail, @@ -260,6 +264,8 @@ async function handleRevokeGuest(prisma: PrismaClient, req: express.Request, res // cache. revokeSessionsForUser drops the cache entries with the rows. await revokeSessionsForUser(prisma, guestMembership.userId); await prisma.membership.delete({ where: { id: membershipId } }); + // End the guest's open world and AV connections now, not at the next sweep. + await revokeTenantAccess(tenant.slug, guestMembership.userId); res.json({ ok: true }); } @@ -336,5 +342,5 @@ export function registerGuestRoutes(app: express.Application, prisma: PrismaClie app.delete('/guests/:membershipId', (req, res) => handleRevokeGuest(prisma, req, res)); // Public, unauthenticated magic-link redemption: throttled per client IP to // curb guest-token brute-force (see middleware/rateLimit.ts). - app.post('/auth/guest', guestLoginRateLimiter, (req, res) => handleGuestLogin(prisma, req, res)); + app.post('/auth/guest', credentialRoute, guestLoginRateLimiter, (req, res) => handleGuestLogin(prisma, req, res)); } diff --git a/apps/server/src/api/routes/health.test.ts b/apps/server/src/api/routes/health.test.ts index 3ac1b992..b4afebd5 100644 --- a/apps/server/src/api/routes/health.test.ts +++ b/apps/server/src/api/routes/health.test.ts @@ -3,6 +3,12 @@ * client-supplied `identity`, and must only mint tokens for the one * LiveKit room the zone orchestrator actually reconciles (`world`). * See knowledge/... H4 spec, WP0. + * + * A LiveKit token belongs to a login session: the route resolves the raw + * token from the `auth_token` cookie or the `Authorization: Bearer` header + * against the database and takes the identity from that session. A + * credential that is not a live session therefore never obtains an SFU + * token, and the identity is the session's user, never the client's word. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type express from 'express'; @@ -11,13 +17,16 @@ vi.mock('../../logger.js', () => ({ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, })); -const requireAuthMock = vi.fn(); const getTenantFromReqMock = vi.fn(); -const requireMembershipMock = vi.fn(); vi.mock('../utils/authHelpers.js', () => ({ - requireAuth: (...args: unknown[]) => requireAuthMock(...args), getTenantFromReq: (...args: unknown[]) => getTenantFromReqMock(...args), - requireMembership: (...args: unknown[]) => requireMembershipMock(...args), + // The session reference carried by the LiveKit token is derived from it. + getJwtSecret: () => 'test-jwt-secret', +})); + +const validateTenantSessionFreshMock = vi.fn(); +vi.mock('../utils/sessionAuth.js', () => ({ + validateTenantSessionFresh: (...args: unknown[]) => validateTenantSessionFreshMock(...args), })); const createLivekitTokenMock = vi.fn(); @@ -29,8 +38,24 @@ import { handleLivekitToken, handleReadyz } from './health.js'; import type { PrismaClient } from '../../generated/prisma/index.js'; import { MIN_ZONE_PRIVACY_CLIENT_VERSION } from '@meetropolis/shared'; -function fakeReq(body: Record): express.Request { - return { body, headers: {} } as unknown as express.Request; +/** Credential the request helpers present to the route. */ +const SESSION_TOKEN = 'session-token'; + +/** A live session of a member of the tenant the route resolves. */ +function allowedSession(userId: string, tenantId: string, sessionId = 'db-session-1') { + return { status: 'allowed', userId, sessionId, tenantId, access: 'member' }; +} + +/** Request that presents the credential as the `auth_token` cookie. */ +function fakeReq(body: Record, token: string | null = SESSION_TOKEN): express.Request { + const cookies: Record = {}; + if (token !== null) cookies.auth_token = token; + return { body, headers: {}, cookies } as unknown as express.Request; +} + +/** Request that presents the credential as a bearer token. */ +function fakeBearerReq(body: Record, token: string = SESSION_TOKEN): express.Request { + return { body, headers: { authorization: `Bearer ${token}` } } as unknown as express.Request; } function fakeRes(): express.Response { @@ -43,18 +68,19 @@ function fakeRes(): express.Response { } function fakePrisma(): PrismaClient { - return { $queryRaw: vi.fn().mockResolvedValue([{ ok: 1 }]) } as unknown as PrismaClient; + return { + $queryRaw: vi.fn().mockResolvedValue([{ ok: 1 }]), + membership: { findUnique: vi.fn().mockResolvedValue({ expiresAt: null }) }, + } as unknown as PrismaClient; } const ORIGINAL_ENV = { ...process.env }; beforeEach(() => { - requireAuthMock.mockReset(); getTenantFromReqMock.mockReset(); - requireMembershipMock.mockReset(); - // Default: caller IS a member of the resolved tenant. The membership-gate - // suite below overrides this per case. - requireMembershipMock.mockResolvedValue({ role: 'member' }); + validateTenantSessionFreshMock.mockReset(); + // Default: the caller presents a live session in the resolved tenant. + validateTenantSessionFreshMock.mockResolvedValue(allowedSession('user-real', 't1')); createLivekitTokenMock.mockReset(); process.env.LIVEKIT_API_KEY = 'devkey'; process.env.LIVEKIT_API_SECRET = 'secret'; @@ -66,23 +92,30 @@ afterEach(() => { describe('handleLivekitToken: identity hardening', () => { it('overrides a client-supplied identity with the authenticated user id', async () => { - requireAuthMock.mockReturnValue({ userId: 'user-real' }); + validateTenantSessionFreshMock.mockResolvedValue(allowedSession('user-real', 't1')); getTenantFromReqMock.mockReturnValue({ id: 't1', slug: 'acme' }); createLivekitTokenMock.mockResolvedValue('jwt-token'); + const prisma = fakePrisma(); const req = fakeReq({ roomName: 'world', identity: 'user-victim' }); const res = fakeRes(); - await handleLivekitToken(fakePrisma(), req, res); + await handleLivekitToken(prisma, req, res); + expect(validateTenantSessionFreshMock).toHaveBeenCalledWith(prisma, SESSION_TOKEN, 't1'); expect(createLivekitTokenMock).toHaveBeenCalledWith( expect.objectContaining({ identity: 'user-real', roomName: 'acme:world' }), ); expect(res.type).toHaveBeenCalledWith('text/plain'); expect(res.send).toHaveBeenCalledWith('jwt-token'); + // The minted token is bound to the session it was issued for. + const tokenArgs = createLivekitTokenMock.mock.calls[0][0] as { metadata: string }; + const metadata = JSON.parse(tokenArgs.metadata) as Record; + expect(Object.keys(metadata)).toContain('sessionRef'); + expect(typeof metadata.sessionRef).toBe('string'); }); it('rejects a roomName other than the single reconciled room', async () => { - requireAuthMock.mockReturnValue({ userId: 'user-real' }); + validateTenantSessionFreshMock.mockResolvedValue(allowedSession('user-real', 't1')); getTenantFromReqMock.mockReturnValue({ id: 't1', slug: 'acme' }); const req = fakeReq({ roomName: 'some-other-room', identity: 'user-real' }); @@ -94,19 +127,33 @@ describe('handleLivekitToken: identity hardening', () => { expect(createLivekitTokenMock).not.toHaveBeenCalled(); }); - it('rejects an unauthenticated request before touching LiveKit', async () => { - requireAuthMock.mockReturnValue(null); + it('rejects a request without a session credential before touching LiveKit', async () => { + getTenantFromReqMock.mockReturnValue({ id: 't1', slug: 'acme' }); + + const req = fakeReq({ roomName: 'world', identity: 'user-real' }, null); + const res = fakeRes(); + await handleLivekitToken(fakePrisma(), req, res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'unauthorized' }); + expect(validateTenantSessionFreshMock).not.toHaveBeenCalled(); + expect(createLivekitTokenMock).not.toHaveBeenCalled(); + }); + + it('rejects a request whose credential does not resolve to a login session', async () => { + getTenantFromReqMock.mockReturnValue({ id: 't1', slug: 'acme' }); + validateTenantSessionFreshMock.mockResolvedValue({ status: 'unauthenticated' }); const req = fakeReq({ roomName: 'world', identity: 'user-real' }); const res = fakeRes(); await handleLivekitToken(fakePrisma(), req, res); expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'unauthorized' }); expect(createLivekitTokenMock).not.toHaveBeenCalled(); }); it('rejects a request with no resolvable tenant', async () => { - requireAuthMock.mockReturnValue({ userId: 'user-real' }); getTenantFromReqMock.mockReturnValue(null); const req = fakeReq({ roomName: 'world', identity: 'user-real' }); @@ -117,11 +164,26 @@ describe('handleLivekitToken: identity hardening', () => { expect(res.json).toHaveBeenCalledWith({ error: 'tenant_required' }); expect(createLivekitTokenMock).not.toHaveBeenCalled(); }); + + it('refuses to mint a token for a reserved service identity', async () => { + getTenantFromReqMock.mockReturnValue({ id: 't1', slug: 'acme' }); + + for (const reservedId of ['npc-scout', 'svc-transcriber']) { + validateTenantSessionFreshMock.mockResolvedValue(allowedSession(reservedId, 't1')); + const req = fakeReq({ roomName: 'world', identity: reservedId }); + const res = fakeRes(); + await handleLivekitToken(fakePrisma(), req, res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ error: 'forbidden' }); + } + expect(createLivekitTokenMock).not.toHaveBeenCalled(); + }); }); -describe('handleLivekitToken: cross-tenant membership gate (A13)', () => { +describe('handleLivekitToken: tenant membership gate', () => { beforeEach(() => { - requireAuthMock.mockReturnValue({ userId: 'lobster-owner' }); + validateTenantSessionFreshMock.mockResolvedValue(allowedSession('lobster-owner', 't-default')); // X-Tenant precedence has already forced req.tenant to a FOREIGN tenant. getTenantFromReqMock.mockReturnValue({ id: 't-default', slug: 'default' }); createLivekitTokenMock.mockResolvedValue('jwt-token'); @@ -129,7 +191,7 @@ describe('handleLivekitToken: cross-tenant membership gate (A13)', () => { it('refuses to mint a token for a tenant the caller is not a member of (403, no token)', async () => { // The attacker holds a valid session but no membership in `default`. - requireMembershipMock.mockResolvedValue(null); + validateTenantSessionFreshMock.mockResolvedValue({ status: 'forbidden', reason: 'membership_unavailable' }); const req = fakeReq({ roomName: 'world', identity: 'lobster-owner' }); const res = fakeRes(); @@ -141,16 +203,16 @@ describe('handleLivekitToken: cross-tenant membership gate (A13)', () => { }); it('mints a token for the own tenant when a membership exists (200)', async () => { - requireMembershipMock.mockResolvedValue({ role: 'member' }); - - const req = fakeReq({ + const prisma = fakePrisma(); + const req = fakeBearerReq({ roomName: 'world', identity: 'lobster-owner', zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION, }); const res = fakeRes(); - await handleLivekitToken(fakePrisma(), req, res); + await handleLivekitToken(prisma, req, res); + expect(validateTenantSessionFreshMock).toHaveBeenCalledWith(prisma, SESSION_TOKEN, 't-default'); expect(createLivekitTokenMock).toHaveBeenCalledWith( expect.objectContaining({ identity: 'lobster-owner', roomName: 'default:world' }), ); @@ -160,7 +222,7 @@ describe('handleLivekitToken: cross-tenant membership gate (A13)', () => { describe('handleLivekitToken: H4 client zone-privacy version gate', () => { beforeEach(() => { - requireAuthMock.mockReturnValue({ userId: 'user-real' }); + validateTenantSessionFreshMock.mockResolvedValue(allowedSession('user-real', 't1')); getTenantFromReqMock.mockReturnValue({ id: 't1', slug: 'acme' }); createLivekitTokenMock.mockResolvedValue('jwt-token'); }); @@ -173,7 +235,7 @@ describe('handleLivekitToken: H4 client zone-privacy version gate', () => { expect(createLivekitTokenMock).toHaveBeenCalledWith(expect.objectContaining({ canPublish: false })); }); - it('mints canPublish:false when zonePrivacyVersion is below the minimum, but leaves canSubscribe untouched', async () => { + it('mints canPublish:false when zonePrivacyVersion is below the minimum, but keeps canSubscribe true', async () => { const req = fakeReq({ roomName: 'world', identity: 'user-real', diff --git a/apps/server/src/api/routes/health.ts b/apps/server/src/api/routes/health.ts index 5fcb1d39..3c7bcada 100644 --- a/apps/server/src/api/routes/health.ts +++ b/apps/server/src/api/routes/health.ts @@ -12,8 +12,11 @@ import { livekitOutboundBitrateBps, livekitPacketLossRatio, } from '../../metrics.js'; -import { requireAuth, getTenantFromReq, requireMembership } from '../utils/authHelpers.js'; +import { requireAuth, getTenantFromReq } from '../utils/authHelpers.js'; +import { validateTenantSessionFresh } from '../utils/sessionAuth.js'; +import { readAuthCookie, readBearerToken } from '../../types/authShapes.js'; import { evaluateTranscriptionGate } from '../../rooms/lifecycle/transcriptionGate.js'; +import { avSessionMetadata, isReservedAvIdentity } from '../../rooms/lifecycle/avSessionRef.js'; function handleHealth(_req: express.Request, res: express.Response): void { res.json({ ok: true }); @@ -166,11 +169,6 @@ export async function handleLivekitToken( req: express.Request, res: express.Response, ): Promise { - const auth = requireAuth(req); - if (!auth) { - res.status(401).json({ error: 'unauthorized' }); - return; - } const parse = livekitTokenSchema.safeParse(req.body || {}); if (!parse.success) { res.status(400).json({ error: 'roomName and identity required' }); @@ -181,14 +179,34 @@ export async function handleLivekitToken( res.status(400).json({ error: 'invalid_room_name' }); return; } - // Identity is ALWAYS the authenticated user id, never client input. - // The zone-membership model (WorldRoom Player.identity, audioZones/*) is - // keyed on this value; trusting a client-supplied identity would let a - // user mint a token that impersonates another participant and bypass - // every allow-list computed from Colyseus state. - const identity = auth.userId; + const corrId = (req.headers['x-correlation-id'] || '').toString(); + const tenant = getTenantFromReq(req); + if (!tenant) { + res.status(400).json({ error: 'tenant_required' }); + return; + } + // A LiveKit token belongs to a login session: the raw token from cookie or + // bearer header is checked against the database, so an API token fails. + const rawToken = readAuthCookie(req) ?? readBearerToken(req); + if (!rawToken) { + res.status(401).json({ error: 'unauthorized' }); + return; + } try { - const corrId = (req.headers['x-correlation-id'] || '').toString(); + const session = await validateTenantSessionFresh(prisma, rawToken, tenant.id); + if (session.status !== 'allowed') { + const forbidden = session.status === 'forbidden'; + const reason = forbidden ? session.reason : session.status; + logger.warn({ event: 'livekit.token.session_rejected', correlationId: corrId || undefined, reason }); + res.status(forbidden ? 403 : 401).json({ error: forbidden ? 'forbidden' : 'unauthorized' }); + return; + } + const identity = session.userId; + if (isReservedAvIdentity(identity)) { + logger.warn({ event: 'livekit.token.reserved_identity', correlationId: corrId || undefined }); + res.status(403).json({ error: 'forbidden' }); + return; + } if (clientSuppliedIdentity !== identity) { logger.warn({ event: 'livekit.token.identity_override', @@ -198,42 +216,26 @@ export async function handleLivekitToken( }); } try { - logger.info({ - event: 'livekit.token.request', - correlationId: corrId || undefined, - roomName, - identity, - ua: (req.headers['user-agent'] || '').toString(), - }); + logger.info({ event: 'livekit.token.request', correlationId: corrId || undefined, roomName, identity }); } catch {} if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) { res.status(500).json({ error: 'livekit not configured' }); return; } - const tenant = getTenantFromReq(req); - if (!tenant) { - res.status(400).json({ error: 'tenant_required' }); - return; - } - // Tenant resolution (tenancy.ts) lets the client X-Tenant header override - // the session JWT, so without this check any user could mint a token for a - // FOREIGN tenant's AV room (enumerate + publish). Gate on real membership: - // an AV join needs no elevated role, so any role (incl. guest) qualifies; a - // spoofed foreign tenant does not. Generic 403 keeps it non-enumerable. - const membership = await requireMembership(req, identity, prisma); - if (!membership) { - logger.warn({ event: 'livekit.token.forbidden', correlationId: corrId || undefined, identity }); - res.status(403).json({ error: 'forbidden' }); - return; - } + // The membership is read for its end date only; the access was decided above. + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: tenant.id, userId: identity } }, + select: { expiresAt: true }, + }); const gateDecision = await evaluateTranscriptionGate(prisma, tenant.id, identity); if (gateDecision === 'consent_required') return respondTranscriptionConsentRequired(res); if (gateDecision === 'unavailable') return respondTranscriptionGateUnavailable(res); const effectiveCanPublish = resolveEffectiveCanPublish(canPublish, zonePrivacyVersion, identity, corrId); - const roomNameWithTenant = `${tenant.slug}:${roomName}`; const token = await createLivekitToken({ - roomName: roomNameWithTenant, + roomName: `${tenant.slug}:${roomName}`, identity, + accessExpiresAt: membership?.expiresAt ?? null, + metadata: avSessionMetadata(session.sessionId), name, canPublish: effectiveCanPublish, canPublishData: true, diff --git a/apps/server/src/api/routes/invites.emailProof.integration.test.ts b/apps/server/src/api/routes/invites.emailProof.integration.test.ts new file mode 100644 index 00000000..0edd4891 --- /dev/null +++ b/apps/server/src/api/routes/invites.emailProof.integration.test.ts @@ -0,0 +1,103 @@ +import crypto from 'crypto'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerAuthRoutes } from './auth.js'; +import { registerInviteRoutes } from './invites.js'; + +const fixture = createHttpFixture(); +const originalBase = process.env.PUBLIC_BASE_URL; +const app = fixture.app(); +registerAuthRoutes(app, fixture.prisma); +registerInviteRoutes(app, fixture.prisma); +beforeAll(() => { + process.env.PUBLIC_BASE_URL = 'https://app.example.test'; +}); +afterAll(async () => { + if (originalBase === undefined) delete process.env.PUBLIC_BASE_URL; + else process.env.PUBLIC_BASE_URL = originalBase; + await fixture.close(); +}); + +async function invite(email: string) { + const { tenant } = await fixture.tenant(); + const value = await fixture.prisma.invite.create({ + data: { + tenantId: tenant.id, + email, + code: crypto.randomBytes(12).toString('hex'), + expiresAt: new Date(Date.now() + 3_600_000), + role: 'admin', + }, + }); + return { tenant, value }; +} + +describe('invitation acceptance requires separate email proof', () => { + it('grants no membership or invitation role before email proof for a new registration', async () => { + const email = `fixture-account-${crypto.randomUUID()}@example.test`; + fixture.userEmails.push(email); + const { tenant, value } = await invite(email); + const result = await request(app) + .post('/auth/register') + .set('X-Tenant', tenant.slug) + .send({ code: value.code, email, password: crypto.randomBytes(20).toString('hex') }); + const user = await fixture.prisma.user.findUnique({ where: { email } }); + const count = user ? await fixture.prisma.membership.count({ where: { userId: user.id, tenantId: tenant.id } }) : 0; + expect(count).toBe(0); + expect((await fixture.prisma.invite.findUniqueOrThrow({ where: { id: value.id } })).usedAt).toBeNull(); + expect(result.status).toBeGreaterThanOrEqual(400); + expect(user?.emailVerifiedAt ?? null).toBeNull(); + }); + + it('grants no new membership to an existing unverified account', async () => { + const own = await fixture.tenant(); + const caller = await fixture.caller(own.tenant); + const user = await fixture.prisma.user.update({ where: { id: caller.id }, data: { emailVerifiedAt: null } }); + const { tenant, value } = await invite(user.email); + const result = await request(app) + .post('/invites/accept') + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ code: value.code }); + expect(await fixture.prisma.membership.count({ where: { userId: user.id, tenantId: tenant.id } })).toBe(0); + expect((await fixture.prisma.invite.findUniqueOrThrow({ where: { id: value.id } })).usedAt).toBeNull(); + expect(result.status).toBeGreaterThanOrEqual(400); + }); + + for (const mode of ['production', 'development']) { + it(`returns neither a proof token nor a link after real delivery failure in ${mode}`, async () => { + const result = await promisify(execFile)( + process.execPath, + ['--import', 'tsx', 'test/fixtures/verifyDeliveryProbe.ts'], + { cwd: process.cwd(), env: { ...process.env, NODE_ENV: mode }, timeout: 45_000, maxBuffer: 256_000 }, + ); + const line = result.stdout.split('\n').find((value) => value.startsWith('VERIFICATION_DELIVERY_RESULT:')); + if (!line) throw new Error('The delivery probe process returned no result evidence.'); + const parsed: unknown = JSON.parse(line.slice('VERIFICATION_DELIVERY_RESULT:'.length)); + if (!parsed || typeof parsed !== 'object' || !('secret' in parsed)) throw new Error('Invalid result evidence.'); + expect(parsed.secret).toBe(false); + }, 50_000); + } + + it('explains an invalid legacy invitation link', async () => { + const result = await request(app).post('/public/invites/preview').send({ code: 'undefined' }); + expect(result.status).toBe(404); + expect(String(result.body.error)).toMatch(/invitation|update/i); + }); + + it('rejects a code in the DELETE path with 400 after the administrator gate and preserves the invitation', async () => { + const { tenant, value } = await invite(`fixture-account-${crypto.randomUUID()}@example.test`); + const admin = await fixture.caller(tenant, 'admin'); + const result = await request(app) + .delete(`/invites/${value.code}`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${admin.session}`); + expect(result.status).toBe(400); + expect(result.body.code).toBe('invite_id_invalid'); + expect(String(result.body.error)).toMatch(/update/i); + expect((await fixture.prisma.invite.findUniqueOrThrow({ where: { id: value.id } })).usedAt).toBeNull(); + }); +}); diff --git a/apps/server/src/api/routes/invites.integration.test.ts b/apps/server/src/api/routes/invites.integration.test.ts new file mode 100644 index 00000000..bcc6513d --- /dev/null +++ b/apps/server/src/api/routes/invites.integration.test.ts @@ -0,0 +1,807 @@ +import crypto from 'node:crypto'; +import express from 'express'; +import request from 'supertest'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createPrismaClient } from '../../db.js'; +import { setAuthResolution } from '../utils/authState.js'; +import { handleAuthInvite, handleAuthRegister } from './auth.signin.js'; +import { registerMiscRoutes } from './misc.js'; + +const capturedLogs = vi.hoisted(() => { + process.env.RATE_LIMIT_ENABLED = 'false'; + return { events: [] as Array<{ level: string; value: unknown }> }; +}); + +vi.mock('../../logger.js', () => ({ + logger: { + debug: (value: unknown) => capturedLogs.events.push({ level: 'debug', value }), + error: (value: unknown) => capturedLogs.events.push({ level: 'error', value }), + info: (value: unknown) => capturedLogs.events.push({ level: 'info', value }), + warn: (value: unknown) => capturedLogs.events.push({ level: 'warn', value }), + }, +})); + +vi.mock('../../tenancyLoader.js', () => ({ + getTenancyModule: () => Promise.resolve({ isMultiTenantEnabled: () => true }), +})); + +if (!process.env.DATABASE_URL) throw new Error('invites.integration.test.ts needs DATABASE_URL'); +if (!process.env.MAILPIT_URL || !process.env.MAILPIT_SMTP_HOST || !process.env.MAILPIT_SMTP_PORT) { + throw new Error('invites.integration.test.ts needs MAILPIT_URL, MAILPIT_SMTP_HOST, and MAILPIT_SMTP_PORT'); +} + +const prisma = createPrismaClient(); +const mailpitUrl = process.env.MAILPIT_URL.replace(/\/$/, ''); +const tenantIds: string[] = []; +const userIds: string[] = []; +const inviteFields = 'id,email,role,status,expiresAt,lastSentAt,lastSendError,createdAt,usedAt,url'.split(',').sort(); +const smtpEnvKeys = [ + 'SMTP_HOST', + 'SMTP_PORT', + 'SMTP_FROM', + 'SMTP_TLS_REJECT_UNAUTHORIZED', + 'PUBLIC_BASE_URL', + 'PUBLIC_BASE_URL_ALLOW_LOOPBACK', +] as const; +type SmtpEnvKey = (typeof smtpEnvKeys)[number]; +let originalSmtpEnv: Record; +let membershipTrigger: MembershipTrigger | null = null; + +interface Fixture { + app: express.Application; + tenantId: string; + ownerId: string; + adminId: string; + memberId: string; +} + +interface InviteResponse { + code: string; + role: string; + inviteUrl: string; + expiresAt: string; + emailSent: boolean; +} + +interface InviteLifecycleRow { + expiresAt: Date | null; + lastSentAt: Date | null; + sendCount: number; + lastSendError: string | null; +} + +interface MembershipTrigger { + functionName: string; + triggerName: string; + tableName: string; +} + +interface ListedInvite { + id: string; + status: string; + expiresAt: string | null; + lastSendError: string | null; + url: string | null; +} + +function makeApp(): express.Application { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + const userId = req.headers['x-user']; + setAuthResolution(req, { + auth: typeof userId === 'string' ? { userId, sessionId: `sess-${userId}`, tokenHash: `hash-${userId}` } : null, + }); + const tenantId = req.headers['x-tenant']; + if (typeof tenantId === 'string') req.tenant = { id: tenantId, slug: tenantId, name: tenantId } as never; + next(); + }); + app.post('/auth/invite', (req, res) => handleAuthInvite(prisma, req, res)); + app.post('/auth/register', (req, res) => handleAuthRegister(prisma, req, res)); + registerMiscRoutes(app, prisma); + return app; +} + +async function createFixture(): Promise { + const suffix = crypto.randomUUID(); + const tenant = await prisma.tenant.create({ data: { slug: `invites-${suffix}`, name: `Invites ${suffix}` } }); + tenantIds.push(tenant.id); + const owner = await prisma.user.create({ data: { email: `owner-${suffix}@example.test` } }); + const admin = await prisma.user.create({ data: { email: `admin-${suffix}@example.test` } }); + const member = await prisma.user.create({ data: { email: `member-${suffix}@example.test` } }); + userIds.push(owner.id, admin.id, member.id); + await prisma.membership.create({ data: { tenantId: tenant.id, userId: owner.id, role: 'owner' } }); + await prisma.membership.create({ data: { tenantId: tenant.id, userId: admin.id, role: 'admin' } }); + await prisma.membership.create({ data: { tenantId: tenant.id, userId: member.id, role: 'member' } }); + return { app: makeApp(), tenantId: tenant.id, ownerId: owner.id, adminId: admin.id, memberId: member.id }; +} + +function inviteRequest(fixture: Fixture, userId: string, email: string, role: string) { + return request(fixture.app) + .post('/auth/invite') + .set('x-user', userId) + .set('x-tenant', fixture.tenantId) + .send({ email, role }); +} + +function inviteAction(fixture: Fixture, userId: string, method: 'delete' | 'post', path: string) { + const action = method === 'delete' ? request(fixture.app).delete(path) : request(fixture.app).post(path); + return action.set('x-user', userId).set('x-tenant', fixture.tenantId); +} + +const listInvites = (fixture: Fixture, userId: string) => + request(fixture.app).get('/invites').set('x-user', userId).set('x-tenant', fixture.tenantId); + +async function inviteLifecycle(code: string): Promise { + const rows = await prisma.$queryRaw` + SELECT "expiresAt", "lastSentAt", "sendCount", "lastSendError" FROM "Invite" WHERE "code" = ${code} + `; + if (!rows[0]) throw new Error('Expected invite lifecycle row'); + return rows[0]; +} + +async function createInviteRecord( + fixture: Fixture, + email: string | null, + tenantId = fixture.tenantId, + role = 'member', +) { + return prisma.invite.create({ + data: { + code: crypto.randomUUID().replaceAll('-', ''), + email, + createdBy: fixture.ownerId, + tenantId, + role, + }, + }); +} + +async function createActiveInvite(fixture: Fixture, email: string, role = 'member') { + const invite = await createInviteRecord(fixture, email, fixture.tenantId, role); + await prisma.$executeRaw` + UPDATE "Invite" SET "expiresAt" = now() + interval '7 days' WHERE "id" = ${invite.id} + `; + return invite; +} + +async function createAccount(email: string, name: string) { + const user = await prisma.user.create({ data: { email, name } }); + userIds.push(user.id); + return user; +} + +function previewInvite(fixture: Fixture, code?: string) { + return request(fixture.app) + .post('/public/invites/preview') + .send(code === undefined ? {} : { code }); +} + +function acceptInvite(fixture: Fixture, code?: string, userId?: string) { + const action = request(fixture.app).post('/invites/accept'); + if (userId) action.set('x-user', userId); + return action.send(code === undefined ? {} : { code }); +} + +async function rejectInviteBindingInsert(inviteId: string): Promise { + const suffix = crypto.randomUUID().replaceAll('-', ''); + const functionName = `qacc_reject_binding_${suffix}`; + const triggerName = `qacc_reject_binding_insert_${suffix}`; + membershipTrigger = { functionName, triggerName, tableName: 'EmailVerification' }; + await prisma.$executeRawUnsafe(` +CREATE FUNCTION "${functionName}"() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN +IF NEW."inviteId" = '${inviteId}' THEN RAISE EXCEPTION 'test invite binding failure'; END IF; +RETURN NEW; +END; +$$ +`); + await prisma.$executeRawUnsafe(` +CREATE TRIGGER "${triggerName}" BEFORE INSERT ON "EmailVerification" +FOR EACH ROW EXECUTE FUNCTION "${functionName}"() +`); +} + +async function rejectMembershipInsertForTenant(tenantId: string): Promise { + const suffix = crypto.randomUUID().replaceAll('-', ''); + const functionName = `qacc_reject_membership_${suffix}`; + const triggerName = `qacc_reject_insert_${suffix}`; + membershipTrigger = { functionName, triggerName, tableName: 'Membership' }; + await prisma.$executeRawUnsafe(` + CREATE FUNCTION "${functionName}"() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW."tenantId" = '${tenantId}' THEN RAISE EXCEPTION 'test membership failure'; END IF; + RETURN NEW; + END; + $$ + `); + await prisma.$executeRawUnsafe(` + CREATE TRIGGER "${triggerName}" BEFORE INSERT ON "Membership" + FOR EACH ROW EXECUTE FUNCTION "${functionName}"() + `); +} + +async function createForeignInvite(fixture: Fixture, email: string) { + const tenant = await prisma.tenant.create({ data: { slug: `foreign-${crypto.randomUUID()}`, name: 'Foreign' } }); + tenantIds.push(tenant.id); + return createInviteRecord(fixture, email, tenant.id); +} + +async function inviteByCode(code: string) { + const invite = await prisma.invite.findUnique({ where: { code } }); + if (!invite) throw new Error('Expected invite row'); + return invite; +} + +function registerInvite(fixture: Fixture, code: string, email: string, name = 'Registered Invitee') { + return request(fixture.app) + .post('/auth/register') + .send({ code, email, name, password: 'qacc-registration-password' }); +} + +async function waitForEmailVerification(email: string): Promise { + await vi.waitFor( + async () => { + expect(await prisma.emailVerification.count({ where: { user: { email } } })).toBe(2); + }, + { timeout: 10_000 }, + ); +} + +async function waitForMail(to: string, minimumCount = 1): Promise<{ text: string; count: number }> { + const deadline = Date.now() + 10_000; + while (Date.now() < deadline) { + const query = new URLSearchParams({ query: `to:"${to}"` }); + const search = await fetch(`${mailpitUrl}/api/v1/search?${query.toString()}`); + if (!search.ok) throw new Error('Mailpit search request failed'); + const result = (await search.json()) as { total?: number; messages?: Array<{ ID: string }> }; + const count = result.total ?? result.messages?.length ?? 0; + const latest = result.messages?.[0]; + if (count >= minimumCount && latest) { + const detail = await fetch(`${mailpitUrl}/api/v1/message/${latest.ID}`); + if (!detail.ok) throw new Error('Mailpit message request failed'); + const message = (await detail.json()) as { Text: string }; + return { text: message.Text, count }; + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(`Mailpit did not receive ${minimumCount} invitation message(s)`); +} + +beforeAll(() => { + originalSmtpEnv = Object.fromEntries(smtpEnvKeys.map((key) => [key, process.env[key]])) as Record< + SmtpEnvKey, + string | undefined + >; + process.env.SMTP_HOST = process.env.MAILPIT_SMTP_HOST; + process.env.SMTP_PORT = process.env.MAILPIT_SMTP_PORT; + process.env.SMTP_FROM = 'invites@meetropolis.test'; + process.env.SMTP_TLS_REJECT_UNAUTHORIZED = 'false'; + process.env.PUBLIC_BASE_URL = 'http://localhost:42000'; + process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK = 'true'; +}); + +afterEach(async () => { + if (membershipTrigger) { + await prisma.$executeRawUnsafe( + `DROP TRIGGER IF EXISTS "${membershipTrigger.triggerName}" ON "${membershipTrigger.tableName}"`, + ); + await prisma.$executeRawUnsafe(`DROP FUNCTION IF EXISTS "${membershipTrigger.functionName}"()`); + membershipTrigger = null; + } + const currentTenantIds = tenantIds.splice(0); + const currentUserIds = userIds.splice(0); + if (currentTenantIds.length) await prisma.invite.deleteMany({ where: { tenantId: { in: currentTenantIds } } }); + if (currentTenantIds.length || currentUserIds.length) { + await prisma.membership.deleteMany({ + where: { + OR: [ + ...(currentTenantIds.length ? [{ tenantId: { in: currentTenantIds } }] : []), + ...(currentUserIds.length ? [{ userId: { in: currentUserIds } }] : []), + ], + }, + }); + } + if (currentUserIds.length) { + await prisma.emailVerification.deleteMany({ where: { userId: { in: currentUserIds } } }); + await prisma.session.deleteMany({ where: { userId: { in: currentUserIds } } }); + await prisma.user.deleteMany({ where: { id: { in: currentUserIds } } }); + } + if (currentTenantIds.length) await prisma.tenant.deleteMany({ where: { id: { in: currentTenantIds } } }); +}); + +afterAll(async () => { + await prisma.$disconnect(); + smtpEnvKeys.forEach((key) => + originalSmtpEnv[key] === undefined ? delete process.env[key] : (process.env[key] = originalSmtpEnv[key]), + ); +}); + +describe('Q-ACC-7 invite delivery feedback and open invite reuse', () => { + it('delivers, records success, reuses an open invite, and rejects an existing member', async () => { + const fixture = await createFixture(); + const email = `invite-${crypto.randomUUID()}@example.test`; + const startedAt = Date.now(); + const firstResponse = await inviteRequest(fixture, fixture.ownerId, email, 'admin'); + const first = firstResponse.body as InviteResponse; + expect(firstResponse.status).toBe(200); + expect(first.emailSent).toBe(true); + expect(first.inviteUrl).toBe(`http://localhost:42000/#/?invite=${first.code}`); + expect(new Date(first.expiresAt).getTime() - startedAt).toBeCloseTo(7 * 24 * 60 * 60 * 1000, -3); + const firstMail = await waitForMail(email); + expect(firstMail.text).toContain(first.inviteUrl); + const firstRow = await inviteLifecycle(first.code); + expect(firstRow.lastSentAt).toBeInstanceOf(Date); + expect(firstRow.sendCount).toBe(1); + expect(firstRow.lastSendError).toBeNull(); + + const secondResponse = await inviteRequest(fixture, fixture.ownerId, email, 'member'); + const second = secondResponse.body as InviteResponse; + const secondMail = await waitForMail(email, 2); + const secondRow = await inviteLifecycle(first.code); + expect(secondResponse.status).toBe(200); + expect(second.code).toBe(first.code); + expect(second.role).toBe('member'); + expect(secondMail.count).toBe(2); + expect(await prisma.invite.count({ where: { tenantId: fixture.tenantId, email } })).toBe(1); + expect(secondRow.sendCount).toBe(2); + expect(secondRow.expiresAt!.getTime()).toBeGreaterThan(firstRow.expiresAt!.getTime()); + + const existing = await prisma.user.create({ data: { email: `existing-${crypto.randomUUID()}@example.test` } }); + userIds.push(existing.id); + await prisma.membership.create({ data: { tenantId: fixture.tenantId, userId: existing.id, role: 'member' } }); + const before = await prisma.invite.count({ where: { tenantId: fixture.tenantId } }); + const rejected = await inviteRequest(fixture, fixture.ownerId, existing.email, 'member'); + expect(rejected.status).toBe(409); + expect(rejected.body).toEqual({ error: 'already_member' }); + expect(await prisma.invite.count({ where: { tenantId: fixture.tenantId } })).toBe(before); + }); +}); + +describe('Q-ACC-8 invite expiry, status, and resend', () => { + it('lists the exact projection and expires open invites with a NULL expiry', async () => { + const fixture = await createFixture(); + const pending = await createInviteRecord(fixture, `pending-${crypto.randomUUID()}@example.test`); + const expired = await createInviteRecord(fixture, `expired-${crypto.randomUUID()}@example.test`); + const accepted = await createInviteRecord(fixture, `accepted-${crypto.randomUUID()}@example.test`); + const nullExpiry = await createInviteRecord(fixture, `null-${crypto.randomUUID()}@example.test`); + await prisma.$executeRaw` + UPDATE "Invite" SET "expiresAt" = now() + interval '2 days', "lastSentAt" = now(), + "lastSendError" = 'not_delivered' WHERE "code" = ${pending.code} + `; + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = now() - interval '1 day' WHERE "code" = ${expired.code}`; + await prisma.$executeRaw`UPDATE "Invite" SET "usedAt" = now() WHERE "code" = ${accepted.code}`; + + const response = await listInvites(fixture, fixture.ownerId); + const invites = response.body as ListedInvite[]; + const listedPending = invites.find(({ id }) => id === pending.id); + const listedExpired = invites.find(({ id }) => id === expired.id); + const listedAccepted = invites.find(({ id }) => id === accepted.id); + const listedNullExpiry = invites.find(({ id }) => id === nullExpiry.id); + + expect(response.status).toBe(200); + expect(Object.keys(listedPending ?? {}).sort()).toEqual(inviteFields); + expect(listedPending).toMatchObject({ id: pending.id, status: 'pending', lastSendError: 'not_delivered' }); + expect(listedPending?.url).toContain(`?invite=${pending.code}`); + expect(listedExpired).toMatchObject({ id: expired.id, status: 'expired' }); + expect(listedAccepted).toMatchObject({ id: accepted.id, status: 'accepted' }); + expect(listedNullExpiry).toMatchObject({ id: nullExpiry.id, status: 'expired', expiresAt: null }); + }); + + it('resends a past-expiry invite by ID and updates its lifecycle', async () => { + const fixture = await createFixture(); + const email = `resend-${crypto.randomUUID()}@example.test`; + const firstResponse = await inviteRequest(fixture, fixture.ownerId, email, 'member'); + const first = firstResponse.body as InviteResponse; + expect(first.emailSent).toBe(true); + await waitForMail(email); + const invite = await inviteByCode(first.code); + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = now() - interval '1 day' WHERE "code" = ${first.code}`; + const before = await inviteLifecycle(first.code); + + const resentResponse = await inviteAction(fixture, fixture.ownerId, 'post', `/invites/${invite.id}/resend`); + const resent = resentResponse.body as InviteResponse; + await waitForMail(email, 2); + const after = await inviteLifecycle(first.code); + expect(resentResponse.status).toBe(200); + expect(Object.keys(resent).sort()).toEqual(['code', 'role', 'inviteUrl', 'expiresAt', 'emailSent'].sort()); + expect(resent.code).toBe(first.code); + expect(new Date(resent.expiresAt).getTime()).toBeGreaterThan(Date.now()); + expect(resent.emailSent).toBe(true); + expect(after.sendCount).toBe(before.sendCount + 1); + expect(after.lastSentAt).toBeInstanceOf(Date); + expect(after.lastSendError).toBeNull(); + + const listed = await listInvites(fixture, fixture.ownerId); + expect((listed.body as ListedInvite[]).find(({ id }) => id === invite.id)?.status).toBe('pending'); + }); + + it('resends an invite with NULL expiry and restores its pending status', async () => { + const fixture = await createFixture(); + const email = `null-expiry-${crypto.randomUUID()}@example.test`; + const first = (await inviteRequest(fixture, fixture.ownerId, email, 'member')).body as InviteResponse; + const invite = await inviteByCode(first.code); + await waitForMail(email); + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = NULL WHERE "id" = ${invite.id}`; + const before = await inviteLifecycle(first.code); + + const response = await inviteAction(fixture, fixture.ownerId, 'post', `/invites/${invite.id}/resend`); + const resent = response.body as InviteResponse; + await waitForMail(email, 2); + const after = await inviteLifecycle(first.code); + const listed = await listInvites(fixture, fixture.ownerId); + expect(response.status).toBe(200); + expect(resent.code).toBe(first.code); + expect(new Date(resent.expiresAt).getTime()).toBeGreaterThan(Date.now()); + expect(resent.emailSent).toBe(true); + expect(after.sendCount).toBe(before.sendCount + 1); + expect((listed.body as ListedInvite[]).find(({ id }) => id === invite.id)?.status).toBe('pending'); + }); + + it('rejects a code-shaped revocation ID with 400 and preserves its row and mail count', async () => { + const fixture = await createFixture(); + const email = `old-client-${crypto.randomUUID()}@example.test`; + const created = await inviteRequest(fixture, fixture.ownerId, email, 'member'); + const invite = await inviteByCode((created.body as InviteResponse).code); + await waitForMail(email); + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = NULL WHERE "id" = ${invite.id}`; + const before = await inviteLifecycle(invite.code); + const rowCount = await prisma.invite.count({ where: { tenantId: fixture.tenantId } }); + + const deleted = await inviteAction(fixture, fixture.ownerId, 'delete', `/invites/${invite.code}`); + const resent = await inviteAction(fixture, fixture.ownerId, 'post', `/invites/${invite.code}/resend`); + expect(deleted.status).toBe(400); + expect(deleted.body).toEqual({ + code: 'invite_id_invalid', + error: 'Update the application and use the current invitation list to revoke invitations.', + }); + expect(resent.status).toBe(404); + expect(resent.body).toEqual({ error: 'not found' }); + expect(await prisma.invite.findUnique({ where: { id: invite.id } })).not.toBeNull(); + expect(await prisma.invite.count({ where: { tenantId: fixture.tenantId } })).toBe(rowCount); + expect(await inviteLifecycle(invite.code)).toEqual(before); + expect((await waitForMail(email, 1)).count).toBe(1); + }); + + it('rejects used, unknown, foreign, and member resends', async () => { + const fixture = await createFixture(); + const used = await createInviteRecord(fixture, `used-${crypto.randomUUID()}@example.test`); + await prisma.$executeRaw`UPDATE "Invite" SET "usedAt" = now() WHERE "code" = ${used.code}`; + const usedResponse = await inviteAction(fixture, fixture.ownerId, 'post', `/invites/${used.id}/resend`); + expect(usedResponse.status).toBe(400); + expect(usedResponse.body).toEqual({ error: 'already used' }); + + const missingResponse = await inviteAction(fixture, fixture.ownerId, 'post', '/invites/unknown-id/resend'); + expect(missingResponse.status).toBe(404); + expect(missingResponse.body).toEqual({ error: 'not found' }); + + const foreignInvite = await createForeignInvite(fixture, `foreign-${crypto.randomUUID()}@example.test`); + const foreignResponse = await inviteAction(fixture, fixture.ownerId, 'post', `/invites/${foreignInvite.id}/resend`); + expect(foreignResponse.status).toBe(404); + expect(foreignResponse.body).toEqual({ error: 'not found' }); + + const memberResponse = await inviteAction(fixture, fixture.memberId, 'post', `/invites/${used.id}/resend`); + expect(memberResponse.status).toBe(403); + expect(memberResponse.body).toEqual({ error: 'forbidden' }); + }); + + it('deletes by ID and returns 404 for an invite in another tenant', async () => { + const fixture = await createFixture(); + const invite = await createInviteRecord(fixture, `delete-${crypto.randomUUID()}@example.test`); + const deleted = await inviteAction(fixture, fixture.ownerId, 'delete', `/invites/${invite.id}`); + expect(deleted.status).toBe(200); + expect(deleted.body).toEqual({ ok: true }); + expect(await prisma.invite.findUnique({ where: { id: invite.id } })).toBeNull(); + + const foreign = await createForeignInvite(fixture, `foreign-delete-${crypto.randomUUID()}@example.test`); + const foreignResponse = await inviteAction(fixture, fixture.ownerId, 'delete', `/invites/${foreign.id}`); + expect(foreignResponse.status).toBe(404); + expect(foreignResponse.body).toEqual({ error: 'not found' }); + expect(await prisma.invite.findUnique({ where: { id: foreign.id } })).not.toBeNull(); + }); +}); + +describe('Q-ACC-4 invite list and revoke require tenant admins', () => { + it('denies list and revoke to a plain member without changing the invite', async () => { + const fixture = await createFixture(); + const invite = await createInviteRecord(fixture, `member-access-${crypto.randomUUID()}@example.test`); + + const listed = await listInvites(fixture, fixture.memberId); + const deleted = await inviteAction(fixture, fixture.memberId, 'delete', `/invites/${invite.id}`); + + expect(listed.status).toBe(403); + expect(listed.body).toEqual({ error: 'forbidden' }); + expect(deleted.status).toBe(403); + expect(deleted.body).toEqual({ error: 'forbidden' }); + expect(await prisma.invite.findUnique({ where: { id: invite.id } })).not.toBeNull(); + }); + + it('allows admins and owners to list and revoke pending and expired invites', async () => { + const fixture = await createFixture(); + const pending = await createInviteRecord(fixture, `pending-${crypto.randomUUID()}@example.test`); + const expired = await createInviteRecord(fixture, `expired-${crypto.randomUUID()}@example.test`); + const accepted = await createInviteRecord(fixture, `accepted-${crypto.randomUUID()}@example.test`); + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = now() + interval '2 days' WHERE "id" = ${pending.id}`; + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = now() - interval '1 day' WHERE "id" = ${expired.id}`; + await prisma.$executeRaw`UPDATE "Invite" SET "usedAt" = now() WHERE "id" = ${accepted.id}`; + + expect((await listInvites(fixture, fixture.adminId)).status).toBe(200); + expect((await listInvites(fixture, fixture.ownerId)).status).toBe(200); + const deletedPending = await inviteAction(fixture, fixture.adminId, 'delete', `/invites/${pending.id}`); + const deletedExpired = await inviteAction(fixture, fixture.ownerId, 'delete', `/invites/${expired.id}`); + const deletedAccepted = await inviteAction(fixture, fixture.adminId, 'delete', `/invites/${accepted.id}`); + + expect(deletedPending.status).toBe(200); + expect(deletedExpired.status).toBe(200); + expect(deletedAccepted.status).toBe(400); + expect(deletedAccepted.body).toEqual({ error: 'already used' }); + }); +}); + +describe('Q-ACC-5 bound invites for existing accounts', () => { + it('previews a public invite with only the documented fields and validates the code', async () => { + const fixture = await createFixture(); + const invite = await createActiveInvite(fixture, `x-${crypto.randomUUID()}@example.test`); + + const preview = await previewInvite(fixture, invite.code); + expect(preview.status).toBe(200); + expect(Object.keys(preview.body).sort()).toEqual(['tenantName', 'role', 'status', 'emailMasked'].sort()); + expect(preview.body).toEqual({ + tenantName: expect.any(String), + role: 'member', + status: 'pending', + emailMasked: 'x***@example.test', + }); + expect((await previewInvite(fixture, 'unknown-code')).status).toBe(404); + expect((await previewInvite(fixture)).status).toBe(400); + expect((await previewInvite(fixture, 'abc')).status).toBe(400); + }); + + it('checks authentication, schema, existence, status, and bound email in order', async () => { + const fixture = await createFixture(); + const boundEmail = `bound-${crypto.randomUUID()}@example.test`; + const mismatch = await createAccount(`other-${crypto.randomUUID()}@example.test`, 'Other Account'); + const invite = await createActiveInvite(fixture, boundEmail); + const expired = await createActiveInvite(fixture, `expired-${crypto.randomUUID()}@example.test`); + const used = await createActiveInvite(fixture, `used-${crypto.randomUUID()}@example.test`); + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = now() - interval '1 day' WHERE "id" = ${expired.id}`; + await prisma.invite.update({ where: { id: used.id }, data: { usedAt: new Date() } }); + + expect((await acceptInvite(fixture, undefined)).status).toBe(401); + expect((await acceptInvite(fixture, undefined, fixture.ownerId)).status).toBe(400); + expect((await acceptInvite(fixture, 'unknown-code', fixture.ownerId)).status).toBe(404); + const mismatched = await acceptInvite(fixture, invite.code, mismatch.id); + expect(mismatched.status).toBe(403); + expect(mismatched.body).toEqual({ error: 'invite_email_mismatch' }); + expect((await acceptInvite(fixture, expired.code, fixture.ownerId)).status).toBe(409); + expect((await acceptInvite(fixture, used.code, fixture.ownerId)).status).toBe(409); + expect( + await prisma.invite.findUnique({ where: { id: invite.id }, select: { usedAt: true, usedById: true } }), + ).toEqual({ + usedAt: null, + usedById: null, + }); + expect(await prisma.membership.count({ where: { tenantId: fixture.tenantId, userId: mismatch.id } })).toBe(0); + }); + + it('accepts a matching account, creates its membership, consumes the invite, and sets a session cookie', async () => { + const fixture = await createFixture(); + const email = `accept-${crypto.randomUUID()}@example.test`; + const account = await createAccount(email, 'Invitee Name'); + const invite = await createActiveInvite(fixture, email, 'admin'); + await prisma.user.update({ where: { id: account.id }, data: { emailVerifiedAt: new Date() } }); + + const response = await acceptInvite(fixture, invite.code, account.id); + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: fixture.tenantId, userId: account.id } }, + }); + const used = await prisma.invite.findUnique({ where: { id: invite.id }, select: { usedAt: true, usedById: true } }); + + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ id: account.id, email, name: 'Invitee Name', alreadyMember: false }); + expect(membership).toMatchObject({ role: 'admin' }); + expect(used).toMatchObject({ usedAt: expect.any(Date), usedById: account.id }); + expect(response.headers['set-cookie']).toEqual(expect.arrayContaining([expect.stringContaining('auth_token=')])); + }); + + it('consumes an invite for an existing member without changing that member role', async () => { + const fixture = await createFixture(); + const owner = await prisma.user.findUniqueOrThrow({ where: { id: fixture.ownerId } }); + const invite = await createActiveInvite(fixture, owner.email, 'member'); + await prisma.user.update({ where: { id: owner.id }, data: { emailVerifiedAt: new Date() } }); + + const response = await acceptInvite(fixture, invite.code, owner.id); + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: fixture.tenantId, userId: owner.id } }, + }); + + expect(response.status).toBe(200); + expect(response.body.alreadyMember).toBe(true); + expect(membership?.role).toBe('owner'); + expect(await prisma.invite.findUnique({ where: { id: invite.id }, select: { usedById: true } })).toEqual({ + usedById: owner.id, + }); + }); + + it('allows only one of five parallel requests to consume an invite', async () => { + const fixture = await createFixture(); + const account = await createAccount(`parallel-${crypto.randomUUID()}@example.test`, 'Parallel Invitee'); + const invite = await createActiveInvite(fixture, account.email); + await prisma.user.update({ where: { id: account.id }, data: { emailVerifiedAt: new Date() } }); + + const responses = await Promise.all( + Array.from({ length: 5 }, () => acceptInvite(fixture, invite.code, account.id)), + ); + + expect(responses.filter(({ status }) => status === 200)).toHaveLength(1); + expect(responses.filter(({ status }) => status === 409)).toHaveLength(4); + }); + + it('rolls back invite consumption when membership creation fails', async () => { + const fixture = await createFixture(); + const account = await createAccount(`rollback-${crypto.randomUUID()}@example.test`, 'Rollback Invitee'); + const invite = await createActiveInvite(fixture, account.email); + await rejectMembershipInsertForTenant(fixture.tenantId); + await prisma.user.update({ where: { id: account.id }, data: { emailVerifiedAt: new Date() } }); + + const response = await acceptInvite(fixture, invite.code, account.id); + const row = await prisma.invite.findUnique({ where: { id: invite.id }, select: { usedAt: true, usedById: true } }); + + expect(response.status).toBe(500); + expect(response.body).toEqual({ error: 'accept_failed' }); + expect(row).toEqual({ usedAt: null, usedById: null }); + expect(await prisma.membership.count({ where: { tenantId: fixture.tenantId, userId: account.id } })).toBe(0); + }); +}); + +describe('Q-ACC-6 atomic registration with an invite code', () => { + it('returns invite_unavailable for unknown and already-used invitations', async () => { + const fixture = await createFixture(); + const email = `unavailable-${crypto.randomUUID()}@example.test`; + const used = await createActiveInvite(fixture, email); + await prisma.invite.update({ where: { id: used.id }, data: { usedAt: new Date() } }); + + const unknown = await registerInvite(fixture, 'unknown-code', email); + const accepted = await registerInvite(fixture, used.code, email); + + expect(unknown.status).toBe(400); + expect(unknown.body).toEqual({ error: 'invite_unavailable' }); + expect(accepted.status).toBe(400); + expect(accepted.body).toEqual({ error: 'invite_unavailable' }); + }); + + it('rejects an expired invitation without creating a user', async () => { + const fixture = await createFixture(); + const email = `expired-register-${crypto.randomUUID()}@example.test`; + const invite = await createActiveInvite(fixture, email); + await prisma.$executeRaw`UPDATE "Invite" SET "expiresAt" = now() - interval '1 day' WHERE "id" = ${invite.id}`; + + const response = await registerInvite(fixture, invite.code, email); + + expect(response.status).toBe(400); + expect(response.body).toEqual({ error: 'invite_expired' }); + expect(await prisma.user.findUnique({ where: { email } })).toBeNull(); + }); + + it('rejects mismatched and unbound invitation emails without creating users', async () => { + const fixture = await createFixture(); + const inviteEmail = `bound-register-${crypto.randomUUID()}@example.test`; + const mismatchEmail = `wrong-register-${crypto.randomUUID()}@example.test`; + const mismatchedInvite = await createActiveInvite(fixture, inviteEmail); + const unboundInvite = await createInviteRecord(fixture, null); + await prisma.$executeRaw` + UPDATE "Invite" SET "expiresAt" = now() + interval '7 days' WHERE "id" = ${unboundInvite.id} + `; + + const mismatched = await registerInvite(fixture, mismatchedInvite.code, mismatchEmail); + const unboundEmail = `unbound-register-${crypto.randomUUID()}@example.test`; + const unbound = await registerInvite(fixture, unboundInvite.code, unboundEmail); + + expect(mismatched.status).toBe(403); + expect(mismatched.body).toEqual({ error: 'invite_email_mismatch' }); + expect(unbound.status).toBe(403); + expect(unbound.body).toEqual({ error: 'invite_email_mismatch' }); + expect(await prisma.user.findUnique({ where: { email: mismatchEmail } })).toBeNull(); + expect(await prisma.user.findUnique({ where: { email: unboundEmail } })).toBeNull(); + }); + + it('creates the user and invite binding without a membership before email proof', async () => { + const fixture = await createFixture(); + const email = `registered-${crypto.randomUUID()}@example.test`; + const invite = await createActiveInvite(fixture, email, 'admin'); + + const response = await registerInvite(fixture, invite.code, email); + const user = await prisma.user.findUniqueOrThrow({ where: { email } }); + userIds.push(user.id); + await waitForEmailVerification(email); + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: fixture.tenantId, userId: user.id } }, + }); + const redeemed = await prisma.invite.findUnique({ + where: { id: invite.id }, + select: { usedAt: true, usedById: true }, + }); + await waitForMail(email); + + expect(response.status).toBe(409); + expect(response.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + expect(response.body.delivery).toBe('sent'); + expect(response.body).not.toHaveProperty('token'); + expect(user.emailVerifiedAt).toBeNull(); + expect(membership).toBeNull(); + expect(redeemed).toEqual({ usedAt: null, usedById: null }); + }); + + it('rolls back the new user and the invite binding when the binding insert fails', async () => { + const fixture = await createFixture(); + const email = `registration-rollback-${crypto.randomUUID()}@example.test`; + const invite = await createActiveInvite(fixture, email); + await rejectInviteBindingInsert(invite.id); + + const response = await registerInvite(fixture, invite.code, email); + const redeemed = await prisma.invite.findUnique({ + where: { id: invite.id }, + select: { usedAt: true, usedById: true }, + }); + + expect(response.status).toBe(500); + expect(response.body).toEqual({ error: 'registration failed' }); + expect(await prisma.user.findUnique({ where: { email } })).toBeNull(); + expect(redeemed).toEqual({ usedAt: null, usedById: null }); + }); + + it('creates exactly one account for five parallel registrations with one code and address', async () => { + const fixture = await createFixture(); + const email = `parallel-register-${crypto.randomUUID()}@example.test`; + const invite = await createActiveInvite(fixture, email); + + const responses = await Promise.all(Array.from({ length: 5 }, () => registerInvite(fixture, invite.code, email))); + const registeredUser = await prisma.user.findUnique({ where: { email } }); + if (registeredUser) userIds.push(registeredUser.id); + expect(responses.filter(({ status }) => status === 409)).toHaveLength(5); + await waitForEmailVerification(email); + await waitForMail(email); + + expect(registeredUser).not.toBeNull(); + expect(responses.filter((res) => res.body.code === 'EMAIL_VERIFICATION_REQUIRED')).toHaveLength(1); + expect(responses.filter((res) => res.body.code === 'ACCOUNT_LOGIN_REQUIRED')).toHaveLength(4); + }); +}); + +describe('POST /auth/register display names', () => { + it('creates the user with the trimmed name', async () => { + const fixture = await createFixture(); + const email = `display-name-${crypto.randomUUID()}@example.test`; + const invite = await createActiveInvite(fixture, email); + + const response = await registerInvite(fixture, invite.code, email, ' Jörg Müller '); + const user = await prisma.user.findUniqueOrThrow({ where: { email } }); + userIds.push(user.id); + await waitForMail(email); + + expect(response.status).toBe(409); + expect(response.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + expect(response.body.delivery).toBe('sent'); + expect(response.body).not.toHaveProperty('token'); + expect(user.name).toBe('Jörg Müller'); + }); + + it('still accepts a registration without a name', async () => { + const fixture = await createFixture(); + const email = `display-name-missing-${crypto.randomUUID()}@example.test`; + const invite = await createActiveInvite(fixture, email); + + const response = await request(fixture.app) + .post('/auth/register') + .send({ code: invite.code, email, password: 'qacc-registration-password' }); + const user = await prisma.user.findUniqueOrThrow({ where: { email } }); + userIds.push(user.id); + await waitForMail(email); + + expect(response.status).toBe(409); + expect(response.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + expect(response.body.delivery).toBe('sent'); + expect(response.body).not.toHaveProperty('token'); + expect(user.name).toBeNull(); + }); +}); diff --git a/apps/server/src/api/routes/invites.ts b/apps/server/src/api/routes/invites.ts new file mode 100644 index 00000000..d62b5289 --- /dev/null +++ b/apps/server/src/api/routes/invites.ts @@ -0,0 +1,244 @@ +import type express from 'express'; +import { PrismaClient } from '../../generated/prisma/index.js'; +import type { Role } from '../../generated/prisma/index.js'; +import { logger } from '../../logger.js'; +import { z } from 'zod'; +import { requireAuth, requireVerificationAuth, getTenantFromReq, requireMembership } from '../utils/authHelpers.js'; +import { buildPublicWebLink, publicWebBase, requirePublicWebBase } from '../utils/publicLinks.js'; +import { pathParam } from '../utils/requestHelpers.js'; +import { + inviteAcceptRateLimiter, + invitePreviewRateLimiter, + inviteResendRateLimiter, +} from '../middleware/inviteRateLimit.js'; +import { + consumeInvite, + deriveInviteStatus, + deliverInvite, + inviteEmailMatches, + inviteExpiry, + inviteResponse, + InviteUnavailableError, + maskInviteEmail, +} from '../utils/inviteLifecycle.js'; +import { deliveringEmailModule, lockEmailAccount } from '../utils/emailProof.js'; +import { beginInviteVerification, verificationPending } from '../utils/inviteVerification.js'; +import { establishSession } from '../utils/sessionAuth.js'; +import { buildSigninResponseBody, isNativeClientRequest } from './auth.helpers.js'; + +const inviteCodeSchema = z.object({ code: z.string().min(4) }); + +async function handleListInvites(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const admin = await requireTenantAdmin(prisma, req, res); + if (!admin) return; + const { tenant } = admin; + const list = await prisma.invite.findMany({ where: { tenantId: tenant.id }, orderBy: { createdAt: 'desc' } }); + const baseUrl = publicWebBase(); + res.json( + list.map((invite) => ({ + id: invite.id, + email: invite.email, + role: invite.role, + status: deriveInviteStatus(invite), + expiresAt: invite.expiresAt, + lastSentAt: invite.lastSentAt, + lastSendError: invite.lastSendError, + createdAt: invite.createdAt, + usedAt: invite.usedAt, + url: baseUrl ? buildPublicWebLink(baseUrl, `?invite=${invite.code}`) : null, + })), + ); +} + +async function handleDeleteInvite(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const admin = await requireTenantAdmin(prisma, req, res); + if (!admin) return; + const { tenant } = admin; + const id = pathParam(req, 'id'); + if (!/^c[0-9a-z]{24}$/.test(id)) { + res.status(400).json({ code: 'invite_id_invalid', error: 'Update the application and use the current invitation list to revoke invitations.' }); + return; + } + try { + const invite = await prisma.invite.findUnique({ where: { id } }); + if (!invite || invite.tenantId !== tenant.id) { + res.status(404).json({ error: 'not found' }); + return; + } + if (invite.usedAt) { + res.status(400).json({ error: 'already used' }); + return; + } + await prisma.invite.delete({ where: { id } }); + res.json({ ok: true }); + } catch { + res.status(400).json({ error: 'delete failed' }); + } +} + +async function requireTenantAdmin(prisma: PrismaClient, req: express.Request, res: express.Response) { + const auth = requireAuth(req); + if (!auth) { + res.status(401).json({ error: 'unauthorized' }); + return null; + } + const tenant = getTenantFromReq(req); + if (!tenant) { + res.status(400).json({ error: 'tenant_required' }); + return null; + } + const membership = await requireMembership(req, auth.userId, prisma); + if (!membership || (membership.role !== 'admin' && membership.role !== 'owner')) { + res.status(403).json({ error: 'forbidden' }); + return null; + } + return { auth, tenant }; +} + +async function handleResendInvite(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const admin = await requireTenantAdmin(prisma, req, res); + if (!admin) return; + const id = pathParam(req, 'id'); + const invite = await prisma.invite.findUnique({ where: { id } }); + if (!invite || invite.tenantId !== admin.tenant.id) { + res.status(404).json({ error: 'not found' }); + return; + } + if (invite.usedAt) { + res.status(400).json({ error: 'already used' }); + return; + } + const baseUrl = requirePublicWebBase(res, 'invites.resend'); + if (!baseUrl) return; + const updated = await prisma.invite.update({ where: { id }, data: { expiresAt: inviteExpiry() } }); + const inviteUrl = buildPublicWebLink(baseUrl, `?invite=${updated.code}`); + const emailSent = await deliverInvite(prisma, { + invite: { id: updated.id, email: updated.email, tenantId: updated.tenantId }, + inviterUserId: admin.auth.userId, + tenantName: admin.tenant.name, + inviteUrl, + }); + res.json(inviteResponse(updated, inviteUrl, emailSent)); +} + +async function handlePublicInvitePreview( + prisma: PrismaClient, + req: express.Request, + res: express.Response, +): Promise { + const parse = inviteCodeSchema.safeParse(req.body || {}); + if (!parse.success) { + res.status(400).json({ error: 'code required' }); + return; + } + const invite = await prisma.invite.findUnique({ + where: { code: parse.data.code }, + include: { tenant: { select: { name: true } } }, + }); + if (!invite) { + res.status(404).json({ code: 'invite_invalid', error: 'This invitation link is invalid. Request a new invitation or update the application.' }); + return; + } + res.json({ + tenantName: invite.tenant.name, + role: invite.role, + status: deriveInviteStatus(invite), + emailMasked: maskInviteEmail(invite.email), + }); +} + +async function acceptInviteTransaction( + prisma: PrismaClient, + invite: { id: string; tenantId: string; role: Role }, + code: string, + userId: string, + now: Date, +): Promise { + return prisma.$transaction(async (tx) => { + await lockEmailAccount(tx, userId); + await tx.$queryRaw`SELECT "id" FROM "Invite" WHERE "id" = ${invite.id} FOR UPDATE`; + const account = await tx.user.findUnique({ where: { id: userId } }); + const current = await tx.invite.findUnique({ where: { id: invite.id } }); + if (!account?.emailVerifiedAt || !current || !inviteEmailMatches(current.email, account.email)) throw new InviteUnavailableError(); + if (!(await consumeInvite(tx, code, userId, now))) throw new InviteUnavailableError(); + const membership = await tx.membership.findUnique({ + where: { tenantId_userId: { tenantId: invite.tenantId, userId } }, + }); + if (membership?.inviteVerificationRequired) { + await tx.membership.update({ where: { id: membership.id }, data: { role: invite.role, inviteVerificationRequired: false } }); + return false; + } + if (membership) return true; + await tx.membership.create({ data: { tenantId: invite.tenantId, userId, role: invite.role } }); + return false; + }); +} + +async function handleAcceptInvite(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { + const auth = requireVerificationAuth(req); + if (!auth) { + res.status(401).json({ error: 'unauthorized' }); + return; + } + const parse = inviteCodeSchema.safeParse(req.body || {}); + if (!parse.success) { + res.status(400).json({ error: 'code required' }); + return; + } + const { code } = parse.data; + try { + const invite = await prisma.invite.findUnique({ where: { code } }); + if (!invite) { + res.status(404).json({ error: 'not found' }); + return; + } + if (deriveInviteStatus(invite) !== 'pending') { + res.status(409).json({ error: 'invite_unavailable' }); + return; + } + const user = await prisma.user.findUnique({ where: { id: auth.userId } }); + if (!user) throw new Error('Authenticated invite account not found'); + if (!inviteEmailMatches(invite.email, user.email)) { + res.status(403).json({ error: 'invite_email_mismatch' }); + return; + } + if (!user.emailVerifiedAt) { + if (!(await deliveringEmailModule())) { + res.status(503).json({ code: 'EMAIL_DELIVERY_UNAVAILABLE', error: 'This invitation requires confirmation email delivery. Please contact an administrator.' }); + return; + } + const outcome = await beginInviteVerification(prisma, user.id, invite.id); + await establishSession({ prisma, req, res, userId: user.id, tenantId: invite.tenantId, verificationOnly: true }); + verificationPending(res, outcome); + return; + } + const alreadyMember = await acceptInviteTransaction(prisma, invite, code, user.id, new Date()); + if (auth.verificationOnly) { + res.status(409).json({ code: 'ACCOUNT_LOGIN_REQUIRED', error: 'Please sign in to complete the invitation.' }); + return; + } + const session = await establishSession({ prisma, req, res, userId: user.id, tenantId: invite.tenantId }); + res.json({ ...buildSigninResponseBody(user, session.token, isNativeClientRequest(req)), alreadyMember }); + } catch (error: unknown) { + if (error instanceof InviteUnavailableError) { + res.status(409).json({ error: 'invite_unavailable' }); + return; + } + logger.error({ + event: 'invites.accept_failed', + userId: auth.userId, + errorName: error instanceof Error ? error.name : typeof error, + }); + res.status(500).json({ error: 'accept_failed' }); + } +} + +export function registerInviteRoutes(app: express.Application, prisma: PrismaClient): void { + app.post('/invites/accept', inviteAcceptRateLimiter, (req, res) => handleAcceptInvite(prisma, req, res)); + app.post('/public/invites/preview', invitePreviewRateLimiter, (req, res) => + handlePublicInvitePreview(prisma, req, res), + ); + app.get('/invites', (req, res) => handleListInvites(prisma, req, res)); + app.delete('/invites/:id', (req, res) => handleDeleteInvite(prisma, req, res)); + app.post('/invites/:id/resend', inviteResendRateLimiter, (req, res) => handleResendInvite(prisma, req, res)); +} diff --git a/apps/server/src/api/routes/maps.editor.ts b/apps/server/src/api/routes/maps.editor.ts index a32997c1..9baa7aa0 100644 --- a/apps/server/src/api/routes/maps.editor.ts +++ b/apps/server/src/api/routes/maps.editor.ts @@ -4,6 +4,7 @@ import { z } from 'zod'; import { logger } from '../../logger.js'; import { requireAuth, getTenantFromReq, requireApiToken, requireMembership } from '../utils/authHelpers.js'; import { pathParam } from '../utils/requestHelpers.js'; +import { isTenantAccessDenied } from '../utils/tenantAccessState.js'; import { broadcastMapUpdate } from '../utils/broadcast.js'; import { findMapById } from './maps.read.js'; import { acquireMapAdvisoryLock } from '../utils/advisoryLocks.js'; @@ -67,6 +68,10 @@ export async function resolveEditorMemberTenant( return null; } const tenant = getTenantFromReq(req); + if (!tenant && isTenantAccessDenied(req)) { + res.status(403).json({ error: 'forbidden' }); + return null; + } if (!tenant) { res.status(400).json({ error: 'tenant_required' }); return null; diff --git a/apps/server/src/api/routes/maps.editor.zones.ts b/apps/server/src/api/routes/maps.editor.zones.ts index 896cd700..a649682b 100644 --- a/apps/server/src/api/routes/maps.editor.zones.ts +++ b/apps/server/src/api/routes/maps.editor.zones.ts @@ -1,12 +1,13 @@ import type express from 'express'; import { PrismaClient } from '../../generated/prisma/index.js'; -import { z } from 'zod'; import { logger } from '../../logger.js'; import { getTenantFromReq, requireMembership } from '../utils/authHelpers.js'; import { pathParam } from '../utils/requestHelpers.js'; import { broadcastMapUpdate, broadcastSpawnUpdate } from '../utils/broadcast.js'; +import { countRejectedPayload } from '../../rooms/validation/rejectionMetrics.js'; import { findMapById } from './maps.read.js'; import { authenticateEditor, resolveEditorMemberTenant, type MapMeta } from './maps.editor.js'; +import { editorStateSchema } from './editorStateSchema.js'; import type { MapDb } from '../utils/mapChunkMutations.js'; import { acquireMapAdvisoryLock } from '../utils/advisoryLocks.js'; @@ -71,17 +72,6 @@ export async function handleEditorStateGet( }); } -const editorStateSchema = z.object({ - tilesets: z.array(z.any()).optional(), - zones: z.array(z.any()).optional(), - backgroundColor: z - .string() - .regex(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/) - .optional(), - replaceZones: z.boolean().optional(), - spawn: z.object({ x: z.number(), y: z.number() }).optional(), -}); - async function ensureLobbyRoom(prisma: MapDb, mapId: string, tenantId: string) { const roomForZones = await prisma.room.findFirst({ where: { mapId }, orderBy: { createdAt: 'asc' } }); if (roomForZones) return roomForZones; @@ -156,6 +146,7 @@ export async function handleEditorStatePut( if (!tenant) return; const parse = editorStateSchema.safeParse(req.body || {}); if (!parse.success) { + countRejectedPayload('editor_state', 'schema'); res.status(400).json({ error: 'invalid editor payload' }); return; } diff --git a/apps/server/src/api/routes/misc.ts b/apps/server/src/api/routes/misc.ts index d92abf63..fd53bfb6 100644 --- a/apps/server/src/api/routes/misc.ts +++ b/apps/server/src/api/routes/misc.ts @@ -4,23 +4,10 @@ import { z } from 'zod'; import { logger } from '../../logger.js'; import { requireAuth, getTenantFromReq, requireMembership } from '../utils/authHelpers.js'; import { pathParam } from '../utils/requestHelpers.js'; -import { displayNameSchema, invalidNameBody, invalidNameBodyFor } from '../utils/displayName.js'; -import { customAvatarPacksDir, deleteCustomAvatarFiles } from '../../services/avatarComposer.js'; - -/** - * Remove a user's composed avatar sprite/preview files before the user row (and - * its CustomAvatar row via cascade) is deleted. A DB cascade never touches the - * filesystem, so without this the ~2 PNGs per custom avatar would be orphaned. - * Best-effort — a failure here must not block account deletion. - */ -async function purgeCustomAvatarFiles(prisma: PrismaClient, userId: string): Promise { - try { - const ca = await prisma.customAvatar.findUnique({ where: { userId }, select: { uuid: true } }); - if (ca) await deleteCustomAvatarFiles(customAvatarPacksDir(), ca.uuid); - } catch (err) { - logger.warn({ event: 'user.delete.avatar_cleanup_failed', userId, error: String(err) }); - } -} +import { displayNameSchema, invalidNameBodyFor } from '../utils/displayName.js'; +import { deleteAccount, MembershipNotFoundError, removeMemberFromTenant } from '../../services/accountDeletion.js'; +import { updateOwnProfile } from './accountProfile.js'; +import { registerInviteRoutes } from './invites.js'; type MembershipRow = Prisma.MembershipGetPayload>; type UserListRow = Prisma.UserGetPayload<{ @@ -40,35 +27,7 @@ async function handleUpdateMe(prisma: PrismaClient, req: express.Request, res: e res.status(401).json({ error: 'unauthorized' }); return; } - const { name: rawName, email } = (req.body ?? {}) as { name?: unknown; email?: string }; - // Only the name is validated: `email` and everything else behave as before. - // A null name counts as absent, as it always did. - let name: string | undefined; - if (rawName !== undefined && rawName !== null) { - const parsedName = displayNameSchema.safeParse(rawName); - if (!parsedName.success) { - res.status(400).json(invalidNameBody(parsedName.error.issues)); - return; - } - name = parsedName.data; - } - if (!name && !email) { - res.status(400).json({ error: 'nothing to update' }); - return; - } - try { - const u = await prisma.user.update({ - where: { id: auth.userId }, - data: { name: name ?? undefined, email: email ?? undefined }, - }); - res.json({ id: u.id, email: u.email, name: u.name }); - } catch (e: unknown) { - if (e && typeof e === 'object' && 'code' in e && e.code === 'P2002') { - res.status(400).json({ error: 'email already in use' }); - return; - } - res.status(400).json({ error: 'update failed' }); - } + await updateOwnProfile(prisma, auth.userId, req.body, res); } function loadExportUser(prisma: PrismaClient, userId: string) { @@ -209,29 +168,6 @@ async function checkSoleOwnership( return false; } -async function purgeUserAndRelated(prisma: PrismaClient, userId: string): Promise { - try { - await prisma.presence.deleteMany({ where: { userId } }); - } catch {} - try { - await prisma.passwordReset.deleteMany({ where: { userId } }); - } catch {} - try { - await prisma.apiToken.deleteMany({ where: { userId } }); - } catch {} - try { - await prisma.invite.updateMany({ where: { usedById: userId }, data: { usedById: null } }); - } catch {} - try { - await prisma.invite.updateMany({ where: { createdBy: userId }, data: { createdBy: null } }); - } catch {} - try { - await prisma.membership.deleteMany({ where: { userId } }); - } catch {} - await purgeCustomAvatarFiles(prisma, userId); - await prisma.user.delete({ where: { id: userId } }); -} - async function handleDeleteMe(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { const auth = requireAuth(req); if (!auth) { @@ -258,62 +194,18 @@ async function handleDeleteMe(prisma: PrismaClient, req: express.Request, res: e return; } - logger.info('[Users] Account self-deletion initiated', { userId, email: user.email }); - await purgeUserAndRelated(prisma, userId); - logger.info('[Users] Account deleted successfully', { userId }); + logger.info({ event: 'user.self_delete.started', userId }); + await deleteAccount(prisma, userId); + logger.info({ event: 'user.self_delete.completed', userId }); res.clearCookie('token', { httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production' }); res.json({ ok: true, message: 'Account deleted successfully' }); } catch (e) { - logger.error('[Users] Account self-deletion failed', e); + logger.error({ event: 'user.self_delete.failed', userId, error: e instanceof Error ? e.message : String(e) }); res.status(500).json({ error: 'deletion failed' }); } } -async function handleListInvites(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { - const auth = requireAuth(req); - if (!auth) { - res.status(401).json({ error: 'unauthorized' }); - return; - } - const tenant = getTenantFromReq(req); - if (!tenant) { - res.status(400).json({ error: 'tenant_required' }); - return; - } - const list = await prisma.invite.findMany({ where: { tenantId: tenant.id }, orderBy: { createdAt: 'desc' } }); - res.json(list); -} - -async function handleDeleteInvite(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { - const auth = requireAuth(req); - if (!auth) { - res.status(401).json({ error: 'unauthorized' }); - return; - } - const tenant = getTenantFromReq(req); - if (!tenant) { - res.status(400).json({ error: 'tenant_required' }); - return; - } - const code = pathParam(req, 'code'); - try { - const inv = await prisma.invite.findUnique({ where: { code } }); - if (!inv || inv.tenantId !== tenant.id) { - res.status(404).json({ error: 'not found' }); - return; - } - if (inv.usedAt) { - res.status(400).json({ error: 'already used' }); - return; - } - await prisma.invite.delete({ where: { code } }); - res.json({ ok: true }); - } catch { - res.status(400).json({ error: 'delete failed' }); - } -} - /** * The member directory of the tenant this request is about — names, e-mail * addresses, roles and guest expiry. @@ -390,6 +282,11 @@ async function handleUpdateUser(prisma: PrismaClient, req: express.Request, res: } const id = pathParam(req, 'id'); + if (id === auth.userId) { await updateOwnProfile(prisma, auth.userId, req.body, res); return; } + if (req.body && typeof req.body === 'object' && 'email' in req.body) { + res.status(403).json({ code: 'SELF_EMAIL_CHANGE_REQUIRED', error: 'Only the account holder can change their email address through a confirmation link.' }); + return; + } if (id !== auth.userId) { const callerMembership = await requireMembership(req, auth.userId, prisma); if (!callerMembership || (callerMembership.role !== 'owner' && callerMembership.role !== 'admin')) { @@ -412,12 +309,11 @@ async function handleUpdateUser(prisma: PrismaClient, req: express.Request, res: res.status(400).json({ error: 'nothing to update' }); return; } - const { email, name } = parse.data; + const { name } = parse.data; try { - const normalized = email ? email.trim().toLowerCase() : undefined; const user = await prisma.user.update({ where: { id }, - data: { email: normalized ?? undefined, name: name ?? undefined }, + data: { name: name ?? undefined }, }); res.json({ id: user.id, email: user.email, name: user.name }); } catch (e: unknown) { @@ -493,26 +389,6 @@ async function handleChangeRole(prisma: PrismaClient, req: express.Request, res: } } -async function purgeUserMembershipData(prisma: PrismaClient, id: string): Promise { - try { - await prisma.presence.deleteMany({ where: { userId: id } }); - } catch {} - try { - await prisma.passwordReset.deleteMany({ where: { userId: id } }); - } catch {} - try { - await prisma.apiToken.deleteMany({ where: { userId: id } }); - } catch {} - try { - await prisma.invite.updateMany({ where: { usedById: id }, data: { usedById: null } }); - } catch {} - try { - await prisma.membership.deleteMany({ where: { userId: id } }); - } catch {} - await purgeCustomAvatarFiles(prisma, id); - await prisma.user.delete({ where: { id } }); -} - async function handleDeleteUser(prisma: PrismaClient, req: express.Request, res: express.Response): Promise { const auth = requireAuth(req); if (!auth) { @@ -549,17 +425,27 @@ async function handleDeleteUser(prisma: PrismaClient, req: express.Request, res: } try { - const exists = await prisma.user.findUnique({ where: { id } }); - if (!exists) { - res.status(404).json({ error: 'not found' }); + const { accountDeleted } = await removeMemberFromTenant(prisma, { userId: id, tenantId: tenant.id }); + logger.info({ + event: 'user.member_removed', + userId: id, + removedBy: auth.userId, + tenantId: tenant.id, + accountDeleted, + }); + res.json({ ok: true, accountDeleted }); + } catch (e) { + if (e instanceof MembershipNotFoundError) { + res.status(404).json({ error: 'user not found in this tenant' }); return; } - await purgeUserMembershipData(prisma, id); - logger.info({ event: 'user.deleted', userId: id, deletedBy: auth.userId, tenantId: tenant.id }); - res.json({ ok: true }); - } catch (e) { - logger.error('[Users] delete failed', e); - res.status(400).json({ error: 'delete failed' }); + logger.error({ + event: 'user.member_remove_failed', + userId: id, + tenantId: tenant.id, + error: e instanceof Error ? e.message : String(e), + }); + res.status(500).json({ error: 'delete failed' }); } } @@ -567,8 +453,7 @@ export function registerMiscRoutes(app: express.Application, prisma: PrismaClien app.patch('/me', (req, res) => handleUpdateMe(prisma, req, res)); app.get('/users/me/export', (req, res) => handleExportMyData(prisma, req, res)); app.delete('/users/me', (req, res) => handleDeleteMe(prisma, req, res)); - app.get('/invites', (req, res) => handleListInvites(prisma, req, res)); - app.delete('/invites/:code', (req, res) => handleDeleteInvite(prisma, req, res)); + registerInviteRoutes(app, prisma); app.get('/users', (req, res) => handleListUsers(prisma, req, res)); app.patch('/users/:id', (req, res) => handleUpdateUser(prisma, req, res)); app.patch('/users/:id/role', (req, res) => handleChangeRole(prisma, req, res)); diff --git a/apps/server/src/api/routes/npcMedia.ts b/apps/server/src/api/routes/npcMedia.ts index 0d699fd5..2e4d93b0 100644 --- a/apps/server/src/api/routes/npcMedia.ts +++ b/apps/server/src/api/routes/npcMedia.ts @@ -4,9 +4,10 @@ import crypto from 'crypto'; import path from 'path'; import fs from 'fs'; import fsp from 'fs/promises'; -import multer from 'multer'; +import { uploadGuard, uploadParser, boundedMultipart } from '../middleware/uploadPolicy.js'; import { requireAuth, requireApiToken, getTenantFromReq, requireMembership } from '../utils/authHelpers.js'; import { pathParam } from '../utils/requestHelpers.js'; +import { detectMimeFromMagic } from '../utils/mediaMime.js'; import { logger } from '../../logger.js'; // --- Allowed MIME types and their extensions --- @@ -21,26 +22,6 @@ const ALLOWED_MEDIA: Record = { 'video/webm': '.webm', }; -// --- Magic bytes for common formats --- - -const MAGIC_BYTES: ReadonlyArray<{ bytes: number[]; mime: string }> = [ - { bytes: [0x52, 0x49, 0x46, 0x46], mime: 'audio/wav' }, // RIFF (WAV) - { bytes: [0xff, 0xfb], mime: 'audio/mpeg' }, // MP3 frame sync - { bytes: [0xff, 0xf3], mime: 'audio/mpeg' }, - { bytes: [0xff, 0xf2], mime: 'audio/mpeg' }, - { bytes: [0x49, 0x44, 0x33], mime: 'audio/mpeg' }, // ID3 tag - { bytes: [0x4f, 0x67, 0x67, 0x53], mime: 'audio/ogg' }, // OGG - { bytes: [0x1a, 0x45, 0xdf, 0xa3], mime: 'video/webm' }, // WebM/MKV - { bytes: [0x00, 0x00, 0x00], mime: 'video/mp4' }, // MP4 (ftyp follows) -]; - -function detectMimeFromMagic(buf: Buffer): string | null { - for (const { bytes, mime } of MAGIC_BYTES) { - if (bytes.every((b, i) => buf[i] === b)) return mime; - } - return null; -} - function mapMimeToMediaType(mime: string): 'audio' | 'video' | 'screenshare' { if (mime.startsWith('video/')) return 'video'; return 'audio'; @@ -101,6 +82,8 @@ async function handleUploadMedia( const mime = detectedMime || file.mimetype; if (!ALLOWED_MEDIA[mime]) return res.status(400).json({ error: 'unsupported_media_type', detected: mime }); + if (mime.startsWith('audio/') && file.size > 25 * 1024 * 1024) return res.status(413).json({ error: 'Audio file too large.', code: 'UPLOAD_TOO_LARGE' }); + // Optional override mediaType from query (for screenshare) const mediaTypeQuery = req.query.mediaType as string | undefined; const mediaType: 'audio' | 'video' | 'screenshare' = @@ -182,12 +165,9 @@ export function registerNpcMediaRoutes(app: express.Application, prisma: PrismaC /* ignore */ } - const upload = multer({ - storage: multer.memoryStorage(), - limits: { fileSize: 100 * 1024 * 1024 }, // 100MB - }); + const upload = uploadParser('npc'); - app.post('/npcs/:id/media', upload.single('file'), (req, res) => handleUploadMedia(req, res, prisma, npcMediaDir)); + app.post('/npcs/:id/media', uploadGuard(prisma, 'npc'), boundedMultipart(upload.single('file')), (req, res) => handleUploadMedia(req, res, prisma, npcMediaDir)); app.get('/npcs/:id/media', (req, res) => handleListMedia(req, res, prisma)); app.delete('/npcs/:id/media/:mediaId', (req, res) => handleDeleteMedia(req, res, prisma, npcMediaDir)); } diff --git a/apps/server/src/api/routes/publicLinks.integration.test.ts b/apps/server/src/api/routes/publicLinks.integration.test.ts new file mode 100644 index 00000000..20b8d734 --- /dev/null +++ b/apps/server/src/api/routes/publicLinks.integration.test.ts @@ -0,0 +1,321 @@ +import crypto from 'node:crypto'; +import express from 'express'; +import request from 'supertest'; +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createPrismaClient } from '../../db.js'; +import { setAuthResolution } from '../utils/authState.js'; +import { handleAuthForgot } from './auth.password.js'; +import { handleAuthInvite } from './auth.signin.js'; +import { registerAdminPasswordResetRoutes } from './admin.passwordReset.js'; +import { registerGuestRoutes } from './guests.js'; +import { registerMiscRoutes } from './misc.js'; + +const capturedLogs = vi.hoisted(() => ({ events: [] as Array<{ level: string; value: unknown }> })); + +vi.mock('../../logger.js', () => ({ + logger: { + debug: (value: unknown) => capturedLogs.events.push({ level: 'debug', value }), + error: (value: unknown) => capturedLogs.events.push({ level: 'error', value }), + info: (value: unknown) => capturedLogs.events.push({ level: 'info', value }), + warn: (value: unknown) => capturedLogs.events.push({ level: 'warn', value }), + }, +})); + +vi.mock('../../emailLoader.js', () => ({ sendIfAvailable: vi.fn(() => Promise.resolve(false)) })); + +vi.mock('../../tenancyLoader.js', () => ({ + getTenancyModule: () => Promise.resolve({ isMultiTenantEnabled: () => true }), +})); + +if (!process.env.DATABASE_URL) { + throw new Error('publicLinks.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const guestEmails: string[] = []; +const publicEnvKeys = ['PUBLIC_BASE_URL', 'BILLING_PUBLIC_URL', 'PUBLIC_BASE_URL_ALLOW_LOOPBACK'] as const; +type PublicEnvKey = (typeof publicEnvKeys)[number]; +let originalPublicEnv: Record; + +interface Fixture { + app: express.Application; + tenantId: string; + adminId: string; + targetId: string; + targetEmail: string; +} + +function makeApp(): express.Application { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + const rawUser = req.headers['x-user']; + const userId = typeof rawUser === 'string' ? rawUser : null; + setAuthResolution(req, { + auth: userId ? { userId, sessionId: `sess-${userId}`, tokenHash: `hash-${userId}` } : null, + }); + const rawTenant = req.headers['x-tenant']; + if (typeof rawTenant === 'string') { + req.tenant = { id: rawTenant, slug: rawTenant, name: rawTenant } as never; + } + next(); + }); + registerGuestRoutes(app, prisma); + app.post('/auth/invite', (req, res) => handleAuthInvite(prisma, req, res)); + registerMiscRoutes(app, prisma); + registerAdminPasswordResetRoutes(app, prisma); + app.post('/auth/forgot', (req, res) => handleAuthForgot(prisma, req, res)); + return app; +} + +async function createFixture(): Promise { + const suffix = crypto.randomUUID(); + const slug = `qlink-${suffix}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + + const admin = await prisma.user.create({ data: { email: `admin-${suffix}@example.test` } }); + const target = await prisma.user.create({ + data: { email: `target-${suffix}@example.test`, passwordHash: 'test-password-hash' }, + }); + userIds.push(admin.id, target.id); + + await prisma.membership.create({ data: { tenantId: tenant.id, userId: admin.id, role: 'admin' } }); + await prisma.membership.create({ data: { tenantId: tenant.id, userId: target.id, role: 'member' } }); + + return { app: makeApp(), tenantId: tenant.id, adminId: admin.id, targetId: target.id, targetEmail: target.email }; +} + +function setPublicEnv(values: Record): void { + for (const key of publicEnvKeys) { + const value = values[key]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +} + +async function waitForForgotToFinish(previousLogCount: number): Promise { + await vi.waitFor(() => { + expect(capturedLogs.events.length).toBeGreaterThan(previousLogCount); + }); +} + +async function createManualInvite(fixture: Fixture): Promise { + const code = crypto.randomUUID().replaceAll('-', ''); + const email = `listed-${crypto.randomUUID()}@example.test`; + await prisma.invite.create({ + data: { code, email, createdBy: fixture.adminId, tenantId: fixture.tenantId, role: 'member' }, + }); + return email; +} + +async function exerciseMissingBase(values: Record): Promise { + setPublicEnv(values); + const fixture = await createFixture(); + const listedEmail = await createManualInvite(fixture); + const inviteCountBefore = await prisma.invite.count({ where: { tenantId: fixture.tenantId } }); + const resetCountBefore = await prisma.passwordReset.count({ where: { userId: fixture.targetId } }); + const guestEmail = `guest-${crypto.randomUUID()}@example.test`; + guestEmails.push(guestEmail); + + const guestResponse = await request(fixture.app) + .post('/guests') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .set('Origin', 'https://web.example') + .send({ email: guestEmail, name: 'Guest', expiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString() }); + const guestMemberships = await prisma.membership.findMany({ + where: { tenantId: fixture.tenantId, role: 'guest' }, + select: { id: true }, + }); + const guestTokenCountAfter = await prisma.guestToken.count({ + where: { membershipId: { in: guestMemberships.map(({ id }) => id) } }, + }); + + const inviteResponse = await request(fixture.app) + .post('/auth/invite') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .set('Origin', 'https://web.example') + .send({ email: `invite-${crypto.randomUUID()}@example.test`, role: 'member' }); + const inviteCountAfter = await prisma.invite.count({ where: { tenantId: fixture.tenantId } }); + + const listResponse = await request(fixture.app) + .get('/invites') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId); + const listedInvite = (listResponse.body as Array<{ email: string | null; url?: string | null }>).find( + ({ email }) => email === listedEmail, + ); + + const resetResponse = await request(fixture.app) + .post(`/admin/users/${fixture.targetId}/reset-token`) + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .set('Origin', 'https://web.example'); + const resetCountAfterAdmin = await prisma.passwordReset.count({ where: { userId: fixture.targetId } }); + + const logsBeforeForgot = capturedLogs.events.length; + const forgotResponse = await request(fixture.app).post('/auth/forgot').send({ email: fixture.targetEmail }); + await waitForForgotToFinish(logsBeforeForgot); + const resetCountAfterForgot = await prisma.passwordReset.count({ where: { userId: fixture.targetId } }); + + expect.soft(guestResponse.status).toBe(500); + expect.soft(guestResponse.body).toEqual({ error: 'public_base_url_missing' }); + expect.soft(guestTokenCountAfter).toBe(0); + expect.soft(inviteResponse.status).toBe(500); + expect.soft(inviteResponse.body).toEqual({ error: 'public_base_url_missing' }); + expect.soft(inviteCountAfter - inviteCountBefore).toBe(0); + expect.soft(listedInvite?.url).toBeNull(); + expect.soft(resetResponse.status).toBe(500); + expect.soft(resetResponse.body).toEqual({ error: 'public_base_url_missing' }); + expect.soft(resetCountAfterAdmin - resetCountBefore).toBe(0); + expect.soft(forgotResponse.status).toBe(200); + expect.soft(resetCountAfterForgot - resetCountBefore).toBe(0); +} + +beforeEach(() => { + originalPublicEnv = Object.fromEntries(publicEnvKeys.map((key) => [key, process.env[key]])) as Record< + PublicEnvKey, + string | undefined + >; + capturedLogs.events.length = 0; +}); + +afterEach(async () => { + const currentTenantIds = tenantIds.splice(0); + const currentUserIds = userIds.splice(0); + const currentGuestEmails = guestEmails.splice(0); + const extraUsers = currentGuestEmails.length + ? await prisma.user.findMany({ where: { email: { in: currentGuestEmails } }, select: { id: true } }) + : []; + const allUserIds = [...currentUserIds, ...extraUsers.map(({ id }) => id)]; + const memberships = currentTenantIds.length + ? await prisma.membership.findMany({ where: { tenantId: { in: currentTenantIds } }, select: { id: true } }) + : []; + + if (currentTenantIds.length) { + await prisma.invite.deleteMany({ where: { tenantId: { in: currentTenantIds } } }); + } + if (memberships.length) { + await prisma.guestToken.deleteMany({ where: { membershipId: { in: memberships.map(({ id }) => id) } } }); + } + if (allUserIds.length) { + await prisma.passwordReset.deleteMany({ where: { userId: { in: allUserIds } } }); + await prisma.emailVerification.deleteMany({ where: { userId: { in: allUserIds } } }); + await prisma.session.deleteMany({ where: { userId: { in: allUserIds } } }); + } + if (currentTenantIds.length || allUserIds.length) { + await prisma.membership.deleteMany({ + where: { + OR: [ + ...(currentTenantIds.length ? [{ tenantId: { in: currentTenantIds } }] : []), + ...(allUserIds.length ? [{ userId: { in: allUserIds } }] : []), + ], + }, + }); + } + if (allUserIds.length) await prisma.user.deleteMany({ where: { id: { in: allUserIds } } }); + if (currentTenantIds.length) await prisma.tenant.deleteMany({ where: { id: { in: currentTenantIds } } }); + + for (const key of publicEnvKeys) { + const value = originalPublicEnv[key]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +}); + +afterAll(async () => { + await prisma.$disconnect(); +}); + +describe('public web links (real database)', () => { + it('A: uses PUBLIC_BASE_URL even when the request Origin is native', async () => { + setPublicEnv({ + PUBLIC_BASE_URL: 'https://public.example/', + BILLING_PUBLIC_URL: undefined, + PUBLIC_BASE_URL_ALLOW_LOOPBACK: undefined, + }); + const fixture = await createFixture(); + const guestEmail = `guest-${crypto.randomUUID()}@example.test`; + guestEmails.push(guestEmail); + + const guest = await request(fixture.app) + .post('/guests') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .set('Origin', 'tauri://localhost') + .send({ email: guestEmail, name: 'Guest', expiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString() }); + const inviteEmail = `invite-${crypto.randomUUID()}@example.test`; + const invite = await request(fixture.app) + .post('/auth/invite') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .set('Origin', 'tauri://localhost') + .send({ email: inviteEmail, role: 'member' }); + const listed = await request(fixture.app) + .get('/invites') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId); + const listedInvite = (listed.body as Array<{ email: string | null; url?: string | null }>).find( + ({ email }) => email === inviteEmail, + ); + const reset = await request(fixture.app) + .post(`/admin/users/${fixture.targetId}/reset-token`) + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .set('Origin', 'tauri://localhost'); + const logsBeforeForgot = capturedLogs.events.length; + const forgot = await request(fixture.app).post('/auth/forgot').send({ email: fixture.targetEmail }); + await waitForForgotToFinish(logsBeforeForgot); + const resetTokenCount = await prisma.passwordReset.count({ where: { userId: fixture.targetId } }); + + expect.soft(guest.status).toBe(200); + expect.soft(guest.body.magicLink.startsWith('https://public.example/#/guest?token=')).toBe(true); + expect.soft(invite.status).toBe(200); + expect.soft(invite.body.inviteUrl).toBe(`https://public.example/#/?invite=${invite.body.code}`); + expect.soft(listedInvite?.url).toBe(`https://public.example/#/?invite=${invite.body.code}`); + expect.soft(reset.status).toBe(200); + expect.soft(reset.body.resetUrl.startsWith('https://public.example/#/reset?token=')).toBe(true); + expect.soft(forgot.status).toBe(200); + expect.soft(resetTokenCount).toBeGreaterThan(0); + }); + + it('B: does not fall back to BILLING_PUBLIC_URL or the request Origin', async () => { + await exerciseMissingBase({ + PUBLIC_BASE_URL: undefined, + BILLING_PUBLIC_URL: 'https://billing.example', + PUBLIC_BASE_URL_ALLOW_LOOPBACK: undefined, + }); + }); + + it.each(['tauri://localhost', 'http://tauri.localhost', 'http://localhost:5173'] as const)( + 'C: rejects invalid configured base %s without the loopback switch', + async (publicBaseUrl) => { + await exerciseMissingBase({ + PUBLIC_BASE_URL: publicBaseUrl, + BILLING_PUBLIC_URL: undefined, + PUBLIC_BASE_URL_ALLOW_LOOPBACK: undefined, + }); + }, + ); + + it('D: permits a loopback PUBLIC_BASE_URL when the explicit switch is true', async () => { + setPublicEnv({ + PUBLIC_BASE_URL: 'http://localhost:42040', + BILLING_PUBLIC_URL: undefined, + PUBLIC_BASE_URL_ALLOW_LOOPBACK: 'true', + }); + const fixture = await createFixture(); + const invite = await request(fixture.app) + .post('/auth/invite') + .set('x-user', fixture.adminId) + .set('x-tenant', fixture.tenantId) + .send({ email: `invite-${crypto.randomUUID()}@example.test`, role: 'member' }); + + expect(invite.status).toBe(200); + expect(invite.body.inviteUrl).toBe(`http://localhost:42040/#/?invite=${invite.body.code}`); + }); +}); diff --git a/apps/server/src/api/routes/tenantScope.integration.test.ts b/apps/server/src/api/routes/tenantScope.integration.test.ts new file mode 100644 index 00000000..a63f0eef --- /dev/null +++ b/apps/server/src/api/routes/tenantScope.integration.test.ts @@ -0,0 +1,215 @@ +import crypto from 'crypto'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Role, Tenant } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { resolveTenantBySlug } from '../../tenancy.js'; +import { createTenantAccessMiddleware } from '../middleware/tenantAccess.js'; +import { getApiTokenPepper, getJwtSecret, getTenantFromReq, requireAuth } from '../utils/authHelpers.js'; +import { invalidateSessionsForUser } from '../utils/sessionCache.js'; +import { createSessionAuthMiddleware, hashSessionToken } from '../utils/sessionAuth.js'; +import { handleAuthPosition } from './auth.profile.js'; +import { registerNpcRoutes } from './npcs.js'; +import { registerPresenceRoutes } from './presence.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('tenantScope.integration.test.ts requires an isolated migrated DATABASE_URL'); +} +const databaseUrl = new URL(process.env.DATABASE_URL); +if (databaseUrl.hostname !== '127.0.0.1' || databaseUrl.port !== '35440') { + throw new Error('This test requires the local test database on port 35440'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +type Caller = { id: string; session: string; apiToken: string }; +let app: express.Express; +let tenantA: Tenant; +let tenantB: Tenant; +let memberA: Caller; +let memberB: Caller; +let npcId: string; +let roomA: string; + +async function createTenant(): Promise { + const slug = `scope-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + const map = await prisma.map.create({ data: { tenantId: tenant.id, name: 'office', meta: {} } }); + await prisma.room.create({ data: { tenantId: tenant.id, mapId: map.id, name: `scope-${tenant.id}` } }); + return tenant; +} + +async function createCaller(tenant: Tenant, role: Role = 'member', expiresAt?: Date): Promise { + const user = await prisma.user.create({ data: { email: `scope-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId: tenant.id, role, expiresAt } }); + const session = jwt.sign({ sub: user.id, tid: tenant.id, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(session), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + const apiToken = `mt_${crypto.randomBytes(24).toString('hex')}`; + const hash = crypto + .createHash('sha256') + .update(getApiTokenPepper() + apiToken) + .digest('hex'); + await prisma.apiToken.create({ data: { userId: user.id, hash, name: 'scope-fixture' } }); + return { id: user.id, session, apiToken }; +} + +function expectDenied(res: request.Response): void { + expect(res.status).toBe(400); + expect(res.body).toEqual({ error: 'tenant_required' }); +} + +beforeAll(async () => { + tenantA = await createTenant(); + tenantB = await createTenant(); + roomA = `scope-${tenantA.id}`; + memberA = await createCaller(tenantA); + memberB = await createCaller(tenantB); + const npc = await prisma.npc.create({ + data: { tenantId: tenantB.id, identity: `scope-${crypto.randomUUID()}`, name: 'Scope fixture' }, + }); + npcId = npc.id; + app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + void resolveTenantBySlug(prisma, req) + .then((tenant) => { + req.tenant = tenant ?? undefined; + req.tenantId = tenant?.id; + next(); + }) + .catch((error: unknown) => next(error)); + }); + app.use(createSessionAuthMiddleware(prisma)); + app.use(createTenantAccessMiddleware(prisma)); + registerPresenceRoutes(app, prisma, requireAuth, getTenantFromReq); + registerNpcRoutes(app, prisma); + app.post('/auth/position', (req, res) => handleAuthPosition(prisma, req, res)); +}); + +afterAll(async () => { + for (const userId of userIds) invalidateSessionsForUser(userId); + try { + await prisma.presence.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.npc.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.room.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.map.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.apiToken.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + } finally { + await prisma.$disconnect(); + } +}); + +describe('tenant route authorization through the real resolver and database', () => { + it('serves presence only for the resolved tenant of an active member', async () => { + const own = await request(app) + .get('/presence/recent') + .set('x-tenant', tenantA.slug) + .set('Authorization', `Bearer ${memberA.session}`); + expect(own.status).toBe(200); + expect(own.body).toContainEqual(expect.objectContaining({ userId: memberA.id })); + expect(own.body).not.toContainEqual(expect.objectContaining({ userId: memberB.id })); + expectDenied( + await request(app) + .get('/presence/recent') + .set('x-tenant', tenantB.slug) + .set('Authorization', `Bearer ${memberA.session}`), + ); + }); + + it('resolves query tenant before the session tenant and header before query', async () => { + expectDenied( + await request(app) + .get('/presence/recent') + .query({ tenant: tenantB.slug }) + .set('Authorization', `Bearer ${memberA.session}`), + ); + const own = await request(app) + .get('/presence/recent') + .query({ tenant: tenantB.slug }) + .set('x-tenant', tenantA.slug) + .set('Authorization', `Bearer ${memberA.session}`); + expect(own.status).toBe(200); + expect(own.body).toContainEqual(expect.objectContaining({ userId: memberA.id })); + }); + + it('writes presence only in the proven tenant and preserves it after foreign writes', async () => { + const position = { roomId: roomA, x: 12, y: 24, direction: 'down' }; + const own = await request(app) + .post('/auth/position') + .set('x-tenant', tenantA.slug) + .set('Authorization', `Bearer ${memberA.session}`) + .send(position); + expect(own.status).toBe(200); + const before = await prisma.presence.findMany({ where: { userId: memberA.id } }); + expect(before).toHaveLength(1); + expect(before[0]).toMatchObject({ tenantId: tenantA.id, x: 12, y: 24 }); + expectDenied( + await request(app) + .post('/auth/position') + .set('x-tenant', tenantB.slug) + .set('Authorization', `Bearer ${memberA.session}`) + .send({ ...position, x: 99 }), + ); + expect(await prisma.presence.findMany({ where: { userId: memberA.id } })).toEqual(before); + }); + + it('refuses the actual NPC command route to foreign session and API-token callers', async () => { + const before = await prisma.npc.findUniqueOrThrow({ where: { id: npcId } }); + for (const token of [memberA.session, memberA.apiToken]) { + expectDenied( + await request(app) + .post(`/npcs/${npcId}/command`) + .set('x-tenant', tenantB.slug) + .set('Authorization', `Bearer ${token}`) + .send({ action: 'stop_movement' }), + ); + } + expect(await prisma.npc.findUniqueOrThrow({ where: { id: npcId } })).toEqual(before); + }); + + it('allows the same command for its active member without an external NPC service', async () => { + expect(global.activeWorldRooms?.size ?? 0).toBe(0); + const result = await request(app) + .post(`/npcs/${npcId}/command`) + .set('x-tenant', tenantB.slug) + .set('Authorization', `Bearer ${memberB.session}`) + .send({ action: 'stop_movement' }); + expect(result.status).toBe(200); + expect(result.body).toEqual({ ok: true, delivered: 0 }); + }); + + it('refuses expired guests and memberships removed after session creation', async () => { + const expired = await createCaller(tenantA, 'guest', new Date(Date.now() - 60_000)); + const removed = await createCaller(tenantA); + await prisma.membership.delete({ where: { tenantId_userId: { tenantId: tenantA.id, userId: removed.id } } }); + for (const caller of [expired, removed]) { + expectDenied( + await request(app) + .get('/presence/recent') + .set('x-tenant', tenantA.slug) + .set('Authorization', `Bearer ${caller.session}`), + ); + expectDenied( + await request(app) + .post('/auth/position') + .set('x-tenant', tenantA.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({ x: 1, y: 1, direction: 'down' }), + ); + expect(await prisma.presence.count({ where: { userId: caller.id } })).toBe(0); + } + }); +}); diff --git a/apps/server/src/api/routes/tmj.authorization.integration.test.ts b/apps/server/src/api/routes/tmj.authorization.integration.test.ts new file mode 100644 index 00000000..71eec252 --- /dev/null +++ b/apps/server/src/api/routes/tmj.authorization.integration.test.ts @@ -0,0 +1,84 @@ +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerTmjImportRoute } from './tmj.import.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +const tmj = Buffer.from( + JSON.stringify({ + width: 2, + height: 2, + tilewidth: 32, + tileheight: 32, + tilesets: [], + layers: [], + }), +); + +beforeAll(() => { + registerTmjImportRoute(app, fixture.prisma); + app.use(errorHandler); +}); +afterAll(() => fixture.close()); + +describe('TMJ import through a real session, tenant resolver and PostgreSQL', () => { + it('rejects member changes and permits the same import for owners and administrators', async () => { + const own = await fixture.tenant(); + const other = await fixture.tenant(); + const member = await fixture.caller(own.tenant); + const owner = await fixture.caller(own.tenant, 'owner'); + const admin = await fixture.caller(own.tenant, 'admin'); + const guest = await fixture.caller(own.tenant, 'guest'); + const foreign = await fixture.caller(other.tenant, 'owner'); + const layer = await fixture.prisma.mapLayer.create({ + data: { mapId: own.map.id, name: 'ground', chunkSize: 32 }, + }); + await fixture.prisma.mapChunk.create({ + data: { layerId: layer.id, x: 0, y: 0, version: 1, encoding: 'rle', data: new Uint8Array([1, 0]) }, + }); + const before = { + map: await fixture.prisma.map.findUniqueOrThrow({ where: { id: own.map.id } }), + layers: await fixture.prisma.mapLayer.findMany({ where: { mapId: own.map.id } }), + chunks: await fixture.prisma.mapChunk.findMany({ where: { layerId: layer.id } }), + }; + const endpoint = `/maps/${own.map.id}/import-tmj`; + const denied = await request(app) + .post(endpoint) + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${member.session}`) + .attach('file', tmj, 'office.tmj'); + expect(denied.status).toBe(403); + expect(await fixture.prisma.map.findUniqueOrThrow({ where: { id: own.map.id } })).toEqual(before.map); + expect(await fixture.prisma.mapLayer.findMany({ where: { mapId: own.map.id } })).toEqual(before.layers); + expect(await fixture.prisma.mapChunk.findMany({ where: { layerId: layer.id } })).toEqual(before.chunks); + + for (const caller of [guest, foreign]) { + const result = await request(app) + .post(endpoint) + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .attach('file', tmj, 'office.tmj'); + expect(result.status).toBe(403); + } + for (const token of [owner.session, admin.session, owner.apiToken]) { + const allowed = await request(app) + .post(endpoint) + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${token}`) + .attach('file', tmj, 'office.tmj'); + expect(allowed.status).toBe(200); + expect(await fixture.prisma.map.findUniqueOrThrow({ where: { id: own.map.id } })).toMatchObject({ + width: 2, + height: 2, + }); + } + const foreignMap = await request(app) + .post(`/maps/${other.map.id}/import-tmj`) + .set('x-tenant', own.tenant.slug) + .set('Authorization', `Bearer ${owner.session}`) + .attach('file', tmj, 'office.tmj'); + expect(foreignMap.status).toBe(404); + }); +}); diff --git a/apps/server/src/api/routes/tmj.import.ts b/apps/server/src/api/routes/tmj.import.ts index 166023cf..a1e4e604 100644 --- a/apps/server/src/api/routes/tmj.import.ts +++ b/apps/server/src/api/routes/tmj.import.ts @@ -3,9 +3,9 @@ import path from 'path'; import { fileURLToPath } from 'url'; import type express from 'express'; import type { PrismaClient } from '../../generated/prisma/index.js'; -import multer from 'multer'; +import { uploadGuard, uploadParser, boundedMultipart } from '../middleware/uploadPolicy.js'; import { logger } from '../../logger.js'; -import { requireAuth, getTenantFromReq } from '../utils/authHelpers.js'; +import { resolveEditorMemberTenant } from './maps.editor.js'; import { pathParam } from '../utils/requestHelpers.js'; import { broadcastMapUpdate } from '../utils/broadcast.js'; import { reconcileCollisionTiles, rectCollisionTiles } from '../utils/collisionReconciler.js'; @@ -27,10 +27,7 @@ import { const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const upload = multer({ - storage: multer.memoryStorage(), - limits: { fileSize: 10 * 1024 * 1024 }, -}); +const upload = uploadParser('tmj'); const importUpload = upload.fields([ { name: 'file', maxCount: 1 }, @@ -258,10 +255,8 @@ export async function handleTmjImport( res: express.Response, ): Promise { try { - const auth = requireAuth(req); - if (!auth) return void res.status(401).json({ error: 'unauthorized' }); - const tenant = getTenantFromReq(req); - if (!tenant) return void res.status(400).json({ error: 'tenant_required' }); + const tenant = await resolveEditorMemberTenant(prisma, req, res, { requireAdmin: true }); + if (!tenant) return; const parsed = parseImport(req, res); if (!parsed) return; const map = await prisma.map.findFirst({ where: { id: pathParam(req, 'id'), tenantId: tenant.id } }); @@ -291,5 +286,5 @@ export async function handleTmjImport( } export function registerTmjImportRoute(app: express.Application, prisma: PrismaClient): void { - app.post('/maps/:id/import-tmj', importUpload, (req, res) => handleTmjImport(prisma, req, res)); + app.post('/maps/:id/import-tmj', uploadGuard(prisma, 'tmj'), boundedMultipart(importUpload), (req, res) => handleTmjImport(prisma, req, res)); } diff --git a/apps/server/src/api/routes/uploads.global.integration.test.ts b/apps/server/src/api/routes/uploads.global.integration.test.ts new file mode 100644 index 00000000..0cd519af --- /dev/null +++ b/apps/server/src/api/routes/uploads.global.integration.test.ts @@ -0,0 +1,138 @@ +import crypto from 'node:crypto'; +import { mkdtemp, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import JSZip from 'jszip'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { uploadTransport, writeBytes } from '../../../test/fixtures/uploadFixture.js'; +import { registerAssetPackRoutes } from './assetPacks.js'; +import { registerAvatarPackRoutes } from './avatarPacks.js'; +import { registerAdminMapRoutes } from './adminMaps.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +let directory = ''; +const previous = process.env.ASSET_PACKS_DIR; +const packUuids: string[] = []; +beforeAll(async () => { + directory = await mkdtemp(path.join(os.tmpdir(), 'global-media-upload-fixture-')); + process.env.ASSET_PACKS_DIR = directory; + registerAssetPackRoutes(app, fixture.prisma); + registerAvatarPackRoutes(app, fixture.prisma); + registerAdminMapRoutes(app, fixture.prisma); + app.use(errorHandler); +}); +afterAll(async () => { + await fixture.prisma.assetPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await fixture.close(); + if (directory) await rm(directory, { recursive: true, force: true }); + if (previous === undefined) delete process.env.ASSET_PACKS_DIR; + else process.env.ASSET_PACKS_DIR = previous; +}); +async function operator() { + const own = await fixture.tenant(); + const caller = await fixture.caller(own.tenant); + let internal = await fixture.prisma.tenant.findUnique({ where: { slug: 'internal' } }); + if (!internal) { + internal = await fixture.prisma.tenant.create({ data: { slug: 'internal', name: 'Internal test tenant' } }); + fixture.tenantIds.push(internal.id); + } + await fixture.prisma.membership.create({ data: { tenantId: internal.id, userId: caller.id, role: 'owner' } }); + return { ...own, caller }; +} + +for (const [route, limit] of [ + ['/asset-packs/upload', 50], + ['/avatar-packs/upload-sprite', 5], + ['/admin/maps/import', 50], +] as const) { + it(`${route} accepts the exact file limit for content validation and rejects one extra byte with 413`, async () => { + const value = await operator(); + for (const overflow of [false, true]) { + const transport = await uploadTransport(app); + const { req, result } = transport.open(route, { + 'X-Tenant': value.tenant.slug, + Authorization: `Bearer ${value.caller.session}`, + 'Content-Type': 'multipart/form-data; boundary=fixture-global', + }); + try { + await transport.ready(1); + for (const [name, text] of [ + ['packUuid', crypto.randomUUID()], + ['tenantId', value.tenant.id], + ['name', crypto.randomUUID()], + ]) { + req.write(`--fixture-global\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${text}\r\n`); + } + req.write( + '--fixture-global\r\nContent-Disposition: form-data; name="file"; filename="invalid.bin"\r\nContent-Type: application/octet-stream\r\n\r\n', + ); + await writeBytes(req, limit * 1024 * 1024 + Number(overflow), 0); + req.end('\r\n--fixture-global--\r\n'); + const response = await result; + if (overflow) expect(response.status).toBe(413); + else expect([400, 500].includes(response.status)).toBe(true); + } finally { + req.destroy(); + await transport.close(); + } + } + }, 90_000); +} + +it('accepts valid small ZIP, PNG and administrator map uploads', async () => { + const value = await operator(); + const uuid = crypto.randomUUID(); + packUuids.push(uuid); + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Zl1sAAAAASUVORK5CYII=', + 'base64', + ); + const zip = new JSZip(); + zip.file( + 'config.json', + JSON.stringify({ + uuid, + name: 'Upload test', + description: 'Upload fixture', + author: 'Test author', + version: '1.0.0', + terrain: [], + structures: [], + objects: [{ id: 'pixel', key: 'pixel', category: 'objects', dataURL: 'assets/pixel.png', width: 1, height: 1 }], + }), + ); + zip.file('assets/pixel.png', png); + const pack = await request(app) + .post('/asset-packs/upload') + .set('X-Tenant', value.tenant.slug) + .set('Authorization', `Bearer ${value.caller.apiToken}`) + .attach('file', await zip.generateAsync({ type: 'nodebuffer' }), { + filename: 'pack.zip', + contentType: 'application/zip', + }); + expect(pack.status).toBe(200); + expect(await fixture.prisma.assetPack.count({ where: { uuid } })).toBe(1); + const sprite = await request(app) + .post('/avatar-packs/upload-sprite') + .set('X-Tenant', value.tenant.slug) + .set('Authorization', `Bearer ${value.caller.session}`) + .field('packUuid', uuid) + .attach('file', png, { filename: 'sprite.png', contentType: 'image/png' }); + expect(sprite.status).toBe(200); + const map = await request(app) + .post('/admin/maps/import') + .set('X-Tenant', value.tenant.slug) + .set('Authorization', `Bearer ${value.caller.apiToken}`) + .field('tenantId', value.tenant.id) + .field('name', `fixture-admin-map-${crypto.randomUUID()}`) + .attach( + 'file', + Buffer.from(JSON.stringify({ width: 2, height: 2, tilewidth: 32, tileheight: 32, layers: [], tilesets: [] })), + { filename: 'map.json', contentType: 'application/json' }, + ); + expect(map.status).toBe(200); +}); diff --git a/apps/server/src/api/routes/uploads.guard.integration.test.ts b/apps/server/src/api/routes/uploads.guard.integration.test.ts new file mode 100644 index 00000000..3e25637b --- /dev/null +++ b/apps/server/src/api/routes/uploads.guard.integration.test.ts @@ -0,0 +1,87 @@ +import { mkdtemp, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import request from 'supertest'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerAssetPackRoutes } from './assetPacks.js'; +import { registerAvatarPackRoutes } from './avatarPacks.js'; +import { registerNpcMediaRoutes } from './npcMedia.js'; +import { registerAdminMapRoutes } from './adminMaps.js'; +import { registerTmjImportRoute } from './tmj.import.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +const original = { packs: process.env.ASSET_PACKS_DIR, npc: process.env.NPC_MEDIA_DIR }; +let temporary = ''; +beforeAll(async () => { + temporary = await mkdtemp(path.join(os.tmpdir(), 'multipart-upload-fixture-')); + process.env.ASSET_PACKS_DIR = path.join(temporary, 'packs'); + process.env.NPC_MEDIA_DIR = path.join(temporary, 'npc'); + registerAssetPackRoutes(app, fixture.prisma); + registerAvatarPackRoutes(app, fixture.prisma); + registerNpcMediaRoutes(app, fixture.prisma); + registerAdminMapRoutes(app, fixture.prisma); + registerTmjImportRoute(app, fixture.prisma); + app.use(errorHandler); +}); +afterAll(async () => { + if (original.packs === undefined) delete process.env.ASSET_PACKS_DIR; + else process.env.ASSET_PACKS_DIR = original.packs; + if (original.npc === undefined) delete process.env.NPC_MEDIA_DIR; + else process.env.NPC_MEDIA_DIR = original.npc; + await fixture.close(); + if (temporary) await rm(temporary, { recursive: true, force: true }); +}); + +for (const route of [ + '/asset-packs/upload', + '/avatar-packs/upload-sprite', + '/npcs/missing/media', + '/admin/maps/import', + '/maps/missing/import-tmj', +]) { + it(`${route} checks authentication and role before malformed multipart parsing`, async () => { + const { tenant } = await fixture.tenant(); + const member = await fixture.caller(tenant); + const anonymous = await request(app) + .post(route) + .set('X-Tenant', tenant.slug) + .set('Content-Type', 'multipart/form-data; boundary=fixture-broken') + .send('incomplete body'); + expect(anonymous.status).toBe(401); + const denied = await request(app) + .post(route) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${member.session}`) + .set('Content-Type', 'multipart/form-data; boundary=fixture-broken') + .send('incomplete body'); + expect(denied.status).toBe(403); + }); +} + +it('returns tenant_required without a resolved tenant', async () => { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const result = await request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('Authorization', `Bearer ${owner.session}`) + .set('Content-Type', 'multipart/form-data; boundary=fixture-broken') + .send('incomplete body'); + expect(result.status).toBe(400); + expect(result.body).toEqual({ error: 'tenant_required' }); +}); + +it('returns admin-required forbidden for tmj member uploads', async () => { + const { tenant, map } = await fixture.tenant(); + const member = await fixture.caller(tenant); + const result = await request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${member.session}`) + .set('Content-Type', 'multipart/form-data; boundary=fixture-broken') + .send('incomplete body'); + expect(result.status).toBe(403); + expect(result.body).toEqual({ error: 'forbidden - admin required' }); +}); diff --git a/apps/server/src/api/routes/uploads.limits.integration.test.ts b/apps/server/src/api/routes/uploads.limits.integration.test.ts new file mode 100644 index 00000000..3a5bed8f --- /dev/null +++ b/apps/server/src/api/routes/uploads.limits.integration.test.ts @@ -0,0 +1,90 @@ +import request from 'supertest'; +import { afterAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { registerTmjImportRoute } from './tmj.import.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +registerTmjImportRoute(app, fixture.prisma); +app.use(errorHandler); +afterAll(() => fixture.close()); +const MiB = 1024 * 1024; +const json = JSON.stringify({ width: 2, height: 2, tilewidth: 32, tileheight: 32, layers: [], tilesets: [] }); +function tmj(size: number) { + return Buffer.from(json + ' '.repeat(Math.max(0, size - Buffer.byteLength(json)))); +} + +it('includes the TMJ file limit and rejects one extra byte with 413 without changing the map', async () => { + for (const [size, expected] of [ + [10 * MiB, 200], + [10 * MiB + 1, 413], + ]) { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const result = await request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${owner.session}`) + .attach('file', tmj(size), { filename: 'map.tmj', contentType: 'application/json' }); + expect(result.status).toBe(expected); + expect((await fixture.prisma.map.findUniqueOrThrow({ where: { id: map.id } })).width).toBe( + expected === 200 ? 2 : 4, + ); + } +}, 60_000); + +it('enforces 5 MiB image and 64 KiB field limits alongside a valid map', async () => { + for (const field of ['image', 'text']) { + for (const overflow of [false, true]) { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const post = request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${owner.session}`) + .attach('file', tmj(Buffer.byteLength(json)), { filename: 'map.tmj', contentType: 'application/json' }); + if (field === 'image') + post.attach('images', Buffer.alloc(5 * MiB + Number(overflow)), { + filename: 'unused.png', + contentType: 'image/png', + }); + else post.field('description', 'a'.repeat(64 * 1024 + Number(overflow))); + const result = await post; + expect(result.status).toBe(overflow ? 413 : 200); + expect((await fixture.prisma.map.findUniqueOrThrow({ where: { id: map.id } })).width).toBe(overflow ? 4 : 2); + } + } +}, 60_000); + +it('limits requests to 16 fields and 11 files without changing the map on rejection', async () => { + for (const overflow of [false, true]) { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const post = request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${owner.session}`) + .attach('file', tmj(Buffer.byteLength(json)), { filename: 'map.tmj', contentType: 'application/json' }); + for (let i = 0; i < 10; i++) + post.attach('images', Buffer.from([0]), { filename: `unused-${i}.png`, contentType: 'image/png' }); + for (let i = 0; i < 16 + Number(overflow); i++) post.field(`field${i}`, 'a'); + expect((await post).status).toBe(overflow ? 413 : 200); + expect((await fixture.prisma.map.findUniqueOrThrow({ where: { id: map.id } })).width).toBe(overflow ? 4 : 2); + } +}); + +it('closes the connection on oversized content length', async () => { + const { tenant, map } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const result = await request(app) + .post(`/maps/${map.id}/import-tmj`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${owner.session}`) + .attach('file', tmj(61 * MiB + 1), { + filename: 'map.tmj', + contentType: 'application/json', + }); + expect(result.status).toBe(413); + expect(String(result.headers['connection'] || '')).toMatch(/close/i); +}, 60_000); diff --git a/apps/server/src/api/routes/uploads.npc.integration.test.ts b/apps/server/src/api/routes/uploads.npc.integration.test.ts new file mode 100644 index 00000000..ecacd176 --- /dev/null +++ b/apps/server/src/api/routes/uploads.npc.integration.test.ts @@ -0,0 +1,56 @@ +import crypto from 'node:crypto'; +import { mkdtemp, rm, readdir } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, beforeAll, expect, it } from 'vitest'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { uploadTransport, writeBytes } from '../../../test/fixtures/uploadFixture.js'; +import { registerNpcMediaRoutes } from './npcMedia.js'; +import { errorHandler } from '../errorHandler.js'; + +const fixture = createHttpFixture(); +const app = fixture.app(); +let directory = ''; +const previous = process.env.NPC_MEDIA_DIR; +beforeAll(async () => { + directory = await mkdtemp(path.join(os.tmpdir(), 'npc-media-upload-fixture-')); + process.env.NPC_MEDIA_DIR = directory; + registerNpcMediaRoutes(app, fixture.prisma); + app.use(errorHandler); +}); +afterAll(async () => { + await fixture.close(); + if (directory) await rm(directory, { recursive: true, force: true }); + if (previous === undefined) delete process.env.NPC_MEDIA_DIR; + else process.env.NPC_MEDIA_DIR = previous; +}); + +it('detects audio with forged headers and split magic bytes before the 25 MiB limit', async () => { + const { tenant } = await fixture.tenant(); + const owner = await fixture.caller(tenant, 'owner'); + const npc = await fixture.prisma.npc.create({ + data: { tenantId: tenant.id, identity: crypto.randomUUID(), name: 'Upload fixture' }, + }); + const transport = await uploadTransport(app); + const { req, result } = transport.open(`/npcs/${npc.id}/media`, { + 'X-Tenant': tenant.slug, + Authorization: `Bearer ${owner.apiToken}`, + 'Content-Type': 'multipart/form-data; boundary=fixture-npc', + }); + try { + await transport.ready(1); + req.write( + '--fixture-npc\r\nContent-Disposition: form-data; name="file"; filename="audio.wav"\r\nContent-Type: video/mp4\r\n\r\n', + ); + req.write('R'); + req.write('IFF'); + await writeBytes(req, 25 * 1024 * 1024 - 4 + 1, 0); + req.end('\r\n--fixture-npc--\r\n'); + expect((await result).status).toBe(413); + expect(await fixture.prisma.npcMediaFile.count({ where: { npcId: npc.id } })).toBe(0); + expect(await readdir(directory)).toHaveLength(0); + } finally { + req.destroy(); + await transport.close(); + } +}, 60_000); diff --git a/apps/server/src/api/routes/userDeletion.integration.test.ts b/apps/server/src/api/routes/userDeletion.integration.test.ts new file mode 100644 index 00000000..7cc143ad --- /dev/null +++ b/apps/server/src/api/routes/userDeletion.integration.test.ts @@ -0,0 +1,171 @@ +import crypto from 'crypto'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, afterEach, describe, expect, it } from 'vitest'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { registerMiscRoutes } from './misc.js'; +import { setAuthResolution } from '../utils/authState.js'; +import { getJwtSecret } from '../utils/authHelpers.js'; +import { hashSessionToken, validateSessionToken } from '../utils/sessionAuth.js'; + +/** + * Regression tests for member removal and account deletion (Q-ACC-1..3) + * against a REAL PostgreSQL database with all migrations applied. + * + * No Prisma double on purpose: the defect lived in foreign-key rules + * (`Session` and `EmailVerification` reference `User` with ON DELETE RESTRICT) + * that only a real database enforces. The old code deleted every membership, + * swallowed the errors and then failed on `user.delete`, so the admin saw an + * error while the user had already vanished from every tenant. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('userDeletion.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; + +/** Same harness as misc.users.test.ts, but backed by the real client. */ +function makeApp() { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + const rawUser = req.headers['x-user']; + const userId = typeof rawUser === 'string' ? rawUser : null; + setAuthResolution(req, { + auth: userId ? { userId, sessionId: `sess-${userId}`, tokenHash: `hash-${userId}` } : null, + }); + const rawTenant = req.headers['x-tenant']; + if (typeof rawTenant === 'string') req.tenant = { id: rawTenant, slug: rawTenant, name: rawTenant } as never; + next(); + }); + registerMiscRoutes(app, prisma); + return app; +} + +async function createTenant(): Promise { + const slug = `qacc-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser(memberships: Array<{ tenantId: string; role: Role }>): Promise { + const user = await prisma.user.create({ data: { email: `qacc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + for (const m of memberships) { + await prisma.membership.create({ data: { userId: user.id, tenantId: m.tenantId, role: m.role } }); + } + return user.id; +} + +/** A real login footprint: a signed session token with its Session row, plus a pending email verification. */ +async function addLoginFootprint(userId: string, tenantId: string): Promise { + const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + await prisma.emailVerification.create({ + data: { + userId, + token: crypto.randomUUID(), + email: `pending-${crypto.randomUUID()}@example.test`, + expiresAt: new Date(Date.now() + 3_600_000), + }, + }); + return token; +} + +async function rowCounts(userId: string) { + const [users, memberships, sessions, verifications] = await Promise.all([ + prisma.user.count({ where: { id: userId } }), + prisma.membership.count({ where: { userId } }), + prisma.session.count({ where: { userId } }), + prisma.emailVerification.count({ where: { userId } }), + ]); + return { users, memberships, sessions, verifications }; +} + +afterEach(async () => { + const ids = userIds.splice(0); + await prisma.session.deleteMany({ where: { userId: { in: ids } } }); + await prisma.emailVerification.deleteMany({ where: { userId: { in: ids } } }); + await prisma.membership.deleteMany({ where: { userId: { in: ids } } }); + await prisma.user.deleteMany({ where: { id: { in: ids } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds.splice(0) } } }); +}); + +afterAll(async () => { + await prisma.$disconnect(); +}); + +describe('DELETE /users/:id — member removal (real database)', () => { + it('removes a single-tenant member with sessions and a pending verification completely', async () => { + const tenant = await createTenant(); + const admin = await createUser([{ tenantId: tenant, role: 'admin' }]); + const member = await createUser([{ tenantId: tenant, role: 'member' }]); + const token = await addLoginFootprint(member, tenant); + + const res = await request(makeApp()).delete(`/users/${member}`).set('x-user', admin).set('x-tenant', tenant); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ ok: true, accountDeleted: true }); + expect(await rowCounts(member)).toEqual({ users: 0, memberships: 0, sessions: 0, verifications: 0 }); + expect(await validateSessionToken(prisma, token)).toBeNull(); + }); + + it('removes only the membership in the admin’s tenant when the user belongs to another tenant too', async () => { + const tenantA = await createTenant(); + const tenantB = await createTenant(); + const admin = await createUser([{ tenantId: tenantA, role: 'admin' }]); + const member = await createUser([ + { tenantId: tenantA, role: 'member' }, + { tenantId: tenantB, role: 'member' }, + ]); + const token = await addLoginFootprint(member, tenantA); + + const res = await request(makeApp()).delete(`/users/${member}`).set('x-user', admin).set('x-tenant', tenantA); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ ok: true, accountDeleted: false }); + expect(await prisma.membership.count({ where: { userId: member, tenantId: tenantA } })).toBe(0); + expect(await prisma.membership.count({ where: { userId: member, tenantId: tenantB } })).toBe(1); + expect(await prisma.user.count({ where: { id: member } })).toBe(1); + expect(await prisma.session.count({ where: { userId: member } })).toBe(0); + expect(await validateSessionToken(prisma, token)).toBeNull(); + }); + + it('refuses an admin removing an owner and changes nothing', async () => { + const tenant = await createTenant(); + const admin = await createUser([{ tenantId: tenant, role: 'admin' }]); + const owner = await createUser([{ tenantId: tenant, role: 'owner' }]); + await addLoginFootprint(owner, tenant); + + const res = await request(makeApp()).delete(`/users/${owner}`).set('x-user', admin).set('x-tenant', tenant); + + expect(res.status).toBe(403); + expect(await rowCounts(owner)).toEqual({ users: 1, memberships: 1, sessions: 1, verifications: 1 }); + }); +}); + +describe('DELETE /users/me — self-deletion (real database)', () => { + it('deletes the account with its sessions and pending verification', async () => { + const tenant = await createTenant(); + await createUser([{ tenantId: tenant, role: 'owner' }]); + const member = await createUser([{ tenantId: tenant, role: 'member' }]); + const token = await addLoginFootprint(member, tenant); + + const res = await request(makeApp()).delete('/users/me').set('x-user', member).set('x-tenant', tenant); + + expect(res.status).toBe(200); + expect(res.body.ok).toBe(true); + expect(await rowCounts(member)).toEqual({ users: 0, memberships: 0, sessions: 0, verifications: 0 }); + expect(await validateSessionToken(prisma, token)).toBeNull(); + }); +}); diff --git a/apps/server/src/api/utils/authHelpers.ts b/apps/server/src/api/utils/authHelpers.ts index f6ad9e7c..0e86447f 100644 --- a/apps/server/src/api/utils/authHelpers.ts +++ b/apps/server/src/api/utils/authHelpers.ts @@ -1,8 +1,11 @@ import type express from 'express'; import type { PrismaClient, Tenant } from '../../generated/prisma/index.js'; import jwt from 'jsonwebtoken'; +import { isTenantAccessDenied } from './tenantAccessState.js'; +import { isInternalOwner } from './tenantMembership.js'; import crypto from 'crypto'; import { logger } from '../../logger.js'; +import { getRequestRouteTemplate } from './requestRoute.js'; import { type AuthTokenPayload } from '../../types/authShapes.js'; import { getAuthResolution } from './authState.js'; @@ -81,12 +84,13 @@ export function setAuthCookie(res: express.Response, token: string) { * payload shape — see AGENTS.md "no swallowed errors" / avoid drift between * auth paths. */ -export function verifyAuthJwt(raw: string): { userId: string; tenantId?: string } | null { +export function verifyAuthJwt(raw: string): { userId: string; tenantId?: string; verificationOnly?: true } | null { try { const payload = jwt.verify(raw, getJwtSecret()) as AuthTokenPayload; if (typeof payload.sub !== 'string') return null; const tenantId = typeof payload.tid === 'string' ? payload.tid : undefined; - return { userId: payload.sub, tenantId }; + if (payload.scope !== undefined && payload.scope !== 'email_verification') return null; + return { userId: payload.sub, tenantId, ...(payload.scope === 'email_verification' ? { verificationOnly: true as const } : {}) }; } catch { return null; } @@ -113,15 +117,22 @@ export function requireAuth(req: express.Request): { userId: string; tenantId?: if (!resolution) { logger.error({ event: 'auth.session_middleware_missing', - path: typeof req.path === 'string' ? req.path : undefined, + path: getRequestRouteTemplate(req), }); return null; } const { auth } = resolution; - if (!auth) return null; + if (!auth || auth.verificationOnly) return null; return { userId: auth.userId, tenantId: auth.tenantId }; } +/** Explicit opt-in for the proof/acceptance endpoints only. */ +export function requireVerificationAuth(req: express.Request) { + const auth = getAuthResolution(req)?.auth; + if (!auth) return null; + return { userId: auth.userId, tenantId: auth.tenantId, verificationOnly: auth.verificationOnly === true }; +} + export async function requireApiToken(req: express.Request, prisma: PrismaClient): Promise<{ userId: string } | null> { const authz = req.headers['authorization']?.toString(); if (!authz || !authz.startsWith('Bearer ')) return null; @@ -166,12 +177,12 @@ export async function requireMembership( req: express.Request, userId: string, prisma: PrismaClient, -): Promise<{ role: string } | null> { +): Promise<{ role: string; expiresAt: Date | null } | null> { const tenant = getTenantFromReq(req); if (!tenant) return null; const m = await prisma.membership.findUnique({ where: { tenantId_userId: { tenantId: tenant.id, userId } } }); - if (!m) return null; - return { role: m.role }; + if (!m || m.inviteVerificationRequired || (m.expiresAt && m.expiresAt <= new Date())) return null; + return { role: m.role, expiresAt: m.expiresAt }; } export async function requireSuperAdmin( @@ -191,13 +202,7 @@ export async function requireInternalOwner( prisma: PrismaClient, ): Promise { try { - const internal = await prisma.tenant.findUnique({ where: { slug: 'internal' } }); - if (!internal) return false; - const member = await prisma.membership.findUnique({ - where: { tenantId_userId: { tenantId: internal.id, userId } }, - }); - if (!member) return false; - return member.role === 'owner'; + return await isInternalOwner(prisma, userId); } catch { return false; } @@ -259,6 +264,10 @@ export function createRequireTenantAdmin( return; } const tenant = getTenantFromReq(req); + if (!tenant && isTenantAccessDenied(req)) { + res.status(403).json({ error: 'forbidden' }); + return; + } if (!tenant) { res.status(400).json({ error: 'tenant_required' }); return; diff --git a/apps/server/src/api/utils/authState.ts b/apps/server/src/api/utils/authState.ts index b618986d..6b31f72a 100644 --- a/apps/server/src/api/utils/authState.ts +++ b/apps/server/src/api/utils/authState.ts @@ -18,6 +18,8 @@ import type express from 'express'; /** Identity carried by a request whose token maps to a live session row. */ export interface ResolvedAuth { userId: string; + /** Restricted proof/acceptance session; never usable as ordinary authentication. */ + verificationOnly?: true; tenantId?: string; /** Id of the backing `Session` row — the authority for this request. */ sessionId: string; diff --git a/apps/server/src/api/utils/broadcast.ts b/apps/server/src/api/utils/broadcast.ts index 90709c96..08b270df 100644 --- a/apps/server/src/api/utils/broadcast.ts +++ b/apps/server/src/api/utils/broadcast.ts @@ -1,5 +1,9 @@ +import crypto from 'node:crypto'; import { logger } from '../../logger.js'; +/** Process identity: rooms skip revocation messages they already applied locally. */ +export const PROCESS_ID = crypto.randomUUID(); + // `gameServer` and `activeWorldRooms` are declared once, in types/global.d.ts. // This file used to re-declare both with shapes of its own; the duplicate is a // TS2403 that `skipLibCheck` swallows, and the two descriptions had already @@ -33,3 +37,53 @@ export function broadcastSpawnUpdate(mapId: string, spawn: { x: number; y: numbe } catch {} } } + +/** Presence channel on which every world room learns that a user lost access. */ +export const ACCESS_REVOKED_CHANNEL = 'access_revoked'; + +/** + * Tell every world room, in any process, that `userId` lost access (member + * removed, account deleted, guest revoked), so the user's open world + * connections end at once. Each room decides per session, by its verified + * tenant, which clients must leave. Call it only after the change is + * committed. The rooms' periodic access sweep (rooms/lifecycle/guestExpiry.ts) + * stays the safety net when a message is lost. + * + * Local rooms revoke first, synchronously: even when the publish below + * fails, this process no longer keeps a revoked session. + */ +export function broadcastAccessRevoked(userId: string): void { + for (const room of global.activeWorldRooms ?? []) { + try { + room.revokeAccess(userId); + } catch (e: unknown) { + logger.warn({ + event: 'world.access_revoked_local_failed', + userId, + error: e instanceof Error ? e.message : String(e), + }); + } + } + const presence = global.gameServer?.presence; + if (!presence) { + logger.debug('[Broadcast] no game server presence, access revocation not published', { userId }); + return; + } + const logFailure = (e: unknown): void => { + logger.warn({ + event: 'world.access_revoked_publish_failed', + userId, + error: e instanceof Error ? e.message : String(e), + }); + }; + // Runs after a committed change and must never throw. The in-process + // LocalPresence publishes synchronously (it returns itself), the Redis + // presence returns a promise; Promise.resolve covers both. The origin + // marks messages this process already applied above, so its rooms skip + // them instead of revoking twice. + try { + Promise.resolve(presence.publish(ACCESS_REVOKED_CHANNEL, { userId, origin: PROCESS_ID })).catch(logFailure); + } catch (e: unknown) { + logFailure(e); + } +} diff --git a/apps/server/src/api/utils/emailProof.migration.integration.test.ts b/apps/server/src/api/utils/emailProof.migration.integration.test.ts new file mode 100644 index 00000000..018f574d --- /dev/null +++ b/apps/server/src/api/utils/emailProof.migration.integration.test.ts @@ -0,0 +1,164 @@ +import crypto from 'node:crypto'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { getJwtSecret } from './authHelpers.js'; +import { createSessionAuthMiddleware, hashSessionToken } from './sessionAuth.js'; +import { createTenantAccessMiddleware } from '../middleware/tenantAccess.js'; +import { resolveTenantBySlug } from '../../tenancy.js'; +import { registerAuthRoutes } from '../routes/auth.js'; +import { readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { Client } from 'pg'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { PrismaClient } from '../../generated/prisma/index.js'; +import { afterAll, expect, it } from 'vitest'; +import { hasTenantAccess } from './tenantMembership.js'; + +// Apply the complete real migration history in a private schema. +const rawUrl = process.env.DATABASE_URL; +if (!rawUrl) throw new Error('The assigned test database is missing.'); +const url = new URL(rawUrl); +if (url.hostname !== '127.0.0.1' || url.port !== '35440') throw new Error('Migration tests require 127.0.0.1:35440.'); +const schema = `email_proof_migration_fixture_${crypto.randomBytes(10).toString('hex')}`; +const client = new Client({ connectionString: rawUrl }); +let prisma: PrismaClient | undefined; +let connected = false; +let created = false; +afterAll(async () => { + await prisma?.$disconnect(); + try { + if (created) await client.query(`DROP SCHEMA "${schema}" CASCADE`); + } finally { + if (connected) await client.end(); + } +}); + +it('marks only proven unverified invitation memberships and preserves identifiers and roles during migration', async () => { + await client.connect(); + connected = true; + await client.query(`CREATE SCHEMA "${schema}"`); + created = true; + await client.query(`SET search_path TO "${schema}"`); + const directory = path.resolve('prisma/migrations'); + const migrations = (await readdir(directory, { withFileTypes: true })) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort(); + const first = '20261109080000_add_email_verification_intents'; + const second = '20261109080001_gate_unverified_invite_memberships'; + if (!migrations.includes(first) || !migrations.includes(second)) + throw new Error('Required email-proof migrations are missing.'); + for (const migration of migrations.filter((name) => name < first)) { + const sql = await readFile(path.join(directory, migration, 'migration.sql'), 'utf8'); + // The bootstrap names public explicitly; all table and type statements + // remain unchanged and run in the private schema through search_path. + await client.query(sql.replace('CREATE SCHEMA IF NOT EXISTS "public";', '')); + } + const ids = Array.from({ length: 12 }, () => `c${crypto.randomBytes(12).toString('hex')}`); + const [ + tenant, + other, + unverified, + verified, + independent, + memberA, + memberB, + memberC, + memberOther, + inviteA, + inviteB, + oldProof, + ] = ids; + await client.query('INSERT INTO "Tenant" ("id","slug","name","updatedAt") VALUES ($1,$1,$1,now()),($2,$2,$2,now())', [ + tenant, + other, + ]); + await client.query( + `INSERT INTO "User" ("id","email","emailVerifiedAt","updatedAt") VALUES ($1,$1||'@example.test',NULL,now()),($2,$2||'@example.test',now(),now()),($3,$3||'@example.test',NULL,now())`, + [unverified, verified, independent], + ); + await client.query( + `INSERT INTO "Membership" ("id","tenantId","userId","role","updatedAt") VALUES + ($1,$5,$7,'admin',now()),($2,$5,$8,'owner',now()),($3,$5,$9,'member',now()),($4,$6,$7,'member',now())`, + [memberA, memberB, memberC, memberOther, tenant, other, unverified, verified, independent], + ); + await client.query( + `INSERT INTO "Invite" ("id","code","tenantId","email","usedAt","usedById") VALUES + ($1,$6,$3,$4||'@example.test',now(),$4),($2,$7,$3,$5||'@example.test',now(),$5)`, + [ + inviteA, + inviteB, + tenant, + unverified, + verified, + crypto.randomBytes(12).toString('hex'), + crypto.randomBytes(12).toString('hex'), + ], + ); + await client.query( + 'INSERT INTO "EmailVerification" ("id","token","userId","email","expiresAt") VALUES ($1,$1,$2,$2||\'@example.test\',now()+interval \'1 day\')', + [oldProof, unverified], + ); + await client.query(await readFile(path.join(directory, first, 'migration.sql'), 'utf8')); + await client.query(await readFile(path.join(directory, second, 'migration.sql'), 'utf8')); + const members = await client.query( + 'SELECT "id","role","inviteVerificationRequired" AS blocked FROM "Membership" ORDER BY "id"', + ); + expect(members.rows).toHaveLength(4); + expect(members.rows.find((row) => row.id === memberA)).toEqual({ id: memberA, role: 'admin', blocked: true }); + expect(members.rows.find((row) => row.id === memberB)).toEqual({ id: memberB, role: 'owner', blocked: false }); + expect(members.rows.filter((row) => row.id !== memberA).every((row) => row.blocked === false)).toBe(true); + const expired = await client.query( + 'SELECT "expiresAt"<=now() AS expired, "readyAt" IS NULL AS unready FROM "EmailVerification" WHERE "id"=$1', + [oldProof], + ); + expect(expired.rows[0]).toEqual({ expired: true, unready: true }); + prisma = new PrismaClient({ + adapter: new PrismaPg({ connectionString: rawUrl, options: `-c search_path=${schema}` }, { schema }), + }); + expect(await hasTenantAccess(prisma, unverified, tenant)).toBe(false); + expect(await hasTenantAccess(prisma, unverified, other)).toBe(true); + expect(await hasTenantAccess(prisma, verified, tenant)).toBe(true); + expect(await hasTenantAccess(prisma, independent, tenant)).toBe(true); + const migrated = prisma; + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + void resolveTenantBySlug(migrated, req) + .then((tenant) => { + req.tenant = tenant ?? undefined; + req.tenantId = tenant?.id; + next(); + }) + .catch(next); + }); + app.use(createSessionAuthMiddleware(migrated)); + app.use(createTenantAccessMiddleware(migrated)); + registerAuthRoutes(app, migrated); + const rawSession = jwt.sign({ sub: unverified, tid: tenant, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await migrated.session.create({ + data: { userId: unverified, tokenHash: hashSessionToken(rawSession), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + const blockedHttp = await request(app) + .get('/auth/me') + .set('X-Tenant', tenant) + .set('Authorization', `Bearer ${rawSession}`); + expect(blockedHttp.status).toBe(409); + expect(blockedHttp.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + // Cascading removes only the associated intent and does not prevent revocation. + await prisma.emailVerification.create({ + data: { + token: crypto.randomBytes(32).toString('hex'), + userId: unverified, + email: `${unverified}@example.test`, + purpose: 'invite', + inviteId: inviteA, + expiresAt: new Date(Date.now() + 60_000), + }, + }); + await prisma.invite.delete({ where: { id: inviteA } }); + expect(await prisma.emailVerification.count({ where: { inviteId: inviteA } })).toBe(0); +}, 120_000); diff --git a/apps/server/src/api/utils/emailProof.ts b/apps/server/src/api/utils/emailProof.ts new file mode 100644 index 00000000..5773e28c --- /dev/null +++ b/apps/server/src/api/utils/emailProof.ts @@ -0,0 +1,156 @@ +import crypto from 'crypto'; +import type { PrismaClient, Prisma } from '../../generated/prisma/index.js'; +import { getEmailModule } from '../../emailLoader.js'; +import { buildPublicWebLink, publicWebBase } from './publicLinks.js'; +import { normalizeEmailForStorage } from './authHelpers.js'; +import { inviteEmailMatches, consumeInvite } from './inviteLifecycle.js'; + +export type EmailProofPurpose = 'verify' | 'invite' | 'email_change'; +export type EmailProofOutcome = + | { status: 'user_not_found' | 'already_verified' | 'no_public_base_url' | 'delivery_unavailable' | 'binding_required' } + | { status: 'throttled'; retryAfter: number } + | { status: 'issued'; sent: true }; + +const TTL_MS = 24 * 60 * 60 * 1000; +const COOLDOWN_MS = 2 * 60 * 1000; +const DELIVERY_PROVIDERS = new Set(['oss-smtp', 'ee-smtp', 'ee-resend']); + +export async function deliveringEmailModule() { + const mod = await getEmailModule(); + return mod && DELIVERY_PROVIDERS.has(mod.providerName ?? '') ? mod : null; +} + +export function hashEmailProof(token: string): string { + return crypto.createHash('sha256').update(token).digest('hex'); +} + +/** Serialize issuance and consumption across address round trips and concurrent changes. */ +export async function lockEmailAccount(tx: Prisma.TransactionClient, userId: string): Promise { + await tx.$queryRaw`SELECT "id" FROM "User" WHERE "id" = ${userId} FOR UPDATE`; +} + +async function prepareEmailProof( + tx: Prisma.TransactionClient, + input: { userId: string; purpose: EmailProofPurpose; inviteId?: string; email?: string; token: string }, +) { + const { userId, purpose, inviteId, token } = input; + await lockEmailAccount(tx, userId); + const user = await tx.user.findUnique({ where: { id: userId } }); + if (!user) return { status: 'user_not_found' as const }; + if (purpose === 'verify' && user.emailVerifiedAt) return { status: 'already_verified' as const }; + const email = normalizeEmailForStorage(input.email ?? user.email); + if (purpose === 'invite') { + const invite = inviteId ? await tx.invite.findUnique({ where: { id: inviteId } }) : null; + if (!invite || !inviteEmailMatches(invite.email, user.email)) return { status: 'binding_required' as const }; + } + const recent = await tx.emailVerification.findFirst({ + where: { userId, purpose, inviteId: inviteId ?? null, email, usedAt: null, expiresAt: { gt: new Date() }, + createdAt: { gt: new Date(Date.now() - COOLDOWN_MS) } }, + orderBy: { createdAt: 'desc' }, + }); + if (recent) return { status: 'throttled' as const, + retryAfter: Math.max(1, Math.ceil((recent.createdAt.getTime() + COOLDOWN_MS - Date.now()) / 1000)) }; + if (purpose === 'email_change') { + await tx.emailVerification.updateMany({ where: { userId, purpose, usedAt: null }, data: { usedAt: new Date() } }); + } + const intent = await tx.emailVerification.create({ data: { + token, userId, purpose, inviteId, email, sourceEmail: user.email, expiresAt: new Date(Date.now() + TTL_MS), + } }); + return { status: 'prepared' as const, intent, user }; +} + +export async function issueEmailProof(params: { + prisma: PrismaClient; + userId: string; + purpose: EmailProofPurpose; + inviteId?: string; + email?: string; +}): Promise { + const { prisma, userId, purpose, inviteId } = params; + const mail = await deliveringEmailModule(); + if (!mail) return { status: 'delivery_unavailable' }; + const base = publicWebBase(); + if (!base) return { status: 'no_public_base_url' }; + const rawToken = crypto.randomBytes(32).toString('hex'); + const token = hashEmailProof(rawToken); + const prepared = await prisma.$transaction((tx) => + prepareEmailProof(tx, { userId, purpose, inviteId, email: params.email, token }), + ); + if (prepared.status !== 'prepared') return prepared; + const { intent, user } = prepared; + let sent = false; + try { + sent = await mail.sendVerify({ to: intent.email, name: user.name ?? '', + verifyUrl: buildPublicWebLink(base, `verify?token=${rawToken}`), + locale: user.locale === 'en' ? 'en' : 'de' }); + if (sent && purpose === 'email_change') { + const text = 'A change of your email address was requested. Your current address remains active until confirmation. If this was not you, change your password.'; + sent = await mail.sendRaw({ to: user.email, subject: 'Email change requested', + text, html: `

${text}

` }); + } + } catch { + // Provider errors may contain recipient or message data; do not log them. + sent = false; + } + if (!sent) { + await prisma.emailVerification.updateMany({ where: { id: intent.id, readyAt: null }, data: { expiresAt: new Date() } }); + return { status: 'delivery_unavailable' }; + } + const ready = await prisma.emailVerification.updateMany({ + where: { id: intent.id, usedAt: null, user: { email: user.email } }, data: { readyAt: new Date() }, + }); + return ready.count === 1 ? { status: 'issued', sent: true } : { status: 'binding_required' }; +} + +export class EmailProofInvalid extends Error {} + +/** Verify proof, bind the address and consume the invitation in one transaction. */ +export async function completeEmailProof(prisma: PrismaClient, rawToken: string) { + const token = hashEmailProof(rawToken); + return prisma.$transaction(async (tx) => { + const initial = await tx.emailVerification.findUnique({ where: { token } }); + if (!initial) throw new EmailProofInvalid(); + await lockEmailAccount(tx, initial.userId); + const proof = await tx.emailVerification.findUnique({ where: { token } }); + const user = await tx.user.findUnique({ where: { id: initial.userId } }); + const now = new Date(); + if (!proof || !user || proof.usedAt || !proof.readyAt || proof.expiresAt <= now || + proof.sourceEmail !== user.email || (proof.purpose !== 'email_change' && !inviteEmailMatches(proof.email, user.email))) { + throw new EmailProofInvalid(); + } + let tenantSlug: string | undefined; + if (proof.purpose === 'invite') { + if (!proof.inviteId) throw new EmailProofInvalid(); + await tx.$queryRaw`SELECT "id" FROM "Invite" WHERE "id" = ${proof.inviteId} FOR UPDATE`; + const invite = await tx.invite.findUnique({ where: { id: proof.inviteId }, include: { tenant: true } }); + if (!invite || !inviteEmailMatches(invite.email, proof.email)) throw new EmailProofInvalid(); + const key = { tenantId: invite.tenantId, userId: user.id }; + const member = await tx.membership.findUnique({ where: { tenantId_userId: key } }); + if (invite.usedAt) { + if (invite.usedById !== user.id || !member?.inviteVerificationRequired) throw new EmailProofInvalid(); + await tx.membership.update({ where: { tenantId_userId: key }, data: { inviteVerificationRequired: false } }); + } else { + if (!(await consumeInvite(tx, invite.code, user.id, now))) throw new EmailProofInvalid(); + await tx.membership.upsert({ where: { tenantId_userId: key }, + create: { ...key, role: invite.role }, + update: member?.inviteVerificationRequired ? { role: invite.role, inviteVerificationRequired: false } : {} }); + } + tenantSlug = invite.tenant.slug; + } else if (proof.purpose !== 'verify' && proof.purpose !== 'email_change') { + throw new EmailProofInvalid(); + } + if (proof.purpose === 'email_change') { + const occupied = await tx.user.findFirst({ where: { id: { not: user.id }, email: { equals: proof.email, mode: 'insensitive' } }, select: { id: true } }); + if (occupied) throw new EmailProofInvalid(); + } + const consumed = await tx.emailVerification.updateMany({ + where: { id: proof.id, usedAt: null, readyAt: { not: null }, expiresAt: { gt: now } }, data: { usedAt: now }, + }); + if (consumed.count !== 1) throw new EmailProofInvalid(); + await tx.user.update({ where: { id: user.id }, data: { + ...(proof.purpose === 'email_change' ? { email: proof.email } : {}), emailVerifiedAt: now, + } }); + await tx.emailVerification.updateMany({ where: { userId: user.id, usedAt: null }, data: { usedAt: now } }); + return { purpose: proof.purpose, tenantSlug, nextAction: 'login' as const }; + }); +} diff --git a/apps/server/src/api/utils/inviteLifecycle.test.ts b/apps/server/src/api/utils/inviteLifecycle.test.ts new file mode 100644 index 00000000..78782b07 --- /dev/null +++ b/apps/server/src/api/utils/inviteLifecycle.test.ts @@ -0,0 +1,76 @@ +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const delivery = vi.hoisted(() => ({ context: undefined as Record | undefined })); + +vi.mock('../../emailLoader.js', () => ({ + sendIfAvailable: vi.fn((_send: unknown, _event: string, context: Record) => { + delivery.context = context; + return Promise.resolve(false); + }), +})); + +import { sendIfAvailable } from '../../emailLoader.js'; +import { + deriveInviteStatus, + deliverInvite, + inviteEmailMatches, + inviteExpiry, + INVITE_NOT_DELIVERED, + maskInviteEmail, +} from './inviteLifecycle.js'; + +const now = new Date('2026-11-06T12:00:00.000Z'); + +describe('inviteLifecycle', () => { + beforeEach(() => { + delivery.context = undefined; + vi.mocked(sendIfAvailable).mockClear(); + }); + + it('sets a seven-day expiry and derives pending, expired, and accepted status', () => { + expect(inviteExpiry(now)).toEqual(new Date('2026-11-13T12:00:00.000Z')); + expect(deriveInviteStatus({ usedAt: null, expiresAt: inviteExpiry(now) }, now)).toBe('pending'); + expect(deriveInviteStatus({ usedAt: null, expiresAt: now }, now)).toBe('expired'); + expect(deriveInviteStatus({ usedAt: null, expiresAt: null }, now)).toBe('expired'); + expect(deriveInviteStatus({ usedAt: now, expiresAt: inviteExpiry(now) }, now)).toBe('accepted'); + }); + + it('masks an email address and returns null for missing or malformed input', () => { + expect(maskInviteEmail('anna@example.test')).toBe('a***@example.test'); + expect(maskInviteEmail('malformed')).toBeNull(); + expect(maskInviteEmail(null)).toBeNull(); + }); + + it('matches normalized addresses and rejects an invite without a bound email', () => { + expect(inviteEmailMatches(' Test+invite@Example.test ', 'test@example.test')).toBe(true); + expect(inviteEmailMatches(null, 'test@example.test')).toBe(false); + }); + + it('records a failed delivery without claiming it was sent or logging its code', async () => { + const invite = { id: 'invite-id', email: 'person@example.test', tenantId: 'tenant-id' }; + const prisma = { + user: { findUnique: vi.fn().mockResolvedValue({ name: 'Inviter', email: 'inviter@example.test', locale: 'en' }) }, + invite: { update: vi.fn().mockResolvedValue(undefined) }, + } as PrismaClient; + + await expect( + deliverInvite(prisma, { + invite, + inviterUserId: 'inviter-id', + tenantName: 'Example Team', + inviteUrl: 'https://app.example.test/#/?invite=invite-code', + }), + ).resolves.toBe(false); + + expect(vi.mocked(sendIfAvailable)).toHaveBeenCalledWith(expect.any(Function), 'invite.email_failed', { + tenantId: invite.tenantId, + inviteId: invite.id, + }); + expect(delivery.context).toEqual({ tenantId: invite.tenantId, inviteId: invite.id }); + expect(prisma.invite.update).toHaveBeenCalledWith({ + where: { id: invite.id }, + data: { lastSendError: INVITE_NOT_DELIVERED }, + }); + }); +}); diff --git a/apps/server/src/api/utils/inviteLifecycle.ts b/apps/server/src/api/utils/inviteLifecycle.ts new file mode 100644 index 00000000..88ef7b62 --- /dev/null +++ b/apps/server/src/api/utils/inviteLifecycle.ts @@ -0,0 +1,142 @@ +import crypto from 'crypto'; +import { PrismaClient, Prisma } from '../../generated/prisma/index.js'; +import type { Role } from '../../generated/prisma/index.js'; +import { normalizeEmailForMatching, normalizeEmailForStorage } from './authHelpers.js'; +import { sendIfAvailable } from '../../emailLoader.js'; + +export const INVITE_TTL_DAYS = 7; +export type InviteStatus = 'pending' | 'accepted' | 'expired'; +export const INVITE_NOT_DELIVERED = 'not_delivered'; + +export function inviteExpiry(now = new Date()): Date { + return new Date(now.getTime() + INVITE_TTL_DAYS * 24 * 60 * 60 * 1000); +} + +export function deriveInviteStatus( + invite: { usedAt: Date | null; expiresAt: Date | null }, + now = new Date(), +): InviteStatus { + if (invite.usedAt) return 'accepted'; + if (!invite.expiresAt || invite.expiresAt <= now) return 'expired'; + return 'pending'; +} + +export function maskInviteEmail(email: string | null): string | null { + if (email === null) return null; + const atIndex = email.indexOf('@'); + if (atIndex < 0) return null; + return `${email.slice(0, 1)}***${email.slice(atIndex)}`; +} + +export function inviteEmailMatches(inviteEmail: string | null, accountEmail: string): boolean { + return inviteEmail !== null && normalizeEmailForMatching(inviteEmail) === normalizeEmailForMatching(accountEmail); +} + +export async function consumeInvite( + tx: Prisma.TransactionClient, + code: string, + userId: string, + now: Date, +): Promise { + const result = await tx.invite.updateMany({ + where: { code, usedAt: null, expiresAt: { gt: now } }, + data: { usedAt: now, usedById: userId }, + }); + return result.count === 1; +} + +export async function registerInvitedUser( + prisma: PrismaClient, + args: { + code: string; + email: string; + name: string | undefined; + passwordHash: string; + role: Role; + tenantId: string; + now: Date; + }, +) { + return prisma.$transaction(async (tx) => { + const user = await tx.user.create({ + data: { email: normalizeEmailForStorage(args.email), name: args.name, passwordHash: args.passwordHash }, + }); + const invite = await tx.invite.findUnique({ where: { code: args.code } }); + if (!invite || deriveInviteStatus(invite, args.now) !== 'pending' || !inviteEmailMatches(invite.email, user.email)) { + throw new InviteUnavailableError(); + } + // Create the binding atomically with the account. This record cannot be redeemed; + // the subsequent delivery creates the actual mailbox proof. + await tx.emailVerification.create({ data: { + userId: user.id, email: user.email, sourceEmail: user.email, purpose: 'invite', inviteId: invite.id, + token: crypto.createHash('sha256').update(crypto.randomBytes(32)).digest('hex'), expiresAt: args.now, + } }); + return user; + }); +} + +export class InviteUnavailableError extends Error { + constructor() { + super('Invite is unavailable'); + this.name = 'InviteUnavailableError'; + } +} + +export async function deliverInvite( + prisma: PrismaClient, + args: { + invite: { id: string; email: string | null; tenantId: string }; + inviterUserId: string; + tenantName: string; + inviteUrl: string; + }, +): Promise { + let emailSent = false; + if (args.invite.email) { + const inviter = await prisma.user.findUnique({ + where: { id: args.inviterUserId }, + select: { name: true, email: true, locale: true }, + }); + const inviterName = inviter?.name || inviter?.email || 'Someone'; + // Locale chain: request locale (not exposed by /auth/invite), inviter.locale, + // then MAIL_DEFAULT_LOCALE / 'de' in the email resolver. The invitee is not + // a known user yet, so the inviter's UI locale is the best available signal. + const inviterLocale = inviter?.locale === 'en' ? 'en' : inviter?.locale === 'de' ? 'de' : undefined; + emailSent = await sendIfAvailable( + (mod) => + mod.sendInvite({ + to: args.invite.email!, + inviterName, + tenantName: args.tenantName, + inviteUrl: args.inviteUrl, + locale: inviterLocale, + }), + 'invite.email_failed', + { tenantId: args.invite.tenantId, inviteId: args.invite.id }, + ); + } + + if (emailSent) { + await prisma.invite.update({ + where: { id: args.invite.id }, + data: { lastSentAt: new Date(), sendCount: { increment: 1 }, lastSendError: null }, + }); + } else { + await prisma.invite.update({ where: { id: args.invite.id }, data: { lastSendError: INVITE_NOT_DELIVERED } }); + } + return emailSent; +} + +export function inviteResponse( + invite: { code: string; role: string; expiresAt: Date | null }, + inviteUrl: string, + emailSent: boolean, +) { + return { + code: invite.code, + role: invite.role, + inviteUrl, + expiresAt: invite.expiresAt?.toISOString() ?? null, + emailSent, + }; +} diff --git a/apps/server/src/api/utils/inviteVerification.ts b/apps/server/src/api/utils/inviteVerification.ts new file mode 100644 index 00000000..65c1a32f --- /dev/null +++ b/apps/server/src/api/utils/inviteVerification.ts @@ -0,0 +1,45 @@ +import type express from 'express'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { inviteEmailMatches } from './inviteLifecycle.js'; +import { issueEmailProof, type EmailProofOutcome } from './emailProof.js'; + +/** Find only an intent already bound to this account. */ +export async function pendingInviteForUser(prisma: PrismaClient, userId: string, tenantId?: string) { + const proof = await prisma.emailVerification.findFirst({ + where: { userId, purpose: 'invite', usedAt: null, invite: { + usedAt: null, expiresAt: { gt: new Date() }, ...(tenantId ? { tenantId } : {}), + } }, orderBy: { createdAt: 'desc' }, include: { invite: true }, + }); + const user = await prisma.user.findUnique({ where: { id: userId }, select: { email: true } }); + if (!user) return null; + if (proof?.invite && inviteEmailMatches(proof.invite.email, user.email)) return proof.invite; + const marked = await prisma.membership.findMany({ + where: { userId, inviteVerificationRequired: true, ...(tenantId ? { tenantId } : {}) }, select: { tenantId: true }, + }); + if (!marked.length) return null; + const oldInvites = await prisma.invite.findMany({ + where: { usedById: userId, usedAt: { not: null }, tenantId: { in: marked.map((m) => m.tenantId) } }, + orderBy: { createdAt: 'desc' }, + }); + return oldInvites.find((invite) => inviteEmailMatches(invite.email, user.email)) ?? null; +} + +export function verificationPending(res: express.Response, outcome?: EmailProofOutcome): void { + if (outcome?.status === 'throttled') res.setHeader('Retry-After', outcome.retryAfter); + const delivery = outcome?.status === 'issued' ? 'sent' + : outcome?.status === 'throttled' ? 'cooldown' : 'unavailable'; + res.status(409).json({ code: 'EMAIL_VERIFICATION_REQUIRED', + error: delivery === 'unavailable' + ? 'Confirm your email address. Confirmation email could not be delivered. Please contact an administrator.' + : 'Confirm your email address through the confirmation email before using this invitation.', + delivery, ...(outcome?.status === 'throttled' ? { retryAfter: outcome.retryAfter } : {}) }); +} + +export function verificationBindingRequired(res: express.Response): void { + res.status(409).json({ code: 'EMAIL_VERIFICATION_BINDING_REQUIRED', + error: 'This invitation does not match your current email address. Confirm the matching address change or request a new invitation bound to your address.' }); +} + +export async function beginInviteVerification(prisma: PrismaClient, userId: string, inviteId: string) { + return issueEmailProof({ prisma, userId, purpose: 'invite', inviteId }); +} diff --git a/apps/server/src/api/utils/mediaMime.ts b/apps/server/src/api/utils/mediaMime.ts new file mode 100644 index 00000000..bf7d26b6 --- /dev/null +++ b/apps/server/src/api/utils/mediaMime.ts @@ -0,0 +1,19 @@ +// Share the existing signatures between streaming limits and media handlers. + +const MAGIC_BYTES: ReadonlyArray<{ bytes: number[]; mime: string }> = [ + { bytes: [0x52, 0x49, 0x46, 0x46], mime: 'audio/wav' }, // RIFF (WAV) + { bytes: [0xff, 0xfb], mime: 'audio/mpeg' }, // MP3 frame sync + { bytes: [0xff, 0xf3], mime: 'audio/mpeg' }, + { bytes: [0xff, 0xf2], mime: 'audio/mpeg' }, + { bytes: [0x49, 0x44, 0x33], mime: 'audio/mpeg' }, // ID3 tag + { bytes: [0x4f, 0x67, 0x67, 0x53], mime: 'audio/ogg' }, // OGG + { bytes: [0x1a, 0x45, 0xdf, 0xa3], mime: 'video/webm' }, // WebM/MKV + { bytes: [0x00, 0x00, 0x00], mime: 'video/mp4' }, // MP4 (ftyp follows) +]; + +export function detectMimeFromMagic(buf: Buffer): string | null { + for (const { bytes, mime } of MAGIC_BYTES) { + if (bytes.every((b, i) => buf[i] === b)) return mime; + } + return null; +} diff --git a/apps/server/src/api/utils/passwordResetTokens.ts b/apps/server/src/api/utils/passwordResetTokens.ts index 3e31c45b..ec783ec1 100644 --- a/apps/server/src/api/utils/passwordResetTokens.ts +++ b/apps/server/src/api/utils/passwordResetTokens.ts @@ -78,6 +78,19 @@ export async function issuePasswordResetToken( return { token, expiresAt }; } +/** + * Drop a single unused reset token by its raw value. + * Used after a failed delivery so a token the admin never saw cannot stay live. + */ +export async function revokePasswordResetToken( + prisma: PrismaClient, + token: string, +): Promise { + await prisma.passwordReset.deleteMany({ + where: { token: hashResetToken(token), usedAt: null }, + }); +} + /** * Validate a raw token and burn it in the same step. Returns the owning user id, * or null when the token is unknown, already used, expired, or does not belong diff --git a/apps/server/src/api/utils/publicLinks.guard.test.ts b/apps/server/src/api/utils/publicLinks.guard.test.ts new file mode 100644 index 00000000..5e5eee42 --- /dev/null +++ b/apps/server/src/api/utils/publicLinks.guard.test.ts @@ -0,0 +1,35 @@ +import { readdir, readFile } from 'node:fs/promises'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +async function sourceFiles(directory: string): Promise { + const entries = await readdir(directory, { withFileTypes: true }); + const nested = await Promise.all( + entries.map(async (entry) => { + if (entry.isDirectory()) { + if (entry.name === 'generated') return []; + return sourceFiles(path.join(directory, entry.name)); + } + if (entry.name.endsWith('.test.ts')) return []; + return [path.join(directory, entry.name)]; + }), + ); + return nested.flat(); +} + +describe('public link source guard', () => { + it('keeps PUBLIC_BASE_URL and hash-link construction inside one resolver', async () => { + const srcRoot = path.resolve(process.cwd(), 'src'); + const files = await sourceFiles(srcRoot); + const matches = await Promise.all( + files.map(async (file) => { + const content = await readFile(file, 'utf8'); + return /process\.env\.PUBLIC_BASE_URL|\/#\//.test(content) + ? path.relative(srcRoot, file).split(path.sep).join('/') + : null; + }), + ); + + expect(matches.filter((file): file is string => file !== null).sort()).toEqual(['api/utils/publicLinks.ts']); + }); +}); diff --git a/apps/server/src/api/utils/publicLinks.test.ts b/apps/server/src/api/utils/publicLinks.test.ts new file mode 100644 index 00000000..f005a845 --- /dev/null +++ b/apps/server/src/api/utils/publicLinks.test.ts @@ -0,0 +1,128 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { buildPublicWebLink, publicBaseUrlProblem, publicWebBase, resolvePublicWebBase } from './publicLinks.js'; + +const originalPublicBaseUrl = process.env.PUBLIC_BASE_URL; +const originalAllowLoopback = process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK; +const originalBillingPublicUrl = process.env.BILLING_PUBLIC_URL; + +afterEach(() => { + if (originalPublicBaseUrl === undefined) delete process.env.PUBLIC_BASE_URL; + else process.env.PUBLIC_BASE_URL = originalPublicBaseUrl; + if (originalAllowLoopback === undefined) delete process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK; + else process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK = originalAllowLoopback; + if (originalBillingPublicUrl === undefined) delete process.env.BILLING_PUBLIC_URL; + else process.env.BILLING_PUBLIC_URL = originalBillingPublicUrl; +}); + +describe('resolvePublicWebBase', () => { + it('trims whitespace and trailing slashes while preserving the path', () => { + expect( + resolvePublicWebBase({ publicBaseUrl: ' https://public.example/work/room/// ', allowLoopback: false }), + ).toBe('https://public.example/work/room'); + }); + + it.each([undefined, '', ' \t ', 'public.example', 'ftp://public.example', 'tauri://localhost'])( + 'rejects an unusable base %s', + (publicBaseUrl) => { + expect(resolvePublicWebBase({ publicBaseUrl, allowLoopback: true })).toBeNull(); + }, + ); + + it.each(['http://tauri.localhost', 'https://desktop.tauri.localhost'])( + 'always rejects the Tauri host %s', + (publicBaseUrl) => { + expect(resolvePublicWebBase({ publicBaseUrl, allowLoopback: false })).toBeNull(); + expect(resolvePublicWebBase({ publicBaseUrl, allowLoopback: true })).toBeNull(); + }, + ); + + it.each([ + 'http://localhost:5173', + 'https://client.localhost', + 'http://127.0.0.1:4200', + 'http://127.42.5.3', + 'http://[::1]:4200', + 'http://0.0.0.0:4200', + ])('rejects loopback base %s without the explicit switch', (publicBaseUrl) => { + expect(resolvePublicWebBase({ publicBaseUrl, allowLoopback: false })).toBeNull(); + }); + + it.each([ + 'http://localhost:5173', + 'https://client.localhost', + 'http://127.0.0.1:4200', + 'http://127.42.5.3', + 'http://[::1]:4200', + 'http://0.0.0.0:4200', + ])('allows loopback base %s with the explicit switch', (publicBaseUrl) => { + expect(resolvePublicWebBase({ publicBaseUrl, allowLoopback: true })).toBe(publicBaseUrl); + }); +}); + +describe('publicBaseUrlProblem', () => { + it('reports a missing base', () => { + expect(publicBaseUrlProblem({ publicBaseUrl: undefined, allowLoopback: false })).toBe('missing'); + expect(publicBaseUrlProblem({ publicBaseUrl: ' ', allowLoopback: false })).toBe('missing'); + }); + + it.each([ + 'public.example', + 'ftp://public.example', + 'https://public.example/path?invite=code', + 'https://public.example/path#app', + 'https://public.example/path?', + 'https://public.example/path#', + ])('reports invalid base %s', (publicBaseUrl) => { + expect(publicBaseUrlProblem({ publicBaseUrl, allowLoopback: true })).toBe('invalid'); + }); + + it.each(['tauri://localhost', 'http://tauri.localhost', 'https://desktop.tauri.localhost'])( + 'reports native base %s', + (publicBaseUrl) => { + expect(publicBaseUrlProblem({ publicBaseUrl, allowLoopback: true })).toBe('native'); + }, + ); + + it.each(['http://localhost:5173', 'http://127.0.0.1:4200', 'http://[::1]:4200', 'http://0.0.0.0:4200'])( + 'reports loopback base %s when it is disabled', + (publicBaseUrl) => { + expect(publicBaseUrlProblem({ publicBaseUrl, allowLoopback: false })).toBe('loopback'); + }, + ); + + it('returns null for valid public bases and explicitly allowed loopback bases', () => { + expect(publicBaseUrlProblem({ publicBaseUrl: 'https://public.example/work', allowLoopback: false })).toBeNull(); + expect(publicBaseUrlProblem({ publicBaseUrl: 'http://localhost:42040', allowLoopback: true })).toBeNull(); + }); + + it.each(['https://public.example/path?query=1', 'https://public.example/path#section'])( + 'makes resolvePublicWebBase reject base %s', + (publicBaseUrl) => { + expect(resolvePublicWebBase({ publicBaseUrl, allowLoopback: true })).toBeNull(); + }, + ); +}); + +describe('public web link helpers', () => { + it('builds a hash route beneath the configured base path', () => { + expect(buildPublicWebLink('https://public.example/work', 'reset?token=abc')).toBe( + 'https://public.example/work/#/reset?token=abc', + ); + }); + + it('reads PUBLIC_BASE_URL and the loopback switch from the environment', () => { + process.env.PUBLIC_BASE_URL = 'http://localhost:42040/'; + process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK = 'true'; + process.env.BILLING_PUBLIC_URL = 'https://billing.example'; + + expect(publicWebBase()).toBe('http://localhost:42040'); + }); + + it('does not use BILLING_PUBLIC_URL when PUBLIC_BASE_URL is missing', () => { + delete process.env.PUBLIC_BASE_URL; + delete process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK; + process.env.BILLING_PUBLIC_URL = 'https://billing.example'; + + expect(publicWebBase()).toBeNull(); + }); +}); diff --git a/apps/server/src/api/utils/publicLinks.ts b/apps/server/src/api/utils/publicLinks.ts new file mode 100644 index 00000000..d1ce9d97 --- /dev/null +++ b/apps/server/src/api/utils/publicLinks.ts @@ -0,0 +1,75 @@ +import type express from 'express'; +import { logger } from '../../logger.js'; + +interface PublicWebBaseOptions { + publicBaseUrl?: string | undefined; + allowLoopback: boolean; +} + +function isLoopbackHost(hostname: string): boolean { + if (hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '0.0.0.0' || hostname === '[::1]') { + return true; + } + + const octets = hostname.split('.'); + return octets.length === 4 && octets[0] === '127' && octets.every((octet) => /^\d+$/.test(octet)); +} + +export function publicBaseUrlProblem({ + publicBaseUrl, + allowLoopback, +}: PublicWebBaseOptions): 'missing' | 'invalid' | 'native' | 'loopback' | null { + const value = publicBaseUrl?.trim(); + if (!value) return 'missing'; + + let parsed: URL; + try { + parsed = new URL(value); + } catch { + return 'invalid'; + } + + if (parsed.protocol === 'tauri:') return 'native'; + + const hostname = parsed.hostname.toLowerCase(); + if (hostname === 'tauri.localhost' || hostname.endsWith('.tauri.localhost')) return 'native'; + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return 'invalid'; + if (/[?#]/.test(value)) return 'invalid'; + if (!allowLoopback && isLoopbackHost(hostname)) return 'loopback'; + + return null; +} + +export function resolvePublicWebBase({ publicBaseUrl, allowLoopback }: PublicWebBaseOptions): string | null { + if (publicBaseUrlProblem({ publicBaseUrl, allowLoopback }) !== null) return null; + + return publicBaseUrl?.trim().replace(/\/+$/, '') ?? null; +} + +export function buildPublicWebLink(base: string, route: string): string { + return `${base}/#/${route}`; +} + +export function publicWebBase(): string | null { + return resolvePublicWebBase({ + publicBaseUrl: process.env.PUBLIC_BASE_URL, + allowLoopback: process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK === 'true', + }); +} + +export function warnIfPublicBaseUrlUnusable(): void { + const problem = publicBaseUrlProblem({ + publicBaseUrl: process.env.PUBLIC_BASE_URL, + allowLoopback: process.env.PUBLIC_BASE_URL_ALLOW_LOOPBACK === 'true', + }); + if (problem) logger.warn({ event: 'links.public_base_url_unusable', problem }); +} + +export function requirePublicWebBase(res: express.Response, route: string): string | null { + const base = publicWebBase(); + if (base) return base; + + logger.error({ event: 'links.public_base_url_missing', route }); + res.status(500).json({ error: 'public_base_url_missing' }); + return null; +} diff --git a/apps/server/src/api/utils/requestRoute.ts b/apps/server/src/api/utils/requestRoute.ts new file mode 100644 index 00000000..fc3f7d7e --- /dev/null +++ b/apps/server/src/api/utils/requestRoute.ts @@ -0,0 +1,16 @@ +import type { Request } from 'express'; + +/** + * Bestimmt das Routen-Template eines Requests für Logs und Metriklabels. + * + * Gibt bei bekanntem Routen-Template `baseUrl + route.path` zurück, sonst + * exakt `""`. Es werden ausschließlich `baseUrl` und ein + * stringförmiges `route.path` gelesen; konkrete Pfade, URLs, Parameter und + * Querystrings fließen nie ein. Vor dem Routing ist die Route noch nicht + * bekannt, daher meldet ein früher Aufruf `""`. + */ +export function getRequestRouteTemplate(req: Pick): string { + const route = req.route as { path?: unknown } | undefined; + if (typeof route?.path === 'string') return `${req.baseUrl}${route.path}`; + return ''; +} diff --git a/apps/server/src/api/utils/sessionAuth.fresh.integration.test.ts b/apps/server/src/api/utils/sessionAuth.fresh.integration.test.ts new file mode 100644 index 00000000..86e03104 --- /dev/null +++ b/apps/server/src/api/utils/sessionAuth.fresh.integration.test.ts @@ -0,0 +1,127 @@ +import { afterAll, expect, it } from 'vitest'; +import crypto from 'node:crypto'; +import jwt from 'jsonwebtoken'; +import { getJwtSecret } from './authHelpers.js'; +import { hashSessionToken } from './sessionAuth.js'; +import net from 'node:net'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { PrismaClient } from '../../generated/prisma/index.js'; +import { createHttpFixture } from '../../../test/fixtures/httpFixture.js'; +import { validateSessionToken, validateTenantSessionFresh } from './sessionAuth.js'; + +const fixture = createHttpFixture(); +afterAll(() => fixture.close()); + +it('reads the session and membership afresh despite a populated general session cache', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + expect(!!(await validateSessionToken(fixture.prisma, caller.session))).toBe(true); + expect((await validateTenantSessionFresh(fixture.prisma, caller.session, tenant.id)).status).toBe('allowed'); + await fixture.prisma.membership.update({ + where: { tenantId_userId: { tenantId: tenant.id, userId: caller.id } }, + data: { inviteVerificationRequired: true }, + }); + expect(await validateTenantSessionFresh(fixture.prisma, caller.session, tenant.id)).toEqual({ + status: 'forbidden', + reason: 'verification_required', + }); + await fixture.prisma.membership.update({ + where: { tenantId_userId: { tenantId: tenant.id, userId: caller.id } }, + data: { inviteVerificationRequired: false, expiresAt: new Date(Date.now() - 1000) }, + }); + expect((await validateTenantSessionFresh(fixture.prisma, caller.session, tenant.id)).status).toBe('forbidden'); + await fixture.prisma.membership.delete({ where: { tenantId_userId: { tenantId: tenant.id, userId: caller.id } } }); + expect((await validateTenantSessionFresh(fixture.prisma, caller.session, tenant.id)).status).toBe('forbidden'); + await fixture.prisma.session.delete({ where: { id: caller.sessionId } }); + expect(await validateTenantSessionFresh(fixture.prisma, caller.session, tenant.id)).toEqual({ + status: 'unauthenticated', + }); + expect(await validateTenantSessionFresh(fixture.prisma, caller.apiToken, tenant.id)).toEqual({ + status: 'unauthenticated', + }); +}); + +it('reads platform-operator rights and their markers afresh on every call', async () => { + const { tenant } = await fixture.tenant(); + const other = await fixture.tenant(); + const caller = await fixture.caller(tenant); + let internal = await fixture.prisma.tenant.findUnique({ where: { slug: 'internal' } }); + if (!internal) { + internal = await fixture.prisma.tenant.create({ data: { slug: 'internal', name: 'Internal test tenant' } }); + fixture.tenantIds.push(internal.id); + } + const operator = await fixture.prisma.membership.create({ + data: { tenantId: internal.id, userId: caller.id, role: 'owner' }, + }); + const result = await validateTenantSessionFresh(fixture.prisma, caller.session, other.tenant.id); + expect(result.status === 'allowed' && result.access === 'platform_operator').toBe(true); + await fixture.prisma.membership.update({ where: { id: operator.id }, data: { inviteVerificationRequired: true } }); + expect((await validateTenantSessionFresh(fixture.prisma, caller.session, other.tenant.id)).status).toBe('forbidden'); +}); + +it('propagates a real database connection failure instead of treating it as missing authentication', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + const port = await new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + server.close(); + reject(new Error('No local probe port')); + return; + } + server.close((error) => (error ? reject(error) : resolve(address.port))); + }); + }); + const url = new URL(process.env.DATABASE_URL!); + url.port = String(port); + const unavailable = new PrismaClient({ + adapter: new PrismaPg({ connectionString: url.toString(), connectionTimeoutMillis: 1000 }), + }); + try { + await expect(validateTenantSessionFresh(unavailable, caller.session, tenant.id)).rejects.toThrow(); + } finally { + await unavailable.$disconnect(); + } +}); + +it('distinguishes expired sessions, mismatched subjects and missing tenants without a cache fallback', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + await validateSessionToken(fixture.prisma, caller.session); + expect(await validateTenantSessionFresh(fixture.prisma, caller.session, crypto.randomUUID())).toEqual({ + status: 'forbidden', + reason: 'tenant_unavailable', + }); + await fixture.prisma.session.update({ + where: { id: caller.sessionId }, + data: { expiresAt: new Date(Date.now() - 1000) }, + }); + expect(await validateTenantSessionFresh(fixture.prisma, caller.session, tenant.id)).toEqual({ + status: 'unauthenticated', + }); + const other = await fixture.caller(tenant); + const raw = jwt.sign({ sub: other.id, tid: tenant.id, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await fixture.prisma.session.create({ + data: { userId: caller.id, tokenHash: hashSessionToken(raw), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + expect(await validateTenantSessionFresh(fixture.prisma, raw, tenant.id)).toEqual({ status: 'unauthenticated' }); +}); + +it('rejects verification-only sessions even after the account has been confirmed', async () => { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + const token = jwt.sign( + { sub: caller.id, tid: tenant.id, jti: crypto.randomUUID(), scope: 'email_verification' }, + getJwtSecret(), + { expiresIn: '15m' }, + ); + await fixture.prisma.session.create({ + data: { userId: caller.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 900_000) }, + }); + expect(await validateTenantSessionFresh(fixture.prisma, token, tenant.id)).toEqual({ status: 'unauthenticated' }); +}); diff --git a/apps/server/src/api/utils/sessionAuth.ts b/apps/server/src/api/utils/sessionAuth.ts index de4fdece..e87163d5 100644 --- a/apps/server/src/api/utils/sessionAuth.ts +++ b/apps/server/src/api/utils/sessionAuth.ts @@ -1,11 +1,13 @@ import type express from 'express'; import crypto from 'crypto'; import jwt from 'jsonwebtoken'; -import type { PrismaClient } from '../../generated/prisma/index.js'; +import type { PrismaClient, Prisma } from '../../generated/prisma/index.js'; import { logger } from '../../logger.js'; import { readAuthCookie, readBearerToken } from '../../types/authShapes.js'; import { getJwtSecret, setAuthCookie, verifyAuthJwt } from './authHelpers.js'; -import { setAuthResolution, type ResolvedAuth } from './authState.js'; +import { getAuthResolution, setAuthResolution, type ResolvedAuth } from './authState.js'; +import { createVerificationSessionScope } from '../middleware/verificationSessionScope.js'; +import { isInternalOwner } from './tenantMembership.js'; import { getCachedSession, setCachedSession, @@ -58,6 +60,33 @@ export function hashSessionToken(rawToken: string): string { return crypto.createHash('sha256').update(rawToken).digest('hex'); } +export type FreshAssetSessionResult = + | { status: 'allowed'; userId: string; sessionId: string; tenantId: string; access: 'member' | 'platform_operator' } + | { status: 'unauthenticated' } + | { status: 'forbidden'; reason: 'membership_unavailable' | 'verification_required' | 'tenant_unavailable' }; + +/** Read the session, tenant, membership and verification marker afresh on every call. + * Use no cache or API-token path; propagate database errors to the caller. + */ +export async function validateTenantSessionFresh( + prisma: PrismaClient, rawToken: string, tenantId: string, +): Promise { + const claims = verifyAuthJwt(rawToken); + if (!claims || claims.verificationOnly) return { status: 'unauthenticated' }; + const session = await prisma.session.findUnique({ where: { tokenHash: hashSessionToken(rawToken) }, + select: { id: true, userId: true, expiresAt: true } }); + if (!session || session.userId !== claims.userId || session.expiresAt <= new Date()) return { status: 'unauthenticated' }; + const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { id: true } }); + if (!tenant) return { status: 'forbidden', reason: 'tenant_unavailable' }; + const member = await prisma.membership.findUnique({ where: { tenantId_userId: { tenantId, userId: session.userId } }, + select: { expiresAt: true, inviteVerificationRequired: true } }); + if (member?.inviteVerificationRequired) return { status: 'forbidden', reason: 'verification_required' }; + const access = member && (!member.expiresAt || member.expiresAt > new Date()) ? 'member' + : await isInternalOwner(prisma, session.userId) ? 'platform_operator' : null; + if (!access) return { status: 'forbidden', reason: 'membership_unavailable' }; + return { status: 'allowed', userId: session.userId, sessionId: session.id, tenantId, access }; +} + /** * The Prisma surface {@link validateSessionToken} actually needs. * @@ -77,6 +106,7 @@ export interface EstablishSessionParams { userId: string; /** Tenant the session is scoped to; becomes the JWT's `tid` claim. */ tenantId: string; + verificationOnly?: boolean; } export interface EstablishedSession { @@ -105,11 +135,12 @@ export interface EstablishedSession { */ export async function establishSession(params: EstablishSessionParams): Promise { const { prisma, req, res, userId, tenantId } = params; - const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { - expiresIn: JWT_EXPIRES_IN, + const verificationOnly = params.verificationOnly === true; + const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID(), ...(verificationOnly ? { scope: 'email_verification' } : {}) }, getJwtSecret(), { + expiresIn: verificationOnly ? '15m' : JWT_EXPIRES_IN, }); const tokenHash = hashSessionToken(token); - const expiresAt = new Date(Date.now() + SESSION_TTL_MS); + const expiresAt = new Date(Date.now() + (verificationOnly ? 15 * 60_000 : SESSION_TTL_MS)); const session = await prisma.session.create({ data: { @@ -124,7 +155,7 @@ export async function establishSession(params: EstablishSessionParams): Promise< setAuthCookie(res, token); - const auth: ResolvedAuth = { userId, tenantId, sessionId: session.id, tokenHash }; + const auth: ResolvedAuth = { userId, tenantId, sessionId: session.id, tokenHash, ...(verificationOnly ? { verificationOnly: true as const } : {}) }; setCachedSession(auth, expiresAt); // The request that establishes a session is itself authenticated from here // on, so `requireAuth` works for any work the handler still does. @@ -143,13 +174,13 @@ export async function establishSession(params: EstablishSessionParams): Promise< * world-join gate in rooms/lifecycle/onAuth.ts) can apply the same authority * instead of trusting the signature alone. */ -export async function validateSessionToken(prisma: SessionPrisma, rawToken: string): Promise { +export async function validateSessionToken(prisma: SessionPrisma, rawToken: string, opts?: { allowVerificationOnly?: boolean }): Promise { const payload = verifyAuthJwt(rawToken); - if (!payload) return null; + if (!payload || (payload.verificationOnly && !opts?.allowVerificationOnly)) return null; const tokenHash = hashSessionToken(rawToken); const cached = getCachedSession(tokenHash); - if (cached) return cached; + if (cached) return payload.verificationOnly ? { ...cached, verificationOnly: true } : cached; const session = await prisma.session.findUnique({ where: { tokenHash }, @@ -166,6 +197,7 @@ export async function validateSessionToken(prisma: SessionPrisma, rawToken: stri const auth: ResolvedAuth = { userId: session.userId, + ...(payload.verificationOnly ? { verificationOnly: true as const } : {}), tenantId: payload.tenantId, sessionId: session.id, tokenHash, @@ -185,7 +217,8 @@ export async function validateSessionToken(prisma: SessionPrisma, rawToken: stri * an unvalidated token through. */ export function createSessionAuthMiddleware(prisma: PrismaClient): express.RequestHandler { - return (req, _res, next) => { + const verificationScope = createVerificationSessionScope(); + return (req, res, next) => { const raw = readAuthCookie(req) ?? readBearerToken(req); if (!raw) { setAuthResolution(req, { auth: null }); @@ -194,13 +227,14 @@ export function createSessionAuthMiddleware(prisma: PrismaClient): express.Reque } void (async () => { try { - setAuthResolution(req, { auth: await validateSessionToken(prisma, raw) }); + setAuthResolution(req, { auth: await validateSessionToken(prisma, raw, { allowVerificationOnly: true }) }); } catch (e: unknown) { // Fail closed: an unresolvable token is not an authenticated request. logger.error({ event: 'auth.session.resolve_failed', error: e instanceof Error ? e.message : String(e) }); setAuthResolution(req, { auth: null }); } - next(); + if (getAuthResolution(req)?.auth?.verificationOnly) verificationScope(req, res, next); + else next(); })(); }; } @@ -245,6 +279,21 @@ export async function revokeSessionsForUser( return result.count; } +/** + * Delete every session of `userId` inside an interactive transaction (account + * deletion and member removal, see services/accountDeletion.ts). + * + * The cache is invalidated here as well, but that is not sufficient on its own: + * until the transaction commits, a concurrent request can still read the row + * and re-cache it. Callers therefore MUST call `invalidateSessionsForUser` + * again after the commit. + */ +export async function revokeSessionsForUserInTx(tx: Prisma.TransactionClient, userId: string): Promise { + const result = await tx.session.deleteMany({ where: { userId } }); + invalidateSessionsForUser(userId); + return result.count; +} + /** * Drop `userId`'s already-expired session rows (housekeeping for the * active-sessions list, which must not show corpses). diff --git a/apps/server/src/api/utils/tenantAccessState.ts b/apps/server/src/api/utils/tenantAccessState.ts new file mode 100644 index 00000000..0fd39b73 --- /dev/null +++ b/apps/server/src/api/utils/tenantAccessState.ts @@ -0,0 +1,28 @@ +import type express from 'express'; +import type { Tenant } from '../../generated/prisma/index.js'; + +/** + * Remembers which tenant the central guard removed from a request (see + * api/middleware/tenantAccess.ts). Kept free of runtime imports so the guard, + * auth helpers and route helpers can share it without an import cycle. + */ +const deniedTenants = new WeakMap(); + +export function markTenantAccessDenied(req: express.Request, tenant: Tenant): void { + deniedTenants.set(req, tenant); +} + +/** True when the central guard removed the tenant context of `req`. */ +export function isTenantAccessDenied(req: express.Request): boolean { + return deniedTenants.has(req); +} + +/** The tenant the central guard removed from `req`, if any. */ +export function getDeniedTenant(req: express.Request): Tenant | undefined { + return deniedTenants.get(req); +} + +/** Forget the tenant denial after a credential route restores its tenant context. */ +export function clearTenantAccessDenied(req: express.Request): void { + deniedTenants.delete(req); +} diff --git a/apps/server/src/api/utils/tenantMembership.ts b/apps/server/src/api/utils/tenantMembership.ts new file mode 100644 index 00000000..f12c1655 --- /dev/null +++ b/apps/server/src/api/utils/tenantMembership.ts @@ -0,0 +1,30 @@ +import type { PrismaClient } from '../../generated/prisma/index.js'; + +export type TenantAccessPrisma = Pick; + +/** Owners of the `internal` tenant operate the platform (the rule requireSuperAdmin applies). */ +export async function isInternalOwner(prisma: TenantAccessPrisma, userId: string): Promise { + const internal = await prisma.tenant.findUnique({ where: { slug: 'internal' }, select: { id: true } }); + if (!internal) return false; + const member = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: internal.id, userId } }, + select: { role: true, expiresAt: true, inviteVerificationRequired: true }, + }); + return member?.role === 'owner' && !member.inviteVerificationRequired && (!member.expiresAt || member.expiresAt > new Date()); +} + +/** + * May `userId` act inside `tenantId`? True for an active membership (an + * expired guest membership does not count) and for operators. Shared by the + * HTTP tenant guard (api/middleware/tenantAccess.ts) and the world-join gate + * (rooms/lifecycle/onAuth.ts) so both enforce one rule. + */ +export async function hasTenantAccess(prisma: TenantAccessPrisma, userId: string, tenantId: string): Promise { + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId, userId } }, + select: { expiresAt: true, inviteVerificationRequired: true }, + }); + if (membership?.inviteVerificationRequired) return false; + if (membership && (!membership.expiresAt || membership.expiresAt > new Date())) return true; + return isInternalOwner(prisma, userId); +} diff --git a/apps/server/src/email/consoleProvider.redaction.test.ts b/apps/server/src/email/consoleProvider.redaction.test.ts new file mode 100644 index 00000000..4a053bed --- /dev/null +++ b/apps/server/src/email/consoleProvider.redaction.test.ts @@ -0,0 +1,15 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { expect, it } from 'vitest'; + +it('redacts recipients, subjects, message bodies and links in every console-provider mode', async () => { + for (const mode of ['development', 'production', 'test']) { + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ['--import', 'tsx', 'test/fixtures/consoleDeliveryProbe.ts'], + { cwd: process.cwd(), env: { ...process.env, NODE_ENV: mode }, timeout: 15_000 }, + ); + const leaked = /private-fixture|example\.test|PRIVATE_|https:\/\//.test(stdout + stderr); + expect(leaked).toBe(false); + } +}); diff --git a/apps/server/src/email/consoleProvider.ts b/apps/server/src/email/consoleProvider.ts index 47dcd8f4..4c902be5 100644 --- a/apps/server/src/email/consoleProvider.ts +++ b/apps/server/src/email/consoleProvider.ts @@ -1,40 +1,10 @@ import { logger } from '../logger.js'; import type { EmailProvider, SendRawParams } from './types.js'; -/** - * Console fallback provider for the OSS stack. - * - * Unlike the EE ConsoleProvider, this one returns `false` so that - * callers (e.g. `/auth/verify/request`) know that no real delivery - * occurred and can pass the token through the API response if needed. - * - * Body redaction: in production only subject and recipient domain are - * logged — never the content. This ensures that neither reset tokens nor - * verify URLs end up in a production logging stack. In development - * (NODE_ENV !== 'production') the full body is printed for developer - * convenience. - */ +/** Deliver no mail and log no mail data, including in development and tests. */ export class ConsoleEmailProvider implements EmailProvider { - send(params: SendRawParams): Promise { - const isProduction = process.env.NODE_ENV === 'production'; - const toDomain = params.to.includes('@') ? params.to.split('@').pop() : params.to; - - if (isProduction) { - logger.info({ - event: 'email.console.send_redacted', - to_domain: toDomain, - subject: params.subject, - body_redacted: true, - }); - } else { - logger.info({ - event: 'email.console.send_dev', - to: params.to, - subject: params.subject, - text: params.text, - }); - } - + send(_params: SendRawParams): Promise { + logger.info({ event: 'email.console.send_redacted', body_redacted: true, delivered: false }); return Promise.resolve(false); } } diff --git a/apps/server/src/email/index.ts b/apps/server/src/email/index.ts index 224ae910..5e05f5a9 100644 --- a/apps/server/src/email/index.ts +++ b/apps/server/src/email/index.ts @@ -6,8 +6,8 @@ * 2. Template renderer (`renderForLocale`) * 3. Brand context + default locale (read once from ENV at boot) * - * In test mode (`NODE_ENV === 'test'`) the factory returns `null` so that - * Vitest suites do not accidentally produce stdout spam. + * Keep the console disabled in tests. An explicitly configured SMTP provider + * enables real Mailpit integration. * * Provider selection at boot: * - `SMTP_HOST` + `SMTP_FROM` set → SmtpEmailProvider. @@ -49,6 +49,7 @@ class OssEmailModule implements EmailModule { private readonly provider: EmailProvider, private readonly brand: BrandContext, private readonly defaultLocale: EmailLocale, + readonly providerName: string, ) {} private effective(locale: EmailLocale | undefined): EmailLocale { @@ -86,11 +87,10 @@ class OssEmailModule implements EmailModule { * when the EE tenancy module is not available. * * Return value: - * - `null` in test environments (prevents stdout spam in Vitest). + * - `null` in test mode without SMTP configuration. * - Otherwise an `EmailModule` with an SMTP or Console provider. */ export function createOssEmailModule(): EmailModule | null { - if (process.env.NODE_ENV === 'test') return null; const brand = readBrandContext(); const defaultLocale = readEnvDefaultLocale(); @@ -109,17 +109,21 @@ export function createOssEmailModule(): EmailModule | null { smtpPool: smtpOptions.pool, smtpVerifyOnBoot: smtpOptions.verifyOnBoot, }); - return new OssEmailModule(provider, brand, defaultLocale); + return new OssEmailModule(provider, brand, defaultLocale, 'oss-smtp'); } + if (process.env.NODE_ENV === 'test') return null; + // Console fallback. Important: returns false in send() so callers know // no real send happened. Also emits a one-time WARN at boot. const provider = new ConsoleEmailProvider(); - logger.warn({ + // In production nothing is delivered without a provider: say so loudly. + const logFallback = process.env.NODE_ENV === 'production' ? logger.error.bind(logger) : logger.warn.bind(logger); + logFallback({ event: 'email.fallback_console', - message: 'No mail provider configured (SMTP_HOST/SMTP_FROM unset and no EE-tenancy module) — mails are logged only', + message: 'No mail provider configured (SMTP_HOST/SMTP_FROM unset and no EE-tenancy module) — mails are not delivered', brand: brand.brandName, defaultLocale, }); - return new OssEmailModule(provider, brand, defaultLocale); + return new OssEmailModule(provider, brand, defaultLocale, 'oss-console'); } diff --git a/apps/server/src/email/smtpProvider.requireTls.test.ts b/apps/server/src/email/smtpProvider.requireTls.test.ts new file mode 100644 index 00000000..31dabfb6 --- /dev/null +++ b/apps/server/src/email/smtpProvider.requireTls.test.ts @@ -0,0 +1,55 @@ +/** + * The SMTP provider must not fall back to a plain-text session when the server + * does not offer STARTTLS: that downgrade exposes the SMTP credentials and the + * mail with its links. Checked with real nodemailer against a real SMTP server + * that offers no STARTTLS (testUtils/plainSmtpServer.ts). + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { SmtpEmailProvider, loadSmtpOptionsFromEnv, type SmtpProviderEnv } from './smtpProvider.js'; +import { startPlainSmtpServer, type PlainSmtpServer } from '../testUtils/plainSmtpServer.js'; + +let server: PlainSmtpServer; + +beforeEach(async () => { + server = await startPlainSmtpServer(); +}); +afterEach(async () => { + await server.close(); +}); + +function provider(extra: SmtpProviderEnv): SmtpEmailProvider { + const options = loadSmtpOptionsFromEnv({ + SMTP_HOST: '127.0.0.1', + SMTP_PORT: String(server.port), + SMTP_SECURE: 'false', + SMTP_FROM: 'Meetropolis ', + ...extra, + }); + if (!options) throw new Error('loadSmtpOptionsFromEnv returned null'); + return new SmtpEmailProvider(options); +} + +const mail = { to: 'someone@example.test', subject: 'Einladung', text: 'secret-link', html: '

secret-link

' }; + +describe('SmtpEmailProvider without TLS on the server side', () => { + it('refuses to send in plain text by default', async () => { + const sender = provider({}); + try { + expect(await sender.send(mail)).toBe(false); + expect(server.received).toHaveLength(0); + } finally { + sender.close(); + } + }); + + it('sends in plain text only when SMTP_REQUIRE_TLS=false', async () => { + const sender = provider({ SMTP_REQUIRE_TLS: 'false' }); + try { + expect(await sender.send(mail)).toBe(true); + expect(server.received).toHaveLength(1); + expect(server.received[0]).toContain('secret-link'); + } finally { + sender.close(); + } + }); +}); diff --git a/apps/server/src/email/smtpProvider.ts b/apps/server/src/email/smtpProvider.ts index 6ea87c5d..8ccd9783 100644 --- a/apps/server/src/email/smtpProvider.ts +++ b/apps/server/src/email/smtpProvider.ts @@ -33,6 +33,14 @@ export interface SmtpProviderOptions { replyTo?: string; pool: boolean; rejectUnauthorized: boolean; + /** + * Refuse to send unless the connection is encrypted (direct TLS or a + * successful STARTTLS upgrade). Without it nodemailer falls back to plain + * text when the server does not offer STARTTLS, so a downgrade on the path + * exposes the SMTP credentials and the mail, including its links. Opt out + * (`SMTP_REQUIRE_TLS=false`) only for a local server without TLS (Mailpit). + */ + requireTLS: boolean; verifyOnBoot: boolean; } @@ -46,6 +54,7 @@ export interface SmtpProviderEnv { SMTP_REPLY_TO?: string; SMTP_POOL?: string; SMTP_TLS_REJECT_UNAUTHORIZED?: string; + SMTP_REQUIRE_TLS?: string; SMTP_VERIFY_ON_BOOT?: string; } @@ -103,7 +112,6 @@ export function loadSmtpOptionsFromEnv(env: SmtpProviderEnv = process.env): Smtp if (!validateFrom(from)) { logger.warn({ event: 'email.smtp.invalid_from', - from, message: 'SMTP_FROM looks invalid (missing @ or contains CR/LF) — refusing to initialize SMTP provider', }); return null; @@ -119,6 +127,7 @@ export function loadSmtpOptionsFromEnv(env: SmtpProviderEnv = process.env): Smtp replyTo: env.SMTP_REPLY_TO?.trim() || undefined, pool: parseBool(env.SMTP_POOL, false), rejectUnauthorized: parseBool(env.SMTP_TLS_REJECT_UNAUTHORIZED, true), + requireTLS: parseBool(env.SMTP_REQUIRE_TLS, true), verifyOnBoot: parseBool(env.SMTP_VERIFY_ON_BOOT, false), }; } @@ -143,6 +152,7 @@ export class SmtpEmailProvider implements EmailProvider { connectionTimeout: CONNECTION_TIMEOUT_MS, greetingTimeout: GREETING_TIMEOUT_MS, socketTimeout: SOCKET_TIMEOUT_MS, + requireTLS: options.secure !== true && options.requireTLS, tls: { rejectUnauthorized: options.rejectUnauthorized }, }; this.transporter = nodemailer.createTransport(poolOptions); @@ -155,6 +165,7 @@ export class SmtpEmailProvider implements EmailProvider { connectionTimeout: CONNECTION_TIMEOUT_MS, greetingTimeout: GREETING_TIMEOUT_MS, socketTimeout: SOCKET_TIMEOUT_MS, + requireTLS: options.secure !== true && options.requireTLS, tls: { rejectUnauthorized: options.rejectUnauthorized }, }; this.transporter = nodemailer.createTransport(smtpOptions); @@ -180,7 +191,7 @@ export class SmtpEmailProvider implements EmailProvider { event: 'email.smtp.verify_failed', host: options.host, port: options.port, - error: e instanceof Error ? e.message : String(e), + errorName: e instanceof Error ? e.name : typeof e, }); }); } @@ -222,9 +233,8 @@ export class SmtpEmailProvider implements EmailProvider { : undefined; logger.info({ event: 'email.smtp.send_ok', - to: params.to, - subject: params.subject, - messageId, + delivered: true, + hasMessageId: !!messageId, attempt, }); return true; @@ -237,10 +247,8 @@ export class SmtpEmailProvider implements EmailProvider { } logger.error({ event: 'email.smtp.send_failed', - to: params.to, - subject: params.subject, attempts: MAX_ATTEMPTS, - error: lastError instanceof Error ? lastError.message : String(lastError), + errorName: lastError instanceof Error ? lastError.name : typeof lastError, }); return false; } diff --git a/apps/server/src/emailLoader.ts b/apps/server/src/emailLoader.ts index fc9deeac..ebc970da 100644 --- a/apps/server/src/emailLoader.ts +++ b/apps/server/src/emailLoader.ts @@ -12,11 +12,10 @@ import { createOssEmailModule } from './email/index.js'; * 2. OSS-SMTP (`./email/index.ts`) when the EE module is unavailable but * `SMTP_HOST` + `SMTP_FROM` are configured. * 3. OSS-Console fallback (`./email/index.ts`) when neither EE nor SMTP is - * configured. Logs a one-time warn at boot and reports `false` from - * `send()` so callers (verify-request etc.) keep surfacing tokens. + * configured. Reports false without logging message data. * - * Sensitive tokens (e.g. password reset) are never routed through this - * module — they remain admin-triggered and surface in the admin UI. + * Require known delivery metadata before issuing confirmation or reset tokens. + * Do not send links to console or unknown providers. */ export type EmailLocale = 'de' | 'en'; @@ -86,6 +85,8 @@ export interface SendRawParams { export interface EmailModule { readonly version: 1; + /** Delivering provider as reported by the module (e.g. `ee-resend`, `ee-smtp`, `ee-console`). */ + readonly providerName?: string; sendInvite(params: SendInviteParams): Promise; sendGuestInvite(params: SendGuestInviteParams): Promise; sendWelcome(params: SendWelcomeParams): Promise; @@ -137,10 +138,15 @@ export async function getEmailModule(): Promise { const candidate = factory(); if (isEmailModule(candidate)) { cached = candidate; - logger.info({ - event: 'email.module_loaded', - provider: process.env.RESEND_API_KEY ? 'ee-resend' : 'ee-console', - }); + const provider = typeof candidate.providerName === 'string' ? candidate.providerName : 'ee-unknown'; + logger.info({ event: 'email.module_loaded', provider }); + if (provider === 'ee-console' && process.env.NODE_ENV === 'production') { + logger.error({ + event: 'email.no_delivery_configured', + provider, + message: 'Neither RESEND_API_KEY/RESEND_FROM nor SMTP_HOST/SMTP_FROM is set: mails are NOT delivered', + }); + } return cached; } logger.warn({ event: 'email.module_invalid_shape', source: 'ee-tenancy' }); @@ -151,7 +157,7 @@ export async function getEmailModule(): Promise { logger.debug({ event: 'email.module_not_available', reason: 'import_failed', - error: e instanceof Error ? e.message : String(e), + errorName: e instanceof Error ? e.name : typeof e, }); } @@ -165,7 +171,7 @@ export async function getEmailModule(): Promise { } catch (e: unknown) { logger.error({ event: 'email.oss_module_init_failed', - error: e instanceof Error ? e.message : String(e), + errorName: e instanceof Error ? e.name : typeof e, }); } @@ -191,7 +197,7 @@ export async function sendIfAvailable( logger.error({ event: errorEvent, ...context, - error: e instanceof Error ? e.message : String(e), + errorName: e instanceof Error ? e.name : typeof e, }); return false; } diff --git a/apps/server/src/guestSessionRevocation.test.ts b/apps/server/src/guestSessionRevocation.test.ts index c59b9187..c52980bf 100644 --- a/apps/server/src/guestSessionRevocation.test.ts +++ b/apps/server/src/guestSessionRevocation.test.ts @@ -64,6 +64,7 @@ const db = vi.hoisted(() => { if (typeof where.id === 'string' && row.id !== where.id) return false; if (typeof where.tenantId === 'string' && row.tenantId !== where.tenantId) return false; if (typeof where.userId === 'string' && row.userId !== where.userId) return false; + if (Array.isArray(where.userId?.in) && !where.userId.in.includes(row.userId)) return false; if (typeof where.role === 'string' && row.role !== where.role) return false; if (where.expiresAt?.lt) { if (!row.expiresAt || row.expiresAt.getTime() >= where.expiresAt.lt.getTime()) return false; @@ -87,6 +88,14 @@ const db = vi.hoisted(() => { const prisma = { session: { findUnique: ({ where }: any) => Promise.resolve(sessions.find((r) => r.tokenHash === where.tokenHash) ?? null), + findMany: ({ where }: any) => + Promise.resolve( + sessions.filter((r) => { + if (Array.isArray(where?.id?.in) && !where.id.in.includes(r.id)) return false; + if (where?.expiresAt?.gt && !(r.expiresAt.getTime() > where.expiresAt.gt.getTime())) return false; + return true; + }), + ), update: ({ where, data }: any) => { const row = sessions.find((r) => r.id === where.id); if (row) Object.assign(row, data); @@ -131,6 +140,7 @@ import { setAuthResolution } from './api/utils/authState.js'; import { registerGuestRoutes } from './api/routes/guests.js'; import { guestExpiryMiddleware } from './api/middleware/guestExpiry.js'; import { startGuestExpiryInterval } from './rooms/lifecycle/guestExpiry.js'; +import { createWorldAccess } from './rooms/lifecycle/worldAccess.js'; import type { WorldRoom } from './rooms/WorldRoom.js'; import type { PrismaClient } from './generated/prisma/index.js'; @@ -255,13 +265,40 @@ describe('guestExpiryMiddleware (REST)', () => { }); describe('room guest-expiry sweep', () => { - function makeRoom(players: Map, clients: unknown[]): WorldRoom { - return { + /** Database session row id behind a seeded token, as onAuth would store it. */ + function sessionRowId(token: string): string { + const row = db.sessions.find((s) => s.tokenHash === hashSessionToken(token)); + if (!row) throw new Error('test setup: session row missing'); + return row.id; + } + + function makeRoom( + players: Map, + clients: unknown[], + sessionIds: Map, + ): WorldRoom { + // The sweep reads each session's verified tenant from the registry, never + // the room slug: every player here was verified for this tenant at join time. + // The bundled session check needs each entry's database session row, as a + // real join via onAuth would store it. + const room = { metadata: { tenant: TENANT.slug }, prismaForPresence: prisma, state: { players }, clients, } as unknown as WorldRoom; + room.worldAccess = createWorldAccess(room); + for (const [sessionId, player] of players) { + room.worldAccess.register(sessionId, { + identity: player.identity, + tenantId: TENANT.id, + tenantSlug: TENANT.slug, + authSessionId: sessionIds.get(sessionId), + isNpc: false, + zonePrivacyVersion: 1, + }); + } + return room; } /** @@ -290,7 +327,8 @@ describe('room guest-expiry sweep', () => { const leave = vi.fn(); const error = vi.fn(); const players = new Map([['sess-a', { identity: GUEST_USER }]]); - await runOneSweep(makeRoom(players, [{ sessionId: 'sess-a', leave, error }])); + const sessionIds = new Map([['sess-a', sessionRowId(token)]]); + await runOneSweep(makeRoom(players, [{ sessionId: 'sess-a', leave, error }], sessionIds)); // Kicked from the room … expect(error).toHaveBeenCalledWith(4006, 'guest_expired'); @@ -307,7 +345,8 @@ describe('room guest-expiry sweep', () => { const leave = vi.fn(); const players = new Map([['sess-a', { identity: GUEST_USER }]]); - await runOneSweep(makeRoom(players, [{ sessionId: 'sess-a', leave, error: vi.fn() }])); + const sessionIds = new Map([['sess-a', sessionRowId(token)]]); + await runOneSweep(makeRoom(players, [{ sessionId: 'sess-a', leave, error: vi.fn() }], sessionIds)); expect(leave).not.toHaveBeenCalled(); await expect(validateSessionToken(prisma, token)).resolves.not.toBeNull(); diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index d7b1258b..47459654 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -26,6 +26,7 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); import { WorldRoom } from './rooms/WorldRoom.js'; import { getApiPrismaClient, registerApi } from './api.js'; +import { warnIfPublicBaseUrlUnusable } from './api/utils/publicLinks.js'; import { logger } from './logger.js'; import { registry, metricsMiddleware } from './metrics.js'; import { tenantMiddleware } from './tenancy.js'; @@ -306,6 +307,7 @@ if (toolsUser && toolsPassword) { } await registerApi(app); +warnIfPublicBaseUrlUnusable(); // Expose Prometheus Metriken app.get('/metrics', async (_req, res) => { diff --git a/apps/server/src/livekit.ts b/apps/server/src/livekit.ts index f2374db5..82842fb7 100644 --- a/apps/server/src/livekit.ts +++ b/apps/server/src/livekit.ts @@ -1,18 +1,52 @@ import { AccessToken } from 'livekit-server-sdk'; import type { AccessTokenOptions } from 'livekit-server-sdk'; +/** + * Lifetime of a LiveKit access token. The SDK default is 6 h, and LiveKit + * cannot revoke an issued token, so a user who lost access could rejoin a call + * with a cached token for that long. Connected participants keep working past + * the lifetime because the LiveKit server hands them refreshed tokens. + * Override with LIVEKIT_TOKEN_TTL_SECONDS (60 to 86400). + */ +export const DEFAULT_LIVEKIT_TOKEN_TTL_SECONDS = 15 * 60; + +export function livekitTokenTtlSeconds(env: Record = process.env): number { + const raw = Number(env.LIVEKIT_TOKEN_TTL_SECONDS); + if (!Number.isInteger(raw) || raw < 60 || raw > 86_400) return DEFAULT_LIVEKIT_TOKEN_TTL_SECONDS; + return raw; +} + +/** + * Token lifetime for a member whose access ends at `expiresAt` (guests): never + * past the end of the access, otherwise the regular lifetime. + */ +export function tokenTtlForAccess(expiresAt: Date | null, now: Date = new Date()): number { + const regular = livekitTokenTtlSeconds(); + if (!expiresAt) return regular; + const remaining = Math.floor((expiresAt.getTime() - now.getTime()) / 1000); + return Math.max(1, Math.min(regular, remaining)); +} + export async function createLivekitToken(params: { roomName: string; identity: string; + /** End of the member's tenant access (guests); the token never outlives it. */ + accessExpiresAt?: Date | null; name?: string; + /** Participant metadata, e.g. the opaque session reference of the issuer. */ + metadata?: string; canPublish?: boolean; canPublishData?: boolean; canSubscribe?: boolean; }) { const apiKey = process.env.LIVEKIT_API_KEY!; const apiSecret = process.env.LIVEKIT_API_SECRET!; - const opts: AccessTokenOptions = { identity: params.identity }; + const opts: AccessTokenOptions = { + identity: params.identity, + ttl: tokenTtlForAccess(params.accessExpiresAt ?? null), + }; if (typeof params.name === 'string') opts.name = params.name; + if (typeof params.metadata === 'string') opts.metadata = params.metadata; const at = new AccessToken(apiKey, apiSecret, opts); at.addGrant({ room: params.roomName, @@ -20,6 +54,9 @@ export async function createLivekitToken(params: { canPublish: params.canPublish ?? true, canPublishData: params.canPublishData ?? true, canSubscribe: params.canSubscribe ?? true, + // No canUpdateOwnMetadata grant: the session reference in the metadata is + // written by the server and read back by the access reconciliation, so a + // participant must never be able to rewrite it (absent means denied). }); const jwt = await at.toJwt(); return jwt; diff --git a/apps/server/src/livekit.ttl.test.ts b/apps/server/src/livekit.ttl.test.ts new file mode 100644 index 00000000..e78c70ab --- /dev/null +++ b/apps/server/src/livekit.ttl.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + createLivekitToken, + DEFAULT_LIVEKIT_TOKEN_TTL_SECONDS, + livekitTokenTtlSeconds, + tokenTtlForAccess, +} from './livekit.js'; + +/** + * LiveKit cannot revoke an issued token, so its lifetime bounds how long a + * user who lost access could rejoin a call with a cached token. The SDK default + * was 6 h; the server now sets an explicit lifetime. + */ + +function lifetimeOf(jwt: string): number { + const payload = JSON.parse(Buffer.from(jwt.split('.')[1] ?? '', 'base64url').toString('utf8')) as { + exp: number; + nbf: number; + }; + return payload.exp - payload.nbf; +} + +describe('LiveKit token lifetime', () => { + afterEach(() => vi.unstubAllEnvs()); + + it('defaults to 15 minutes', () => { + expect(DEFAULT_LIVEKIT_TOKEN_TTL_SECONDS).toBe(900); + expect(livekitTokenTtlSeconds({})).toBe(900); + }); + + it('accepts an override between one minute and one day', () => { + expect(livekitTokenTtlSeconds({ LIVEKIT_TOKEN_TTL_SECONDS: '120' })).toBe(120); + expect(livekitTokenTtlSeconds({ LIVEKIT_TOKEN_TTL_SECONDS: '30' })).toBe(900); + expect(livekitTokenTtlSeconds({ LIVEKIT_TOKEN_TTL_SECONDS: '172800' })).toBe(900); + expect(livekitTokenTtlSeconds({ LIVEKIT_TOKEN_TTL_SECONDS: 'soon' })).toBe(900); + }); + + it('signs tokens with that lifetime instead of the SDK default of 6 hours', async () => { + vi.stubEnv('LIVEKIT_API_KEY', 'test-key'); + vi.stubEnv('LIVEKIT_API_SECRET', 'test-secret-with-enough-length-0123456789'); + const jwt = await createLivekitToken({ roomName: 'acme:main', identity: 'user-1' }); + expect(lifetimeOf(jwt)).toBe(900); + }); + + it('caps a guest token at the end of the guest access', async () => { + vi.stubEnv('LIVEKIT_API_KEY', 'test-key'); + vi.stubEnv('LIVEKIT_API_SECRET', 'test-secret-with-enough-length-0123456789'); + const accessExpiresAt = new Date(Date.now() + 120_000); + const jwt = await createLivekitToken({ roomName: 'acme:main', identity: 'guest-1', accessExpiresAt }); + expect(lifetimeOf(jwt)).toBeGreaterThanOrEqual(118); + expect(lifetimeOf(jwt)).toBeLessThanOrEqual(120); + }); + + it('never lets a guest token outlive the guest access', () => { + const now = new Date('2026-11-06T12:00:00Z'); + expect(tokenTtlForAccess(null, now)).toBe(900); + expect(tokenTtlForAccess(new Date('2026-11-06T12:05:00Z'), now)).toBe(300); + expect(tokenTtlForAccess(new Date('2026-11-07T12:00:00Z'), now)).toBe(900); + expect(tokenTtlForAccess(new Date('2026-11-06T11:59:00Z'), now)).toBe(1); + }); +}); diff --git a/apps/server/src/metrics.ts b/apps/server/src/metrics.ts index 73d4f092..5f858db3 100644 --- a/apps/server/src/metrics.ts +++ b/apps/server/src/metrics.ts @@ -1,5 +1,6 @@ import client from 'prom-client'; import type { Request, Response, NextFunction, RequestHandler } from 'express'; +import { getRequestRouteTemplate } from './api/utils/requestRoute.js'; // Central registry object (not global) export const registry = new client.Registry(); @@ -74,16 +75,13 @@ registry.registerMetric(livekitPacketLossRatio); export function metricsMiddleware(): RequestHandler { return function (req: Request, res: Response, next: NextFunction) { const start = process.hrtime.bigint(); - // The route may only become available after routing; fall back to originalUrl. + // The route is only known after routing; unmatched requests are labelled "". res.on('finish', () => { try { const end = process.hrtime.bigint(); const dur = Number(end - start) / 1e9; // Seconds. const method = (req.method || 'GET').toUpperCase(); - // express-serve-static-core types req.route as `any`; narrow defensively. - const routeObj = req.route as { path?: unknown } | undefined; - const routePath = typeof routeObj?.path === 'string' ? routeObj.path : undefined; - const route = routePath ?? req.originalUrl ?? 'unknown'; + const route = getRequestRouteTemplate(req); const status = String(res.statusCode || 0); httpRequestDuration.labels(method, route, status).observe(dur); } catch (_error) { diff --git a/apps/server/src/rooms/WorldRoom.ts b/apps/server/src/rooms/WorldRoom.ts index 163d1633..eb5354ef 100644 --- a/apps/server/src/rooms/WorldRoom.ts +++ b/apps/server/src/rooms/WorldRoom.ts @@ -1,4 +1,4 @@ -import { Room, type Client, type AuthContext } from 'colyseus'; +import { Room, ServerError, type Client, type AuthContext } from 'colyseus'; import { Schema, type, view, MapSchema } from '@colyseus/schema'; import { logger } from '../logger.js'; import { colyseusRooms } from '../metrics.js'; @@ -20,10 +20,14 @@ import { handleEditorUpdate, subscribeMapUpdates } from './handlers/editorHandle import { handleBubbleUpdate } from './handlers/bubbleHandler.js'; import { handleChangeMap } from './handlers/mapSwitchHandler.js'; import { performOnJoin } from './lifecycle/onJoin.js'; +import { createWorldAccess, type WorldAccessRegistry } from './lifecycle/worldAccess.js'; import { performOnLeave } from './lifecycle/onLeave.js'; import { startGuestExpiryInterval } from './lifecycle/guestExpiry.js'; +import { clearWorldAccessLeaseTimer } from './lifecycle/worldAccessLease.js'; +import { subscribeAccessRevocations } from './lifecycle/accessRevocation.js'; import { loadInitialSpawn } from './lifecycle/onCreateSetup.js'; -import { authenticateWorldJoin, type WorldAuth } from './lifecycle/onAuth.js'; +import { AUTH_REJECTED_CODE, isWorldAuth, type WorldAuth } from './lifecycle/onAuth.js'; +import { authenticateWorldMatchmake } from './lifecycle/worldMatchmakeAuth.js'; import { enforceRoomPartition } from './lifecycle/roomPartition.js'; import { watchTranscriptionGate } from './lifecycle/transcriptionGateWatcher.js'; @@ -121,6 +125,9 @@ export class WorldRoom extends Room<{ state: WorldState }> { // client only ever sees players of its own authenticated tenant even when two // tenants share this room instance. Server-only, never broadcast. public playerTenantKey: Map = new Map(); + // Per-client verified tenants. The revocation handler and the access + // sweep check each session against its own tenant, never the room slug. + public worldAccess: WorldAccessRegistry = createWorldAccess(this); // Graceful leave: pending delete timer per sessionId, used for reconnect healing. public pendingLeaves: Map> = new Map(); @@ -131,9 +138,13 @@ export class WorldRoom extends Room<{ state: WorldState }> { // Periodic intervals private guestExpiryInterval: ReturnType | null = null; + private accessRevocationUnsubscribe: (() => void) | null = null; private transcriptionGateUnsubscribe: (() => void) | null = null; - override onCreate(options?: RoomOptions): void { + // Async so the room is only created once its revocation channel is + // subscribed: a failed subscription rejects onCreate and Colyseus refuses + // the room, instead of serving a room no revocation can reach. + override async onCreate(options?: RoomOptions): Promise { this.setState(new WorldState()); // Room is auto-disposed when empty (Colyseus default; explicit for clarity) this.autoDispose = true; @@ -186,8 +197,8 @@ export class WorldRoom extends Room<{ state: WorldState }> { }); // Bubble groups - this.onMessage('bubble_update', (_client, data: { id?: string; members?: string[] }) => - handleBubbleUpdate(this, data), + this.onMessage('bubble_update', (client, data: { id?: string; members?: string[] }) => + handleBubbleUpdate(this, client, data), ); // NPC command (no-op: NPC service listens to broadcasts from API) @@ -206,6 +217,10 @@ export class WorldRoom extends Room<{ state: WorldState }> { // Subscribe to map updates via Presence (cross-process via Redis, or local) const tenantSlugForPresence = options?.tenant || (this.metadata as RoomMetadata)?.tenant || 'default'; subscribeMapUpdates(this, tenantSlugForPresence); + // Members removed or revoked while connected leave the world at once. + // One channel for every tenant: the registry tells whose session is whose. + // Awaited: without the subscription the room must not exist (see above). + this.accessRevocationUnsubscribe = await subscribeAccessRevocations(this); // Setup zone lock handlers setupZoneLockHandlers(this, this.zoneLockState, this.prismaForPresence ?? createPrismaClient()); @@ -238,22 +253,41 @@ export class WorldRoom extends Room<{ state: WorldState }> { broadcastToMap(this, mapId, event, data, except); } - // H4 hardening: authoritative identity binding + client zone-privacy - // version gate. Runs before onJoin (Colyseus attaches the return value - // to client.auth); see lifecycle/onAuth.ts for the fail-closed rules. - // NOTE: this must stay an ESM-imported `Room` (see the CJS/ESM note in - // index.ts) for Colyseus to honor an instance-level onAuth at all. - override async onAuth(_client: Client, options: RoomOptions | undefined, context: AuthContext): Promise { - const auth = await authenticateWorldJoin(options, context, this.prismaForPresence ?? createPrismaClient()); - enforceRoomPartition(options, auth, (this.metadata as RoomMetadata | undefined)?.tenant); - return auth; + // Local access revocation, called by broadcastAccessRevoked before the + // event is published: a failed publish must not keep a revoked session. + public revokeAccess(userId: string): void { + this.worldAccess.revoke(userId).catch((e) => { + logger.error('[WorldRoom] Failed to revoke world access', e); + }); + } + + // Static auth runs before the seat is reserved. Colyseus copies the + // result onto `client.auth` when the seat is consumed and skips instance + // auth. Reconnect does not call `onJoin`, so this registration stays on + // the first consume only. + static async onAuth(token: string, options: RoomOptions | undefined, context: AuthContext): Promise { + return authenticateWorldMatchmake(token, options, context); } override async onJoin(client: Client, options?: RoomOptions): Promise { + if (!isWorldAuth(client.auth)) { + throw new ServerError(AUTH_REJECTED_CODE, 'missing_world_auth'); + } + try { + if (!client.auth.isNpc) { + this.worldAccess.registerPending(client.sessionId, client.auth.identity, client.auth.tenantId); + } + this.worldAccess.register(client.sessionId, client.auth); + enforceRoomPartition(options, client.auth, (this.metadata as RoomMetadata | undefined)?.tenant); + } catch (error) { + this.worldAccess.forget(client.sessionId); + throw error; + } await performOnJoin(this, activeRooms, client, options, Player); } override onLeave(client: Client, code?: number): void { + this.worldAccess.forget(client.sessionId); performOnLeave(this, client, code); } @@ -270,6 +304,11 @@ export class WorldRoom extends Room<{ state: WorldState }> { clearInterval(this.guestExpiryInterval); this.guestExpiryInterval = null; } + clearWorldAccessLeaseTimer(this); + if (this.accessRevocationUnsubscribe) { + this.accessRevocationUnsubscribe(); + this.accessRevocationUnsubscribe = null; + } // Alle pending Graceful-Leave-Timer abbrechen for (const timer of this.pendingLeaves.values()) { try { @@ -281,6 +320,7 @@ export class WorldRoom extends Room<{ state: WorldState }> { this.pendingLeaves.clear(); this.lastSeen.clear(); this.playerTenantKey.clear(); + this.worldAccess.clear(); stopAudioZoneRuntime(this); activeRooms.delete(this); try { diff --git a/apps/server/src/rooms/handlers/bubbleHandler.ts b/apps/server/src/rooms/handlers/bubbleHandler.ts index 0c8e4456..fd985ae8 100644 --- a/apps/server/src/rooms/handlers/bubbleHandler.ts +++ b/apps/server/src/rooms/handlers/bubbleHandler.ts @@ -1,23 +1,139 @@ +import type { Client } from 'colyseus'; import { logger } from '../../logger.js'; import type { WorldRoom } from '../WorldRoom.js'; -import { broadcastBubbleState, canonicalGroupId } from '../utils/bubbleHelpers.js'; - -export function handleBubbleUpdate(room: WorldRoom, data: { id?: string; members?: string[] }): void { - const raw = Array.isArray(data?.members) ? data.members : []; - const filtered = Array.from(new Set(raw)).filter((id) => room.state.players.has(id)); - logger.info('[WorldRoom] bubble_update:', filtered); - // Remove members from existing groups - if (filtered.length > 0) { - const toRemoveFrom: string[] = []; - for (const [gid, mems] of Object.entries(room.bubbleGroups)) { - if (mems.some((m) => filtered.includes(m))) toRemoveFrom.push(gid); +import { canonicalGroupId } from '../utils/bubbleHelpers.js'; +import { broadcastBubbleStateToClients, sameScope, senderScope, type SocialScope } from './socialScope.js'; + +/** + * Bubble groups are bound to the sender: only seats of the sender's own + * tenant and map take part in a group, and the server owns the group id. The + * client may name a group it already knows (join, expand, leave) but it can + * neither invent an id nor take a group of somebody else apart. + */ +export function handleBubbleUpdate(room: WorldRoom, client: Client, data: { id?: string; members?: string[] }): void { + const scope = senderScope(room, client); + if (!scope) { + logger.debug('[WorldRoom] Dropped bubble_update without a proven scope'); + return; + } + const requested = memberIds(data?.members); + if (requested.length === 0) return; + for (const sessionId of requested) { + if (!sameScope(room, sessionId, scope)) { + logger.debug('[WorldRoom] Dropped bubble_update for a seat outside the sender scope'); + return; } - for (const gid of toRemoveFrom) delete room.bubbleGroups[gid]; } - // Empty list means: just dissolve, do not form a new group - if (filtered.length >= 2) { - const gid = data?.id && typeof data.id === 'string' && data.id.length > 0 ? data.id : canonicalGroupId(filtered); - room.bubbleGroups[gid] = filtered; + const groupId = typeof data?.id === 'string' && data.id.length > 0 ? data.id : undefined; + if (groupId === undefined) { + formOwnGroup(room, scope, requested); + return; + } + updateExistingGroup(room, scope, groupId, requested); +} + +/** The session ids of a message, without duplicates and without empty entries. */ +function memberIds(value: unknown): string[] { + if (!Array.isArray(value)) return []; + const ids: string[] = []; + for (const entry of value) { + if (typeof entry !== 'string' || entry.length === 0) continue; + if (!ids.includes(entry)) ids.push(entry); + } + return ids; +} + +/** + * Is the requested list the way out of a bubble? The sender has to be a + * member, the list has to hold every seat that is still in the group, and it + * may not bring in a seat that never belonged to the group. + */ +function isLeaveOf(liveMembers: string[], storedMembers: string[], requested: string[], senderId: string): boolean { + if (!storedMembers.includes(senderId)) return false; + const remaining = liveMembers.filter((sessionId) => sessionId !== senderId); + if (!remaining.every((sessionId) => requested.includes(sessionId))) return false; + return requested.every((sessionId) => storedMembers.includes(sessionId)); +} + +/** Does the requested list keep every seat that is still in the group? */ +function keepsOldMembers(liveMembers: string[], requested: string[]): boolean { + return liveMembers.every((sessionId) => requested.includes(sessionId)); +} + +/** The group the seat belongs to. */ +function ownGroupId(room: WorldRoom, sessionId: string): string | undefined { + for (const [id, members] of Object.entries(room.bubbleGroups)) { + if (members.includes(sessionId)) return id; + } + return undefined; +} + +/** + * A message that names an existing group: joining it, expanding it or + * leaving it. The group id is the one the server handed out, never a new one. + */ +function updateExistingGroup(room: WorldRoom, scope: SocialScope, groupId: string, requested: string[]): void { + const existing = room.bubbleGroups[groupId]; + if (!existing) { + logger.debug('[WorldRoom] Dropped bubble_update for an unknown group'); + return; + } + const liveMembers = existing.filter((sessionId) => room.state.players.has(sessionId)); + if (isLeaveOf(liveMembers, existing, requested, scope.sessionId)) { + setGroupMembers(room, groupId, requested); + broadcastBubbleStateToClients(room); + return; + } + if (!requested.includes(scope.sessionId) || !keepsOldMembers(liveMembers, requested)) { + logger.debug('[WorldRoom] Dropped bubble_update that would take a group apart'); + return; + } + detachPeers(room, scope, requested, groupId); + setGroupMembers(room, groupId, requested); + broadcastBubbleStateToClients(room); +} + +/** + * A message without a group id: the sender forms or enlarges the group of + * its own scope. The sender has to be part of the list, and the named peers + * move into that group. + */ +function formOwnGroup(room: WorldRoom, scope: SocialScope, requested: string[]): void { + if (!requested.includes(scope.sessionId)) { + logger.debug('[WorldRoom] Dropped bubble_update of a seat outside its own group'); + return; + } + const own = ownGroupId(room, scope.sessionId); + if (requested.length < 2) { + // The sender names only itself: it leaves its own group. + if (!own) return; + delete room.bubbleGroups[own]; + broadcastBubbleStateToClients(room); + return; + } + detachPeers(room, scope, requested, own); + if (own) delete room.bubbleGroups[own]; + room.bubbleGroups[canonicalGroupId(requested)] = requested; + broadcastBubbleStateToClients(room); +} + +/** Move the named peers out of their own group into the group of the sender. */ +function detachPeers(room: WorldRoom, scope: SocialScope, requested: string[], keepGroupId: string | undefined): void { + for (const sessionId of requested) { + if (sessionId === scope.sessionId) continue; + const other = ownGroupId(room, sessionId); + if (!other || other === keepGroupId) continue; + const members = room.bubbleGroups[other].filter((member) => member !== sessionId); + if (members.length < 2) delete room.bubbleGroups[other]; + else room.bubbleGroups[other] = members; + } +} + +/** Write the new member list of a group. A group needs at least two members. */ +function setGroupMembers(room: WorldRoom, groupId: string, members: string[]): void { + if (members.length < 2) { + delete room.bubbleGroups[groupId]; + return; } - broadcastBubbleState(room); + room.bubbleGroups[groupId] = members; } diff --git a/apps/server/src/rooms/handlers/dndHandler.ts b/apps/server/src/rooms/handlers/dndHandler.ts index 0d162885..82239d43 100644 --- a/apps/server/src/rooms/handlers/dndHandler.ts +++ b/apps/server/src/rooms/handlers/dndHandler.ts @@ -2,15 +2,22 @@ import type { Client } from 'colyseus'; import { logger } from '../../logger.js'; import type { WorldRoom } from '../WorldRoom.js'; import { broadcastToMap } from '../utils/broadcastHelpers.js'; +import { countRejectedPayload } from '../validation/rejectionMetrics.js'; +import { dndSchema } from '../validation/worldPayloadSchemas.js'; -export function handleDndStatus(room: WorldRoom, client: Client, data: { dnd: boolean }): void { +export function handleDndStatus(room: WorldRoom, client: Client, data: unknown): void { + const parsed = dndSchema.safeParse(data); + if (!parsed.success) { + countRejectedPayload('dnd_status', 'schema'); + return; + } const player = room.state.players.get(client.sessionId); if (!player) { logger.warn('[WorldRoom] DND status from unknown player:', client.sessionId); return; } - player.dnd = data.dnd; - logger.info('[WorldRoom] Player', client.sessionId, 'DND status:', data.dnd); + player.dnd = parsed.data.dnd; + logger.info('[WorldRoom] Player', client.sessionId, 'DND status:', parsed.data.dnd); broadcastToMap( room, @@ -18,7 +25,7 @@ export function handleDndStatus(room: WorldRoom, client: Client, data: { dnd: bo 'player_dnd', { id: client.sessionId, - dnd: data.dnd, + dnd: parsed.data.dnd, }, client, ); diff --git a/apps/server/src/rooms/handlers/editorAuthorization.integration.test.ts b/apps/server/src/rooms/handlers/editorAuthorization.integration.test.ts new file mode 100644 index 00000000..5edc6609 --- /dev/null +++ b/apps/server/src/rooms/handlers/editorAuthorization.integration.test.ts @@ -0,0 +1,305 @@ +/** + * Editor updates only reach clients that share the sender map with a current owner or admin role. + * + * A real Colyseus server with the real WorldRoom (see + * testUtils/matchmakeHarness.ts), a real PostgreSQL database (db.js is NOT + * mocked) and real @colyseus/sdk clients. Two maps of one tenant separate the + * recipients: every join starts on the `office` map, and one recipient moves + * to the `studio` map through the real `change_map` handler. Seeds come from + * testUtils/worldSeed.ts, roles change through the real membership row. + * + * A sender never receives its own broadcast, so every case pairs the sender + * with one or two receiving clients. Message shapes match the web client: + * `{ type: 'reload_all' }` after saving, `{ type: 'zone', polys: [...] }` + * after moving through the world. + * + * Three cases fail on the unfixed basis: a member sender reaches the room, a + * foreign mapId steers the broadcast onto the named map, and a sender demoted + * after joining keeps reaching the room. The two owner/admin controls hold + * with and without the fix. + */ + +import crypto from 'node:crypto'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import { createPrismaClient } from '../../db.js'; +import { cleanupTenants, seedMember, seedTenant } from '../../testUtils/worldSeed.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('editorAuthorization.integration.test.ts needs DATABASE_URL for a migrated test database'); +} + +const prisma = createPrismaClient(); +const packUuids: string[] = []; +const openRooms: Room[] = []; +let server: MatchmakeTestServer; +let tenantId = ''; +let tenantSlug = ''; +let fixturePackUuid = ''; +let officeId = ''; +let studioId = ''; + +/** A zone payload shaped like the web client sends after moving through the world. */ +const ZONE_POLYS = [ + { name: 'hall', points: [{ x: 10, y: 10 }, { x: 60, y: 10 }, { x: 60, y: 60 }] }, +]; + +/** + * One global (tenantId null) avatar pack so a join that passes the gate can + * run to completion. Real fixture row, not a mock: without any pack in scope + * even a fully authorized join is refused later in onJoin. + */ +async function seedGlobalAvatarPack(): Promise { + const uuid = `edauth-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'editor authorization join fixture', + author: 'edauth-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +function joinOptions(): Record { + return { + tenant: tenantSlug, + // A real client always names its avatar; without one even an authorized + // join stops later in onJoin, which would blur the editor signal. + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; +} + +async function joinWorld(identity: string, token: string): Promise<{ room?: Room; error?: unknown }> { + const client = new Client(server.base); + client.auth.token = token; + try { + const room = await client.joinOrCreate('world', { ...joinOptions(), identity }); + return { room }; + } catch (error) { + return { error }; + } +} + +/** Remember a room so the suite leaves it even when the case fails midway. */ +function track(room: Room | undefined): void { + if (room) openRooms.push(room); +} + +/** Cleanup-only leave: never fail the test, never hang on a swept room. */ +async function leaveQuietly(room: Room | undefined): Promise { + if (!room) return; + await Promise.race([room.leave().catch(() => {}), sleep(3_000)]); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Collect one message type; the suite polls the array with a bounded wait. */ +function collectEditorUpdates(room: Room): { received: unknown[] } { + const received: unknown[] = []; + room.onMessage('editor_update', (payload: unknown) => { + received.push(payload); + }); + return { received }; +} + +function ownMapId(room: Room): string | undefined { + const player = room.state.players.get(room.sessionId) as { mapId?: unknown } | undefined; + return typeof player?.mapId === 'string' ? player.mapId : undefined; +} + +/** Real waiting with polling on the condition, never a fixed sleep as proof. */ +async function waitForCount(received: unknown[], count: number, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (received.length < count) { + if (Date.now() > deadline) return false; + await sleep(100); + } + return true; +} + +/** The authoritative seat map of this client, read from the synced room state. */ +async function waitForOwnMap(room: Room, mapId: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (ownMapId(room) !== mapId) { + if (Date.now() > deadline) return false; + await sleep(100); + } + return true; +} + +/** Move through the real map switch handler; true once the seat sits on the target map. */ +async function moveToMap(room: Room, mapId: string): Promise { + room.send('change_map', { mapId }); + return waitForOwnMap(room, mapId, 10_000); +} + +/** Demote through the real membership row, as an admin console would. */ +async function demoteToMember(userId: string): Promise { + await prisma.membership.update({ + where: { tenantId_userId: { tenantId, userId } }, + data: { role: 'member' }, + }); +} + +beforeAll(async () => { + const tenant = await seedTenant(prisma); + tenantId = tenant.id; + tenantSlug = tenant.slug; + await seedGlobalAvatarPack(); + // The tenant default map name is `office`, so every join starts there; the + // second map only hosts recipients moved over explicitly below. + officeId = (await prisma.map.create({ data: { tenantId, name: 'office', meta: {} } })).id; + studioId = (await prisma.map.create({ data: { tenantId, name: 'studio', meta: {} } })).id; + server = await startMatchmakeServer(); +}); + +beforeEach(async () => { + await disposeAllRooms(); +}); + +afterEach(async () => { + while (openRooms.length > 0) { + await leaveQuietly(openRooms.pop()); + } +}); + +afterAll(async () => { + await stopMatchmakeServer(server); + await prisma.presence.deleteMany({ where: { tenantId } }); + await prisma.room.deleteMany({ where: { tenantId } }); + await prisma.npc.deleteMany({ where: { tenantId } }); + await prisma.map.deleteMany({ where: { tenantId } }); + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await cleanupTenants(prisma, [tenantId]); + await prisma.$disconnect(); +}); + +describe('editor updates sent by a member', () => { + it('reach no other client on the same map', async () => { + const sender = await seedMember(prisma, tenantId, { role: 'member' }); + const receiver = await seedMember(prisma, tenantId, { role: 'admin' }); + const senderJoin = await joinWorld(sender.userId, sender.token); + const receiverJoin = await joinWorld(receiver.userId, receiver.token); + track(senderJoin.room); + track(receiverJoin.room); + expect(senderJoin.error, 'member sender must join the world').toBeUndefined(); + expect(receiverJoin.error, 'admin receiver must join the world').toBeUndefined(); + if (!senderJoin.room || !receiverJoin.room) throw new Error('member case created no rooms'); + expect(await waitForOwnMap(senderJoin.room, officeId, 10_000), 'sender starts on the office map').toBe(true); + expect(await waitForOwnMap(receiverJoin.room, officeId, 10_000), 'receiver starts on the office map').toBe( + true, + ); + const { received } = collectEditorUpdates(receiverJoin.room); + senderJoin.room.send('editor_update', { type: 'reload_all' }); + await sleep(1_500); + expect(received).toEqual([]); + }, 30_000); +}); + +describe('editor updates naming another map', () => { + it('reach no client on the named map', async () => { + const sender = await seedMember(prisma, tenantId, { role: 'admin' }); + const sameMap = await seedMember(prisma, tenantId, { role: 'admin' }); + const otherMap = await seedMember(prisma, tenantId, { role: 'owner' }); + const senderJoin = await joinWorld(sender.userId, sender.token); + const sameJoin = await joinWorld(sameMap.userId, sameMap.token); + const otherJoin = await joinWorld(otherMap.userId, otherMap.token); + track(senderJoin.room); + track(sameJoin.room); + track(otherJoin.room); + expect(senderJoin.error, 'admin sender must join the world').toBeUndefined(); + expect(sameJoin.error, 'same-map receiver must join the world').toBeUndefined(); + expect(otherJoin.error, 'other-map receiver must join the world').toBeUndefined(); + if (!senderJoin.room || !sameJoin.room || !otherJoin.room) throw new Error('foreign map case created no rooms'); + expect(await waitForOwnMap(senderJoin.room, officeId, 10_000), 'sender starts on the office map').toBe(true); + expect(await waitForOwnMap(sameJoin.room, officeId, 10_000), 'same-map receiver stays on office').toBe(true); + expect(await moveToMap(otherJoin.room, studioId), 'other-map receiver moves to the studio map').toBe(true); + const foreign = collectEditorUpdates(otherJoin.room); + senderJoin.room.send('editor_update', { type: 'zone', polys: ZONE_POLYS, mapId: studioId }); + await sleep(1_500); + expect(foreign.received).toEqual([]); + }, 30_000); +}); + +describe('editor updates sent after a demotion', () => { + it('reach no other client on the same map', async () => { + const sender = await seedMember(prisma, tenantId, { role: 'admin' }); + const receiver = await seedMember(prisma, tenantId, { role: 'admin' }); + const senderJoin = await joinWorld(sender.userId, sender.token); + const receiverJoin = await joinWorld(receiver.userId, receiver.token); + track(senderJoin.room); + track(receiverJoin.room); + expect(senderJoin.error, 'admin sender must join the world').toBeUndefined(); + expect(receiverJoin.error, 'admin receiver must join the world').toBeUndefined(); + if (!senderJoin.room || !receiverJoin.room) throw new Error('demotion case created no rooms'); + expect(await waitForOwnMap(senderJoin.room, officeId, 10_000), 'sender starts on the office map').toBe(true); + expect(await waitForOwnMap(receiverJoin.room, officeId, 10_000), 'receiver starts on the office map').toBe( + true, + ); + const { received } = collectEditorUpdates(receiverJoin.room); + await demoteToMember(sender.userId); + senderJoin.room.send('editor_update', { type: 'reload_all' }); + await sleep(1_500); + expect(received).toEqual([]); + }, 30_000); +}); + +describe('editor updates sent by an owner', () => { + it('reach peers on the sender map', async () => { + const sender = await seedMember(prisma, tenantId, { role: 'owner' }); + const receiver = await seedMember(prisma, tenantId, { role: 'admin' }); + const senderJoin = await joinWorld(sender.userId, sender.token); + const receiverJoin = await joinWorld(receiver.userId, receiver.token); + track(senderJoin.room); + track(receiverJoin.room); + expect(senderJoin.error, 'owner sender must join the world').toBeUndefined(); + expect(receiverJoin.error, 'admin receiver must join the world').toBeUndefined(); + if (!senderJoin.room || !receiverJoin.room) throw new Error('owner control created no rooms'); + expect(await waitForOwnMap(senderJoin.room, officeId, 10_000), 'sender starts on the office map').toBe(true); + expect(await waitForOwnMap(receiverJoin.room, officeId, 10_000), 'receiver starts on the office map').toBe( + true, + ); + const { received } = collectEditorUpdates(receiverJoin.room); + senderJoin.room.send('editor_update', { type: 'reload_all' }); + expect(await waitForCount(received, 1, 10_000), 'peer receives the owner update').toBe(true); + expect((received[0] as { type?: unknown } | undefined)?.type).toBe('reload_all'); + }, 30_000); +}); + +describe('editor updates sent by an admin', () => { + it('reach peers on the sender map', async () => { + const sender = await seedMember(prisma, tenantId, { role: 'admin' }); + const receiver = await seedMember(prisma, tenantId, { role: 'owner' }); + const senderJoin = await joinWorld(sender.userId, sender.token); + const receiverJoin = await joinWorld(receiver.userId, receiver.token); + track(senderJoin.room); + track(receiverJoin.room); + expect(senderJoin.error, 'admin sender must join the world').toBeUndefined(); + expect(receiverJoin.error, 'owner receiver must join the world').toBeUndefined(); + if (!senderJoin.room || !receiverJoin.room) throw new Error('admin control created no rooms'); + expect(await waitForOwnMap(senderJoin.room, officeId, 10_000), 'sender starts on the office map').toBe(true); + expect(await waitForOwnMap(receiverJoin.room, officeId, 10_000), 'receiver starts on the office map').toBe( + true, + ); + const { received } = collectEditorUpdates(receiverJoin.room); + senderJoin.room.send('editor_update', { type: 'zone', polys: ZONE_POLYS }); + expect(await waitForCount(received, 1, 10_000), 'peer receives the admin update').toBe(true); + expect((received[0] as { type?: unknown } | undefined)?.type).toBe('zone'); + }, 30_000); +}); diff --git a/apps/server/src/rooms/handlers/editorAuthorization.ts b/apps/server/src/rooms/handlers/editorAuthorization.ts new file mode 100644 index 00000000..5ac66890 --- /dev/null +++ b/apps/server/src/rooms/handlers/editorAuthorization.ts @@ -0,0 +1,58 @@ +import { z } from 'zod'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { hasTenantAccess } from '../../api/utils/tenantMembership.js'; +import { editorZoneSchema, MAX_EDITOR_ZONES } from '../../api/routes/editorStateSchema.js'; +import { logger } from '../../logger.js'; + +/** Prisma surface the editor gate needs: the membership row for the role + * check, the map row for the tenant check, and whatever the shared tenant + * access rule reads. Callers pass the room's own client instance. */ +export type EditorAuthPrisma = Pick; + +/** + * Live `editor_update` payloads the world room accepts. The `reload_all` + * variant carries nothing but the optional sender-declared `mapId`; the + * `zone` variant carries the zone list, validated zone by zone against the + * same schema the editor-state route uses. Unknown keys on the `zone` + * variant are dropped by the parse, so only typed data reaches the + * broadcast. An unknown `type` fails the parse and the message is dropped. + */ +const mapIdSchema = z.string().min(1).max(256).optional(); + +export const editorUpdateSchema = z.discriminatedUnion('type', [ + z.object({ type: z.literal('reload_all'), mapId: mapIdSchema }).strict(), + z.object({ + type: z.literal('zone'), + mapId: mapIdSchema, + polys: z.array(editorZoneSchema).max(MAX_EDITOR_ZONES), + }), +]); + +export type EditorUpdateInput = z.infer; + +/** + * Fresh, database-backed editor proof for one live update: the sender holds an + * active membership with role `owner` or `admin` in the proven tenant (plus + * the shared tenant access rule), and the map belongs to that same tenant. + * Fails closed (false) on any mismatch or lookup error. + */ +export async function authorizeEditorUpdate( + prisma: EditorAuthPrisma, + userId: string, + tenantId: string, + mapId: string, +): Promise { + try { + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId, userId } }, + select: { role: true }, + }); + if (membership?.role !== 'owner' && membership?.role !== 'admin') return false; + if (!(await hasTenantAccess(prisma, userId, tenantId))) return false; + const map = await prisma.map.findUnique({ where: { id: mapId }, select: { tenantId: true } }); + return map?.tenantId === tenantId; + } catch (e: unknown) { + logger.debug('[WorldRoom] Editor authorization lookup failed', e); + return false; + } +} diff --git a/apps/server/src/rooms/handlers/editorHandler.ts b/apps/server/src/rooms/handlers/editorHandler.ts index 768860aa..2ec27a55 100644 --- a/apps/server/src/rooms/handlers/editorHandler.ts +++ b/apps/server/src/rooms/handlers/editorHandler.ts @@ -1,41 +1,90 @@ import type { Client } from 'colyseus'; import { logger } from '../../logger.js'; -import { createPrismaClient } from '../../db.js'; import type { WorldRoom } from '../WorldRoom.js'; import { broadcastToMap } from '../utils/broadcastHelpers.js'; import { invalidateZoneCache } from './zoneLockHandler.js'; import { refreshZonesAndRecompute } from '../audioZones/runtime.js'; +import { requireWorldAuth, type WorldAuth } from '../lifecycle/onAuth.js'; +import { authorizeEditorUpdate, editorUpdateSchema } from './editorAuthorization.js'; export function handleEditorUpdate( room: WorldRoom, client: Client, data: { type: string; [key: string]: unknown }, ): void { - logger.debug('[WorldRoom] Editor update from:', client.sessionId, 'type:', data.type); + const parsed = editorUpdateSchema.safeParse(data); + if (!parsed.success) { + logger.debug('[WorldRoom] Dropped editor_update with an unknown type'); + return; + } const player = room.state.players.get(client.sessionId); - const mapId = typeof data.mapId === 'string' ? data.mapId : player?.mapId; - if (mapId) { - broadcastToMap(room, mapId, 'editor_update', data, client); - } else { - // No resolvable mapId: cannot tenant-scope (broadcastToMap filters - // recipients by their player.mapId). Drop rather than room-broadcast so one - // tenant's editor geometry never bleeds to another in a shared room. Every - // real edit carries the editor's map (data.mapId or the player's current - // mapId), so this only drops anomalous player-less/mapless events. - logger.debug('[WorldRoom] Dropped editor_update without a resolvable mapId (cannot tenant-scope)'); + if (!player || player.isNpc) { + logger.debug('[WorldRoom] Dropped editor_update without a human player seat'); + return; + } + let auth: WorldAuth; + try { + auth = requireWorldAuth(client); + } catch { + logger.debug('[WorldRoom] Dropped editor_update without proven world auth'); + return; + } + if (auth.isNpc) { + logger.debug('[WorldRoom] Dropped editor_update from a service seat'); + return; + } + const tenantId = auth.tenantId; + if (!tenantId) { + logger.debug('[WorldRoom] Dropped editor_update without a proven tenant'); + return; } - // Invalidate zone cache on editor updates so locks use fresh zone data - invalidateZoneCache(room.zoneLockState); - // H4: zone polygons may have moved -- recompute audio-zone islands for - // everyone on this map against the fresh geometry. Fire-and-forget: this - // handler is synchronous (Colyseus onMessage), and a brief delay before - // recomputation is acceptable (the reconciler heals any window). - if (mapId) { - const prisma = room.prismaForPresence ?? createPrismaClient(); - void refreshZonesAndRecompute(room, mapId, prisma).catch((e) => - logger.debug('[WorldRoom] Failed to recompute audio zones after editor_update', e), - ); + // The server-side player map is authoritative. A sender-declared mapId that + // names a different map is dropped; it is never forwarded (see below). + const mapId = player.mapId; + if (!mapId) { + logger.debug('[WorldRoom] Dropped editor_update without a server-side map'); + return; } + if (parsed.data.mapId !== undefined && parsed.data.mapId !== mapId) { + logger.debug('[WorldRoom] Dropped editor_update for a foreign map'); + return; + } + // The room's own database handle proves the role below. Without it there is + // no fresh proof, so the update is dropped instead of opening a new handle. + const prisma = room.prismaForPresence; + if (!prisma) { + logger.debug('[WorldRoom] Dropped editor_update without room database state'); + return; + } + const userId = auth.identity; + void authorizeEditorUpdate(prisma, userId, tenantId, mapId) + .then((allowed) => { + if (!allowed) { + logger.debug('[WorldRoom] Dropped editor_update without owner/admin proof'); + return; + } + // Re-check the seat after the database round trip: the sender may have + // left or switched maps while the proof was loading. Only the same + // player on the same map receives the broadcast below. + const current = room.state.players.get(client.sessionId); + if (current !== player || current.mapId !== mapId || current.isNpc) { + logger.debug('[WorldRoom] Dropped editor_update after the sender seat changed'); + return; + } + // The canonical map always wins: a sender-declared mapId is never + // forwarded, so geometry cannot leak onto another map. Only parsed + // data is broadcast, never the raw sender payload. + broadcastToMap(room, mapId, 'editor_update', { ...parsed.data, mapId }, client); + // Zone locks cache per map, so only this map is invalidated; the + // recompute below then refreshes exactly the islands on this map. + invalidateZoneCache(room.zoneLockState, mapId); + void refreshZonesAndRecompute(room, mapId, prisma).catch((e) => + logger.debug('[WorldRoom] Failed to recompute audio zones after editor_update', e), + ); + }) + .catch((e: unknown) => { + logger.debug('[WorldRoom] Failed to authorize editor_update', e); + }); } // Subscribe to map updates via Presence (works across processes if Redis diff --git a/apps/server/src/rooms/handlers/playerHandlers.ts b/apps/server/src/rooms/handlers/playerHandlers.ts index 8584cd01..f00256e1 100644 --- a/apps/server/src/rooms/handlers/playerHandlers.ts +++ b/apps/server/src/rooms/handlers/playerHandlers.ts @@ -4,57 +4,93 @@ import type { WorldRoom } from '../WorldRoom.js'; import { isMovementBlocked } from './zoneLockHandler.js'; import { broadcastToMap } from '../utils/broadcastHelpers.js'; import { trackMove } from '../audioZones/runtime.js'; +import { getBoundsPxForMap } from '../utils/mapBoundsHelpers.js'; +import { countRejectedPayload } from '../validation/rejectionMetrics.js'; +import { moveSchema } from '../validation/worldPayloadSchemas.js'; export interface MoveData { + x: number; + y: number; + direction: 'up' | 'down' | 'left' | 'right'; +} + +const MOVE_INTERVAL_MS = 80; + +// Full pixel size of the cached map. getBoundsPxForMap insets by half a tile, +// so the closed window is [0, width] x [0, height], not that inset rectangle. +// A map missing from mapCache is rejected here; the room-level fallback is not used. +function isMoveInsideMap(room: WorldRoom, mapId: string, x: number, y: number): boolean { + if (!room.mapCache.has(mapId)) return false; + const bounds = getBoundsPxForMap(room, mapId); + const entry = room.mapCache.get(mapId); + if (!bounds || !entry) return false; + const width = entry.widthTiles * entry.tileWidthPx; + const height = entry.heightTiles * entry.tileHeightPx; + return x >= 0 && x <= width && y >= 0 && y <= height; +} + +function publishMove(room: WorldRoom, client: Client, player: { x: number; y: number; direction: string; + mapId: string; + mapName: string; +}, move: MoveData): void { + player.x = move.x; + player.y = move.y; + player.direction = move.direction; + + // H4: recompute audio-zone island membership on every accepted move. + trackMove(room, client.sessionId); + + broadcastToMap( + room, + player.mapId, + 'player_moved', + { + id: client.sessionId, + x: move.x, + y: move.y, + direction: move.direction, + mapId: player.mapId, + mapName: player.mapName, + }, + client, + ); } -// Move handler with throttling (~12.5 Hz). Updates `lastSeen` on every -// invocation, so moves act as implicit heartbeats. +// Move handler with throttling (~12.5 Hz). Schema and map bounds run before +// any timestamp, throttle, or player-state write. An accepted move still +// updates `lastSeen` before the throttle, so it acts as an implicit heartbeat. export function createMoveHandler(room: WorldRoom) { const lastMove: Map = new Map(); - return (client: Client, data: MoveData): void => { - const now = Date.now(); - room.lastSeen.set(client.sessionId, now); - const prev = lastMove.get(client.sessionId) || 0; - if (now - prev < 80) { + return (client: Client, data: unknown): void => { + const parsed = moveSchema.safeParse(data); + if (!parsed.success) { + countRejectedPayload('move', 'schema'); return; } - lastMove.set(client.sessionId, now); const player = room.state.players.get(client.sessionId); if (!player) { logger.warn('[WorldRoom] Move from unknown player:', client.sessionId); return; } - const moveCheck = isMovementBlocked(room.zoneLockState, client.sessionId, player.mapId, { x: data.x, y: data.y }); + const { x, y } = parsed.data; + if (!isMoveInsideMap(room, player.mapId, x, y)) { + countRejectedPayload('move', 'bounds'); + return; + } + const now = Date.now(); + room.lastSeen.set(client.sessionId, now); + const prev = lastMove.get(client.sessionId) || 0; + if (now - prev < MOVE_INTERVAL_MS) return; + lastMove.set(client.sessionId, now); + const moveCheck = isMovementBlocked(room.zoneLockState, client.sessionId, player.mapId, { x, y }); if (moveCheck.blocked) { client.send('zone_move_blocked', { zoneName: moveCheck.zoneName }); return; } - - player.x = data.x; - player.y = data.y; - player.direction = data.direction; - - // H4: recompute audio-zone island membership on every accepted move. - trackMove(room, client.sessionId); - - broadcastToMap( - room, - player.mapId, - 'player_moved', - { - id: client.sessionId, - x: data.x, - y: data.y, - direction: data.direction, - mapId: player.mapId, - mapName: player.mapName, - }, - client, - ); + publishMove(room, client, player, parsed.data); }; } diff --git a/apps/server/src/rooms/handlers/socialAuthorization.integration.test.ts b/apps/server/src/rooms/handlers/socialAuthorization.integration.test.ts new file mode 100644 index 00000000..3e8a94e9 --- /dev/null +++ b/apps/server/src/rooms/handlers/socialAuthorization.integration.test.ts @@ -0,0 +1,596 @@ +/** + * Bubble and zone-lock operations stay inside the sender's tenant and map. + * + * Both clients send the host slug as `options.tenant` (the room partition + * key). The guest session belongs to the other tenant. That mismatch is + * admitted while `ZONE_PRIVACY_TENANT_ENFORCE` is not `'true'`, so both seats + * land in one room. Shapes follow the web client, plus `zone_access_request` + * `{ zoneName, mapId }` which only the room handler reads. The zone polygon + * is stored on the zone row and on `Map.meta.zones`. + */ + +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { matchMaker } from 'colyseus'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION, type ZoneLockInfo } from '@meetropolis/shared'; +import crypto from 'node:crypto'; +import { createPrismaClient } from '../../db.js'; +import type { WorldRoom } from '../WorldRoom.js'; +import { cleanupTenants, seedMember, seedTenant, type SeededMember } from '../../testUtils/worldSeed.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('socialAuthorization.integration.test.ts needs DATABASE_URL for a migrated test database'); +} + +const prisma = createPrismaClient(); +const QUIET_MS = 1_500; +const STEP_MS = 10_000; +const CASE_MS = 30_000; +const ZONE_NAME = 'north-wing'; +const FORGED_GROUP_ID = 'client-supplied-group'; +const INSIDE = { x: 40, y: 40 }; +const OUTSIDE = { x: 400, y: 400 }; +const ZONE_POINTS = [ + { x: 0, y: 0 }, + { x: 80, y: 0 }, + { x: 80, y: 80 }, + { x: 0, y: 80 }, +]; + +const packUuids: string[] = []; +const openRooms: Room[] = []; +let server: MatchmakeTestServer | undefined; +let hostId = ''; +let guestId = ''; +let hostSlug = ''; +let avatarId = ''; +let officeId = ''; +let studioId = ''; + +function sleep(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +async function waitUntil(predicate: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) return false; + await sleep(50); + } + return true; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function stringList(value: unknown): string[] { + if (!Array.isArray(value)) return []; + return value.filter((item): item is string => typeof item === 'string'); +} + +function worldOf(room: Room): WorldRoom { + const found = matchMaker.getLocalRoomById(room.roomId); + if (!found) throw new Error('world room is not running'); + return found as WorldRoom; +} + +function lockKey(): string { + return `${officeId}:${ZONE_NAME}`; +} + +function zoneLock(room: Room): ZoneLockInfo | undefined { + return worldOf(room).zoneLockState.locks.get(lockKey()); +} + +function accessIds(room: Room): string[] { + return [...(zoneLock(room)?.accessList ?? [])]; +} + +function pendingIds(room: Room): string[] { + return zoneLock(room)?.pendingRequests.map((request) => request.sessionId) ?? []; +} + +function groupMembers(room: Room, sessionId: string): string[] | undefined { + for (const members of Object.values(worldOf(room).bubbleGroups)) { + if (members.includes(sessionId)) return [...members]; + } + return undefined; +} + +function groupKey(room: Room, sessionId: string): string | undefined { + for (const [id, members] of Object.entries(worldOf(room).bubbleGroups)) { + if (members.includes(sessionId)) return id; + } + return undefined; +} + +function playerMap(room: Room): string | undefined { + const player = room.state.players.get(room.sessionId) as { mapId?: unknown } | undefined; + return typeof player?.mapId === 'string' ? player.mapId : undefined; +} + +function collect(room: Room, type: string): unknown[] { + const received: unknown[] = []; + room.onMessage(type, (payload: unknown) => { + received.push(payload); + }); + return received; +} + +function bubbleMentions(payloads: unknown[], sessionId: string): boolean { + return payloads.some((payload) => { + if (!isRecord(payload)) return false; + if (stringList(payload.members).includes(sessionId)) return true; + if (!Array.isArray(payload.groups)) return false; + return payload.groups.some((group) => isRecord(group) && stringList(group.members).includes(sessionId)); + }); +} + +function bubbleUsesId(payloads: unknown[], groupId: string): boolean { + return payloads.some((payload) => { + if (!isRecord(payload) || !Array.isArray(payload.groups)) return false; + return payload.groups.some((group) => isRecord(group) && group.id === groupId); + }); +} + +function lockMentions(payloads: unknown[], zoneName: string, mapId: string): boolean { + return payloads.some((payload) => { + if (!isRecord(payload) || !Array.isArray(payload.locks)) return false; + return payload.locks.some((lock) => isRecord(lock) && lock.zoneName === zoneName && lock.mapId === mapId); + }); +} + +function deniedZone(payloads: unknown[], zoneName: string): boolean { + return payloads.some((payload) => isRecord(payload) && payload.zoneName === zoneName); +} + +async function leaveQuietly(room: Room | undefined): Promise { + if (!room) return; + await Promise.race([room.leave().catch(() => undefined), sleep(3_000)]); +} + +async function connect(token: string, at: { x: number; y: number }): Promise { + const client = new Client(server?.base ?? ''); + client.auth.token = token; + const room = await client.joinOrCreate('world', { + tenant: hostSlug, + avatarId, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + x: at.x, + y: at.y, + }); + openRooms.push(room); + const seated = await waitUntil(() => worldOf(room).state.players.has(room.sessionId), STEP_MS); + expect(seated, 'the client has a seat').toBe(true); + return room; +} + +function expectSameRoom(rooms: Room[]): void { + const roomId = rooms[0]?.roomId; + expect(roomId, 'a world room exists').toBeTruthy(); + for (const room of rooms) expect(room.roomId, 'clients share one world room').toBe(roomId); +} + +async function waitForMap(room: Room, mapId: string): Promise { + const arrived = await waitUntil(() => playerMap(room) === mapId, STEP_MS); + expect(arrived, 'the seat is on the expected map').toBe(true); +} + +async function formGroup(sender: Room, peer: Room): Promise { + sender.send('bubble_update', { members: [sender.sessionId, peer.sessionId] }); + const formed = await waitUntil( + () => (groupMembers(sender, sender.sessionId) ?? []).includes(peer.sessionId), + STEP_MS, + ); + expect(formed, 'the sender and the peer share a group').toBe(true); +} + +async function lockZone(room: Room): Promise { + room.send('zone_lock', { zoneName: ZONE_NAME }); + const locked = await waitUntil(() => accessIds(room).includes(room.sessionId), STEP_MS); + expect(locked, 'the zone is locked by the sender').toBe(true); +} + +async function moveTo(room: Room, mapId: string): Promise { + room.send('change_map', { mapId }); + await waitForMap(room, mapId); +} + +async function seedPlayers(tenantId: string, count: number): Promise { + return Promise.all(Array.from({ length: count }, () => seedMember(prisma, tenantId))); +} + +async function seedGlobalAvatarPack(): Promise { + const uuid = `world-social-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'shared world join fixture', + author: 'world-social-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + avatarId = `${uuid}:business_man`; +} + +async function seedMap(tenantId: string, name: string, withZone: boolean): Promise { + const created = await prisma.map.create({ + data: { + tenantId, + name, + width: 50, + height: 50, + tileWidth: 16, + tileHeight: 16, + meta: withZone ? { spawn: INSIDE, zones: [{ name: ZONE_NAME, points: ZONE_POINTS }] } : {}, + }, + }); + if (!withZone) return created.id; + const floor = await prisma.room.create({ data: { name: 'floor', tenantId, mapId: created.id } }); + await prisma.zone.create({ + data: { + name: ZONE_NAME, + polygon: ZONE_POINTS, + type: 'default', + roomId: floor.id, + mapId: created.id, + tenantId, + }, + }); + return created.id; +} + +beforeAll(async () => { + const host = await seedTenant(prisma); + const guest = await seedTenant(prisma); + hostId = host.id; + hostSlug = host.slug; + guestId = guest.id; + await seedGlobalAvatarPack(); + officeId = await seedMap(hostId, 'office', true); + studioId = await seedMap(hostId, 'studio', false); + await seedMap(guestId, 'office', false); + server = await startMatchmakeServer(); +}, CASE_MS); + +beforeEach(async () => { + await disposeAllRooms(); +}, CASE_MS); + +afterEach(async () => { + while (openRooms.length > 0) await leaveQuietly(openRooms.pop()); +}, CASE_MS); + +afterAll(async () => { + if (server) await stopMatchmakeServer(server); + const tenantIds = [hostId, guestId].filter((id) => id.length > 0); + if (tenantIds.length > 0) { + await prisma.zone.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.presence.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.room.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.map.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await cleanupTenants(prisma, tenantIds); + } + if (packUuids.length > 0) await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await prisma.$disconnect(); +}, CASE_MS); + +describe('bubble updates from another tenant', () => { + it('leave the other tenant group unchanged', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const eve = await connect(guest.token, INSIDE); + expectSameRoom([alice, bob, eve]); + const seen = collect(alice, 'bubble_state'); + await formGroup(alice, bob); + expect(await waitUntil(() => seen.length > 0, STEP_MS), 'the group was announced').toBe(true); + seen.length = 0; + eve.send('bubble_update', { members: [eve.sessionId, alice.sessionId] }); + await sleep(QUIET_MS); + expect(groupMembers(alice, alice.sessionId)).toEqual([alice.sessionId, bob.sessionId]); + expect(groupMembers(eve, eve.sessionId)).toBeUndefined(); + expect(seen).toEqual([]); + }, CASE_MS); +}); + +describe('bubble updates from another map', () => { + it('leave the group on the original map unchanged', async () => { + const [hostA, hostB, hostC] = await seedPlayers(hostId, 3); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const carol = await connect(hostC.token, INSIDE); + const eve = await connect(guest.token, INSIDE); + expectSameRoom([alice, bob, carol, eve]); + const seen = collect(alice, 'bubble_state'); + await formGroup(alice, bob); + await moveTo(carol, studioId); + expect(await waitUntil(() => seen.length > 0, STEP_MS), 'the group was announced').toBe(true); + seen.length = 0; + carol.send('bubble_update', { members: [carol.sessionId, alice.sessionId] }); + await sleep(QUIET_MS); + expect(groupMembers(alice, alice.sessionId)).toEqual([alice.sessionId, bob.sessionId]); + expect(seen).toEqual([]); + }, CASE_MS); +}); + +describe('bubble updates from outside a group', () => { + it('leave that group intact', async () => { + const [hostA, hostB, hostC] = await seedPlayers(hostId, 3); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const carol = await connect(hostC.token, INSIDE); + const eve = await connect(guest.token, INSIDE); + expectSameRoom([alice, bob, carol, eve]); + const seen = collect(alice, 'bubble_state'); + await formGroup(alice, bob); + expect(await waitUntil(() => seen.length > 0, STEP_MS), 'the group was announced').toBe(true); + seen.length = 0; + carol.send('bubble_update', { members: [alice.sessionId] }); + await sleep(QUIET_MS); + expect(groupMembers(alice, alice.sessionId)).toEqual([alice.sessionId, bob.sessionId]); + expect(seen).toEqual([]); + }, CASE_MS); +}); + +describe('bubble updates that rename a group', () => { + it('keep the existing group id', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const eve = await connect(guest.token, INSIDE); + expectSameRoom([alice, bob, eve]); + const seen = collect(alice, 'bubble_state'); + await formGroup(alice, bob); + const id = groupKey(alice, alice.sessionId); + expect(id, 'the server assigned a group id').toBeTruthy(); + expect(await waitUntil(() => seen.length > 0, STEP_MS), 'the group was announced').toBe(true); + seen.length = 0; + alice.send('bubble_update', { id: FORGED_GROUP_ID, members: [alice.sessionId, bob.sessionId] }); + await sleep(QUIET_MS); + expect(groupKey(alice, alice.sessionId)).toBe(id); + expect(Object.keys(worldOf(alice).bubbleGroups)).not.toContain(FORGED_GROUP_ID); + expect(bubbleUsesId(seen, FORGED_GROUP_ID)).toBe(false); + }, CASE_MS); +}); + +describe('bubble state sent when a client joins', () => { + it('omits groups from another tenant', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + await formGroup(alice, bob); + const eve = await connect(guest.token, INSIDE); + const full = collect(eve, 'full_state'); + const bubbles = collect(eve, 'bubble_state'); + expectSameRoom([alice, eve]); + await sleep(QUIET_MS); + expect(full.length, 'the join seed was delivered').toBeGreaterThan(0); + expect(bubbleMentions(bubbles, alice.sessionId)).toBe(false); + expect(bubbleMentions(bubbles, bob.sessionId)).toBe(false); + }, CASE_MS); +}); + +describe('zone access requests that name another map', () => { + it('leave that lock without a new request', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, OUTSIDE); + const eve = await connect(guest.token, OUTSIDE); + expectSameRoom([alice, bob, eve]); + await waitForMap(alice, officeId); + await waitForMap(bob, officeId); + const seen = collect(alice, 'zone_lock_state'); + await lockZone(alice); + seen.length = 0; + await moveTo(bob, studioId); + bob.send('zone_access_request', { zoneName: ZONE_NAME, mapId: officeId }); + await sleep(QUIET_MS); + expect(pendingIds(alice)).toEqual([]); + expect(accessIds(alice)).toEqual([alice.sessionId]); + expect(seen).toEqual([]); + }, CASE_MS); +}); + +describe('zone access responses without a pending request', () => { + it('leave the access list unchanged', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(hostA.token, INSIDE); + const carol = await connect(hostB.token, OUTSIDE); + const eve = await connect(guest.token, OUTSIDE); + expectSameRoom([alice, carol, eve]); + await waitForMap(alice, officeId); + await waitForMap(carol, officeId); + const seen = collect(carol, 'zone_lock_state'); + await lockZone(alice); + const before = accessIds(alice); + seen.length = 0; + alice.send('zone_access_response', { zoneName: ZONE_NAME, sessionId: carol.sessionId, approved: true }); + await sleep(QUIET_MS); + expect(accessIds(alice)).toEqual(before); + expect(pendingIds(alice)).toEqual([]); + expect(seen).toEqual([]); + }, CASE_MS); +}); + +describe('zone lock state sent when a client joins', () => { + it('omits locks from another tenant', async () => { + const [host] = await seedPlayers(hostId, 1); + const [guest] = await seedPlayers(guestId, 1); + const alice = await connect(host.token, INSIDE); + await waitForMap(alice, officeId); + await lockZone(alice); + const eve = await connect(guest.token, OUTSIDE); + const full = collect(eve, 'full_state'); + const locks = collect(eve, 'zone_lock_state'); + expectSameRoom([alice, eve]); + await sleep(QUIET_MS); + expect(full.length, 'the join seed was delivered').toBeGreaterThan(0); + expect(lockMentions(locks, ZONE_NAME, officeId)).toBe(false); + }, CASE_MS); +}); + +describe('a player forms a bubble', () => { + it('groups the sender with the named peer', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const seen = collect(bob, 'bubble_state'); + alice.send('bubble_update', { members: [alice.sessionId, bob.sessionId] }); + const announced = await waitUntil( + () => bubbleMentions(seen, alice.sessionId) && bubbleMentions(seen, bob.sessionId), + STEP_MS, + ); + expect(announced).toBe(true); + expect(groupMembers(alice, alice.sessionId)).toEqual([alice.sessionId, bob.sessionId]); + }, CASE_MS); +}); + +describe('a player joins a bubble', () => { + it('adds the sender to the existing group', async () => { + const [hostA, hostB, hostC] = await seedPlayers(hostId, 3); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const carol = await connect(hostC.token, INSIDE); + await formGroup(alice, bob); + const id = groupKey(alice, alice.sessionId); + expect(id).toBeTruthy(); + const seen = collect(bob, 'bubble_state'); + carol.send('bubble_update', { id, members: [alice.sessionId, bob.sessionId, carol.sessionId] }); + const joined = await waitUntil(() => bubbleMentions(seen, carol.sessionId), STEP_MS); + expect(joined).toBe(true); + expect(groupMembers(alice, alice.sessionId)).toEqual([alice.sessionId, bob.sessionId, carol.sessionId]); + }, CASE_MS); +}); + +describe('a player expands a bubble', () => { + it('adds the named peer to the sender group', async () => { + const [hostA, hostB, hostC] = await seedPlayers(hostId, 3); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const carol = await connect(hostC.token, INSIDE); + await formGroup(alice, bob); + const id = groupKey(alice, alice.sessionId); + expect(id).toBeTruthy(); + const seen = collect(carol, 'bubble_state'); + alice.send('bubble_update', { id, members: [alice.sessionId, bob.sessionId, carol.sessionId] }); + const expanded = await waitUntil(() => bubbleMentions(seen, carol.sessionId), STEP_MS); + expect(expanded).toBe(true); + expect(groupKey(alice, alice.sessionId)).toBe(id); + expect(groupMembers(alice, alice.sessionId)).toEqual([alice.sessionId, bob.sessionId, carol.sessionId]); + }, CASE_MS); +}); + +describe('a player leaves a bubble', () => { + it('keeps every member except the sender', async () => { + const [hostA, hostB, hostC] = await seedPlayers(hostId, 3); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, INSIDE); + const carol = await connect(hostC.token, INSIDE); + await formGroup(alice, bob); + const id = groupKey(alice, alice.sessionId); + expect(id).toBeTruthy(); + alice.send('bubble_update', { id, members: [alice.sessionId, bob.sessionId, carol.sessionId] }); + const expanded = await waitUntil( + () => (groupMembers(alice, alice.sessionId) ?? []).includes(carol.sessionId), + STEP_MS, + ); + expect(expanded).toBe(true); + const previous = groupMembers(alice, alice.sessionId) ?? []; + const remaining = previous.filter((sessionId) => sessionId !== alice.sessionId); + alice.send('bubble_update', { id, members: remaining }); + const left = await waitUntil(() => { + const now = groupMembers(bob, bob.sessionId); + if (!now || now.length !== remaining.length) return false; + return remaining.every((sessionId, index) => now[index] === sessionId); + }, STEP_MS); + expect(left).toBe(true); + }, CASE_MS); +}); + +describe('a player locks a zone', () => { + it('records the sender on the zone access list', async () => { + const [host] = await seedPlayers(hostId, 1); + const alice = await connect(host.token, INSIDE); + await waitForMap(alice, officeId); + const seen = collect(alice, 'zone_lock_state'); + alice.send('zone_lock', { zoneName: ZONE_NAME }); + const recorded = await waitUntil( + () => lockMentions(seen, ZONE_NAME, officeId) && accessIds(alice).includes(alice.sessionId), + STEP_MS, + ); + expect(recorded).toBe(true); + }, CASE_MS); +}); + +describe('a player approves a zone request', () => { + it('adds the requester to the access list', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, OUTSIDE); + await waitForMap(alice, officeId); + await waitForMap(bob, officeId); + await lockZone(alice); + bob.send('zone_access_request', { zoneName: ZONE_NAME, mapId: officeId }); + expect(await waitUntil(() => pendingIds(alice).includes(bob.sessionId), STEP_MS)).toBe(true); + alice.send('zone_access_response', { zoneName: ZONE_NAME, sessionId: bob.sessionId, approved: true }); + const approved = await waitUntil(() => accessIds(alice).includes(bob.sessionId), STEP_MS); + expect(approved).toBe(true); + expect(pendingIds(alice)).not.toContain(bob.sessionId); + }, CASE_MS); +}); + +describe('a player denies a zone request', () => { + it('tells the requester the zone stays closed', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, OUTSIDE); + await waitForMap(alice, officeId); + await waitForMap(bob, officeId); + await lockZone(alice); + const denied = collect(bob, 'zone_access_denied'); + bob.send('zone_access_request', { zoneName: ZONE_NAME, mapId: officeId }); + expect(await waitUntil(() => pendingIds(alice).includes(bob.sessionId), STEP_MS)).toBe(true); + alice.send('zone_access_response', { zoneName: ZONE_NAME, sessionId: bob.sessionId, approved: false }); + const told = await waitUntil(() => deniedZone(denied, ZONE_NAME), STEP_MS); + expect(told).toBe(true); + expect(accessIds(alice)).toEqual([alice.sessionId]); + expect(pendingIds(alice)).not.toContain(bob.sessionId); + }, CASE_MS); +}); + +describe('a player leaves the room', () => { + it('releases the zone lock when nobody with access remains', async () => { + const [hostA, hostB] = await seedPlayers(hostId, 2); + const alice = await connect(hostA.token, INSIDE); + const bob = await connect(hostB.token, OUTSIDE); + await waitForMap(alice, officeId); + await waitForMap(bob, officeId); + await lockZone(alice); + const seen = collect(bob, 'zone_lock_state'); + await alice.leave(); + const released = await waitUntil(() => !zoneLock(bob) && seen.length > 0, STEP_MS); + expect(released).toBe(true); + expect(lockMentions(seen, ZONE_NAME, officeId)).toBe(false); + }, CASE_MS); +}); diff --git a/apps/server/src/rooms/handlers/socialScope.ts b/apps/server/src/rooms/handlers/socialScope.ts new file mode 100644 index 00000000..1c0f49f2 --- /dev/null +++ b/apps/server/src/rooms/handlers/socialScope.ts @@ -0,0 +1,177 @@ +import type { Client } from 'colyseus'; +import type { ZoneLockInfo } from '@meetropolis/shared'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { logger } from '../../logger.js'; +import type { WorldRoom } from '../WorldRoom.js'; +import { NO_TENANT_KEY, isPlayerVisibleToTenant, tenantKeyForClient } from '../lifecycle/tenantView.js'; + +/** + * Shared scope checks for the social room features (bubble groups and zone + * locks). + * + * Every social operation is bound to the sender: the tenant proven by the + * verified auth of its client and the map the server keeps for that seat. A + * client never names its own scope - the room state and the tenant registry + * decide. The very same scope decides what a recipient is allowed to see + * (bubble groups, zone locks), so a second tenant that shares the room + * instance never observes foreign state. + * + * The tenant key is the verified tenant id (`tenantKeyForClient` for the + * sender, `room.playerTenantKey` for any other seat). A seat without a proven + * tenant has no scope at all and is never accepted. + */ +export interface SocialScope { + /** The seat the scope belongs to. */ + sessionId: string; + /** Verified tenant key of the seat. */ + tenantKey: string; + /** The verified tenant id, used for database proofs. */ + tenantId: string; + /** The server-side map the seat currently stands on. */ + mapId: string; +} + +/** One bubble group as a recipient sees it. */ +export interface BubbleGroupView { + id: string; + members: string[]; +} + +/** The bubble state of one recipient. */ +export interface BubbleStateView { + groups: BubbleGroupView[]; + members: string[]; +} + +/** The seat of a client, if it is seated and has a proven tenant. */ +export function senderScope(room: WorldRoom, client: Client): SocialScope | null { + const tenantKey = tenantKeyForClient(client); + if (!tenantKey || tenantKey === NO_TENANT_KEY) return null; + const player = room.state?.players?.get(client.sessionId); + if (!player) return null; + return { sessionId: client.sessionId, tenantKey, tenantId: tenantKey, mapId: player.mapId }; +} + +/** The scope of any seat, taken from the room's own tenant registry. */ +export function sessionScope(room: WorldRoom, sessionId: string): SocialScope | null { + const player = room.state?.players?.get(sessionId); + if (!player) return null; + const tenantKey = room.playerTenantKey.get(sessionId); + if (!tenantKey || tenantKey === NO_TENANT_KEY) return null; + return { sessionId, tenantKey, tenantId: tenantKey, mapId: player.mapId }; +} + +/** + * Does the seat still live in the given scope? Used after every await: a + * sender that left the room or switched maps in the meantime must not be able + * to finish the operation it started. + */ +export function sameScope(room: WorldRoom, sessionId: string, scope: SocialScope): boolean { + const current = sessionScope(room, sessionId); + return current !== null && current.tenantKey === scope.tenantKey && current.mapId === scope.mapId; +} + +/** The bubble state one recipient may see: only groups inside its own scope. */ +export function bubbleStateForClient(room: WorldRoom, client: Client): BubbleStateView { + const viewerKey = tenantKeyForClient(client); + const viewer = room.state?.players?.get(client.sessionId); + const viewerMapId = viewer?.mapId; + const groups: BubbleGroupView[] = []; + for (const [id, rawMembers] of Object.entries(room.bubbleGroups)) { + const members = rawMembers.filter((member) => room.state.players.has(member)); + if (members.length < 2) continue; + if (!members.every((member) => memberInScope(room, member, viewerKey, viewerMapId))) continue; + groups.push({ id, members }); + } + const members: string[] = []; + for (const group of groups) { + for (const member of group.members) { + if (!members.includes(member)) members.push(member); + } + } + return { groups, members }; +} + +/** Send the bubble state to every client, each one scoped to its own tenant and map. */ +export function broadcastBubbleStateToClients(room: WorldRoom): void { + for (const client of room.clients) { + client.send('bubble_state', bubbleStateForClient(room, client)); + } +} + +/** + * The zone locks one recipient may see. A lock belongs to the tenant of the + * seats that hold it and to the map it was created on, so a recipient only + * sees locks of its own tenant on its own map. The envelope (zone name, map + * id, session ids) carries no personal data; the pending requests of other + * tenants are stripped. + */ +export function zoneLocksForClient(room: WorldRoom, client: Client): ZoneLockInfo[] { + const viewerKey = tenantKeyForClient(client); + const viewer = room.state?.players?.get(client.sessionId); + const viewerMapId = viewer?.mapId; + const visible: ZoneLockInfo[] = []; + for (const lock of room.zoneLockState.locks.values()) { + const lockView = visibleLock(room, lock, viewerKey, viewerMapId); + if (lockView) visible.push(lockView); + } + return visible; +} + +/** + * Does the zone belong to the tenant and the map of the scope? The database + * decides, never the client. Fails closed when the lookup fails. + */ +export async function zoneBelongsToScope(prisma: PrismaClient, scope: SocialScope, zoneName: string): Promise { + try { + const zone = await prisma.zone.findFirst({ + where: { tenantId: scope.tenantId, mapId: scope.mapId, name: zoneName }, + select: { id: true }, + }); + return zone !== null; + } catch (e) { + logger.debug('[WorldRoom] Zone ownership lookup failed', e); + return false; + } +} + +/** Is the seat part of the recipient's tenant and map? */ +function memberInScope( + room: WorldRoom, + sessionId: string, + viewerKey: string, + viewerMapId: string | undefined, +): boolean { + const player = room.state?.players?.get(sessionId); + if (!player) return false; + if (viewerMapId !== undefined && player.mapId !== viewerMapId) return false; + const ownerKey = room.playerTenantKey.get(sessionId); + return ownerKey !== undefined && ownerKey === viewerKey; +} + +/** The lock as one recipient may see it, or null when it stays hidden. */ +function visibleLock( + room: WorldRoom, + lock: ZoneLockInfo, + viewerKey: string, + viewerMapId: string | undefined, +): ZoneLockInfo | null { + if (viewerMapId !== undefined && lock.mapId !== viewerMapId) return null; + const ownerKeys = lockOwnerKeys(room, lock); + if (ownerKeys.size > 0 && !ownerKeys.has(viewerKey)) return null; + const pendingRequests = lock.pendingRequests.filter((request) => + isPlayerVisibleToTenant(false, room.playerTenantKey.get(request.sessionId), viewerKey), + ); + if (pendingRequests.length === lock.pendingRequests.length) return lock; + return { ...lock, pendingRequests }; +} + +/** The verified tenants of the seats that hold a lock. */ +function lockOwnerKeys(room: WorldRoom, lock: ZoneLockInfo): Set { + const keys = new Set(); + for (const sessionId of [lock.lockedBy, ...lock.accessList]) { + const key = room.playerTenantKey.get(sessionId); + if (key) keys.add(key); + } + return keys; +} diff --git a/apps/server/src/rooms/handlers/zoneLockHandler.tenant.test.ts b/apps/server/src/rooms/handlers/zoneLockHandler.tenant.test.ts index bc76e216..705e11a4 100644 --- a/apps/server/src/rooms/handlers/zoneLockHandler.tenant.test.ts +++ b/apps/server/src/rooms/handlers/zoneLockHandler.tenant.test.ts @@ -2,9 +2,11 @@ * Skeptic follow-up (zone_lock_state, MAJOR): the zone-lock roster is another * room-state channel. Each lock's pendingRequests carries identity (userId) + * name (display name, = email when unset) — cross-tenant PII in a shared apex/ - * 'default' room. zoneLocksForClient must strip pendingRequests that belong to - * other tenants (by the requester's verified room.playerTenantKey) while leaving - * the lock envelope (sessionIds only) and same-tenant requests fully intact. + * 'default' room. zoneLocksForClient must scope the whole lock state to the + * viewer: a lock of another tenant is not shown at all, and pendingRequests of + * other tenants are stripped (by the requester's verified room.playerTenantKey). + * Same-tenant requests stay fully visible so the approve/deny flow keeps + * working. */ import { describe, it, expect, vi } from 'vitest'; @@ -33,8 +35,8 @@ function client(tenantId?: string): Client { } as unknown as Client; } -describe('zoneLocksForClient: pendingRequests are tenant-scoped (PII channel)', () => { - it('a viewer only sees same-tenant pendingRequests; the envelope stays intact', () => { +describe('zoneLocksForClient: the lock state is tenant-scoped (PII channel)', () => { + it('a viewer only sees same-tenant pendingRequests; a foreign tenant sees no lock', () => { const lock: Lock = { zoneName: 'meeting', mapId: 'map-a', @@ -60,9 +62,10 @@ describe('zoneLocksForClient: pendingRequests are tenant-scoped (PII channel)', // Tenant A viewer: only the tenant-A requester, never tenant B's PII. expect(aView[0].pendingRequests.map((r) => r.identity)).toEqual(['userA']); expect(aView[0].pendingRequests.some((r) => r.name.includes('tenant-b'))).toBe(false); - // Tenant B viewer: only the tenant-B requester. - expect(bView[0].pendingRequests.map((r) => r.identity)).toEqual(['userB']); - // Envelope preserved (sessionIds only, no PII). + // Tenant B viewer: the lock of tenant A stays hidden, envelope included. + expect(bView).toEqual([]); + // The owning tenant keeps the envelope (sessionIds only, no PII). + expect(aView).toHaveLength(1); expect(aView[0].zoneName).toBe('meeting'); expect(aView[0].mapId).toBe('map-a'); expect(aView[0].lockedBy).toBe('sidOwnerA'); diff --git a/apps/server/src/rooms/handlers/zoneLockHandler.ts b/apps/server/src/rooms/handlers/zoneLockHandler.ts index 67b9eb8e..7c024cbd 100644 --- a/apps/server/src/rooms/handlers/zoneLockHandler.ts +++ b/apps/server/src/rooms/handlers/zoneLockHandler.ts @@ -4,7 +4,11 @@ import type { Client } from 'colyseus'; import { PrismaClient } from '../../generated/prisma/index.js'; import { logger } from '../../logger.js'; import type { WorldRoom, Player } from '../WorldRoom.js'; -import { tenantKeyForClient, isPlayerVisibleToTenant } from '../lifecycle/tenantView.js'; +import { sameScope, senderScope, zoneBelongsToScope, zoneLocksForClient, type SocialScope } from './socialScope.js'; + +// The lock view moved next to the other scope helpers; the export stays here +// for the callers that already import it from this module. +export { zoneLocksForClient }; interface MapMetaShape { zones?: ZoneMetaEntry[]; @@ -114,41 +118,10 @@ function lockKey(mapId: string, zoneName: string): string { return `${mapId}:${zoneName}`; } -// Tenant-scope one lock for a viewer: keep the lock envelope (zoneName, mapId, -// lockedBy, accessList — all sessionIds, no PII) but drop pendingRequests whose -// requester belongs to a different tenant. Each pending request carries -// identity (userId) + name (display name, = email when no display name is set): -// in a shared apex/'default' room that is cross-tenant PII. Filtering by the -// requester's verified tenant (room.playerTenantKey) closes the leak in BOTH -// directions (a foreign lock's requests, and a foreign request injected into -// this tenant's lock) while leaving same-tenant requests fully visible so the -// approve/deny flow keeps working. Only allocates a copy when something is -// actually stripped. An unknown requester tenant (left the room mid-request) -// fails closed: hidden, not leaked. -function filterLockForTenant(room: WorldRoom, lock: ZoneLockInfo, viewerKey: string): ZoneLockInfo { - const pendingRequests = lock.pendingRequests.filter((r: { sessionId: string }) => - isPlayerVisibleToTenant(false, room.playerTenantKey.get(r.sessionId), viewerKey), - ); - if (pendingRequests.length === lock.pendingRequests.length) return lock; - return { ...lock, pendingRequests }; -} - -// Build the tenant-filtered zone_lock_state payload for one client (used by both -// the change-broadcast and the join-seed in onJoin.completion). -export function zoneLocksForClient(room: WorldRoom, client: Client): ZoneLockInfo[] { - const viewerKey = tenantKeyForClient(client); - const out: ZoneLockInfo[] = []; - for (const lock of room.zoneLockState.locks.values()) { - out.push(filterLockForTenant(room, lock, viewerKey)); - } - return out; -} - -// Broadcast the lock state to every client, tenant-scoped per recipient so a -// shared-room foreign tenant never receives another tenant's pending-request -// identity/name (PII). Replaces the previous room-wide broadcast. Reads the -// locks off room.zoneLockState (the single ZoneLockState instance), so no state -// argument is needed. +// Broadcast the lock state to every client, scoped per recipient so a +// shared-room foreign tenant never receives another tenant's lock or its +// pending-request identity/name (PII). Reads the locks off room.zoneLockState +// (the single ZoneLockState instance), so no state argument is needed. function broadcastLockState(room: WorldRoom): void { for (const client of room.clients) { client.send('zone_lock_state', { locks: zoneLocksForClient(room, client) }); @@ -210,82 +183,109 @@ export function getRoomTenantSlug(room: WorldRoom): string { return meta?.tenant || process.env.DEFAULT_TENANT_SLUG || 'default'; } +// The seats of the sender's own tenant and map that stand inside the zone. +function accessListFor(room: WorldRoom, scope: SocialScope, zones: ZonePolygon[], zoneName: string): string[] { + const accessList: string[] = []; + room.state.players.forEach((player: Player, sessionId: string) => { + if (player.mapId !== scope.mapId) return; + if (room.playerTenantKey.get(sessionId) !== scope.tenantKey) return; + if (getPlayerZone(zones, { x: player.x, y: player.y }) !== zoneName) return; + accessList.push(sessionId); + }); + return accessList; +} + +// Lock a zone. The zone has to belong to the tenant and the map of the +// sender, and the sender has to stand inside it. async function handleZoneLock( room: WorldRoom, state: ZoneLockState, prisma: PrismaClient, - client: { sessionId: string }, + client: Client, data: { zoneName?: string }, ): Promise { - const player = room.state.players.get(client.sessionId); - if (!player || !data?.zoneName) return; + const scope = senderScope(room, client); + const zoneName = data?.zoneName; + if (!scope || typeof zoneName !== 'string' || zoneName.length === 0) return; - const mapId = player.mapId; - const tenantSlug = getRoomTenantSlug(room); - const zones = await loadZones(state, mapId, tenantSlug, prisma); - const playerZone = getPlayerZone(zones, { x: player.x, y: player.y }); + const key = lockKey(scope.mapId, zoneName); + if (state.locks.has(key)) return; - if (playerZone !== data.zoneName) return; + // The zone has to belong to the tenant and the map of the sender. The + // database decides, never the client. + if (!(await zoneBelongsToScope(prisma, scope, zoneName))) return; + if (!sameScope(room, client.sessionId, scope)) return; - const key = lockKey(mapId, data.zoneName); - if (state.locks.has(key)) return; + const zones = await loadZones(state, scope.mapId, getRoomTenantSlug(room), prisma); + if (!sameScope(room, client.sessionId, scope)) return; - const accessList: string[] = []; - room.state.players.forEach((p: Player, sessionId: string) => { - if (p.mapId !== mapId) return; - const zone = getPlayerZone(zones, { x: p.x, y: p.y }); - if (zone === data.zoneName) accessList.push(sessionId); - }); + const player = room.state.players.get(client.sessionId); + if (!player) return; + if (getPlayerZone(zones, { x: player.x, y: player.y }) !== zoneName) return; + const accessList = accessListFor(room, scope, zones, zoneName); state.locks.set(key, { - zoneName: data.zoneName, - mapId, + zoneName, + mapId: scope.mapId, lockedBy: client.sessionId, accessList, pendingRequests: [], }); broadcastLockState(room); - logger.info('[ZoneLock] Zone locked:', data.zoneName, 'by', client.sessionId, 'access:', accessList.length); + logger.info('[ZoneLock] Zone locked:', zoneName, 'by', client.sessionId, 'access:', accessList.length); } -function handleZoneUnlock( +// Unlock a zone. The right stays with the seats on the access list. +async function handleZoneUnlock( room: WorldRoom, state: ZoneLockState, - client: { sessionId: string }, + prisma: PrismaClient, + client: Client, data: { zoneName?: string }, -): void { - if (!data?.zoneName) return; - const player = room.state.players.get(client.sessionId); - if (!player) return; +): Promise { + const scope = senderScope(room, client); + const zoneName = data?.zoneName; + if (!scope || typeof zoneName !== 'string' || zoneName.length === 0) return; - const key = lockKey(player.mapId, data.zoneName); + const key = lockKey(scope.mapId, zoneName); const lock = state.locks.get(key); if (!lock) return; - if (!lock.accessList.includes(client.sessionId)) return; + if (!(await zoneBelongsToScope(prisma, scope, zoneName))) return; + if (!sameScope(room, client.sessionId, scope)) return; + state.locks.delete(key); broadcastLockState(room); - logger.info('[ZoneLock] Zone unlocked:', data.zoneName, 'by', client.sessionId); + logger.info('[ZoneLock] Zone unlocked:', zoneName, 'by', client.sessionId); } -function handleZoneAccessRequest( +// Ask for access to a locked zone of the map the sender stands on. A named +// map is only a checked match, never a target. +async function handleZoneAccessRequest( room: WorldRoom, state: ZoneLockState, - client: { sessionId: string }, + prisma: PrismaClient, + client: Client, data: { zoneName?: string; mapId?: string }, -): void { - if (!data?.zoneName || !data?.mapId) return; - const player = room.state.players.get(client.sessionId); - if (!player) return; +): Promise { + const scope = senderScope(room, client); + const zoneName = data?.zoneName; + if (!scope || typeof zoneName !== 'string' || zoneName.length === 0) return; + if (typeof data?.mapId === 'string' && data.mapId !== scope.mapId) return; - const key = lockKey(data.mapId, data.zoneName); + const key = lockKey(scope.mapId, zoneName); const lock = state.locks.get(key); if (!lock) return; - if (lock.accessList.includes(client.sessionId)) return; - if (lock.pendingRequests.some((r: { sessionId: string }) => r.sessionId === client.sessionId)) return; + if (lock.pendingRequests.some((request: { sessionId: string }) => request.sessionId === client.sessionId)) return; + + if (!(await zoneBelongsToScope(prisma, scope, zoneName))) return; + if (!sameScope(room, client.sessionId, scope)) return; + + const player = room.state.players.get(client.sessionId); + if (!player) return; lock.pendingRequests.push({ sessionId: client.sessionId, @@ -294,36 +294,50 @@ function handleZoneAccessRequest( }); broadcastLockState(room); - logger.info('[ZoneLock] Access request for', data.zoneName, 'from', client.sessionId); + logger.info('[ZoneLock] Access request for', zoneName, 'from', client.sessionId); } -function handleZoneAccessResponse( +// Answer a pending access request. Only a seat on the access list may decide, +// and only about a request that is actually pending for a live seat of the +// same tenant and map. +async function handleZoneAccessResponse( room: WorldRoom, state: ZoneLockState, - client: { sessionId: string }, + prisma: PrismaClient, + client: Client, data: { zoneName?: string; sessionId?: string; approved?: boolean }, -): void { - if (!data?.zoneName || !data?.sessionId) return; - const player = room.state.players.get(client.sessionId); - if (!player) return; - - const key = lockKey(player.mapId, data.zoneName); +): Promise { + const scope = senderScope(room, client); + const zoneName = data?.zoneName; + const targetId = data?.sessionId; + const approved = data?.approved; + if (!scope || typeof zoneName !== 'string' || zoneName.length === 0) return; + if (typeof targetId !== 'string' || targetId.length === 0) return; + if (typeof approved !== 'boolean') return; + + const key = lockKey(scope.mapId, zoneName); const lock = state.locks.get(key); if (!lock) return; - if (!lock.accessList.includes(client.sessionId)) return; + if (!lock.pendingRequests.some((request: { sessionId: string }) => request.sessionId === targetId)) return; + if (!sameScope(room, targetId, scope)) return; + + if (!(await zoneBelongsToScope(prisma, scope, zoneName))) return; + if (!sameScope(room, client.sessionId, scope)) return; - lock.pendingRequests = lock.pendingRequests.filter((r: { sessionId: string }) => r.sessionId !== data.sessionId); + lock.pendingRequests = lock.pendingRequests.filter( + (request: { sessionId: string }) => request.sessionId !== targetId, + ); - if (data.approved) { - lock.accessList.push(data.sessionId); - logger.info('[ZoneLock] Access approved for', data.sessionId, 'to', data.zoneName); + if (approved) { + lock.accessList.push(targetId); + logger.info('[ZoneLock] Access approved for', targetId, 'to', zoneName); } else { - const requesterClient = room.clients.find((c) => c.sessionId === data.sessionId); + const requesterClient = room.clients.find((c) => c.sessionId === targetId); if (requesterClient) { - requesterClient.send('zone_access_denied', { zoneName: data.zoneName }); + requesterClient.send('zone_access_denied', { zoneName }); } - logger.info('[ZoneLock] Access denied for', data.sessionId, 'to', data.zoneName); + logger.info('[ZoneLock] Access denied for', targetId, 'to', zoneName); } broadcastLockState(room); @@ -337,13 +351,15 @@ export function setupZoneLockHandlers(room: WorldRoom, state: ZoneLockState, pri room.onMessage('zone_lock', (client, data) => { void handleZoneLock(room, state, prisma, client, data); }); - room.onMessage('zone_unlock', (client, data) => handleZoneUnlock(room, state, client, data)); - room.onMessage('zone_access_request', (client, data) => - handleZoneAccessRequest(room, state, client, data), - ); - room.onMessage('zone_access_response', (client, data) => - handleZoneAccessResponse(room, state, client, data), - ); + room.onMessage('zone_unlock', (client, data) => { + void handleZoneUnlock(room, state, prisma, client, data); + }); + room.onMessage('zone_access_request', (client, data) => { + void handleZoneAccessRequest(room, state, prisma, client, data); + }); + room.onMessage('zone_access_response', (client, data) => { + void handleZoneAccessResponse(room, state, prisma, client, data); + }); } // Player leaves: remove them from every list. diff --git a/apps/server/src/rooms/lifecycle/accessRevocation.integration.test.ts b/apps/server/src/rooms/lifecycle/accessRevocation.integration.test.ts new file mode 100644 index 00000000..b980791f --- /dev/null +++ b/apps/server/src/rooms/lifecycle/accessRevocation.integration.test.ts @@ -0,0 +1,149 @@ +import crypto from 'crypto'; +import { LocalPresence } from 'colyseus'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { logger } from '../../logger.js'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { hashSessionToken } from '../../api/utils/sessionAuth.js'; +import { deleteAccount, removeMemberFromTenant } from '../../services/accountDeletion.js'; +import type { WorldRoom } from '../WorldRoom.js'; +import { subscribeAccessRevocations } from './accessRevocation.js'; +import { createWorldAccess } from './worldAccess.js'; + +/** + * Removing a member or deleting an account ends the user's open world + * connections at once, through the access-revoked event on Colyseus presence + * (the in-process LocalPresence the server uses without Redis), against a REAL + * PostgreSQL database. The periodic access sweep is only the safety net and is + * not involved here. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('accessRevocation.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const presence = new LocalPresence(); +const userIds: string[] = []; +let tenantId: string; +let tenantSlug: string; +let previousGameServer: typeof global.gameServer; +let previousActiveWorldRooms: typeof global.activeWorldRooms; + +async function createUser(role: Role): Promise<{ id: string; sessionId: string }> { + const user = await prisma.user.create({ data: { email: `qacc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId, role } }); + // Every connected client stands on a live session row, as a real join via + // onAuth would leave it: the revoke handler checks the session row first. + const session = await prisma.session.create({ + data: { + userId: user.id, + tokenHash: hashSessionToken(crypto.randomUUID()), + expiresAt: new Date(Date.now() + 3_600_000), + }, + select: { id: true }, + }); + return { id: user.id, sessionId: session.id }; +} + +async function connectedRoom(users: Array<{ id: string; sessionId: string }>) { + const clients = users.map((user, i) => ({ + identity: user.id, + sessionId: `sess-${i}`, + leave: vi.fn(), + error: vi.fn(), + })); + const players = new Map(clients.map((c) => [c.sessionId, { identity: c.identity }])); + // The revocation handler reads each session's verified tenant from the + // registry: every client here was verified for this tenant at join time. + const room = { presence, prismaForPresence: prisma, state: { players }, clients } as unknown as WorldRoom; + room.worldAccess = createWorldAccess(room); + // Real rooms expose revokeAccess (see WorldRoom); the stand-in wires the + // same delegation so the local broadcast path reaches its real registry. + room.revokeAccess = (targetUserId: string): void => { + room.worldAccess.revoke(targetUserId).catch((e: unknown) => { + logger.error('[WorldRoom] Failed to revoke world access', e); + }); + }; + for (const [i, client] of clients.entries()) { + room.worldAccess.register(client.sessionId, { + identity: client.identity, + tenantId, + tenantSlug, + authSessionId: users[i]?.sessionId, + isNpc: false, + zonePrivacyVersion: 1, + }); + } + // The subscription is awaited, as WorldRoom.onCreate awaits it: a room + // without its revocation channel must not exist. + const unsubscribe = await subscribeAccessRevocations(room); + // Real rooms join `global.activeWorldRooms` in onCreate, which is where + // broadcastAccessRevoked revokes locally first; the stand-in registers + // itself the same way so the local path reaches it. + const active = global.activeWorldRooms ?? new Set(); + active.add(room); + global.activeWorldRooms = active; + const release = (): void => { + unsubscribe(); + active.delete(room); + }; + return { clients, unsubscribe: release }; +} + +/** The revocation handler re-proves access against the database; poll for it. */ +async function waitFor(left: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!left()) { + if (Date.now() > deadline) throw new Error(`condition not met within ${timeoutMs} ms`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +beforeAll(async () => { + previousGameServer = global.gameServer; + previousActiveWorldRooms = global.activeWorldRooms; + global.gameServer = { presence }; + tenantSlug = `qacc-${crypto.randomUUID()}`; + tenantId = (await prisma.tenant.create({ data: { slug: tenantSlug, name: tenantSlug } })).id; +}); + +afterAll(async () => { + global.gameServer = previousGameServer; + global.activeWorldRooms = previousActiveWorldRooms; + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: tenantId } }); + await prisma.$disconnect(); +}); + +describe('open world connections end with the access (real database)', () => { + it('disconnects a member at once when an admin removes them, and nobody else', async () => { + const stays = await createUser('member'); + const removed = await createUser('member'); + const { clients, unsubscribe } = await connectedRoom([stays, removed]); + + await removeMemberFromTenant(prisma, { userId: removed.id, tenantId }); + const [staysClient, removedClient] = clients; + await waitFor(() => removedClient.leave.mock.calls.length > 0, 5_000); + unsubscribe(); + + // Member removal signs the user out everywhere, so the bundled session + // check fires first: `session_revoked`, not `not_member_of_tenant`. + expect(removedClient.error).toHaveBeenCalledWith(4401, 'session_revoked'); + expect(staysClient.leave).not.toHaveBeenCalled(); + }); + + it('disconnects a user at once when they delete their own account', async () => { + const leaving = await createUser('member'); + const { clients, unsubscribe } = await connectedRoom([leaving]); + + await deleteAccount(prisma, leaving.id); + await waitFor(() => clients[0].leave.mock.calls.length > 0, 5_000); + unsubscribe(); + + expect(clients[0].leave).toHaveBeenCalled(); + }); +}); diff --git a/apps/server/src/rooms/lifecycle/accessRevocation.ts b/apps/server/src/rooms/lifecycle/accessRevocation.ts new file mode 100644 index 00000000..0f610cc2 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/accessRevocation.ts @@ -0,0 +1,27 @@ +import { logger } from '../../logger.js'; +import { ACCESS_REVOKED_CHANNEL, PROCESS_ID } from '../../api/utils/broadcast.js'; +import type { WorldRoom } from '../WorldRoom.js'; + +/** + * Subscribe `room` to the single per-user access-revocation channel (published + * by broadcastAccessRevoked after a member removal, an account deletion or a + * guest revocation). The room's world-access registry decides per session, by + * its own verified tenant, which clients must leave at once. Messages this + * process published itself are skipped: the broadcaster already revoked its + * rooms locally before publishing. Returns the unsubscribe function for + * onDispose; a failed subscription rejects, so the room is never created + * without its revocation channel. + */ +export async function subscribeAccessRevocations(room: WorldRoom): Promise<() => void> { + const onRevoked = (message: { userId?: unknown; origin?: unknown }): void => { + if (typeof message?.userId !== 'string') return; + if (message?.origin === PROCESS_ID) return; + room.worldAccess.revoke(message.userId).catch((e: unknown) => { + logger.error('[WorldRoom] Failed to revoke world access', e); + }); + }; + await room.presence.subscribe(ACCESS_REVOKED_CHANNEL, onRevoked); + return () => { + room.presence.unsubscribe(ACCESS_REVOKED_CHANNEL, onRevoked); + }; +} diff --git a/apps/server/src/rooms/lifecycle/avAccessReconciler.ts b/apps/server/src/rooms/lifecycle/avAccessReconciler.ts new file mode 100644 index 00000000..b9fb0395 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/avAccessReconciler.ts @@ -0,0 +1,263 @@ +import { RoomServiceClient, type ParticipantInfo } from 'livekit-server-sdk'; +import { logger } from '../../logger.js'; +import { hasTenantAccess } from '../../api/utils/tenantMembership.js'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { TRANSCRIBER_IDENTITY } from '../audioZones/islandAttributes.js'; +import { mapLivekitUrlToHttp } from '../audioZones/livekitAdmin.js'; +import { avSessionRefMatches, readAvSessionRef } from './avSessionRef.js'; +import { enqueueAvRevocation, ensureAvPendingRevocations } from './avPendingRevocations.js'; + +const RECONCILE_INTERVAL_MS = 30_000; +const LIST_CONCURRENCY = 4; +const NPC_PREFIX = 'npc-'; +const WORLD_SUBROOM = 'world'; + +type ReconcilerPrisma = Pick; + +export interface AvAccessReconciler { + runRound(): Promise; + stop(): Promise; +} + +interface NpcCheck { + roomName: string; + identity: string; + tenantId: string; + record: string; +} + +interface UserCheck { + roomName: string; + identity: string; + tenantId: string; + ref: string; +} + +interface RoundRemoval { + roomName: string; + identity: string; +} + +function errorText(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** Tenant slug from `:world`; every other room name is out of scope. */ +function parseWorldSlug(roomName: string): string | null { + const at = roomName.lastIndexOf(':'); + if (at <= 0 || roomName.slice(at + 1) !== WORLD_SUBROOM) return null; + return roomName.slice(0, at); +} + +/** Admin client for reconciliation rounds: 5 s request timeout. */ +function createReconcileClient(): RoomServiceClient | null { + const apiKey = process.env.LIVEKIT_API_KEY; + const apiSecret = process.env.LIVEKIT_API_SECRET; + const rawUrl = process.env.LIVEKIT_URL; + if (!apiKey || !apiSecret || !rawUrl) return null; + return new RoomServiceClient(mapLivekitUrlToHttp(rawUrl), apiKey, apiSecret, { requestTimeout: 5 }); +} + +function collectWorldRooms(rooms: Array<{ name: string }>): Map { + const found = new Map(); + for (const room of rooms) { + const slug = parseWorldSlug(room.name); + if (slug !== null) found.set(room.name, slug); + } + return found; +} + +async function resolveTenantIds(prisma: ReconcilerPrisma, slugs: string[]): Promise> { + const unique = [...new Set(slugs)]; + const rows = await prisma.tenant.findMany({ where: { slug: { in: unique } }, select: { id: true, slug: true } }); + return new Map(rows.map((row) => [row.slug, row.id])); +} + +/** At most four participant listings at once; a failed room is skipped this round. */ +async function listParticipantsBounded( + client: RoomServiceClient, + roomNames: string[], +): Promise> { + const found = new Map(); + for (let at = 0; at < roomNames.length; at += LIST_CONCURRENCY) { + const batch = roomNames.slice(at, at + LIST_CONCURRENCY); + const listed = await Promise.all( + batch.map(async (roomName) => { + try { + return await client.listParticipants(roomName); + } catch (error: unknown) { + logger.warn({ event: 'av.reconcile_list_failed', error: errorText(error) }); + return null; + } + }), + ); + batch.forEach((roomName, index) => { + const participants = listed[index]; + if (participants) found.set(roomName, participants); + }); + } + return found; +} + +function classifyParticipants( + roomParticipants: Map, + worldSlugs: Map, + tenantBySlug: Map, +): { npcChecks: NpcCheck[]; userChecks: UserCheck[]; removals: RoundRemoval[]; total: number } { + const npcChecks: NpcCheck[] = []; + const userChecks: UserCheck[] = []; + const removals: RoundRemoval[] = []; + let total = 0; + for (const [roomName, participants] of roomParticipants) { + const slug = worldSlugs.get(roomName); + if (!slug) continue; + const tenantId = tenantBySlug.get(slug); + for (const participant of participants) { + total += 1; + const identity = participant.identity; + if (identity === TRANSCRIBER_IDENTITY) continue; + if (identity.startsWith(NPC_PREFIX)) { + if (!tenantId) removals.push({ roomName, identity }); + else npcChecks.push({ roomName, identity, tenantId, record: identity.slice(NPC_PREFIX.length) }); + continue; + } + if (!tenantId) { + removals.push({ roomName, identity }); + continue; + } + const ref = readAvSessionRef(participant.metadata); + if (ref === null) removals.push({ roomName, identity }); + else userChecks.push({ roomName, identity, tenantId, ref }); + } + } + return { npcChecks, userChecks, removals, total }; +} + +/** NPC checks without an exact tenant plus record pair; one bundled query. */ +async function unknownNpcs(prisma: ReconcilerPrisma, checks: NpcCheck[]): Promise { + if (checks.length === 0) return []; + const rows = await prisma.npc.findMany({ + where: { + tenantId: { in: [...new Set(checks.map((check) => check.tenantId))] }, + identity: { in: [...new Set(checks.map((check) => check.record))] }, + }, + select: { tenantId: true, identity: true }, + }); + const valid = new Set(rows.map((row) => JSON.stringify([row.tenantId, row.identity]))); + return checks + .filter((check) => !valid.has(JSON.stringify([check.tenantId, check.record]))) + .map((check) => ({ roomName: check.roomName, identity: check.identity })); +} + +/** + * User checks whose reference matches no live session of the same subject; + * all sessions load in one query, matching is local. Throws on database + * errors so the round aborts without removing anyone. + */ +async function withoutLiveSession( + prisma: ReconcilerPrisma, + checks: UserCheck[], +): Promise<{ matched: UserCheck[]; removals: RoundRemoval[] }> { + if (checks.length === 0) return { matched: [], removals: [] }; + const now = new Date(); + const rows = await prisma.session.findMany({ + where: { userId: { in: [...new Set(checks.map((check) => check.identity))] }, expiresAt: { gt: now } }, + select: { id: true, userId: true }, + }); + const byUser = new Map(); + for (const row of rows) { + const known = byUser.get(row.userId); + if (known) known.push(row.id); + else byUser.set(row.userId, [row.id]); + } + const matched: UserCheck[] = []; + const removals: RoundRemoval[] = []; + for (const check of checks) { + const sessions = byUser.get(check.identity) ?? []; + if (sessions.some((sessionId) => avSessionRefMatches(check.ref, sessionId))) matched.push(check); + else removals.push({ roomName: check.roomName, identity: check.identity }); + } + return { matched, removals }; +} + +/** Matched checks without current tenant access; throws so the round aborts. */ +async function withoutTenantAccess(prisma: ReconcilerPrisma, checks: UserCheck[]): Promise { + const grants = await Promise.all( + checks.map((check) => hasTenantAccess(prisma, check.identity, check.tenantId)), + ); + return checks + .filter((_, index) => !grants[index]) + .map((check) => ({ roomName: check.roomName, identity: check.identity })); +} + +async function runReconcileRound(prisma: ReconcilerPrisma): Promise { + const started = Date.now(); + const client = createReconcileClient(); + if (!client) { + logger.debug({ event: 'av.reconcile_skipped', reason: 'not_configured' }); + return; + } + let rooms: Array<{ name: string }>; + try { + rooms = await client.listRooms(); + } catch (error: unknown) { + logger.warn({ event: 'av.reconcile_list_failed', error: errorText(error) }); + return; + } + const worldSlugs = collectWorldRooms(rooms); + if (worldSlugs.size === 0) { + logger.info({ event: 'av.reconcile_round', rooms: 0, participants: 0, removals: 0, durationMs: 0 }); + return; + } + try { + const tenantBySlug = await resolveTenantIds(prisma, [...worldSlugs.values()]); + const roomParticipants = await listParticipantsBounded(client, [...worldSlugs.keys()]); + const classified = classifyParticipants(roomParticipants, worldSlugs, tenantBySlug); + const removals = [...classified.removals]; + removals.push(...(await unknownNpcs(prisma, classified.npcChecks))); + const { matched, removals: sessionRemovals } = await withoutLiveSession(prisma, classified.userChecks); + removals.push(...sessionRemovals); + removals.push(...(await withoutTenantAccess(prisma, matched))); + for (const removal of removals) enqueueAvRevocation(removal.roomName, removal.identity); + logger.info({ + event: 'av.reconcile_round', + rooms: worldSlugs.size, + participants: classified.total, + removals: removals.length, + durationMs: Date.now() - started, + }); + } catch (error: unknown) { + logger.warn({ event: 'av.reconcile_aborted', error: errorText(error) }); + } +} + +/** + * Periodic tenant-call reconciliation: every 30 s exactly one round lists + * every `:world` room and removes participants without a live, + * session-bound grant through the confirmed backlog. Database errors abort + * the round and remove nothing. No positive cache, no switches. + */ +export function startAvAccessReconciler(prisma: ReconcilerPrisma): AvAccessReconciler { + ensureAvPendingRevocations(); + let current: Promise | null = null; + const runRound = (): Promise => { + if (current) return current; + current = runReconcileRound(prisma).finally(() => { + current = null; + }); + return current; + }; + const timer = setInterval(() => { + runRound().catch(() => { + /* logged inside the round */ + }); + }, RECONCILE_INTERVAL_MS); + timer.unref(); + return { + runRound, + stop: async () => { + clearInterval(timer); + if (current) await current; + }, + }; +} diff --git a/apps/server/src/rooms/lifecycle/avAccessRevocation.integration.test.ts b/apps/server/src/rooms/lifecycle/avAccessRevocation.integration.test.ts new file mode 100644 index 00000000..6c1ac6b1 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/avAccessRevocation.integration.test.ts @@ -0,0 +1,450 @@ +/** + * LiveKit token binding and confirmed participant removal through the real + * stack: the HTTP token route on a real Colyseus server, a real database and + * a real SFU. The reconciler started here is the harness hook; until the + * server reconciles SFU access it does nothing, so the removal cases below + * still see the participant afterwards. + * + * Presence is always the admin participant list. A client disconnect is only + * cleanup. The session reference is derived in this file from the JWT secret + * and the session row id; the token route is expected to embed that value. + * + * The outage case and the restart case are time-dependent and count as + * load-suspect under high machine load. + */ + +import { createHmac, hkdfSync, randomUUID } from 'node:crypto'; +import cookieParser from 'cookie-parser'; +import express from 'express'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { Client } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import { createPrismaClient } from '../../db.js'; +import { registerApi } from '../../api.js'; +import { tenantMiddleware } from '../../tenancy.js'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; +import { removeMemberFromTenant } from '../../services/accountDeletion.js'; +import { createLivekitAdminClient } from '../audioZones/livekitAdmin.js'; +import { cleanupTenants, seedMember, seedTenant, type SeededMember } from '../../testUtils/worldSeed.js'; +import { + connectParticipant, + disconnectAll, + listIdentities, + mintServiceToken, + pauseSfu, + startAvReconcile, + unpauseSfu, + waitForIdentityGone, + waitForIdentityPresent, + type AvReconciler, +} from '../../testUtils/sfuHarness.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +const FILE = 'avAccessRevocation.integration.test.ts'; +const SESSION_REF_INFO = 'meetropolis/av-session-ref/v1'; +const PROBE_ROOM = 'readyz'; +const PROBE_IDENTITY = 'probe'; +const TRANSCRIBER_IDENTITY = 'svc-transcriber'; +const FORGED_METADATA = '{"sessionRef":"forged"}'; +const SFU_TIMEOUT_MS = 60_000; +const ROUND_TIMEOUT_MS = 10_000; +const RETRY_WINDOW_MS = 40_000; +const PAUSE_LIMIT_MS = 12_000; +const PAUSE_CASE_TIMEOUT_MS = 120_000; + +function requireEnv(name: string, purpose: string): void { + if (!process.env[name]) throw new Error(`${FILE} needs ${name} ${purpose}`); +} + +requireEnv('DATABASE_URL', 'pointing at a migrated test database'); +requireEnv('LIVEKIT_URL', 'pointing at the test SFU'); +requireEnv('LIVEKIT_API_KEY', 'for the test SFU'); +requireEnv('LIVEKIT_API_SECRET', 'for the test SFU'); +requireEnv('TEST_SFU_CONTAINER', 'naming the test SFU container'); + +const tenantSlug = `av-${randomUUID().replace(/-/g, '').slice(0, 12)}`; +process.env.DEFAULT_TENANT_SLUG = tenantSlug; + +const prisma = createPrismaClient(); +const packUuids: string[] = []; +const extraTenantIds: string[] = []; +const extraUserIds: string[] = []; +let apiReady: Promise = Promise.resolve(); +let server: MatchmakeTestServer; +let previousGameServer: typeof global.gameServer; +let reconciler: AvReconciler | undefined; +let tenantId = ''; +let fixturePackUuid = ''; + +function shortId(): string { + return randomUUID().replace(/-/g, '').slice(0, 12); +} + +function delay(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +function worldName(slug: string): string { + return `${slug}:world`; +} + +/** HMAC of the session row id, keyed by HKDF(JWT secret, empty salt, fixed label). */ +function sessionRefFor(sessionId: string): string { + const key = Buffer.from(hkdfSync('sha256', getJwtSecret(), Buffer.alloc(0), SESSION_REF_INFO, 32)); + return `v1.${createHmac('sha256', key).update(sessionId).digest('base64url')}`; +} + +function jwtMetadata(token: string): string { + const part = token.split('.')[1]; + if (!part) return ''; + try { + const parsed: unknown = JSON.parse(Buffer.from(part, 'base64url').toString('utf8')); + if (typeof parsed !== 'object' || parsed === null || !('metadata' in parsed)) return ''; + return typeof parsed.metadata === 'string' ? parsed.metadata : ''; + } catch { + return ''; + } +} + +function sessionRefFromMetadata(metadata: string): string | null { + try { + const parsed: unknown = JSON.parse(metadata); + if (typeof parsed !== 'object' || parsed === null || !('sessionRef' in parsed)) return null; + return typeof parsed.sessionRef === 'string' ? parsed.sessionRef : null; + } catch { + return null; + } +} + +function currentReconciler(): AvReconciler { + if (!reconciler) throw new Error(`${FILE} expected the reconciler to be started`); + return reconciler; +} + +function configureApi(app: express.Express): void { + app.use(cookieParser()); + app.use(express.json()); + app.use(tenantMiddleware as unknown as express.RequestHandler); + apiReady = registerApi(app); +} + +async function seedAvatarPack(): Promise { + const uuid = `avpack-${shortId()}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'session join fixture', + author: 'fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +interface TokenResponse { + status: number; + text: string; +} + +async function postLivekitToken(member: SeededMember, slug: string = tenantSlug): Promise { + const response = await fetch(`${server.base}/livekit/token`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Tenant': slug, + Authorization: `Bearer ${member.token}`, + }, + body: JSON.stringify({ + roomName: 'world', + name: member.userId, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + identity: member.userId, + }), + }); + return { status: response.status, text: (await response.text()).trim() }; +} + +async function issuedToken(member: SeededMember, slug: string = tenantSlug): Promise { + const issued = await postLivekitToken(member, slug); + if (issued.status !== 200 || issued.text.length === 0) { + throw new Error(`livekit token request failed with status ${issued.status}`); + } + return issued.text; +} + +async function expectPresent(roomName: string, identity: string): Promise { + expect(await waitForIdentityPresent(roomName, identity, ROUND_TIMEOUT_MS)).toBe(true); +} + +async function expectRemoved(roomName: string, identity: string, timeoutMs = ROUND_TIMEOUT_MS): Promise { + expect(await waitForIdentityGone(roomName, identity, timeoutMs)).toBe(true); +} + +async function connectIssued(member: SeededMember, slug: string = tenantSlug): Promise { + const token = await issuedToken(member, slug); + await connectParticipant(token); + await expectPresent(worldName(slug), member.userId); + return token; +} + +async function connectMinted(roomName: string, identity: string): Promise { + await connectParticipant(await mintServiceToken(roomName, identity)); + await expectPresent(roomName, identity); +} + +/** Publisher wire identity is the `npc-` prefix plus the stored record identity. */ +async function connectRecordedNpc(slug: string): Promise { + const recordIdentity = `keeper-${shortId()}`; + const wireIdentity = `npc-${recordIdentity}`; + await prisma.npc.create({ + data: { tenantId, identity: recordIdentity, name: recordIdentity }, + }); + await connectMinted(worldName(slug), wireIdentity); + return wireIdentity; +} + +/** Keeps the socket referenced so the joined seat still exists when access is revoked. */ +async function joinWorld(member: SeededMember): Promise<{ sessionId: string }> { + const client = new Client(server.base); + client.auth.token = member.token; + const room = await client.joinOrCreate('world', { + tenant: tenantSlug, + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + identity: member.userId, + }); + return room; +} + +/** Fixed 12s freeze. Revocation must not extend it, and the participant must outlive it. */ +async function pauseForRevocation(member: SeededMember, duringPause?: () => Promise): Promise { + await pauseSfu(); + try { + void removeMemberFromTenant(prisma, { userId: member.userId, tenantId }).catch(() => undefined); + const window = delay(PAUSE_LIMIT_MS); + if (duringPause) await Promise.race([duringPause(), window]); + await window; + } finally { + await unpauseSfu(); + } +} + +async function dropUser(userId: string): Promise { + await prisma.presence.deleteMany({ where: { userId } }); + await prisma.session.deleteMany({ where: { userId } }); + await prisma.membership.deleteMany({ where: { userId } }); + await prisma.user.deleteMany({ where: { id: userId } }); +} + +async function deleteTenantRow(id: string): Promise { + const members = await prisma.membership.findMany({ where: { tenantId: id }, select: { userId: true } }); + for (const member of members) extraUserIds.push(member.userId); + await prisma.presence.deleteMany({ where: { tenantId: id } }); + await prisma.zone.deleteMany({ where: { tenantId: id } }); + await prisma.room.deleteMany({ where: { tenantId: id } }); + await prisma.npc.deleteMany({ where: { tenantId: id } }); + await prisma.map.deleteMany({ where: { tenantId: id } }); + await prisma.invite.deleteMany({ where: { tenantId: id } }); + await prisma.membership.deleteMany({ where: { tenantId: id } }); + await prisma.tenant.deleteMany({ where: { id } }); +} + +/** + * The harness list returns identities only. Metadata is read from the same + * admin `listParticipants` call through the product client. + */ +async function storedMetadata(roomName: string, identity: string): Promise { + const admin = createLivekitAdminClient(); + if (!admin) throw new Error(`${FILE} needs a LiveKit admin client to read participant metadata`); + const participants = await admin.listParticipants(roomName); + const found = participants.find((participant) => participant.identity === identity); + return found?.metadata ?? ''; +} + +beforeAll(async () => { + tenantId = (await seedTenant(prisma, { slug: tenantSlug })).id; + await seedAvatarPack(); + await prisma.map.create({ data: { tenantId, name: 'office', meta: {} } }); + server = await startMatchmakeServer({ configureApp: configureApi }); + await apiReady; + previousGameServer = global.gameServer; + global.gameServer = server.gameServer; +}); + +beforeEach(async () => { + await disposeAllRooms(); + reconciler = await startAvReconcile(prisma); +}); + +afterEach(async () => { + await disconnectAll(); + if (reconciler) await reconciler.stop(); + reconciler = undefined; + await disposeAllRooms(); +}); + +afterAll(async () => { + await stopMatchmakeServer(server); + global.gameServer = previousGameServer; + const tenantIds = [tenantId, ...extraTenantIds]; + await prisma.presence.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.zone.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.room.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.npc.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.map.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.invite.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await cleanupTenants(prisma, tenantIds); + if (extraUserIds.length > 0) { + await prisma.session.deleteMany({ where: { userId: { in: extraUserIds } } }); + await prisma.user.deleteMany({ where: { id: { in: extraUserIds } } }); + } + await prisma.$disconnect(); +}); + +describe('livekit token metadata', () => { + it('binds the token to the session reference', async () => { + const member = await seedMember(prisma, tenantId); + const issued = await postLivekitToken(member); + const metadata = jwtMetadata(issued.text); + expect(issued.status).toBe(200); + expect(metadata.includes(member.sessionId)).toBe(false); + expect(sessionRefFromMetadata(metadata)).toBe(sessionRefFor(member.sessionId)); + }, 30_000); +}); + +describe('current members', () => { + it('keeps a participant with a live session', async () => { + const member = await seedMember(prisma, tenantId); + await connectIssued(member); + await currentReconciler().runRound(); + expect(await listIdentities(worldName(tenantSlug))).toContain(member.userId); + }, SFU_TIMEOUT_MS); +}); + +describe('reserved participant identities', () => { + it('refuses a token for a service identity and an npc identity', async () => { + const identities = [TRANSCRIBER_IDENTITY, `npc-${shortId()}`]; + const statuses: number[] = []; + for (const userId of identities) { + await dropUser(userId); + const member = await seedMember(prisma, tenantId, { userId }); + statuses.push((await postLivekitToken(member)).status); + } + expect(statuses.every((status) => status >= 400 && status < 500)).toBe(true); + }, 30_000); +}); + +describe('npc publishers', () => { + it('keeps an npc participant with a matching record', async () => { + const wireIdentity = await connectRecordedNpc(tenantSlug); + await currentReconciler().runRound(); + expect(await listIdentities(worldName(tenantSlug))).toContain(wireIdentity); + }, SFU_TIMEOUT_MS); +}); + +describe('reused token after membership removal', () => { + it('removes the participant on the next round', async () => { + const member = await seedMember(prisma, tenantId); + const token = await connectIssued(member); + await removeMemberFromTenant(prisma, { userId: member.userId, tenantId }); + await disconnectAll(); + await connectParticipant(token); + await expectPresent(worldName(tenantSlug), member.userId); + await currentReconciler().runRound(); + await expectRemoved(worldName(tenantSlug), member.userId); + }, SFU_TIMEOUT_MS); +}); + +describe('service identities', () => { + it('keeps the transcriber participant', async () => { + await connectMinted(worldName(tenantSlug), TRANSCRIBER_IDENTITY); + await currentReconciler().runRound(); + expect(await listIdentities(worldName(tenantSlug))).toContain(TRANSCRIBER_IDENTITY); + }, SFU_TIMEOUT_MS); +}); + +describe('revocation during a media-server outage', () => { + it('removes the participant within the retry window', async () => { + const member = await seedMember(prisma, tenantId); + const world = await joinWorld(member); + await connectIssued(member); + await pauseForRevocation(member); + await expectRemoved(worldName(tenantSlug), member.userId, RETRY_WINDOW_MS); + expect(world.sessionId).toEqual(expect.any(String)); + }, PAUSE_CASE_TIMEOUT_MS); +}); + +describe('participant metadata', () => { + it('rejects a self-serve metadata change', async () => { + const member = await seedMember(prisma, tenantId); + const token = await issuedToken(member); + const room = await connectParticipant(token); + const local = room.localParticipant; + if (!local) throw new Error('connected room has no local participant'); + await expectPresent(worldName(tenantSlug), member.userId); + await Promise.race([local.updateMetadata(FORGED_METADATA).catch(() => undefined), delay(10_000)]); + expect(await storedMetadata(worldName(tenantSlug), member.userId)).not.toBe(FORGED_METADATA); + expect(await listIdentities(worldName(tenantSlug))).toContain(member.userId); + }, SFU_TIMEOUT_MS); +}); + +describe('revocation across a reconciler restart', () => { + it('removes the participant on the round after restart', async () => { + const member = await seedMember(prisma, tenantId); + await connectIssued(member); + await pauseForRevocation(member, async () => { + await reconciler?.stop(); + reconciler = undefined; + }); + reconciler = await startAvReconcile(prisma); + await reconciler.runRound(); + await expectRemoved(worldName(tenantSlug), member.userId, RETRY_WINDOW_MS); + }, PAUSE_CASE_TIMEOUT_MS); +}); + +describe('rooms outside a tenant call', () => { + it('leaves the readiness probe room unchanged', async () => { + await connectMinted(PROBE_ROOM, PROBE_IDENTITY); + await currentReconciler().runRound(); + expect(await listIdentities(PROBE_ROOM)).toContain(PROBE_IDENTITY); + }, SFU_TIMEOUT_MS); +}); + +describe('unknown npc identities', () => { + it('removes an npc participant with no matching record', async () => { + const identity = `npc-${shortId()}`; + await connectMinted(worldName(tenantSlug), identity); + await currentReconciler().runRound(); + await expectRemoved(worldName(tenantSlug), identity); + }, SFU_TIMEOUT_MS); +}); + +describe('unresolvable tenant rooms', () => { + it('removes user participants after a slug rename and a tenant deletion', async () => { + const renamed = await seedTenant(prisma); + const deleted = await seedTenant(prisma); + extraTenantIds.push(renamed.id, deleted.id); + const renamedMember = await seedMember(prisma, renamed.id); + const deletedMember = await seedMember(prisma, deleted.id); + await connectMinted(worldName(renamed.slug), renamedMember.userId); + await connectMinted(worldName(deleted.slug), deletedMember.userId); + await prisma.tenant.update({ where: { id: renamed.id }, data: { slug: `${renamed.slug}-renamed` } }); + await deleteTenantRow(deleted.id); + await currentReconciler().runRound(); + const renamedGone = await waitForIdentityGone(worldName(renamed.slug), renamedMember.userId, ROUND_TIMEOUT_MS); + const deletedGone = await waitForIdentityGone(worldName(deleted.slug), deletedMember.userId, ROUND_TIMEOUT_MS); + expect([renamedGone, deletedGone]).toEqual([true, true]); + }, SFU_TIMEOUT_MS); +}); diff --git a/apps/server/src/rooms/lifecycle/avPendingRevocations.test.ts b/apps/server/src/rooms/lifecycle/avPendingRevocations.test.ts new file mode 100644 index 00000000..46aec733 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/avPendingRevocations.test.ts @@ -0,0 +1,223 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + AV_PENDING_MAX_ENTRIES, + createAvPendingRevocations, + type AvPendingBacklog, + type AvRemovalOutcome, +} from './avPendingRevocations.js'; + +const created: AvPendingBacklog[] = []; + +async function flush(): Promise { + await vi.advanceTimersByTimeAsync(0); +} + +function track(stub: () => Promise): { calls: number[]; remove: () => Promise } { + const calls: number[] = []; + return { + calls, + remove: async () => { + calls.push(calls.length + 1); + return stub(); + }, + }; +} + +function failing(): { calls: number[]; remove: () => Promise } { + return track(() => Promise.resolve('failed')); +} + +async function stopAll(): Promise { + while (created.length > 0) { + const next = created.pop() as AvPendingBacklog; + await next.stop(); + } +} + +type BacklogModule = typeof import('./avPendingRevocations.js'); + +async function freshBacklogModule(): Promise { + vi.resetModules(); + return import('./avPendingRevocations.js'); +} + +const LIVEKIT_ENV_KEYS = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'] as const; + +/** Unreachable SFU coordinates so the singleton attempt fails fast and stays queued. */ +function setDummyLivekitEnv(): () => void { + const previous = new Map(); + for (const key of LIVEKIT_ENV_KEYS) { + previous.set(key, process.env[key]); + process.env[key] = key === 'LIVEKIT_URL' ? 'http://127.0.0.1:9' : `test-${key.toLowerCase()}`; + } + return () => { + for (const key of LIVEKIT_ENV_KEYS) { + const value = previous.get(key); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; +} + +async function stopFresh(fresh: BacklogModule): Promise { + const stopping = fresh.stopAvPendingRevocations(); + await vi.advanceTimersByTimeAsync(5000); + await stopping; +} + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(async () => { + await stopAll(); + vi.useRealTimers(); +}); + +describe('av pending revocations', () => { + it('drops the entry after a confirmed removal', async () => { + const { remove } = track(() => Promise.resolve('removed')); + const backlog = createAvPendingRevocations({ remove }); + created.push(backlog); + expect(backlog.enqueue('slug:world', 'user-a')).toBe(true); + await flush(); + expect(backlog.pendingCount()).toBe(0); + }); + + it('drops the entry when the participant is already absent', async () => { + const { remove } = track(() => Promise.resolve('absent')); + const backlog = createAvPendingRevocations({ remove }); + created.push(backlog); + expect(backlog.enqueue('slug:world', 'user-a')).toBe(true); + await flush(); + expect(backlog.pendingCount()).toBe(0); + }); + + it('merges duplicate entries for one room and identity', async () => { + const tracked = failing(); + const backlog = createAvPendingRevocations({ remove: tracked.remove }); + created.push(backlog); + expect(backlog.enqueue('slug:world', 'user-a')).toBe(true); + expect(backlog.enqueue('slug:world', 'user-a')).toBe(true); + await flush(); + expect(tracked.calls.length).toBe(1); + expect(backlog.pendingCount()).toBe(1); + }); + + it('retries a failure with growing gaps', async () => { + const tracked = failing(); + const backlog = createAvPendingRevocations({ remove: tracked.remove }); + created.push(backlog); + backlog.enqueue('slug:world', 'user-a'); + await flush(); + expect(tracked.calls.length).toBe(1); + await vi.advanceTimersByTimeAsync(1000); + expect(tracked.calls.length).toBe(2); + await vi.advanceTimersByTimeAsync(1999); + expect(tracked.calls.length).toBe(2); + await vi.advanceTimersByTimeAsync(1); + expect(tracked.calls.length).toBe(3); + await vi.advanceTimersByTimeAsync(4000); + expect(tracked.calls.length).toBe(4); + await vi.advanceTimersByTimeAsync(8000); + expect(tracked.calls.length).toBe(5); + await vi.advanceTimersByTimeAsync(16000); + expect(tracked.calls.length).toBe(6); + }); + + it('caps the steady gap at thirty seconds', async () => { + const tracked = failing(); + const backlog = createAvPendingRevocations({ remove: tracked.remove }); + created.push(backlog); + backlog.enqueue('slug:world', 'user-a'); + await flush(); + for (const gap of [1000, 2000, 4000, 8000, 16000, 30000]) { + await vi.advanceTimersByTimeAsync(gap); + } + expect(tracked.calls.length).toBe(7); + await vi.advanceTimersByTimeAsync(29_999); + expect(tracked.calls.length).toBe(7); + await vi.advanceTimersByTimeAsync(1); + expect(tracked.calls.length).toBe(8); + }); + + it('rejects new entries past the cap and keeps the rest', async () => { + const tracked = failing(); + const backlog = createAvPendingRevocations({ remove: tracked.remove, maxEntries: 2 }); + created.push(backlog); + expect(backlog.enqueue('slug:world', 'user-a')).toBe(true); + expect(backlog.enqueue('slug:world', 'user-b')).toBe(true); + expect(backlog.enqueue('slug:world', 'user-c')).toBe(false); + expect(backlog.pendingCount()).toBe(2); + expect(AV_PENDING_MAX_ENTRIES).toBe(4096); + }); + + it('runs at most four removals at once', async () => { + let active = 0; + let peak = 0; + const release: Array<() => void> = []; + const backlog = createAvPendingRevocations({ + remove: () => + new Promise((resolve) => { + active += 1; + peak = Math.max(peak, active); + release.push(() => { + active -= 1; + resolve('removed'); + }); + }), + }); + created.push(backlog); + for (let index = 0; index < 6; index += 1) backlog.enqueue('slug:world', `user-${index}`); + await flush(); + expect(peak).toBe(4); + while (release.length > 0) (release.shift() as () => void)(); + await flush(); + while (release.length > 0) (release.shift() as () => void)(); + await flush(); + expect(backlog.pendingCount()).toBe(0); + }); + + it('accepts nothing after stop and keeps no timers', async () => { + const tracked = failing(); + const backlog = createAvPendingRevocations({ remove: tracked.remove }); + created.push(backlog); + backlog.enqueue('slug:world', 'user-a'); + await flush(); + await backlog.stop(); + expect(backlog.enqueue('slug:world', 'user-b')).toBe(false); + await vi.advanceTimersByTimeAsync(120_000); + expect(tracked.calls.length).toBe(1); + }); + + it('enqueue before any start is kept and processed', async () => { + const restoreEnv = setDummyLivekitEnv(); + try { + const fresh = await freshBacklogModule(); + expect(fresh.enqueueAvRevocation('slug:world', 'user-a')).toBe(true); + await vi.advanceTimersByTimeAsync(6000); + expect(fresh.avPendingCount()).toBe(1); + await stopFresh(fresh); + expect(fresh.avPendingCount()).toBe(0); + } finally { + restoreEnv(); + } + }); + + it('start does not discard a running backlog', async () => { + const restoreEnv = setDummyLivekitEnv(); + try { + const fresh = await freshBacklogModule(); + expect(fresh.enqueueAvRevocation('slug:world', 'user-a')).toBe(true); + await vi.advanceTimersByTimeAsync(6000); + expect(fresh.avPendingCount()).toBe(1); + fresh.ensureAvPendingRevocations(); + expect(fresh.avPendingCount()).toBe(1); + expect(fresh.enqueueAvRevocation('slug:world', 'user-b')).toBe(true); + expect(fresh.avPendingCount()).toBe(2); + await stopFresh(fresh); + } finally { + restoreEnv(); + } + }); +}); diff --git a/apps/server/src/rooms/lifecycle/avPendingRevocations.ts b/apps/server/src/rooms/lifecycle/avPendingRevocations.ts new file mode 100644 index 00000000..dedcef09 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/avPendingRevocations.ts @@ -0,0 +1,247 @@ +import { logger } from '../../logger.js'; +import { removeParticipantConfirmed } from './livekitRevocation.js'; + +/** Outcome of one privileged removal attempt. */ +export type AvRemovalOutcome = 'removed' | 'absent' | 'failed'; + +/** Privileged removal; injected in tests, LiveKit in production. */ +export type AvRemoveOperation = (roomName: string, identity: string) => Promise; + +/** Confirmed-revocation backlog: retries failures, never grants access. */ +export interface AvPendingBacklog { + enqueue(roomName: string, identity: string): boolean; + stop(): Promise; + pendingCount(): number; +} + +export interface AvPendingOptions { + remove: AvRemoveOperation; + maxEntries?: number; + maxConcurrent?: number; + backoffMs?: number[]; + settleTimeoutMs?: number; +} + +/** Process cap: room plus identity keys, duplicates merged. */ +export const AV_PENDING_MAX_ENTRIES = 4096; +/** Privileged calls running at once. */ +export const AV_PENDING_MAX_CONCURRENT = 4; +/** Retry gaps: 1, 2, 4, 8, 16 s, then the steady gap. */ +export const AV_PENDING_BACKOFF_MS = [1000, 2000, 4000, 8000, 16000]; +/** Steady retry gap after the growing phase. */ +export const AV_PENDING_STEADY_MS = 30_000; +/** Stop waits for running calls at most this long. */ +export const AV_PENDING_SETTLE_MS = 5000; + +interface BacklogEntry { + key: string; + roomName: string; + identity: string; + failures: number; +} + +interface BacklogState { + remove: AvRemoveOperation; + maxEntries: number; + maxConcurrent: number; + backoffs: number[]; + steadyMs: number; + settleMs: number; + entries: Map; + waiters: Array<() => void>; + sleepers: Set<() => void>; + timers: Set>; + inflight: Set>; + running: number; + stopped: boolean; + dropped: number; +} + +function backoffFor(backoffs: number[], steadyMs: number, failures: number): number { + if (failures < backoffs.length) return backoffs[failures] as number; + return steadyMs; +} + +/** A slot frees the next waiter (handoff) or decrements the counter. */ +function releaseSlot(state: BacklogState): void { + const next = state.waiters.shift(); + if (next) { + next(); + return; + } + state.running -= 1; +} + +/** False when the backlog stopped while waiting; the caller then exits. */ +function acquireSlot(state: BacklogState): Promise { + if (state.stopped) return Promise.resolve(false); + if (state.running < state.maxConcurrent) { + state.running += 1; + return Promise.resolve(true); + } + return new Promise((resolve) => { + state.waiters.push(() => resolve(!state.stopped)); + }); +} + +/** Wakeable sleep; stop clears the timer and wakes every sleeper at once. */ +function sleepMs(state: BacklogState, ms: number): Promise { + return new Promise((resolve) => { + const wake = (): void => { + state.sleepers.delete(wake); + state.timers.delete(timer); + resolve(); + }; + const timer = setTimeout(wake, ms); + timer.unref(); + state.timers.add(timer); + state.sleepers.add(wake); + }); +} + +async function runEntry(state: BacklogState, entry: BacklogEntry): Promise { + for (;;) { + if (state.stopped || !state.entries.has(entry.key)) return; + const admitted = await acquireSlot(state); + if (!admitted || state.stopped || !state.entries.has(entry.key)) { + if (admitted) releaseSlot(state); + return; + } + let outcome: AvRemovalOutcome; + try { + outcome = await state.remove(entry.roomName, entry.identity); + } catch { + outcome = 'failed'; + } finally { + releaseSlot(state); + } + if (outcome === 'removed' || outcome === 'absent') { + state.entries.delete(entry.key); + return; + } + const gap = backoffFor(state.backoffs, state.steadyMs, entry.failures); + entry.failures += 1; + await sleepMs(state, gap); + } +} + +function enqueueInto(state: BacklogState, roomName: string, identity: string): boolean { + if (state.stopped) return false; + const key = JSON.stringify([roomName, identity]); + if (state.entries.has(key)) return true; + if (state.entries.size >= state.maxEntries) { + state.dropped += 1; + logger.warn({ event: 'av.revocation_overflow', dropped: state.dropped }); + return false; + } + const entry: BacklogEntry = { key, roomName, identity, failures: 0 }; + state.entries.set(key, entry); + const task = runEntry(state, entry); + state.inflight.add(task); + void task.then(() => { + state.inflight.delete(task); + }); + return true; +} + +async function stopBacklog(state: BacklogState): Promise { + state.stopped = true; + for (const timer of state.timers) clearTimeout(timer); + state.timers.clear(); + for (const wake of [...state.waiters]) wake(); + state.waiters.length = 0; + for (const wake of [...state.sleepers]) wake(); + state.sleepers.clear(); + state.entries.clear(); + if (state.inflight.size === 0) return; + const settle = new Promise((resolve) => { + const timer = setTimeout(resolve, state.settleMs); + timer.unref(); + }); + await Promise.race([Promise.allSettled([...state.inflight]), settle]); +} + +/** + * Backlog with an injected removal operation. The production instance uses + * the confirmed LiveKit removal; tests inject a stub and fake timers. + */ +export function createAvPendingRevocations(options: AvPendingOptions): AvPendingBacklog { + const state: BacklogState = { + remove: options.remove, + maxEntries: options.maxEntries ?? AV_PENDING_MAX_ENTRIES, + maxConcurrent: options.maxConcurrent ?? AV_PENDING_MAX_CONCURRENT, + backoffs: options.backoffMs ?? AV_PENDING_BACKOFF_MS, + steadyMs: AV_PENDING_STEADY_MS, + settleMs: options.settleTimeoutMs ?? AV_PENDING_SETTLE_MS, + entries: new Map(), + waiters: [], + sleepers: new Set(), + timers: new Set(), + inflight: new Set(), + running: 0, + stopped: false, + dropped: 0, + }; + return { + enqueue: (roomName, identity) => enqueueInto(state, roomName, identity), + stop: () => stopBacklog(state), + pendingCount: () => state.entries.size, + }; +} + +type BacklogPhase = 'idle' | 'running' | 'stopped'; + +let phase: BacklogPhase = 'idle'; +let singleton: AvPendingBacklog | null = null; + +function hasLivekitConfig(): boolean { + return Boolean(process.env.LIVEKIT_URL && process.env.LIVEKIT_API_KEY && process.env.LIVEKIT_API_SECRET); +} + +/** + * Begin (or keep) the process backlog epoch. Creates a backlog only from + * `idle` or `stopped`, never discards a running one, and ends `running`. + */ +export function ensureAvPendingRevocations(): void { + if (phase === 'running' && singleton) return; + singleton = createAvPendingRevocations({ remove: removeParticipantConfirmed }); + phase = 'running'; +} + +/** Entries currently held by the process backlog (0 without a backlog). */ +export function avPendingCount(): number { + return singleton ? singleton.pendingCount() : 0; +} + +/** + * Queue a confirmed removal through the process backlog. Lazily starts the + * backlog from `idle` so revocations before the reconciler boot are kept; + * after the stop nothing is accepted. Without LiveKit coordinates nothing is + * accepted either, so no endless retry builds up. Returns false when the + * entry was dropped or the backlog overflows; the periodic reconciler picks + * the participant up again. Never grants access. + */ +export function enqueueAvRevocation(roomName: string, identity: string): boolean { + if (phase === 'stopped') { + logger.debug({ event: 'av.revocation_dropped', reason: 'backlog_stopped' }); + return false; + } + if (!hasLivekitConfig()) { + logger.debug({ event: 'av.revocation_dropped', reason: 'not_configured' }); + return false; + } + ensureAvPendingRevocations(); + return singleton ? singleton.enqueue(roomName, identity) : false; +} + +/** + * Drop every timer and entry, await running calls briefly, accept nothing + * more. A restart loses the entries like a real process exit; the next + * reconciler round rediscovers the participants. + */ +export async function stopAvPendingRevocations(): Promise { + phase = 'stopped'; + const current = singleton; + singleton = null; + if (current) await current.stop(); +} diff --git a/apps/server/src/rooms/lifecycle/avSessionRef.ts b/apps/server/src/rooms/lifecycle/avSessionRef.ts new file mode 100644 index 00000000..d38882de --- /dev/null +++ b/apps/server/src/rooms/lifecycle/avSessionRef.ts @@ -0,0 +1,104 @@ +import crypto from 'crypto'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; + +/** + * Opaque binding between a LiveKit participant and the login session that + * issued its token. + * + * A participant on the SFU is addressed by an identity alone, so a token that + * stays valid after the session behind it ended would let its holder rejoin + * with a cached token. The token therefore carries a reference that only the + * server can resolve back to a session: an HMAC over the session row id under + * a key derived from the JWT secret with its own purpose label. The + * reference proves "this participant holds the session it was issued for" + * without exposing the session id, the token or the token hash to the SFU or + * to any other participant. + */ + +/** Version prefix of the reference; a change of the derivation needs a new one. */ +const SESSION_REF_VERSION = 'v1'; + +/** Purpose label of the key derivation; never reuse it for another purpose. */ +const SESSION_REF_KEY_INFO = 'meetropolis/av-session-ref/v1'; + +/** Length of the derived key in bytes. */ +const SESSION_REF_KEY_LENGTH = 32; + +/** Length of the base64url encoded digest of a 32 byte HMAC, without padding. */ +const SESSION_REF_LENGTH = 43; + +const SESSION_REF_PATTERN = new RegExp(`^${SESSION_REF_VERSION}\\.[A-Za-z0-9_-]{${SESSION_REF_LENGTH}}$`); + +/** + * Identities reserved for services and for the readiness probe. The user + * endpoint never issues them, so such an identity always belongs to a + * service, never to a member. + */ +const RESERVED_IDENTITY_PREFIXES = ['npc-', 'svc-']; + +/** Identity of the readiness probe participant (see the health route). */ +const RESERVED_PROBE_IDENTITY = 'probe'; + +let cachedKey: Buffer | null = null; + +/** Derive the reference key once per process. */ +function sessionRefKey(): Buffer { + if (cachedKey) return cachedKey; + const derived = crypto.hkdfSync( + 'sha256', + getJwtSecret(), + Buffer.alloc(0), + SESSION_REF_KEY_INFO, + SESSION_REF_KEY_LENGTH, + ); + cachedKey = Buffer.from(derived); + return cachedKey; +} + +/** Opaque, versioned reference of one login session. */ +export function avSessionRef(sessionId: string): string { + const digest = crypto.createHmac('sha256', sessionRefKey()).update(sessionId).digest('base64url'); + return `${SESSION_REF_VERSION}.${digest}`; +} + +/** + * Metadata written into the LiveKit token. It carries the reference and + * nothing else - no session id, no token, no token hash. + */ +export function avSessionMetadata(sessionId: string): string { + return JSON.stringify({ sessionRef: avSessionRef(sessionId) }); +} + +/** + * Read the session reference out of participant metadata. + * + * Returns null for missing, malformed or foreign metadata: only a reference + * of the current version and of the expected fixed length is accepted. + */ +export function readAvSessionRef(metadata: string | undefined): string | null { + if (typeof metadata !== 'string' || metadata.length === 0) return null; + let parsed: unknown; + try { + parsed = JSON.parse(metadata); + } catch { + return null; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null; + const ref = (parsed as Record).sessionRef; + if (typeof ref !== 'string' || !SESSION_REF_PATTERN.test(ref)) return null; + return ref; +} + +/** Constant-time check that a reference belongs to the given session. */ +export function avSessionRefMatches(ref: string, sessionId: string): boolean { + const expected = Buffer.from(avSessionRef(sessionId), 'utf8'); + const presented = Buffer.from(ref, 'utf8'); + if (presented.length !== expected.length) return false; + return crypto.timingSafeEqual(presented, expected); +} + +/** True for the identities the user endpoint must never issue. */ +export function isReservedAvIdentity(identity: string): boolean { + if (identity === RESERVED_PROBE_IDENTITY) return true; + return RESERVED_IDENTITY_PREFIXES.some((prefix) => identity.startsWith(prefix)); +} diff --git a/apps/server/src/rooms/lifecycle/guestExpiry.ts b/apps/server/src/rooms/lifecycle/guestExpiry.ts index 6314d5f9..8cf7052d 100644 --- a/apps/server/src/rooms/lifecycle/guestExpiry.ts +++ b/apps/server/src/rooms/lifecycle/guestExpiry.ts @@ -1,65 +1,93 @@ import { logger } from '../../logger.js'; import { createPrismaClient } from '../../db.js'; import { revokeSessionsForUser } from '../../api/utils/sessionAuth.js'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { + classifyDeniedAccess, + denialClose, + readWorldAccess, + type WorldAccessDenial, + type WorldAccessEntry, +} from './worldAccess.js'; +import { applyAccessProof, rescheduleWorldAccessLeaseTimer, resolveWorldAccessTiming } from './worldAccessLease.js'; +import { enqueueAvRevocation } from './avPendingRevocations.js'; import type { WorldRoom } from '../WorldRoom.js'; -interface RoomMetadata { - tenant?: string; - [key: string]: unknown; +/** Disconnect one joined session; the AV call ends separately below. */ +function disconnectSession(room: WorldRoom, sessionId: string, code: number, reason: string): void { + const client = room.clients.find((c) => c.sessionId === sessionId); + if (!client) return; + try { + client.error(code, reason); + } catch { + /* best-effort: the client may already be gone */ + } + client.leave(1000); } -// Periodic check: disconnect guest users whose membership expiresAt is -// in the past, and delete their sessions. Runs every 60s. -export function startGuestExpiryInterval(room: WorldRoom): ReturnType { - return setInterval(() => { - void (async () => { - try { - const tenantSlug = (room.metadata as RoomMetadata)?.tenant || process.env.DEFAULT_TENANT_SLUG || 'default'; - const prisma = room.prismaForPresence ?? createPrismaClient(); - const tenant = await prisma.tenant.findUnique({ where: { slug: tenantSlug } }); - if (!tenant) return; - - const expiredGuests = await prisma.membership.findMany({ - where: { - tenantId: tenant.id, - role: 'guest', - expiresAt: { lt: new Date() }, - }, - select: { userId: true }, - }); - - if (expiredGuests.length === 0) return; +async function denialOf(prisma: PrismaClient, entry: WorldAccessEntry): Promise { + try { + return await classifyDeniedAccess(prisma, entry.userId, entry.tenantId, entry.authSessionId); + } catch (e) { + logger.warn({ + event: 'world.access_revoked_check_failed', + userId: entry.userId, + tenantId: entry.tenantId, + error: String(e), + }); + return 'not_member_of_tenant'; + } +} - const expiredUserIds = new Set(expiredGuests.map((g) => g.userId)); +/** Proven denial: disconnect, and drop an expired guest's sessions so the + * cached token cannot walk back in. Never called for a successful proof. */ +async function disconnectDenied(room: WorldRoom, prisma: PrismaClient, entry: WorldAccessEntry): Promise { + const reason = await denialOf(prisma, entry); + const close = denialClose(reason); + disconnectSession(room, entry.sessionId, close.code, close.message); + if (reason === 'guest_expired') { + await revokeSessionsForUser(prisma, entry.userId).catch(() => { + /* best-effort */ + }); + } else if (reason === 'not_member_of_tenant') { + logger.warn({ event: 'world.access_revoked', tenantId: entry.tenantId, userId: entry.userId }); + } + // Confirmed AV removal through the process-wide backlog (see worldAccess.ts). + enqueueAvRevocation(`${entry.tenantSlug}:world`, entry.userId); +} - // Find connected clients that are expired guests - room.state.players.forEach((player, sessionId) => { - if (expiredUserIds.has(player.identity)) { - const matchedClient = room.clients.find((c) => c.sessionId === sessionId); - if (matchedClient) { - try { - matchedClient.error(4006, 'guest_expired'); - } catch { - /* best-effort */ - } - matchedClient.leave(1000); - } - } - }); +/** + * Re-read every joined seat. Proofs are applied only after every read + * returned; a database error renews nothing and disconnects nobody (the + * lease still ends the seat). A missing session or a failed access proof + * disconnects and is never renewed. + */ +async function sweepJoinedAccess(room: WorldRoom): Promise { + const prisma = room.prismaForPresence ?? createPrismaClient(); + const joined = room.worldAccess.joined(); + const checks: Array<{ entry: WorldAccessEntry; ok: boolean; expiresAt: Date | null }> = []; + for (const entry of joined) { + const check = await readWorldAccess(prisma, entry.userId, entry.tenantId, entry.authSessionId); + checks.push({ entry, ok: check.ok, expiresAt: check.expiresAt }); + } + for (const item of checks) { + if (item.ok) { + applyAccessProof(item.entry, item.expiresAt); + continue; + } + await disconnectDenied(room, prisma, item.entry); + } + rescheduleWorldAccessLeaseTimer(room); +} - // Delete sessions for expired guests. Via the helper, never a raw - // `session.deleteMany`: the rows are only half the session. Leaving the - // in-process cache populated lets the just-kicked guest re-join the - // world with the very same token for up to SESSION_CACHE_TTL_MS, since - // onAuth resolves against that cache. - for (const userId of expiredUserIds) { - await revokeSessionsForUser(prisma, userId).catch(() => { - /* best-effort */ - }); - } - } catch (e) { - logger.debug('[WorldRoom] Guest expiry check failed', e); - } - })(); - }, 60_000); +// Periodic access check of a world room, every WORLD_ACCESS_SWEEP_MS +// (default 30 s): each joined human seat is re-proven with its stored +// database session id. Failed proofs disconnect. Seats that keep access +// get a fresh lease (see worldAccessLease.ts). A failed sweep renews nothing. +export function startGuestExpiryInterval(room: WorldRoom): ReturnType { + return setInterval(() => { + void sweepJoinedAccess(room).catch((e: unknown) => { + logger.warn('[WorldRoom] Room access sweep failed', e); + }); + }, resolveWorldAccessTiming().sweepMs); } diff --git a/apps/server/src/rooms/lifecycle/livekitRevocation.ts b/apps/server/src/rooms/lifecycle/livekitRevocation.ts new file mode 100644 index 00000000..46ad4c2a --- /dev/null +++ b/apps/server/src/rooms/lifecycle/livekitRevocation.ts @@ -0,0 +1,69 @@ +import { RoomServiceClient } from 'livekit-server-sdk'; +import { logger } from '../../logger.js'; +import { mapLivekitUrlToHttp } from '../audioZones/livekitAdmin.js'; + +/** Outcome of one privileged removal attempt: retry every `failed`. */ +export type ConfirmedRemoval = 'removed' | 'absent' | 'failed'; + +/** Twirp `not_found` (or HTTP 404) proves the participant is already gone. */ +function isAbsentError(error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false; + if ('code' in error && error.code === 'not_found') return true; + return 'status' in error && error.status === 404; +} + +/** Admin client for confirmed removals: 5 s request timeout via client options. */ +function createConfirmedService(): RoomServiceClient | null { + const apiKey = process.env.LIVEKIT_API_KEY; + const apiSecret = process.env.LIVEKIT_API_SECRET; + const rawUrl = process.env.LIVEKIT_URL; + if (!apiKey || !apiSecret || !rawUrl) return null; + return new RoomServiceClient(mapLivekitUrlToHttp(rawUrl), apiKey, apiSecret, { requestTimeout: 5 }); +} + +/** + * Remove one participant with a confirmed outcome: `removed` after a + * successful call, `absent` only for a `not_found` error or when the + * participant is missing from the list, every other failure (timeout, + * network, auth, missing credentials) is `failed`. Never throws. + */ +export async function removeParticipantConfirmed( + roomName: string, + identity: string, +): Promise { + const client = createConfirmedService(); + if (!client) { + logger.debug({ event: 'livekit.revoke_skipped', reason: 'not_configured', roomName }); + return 'failed'; + } + try { + const participants = await client.listParticipants(roomName); + if (!participants.some((participant) => participant.identity === identity)) return 'absent'; + } catch (error: unknown) { + if (isAbsentError(error)) return 'absent'; + logger.warn({ event: 'livekit.revoke_failed', roomName, error: errorText(error) }); + return 'failed'; + } + try { + await client.removeParticipant(roomName, identity); + logger.info({ event: 'livekit.participant_removed', roomName, userId: identity }); + return 'removed'; + } catch (error: unknown) { + if (isAbsentError(error)) return 'absent'; + logger.warn({ event: 'livekit.revoke_failed', roomName, error: errorText(error) }); + return 'failed'; + } +} + +/** + * Removes a user from the LiveKit calls of a tenant when the user loses access + * to it. Disconnecting the world (Colyseus) does not end an AV call: the + * LiveKit connection is separate and its access token stays valid until it + * expires. LiveKit rooms of a tenant are named `:` (see + * /livekit/token in api/routes/health.ts) and the participant identity is the + * user id. + */ + +function errorText(e: unknown): string { + return e instanceof Error ? e.message : String(e); +} diff --git a/apps/server/src/rooms/lifecycle/npcServiceAuth.ts b/apps/server/src/rooms/lifecycle/npcServiceAuth.ts new file mode 100644 index 00000000..dfbe3f34 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/npcServiceAuth.ts @@ -0,0 +1,60 @@ +import crypto from 'crypto'; +import type { PrismaClient } from '../../generated/prisma/index.js'; + +/** + * Rejected stand-ins for `NPC_SERVICE_SECRET`: the literal used when the + * variable is unset. Compared after trim, in every environment. + */ +const KNOWN_NPC_SERVICE_SECRET_DEFAULTS = ['dev-npc-secret'] as const; + +const MIN_NPC_SERVICE_SECRET_LENGTH = 32; + +/** Join identities are this prefix plus the stored `Npc.identity`. */ +const NPC_JOIN_PREFIX = 'npc-'; + +/** + * A secret is usable only when it is present, not blank, not a known default, + * and at least 32 characters after trim. The value itself is never returned. + */ +export function isSecureNpcServiceSecret(value: string | undefined): boolean { + if (typeof value !== 'string') return false; + const trimmed = value.trim(); + if (trimmed.length < MIN_NPC_SERVICE_SECRET_LENGTH) return false; + return !KNOWN_NPC_SERVICE_SECRET_DEFAULTS.some((known) => known === trimmed); +} + +/** + * True only when the server secret is usable and `presented` is a string of + * the same byte length that matches it. Length is checked before the compare + * because `timingSafeEqual` rejects unequal buffers. + */ +export function verifyNpcServiceToken(presented: unknown): boolean { + const secret = process.env.NPC_SERVICE_SECRET; + if (!isSecureNpcServiceSecret(secret) || typeof secret !== 'string') return false; + if (typeof presented !== 'string') return false; + const expected = Buffer.from(secret); + const actual = Buffer.from(presented); + if (expected.length !== actual.length) return false; + return crypto.timingSafeEqual(expected, actual); +} + +/** + * The NPC service joins as `npc-` plus `Npc.identity` (one prefix, the value + * stored for that tenant). `@@unique([tenantId, identity])` makes the row + * unique. Returns null when the prefix or the row is missing. + */ +export async function resolveNpcPrincipal( + prisma: PrismaClient, + tenantId: string, + joinIdentity: string, +): Promise<{ npcId: string; identity: string } | null> { + if (!joinIdentity.startsWith(NPC_JOIN_PREFIX)) return null; + const identity = joinIdentity.slice(NPC_JOIN_PREFIX.length); + if (identity.length === 0) return null; + const row = await prisma.npc.findUnique({ + where: { tenantId_identity: { tenantId, identity } }, + select: { id: true, identity: true }, + }); + if (!row) return null; + return { npcId: row.id, identity: row.identity }; +} diff --git a/apps/server/src/rooms/lifecycle/onAuth.identity.test.ts b/apps/server/src/rooms/lifecycle/onAuth.identity.test.ts index 73b7a854..530b5c26 100644 --- a/apps/server/src/rooms/lifecycle/onAuth.identity.test.ts +++ b/apps/server/src/rooms/lifecycle/onAuth.identity.test.ts @@ -1,16 +1,16 @@ /** - * With ZONE_PRIVACY_AUTH_ENFORCE off, a join without a token is admitted under - * the identity the client names, and that identity goes into the room state. - * It must not be allowed to be as long as the client likes. + * A join without a token is refused regardless of the version setting: + * the client-supplied identity never reaches the room state, however short. + * The verified token subject is the only identity a human join can carry. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const log = vi.hoisted(() => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })); vi.mock('../../logger.js', () => ({ logger: log })); -const validateSessionTokenMock = vi.fn(); +const validateTenantSessionFreshMock = vi.fn(); vi.mock('../../api/utils/sessionAuth.js', () => ({ - validateSessionToken: (...args: unknown[]) => validateSessionTokenMock(...args), + validateTenantSessionFresh: (...args: unknown[]) => validateTenantSessionFreshMock(...args), })); import { authenticateWorldJoin, AUTH_REJECTED_CODE } from './onAuth.js'; @@ -23,8 +23,11 @@ type AuthContext = Parameters[1]; const ORIGINAL_ENV = { ...process.env }; const prisma = { - tenant: { findUnique: vi.fn(() => Promise.resolve(null)) }, + tenant: { findUnique: vi.fn(() => Promise.resolve({ id: 'tenant-1', slug: 'tenant-1' })) }, session: { findUnique: vi.fn(), update: vi.fn() }, + // Joins in these tests come from members; the membership gate has its own tests. + membership: { findUnique: vi.fn(() => Promise.resolve({ expiresAt: null })) }, + npc: { findUnique: vi.fn(() => Promise.resolve({ id: 'npc-id', identity: 'bob' })) }, } as unknown as WorldJoinPrisma; const tokenless: AuthContext = { headers: new Headers(), ip: '127.0.0.1' }; @@ -40,41 +43,43 @@ afterEach(() => { process.env = { ...ORIGINAL_ENV }; }); -describe('identity of a token-less join in staged mode', () => { - it.each(['legacy-user', 'clx0a1b2c3d4e5f6g7h8i9j0k', 'loadtest-bot-0042', 'Jörg'])( - 'admits %s unchanged', +describe('identity of a token-less join without version enforcement', () => { + it.each(['legacy-user', 'clx0a1b2c3d4e5f6g7h8i9j0k', 'loadtest-bot-0042', 'J\u00f6rg'])( + 'rejects %s without a valid session', async (identity) => { const options: RoomOptions = { identity, zonePrivacyVersion: 0 }; - const auth = await authenticateWorldJoin(options, tokenless, prisma); - - expect(auth).toEqual({ identity, isNpc: false, zonePrivacyVersion: 0 }); + await expect(authenticateWorldJoin(options, tokenless, prisma)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'unauthorized', + }); }, ); - it('admits an identity of exactly the limit', async () => { - const identity = 'u'.repeat(MAX_JOIN_IDENTITY_LENGTH); - - const auth = await authenticateWorldJoin({ identity, zonePrivacyVersion: 0 }, tokenless, prisma); + it('rejects an identity of exactly the limit without a valid session', async () => { + const options: RoomOptions = { identity: 'u'.repeat(MAX_JOIN_IDENTITY_LENGTH), zonePrivacyVersion: 0 }; - expect(auth.identity).toBe(identity); + await expect(authenticateWorldJoin(options, tokenless, prisma)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'unauthorized', + }); }); - it('refuses an identity one above the limit', async () => { + it('rejects an identity one above the limit without a valid session', async () => { const options: RoomOptions = { identity: 'u'.repeat(MAX_JOIN_IDENTITY_LENGTH + 1), zonePrivacyVersion: 0 }; await expect(authenticateWorldJoin(options, tokenless, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE, - message: 'identity_invalid', + message: 'unauthorized', }); }); it('refuses a 900,000 character identity and logs only a bounded line', async () => { - const options: RoomOptions = { identity: 'x'.repeat(900_000), zonePrivacyVersion: 0 }; + const options: RoomOptions = { identity: 'x'.repeat(900_000), zonePrivacyVersion: 1 }; await expect(authenticateWorldJoin(options, tokenless, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE, - message: 'identity_invalid', + message: 'unauthorized', }); expect(log.warn).toHaveBeenCalledTimes(1); @@ -82,8 +87,15 @@ describe('identity of a token-less join in staged mode', () => { }); it('does not touch a verified join, whose identity is the token subject', async () => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-real', tenantId: 'tenant-1' }); - const options: RoomOptions = { identity: 'x'.repeat(900_000), zonePrivacyVersion: 0 }; + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-real', + tenantId: 'tenant-1', + }); + prisma.tenant.findUnique.mockResolvedValueOnce({ slug: 'tenant-1' }); + const options: RoomOptions = { identity: 'x'.repeat(900_000), zonePrivacyVersion: 1 }; const context: AuthContext = { headers: new Headers({ cookie: 'auth_token=jwt' }), ip: '127.0.0.1' }; const auth = await authenticateWorldJoin(options, context, prisma); diff --git a/apps/server/src/rooms/lifecycle/onAuth.logging.test.ts b/apps/server/src/rooms/lifecycle/onAuth.logging.test.ts index 02780677..56c50c0d 100644 --- a/apps/server/src/rooms/lifecycle/onAuth.logging.test.ts +++ b/apps/server/src/rooms/lifecycle/onAuth.logging.test.ts @@ -10,9 +10,9 @@ import { MIN_ZONE_PRIVACY_CLIENT_VERSION } from '@meetropolis/shared'; const log = vi.hoisted(() => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })); vi.mock('../../logger.js', () => ({ logger: log })); -const validateSessionTokenMock = vi.fn(); +const validateTenantSessionFreshMock = vi.fn(); vi.mock('../../api/utils/sessionAuth.js', () => ({ - validateSessionToken: (...args: unknown[]) => validateSessionTokenMock(...args), + validateTenantSessionFresh: (...args: unknown[]) => validateTenantSessionFreshMock(...args), })); import { authenticateWorldJoin } from './onAuth.js'; @@ -27,8 +27,11 @@ const LOG_BUDGET_CHARS = 1_000; const ORIGINAL_ENV = { ...process.env }; const prisma = { - tenant: { findUnique: vi.fn(() => Promise.resolve({ slug: 'auth-a' })) }, + tenant: { findUnique: vi.fn(() => Promise.resolve({ id: 'tenant-a-id', slug: 'auth-a' })) }, session: { findUnique: vi.fn(), update: vi.fn() }, + // Joins in these tests come from members; the membership gate has its own tests. + membership: { findUnique: vi.fn(() => Promise.resolve({ expiresAt: null })) }, + npc: { findUnique: vi.fn(() => Promise.resolve({ id: 'npc-id', identity: 'bob' })) }, } as unknown as WorldJoinPrisma; function context(): AuthContext { @@ -49,10 +52,10 @@ beforeEach(() => { vi.clearAllMocks(); process.env = { ...ORIGINAL_ENV }; process.env.NODE_ENV = 'test'; - process.env.NPC_SERVICE_SECRET = 'test-npc-secret'; + process.env.NPC_SERVICE_SECRET = 'n'.repeat(40); delete process.env.ZONE_PRIVACY_AUTH_ENFORCE; delete process.env.ZONE_PRIVACY_TENANT_ENFORCE; - validateSessionTokenMock.mockReset(); + validateTenantSessionFreshMock.mockReset(); }); afterEach(() => { @@ -69,14 +72,15 @@ describe('onAuth logs stay bounded', () => { expect(logged()).toContain('(900004 chars)'); }); - it('for the identity of a token-less join admitted in staged mode', async () => { - // The longest identity that is still admitted (see joinFields.ts) is cut in the log. + it('for a token-less join refused without a valid session', async () => { + // The refusal logs no client-supplied value at all (see onAuth.ts), so + // even a huge client-supplied identity stays far below the budget. const options: RoomOptions = { identity: 'x'.repeat(MAX_JOIN_IDENTITY_LENGTH), zonePrivacyVersion: 0 }; - await authenticateWorldJoin(options, tokenless(), prisma); + await expect(authenticateWorldJoin(options, tokenless(), prisma)).rejects.toThrow(); expect(log.warn).toHaveBeenCalled(); - expect(logged()).toContain(`(${MAX_JOIN_IDENTITY_LENGTH} chars)`); + expect(logged()).not.toContain('x'.repeat(100)); expect(logged().length).toBeLessThan(LOG_BUDGET_CHARS); }); @@ -84,7 +88,13 @@ describe('onAuth logs stay bounded', () => { ['rejects', 'true'], ['admits', undefined], ])('for a mismatching options.tenant when the room match %s', async (_label, enforce) => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-1', tenantId: 'tenant-a-id' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-1', + tenantId: 'tenant-a-id', + }); if (enforce) process.env.ZONE_PRIVACY_TENANT_ENFORCE = enforce; const options: RoomOptions = { tenant: HUGE, zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; @@ -98,7 +108,13 @@ describe('onAuth logs stay bounded', () => { ['enforcement on', 'true'], ['enforcement off', undefined], ])('for a zone-privacy version that is a long string, %s', async (_label, enforce) => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-1' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-1', + tenantId: 'tenant-a-id', + }); if (enforce) process.env.ZONE_PRIVACY_AUTH_ENFORCE = enforce; // A client can send any JSON value; the wire type says number only in theory. const options = { zonePrivacyVersion: HUGE } as unknown as RoomOptions; @@ -111,8 +127,14 @@ describe('onAuth logs stay bounded', () => { }); it('leaves short, ordinary values readable', async () => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-1', tenantId: 'tenant-a-id' }); - const options: RoomOptions = { tenant: 'spoof-b', zonePrivacyVersion: 0 }; + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-1', + tenantId: 'tenant-a-id', + }); + const options: RoomOptions = { tenant: 'spoof-b', zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; await authenticateWorldJoin(options, context(), prisma); diff --git a/apps/server/src/rooms/lifecycle/onAuth.session.integration.test.ts b/apps/server/src/rooms/lifecycle/onAuth.session.integration.test.ts new file mode 100644 index 00000000..c7d3b7df --- /dev/null +++ b/apps/server/src/rooms/lifecycle/onAuth.session.integration.test.ts @@ -0,0 +1,183 @@ +/** + * Human world joins always require a live session row. + * + * A real Colyseus server with the real WorldRoom (see + * testUtils/matchmakeHarness.ts), a real PostgreSQL database (db.js is NOT + * mocked) and a real @colyseus/sdk client. Every case runs with + * ZONE_PRIVACY_AUTH_ENFORCE unset and with it set to 'true'. + * + * Before the R4 fix the token-less, revoked-session and deleted-account joins + * are admitted while enforcement is off (the legacy fallback); after the fix + * every one of them is rejected with 4401 'unauthorized'. + */ + +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; +import { hashSessionToken, revokeSessionsForUser } from '../../api/utils/sessionAuth.js'; +import { deleteAccount } from '../../services/accountDeletion.js'; +import { AUTH_REJECTED_CODE } from './onAuth.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('onAuth.session.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const packUuids: string[] = []; +let server: MatchmakeTestServer; +let tenantId: string; +let tenantSlug: string; +let fixturePackUuid = ''; + +/** + * One global (tenantId null) avatar pack so a join that passes onAuth can run + * to completion. Real fixture row, not a mock: without any pack in scope even + * a fully authorized join is refused later in onJoin with 526. + */ +async function seedGlobalAvatarPack(): Promise { + const uuid = `s1r4-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'session join fixture', + author: 's1r4-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +async function createMember(role: Role = 'member'): Promise<{ id: string; token: string }> { + const user = await prisma.user.create({ + data: { + email: `s1r4-${crypto.randomUUID()}@example.test`, + // Points at the seeded global pack so the avatar allow-list has a hit. + avatarId: `${fixturePackUuid}:business_man`, + }, + }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId, role } }); + // The session is scoped to the world's tenant, whatever the memberships say. + const token = jwt.sign({ sub: user.id, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, token }; +} + +function joinOptions(identity: string): Record { + return { + tenant: tenantSlug, + identity, + // A real client always names its avatar; without one even an authorized + // join stops later in onJoin (526), which would blur this gate's signal. + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; +} + +interface JoinAttempt { + room?: Room; + error?: unknown; +} + +async function attemptJoin(identity: string, token?: string): Promise { + const client = new Client(server.base); + if (token) client.auth.token = token; + try { + const room = await client.joinOrCreate('world', joinOptions(identity)); + return { room }; + } catch (error) { + return { error }; + } +} + +/** A rejected join carries 4401 'unauthorized'; an admitted join is left behind. */ +async function expectUnauthorized(attempt: JoinAttempt): Promise { + if (attempt.room) await attempt.room.leave(); + expect(attempt.error).toMatchObject({ code: AUTH_REJECTED_CODE, message: 'unauthorized' }); +} + +beforeAll(async () => { + tenantSlug = `s1r4-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + const tenant = await prisma.tenant.create({ data: { slug: tenantSlug, name: tenantSlug } }); + tenantIds.push(tenant.id); + tenantId = tenant.id; + await seedGlobalAvatarPack(); + server = await startMatchmakeServer(); +}); + +beforeEach(async () => { + await disposeAllRooms(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +afterAll(async () => { + await stopMatchmakeServer(server); + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +for (const enforced of [undefined, 'true'] as const) { + describe(`human joins need a live session (enforcement ${enforced ?? 'off'})`, () => { + beforeEach(() => { + if (enforced) vi.stubEnv('ZONE_PRIVACY_AUTH_ENFORCE', enforced); + }); + + it('rejects a join with no token, even for the identity of a real member', async () => { + const member = await createMember(); + + await expectUnauthorized(await attemptJoin(member.id)); + }); + + it('rejects a join whose session was revoked', async () => { + const member = await createMember(); + await revokeSessionsForUser(prisma, member.id); + + await expectUnauthorized(await attemptJoin(member.id, member.token)); + }); + + it('rejects a join whose account was deleted', async () => { + const member = await createMember(); + await deleteAccount(prisma, member.id); + + await expectUnauthorized(await attemptJoin(member.id, member.token)); + }); + + it('admits a join with a valid token (positive control)', async () => { + const member = await createMember(); + + const { room, error } = await attemptJoin(member.id, member.token); + + expect(error).toBeUndefined(); + expect(room?.sessionId).toEqual(expect.any(String)); + await room?.leave(); + }); + }); +} diff --git a/apps/server/src/rooms/lifecycle/onAuth.test.ts b/apps/server/src/rooms/lifecycle/onAuth.test.ts index c13d28e3..c0bbb04a 100644 --- a/apps/server/src/rooms/lifecycle/onAuth.test.ts +++ b/apps/server/src/rooms/lifecycle/onAuth.test.ts @@ -2,13 +2,13 @@ * Unit tests for the H4 hardening gate: identity binding (onAuth) + * client zone-privacy version gate. * - * All external dependencies (logger, sessionAuth.validateSessionToken) are + * All external dependencies (logger, sessionAuth.validateTenantSessionFresh) are * mocked so no real JWT signing/DB is required. Tests exercise the pure * decision logic in authenticateWorldJoin/isWorldAuth/requireWorldAuth. * - * The gate resolves tokens through `validateSessionToken` (the session ROW is + * The gate resolves tokens through `validateTenantSessionFresh` (the session ROW is * the authority), not through `verifyAuthJwt` (signature only) — a revoked - * session must not open the world. `validateSessionToken` returning null is + * session must not open the world. `validateTenantSessionFresh` returning null is * therefore the single "not authenticated" signal here, covering a bad * signature AND a valid signature whose session is gone. */ @@ -20,9 +20,13 @@ vi.mock('../../logger.js', () => ({ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, })); -const validateSessionTokenMock = vi.fn(); +const validateTenantSessionFreshMock = vi.fn(); +const verifyAuthJwtMock = vi.fn(); +vi.mock('../../api/utils/authHelpers.js', () => ({ + verifyAuthJwt: (...args: unknown[]) => verifyAuthJwtMock(...args), +})); vi.mock('../../api/utils/sessionAuth.js', () => ({ - validateSessionToken: (...args: unknown[]) => validateSessionTokenMock(...args), + validateTenantSessionFresh: (...args: unknown[]) => validateTenantSessionFreshMock(...args), })); import { @@ -36,10 +40,13 @@ import type { RoomOptions } from '../WorldRoom.js'; type WorldJoinPrisma = Parameters[2]; -/** Default resolver: no tenant row, so no authoritative slug is attached. */ +/** Default resolver: the verified tenant has a slug, so it is attached. */ const prisma = { - tenant: { findUnique: vi.fn(() => Promise.resolve(null)) }, + tenant: { findUnique: vi.fn(() => Promise.resolve({ id: 'tenant-1', slug: 'acme' })) }, session: { findUnique: vi.fn(), update: vi.fn() }, + // Joins in these tests come from members; the membership gate has its own tests. + membership: { findUnique: vi.fn(() => Promise.resolve({ expiresAt: null })) }, + npc: { findUnique: vi.fn(() => Promise.resolve({ id: 'npc-id', identity: 'bob' })) }, } as unknown as WorldJoinPrisma; function makeContext(opts: { token?: string; cookie?: string } = {}): AuthContext { @@ -56,12 +63,11 @@ function makeContext(opts: { token?: string; cookie?: string } = {}): AuthContex const ORIGINAL_ENV = { ...process.env }; beforeEach(() => { - validateSessionTokenMock.mockReset(); + validateTenantSessionFreshMock.mockReset(); + verifyAuthJwtMock.mockReset(); + verifyAuthJwtMock.mockReturnValue({ userId: 'user-real', tenantId: 'tenant-1' }); process.env = { ...ORIGINAL_ENV }; process.env.NODE_ENV = 'test'; - // Default the suite to the fully-enforced gate; the staged-rollout describe - // block below turns it off explicitly to exercise the transitional path. - process.env.ZONE_PRIVACY_AUTH_ENFORCE = 'true'; }); afterEach(() => { @@ -70,7 +76,13 @@ afterEach(() => { describe('authenticateWorldJoin: user identity binding', () => { it('binds identity to the JWT subject, ignoring a client-supplied options.identity', async () => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-real', tenantId: 'tenant-1' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-real', + tenantId: 'tenant-1', + }); const options: RoomOptions = { identity: 'user-victim', zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const context = makeContext({ cookie: 'auth_token=jwt-abc' }); @@ -79,20 +91,29 @@ describe('authenticateWorldJoin: user identity binding', () => { expect(auth).toEqual({ identity: 'user-real', tenantId: 'tenant-1', + tenantSlug: 'acme', + sessionId: 'db-session-1', + authSessionId: 'db-session-1', isNpc: false, zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION, }); - expect(validateSessionTokenMock).toHaveBeenCalledWith(prisma, 'jwt-abc'); + expect(validateTenantSessionFreshMock).toHaveBeenCalledWith(prisma, 'jwt-abc', 'tenant-1'); }); it('prefers context.token (Bearer/native) over the auth_token cookie when both are present', async () => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-native' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-native', + tenantId: 'tenant-1', + }); const options: RoomOptions = { zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const context = makeContext({ token: 'bearer-jwt', cookie: 'auth_token=cookie-jwt' }); await authenticateWorldJoin(options, context, prisma); - expect(validateSessionTokenMock).toHaveBeenCalledWith(prisma, 'bearer-jwt'); + expect(validateTenantSessionFreshMock).toHaveBeenCalledWith(prisma, 'bearer-jwt', 'tenant-1'); }); it('rejects a join with no cookie and no bearer token (fail-closed)', async () => { @@ -102,40 +123,52 @@ describe('authenticateWorldJoin: user identity binding', () => { await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE, }); - expect(validateSessionTokenMock).not.toHaveBeenCalled(); + expect(validateTenantSessionFreshMock).not.toHaveBeenCalled(); }); it('rejects a join whose token fails JWT verification', async () => { - validateSessionTokenMock.mockResolvedValue(null); + verifyAuthJwtMock.mockReturnValue(null); const options: RoomOptions = { zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const context = makeContext({ cookie: 'auth_token=expired-or-tampered' }); await expect(authenticateWorldJoin(options, context, prisma)).rejects.toBeInstanceOf(ServerError); - await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE }); + await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'unauthorized', + }); + expect(validateTenantSessionFreshMock).not.toHaveBeenCalled(); }); it('rejects a REVOKED session even though the JWT signature is still valid', async () => { + verifyAuthJwtMock.mockReturnValue({ userId: 'user-revoked', tenantId: 'tenant-1' }); // The regression this gate exists for: logout / session revocation / // password reset delete the Session row but cannot un-sign the JWT, which // stays cryptographically valid for its full 30-day lifetime. Resolving the - // token through validateSessionToken (null = no live row) is what closes the + // token through validateTenantSessionFresh (unauthenticated = no live row) is what closes the // world door at the same moment REST closes; verifyAuthJwt would still say // "signed by us" and admit the join. - validateSessionTokenMock.mockResolvedValue(null); + validateTenantSessionFreshMock.mockResolvedValue({ status: 'unauthenticated' }); const options: RoomOptions = { identity: 'user-revoked', zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const context = makeContext({ cookie: 'auth_token=validly-signed-but-revoked' }); await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE, }); - expect(validateSessionTokenMock).toHaveBeenCalledWith(prisma, 'validly-signed-but-revoked'); + expect(validateTenantSessionFreshMock).toHaveBeenCalledWith(prisma, 'validly-signed-but-revoked', 'tenant-1'); }); it('accepts a guest JWT identically to a regular user JWT (same {sub,tid} shape)', async () => { // Guest logins sign the exact same JWT payload shape as regular users // (see apps/server/src/api/routes/guests.ts handleGuestLogin) - the // gate must not special-case them. - validateSessionTokenMock.mockResolvedValue({ userId: 'guest-42', tenantId: 'tenant-acme' }); + verifyAuthJwtMock.mockReturnValue({ userId: 'guest-42', tenantId: 'tenant-acme' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'guest-42', + tenantId: 'tenant-acme', + }); const options: RoomOptions = { zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const context = makeContext({ cookie: 'auth_token=guest-jwt' }); @@ -144,36 +177,50 @@ describe('authenticateWorldJoin: user identity binding', () => { expect(auth).toEqual({ identity: 'guest-42', tenantId: 'tenant-acme', + tenantSlug: 'acme', + sessionId: 'db-session-1', + authSessionId: 'db-session-1', isNpc: false, zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION, }); }); }); -describe('authenticateWorldJoin: staged rollout (ZONE_PRIVACY_AUTH_ENFORCE off)', () => { +describe('authenticateWorldJoin: legacy clients without the current protocol', () => { beforeEach(() => { delete process.env.ZONE_PRIVACY_AUTH_ENFORCE; + verifyAuthJwtMock.mockReturnValue({ userId: 'user-real', tenantId: 'tenant-1' }); }); - it('admits a token-less legacy join with the client-supplied identity instead of rejecting', async () => { + it('rejects a token-less join when the legacy switch is unset', async () => { const options: RoomOptions = { identity: 'legacy-user', zonePrivacyVersion: 0 }; const context = makeContext({}); - const auth = await authenticateWorldJoin(options, context, prisma); - - expect(auth).toEqual({ identity: 'legacy-user', isNpc: false, zonePrivacyVersion: 0 }); - expect(validateSessionTokenMock).not.toHaveBeenCalled(); + await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'unauthorized', + }); + expect(validateTenantSessionFreshMock).not.toHaveBeenCalled(); }); - it('still rejects a token-less join that has no fallback identity at all', async () => { + it('rejects a token-less join that has no identity at all', async () => { const options: RoomOptions = { zonePrivacyVersion: 0 }; const context = makeContext({}); - await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE }); + await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'unauthorized', + }); }); - it('binds identity to the verified JWT even in staged mode when a token is present', async () => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-real', tenantId: 'tenant-1' }); + it('binds identity to the verified JWT when the legacy switch is unset', async () => { + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-real', + tenantId: 'tenant-1', + }); const options: RoomOptions = { identity: 'user-victim', zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const context = makeContext({ cookie: 'auth_token=jwt-abc' }); @@ -182,21 +229,49 @@ describe('authenticateWorldJoin: staged rollout (ZONE_PRIVACY_AUTH_ENFORCE off)' expect(auth.identity).toBe('user-real'); }); - it('admits an old-version but authenticated client instead of rejecting', async () => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-old-client' }); + it('rejects an old-version authenticated client', async () => { + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-old-client', + tenantId: 'tenant-1', + }); const options: RoomOptions = { zonePrivacyVersion: 0 }; const context = makeContext({ cookie: 'auth_token=jwt-old' }); + await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ code: CLIENT_TOO_OLD_CODE }); + expect(validateTenantSessionFreshMock).toHaveBeenCalledTimes(1); + expect(validateTenantSessionFreshMock).toHaveBeenCalledWith(prisma, 'jwt-old', 'tenant-1'); + }); + + it('allows the current protocol when the legacy enforcement switch is set', async () => { + process.env.ZONE_PRIVACY_AUTH_ENFORCE = 'true'; + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-real', + tenantId: 'tenant-1', + }); + const options: RoomOptions = { zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; + const context = makeContext({ cookie: 'auth_token=jwt-current' }); + const auth = await authenticateWorldJoin(options, context, prisma); - expect(auth.identity).toBe('user-old-client'); - expect(auth.isNpc).toBe(false); + expect(auth.identity).toBe('user-real'); }); }); describe('authenticateWorldJoin: client zone-privacy version gate', () => { beforeEach(() => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-real' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-real', + tenantId: 'tenant-1', + }); }); it('rejects a join with a version below the minimum', async () => { @@ -232,18 +307,19 @@ describe('authenticateWorldJoin: client zone-privacy version gate', () => { describe('authenticateWorldJoin: NPC identities', () => { beforeEach(() => { - process.env.NPC_SERVICE_SECRET = 'test-npc-secret'; + process.env.NPC_SERVICE_SECRET = 'n'.repeat(40); }); - it('accepts an npc-* join with the correct service token, exempt from the version gate', async () => { - const options: RoomOptions = { identity: 'npc-bob', serviceToken: 'test-npc-secret' }; + it('accepts a registered NPC with a secure service token', async () => { + const options: RoomOptions = { identity: 'npc-bob', serviceToken: 'n'.repeat(40) }; const context = makeContext({}); const auth = await authenticateWorldJoin(options, context, prisma); expect(auth.identity).toBe('npc-bob'); expect(auth.isNpc).toBe(true); - expect(validateSessionTokenMock).not.toHaveBeenCalled(); + expect(auth.sessionId).toBeNull(); + expect(validateTenantSessionFreshMock).not.toHaveBeenCalled(); }); it('rejects an npc-* join with a wrong service token', async () => { @@ -269,8 +345,7 @@ describe('authenticateWorldJoin: NPC identities', () => { await expect(authenticateWorldJoin(options, context, prisma)).rejects.toMatchObject({ code: AUTH_REJECTED_CODE }); }); - it('rejects an npc-* join in production when NPC_SERVICE_SECRET is left at the insecure default', async () => { - process.env.NODE_ENV = 'production'; + it('rejects an NPC when the service secret is the insecure default', async () => { process.env.NPC_SERVICE_SECRET = 'dev-npc-secret'; const options: RoomOptions = { identity: 'npc-bob', serviceToken: 'dev-npc-secret' }; const context = makeContext({}); @@ -283,14 +358,21 @@ describe('authenticateWorldJoin: room-tenant enforcement decoupled from H4 flag // Passing a prisma resolver lets onAuth resolve the tenant slug from the // verified tenantId (id -> slug); 'auth-a' is the authenticated tenant. const fakePrisma = { - tenant: { findUnique: vi.fn(() => Promise.resolve({ slug: 'auth-a' })) }, + tenant: { findUnique: vi.fn(() => Promise.resolve({ id: 'tenant-a-id', slug: 'auth-a' })) }, + membership: { findUnique: vi.fn(() => Promise.resolve({ expiresAt: null })) }, + npc: { findUnique: vi.fn(() => Promise.resolve({ id: 'npc-id', identity: 'bob' })) }, } as unknown as Parameters[2]; beforeEach(() => { - validateSessionTokenMock.mockResolvedValue({ userId: 'user-1', tenantId: 'tenant-a-id' }); - // The suite default leaves ZONE_PRIVACY_AUTH_ENFORCE=true (the H4 identity - // gate, already ON in prod). The tenant-room match must ride on its OWN - // flag, so clear that one by default here. + verifyAuthJwtMock.mockReturnValue({ userId: 'user-1', tenantId: 'tenant-a-id' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-1', + tenantId: 'tenant-a-id', + }); + // Tenant-room matching remains controlled by its dedicated setting. delete process.env.ZONE_PRIVACY_TENANT_ENFORCE; }); @@ -302,12 +384,7 @@ describe('authenticateWorldJoin: room-tenant enforcement decoupled from H4 flag }); it('DEPLOY-LOCKOUT GUARD (Finding 3): admits a tenant mismatch when only the H4 flag is ON', async () => { - // Reproduces the production state: ZONE_PRIVACY_AUTH_ENFORCE=true (suite - // default) but ZONE_PRIVACY_TENANT_ENFORCE unset. Old apex clients post - // options.tenant='default' for every tenant; if the tenant match rode on the - // already-on H4 flag they would be mass-rejected on the next deploy. The - // decoupling MUST admit them (identity bound, authoritative slug attached). - expect(process.env.ZONE_PRIVACY_AUTH_ENFORCE).toBe('true'); + // The dedicated tenant setting is unset, so the authenticated tenant remains authoritative. const options: RoomOptions = { tenant: 'spoof-b', zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; const auth = await authenticateWorldJoin(options, makeContext({ cookie: 'auth_token=x' }), fakePrisma); expect(auth.identity).toBe('user-1'); // admitted, not rejected @@ -336,9 +413,50 @@ describe('authenticateWorldJoin: room-tenant enforcement decoupled from H4 flag }); }); +describe('authenticateWorldJoin: unresolvable tenant slug fails closed', () => { + beforeEach(() => { + verifyAuthJwtMock.mockReturnValue({ userId: 'user-real', tenantId: 'tenant-1' }); + validateTenantSessionFreshMock.mockResolvedValue({ + status: 'allowed', + sessionId: 'db-session-1', + access: 'member', + userId: 'user-real', + tenantId: 'tenant-1', + }); + }); + + it('rejects with tenant_unresolved when the tenant row is gone', async () => { + const noTenant = { + ...prisma, + tenant: { findUnique: vi.fn(() => Promise.resolve({ id: 'tenant-1', slug: 'tenant-1' })) }, + } as unknown as WorldJoinPrisma; + const options: RoomOptions = { zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; + const context = makeContext({ cookie: 'auth_token=jwt-abc' }); + + await expect(authenticateWorldJoin(options, context, noTenant)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'tenant_unresolved', + }); + }); + + it('rejects with tenant_unresolved when the slug lookup fails', async () => { + const failingTenant = { + ...prisma, + tenant: { findUnique: vi.fn(() => Promise.reject(new Error('db down'))) }, + } as unknown as WorldJoinPrisma; + const options: RoomOptions = { zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION }; + const context = makeContext({ cookie: 'auth_token=jwt-abc' }); + + await expect(authenticateWorldJoin(options, context, failingTenant)).rejects.toMatchObject({ + code: AUTH_REJECTED_CODE, + message: 'tenant_unresolved', + }); + }); +}); + describe('isWorldAuth / requireWorldAuth', () => { it('accepts a well-formed WorldAuth value', () => { - expect(isWorldAuth({ identity: 'a', isNpc: false, zonePrivacyVersion: 1 })).toBe(true); + expect(isWorldAuth({ identity: 'a', isNpc: false, zonePrivacyVersion: 1, sessionId: 'session-1' })).toBe(true); }); it('rejects malformed or missing values', () => { @@ -349,7 +467,7 @@ describe('isWorldAuth / requireWorldAuth', () => { }); it('requireWorldAuth returns the auth payload when present and valid', () => { - const client = { auth: { identity: 'user-1', isNpc: false, zonePrivacyVersion: 1 } }; + const client = { auth: { identity: 'user-1', isNpc: false, zonePrivacyVersion: 1, sessionId: 'session-1' } }; expect(requireWorldAuth(client)).toEqual(client.auth); }); diff --git a/apps/server/src/rooms/lifecycle/onAuth.ts b/apps/server/src/rooms/lifecycle/onAuth.ts index c1435ebd..8ed90c49 100644 --- a/apps/server/src/rooms/lifecycle/onAuth.ts +++ b/apps/server/src/rooms/lifecycle/onAuth.ts @@ -1,80 +1,60 @@ /** - * H4 hardening (identity binding + client-version gate) for the `world` - * Colyseus room. + * Identity binding and client-version gate for the `world` room. * - * `WorldRoom.onAuth` (instance-level, see WorldRoom.ts) delegates here. - * Colyseus calls this during the room join handshake, before `onJoin` - * runs, and attaches the resolved `WorldAuth` to `client.auth` (see - * node_modules/@colyseus/core/build/Room.mjs `_onJoin`). Every downstream - * consumer of "who is this client" (onJoin.ts, sessionHandlers.ts) must - * read `client.auth`, never `options.identity` — the latter is - * client-supplied and was the actual privacy hole this module closes: the - * H4 zone-privacy allow-lists are keyed on identity, so an unverified - * identity would let a client claim someone else's zone membership. + * Matchmaking calls `authenticateWorldMatchmake`, which resolves the raw + * token and delegates to `authenticateWorldJoin`. Colyseus stores the + * returned value as seat auth data and copies it onto `client.auth` when + * the seat is consumed. Registration runs at the start of `onJoin`. + * Reconnect does not enter `onJoin`. * - * Fail-closed when enforcement is on (`ZONE_PRIVACY_AUTH_ENFORCE=true`): every - * rejection path throws `ServerError`, which Colyseus turns into a - * `client.error(code, message)` + clean disconnect (see Room.mjs `_onJoin`'s - * catch block). During staged rollout (enforcement off, the default) a - * token-less or old-version join is admitted with a warning so a server deploy - * does not lock out desktop clients that predate the join-token change — see - * `isAuthEnforced()` below. Even in staged mode a resolvable token always binds - * the identity to the verified JWT subject; the client-supplied identity is - * only ever used as the transitional fallback for a token-less join. + * Consumers read `client.auth`, never `options.identity`. Every rejection + * throws `ServerError`. Humans need a fresh allowed session and the current + * zone-privacy version. NPC joins are a service principal and do not use + * that version check. */ -import crypto from 'crypto'; import { ServerError, type AuthContext } from 'colyseus'; import { logger } from '../../logger.js'; -import { validateSessionToken } from '../../api/utils/sessionAuth.js'; +import { verifyAuthJwt } from '../../api/utils/authHelpers.js'; +import { validateTenantSessionFresh } from '../../api/utils/sessionAuth.js'; import { MIN_ZONE_PRIVACY_CLIENT_VERSION, ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; import type { RoomOptions } from '../WorldRoom.js'; import type { PrismaClient } from '../../generated/prisma/index.js'; import { clientNumberForLog, clientStringForLog } from './logSafe.js'; -import { MAX_JOIN_IDENTITY_LENGTH } from './joinFields.js'; +import { resolveNpcPrincipal, verifyNpcServiceToken } from './npcServiceAuth.js'; -/** - * Prisma surface onAuth needs: `session` to resolve the presented token against - * its live session row, `tenant` to resolve a tenant's slug from its verified id. - * - * Required, not optional: session validation cannot happen without it, and an - * "authenticate anyway" fallback for a caller that forgot to pass it is exactly - * the signature-only trust this gate exists to remove. - */ -type WorldJoinPrisma = Pick; - -/** Dedicated close/error codes for this gate, distinct from the existing - * 4001-4008 range used by onJoin.limiter.ts / onJoin.completion.ts / guest - * expiry / the transcription gate, so the client can branch on "must re-login" - * vs "must update". */ +/** Dedicated close codes so the client can tell re-login from update. */ export const AUTH_REJECTED_CODE = 4401; export const CLIENT_TOO_OLD_CODE = 4426; export interface WorldAuth { identity: string; tenantId?: string; - // The AUTHENTICATED tenant slug, resolved from the JWT-verified tenantId. - // Join-path consumers (presence seeding, guest expiry, map/bounds) must scope - // by this, never by the client-supplied options.tenant, to avoid leaking - // another tenant's members/presence. Absent for NPC and token-less joins. + // Authenticated tenant slug. Join consumers must scope by this, never by + // the client-supplied options.tenant. tenantSlug?: string; + // Database session id for a human. Null for an NPC. Safe to serialize; + // never a raw token or a token hash. + sessionId: string | null; + // Same session id, read by the access registry until it uses `sessionId`. + // Absent for an NPC, which is not registered. + authSessionId?: string; isNpc: boolean; zonePrivacyVersion: number; } -/** Runtime shape check for `client.auth`. Colyseus types `Client.auth` as - * `any` (arbitrary user data); this narrows it with a property check - * instead of an unchecked cast, per LIBRARY_BOUNDARIES.md pattern 3. */ +/** Runtime shape check for `client.auth` (Colyseus types it as arbitrary data). */ export function isWorldAuth(value: unknown): value is WorldAuth { if (typeof value !== 'object' || value === null) return false; - const v = value as Record; - return typeof v.identity === 'string' && typeof v.isNpc === 'boolean' && typeof v.zonePrivacyVersion === 'number'; + const record = value as Record; + return ( + typeof record.identity === 'string' && + typeof record.isNpc === 'boolean' && + typeof record.zonePrivacyVersion === 'number' + ); } -/** Minimal manual cookie parser: `context.headers` is a Fetch `Headers` - * instance (WebSocketTransport wraps the WS-upgrade request headers), not - * an Express `Request` — cookie-parser does not apply here. Mirrors - * cookie-parser's basic decode-per-pair behavior for the one cookie we need. */ -function parseCookieValue(cookieHeader: string, name: string): string | null { +/** Decode one cookie pair. `context.headers` is a Fetch `Headers` object. */ +export function parseCookieValue(cookieHeader: string, name: string): string | null { for (const part of cookieHeader.split(';')) { const eqIdx = part.indexOf('='); if (eqIdx === -1) continue; @@ -90,110 +70,31 @@ function parseCookieValue(cookieHeader: string, name: string): string | null { return null; } -/** Order: Bearer/query token (Native/Tauri, via `client.auth.token` on the - * SDK -> `_authToken` query param on the WS handshake) before the - * `auth_token` cookie (Browser, sent automatically on the WS handshake for - * same-site requests). Deterministic precedence when both are present. */ -function resolveRawAuthToken(context: AuthContext): string | null { +/** + * Bearer or query token first, then the `auth_token` cookie. `presentedToken` + * is the argument Colyseus passes to static `onAuth` and wins when set. + */ +export function resolveRawAuthToken(context: AuthContext, presentedToken?: string): string | null { + if (typeof presentedToken === 'string' && presentedToken.length > 0) return presentedToken; if (context.token) return context.token; const cookieHeader = context.headers.get('cookie'); if (!cookieHeader) return null; return parseCookieValue(cookieHeader, 'auth_token'); } -function timingSafeEqualStrings(a: string, b: string): boolean { - const aBuf = Buffer.from(a); - const bBuf = Buffer.from(b); - return aBuf.length === bBuf.length && crypto.timingSafeEqual(aBuf, bBuf); -} - -/** Analogous to getJwtSecret() in authHelpers.ts: refuses the known - * insecure default once NODE_ENV=production, instead of only checking - * "is it set at all" (a deployer could set NPC_SERVICE_SECRET=dev-npc-secret - * verbatim and still pass an "is it set" check). */ -function getNpcServiceSecret(): string { - const fromEnv = process.env.NPC_SERVICE_SECRET; - const isProduction = process.env.NODE_ENV === 'production'; - if (fromEnv && fromEnv.length > 0) { - if (isProduction && fromEnv === 'dev-npc-secret') { - throw new ServerError(AUTH_REJECTED_CODE, 'npc_service_secret_insecure'); - } - return fromEnv; - } - if (isProduction) { - throw new ServerError(AUTH_REJECTED_CODE, 'npc_service_secret_missing'); - } - return 'dev-npc-secret'; -} - -function authenticateNpc(options: RoomOptions): WorldAuth { - const identity = options.identity; - if (!identity) { - throw new ServerError(AUTH_REJECTED_CODE, 'npc_identity_missing'); - } - const expected = getNpcServiceSecret(); - const provided = options.serviceToken; - if (!provided || !timingSafeEqualStrings(provided, expected)) { - logger.warn('[WorldRoom] Rejected NPC join: invalid service token', { identity: clientStringForLog(identity) }); - throw new ServerError(AUTH_REJECTED_CODE, 'npc_service_token_invalid'); - } - // NPCs are server-controlled (npc-service authenticates via - // NPC_SERVICE_SECRET, not a per-user JWT) and are exempt from the - // client zone-privacy version gate: they never publish LiveKit tracks. - return { identity, isNpc: true, zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION }; -} - /** - * Staged rollout switch. When unset/false the gate BINDS the identity whenever - * a token resolves (browsers via cookie, updated native clients via token) but - * ADMITS a token-less or old-version join with a warning instead of rejecting - * it. This lets the server ship before every independently-updating client - * (the bundled desktop app) sends the join token / version, so a deploy does - * not lock those users out of the world. Flip `ZONE_PRIVACY_AUTH_ENFORCE=true` - * once client adoption is confirmed (watch the admit warnings) to make the - * identity binding and version gate fully fail-closed. Browsers and the - * npc-service update atomically with the server deploy and are unaffected by - * the toggle. - */ -function isAuthEnforced(): boolean { - return process.env.ZONE_PRIVACY_AUTH_ENFORCE === 'true'; -} - -/** - * Independent staged-rollout switch for the TENANT-ROOM match check - * (enforceTenantMatch), deliberately DECOUPLED from ZONE_PRIVACY_AUTH_ENFORCE. - * - * ZONE_PRIVACY_AUTH_ENFORCE (the H4 identity + client-version gate) is already - * =true in production (set 2026-07-08). The tenant-room match must NOT ride on - * that same flag: old clients (the bundled desktop app ships the auth-slug send - * only in a later release) post `options.tenant='default'` for every tenant on - * an apex domain, so enforcing the match under the already-on H4 flag would - * mass-reject / lock those users out. Keep this DEFAULT-OFF (warn+log only) and - * flip ZONE_PRIVACY_TENANT_ENFORCE=true once client adoption is confirmed — - * before public launch. The fail-closed presence/map scoping (onJoin.completion) - * and the per-client StateView room-state filter (WorldRoom players @view()) - * already isolate all DATA regardless of this flag; this only closes the - * residual Colyseus room-partition sharing. + * Staged switch for the tenant-room match. Default off: a slug mismatch is + * logged and admitted. On, it is rejected. Presence, maps and the per-client + * state view already isolate data either way. */ export function isTenantEnforced(): boolean { return process.env.ZONE_PRIVACY_TENANT_ENFORCE === 'true'; } /** - * Enforce that the room the client asked to join (`options.tenant`, the - * Colyseus `filterBy(['tenant'])` partition key) matches the JWT-verified - * tenant. Otherwise the player shares one WorldRoom with another tenant. - * - * Note: on an apex/root domain the web client derives no subdomain and, until - * it ships the auth-slug send, posts `options.tenant='default'` for EVERY - * tenant, collapsing all tenants into the 'default' room. This check is gated by - * its OWN flag ZONE_PRIVACY_TENANT_ENFORCE (NOT the already-on - * ZONE_PRIVACY_AUTH_ENFORCE — see isTenantEnforced): default-off warns+logs (so - * those pre-update clients are not locked out right after a deploy), on rejects - * the mismatch. The fail-closed presence/map scoping and the per-client - * StateView room-state filter already isolate all DATA regardless; this only - * closes the residual room-partition sharing. Flip enforce=on once clients send - * the auth slug (see lib/colyseus.ts) — before public launch. + * `options.tenant` is the room partition key and must match the authenticated + * slug. A missing slug skips this check. A mismatch is rejected only while + * the tenant switch is on. */ function enforceTenantMatch(options: RoomOptions | undefined, authSlug: string | undefined, identity: string): void { const requested = options?.tenant; @@ -213,139 +114,198 @@ function enforceTenantMatch(options: RoomOptions | undefined, authSlug: string | }); } -/** Resolve a tenant's slug from its (JWT-verified) id. Best-effort: returns - * undefined on a missing id, missing resolver or a DB error, so a lookup - * failure never blocks the join — the caller then falls back to the - * client-supplied slug for non-security-critical uses only. */ -async function resolveTenantSlug( - prisma: Pick, - tenantId: string | undefined, -): Promise { +/** Slug the room would file this join under when the client omits one. */ +function joinTenantSlug(options: RoomOptions | undefined): string { + const requested = options?.tenant; + if (typeof requested === 'string' && requested.length > 0) return requested; + return process.env.DEFAULT_TENANT_SLUG || 'default'; +} + +/** Tenant row for the join slug. Undefined when the row is missing or the read fails. */ +async function resolveJoinTenant( + prisma: PrismaClient, + options: RoomOptions | undefined, +): Promise<{ id: string; slug: string } | undefined> { + try { + const row = await prisma.tenant.findUnique({ + where: { slug: joinTenantSlug(options) }, + select: { id: true, slug: true }, + }); + if (!row?.id || !row.slug) return undefined; + return { id: row.id, slug: row.slug }; + } catch (error) { + logger.debug('[WorldRoom] Failed to resolve tenant from join options', error); + return undefined; + } +} + +async function requireJoinTenant( + prisma: PrismaClient, + options: RoomOptions | undefined, +): Promise<{ id: string; slug: string }> { + const tenant = await resolveJoinTenant(prisma, options); + if (!tenant) { + logger.warn('[WorldRoom] Rejected join: verified tenant has no resolvable slug'); + throw new ServerError(AUTH_REJECTED_CODE, 'tenant_unresolved'); + } + return tenant; +} + +/** Slug for a proven tenant id. Undefined on a missing row or a read error. */ +async function resolveTenantSlug(prisma: PrismaClient, tenantId: string | undefined): Promise { if (!tenantId) return undefined; try { - const t = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); - return t?.slug ?? undefined; - } catch (e) { - logger.debug('[WorldRoom] Failed to resolve authenticated tenant slug', e); + const row = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); + return row?.slug ?? undefined; + } catch (error) { + logger.debug('[WorldRoom] Failed to resolve authenticated tenant slug', error); return undefined; } } +function refuseFreshSession( + result: + | { status: 'unauthenticated' } + | { status: 'forbidden'; reason: 'membership_unavailable' | 'verification_required' | 'tenant_unavailable' }, +): never { + if (result.status === 'unauthenticated') { + logger.warn('[WorldRoom] Rejected world join without a valid session'); + throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); + } + if (result.reason === 'tenant_unavailable') { + logger.warn('[WorldRoom] Rejected join: verified tenant has no resolvable slug'); + throw new ServerError(AUTH_REJECTED_CODE, 'tenant_unresolved'); + } + logger.warn('[WorldRoom] Rejected join: no access to the session tenant'); + const message = result.reason === 'verification_required' ? 'verification_required' : 'not_member_of_tenant'; + throw new ServerError(AUTH_REJECTED_CODE, message); +} + +/** Humans must send the current zone-privacy version. NPC joins do not. */ +function requireZonePrivacyVersion(options: RoomOptions | undefined, identity: string): number { + const zonePrivacyVersion = options?.zonePrivacyVersion; + if (typeof zonePrivacyVersion === 'number' && zonePrivacyVersion >= MIN_ZONE_PRIVACY_CLIENT_VERSION) { + return zonePrivacyVersion; + } + logger.warn('[WorldRoom] Rejected join: client zone-privacy protocol version too old', { + identity, + zonePrivacyVersion: clientNumberForLog(zonePrivacyVersion), + minRequired: MIN_ZONE_PRIVACY_CLIENT_VERSION, + }); + throw new ServerError(CLIENT_TOO_OLD_CODE, 'client_too_old'); +} + +/** + * Join-lifecycle callback. Fires once the session is allowed, before the + * remaining slug and version checks. The room registers the seat later, + * when `onJoin` has a session id. + */ +export interface WorldJoinHooks { + onSessionVerified?: (userId: string, tenantId: string | undefined) => void; +} + async function authenticateUser( options: RoomOptions | undefined, context: AuthContext, - prisma: WorldJoinPrisma, + prisma: PrismaClient, + hooks: WorldJoinHooks | undefined, ): Promise { const raw = resolveRawAuthToken(context); - // The SESSION ROW is the authority, not the JWT signature. Verifying the - // signature alone (the previous behaviour) meant logout, session revocation - // and password reset closed the REST door while leaving the world — presence, - // camera, microphone — open for the token's remaining 30 days. The world is - // the product, so it must apply the same authority REST does. - const verified = raw ? await validateSessionToken(prisma, raw) : null; - - if (!verified) { - if (isAuthEnforced()) { - throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); - } - // Staged rollout: a legacy client (old bundled desktop build) that predates - // sending the join token. Fall back to the client-supplied identity — the - // pre-H4 behavior — so it is not locked out. Zone privacy for this client - // rests on an unverified identity until it updates; acceptable transitional - // state, made observable via this warning. - const fallbackId = options?.identity; - if (!fallbackId) { - throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); - } - // The identity goes into the room state and every peer is sent it. No - // identity the server knows is long, so a long one is refused outright. - if (fallbackId.length > MAX_JOIN_IDENTITY_LENGTH) { - logger.warn('[WorldRoom] Rejected token-less join: client identity is too long', { - identity: clientStringForLog(fallbackId), - }); - throw new ServerError(AUTH_REJECTED_CODE, 'identity_invalid'); - } - logger.warn('[WorldRoom] Admitted world join with UNVERIFIED identity (enforcement off)', { - identity: clientStringForLog(fallbackId), - }); - return { identity: fallbackId, isNpc: false, zonePrivacyVersion: options?.zonePrivacyVersion ?? 0 }; + if (!raw) { + logger.warn('[WorldRoom] Rejected world join without a valid session'); + throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); } - - // Resolve the authoritative tenant slug once, then enforce that the room the - // client asked for (options.tenant) matches it (flag-gated; warn-only during - // rollout). + // The proven tenant is the JWT `tid` claim, never the client-supplied + // `options.tenant` (which `enforceTenantMatch` only checks flag-gated below). + const claims = verifyAuthJwt(raw); + if (!claims) { + logger.warn('[WorldRoom] Rejected world join without a valid session'); + throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); + } + const tid = claims.tenantId; + if (!tid) { + logger.warn('[WorldRoom] Rejected join: verified tenant has no resolvable slug'); + throw new ServerError(AUTH_REJECTED_CODE, 'tenant_unresolved'); + } + const verified = await validateTenantSessionFresh(prisma, raw, tid); + if (verified.status !== 'allowed') refuseFreshSession(verified); + if (verified.access !== 'member' && verified.access !== 'platform_operator') { + throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); + } + hooks?.onSessionVerified?.(verified.userId, verified.tenantId); const tenantSlug = await resolveTenantSlug(prisma, verified.tenantId); - enforceTenantMatch(options, tenantSlug, verified.userId); - - const zonePrivacyVersion = options?.zonePrivacyVersion; - if (typeof zonePrivacyVersion !== 'number' || zonePrivacyVersion < MIN_ZONE_PRIVACY_CLIENT_VERSION) { - if (isAuthEnforced()) { - logger.warn('[WorldRoom] Rejected join: client zone-privacy protocol version too old', { - identity: verified.userId, - zonePrivacyVersion: clientNumberForLog(zonePrivacyVersion), - minRequired: MIN_ZONE_PRIVACY_CLIENT_VERSION, - }); - throw new ServerError(CLIENT_TOO_OLD_CODE, 'client_too_old'); - } - logger.warn('[WorldRoom] Admitted join from old zone-privacy client (enforcement off)', { + if (!verified.tenantId || !tenantSlug) { + logger.warn('[WorldRoom] Rejected join: verified tenant has no resolvable slug', { identity: verified.userId, - zonePrivacyVersion: clientNumberForLog(zonePrivacyVersion), - minRequired: MIN_ZONE_PRIVACY_CLIENT_VERSION, }); - const legacy: WorldAuth = { - identity: verified.userId, - isNpc: false, - zonePrivacyVersion: typeof zonePrivacyVersion === 'number' ? zonePrivacyVersion : 0, - }; - if (verified.tenantId) legacy.tenantId = verified.tenantId; - if (tenantSlug) legacy.tenantSlug = tenantSlug; - return legacy; + throw new ServerError(AUTH_REJECTED_CODE, 'tenant_unresolved'); } + enforceTenantMatch(options, tenantSlug, verified.userId); + const zonePrivacyVersion = requireZonePrivacyVersion(options, verified.userId); + return { + identity: verified.userId, + tenantId: verified.tenantId, + tenantSlug, + sessionId: verified.sessionId, + authSessionId: verified.sessionId, + isNpc: false, + zonePrivacyVersion, + }; +} - const auth: WorldAuth = { identity: verified.userId, isNpc: false, zonePrivacyVersion }; - if (verified.tenantId) auth.tenantId = verified.tenantId; - if (tenantSlug) auth.tenantSlug = tenantSlug; - return auth; +/** Service token, then the NPC row for this tenant. No zone-privacy gate. */ +async function authenticateNpc(options: RoomOptions, prisma: PrismaClient): Promise { + const identity = options.identity; + if (typeof identity !== 'string' || identity.length === 0) { + throw new ServerError(AUTH_REJECTED_CODE, 'npc_identity_missing'); + } + if (!verifyNpcServiceToken(options.serviceToken)) { + logger.warn('[WorldRoom] Rejected NPC join: invalid service token', { + identity: clientStringForLog(identity), + }); + throw new ServerError(AUTH_REJECTED_CODE, 'npc_service_token_invalid'); + } + const tenant = await requireJoinTenant(prisma, options); + const principal = await resolveNpcPrincipal(prisma, tenant.id, identity); + const joinIdentity = principal ? `npc-${principal.identity}` : ''; + if (!principal || joinIdentity !== identity) { + logger.warn('[WorldRoom] Rejected NPC join: no matching npc', { + identity: clientStringForLog(identity), + }); + throw new ServerError(AUTH_REJECTED_CODE, 'unauthorized'); + } + return { + identity: joinIdentity, + tenantId: tenant.id, + tenantSlug: tenant.slug, + sessionId: null, + isNpc: true, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; } /** - * Colyseus `onAuth` entry point. Resolves the authoritative identity for a - * `world` join. Never trusts `options.identity` for that purpose — it is - * only accepted (via the NPC branch) as the fixed `npc-*` identity the - * npc-service itself assigns, gated by a separate shared-secret check. - * - * The NPC branch is synchronous (and needs no database); the user branch awaits - * the session lookup plus a tenant-slug lookup. The try/catch guarantees a - * rejected, never a thrown, Promise so callers can rely on `Promise` - * either way. `prisma` is REQUIRED: without it a token cannot be checked against - * its session row, and admitting a join on the signature alone is the hole this - * gate closes. + * Resolves the authoritative world identity. A presented `serviceToken` + * selects the NPC principal and never a user. Otherwise the human path + * ignores `options.identity`. `hooks` is optional; direct callers may omit it. */ -export function authenticateWorldJoin( +export async function authenticateWorldJoin( options: RoomOptions | undefined, context: AuthContext, - prisma: WorldJoinPrisma, + prisma: PrismaClient, + hooks?: WorldJoinHooks, ): Promise { try { - if (options?.identity?.startsWith('npc-')) { - return Promise.resolve(authenticateNpc(options)); + if (typeof options?.serviceToken === 'string') { + return await authenticateNpc(options, prisma); } - return authenticateUser(options, context, prisma); - } catch (e) { - return Promise.reject(e instanceof Error ? e : new Error(String(e))); + return await authenticateUser(options, context, prisma, hooks); + } catch (error) { + throw error instanceof Error ? error : new Error(String(error)); } } -/** - * Reads the `WorldAuth` payload `onAuth()` attached to `client.auth`, for - * call sites inside `onJoin` (see onJoin.ts). Colyseus guarantees `onAuth` - * ran and populated `client.auth` before `onJoin` fires (Room.mjs - * `_onJoin`), so a missing/malformed value here means a room build without - * this gate wired up — fail closed rather than fall back to - * `options.identity`. Safe to throw: `onJoin` errors are caught by - * Colyseus and turned into a clean client disconnect (Room.mjs `_onJoin`'s - * catch block), not an unhandled rejection. - */ +/** `client.auth` after a successful auth. Missing or malformed data is rejected. */ export function requireWorldAuth(client: { auth?: unknown }): WorldAuth { if (!isWorldAuth(client.auth)) { throw new ServerError(AUTH_REJECTED_CODE, 'missing_world_auth'); diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.bounds.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.bounds.test.ts index 0414c103..b685f74d 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.bounds.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.bounds.test.ts @@ -16,12 +16,26 @@ interface MapWhere { } const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { findUnique: vi.fn(() => Promise.resolve({ defaultMapName: 'office' })) }, map: { findFirst: vi.fn((_args: { where: MapWhere }) => Promise.resolve<{ id: string; name: string } | null>(null)), findUnique: vi.fn(() => Promise.resolve(null)), }, - membership: { findMany: vi.fn(() => Promise.resolve([])), findFirst: vi.fn(() => Promise.resolve(null)) }, + membership: { + findMany: vi.fn(() => Promise.resolve([])), + findFirst: vi.fn(() => Promise.resolve(null)), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), + }, presence: { findMany: vi.fn(() => Promise.resolve([])) }, user: { findUnique: vi.fn(() => Promise.resolve(null)) }, avatarPack: { findFirst: vi.fn(() => Promise.resolve({ avatars: [{ key: 'business_man' }] })) }, @@ -43,6 +57,7 @@ vi.mock('../audioZones/runtime.js', () => ({ import { completePendingJoin } from './onJoin.completion.js'; import { MAX_JOIN_TEXT_LENGTH } from './joinFields.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, Player as PlayerCtor, RoomOptions } from '../WorldRoom.js'; type CompletionClient = Parameters[1]; @@ -80,18 +95,29 @@ function makeRoom(): { room: WorldRoom; players: Map } { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); return { room, players }; } -/** A token-less human join (staged mode): no verified tenant on client.auth. */ +/** A human join with a verified session represented by the test double. */ async function join(options: RoomOptions): Promise { const { room, players } = makeRoom(); const client = { sessionId: 'sid-1', send: vi.fn(), view: { add() {}, remove() {}, has: () => false }, - auth: { identity: 'user-1', isNpc: false, zonePrivacyVersion: 1 }, + auth: { identity: 'user-1', sessionId: 'db-session', isNpc: false, zonePrivacyVersion: 1 }, } as unknown as CompletionClient; + // The admit gate needs the onAuth entry for this session; the tenant values + // are the double's own, the membership proof above stays active. + room.worldAccess.register('sid-1', { + identity: 'user-1', + sessionId: 'db-session', + tenantId: 'tenant-1', + tenantSlug: 'tenant-1', + isNpc: false, + zonePrivacyVersion: 1, + }); await completePendingJoin(room, client, options, 'user-1', FakePlayer as unknown as typeof PlayerCtor); const player = players.get('sid-1'); if (!player) throw new Error('the join did not create a player'); @@ -128,13 +154,13 @@ describe('the direction of a joining player', () => { describe('the map name of a joining player', () => { it('is the name of the map row when the lookup by name succeeds', async () => { fakePrisma.map.findFirst.mockImplementation(({ where }) => - Promise.resolve(where.name === 'Büro 2. Etage' ? { id: 'map-9', name: 'Büro 2. Etage' } : null), + Promise.resolve(where.name === 'B\u00fcro 2. Etage' ? { id: 'map-9', name: 'B\u00fcro 2. Etage' } : null), ); - const player = await join({ mapName: 'Büro 2. Etage' }); + const player = await join({ mapName: 'B\u00fcro 2. Etage' }); expect(player.mapId).toBe('map-9'); - expect(player.mapName).toBe('Büro 2. Etage'); + expect(player.mapName).toBe('B\u00fcro 2. Etage'); }); it('still finds a map whose name is longer than the display limit', async () => { @@ -152,7 +178,7 @@ describe('the map name of a joining player', () => { it('is the requested name, unchanged, when the lookup fails and the name is short', async () => { fakePrisma.map.findFirst.mockRejectedValue(new Error('database unavailable')); - expect((await join({ mapName: 'Büro' })).mapName).toBe('Büro'); + expect((await join({ mapName: 'B\u00fcro' })).mapName).toBe('B\u00fcro'); }); it('is cut to the limit when the lookup fails and the client sent 900,000 characters', async () => { diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.dnd.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.dnd.test.ts index c5bb6d8d..fcfc1c23 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.dnd.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.dnd.test.ts @@ -23,6 +23,15 @@ vi.mock('../../metrics.js', () => ({ // resolveInitialMap's tenant-scoped lookups. type FindArgs = { where?: { id?: string; name?: string; slug?: string } }; const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { // checkGuestExpired + seedPresenceRecent look up by slug and short-circuit // on null. resolveInitialMap looks up the tenant's defaultMapName by id. @@ -39,6 +48,12 @@ const fakePrisma = { }), }, user: { findUnique: vi.fn(() => Promise.resolve(null)) }, + membership: { + findMany: vi.fn(() => Promise.resolve([])), + findFirst: vi.fn(() => Promise.resolve(null)), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), + }, avatarPack: { findFirst: vi.fn(() => Promise.resolve({ avatars: [{ key: 'business_man' }] })), }, @@ -69,6 +84,7 @@ vi.mock('../audioZones/runtime.js', () => ({ })); import { completePendingJoin } from './onJoin.completion.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, RoomOptions, Player as PlayerCtor } from '../WorldRoom.js'; import type { Client } from 'colyseus'; @@ -116,9 +132,22 @@ function makeRoom(): { room: WorldRoom; players: Map } { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); return { room, players }; } +/** The onAuth entry the admit gate needs for a human session. */ +function registerJoin(room: WorldRoom, sessionId: string, identity: string): void { + room.worldAccess.register(sessionId, { + identity, + sessionId: 'db-session', + tenantId: 'tenant-1', + tenantSlug: 'tenant-1', + isNpc: false, + zonePrivacyVersion: 1, + }); +} + // Common options that keep every DB-backed resolver on its short-circuit // path (explicit mapId, name and avatarId). function baseOptions(extra: Partial): RoomOptions { @@ -135,6 +164,7 @@ describe('completePendingJoin: dnd resync via join option', () => { it('sets player.dnd = true and broadcasts player_joined with dnd:true when options.dnd === true', async () => { const { room, players } = makeRoom(); const client = { sessionId: 'sid-1', send: vi.fn(), view: fakeView() } as unknown as Client; + registerJoin(room, 'sid-1', 'user-1'); await completePendingJoin(room, client, baseOptions({ dnd: true }), 'user-1', fakePlayerClass); @@ -151,6 +181,7 @@ describe('completePendingJoin: dnd resync via join option', () => { it('defaults player.dnd to false when the dnd option is absent', async () => { const { room, players } = makeRoom(); const client = { sessionId: 'sid-2', send: vi.fn(), view: fakeView() } as unknown as Client; + registerJoin(room, 'sid-2', 'user-2'); await completePendingJoin(room, client, baseOptions({}), 'user-2', fakePlayerClass); @@ -167,6 +198,7 @@ describe('completePendingJoin: dnd resync via join option', () => { it('does not enable DND for a non-boolean truthy value (string "true")', async () => { const { room, players } = makeRoom(); const client = { sessionId: 'sid-3', send: vi.fn(), view: fakeView() } as unknown as Client; + registerJoin(room, 'sid-3', 'user-3'); // A spoofed/legacy client could send a string; only a real boolean true counts. const options = baseOptions({ dnd: 'true' as unknown as boolean }); @@ -200,8 +232,16 @@ describe('completePendingJoin: cross-tenant mapId rejection', () => { send: vi.fn(), view: fakeView(), // WorldAuth attached by onAuth: the JWT-verified tenant is 'tenant-a'. - auth: { identity: 'user-b', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a' }, + auth: { identity: 'user-b', sessionId: 'db-session', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a' }, } as unknown as Client; + room.worldAccess.register('sid-A', { + identity: 'user-b', + sessionId: 'db-session', + tenantId: 'tenant-a', + tenantSlug: 'auth-a', + isNpc: false, + zonePrivacyVersion: 1, + }); // 'map-b' belongs to another tenant (not owned by tenant-a in the mock). const options = baseOptions({ mapId: 'map-b' }); diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.logging.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.logging.test.ts index 34a23601..df6ceeae 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.logging.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.logging.test.ts @@ -12,9 +12,23 @@ vi.mock('../../metrics.js', () => ({ colyseusPlayers: { inc: vi.fn(), dec: vi.fn // The map lookups miss, so the player ends up on the unresolved placeholder map // and the requested map name is what the fallback keeps. const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { findUnique: vi.fn(() => Promise.resolve({ defaultMapName: 'office' })) }, map: { findFirst: vi.fn(() => Promise.resolve(null)), findUnique: vi.fn(() => Promise.resolve(null)) }, - membership: { findMany: vi.fn(() => Promise.resolve([])), findFirst: vi.fn(() => Promise.resolve(null)) }, + membership: { + findMany: vi.fn(() => Promise.resolve([])), + findFirst: vi.fn(() => Promise.resolve(null)), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), + }, presence: { findMany: vi.fn(() => Promise.resolve([])) }, user: { findUnique: vi.fn(() => Promise.resolve(null)) }, avatarPack: { findFirst: vi.fn(() => Promise.resolve({ avatars: [{ key: 'business_man' }] })) }, @@ -36,6 +50,7 @@ vi.mock('../audioZones/runtime.js', () => ({ import { completePendingJoin } from './onJoin.completion.js'; import { MAX_JOIN_TEXT_LENGTH } from './joinFields.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, Player as PlayerCtor } from '../WorldRoom.js'; type CompletionClient = Parameters[1]; @@ -60,7 +75,7 @@ const PLACEHOLDER_PREFIX = '__unresolved__:'; const LOG_BUDGET_CHARS = 1_000; function makeRoom(): WorldRoom { - return { + const room = { prismaForPresence: fakePrisma, state: { players: new Map() }, lastSeen: new Map(), @@ -75,6 +90,20 @@ function makeRoom(): WorldRoom { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); + return room; +} + +/** The onAuth entry the admit gate needs for a human session. */ +function registerJoin(room: WorldRoom, identity: string): void { + room.worldAccess.register('sid-1', { + identity, + sessionId: 'db-session', + tenantId: 'tenant-1', + tenantSlug: 'tenant-1', + isNpc: false, + zonePrivacyVersion: 1, + }); } function makeClient(identity: string): CompletionClient { @@ -82,7 +111,7 @@ function makeClient(identity: string): CompletionClient { sessionId: 'sid-1', send: vi.fn(), view: { add() {}, remove() {}, has: () => false }, - auth: { identity, isNpc: false, zonePrivacyVersion: 1 }, + auth: { identity, sessionId: 'db-session', isNpc: false, zonePrivacyVersion: 1 }, } as unknown as CompletionClient; } @@ -98,8 +127,10 @@ beforeEach(() => { describe('completePendingJoin logs stay bounded', () => { it('for a long identity, name and map name', async () => { const options = { name: HUGE, mapName: HUGE, mapId: HUGE }; + const room = makeRoom(); + registerJoin(room, HUGE); - await completePendingJoin(makeRoom(), makeClient(HUGE), options, HUGE, FakePlayer as unknown as typeof PlayerCtor); + await completePendingJoin(room, makeClient(HUGE), options, HUGE, FakePlayer as unknown as typeof PlayerCtor); expect(log.info).toHaveBeenCalledWith( '[WorldRoom] Player joined:', @@ -120,8 +151,10 @@ describe('completePendingJoin logs stay bounded', () => { }); it('for a long tenant that names the unresolved placeholder map', async () => { + const room = makeRoom(); + registerJoin(room, 'user-1'); await completePendingJoin( - makeRoom(), + room, makeClient('user-1'), { tenant: HUGE }, 'user-1', @@ -147,10 +180,12 @@ describe('completePendingJoin logs stay bounded', () => { }); it('and leave an ordinary name and identity readable', async () => { + const room = makeRoom(); + registerJoin(room, 'user-1'); await completePendingJoin( - makeRoom(), + room, makeClient('user-1'), - { name: 'Jörg Müller' }, + { name: 'J\u00f6rg M\u00fcller' }, 'user-1', FakePlayer as unknown as typeof PlayerCtor, ); diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.mapfallback.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.mapfallback.test.ts index 122647ac..2b673a2f 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.mapfallback.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.mapfallback.test.ts @@ -17,9 +17,23 @@ vi.mock('../../metrics.js', () => ({ // Every map lookup misses → resolveInitialMap must fall through to the // namespaced placeholder. tenant.findUnique returns a default map name only. const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { findUnique: vi.fn(() => Promise.resolve({ defaultMapName: 'office' })) }, map: { findFirst: vi.fn(() => Promise.resolve(null)) }, - membership: { findMany: vi.fn(() => Promise.resolve([])), findFirst: vi.fn(() => Promise.resolve(null)) }, + membership: { + findMany: vi.fn(() => Promise.resolve([])), + findFirst: vi.fn(() => Promise.resolve(null)), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), + }, presence: { findMany: vi.fn(() => Promise.resolve([])) }, user: { findUnique: vi.fn(() => Promise.resolve(null)) }, avatarPack: { @@ -42,6 +56,7 @@ vi.mock('../audioZones/runtime.js', () => ({ })); import { completePendingJoin } from './onJoin.completion.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, Player as PlayerCtor } from '../WorldRoom.js'; import type { Client } from 'colyseus'; @@ -81,6 +96,7 @@ function makeRoom(): { room: WorldRoom; players: Map } { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); return { room, players }; } @@ -89,10 +105,22 @@ function makeClient(sessionId: string, tenantId: string): Client { sessionId, send: vi.fn(), view: fakeView(), - auth: { identity: sessionId, isNpc: false, zonePrivacyVersion: 1, tenantId }, + auth: { identity: sessionId, sessionId: `db-${sessionId}`, isNpc: false, zonePrivacyVersion: 1, tenantId }, } as unknown as Client; } +/** The onAuth entry the admit gate needs for a human session. */ +function registerJoin(room: WorldRoom, sessionId: string, tenantId: string): void { + room.worldAccess.register(sessionId, { + identity: sessionId, + sessionId: `db-${sessionId}`, + tenantId, + tenantSlug: tenantId, + isNpc: false, + zonePrivacyVersion: 1, + }); +} + beforeEach(() => { fakePrisma.tenant.findUnique.mockClear(); fakePrisma.map.findFirst.mockClear(); @@ -103,6 +131,8 @@ describe('completePendingJoin: unresolvable map falls back to a tenant-namespace const { room: roomA, players: pa } = makeRoom(); const { room: roomB, players: pb } = makeRoom(); + registerJoin(roomA, 'sid-a', 'tid-a'); + registerJoin(roomB, 'sid-b', 'tid-b'); await completePendingJoin(roomA, makeClient('sid-a', 'tid-a'), {}, 'user-a', fakePlayerClass); await completePendingJoin(roomB, makeClient('sid-b', 'tid-b'), {}, 'user-b', fakePlayerClass); diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.npc-avatar.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.npc-avatar.test.ts index 503177f1..2ef96da8 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.npc-avatar.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.npc-avatar.test.ts @@ -31,6 +31,15 @@ vi.mock('../../metrics.js', () => ({ type FindArgs = { where?: { id?: string; name?: string; slug?: string } }; let userAvatarId: string | null = null; const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { findUnique: vi.fn((args: FindArgs) => { if (args?.where?.id) return Promise.resolve({ id: 'tenant-a', defaultMapName: 'office' }); @@ -52,6 +61,8 @@ const fakePrisma = { membership: { findFirst: vi.fn(() => Promise.resolve(null)), findMany: vi.fn(() => Promise.resolve([])), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), }, presence: { findMany: vi.fn(() => Promise.resolve([])) }, avatarPack: { @@ -94,6 +105,7 @@ vi.mock('../audioZones/runtime.js', () => ({ })); import { completePendingJoin } from './onJoin.completion.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, RoomOptions, Player as PlayerCtor } from '../WorldRoom.js'; import type { Client } from 'colyseus'; @@ -121,7 +133,7 @@ interface ClientDouble { sessionId: string; send: ReturnType; view: unknown; - auth: { identity: string; isNpc: boolean; zonePrivacyVersion: number; tenantId?: string }; + auth: { identity: string; sessionId?: string; isNpc: boolean; zonePrivacyVersion: number; tenantId?: string }; } function clientDouble(value: ClientDouble): Client { @@ -145,9 +157,22 @@ function makeRoom(): { room: WorldRoom; players: Map } { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); return { room, players }; } +/** The onAuth entry the admit gate needs for a human session (NPCs need none). */ +function registerJoin(room: WorldRoom, sessionId: string, identity: string): void { + room.worldAccess.register(sessionId, { + identity, + sessionId: `db-${sessionId}`, + tenantId: 'tenant-a', + tenantSlug: 'auth-a', + isNpc: false, + zonePrivacyVersion: 1, + }); +} + // The uuid of a custom avatar composed inside tenant A. Whoever learns it can // GET the PNG with no session at all. const LEAKED_ID = 'custom:90579cc0-b608-4dc0-a4e4-cb8e4495fe70'; @@ -212,10 +237,17 @@ describe('completePendingJoin: NPCs never carry a custom avatar', () => { sessionId: 'sid-human', send: vi.fn(), view: fakeView(), - auth: { identity: 'user-a', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a' }, + auth: { + identity: 'user-a', + sessionId: 'db-sid-human', + isNpc: false, + zonePrivacyVersion: 1, + tenantId: 'tenant-a', + }, }); userAvatarId = LEAKED_ID; + registerJoin(room, 'sid-human', 'user-a'); await completePendingJoin(room, client, baseOptions({ avatarId: LEAKED_ID }), 'user-a', fakePlayerClass); const player = players.get('sid-human'); @@ -226,11 +258,18 @@ describe('completePendingJoin: NPCs never carry a custom avatar', () => { it('falls back to the database avatar when an authenticated join requests a foreign pack', async () => { userAvatarId = DEFAULT_ID; const { room, players } = makeRoom(); + registerJoin(room, 'sid-scoped-human', 'user-a'); const client = clientDouble({ sessionId: 'sid-scoped-human', send: vi.fn(), view: fakeView(), - auth: { identity: 'user-a', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a' }, + auth: { + identity: 'user-a', + sessionId: 'db-sid-scoped-human', + isNpc: false, + zonePrivacyVersion: 1, + tenantId: 'tenant-a', + }, }); await completePendingJoin( @@ -251,11 +290,12 @@ describe('completePendingJoin: NPCs never carry a custom avatar', () => { it('rejects an out-of-scope avatar when no database user exists', async () => { const { room, players } = makeRoom(); + registerJoin(room, 'sid-legacy-human', 'legacy-user'); const client = clientDouble({ sessionId: 'sid-legacy-human', send: vi.fn(), view: fakeView(), - auth: { identity: 'legacy-user', isNpc: false, zonePrivacyVersion: 1 }, + auth: { identity: 'legacy-user', sessionId: 'db-sid-legacy-human', isNpc: false, zonePrivacyVersion: 1 }, }); await completePendingJoin( diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.presence.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.presence.test.ts index 8eb3f752..4ac9304e 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.presence.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.presence.test.ts @@ -17,6 +17,15 @@ interface MemberRow { } const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { findUnique: vi.fn(() => Promise.resolve({ defaultMapName: 'office' })) }, map: { findFirst: vi.fn(() => Promise.resolve({ id: 'map-1', name: 'office' })), @@ -25,6 +34,8 @@ const fakePrisma = { membership: { findMany: vi.fn((): Promise => Promise.resolve([])), findFirst: vi.fn(() => Promise.resolve(null)), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), }, presence: { findMany: vi.fn(() => Promise.resolve([])) }, user: { findUnique: vi.fn(() => Promise.resolve({ name: 'Alice', email: 'alice@example.test', avatarId: null })) }, @@ -47,6 +58,7 @@ vi.mock('../audioZones/runtime.js', () => ({ import { completePendingJoin } from './onJoin.completion.js'; import { MAX_JOIN_TEXT_LENGTH } from './joinFields.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, Player as PlayerCtor } from '../WorldRoom.js'; type CompletionClient = Parameters[1]; @@ -91,11 +103,21 @@ async function seededList(members: MemberRow[]): Promise { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); + // The onAuth entry the admit gate needs for this session. + room.worldAccess.register('sid-1', { + identity: 'user-1', + sessionId: 'db-session', + tenantId: 'tenant-1', + tenantSlug: 'tenant-1', + isNpc: false, + zonePrivacyVersion: 1, + }); const client = { sessionId: 'sid-1', send, view: { add() {}, remove() {}, has: () => false }, - auth: { identity: 'user-1', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-1' }, + auth: { identity: 'user-1', sessionId: 'db-session', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-1' }, } as unknown as CompletionClient; await completePendingJoin(room, client, {}, 'user-1', FakePlayer as unknown as typeof PlayerCtor); @@ -130,10 +152,21 @@ describe('presence_recent seed', () => { it('leaves ordinary names, umlauts and addresses unchanged', async () => { const list = await seededList([ - { userId: 'u-1', user: { id: 'u-1', email: 'jörg@example.test', name: 'Jörg Müller-Lüdenscheidt' } }, + { + userId: 'u-1', + user: { + id: 'u-1', + email: 'j\u00f6rg@example.test', + name: 'J\u00f6rg M\u00fcller-L\u00fcdenscheidt', + }, + }, ]); - expect(list[0]?.user).toEqual({ id: 'u-1', email: 'jörg@example.test', name: 'Jörg Müller-Lüdenscheidt' }); + expect(list[0]?.user).toEqual({ + id: 'u-1', + email: 'j\u00f6rg@example.test', + name: 'J\u00f6rg M\u00fcller-L\u00fcdenscheidt', + }); }); it('keeps a missing name null and a missing user empty, as before', async () => { diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.tenant-isolation.test.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.tenant-isolation.test.ts index 64b01ba9..e3b8f365 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.tenant-isolation.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.tenant-isolation.test.ts @@ -31,6 +31,15 @@ const A = { id: 'tenant-a-id', slug: 'auth-a', defaultMapName: 'office' }; const B = { id: 'tenant-b-id', slug: 'spoof-b', defaultMapName: 'office' }; type Where = { where?: { id?: string; slug?: string; tenantId?: string; name?: string } }; const fakePrisma = { + session: { + findMany: vi.fn((args: { where?: { id?: { in?: string[] }; userId?: string } }) => + Promise.resolve([{ + id: args.where?.id?.in?.[0] ?? 'db-session', + userId: args.where?.userId ?? 'user-1', + expiresAt: new Date(Date.now() + 60_000), + }]), + ), + }, tenant: { findUnique: vi.fn((args: Where) => { const w = args?.where ?? {}; @@ -61,6 +70,8 @@ const fakePrisma = { return Promise.resolve([]); }), findFirst: vi.fn(() => Promise.resolve(null)), // not an expired guest + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), }, presence: { findMany: vi.fn(() => Promise.resolve([])), @@ -89,6 +100,7 @@ vi.mock('../audioZones/runtime.js', () => ({ })); import { completePendingJoin } from './onJoin.completion.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, RoomOptions, Player as PlayerCtor } from '../WorldRoom.js'; import type { Client } from 'colyseus'; @@ -115,7 +127,7 @@ function fakeView(): unknown { } function makeRoom(): WorldRoom { - return { + const room = { prismaForPresence: fakePrisma, state: { players: new Map() }, lastSeen: new Map(), @@ -131,6 +143,20 @@ function makeRoom(): WorldRoom { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); + return room; +} + +/** The onAuth entry the admit gate needs for a human session. */ +function registerJoin(room: WorldRoom, sessionId: string): void { + room.worldAccess.register(sessionId, { + identity: 'user-a', + sessionId: `db-${sessionId}`, + tenantId: 'tenant-a-id', + tenantSlug: 'auth-a', + isNpc: false, + zonePrivacyVersion: 1, + }); } beforeEach(() => { @@ -158,8 +184,16 @@ describe('completePendingJoin: presence/guest scoped by the verified auth tenant send: vi.fn(), view: fakeView(), // Verified user of tenant A; the client SPOOFS options.tenant='spoof-b'. - auth: { identity: 'user-a', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a-id', tenantSlug: 'auth-a' }, + auth: { + identity: 'user-a', + sessionId: 'db-sid-1', + isNpc: false, + zonePrivacyVersion: 1, + tenantId: 'tenant-a-id', + tenantSlug: 'auth-a', + }, } as unknown as Client; + registerJoin(room, 'sid-1'); const options = { tenant: 'spoof-b', mapName: 'office', name: 'Alice', avatarId: 'av' } as RoomOptions; await completePendingJoin(room, client, options, 'user-a', fakePlayerClass); @@ -180,8 +214,9 @@ describe('completePendingJoin: presence/guest scoped by the verified auth tenant view: fakeView(), // Verified tenantId, but NO tenantSlug — mirrors resolveTenantSlug failing // (transient DB error, or a deleted tenant with a still-valid 30d JWT). - auth: { identity: 'user-a', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a-id' }, + auth: { identity: 'user-a', sessionId: 'db-sid-2', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-a-id' }, } as unknown as Client; + registerJoin(room, 'sid-2'); const options = { tenant: 'spoof-b', mapName: 'office', name: 'Attacker', avatarId: 'av' } as RoomOptions; await completePendingJoin(room, client, options, 'user-a', fakePlayerClass); diff --git a/apps/server/src/rooms/lifecycle/onJoin.completion.ts b/apps/server/src/rooms/lifecycle/onJoin.completion.ts index a3bab3ea..7acd3889 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.completion.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.completion.ts @@ -3,9 +3,10 @@ import { logger } from '../../logger.js'; import { colyseusPlayers } from '../../metrics.js'; import { createPrismaClient } from '../../db.js'; import type { WorldRoom, RoomOptions, Player as PlayerCtor } from '../WorldRoom.js'; +import { admitPlayer } from './worldAccess.js'; import { broadcastToMap } from '../utils/broadcastHelpers.js'; import { sanitizePosition, sanitizePositionForMap, getMapCenter, type MapMeta } from '../utils/mapBoundsHelpers.js'; -import { getAllBubbleMembers } from '../utils/bubbleHelpers.js'; +import { bubbleStateForClient } from '../handlers/socialScope.js'; import type { RoomMetadata } from './onJoin.limiter.js'; import { isWorldAuth } from './onAuth.js'; import { tenantKeyForClient, isPlayerVisibleToTenant, syncTenantViewsOnJoin } from './tenantView.js'; @@ -232,6 +233,9 @@ async function seedPresenceRecent( setTimeout(() => { try { + // The join may have been revoked after the player list was read; + // only a still-joined session sees other members' contact details. + if (!room.worldAccess.isJoined(client.sessionId)) return; client.send('presence_recent', out); } catch (e) { logger.debug('[WorldRoom] Failed to send presence_recent', e); @@ -307,6 +311,9 @@ function scheduleFullStateSend(room: WorldRoom, client: Client): void { const viewerKey = tenantKeyForClient(client); setTimeout(() => { try { + // The join may have been revoked while the delayed send was pending; + // only a still-joined session receives the world state. + if (!room.worldAccess.isJoined(client.sessionId)) return; client.send('full_state', { players: Array.from(room.state.players.entries()) .filter(([sid, p]) => isPlayerVisibleToTenant(p.isNpc, room.playerTenantKey.get(sid), viewerKey)) @@ -324,14 +331,10 @@ function scheduleFullStateSend(room: WorldRoom, client: Client): void { mapName: p.mapName, })), }); - const groups = Object.entries(room.bubbleGroups) - .map(([id, members]) => ({ - id, - members: members.filter((m) => room.state.players.has(m)), - })) - .filter((g) => Array.isArray(g.members) && g.members.length >= 2); - const members = getAllBubbleMembers(room); - client.send('bubble_state', { groups, members }); + // The bubble seed is scoped to the joining client's own tenant and map, + // exactly like the change-broadcast: a group of another tenant in a + // shared room never reaches this client. + client.send('bubble_state', bubbleStateForClient(room, client)); // Tenant-scope the zone-lock seed exactly like the change-broadcast: strip // pendingRequests (identity/name = PII) belonging to other tenants so a // shared-room foreign tenant never receives them. @@ -361,8 +364,8 @@ export async function completePendingJoin( // Every tenant-scoped read below is scoped by this, NEVER by the // client-supplied options.tenant, so a spoofed options.tenant cannot leak // another tenant's members/presence or pin the player onto another tenant's - // map. Absent only for NPC / token-less legacy joins, which fall back to the - // room/options slug (NPCs are secret-gated, legacy is a transitional state). + // map. Absent only for NPC joins, which fall back to the room/options slug + // (NPCs are secret-gated). const auth = isWorldAuth(client.auth) ? client.auth : undefined; const authTenantId = auth?.tenantId; const authTenantSlug = auth?.tenantSlug; @@ -409,7 +412,7 @@ export async function completePendingJoin( // never see a stale "available" state. player.dnd = options?.dnd === true; - room.state.players.set(client.sessionId, player); + if (!(await admitPlayer(room, client, player))) return; // Record the player's verified tenant and wire the per-client StateView // filters so this player is only ever synced to same-tenant clients (NPCs to // all). MUST run synchronously here — before onJoin resolves — so the initial diff --git a/apps/server/src/rooms/lifecycle/onJoin.name.test.ts b/apps/server/src/rooms/lifecycle/onJoin.name.test.ts index 1d0501fb..b4b8548e 100644 --- a/apps/server/src/rooms/lifecycle/onJoin.name.test.ts +++ b/apps/server/src/rooms/lifecycle/onJoin.name.test.ts @@ -18,7 +18,12 @@ const fakePrisma = { findFirst: vi.fn(() => Promise.resolve({ id: 'map-1', name: 'office' })), findUnique: vi.fn(() => Promise.resolve({ tenantId: 'tenant-1' })), }, - membership: { findMany: vi.fn(() => Promise.resolve([])), findFirst: vi.fn(() => Promise.resolve(null)) }, + membership: { + findMany: vi.fn(() => Promise.resolve([])), + findFirst: vi.fn(() => Promise.resolve(null)), + // The admit gate re-proves the verified tenant; the double stays a member. + findUnique: vi.fn(() => Promise.resolve({ role: 'member', expiresAt: null })), + }, presence: { findMany: vi.fn(() => Promise.resolve([])) }, user: { findUnique: vi.fn() }, avatarPack: { findFirst: vi.fn(() => Promise.resolve({ avatars: [{ key: 'business_man' }] })) }, @@ -40,6 +45,7 @@ vi.mock('../audioZones/runtime.js', () => ({ import { completePendingJoin } from './onJoin.completion.js'; import { MAX_JOIN_TEXT_LENGTH } from './joinFields.js'; +import { WorldAccessRegistry } from './worldAccess.js'; import type { WorldRoom, Player as PlayerCtor, RoomOptions } from '../WorldRoom.js'; type CompletionClient = Parameters[1]; @@ -83,9 +89,21 @@ function makeRoom(): { room: WorldRoom; players: Map } { tileHeightPx: 32, defaultSpawn: { x: 10, y: 10 }, } as unknown as WorldRoom; + room.worldAccess = new WorldAccessRegistry(room); return { room, players }; } +/** The onAuth entry the admit gate needs for a human session. */ +function registerJoin(room: WorldRoom, identity: string): void { + room.worldAccess.register('sid-1', { + identity, + tenantId: 'tenant-1', + tenantSlug: 'tenant-1', + isNpc: false, + zonePrivacyVersion: 1, + }); +} + function clientWith(auth: Record): CompletionClient { return { sessionId: 'sid-1', @@ -99,6 +117,7 @@ function clientWith(auth: Record): CompletionClient { async function joinAsAccount(options: RoomOptions, account: AccountRow | null, identity = 'user-1'): Promise { fakePrisma.user.findUnique.mockResolvedValue(account); const { room, players } = makeRoom(); + registerJoin(room, identity); const client = clientWith({ identity, isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-1' }); await completePendingJoin(room, client, options, identity, FakePlayer as unknown as typeof PlayerCtor); return players.get('sid-1')?.name ?? ''; @@ -108,6 +127,7 @@ async function joinAsAccount(options: RoomOptions, account: AccountRow | null, i async function joinWithoutAccount(options: RoomOptions, identity: string, isNpc = false): Promise { fakePrisma.user.findUnique.mockResolvedValue(null); const { room, players } = makeRoom(); + if (!isNpc) registerJoin(room, identity); const client = clientWith({ identity, isNpc, zonePrivacyVersion: 1 }); await completePendingJoin(room, client, options, identity, FakePlayer as unknown as typeof PlayerCtor); return players.get('sid-1')?.name ?? ''; @@ -154,6 +174,7 @@ describe('the display name of a verified account', () => { it('is the identity, not the client name, when the account lookup fails', async () => { fakePrisma.user.findUnique.mockRejectedValue(new Error('database unavailable')); const { room, players } = makeRoom(); + registerJoin(room, 'user-1'); const client = clientWith({ identity: 'user-1', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-1' }); await completePendingJoin(room, client, { name: HUGE }, 'user-1', FakePlayer as unknown as typeof PlayerCtor); @@ -164,6 +185,7 @@ describe('the display name of a verified account', () => { it('is the identity when the account lookup fails and the client names a short name of its own', async () => { fakePrisma.user.findUnique.mockRejectedValue(new Error('database unavailable')); const { room, players } = makeRoom(); + registerJoin(room, 'user-1'); const client = clientWith({ identity: 'user-1', isNpc: false, zonePrivacyVersion: 1, tenantId: 'tenant-1' }); await completePendingJoin(room, client, { name: 'Mallory' }, 'user-1', FakePlayer as unknown as typeof PlayerCtor); @@ -193,6 +215,7 @@ describe('the display name of a join the server knows no account for', () => { it('is still the client name, cut to the limit, when the lookup fails and there is no verified tenant', async () => { fakePrisma.user.findUnique.mockRejectedValue(new Error('database unavailable')); const { room, players } = makeRoom(); + registerJoin(room, 'bot-7'); const client = clientWith({ identity: 'bot-7', isNpc: false, zonePrivacyVersion: 1 }); await completePendingJoin(room, client, { name: HUGE }, 'bot-7', FakePlayer as unknown as typeof PlayerCtor); diff --git a/apps/server/src/rooms/lifecycle/roomPartition.test.ts b/apps/server/src/rooms/lifecycle/roomPartition.test.ts index 9bbbbb85..6598282c 100644 --- a/apps/server/src/rooms/lifecycle/roomPartition.test.ts +++ b/apps/server/src/rooms/lifecycle/roomPartition.test.ts @@ -7,9 +7,11 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import crypto from 'node:crypto'; import jwt from 'jsonwebtoken'; -import { ServerError, matchMaker, type AuthContext, type Client } from 'colyseus'; +import { ServerError, matchMaker, type AuthContext } from 'colyseus'; const warn = vi.hoisted(() => vi.fn()); +const freshSessionMock = vi.hoisted(() => vi.fn()); +vi.mock('../../api/utils/sessionAuth.js', () => ({ validateTenantSessionFresh: freshSessionMock })); vi.mock('../../logger.js', () => ({ logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() }, })); @@ -27,10 +29,11 @@ import { } from '../../testUtils/matchmakeHarness.js'; import { enforceRoomPartition } from './roomPartition.js'; import { AUTH_REJECTED_CODE, type WorldAuth } from './onAuth.js'; -import type { WorldRoom } from '../WorldRoom.js'; +import { WorldRoom } from '../WorldRoom.js'; const verified = (tenantSlug?: string): WorldAuth => ({ identity: 'user-1', + sessionId: 'db-session-1', isNpc: false, zonePrivacyVersion: 1, ...(tenantSlug ? { tenantId: `tid-${tenantSlug}`, tenantSlug } : {}), @@ -84,7 +87,7 @@ describe('WorldRoom.onAuth with a verified session', () => { const SECRET = 'x'.repeat(40); let server: MatchmakeTestServer; - const tenantRows: Record = { 'tid-beta': { slug: 'beta' } }; + const tenantRows: Record = { 'tid-beta': { id: 'tid-beta', slug: 'beta' } }; /** A signed token for `userId` of tenant beta plus the session row the room's prisma will return. */ function sessionFor(userId: string): { token: string; context: AuthContext } { @@ -105,13 +108,24 @@ describe('WorldRoom.onAuth with a verified session', () => { createPrismaClientMock.mockImplementation(() => ({ ...makeFakePrisma(), tenant: { - findUnique: ({ where }: { where: { id?: string } }) => Promise.resolve(tenantRows[where.id ?? ''] ?? null), + findUnique: ({ where }: { where: { id?: string; slug?: string } }) => + Promise.resolve(tenantRows[where.id ?? (where.slug === 'beta' ? 'tid-beta' : '')] ?? null), }, session: { findUnique: ({ where }: { where: { tokenHash: string } }) => Promise.resolve(sessions.get(where.tokenHash) ?? null), update: () => Promise.resolve({}), }, + // Every session here belongs to a member of its own tenant; the + // membership gate has its own tests (worldAccess.integration.test.ts). + membership: { findUnique: () => Promise.resolve({ expiresAt: null, role: 'member' }) }, + })); + freshSessionMock.mockImplementation((_prisma: unknown, _rawToken: string, tenantId: string) => Promise.resolve({ + status: 'allowed', + userId: 'user-1', + sessionId: 'db-session-1', + tenantId, + access: 'member', })); server = await startMatchmakeServer(); }); @@ -136,32 +150,35 @@ describe('WorldRoom.onAuth with a verified session', () => { const room = matchMaker.getLocalRoomById(res.body.roomId ?? ''); return room as WorldRoom; } - const client = {} as Client; it('admits a member of another tenant that sent no tenant into acme’s room while enforcement is off', async () => { - const room = await acmeRoom(); + await acmeRoom(); const { context } = sessionFor('user-1'); - const auth = await room.onAuth(client, { zonePrivacyVersion: 1 }, context); + const auth = await WorldRoom.onAuth(context.token ?? '', { zonePrivacyVersion: 1 }, context); expect(auth.tenantSlug).toBe('beta'); + enforceRoomPartition(undefined, auth, 'acme'); expect(warn).toHaveBeenCalledWith(expect.stringContaining('no tenant requested'), expect.anything()); }); - it('refuses it once ZONE_PRIVACY_TENANT_ENFORCE is on', async () => { - const room = await acmeRoom(); + it('refuses a tenant-less member from another room once enforcement is on', async () => { + await acmeRoom(); const { context } = sessionFor('user-2'); vi.stubEnv('ZONE_PRIVACY_TENANT_ENFORCE', 'true'); - await expect(room.onAuth(client, { zonePrivacyVersion: 1 }, context)).rejects.toMatchObject({ - code: AUTH_REJECTED_CODE, - message: 'tenant_mismatch', - }); + const auth = await WorldRoom.onAuth(context.token ?? '', { zonePrivacyVersion: 1 }, context); + try { + enforceRoomPartition(undefined, auth, 'acme'); + expect.unreachable('expected a refusal'); + } catch (error) { + expect(error).toMatchObject({ code: AUTH_REJECTED_CODE, message: 'tenant_mismatch' }); + } }); - it('keeps refusing a named foreign tenant when enforcement is on (existing check)', async () => { - const room = await acmeRoom(); + it('keeps refusing a named foreign tenant when enforcement is on', async () => { + await acmeRoom(); const { context } = sessionFor('user-3'); vi.stubEnv('ZONE_PRIVACY_TENANT_ENFORCE', 'true'); - await expect(room.onAuth(client, { tenant: 'acme', zonePrivacyVersion: 1 }, context)).rejects.toMatchObject({ - message: 'tenant_mismatch', - }); + await expect( + WorldRoom.onAuth(context.token ?? '', { tenant: 'acme', zonePrivacyVersion: 1 }, context), + ).rejects.toMatchObject({ code: AUTH_REJECTED_CODE, message: 'tenant_mismatch' }); }); }); diff --git a/apps/server/src/rooms/lifecycle/roomPartition.ts b/apps/server/src/rooms/lifecycle/roomPartition.ts index bf87433c..4213fe58 100644 --- a/apps/server/src/rooms/lifecycle/roomPartition.ts +++ b/apps/server/src/rooms/lifecycle/roomPartition.ts @@ -21,7 +21,7 @@ import { AUTH_REJECTED_CODE, isTenantEnforced, type WorldAuth } from './onAuth.j * either way (verified-tenant scoping, StateView filter, seat counting); this * closes the residual sharing of the Colyseus room. * - * A join that carries no verified tenant (NPCs, a token-less staged join) has + * A join that carries no verified tenant (NPCs, which carry no session) has * nothing to compare and is left alone. */ export function enforceRoomPartition( diff --git a/apps/server/src/rooms/lifecycle/transcriptionGate.test.ts b/apps/server/src/rooms/lifecycle/transcriptionGate.test.ts index 12c18eae..df570ccb 100644 --- a/apps/server/src/rooms/lifecycle/transcriptionGate.test.ts +++ b/apps/server/src/rooms/lifecycle/transcriptionGate.test.ts @@ -10,9 +10,9 @@ const mocks = vi.hoisted(() => ({ loggerInfo: vi.fn(), loggerWarn: vi.fn(), loggerError: vi.fn(), - requireAuth: vi.fn(), getTenantFromReq: vi.fn(), - requireMembership: vi.fn(), + validateTenantSessionFresh: vi.fn(), + membershipFindUnique: vi.fn(), createLivekitToken: vi.fn(), })); @@ -30,9 +30,13 @@ vi.mock('../../logger.js', () => ({ })); vi.mock('../../api/utils/authHelpers.js', () => ({ - requireAuth: mocks.requireAuth, getTenantFromReq: mocks.getTenantFromReq, - requireMembership: mocks.requireMembership, + // The session reference carried by the LiveKit token is derived from it. + getJwtSecret: () => 'test-jwt-secret', +})); + +vi.mock('../../api/utils/sessionAuth.js', () => ({ + validateTenantSessionFresh: mocks.validateTenantSessionFresh, })); vi.mock('../../livekit.js', () => ({ @@ -43,7 +47,10 @@ import { handleLivekitToken } from '../../api/routes/health.js'; import { evaluateTranscriptionGate, enforceTranscriptionGate } from './transcriptionGate.js'; import { hasTranscriptionClearance, revokeTranscriptionClearance } from './transcriptionClearance.js'; -const prisma = { $disconnect: vi.fn().mockResolvedValue(undefined) } as PrismaClient; +const prisma = { + $disconnect: vi.fn().mockResolvedValue(undefined), + membership: { findUnique: mocks.membershipFindUnique }, +} as unknown as PrismaClient; const getJoinRequirementMock = vi.fn(() => Promise.resolve(null)); const moduleImplementation = { version: 1 as const, @@ -58,8 +65,9 @@ function makeClient() { return { error: vi.fn(), leave: vi.fn() } as Client; } +/** Request that presents the session credential as the `auth_token` cookie. */ function fakeReq(body: Record): express.Request { - return { body, headers: {} } as express.Request; + return { body, headers: {}, cookies: { auth_token: 'session-token' } } as unknown as express.Request; } function fakeRes(): express.Response { @@ -75,9 +83,15 @@ beforeEach(() => { getJoinRequirementMock.mockReset().mockResolvedValue(null); mocks.getTranscriptionModuleSync.mockReset().mockReturnValue(moduleImplementation); mocks.loggerWarn.mockReset(); - mocks.requireAuth.mockReset().mockReturnValue({ userId: 'user-1' }); mocks.getTenantFromReq.mockReset().mockReturnValue({ id: 'tenant-1', slug: 'acme' }); - mocks.requireMembership.mockReset().mockResolvedValue({ role: 'member' }); + mocks.validateTenantSessionFresh.mockReset().mockResolvedValue({ + status: 'allowed', + userId: 'user-1', + sessionId: 'db-session-1', + tenantId: 'tenant-1', + access: 'member', + }); + mocks.membershipFindUnique.mockReset().mockResolvedValue({ expiresAt: null }); mocks.createLivekitToken.mockReset().mockResolvedValue('livekit-token'); vi.stubEnv('LIVEKIT_API_KEY', 'test-key'); vi.stubEnv('LIVEKIT_API_SECRET', 'test-secret'); @@ -285,6 +299,7 @@ describe('handleLivekitToken transcription gate', () => { await handleLivekitToken(prisma, fakeReq({ roomName: 'world', identity: 'user-1' }), res); + expect(mocks.validateTenantSessionFresh).toHaveBeenCalledWith(prisma, 'session-token', 'tenant-1'); expect(mocks.createLivekitToken).toHaveBeenCalled(); expect(res.send).toHaveBeenCalledWith('livekit-token'); }); diff --git a/apps/server/src/rooms/lifecycle/worldAccess.integration.test.ts b/apps/server/src/rooms/lifecycle/worldAccess.integration.test.ts new file mode 100644 index 00000000..c71e1135 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccess.integration.test.ts @@ -0,0 +1,173 @@ +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import type { AuthContext } from 'colyseus'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; +import { hashSessionToken } from '../../api/utils/sessionAuth.js'; +import type { WorldRoom } from '../WorldRoom.js'; +import { authenticateWorldJoin } from './onAuth.js'; +import { startGuestExpiryInterval } from './guestExpiry.js'; +import { createWorldAccess } from './worldAccess.js'; + +/** + * World access requires a tenant membership, at join time and while connected, + * checked against a REAL PostgreSQL database. + * + * A session stays valid after its owner lost the membership of the tenant in + * its `tid` claim (removed member, expired guest). The world join must refuse + * such a session, and a client that is already connected must be disconnected + * by the room's periodic access sweep. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('worldAccess.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +let tenantId: string; +let tenantSlug: string; + +async function createTenant(slug = `qacc-${crypto.randomUUID()}`): Promise { + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser( + memberships: Array<{ tenantId: string; role: Role; expiresAt?: Date }>, +): Promise<{ id: string; token: string; sessionId: string }> { + const user = await prisma.user.create({ data: { email: `qacc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + for (const m of memberships) await prisma.membership.create({ data: { userId: user.id, ...m } }); + // The session is scoped to the world's tenant, whatever the memberships say. + const token = jwt.sign({ sub: user.id, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + const session = await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + select: { id: true }, + }); + return { id: user.id, token, sessionId: session.id }; +} + +function join(token: string) { + const context = { token, headers: new Headers(), ip: '127.0.0.1' } as AuthContext; + return authenticateWorldJoin( + { tenant: tenantSlug, zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION }, + context, + prisma, + ); +} + +function makeRoom( + players: Map, + clients: unknown[], + sessionIds: Map, +): WorldRoom { + const room = { + metadata: { tenant: tenantSlug }, + prismaForPresence: prisma, + state: { players }, + clients, + } as unknown as WorldRoom; + // The sweep reads each session's verified tenant from the registry, never + // the room slug: every player here was verified for this tenant at join time. + // The bundled session check needs each entry's database session row, as a + // real join via onAuth would store it. + room.worldAccess = createWorldAccess(room); + for (const [sessionId, player] of players) { + room.worldAccess.register(sessionId, { + identity: player.identity, + tenantId, + tenantSlug, + sessionId: sessionIds.get(sessionId) ?? null, + authSessionId: sessionIds.get(sessionId), + isNpc: false, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }); + } + return room; +} + +/** Fire the room's 60 s sweep once (timer functions only, the clock stays real). */ +async function runOneSweep(room: WorldRoom): Promise { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + try { + const interval = startGuestExpiryInterval(room); + await vi.advanceTimersByTimeAsync(60_000); + clearInterval(interval); + } finally { + vi.useRealTimers(); + } +} + +beforeAll(async () => { + tenantSlug = `qacc-${crypto.randomUUID()}`; + tenantId = await createTenant(tenantSlug); +}); + +afterAll(async () => { + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('world join requires a membership (real database)', () => { + it('admits a member', async () => { + const member = await createUser([{ tenantId, role: 'member' }]); + await expect(join(member.token)).resolves.toMatchObject({ identity: member.id }); + }); + + it('refuses a signed-in user without a membership in the session tenant', async () => { + const removed = await createUser([]); + await expect(join(removed.token)).rejects.toThrow('not_member_of_tenant'); + }); + + it('refuses an expired guest', async () => { + const guest = await createUser([{ tenantId, role: 'guest', expiresAt: new Date(Date.now() - 60_000) }]); + await expect(join(guest.token)).rejects.toThrow('not_member_of_tenant'); + }); + + it('admits an operator (owner of the internal tenant)', async () => { + const existing = await prisma.tenant.findUnique({ where: { slug: 'internal' } }); + const internalId = existing?.id ?? (await createTenant('internal')); + const operator = await createUser([{ tenantId: internalId, role: 'owner' }]); + await expect(join(operator.token)).resolves.toMatchObject({ identity: operator.id }); + }); +}); + +describe('connected clients lose the world with their membership (real database)', () => { + it('disconnects a connected user whose membership is gone and keeps the members', async () => { + const member = await createUser([{ tenantId, role: 'member' }]); + const removed = await createUser([{ tenantId, role: 'member' }]); + await prisma.membership.deleteMany({ where: { userId: removed.id } }); + + const memberClient = { sessionId: 'sess-member', leave: vi.fn(), error: vi.fn() }; + const removedClient = { sessionId: 'sess-removed', leave: vi.fn(), error: vi.fn() }; + const players = new Map([ + ['sess-member', { identity: member.id }], + ['sess-removed', { identity: removed.id }], + ]); + // The membership is removed directly, without touching the session rows: + // the session check passes and the membership proof still disconnects + // with `not_member_of_tenant`. + const sessionIds = new Map([ + ['sess-member', member.sessionId], + ['sess-removed', removed.sessionId], + ]); + await runOneSweep(makeRoom(players, [memberClient, removedClient], sessionIds)); + + await vi.waitFor(() => expect(removedClient.error).toHaveBeenCalledWith(4401, 'not_member_of_tenant'), { + timeout: 5_000, + }); + expect(removedClient.leave).toHaveBeenCalled(); + expect(memberClient.leave).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/server/src/rooms/lifecycle/worldAccess.outage.integration.test.ts b/apps/server/src/rooms/lifecycle/worldAccess.outage.integration.test.ts new file mode 100644 index 00000000..88502783 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccess.outage.integration.test.ts @@ -0,0 +1,354 @@ +/** + * A world session must not outlive its verifiable access. + * + * A real Colyseus server with the real `WorldRoom` (see + * testUtils/matchmakeHarness.ts), a real PostgreSQL database (db.js is NOT + * mocked) and real @colyseus/sdk clients. `WORLD_ACCESS_SWEEP_MS=1000` and + * `WORLD_ACCESS_LEASE_MS=4000` drive the post-fix cadence (inert before the + * fix, whose sweep is a hard-coded 60 s). + * + * 1. local revocation despite a failed publish: with presence `publish` + * rejecting, `removeMemberFromTenant` still disconnects the client within + * 2 s. Before the fix the client stays (the publish is only logged and + * the next sweep is a minute away). + * 2. unreachable database: with the database container paused the client is + * disconnected within lease + 3 s with code 4503 `access_unverified`. + * Before the fix the client stays (no lease timer; the wait window is + * 12 s). + * 3. a short hiccup disconnects nobody: pause for 1.5 s, unpause, and the + * client is still connected after 6 more s. Green before and after the + * fix. + * 4. a guest ends at its stored expiry: a guest with `expiresAt = now + 3 s` + * is disconnected with 4006 `guest_expired` no earlier than `expiresAt` + * and no later than `expiresAt + 1 s`. Before the fix the client stays + * until the 60 s sweep (wait window 6 s). + * 5. a deleted session ends the world session even though the membership is + * intact: after `revokeSessionsForUser` the client is disconnected within + * sweep + 3 s with 4401 `session_revoked`. Before the fix the lease keeps + * renewing and the client stays (wait window 8 s). + * + * The database container is paused via `docker pause` on `TEST_PG_CONTAINER`. + * A missing or empty value fails at load; `unpause` always runs in a + * `finally`. Without docker access the file fails fast with a clear error. + */ + +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; +import { hashSessionToken, revokeSessionsForUser } from '../../api/utils/sessionAuth.js'; +import { removeMemberFromTenant } from '../../services/accountDeletion.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('worldAccess.outage.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const execFileAsync = promisify(execFile); + +function requireTestPgContainer(): string { + const value = process.env.TEST_PG_CONTAINER; + if (!value) { + throw new Error( + 'worldAccess.outage.integration.test.ts needs TEST_PG_CONTAINER naming the test database container', + ); + } + return value; +} + +const PG_CONTAINER = requireTestPgContainer(); +const FILE = 'worldAccess.outage.integration.test.ts'; + +async function dockerPause(): Promise { + try { + await execFileAsync('docker', ['pause', PG_CONTAINER]); + } catch (e: unknown) { + throw new Error( + `${FILE} needs docker access to pause ${PG_CONTAINER}: ${e instanceof Error ? e.message : String(e)}`, + ); + } +} + +async function dockerUnpause(): Promise { + try { + await execFileAsync('docker', ['unpause', PG_CONTAINER]); + } catch (e: unknown) { + throw new Error( + `${FILE} needs docker access to unpause ${PG_CONTAINER}: ${e instanceof Error ? e.message : String(e)}`, + ); + } +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const packUuids: string[] = []; +let server: MatchmakeTestServer; +let previousGameServer: typeof global.gameServer; +let tenantId: string; +let tenantSlug: string; +let fixturePackUuid = ''; + +/** + * One global (tenantId null) avatar pack so a join that passes onAuth can run + * to completion. Real fixture row, not a mock: without any pack in scope even + * a fully authorized join is refused later in onJoin with 526. + */ +async function seedGlobalAvatarPack(): Promise { + const uuid = `s1r6-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'outage join fixture', + author: 's1r6-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +async function createTenant(slug: string): Promise { + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser( + memberships: Array<{ tenantId: string; role: Role; expiresAt?: Date }>, + sessionTenantId: string, +): Promise<{ id: string; token: string }> { + const user = await prisma.user.create({ + data: { + email: `s1r6-${crypto.randomUUID()}@example.test`, + avatarId: `${fixturePackUuid}:business_man`, + }, + }); + userIds.push(user.id); + for (const m of memberships) await prisma.membership.create({ data: { userId: user.id, ...m } }); + const token = jwt.sign({ sub: user.id, tid: sessionTenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, token }; +} + +interface TrackedJoin { + room?: Room; + error?: unknown; + left: boolean; + leftAt: number | null; + errorMessages: unknown[]; +} + +function joinOptions(tenant?: string): Record { + return { + ...(tenant ? { tenant } : {}), + // A real client always names its avatar; without one even an authorized + // join stops later in onJoin (526), which would blur this gate's signal. + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; +} + +async function joinWorld(identity: string, token: string, tenant?: string): Promise { + const client = new Client(server.base); + client.auth.token = token; + const tracked: TrackedJoin = { left: false, leftAt: null, errorMessages: [] }; + try { + const room = await client.joinOrCreate('world', joinOptions(tenant)); + tracked.room = room; + room.onLeave(() => { + tracked.left = true; + tracked.leftAt = Date.now(); + }); + room.onError((code, message) => { + tracked.errorMessages.push({ code, message }); + }); + } catch (error) { + tracked.error = error; + } + return tracked; +} + +/** Real waiting with polling on the condition, never a fixed sleep as proof. */ +async function waitFor(left: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!left()) { + if (Date.now() > deadline) throw new Error(`condition not met within ${timeoutMs} ms`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +/** Cleanup-only leave: never fail the test, never hang on an already swept room. */ +async function leaveQuietly(join: TrackedJoin): Promise { + if (join.left || !join.room) return; + await Promise.race([join.room.leave().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 3_000))]); +} + +beforeAll(async () => { + // Fail fast with a clear error when docker (or the container) is missing: + // cases 2 and 3 pause the database through it. + try { + await execFileAsync('docker', ['inspect', PG_CONTAINER]); + } catch (e: unknown) { + throw new Error(`${FILE} needs docker access to ${PG_CONTAINER}: ${e instanceof Error ? e.message : String(e)}`); + } + vi.stubEnv('WORLD_ACCESS_SWEEP_MS', '1000'); + vi.stubEnv('WORLD_ACCESS_LEASE_MS', '4000'); + tenantSlug = `s1r6-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + tenantId = await createTenant(tenantSlug); + await seedGlobalAvatarPack(); + server = await startMatchmakeServer(); + // Revocation events flow through the server presence, as in production + // (index.ts exposes the Colyseus server globally for broadcasters). + previousGameServer = global.gameServer; + global.gameServer = server.gameServer; +}); + +beforeEach(async () => { + await disposeAllRooms(); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +afterAll(async () => { + vi.unstubAllEnvs(); + await stopMatchmakeServer(server); + global.gameServer = previousGameServer; + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('world access survives publish and database faults (real database)', () => { + it('case 1: revocation reaches the room even when the publish fails', async () => { + const joined = await joinWorld( + 's1r6-case1', + (await createUser([{ tenantId, role: 'member' }], tenantId)).token, + tenantSlug, + ); + expect(joined.error, 'Fall 1: Beitritt muss gelingen').toBeUndefined(); + const presence = server.gameServer.presence; + if (!presence) throw new Error(`${FILE} Fall 1: matchmake server has no presence`); + const publishSpy = vi.spyOn(presence, 'publish').mockRejectedValue(new Error('s1r6 presence down')); + try { + const userId = userIds[userIds.length - 1]; + await removeMemberFromTenant(prisma, { userId, tenantId }); + await waitFor(() => joined.left, 2_000); + } finally { + publishSpy.mockRestore(); + } + expect(joined.left, 'Fall 1: Client muss trotz Publish-Fehler getrennt sein').toBe(true); + + await leaveQuietly(joined); + }, 30_000); + + it('case 2: an unreachable database ends the session with 4503 access_unverified', async () => { + const joined = await joinWorld( + 's1r6-case2', + (await createUser([{ tenantId, role: 'member' }], tenantId)).token, + tenantSlug, + ); + expect(joined.error, 'Fall 2: Beitritt muss gelingen').toBeUndefined(); + try { + await dockerPause(); + // Lease (4 s) + 3 s headroom; before the fix nothing fires here. + await waitFor(() => joined.left, 12_000); + } finally { + await dockerUnpause(); + } + expect(joined.left, 'Fall 2: Client muss bei unerreichbarer DB getrennt sein').toBe(true); + expect( + joined.errorMessages, + `Fall 2: 4503 access_unverified erwartet, erhalten=${JSON.stringify(joined.errorMessages)}`, + ).toContainEqual({ code: 4503, message: 'access_unverified' }); + + await leaveQuietly(joined); + }, 60_000); + + it('case 3: a short database hiccup disconnects nobody', async () => { + const joined = await joinWorld( + 's1r6-case3', + (await createUser([{ tenantId, role: 'member' }], tenantId)).token, + tenantSlug, + ); + expect(joined.error, 'Fall 3: Beitritt muss gelingen').toBeUndefined(); + try { + await dockerPause(); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + } finally { + await dockerUnpause(); + } + await new Promise((resolve) => setTimeout(resolve, 6_000)); + expect(joined.left, 'Fall 3: Client muss nach kurzem Schluckauf verbunden bleiben').toBe(false); + + await leaveQuietly(joined); + }, 60_000); + + it('case 4: a guest ends at its stored expiry with 4006 guest_expired', async () => { + const expiresAtMs = Date.now() + 3_000; + const joined = await joinWorld( + 's1r6-case4', + (await createUser([{ tenantId, role: 'guest', expiresAt: new Date(expiresAtMs) }], tenantId)).token, + tenantSlug, + ); + expect(joined.error, 'Fall 4: Gast-Beitritt muss gelingen').toBeUndefined(); + await waitFor(() => joined.left, Math.max(expiresAtMs - Date.now() + 1_000, 2_000)); + expect(joined.left, 'Fall 4: Gast muss zum Ablauf getrennt sein').toBe(true); + expect( + joined.errorMessages, + `Fall 4: 4006 guest_expired erwartet, erhalten=${JSON.stringify(joined.errorMessages)}`, + ).toContainEqual({ code: 4006, message: 'guest_expired' }); + expect( + joined.leftAt, + `Fall 4: Trennung nicht vor expiresAt, leftAt=${String(joined.leftAt)} expiresAt=${String(expiresAtMs)}`, + ).toBeGreaterThanOrEqual(expiresAtMs - 750); + + await leaveQuietly(joined); + }, 30_000); + + it('case 5: a deleted session ends the world session with 4401 session_revoked', async () => { + const user = await createUser([{ tenantId, role: 'member' }], tenantId); + const joined = await joinWorld('s1r6-case5', user.token, tenantSlug); + expect(joined.error, 'Fall 5: Beitritt muss gelingen').toBeUndefined(); + const userId = userIds[userIds.length - 1]; + // Only the session row goes: the membership stays, so the session check — + // not a missing membership — has to end the world session. + await revokeSessionsForUser(prisma, userId); + expect( + await prisma.membership.findUnique({ where: { tenantId_userId: { tenantId, userId } } }), + 'Fall 5: Mitgliedschaft muss bestehen bleiben', + ).not.toBeNull(); + // Next sweep (1 s) + headroom; before the fix the lease keeps renewing. + await waitFor(() => joined.left, 8_000); + expect(joined.left, 'Fall 5: Client muss nach Sitzungsende getrennt sein').toBe(true); + expect( + joined.errorMessages, + `Fall 5: 4401 session_revoked erwartet, erhalten=${JSON.stringify(joined.errorMessages)}`, + ).toContainEqual({ code: 4401, message: 'session_revoked' }); + + await leaveQuietly(joined); + }, 30_000); +}); diff --git a/apps/server/src/rooms/lifecycle/worldAccess.pendingJoin.integration.test.ts b/apps/server/src/rooms/lifecycle/worldAccess.pendingJoin.integration.test.ts new file mode 100644 index 00000000..4bf411e8 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccess.pendingJoin.integration.test.ts @@ -0,0 +1,314 @@ +/** + * A revocation between onAuth and player registration must kill the + * pending join. + * + * A real Colyseus server with the real `WorldRoom` (see + * testUtils/matchmakeHarness.ts), a real PostgreSQL database and real + * @colyseus/sdk clients. `db.js` is mocked ONLY to wrap the REAL PrismaClient + * with a gate: `membership.findFirst` with `where.role === 'guest'` for the + * target userId (that is `checkGuestExpired` in onJoin.completion.ts — after + * onAuth, before `players.set`) waits until the test removes the membership + * and releases it, then passes through to the real query. Every other call + * goes straight to the real database. + * + * Flow: the user is a member of A and B; `joinOrCreate` for A starts (not + * awaited) -> wait until the gate is reached -> `removeMemberFromTenant` (a + * real commit with a real revocation event) -> release the gate. + * + * After the R5 fix the join is rejected with 4401, the room holds no player + * of that identity, and the client never receives `presence_recent` or + * `full_state`. Before the fix the join succeeds. + * + * Rejection form (observed on the green run): `joinOrCreate` REJECTS with + * code 4401 (`MatchMakeError`) — the server's `client.error(4401)` during the + * join handshake surfaces as a refused matchmake, so there is no room to + * leave and no `onError`/`onLeave` sequence. The test therefore accepts a + * rejected `joinOrCreate` OR an error-plus-leave on a resolved room, and + * asserts the shared invariants (4401, no player, no confidential messages) + * in both cases. + */ + +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import type { Role } from '../../generated/prisma/index.js'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; +import { hashSessionToken } from '../../api/utils/sessionAuth.js'; +import { removeMemberFromTenant } from '../../services/accountDeletion.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error( + 'worldAccess.pendingJoin.integration.test.ts needs DATABASE_URL pointing at a migrated test database', + ); +} + +/** Gate state: hoisted so the `vi.mock` factory below can close over it. */ +const gate = vi.hoisted(() => { + let releaseGate!: () => void; + const gatePromise = new Promise((resolve) => { + releaseGate = resolve; + }); + return { + targetUserId: null as string | null, + hit: false, + passed: false, + gatePromise, + release: (): void => releaseGate(), + }; +}); + +type MembershipFindFirst = PrismaClient['membership']['findFirst']; + +vi.mock('../../db.js', async (importOriginal) => { + const actual = await importOriginal(); + const real = actual.createPrismaClient(); + const gatedMembership = Object.create(real.membership) as PrismaClient['membership']; + const realFindFirst = real.membership.findFirst.bind(real.membership); + gatedMembership.findFirst = (async (args: unknown) => { + const where = (args as { where?: { role?: unknown; userId?: unknown } } | undefined)?.where; + if (gate.targetUserId !== null && !gate.passed && where?.role === 'guest' && where?.userId === gate.targetUserId) { + gate.hit = true; + gate.passed = true; + await gate.gatePromise; + } + return realFindFirst(args as never); + }) as MembershipFindFirst; + const wrapped = new Proxy(real, { + get(target, prop): unknown { + if (prop === 'membership') return gatedMembership; + const value = Reflect.get(target, prop, target) as unknown; + return typeof value === 'function' ? (value as (...a: never[]) => unknown).bind(target) : value; + }, + }); + return { createPrismaClient: () => wrapped }; +}); + +import { createPrismaClient } from '../../db.js'; + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const packUuids: string[] = []; +let server: MatchmakeTestServer; +let previousGameServer: typeof global.gameServer; +let tenantAId: string; +let tenantASlug: string; +let tenantBId: string; +let fixturePackUuid = ''; + +/** + * One global (tenantId null) avatar pack so a join that passes onAuth can run + * to completion. Real fixture row, not a mock: without any pack in scope even + * a fully authorized join is refused later in onJoin with 526. + */ +async function seedGlobalAvatarPack(): Promise { + const uuid = `s1r5-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'pending join fixture', + author: 's1r5-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +async function createTenant(slug: string): Promise { + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser( + memberships: Array<{ tenantId: string; role: Role }>, + sessionTenantId: string, +): Promise<{ id: string; token: string }> { + const user = await prisma.user.create({ + data: { + email: `s1r5-${crypto.randomUUID()}@example.test`, + avatarId: `${fixturePackUuid}:business_man`, + }, + }); + userIds.push(user.id); + for (const m of memberships) await prisma.membership.create({ data: { userId: user.id, ...m } }); + const token = jwt.sign({ sub: user.id, tid: sessionTenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, token }; +} + +function joinOptions(tenant?: string): Record { + return { + ...(tenant ? { tenant } : {}), + // A real client always names its avatar; without one even an authorized + // join stops later in onJoin (526), which would blur this gate's signal. + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; +} + +/** Real waiting with polling on the condition, never a fixed sleep as proof. */ +async function waitFor(left: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!left()) { + if (Date.now() > deadline) throw new Error(`condition not met within ${timeoutMs} ms`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +/** Cleanup-only leave: never fail the test, never hang on an already swept room. */ +async function leaveQuietly(room: Room | undefined, left: () => boolean): Promise { + if (left() || !room) return; + await Promise.race([room.leave().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 3_000))]); +} + +beforeAll(async () => { + tenantASlug = `s1r5-a-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + const tenantBSlug = `s1r5-b-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + tenantAId = await createTenant(tenantASlug); + tenantBId = await createTenant(tenantBSlug); + await seedGlobalAvatarPack(); + server = await startMatchmakeServer(); + // Revocation events flow through the server presence, as in production + // (index.ts exposes the Colyseus server globally for broadcasters). + previousGameServer = global.gameServer; + global.gameServer = server.gameServer; +}); + +beforeEach(async () => { + await disposeAllRooms(); +}); + +afterAll(async () => { + await stopMatchmakeServer(server); + global.gameServer = previousGameServer; + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('revocation between onAuth and player registration ends the pending join', () => { + it('rejects with 4401, publishes no player and sends no confidential state', async () => { + // An observer member of A stays in A's room for the whole test, so the + // room (and its player set) outlives the rejected join: its synced state + // is the witness that no player of the revoked identity was published. + const observer = await createUser([{ tenantId: tenantAId, role: 'member' }], tenantAId); + const observerClient = new Client(server.base); + observerClient.auth.token = observer.token; + const observerRoom = await observerClient.joinOrCreate('world', joinOptions(tenantASlug)); + const observedJoins: unknown[] = []; + observerRoom.onMessage('player_joined', (msg: unknown) => observedJoins.push(msg)); + const observerRoomId = observerRoom.roomId; + + // The revoked user is a member of A and B; its session belongs to A. + const revoked = await createUser( + [ + { tenantId: tenantAId, role: 'member' }, + { tenantId: tenantBId, role: 'member' }, + ], + tenantAId, + ); + gate.targetUserId = revoked.id; + + const revokedClient = new Client(server.base); + revokedClient.auth.token = revoked.token; + // Started, not awaited: onAuth passes while the membership still exists, + // then the join parks at the guest-expiry gate before `players.set`. + const joinPromise = revokedClient.joinOrCreate('world', joinOptions(tenantASlug)); + + // The gate proves onAuth already admitted this identity for A. + await waitFor(() => gate.hit, 15_000); + + // Real commit with a real revocation event, strictly between onAuth and + // the player registration. + await removeMemberFromTenant(prisma, { userId: revoked.id, tenantId: tenantAId }); + gate.release(); + + let joinError: unknown; + let revokedRoom: Room | undefined; + try { + revokedRoom = await joinPromise; + } catch (error) { + joinError = error; + } + + const seen = { presenceRecent: false, fullState: false, errors: [] as unknown[], left: false }; + if (revokedRoom) { + expect(revokedRoom.roomId, 'pending join lands in the observed room').toBe(observerRoomId); + revokedRoom.onMessage('presence_recent', () => { + seen.presenceRecent = true; + }); + revokedRoom.onMessage('full_state', () => { + seen.fullState = true; + }); + revokedRoom.onError((code, message) => { + seen.errors.push({ code, message }); + }); + revokedRoom.onLeave(() => { + seen.left = true; + }); + // A resolved join that is then rejected still has to leave promptly. + // Pre-fix the join simply succeeds and stays, so the absence of any + // error is not waited on: the 4401 assertion below fails instead. + if (!joinError) { + await waitFor(() => seen.errors.length > 0, 5_000).catch(() => {}); + if (seen.errors.length > 0) await waitFor(() => seen.left, 5_000); + } + } + + console.log( + `[s1r5-rot] join rejected=${JSON.stringify(joinError ?? seen.errors)} left=${String(seen.left)} ` + + `presence_recent=${String(seen.presenceRecent)} full_state=${String(seen.fullState)}`, + ); + + // Rejected with 4401 in one of the two documented forms. + const rejectedUpfront = joinError !== undefined && (joinError as { code?: unknown }).code === 4401; + const rejectedAfterJoin = + joinError === undefined && seen.errors.some((e) => (e as { code?: unknown }).code === 4401) && seen.left; + expect( + rejectedUpfront || rejectedAfterJoin, + `pending join must be rejected with 4401 (upfront=${String(joinError)} after=${JSON.stringify(seen.errors)})`, + ).toBe(true); + + // Settling window for the delayed confidential sends (they fire 200 ms + // after completion when scheduled): nothing may arrive late. + await new Promise((resolve) => setTimeout(resolve, 800)); + expect(seen.presenceRecent, 'rejected join must not receive presence_recent').toBe(false); + expect(seen.fullState, 'rejected join must not receive full_state').toBe(false); + + // The room holds no player of the revoked identity: nothing was announced + // to the observer, and its synced state carries no such player. + expect( + observedJoins.filter((m) => (m as { identity?: unknown }).identity === revoked.id), + 'no player_joined for the revoked identity', + ).toHaveLength(0); + const observerIdentities: unknown[] = []; + for (const player of observerRoom.state.players.values()) { + observerIdentities.push((player as { identity?: unknown }).identity); + } + expect(observerIdentities, 'room state holds no player of the revoked identity').not.toContain(revoked.id); + + await leaveQuietly(revokedRoom, () => seen.left); + await leaveQuietly(observerRoom, () => false); + }, 60_000); +}); diff --git a/apps/server/src/rooms/lifecycle/worldAccess.tenants.integration.test.ts b/apps/server/src/rooms/lifecycle/worldAccess.tenants.integration.test.ts new file mode 100644 index 00000000..f00f12ed --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccess.tenants.integration.test.ts @@ -0,0 +1,264 @@ +/** + * Revocation and the room access sweep must use the verified client + * tenant, not the room slug. + * + * A real Colyseus server with the real `WorldRoom` (see + * testUtils/matchmakeHarness.ts), a real PostgreSQL database (db.js is NOT + * mocked) and real @colyseus/sdk clients. ZONE_PRIVACY_TENANT_ENFORCE stays + * unset, so the legacy mixed-room join is admitted at join time. + * + * Before the R3 fix the sweep reads only `room.metadata.tenant` and every + * room listens only on its own `access_revoked:` channel: + * 1. an allowed mixed-room client (member of A in M's room) is swept as + * `not_member_of_tenant`, although its verified tenant A still grants + * access; + * 2. with a missing metadata tenant the sweep skips the room entirely, so a + * client whose membership is gone stays connected; + * 3. a revocation in A never reaches the client's session in M's room; + * 4. deleting an operator account (no membership in A) never reaches A's room; + * 5. control: a second member of A in the same room is unaffected by 3. + */ + +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { getJwtSecret } from '../../api/utils/authHelpers.js'; +import { hashSessionToken } from '../../api/utils/sessionAuth.js'; +import { deleteAccount, removeMemberFromTenant } from '../../services/accountDeletion.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('worldAccess.tenants.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const packUuids: string[] = []; +let server: MatchmakeTestServer; +let previousGameServer: typeof global.gameServer; +let tenantAId: string; +let tenantASlug: string; +let tenantMSlug: string; +let fixturePackUuid = ''; + +/** + * One global (tenantId null) avatar pack so a join that passes onAuth can run + * to completion. Real fixture row, not a mock: without any pack in scope even + * a fully authorized join is refused later in onJoin with 526. + */ +async function seedGlobalAvatarPack(): Promise { + const uuid = `s1r3-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'tenant join fixture', + author: 's1r3-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +async function createTenant(slug: string): Promise { + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser( + memberships: Array<{ tenantId: string; role: Role; expiresAt?: Date }>, + sessionTenantId: string, +): Promise<{ id: string; token: string }> { + const user = await prisma.user.create({ + data: { + email: `s1r3-${crypto.randomUUID()}@example.test`, + avatarId: `${fixturePackUuid}:business_man`, + }, + }); + userIds.push(user.id); + for (const m of memberships) await prisma.membership.create({ data: { userId: user.id, ...m } }); + const token = jwt.sign({ sub: user.id, tid: sessionTenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, token }; +} + +interface TrackedJoin { + room?: Room; + error?: unknown; + left: boolean; + errorMessages: unknown[]; +} + +function joinOptions(tenant?: string): Record { + return { + ...(tenant ? { tenant } : {}), + // A real client always names its avatar; without one even an authorized + // join stops later in onJoin (526), which would blur this gate's signal. + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; +} + +async function joinWorld(identity: string, token: string, tenant?: string): Promise { + const client = new Client(server.base); + client.auth.token = token; + const tracked: TrackedJoin = { left: false, errorMessages: [] }; + try { + const room = await client.joinOrCreate('world', joinOptions(tenant)); + tracked.room = room; + room.onLeave(() => { + tracked.left = true; + }); + room.onError((code, message) => { + tracked.errorMessages.push({ code, message }); + }); + } catch (error) { + tracked.error = error; + } + return tracked; +} + +/** Real waiting with polling on the condition, never a fixed sleep as proof. */ +async function waitFor(left: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!left()) { + if (Date.now() > deadline) throw new Error(`condition not met within ${timeoutMs} ms`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +/** Cleanup-only leave: never fail the test, never hang on an already swept room. */ +async function leaveQuietly(join: TrackedJoin): Promise { + if (join.left || !join.room) return; + await Promise.race([join.room.leave().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 3_000))]); +} + +beforeAll(async () => { + tenantASlug = `s1r3-a-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + tenantMSlug = `s1r3-m-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + tenantAId = await createTenant(tenantASlug); + await createTenant(tenantMSlug); + await seedGlobalAvatarPack(); + server = await startMatchmakeServer(); + // Revocation events flow through the server presence, as in production + // (index.ts exposes the Colyseus server globally for broadcasters). + previousGameServer = global.gameServer; + global.gameServer = server.gameServer; +}); + +beforeEach(async () => { + await disposeAllRooms(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +afterAll(async () => { + await stopMatchmakeServer(server); + global.gameServer = previousGameServer; + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('verified client tenant wins over the room slug (real database)', () => { + it('keeps an allowed mixed-room client and sweeps one whose tenant is gone', async () => { + // Fall 2 first, on the empty server: without options.tenant the join + // creates a room whose metadata is DEFAULT_TENANT_SLUG. + const missingSlug = `s1r3-gone-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + vi.stubEnv('DEFAULT_TENANT_SLUG', missingSlug); + const gone = await createUser([{ tenantId: tenantAId, role: 'member' }], tenantAId); + const goneJoin = await joinWorld(gone.id, gone.token); + expect(goneJoin.error, 'Fall 2: Beitritt ohne Tenant muss gelingen').toBeUndefined(); + // Direct membership removal, without any revocation event. + await prisma.membership.deleteMany({ where: { userId: gone.id } }); + + // Fall 1: member of A in the room of M (M exists, the join is allowed + // while ZONE_PRIVACY_TENANT_ENFORCE is unset). + const mixed = await createUser([{ tenantId: tenantAId, role: 'member' }], tenantAId); + const mixedJoin = await joinWorld(mixed.id, mixed.token, tenantMSlug); + expect(mixedJoin.error, 'Fall 1: Mischraum-Beitritt muss gelingen').toBeUndefined(); + + // One shared wait for both cases: at least one full pre-fix 60 s sweep. + await new Promise((resolve) => setTimeout(resolve, 65_000)); + + console.log( + `[s1r3-rot] nach 65 s: Fall 1 (Mischraum) verbunden=${String(!mixedJoin.left)} ` + + `Fehler=${JSON.stringify(mixedJoin.errorMessages)} | Fall 2 (Metadaten-Tenant fehlt) ` + + `verbunden=${String(!goneJoin.left)} Fehler=${JSON.stringify(goneJoin.errorMessages)}`, + ); + expect( + mixedJoin.left, + `Fall 1: Mischraum-Client muss verbunden bleiben, Fehler=${JSON.stringify(mixedJoin.errorMessages)}`, + ).toBe(false); + await waitFor(() => goneJoin.left, 5_000); + expect(goneJoin.left, 'Fall 2: Client ohne Metadaten-Tenant muss getrennt sein').toBe(true); + + await leaveQuietly(mixedJoin); + await leaveQuietly(goneJoin); + }, 120_000); + + it('ends the mixed-room session on revocation in its own tenant, nobody else', async () => { + const staying = await createUser([{ tenantId: tenantAId, role: 'member' }], tenantAId); + const revoked = await createUser([{ tenantId: tenantAId, role: 'member' }], tenantAId); + const stayingJoin = await joinWorld(staying.id, staying.token, tenantMSlug); + const revokedJoin = await joinWorld(revoked.id, revoked.token, tenantMSlug); + expect(stayingJoin.error).toBeUndefined(); + expect(revokedJoin.error).toBeUndefined(); + expect(stayingJoin.room?.roomId).toBe(revokedJoin.room?.roomId); + + await removeMemberFromTenant(prisma, { userId: revoked.id, tenantId: tenantAId }); + + // Fall 3: the revocation in A must end the session in M's room at once. + await waitFor(() => revokedJoin.left, 3_000); + expect(revokedJoin.left, 'Fall 3: entzogener Client muss getrennt sein').toBe(true); + // Fall 5 (Gegenprobe): the other member of A in the same room stays. + expect(stayingJoin.left, 'Fall 5: zweites Mitglied von A bleibt verbunden').toBe(false); + + await leaveQuietly(stayingJoin); + await leaveQuietly(revokedJoin); + }, 30_000); + + it('ends the world session of a deleted operator account', async () => { + const existing = await prisma.tenant.findUnique({ where: { slug: 'internal' } }); + const internalId = existing?.id ?? (await createTenant('internal')); + const createdInternal = !existing; + try { + const operator = await createUser([{ tenantId: internalId, role: 'owner' }], tenantAId); + const operatorJoin = await joinWorld(operator.id, operator.token, tenantASlug); + expect(operatorJoin.error, 'Fall 4: Betreiber-Beitritt muss gelingen').toBeUndefined(); + + // Fall 4: account deletion publishes no slug of A, yet A's room must end + // the operator session at once. + await deleteAccount(prisma, operator.id); + await waitFor(() => operatorJoin.left, 3_000); + expect(operatorJoin.left, 'Fall 4: Betreiber muss nach Kontoloeschung getrennt sein').toBe(true); + + await leaveQuietly(operatorJoin); + } finally { + if (createdInternal) await prisma.tenant.deleteMany({ where: { id: internalId } }); + } + }, 30_000); +}); diff --git a/apps/server/src/rooms/lifecycle/worldAccess.ts b/apps/server/src/rooms/lifecycle/worldAccess.ts new file mode 100644 index 00000000..55f123d2 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccess.ts @@ -0,0 +1,346 @@ +import { ServerError, type Client } from 'colyseus'; +import { logger } from '../../logger.js'; +import { createPrismaClient } from '../../db.js'; +import { hasTenantAccess } from '../../api/utils/tenantMembership.js'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { AUTH_REJECTED_CODE, type WorldAuth } from './onAuth.js'; +import { enqueueAvRevocation } from './avPendingRevocations.js'; +import { applyAccessProof, rescheduleWorldAccessLeaseTimer } from './worldAccessLease.js'; +import type { Player, WorldRoom } from '../WorldRoom.js'; + +/** Distinct close/error code for an expired guest (matches checkGuestExpired). */ +const GUEST_EXPIRED_CODE = 4006; + +/** + * Per-client world access: every human client the room accepted is + * tracked with its VERIFIED tenant, so revocation and the access sweep check + * the tenant the session belongs to — never the room slug. + * + * An entry counts as joined when `room.state.players` holds its sessionId, + * else as joining; there is no separate state flag (`completePendingJoin` + * owns the player map). NPC joins carry no tenant and get no entry. + */ + +type AccessPrisma = Pick; + +export interface WorldAccessEntry { + sessionId: string; + userId: string; + tenantId: string; + tenantSlug: string; + /** Database session id from `WorldAuth.sessionId`. Null fails closed. */ + authSessionId: string | null; + epoch: number; + leaseUntil: number | null; + accessExpiresAt: number | null; +} + +export type WorldAccessCheck = { ok: boolean; expiresAt: Date | null }; + +export type WorldAccessDenial = 'session_revoked' | 'guest_expired' | 'not_member_of_tenant'; + +/** + * Database session id carried on `WorldAuth`. `sessionId` wins. The optional + * bridge field is the same id for callers that have not moved yet. + */ +function sessionIdFromAuth(auth: WorldAuth): string | null { + if (typeof auth.sessionId === 'string' && auth.sessionId.length > 0) return auth.sessionId; + if (typeof auth.authSessionId === 'string' && auth.authSessionId.length > 0) return auth.authSessionId; + return null; +} + +/** Session row for this id and user, still in the future. Missing or mismatched fails closed. */ +async function loadBoundSession( + prisma: AccessPrisma, + userId: string, + sessionId: string | null, +): Promise<{ expiresAt: Date } | null> { + if (!sessionId) return null; + const now = new Date(); + const rows = await prisma.session.findMany({ + where: { id: { in: [sessionId] }, userId, expiresAt: { gt: now } }, + select: { id: true, userId: true, expiresAt: true }, + }); + const row = rows.find((candidate) => candidate.id === sessionId && candidate.userId === userId); + if (!row || row.expiresAt.getTime() <= now.getTime()) return null; + return { expiresAt: row.expiresAt }; +} + +/** + * Deadline only. A membership expiry that is already past is not applied: + * `hasTenantAccess` has already allowed the subject, and the past date must + * not take the seat away. No membership expiry leaves the session expiry. + */ +function accessDeadline(membershipExpiresAt: Date | null, sessionExpiresAt: Date): Date { + if (membershipExpiresAt === null) return sessionExpiresAt; + if (membershipExpiresAt.getTime() <= Date.now()) return sessionExpiresAt; + const sessionMs = sessionExpiresAt.getTime(); + return membershipExpiresAt.getTime() < sessionMs ? membershipExpiresAt : sessionExpiresAt; +} + +/** + * Fresh proof for `userId` in `tenantId` on `sessionId`. Grant is only + * `hasTenantAccess`. The session row must exist, belong to `userId` and still + * be open. `expiresAt` is the earlier of that session expiry and a still-open + * membership expiry, and is never itself a grant. Database errors propagate. + * A missing row is `{ ok: false }`. + */ +export async function readWorldAccess( + prisma: AccessPrisma, + userId: string, + tenantId: string, + sessionId: string | null, +): Promise { + const session = await loadBoundSession(prisma, userId, sessionId); + if (!session) return { ok: false, expiresAt: null }; + if (!(await hasTenantAccess(prisma, userId, tenantId))) return { ok: false, expiresAt: null }; + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId, userId } }, + select: { expiresAt: true }, + }); + return { ok: true, expiresAt: accessDeadline(membership?.expiresAt ?? null, session.expiresAt) }; +} + +/** Why a failed proof ends the seat. Not a second grant. */ +export async function classifyDeniedAccess( + prisma: AccessPrisma, + userId: string, + tenantId: string, + sessionId: string | null, +): Promise { + const session = await loadBoundSession(prisma, userId, sessionId); + if (!session) return 'session_revoked'; + const membership = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId, userId } }, + select: { role: true, expiresAt: true }, + }); + const guestLapsed = + membership?.role === 'guest' && membership.expiresAt !== null && membership.expiresAt.getTime() <= Date.now(); + if (guestLapsed) return 'guest_expired'; + return 'not_member_of_tenant'; +} + +export function denialClose(reason: WorldAccessDenial): { code: number; message: string } { + if (reason === 'guest_expired') return { code: GUEST_EXPIRED_CODE, message: 'guest_expired' }; + if (reason === 'session_revoked') return { code: AUTH_REJECTED_CODE, message: 'session_revoked' }; + return { code: AUTH_REJECTED_CODE, message: 'not_member_of_tenant' }; +} + +async function deniedReason(prisma: AccessPrisma, entry: WorldAccessEntry): Promise { + try { + return await classifyDeniedAccess(prisma, entry.userId, entry.tenantId, entry.authSessionId); + } catch (e) { + logger.warn({ + event: 'world.access_revoked_check_failed', + userId: entry.userId, + tenantId: entry.tenantId, + error: String(e), + }); + return 'not_member_of_tenant'; + } +} + +export class WorldAccessRegistry { + private readonly entries = new Map(); + + constructor(private readonly room: WorldRoom) {} + + /** + * Track a verified human join; NPC joins get no entry. Fail-closed. + * Supplements a pending entry left by `registerPending` (keeps its epoch, + * so a revocation that arrived mid-join survives); creates a fresh entry + * (epoch 0) when there is none. + */ + register(sessionId: string, auth: WorldAuth): void { + if (auth.isNpc) return; + if (!auth.tenantId || !auth.tenantSlug) { + throw new ServerError(AUTH_REJECTED_CODE, 'tenant_unresolved'); + } + const provenSessionId = sessionIdFromAuth(auth); + const pending = this.entries.get(sessionId); + if (pending) { + pending.userId = auth.identity; + pending.tenantId = auth.tenantId; + pending.tenantSlug = auth.tenantSlug; + pending.authSessionId = provenSessionId ?? pending.authSessionId; + return; + } + this.entries.set(sessionId, { + sessionId, + userId: auth.identity, + tenantId: auth.tenantId, + tenantSlug: auth.tenantSlug, + authSessionId: provenSessionId, + epoch: 0, + leaseUntil: null, + accessExpiresAt: null, + }); + } + + /** + * Preliminary entry for a session whose token just verified, before its + * tenant membership was proven. Carries no tenant slug yet; `register` + * completes it after the full authentication. Never resets the epoch, and + * never throws: a failed insert must not break the join it protects. + */ + registerPending(sessionId: string, userId: string, tenantId: string | undefined): void { + const existing = this.entries.get(sessionId); + if (existing) { + existing.userId = userId; + if (tenantId) existing.tenantId = tenantId; + return; + } + this.entries.set(sessionId, { + sessionId, + userId, + tenantId: tenantId ?? '', + tenantSlug: '', + authSessionId: null, + epoch: 0, + leaseUntil: null, + accessExpiresAt: null, + }); + } + + /** Raw entry lookup for the join gate; the epoch comparison pins it. */ + entryFor(sessionId: string): WorldAccessEntry | undefined { + return this.entries.get(sessionId); + } + + /** + * True once the session's player is published — and only then — so + * confidential sends after `players.set` can re-check it right before + * `client.send`. NPC players have no entry and always pass. + */ + isJoined(sessionId: string): boolean { + const player = this.room.state.players.get(sessionId); + if (!player) return false; + if (player.isNpc) return true; + return this.entries.has(sessionId); + } + + forget(sessionId: string): void { + this.entries.delete(sessionId); + rescheduleWorldAccessLeaseTimer(this.room); + } + + clear(): void { + this.entries.clear(); + } + + /** Entries whose session already published its player (joined, not joining). */ + joined(): WorldAccessEntry[] { + return [...this.entries.values()].filter((e) => this.room.state.players.has(e.sessionId)); + } + + private disconnect(sessionId: string, code: number, reason: string): void { + const client = this.room.clients.find((c) => c.sessionId === sessionId); + if (!client) return; + try { + client.error(code, reason); + } catch { + /* best-effort: the client may already be gone */ + } + client.leave(1000); + } + + /** Re-prove one joined entry. True when the lease was renewed. + * A database error renews nothing and leaves the current lease in place. */ + private async reprove(prisma: AccessPrisma, entry: WorldAccessEntry): Promise { + let check: WorldAccessCheck; + try { + check = await readWorldAccess(prisma, entry.userId, entry.tenantId, entry.authSessionId); + } catch (e) { + logger.warn({ + event: 'world.access_revoked_check_failed', + userId: entry.userId, + tenantId: entry.tenantId, + error: String(e), + }); + return false; + } + if (check.ok) { + applyAccessProof(entry, check.expiresAt); + return true; + } + const close = denialClose(await deniedReason(prisma, entry)); + this.disconnect(entry.sessionId, close.code, close.message); + // Confirmed AV removal: the world send ends at once, the call ends once + // the backlog proves it. The process-wide backlog survives leave/dispose. + enqueueAvRevocation(`${entry.tenantSlug}:world`, entry.userId); + return false; + } + + /** Per-user revocation: bump every entry of `userId`, then re-prove each JOINED + * session against its stored database session id and verified tenant. A failed + * proof disconnects and leaves the tenant calls. A database error renews + * nothing; the lease still ends the seat. */ + async revoke(userId: string): Promise { + const owned = [...this.entries.values()].filter((e) => e.userId === userId); + if (owned.length === 0) return; + for (const entry of owned) entry.epoch += 1; + const prisma = this.room.prismaForPresence ?? createPrismaClient(); + let renewed = false; + for (const entry of owned) { + if (!this.room.state.players.has(entry.sessionId)) continue; + if (await this.reprove(prisma, entry)) renewed = true; + } + if (renewed) rescheduleWorldAccessLeaseTimer(this.room); + } +} + +export function createWorldAccess(room: WorldRoom): WorldAccessRegistry { + return new WorldAccessRegistry(room); +} + +/** Best-effort reject: the client may already be gone. */ +function rejectJoin(room: WorldRoom, client: Client, code: number, reason: string): void { + try { + client.error(code, reason); + } catch { + /* best-effort: the client may already be gone */ + } + room.worldAccess.forget(client.sessionId); + client.leave(1000); +} + +/** + * Final access proof before a joining player becomes visible + * (`completePendingJoin` calls this instead of setting the player directly). + * Snapshots the entry epoch, re-proves `hasTenantAccess` and the stored + * database session id, then — synchronously, without another `await` — + * publishes the player only when the entry still exists, its epoch is + * unchanged and the proof holds. Anything else rejects the join fail-closed + * (a database error too). A published player carries a fresh access lease + * (see worldAccessLease.ts). Returns true when the player was published. + */ +export async function admitPlayer(room: WorldRoom, client: Client, player: Player): Promise { + if (player.isNpc) { + room.state.players.set(client.sessionId, player); + return true; + } + const entry = room.worldAccess.entryFor(client.sessionId); + if (!entry) { + rejectJoin(room, client, AUTH_REJECTED_CODE, 'not_member_of_tenant'); + return false; + } + const epoch = entry.epoch; + const prisma = room.prismaForPresence ?? createPrismaClient(); + let check: WorldAccessCheck; + try { + check = await readWorldAccess(prisma, entry.userId, entry.tenantId, entry.authSessionId); + } catch { + rejectJoin(room, client, AUTH_REJECTED_CODE, 'not_member_of_tenant'); + return false; + } + const current = room.worldAccess.entryFor(client.sessionId); + if (current && current.epoch === epoch && check.ok) { + room.state.players.set(client.sessionId, player); + applyAccessProof(current, check.expiresAt); + rescheduleWorldAccessLeaseTimer(room); + return true; + } + const close = denialClose(await deniedReason(prisma, entry)); + rejectJoin(room, client, close.code, close.message); + return false; +} diff --git a/apps/server/src/rooms/lifecycle/worldAccessLease.test.ts b/apps/server/src/rooms/lifecycle/worldAccessLease.test.ts new file mode 100644 index 00000000..649742b4 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccessLease.test.ts @@ -0,0 +1,62 @@ +/** + * An expired lease entry must be forgotten when it is + * disconnected. Otherwise the entry stays joined until `onLeave`, the timer + * re-plans with a 0 ms delay and the disconnect (plus the AV cleanup) repeats + * in a loop for a client that never answers the close. + * + * Unit test, no database: a real `WorldAccessRegistry` over a room double + * (as in worldAccess.integration.test.ts), whose client only counts `error` + * and `leave` and never triggers `onLeave`. The entry is joined with a + * `leaseUntil` in the past; after rescheduling and 100 ms of virtual time + * the client must have errored exactly once. Before the fix it errors + * repeatedly. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { WorldRoom } from '../WorldRoom.js'; +import { createWorldAccess } from './worldAccess.js'; +import { clearWorldAccessLeaseTimer, rescheduleWorldAccessLeaseTimer } from './worldAccessLease.js'; + +function expiredLeaseRoom(): { + room: WorldRoom; + error: ReturnType; + leave: ReturnType; +} { + const error = vi.fn(); + const leave = vi.fn(); + const room = { + state: { players: new Map([['sess-1', { identity: 'user-1' }]]) }, + clients: [{ sessionId: 'sess-1', error, leave }], + } as unknown as WorldRoom; + room.worldAccess = createWorldAccess(room); + room.worldAccess.register('sess-1', { + identity: 'user-1', + tenantId: 'tenant-1', + tenantSlug: 'tenant-1', + isNpc: false, + zonePrivacyVersion: 1, + }); + const entry = room.worldAccess.entryFor('sess-1'); + if (!entry) throw new Error('test setup: registry entry missing'); + entry.leaseUntil = Date.now() - 1_000; + entry.accessExpiresAt = null; + return { room, error, leave }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('expired world access leases are forgotten once disconnected', () => { + it('errors the client exactly once for an expired lease', async () => { + const { room, error } = expiredLeaseRoom(); + try { + vi.useFakeTimers(); + rescheduleWorldAccessLeaseTimer(room); + await vi.advanceTimersByTimeAsync(100); + } finally { + clearWorldAccessLeaseTimer(room); + vi.useRealTimers(); + } + expect(error).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/server/src/rooms/lifecycle/worldAccessLease.ts b/apps/server/src/rooms/lifecycle/worldAccessLease.ts new file mode 100644 index 00000000..b531d750 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccessLease.ts @@ -0,0 +1,141 @@ +import { logger } from '../../logger.js'; +import { enqueueAvRevocation } from './avPendingRevocations.js'; +import type { WorldAccessEntry } from './worldAccess.js'; +import type { WorldRoom } from '../WorldRoom.js'; + +/** + * Bounded access lease for joined world sessions. Every joined + * entry carries `leaseUntil = min(now + WORLD_ACCESS_LEASE_MS, + * accessExpiresAt ?? Infinity)`: a session the room can no longer verify + * (revocation publish lost, database unreachable) ends at the latest when + * the lease runs out, instead of staying until the next successful sweep. + * A stored access deadline always wins over the lease window. + */ + +/** Close/error code for a session whose access could not be re-verified. */ +export const WORLD_ACCESS_UNVERIFIED_CODE = 4503; + +const GUEST_EXPIRED_CODE = 4006; + +const DEFAULT_SWEEP_MS = 30_000; +const DEFAULT_LEASE_MS = 120_000; +/** `setTimeout` throws above 2^31 - 1; cap the delay instead. */ +const MAX_TIMER_DELAY_MS = 2_147_483_647; + +export interface WorldAccessTiming { + sweepMs: number; + leaseMs: number; +} + +function readPositiveInt(name: string, fallback: number): number { + const raw = process.env[name]; + if (raw === undefined) return fallback; + const parsed = Number(raw); + if (!Number.isInteger(parsed) || parsed <= 0) return fallback; + return parsed; +} + +/** + * Sweep and lease cadence from the environment. Non-numeric, non-positive + * or non-integer values fall back to the defaults; a lease shorter than two + * sweeps cannot renew in time, so both values fall back with a warning. + */ +export function resolveWorldAccessTiming(): WorldAccessTiming { + const sweepMs = readPositiveInt('WORLD_ACCESS_SWEEP_MS', DEFAULT_SWEEP_MS); + const leaseMs = readPositiveInt('WORLD_ACCESS_LEASE_MS', DEFAULT_LEASE_MS); + if (leaseMs < 2 * sweepMs) { + logger.warn({ event: 'world.access_timing_invalid', sweepMs, leaseMs }); + return { sweepMs: DEFAULT_SWEEP_MS, leaseMs: DEFAULT_LEASE_MS }; + } + return { sweepMs, leaseMs }; +} + +/** + * Stamp a fresh proof onto an entry. The lease ends at the earlier of + * now plus the lease duration and `expiresAt` (omitted when there is no + * deadline). Call it whenever an access check succeeded — the join gate, + * the revocation handler and the sweep. + */ +export function applyAccessProof(entry: WorldAccessEntry, expiresAt: Date | null): void { + const { leaseMs } = resolveWorldAccessTiming(); + const now = Date.now(); + const accessExpiresAt = expiresAt ? expiresAt.getTime() : null; + entry.accessExpiresAt = accessExpiresAt; + entry.leaseUntil = Math.min(now + leaseMs, accessExpiresAt ?? Number.POSITIVE_INFINITY); +} + +const leaseTimers = new WeakMap>(); + +export function clearWorldAccessLeaseTimer(room: WorldRoom): void { + const timer = leaseTimers.get(room); + if (timer !== undefined) { + clearTimeout(timer); + leaseTimers.delete(room); + } +} + +/** Best-effort reject: the client may already be gone. */ +function disconnectLeaseEntry(room: WorldRoom, entry: WorldAccessEntry, code: number, reason: string): void { + const client = room.clients.find((c) => c.sessionId === entry.sessionId); + if (!client) return; + try { + client.error(code, reason); + } catch { + /* best-effort: the client may already be gone */ + } + client.leave(1000); +} + +/** + * Room-local expiry pass, without any database access: every joined entry + * whose lease ran out is disconnected. A stored access deadline that has + * passed disconnects with 4006 `guest_expired`; anything else can no longer + * be verified and disconnects with 4503 `access_unverified`. AV calls end + * in both cases. + */ +export async function expireWorldAccessLeases(room: WorldRoom): Promise { + const now = Date.now(); + const expired = room.worldAccess.joined().filter((e) => e.leaseUntil !== null && e.leaseUntil <= now); + for (const entry of expired) { + if (entry.accessExpiresAt !== null && entry.accessExpiresAt <= now) { + disconnectLeaseEntry(room, entry, GUEST_EXPIRED_CODE, 'guest_expired'); + } else { + disconnectLeaseEntry(room, entry, WORLD_ACCESS_UNVERIFIED_CODE, 'access_unverified'); + } + // Forget the entry at once, even when no client was found: otherwise it + // stays joined until onLeave, the timer re-plans with no delay and the + // disconnect repeats in a loop. + room.worldAccess.forget(entry.sessionId); + // Confirmed AV removal through the process-wide backlog (see worldAccess.ts). + enqueueAvRevocation(`${entry.tenantSlug}:world`, entry.userId); + } +} + +/** + * Plan the room's expiry pass at the earliest joined lease. Re-plan on + * admit/renew/forget; the timer needs no database and is cleared on dispose. + */ +export function rescheduleWorldAccessLeaseTimer(room: WorldRoom): void { + clearWorldAccessLeaseTimer(room); + const now = Date.now(); + let earliest: number | null = null; + for (const entry of room.worldAccess.joined()) { + if (entry.leaseUntil === null) continue; + if (earliest === null || entry.leaseUntil < earliest) earliest = entry.leaseUntil; + } + if (earliest === null) return; + const delay = Math.min(Math.max(earliest - now, 0), MAX_TIMER_DELAY_MS); + leaseTimers.set( + room, + setTimeout(() => { + leaseTimers.delete(room); + void expireWorldAccessLeases(room) + .catch((e: unknown) => { + logger.warn('[WorldRoom] Room access lease expiry failed', e); + }) + .finally(() => { + rescheduleWorldAccessLeaseTimer(room); + }); + }, delay), + ); +} diff --git a/apps/server/src/rooms/lifecycle/worldAccessSecurity.integration.test.ts b/apps/server/src/rooms/lifecycle/worldAccessSecurity.integration.test.ts new file mode 100644 index 00000000..f4160f54 --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldAccessSecurity.integration.test.ts @@ -0,0 +1,539 @@ +/** + * World authentication and live world access through the real stack. + * + * A real Colyseus server with the real `WorldRoom` (see + * testUtils/matchmakeHarness.ts), a real PostgreSQL database (db.js is NOT + * mocked) and real @colyseus/sdk clients. The HTTP API the loadtest login + * needs runs on the same server through `configureApp` (cookieParser, the + * tenant middleware and registerApi, as in the tenant isolation test). + * + * Ten cases below fail on the unfixed basis: matchmaking without a + * session reserves a seat, a consumed seat survives its deleted session row + * through the session cache, a running member flagged for verification is + * neither swept nor revoked, an old protocol version is admitted while the + * enforcement flag is missing or false, insecure service secrets and + * record-less service joins are admitted, and the legacy loadtest bot never + * presents the account credentials. The nine controls hold with and without + * the fix: a room slug that is not the session tenant is admitted with a + * warning while the tenant enforcement is off and refused while it is on, + * and a session whose tenant claim names a foreign tenant is refused. + */ + +import cookieParser from 'cookie-parser'; +import crypto from 'crypto'; +import express from 'express'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import type { AuthContext } from 'colyseus'; +import { MIN_ZONE_PRIVACY_CLIENT_VERSION, ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import { createPrismaClient } from '../../db.js'; +import { registerApi } from '../../api.js'; +import { tenantMiddleware } from '../../tenancy.js'; +import { validateSessionToken } from '../../api/utils/sessionAuth.js'; +import { broadcastAccessRevoked } from '../../api/utils/broadcast.js'; +import { logger } from '../../logger.js'; +import { AUTH_REJECTED_CODE, CLIENT_TOO_OLD_CODE, authenticateWorldJoin } from './onAuth.js'; +import { cleanupTenants, issueSession, seedMember, seedTenant } from '../../testUtils/worldSeed.js'; +import { + disposeAllRooms, + matchmake, + rawPost, + startMatchmakeServer, + stopMatchmakeServer, + worldRooms, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; +import { spawnColyseusBot } from '../../../../loadtest/src/workers/colyseusBot.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('worldAccessSecurity.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const FILE = 'worldAccessSecurity.integration.test.ts'; +const FORGED_HEADER_IP = '203.0.113.9'; +/** The warning the room logs when it admits a slug that is not the session tenant. */ +const ADMITTED_MISMATCH_WARNING = + '[WorldRoom] Admitted join with options.tenant != authenticated tenant (enforcement off)'; + +process.env.DEFAULT_TENANT_SLUG = `wsec-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + +const prisma = createPrismaClient(); +const packUuids: string[] = []; +let server: MatchmakeTestServer; +let previousGameServer: typeof global.gameServer; +let tenantId = ''; +let tenantSlug = ''; +let fixturePackUuid = ''; +/** Tenants the slug cases add; the cleanup list removes them with the default one. */ +const extraTenantIds: string[] = []; + +/** + * One global (tenantId null) avatar pack so a join that passes the gate can + * run to completion. Real fixture row, not a mock: without any pack in scope + * even a fully authorized join is refused later in onJoin. + */ +async function seedGlobalAvatarPack(): Promise { + const uuid = `wsec-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'world access join fixture', + author: 'wsec-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +function baseJoinOptions(): Record { + return { + tenant: tenantSlug, + // A real client always names its avatar; without one even an authorized + // join stops later in onJoin, which would blur the gate's signal. + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }; +} + +interface TrackedJoin { + room?: Room; + error?: unknown; + left: boolean; + errorMessages: unknown[]; +} + +async function joinWorld( + identity: string, + token: string | undefined, + extra?: Record, +): Promise { + const client = new Client(server.base); + if (token) client.auth.token = token; + const tracked: TrackedJoin = { left: false, errorMessages: [] }; + try { + const room = await client.joinOrCreate('world', { ...baseJoinOptions(), identity, ...extra }); + tracked.room = room; + room.onLeave(() => { + tracked.left = true; + }); + room.onError((code, message) => { + tracked.errorMessages.push({ code, message }); + }); + } catch (error) { + tracked.error = error; + } + return tracked; +} + +/** Real waiting with polling on the condition, never a fixed sleep as proof. */ +async function waitForLeft(tracked: TrackedJoin, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!tracked.left) { + if (Date.now() > deadline) return false; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + return true; +} + +/** Cleanup-only leave: never fail the test, never hang on a swept room. */ +async function leaveQuietly(tracked: TrackedJoin): Promise { + if (tracked.left || !tracked.room) return; + await Promise.race([tracked.room.leave().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 3_000))]); +} + +/** + * Real waiting with polling on the condition: the client state reaches the + * client after the join resolved, so the roster is read with a deadline and + * never with a fixed sleep as proof. + */ +async function waitForPlayers(tracked: TrackedJoin, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const seen = tracked.room ? [...tracked.room.state.players.values()].map((player) => player.identity) : []; + if (seen.length > 0 || Date.now() > deadline) return seen; + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +/** Flag a membership as needing verification (field from the session basis). */ +async function setVerificationFlag(userId: string, flagged: boolean): Promise { + await prisma.membership.update({ + where: { tenantId_userId: { tenantId, userId } }, + data: { inviteVerificationRequired: flagged }, + }); +} + +/** Swap the service secret for one join; the caller restores in a finally. */ +function useServiceSecret(value: string | undefined): () => void { + const previous = process.env.NPC_SERVICE_SECRET; + if (value === undefined) delete process.env.NPC_SERVICE_SECRET; + else process.env.NPC_SERVICE_SECRET = value; + return () => { + if (previous === undefined) delete process.env.NPC_SERVICE_SECRET; + else process.env.NPC_SERVICE_SECRET = previous; + }; +} + +/** Swap the tenant-enforcement flag for one join; the caller restores it. */ +function useTenantEnforcement(value: string | undefined): () => void { + const previous = process.env.ZONE_PRIVACY_TENANT_ENFORCE; + if (value === undefined) delete process.env.ZONE_PRIVACY_TENANT_ENFORCE; + else process.env.ZONE_PRIVACY_TENANT_ENFORCE = value; + return () => { + if (previous === undefined) delete process.env.ZONE_PRIVACY_TENANT_ENFORCE; + else process.env.ZONE_PRIVACY_TENANT_ENFORCE = previous; + }; +} + +/** A second, real tenant whose slug a join can name; the cleanup list removes it. */ +async function seedSecondTenant(): Promise<{ id: string; slug: string }> { + const tenant = await seedTenant(prisma); + extraTenantIds.push(tenant.id); + return tenant; +} + +/** Join with an outdated protocol version under the given enforcement flag. */ +async function joinWithOldVersion(authFlag: string | undefined): Promise { + const previous = process.env.ZONE_PRIVACY_AUTH_ENFORCE; + try { + if (authFlag === undefined) delete process.env.ZONE_PRIVACY_AUTH_ENFORCE; + else process.env.ZONE_PRIVACY_AUTH_ENFORCE = authFlag; + const member = await seedMember(prisma, tenantId); + return await joinWorld(member.userId, member.token, { + zonePrivacyVersion: MIN_ZONE_PRIVACY_CLIENT_VERSION - 1, + }); + } finally { + if (previous === undefined) delete process.env.ZONE_PRIVACY_AUTH_ENFORCE; + else process.env.ZONE_PRIVACY_AUTH_ENFORCE = previous; + } +} + +function configureApi(app: express.Express): void { + app.use(cookieParser()); + app.use(express.json()); + app.use(tenantMiddleware as unknown as express.RequestHandler); + // Async wiring without awaits before listen: the first API request arrives + // long after this resolves, so the table is complete by then. + void registerApi(app); +} + +beforeAll(async () => { + vi.stubEnv('WORLD_ACCESS_SWEEP_MS', '1000'); + tenantSlug = process.env.DEFAULT_TENANT_SLUG as string; + tenantId = (await seedTenant(prisma, { slug: tenantSlug })).id; + await seedGlobalAvatarPack(); + await prisma.map.create({ data: { tenantId, name: 'office', meta: {} } }); + server = await startMatchmakeServer({ configureApp: configureApi }); + // Revocation events flow through the server presence, as in production + // (index.ts exposes the Colyseus server globally for broadcasters). + previousGameServer = global.gameServer; + global.gameServer = server.gameServer; +}); + +beforeEach(async () => { + await disposeAllRooms(); +}); + +afterAll(async () => { + vi.unstubAllEnvs(); + await stopMatchmakeServer(server); + global.gameServer = previousGameServer; + await prisma.presence.deleteMany({ where: { tenantId } }); + await prisma.room.deleteMany({ where: { tenantId } }); + await prisma.npc.deleteMany({ where: { tenantId } }); + await prisma.map.deleteMany({ where: { tenantId } }); + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await cleanupTenants(prisma, [tenantId, ...extraTenantIds]); + await prisma.$disconnect(); +}); + +describe('world matchmaking without a session', () => { + it('refuses a forged forwarded header without reserving a seat', async () => { + const body = JSON.stringify({ ...baseJoinOptions(), identity: 'wsec-stranger' }); + const status = await rawPost( + server, + { + 'content-type': 'application/json', + 'content-length': String(Buffer.byteLength(body)), + 'x-forwarded-for': FORGED_HEADER_IP, + }, + (req) => req.end(body), + ); + expect(status).not.toBe(200); + expect(await worldRooms()).toHaveLength(0); + }, 30_000); +}); + +describe('world matchmaking with a revoked session', () => { + it('refuses a deleted session without reserving a seat', async () => { + const member = await seedMember(prisma, tenantId); + await prisma.session.deleteMany({ where: { userId: member.userId } }); + const reservation = await matchmake(server, JSON.stringify(baseJoinOptions()), { + headers: { Cookie: `auth_token=${member.token}` }, + }); + expect(reservation.status).not.toBe(200); + expect(await worldRooms()).toHaveLength(0); + }, 30_000); +}); + +describe('world seat consumed after the session row is gone', () => { + it('rejects the join and publishes no player', async () => { + const member = await seedMember(prisma, tenantId); + const first = await joinWorld(member.userId, member.token); + expect(first.error, 'first join with a live session must succeed').toBeUndefined(); + // Fill the shared session cache, then remove the row it points at. + expect(await validateSessionToken(prisma, member.token)).not.toBeNull(); + await leaveQuietly(first); + await prisma.session.deleteMany({ where: { userId: member.userId } }); + + const second = await joinWorld(member.userId, member.token); + await leaveQuietly(second); + expect(second.error).toMatchObject({ code: AUTH_REJECTED_CODE }); + + const controlMember = await seedMember(prisma, tenantId); + const control = await joinWorld(controlMember.userId, controlMember.token); + try { + expect(control.error, 'control join must succeed').toBeUndefined(); + if (!control.room) throw new Error(`${FILE} control join created no room`); + const seen = [...control.room.state.players.values()].map((player) => player.identity); + expect(seen).not.toContain(member.userId); + } finally { + await leaveQuietly(control); + } + }, 30_000); +}); + +describe('running member flagged for verification', () => { + it('ends the world session on the next sweep', async () => { + const member = await seedMember(prisma, tenantId); + const tracked = await joinWorld(member.userId, member.token); + expect(tracked.error, 'join must succeed before the flag is set').toBeUndefined(); + if (!tracked.room) throw new Error(`${FILE} join created no room before the flag is set`); + await setVerificationFlag(member.userId, true); + const left = await waitForLeft(tracked, 8_000); + await leaveQuietly(tracked); + expect(left).toBe(true); + }, 30_000); + + it('ends the world session on the revocation event', async () => { + const member = await seedMember(prisma, tenantId); + const tracked = await joinWorld(member.userId, member.token); + expect(tracked.error, 'join must succeed before the flag is set').toBeUndefined(); + if (!tracked.room) throw new Error(`${FILE} join created no room before the flag is set`); + await setVerificationFlag(member.userId, true); + broadcastAccessRevoked(member.userId); + const left = await waitForLeft(tracked, 5_000); + await leaveQuietly(tracked); + expect(left).toBe(true); + }, 30_000); +}); + +describe('old zone protocol without enforcement', () => { + it('rejects an old client when the flag is missing', async () => { + const tracked = await joinWithOldVersion(undefined); + await leaveQuietly(tracked); + expect(tracked.error).toMatchObject({ code: CLIENT_TOO_OLD_CODE }); + expect(tracked.room).toBeUndefined(); + }, 30_000); + + it('rejects an old client when the flag is false', async () => { + const tracked = await joinWithOldVersion('false'); + await leaveQuietly(tracked); + expect(tracked.error).toMatchObject({ code: CLIENT_TOO_OLD_CODE }); + expect(tracked.room).toBeUndefined(); + }, 30_000); +}); + +describe('insecure service secret', () => { + it('reserves no seat for any insecure secret variant', async () => { + const variants = [ + { name: 'missing', secret: undefined, presented: 'dev-npc-secret' }, + { name: 'blank', secret: ' ', presented: ' ' }, + { name: 'default', secret: 'dev-npc-secret', presented: 'dev-npc-secret' }, + { name: 'short', secret: 'x'.repeat(31), presented: 'x'.repeat(31) }, + ]; + for (const variant of variants) { + const restore = useServiceSecret(variant.secret); + try { + const identity = `npc-wsec-${variant.name}-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + const tracked = await joinWorld(identity, undefined, { serviceToken: variant.presented }); + await leaveQuietly(tracked); + expect(tracked.error, `variant ${variant.name} must be refused`).toMatchObject({ + code: AUTH_REJECTED_CODE, + }); + expect(tracked.room, `variant ${variant.name} must reserve nothing`).toBeUndefined(); + } finally { + restore(); + } + } + }, 30_000); +}); + +describe('service join without a matching record', () => { + it('reserves no seat without a record in the tenant', async () => { + const secret = crypto.randomBytes(32).toString('hex'); + const restore = useServiceSecret(secret); + try { + const identity = `npc-wsec-orphan-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + const tracked = await joinWorld(identity, undefined, { serviceToken: secret }); + await leaveQuietly(tracked); + expect(tracked.error).toMatchObject({ code: AUTH_REJECTED_CODE }); + expect(tracked.room).toBeUndefined(); + } finally { + restore(); + } + }, 30_000); +}); + +describe('regular account through the loadtest bot', () => { + it('reaches the world under the account identity', async () => { + const password = `wsec-${crypto.randomUUID()}`; + const member = await seedMember(prisma, tenantId, { + email: `wsec-${crypto.randomUUID()}@example.test`, + password, + }); + let joined: { userId?: unknown; stop?: () => Promise } | undefined; + let joinError: unknown; + try { + joined = await spawnColyseusBot({ apiBase: server.base, tenant: tenantSlug, email: member.email, password }); + } catch (error) { + joinError = error; + } + try { + expect(joinError, 'bot login and world join must succeed').toBeUndefined(); + expect(joined?.userId).toBe(member.userId); + } finally { + await joined?.stop?.(); + } + }, 30_000); +}); + +describe('proven sessions keep working', () => { + it('accepts a bearer session and a cookie session', async () => { + const member = await seedMember(prisma, tenantId); + const context = { headers: new Headers(), ip: '127.0.0.1' }; + const bearer = await authenticateWorldJoin(baseJoinOptions(), { ...context, token: member.token }, prisma); + expect(bearer.identity).toBe(member.userId); + const cookie = await authenticateWorldJoin( + baseJoinOptions(), + { ...context, headers: new Headers({ cookie: `auth_token=${member.token}` }) }, + prisma, + ); + expect(cookie.identity).toBe(member.userId); + const tracked = await joinWorld(member.userId, member.token); + await leaveQuietly(tracked); + expect(tracked.error).toBeUndefined(); + expect(tracked.room?.sessionId).toEqual(expect.any(String)); + }, 30_000); + + it('ignores a foreign identity option', async () => { + const member = await seedMember(prisma, tenantId); + const context = { token: member.token, headers: new Headers(), ip: '127.0.0.1' } as AuthContext; + const auth = await authenticateWorldJoin({ ...baseJoinOptions(), identity: 'wsec-stranger' }, context, prisma); + expect(auth.identity).toBe(member.userId); + const tracked = await joinWorld('wsec-stranger', member.token); + await leaveQuietly(tracked); + expect(tracked.error).toBeUndefined(); + }, 30_000); + + it('accepts the current protocol version', async () => { + const member = await seedMember(prisma, tenantId); + const tracked = await joinWorld(member.userId, member.token); + await leaveQuietly(tracked); + expect(tracked.error).toBeUndefined(); + expect(tracked.room?.sessionId).toEqual(expect.any(String)); + }, 30_000); + + it('refuses a join flagged before join', async () => { + const member = await seedMember(prisma, tenantId); + await setVerificationFlag(member.userId, true); + const tracked = await joinWorld(member.userId, member.token); + await leaveQuietly(tracked); + expect(tracked.error).toMatchObject({ code: AUTH_REJECTED_CODE }); + }, 30_000); + + it('keeps a valid session despite a forwarded header', async () => { + const member = await seedMember(prisma, tenantId); + const context = { + token: member.token, + headers: new Headers({ 'x-forwarded-for': FORGED_HEADER_IP, 'x-real-ip': FORGED_HEADER_IP }), + ip: FORGED_HEADER_IP, + } as AuthContext; + const auth = await authenticateWorldJoin(baseJoinOptions(), context, prisma); + expect(auth.identity).toBe(member.userId); + }, 30_000); + + it('admits a service client with a secure secret and a matching record', async () => { + const secret = crypto.randomBytes(32).toString('hex'); + const restore = useServiceSecret(secret); + const recordIdentity = `wsec-attendant-${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`; + await prisma.npc.create({ data: { tenantId, identity: recordIdentity, name: recordIdentity } }); + try { + const tracked = await joinWorld(`npc-${recordIdentity}`, undefined, { serviceToken: secret }); + await leaveQuietly(tracked); + expect(tracked.error).toBeUndefined(); + expect(tracked.room?.sessionId).toEqual(expect.any(String)); + } finally { + restore(); + } + }, 30_000); +}); + +describe('room slug and session tenant', () => { + it('admits a mismatched room slug with a warning while tenant enforcement is off', async () => { + const other = await seedSecondTenant(); + const member = await seedMember(prisma, tenantId); + const restore = useTenantEnforcement(undefined); + const warnSpy = vi.spyOn(logger, 'warn'); + try { + // A foreign identity option: the player must still carry the session identity. + const tracked = await joinWorld('wsec-stranger', member.token, { tenant: other.slug }); + try { + expect(tracked.error, 'the join must be admitted while tenant enforcement is off').toBeUndefined(); + if (!tracked.room) throw new Error(`${FILE} the admitted join created no room`); + const seen = await waitForPlayers(tracked, 5_000); + expect(seen, 'the player must carry the session identity').toContain(member.userId); + expect(seen, 'the client identity must not become the player identity').not.toContain('wsec-stranger'); + } finally { + await leaveQuietly(tracked); + } + expect(warnSpy).toHaveBeenCalledWith( + ADMITTED_MISMATCH_WARNING, + expect.objectContaining({ requested: other.slug, authenticated: tenantSlug }), + ); + } finally { + warnSpy.mockRestore(); + restore(); + } + }, 30_000); + + it('refuses a mismatched room slug while tenant enforcement is on', async () => { + const other = await seedSecondTenant(); + const member = await seedMember(prisma, tenantId); + const restore = useTenantEnforcement('true'); + try { + const tracked = await joinWorld(member.userId, member.token, { tenant: other.slug }); + await leaveQuietly(tracked); + expect(tracked.error).toMatchObject({ code: AUTH_REJECTED_CODE, message: 'tenant_mismatch' }); + expect(tracked.room).toBeUndefined(); + } finally { + restore(); + } + }, 30_000); + + it('refuses a session whose tenant claim names a foreign tenant', async () => { + const other = await seedSecondTenant(); + const member = await seedMember(prisma, tenantId); + // A live session whose `tid` claim names the other tenant; the user is a + // member of the default tenant only. + const foreign = await issueSession(prisma, member.userId, other.id); + const tracked = await joinWorld(member.userId, foreign.token, { tenant: other.slug }); + await leaveQuietly(tracked); + expect(tracked.error).toMatchObject({ code: AUTH_REJECTED_CODE }); + expect(tracked.room).toBeUndefined(); + }, 30_000); +}); diff --git a/apps/server/src/rooms/lifecycle/worldMatchmakeAuth.ts b/apps/server/src/rooms/lifecycle/worldMatchmakeAuth.ts new file mode 100644 index 00000000..bb2bfbdf --- /dev/null +++ b/apps/server/src/rooms/lifecycle/worldMatchmakeAuth.ts @@ -0,0 +1,29 @@ +import type { AuthContext } from 'colyseus'; +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import type { RoomOptions } from '../WorldRoom.js'; +import { authenticateWorldJoin, resolveRawAuthToken, type WorldAuth } from './onAuth.js'; + +/** + * Static world-room auth. Colyseus calls this before it reserves a seat. + * The raw token is the `token` argument, otherwise the `auth_token` cookie. + * The returned `WorldAuth` is stored as seat `authData` and must not carry + * the raw token. Matchmaking shares one Prisma client; the room keeps its + * own client for the join. + */ +let matchmakePrisma: PrismaClient | null = null; + +function getMatchmakePrisma(): PrismaClient { + if (!matchmakePrisma) matchmakePrisma = createPrismaClient(); + return matchmakePrisma; +} + +export async function authenticateWorldMatchmake( + token: string, + options: RoomOptions | undefined, + context: AuthContext, +): Promise { + const raw = resolveRawAuthToken(context, token); + const authContext: AuthContext = raw ? { ...context, token: raw } : context; + return authenticateWorldJoin(options, authContext, getMatchmakePrisma()); +} diff --git a/apps/server/src/rooms/validation/rejectionMetrics.ts b/apps/server/src/rooms/validation/rejectionMetrics.ts new file mode 100644 index 00000000..778b61bf --- /dev/null +++ b/apps/server/src/rooms/validation/rejectionMetrics.ts @@ -0,0 +1,16 @@ +import client from 'prom-client'; +import { registry } from '../../metrics.js'; + +export type RejectedPayloadType = 'move' | 'dnd_status' | 'editor_state'; +export type RejectedPayloadReason = 'schema' | 'bounds'; + +const worldPayloadRejectedTotal = new client.Counter({ + name: 'meetropolis_world_payload_rejected_total', + help: 'World and editor payloads rejected before state changed', + labelNames: ['type', 'reason'] as const, +}); +registry.registerMetric(worldPayloadRejectedTotal); + +export function countRejectedPayload(type: RejectedPayloadType, reason: RejectedPayloadReason): void { + worldPayloadRejectedTotal.labels(type, reason).inc(); +} diff --git a/apps/server/src/rooms/validation/worldPayloadSchemas.ts b/apps/server/src/rooms/validation/worldPayloadSchemas.ts new file mode 100644 index 00000000..b8730aac --- /dev/null +++ b/apps/server/src/rooms/validation/worldPayloadSchemas.ts @@ -0,0 +1,15 @@ +import { z } from 'zod'; + +export const moveSchema = z + .object({ + x: z.number().finite(), + y: z.number().finite(), + direction: z.enum(['up', 'down', 'left', 'right']), + }) + .strict(); + +export const dndSchema = z + .object({ + dnd: z.boolean(), + }) + .strict(); diff --git a/apps/server/src/rooms/validation/worldPayloads.integration.test.ts b/apps/server/src/rooms/validation/worldPayloads.integration.test.ts new file mode 100644 index 00000000..6dbfb769 --- /dev/null +++ b/apps/server/src/rooms/validation/worldPayloads.integration.test.ts @@ -0,0 +1,648 @@ +/** + * Runtime checks for move, do-not-disturb, and editor-state payloads. + * + * Real Colyseus (`testUtils/matchmakeHarness.ts`), real PostgreSQL (`db.js` is + * not mocked), and the HTTP API on the same server (`configureApp`: cookie + * parser, tenant middleware, `registerApi`). Seeds come from + * `testUtils/worldSeed.ts`. + * + * Ten cases fail on the unfixed basis: a move or do-not-disturb message is + * applied and broadcast as sent, and an editor body with a bad tileset, polygon, + * capacity, or zone type is stored. The rejection counter is absent there, so + * its value reads as 0. The controls hold on the unfixed basis and with the limits. + */ + +import cookieParser from 'cookie-parser'; +import crypto from 'crypto'; +import express from 'express'; +import { Counter } from 'prom-client'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { Client, type Room } from '@colyseus/sdk'; +import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; +import { createPrismaClient } from '../../db.js'; +import { registerApi } from '../../api.js'; +import { tenantMiddleware } from '../../tenancy.js'; +import { registry } from '../../metrics.js'; +import { cleanupTenants, seedMember, seedTenant, type SeededMember } from '../../testUtils/worldSeed.js'; +import { + disposeAllRooms, + startMatchmakeServer, + stopMatchmakeServer, + type MatchmakeTestServer, +} from '../../testUtils/matchmakeHarness.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('worldPayloads.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const REJECTION_METRIC = 'meetropolis_world_payload_rejected_total'; +const TILES_X = 10; +const TILES_Y = 8; +const TILE_PX = 32; +/** Closed pixel window of the seeded map: tiles times tile size, both edges included. */ +const MAP_WIDTH = TILES_X * TILE_PX; +const MAP_HEIGHT = TILES_Y * TILE_PX; +const INTERIOR_X = 32; +const INTERIOR_Y = 32; +const MOVE_GAP_MS = 100; + +process.env.DEFAULT_TENANT_SLUG = `wp-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + +const prisma = createPrismaClient(); +const packUuids: string[] = []; +const moveBag: unknown[] = []; +const dndBag: unknown[] = []; +const editorBag: unknown[] = []; + +let server: MatchmakeTestServer | undefined; +let previousGameServer: typeof global.gameServer; +let tenantId = ''; +let tenantSlug = ''; +let mapId = ''; +let fixturePackUuid = ''; +let admin: SeededMember | undefined; +let guest: SeededMember | undefined; +let actor: Room | undefined; +let peer: Room | undefined; + +type Direction = 'up' | 'down' | 'left' | 'right'; +type RejectionType = 'move' | 'dnd_status' | 'editor_state'; +type RejectionReason = 'schema' | 'bounds'; + +interface MoveSample { + x: number; + y: number; + direction: string; +} + +interface Pose { + x: number; + y: number; + direction: string; + dnd: boolean; + mapId: string; +} + +interface Point { + x: number; + y: number; +} + +interface EditorTileset { + key: string; + dataUrl: string; + tileWidth: number; + tileHeight: number; + margin?: number; + spacing?: number; + category?: string; +} + +const KNOWN_TILESET: EditorTileset = { + key: 'floor', + dataUrl: 'x', + tileWidth: 16, + tileHeight: 16, + margin: 0, + spacing: 0, + category: 'ground', +}; + +function triangle(): Point[] { + return [ + { x: 0, y: 0 }, + { x: 8, y: 0 }, + { x: 0, y: 8 }, + ]; +} + +function points(count: number): Point[] { + const list: Point[] = []; + for (let index = 0; index < count; index += 1) list.push({ x: index, y: 0 }); + return list; +} + +function tilesetList(count: number): EditorTileset[] { + const list: EditorTileset[] = []; + for (let index = 0; index < count; index += 1) { + list.push({ key: `sheet-${index}`, dataUrl: 'x', tileWidth: 1, tileHeight: 1 }); + } + return list; +} + +function zoneList(count: number): Array<{ name: string; points: Point[] }> { + const shape = triangle(); + const list: Array<{ name: string; points: Point[] }> = []; + for (let index = 0; index < count; index += 1) list.push({ name: `area-${index}`, points: shape }); + return list; +} + +function configureApi(app: express.Express): void { + app.use(cookieParser()); + app.use(express.json()); + app.use(tenantMiddleware as unknown as express.RequestHandler); + // Routes finish registering before the first request; listen does not await this. + void registerApi(app); +} + +async function seedGlobalAvatarPack(): Promise { + const uuid = `pack-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; + await prisma.avatarPack.create({ + data: { + uuid, + name: uuid, + description: 'world payload join fixture', + author: 'payload-fixture', + version: '1', + avatars: [{ key: 'business_man' }], + tenantId: null, + }, + }); + packUuids.push(uuid); + fixturePackUuid = uuid; +} + +async function rejectionCount(type: RejectionType, reason: RejectionReason): Promise { + const metric = registry.getSingleMetric(REJECTION_METRIC); + if (!(metric instanceof Counter)) return 0; + const snapshot = await metric.get(); + let total = 0; + for (const sample of snapshot.values) { + if (String(sample.labels.type) === type && String(sample.labels.reason) === reason) total += sample.value; + } + return total; +} + +async function waitUntil(predicate: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() >= deadline) return false; + await new Promise((resolve) => setTimeout(resolve, 25)); + } + return true; +} + +async function elapsed(timeoutMs: number): Promise { + await new Promise((resolve) => setTimeout(resolve, timeoutMs)); + return true; +} + +function poseOf(room: Room): Pose | null { + for (const player of room.state.players.values()) { + if (player.id !== room.sessionId) continue; + return { + x: player.x, + y: player.y, + direction: player.direction, + dnd: player.dnd, + mapId: player.mapId, + }; + } + return null; +} + +function samePose(left: Pose | null, right: Pose | null): boolean { + if (!left || !right) return false; + return ( + left.x === right.x && + left.y === right.y && + left.direction === right.direction && + left.dnd === right.dnd && + left.mapId === right.mapId + ); +} + +function messageId(message: unknown): string | null { + if (typeof message !== 'object' || message === null || !('id' in message)) return null; + return typeof message.id === 'string' ? message.id : null; +} + +async function joinMember(member: SeededMember): Promise { + const client = new Client(server?.base ?? ''); + client.auth.token = member.token; + return client.joinOrCreate('world', { + tenant: tenantSlug, + identity: member.userId, + avatarId: `${fixturePackUuid}:business_man`, + zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION, + }); +} + +function wirePeer(actorSessionId: string): void { + if (!peer) return; + peer.onMessage('player_moved', (message: unknown) => { + if (messageId(message) === actorSessionId) moveBag.push(message); + }); + peer.onMessage('player_dnd', (message: unknown) => { + if (messageId(message) === actorSessionId) dndBag.push(message); + }); + peer.onMessage('editor_update', (message: unknown) => { + editorBag.push(message); + }); +} + +async function leaveRoom(room: Room | undefined): Promise { + if (!room) return; + await Promise.race([ + room.leave().catch(() => undefined), + new Promise((resolve) => setTimeout(resolve, 3_000)), + ]); +} + +/** Repeat a valid move until the cache from room creation is visible in the pose. */ +async function land(x: number, y: number, direction: Direction): Promise { + const room = actor; + if (!room) return false; + const deadline = Date.now() + 5_000; + while (Date.now() < deadline) { + room.send('move', { x, y, direction }); + const arrived = await waitUntil(() => { + const pose = poseOf(room); + return pose !== null && pose.x === x && pose.y === y && pose.direction === direction; + }, 200); + if (arrived) return true; + await elapsed(MOVE_GAP_MS); + } + return false; +} + +async function expectRejectedSignal( + type: RejectionType, + reason: RejectionReason, + send: () => void, + changed: () => boolean, + bag: unknown[], +): Promise { + bag.length = 0; + const before = await rejectionCount(type, reason); + send(); + const sawChange = await waitUntil(() => bag.length > 0 || changed(), 1_500); + expect(sawChange).toBe(false); + expect(bag).toHaveLength(0); + expect(changed()).toBe(false); + expect((await rejectionCount(type, reason)) - before).toBe(1); +} + +async function expectRejectedMove(payload: MoveSample, reason: RejectionReason): Promise { + const room = actor; + if (!room) throw new Error('world client is not connected'); + expect(await land(INTERIOR_X, INTERIOR_Y, 'down')).toBe(true); + await elapsed(MOVE_GAP_MS); + const before = poseOf(room); + await expectRejectedSignal( + 'move', + reason, + () => room.send('move', payload), + () => !samePose(poseOf(room), before), + moveBag, + ); +} + +async function putEditor(body: unknown): Promise { + const payload = typeof body === 'string' ? body : JSON.stringify(body); + const response = await fetch(`${server?.base ?? ''}/maps/${mapId}/editor-state`, { + method: 'PUT', + headers: { authorization: `Bearer ${admin?.token ?? ''}`, 'content-type': 'application/json' }, + body: payload, + }); + await response.text(); + return response.status; +} + +async function getEditor(): Promise { + const response = await fetch(`${server?.base ?? ''}/maps/${mapId}/editor-state`, { + headers: { authorization: `Bearer ${admin?.token ?? ''}` }, + }); + const body: unknown = await response.json(); + return body; +} + +async function editorSnapshot(): Promise { + const map = await prisma.map.findUnique({ where: { id: mapId }, select: { meta: true } }); + const zones = await prisma.zone.findMany({ + where: { mapId }, + orderBy: { name: 'asc' }, + select: { + name: true, + capacity: true, + polygon: true, + type: true, + portalTarget: true, + portalSpawnX: true, + portalSpawnY: true, + }, + }); + return JSON.stringify({ meta: map?.meta ?? null, zones }); +} + +async function tilesetCount(): Promise { + const map = await prisma.map.findUnique({ where: { id: mapId }, select: { meta: true } }); + const meta = map?.meta; + if (typeof meta !== 'object' || meta === null || Array.isArray(meta) || !('tilesets' in meta)) return 0; + return Array.isArray(meta.tilesets) ? meta.tilesets.length : 0; +} + +async function resetEditor(): Promise { + editorBag.length = 0; + const status = await putEditor({ + tilesets: [KNOWN_TILESET], + zones: [{ name: 'Lobby', type: 'default', points: triangle(), capacity: 4 }], + backgroundColor: '#112233', + spawn: { x: INTERIOR_X, y: INTERIOR_Y }, + replaceZones: true, + }); + if (status !== 200) throw new Error(`editor reset returned ${status}`); + const heard = await waitUntil(() => editorBag.length > 0, 1_500); + if (!heard) throw new Error('editor reset produced no editor update'); + editorBag.length = 0; +} + +async function expectRejectedEditor(body: unknown): Promise { + await resetEditor(); + const beforeSnap = await editorSnapshot(); + const before = await rejectionCount('editor_state', 'schema'); + editorBag.length = 0; + const status = await putEditor(body); + const heard = await waitUntil(() => editorBag.length > 0, 1_500); + expect(status).toBe(400); + expect(await editorSnapshot()).toBe(beforeSnap); + expect(heard).toBe(false); + expect((await rejectionCount('editor_state', 'schema')) - before).toBe(1); +} + +async function expectAcceptedEditor(body: unknown): Promise { + const before = await rejectionCount('editor_state', 'schema'); + editorBag.length = 0; + const status = await putEditor(body); + const heard = await waitUntil(() => editorBag.length > 0, 1_500); + expect(status).toBe(200); + expect(heard).toBe(true); + expect((await rejectionCount('editor_state', 'schema')) - before).toBe(0); +} + +beforeAll(async () => { + tenantSlug = process.env.DEFAULT_TENANT_SLUG ?? ''; + tenantId = (await seedTenant(prisma, { slug: tenantSlug })).id; + await seedGlobalAvatarPack(); + mapId = ( + await prisma.map.create({ + data: { + tenantId, + name: 'office', + width: TILES_X, + height: TILES_Y, + tileWidth: TILE_PX, + tileHeight: TILE_PX, + meta: { spawn: { x: INTERIOR_X, y: INTERIOR_Y } }, + }, + }) + ).id; + admin = await seedMember(prisma, tenantId, { role: 'admin' }); + guest = await seedMember(prisma, tenantId, { role: 'member' }); + server = await startMatchmakeServer({ configureApp: configureApi }); + previousGameServer = global.gameServer; + global.gameServer = server.gameServer; +}, 30_000); + +beforeEach(async () => { + await disposeAllRooms(); + moveBag.length = 0; + dndBag.length = 0; + editorBag.length = 0; + if (!admin || !guest) throw new Error('seeded members are missing'); + actor = await joinMember(admin); + try { + peer = await joinMember(guest); + wirePeer(actor.sessionId); + const synced = await waitUntil(() => poseOf(actor as Room)?.mapId === mapId, 5_000); + if (!synced) throw new Error(`joined map ${poseOf(actor)?.mapId ?? 'missing'} is not the seeded map`); + } catch (error) { + await leaveRoom(actor); + await leaveRoom(peer); + actor = undefined; + peer = undefined; + throw error; + } +}, 30_000); + +afterEach(async () => { + await leaveRoom(actor); + await leaveRoom(peer); + actor = undefined; + peer = undefined; +}); + +afterAll(async () => { + await disposeAllRooms(); + if (server) await stopMatchmakeServer(server); + global.gameServer = previousGameServer; + if (tenantId) { + await prisma.zone.deleteMany({ where: { tenantId } }); + await prisma.presence.deleteMany({ where: { tenantId } }); + await prisma.room.deleteMany({ where: { tenantId } }); + await prisma.map.deleteMany({ where: { tenantId } }); + await prisma.avatarPack.deleteMany({ where: { uuid: { in: packUuids } } }); + await cleanupTenants(prisma, [tenantId]); + } + await prisma.$disconnect(); +}, 30_000); + +describe('move payload', () => { + it('move payload > drops a coordinate that is not a number', async () => { + await expectRejectedMove({ x: Number.NaN, y: INTERIOR_Y, direction: 'up' }, 'schema'); + }, 30_000); + + it('move payload > drops an infinite coordinate', async () => { + await expectRejectedMove({ x: Number.POSITIVE_INFINITY, y: INTERIOR_Y, direction: 'up' }, 'schema'); + }, 30_000); + + it('move payload > drops a coordinate outside the map', async () => { + await expectRejectedMove({ x: MAP_WIDTH + 1, y: 0, direction: 'left' }, 'bounds'); + }, 30_000); + + it('move payload > drops an unknown direction', async () => { + await expectRejectedMove({ x: INTERIOR_X, y: INTERIOR_Y, direction: 'north' }, 'schema'); + }, 30_000); +}); + +describe('dnd payload', () => { + it('dnd payload > drops a status that is not a boolean', async () => { + const room = actor; + if (!room) throw new Error('world client is not connected'); + const before = poseOf(room); + await expectRejectedSignal( + 'dnd_status', + 'schema', + () => room.send('dnd_status', { dnd: 'yes' }), + () => !samePose(poseOf(room), before), + dndBag, + ); + }, 30_000); +}); + +describe('editor state payload', () => { + it('editor state payload > rejects a tileset element that is not a tileset', async () => { + await expectRejectedEditor({ tilesets: [{ key: 1 }] }); + }, 30_000); + + it('editor state payload > rejects a zone polygon that is not a point list', async () => { + await expectRejectedEditor({ + zones: [{ name: 'Gate', polygon: { closed: true } }], + replaceZones: true, + }); + }, 30_000); + + it('editor state payload > rejects a zone capacity that is not an allowed integer', async () => { + await expectRejectedEditor({ + zones: [{ name: 'Hall', capacity: -1, points: triangle() }], + replaceZones: true, + }); + }, 30_000); + + it('editor state payload > rejects a spawn coordinate that is not finite', async () => { + await expectRejectedEditor('{"spawn":{"x":1e309,"y":0}}'); + }, 30_000); + + it('editor state payload > rejects an unknown zone type', async () => { + await expectRejectedEditor({ + zones: [{ name: 'Secret', type: 'private', points: triangle() }], + replaceZones: true, + }); + }, 30_000); +}); + +describe('accepted payloads', () => { + it('accepted payloads > accepts the closed edges of the map', async () => { + expect(await land(INTERIOR_X, INTERIOR_Y, 'down')).toBe(true); + await elapsed(MOVE_GAP_MS); + moveBag.length = 0; + const before = await rejectionCount('move', 'bounds'); + expect(await land(0, 0, 'left')).toBe(true); + await elapsed(MOVE_GAP_MS); + expect(await land(MAP_WIDTH, MAP_HEIGHT, 'right')).toBe(true); + expect(moveBag.length).toBeGreaterThan(0); + expect((await rejectionCount('move', 'bounds')) - before).toBe(0); + }, 30_000); + + it('accepted payloads > accepts every move direction', async () => { + const before = await rejectionCount('move', 'schema'); + const directions: Direction[] = ['up', 'down', 'left', 'right']; + for (const direction of directions) { + await elapsed(MOVE_GAP_MS); + expect(await land(INTERIOR_X, INTERIOR_Y, direction)).toBe(true); + } + expect((await rejectionCount('move', 'schema')) - before).toBe(0); + }, 30_000); + + it('accepted payloads > accepts both dnd values', async () => { + const room = actor; + if (!room) throw new Error('world client is not connected'); + const before = await rejectionCount('dnd_status', 'schema'); + for (const dnd of [true, false]) { + dndBag.length = 0; + room.send('dnd_status', { dnd }); + const heard = await waitUntil(() => { + const pose = poseOf(room); + return pose !== null && pose.dnd === dnd && dndBag.length > 0; + }, 1_500); + expect(heard).toBe(true); + } + expect((await rejectionCount('dnd_status', 'schema')) - before).toBe(0); + }, 30_000); + + it('accepted payloads > accepts a signed zero and a tiny finite coordinate', async () => { + const before = await rejectionCount('move', 'schema'); + expect(await land(-0, Number.MIN_VALUE, 'up')).toBe(true); + expect(actor?.sessionId).toBeTruthy(); + expect((await rejectionCount('move', 'schema')) - before).toBe(0); + }, 30_000); + + it('accepted payloads > accepts the current tileset shape', async () => { + await expectAcceptedEditor({ tilesets: [KNOWN_TILESET] }); + expect(await tilesetCount()).toBe(1); + }, 30_000); + + it('accepted payloads > accepts a portal zone', async () => { + await expectAcceptedEditor({ + zones: [ + { + name: 'Door', + type: 'portal', + points: triangle(), + portalTarget: 'office', + portalSpawnX: 8, + portalSpawnY: 8, + }, + ], + replaceZones: true, + }); + const zone = await prisma.zone.findFirst({ where: { mapId, name: 'Door' } }); + expect(zone?.type).toBe('portal'); + expect(zone?.portalTarget).toBe('office'); + expect(zone?.portalSpawnX).toBe(8); + expect(zone?.portalSpawnY).toBe(8); + }, 30_000); + + it('accepted payloads > accepts every stored polygon shape', async () => { + const shape = triangle(); + const variants = [ + { name: 'ByPoints', points: shape }, + { name: 'ByList', polygon: shape }, + { name: 'ByObject', polygon: { points: shape } }, + ]; + for (const zone of variants) { + await expectAcceptedEditor({ zones: [zone], replaceZones: true }); + const row = await prisma.zone.findFirst({ where: { mapId, name: zone.name } }); + expect(Array.isArray(row?.polygon) ? row.polygon.length : 0).toBe(3); + } + }, 30_000); + + it('accepted payloads > clears zones when the zone list is empty', async () => { + await resetEditor(); + await expectAcceptedEditor({ zones: [], replaceZones: true }); + expect(await prisma.zone.count({ where: { mapId } })).toBe(0); + }, 30_000); + + it('accepted payloads > stores zones returned with an id and a null capacity', async () => { + await expectAcceptedEditor({ zones: [{ name: 'Round', points: triangle() }], replaceZones: true }); + const fetched = await getEditor(); + const zones = + typeof fetched === 'object' && fetched !== null && 'zones' in fetched && Array.isArray(fetched.zones) + ? fetched.zones + : []; + expect(zones).toHaveLength(1); + const zone: unknown = zones[0]; + const roundTrip = + typeof zone === 'object' && + zone !== null && + 'id' in zone && + 'capacity' in zone && + 'name' in zone && + typeof zone.id === 'string' && + zone.id.length > 0 && + zone.capacity === null && + zone.name === 'Round'; + expect(roundTrip).toBe(true); + await expectAcceptedEditor({ zones, replaceZones: true }); + const stored = await prisma.zone.findMany({ where: { mapId } }); + expect(stored).toHaveLength(1); + expect(stored[0]?.name).toBe('Round'); + expect(stored[0]?.capacity).toBeNull(); + }, 30_000); + + it('accepted payloads > accepts 256 tilesets', async () => { + await expectAcceptedEditor({ tilesets: tilesetList(256) }); + expect(await tilesetCount()).toBe(256); + }, 30_000); + + it('accepted payloads > accepts 512 zones', async () => { + await expectAcceptedEditor({ zones: zoneList(512), replaceZones: true }); + expect(await prisma.zone.count({ where: { mapId } })).toBe(512); + }, 60_000); + + it('accepted payloads > accepts a polygon of 2048 points', async () => { + await expectAcceptedEditor({ zones: [{ name: 'Outline', points: points(2048) }], replaceZones: true }); + const row = await prisma.zone.findFirst({ where: { mapId, name: 'Outline' } }); + expect(Array.isArray(row?.polygon) ? row.polygon.length : 0).toBe(2048); + }, 30_000); +}); diff --git a/apps/server/src/services/accountDeletion.ts b/apps/server/src/services/accountDeletion.ts new file mode 100644 index 00000000..e950dbcf --- /dev/null +++ b/apps/server/src/services/accountDeletion.ts @@ -0,0 +1,114 @@ +import type { PrismaClient, Prisma } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; +import { revokeSessionsForUserInTx } from '../api/utils/sessionAuth.js'; +import { invalidateSessionsForUser } from '../api/utils/sessionCache.js'; +import { customAvatarPacksDir, deleteCustomAvatarFiles } from './avatarComposer.js'; +import { revokeAccountAccess, revokeTenantAccess } from './tenantAccessRevocation.js'; + +/** + * Account deletion and member removal. + * + * Every database change runs in ONE interactive transaction: either the whole + * deletion lands or nothing does. The previous implementation deleted rows one + * by one, swallowed every error and then failed on `user.delete` because + * `Session` and `EmailVerification` reference the user with ON DELETE RESTRICT, + * which left accounts without any membership behind while the client was told + * the deletion had failed. + * + * Semantics: + * - `deleteAccount`: removes the account and everything that references it. + * - `removeMemberFromTenant`: removes the membership in ONE tenant and signs the + * user out everywhere. If that was the user's last membership, the account is + * deleted in the same transaction (an account without any tenant has no use). + * + * Filesystem work (custom avatar sprites), cache invalidation and the + * revocation of open world and AV connections happen after the commit and never turn a committed deletion into an error. + */ + +export interface MemberRemovalResult { + accountDeleted: boolean; +} + +export class MembershipNotFoundError extends Error { + constructor(userId: string, tenantId: string) { + super(`membership of user ${userId} in tenant ${tenantId} not found`); + this.name = 'MembershipNotFoundError'; + } +} + +async function purgeAccountRows(tx: Prisma.TransactionClient, userId: string): Promise { + await revokeSessionsForUserInTx(tx, userId); + await tx.emailVerification.deleteMany({ where: { userId } }); + await tx.passwordReset.deleteMany({ where: { userId } }); + await tx.apiToken.deleteMany({ where: { userId } }); + await tx.presence.deleteMany({ where: { userId } }); + await tx.invite.updateMany({ where: { usedById: userId }, data: { usedById: null } }); + await tx.invite.updateMany({ where: { createdBy: userId }, data: { createdBy: null } }); + await tx.membership.deleteMany({ where: { userId } }); + // CustomAvatar and the enterprise transcription tables cascade from User. + await tx.user.delete({ where: { id: userId } }); +} + +async function readCustomAvatarUuid(prisma: PrismaClient, userId: string): Promise { + const avatar = await prisma.customAvatar.findUnique({ where: { userId }, select: { uuid: true } }); + return avatar?.uuid ?? null; +} + +async function removeCustomAvatarFiles(userId: string, uuid: string | null): Promise { + if (!uuid) return; + try { + await deleteCustomAvatarFiles(customAvatarPacksDir(), uuid); + } catch (err) { + // The rows are gone already; orphaned sprite files are a cleanup issue, + // not a reason to report the committed deletion as failed. + logger.warn({ event: 'user.delete.avatar_cleanup_failed', userId, error: String(err) }); + } +} + +/** Delete the account of `userId` with everything that references it. */ +export async function deleteAccount(prisma: PrismaClient, userId: string): Promise { + const avatarUuid = await readCustomAvatarUuid(prisma, userId); + const memberships = await prisma.membership.findMany({ + where: { userId }, + select: { tenant: { select: { slug: true } } }, + }); + await prisma.$transaction(async (tx) => { + await purgeAccountRows(tx, userId); + }); + invalidateSessionsForUser(userId); + await revokeAccountAccess( + userId, + memberships.map((m) => m.tenant.slug), + ); + await removeCustomAvatarFiles(userId, avatarUuid); +} + +/** + * Remove `userId` from `tenantId`. Deletes the whole account when no other + * membership remains. Throws `MembershipNotFoundError` (nothing changed) when + * the membership does not exist. + */ +export async function removeMemberFromTenant( + prisma: PrismaClient, + params: { userId: string; tenantId: string }, +): Promise { + const { userId, tenantId } = params; + const avatarUuid = await readCustomAvatarUuid(prisma, userId); + const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); + const accountDeleted = await prisma.$transaction(async (tx) => { + const removed = await tx.membership.deleteMany({ where: { userId, tenantId } }); + if (removed.count === 0) throw new MembershipNotFoundError(userId, tenantId); + await tx.presence.deleteMany({ where: { userId, tenantId } }); + // Sign the user out everywhere: sessions are not bound to a tenant, and a + // removed member must not keep a live session in the tenant it left. + await revokeSessionsForUserInTx(tx, userId); + const remaining = await tx.membership.count({ where: { userId } }); + if (remaining > 0) return false; + await purgeAccountRows(tx, userId); + return true; + }); + invalidateSessionsForUser(userId); + if (tenant) await revokeTenantAccess(tenant.slug, userId); + if (accountDeleted) await removeCustomAvatarFiles(userId, avatarUuid); + return { accountDeleted }; +} diff --git a/apps/server/src/services/tenantAccessRevocation.ts b/apps/server/src/services/tenantAccessRevocation.ts new file mode 100644 index 00000000..429deef4 --- /dev/null +++ b/apps/server/src/services/tenantAccessRevocation.ts @@ -0,0 +1,31 @@ +import { broadcastAccessRevoked } from '../api/utils/broadcast.js'; +import { enqueueAvRevocation } from '../rooms/lifecycle/avPendingRevocations.js'; + +/** + * Everything that has to happen once a user's access to a tenant is gone + * (member removed, account deleted, guest revoked). Call it only after the + * change is committed; it never throws. + * + * - World: every world room learns the user at once through the single + * per-user access-revoked event and disconnects each of the user's sessions + * whose verified tenant no longer grants access + * (rooms/lifecycle/accessRevocation.ts). + * - AV: the user is removed from the tenant's LiveKit calls, whose + * connection the world disconnect does not end. + */ +export async function revokeTenantAccess(tenantSlug: string, userId: string): Promise { + broadcastAccessRevoked(userId); + enqueueAvRevocation(`${tenantSlug}:world`, userId); +} + +/** + * Account deletion ends the user's sessions in every tenant at once: exactly + * one per-user world event (even with no membership left) plus the AV removal + * per tenant slug. Call it only after the change is committed; it never throws. + */ +export async function revokeAccountAccess(userId: string, tenantSlugs: Iterable): Promise { + broadcastAccessRevoked(userId); + for (const tenantSlug of tenantSlugs) { + enqueueAvRevocation(`${tenantSlug}:world`, userId); + } +} diff --git a/apps/server/src/tenantIsolation.integration.test.ts b/apps/server/src/tenantIsolation.integration.test.ts new file mode 100644 index 00000000..6ff9863c --- /dev/null +++ b/apps/server/src/tenantIsolation.integration.test.ts @@ -0,0 +1,222 @@ +import bcrypt from 'bcryptjs'; +import crypto from 'crypto'; +import cookieParser from 'cookie-parser'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Role } from './generated/prisma/index.js'; +import { createPrismaClient } from './db.js'; +import { registerApi } from './api.js'; +import { tenantMiddleware } from './tenancy.js'; +import { getJwtSecret } from './api/utils/authHelpers.js'; +import { inviteExpiry } from './api/utils/inviteLifecycle.js'; +import { hashSessionToken } from './api/utils/sessionAuth.js'; + +/** + * Tenant isolation through the real HTTP stack (tenantMiddleware, session + * middleware, registerApi) against a REAL PostgreSQL database. + * + * A signed-in caller without a membership in the request's tenant (for example + * a member that was removed while a session was still open) must not read or + * change that tenant's data. The OSS build runs single-tenant, so every request + * resolves to DEFAULT_TENANT_SLUG; the enterprise build resolves the tenant + * from X-Tenant or the session claim, and the same rule applies. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('tenantIsolation.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const TENANT_SLUG = `qacc-iso-${crypto.randomUUID()}`; +process.env.DEFAULT_TENANT_SLUG = TENANT_SLUG; + +const prisma = createPrismaClient(); +const userIds: string[] = []; +const additionalTenantIds: string[] = []; +let app: express.Express; +let tenantId: string; +let mapId: string; +let inviteCode: string; +let inviteId: string; +let memberId: string; +let memberToken: string; +let adminToken: string; +let outsiderToken: string; + +async function createUser(role: Role | null): Promise<{ id: string; token: string }> { + const user = await prisma.user.create({ data: { email: `qacc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + if (role) await prisma.membership.create({ data: { userId: user.id, tenantId, role } }); + const token = jwt.sign({ sub: user.id, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { id: user.id, token }; +} + +const as = (token: string) => ({ Authorization: `Bearer ${token}` }); + +beforeAll(async () => { + tenantId = (await prisma.tenant.create({ data: { slug: TENANT_SLUG, name: TENANT_SLUG } })).id; + const member = await createUser('member'); + memberId = member.id; + memberToken = member.token; + adminToken = (await createUser('admin')).token; + // Signed in, valid session, but no membership: e.g. removed from the tenant. + outsiderToken = (await createUser(null)).token; + mapId = (await prisma.map.create({ data: { tenantId, name: 'Office', meta: {} } })).id; + inviteCode = crypto.randomBytes(12).toString('hex'); + inviteId = ( + await prisma.invite.create({ data: { code: inviteCode, email: 'invitee@example.test', tenantId, role: 'admin' } }) + ).id; + + app = express(); + app.use(cookieParser()); + app.use(express.json()); + app.use(tenantMiddleware as unknown as express.RequestHandler); + await registerApi(app); +}); + +afterAll(async () => { + const cleanupTenantIds = [tenantId, ...additionalTenantIds]; + await prisma.presence.deleteMany({ where: { tenantId } }); + await prisma.emailVerification.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.invite.deleteMany({ where: { tenantId: { in: cleanupTenantIds } } }); + // A presence write auto-creates the default room, which references the map. + await prisma.room.deleteMany({ where: { tenantId } }); + await prisma.map.deleteMany({ where: { tenantId } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: cleanupTenantIds } } }); + await prisma.$disconnect(); +}); + +describe('tenant data requires a membership (real stack)', () => { + it('serves the member roster to a member', async () => { + const res = await request(app).get('/presence/recent').set(as(memberToken)); + expect(res.status).toBe(200); + expect(JSON.stringify(res.body)).toContain(memberId); + }); + + it('refuses the member roster to a signed-in non-member', async () => { + const res = await request(app).get('/presence/recent').set(as(outsiderToken)); + expect(res.status).toBe(400); + expect(res.body.error).toBe('tenant_required'); + }); + + it('refuses a member profile to a signed-in non-member', async () => { + expect((await request(app).get(`/users/${memberId}`).set(as(memberToken))).status).toBe(200); + const res = await request(app).get(`/users/${memberId}`).set(as(outsiderToken)); + expect(res.status).toBe(400); + expect(res.body.error).toBe('tenant_required'); + }); + + it('refuses listing and revoking invites to a signed-in non-member', async () => { + expect((await request(app).get('/invites').set(as(adminToken))).status).toBe(200); + const list = await request(app).get('/invites').set(as(outsiderToken)); + expect(list.status).toBe(400); + const revoke = await request(app).delete(`/invites/${inviteId}`).set(as(outsiderToken)); + expect(revoke.status).toBe(400); + expect(await prisma.invite.count({ where: { code: inviteCode } })).toBe(1); + }); + + it('refuses map export and import to a signed-in non-member', async () => { + const exported = await request(app).get(`/maps/${mapId}/export-tmj`).set(as(outsiderToken)); + expect(exported.status).toBe(400); + expect(exported.body.error).toBe('tenant_required'); + const imported = await request(app).post(`/maps/${mapId}/import-tmj`).set(as(outsiderToken)); + expect(imported.body.error).toBe('tenant_required'); + }); + + it('refuses writing presence into the tenant to a signed-in non-member', async () => { + const res = await request(app) + .post('/auth/position') + .set(as(outsiderToken)) + .send({ x: 1, y: 1, direction: 'down' }); + expect(res.status).toBe(400); + expect(res.body.error).toBe('tenant_required'); + expect(await prisma.presence.count({ where: { tenantId } })).toBe(0); + }); + + it('refuses the NPC list to a signed-in non-member', async () => { + expect((await request(app).get('/npcs').set(as(memberToken))).status).toBe(200); + const res = await request(app).get('/npcs').set(as(outsiderToken)); + expect(res.status).toBe(400); + expect(res.body.error).toBe('tenant_required'); + }); + + it('keeps answering /auth/me for a signed-in non-member with not_member_of_tenant', async () => { + const res = await request(app).get('/auth/me').set(as(outsiderToken)); + expect(res.status).toBe(403); + expect(res.body.error).toBe('not_member_of_tenant'); + }); +}); + +describe('flows that must keep working without a membership (real stack)', () => { + it('serves /public/config to a signed-in non-member', async () => { + const res = await request(app).get('/public/config').set(as(outsiderToken)); + expect(res.status).toBe(200); + }); + + it('lets a member log in while the browser still carries a non-member session', async () => { + const email = `login-${crypto.randomUUID()}@example.test`; + const password = 'Qacc-Login-Password-1'; + const user = await prisma.user.create({ data: { email, passwordHash: await bcrypt.hash(password, 4) } }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId, role: 'member' } }); + const res = await request(app).post('/auth/login').set(as(outsiderToken)).send({ email, password }); + expect(res.status).toBe(200); + }); + + it('lets a signed-in non-member start an invite registration without a membership before email proof', async () => { + const code = crypto.randomBytes(12).toString('hex'); + const email = `invitee-${crypto.randomUUID()}@example.test`; + await prisma.invite.create({ data: { code, email, tenantId, role: 'member', expiresAt: inviteExpiry() } }); + const res = await request(app) + .post('/auth/register') + .set(as(outsiderToken)) + .send({ code, email, password: 'Qacc-Test-Password-1' }); + expect(res.status).toBe(409); + expect(res.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + expect(res.body.delivery).toBe('sent'); + expect(res.body).not.toHaveProperty('token'); + const created = await prisma.user.findUnique({ where: { email }, select: { id: true } }); + expect(created).not.toBeNull(); + if (created) userIds.push(created.id); + expect(await prisma.membership.count({ where: { tenantId, user: { email } } })).toBe(0); + }); + + it('lets a member accept a bound invite when X-Tenant selects another tenant', async () => { + const tenantB = await prisma.tenant.create({ + data: { slug: `qacc-invite-target-${crypto.randomUUID()}`, name: 'Invite Target' }, + }); + additionalTenantIds.push(tenantB.id); + const member = await prisma.user.findUniqueOrThrow({ where: { id: memberId }, select: { email: true } }); + const code = crypto.randomBytes(12).toString('hex'); + const invite = await prisma.invite.create({ + data: { code, email: member.email, tenantId: tenantB.id, role: 'member' }, + }); + await prisma.$executeRaw` + UPDATE "Invite" SET "expiresAt" = now() + interval '7 days' WHERE "id" = ${invite.id} + `; + await prisma.user.update({ where: { id: memberId }, data: { emailVerifiedAt: new Date() } }); + + const response = await request(app) + .post('/invites/accept') + .set(as(memberToken)) + .set('X-Tenant', tenantB.slug) + .send({ code }); + + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ id: memberId, email: member.email, alreadyMember: false }); + expect( + await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: tenantB.id, userId: memberId } }, + }), + ).toMatchObject({ role: 'member' }); + }); +}); diff --git a/apps/server/src/testUtils/matchmakeHarness.ts b/apps/server/src/testUtils/matchmakeHarness.ts index 62c6f6af..a6358ba6 100644 --- a/apps/server/src/testUtils/matchmakeHarness.ts +++ b/apps/server/src/testUtils/matchmakeHarness.ts @@ -49,12 +49,18 @@ export interface StartOptions { * exercise the limit model external callers. */ loopbackExempt?: boolean; + /** + * Extra Express wiring for tests. Runs right after `trust proxy` is set + * and before the HTTP server is created. + */ + configureApp?: (app: express.Express) => void; } export async function startMatchmakeServer(options: StartOptions = {}): Promise { const trustProxy = options.trustProxy ?? false; const app = express(); app.set('trust proxy', trustProxy); + options.configureApp?.(app); app.get('/', (_req, res) => { res.send('ok'); }); diff --git a/apps/server/src/testUtils/plainSmtpServer.ts b/apps/server/src/testUtils/plainSmtpServer.ts new file mode 100644 index 00000000..9a58306f --- /dev/null +++ b/apps/server/src/testUtils/plainSmtpServer.ts @@ -0,0 +1,74 @@ +import net from 'net'; + +/** + * A minimal real SMTP server on 127.0.0.1 that does NOT offer STARTTLS: the + * situation a downgrade on the network path produces. Used to check that the + * mail providers refuse to send in plain text unless told otherwise. It speaks + * just enough SMTP for nodemailer (EHLO, AUTH-less MAIL/RCPT/DATA, RSET, QUIT). + */ +export interface PlainSmtpServer { + port: number; + /** Raw DATA payloads of the messages accepted so far. */ + received: string[]; + close(): Promise; +} + +export async function startPlainSmtpServer(): Promise { + const received: string[] = []; + const server = net.createServer((socket) => { + let buffer = ''; + let inData = false; + let data = ''; + const reply = (line: string) => socket.write(`${line}\r\n`); + reply('220 plain.test ESMTP'); + socket.on('data', (chunk) => { + buffer += chunk.toString('utf8'); + let index: number; + while ((index = buffer.indexOf('\r\n')) >= 0) { + const line = buffer.slice(0, index); + buffer = buffer.slice(index + 2); + if (inData) { + if (line === '.') { + inData = false; + received.push(data); + data = ''; + reply('250 queued'); + } else { + data += `${line}\n`; + } + continue; + } + const command = line.slice(0, 4).toUpperCase(); + if (command === 'EHLO') { + reply('250-plain.test'); + reply('250 8BITMIME'); + } else if ( + command === 'HELO' || + command === 'MAIL' || + command === 'RCPT' || + command === 'RSET' || + command === 'NOOP' + ) { + reply('250 ok'); + } else if (command === 'DATA') { + inData = true; + reply('354 end with .'); + } else if (command === 'QUIT') { + reply('221 bye'); + socket.end(); + } else { + reply('502 not implemented'); + } + } + }); + socket.on('error', () => socket.destroy()); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (address === null || typeof address === 'string') throw new Error('plain SMTP server has no port'); + return { + port: address.port, + received, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} diff --git a/apps/server/src/testUtils/sfuHarness.ts b/apps/server/src/testUtils/sfuHarness.ts new file mode 100644 index 00000000..e314972c --- /dev/null +++ b/apps/server/src/testUtils/sfuHarness.ts @@ -0,0 +1,184 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { AccessToken, RoomServiceClient } from 'livekit-server-sdk'; +import { Room } from '@livekit/rtc-node'; +import type { PrismaClient } from '../generated/prisma/index.js'; +import { mapLivekitUrlToHttp } from '../rooms/audioZones/livekitAdmin.js'; +import { stopAvPendingRevocations } from '../rooms/lifecycle/avPendingRevocations.js'; +import { startAvAccessReconciler } from '../rooms/lifecycle/avAccessReconciler.js'; + +/** + * LiveKit (SFU) harness for database-backed integration tests: real + * participants through `@livekit/rtc-node`, real admin calls through + * `livekit-server-sdk`, real outages through `docker pause`. Mirrors the + * docker pattern of the world access outage test. Nothing here is mocked. + */ + +export interface SfuConfig { + url: string; + apiKey: string; + apiSecret: string; +} + +export interface AvReconciler { + runRound(): Promise; + stop(): Promise; +} + +const execFileAsync = promisify(execFile); +const POLL_INTERVAL_MS = 250; + +const connectedRooms: Room[] = []; + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Read the SFU coordinates from the environment; fail fast when any is missing. */ +export function sfuConfig(): SfuConfig { + const url = process.env.LIVEKIT_URL; + if (!url) throw new Error('sfuHarness needs LIVEKIT_URL pointing at the test SFU'); + const apiKey = process.env.LIVEKIT_API_KEY; + if (!apiKey) throw new Error('sfuHarness needs LIVEKIT_API_KEY for the test SFU'); + const apiSecret = process.env.LIVEKIT_API_SECRET; + if (!apiSecret) throw new Error('sfuHarness needs LIVEKIT_API_SECRET for the test SFU'); + return { url, apiKey, apiSecret }; +} + +/** Name of the container running the test SFU; fail fast when it is missing. */ +function sfuContainer(): string { + const container = process.env.TEST_SFU_CONTAINER; + if (!container) throw new Error('sfuHarness needs TEST_SFU_CONTAINER naming the test SFU container'); + return container; +} + +function adminClient(): RoomServiceClient { + const { url, apiKey, apiSecret } = sfuConfig(); + return new RoomServiceClient(mapLivekitUrlToHttp(url), apiKey, apiSecret); +} + +/** Connect a real participant with `token`; tracked for {@link disconnectAll}. */ +export async function connectParticipant(token: string): Promise { + const { url } = sfuConfig(); + const room = new Room(); + await room.connect(url, token, { autoSubscribe: false }); + connectedRooms.push(room); + return room; +} + +/** Leave every room opened through {@link connectParticipant}; never throws. */ +export async function disconnectAll(): Promise { + const rooms = connectedRooms.splice(0); + for (const room of rooms) { + try { + await room.disconnect(); + } catch { + // Already gone; cleanup must not fail the test. + } + } +} + +/** + * Mint a service-side token for `identity` in `roomName`. Only for + * service-owned and legacy cases in tests (NPC publishers, user tokens + * without a session reference, unknown `npc-` identities). + */ +export async function mintServiceToken( + roomName: string, + identity: string, + opts?: { metadata?: string }, +): Promise { + const { apiKey, apiSecret } = sfuConfig(); + const token = new AccessToken( + apiKey, + apiSecret, + { identity, ...(opts?.metadata !== undefined ? { metadata: opts.metadata } : {}) }, + ); + token.addGrant({ room: roomName, roomJoin: true, canPublish: true, canSubscribe: true }); + return token.toJwt(); +} + +/** Identities currently present in the SFU-side `roomName`. */ +export async function listIdentities(roomName: string): Promise { + return (await adminClient().listParticipants(roomName)).map((participant) => participant.identity); +} + +async function pollIdentity(roomName: string, identity: string, timeoutMs: number, present: boolean): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + if ((await listIdentities(roomName)).includes(identity) === present) return true; + if (Date.now() > deadline) return false; + await delay(POLL_INTERVAL_MS); + } +} + +/** + * Poll until `identity` is gone from `roomName` (every 250 ms). Returns + * whether the condition held in time, so tests can assert on the result. + */ +export async function waitForIdentityGone(roomName: string, identity: string, timeoutMs: number): Promise { + return pollIdentity(roomName, identity, timeoutMs, false); +} + +/** + * Poll until `identity` is present in `roomName` (every 250 ms). Returns + * whether the condition held in time, so tests can assert on the result. + */ +export async function waitForIdentityPresent( + roomName: string, + identity: string, + timeoutMs: number, +): Promise { + return pollIdentity(roomName, identity, timeoutMs, true); +} + +async function setSfuPaused(action: 'pause' | 'unpause'): Promise { + const container = sfuContainer(); + try { + await execFileAsync('docker', [action, container]); + } catch (e: unknown) { + throw new Error( + `sfuHarness needs docker access to ${action} ${container}: ${e instanceof Error ? e.message : String(e)}`, + ); + } +} + +/** Pause the test SFU container. Pair with {@link unpauseSfu} in a `finally`. */ +export async function pauseSfu(): Promise { + await setSfuPaused('pause'); +} + +/** Unpause the test SFU container. */ +export async function unpauseSfu(): Promise { + await setSfuPaused('unpause'); +} + +/** Run `fn` with the SFU paused; the container is always unpaused afterwards. */ +export async function withSfuPaused(fn: () => Promise): Promise { + await pauseSfu(); + try { + return await fn(); + } finally { + await unpauseSfu(); + } +} + +/** + * Start the AV reconciliation loop under test: the real reconciler with a + * 30 s interval (rounds run only through `runRound` here) and the + * process-wide confirmed-removal backlog. `stop` ends both. No other helper + * in this file changes with that fix. + */ +export async function startAvReconcile(prisma: PrismaClient): Promise { + const reconciler = startAvAccessReconciler(prisma); + let stopped = false; + return { + runRound: () => reconciler.runRound(), + stop: async () => { + if (stopped) return; + stopped = true; + await reconciler.stop(); + await stopAvPendingRevocations(); + }, + }; +} diff --git a/apps/server/src/testUtils/worldSeed.ts b/apps/server/src/testUtils/worldSeed.ts new file mode 100644 index 00000000..c50686ff --- /dev/null +++ b/apps/server/src/testUtils/worldSeed.ts @@ -0,0 +1,128 @@ +import crypto from 'crypto'; +import bcrypt from 'bcryptjs'; +import jwt from 'jsonwebtoken'; +import type { PrismaClient, Role } from '../generated/prisma/index.js'; +import { getJwtSecret } from '../api/utils/authHelpers.js'; +import { hashSessionToken } from '../api/utils/sessionAuth.js'; + +/** + * Shared seeding helpers for database-backed integration tests. They bundle + * the fixture pattern the world lifecycle tests repeat: direct + * `prisma.*.create` rows, a JWT shaped like the login flow mints it + * (`{ sub, tid, jti }` signed with the server secret) and a `Session` row + * holding `hashSessionToken(token)`. + */ + +export interface SeededMember { + userId: string; + email: string; + sessionId: string; + token: string; +} + +export interface SeedMemberOptions { + role?: Role; + expiresAt?: Date | null; + userId?: string; + email?: string; + /** + * Plain-text password. Stored hashed with `bcrypt.hash`, the same function + * `src/api/routes/auth.signin.ts` hashes and verifies against at login + * (same cost factor), so a seeded account can log in through the real + * `/auth/login` route. + */ + password?: string; +} + +/** bcrypt cost factor, kept in step with the login route named above. */ +const SEED_BCRYPT_COST = 10; + +function randomEmail(): string { + return `seed-${crypto.randomUUID()}@example.test`; +} + +function randomSlug(prefix: string): string { + return `${prefix}-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`; +} + +/** Create a tenant with a random unique `t-`-prefixed slug. */ +export async function seedTenant( + prisma: PrismaClient, + opts?: { slug?: string }, +): Promise<{ id: string; slug: string }> { + const slug = opts?.slug ?? randomSlug('t'); + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + return { id: tenant.id, slug: tenant.slug }; +} + +/** Mint a session JWT for `userId` scoped to `tenantId` and persist its row. */ +export async function issueSession( + prisma: PrismaClient, + userId: string, + tenantId: string, +): Promise<{ sessionId: string; token: string }> { + const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + const session = await prisma.session.create({ + data: { userId, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + select: { id: true }, + }); + return { sessionId: session.id, token }; +} + +/** Create a user with a membership in `tenantId` and a live session. */ +export async function seedMember( + prisma: PrismaClient, + tenantId: string, + opts?: SeedMemberOptions, +): Promise { + const email = opts?.email ?? randomEmail(); + const passwordHash = + opts?.password !== undefined ? await bcrypt.hash(opts.password, SEED_BCRYPT_COST) : undefined; + const user = await prisma.user.create({ + data: { + ...(opts?.userId !== undefined ? { id: opts.userId } : {}), + email, + ...(passwordHash !== undefined ? { passwordHash } : {}), + }, + }); + await prisma.membership.create({ + data: { + userId: user.id, + tenantId, + role: opts?.role ?? 'member', + ...(opts?.expiresAt !== undefined ? { expiresAt: opts.expiresAt } : {}), + }, + }); + const { sessionId, token } = await issueSession(prisma, user.id, tenantId); + return { userId: user.id, email, sessionId, token }; +} + +/** + * Delete `tenantIds` with their memberships plus the users and sessions left + * without any membership. Users who still belong to another tenant keep their + * rows and sessions, so one test's cleanup cannot orphan a neighbour tenant's + * fixtures. Order follows the existing integration tests: sessions, + * memberships, users, tenants. + */ +export async function cleanupTenants(prisma: PrismaClient, tenantIds: string[]): Promise { + if (tenantIds.length === 0) return; + const members = await prisma.membership.findMany({ + where: { tenantId: { in: tenantIds } }, + select: { userId: true }, + }); + const memberIds = [...new Set(members.map((member) => member.userId))]; + await prisma.membership.deleteMany({ where: { tenantId: { in: tenantIds } } }); + const survivors = await prisma.membership.findMany({ + where: { userId: { in: memberIds } }, + select: { userId: true }, + }); + const survivorIds = new Set(survivors.map((member) => member.userId)); + const orphanedIds = memberIds.filter((id) => !survivorIds.has(id)); + if (orphanedIds.length > 0) { + await prisma.session.deleteMany({ where: { userId: { in: orphanedIds } } }); + await prisma.user.deleteMany({ where: { id: { in: orphanedIds } } }); + } + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); +} diff --git a/apps/server/src/types/shims.d.ts b/apps/server/src/types/shims.d.ts index d30a9404..07d964d2 100644 --- a/apps/server/src/types/shims.d.ts +++ b/apps/server/src/types/shims.d.ts @@ -18,7 +18,8 @@ declare module 'unzipper' { } declare module 'multer' { - import type { RequestHandler } from 'express'; + import type { Request, RequestHandler } from 'express'; + import type { Readable } from 'node:stream'; interface MulterFile { fieldname: string; @@ -48,14 +49,67 @@ declare module 'multer' { any(): RequestHandler; } + // File handed to a storage engine by multer 2.4.0 (lib/make-middleware.js). + // The stream is only present while _handleFile runs. + interface StorageEngineFile { + fieldname: string; + originalname: string; + encoding: string; + mimetype: string; + stream: Readable; + } + + interface StoredFileInfo { + buffer?: Buffer; + size?: number; + } + + interface TypedStorageEngine { + _handleFile( + req: Request, + file: StorageEngineFile, + callback: (error: Error | null, info?: StoredFileInfo) => void, + ): void; + _removeFile(req: Request, file: StorageEngineFile & StoredFileInfo, callback: (error: Error | null) => void): void; + } + + interface TypedOptions { + storage?: TypedStorageEngine; + limits?: { fileSize?: number; files?: number; fields?: number; fieldSize?: number; parts?: number }; + } + + type MulterErrorCode = + | 'LIMIT_PART_COUNT' + | 'LIMIT_FILE_SIZE' + | 'LIMIT_FILE_COUNT' + | 'LIMIT_FIELD_KEY' + | 'LIMIT_FIELD_VALUE' + | 'LIMIT_FIELD_COUNT' + | 'LIMIT_UNEXPECTED_FILE' + | 'MISSING_FIELD_NAME' + | 'LIMIT_FIELD_NESTING' + | 'LIMIT_FIELD_ARRAY_INDEX' + | 'STREAM_DESTROYED' + | 'INVALID_FIELD_NAME'; + + interface MulterErrorInstance extends Error { + code: MulterErrorCode; + field?: string; + filename?: string; + } + interface MulterFactory { (options?: MulterOptions): MulterInstance; memoryStorage(): StorageEngine; diskStorage(opts: Record): StorageEngine; + MulterError: new (code: MulterErrorCode, field?: string, filename?: string) => MulterErrorInstance; } namespace multer { type File = MulterFile; + type Multer = MulterInstance; + type StorageEngine = TypedStorageEngine; + type Options = TypedOptions; } const multer: MulterFactory; diff --git a/apps/server/test/fixtures/adminResetDeliveryProbe.ts b/apps/server/test/fixtures/adminResetDeliveryProbe.ts new file mode 100644 index 00000000..a2becc1b --- /dev/null +++ b/apps/server/test/fixtures/adminResetDeliveryProbe.ts @@ -0,0 +1,60 @@ +import net from 'node:net'; +import request from 'supertest'; +import { createHttpFixture } from './httpFixture.js'; +import { registerAdminPasswordResetRoutes } from '../../src/api/routes/admin.passwordReset.js'; + +delete process.env.RESEND_API_KEY; +delete process.env.SMTP_HOST; +delete process.env.SMTP_FROM; +delete process.env.SMTP_USER; +delete process.env.SMTP_PASS; +process.env.SMTP_POOL = 'false'; +process.env.SMTP_VERIFY_ON_BOOT = 'false'; +process.env.PUBLIC_BASE_URL = 'https://app.example.test'; + +const port = await new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + server.close(); + reject(new Error('No probe port')); + return; + } + server.close((error) => (error ? reject(error) : resolve(address.port))); + }); +}); +process.env.SMTP_HOST = '127.0.0.1'; +process.env.SMTP_PORT = String(port); +process.env.SMTP_FROM = 'fixture-mail@example.test'; +process.env.SMTP_SECURE = 'false'; + +const fixture = createHttpFixture(); +try { + const { tenant } = await fixture.tenant(); + const admin = await fixture.caller(tenant, 'admin'); + const target = await fixture.caller(tenant); + const app = fixture.app(); + registerAdminPasswordResetRoutes(app, fixture.prisma); + const response = await request(app) + .post(`/admin/users/${target.id}/reset-token`) + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${admin.session}`) + .send({}); + const body: unknown = response.body; + const secret = + !!body && + typeof body === 'object' && + ('token' in body || 'resetUrl' in body); + const unused = await fixture.prisma.passwordReset.count({ + where: { userId: target.id, usedAt: null }, + }); + process.stdout.write( + `ADMIN_RESET_DELIVERY_RESULT:${JSON.stringify({ status: response.status, secret, unused })}\n`, + ); + // Allow the configured provider retries for the real local SMTP failure. + await new Promise((resolve) => setTimeout(resolve, 4000)); +} finally { + await fixture.close(); +} diff --git a/apps/server/test/fixtures/consoleDeliveryProbe.ts b/apps/server/test/fixtures/consoleDeliveryProbe.ts new file mode 100644 index 00000000..8bbac039 --- /dev/null +++ b/apps/server/test/fixtures/consoleDeliveryProbe.ts @@ -0,0 +1,7 @@ +import { ConsoleEmailProvider } from '../../src/email/consoleProvider.js'; +await new ConsoleEmailProvider().send({ + to: 'private-fixture@example.test', + subject: 'PRIVATE_SUBJECT', + text: 'PRIVATE_BODY https://example.test/#/verify?token=PRIVATE_TOKEN', + html: '

PRIVATE_HTML

', +}); diff --git a/apps/server/test/fixtures/emailProofFixture.ts b/apps/server/test/fixtures/emailProofFixture.ts new file mode 100644 index 00000000..b3f4a07d --- /dev/null +++ b/apps/server/test/fixtures/emailProofFixture.ts @@ -0,0 +1,68 @@ +import crypto from 'node:crypto'; +import request from 'supertest'; +import { expect } from 'vitest'; +import { createHttpFixture } from './httpFixture.js'; +import { createMailFixture } from './mailFixture.js'; +import { registerAuthRoutes } from '../../src/api/routes/auth.js'; +import { registerMiscRoutes } from '../../src/api/routes/misc.js'; +import { registerInviteRoutes } from '../../src/api/routes/invites.js'; +import { registerAdminPasswordResetRoutes } from '../../src/api/routes/admin.passwordReset.js'; +import { errorHandler } from '../../src/api/errorHandler.js'; + +export function createEmailProofFixture() { + const originalBase = process.env.PUBLIC_BASE_URL; + process.env.PUBLIC_BASE_URL ??= 'https://app.example.test'; + const fixture = createHttpFixture(); + const mail = createMailFixture(); + const app = fixture.app(); + registerAuthRoutes(app, fixture.prisma); + registerMiscRoutes(app, fixture.prisma); + registerInviteRoutes(app, fixture.prisma); + registerAdminPasswordResetRoutes(app, fixture.prisma); + app.use(errorHandler); + const email = () => `fixture-account-${crypto.randomUUID()}@example.test`; + async function registration() { + const own = await fixture.tenant(); + const target = email(); + fixture.userEmails.push(target); + const code = crypto.randomBytes(12).toString('hex'); + const invite = await fixture.prisma.invite.create({ + data: { + tenantId: own.tenant.id, + email: target, + code, + role: 'admin', + expiresAt: new Date(Date.now() + 3_600_000), + }, + }); + const password = crypto.randomBytes(20).toString('hex'); + const result = await request(app) + .post('/auth/register') + .set('X-Tenant', own.tenant.slug) + .send({ code, email: target, password }); + expect(result.status).toBe(409); + expect(result.body.code).toBe('EMAIL_VERIFICATION_REQUIRED'); + const user = await fixture.prisma.user.findUniqueOrThrow({ where: { email: target } }); + fixture.userIds.push(user.id); + const cookies = result.headers['set-cookie']; + const cookie = Array.isArray(cookies) + ? cookies.find((value: string) => value.startsWith('auth_token='))?.split(';')[0] + : null; + if (!cookie) throw new Error('Pending registration did not create a restricted session cookie.'); + return { ...own, user, invite, token: await mail.token(target), password, cookie }; + } + return { + fixture, + mail, + app, + email, + registration, + tokenFromMail: mail.token, + close: async () => { + await mail.close(); + await fixture.close(); + if (originalBase === undefined) delete process.env.PUBLIC_BASE_URL; + else process.env.PUBLIC_BASE_URL = originalBase; + }, + }; +} diff --git a/apps/server/test/fixtures/forgotDeliveryProbe.ts b/apps/server/test/fixtures/forgotDeliveryProbe.ts new file mode 100644 index 00000000..5f01764f --- /dev/null +++ b/apps/server/test/fixtures/forgotDeliveryProbe.ts @@ -0,0 +1,51 @@ +import crypto from 'node:crypto'; +import net from 'node:net'; +import request from 'supertest'; +import { createHttpFixture } from './httpFixture.js'; +import { registerAuthRoutes } from '../../src/api/routes/auth.js'; + +const mode = process.argv[2]; +delete process.env.RESEND_API_KEY; +delete process.env.SMTP_HOST; +delete process.env.SMTP_FROM; +delete process.env.SMTP_USER; +delete process.env.SMTP_PASS; +process.env.SMTP_POOL = 'false'; +process.env.SMTP_VERIFY_ON_BOOT = 'false'; +process.env.PUBLIC_BASE_URL = 'https://app.example.test'; +if (mode === 'closed_smtp') { + const port = await new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + server.close(); + reject(new Error('Kein Probe-Port')); + return; + } + server.close((error) => (error ? reject(error) : resolve(address.port))); + }); + }); + process.env.SMTP_HOST = '127.0.0.1'; + process.env.SMTP_PORT = String(port); + process.env.SMTP_FROM = 'fixture-mail@example.test'; + process.env.SMTP_SECURE = 'false'; +} +const fixture = createHttpFixture(); +try { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant, 'member', crypto.randomBytes(20).toString('hex')); + const user = await fixture.prisma.user.findUniqueOrThrow({ where: { id: caller.id } }); + const app = fixture.app(); + registerAuthRoutes(app, fixture.prisma); + const response = await request(app).post('/auth/forgot').send({ email: user.email }); + process.stdout.write( + `PASSWORD_RESET_DELIVERY_RESULT:${JSON.stringify({ status: response.status, secret: 'token' in response.body || 'resetUrl' in response.body })}\n`, + ); + // Allow the configured provider retries for the real local SMTP failure. + if (mode === 'closed_smtp') await new Promise((resolve) => setTimeout(resolve, 4000)); + else await new Promise((resolve) => setTimeout(resolve, 100)); +} finally { + await fixture.close(); +} diff --git a/apps/server/test/fixtures/httpFixture.ts b/apps/server/test/fixtures/httpFixture.ts new file mode 100644 index 00000000..f9bc9bd9 --- /dev/null +++ b/apps/server/test/fixtures/httpFixture.ts @@ -0,0 +1,125 @@ +import crypto from 'crypto'; +import bcrypt from 'bcryptjs'; +import express from 'express'; +import cookieParser from 'cookie-parser'; +import jwt from 'jsonwebtoken'; +import type { Role, Tenant } from '../../src/generated/prisma/index.js'; +import { createPrismaClient } from '../../src/db.js'; +import { resolveTenantBySlug } from '../../src/tenancy.js'; +import { createTenantAccessMiddleware } from '../../src/api/middleware/tenantAccess.js'; +import { createSessionAuthMiddleware, hashSessionToken } from '../../src/api/utils/sessionAuth.js'; +import { invalidateSessionsForUser } from '../../src/api/utils/sessionCache.js'; +import { getApiTokenPepper, getJwtSecret } from '../../src/api/utils/authHelpers.js'; + +export interface TestCaller { + id: string; + session: string; + sessionId: string; + apiToken: string; +} + +/** Real isolated database fixtures using the production authentication and resolver. */ +export function createHttpFixture() { + const databaseUrl = process.env.DATABASE_URL; + if (!databaseUrl) throw new Error('This test requires the assigned isolated DATABASE_URL'); + const parsed = new URL(databaseUrl); + if (parsed.hostname !== '127.0.0.1' || parsed.port !== '35440') { + throw new Error('This test may only use the local test database on port 35440'); + } + const prisma = createPrismaClient(); + const tenantIds: string[] = []; + const userIds: string[] = []; + const userEmails: string[] = []; + + async function tenant() { + const slug = `fixture-account-${crypto.randomUUID()}`; + const value = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(value.id); + const map = await prisma.map.create({ + data: { tenantId: value.id, name: 'office', meta: {}, width: 4, height: 4, tileWidth: 32, tileHeight: 32 }, + }); + const room = await prisma.room.create({ data: { tenantId: value.id, mapId: map.id, name: 'lobby' } }); + return { tenant: value, map, room }; + } + + async function session(userId: string, tenantId: string) { + const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + const row = await prisma.session.create({ + data: { userId, tokenHash: hashSessionToken(token), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + return { token, id: row.id }; + } + + async function caller(tenantValue: Tenant, role: Role = 'member', password?: string): Promise { + const user = await prisma.user.create({ + data: { + email: `fixture-account-${crypto.randomUUID()}@example.test`, + emailVerifiedAt: new Date(), + passwordHash: password ? await bcrypt.hash(password, 4) : undefined, + }, + }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId: tenantValue.id, role } }); + const auth = await session(user.id, tenantValue.id); + const apiToken = `mt_${crypto.randomBytes(24).toString('hex')}`; + const hash = crypto + .createHash('sha256') + .update(getApiTokenPepper() + apiToken) + .digest('hex'); + await prisma.apiToken.create({ data: { userId: user.id, hash, name: 'http-fixture-caller' } }); + return { id: user.id, session: auth.token, sessionId: auth.id, apiToken }; + } + + function app() { + const value = express(); + value.use(cookieParser()); + value.use(express.json()); + value.use((req, _res, next) => { + void resolveTenantBySlug(prisma, req) + .then((resolved) => { + req.tenant = resolved ?? undefined; + req.tenantId = resolved?.id; + next(); + }) + .catch((error: unknown) => next(error)); + }); + value.use(createSessionAuthMiddleware(prisma)); + value.use(createTenantAccessMiddleware(prisma)); + return value; + } + + async function close() { + const created = await prisma.user.findMany({ where: { email: { in: userEmails } }, select: { id: true } }); + for (const user of created) if (!userIds.includes(user.id)) userIds.push(user.id); + for (const id of userIds) invalidateSessionsForUser(id); + try { + const maps = await prisma.map.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } }); + const mapIds = maps.map((map) => map.id); + await prisma.mapChunk.deleteMany({ where: { layer: { mapId: { in: mapIds } } } }); + await prisma.mapLayer.deleteMany({ where: { mapId: { in: mapIds } } }); + await prisma.mapTileset.deleteMany({ where: { mapId: { in: mapIds } } }); + await prisma.mapAutotile.deleteMany({ where: { mapId: { in: mapIds } } }); + await prisma.mapObject.deleteMany({ where: { mapId: { in: mapIds } } }); + await prisma.zone.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.presence.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.npcMediaFile.deleteMany({ where: { npc: { tenantId: { in: tenantIds } } } }); + await prisma.npc.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.room.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.map.deleteMany({ where: { id: { in: mapIds } } }); + await prisma.invite.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.emailVerification.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.passwordReset.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.apiToken.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + } finally { + await prisma.$disconnect(); + } + } + + return { prisma, tenant, caller, session, app, close, tenantIds, userIds, userEmails }; +} diff --git a/apps/server/test/fixtures/mailFixture.ts b/apps/server/test/fixtures/mailFixture.ts new file mode 100644 index 00000000..f6a8bce8 --- /dev/null +++ b/apps/server/test/fixtures/mailFixture.ts @@ -0,0 +1,37 @@ +import { request as apiRequest, type APIRequestContext } from '@playwright/test'; +import { createMailpitClient, type MailpitClient } from '../../../web/e2e/support/mailpit.js'; + +/** Use the existing Mailpit client and actual local mail delivery. */ +export function createMailFixture() { + let context: APIRequestContext | undefined; + let mailpit: MailpitClient | undefined; + async function connect() { + if (mailpit) return mailpit; + const base = process.env.MAILPIT_URL; + if (!base || !['127.0.0.1', 'localhost'].includes(new URL(base).hostname)) + throw new Error('The assigned local Mailpit service is missing.'); + if (!['127.0.0.1', 'localhost'].includes(process.env.SMTP_HOST ?? '')) + throw new Error('Actual local SMTP delivery is not configured.'); + const port = Number(process.env.SMTP_PORT); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('The assigned SMTP port is missing.'); + context = await apiRequest.newContext(); + mailpit = createMailpitClient(context, base); + return mailpit; + } + async function token(to: string, purpose: 'verify' | 'reset' = 'verify') { + const client = await connect(); + const pattern = purpose === 'verify' ? /#\/verify\?token=/ : /#\/reset\?token=/; + const message = await client.waitForMail({ to, linkPattern: pattern }); + const link = client.extractLinks(message).find((candidate) => pattern.test(candidate)); + const raw = link ? new URLSearchParams(new URL(link).hash.split('?')[1]).get('token') : null; + if (!raw) throw new Error('The delivered email contains no expected link.'); + return raw; + } + return { + connect, + token, + close: async () => { + await context?.dispose(); + }, + }; +} diff --git a/apps/server/test/fixtures/requestTelemetry.ts b/apps/server/test/fixtures/requestTelemetry.ts new file mode 100644 index 00000000..e84f2f54 --- /dev/null +++ b/apps/server/test/fixtures/requestTelemetry.ts @@ -0,0 +1,95 @@ +/** + * Kindprozess-Fixture für requestTelemetry.test.ts. + * + * Baut eine echte Express-App mit der echten metricsMiddleware und dem echten + * requestLogger, feuert drei echte HTTP-Requests über supertest und schreibt + * danach genau eine JSON-Ergebniszeile nach stdout. Die Pino-Logzeilen sind + * die eigene stdout-Ausgabe der Middleware und werden vom Elterntest geparst; + * hier wird nichts synthetisiert. + */ +import express from 'express'; +import request from 'supertest'; +import { metricsMiddleware, registry } from '../../src/metrics.js'; +import { requestLogger } from '../../src/api/requestLogger.js'; + +const RESULT_MARKER = 'qdisc12-telemetry-result'; + +interface CaseResult { + key: string; + status: number; +} + +interface RouteLabel { + labels: Record; + value: number; +} + +function buildApp(): express.Application { + const app = express(); + app.use(metricsMiddleware()); + app.use(requestLogger); + app.get('/invites/:code', (_req, res) => { + res.status(200).type('text/plain').send('ok'); + }); + const api = express.Router(); + api.get('/invites/:code', (_req, res) => { + res.status(200).type('text/plain').send('ok'); + }); + app.use('/api', api); + return app; +} + +async function readRouteLabels(): Promise { + const metric = registry.getSingleMetric('meetropolis_http_request_duration_seconds'); + if (!metric) { + throw new Error('Metrik meetropolis_http_request_duration_seconds fehlt im Registry'); + } + const data = (await metric.get()) as { values: RouteLabel[] }; + return data.values; +} + +async function waitForObservations(expected: number): Promise { + const deadline = Date.now() + 5000; + for (;;) { + const values = await readRouteLabels(); + const count = values + .filter((v) => v.labels['method'] === 'GET' && v.labels['le'] === '+Inf') + .reduce((sum, v) => sum + v.value, 0); + if (count >= expected) return; + if (Date.now() > deadline) { + throw new Error(`nur ${count} von ${expected} Metrikbeobachtungen nach 5 Sekunden`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +async function main(): Promise { + const app = buildApp(); + const server = await new Promise>((resolve, reject) => { + const s = app.listen(0, '127.0.0.1', () => resolve(s)); + s.on('error', reject); + }); + const address = server.address(); + if (typeof address !== 'object' || address === null || typeof address.port !== 'number') { + throw new Error('ephemerer Server meldete keine nutzbare Adresse'); + } + const agent = request(`http://127.0.0.1:${address.port}`); + const cases: CaseResult[] = []; + try { + const a = await agent.get('/invites/QDISC12_CODE?x=y').set('x-correlation-id', 'qdisc12-a'); + cases.push({ key: 'plain-param', status: a.status }); + const b = await agent.get('/missing/QDISC12_MISS?x=y').set('x-correlation-id', 'qdisc12-b'); + cases.push({ key: 'unmatched', status: b.status }); + const c = await agent.get('/api/invites/QDISC12_MOUNT?x=y').set('x-correlation-id', 'qdisc12-c'); + cases.push({ key: 'mounted-param', status: c.status }); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + await waitForObservations(3); + const metricValues = await readRouteLabels(); + process.stdout.write(`${JSON.stringify({ marker: RESULT_MARKER, cases, metricValues })}\n`); + // main kehrt zurück; ohne offene Handles läuft der Prozess natürlich aus, + // stdout drainet dabei vollständig. +} + +void main(); diff --git a/apps/server/test/fixtures/uploadFixture.ts b/apps/server/test/fixtures/uploadFixture.ts new file mode 100644 index 00000000..b298d652 --- /dev/null +++ b/apps/server/test/fixtures/uploadFixture.ts @@ -0,0 +1,57 @@ +import http from 'node:http'; +import { once } from 'node:events'; +import type express from 'express'; + +/** Stream real HTTP requests without buffering the entire multipart body. */ +export async function uploadTransport(app: express.Application) { + const server = http.createServer(app); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('No local test port'); + const serverRequests: http.IncomingMessage[] = []; + server.on('request', (req) => serverRequests.push(req)); + function open(route: string, headers: Record) { + const req = http.request({ host: '127.0.0.1', port: address.port, path: route, method: 'POST', headers }); + const result = new Promise<{ status: number; retryAfter: number }>((resolve, reject) => { + req.once('response', (res) => { + res.resume(); + res.once('end', () => + resolve({ status: res.statusCode ?? 0, retryAfter: Number(res.headers['retry-after'] ?? 0) }), + ); + }); + req.once('error', reject); + }); + // Close each open upload through its own request in finally. + void result.catch(() => {}); + req.flushHeaders(); + return { req, result }; + } + async function ready(count: number) { + const deadline = Date.now() + 5_000; + while (Date.now() < deadline) { + if ( + serverRequests.length >= count && + serverRequests.slice(0, count).every((req) => req.listenerCount('data') > 0) + ) + return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error('The actual upload parser did not become ready.'); + } + async function close() { + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); + } + return { open, ready, close }; +} + +export async function writeBytes(req: http.ClientRequest, size: number, byte = 32) { + const block = Buffer.alloc(64 * 1024, byte); + let sent = 0; + while (sent < size && !req.destroyed && !req.writableEnded) { + const chunk = block.subarray(0, Math.min(block.length, size - sent)); + if (!req.write(chunk)) await once(req, 'drain'); + sent += chunk.length; + } +} diff --git a/apps/server/test/fixtures/verifyDeliveryProbe.ts b/apps/server/test/fixtures/verifyDeliveryProbe.ts new file mode 100644 index 00000000..089fc3a7 --- /dev/null +++ b/apps/server/test/fixtures/verifyDeliveryProbe.ts @@ -0,0 +1,47 @@ +import net from 'node:net'; +import request from 'supertest'; +import { createHttpFixture } from './httpFixture.js'; +import { registerAuthRoutes } from '../../src/api/routes/auth.js'; + +// Use a separate process with the actual loader and delivery path and isolated boot configuration. +const port = await new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + server.close(); + reject(new Error('Kein Testport')); + return; + } + server.close((error) => (error ? reject(error) : resolve(address.port))); + }); +}); +process.env.SMTP_HOST = '127.0.0.1'; +process.env.SMTP_PORT = String(port); +process.env.SMTP_FROM = 'fixture-mail@example.test'; +process.env.SMTP_SECURE = 'false'; +process.env.SMTP_VERIFY_ON_BOOT = 'false'; +process.env.SMTP_POOL = 'false'; +delete process.env.SMTP_USER; +delete process.env.SMTP_PASS; +delete process.env.RESEND_API_KEY; +process.env.PUBLIC_BASE_URL = 'https://app.example.test'; +const fixture = createHttpFixture(); +try { + const { tenant } = await fixture.tenant(); + const caller = await fixture.caller(tenant); + await fixture.prisma.user.update({ where: { id: caller.id }, data: { emailVerifiedAt: null } }); + const app = fixture.app(); + registerAuthRoutes(app, fixture.prisma); + const res = await request(app) + .post('/auth/verify/request') + .set('X-Tenant', tenant.slug) + .set('Authorization', `Bearer ${caller.session}`) + .send({}); + const body: unknown = res.body; + const secret = !!body && typeof body === 'object' && ('token' in body || 'verifyUrl' in body); + process.stdout.write(`VERIFICATION_DELIVERY_RESULT:${JSON.stringify({ status: res.status, secret })}\n`); +} finally { + await fixture.close(); +} diff --git a/apps/web/e2e/accounts/emailChange.spec.ts b/apps/web/e2e/accounts/emailChange.spec.ts new file mode 100644 index 00000000..14cb1ab9 --- /dev/null +++ b/apps/web/e2e/accounts/emailChange.spec.ts @@ -0,0 +1,118 @@ +import { test, expect } from '../fixtures'; +import { browserForTenant, confirmationLink, mailProofFixture, newEmail, openProfile } from './mailProof.support'; + +test.use({ locale: 'de-DE', trace: 'off', screenshot: 'off', video: 'off' }); + +test('pending contract: an email change shows pending confirmation and keeps the old address active', async ({ + stack, + seed, + db, + loginAs, + mailpit, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account(); + const target = newEmail(); + fixture.trackEmail(target); + try { + const { page } = await loginAs(user); + await openProfile(page); + await page.locator('input[type="email"]').fill(target); + await page.getByRole('button', { name: /^(Mailwechsel anfordern|Änderungen speichern)$/ }).click(); + await confirmationLink(mailpit, target); + await mailpit.waitForMail({ to: user.email, subject: 'Email change requested' }); + await expect(page.getByText(/Bestätigungslink an .* gesendet/)).toBeVisible(); + const row = await db.query( + 'SELECT "email"=$2 AS unchanged, "emailVerifiedAt" IS NOT NULL AS verified FROM "User" WHERE "id"=$1', + [user.userId, user.email], + ); + expect(row.rows[0]).toEqual({ unchanged: true, verified: true }); + } finally { + await fixture.cleanup(); + } +}); + +test('pending contract: a separate unauthenticated browser confirms the email change and offers the next action', async ({ + browser, + stack, + seed, + db, + mailpit, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account(); + const target = newEmail(); + fixture.trackEmail(target); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + const mailBrowser = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const login = await context.request.post(`${stack.apiUrl}/auth/login`, { + data: { email: user.email, password: user.password }, + }); + if (!login.ok()) throw new Error('The actual login failed.'); + const change = await context.request.patch(`${stack.apiUrl}/me`, { data: { email: target } }); + if (change.status() !== 202) throw new Error(`Email-change HTTP prerequisite: ${change.status()}`); + const link = await confirmationLink(mailpit, target); + await mailpit.waitForMail({ to: user.email, subject: 'Email change requested' }); + const page = await mailBrowser.newPage(); + await page.goto(link); + await expect(page.getByRole('heading', { name: 'E-Mail-Adresse geändert' })).toBeVisible(); + const row = await db.query( + 'SELECT "email"=$2 AS changed, "emailVerifiedAt" IS NOT NULL AS verified FROM "User" WHERE "id"=$1', + [user.userId, target], + ); + expect(row.rows[0]).toEqual({ changed: true, verified: true }); + expect(page.url().includes('token=')).toBe(false); + await page.getByRole('button', { name: 'Weiter zur Anmeldung oder zum Büro' }).click(); + await expect(page.getByRole('heading', { name: 'Willkommen zurück' })).toBeVisible(); + } finally { + await context.close(); + await mailBrowser.close(); + await fixture.cleanup(); + } +}); + +test('shows delivery failure without a partial email change during a real SMTP outage and restores delivery', async ({ + stack, + seed, + db, + loginAs, + mailpit, + stackControl, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account(); + const target = newEmail(); + fixture.trackEmail(target); + test.setTimeout(180_000); + let paused = false; + try { + const { page } = await loginAs(user); + await openProfile(page); + await stackControl.pause('mailpit'); + paused = true; + await page.locator('input[type="email"]').fill(target); + const response = page.waitForResponse( + (response) => response.url().endsWith('/me') && response.request().method() === 'PATCH', + { timeout: 90_000 }, + ); + await page.getByRole('button', { name: 'Mailwechsel anfordern', exact: true }).click(); + expect((await response).status()).toBe(503); + await expect(page.getByText(/could not be delivered|Verification request failed/)).toBeVisible(); + const row = await db.query('SELECT "email"=$2 AS unchanged FROM "User" WHERE "id"=$1', [user.userId, user.email]); + expect(row.rows[0]?.unchanged).toBe(true); + const proof = await db.query( + 'SELECT count(*)::int AS count FROM "EmailVerification" WHERE "userId"=$1 AND "readyAt" IS NOT NULL AND "usedAt" IS NULL', + [user.userId], + ); + expect(proof.rows[0]?.count).toBe(0); + await stackControl.unpause('mailpit'); + paused = false; + await page.getByRole('button', { name: 'Mailwechsel anfordern', exact: true }).click(); + await confirmationLink(mailpit, target); + await expect(page.getByText(/Bestätigungslink an .* gesendet/)).toBeVisible(); + } finally { + if (paused) await stackControl.unpause('mailpit'); + await fixture.cleanup(); + } +}); diff --git a/apps/web/e2e/accounts/inviteVerification.spec.ts b/apps/web/e2e/accounts/inviteVerification.spec.ts new file mode 100644 index 00000000..bd9eda38 --- /dev/null +++ b/apps/web/e2e/accounts/inviteVerification.spec.ts @@ -0,0 +1,335 @@ +import { createApiRequest, MeetropolisApi } from '../support/api'; +import { test, expect } from '../fixtures'; +import { browserForTenant, confirmationLink, mailProofFixture, newEmail, signIn } from './mailProof.support'; + +test.use({ locale: 'de-DE', trace: 'off', screenshot: 'off', video: 'off' }); + +test('pending contract: a new registration stays outside the world until separate mailbox proof', async ({ + browser, + playwright, + stack, + seed, + db, + mailpit, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const email = newEmail(); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const invite = await fixture.invite(playwright.request, email); + const invitation = await mailpit.waitForMail({ to: email, linkPattern: /invite=/ }); + const link = mailpit.extractLinks(invitation).find((candidate) => candidate.includes('invite=')); + if (!link) throw new Error('Invitation email is missing.'); + const page = await context.newPage(); + let registrations = 0; + page.on('request', (req) => { + if (req.method() === 'POST' && req.url().endsWith('/auth/register')) registrations++; + }); + await page.goto(link); + await page.getByRole('button', { name: 'Registrieren', exact: true }).click(); + await page.getByLabel('Vorname').fill('Mailbox'); + await page.getByLabel('Nachname').fill('Testperson'); + await page.getByLabel('Geschäftliche E-Mail').fill(email); + await page.getByLabel('Passwort', { exact: true }).fill(stack.userPassword); + await page.getByRole('button', { name: 'Weiter', exact: true }).click(); + const verifyLink = await confirmationLink(mailpit, email); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + expect(registrations).toBe(1); + expect(await fixture.membershipCount(email)).toBe(0); + await page.reload(); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + const mailBrowser = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const mailPage = await mailBrowser.newPage(); + await mailPage.goto(verifyLink); + await expect(mailPage.getByRole('heading', { name: 'Einladung bestätigt' })).toBeVisible(); + expect(await fixture.membershipCount(email)).toBe(1); + const used = await db.query('SELECT "usedAt" IS NOT NULL AS used FROM "Invite" WHERE "code"=$1', [invite.code]); + expect(used.rows[0]?.used).toBe(true); + } finally { + await mailBrowser.close(); + } + await page.getByRole('button', { name: 'Bestätigung prüfen', exact: true }).click(); + await page.getByLabel('E-Mail-Adresse', { exact: true }).fill(email); + await page.getByLabel('Passwort', { exact: true }).fill(stack.userPassword); + await page.getByRole('button', { name: 'Anmelden', exact: true }).click(); + await page.waitForURL(/#\/app(?:$|\?)/); + const me = await context.request.get(`${stack.apiUrl}/auth/me`); + expect(me.status()).toBe(200); + const granted: unknown = await me.json(); + expect( + !!granted && + typeof granted === 'object' && + 'tenantSlug' in granted && + granted.tenantSlug === fixture.tenant.slug && + 'role' in granted && + granted.role === 'member', + ).toBe(true); + } finally { + await context.close(); + await fixture.cleanup(); + } +}); + +test('pending contract: an existing unverified account keeps its invitation after acceptance and reload', async ({ + browser, + playwright, + stack, + seed, + db, + mailpit, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account({ verified: false, member: false }); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const invitation = await fixture.invite(playwright.request, user.email); + const page = await context.newPage(); + await page.goto(`${stack.baseUrl}/#/?invite=${invitation.code}`); + await page.getByRole('button', { name: 'Anmelden', exact: true }).click(); + await page.getByLabel('E-Mail-Adresse', { exact: true }).fill(user.email); + await page.getByLabel('Passwort', { exact: true }).fill(user.password!); + await page.getByRole('button', { name: 'Anmelden', exact: true }).click(); + await confirmationLink(mailpit, user.email); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + expect(await fixture.membershipCount(user.email)).toBe(0); + await page.reload(); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + expect(await page.evaluate(() => !!sessionStorage.getItem('meetropolis.pendingInvite'))).toBe(true); + } finally { + await context.close(); + await fixture.cleanup(); + } +}); + +test('pending contract: a marked legacy membership requires proof after a correct login', async ({ + browser, + stack, + seed, + db, + mailpit, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account(); + await fixture.mark(user); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const page = await context.newPage(); + await signIn(page, stack, user); + await confirmationLink(mailpit, user.email); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + const result = await db.query('SELECT "inviteVerificationRequired" FROM "Membership" WHERE "userId"=$1', [ + user.userId, + ]); + expect(result.rows[0]?.inviteVerificationRequired).toBe(true); + } finally { + await context.close(); + await fixture.cleanup(); + } +}); + +test('pending contract: an existing marked session opens pending confirmation', async ({ + browser, + stack, + seed, + db, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account(); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const login = await context.request.post(`${stack.apiUrl}/auth/login`, { + data: { email: user.email, password: user.password }, + }); + if (!login.ok()) throw new Error(`Actual session creation: HTTP ${login.status()}`); + await fixture.mark(user); + const page = await context.newPage(); + await page.goto(`${stack.baseUrl}/#/app`); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + expect((await context.request.get(`${stack.apiUrl}/auth/me`)).status()).toBe(409); + } finally { + await context.close(); + await fixture.cleanup(); + } +}); + +test('accepts an invitation for a verified matching account without granting its role early', async ({ + browser, + playwright, + stack, + seed, + db, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const user = await fixture.account({ member: false }); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const invite = await fixture.invite(playwright.request, user.email); + const login = await context.request.post(`${stack.apiUrl}/auth/login`, { + data: { email: user.email, password: user.password }, + }); + expect(login.status()).toBe(200); + expect(await fixture.membershipCount(user.email)).toBe(0); + const accepted = await context.request.post(`${stack.apiUrl}/invites/accept`, { data: { code: invite.code } }); + expect(accepted.status()).toBe(200); + expect(await fixture.membershipCount(user.email)).toBe(1); + const me = await context.request.get(`${stack.apiUrl}/auth/me`); + expect(me.status()).toBe(200); + const body: unknown = await me.json(); + expect(!!body && typeof body === 'object' && 'tenantSlug' in body && body.tenantSlug === fixture.tenant.slug).toBe( + true, + ); + } finally { + await context.close(); + await fixture.cleanup(); + } +}); + +test('shows the actual resend cooldown without automatically retrying the request', async ({ + browser, + playwright, + stack, + seed, + db, + mailpit, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const email = newEmail(); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const invite = await fixture.invite(playwright.request, email); + const registered = await context.request.post(`${stack.apiUrl}/auth/register`, { + data: { code: invite.code, email, password: stack.userPassword }, + }); + expect(registered.status()).toBe(409); + await confirmationLink(mailpit, email); + const page = await context.newPage(); + await page.goto(`${stack.baseUrl}/#/verify-pending`); + let count = 0; + page.on('request', (request) => { + if (request.method() === 'POST' && request.url().endsWith('/auth/verify/request')) count++; + }); + const response = page.waitForResponse((response) => response.url().endsWith('/auth/verify/request')); + await page.getByRole('button', { name: 'Bestätigungsmail erneut anfordern' }).click(); + expect((await response).status()).toBe(429); + await expect(page.getByRole('status')).toContainText('Sekunden'); + expect(count).toBe(1); + await expect(page.getByRole('button', { name: 'Bestätigungsmail erneut anfordern' })).toBeDisabled(); + } finally { + await context.close(); + await fixture.cleanup(); + } +}); + +for (const action of ['expire', 'revoke']) { + test(`grants no access after ${action} during pending verification`, async ({ + browser, + playwright, + stack, + seed, + db, + mailpit, + }) => { + const fixture = mailProofFixture(db, seed, stack); + const email = newEmail(); + const context = await browserForTenant(browser, stack, fixture.tenant.slug); + const mailBrowser = await browserForTenant(browser, stack, fixture.tenant.slug); + try { + const invite = await fixture.invite(playwright.request, email); + expect( + ( + await context.request.post(`${stack.apiUrl}/auth/register`, { + data: { code: invite.code, email, password: stack.userPassword }, + }) + ).status(), + ).toBe(409); + const link = await confirmationLink(mailpit, email); + if (action === 'expire') + await db.query( + `UPDATE "EmailVerification" SET "expiresAt"=now()-interval '1 second' WHERE "userId" IN (SELECT "id" FROM "User" WHERE "email"=$1)`, + [email], + ); + else await db.query('DELETE FROM "Invite" WHERE "code"=$1', [invite.code]); + const page = await mailBrowser.newPage(); + await page.goto(link); + await expect( + page.getByText( + 'Dieser Link ist ungültig, abgelaufen oder bereits verwendet. Bitte fordere eine neue Bestätigung an.', + ), + ).toBeVisible(); + expect(await fixture.membershipCount(email)).toBe(0); + } finally { + await context.close(); + await mailBrowser.close(); + await fixture.cleanup(); + } + }); +} + +test('fixture contract: completes new registration and existing-account acceptance through the real mailbox', async ({ + playwright, + stack, + seed, + db, +}) => { + const fixture = mailProofFixture(db, seed, stack); + try { + for (const existing of [false, true]) { + const account = existing ? await fixture.account({ verified: false, member: false }) : null; + const email = account?.email ?? newEmail(); + const invite = await fixture.invite(playwright.request, email); + const context = await createApiRequest(playwright.request, stack.apiUrl, fixture.tenant.slug); + try { + // This context deliberately starts without an authenticated cookie. + const api = new MeetropolisApi(context, stack.apiUrl, fixture.tenant.slug); + const me = await api.registerWithInvite({ + code: invite.code, + email, + name: 'Mailbox test user', + password: account?.password ?? stack.userPassword, + }); + expect(me.tenantSlug).toBe(fixture.tenant.slug); + expect(me.role).toBe('member'); + expect(await fixture.membershipCount(email)).toBe(1); + const verified = await db.query( + 'SELECT "emailVerifiedAt" IS NOT NULL AS verified FROM "User" WHERE "email"=$1', + [email], + ); + expect(verified.rows[0]?.verified).toBe(true); + } finally { + await context.dispose(); + } + } + } finally { + await fixture.cleanup(); + } +}); + +test('fixture contract: rejects wrong credentials before accepting an existing account invitation', async ({ + playwright, + stack, + seed, + db, +}) => { + const fixture = mailProofFixture(db, seed, stack); + const account = await fixture.account({ verified: false, member: false }); + const invite = await fixture.invite(playwright.request, account.email); + const context = await createApiRequest(playwright.request, stack.apiUrl, fixture.tenant.slug); + try { + const api = new MeetropolisApi(context, stack.apiUrl, fixture.tenant.slug); + await expect( + api.registerWithInvite({ + code: invite.code, + email: account.email, + name: 'Mailbox test user', + password: 'incorrect-password', + }), + ).rejects.toThrow('/auth/login: HTTP 401.'); + expect(await fixture.membershipCount(account.email)).toBe(0); + const unchanged = await db.query('SELECT "usedAt" IS NULL AS unused FROM "Invite" WHERE "code"=$1', [invite.code]); + expect(unchanged.rows[0]?.unused).toBe(true); + } finally { + await context.dispose(); + await fixture.cleanup(); + } +}); diff --git a/apps/web/e2e/accounts/invites.spec.ts b/apps/web/e2e/accounts/invites.spec.ts new file mode 100644 index 00000000..0e5ba658 --- /dev/null +++ b/apps/web/e2e/accounts/invites.spec.ts @@ -0,0 +1,250 @@ +import crypto from 'crypto'; + +import type { APIRequest, APIRequestContext, Page } from '@playwright/test'; + +import { test, expect } from '../fixtures'; +import type { TestStackEnv } from '../fixtures'; +import { getSeedTenant } from '../fixtures/helpers'; +import { MeetropolisApi, createApiRequest } from '../support/api'; +import type { TenantSeed } from '../support/api'; +import type { Client } from 'pg'; +import type { SeedData } from '../support/api'; +import { mailProofFixture } from './mailProof.support'; + +test.use({ locale: 'de-DE' }); + +const PASSWORD = 'Qacc-E2E-Password-1'; +const APP_URL = /#\/app(?:$|\?)/; + +function uniqueEmail(): string { + return `invite-${crypto.randomUUID()}@example.test`; +} + +function inviteLinkFromMail(links: string[]): string { + const link = links.find((candidate) => candidate.includes('invite=')); + if (!link) throw new Error('Invitation email contains no invitation link.'); + return link; +} + +async function loginOwner(playwright: { request: APIRequest }, stack: TestStackEnv, tenant: TenantSeed) { + const owner = tenant.users.owner; + if (!owner) throw new Error(`Seed tenant ${tenant.slug} contains no owner.`); + const request = await createApiRequest(playwright.request, stack.apiUrl, tenant.slug); + const api = new MeetropolisApi(request, stack.apiUrl, tenant.slug); + await api.login(owner.email, owner.password ?? stack.userPassword); + return { api, request }; +} + +async function readPreview(playwright: { request: APIRequest }, apiUrl: string, code: string) { + const request: APIRequestContext = await playwright.request.newContext(); + try { + const res = await request.post(`${apiUrl}/public/invites/preview`, { data: { code } }); + if (!res.ok()) throw new Error(`POST /public/invites/preview: HTTP ${res.status()}.`); + return (await res.json()) as { tenantName: string; emailMasked: string; status: string }; + } finally { + await request.dispose(); + } +} + +async function readBrowserMe(page: Page, apiUrl: string): Promise<{ tenantSlug: string }> { + return page.evaluate(async (url: string) => { + const res = await fetch(`${url}/auth/me`, { credentials: 'include' }); + if (!res.ok) throw new Error(`GET /auth/me: HTTP ${res.status}.`); + return (await res.json()) as { tenantSlug: string }; + }, apiUrl); +} + +async function existingNonMemberAccount( + stack: TestStackEnv, + seed: SeedData, + tenant: TenantSeed, + db: Client, +): Promise<{ email: string; password: string; dispose: () => Promise }> { + const other = Object.values(seed.tenants).find( + (candidate) => candidate.slug !== tenant.slug && candidate.users.owner, + ); + const secondOwner = other?.users.owner; + if (secondOwner) { + return { + email: secondOwner.email, + password: secondOwner.password ?? stack.userPassword, + dispose: () => Promise.resolve(), + }; + } + const fixture = mailProofFixture(db, seed, stack); + try { + const account = await fixture.account({ member: false }); + return { email: account.email, password: account.password ?? stack.userPassword, dispose: fixture.cleanup }; + } catch (error: unknown) { + await fixture.cleanup(); + throw error; + } +} + +test.describe('invitations end to end', () => { + test('a new user registers from the invitation mail and lands in the tenant', async ({ + browser, + playwright, + stack, + seed, + mailpit, + db, + }) => { + const tenant = getSeedTenant(seed); + const { api: ownerApi, request: ownerRequest } = await loginOwner(playwright, stack, tenant); + try { + const email = uniqueEmail(); + const { code } = await ownerApi.invite(email, 'member'); + const mail = await mailpit.waitForMail({ to: email, linkPattern: /invite=/ }); + expect(mail.text).toMatch(/Die Einladung ist bis .* gültig\./); + const link = inviteLinkFromMail(mailpit.extractLinks(mail)); + const preview = await readPreview(playwright, stack.apiUrl, code); + + const context = await browser.newContext({ baseURL: stack.baseUrl, locale: 'de-DE' }); + try { + const page = await context.newPage(); + await page.goto(link); + await expect(page.getByRole('heading', { name: `Einladung zu ${preview.tenantName}` })).toBeVisible({ + timeout: 30_000, + }); + await expect(page.getByText(`Die Einladung gilt für ${preview.emailMasked}.`)).toBeVisible(); + await page.getByRole('button', { name: 'Registrieren' }).click(); + await page.getByLabel('Vorname').fill('Ada'); + await page.getByLabel('Nachname').fill('Lovelace'); + await page.getByLabel('Geschäftliche E-Mail').fill(email); + await page.getByLabel('Passwort').fill(PASSWORD); + await page.getByRole('button', { name: 'Weiter' }).click(); + await expect(page.getByRole('heading', { name: 'Bitte bestätige deine E-Mail-Adresse' })).toBeVisible(); + const before = await db.query( + 'SELECT count(*)::int AS count FROM "Membership" m JOIN "User" u ON u."id"=m."userId" WHERE u."email"=$1 AND m."tenantId"=$2', + [email, tenant.tenantId], + ); + expect(before.rows[0]?.count).toBe(0); + const proof = await mailpit.waitForMail({ to: email, linkPattern: /#\/verify\?token=/ }); + const verifyLink = mailpit.extractLinks(proof).find((candidate) => /#\/verify\?token=/.test(candidate)); + if (!verifyLink) throw new Error('The confirmation email contains no confirmation link.'); + const mailContext = await browser.newContext({ baseURL: stack.baseUrl, locale: 'de-DE' }); + try { + const mailPage = await mailContext.newPage(); + await mailPage.goto(verifyLink); + await expect(mailPage.getByRole('heading', { name: 'Einladung bestätigt' })).toBeVisible(); + } finally { + await mailContext.close(); + } + await page.getByRole('button', { name: 'Bestätigung prüfen', exact: true }).click(); + await page.getByLabel('E-Mail-Adresse', { exact: true }).fill(email); + await page.getByLabel('Passwort', { exact: true }).fill(PASSWORD); + await page.getByRole('button', { name: 'Anmelden', exact: true }).click(); + await page.waitForURL(APP_URL); + const me = await readBrowserMe(page, stack.apiUrl); + expect(me.tenantSlug).toBe(tenant.slug); + } finally { + await context.close(); + } + } finally { + await ownerRequest.dispose(); + } + }); + + test('an existing account accepts the invitation after signing in', async ({ + browser, + playwright, + stack, + seed, + mailpit, + db, + }) => { + const tenant = getSeedTenant(seed); + const { api: ownerApi, request: ownerRequest } = await loginOwner(playwright, stack, tenant); + try { + const account = await existingNonMemberAccount(stack, seed, tenant, db); + try { + await ownerApi.invite(account.email, 'member'); + const mail = await mailpit.waitForMail({ to: account.email, linkPattern: /invite=/ }); + const link = inviteLinkFromMail(mailpit.extractLinks(mail)); + + const context = await browser.newContext({ baseURL: stack.baseUrl, locale: 'de-DE' }); + try { + const page = await context.newPage(); + await page.goto(link); + await expect(page.getByRole('button', { name: 'Anmelden' })).toBeVisible({ timeout: 30_000 }); + await page.getByRole('button', { name: 'Anmelden' }).click(); + await expect(page.getByRole('heading', { name: 'Willkommen zurück' })).toBeVisible(); + await page.getByLabel('E-Mail-Adresse').fill(account.email); + await page.getByLabel('Passwort').fill(account.password); + await page.getByRole('button', { name: 'Anmelden' }).click(); + await page.waitForURL(APP_URL); + const me = await readBrowserMe(page, stack.apiUrl); + expect(me.tenantSlug).toBe(tenant.slug); + } finally { + await context.close(); + } + } finally { + await account.dispose(); + } + } finally { + await ownerRequest.dispose(); + } + }); + + test('an expired invitation cannot be accepted', async ({ browser, playwright, stack, seed, db }) => { + const tenant = getSeedTenant(seed); + const { api: ownerApi, request: ownerRequest } = await loginOwner(playwright, stack, tenant); + try { + const email = uniqueEmail(); + const { code } = await ownerApi.invite(email, 'member'); + await db.query( + `UPDATE "Invite" SET "expiresAt" = now() - interval '1 minute' WHERE "tenantId" = $1 AND "email" = $2`, + [tenant.tenantId, email], + ); + + const context = await browser.newContext({ baseURL: stack.baseUrl, locale: 'de-DE' }); + try { + const page = await context.newPage(); + await page.goto(`${stack.baseUrl.replace(/\/+$/, '')}/#/?invite=${code}`); + await expect(page.getByText('Diese Einladung ist abgelaufen. Bitte um eine neue Einladung.')).toBeVisible({ + timeout: 30_000, + }); + await expect(page.getByRole('button', { name: 'Einladung annehmen' })).toHaveCount(0); + } finally { + await context.close(); + } + } finally { + await ownerRequest.dispose(); + } + }); + + test('a revoked invitation is gone', async ({ browser, playwright, stack, seed, mailpit }) => { + const tenant = getSeedTenant(seed); + const { api: ownerApi, request: ownerRequest } = await loginOwner(playwright, stack, tenant); + try { + const email = uniqueEmail(); + await ownerApi.invite(email, 'member'); + const mail = await mailpit.waitForMail({ to: email, linkPattern: /invite=/ }); + const link = inviteLinkFromMail(mailpit.extractLinks(mail)); + + const listRes = await ownerRequest.get(`${stack.apiUrl}/invites`); + if (!listRes.ok()) throw new Error(`GET /invites: HTTP ${listRes.status()}.`); + const entries = (await listRes.json()) as Array<{ id?: unknown; email?: unknown }>; + const entry = entries.find( + (candidate) => typeof candidate.email === 'string' && candidate.email.toLowerCase() === email, + ); + if (!entry || typeof entry.id !== 'string') throw new Error('GET /invites does not contain the invitation.'); + const removal = await ownerRequest.delete(`${stack.apiUrl}/invites/${encodeURIComponent(entry.id)}`); + expect(removal.status()).toBe(200); + + const context = await browser.newContext({ baseURL: stack.baseUrl, locale: 'de-DE' }); + try { + const page = await context.newPage(); + await page.goto(link); + await expect(page.getByText('Diese Einladung gibt es nicht oder sie wurde widerrufen.')).toBeVisible({ + timeout: 30_000, + }); + } finally { + await context.close(); + } + } finally { + await ownerRequest.dispose(); + } + }); +}); diff --git a/apps/web/e2e/accounts/legacyInviteClients.spec.ts b/apps/web/e2e/accounts/legacyInviteClients.spec.ts new file mode 100644 index 00000000..c7c871ea --- /dev/null +++ b/apps/web/e2e/accounts/legacyInviteClients.spec.ts @@ -0,0 +1,102 @@ +import crypto from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { test, expect } from '../fixtures'; +import { createApiRequest } from '../support/api'; +import { mailProofFixture } from './mailProof.support'; + +test.use({ locale: 'de-DE', trace: 'off', screenshot: 'off', video: 'off' }); + +/** Use the actual legacy build from 1402ee5+e592dbd. */ +test('keeps a failed legacy code revocation visible while the invitation remains valid @legacy', async ({ + browser, + playwright, + stack, + seed, + db, +}) => { + const legacyBase = process.env.LEGACY_WEB_BASE_URL; + const manifestPath = process.env.LEGACY_WEB_BUNDLE_MANIFEST; + if (!legacyBase || !manifestPath) throw new Error('Approved legacy build evidence is missing.'); + const manifest: unknown = JSON.parse(await readFile(manifestPath, 'utf8')); + if ( + !manifest || + typeof manifest !== 'object' || + !('revision' in manifest) || + manifest.revision !== '1402ee5+e592dbd' || + !('files' in manifest) || + !manifest.files || + typeof manifest.files !== 'object' + ) + throw new Error('Invalid legacy bundle evidence.'); + const expected = new Map( + Object.entries(manifest.files).filter((entry): entry is [string, string] => typeof entry[1] === 'string'), + ); + const verified = new Set(); + const mismatches: string[] = []; + const fixture = mailProofFixture(db, seed, stack); + const target = await fixture.account({ member: false }); + const invitation = await fixture.invite(playwright.request, target.email); + const owner = fixture.tenant.users.owner; + if (!owner) throw new Error('Seed owner is missing.'); + const context = await browser.newContext({ + baseURL: legacyBase, + locale: 'de-DE', + extraHTTPHeaders: { 'X-Tenant': fixture.tenant.slug }, + }); + const targetRequest = await createApiRequest(playwright.request, stack.apiUrl, fixture.tenant.slug); + try { + const login = await context.request.post(`${stack.apiUrl}/auth/login`, { + data: { email: owner.email, password: owner.password ?? stack.userPassword }, + }); + if (!login.ok()) throw new Error('The actual owner login failed.'); + const page = await context.newPage(); + const checks: Promise[] = []; + page.on('response', (response) => { + const pathname = new URL(response.url()).pathname; + if (!expected.has(pathname)) return; + checks.push( + response.body().then((body) => { + if (crypto.createHash('sha256').update(body).digest('hex') !== expected.get(pathname)) + mismatches.push(pathname); + else verified.add(pathname); + }), + ); + }); + await page.goto(`${legacyBase}/#/app`); + await page.getByRole('button', { name: 'Menü', exact: true }).click(); + await page.getByRole('menuitem', { name: 'Organisation', exact: true }).click(); + await page.getByRole('button', { name: 'Einladungen', exact: true }).click(); + const row = page.getByRole('row').filter({ hasText: target.email }); + await expect(row).toBeVisible(); + const deleted = page.waitForResponse( + (response) => response.request().method() === 'DELETE' && response.url().includes('/invites/'), + ); + await row.getByRole('button', { name: 'Löschen', exact: true }).click(); + await page.getByRole('button', { name: 'Bestätigen', exact: true }).click(); + const result = await deleted; + expect(result.status()).toBe(400); + const body: unknown = await result.json(); + expect(!!body && typeof body === 'object' && 'code' in body && body.code === 'invite_id_invalid').toBe(true); + await expect(page.getByText('Einladung konnte nicht gelöscht werden', { exact: true })).toBeVisible(); + await expect(row).toBeVisible(); + const state = await db.query( + 'SELECT "usedAt" IS NULL AS valid, "expiresAt">now() AS unexpired FROM "Invite" WHERE "code"=$1', + [invitation.code], + ); + expect(state.rows[0]).toEqual({ valid: true, unexpired: true }); + const signedIn = await targetRequest.post(`${stack.apiUrl}/auth/login`, { + data: { email: target.email, password: target.password }, + }); + expect(signedIn.status()).toBe(200); + const accepted = await targetRequest.post(`${stack.apiUrl}/invites/accept`, { data: { code: invitation.code } }); + expect(accepted.status()).toBe(200); + expect(await fixture.membershipCount(target.email)).toBe(1); + await Promise.all(checks); + expect(mismatches).toHaveLength(0); + expect(verified.size).toBeGreaterThan(0); + } finally { + await context.close(); + await targetRequest.dispose(); + await fixture.cleanup(); + } +}); diff --git a/apps/web/e2e/accounts/mailProof.support.ts b/apps/web/e2e/accounts/mailProof.support.ts new file mode 100644 index 00000000..a5399af6 --- /dev/null +++ b/apps/web/e2e/accounts/mailProof.support.ts @@ -0,0 +1,122 @@ +import crypto from 'node:crypto'; +import type { APIRequest, Browser, BrowserContext, Page } from '@playwright/test'; +import type { Client } from 'pg'; +import type { TestStackEnv } from '../fixtures'; +import type { SeedData, TestUser } from '../support/api'; +import { createApiRequest, MeetropolisApi } from '../support/api'; +import { getSeedTenant } from '../fixtures/helpers'; +import type { MailpitClient } from '../support/mailpit'; + +export const newEmail = () => `fixture-account-${crypto.randomUUID()}@example.test`; +const id = () => `c${crypto.randomBytes(12).toString('hex')}`; + +/** Use real account records in the existing test database. */ +export function mailProofFixture(db: Client, seed: SeedData, stack: TestStackEnv) { + const url = new URL(stack.databaseUrl); + if (url.hostname !== '127.0.0.1' || url.port !== '35440') + throw new Error('This test requires the assigned database on 127.0.0.1:35440.'); + const tenant = getSeedTenant(seed); + const owner = tenant.users.owner; + if (!owner) throw new Error('Seed contains no owner'); + const emails: string[] = []; + const extraTenants: string[] = []; + async function account(options: { verified?: boolean; member?: boolean } = {}): Promise { + const email = newEmail(); + emails.push(email); + const userId = id(); + const inserted = await db.query( + `INSERT INTO "User" ("id", "email", "name", "passwordHash", "emailVerifiedAt", "updatedAt", "onboardingCompleted") + SELECT $1, $2, 'Mailbox test user', "passwordHash", CASE WHEN $3 THEN now() ELSE NULL END, now(), true FROM "User" WHERE "id"=$4 RETURNING "id"`, + [userId, email, options.verified !== false, owner.userId], + ); + if (inserted.rowCount !== 1) throw new Error('Seed owner password hash is missing.'); + let tenantId = tenant.tenantId; + let tenantSlug = tenant.slug; + if (options.member === false) { + tenantId = id(); + tenantSlug = `fixture-account-${crypto.randomUUID()}`; + extraTenants.push(tenantId); + await db.query('INSERT INTO "Tenant" ("id","slug","name","updatedAt") VALUES ($1,$2,$2,now())', [ + tenantId, + tenantSlug, + ]); + } + await db.query( + 'INSERT INTO "Membership" ("id","tenantId","userId","role","updatedAt") VALUES ($1,$2,$3,\'member\',now())', + [id(), tenantId, userId], + ); + return { + userId, + email, + displayName: 'Mailbox test user', + role: 'member', + tenantSlug, + password: owner.password ?? stack.userPassword, + }; + } + async function mark(user: TestUser) { + await db.query('UPDATE "User" SET "emailVerifiedAt"=NULL WHERE "id"=$1', [user.userId]); + await db.query('UPDATE "Membership" SET "inviteVerificationRequired"=true WHERE "userId"=$1 AND "tenantId"=$2', [ + user.userId, + tenant.tenantId, + ]); + await db.query( + `INSERT INTO "Invite" ("id","code","email","tenantId","role","usedAt","usedById","expiresAt") + VALUES ($1,$2,$3,$4,'member',now(),$5,now()+interval '1 day')`, + [id(), crypto.randomBytes(12).toString('hex'), user.email, tenant.tenantId, user.userId], + ); + } + async function invite(playwrightRequest: APIRequest, email: string) { + if (!emails.includes(email)) emails.push(email); + const request = await createApiRequest(playwrightRequest, stack.apiUrl, tenant.slug); + try { + const api = new MeetropolisApi(request, stack.apiUrl, tenant.slug); + await api.login(owner.email, owner.password ?? stack.userPassword); + return await api.invite(email, 'member'); + } finally { + await request.dispose(); + } + } + async function membershipCount(email: string) { + const result = await db.query( + 'SELECT count(*)::int AS count FROM "Membership" m JOIN "User" u ON u."id"=m."userId" WHERE u."email"=$1 AND m."tenantId"=$2', + [email, tenant.tenantId], + ); + return Number(result.rows[0]?.count); + } + async function cleanup() { + const users = await db.query('SELECT "id" FROM "User" WHERE "email"=ANY($1::text[])', [emails]); + const ids = users.rows.map((row: { id: string }) => row.id); + await db.query('DELETE FROM "EmailVerification" WHERE "userId"=ANY($1::text[])', [ids]); + await db.query('DELETE FROM "Invite" WHERE "email"=ANY($1::text[]) OR "usedById"=ANY($2::text[])', [emails, ids]); + for (const table of ['Presence', 'PasswordReset', 'ApiToken', 'Session', 'Membership']) { + await db.query(`DELETE FROM "${table}" WHERE "userId"=ANY($1::text[])`, [ids]); + } + await db.query('DELETE FROM "User" WHERE "id"=ANY($1::text[])', [ids]); + await db.query('DELETE FROM "Tenant" WHERE "id"=ANY($1::text[])', [extraTenants]); + } + return { tenant, account, mark, invite, membershipCount, cleanup, trackEmail: (email: string) => emails.push(email) }; +} + +export async function browserForTenant(browser: Browser, stack: TestStackEnv, slug: string): Promise { + return browser.newContext({ baseURL: stack.baseUrl, locale: 'de-DE', extraHTTPHeaders: { 'X-Tenant': slug } }); +} + +export async function confirmationLink(mailpit: MailpitClient, email: string) { + const mail = await mailpit.waitForMail({ to: email, linkPattern: /#\/verify\?token=/ }); + const link = mailpit.extractLinks(mail).find((candidate) => /#\/verify\?token=/.test(candidate)); + if (!link) throw new Error('Confirmation email contains no confirmation link.'); + return link; +} + +export async function signIn(page: Page, stack: TestStackEnv, user: TestUser) { + await page.goto(`${stack.baseUrl}/#/login`); + await page.getByLabel('E-Mail-Adresse', { exact: true }).fill(user.email); + await page.getByLabel('Passwort', { exact: true }).fill(user.password ?? stack.userPassword); + await page.getByRole('button', { name: 'Anmelden', exact: true }).click(); +} + +export async function openProfile(page: Page) { + await page.getByRole('button', { name: 'Menü', exact: true }).click(); + await page.getByRole('menuitem', { name: 'Profil', exact: true }).click(); +} diff --git a/apps/web/e2e/fixtures/helpers.ts b/apps/web/e2e/fixtures/helpers.ts new file mode 100644 index 00000000..3cc94eb5 --- /dev/null +++ b/apps/web/e2e/fixtures/helpers.ts @@ -0,0 +1,129 @@ +import { readFile } from 'node:fs/promises'; + +import { expect } from '@playwright/test'; + +import type { FreshTenant, Role, SeedData, TenantSeed, TestUser } from '../support/api'; +import type { Page } from '@playwright/test'; + +export const TESTSTACK_ENV_MESSAGE = + 'Teststack-Env fehlt: /Users/ricoroder/Cursor/meetropolis-deploy/scripts/teststack.sh up'; + +export function requiredEnv(name: string): string { + const value = process.env[name]; + if (!value) throw new Error(TESTSTACK_ENV_MESSAGE); + return value; +} + +function asRecord(value: unknown, label: string): Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${label}: ungültige Seed-JSON-Struktur.`); + } + return value as Record; +} + +function readString(record: Record, name: string, label: string): string { + const value = record[name]; + if (typeof value !== 'string' || value.length === 0) throw new Error(`${label}: Feld ${name} fehlt.`); + return value; +} + +function readOptionalString(record: Record, name: string, label: string): string | undefined { + const value = record[name]; + if (value === undefined) return undefined; + if (typeof value !== 'string' || value.length === 0) throw new Error(`${label}: Feld ${name} ist ungültig.`); + return value; +} + +function parseRole(value: unknown, label: string): Role { + if (value === 'owner' || value === 'admin' || value === 'member' || value === 'guest' || value === 'operator') { + return value; + } + throw new Error(`${label}: ungültige Rolle.`); +} + +function parseUser(value: unknown, label: string): TestUser { + const record = asRecord(value, label); + const password = readOptionalString(record, 'password', label); + const guestUrl = readOptionalString(record, 'guestUrl', label); + return { + userId: readString(record, 'userId', label), + email: readString(record, 'email', label), + displayName: readString(record, 'displayName', label), + role: parseRole(record.role, label), + tenantSlug: readString(record, 'tenantSlug', label), + ...(password ? { password } : {}), + ...(guestUrl ? { guestUrl } : {}), + }; +} + +function parseTenant(value: unknown, label: string): TenantSeed { + const record = asRecord(value, label); + const rawUsers = asRecord(record.users, `${label}.users`); + const users: Partial> = {}; + for (const [key, user] of Object.entries(rawUsers)) { + const role = parseRole(key, `${label}.users`); + users[role] = parseUser(user, `${label}.users.${role}`); + } + return { + tenantId: readString(record, 'tenantId', label), + slug: readString(record, 'slug', label), + roomId: readString(record, 'roomId', label), + mapId: readString(record, 'mapId', label), + users, + }; +} + +export async function readSeedFile(path: string): Promise { + const content = await readFile(path, 'utf8'); + let parsed: unknown; + try { + parsed = JSON.parse(content); + } catch { + throw new Error(`Seed-Datei ist kein gültiges JSON: ${path}`); + } + const record = asRecord(parsed, 'Seed-Datei'); + if (record.edition !== 'ee' && record.edition !== 'oss') + throw new Error('Seed-Datei: edition muss ee oder oss sein.'); + const rawTenants = asRecord(record.tenants, 'Seed-Datei.tenants'); + const tenants: Record = {}; + for (const [slug, tenant] of Object.entries(rawTenants)) tenants[slug] = parseTenant(tenant, `tenants.${slug}`); + return { edition: record.edition, operator: parseUser(record.operator, 'operator'), tenants }; +} + +export function appRouteUrl(baseUrl: string, route: 'app' | 'login'): string { + const url = new URL(baseUrl); + url.hash = `/${route}`; + return url.toString(); +} + +function escapedRegex(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export async function waitForParticipant(page: Page, user: TestUser): Promise { + await expect( + page.getByRole('complementary').getByRole('button', { name: new RegExp(escapedRegex(user.displayName), 'i') }), + ).toBeVisible({ timeout: 60_000 }); +} + +export function getSeedTenant(seed: SeedData): TenantSeed { + const tenant = seed.tenants.acme ?? seed.tenants.default ?? Object.values(seed.tenants)[0]; + if (!tenant) throw new Error('Seed-Datei enthält keinen Mandanten.'); + return tenant; +} + +export function pickUsers(tenant: TenantSeed | FreshTenant, n: number, roles?: Role[]): TestUser[] { + if (!Number.isInteger(n) || n < 1) throw new Error('roomUsers erwartet mindestens einen Nutzer.'); + const selectedRoles = roles ?? Array.from({ length: n }, (_value, index) => (index === 0 ? 'owner' : 'member')); + if (selectedRoles.length !== n) throw new Error('roomUsers benötigt genau eine Rolle je Nutzer.'); + return selectedRoles.map((role) => { + const user = role === 'operator' ? undefined : tenant.users[role]; + if (!user) throw new Error(`Mandant ${tenant.slug} enthält keinen Nutzer mit Rolle ${role}.`); + return user; + }); +} + +export function passwordFor(user: TestUser): string { + if (!user.password) throw new Error(`${user.role} ${user.email} hat kein Passwort und muss den Gastweg nutzen.`); + return user.password; +} diff --git a/apps/web/e2e/fixtures/index.ts b/apps/web/e2e/fixtures/index.ts new file mode 100644 index 00000000..81924e8a --- /dev/null +++ b/apps/web/e2e/fixtures/index.ts @@ -0,0 +1,117 @@ +import { Client } from 'pg'; + +import { expect, test as base } from '@playwright/test'; +import type { BrowserContext } from '@playwright/test'; + +import { MeetropolisApi, type TestUser } from '../support/api'; +import { createMailpitClient } from '../support/mailpit'; +import { provideStackControl } from './stackControl'; +import { createFreshTenant } from './tenant'; +import { appRouteUrl, readSeedFile, requiredEnv, TESTSTACK_ENV_MESSAGE, passwordFor } from './helpers'; +import { provideRoomUsers } from './roomUsers'; +import type { Fixtures, TestStackEnv } from './types'; + +export type { + Edition, + MediaPermission, + RoomUser, + RoomUserOptions, + RoomUsersFactory, + StackControl, + StackService, + TestStackEnv, +} from './types'; +export { expect }; + +export const test = base.extend({ + stack: async ({}, provide) => { + const edition = requiredEnv('MT_EDITION'); + if (edition !== 'ee' && edition !== 'oss') throw new Error(TESTSTACK_ENV_MESSAGE); + const stack: TestStackEnv = { + baseUrl: requiredEnv('E2E_BASE_URL'), + apiUrl: requiredEnv('E2E_API_URL'), + databaseUrl: requiredEnv('DATABASE_URL'), + mailpitUrl: requiredEnv('MAILPIT_URL'), + livekitUrl: requiredEnv('LIVEKIT_URL'), + livekitApiKey: requiredEnv('LIVEKIT_API_KEY'), + livekitApiSecret: requiredEnv('LIVEKIT_API_SECRET'), + seedFile: requiredEnv('E2E_SEED_FILE'), + operatorEmail: requiredEnv('E2E_OPERATOR_EMAIL'), + operatorPassword: requiredEnv('E2E_OPERATOR_PASSWORD'), + userPassword: requiredEnv('E2E_USER_PASSWORD'), + edition, + project: requiredEnv('MT_PROJECT'), + }; + await provide(stack); + }, + + seed: async ({ stack }, provide) => { + await provide(await readSeedFile(stack.seedFile)); + }, + + freshTenant: async ({ playwright, stack }, provide, testInfo) => { + testInfo.skip(stack.edition === 'oss', 'freshTenant braucht Enterprise (Mandanten)'); + await provide(await createFreshTenant(playwright.request, stack, testInfo.testId)); + }, + + loginAs: async ({ browser, browserName, stack }, provide) => { + const contexts: BrowserContext[] = []; + try { + await provide(async (user: TestUser) => { + const context = await browser.newContext({ + baseURL: stack.baseUrl, + extraHTTPHeaders: { 'x-tenant': user.tenantSlug }, + ...(browserName === 'firefox' ? {} : { permissions: ['camera', 'microphone'] }), + }); + contexts.push(context); + const page = await context.newPage(); + if (user.role === 'guest') { + if (!user.guestUrl) throw new Error(`Gast ${user.email} hat keinen Magic-Link.`); + await page.goto(user.guestUrl); + await page.waitForURL(/#\/app(?:$|\?)/); + } else { + const api = new MeetropolisApi(context.request, stack.apiUrl, user.tenantSlug); + await api.login(user.email, passwordFor(user)); + await page.goto(appRouteUrl(stack.baseUrl, 'app')); + } + await expect(page.getByRole('complementary').getByText(user.displayName, { exact: true })).toBeVisible({ + timeout: 60_000, + }); + return { context, page }; + }); + } finally { + await Promise.all(contexts.map((context) => context.close())); + } + }, + + roomUsers: async ({ browser, browserName, playwright, seed, stack }, provide, testInfo) => { + await provideRoomUsers({ + browser, + browserName, + browserTypes: playwright, + playwrightRequest: playwright.request, + seed, + stack, + testInfo, + provide, + }); + }, + + mailpit: async ({ request, stack }, provide) => { + await provide(createMailpitClient(request, stack.mailpitUrl)); + }, + + stackControl: async ({ stack }, provide) => { + await provideStackControl({ stack, provide }); + }, + + db: async ({ stack }, provide) => { + const client = new Client({ connectionString: stack.databaseUrl }); + await client.connect(); + try { + await provide(client); + } finally { + await client.end(); + } + }, +}); diff --git a/apps/web/e2e/fixtures/roomUsers.ts b/apps/web/e2e/fixtures/roomUsers.ts new file mode 100644 index 00000000..2799644c --- /dev/null +++ b/apps/web/e2e/fixtures/roomUsers.ts @@ -0,0 +1,120 @@ +import type { Browser, BrowserContext, BrowserType, TestInfo } from '@playwright/test'; +import type { APIRequest } from '@playwright/test'; + +import { MeetropolisApi } from '../support/api'; +import type { FreshTenant, SeedData, TestUser } from '../support/api'; +import type { TestStackEnv, MediaPermission, RoomUser, RoomUsersFactory } from './types'; +import { appRouteUrl, getSeedTenant, passwordFor, pickUsers, waitForParticipant } from './helpers'; +import { createFreshTenant } from './tenant'; + +type BrowserTypes = { chromium: BrowserType; firefox: BrowserType; webkit: BrowserType }; + +export async function provideRoomUsers(args: { + browser: Browser; + browserName: string; + browserTypes: BrowserTypes; + playwrightRequest: APIRequest; + seed: SeedData; + stack: TestStackEnv; + testInfo: TestInfo; + provide: (factory: RoomUsersFactory) => Promise; +}): Promise { + const contexts: BrowserContext[] = []; + const ownedBrowsers: Browser[] = []; + let defaultTenantPromise: Promise | undefined; + const browserType = + args.browserName === 'firefox' + ? args.browserTypes.firefox + : args.browserName === 'webkit' + ? args.browserTypes.webkit + : args.browserTypes.chromium; + + const createRoomUser = async (user: TestUser, permission: MediaPermission, join: boolean): Promise => { + const separateBrowser = permission !== 'granted'; + let targetBrowser = args.browser; + if (separateBrowser) { + const launchOptions = { + ...(args.browserName === 'chromium' ? { args: ['--use-fake-device-for-media-stream'] } : {}), + ...(args.testInfo.project.name === 'chrome' ? { channel: 'chrome' as const } : {}), + }; + targetBrowser = await browserType.launch(launchOptions); + ownedBrowsers.push(targetBrowser); + } + + const context = await targetBrowser.newContext({ + baseURL: args.stack.baseUrl, + extraHTTPHeaders: { 'x-tenant': user.tenantSlug }, + ...(!separateBrowser && args.browserName !== 'firefox' ? { permissions: ['camera', 'microphone'] } : {}), + }); + contexts.push(context); + if (permission === 'denied' && args.browserName !== 'firefox') { + await context.grantPermissions([], { origin: new URL(args.stack.baseUrl).origin }); + } + + const api = new MeetropolisApi(context.request, args.stack.apiUrl, user.tenantSlug); + const page = await context.newPage(); + if (user.role === 'guest') { + if (!user.guestUrl) throw new Error(`Gast ${user.email} hat keinen Magic-Link.`); + if (join) { + await page.goto(user.guestUrl); + await page.waitForURL(/#\/app(?:$|\?)/); + } else { + await api.loginGuest(user.guestUrl); + } + } else { + await api.login(user.email, passwordFor(user)); + if (join) await page.goto(appRouteUrl(args.stack.baseUrl, 'app')); + } + return { user, context, page }; + }; + + try { + await args.provide(async (n, options = {}) => { + const join = options.join !== false; + if (!options.tenant && args.stack.edition === 'oss') { + args.testInfo.skip(true, 'freshTenant braucht Enterprise (Mandanten)'); + } + const tenant = + options.tenant === 'seed' + ? getSeedTenant(args.seed) + : (options.tenant ?? + (await (defaultTenantPromise ??= createFreshTenant( + args.playwrightRequest, + args.stack, + args.testInfo.testId, + )))); + const users = pickUsers(tenant, n, options.roles); + const permissions = users.map((_user, index) => options.permissions?.[index] ?? 'granted'); + if (options.permissions && options.permissions.length !== n) { + throw new Error('roomUsers benötigt genau einen Permission-Status je Nutzer.'); + } + + const roomUsers = + options.joinOrder === 'parallel' + ? await Promise.all(users.map((user, index) => createRoomUser(user, permissions[index] ?? 'granted', join))) + : []; + if (options.joinOrder !== 'parallel') { + for (const [index, user] of users.entries()) { + roomUsers.push(await createRoomUser(user, permissions[index] ?? 'granted', join)); + } + } + + if (join) { + await Promise.all( + roomUsers.map((viewer) => + Promise.all( + roomUsers.filter((other) => other !== viewer).map((other) => waitForParticipant(viewer.page, other.user)), + ), + ), + ); + } + return roomUsers; + }); + } finally { + try { + await Promise.all(contexts.map((context) => context.close())); + } finally { + await Promise.all(ownedBrowsers.map((ownedBrowser) => ownedBrowser.close())); + } + } +} diff --git a/apps/web/e2e/fixtures/stackControl.ts b/apps/web/e2e/fixtures/stackControl.ts new file mode 100644 index 00000000..6332a121 --- /dev/null +++ b/apps/web/e2e/fixtures/stackControl.ts @@ -0,0 +1,57 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +import type { StackControl, StackService, TestStackEnv } from './types'; + +const run = promisify(execFile); + +const PROJECT_PATTERN = /^mtest-[0-9]+$/; + +async function findContainerId(project: string, service: StackService): Promise { + const { stdout } = await run('docker', [ + 'ps', + '-q', + '--filter', + `label=com.docker.compose.project=${project}`, + '--filter', + `label=com.docker.compose.service=${service}`, + ]); + const ids = stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + if (ids.length !== 1) { + throw new Error(`stackControl: ${service} in ${project} hat ${ids.length} Container, erwartet genau 1.`); + } + const id = ids[0]; + if (!id) throw new Error(`stackControl: ${service} in ${project} hat keinen Container.`); + return id; +} + +export async function provideStackControl(args: { + stack: TestStackEnv; + provide: (control: StackControl) => Promise; +}): Promise { + const project = args.stack.project; + if (!PROJECT_PATTERN.test(project)) { + throw new Error(`stackControl: ungültiges Projekt ${project}, erwartet mtest-.`); + } + const paused = new Set(); + const control: StackControl = { + pause: async (service) => { + await run('docker', ['pause', await findContainerId(project, service)]); + paused.add(service); + }, + unpause: async (service) => { + await run('docker', ['unpause', await findContainerId(project, service)]); + paused.delete(service); + }, + }; + try { + await args.provide(control); + } finally { + for (const service of paused) { + await run('docker', ['unpause', await findContainerId(project, service)]); + } + } +} diff --git a/apps/web/e2e/fixtures/tenant.ts b/apps/web/e2e/fixtures/tenant.ts new file mode 100644 index 00000000..d4e1efb7 --- /dev/null +++ b/apps/web/e2e/fixtures/tenant.ts @@ -0,0 +1,69 @@ +import { createHash, randomUUID } from 'node:crypto'; + +import type { APIRequest } from '@playwright/test'; + +import type { FreshTenant } from '../support/api'; +import { provisionGuest, provisionInvitedUser, provisionTenantOwnerViaOperator } from '../support/provisioning'; +import type { TestStackEnv } from './types'; + +export async function createFreshTenant( + playwrightRequest: APIRequest, + stack: TestStackEnv, + testId: string, +): Promise { + const suffix = createHash('sha256').update(`${testId}:${randomUUID()}`).digest('hex').slice(0, 10); + const slug = `t-${suffix}`; + const ownerSession = await provisionTenantOwnerViaOperator({ + playwrightRequest, + apiUrl: stack.apiUrl, + operatorEmail: stack.operatorEmail, + operatorPassword: stack.operatorPassword, + tenantSlug: slug, + tenantName: `Q-Test ${suffix}`, + ownerEmail: `owner+${suffix}@qtest.test`, + ownerName: 'Test Owner', + ownerPassword: stack.userPassword, + }); + + try { + const ownerApi = ownerSession.api; + const owner = ownerSession.user; + + const users: FreshTenant['users'] = { + owner, + admin: await provisionInvitedUser({ + playwrightRequest, + ownerApi, + apiUrl: stack.apiUrl, + tenantSlug: slug, + email: `admin+${suffix}@qtest.test`, + name: 'Test Admin', + role: 'admin', + password: stack.userPassword, + }), + member: await provisionInvitedUser({ + playwrightRequest, + ownerApi, + apiUrl: stack.apiUrl, + tenantSlug: slug, + email: `member+${suffix}@qtest.test`, + name: 'Test Member', + role: 'member', + password: stack.userPassword, + }), + guest: await provisionGuest({ + playwrightRequest, + ownerApi, + apiUrl: stack.apiUrl, + baseUrl: stack.baseUrl, + tenantSlug: slug, + email: `guest+${suffix}@qtest.test`, + }), + }; + + const { tenantId, roomId, mapId } = await ownerApi.tenantRoomAndMap(); + return { tenantId, slug, users, roomId, mapId }; + } finally { + await ownerSession.dispose(); + } +} diff --git a/apps/web/e2e/fixtures/types.ts b/apps/web/e2e/fixtures/types.ts new file mode 100644 index 00000000..83035a12 --- /dev/null +++ b/apps/web/e2e/fixtures/types.ts @@ -0,0 +1,51 @@ +import type { BrowserContext, Page } from '@playwright/test'; +import type { Client } from 'pg'; + +import type { FreshTenant, Role, SeedData, TestUser } from '../support/api'; +import type { MailpitClient } from '../support/mailpit'; + +export type Edition = 'ee' | 'oss'; +export type MediaPermission = 'granted' | 'denied' | 'prompt'; +export type StackService = 'livekit' | 'mailpit' | 'server'; + +export type StackControl = { + pause(service: StackService): Promise; + unpause(service: StackService): Promise; +}; + +export type TestStackEnv = { + baseUrl: string; + apiUrl: string; + databaseUrl: string; + mailpitUrl: string; + livekitUrl: string; + livekitApiKey: string; + livekitApiSecret: string; + seedFile: string; + operatorEmail: string; + operatorPassword: string; + userPassword: string; + edition: Edition; + project: string; +}; + +export type RoomUser = { user: TestUser; context: BrowserContext; page: Page }; +export type RoomUserOptions = { + tenant?: FreshTenant | 'seed'; + roles?: Role[]; + joinOrder?: 'sequential' | 'parallel'; + permissions?: MediaPermission[]; + join?: boolean; +}; +export type RoomUsersFactory = (n: number, options?: RoomUserOptions) => Promise; + +export type Fixtures = { + stack: TestStackEnv; + seed: SeedData; + freshTenant: FreshTenant; + loginAs: (user: TestUser) => Promise<{ context: BrowserContext; page: Page }>; + roomUsers: RoomUsersFactory; + mailpit: MailpitClient; + db: Client; + stackControl: StackControl; +}; diff --git a/apps/web/e2e/smoke/login.spec.ts b/apps/web/e2e/smoke/login.spec.ts new file mode 100644 index 00000000..170c49a8 --- /dev/null +++ b/apps/web/e2e/smoke/login.spec.ts @@ -0,0 +1,26 @@ +import { test, expect } from '../fixtures'; +import type { SeedData } from '../support/api'; + +test.use({ locale: 'en-US' }); + +function seededTenant(seed: SeedData) { + const tenant = seed.tenants.acme ?? seed.tenants.default ?? Object.values(seed.tenants)[0]; + if (!tenant) throw new Error('Seed-Datei enthält keinen Mandanten.'); + return tenant; +} + +test('seed member signs in through the UI @smoke', async ({ page, seed, stack }) => { + const member = seededTenant(seed).users.member; + if (!member?.password) throw new Error('Seed-Mandant enthält keinen Member mit Passwort.'); + + const loginUrl = new URL(stack.baseUrl); + loginUrl.hash = '/login'; + await page.goto(loginUrl.toString()); + const loginForm = page.locator('form'); + await loginForm.locator('input[name="email"]').fill(member.email); + await loginForm.locator('input[name="password"]').fill(member.password); + await loginForm.locator('button[type="submit"]').click(); + + await expect(page).toHaveURL(/#\/app$/); + await expect(page.getByRole('complementary').getByText(/Test Member/i)).toBeVisible(); +}); diff --git a/apps/web/e2e/smoke/mail.spec.ts b/apps/web/e2e/smoke/mail.spec.ts new file mode 100644 index 00000000..3c916631 --- /dev/null +++ b/apps/web/e2e/smoke/mail.spec.ts @@ -0,0 +1,31 @@ +import { test, expect } from '../fixtures'; + +test('password reset mail includes its reset link @smoke', async ({ request, stack, seed, mailpit }) => { + test.skip(stack.edition === 'ee', 'Q-TEST-5: Das EE-Mailmodul leitet derzeit nicht an Mailpit weiter.'); + const tenant = seed.tenants.default; + const member = tenant?.users.member; + if (!member || member.email !== 'member@default.test') { + throw new Error('OSS-Seed enthält nicht member@default.test.'); + } + + // POST /auth/forgot is registered at apps/server/src/api/routes/auth.ts:33-36; + // the public { email } payload is validated in auth.password.ts:15-17, 27-30. + const response = await request.post(`${stack.apiUrl.replace(/\/+$/, '')}/auth/forgot`, { + data: { email: member.email }, + }); + expect(response.status()).toBe(200); + + // The seeded account already has verification and invitation mail in Mailpit. + const message = await mailpit.waitForMail({ + to: member.email, + linkPattern: /#\/reset\?token=/, + }); + const resetLink = mailpit.extractLinks(message).find((link) => { + try { + return new URL(link).hash.startsWith('#/reset?token='); + } catch { + return false; + } + }); + expect(resetLink).toBeTruthy(); +}); diff --git a/apps/web/e2e/smoke/room.spec.ts b/apps/web/e2e/smoke/room.spec.ts new file mode 100644 index 00000000..d17077d3 --- /dev/null +++ b/apps/web/e2e/smoke/room.spec.ts @@ -0,0 +1,10 @@ +import { test } from '../fixtures'; +import { waitForParticipant } from '../fixtures/helpers'; + +test('seed users see each other in the same room @smoke', async ({ roomUsers }) => { + const [owner, member] = await roomUsers(2, { tenant: 'seed' }); + if (!owner || !member) throw new Error('roomUsers hat nicht beide Teilnehmer erstellt.'); + + await waitForParticipant(owner.page, member.user); + await waitForParticipant(member.page, owner.user); +}); diff --git a/apps/web/e2e/stack/stack-control.spec.ts b/apps/web/e2e/stack/stack-control.spec.ts new file mode 100644 index 00000000..aa60fe8a --- /dev/null +++ b/apps/web/e2e/stack/stack-control.spec.ts @@ -0,0 +1,24 @@ +import { test, expect } from '../fixtures'; + +test('@stack mailpit pause blocks and unpause restores the mail api', async ({ + request, + stack, + mailpit, + stackControl, +}) => { + const searchUrl = `${stack.mailpitUrl.replace(/\/+$/, '')}/api/v1/search?${new URLSearchParams({ + query: 'to:stack-control-probe@invalid.test', + }).toString()}`; + + // Reachable through the existing mailpit fixture: the search answers, only the probe address has no mail. + await expect(mailpit.waitForMail({ to: 'stack-control-probe@invalid.test', timeoutMs: 5_000 })).rejects.toThrow( + /keine Nachricht/, + ); + + await stackControl.pause('mailpit'); + await expect(request.get(searchUrl, { timeout: 5_000 })).rejects.toThrow(); + + await stackControl.unpause('mailpit'); + const restored = await request.get(searchUrl, { timeout: 15_000 }); + expect(restored.ok()).toBe(true); +}); diff --git a/apps/web/e2e/support/api.ts b/apps/web/e2e/support/api.ts new file mode 100644 index 00000000..0eb32ffb --- /dev/null +++ b/apps/web/e2e/support/api.ts @@ -0,0 +1,437 @@ +import { request as isolatedRequest, type APIRequest, type APIRequestContext } from '@playwright/test'; +import { createMailpitClient } from './mailpit'; + +export type Role = 'owner' | 'admin' | 'member' | 'guest' | 'operator'; +export type InviteRole = Extract; + +export type TestUser = { + userId: string; + email: string; + displayName: string; + password?: string; + role: Role; + tenantSlug: string; + guestUrl?: string; +}; + +export type TenantSeed = { + tenantId: string; + slug: string; + roomId: string; + mapId: string; + users: Partial>; +}; + +export type SeedData = { + edition: 'ee' | 'oss'; + operator: TestUser; + tenants: Record; +}; + +export type FreshTenant = { + tenantId: string; + slug: string; + users: Record<'owner' | 'admin' | 'member' | 'guest', TestUser>; + roomId: string; + mapId: string; +}; + +export type ApiMe = { + id: string; + email: string; + name: string | null; + tenantSlug: string; + role: Role; +}; + +type InviteResult = { code: string; role: InviteRole }; +type GuestResult = { id: string; guestUrl: string }; +type TenantResult = { id: string; slug: string; defaultMapName: string | null }; +type MapSummary = { id: string; name: string; rooms: Array<{ id: string }> }; +export type AdminTenantUser = { + userId: string; + email: string; + role: Extract; +}; +export type AdminMapSummary = { id: string; name: string; tenantId: string; tenantSlug: string }; + +export function createApiRequest(request: APIRequest, apiUrl: string, tenantSlug?: string): Promise { + return request.newContext({ + baseURL: apiUrl, + ...(tenantSlug ? { extraHTTPHeaders: { 'x-tenant': tenantSlug } } : {}), + }); +} + +function appendRoute(baseUrl: string, route: string): string { + return `${baseUrl.replace(/\/+$/, '')}/${route.replace(/^\/+/, '')}`; +} + +function asRecord(value: unknown, label: string): Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${label}: erwartete JSON-Objektantwort.`); + } + return value as Record; +} + +function requiredString(value: unknown, label: string): string { + if (typeof value !== 'string' || value.length === 0) throw new Error(`${label}: Feld fehlt.`); + return value; +} + +function roleValue(value: unknown, label: string): Role { + if (value === 'owner' || value === 'admin' || value === 'member' || value === 'guest' || value === 'operator') { + return value; + } + throw new Error(`${label}: unbekannte Rolle.`); +} + +function adminRoleValue(value: unknown, label: string): AdminTenantUser['role'] { + if (value === 'owner' || value === 'admin' || value === 'member' || value === 'guest') return value; + throw new Error(`${label}: unbekannte Betreiber-Rolle.`); +} + +function inviteRoleValue(value: unknown, label: string): InviteRole { + if (value === 'admin' || value === 'member') return value; + throw new Error(`${label}: Einladung mit nicht unterstützter Rolle.`); +} + +async function readJson(response: Awaited>, route: string): Promise { + if (!response.ok()) throw new Error(`${route}: HTTP ${response.status()}.`); + const body: unknown = await response.json(); + return body; +} + +export class MeetropolisApi { + constructor( + private readonly request: APIRequestContext, + private readonly apiUrl: string, + private readonly tenantSlug?: string, + ) {} + + /** Complete pending account actions through the existing real mailbox. */ + private async accountAction( + response: Awaited>, + email: string, + password: string, + route: string, + ): Promise { + if (response.status() !== 409) { + await readJson(response, route); + return; + } + const body = asRecord(await response.json(), route); + if (body.code !== 'EMAIL_VERIFICATION_REQUIRED') { + throw new Error(`${route}: HTTP ${response.status()}.`); + } + if ('token' in body || 'verifyUrl' in body) throw new Error('Account response contains a confirmation secret.'); + const mailpitUrl = process.env.MAILPIT_URL; + if (!mailpitUrl || !['127.0.0.1', 'localhost'].includes(new URL(mailpitUrl).hostname)) { + throw new Error('The assigned local mailbox is not configured.'); + } + const mailbox = await isolatedRequest.newContext(); + try { + const mailpit = createMailpitClient(mailbox, mailpitUrl); + const message = await mailpit.waitForMail({ to: email, linkPattern: /#\/verify\?token=/ }); + const link = mailpit.extractLinks(message).find((candidate) => /#\/verify\?token=/.test(candidate)); + const token = link ? new URLSearchParams(new URL(link).hash.split('?')[1]).get('token') : null; + if (!token) throw new Error('The confirmation email contains no confirmation link.'); + await readJson( + await this.request.post(appendRoute(this.apiUrl, '/auth/verify'), { data: { token } }), + '/auth/verify', + ); + // Verification consumes the proof but does not establish a session. + await readJson( + await this.request.post(appendRoute(this.apiUrl, '/auth/login'), { data: { email, password } }), + '/auth/login', + ); + } finally { + await mailbox.dispose(); + } + } + + private async authenticateForInvite(email: string, password: string): Promise { + const route = '/auth/login'; + const response = await this.request.post(appendRoute(this.apiUrl, route), { data: { email, password } }); + if (response.status() === 409) { + const body = asRecord(await response.json(), route); + // These responses follow a successful credential check and session creation. + if (body.code === 'EMAIL_VERIFICATION_REQUIRED' || body.code === 'INVITE_ACCEPT_REQUIRED') return; + } + await readJson(response, route); + } + + async login(email: string, password: string): Promise { + // POST /auth/login is registered at apps/server/src/api/routes/auth.ts:26-30; + // its { email, password } payload is validated in auth.signin.ts:42-43,248-258. + const route = '/auth/login'; + const response = await this.request.post(appendRoute(this.apiUrl, route), { data: { email, password } }); + await this.accountAction(response, email, password, route); + return this.me(); + } + + async tryLogin(email: string, password: string): Promise { + const route = '/auth/login'; + const response = await this.request.post(appendRoute(this.apiUrl, route), { data: { email, password } }); + if (response.status() === 401) return null; + if (response.status() === 409 && asRecord(await response.json(), route).code === 'INVITE_ACCEPT_REQUIRED') { + return null; + } + await this.accountAction(response, email, password, route); + return this.me(); + } + + async loginGuest(guestUrl: string): Promise { + const url = new URL(guestUrl); + const hashQuery = url.hash.includes('?') ? url.hash.slice(url.hash.indexOf('?') + 1) : ''; + const token = new URLSearchParams(hashQuery).get('token'); + if (!token) throw new Error('guestUrl enthält keinen Magic-Link-Token.'); + + // POST /auth/guest is registered beside POST /guests in + // apps/server/src/api/routes/guests.ts:333-339 and establishes the guest session at :267-331. + const route = '/auth/guest'; + await readJson(await this.request.post(appendRoute(this.apiUrl, route), { data: { token } }), route); + return this.me(); + } + + async me(): Promise { + // GET /auth/me is registered at apps/server/src/api/routes/auth.ts:30 and + // returns id, email, name, role, and tenantSlug in auth.signin.ts:369-383. + const route = '/auth/me'; + const body = asRecord(await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route), route); + const name = body.name; + return { + id: requiredString(body.id, route), + email: requiredString(body.email, route), + name: typeof name === 'string' ? name : null, + tenantSlug: requiredString(body.tenantSlug, route), + role: roleValue(body.role, route), + }; + } + + async invite(email: string, role: InviteRole): Promise { + // POST /auth/invite is registered at apps/server/src/api/routes/auth.ts:26; + // owner/admin authorization and the { email, role } schema are in auth.signin.ts:21-59. + const route = '/auth/invite'; + const body = asRecord( + await readJson(await this.request.post(appendRoute(this.apiUrl, route), { data: { email, role } }), route), + route, + ); + return { code: requiredString(body.code, route), role: inviteRoleValue(body.role, route) }; + } + + async createGuest(args: { email: string; name: string; expiresAt: string }): Promise { + // POST /guests checks owner/admin membership and returns a magicLink at + // apps/server/src/api/routes/guests.ts:22-35,161-210. + const route = '/guests'; + const body = asRecord( + await readJson(await this.request.post(appendRoute(this.apiUrl, route), { data: args }), route), + route, + ); + return { + id: requiredString(body.id, route), + guestUrl: requiredString(body.magicLink, route), + }; + } + + async registerWithInvite(args: { code: string; email: string; name: string; password: string }): Promise { + // POST /auth/register is registered at apps/server/src/api/routes/auth.ts:27; + // the invite-code payload and membership creation are in auth.signin.ts:97-151. + const route = '/auth/register'; + let response = await this.request.post(appendRoute(this.apiUrl, route), { data: args }); + let actionRoute = route; + if (response.status() === 409 && asRecord(await response.json(), route).code === 'ACCOUNT_LOGIN_REQUIRED') { + await this.authenticateForInvite(args.email, args.password); + actionRoute = '/invites/accept'; + response = await this.request.post(appendRoute(this.apiUrl, actionRoute), { data: { code: args.code } }); + } + await this.accountAction(response, args.email, args.password, actionRoute); + return this.me(); + } + + async ensureAdminTenant(args: { slug: string; name: string }): Promise { + if (this.tenantSlug !== 'default') { + throw new Error('ensureAdminTenant muss mit dem Betreiber-Kontext des Default-Tenants aufgerufen werden.'); + } + const existing = (await this.adminTenants()).find((tenant) => tenant.slug === args.slug); + if (existing) return existing.id; + + // POST /admin/tenants is registered by the EE tenant-admin module and + // requires the platform super-admin; it does not need X-Tenant for the + // tenant that is being created. + const route = '/admin/tenants'; + const body = asRecord( + await readJson(await this.request.post(appendRoute(this.apiUrl, route), { data: args }), route), + route, + ); + return requiredString(body.id, route); + } + + async adminTenants(): Promise> { + const route = '/admin/tenants'; + const value = await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route); + if (!Array.isArray(value)) throw new Error(`${route}: erwartete Mandantenliste.`); + return value.map((entry, index) => { + const tenant = asRecord(entry, `${route}[${index}]`); + return { + id: requiredString(tenant.id, `${route}[${index}]`), + slug: requiredString(tenant.slug, `${route}[${index}]`), + }; + }); + } + + async adminTenantUsers(tenantId: string): Promise { + const route = `/admin/tenants/${encodeURIComponent(tenantId)}/users`; + const value = await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route); + if (!Array.isArray(value)) throw new Error(`${route}: erwartete Nutzerliste.`); + return value.map((entry, index) => { + const user = asRecord(entry, `${route}[${index}]`); + return { + userId: requiredString(user.userId, `${route}[${index}]`), + email: requiredString(user.email, `${route}[${index}]`), + role: adminRoleValue(user.role, `${route}[${index}]`), + }; + }); + } + + async addAdminTenantUser(args: { + tenantId: string; + email: string; + name: string; + role: Extract; + }): Promise { + const route = `/admin/tenants/${encodeURIComponent(args.tenantId)}/users`; + const body = asRecord( + await readJson( + await this.request.post(appendRoute(this.apiUrl, route), { + data: { email: args.email, name: args.name, role: args.role }, + }), + route, + ), + route, + ); + return { + userId: requiredString(body.userId, route), + email: requiredString(body.email, route), + role: adminRoleValue(body.role, route), + }; + } + + async setAdminTenantUserRole(tenantId: string, userId: string, role: AdminTenantUser['role']): Promise { + const route = `/admin/tenants/${encodeURIComponent(tenantId)}/users/${encodeURIComponent(userId)}/role`; + await readJson(await this.request.patch(appendRoute(this.apiUrl, route), { data: { role } }), route); + } + + async removeAdminTenantUser(tenantId: string, userId: string): Promise { + const route = `/admin/tenants/${encodeURIComponent(tenantId)}/users/${encodeURIComponent(userId)}`; + await readJson(await this.request.delete(appendRoute(this.apiUrl, route)), route); + } + + async setAdminTenantDefaultMap(tenantId: string, defaultMapName: string): Promise { + const route = `/admin/tenants/${encodeURIComponent(tenantId)}`; + await readJson(await this.request.patch(appendRoute(this.apiUrl, route), { data: { defaultMapName } }), route); + } + + async adminMaps(): Promise { + const route = '/admin/maps'; + const value = await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route); + if (!Array.isArray(value)) throw new Error(`${route}: erwartete Kartenliste.`); + return value.map((entry, index) => { + const map = asRecord(entry, `${route}[${index}]`); + return { + id: requiredString(map.id, `${route}[${index}]`), + name: requiredString(map.name, `${route}[${index}]`), + tenantId: requiredString(map.tenantId, `${route}[${index}]`), + tenantSlug: requiredString(map.tenantSlug, `${route}[${index}]`), + }; + }); + } + + async copyAdminMap(sourceMapId: string, targetTenantId: string, newName: string): Promise { + const route = `/admin/maps/${encodeURIComponent(sourceMapId)}/copy`; + await readJson( + await this.request.post(appendRoute(this.apiUrl, route), { data: { targetTenantId, newName } }), + route, + ); + } + + async pendingInviteCode(email: string): Promise { + const route = '/invites'; + const value = await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route); + if (!Array.isArray(value)) throw new Error(`${route}: erwartete Einladungsliste.`); + const normalizedEmail = email.trim().toLowerCase(); + const match = value + .map((entry, index) => ({ entry: asRecord(entry, `${route}[${index}]`), index })) + .find(({ entry }) => entry.email === normalizedEmail && entry.usedAt === null); + if (!match) return null; + // Decision 13 (knowledge/quality/Q-ACC-P3-einladungen.md): no invite code in URL + // paths; the list returns id and url only, so the code comes from the link. + const url = requiredString(match.entry.url, `${route}[${match.index}]`); + const hashQuery = new URL(url).hash.split('?')[1] ?? ''; + const code = new URLSearchParams(hashQuery).get('invite'); + if (!code) throw new Error(`${route}[${match.index}]: invite link without invite code`); + return code; + } + + async tenant(): Promise { + // GET /tenant is registered at apps/server/src/api/routes/tenant.ts:141-143; + // membership-checked metadata is returned at tenant.ts:40-70. + const route = '/tenant'; + const body = asRecord(await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route), route); + return { + id: requiredString(body.id, route), + slug: requiredString(body.slug, route), + defaultMapName: typeof body.defaultMapName === 'string' ? body.defaultMapName : null, + }; + } + + async tenantRoomAndMap(): Promise<{ tenantId: string; roomId: string; mapId: string }> { + const tenant = await this.tenant(); + let maps = await this.maps(); + let map = maps.find((candidate) => candidate.name === tenant.defaultMapName) ?? maps[0]; + if (!map) throw new Error(`Mandant ${tenant.slug} hat keine Karte über GET /maps geliefert.`); + + if (map.rooms.length === 0) { + const mapId = map.id; + await this.createDefaultRoom(tenant.defaultMapName ?? map.name); + maps = await this.maps(); + map = maps.find((candidate) => candidate.id === mapId) ?? map; + } + const room = map.rooms[0]; + if (!room) throw new Error(`Karte ${map.name} hat nach POST /auth/position keinen Raum geliefert.`); + return { tenantId: tenant.id, roomId: room.id, mapId: map.id }; + } + + private async maps(): Promise { + // GET /maps is registered at apps/server/src/api/routes/maps.ts:16 and + // returns each map with its rooms at apps/server/src/api/routes/maps.read.ts:62-70. + const route = '/maps'; + const value = await readJson(await this.request.get(appendRoute(this.apiUrl, route)), route); + if (!Array.isArray(value)) throw new Error(`${route}: erwartete Kartenliste.`); + return value.map((entry, index) => { + const map = asRecord(entry, `${route}[${index}]`); + const rooms = Array.isArray(map.rooms) ? map.rooms : []; + return { + id: requiredString(map.id, `${route}[${index}]`), + name: requiredString(map.name, `${route}[${index}]`), + rooms: rooms.map((entry, roomIndex) => ({ + id: requiredString( + asRecord(entry, `${route}[${index}].rooms[${roomIndex}]`).id, + `${route}[${index}].rooms[${roomIndex}]`, + ), + })), + }; + }); + } + + private async createDefaultRoom(mapName: string): Promise { + // POST /auth/position is registered at apps/server/src/api/routes/auth.ts:52; + // auth.profile.ts:59-65,79-104 shows it creates a default room through the API. + const route = '/auth/position'; + await readJson( + await this.request.post(appendRoute(this.apiUrl, route), { + data: { x: 0, y: 0, direction: 'down', roomId: 'world', mapName }, + }), + route, + ); + } +} diff --git a/apps/web/e2e/support/capabilities.probe.ts b/apps/web/e2e/support/capabilities.probe.ts new file mode 100644 index 00000000..4a03bdd4 --- /dev/null +++ b/apps/web/e2e/support/capabilities.probe.ts @@ -0,0 +1,401 @@ +import { createServer } from 'node:http'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; + +import { test } from '@playwright/test'; + +interface Measurement { + ok: boolean; + errorName?: string; + errorMessage?: string; + trackLabel?: string; + contextState?: string; + maxRms?: number; + width?: number; + height?: number; + bytesReceived?: number; +} + +interface DeviceCounts { + audioinput: number; + audiooutput: number; + videoinput: number; + errorName?: string; + errorMessage?: string; +} + +interface TrackGroup { + count: number; + tracks: Array<{ label: string; readyState: string }>; +} + +interface DisplayMeasurement extends Measurement { + videoTracks?: TrackGroup; + audioTracks?: TrackGroup; +} + +function getErrorDetails(error: unknown): { + errorName: string; + errorMessage: string; +} { + if (error instanceof Error) { + return { errorName: error.name, errorMessage: error.message }; + } + return { errorName: 'UnknownError', errorMessage: String(error) }; +} + +async function capture(name: string, measurement: () => Promise, onError: (error: unknown) => T): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + measurement(), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`${name} timed out after 10000ms`)), 10_000); + }), + ]); + } catch (error) { + return onError(error); + } finally { + if (timer) clearTimeout(timer); + } +} + +function measurementFailure(error: unknown): Measurement { + return { ok: false, ...getErrorDetails(error) }; +} + +test('capabilities', async ({ page, browserName }, testInfo) => { + const server = createServer((_request, response) => { + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + response.end( + 'Capabilities', + ); + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, resolve); + }); + + try { + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('The capability probe server has no TCP address.'); + } + await page.goto(`http://localhost:${address.port}`); + + const mediaDevices = await capture( + 'mediaDevices', + () => page.evaluate(() => Boolean(navigator.mediaDevices)), + () => false, + ); + + const enumerateDevices = await capture( + 'enumerateDevices', + () => + page.evaluate(async () => { + const devices = await navigator.mediaDevices.enumerateDevices(); + return { + audioinput: devices.filter((device) => device.kind === 'audioinput').length, + audiooutput: devices.filter((device) => device.kind === 'audiooutput').length, + videoinput: devices.filter((device) => device.kind === 'videoinput').length, + }; + }), + (error) => ({ + audioinput: 0, + audiooutput: 0, + videoinput: 0, + ...getErrorDetails(error), + }), + ); + + const getUserMediaAudio = await capture( + 'getUserMediaAudio', + async () => { + const result = page.evaluate( + () => + new Promise((resolve) => { + const button = document.querySelector('#audio-capture'); + if (!button) { + resolve({ + ok: false, + errorName: 'MissingButton', + errorMessage: 'The audio-capture button is missing.', + }); + return; + } + + button.addEventListener( + 'click', + () => { + void (async () => { + let stream: MediaStream | undefined; + let context: AudioContext | undefined; + let contextState: string | undefined; + try { + context = new AudioContext(); + await context.resume(); + contextState = context.state; + + stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + const track = stream.getAudioTracks()[0]; + if (!track) throw new Error('getUserMedia returned no audio track.'); + + const source = context.createMediaStreamSource(stream); + const analyser = context.createAnalyser(); + analyser.fftSize = 2048; + source.connect(analyser); + + const samples = new Float32Array(analyser.fftSize); + let maxRms = 0; + const endAt = performance.now() + 2_000; + while (performance.now() < endAt) { + analyser.getFloatTimeDomainData(samples); + let squaredSamples = 0; + for (const sample of samples) squaredSamples += sample * sample; + maxRms = Math.max(maxRms, Math.sqrt(squaredSamples / samples.length)); + await new Promise((resolveDelay) => window.setTimeout(resolveDelay, 25)); + } + + resolve({ ok: true, trackLabel: track.label, contextState, maxRms }); + } catch (error) { + const failedContextState = contextState ?? context?.state; + resolve({ + ok: false, + ...(failedContextState ? { contextState: failedContextState } : {}), + errorName: error instanceof Error ? error.name : 'UnknownError', + errorMessage: error instanceof Error ? error.message : String(error), + }); + } finally { + stream?.getTracks().forEach((track) => track.stop()); + if (context && context.state !== 'closed') await context.close(); + } + })(); + }, + { once: true }, + ); + }), + ); + await page.click('#audio-capture'); + return result; + }, + measurementFailure, + ); + const audioNonSilent = getUserMediaAudio.ok && (getUserMediaAudio.maxRms ?? 0) > 0.001; + + const getUserMediaVideo = await capture( + 'getUserMediaVideo', + () => + page.evaluate(async () => { + let stream: MediaStream | undefined; + let video: HTMLVideoElement | undefined; + try { + stream = await navigator.mediaDevices.getUserMedia({ video: true }); + video = document.createElement('video'); + video.autoplay = true; + video.muted = true; + video.playsInline = true; + video.srcObject = stream; + + const metadataReady = new Promise((resolve, reject) => { + if (video && video.videoWidth > 0 && video.videoHeight > 0) { + resolve(); + return; + } + const timer = window.setTimeout(() => reject(new Error('Timed out waiting for video metadata.')), 5_000); + video?.addEventListener( + 'loadedmetadata', + () => { + window.clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + video?.addEventListener( + 'error', + () => { + window.clearTimeout(timer); + reject(new Error('The video element failed to load metadata.')); + }, + { once: true }, + ); + }); + + await video.play(); + await metadataReady; + return { + ok: true, + width: video.videoWidth, + height: video.videoHeight, + }; + } catch (error) { + return { + ok: false, + errorName: error instanceof Error ? error.name : 'UnknownError', + errorMessage: error instanceof Error ? error.message : String(error), + }; + } finally { + video?.pause(); + if (video) video.srcObject = null; + stream?.getTracks().forEach((track) => track.stop()); + video?.remove(); + } + }), + measurementFailure, + ); + + const getDisplayMedia = await capture( + 'getDisplayMedia', + async () => { + const result = page.evaluate( + () => + new Promise((resolve) => { + const button = document.querySelector('#display-capture'); + if (!button) { + resolve({ + ok: false, + errorName: 'MissingButton', + errorMessage: 'The display-capture button is missing.', + }); + return; + } + + button.addEventListener( + 'click', + () => { + void (async () => { + try { + const stream = await navigator.mediaDevices.getDisplayMedia({ + video: true, + audio: true, + }); + const summarizeTracks = (tracks: MediaStreamTrack[]): TrackGroup => ({ + count: tracks.length, + tracks: tracks.map((track) => ({ + label: track.label, + readyState: track.readyState, + })), + }); + const videoTracks = summarizeTracks(stream.getVideoTracks()); + const audioTracks = summarizeTracks(stream.getAudioTracks()); + stream.getTracks().forEach((track) => track.stop()); + resolve({ ok: true, videoTracks, audioTracks }); + } catch (error) { + resolve({ + ok: false, + errorName: error instanceof Error ? error.name : 'UnknownError', + errorMessage: error instanceof Error ? error.message : String(error), + }); + } + })(); + }, + { once: true }, + ); + }), + ); + await page.click('#display-capture'); + return result; + }, + measurementFailure, + ); + + const webrtcLoopback = await capture( + 'webrtcLoopback', + () => + page.evaluate(async () => { + let stream: MediaStream | undefined; + let sender: RTCPeerConnection | undefined; + let receiver: RTCPeerConnection | undefined; + try { + stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + const audioTrack = stream.getAudioTracks()[0]; + if (!audioTrack) throw new Error('getUserMedia returned no audio track.'); + + sender = new RTCPeerConnection(); + receiver = new RTCPeerConnection(); + sender.addTrack(audioTrack, stream); + + const waitForIceGathering = (connection: RTCPeerConnection): Promise => + new Promise((resolve, reject) => { + if (connection.iceGatheringState === 'complete') { + resolve(); + return; + } + const timer = window.setTimeout(() => reject(new Error('Timed out gathering ICE candidates.')), 5_000); + connection.addEventListener('icegatheringstatechange', () => { + if (connection.iceGatheringState === 'complete') { + window.clearTimeout(timer); + resolve(); + } + }); + }); + + await sender.setLocalDescription(await sender.createOffer()); + await waitForIceGathering(sender); + if (!sender.localDescription) { + throw new Error('The sender has no local offer.'); + } + await receiver.setRemoteDescription(sender.localDescription); + await receiver.setLocalDescription(await receiver.createAnswer()); + await waitForIceGathering(receiver); + if (!receiver.localDescription) { + throw new Error('The receiver has no local answer.'); + } + await sender.setRemoteDescription(receiver.localDescription); + await new Promise((resolve) => window.setTimeout(resolve, 2_000)); + + let bytesReceived = 0; + const stats = await receiver.getStats(); + for (const stat of stats.values()) { + if (stat.type !== 'inbound-rtp') continue; + const inbound = stat as RTCInboundRtpStreamStats; + if (inbound.kind === 'audio' && typeof inbound.bytesReceived === 'number') { + bytesReceived += inbound.bytesReceived; + } + } + + return bytesReceived > 0 + ? { ok: true, bytesReceived } + : { + ok: false, + errorName: 'NoInboundRtp', + errorMessage: 'No inbound audio RTP bytes were received.', + bytesReceived, + }; + } catch (error) { + return { + ok: false, + errorName: error instanceof Error ? error.name : 'UnknownError', + errorMessage: error instanceof Error ? error.message : String(error), + }; + } finally { + sender?.close(); + receiver?.close(); + stream?.getTracks().forEach((track) => track.stop()); + } + }), + measurementFailure, + ); + + const results = { + project: testInfo.project.name, + browser: browserName, + mediaDevices, + enumerateDevices, + getUserMediaAudio, + audioNonSilent, + getUserMediaVideo, + getDisplayMedia, + screenShareAudio: getDisplayMedia.ok && (getDisplayMedia.audioTracks?.count ?? 0) > 0, + webrtcLoopback, + }; + const outputPath = join(testInfo.project.outputDir, `capabilities-${testInfo.project.name}.json`); + await mkdir(dirname(outputPath), { recursive: true }); + await writeFile(outputPath, `${JSON.stringify(results, null, 2)}\n`); + console.log(JSON.stringify(results, null, 2)); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + } +}); diff --git a/apps/web/e2e/support/mailpit.ts b/apps/web/e2e/support/mailpit.ts new file mode 100644 index 00000000..8dcffdb0 --- /dev/null +++ b/apps/web/e2e/support/mailpit.ts @@ -0,0 +1,119 @@ +import type { APIRequestContext } from '@playwright/test'; + +export type MailpitMessage = { + id: string; + subject: string; + to: string[]; + text: string; + html: string; +}; + +export type MailpitClient = { + waitForMail(args: { + to: string; + subject?: string; + linkPattern?: RegExp; + timeoutMs?: number; + }): Promise; + extractLinks(message: MailpitMessage): string[]; +}; + +function asRecord(value: unknown, label: string): Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${label}: unerwartete Mailpit-Antwort.`); + } + return value as Record; +} + +function readString(record: Record, key: string): string { + const value = record[key]; + return typeof value === 'string' ? value : ''; +} + +function readRecipients(value: unknown): string[] { + if (!Array.isArray(value)) return []; + return value.flatMap((recipient) => { + if (recipient === null || typeof recipient !== 'object' || Array.isArray(recipient)) return []; + const address = (recipient as Record).Address; + return typeof address === 'string' ? [address.toLowerCase()] : []; + }); +} + +function appendPath(baseUrl: string, path: string): string { + return `${baseUrl.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`; +} + +function cleanLink(value: string): string { + return value.replace(/&/g, '&').replace(/[),.;]+$/, ''); +} + +export function createMailpitClient(request: APIRequestContext, mailpitUrl: string): MailpitClient { + async function waitForMail({ + to, + subject, + linkPattern, + timeoutMs = 30_000, + }: Parameters[0]) { + const deadline = Date.now() + timeoutMs; + const query = new URLSearchParams({ query: `to:${to}` }); + const searchUrl = `${appendPath(mailpitUrl, '/api/v1/search')}?${query.toString()}`; + const checkedMessageIds = new Set(); + + while (Date.now() < deadline) { + const searchResponse = await request.get(searchUrl); + if (!searchResponse.ok()) throw new Error(`Mailpit-Suche: HTTP ${searchResponse.status()}.`); + const payload = asRecord((await searchResponse.json()) as unknown, 'Mailpit-Suche'); + const summaries = Array.isArray(payload.messages) ? payload.messages : []; + + for (const item of summaries) { + const summary = asRecord(item, 'Mailpit-Nachricht'); + const messageTo = readRecipients(summary.To); + const messageSubject = readString(summary, 'Subject'); + if (!messageTo.includes(to.toLowerCase()) || (subject && messageSubject !== subject)) continue; + + const id = readString(summary, 'ID'); + if (!id || checkedMessageIds.has(id)) continue; + checkedMessageIds.add(id); + const messageUrl = appendPath(mailpitUrl, `/api/v1/message/${encodeURIComponent(id)}`); + const messageResponse = await request.get(messageUrl); + if (!messageResponse.ok()) throw new Error(`Mailpit-Nachricht: HTTP ${messageResponse.status()}.`); + const fullMessage = asRecord((await messageResponse.json()) as unknown, 'Mailpit-Nachricht'); + const message = { + id, + subject: readString(fullMessage, 'Subject') || messageSubject, + to: readRecipients(fullMessage.To), + text: readString(fullMessage, 'Text'), + html: readString(fullMessage, 'HTML'), + }; + if (linkPattern && !extractLinks(message).some((link) => linkPattern.test(link))) continue; + return message; + } + + const remainingMs = deadline - Date.now(); + if (remainingMs > 0) await new Promise((resolve) => setTimeout(resolve, Math.min(250, remainingMs))); + } + + const filters = [subject && `Betreff „${subject}“`, linkPattern && `Linkmuster ${linkPattern}`].filter(Boolean); + throw new Error( + `Mailpit: keine Nachricht für ${to}${filters.length ? ` mit ${filters.join(' und ')}` : ''} innerhalb ${timeoutMs} ms.`, + ); + } + + function extractLinks(message: MailpitMessage): string[] { + const links = new Set(); + const hrefPattern = /href\s*=\s*["']([^"']+)["']/gi; + for (const match of message.html.matchAll(hrefPattern)) { + const link = cleanLink(match[1] ?? ''); + if (link) links.add(link); + } + + const textPattern = /https?:\/\/[^\s<>"']+/gi; + for (const match of `${message.text}\n${message.html}`.matchAll(textPattern)) { + const link = cleanLink(match[0]); + if (link) links.add(link); + } + return [...links]; + } + + return { waitForMail, extractLinks }; +} diff --git a/apps/web/e2e/support/provisioning.ts b/apps/web/e2e/support/provisioning.ts new file mode 100644 index 00000000..f4d1fdc1 --- /dev/null +++ b/apps/web/e2e/support/provisioning.ts @@ -0,0 +1,186 @@ +import type { APIRequest } from '@playwright/test'; + +import { createApiRequest, MeetropolisApi, type ApiMe, type InviteRole, type Role, type TestUser } from './api'; + +type TenantOwnerSession = { api: MeetropolisApi; user: TestUser; dispose: () => Promise }; + +const TEMPLATE_MAP_NAME = 'office-atelier-v1'; + +export function toTestUser(me: ApiMe, password?: string, guestUrl?: string): TestUser { + if (me.name === null || me.name.length === 0) { + throw new Error(`/auth/me did not return a display name for ${me.email}.`); + } + + return { + userId: me.id, + email: me.email, + displayName: me.name, + role: me.role, + tenantSlug: me.tenantSlug, + ...(password ? { password } : {}), + ...(guestUrl ? { guestUrl } : {}), + }; +} + +export function assertTenantRole(me: ApiMe, tenantSlug: string, role: Role): void { + if (me.tenantSlug !== tenantSlug || me.role !== role) { + throw new Error(`Konto ${me.email} hat nicht die erwartete Rolle ${role} in ${tenantSlug}.`); + } +} + +async function ensureTenantTemplateMap(operatorApi: MeetropolisApi, tenantId: string): Promise { + const maps = await operatorApi.adminMaps(); + const tenantMap = maps.find((map) => map.tenantId === tenantId && map.name === TEMPLATE_MAP_NAME); + if (!tenantMap) { + const templateMap = maps.find((map) => map.tenantSlug === 'template' && map.name === TEMPLATE_MAP_NAME); + if (!templateMap) throw new Error(`Vorlagenkarte ${TEMPLATE_MAP_NAME} wurde nicht gefunden.`); + await operatorApi.copyAdminMap(templateMap.id, tenantId, TEMPLATE_MAP_NAME); + } + await operatorApi.setAdminTenantDefaultMap(tenantId, TEMPLATE_MAP_NAME); +} + +export async function provisionTenantOwnerViaOperator(args: { + playwrightRequest: APIRequest; + apiUrl: string; + operatorEmail: string; + operatorPassword: string; + tenantSlug: string; + tenantName: string; + ownerEmail: string; + ownerName: string; + ownerPassword: string; +}): Promise { + const operatorRequest = await createApiRequest(args.playwrightRequest, args.apiUrl, 'default'); + const operatorApi = new MeetropolisApi(operatorRequest, args.apiUrl, 'default'); + let tenantOperatorRequest: Awaited> | undefined; + let ownerRequest: Awaited> | undefined; + let tenantId: string | undefined; + let operatorUserId: string | undefined; + let keepOwnerRequest = false; + + try { + const operator = await operatorApi.login(args.operatorEmail, args.operatorPassword); + assertTenantRole(operator, 'default', 'owner'); + tenantId = await operatorApi.ensureAdminTenant({ slug: args.tenantSlug, name: args.tenantName }); + await ensureTenantTemplateMap(operatorApi, tenantId); + + ownerRequest = await createApiRequest(args.playwrightRequest, args.apiUrl, args.tenantSlug); + const ownerApi = new MeetropolisApi(ownerRequest, args.apiUrl, args.tenantSlug); + let owner = await ownerApi.tryLogin(args.ownerEmail, args.ownerPassword); + if (!owner) { + const operatorMembership = (await operatorApi.adminTenantUsers(tenantId)).find( + (user) => user.userId === operator.id, + ); + operatorUserId = operatorMembership?.userId; + if (!operatorMembership) { + const added = await operatorApi.addAdminTenantUser({ + tenantId, + email: args.operatorEmail, + name: operator.name ?? 'Test Operator', + role: 'admin', + }); + operatorUserId = added.userId; + } else if (operatorMembership.role === 'member') { + await operatorApi.setAdminTenantUserRole(tenantId, operator.id, 'admin'); + } + + tenantOperatorRequest = await createApiRequest(args.playwrightRequest, args.apiUrl, args.tenantSlug); + const tenantOperatorApi = new MeetropolisApi(tenantOperatorRequest, args.apiUrl, args.tenantSlug); + await tenantOperatorApi.login(args.operatorEmail, args.operatorPassword); + const inviteCode = + (await tenantOperatorApi.pendingInviteCode(args.ownerEmail)) ?? + (await tenantOperatorApi.invite(args.ownerEmail, 'member')).code; + owner = await ownerApi.registerWithInvite({ + code: inviteCode, + email: args.ownerEmail, + name: args.ownerName, + password: args.ownerPassword, + }); + assertTenantRole(owner, args.tenantSlug, 'member'); + } + + if (owner.role !== 'owner') { + await operatorApi.setAdminTenantUserRole(tenantId, owner.id, 'owner'); + } + owner = await ownerApi.me(); + assertTenantRole(owner, args.tenantSlug, 'owner'); + + if (!operatorUserId) { + operatorUserId = (await operatorApi.adminTenantUsers(tenantId)).find( + (user) => user.userId === operator.id, + )?.userId; + } + if (operatorUserId) { + await operatorApi.removeAdminTenantUser(tenantId, operatorUserId); + operatorUserId = undefined; + } + + keepOwnerRequest = true; + const retainedOwnerRequest = ownerRequest; + return { + api: ownerApi, + user: toTestUser(owner, args.ownerPassword), + dispose: () => retainedOwnerRequest.dispose(), + }; + } finally { + if (tenantId && operatorUserId) await operatorApi.removeAdminTenantUser(tenantId, operatorUserId); + if (ownerRequest && !keepOwnerRequest) await ownerRequest.dispose(); + if (tenantOperatorRequest) await tenantOperatorRequest.dispose(); + await operatorRequest.dispose(); + } +} + +export async function provisionInvitedUser(args: { + playwrightRequest: APIRequest; + ownerApi: MeetropolisApi; + apiUrl: string; + tenantSlug: string; + email: string; + name: string; + role: InviteRole; + password: string; +}): Promise { + const request = await createApiRequest(args.playwrightRequest, args.apiUrl, args.tenantSlug); + try { + const api = new MeetropolisApi(request, args.apiUrl, args.tenantSlug); + const existing = await api.tryLogin(args.email, args.password); + if (existing) { + assertTenantRole(existing, args.tenantSlug, args.role); + return toTestUser(existing, args.password); + } + + const invitation = await args.ownerApi.invite(args.email, args.role); + const me = await api.registerWithInvite({ + code: invitation.code, + email: args.email, + name: args.name, + password: args.password, + }); + assertTenantRole(me, args.tenantSlug, args.role); + return toTestUser(me, args.password); + } finally { + await request.dispose(); + } +} + +export async function provisionGuest(args: { + playwrightRequest: APIRequest; + ownerApi: MeetropolisApi; + apiUrl: string; + baseUrl: string; + tenantSlug: string; + email: string; +}): Promise { + const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); + const created = await args.ownerApi.createGuest({ email: args.email, name: 'Test Guest', expiresAt }); + const guestUrl = new URL(created.guestUrl, args.baseUrl).toString(); + const request = await createApiRequest(args.playwrightRequest, args.apiUrl, args.tenantSlug); + try { + const api = new MeetropolisApi(request, args.apiUrl, args.tenantSlug); + const me = await api.loginGuest(guestUrl); + assertTenantRole(me, args.tenantSlug, 'guest'); + return toTestUser(me, undefined, guestUrl); + } finally { + await request.dispose(); + } +} diff --git a/apps/web/e2e/support/seed.setup.ts b/apps/web/e2e/support/seed.setup.ts new file mode 100644 index 00000000..c02e7cd1 --- /dev/null +++ b/apps/web/e2e/support/seed.setup.ts @@ -0,0 +1,190 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +import { test } from '../fixtures'; +import { createApiRequest, MeetropolisApi } from './api'; +import type { ApiMe, SeedData, TenantSeed, TestUser } from './api'; +import { + assertTenantRole, + provisionGuest, + provisionInvitedUser, + provisionTenantOwnerViaOperator, + toTestUser, +} from './provisioning'; + +type OwnerSession = { api: MeetropolisApi; user: TestUser }; + +async function tenantSeed(args: { + playwrightRequest: Parameters[0]; + apiUrl: string; + baseUrl: string; + owner: OwnerSession; + password: string; + slug: string; + includeAccounts: boolean; + includeGuest?: boolean; +}): Promise { + const users: Partial> = { owner: args.owner.user }; + if (args.includeAccounts) { + users.admin = await provisionInvitedUser({ + playwrightRequest: args.playwrightRequest, + ownerApi: args.owner.api, + apiUrl: args.apiUrl, + tenantSlug: args.slug, + email: args.slug === 'default' ? 'admin@default.test' : 'admin@acme.test', + name: 'Test Admin', + role: 'admin', + password: args.password, + }); + users.member = await provisionInvitedUser({ + playwrightRequest: args.playwrightRequest, + ownerApi: args.owner.api, + apiUrl: args.apiUrl, + tenantSlug: args.slug, + email: args.slug === 'default' ? 'member@default.test' : 'member@acme.test', + name: 'Test Member', + role: 'member', + password: args.password, + }); + if (args.includeGuest) { + users.guest = await provisionGuest({ + playwrightRequest: args.playwrightRequest, + ownerApi: args.owner.api, + apiUrl: args.apiUrl, + baseUrl: args.baseUrl, + tenantSlug: args.slug, + email: args.slug === 'default' ? 'guest@default.test' : 'guest@acme.test', + }); + } + } + const { tenantId, roomId, mapId } = await args.owner.api.tenantRoomAndMap(); + return { tenantId, slug: args.slug, roomId, mapId, users }; +} + +function assertExpectedSeed(edition: SeedData['edition'], tenants: Record): void { + if (edition === 'ee') { + const acme = tenants.acme?.users; + const globex = tenants.globex?.users; + if (!acme?.owner || !acme.admin || !acme.member || !acme.guest || !globex?.owner) { + throw new Error('EE-Seed muss acme mit Owner/Admin/Member/Gast und globex mit Owner enthalten.'); + } + return; + } + if (!tenants.default?.users.owner || !tenants.default.users.admin || !tenants.default.users.member) { + throw new Error('OSS-Seed muss den Default-Tenant mit Betreiber, Admin und Member enthalten.'); + } + if (tenants.default.users.guest) throw new Error('OSS-Seed darf keinen Gast enthalten.'); +} + +function seedUsers(seed: SeedData): TestUser[] { + const users: TestUser[] = [seed.operator]; + for (const tenant of Object.values(seed.tenants)) { + for (const user of Object.values(tenant.users)) { + if (user) users.push(user); + } + } + return users; +} + +async function verifySeedLogins( + playwrightRequest: Parameters[0], + apiUrl: string, + seed: SeedData, +): Promise { + const users = seedUsers(seed); + for (const user of users) { + const request = await createApiRequest(playwrightRequest, apiUrl, user.tenantSlug); + try { + const api = new MeetropolisApi(request, apiUrl, user.tenantSlug); + let me: ApiMe; + if (user.role === 'guest') { + if (!user.guestUrl) throw new Error(`Gast ${user.email} hat keinen Magic-Link.`); + me = await api.loginGuest(user.guestUrl); + } else { + if (!user.password) throw new Error(`Seed-Konto ${user.email} hat kein Passwort im Seed.`); + me = await api.login(user.email, user.password); + } + assertTenantRole(me, user.tenantSlug, user.role); + user.displayName = toTestUser(me).displayName; + } finally { + await request.dispose(); + } + } + return users.length; +} + +test('create idempotent test seed', async ({ playwright, stack }) => { + const disposers: Array<() => Promise> = []; + try { + const operatorRequest = await createApiRequest(playwright.request, stack.apiUrl, 'default'); + disposers.push(() => operatorRequest.dispose()); + const operatorApi = new MeetropolisApi(operatorRequest, stack.apiUrl, 'default'); + const operatorMe: ApiMe = await operatorApi.login(stack.operatorEmail, stack.operatorPassword); + assertTenantRole(operatorMe, 'default', 'owner'); + const operator = toTestUser(operatorMe, stack.operatorPassword); + + const tenants: Record = {}; + if (stack.edition === 'ee') { + const acme = await provisionTenantOwnerViaOperator({ + playwrightRequest: playwright.request, + apiUrl: stack.apiUrl, + operatorEmail: stack.operatorEmail, + operatorPassword: stack.operatorPassword, + tenantSlug: 'acme', + tenantName: 'Test acme', + ownerEmail: 'owner@acme.test', + ownerName: 'Test Owner', + ownerPassword: stack.userPassword, + }); + disposers.push(acme.dispose); + tenants.acme = await tenantSeed({ + playwrightRequest: playwright.request, + apiUrl: stack.apiUrl, + baseUrl: stack.baseUrl, + owner: acme, + password: stack.userPassword, + slug: 'acme', + includeAccounts: true, + includeGuest: true, + }); + + const globex = await provisionTenantOwnerViaOperator({ + playwrightRequest: playwright.request, + apiUrl: stack.apiUrl, + operatorEmail: stack.operatorEmail, + operatorPassword: stack.operatorPassword, + tenantSlug: 'globex', + tenantName: 'Test globex', + ownerEmail: 'owner@globex.test', + ownerName: 'Test Owner', + ownerPassword: stack.userPassword, + }); + disposers.push(globex.dispose); + const { tenantId, roomId, mapId } = await globex.api.tenantRoomAndMap(); + tenants.globex = { tenantId, slug: 'globex', roomId, mapId, users: { owner: globex.user } }; + } else { + const owner = { api: operatorApi, user: operator }; + tenants.default = await tenantSeed({ + playwrightRequest: playwright.request, + apiUrl: stack.apiUrl, + baseUrl: stack.baseUrl, + owner, + password: stack.userPassword, + slug: 'default', + includeAccounts: true, + includeGuest: false, + }); + } + + assertExpectedSeed(stack.edition, tenants); + const seed: SeedData = { edition: stack.edition, operator, tenants }; + const verifiedCount = await verifySeedLogins(playwright.request, stack.apiUrl, seed); + await mkdir(dirname(stack.seedFile), { recursive: true }); + await writeFile(stack.seedFile, `${JSON.stringify(seed, null, 2)}\n`, 'utf8'); + console.log( + `P2 seed ready: edition=${stack.edition}, tenants=${Object.keys(tenants).join(',')}, API logins=${verifiedCount}`, + ); + } finally { + await Promise.all(disposers.map((dispose) => dispose())); + } +}); diff --git a/apps/web/package.json b/apps/web/package.json index 512bea47..d7953c17 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -13,7 +13,8 @@ "check:av": "vite build && vitest run --reporter=verbose src/lib/livekit.test.ts src/av/core/TrackManager.concurrency.test.ts src/av/core/TrackManager.signalClosed.test.ts src/av/features/DoNotDisturb.test.ts", "test:watch": "vitest", "test:coverage": "vitest run --coverage", - "e2e": "node ./e2e-run.js" + "e2e": "node ./e2e-run.js", + "e2e:probe": "MT_PROBE=1 playwright test --workers=1" }, "dependencies": { "@colyseus/schema": "^4.0.30", @@ -42,6 +43,7 @@ "zustand": "^5.0.15" }, "devDependencies": { + "@types/pg": "^8.21.0", "@playwright/test": "^1.63.0", "@testing-library/dom": "^10.4.2", "@testing-library/jest-dom": "^7.0.1", @@ -55,6 +57,7 @@ "eslint-plugin-react": "^7.37.5", "eslint-plugin-react-hooks": "^7.1.1", "jsdom": "^30.1.1", + "pg": "^8.23.0", "typescript": "^6.0.3", "vite": "~8.3.1", "vitest": "^5.0.2" diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index 34775813..81020ab1 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -1,21 +1,155 @@ +import { existsSync } from 'node:fs'; + import { defineConfig, devices } from '@playwright/test'; +import type { Project } from '@playwright/test'; + +const mediaFlags = [ + '--use-fake-device-for-media-stream', + '--use-fake-ui-for-media-stream', + '--auto-select-desktop-capture-source=Entire screen', +]; + +const projects: Project[] = [ + ...(process.env.MT_SEED === '1' + ? [ + { + name: 'seed', + testMatch: /support\/seed\.setup\.ts/, + }, + ] + : []), + { + name: 'chromium', + grepInvert: /@stack/, + use: { + ...devices['Desktop Chrome'], + launchOptions: { args: mediaFlags }, + permissions: ['camera', 'microphone'], + }, + // measured 2026-11-06 via npm -w @meetropolis/web run e2e:probe + metadata: { + capabilities: { + getUserMediaAudio: true, + audioNonSilent: true, + getUserMediaVideo: true, + getDisplayMedia: true, + webrtcLoopback: true, + screenShareAudio: true, + }, + }, + }, + { + name: 'chrome', + grepInvert: /@stack/, + use: { + ...devices['Desktop Chrome'], + channel: 'chrome', + launchOptions: { args: mediaFlags }, + permissions: ['camera', 'microphone'], + }, + // measured 2026-11-06 via npm -w @meetropolis/web run e2e:probe + metadata: { + capabilities: { + getUserMediaAudio: true, + audioNonSilent: true, + getUserMediaVideo: true, + getDisplayMedia: true, + webrtcLoopback: true, + screenShareAudio: true, + }, + }, + }, + { + name: 'firefox', + grepInvert: /@stack/, + use: { + ...devices['Desktop Firefox'], + launchOptions: { + firefoxUserPrefs: { + 'media.navigator.streams.fake': true, + 'media.navigator.permission.disabled': true, + }, + }, + }, + // measured 2026-11-06 via npm -w @meetropolis/web run e2e:probe + metadata: { + capabilities: { + getUserMediaAudio: false, + audioNonSilent: false, + getUserMediaVideo: true, + getDisplayMedia: true, + webrtcLoopback: true, + screenShareAudio: false, + }, + }, + }, + { + name: 'webkit', + grepInvert: /@stack/, + use: { + ...devices['Desktop Safari'], + permissions: ['camera', 'microphone'], + }, + // measured 2026-11-06 via npm -w @meetropolis/web run e2e:probe + metadata: { + capabilities: { + getUserMediaAudio: true, + audioNonSilent: false, + getUserMediaVideo: true, + getDisplayMedia: true, + webrtcLoopback: true, + screenShareAudio: false, + }, + }, + }, + ...(existsSync('/Applications/Microsoft Edge.app') + ? [ + { + name: 'msedge', + grepInvert: /@stack/, + use: { + channel: 'msedge' as const, + launchOptions: { args: mediaFlags }, + permissions: ['camera', 'microphone'], + }, + // measured 2026-11-06 via npm -w @meetropolis/web run e2e:probe + metadata: { + capabilities: { + getUserMediaAudio: false, + audioNonSilent: false, + getUserMediaVideo: false, + getDisplayMedia: false, + webrtcLoopback: false, + screenShareAudio: false, + }, + }, + }, + ] + : []), + // @stack specs pause shared stack containers, so they run once, in a single project with one worker (Q-TEST-46). + { + name: 'stack', + grep: /@stack/, + workers: 1, + retries: 0, + fullyParallel: false, + use: { ...devices['Desktop Chrome'] }, + }, +]; export default defineConfig({ testDir: './e2e', + testMatch: process.env.MT_PROBE === '1' ? '**/support/capabilities.probe.ts' : '**/*.spec.ts', timeout: 120_000, fullyParallel: true, forbidOnly: !!process.env.CI, - retries: process.env.CI ? 1 : 0, - workers: process.env.CI ? 2 : undefined, + retries: 0, + ...(process.env.CI ? { workers: 2 } : {}), reporter: [['list']], use: { - baseURL: process.env.WEB_BASE_URL || 'http://localhost:5173', - trace: 'on-first-retry', + baseURL: process.env.E2E_BASE_URL || process.env.WEB_BASE_URL || 'http://localhost:5173', + trace: 'retain-on-failure', video: 'retain-on-failure', }, - projects: [ - { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, - { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, - { name: 'webkit', use: { ...devices['Desktop Safari'] } }, - ], + projects, }); diff --git a/apps/web/src/app/routes/AppRoutes.authRemount.test.tsx b/apps/web/src/app/routes/AppRoutes.authRemount.test.tsx new file mode 100644 index 00000000..a8be5eec --- /dev/null +++ b/apps/web/src/app/routes/AppRoutes.authRemount.test.tsx @@ -0,0 +1,215 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PENDING_INVITE_KEY } from '../../lib/pendingInvite'; + +const getEnterpriseWebModule = vi.hoisted(() => vi.fn()); + +vi.mock('../../lib/enterpriseWebLoader', () => ({ getEnterpriseWebModule })); +vi.mock('./hooks/useMiniModeAuthGuard', () => ({ useMiniModeAuthGuard: vi.fn() })); +vi.mock('./WorldScreen', () => ({ WorldScreen: () =>
})); +vi.mock('./components/DesktopUpdateOverlay', () => ({ DesktopUpdateOverlay: () => null })); +vi.mock('../../ui/pub/landing/LandingPage', () => ({ LandingPage: () => null })); +vi.mock('../../ui/pub/download/DesktopDownloadPage', () => ({ DesktopDownloadPage: () => null })); +vi.mock('../../ui/pub/billing/BillingSuccessPage', () => ({ BillingSuccessPage: () => null })); +vi.mock('../../ui/pub/billing/BillingCancelPage', () => ({ BillingCancelPage: () => null })); +vi.mock('../../ui/pub/billing/EmailVerifyPage', () => ({ EmailVerifyPage: () => null })); +vi.mock('../../ui/pub/contact/ContactPage', () => ({ ContactPage: () => null })); +vi.mock('../../ui/pub/legal/SimpleLegalNotice', () => ({ SimpleLegalNotice: () => null })); +vi.mock('../../lib/brandLoader', () => ({ + getBrandModule: () => Promise.resolve(null), + useHasBrandModule: () => ({ loading: false, hasBrand: false }), +})); +vi.mock('../../state/publicConfigStore', () => { + const state = { registrationEnabled: true, load: async () => {} }; + return { usePublicConfigStore: (select: (s: typeof state) => unknown) => select(state) }; +}); +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string) => key, + i18n: { language: 'de', resolvedLanguage: 'de', changeLanguage: () => Promise.resolve() }, + }), +})); + +vi.mock('../providers/i18n', () => ({ + default: { t: (key: string) => key }, +})); + +import { AppRoutes } from './AppRoutes'; + +function jsonResponse(status: number, body: unknown) { + return { ok: status >= 200 && status < 300, status, json: () => Promise.resolve(body) }; +} + +let meStatus = 401; +let previewBodies: string[] = []; +let acceptBodies: string[] = []; + +function urlText(url: string | URL | Request): string { + if (typeof url === 'string') return url; + if (url instanceof URL) return url.href; + return url.url; +} + +function bodyText(init?: RequestInit): string { + return typeof init?.body === 'string' ? init.body : ''; +} + +function stubFetch() { + const fetchMock = vi.fn((url: string | URL | Request, init?: RequestInit) => { + const u = urlText(url); + if (u.endsWith('/public/invites/preview')) { + previewBodies.push(bodyText(init)); + return Promise.resolve( + jsonResponse(200, { + tenantName: 'Acme Corp', + role: 'member', + status: 'pending', + emailMasked: 'j***@acme.test', + }), + ); + } + if (u.endsWith('/auth/me')) { + return Promise.resolve(jsonResponse(meStatus, meStatus === 200 ? { id: 'u1' } : { error: 'unauthorized' })); + } + if (u.endsWith('/auth/login')) { + meStatus = 200; + return Promise.resolve(jsonResponse(200, {})); + } + if (u.endsWith('/invites/accept')) { + acceptBodies.push(bodyText(init)); + return Promise.resolve(jsonResponse(200, {})); + } + return Promise.resolve(jsonResponse(404, { error: 'not_found' })); + }); + vi.stubGlobal('fetch', fetchMock); + return fetchMock; +} + +const reloadMock = vi.fn(); +const realLocation = window.location; + +function installLocationShim() { + reloadMock.mockClear(); + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { + get hash() { + return realLocation.hash; + }, + set hash(v: string) { + realLocation.hash = v; + }, + get hostname() { + return realLocation.hostname; + }, + get host() { + return realLocation.host; + }, + get href() { + return realLocation.href; + }, + set href(v: string) { + realLocation.href = v; + }, + get protocol() { + return realLocation.protocol; + }, + get search() { + return realLocation.search; + }, + get origin() { + return realLocation.origin; + }, + reload: reloadMock, + toString() { + return realLocation.href; + }, + }, + }); +} + +function restoreLocation() { + Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation }); +} + +beforeEach(() => { + meStatus = 401; + previewBodies = []; + acceptBodies = []; + sessionStorage.clear(); + stubFetch(); + installLocationShim(); +}); + +afterEach(() => { + cleanup(); + window.location.hash = ''; + sessionStorage.clear(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + restoreLocation(); + getEnterpriseWebModule.mockReset(); +}); + +describe('AppRoutes auth remount', () => { + it('shows the login form after choosing sign in on an invite link', async () => { + window.location.hash = '#/?invite=CODE1'; + render(); + + expect(await screen.findByText('auth.inviteAccept.inviteTitle')).toBeTruthy(); + + fireEvent.click(screen.getByText('auth.inviteLoginLink')); + window.dispatchEvent(new Event('hashchange')); + + expect(window.location.hash).toBe('#/login'); + expect(await screen.findByText('auth.loginTitle')).toBeTruthy(); + expect(screen.queryByText('auth.inviteTitle')).toBeNull(); + }); + + it('shows the invite acceptance after returning from sign in', async () => { + window.location.hash = '#/login'; + render(); + + expect(await screen.findByText('auth.loginTitle')).toBeTruthy(); + previewBodies = []; + + window.location.hash = '#/?invite=CODE2'; + window.dispatchEvent(new Event('hashchange')); + + expect(await screen.findByText('auth.inviteAccept.inviteTitle')).toBeTruthy(); + await waitFor(() => expect(previewBodies.some((b) => b.includes('CODE2'))).toBe(true)); + }); + + it('accepts the stored invitation once after signing in', async () => { + window.location.hash = '#/?invite=CODE3'; + const { container } = render(); + + expect(await screen.findByText('auth.inviteAccept.inviteTitle')).toBeTruthy(); + + fireEvent.click(screen.getByText('auth.inviteLoginLink')); + window.dispatchEvent(new Event('hashchange')); + + expect(window.location.hash).toBe('#/login'); + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBe('CODE3'); + expect(await screen.findByText('auth.loginTitle')).toBeTruthy(); + + const emailInput = container.querySelector('input[name="email"]'); + const passwordInput = container.querySelector('input[name="password"]'); + if (!emailInput || !passwordInput) throw new Error('login form missing: expected email and password inputs'); + + fireEvent.change(emailInput, { target: { value: 'j@acme.test' } }); + fireEvent.change(passwordInput, { target: { value: 'secret123' } }); + fireEvent.click(screen.getByText('auth.loginSubmit')); + + await waitFor(() => expect(window.location.hash).toBe('#/?invite=CODE3')); + window.dispatchEvent(new Event('hashchange')); + + await waitFor(() => expect(acceptBodies).toHaveLength(1)); + expect(acceptBodies[0]).toBe(JSON.stringify({ code: 'CODE3' })); + await waitFor(() => expect(window.location.hash).toBe('#/app')); + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBeNull(); + expect(window.location.reload).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/src/app/routes/AppRoutes.tsx b/apps/web/src/app/routes/AppRoutes.tsx index f97a95bd..264f51c2 100644 --- a/apps/web/src/app/routes/AppRoutes.tsx +++ b/apps/web/src/app/routes/AppRoutes.tsx @@ -129,12 +129,21 @@ function RouteContent({ route, params, apiBase, registrationEnabled, navigate }: registrationEnabled={registrationEnabled} /> ); + case 'verify-pending': + return ( + + ); case 'verify': return ( navigate('app')} + onSuccess={() => navigate('login')} onBack={() => navigate('landing')} /> ); @@ -157,10 +166,13 @@ function RouteContent({ route, params, apiBase, registrationEnabled, navigate }: /> ); case 'login': - return ; + return ( + + ); case 'register': return ( ); case 'guest-auth': - return ; + return ; case 'connect': return ; case 'app': diff --git a/apps/web/src/app/routes/hooks/useFetchMe.ts b/apps/web/src/app/routes/hooks/useFetchMe.ts index c024c689..d3d7d2a6 100644 --- a/apps/web/src/app/routes/hooks/useFetchMe.ts +++ b/apps/web/src/app/routes/hooks/useFetchMe.ts @@ -1,3 +1,4 @@ +import { readAccountError } from '../../../lib/accountActionResponses'; import { useEffect } from 'react'; import { logger } from '../../../lib/logger'; import { computeBackoffDelayMs, type BackoffOptions } from '../../../lib/backoff'; @@ -68,7 +69,10 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** Outcome of a single /auth/me probe. */ export type FetchMeOutcome = - { status: 'ok'; user: MeResponse } | { status: 'unauthorized' } | { status: 'network-error' }; + | { status: 'ok'; user: MeResponse } + | { status: 'unauthorized' } + | { status: 'network-error' } + | { status: 'verification-required' }; /** Options controlling the boot-time retry policy for transient failures. */ export interface FetchMeRetryOptions { @@ -95,6 +99,9 @@ export async function fetchMeOnce(apiBase: string): Promise { const res = await fetch(`${apiBase}/auth/me`, { credentials: 'include' }); if (res.ok) return { status: 'ok', user: (await res.json()) as MeResponse }; if (isTransientStatus(res.status)) return { status: 'network-error' }; + const error = readAccountError(await res.json().catch(() => null)); + if (error.code === 'EMAIL_VERIFICATION_REQUIRED' || error.code === 'EMAIL_VERIFICATION_BINDING_REQUIRED') + return { status: 'verification-required' }; // 401/403 (and any other non-transient 4xx) are authoritative: not logged in. return { status: 'unauthorized' }; } catch (e) { @@ -251,6 +258,11 @@ export async function runFetchMe( return; } + if (outcome.status === 'verification-required') { + setAuthOffline(false); + window.location.hash = '#/verify-pending'; + return; + } if (outcome.status === 'unauthorized') { setAuthOffline(false); setAuthTenantSlug(null); diff --git a/apps/web/src/app/routes/useHashRoute.test.tsx b/apps/web/src/app/routes/useHashRoute.test.tsx index eb30f093..48ffabb3 100644 --- a/apps/web/src/app/routes/useHashRoute.test.tsx +++ b/apps/web/src/app/routes/useHashRoute.test.tsx @@ -120,3 +120,7 @@ describe('sanitizeTierKey', () => { expect(sanitizeTierKey('-team')).toBeUndefined(); }); }); + +it('matches the exact pending route before the verify prefix and discards proof secrets there', () => { + expect(parseHashRoute('/verify-pending?token=ignored')).toEqual({ route: 'verify-pending', params: {} }); +}); diff --git a/apps/web/src/app/routes/useHashRoute.ts b/apps/web/src/app/routes/useHashRoute.ts index 91d0a606..dc68c0e7 100644 --- a/apps/web/src/app/routes/useHashRoute.ts +++ b/apps/web/src/app/routes/useHashRoute.ts @@ -9,6 +9,7 @@ export type Route = | 'impressum' | 'contact' | 'download' + | 'verify-pending' | 'verify' | 'billing-success' | 'billing-cancel' @@ -72,6 +73,7 @@ export function parseHashRoute(hash: string): { route: Route; params: RouteParam // same page rather than redirecting, so neither URL is the broken one. if (path === '/contact' || path === '/kontakt') return { route: 'contact', params }; if (path === '/download' || path === '/desktop') return { route: 'download', params }; + if (path === '/verify-pending') return { route: 'verify-pending', params }; if (path.startsWith('/verify')) { const sp = new URLSearchParams(searchPart.slice(1)); setOptional(params, 'verifyToken', sp.get('token')); diff --git a/apps/web/src/features/admin/InvitesModal.tsx b/apps/web/src/features/admin/InvitesModal.tsx deleted file mode 100644 index 11e283f0..00000000 --- a/apps/web/src/features/admin/InvitesModal.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import * as React from 'react'; -import { useTranslation } from 'react-i18next'; -import { Modal, Button, Card, Table, THead, TBody, Tr, Th, Td, TableContainer } from '../../ui/system'; - -type Invite = { code: string; email?: string | null; usedAt?: string | null; createdAt?: string }; - -function InvitesTableHeader() { - const { t } = useTranslation(); - return ( - - - {t('admin.invites.code')} - {t('admin.invites.email')} - {t('admin.invites.createdAt')} - {t('admin.invites.status')} - {null} - - - ); -} - -function InvitesLoadingRows() { - return ( - - {[1, 2, 3].map((i) => ( - - -
- - - ))} - - ); -} - -function InvitesEmptyRow() { - const { t } = useTranslation(); - return ( - - - - {t('admin.invites.empty')} - - - - ); -} - -function InviteRow({ inv, onDelete }: { inv: Invite; onDelete: (code: string) => void | Promise }) { - const { t } = useTranslation(); - const placeholder = t('admin.invites.placeholder'); - return ( - - - - {inv.code} - - - {inv.email || placeholder} - {inv.createdAt ? new Date(inv.createdAt).toLocaleString() : placeholder} - {inv.usedAt ? t('admin.invites.statusUsed') : t('admin.invites.statusOpen')} - - - {!inv.usedAt && ( - - )} - - - ); -} - -function useInvites(open: boolean, apiBase: string) { - const [invites, setInvites] = React.useState([]); - const [loading, setLoading] = React.useState(false); - - React.useEffect(() => { - if (!open) return; - void (async () => { - setLoading(true); - try { - const res = await fetch(`${apiBase}/invites`, { credentials: 'include' }); - if (res.ok) setInvites((await res.json()) as Invite[]); - } catch {} - setLoading(false); - })(); - }, [open, apiBase]); - - const deleteInvite = async (code: string) => { - try { - const res = await fetch(`${apiBase}/invites/${encodeURIComponent(code)}`, { - method: 'DELETE', - credentials: 'include', - }); - if (res.ok) setInvites((prev) => prev.filter((i) => i.code !== code)); - } catch {} - }; - - return { invites, loading, deleteInvite }; -} - -export function InvitesModal({ - open, - onOpenChange, - apiBase, -}: { - open: boolean; - onOpenChange: (v: boolean) => void; - apiBase: string; -}) { - const { t } = useTranslation(); - const { invites, loading, deleteInvite } = useInvites(open, apiBase); - - return ( - - - - - - {loading && } - {!loading && invites.length === 0 && } - {!loading && invites.length > 0 && ( - - {invites.map((inv) => ( - - ))} - - )} -
-
-
-
- ); -} diff --git a/apps/web/src/lib/accountActionResponses.test.ts b/apps/web/src/lib/accountActionResponses.test.ts new file mode 100644 index 00000000..72ce5874 --- /dev/null +++ b/apps/web/src/lib/accountActionResponses.test.ts @@ -0,0 +1,38 @@ +import { expect, it } from 'vitest'; +import { + AccountActionError, + needsEmailVerification, + readAccountError, + readEmailChangePending, + readMailSent, + readProofResult, +} from './accountActionResponses'; + +it('preserves status, stable code, message and retry delay across response formats', () => { + expect(readAccountError({ error: 'Please confirm.', code: 'EMAIL_VERIFICATION_REQUIRED' })).toEqual({ + code: 'EMAIL_VERIFICATION_REQUIRED', + message: 'Please confirm.', + retryAfter: null, + }); + expect(readAccountError({ error: { code: 'RATE_LIMITED', message: 'Bitte warten.' }, retryAfter: 15 })).toEqual({ + code: 'RATE_LIMITED', + message: 'Bitte warten.', + retryAfter: 15, + }); + expect(needsEmailVerification(new AccountActionError(409, 'EMAIL_VERIFICATION_REQUIRED', 'Please confirm.'))).toBe( + true, + ); + expect(needsEmailVerification(new AccountActionError(403, 'forbidden', 'Kein Zugang.'))).toBe(false); +}); + +it('does not infer delivery or a confirmed email change from unknown JSON', () => { + for (const value of [null, undefined, '', [], true, { sent: false }, { sent: 'true' }]) + expect(readMailSent(value)).toBe(false); + expect(readMailSent({ sent: true })).toBe(true); + expect(readEmailChangePending({ emailChangePending: true, pendingEmail: 'new@example.test' })).toBe( + 'new@example.test', + ); + expect(readEmailChangePending({ emailChangePending: 'true', pendingEmail: 'new@example.test' })).toBeNull(); + expect(readProofResult({ ok: true, purpose: 'unknown' })).toBeNull(); + expect(readProofResult({ ok: true, purpose: 'email_change' })).toEqual({ purpose: 'email_change', tenantSlug: null }); +}); diff --git a/apps/web/src/lib/accountActionResponses.ts b/apps/web/src/lib/accountActionResponses.ts new file mode 100644 index 00000000..f40cdcb5 --- /dev/null +++ b/apps/web/src/lib/accountActionResponses.ts @@ -0,0 +1,55 @@ +function record(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record : null; +} + +export function readAccountError(value: unknown) { + const body = record(value); + const error = record(body?.error); + return { + code: typeof body?.code === 'string' ? body.code : typeof error?.code === 'string' ? error.code : null, + message: typeof body?.error === 'string' ? body.error : typeof error?.message === 'string' ? error.message : null, + retryAfter: typeof body?.retryAfter === 'number' && body.retryAfter > 0 ? body.retryAfter : null, + }; +} + +export class AccountActionError extends Error { + constructor( + readonly status: number, + readonly code: string | null, + message: string, + readonly retryAfter: number | null = null, + ) { + super(message); + } +} + +export function needsEmailVerification(error: unknown): error is AccountActionError { + return ( + error instanceof AccountActionError && + (error.code === 'EMAIL_VERIFICATION_REQUIRED' || error.code === 'EMAIL_VERIFICATION_BINDING_REQUIRED') + ); +} + +export function readMailSent(value: unknown): boolean { return record(value)?.sent === true; } + +export function readProofResult(value: unknown) { + const body = record(value); + const purpose = body?.purpose; + if (body?.ok !== true || (purpose !== 'invite' && purpose !== 'verify' && purpose !== 'email_change')) return null; + return { purpose, tenantSlug: typeof body.tenantSlug === 'string' ? body.tenantSlug : null }; +} + +export function readEmailChangePending(value: unknown): string | null { + const body = record(value); + return body?.emailChangePending === true && typeof body.pendingEmail === 'string' ? body.pendingEmail : null; +} + +export function readVerificationDelivery(value: unknown): 'sent' | 'unavailable' | 'login_required' | null { + const body = record(value); + if (body?.code === 'ACCOUNT_LOGIN_REQUIRED' && body.status === 'login_required') return 'login_required'; + if (body?.code === 'EMAIL_VERIFICATION_REQUIRED' && (body.status === 'sent' || body.status === 'unavailable')) + return body.status; + if (body?.requiresLogin === true) return 'login_required'; + const delivery = record(value)?.pendingDelivery; + return delivery === 'sent' || delivery === 'unavailable' ? delivery : null; +} diff --git a/apps/web/src/lib/apiErrors.test.ts b/apps/web/src/lib/apiErrors.test.ts index 9e631d1f..e6fe36b9 100644 --- a/apps/web/src/lib/apiErrors.test.ts +++ b/apps/web/src/lib/apiErrors.test.ts @@ -57,6 +57,15 @@ describe('translateApiError', () => { delete translations['apiError.invalid_credentials']; } }); + + it('translates a missing public base URL instead of returning the code', () => { + translations['apiError.public_base_url_missing'] = 'Die öffentliche Adresse ist nicht konfiguriert.'; + try { + expect(translateApiError('public_base_url_missing')).toBe('Die öffentliche Adresse ist nicht konfiguriert.'); + } finally { + delete translations['apiError.public_base_url_missing']; + } + }); }); describe('malformed / missing bodies never call a string method on a non-string', () => { diff --git a/apps/web/src/lib/pendingInvite.test.ts b/apps/web/src/lib/pendingInvite.test.ts new file mode 100644 index 00000000..dd382b83 --- /dev/null +++ b/apps/web/src/lib/pendingInvite.test.ts @@ -0,0 +1,36 @@ +// @vitest-environment jsdom +import { describe, it, expect, beforeEach } from 'vitest'; +import { + PENDING_INVITE_KEY, + clearPendingInvite, + inviteHash, + readPendingInvite, + storePendingInvite, +} from './pendingInvite'; + +describe('pendingInvite', () => { + beforeEach(() => { + sessionStorage.clear(); + }); + + it('stores and reads a code', () => { + storePendingInvite('MEET-ABC-123456'); + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBe('MEET-ABC-123456'); + expect(readPendingInvite()).toBe('MEET-ABC-123456'); + }); + + it('reads null when nothing is stored', () => { + expect(readPendingInvite()).toBeNull(); + }); + + it('clears a stored code', () => { + storePendingInvite('MEET-ABC-123456'); + clearPendingInvite(); + expect(readPendingInvite()).toBeNull(); + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBeNull(); + }); + + it('encodes the code into the invite hash', () => { + expect(inviteHash('MEET A/B?C')).toBe(`#/?invite=${encodeURIComponent('MEET A/B?C')}`); + }); +}); diff --git a/apps/web/src/lib/pendingInvite.ts b/apps/web/src/lib/pendingInvite.ts new file mode 100644 index 00000000..eb63d0af --- /dev/null +++ b/apps/web/src/lib/pendingInvite.ts @@ -0,0 +1,29 @@ +export const PENDING_INVITE_KEY = 'meetropolis.pendingInvite'; + +export function readPendingInvite(): string | null { + try { + return sessionStorage.getItem(PENDING_INVITE_KEY); + } catch { + return null; + } +} + +export function storePendingInvite(code: string): void { + try { + sessionStorage.setItem(PENDING_INVITE_KEY, code); + } catch { + /* private mode: storage unavailable */ + } +} + +export function clearPendingInvite(): void { + try { + sessionStorage.removeItem(PENDING_INVITE_KEY); + } catch { + /* private mode: storage unavailable */ + } +} + +export function inviteHash(code: string): string { + return `#/?invite=${encodeURIComponent(code)}`; +} diff --git a/apps/web/src/locales/de/common.json b/apps/web/src/locales/de/common.json index f18b2cf3..6a1ab7ab 100644 --- a/apps/web/src/locales/de/common.json +++ b/apps/web/src/locales/de/common.json @@ -438,6 +438,7 @@ "tenant.shareInviteCode": "Diesen Einladungscode teilen:", "tenant.copyLink": "Link kopieren", "tenant.linkCopied": "Einladungslink in die Zwischenablage kopiert", + "tenant.linkCopyFailed": "Der Link konnte nicht in die Zwischenablage kopiert werden.", "tenant.done": "Fertig", "tenant.emailOptional": "E-Mail (optional)", "tenant.emailPlaceholder": "name@beispiel.de", @@ -468,6 +469,21 @@ "tenant.inviteDeleteFailed": "Einladung konnte nicht gelöscht werden", "tenant.noInvites": "Noch keine Einladungen", "tenant.invitesLoading": "Einladungen werden geladen…", + "tenant.invitesLoadFailed": "Einladungen konnten nicht geladen werden.", + "tenant.retry": "Erneut versuchen", + "tenant.inviteAccepted": "Angenommen", + "tenant.inviteExpired": "Abgelaufen", + "tenant.inviteValidUntil": "Gültig bis", + "tenant.inviteDelivery": "Zustellung", + "tenant.inviteNotDelivered": "Nicht zugestellt", + "tenant.inviteSentOn": "Gesendet am {{date}}", + "tenant.inviteResend": "Erneut senden", + "tenant.inviteRevoke": "Widerrufen", + "tenant.inviteResent": "Einladung erneut gesendet.", + "tenant.inviteSentTo": "Einladung an {{email}} gesendet.", + "tenant.inviteResendNotDelivered": "Die E-Mail konnte nicht zugestellt werden. Link kopieren und selbst weitergeben.", + "tenant.inviteResendFailed": "Einladung konnte nicht erneut gesendet werden", + "tenant.inviteRevokeFailed": "Einladung konnte nicht widerrufen werden", "tenant.createdAt": "Erstellt am", "tenant.memberCount": "Mitglieder", "tenant.defaultMap": "Standard-Map", @@ -486,6 +502,9 @@ "apiError.code__email__password_required": "Code, E-Mail und Passwort erforderlich", "apiError.invalid_or_used_invite": "Ungültige oder bereits verwendete Einladung", "apiError.invite_does_not_match_email": "Einladung stimmt nicht mit E-Mail überein", + "apiError.invite_email_mismatch": "Diese Einladung gilt für eine andere E-Mail-Adresse. Melde dich mit der eingeladenen Adresse an oder bitte um eine neue Einladung.", + "apiError.invite_unavailable": "Diese Einladung ist nicht mehr gültig. Bitte um eine neue Einladung.", + "apiError.invite_expired": "Diese Einladung ist abgelaufen. Bitte um eine neue Einladung.", "apiError.email_already_in_use": "Diese E-Mail wird bereits verwendet", "apiError.registration_failed": "Registrierung fehlgeschlagen", "apiError.email_and_password_required": "E-Mail und Passwort erforderlich", @@ -561,6 +580,7 @@ "apiError.import_failed": "Import fehlgeschlagen", "apiError.cannot_delete_default_map": "Standard-Karte kann nicht gelöscht werden", "apiError.RATE_LIMITED": "Zu viele Versuche. Bitte warte einen Moment und versuche es erneut.", + "apiError.public_base_url_missing": "Der Link kann nicht erstellt werden, weil die öffentliche Adresse dieser Instanz nicht konfiguriert ist (PUBLIC_BASE_URL). Bitte wende dich an den Betreiber.", "sessionConflict.takenOver.title": "An einem anderen Gerät angemeldet", "sessionConflict.takenOver.description": "Dieser Zugang wurde an einem anderen Gerät übernommen. Es kann jeweils nur ein Gerät gleichzeitig verbunden sein.", "sessionConflict.takenOver.reconnect": "Hier wieder verbinden", @@ -731,5 +751,16 @@ "avatarEditor.option.beard.stubble": "Dreitagebart", "avatarEditor.option.beard.trimmed": "Kurzer Vollbart", "avatarEditor.option.beard.long_beard": "Langer Bart", - "avatarEditor.option.beard.handlebar": "Zwirbelbart" + "avatarEditor.option.beard.handlebar": "Zwirbelbart", + "profile.emailChange.active": "Aktive E-Mail-Adresse", + "profile.emailChange.verified": "Bestätigt", + "profile.emailChange.pending": "Bestätigungslink an {{email}} gesendet. Deine bisherige Adresse bleibt bis zur Bestätigung aktiv.", + "profile.emailChange.completed": "Die bestätigte neue E-Mail-Adresse ist aktiv.", + "profile.emailChange.newAddress": "Neue E-Mail-Adresse", + "profile.emailChange.request": "Mailwechsel anfordern", + "profile.emailChange.refresh": "Status aktualisieren", + "profile.emailChange.failed": "Der Mailwechsel konnte nicht angefordert werden. Deine bisherige Adresse bleibt aktiv.", + "profile.emailChange.cooldown": "Bitte warte vor einer weiteren Anforderung.", + "verifyBanner.cooldown": "Bitte warte noch {{seconds}} Sekunden vor einer weiteren Bestätigungsmail.", + "apiError.invite_id_invalid": "Bitte aktualisiere die Anwendung und verwende die aktuelle Einladungsliste zum Widerrufen." } diff --git a/apps/web/src/locales/de/public.json b/apps/web/src/locales/de/public.json index ee177eab..ed94b0e3 100644 --- a/apps/web/src/locales/de/public.json +++ b/apps/web/src/locales/de/public.json @@ -198,7 +198,21 @@ "successText": "Deine E-Mail wurde erfolgreich bestätigt. Du wirst gleich weitergeleitet...", "errorTitle": "Verifizierung fehlgeschlagen", "noToken": "Kein Verifizierungs-Token vorhanden.", - "backButton": "Zurück zur Startseite" + "backButton": "Zurück zur Startseite", + "invite": { + "title": "Einladung bestätigt", + "text": "Deine E-Mail-Adresse ist bestätigt und die Einladung wurde angenommen." + }, + "verify": { + "title": "E-Mail-Adresse bestätigt", + "text": "Deine E-Mail-Adresse wurde erfolgreich bestätigt." + }, + "email_change": { + "title": "E-Mail-Adresse geändert", + "text": "Deine neue E-Mail-Adresse ist jetzt aktiv und bestätigt." + }, + "continue": "Weiter zur Anmeldung oder zum Büro", + "invalidLink": "Dieser Link ist ungültig, abgelaufen oder bereits verwendet. Bitte fordere eine neue Bestätigung an." }, "auth": { "brandingHeadline": "Dein virtuelles Büro, selbst gehostet.", @@ -239,6 +253,15 @@ "inviteLoginLink": "Anmelden", "inviteNoAccount": "Kein Konto?", "inviteRegisterLink": "Registrieren", + "inviteAccept": { + "loading": "Einladung wird geladen …", + "notFound": "Diese Einladung gibt es nicht oder sie wurde widerrufen.", + "alreadyUsed": "Diese Einladung wurde bereits verwendet.", + "acceptTitle": "Einladung zu {{tenant}} annehmen", + "acceptButton": "Einladung annehmen", + "inviteTitle": "Einladung zu {{tenant}}", + "inviteForEmail": "Die Einladung gilt für {{email}}." + }, "forgotTitle": "Passwort vergessen", "forgotSubtitle": "Gib deine E-Mail-Adresse ein. Wir schicken dir einen Link, mit dem du ein neues Passwort setzt.", "forgotSentTitle": "Schau in dein Postfach", @@ -264,6 +287,7 @@ "dividerOr": "oder", "emailLabel": "E-Mail-Adresse", "passwordLabel": "Passwort", + "requiredFieldsMissing": "Bitte fülle alle Pflichtfelder aus.", "setupTeamTitle": "Richte dein Team ein", "setupTeamSubtitle": "Wie heißt euer Team und wie groß ist es?", "teamName": "Teamname", @@ -336,7 +360,20 @@ "errB2bDeclaration": "Bitte bestätige die Unternehmer-Erklärung.", "errAgb": "Bitte akzeptiere die AGB.", "errB2bRequired": "Für die kostenpflichtige Nutzung sind Firmenname, Rechtsform und die Unternehmer-Erklärung erforderlich.", - "back": "Zurück" + "back": "Zurück", + "emailProof": { + "title": "Bitte bestätige deine E-Mail-Adresse", + "description": "Öffne die separate Bestätigungsmail. Erst nach der Bestätigung kannst du diese Einladung nutzen.", + "idle": "Die Einladung bleibt für dich vorgemerkt.", + "sending": "Bestätigungsmail wird angefordert …", + "sent": "Eine Bestätigungsmail wurde versandt.", + "cooldown": "Bitte warte noch {{seconds}} Sekunden, bevor du erneut eine Mail anforderst.", + "failed": "Die Mail konnte nicht zugestellt werden. Bitte wende dich an die Administration.", + "loginRequired": "Bitte melde dich erneut an, um eine Bestätigungsmail anzufordern.", + "resend": "Bestätigungsmail erneut anfordern", + "login": "Zur Anmeldung", + "check": "Bestätigung prüfen" + } }, "billing": { "reconcilingTitle": "Wir richten dein Büro ein …", diff --git a/apps/web/src/locales/en/common.json b/apps/web/src/locales/en/common.json index ea88b0c4..6ef97bb5 100644 --- a/apps/web/src/locales/en/common.json +++ b/apps/web/src/locales/en/common.json @@ -438,6 +438,7 @@ "tenant.shareInviteCode": "Share this invite code:", "tenant.copyLink": "Copy Link", "tenant.linkCopied": "Invite link copied to clipboard", + "tenant.linkCopyFailed": "The link could not be copied to the clipboard.", "tenant.done": "Done", "tenant.emailOptional": "Email (optional)", "tenant.emailPlaceholder": "user@example.com", @@ -468,6 +469,21 @@ "tenant.inviteDeleteFailed": "Failed to delete invite", "tenant.noInvites": "No invites yet", "tenant.invitesLoading": "Loading invites...", + "tenant.invitesLoadFailed": "Invitations could not be loaded.", + "tenant.retry": "Try again", + "tenant.inviteAccepted": "Accepted", + "tenant.inviteExpired": "Expired", + "tenant.inviteValidUntil": "Valid until", + "tenant.inviteDelivery": "Delivery", + "tenant.inviteNotDelivered": "Not delivered", + "tenant.inviteSentOn": "Sent on {{date}}", + "tenant.inviteResend": "Send again", + "tenant.inviteRevoke": "Revoke", + "tenant.inviteResent": "Invitation sent again.", + "tenant.inviteSentTo": "Invitation sent to {{email}}.", + "tenant.inviteResendNotDelivered": "The email could not be delivered. Copy the link and share it yourself.", + "tenant.inviteResendFailed": "Failed to resend invitation", + "tenant.inviteRevokeFailed": "Failed to revoke invitation", "tenant.createdAt": "Created", "tenant.memberCount": "Members", "tenant.defaultMap": "Default Map", @@ -486,6 +502,9 @@ "apiError.code__email__password_required": "Code, email and password required", "apiError.invalid_or_used_invite": "Invalid or already used invite", "apiError.invite_does_not_match_email": "Invite does not match email", + "apiError.invite_email_mismatch": "This invitation is for a different email address. Sign in with the invited address or ask for a new invitation.", + "apiError.invite_unavailable": "This invitation is no longer valid. Please ask for a new invitation.", + "apiError.invite_expired": "This invitation has expired. Please ask for a new invitation.", "apiError.email_already_in_use": "Email already in use", "apiError.registration_failed": "Registration failed", "apiError.email_and_password_required": "Email and password required", @@ -561,6 +580,7 @@ "apiError.import_failed": "Import failed", "apiError.cannot_delete_default_map": "Default map cannot be deleted", "apiError.RATE_LIMITED": "Too many attempts. Please wait a moment and try again.", + "apiError.public_base_url_missing": "The link cannot be created because this instance's public address is not configured (PUBLIC_BASE_URL). Please contact the operator.", "sessionConflict.takenOver.title": "Signed in on another device", "sessionConflict.takenOver.description": "This account was taken over on another device. Only one device can be connected at a time.", "sessionConflict.takenOver.reconnect": "Reconnect here", @@ -731,5 +751,16 @@ "avatarEditor.option.beard.stubble": "Stubble", "avatarEditor.option.beard.trimmed": "Trimmed beard", "avatarEditor.option.beard.long_beard": "Long beard", - "avatarEditor.option.beard.handlebar": "Handlebar moustache" + "avatarEditor.option.beard.handlebar": "Handlebar moustache", + "profile.emailChange.active": "Active email address", + "profile.emailChange.verified": "Confirmed", + "profile.emailChange.pending": "A confirmation link was sent to {{email}}. Your previous address stays active until confirmation.", + "profile.emailChange.completed": "Your confirmed new email address is active.", + "profile.emailChange.newAddress": "New email address", + "profile.emailChange.request": "Request email change", + "profile.emailChange.refresh": "Refresh status", + "profile.emailChange.failed": "The email change could not be requested. Your previous address stays active.", + "profile.emailChange.cooldown": "Please wait before making another request.", + "verifyBanner.cooldown": "Please wait {{seconds}} seconds before requesting another confirmation email.", + "apiError.invite_id_invalid": "Please update the application and use the current invitation list to revoke invitations." } diff --git a/apps/web/src/locales/en/public.json b/apps/web/src/locales/en/public.json index dfe453d7..f60cc0f9 100644 --- a/apps/web/src/locales/en/public.json +++ b/apps/web/src/locales/en/public.json @@ -198,7 +198,21 @@ "successText": "Your email has been successfully confirmed. You will be redirected shortly...", "errorTitle": "Verification Failed", "noToken": "No verification token provided.", - "backButton": "Back to Home" + "backButton": "Back to Home", + "invite": { + "title": "Invitation confirmed", + "text": "Your email address is confirmed and the invitation was accepted." + }, + "verify": { + "title": "Email address confirmed", + "text": "Your email address was confirmed successfully." + }, + "email_change": { + "title": "Email address changed", + "text": "Your new email address is now active and confirmed." + }, + "continue": "Continue to sign in or your office", + "invalidLink": "This link is invalid, expired or already used. Please request a new confirmation." }, "auth": { "brandingHeadline": "Your virtual office, your rules.", @@ -239,6 +253,15 @@ "inviteLoginLink": "Sign In", "inviteNoAccount": "No account?", "inviteRegisterLink": "Sign Up", + "inviteAccept": { + "loading": "Loading invitation …", + "notFound": "This invitation does not exist or has been revoked.", + "alreadyUsed": "This invitation has already been used.", + "acceptTitle": "Accept the invitation to {{tenant}}", + "acceptButton": "Accept invitation", + "inviteTitle": "Invitation to {{tenant}}", + "inviteForEmail": "The invitation is for {{email}}." + }, "forgotTitle": "Forgot Password", "forgotSubtitle": "Enter your email address. We'll send you a link to set a new password.", "forgotSentTitle": "Check your inbox", @@ -264,6 +287,7 @@ "dividerOr": "or", "emailLabel": "Email Address", "passwordLabel": "Password", + "requiredFieldsMissing": "Please fill in all required fields.", "setupTeamTitle": "Set up your team", "setupTeamSubtitle": "What's your team called and how big is it?", "teamName": "Team Name", @@ -336,7 +360,20 @@ "errB2bDeclaration": "Please confirm the entrepreneur declaration.", "errAgb": "Please accept the Terms of Service.", "errB2bRequired": "A company name, legal form and the entrepreneur declaration are required for paid use.", - "back": "Back" + "back": "Back", + "emailProof": { + "title": "Please confirm your email address", + "description": "Open the separate confirmation email. You can use this invitation after confirming your address.", + "idle": "Your invitation is kept for you.", + "sending": "Requesting confirmation email …", + "sent": "A confirmation email was sent.", + "cooldown": "Please wait {{seconds}} seconds before requesting another email.", + "failed": "The email could not be delivered. Please contact your administrator.", + "loginRequired": "Please sign in again to request a confirmation email.", + "resend": "Request another confirmation email", + "login": "Back to sign in", + "check": "Check confirmation" + } }, "billing": { "reconcilingTitle": "Setting up your workspace …", diff --git a/apps/web/src/locales/inviteMessages.test.ts b/apps/web/src/locales/inviteMessages.test.ts new file mode 100644 index 00000000..d711fdd3 --- /dev/null +++ b/apps/web/src/locales/inviteMessages.test.ts @@ -0,0 +1,34 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest'; +import deCommon from './de/common.json'; +import enCommon from './en/common.json'; +import dePublic from './de/public.json'; +import enPublic from './en/public.json'; + +const inviteErrorKeys = [ + 'apiError.invite_email_mismatch', + 'apiError.invite_unavailable', + 'apiError.invite_expired', + 'apiError.already_member', +]; + +function localeMessages(lang: 'de' | 'en') { + const common = (lang === 'de' ? deCommon : enCommon) as Record; + const pub = (lang === 'de' ? dePublic : enPublic) as { auth: Record }; + return { common, required: pub.auth.requiredFieldsMissing }; +} + +describe('invite and required-field messages', () => { + for (const lang of ['de', 'en'] as const) { + it(`has non-empty invite and required-field messages in ${lang}`, () => { + const { common, required } = localeMessages(lang); + + for (const key of inviteErrorKeys) { + expect(typeof common[key], key).toBe('string'); + expect((common[key] as string).length).toBeGreaterThan(0); + } + expect(typeof required).toBe('string'); + expect((required as string).length).toBeGreaterThan(0); + }); + } +}); diff --git a/apps/web/src/ui/admin/UserModals.test.tsx b/apps/web/src/ui/admin/UserModals.test.tsx new file mode 100644 index 00000000..a62f6615 --- /dev/null +++ b/apps/web/src/ui/admin/UserModals.test.tsx @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { CreateUserModal } from './UserModals'; + +vi.mock('react-i18next', async (importOriginal) => ({ + ...(await importOriginal()), + useTranslation: () => ({ + t: (key: string, opts?: { email?: string }) => (opts?.email ? `${key}:${opts.email}` : key), + }), +})); + +let emailSent = true; +let lastBody: unknown = null; + +function stubApi() { + lastBody = null; + vi.stubGlobal( + 'fetch', + vi.fn((url: string, init?: RequestInit) => { + if (init?.method === 'POST' && String(url).endsWith('/auth/invite')) { + lastBody = JSON.parse(init.body as string); + return Promise.resolve({ + ok: true, + status: 201, + json: () => + Promise.resolve({ + code: 'ABC123', + role: 'member', + inviteUrl: 'https://public.example/#/?invite=ABC123', + expiresAt: '2026-02-01T00:00:00.000Z', + emailSent, + }), + }); + } + return Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({}) }); + }), + ); +} + +function renderModal() { + const setError = vi.fn(); + render(); + return { setError }; +} + +function fillEmail(email: string) { + fireEvent.change(screen.getByPlaceholderText('admin.users.emailAddress'), { target: { value: email } }); +} + +function submitButton() { + return screen.getByText('admin.users.createInvite').closest('button') as HTMLButtonElement; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('CreateUserModal invite delivery', () => { + it('disables creating while the email is empty', () => { + emailSent = true; + stubApi(); + renderModal(); + + expect(submitButton()).toBeDisabled(); + fillEmail('new@example.test'); + expect(submitButton()).not.toBeDisabled(); + }); + + it('shows the sent confirmation with the address when the email was sent', async () => { + emailSent = true; + stubApi(); + renderModal(); + + fillEmail('new@example.test'); + fireEvent.click(submitButton()); + + expect(await screen.findByText('tenant.inviteSentTo:new@example.test')).toBeTruthy(); + expect(screen.getByText('https://public.example/#/?invite=ABC123')).toBeTruthy(); + expect(screen.getByText('admin.users.copy')).toBeTruthy(); + expect(lastBody).toMatchObject({ email: 'new@example.test' }); + }); + + it('shows the not-delivered hint and the link when the email was not sent', async () => { + emailSent = false; + stubApi(); + renderModal(); + + fillEmail('new@example.test'); + fireEvent.click(submitButton()); + + expect(await screen.findByText('tenant.inviteResendNotDelivered')).toBeTruthy(); + expect(screen.getByText('https://public.example/#/?invite=ABC123')).toBeTruthy(); + expect(screen.getByText('admin.users.copy')).toBeTruthy(); + }); +}); diff --git a/apps/web/src/ui/admin/UserModals.tsx b/apps/web/src/ui/admin/UserModals.tsx index 7e0a332b..a76b035a 100644 --- a/apps/web/src/ui/admin/UserModals.tsx +++ b/apps/web/src/ui/admin/UserModals.tsx @@ -22,11 +22,13 @@ export function CreateUserModal({ const [newEmail, setNewEmail] = React.useState(''); const [newName, setNewName] = React.useState(''); const [newRole, setNewRole] = React.useState<'admin' | 'member'>('member'); - const [inviteCode, setInviteCode] = React.useState(null); + const [invite, setInvite] = React.useState<{ email: string; inviteUrl: string | null; emailSent: boolean } | null>( + null, + ); React.useEffect(() => { if (open) { - setInviteCode(null); + setInvite(null); setNewEmail(''); setNewName(''); } @@ -43,7 +45,7 @@ export function CreateUserModal({ }); if (!res.ok) throw new Error(translateApiError(((await res.json()) as ApiErrorBody)?.error) || t('common.error')); const data = (await res.json()) as InviteResponse; - setInviteCode(data.code || null); + setInvite({ email: newEmail, inviteUrl: data.inviteUrl || null, emailSent: data.emailSent ?? false }); try { await (document as unknown as UserManagementWindow).__userManagementLoad?.(); } catch (err) { @@ -69,6 +71,7 @@ export function CreateUserModal({
)} - {inviteCode && ( + {invite && (
-
{t('admin.users.inviteCode')}
+
+ {invite.emailSent + ? t('tenant.inviteSentTo', { email: invite.email }) + : t('tenant.inviteResendNotDelivered')} +
- {inviteCode} + {invite.inviteUrl}
)} - {state === 'failed' && {t('verifyBanner.failed')}} + {(state === 'failed' || state === 'loginRequired') && {t('verifyBanner.failed')}} + {state === 'cooldown' && {t('verifyBanner.cooldown', { seconds: retryAfter })}} ); } diff --git a/apps/web/src/ui/billing/hooks/useVerificationRequest.ts b/apps/web/src/ui/billing/hooks/useVerificationRequest.ts new file mode 100644 index 00000000..cfbe584c --- /dev/null +++ b/apps/web/src/ui/billing/hooks/useVerificationRequest.ts @@ -0,0 +1,51 @@ +import { useEffect, useRef, useState } from 'react'; +import { useAuthApi } from '../../pub/auth/hooks/useAuthApi'; +import { AccountActionError, readMailSent, readVerificationDelivery } from '../../../lib/accountActionResponses'; + +export function useVerificationRequest(apiBase: string, inspectStatus = false) { + const { post } = useAuthApi(apiBase); + const [state, setState] = useState<'idle' | 'sending' | 'sent' | 'cooldown' | 'failed' | 'loginRequired'>('idle'); + const actionVersion = useRef(0); + const [errorMessage, setErrorMessage] = useState(null); + const [retryAfter, setRetryAfter] = useState(0); + useEffect(() => { + if (!inspectStatus) return; + const controller = new AbortController(); + const version = actionVersion.current; + void fetch(`${apiBase}/auth/verify/status`, { credentials: 'include', signal: controller.signal }) + .then(async (response) => { + if (controller.signal.aborted || version !== actionVersion.current) return; + if (response.status === 401) { + setState('loginRequired'); + return; + } + const delivery = readVerificationDelivery(await response.json().catch(() => null)); + if (!controller.signal.aborted && version === actionVersion.current && delivery) + setState( + delivery === 'sent' ? 'sent' : delivery === 'login_required' ? 'loginRequired' : 'failed', + ); + }).catch(() => { if (!controller.signal.aborted && version === actionVersion.current) setState('failed'); }); + return () => controller.abort(); + }, [apiBase, inspectStatus]); + useEffect(() => { + if (state !== 'cooldown') return; + const timer = setTimeout(() => setState('idle'), retryAfter * 1000); + return () => clearTimeout(timer); + }, [state, retryAfter]); + async function resend() { + if (state === 'sending' || state === 'cooldown') return; + actionVersion.current++; + setErrorMessage(null); + setState('sending'); + try { setState(readMailSent(await post('/auth/verify/request', {})) ? 'sent' : 'failed'); } + catch (error: unknown) { + if (error instanceof AccountActionError && error.code === 'EMAIL_VERIFICATION_BINDING_REQUIRED') + setErrorMessage(error.message); + if (error instanceof AccountActionError && error.status === 429) { + setRetryAfter(error.retryAfter ?? 120); + setState('cooldown'); + } else setState(error instanceof AccountActionError && error.status === 401 ? 'loginRequired' : 'failed'); + } + } + return { state, retryAfter, resend, errorMessage }; +} diff --git a/apps/web/src/ui/pub/auth/AuthPage.tsx b/apps/web/src/ui/pub/auth/AuthPage.tsx index e006f0c3..d7f72923 100644 --- a/apps/web/src/ui/pub/auth/AuthPage.tsx +++ b/apps/web/src/ui/pub/auth/AuthPage.tsx @@ -63,6 +63,9 @@ export function AuthPage({ onForgot: handlers.handleForgot, onReset: handlers.handleReset, onInvite: handleInvite, + onRegisterWithInvite: (code) => { + void handleInvite(code); + }, onCreateTenant: handleCreateTenant, setRegStep: s.setRegStep, setRegData: s.setRegData, diff --git a/apps/web/src/ui/pub/auth/AuthPageRenderer.tsx b/apps/web/src/ui/pub/auth/AuthPageRenderer.tsx index f9dc132e..554bc43c 100644 --- a/apps/web/src/ui/pub/auth/AuthPageRenderer.tsx +++ b/apps/web/src/ui/pub/auth/AuthPageRenderer.tsx @@ -1,8 +1,10 @@ +import { VerificationPendingView } from './VerificationPendingView'; import { LoginView } from './LoginView'; import { RegisterView } from './RegisterView'; import { RegisterStep2View } from './RegisterStep2View'; import { RegisterStep3View } from './RegisterStep3View'; import { RegisterStep4View } from './RegisterStep4View'; +import { InviteAcceptView } from './InviteAcceptView'; import { InviteCodeView } from './InviteCodeView'; import { ForgotPasswordView } from './ForgotPasswordView'; import { ResetPasswordView } from './ResetPasswordView'; @@ -43,6 +45,7 @@ export interface AuthRenderArgs { onForgot: (email: string) => Promise; onReset: (email: string, token: string, password: string) => Promise; onInvite: (code: string) => Promise; + onRegisterWithInvite: (code: string) => void; onCreateTenant: (submission: TenantSignupSubmission) => Promise; setRegStep: (step: number) => void; setRegData: (updater: (prev: RegistrationData) => RegistrationData) => void; @@ -158,7 +161,10 @@ function renderRegisterFlow(args: AuthRenderArgs) { } function renderInvite(args: AuthRenderArgs) { - const { onInvite, switchView, initialInvite, error, registrationEnabled } = args; + const { apiBase, onInvite, onRegisterWithInvite, switchView, initialInvite, error, registrationEnabled } = args; + if (initialInvite) { + return ; + } return ( ; case 'login': return renderLogin(args); case 'register': diff --git a/apps/web/src/ui/pub/auth/InviteAcceptView.test.tsx b/apps/web/src/ui/pub/auth/InviteAcceptView.test.tsx new file mode 100644 index 00000000..32a8fe99 --- /dev/null +++ b/apps/web/src/ui/pub/auth/InviteAcceptView.test.tsx @@ -0,0 +1,172 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { InviteAcceptView } from './InviteAcceptView'; +import { PENDING_INVITE_KEY } from '../../../lib/pendingInvite'; + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (k: string, vars?: Record) => (vars ? `${k} ${Object.values(vars).join(' ')}` : k), + }), +})); + +// Mock the i18next instance behind translateApiError: missing keys echo back, +// so translateApiError falls back to the server message. +vi.mock('../../../app/providers/i18n', () => ({ + default: { t: (key: string) => key }, +})); + +const storeDesktopAuthTokenMock = vi.fn(() => Promise.resolve()); +vi.mock('./hooks/useAuthApi', () => ({ + useAuthApi: () => ({ + post: vi.fn(), + storeDesktopAuthToken: storeDesktopAuthTokenMock, + }), +})); + +const CODE = 'MEET-AAA-111111'; + +function pendingPreview() { + return { tenantName: 'Acme Corp', role: 'member', status: 'pending', emailMasked: 'j***@acme.test' }; +} + +function jsonResponse(status: number, body: unknown) { + return { ok: status >= 200 && status < 300, status, json: () => Promise.resolve(body) }; +} + +let previewStatus = 200; +let previewBody: unknown = null; +let meStatus = 401; +let acceptStatus = 200; +let acceptBody: unknown = {}; +let fetchMock: ReturnType; + +function stubFetch() { + fetchMock = vi.fn((url: string) => { + const u = String(url); + if (u.endsWith('/public/invites/preview')) return Promise.resolve(jsonResponse(previewStatus, previewBody)); + if (u.endsWith('/auth/me')) + return Promise.resolve(jsonResponse(meStatus, meStatus === 200 ? { id: 'u1' } : { error: 'unauthorized' })); + if (u.endsWith('/invites/accept')) return Promise.resolve(jsonResponse(acceptStatus, acceptBody)); + throw new Error(`unexpected fetch: ${u}`); + }); + vi.stubGlobal('fetch', fetchMock); + return fetchMock; +} + +function acceptCalls() { + return fetchMock.mock.calls.filter(([url]) => String(url).endsWith('/invites/accept')); +} + +const reloadMock = vi.fn(); +const originalLocation = window.location; + +function renderView() { + return render( {}} />); +} + +describe('InviteAcceptView', () => { + beforeEach(() => { + vi.clearAllMocks(); + sessionStorage.clear(); + previewStatus = 200; + previewBody = null; + meStatus = 401; + acceptStatus = 200; + acceptBody = {}; + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { hash: '', reload: reloadMock }, + }); + }); + + afterEach(() => { + Object.defineProperty(window, 'location', { configurable: true, writable: true, value: originalLocation }); + sessionStorage.clear(); + vi.unstubAllGlobals(); + }); + + it('shows not_found when the preview answers 404', async () => { + previewStatus = 404; + previewBody = { error: 'not_found' }; + stubFetch(); + + renderView(); + + expect(await screen.findByText('auth.inviteAccept.notFound')).toBeTruthy(); + const [[previewUrl, previewInit]] = fetchMock.mock.calls.filter(([url]) => + String(url).endsWith('/public/invites/preview'), + ); + expect(String(previewUrl)).toContain('/public/invites/preview'); + expect(previewInit).toMatchObject({ method: 'POST', credentials: 'include' }); + }); + + it('shows the expiry text when the invite status is expired', async () => { + previewBody = { tenantName: 'Acme Corp', role: 'member', status: 'expired', emailMasked: 'j***@acme.test' }; + stubFetch(); + + renderView(); + + expect(await screen.findByText('invite_expired')).toBeTruthy(); + }); + + it('shows tenant and masked address when logged out; sign-in stores the code and goes to #/login', async () => { + previewBody = pendingPreview(); + stubFetch(); + + renderView(); + + expect(await screen.findByText(/Acme Corp/)).toBeTruthy(); + expect(screen.getByText(/j\*\*\*@acme\.test/)).toBeTruthy(); + + fireEvent.click(screen.getByText('auth.inviteLoginLink')); + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBe(CODE); + expect(window.location.hash).toBe('#/login'); + }); + + it('accepts on click when logged in: posts {code}, then goes to #/app and reloads', async () => { + previewBody = pendingPreview(); + meStatus = 200; + acceptBody = { id: 'u1', email: 'j@acme.test', name: 'J', alreadyMember: false }; + stubFetch(); + + renderView(); + + fireEvent.click(await screen.findByText('auth.inviteAccept.acceptButton')); + + await waitFor(() => expect(acceptCalls()).toHaveLength(1)); + expect(acceptCalls()[0]?.[1]).toMatchObject({ method: 'POST', credentials: 'include' }); + expect((acceptCalls()[0]?.[1] as RequestInit).body).toBe(JSON.stringify({ code: CODE })); + await waitFor(() => expect(window.location.hash).toBe('#/app')); + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + it('auto-accepts exactly once when logged in with the same code stored', async () => { + sessionStorage.setItem(PENDING_INVITE_KEY, CODE); + previewBody = pendingPreview(); + meStatus = 200; + acceptBody = { id: 'u1', email: 'j@acme.test', name: 'J', alreadyMember: false }; + stubFetch(); + + renderView(); + + await waitFor(() => expect(acceptCalls()).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 200)); + expect(acceptCalls()).toHaveLength(1); + }); + + it('shows the mismatch text and clears storage when accept answers 403 invite_email_mismatch', async () => { + sessionStorage.setItem(PENDING_INVITE_KEY, CODE); + previewBody = pendingPreview(); + meStatus = 200; + acceptStatus = 403; + acceptBody = { error: { code: 'invite_email_mismatch', message: 'apiError.invite_email_mismatch' } }; + stubFetch(); + + renderView(); + + expect(await screen.findByText('apiError.invite_email_mismatch')).toBeTruthy(); + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBeNull(); + }); +}); diff --git a/apps/web/src/ui/pub/auth/InviteAcceptView.tsx b/apps/web/src/ui/pub/auth/InviteAcceptView.tsx new file mode 100644 index 00000000..2f3a42a2 --- /dev/null +++ b/apps/web/src/ui/pub/auth/InviteAcceptView.tsx @@ -0,0 +1,93 @@ +import { useTranslation } from 'react-i18next'; +import { PubBadge, PubButton } from '../components'; +import { AuthMailIcon, AuthMessage } from './AuthFormPartials'; +import { translateApiError } from '../../../lib/apiErrors'; +import { useInviteAccept } from './hooks/useInviteAccept'; + +interface InviteAcceptViewProps { + apiBase: string; + code: string; + onRegisterWithInvite: (code: string) => void; +} + +export function InviteAcceptView({ apiBase, code, onRegisterWithInvite }: InviteAcceptViewProps) { + const { t } = useTranslation('public'); + const { t: tCommon } = useTranslation('common'); + const invite = useInviteAccept({ apiBase, code, onRegisterWithInvite }); + + if (invite.state === 'loading') { + return ( +

+ {t('auth.inviteAccept.loading')} +

+ ); + } + if (invite.state === 'not_found') { + return ; + } + if (invite.state === 'error' || invite.preview === null) { + return ; + } + + const preview = invite.preview; + if (preview.status === 'expired') { + return ; + } + if (preview.status === 'accepted') { + return ( +

+ {t('auth.inviteAccept.alreadyUsed')} +

+ ); + } + + if (!invite.loggedIn) { + return ( +
+ }> + {t('auth.inviteBadge')} + +

+ {t('auth.inviteAccept.inviteTitle', { tenant: preview.tenantName })} +

+

+ {t('auth.inviteAccept.inviteForEmail', { email: preview.emailMasked })} +

+
+ + {t('auth.inviteLoginLink')} + + + {t('auth.inviteRegisterLink')} + +
+
+ ); + } + + const roleLabel = preview.role === 'admin' ? tCommon('tenant.roleAdmin') : tCommon('tenant.roleMember'); + return ( +
+ }> + {t('auth.inviteBadge')} + +

+ {t('auth.inviteAccept.acceptTitle', { tenant: preview.tenantName })} +

+

+ {roleLabel} +

+ { + void invite.accept(); + }} + style={{ width: '100%' }} + > + {t('auth.inviteAccept.acceptButton')} + + {invite.acceptError && } +
+ ); +} diff --git a/apps/web/src/ui/pub/auth/InviteCodeView.tsx b/apps/web/src/ui/pub/auth/InviteCodeView.tsx index 2ef2ff0c..5fc9a76e 100644 --- a/apps/web/src/ui/pub/auth/InviteCodeView.tsx +++ b/apps/web/src/ui/pub/auth/InviteCodeView.tsx @@ -190,9 +190,20 @@ export function InviteCodeView({ const { t } = useTranslation('public'); const [code, setCode] = useState(initialCode); const [loading, setLoading] = useState(false); + const [localError, setLocalError] = useState(null); + const visibleError = localError ?? error; + + function updateCode(v: string) { + setLocalError(null); + setCode(v); + } async function handleSubmit(e: React.FormEvent) { e.preventDefault(); + if (code.trim() === '') { + setLocalError(t('auth.requiredFieldsMissing')); + return; + } setLoading(true); try { await onSubmit(code); @@ -206,6 +217,7 @@ export function InviteCodeView({ onSubmit={(e) => { void handleSubmit(e); }} + noValidate autoComplete="off" style={{ display: 'flex', flexDirection: 'column', gap: 24 }} > @@ -219,11 +231,11 @@ export function InviteCodeView({ placeholder={t('auth.inviteCodePlaceholder')} hint={t('auth.inviteCodeHint')} value={code} - onChange={(e) => setCode(e.target.value)} + onChange={(e) => updateCode(e.target.value)} style={{ letterSpacing: '1px' }} required /> - {error && } + {visibleError && } ({ + useTranslation: () => ({ t: (k: string) => k, i18n: { language: 'en' } }), +})); + +function submitForm() { + fireEvent.submit(screen.getByRole('button', { name: 'auth.loginSubmit' }).closest('form') as HTMLFormElement); +} + +function renderView() { + const onSubmit = vi.fn(() => Promise.resolve()); + render(); + return onSubmit; +} + +describe('LoginView required fields', () => { + it('shows a localized message and does not submit when required fields are empty', () => { + const onSubmit = renderView(); + + submitForm(); + + expect(onSubmit).not.toHaveBeenCalled(); + expect(screen.getByText('auth.requiredFieldsMissing')).toBeInTheDocument(); + }); + + it('treats whitespace-only fields as empty', () => { + const onSubmit = renderView(); + + fireEvent.change(screen.getByLabelText('auth.emailLabel'), { target: { value: ' ' } }); + fireEvent.change(screen.getByPlaceholderText('••••••••'), { target: { value: ' ' } }); + submitForm(); + + expect(onSubmit).not.toHaveBeenCalled(); + expect(screen.getByText('auth.requiredFieldsMissing')).toBeInTheDocument(); + }); + + it('clears the message on next input and submits when the fields are filled', async () => { + const onSubmit = renderView(); + + submitForm(); + expect(screen.getByText('auth.requiredFieldsMissing')).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('auth.emailLabel'), { target: { value: 'a@example.test' } }); + fireEvent.change(screen.getByPlaceholderText('••••••••'), { target: { value: 'secret' } }); + expect(screen.queryByText('auth.requiredFieldsMissing')).toBeNull(); + + submitForm(); + await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('a@example.test', 'secret')); + }); +}); diff --git a/apps/web/src/ui/pub/auth/LoginView.tsx b/apps/web/src/ui/pub/auth/LoginView.tsx index 37d60467..55db45b7 100644 --- a/apps/web/src/ui/pub/auth/LoginView.tsx +++ b/apps/web/src/ui/pub/auth/LoginView.tsx @@ -215,9 +215,25 @@ export function LoginView({ const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); + const [localError, setLocalError] = useState(null); + const visibleError = localError ?? error; + + function updateEmail(v: string) { + setLocalError(null); + setEmail(v); + } + + function updatePassword(v: string) { + setLocalError(null); + setPassword(v); + } async function handleSubmit(e: React.FormEvent) { e.preventDefault(); + if (email.trim() === '' || password.trim() === '') { + setLocalError(t('auth.requiredFieldsMissing')); + return; + } setLoading(true); try { await onSubmit(email, password); @@ -231,13 +247,20 @@ export function LoginView({ onSubmit={(e) => { void handleSubmit(e); }} + noValidate autoComplete="on" style={{ display: 'flex', flexDirection: 'column', gap: 24 }} > - + {successMessage && } - {error && } + {visibleError && } { expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ name: '' })); }); }); + +describe('RegisterView required fields', () => { + function submitForm() { + fireEvent.submit(screen.getByRole('button', { name: 'auth.registerSubmit' }).closest('form') as HTMLFormElement); + } + + it('shows a localized message and does not submit when email and password are empty', () => { + const onSubmit = renderView(); + + fireEvent.change(firstNameField(), { target: { value: 'Jörg' } }); + submitForm(); + + expect(onSubmit).not.toHaveBeenCalled(); + expect(screen.getByText('auth.requiredFieldsMissing')).toBeInTheDocument(); + }); + + it('clears the message on next input and submits when email and password are filled', async () => { + const onSubmit = renderView(); + + submitForm(); + expect(screen.getByText('auth.requiredFieldsMissing')).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('auth.registerEmail'), { target: { value: 'a@example.test' } }); + fireEvent.change(screen.getByLabelText('auth.registerPassword'), { target: { value: 'supersecret' } }); + expect(screen.queryByText('auth.requiredFieldsMissing')).toBeNull(); + + await submit(onSubmit); + }); +}); diff --git a/apps/web/src/ui/pub/auth/RegisterView.tsx b/apps/web/src/ui/pub/auth/RegisterView.tsx index dfbcdf45..6d3c111c 100644 --- a/apps/web/src/ui/pub/auth/RegisterView.tsx +++ b/apps/web/src/ui/pub/auth/RegisterView.tsx @@ -195,9 +195,22 @@ export function RegisterView({ onSubmit, onLogin, initialInvite, error }: Regist const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); + const [localError, setLocalError] = useState(null); + const visibleError = localError ?? error; + + function track(set: (v: string) => void) { + return (v: string) => { + setLocalError(null); + set(v); + }; + } async function handleSubmit(e: React.FormEvent) { e.preventDefault(); + if (email.trim() === '' || password.trim() === '') { + setLocalError(t('auth.requiredFieldsMissing')); + return; + } setLoading(true); try { const name = composeRegisterName(firstName, lastName); @@ -212,6 +225,7 @@ export function RegisterView({ onSubmit, onLogin, initialInvite, error }: Regist onSubmit={(e) => { void handleSubmit(e); }} + noValidate autoComplete="on" style={{ display: 'flex', flexDirection: 'column', gap: 24 }} > @@ -222,12 +236,12 @@ export function RegisterView({ onSubmit, onLogin, initialInvite, error }: Regist lastName={lastName} email={email} password={password} - onFirstName={setFirstName} - onLastName={setLastName} - onEmail={setEmail} - onPassword={setPassword} + onFirstName={track(setFirstName)} + onLastName={track(setLastName)} + onEmail={track(setEmail)} + onPassword={track(setPassword)} /> - {error && } + {visibleError && } +

{t('auth.emailProof.title')}

+

{t('auth.emailProof.description')}

+

+ {request.errorMessage ?? t(`auth.emailProof.${request.state}`, { seconds: request.retryAfter })} +

+ { void request.resend(); }} + > + {t('auth.emailProof.resend')} + + { + void fetch(`${apiBase}/auth/me`, { credentials: 'include' }).then(async (response) => { + if (response.ok) { + clearPendingInvite(); + window.location.hash = '#/app'; + } else if (readAccountError(await response.json().catch(() => null)).code === 'ACCOUNT_LOGIN_REQUIRED') + window.location.hash = '#/login'; + }).catch(() => {}); + }} + > + {t('auth.emailProof.check')} + + { + void fetch(`${apiBase}/auth/logout`, { method: 'POST', credentials: 'include' }).finally(() => { + window.location.hash = '#/login'; + }).catch(() => {}); + }} + > + {t('auth.emailProof.login')} + +
; +} diff --git a/apps/web/src/ui/pub/auth/hooks/useAuthApi.ts b/apps/web/src/ui/pub/auth/hooks/useAuthApi.ts index 94ee30ce..eab92882 100644 --- a/apps/web/src/ui/pub/auth/hooks/useAuthApi.ts +++ b/apps/web/src/ui/pub/auth/hooks/useAuthApi.ts @@ -2,6 +2,7 @@ import { useCallback } from 'react'; import { storeDesktopAuthToken } from '../../../../lib/desktopAuth'; import { logger } from '../../../../lib/logger'; import { translateApiError } from '../../../../lib/apiErrors'; +import { AccountActionError, readAccountError } from '../../../../lib/accountActionResponses'; import { useTranslation } from 'react-i18next'; export function useAuthApi(baseUrl: string) { @@ -43,12 +44,19 @@ export function useAuthApi(baseUrl: string) { body: JSON.stringify(body), }); if (!res.ok) { - const errBody = (await res.json().catch(() => ({}))) as { error?: string }; - throw new Error(translateApiError(errBody.error) || t('common.error')); + const error = readAccountError(await res.json().catch(() => null)); + const retryAfter = Number(res.headers.get('Retry-After')); + throw new AccountActionError( + res.status, + error.code, + translateApiError(error.message) || t('common.error'), + error.retryAfter ?? (retryAfter > 0 ? retryAfter : null), + ); } return (await res.json().catch(() => ({}))) as unknown; } catch (e: unknown) { - logger.warn('[Auth] Fetch error:', (e as Error)?.message || String(e), 'URL:', url); + if (e instanceof AccountActionError && (e.status < 500 || e.code?.startsWith('EMAIL_'))) throw e; + logger.warn('[Auth] Anfrage fehlgeschlagen'); lastErr = e; // Network / connection error: short retry with backoff if (i < attempts.length - 1) { diff --git a/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.test.tsx b/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.test.tsx index c8a72ae6..3ffba375 100644 --- a/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.test.tsx +++ b/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.test.tsx @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { renderHook } from '@testing-library/react'; import { useAuthHandlers } from './useAuthHandlers'; +import { PENDING_INVITE_KEY, inviteHash } from '../../../../lib/pendingInvite'; vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (k: string) => k }), @@ -202,3 +203,63 @@ describe('useAuthHandlers — handleRegister (invite join)', () => { expect(trackSignupMock).not.toHaveBeenCalled(); }); }); + +describe('useAuthHandlers — pending invite after login', () => { + beforeEach(() => { + vi.clearAllMocks(); + getTelemetryModuleMock.mockResolvedValue(null); + sessionStorage.clear(); + window.location.hash = ''; + }); + + afterEach(() => { + sessionStorage.clear(); + window.location.hash = ''; + }); + + it('navigates to the stored invite hash after login when a pending invite exists', async () => { + window.location.hash = '#/login'; + sessionStorage.setItem(PENDING_INVITE_KEY, 'MEET-INV-123456'); + postMock.mockResolvedValueOnce({ token: null }); + + const { result } = renderHook(() => useAuthHandlers(makeArgs())); + await result.current.handleLogin('jane@acme.test', 'secret'); + + expect(window.location.hash).toBe(inviteHash('MEET-INV-123456')); + }); + + it('keeps an allowed next hash even when a pending invite is stored', async () => { + window.location.hash = '#/login?next=' + encodeURIComponent('#/connect?request=abc_-1'); + sessionStorage.setItem(PENDING_INVITE_KEY, 'MEET-INV-123456'); + postMock.mockResolvedValueOnce({ token: null }); + + const { result } = renderHook(() => useAuthHandlers(makeArgs())); + await result.current.handleLogin('jane@acme.test', 'secret'); + + expect(window.location.hash).toBe('#/connect?request=abc_-1'); + }); +}); + +describe('useAuthHandlers — handleRegister clears the pending invite', () => { + beforeEach(() => { + vi.clearAllMocks(); + getTelemetryModuleMock.mockResolvedValue(null); + sessionStorage.clear(); + window.location.hash = ''; + }); + + afterEach(() => { + sessionStorage.clear(); + window.location.hash = ''; + }); + + it('deletes the stored code after a successful registration', async () => { + sessionStorage.setItem(PENDING_INVITE_KEY, 'MEET-INV-123456'); + postMock.mockResolvedValueOnce({ token: null }); + + const { result } = renderHook(() => useAuthHandlers(makeArgs())); + await result.current.handleRegister({ name: 'Jane', email: 'jane@acme.test', password: 'x', invite: 'INV' }, ''); + + expect(sessionStorage.getItem(PENDING_INVITE_KEY)).toBeNull(); + }); +}); diff --git a/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.ts b/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.ts index 6b31160c..939b618f 100644 --- a/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.ts +++ b/apps/web/src/ui/pub/auth/hooks/useAuthHandlers.ts @@ -1,7 +1,9 @@ +import { AccountActionError, needsEmailVerification } from '../../../../lib/accountActionResponses'; import { useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import { useAuthApi } from './useAuthApi'; import { getTelemetryModule } from '../../../../lib/telemetryLoader'; +import { storePendingInvite, clearPendingInvite, inviteHash, readPendingInvite } from '../../../../lib/pendingInvite'; import { readLoginNextParam, resolvePostLoginHash } from '../../../../lib/resolvePostLoginHash'; interface AuthTokenResponse { @@ -16,7 +18,7 @@ interface UseAuthHandlersArgs { setView: (view: AuthViewName) => void; } -export type AuthViewName = 'login' | 'register' | 'invite' | 'forgot' | 'reset' | 'guest'; +export type AuthViewName = 'login' | 'register' | 'invite' | 'forgot' | 'reset' | 'guest' | 'pending'; export interface AuthHandlers { handleLogin: (email: string, password: string) => Promise; @@ -31,6 +33,44 @@ export interface AuthHandlers { postRaw: ReturnType['post']; } +function showVerificationPending(setView: (view: AuthViewName) => void): void { + setView('pending'); + window.location.hash = '#/verify-pending'; +} + +async function resolvePostLoginTarget(post: ReturnType['post']): Promise { + const next = readLoginNextParam(window.location.hash); + const target = resolvePostLoginHash(next); + let pending = readPendingInvite(); + if (pending) { + const preview = await post('/public/invites/preview', { code: pending }); + if (preview && typeof preview === 'object' && 'status' in preview && preview.status === 'accepted') { + clearPendingInvite(); + pending = null; + } + } + return target === '#/app' && pending ? inviteHash(pending) : target; +} + +function handleLoginFailure( + e: unknown, + setView: (view: AuthViewName) => void, + setError: (msg: string | null) => void, +): void { + if (e instanceof AccountActionError && e.code === 'INVITE_ACCEPT_REQUIRED') { + const pending = readPendingInvite(); + if (pending) { + window.location.hash = inviteHash(pending); + return; + } + } + if (needsEmailVerification(e)) { + showVerificationPending(setView); + return; + } + setError((e as Error).message); +} + export function useAuthHandlers({ apiBase, setError, @@ -53,12 +93,12 @@ export function useAuthHandlers({ void getTelemetryModule() .then((t) => t?.trackLogin()) .catch(() => {}); - window.location.hash = resolvePostLoginHash(readLoginNextParam(window.location.hash)); + window.location.hash = await resolvePostLoginTarget(post); } catch (e: unknown) { - setError((e as Error).message); + handleLoginFailure(e, setView, setError); } }, - [post, storeDesktopAuthToken, setError], + [post, storeDesktopAuthToken, setError, setView], ); const handleRegister = useCallback( @@ -67,6 +107,7 @@ export function useAuthHandlers({ currentInvite: string, ) => { setError(null); + storePendingInvite(data.invite || currentInvite); try { const result = (await post('/auth/register', { code: data.invite || currentInvite, @@ -85,12 +126,17 @@ export function useAuthHandlers({ void getTelemetryModule() .then((t) => t?.trackSignup('invite')) .catch(() => {}); + clearPendingInvite(); window.location.hash = '#/app'; } catch (e: unknown) { + if (needsEmailVerification(e)) { + showVerificationPending(setView); + return; + } setError((e as Error).message); } }, - [post, storeDesktopAuthToken, setError], + [post, storeDesktopAuthToken, setError, setView], ); const handleForgot = useCallback( diff --git a/apps/web/src/ui/pub/auth/hooks/useAuthPage.ts b/apps/web/src/ui/pub/auth/hooks/useAuthPage.ts index ed571b22..ee8e4c33 100644 --- a/apps/web/src/ui/pub/auth/hooks/useAuthPage.ts +++ b/apps/web/src/ui/pub/auth/hooks/useAuthPage.ts @@ -1,4 +1,5 @@ import { useCallback } from 'react'; +import { inviteHash } from '../../../../lib/pendingInvite'; import { useAuthHandlers, type AuthViewName } from './useAuthHandlers'; import { useDebugAutoLogin, useGuestAutoLogin, useRedirectWhenRegistrationDisabled } from './useAuthSideEffects'; import { useAuthPageState } from './useAuthPageState'; @@ -64,6 +65,7 @@ export function useAuthPage(args: UseAuthPageArgs) { s.setError(null); s.setInvite(code); s.setView('register'); + window.location.hash = inviteHash(code); return Promise.resolve(); }, [s], diff --git a/apps/web/src/ui/pub/auth/hooks/useInviteAccept.ts b/apps/web/src/ui/pub/auth/hooks/useInviteAccept.ts new file mode 100644 index 00000000..4618bb02 --- /dev/null +++ b/apps/web/src/ui/pub/auth/hooks/useInviteAccept.ts @@ -0,0 +1,125 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { readAccountError } from '../../../../lib/accountActionResponses'; +import { useAuthApi } from './useAuthApi'; +import { translateApiError } from '../../../../lib/apiErrors'; +import { clearPendingInvite, readPendingInvite, storePendingInvite } from '../../../../lib/pendingInvite'; +export interface InvitePreview { + tenantName: string; + role: string; + status: 'pending' | 'accepted' | 'expired'; + emailMasked: string; +} +interface UseInviteAcceptArgs { + apiBase: string; + code: string; + onRegisterWithInvite?: ((code: string) => void) | undefined; +} +async function readErrorCode(res: Response): Promise { + try { + return ((await res.json()) as { error?: unknown }).error ?? null; + } catch { + return null; + } +} +export function useInviteAccept({ apiBase, code, onRegisterWithInvite }: UseInviteAcceptArgs) { + const { t } = useTranslation(); + const { storeDesktopAuthToken } = useAuthApi(apiBase); + const [state, setState] = useState<'loading' | 'not_found' | 'error' | 'ready'>('loading'); + const [error, setError] = useState(null); + const [preview, setPreview] = useState(null); + const [loggedIn, setLoggedIn] = useState(false); + const [accepting, setAccepting] = useState(false); + const [acceptError, setAcceptError] = useState(null); + const autoAccepted = useRef(false); + useEffect(() => { + let cancelled = false; + autoAccepted.current = false; + async function load(): Promise { + const [previewRes, meRes] = await Promise.all([ + fetch(`${apiBase}/public/invites/preview`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ code }), + }).catch(() => null), + fetch(`${apiBase}/auth/me`, { credentials: 'include' }).catch(() => null), + ]); + if (cancelled) return; + setLoggedIn(meRes !== null && meRes.status !== 401); + if (previewRes === null) { + setError(t('common.error')); + setState('error'); + return; + } + if (previewRes.status === 404) { + setState('not_found'); + return; + } + if (!previewRes.ok) { + const err = await readErrorCode(previewRes); + setError(translateApiError(err) || t('common.error')); + setState('error'); + return; + } + setPreview((await previewRes.json().catch(() => null)) as InvitePreview | null); + setState('ready'); + } + void load(); + return () => { + cancelled = true; + }; + }, [apiBase, code, t]); + const accept = useCallback(async (): Promise => { + setAccepting(true); + setAcceptError(null); + try { + const res = await fetch(`${apiBase}/invites/accept`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ code }), + }).catch(() => null); + if (res === null || !res.ok) { + const status = res === null ? 0 : res.status; + const error = readAccountError(res === null ? null : await res.json().catch(() => null)); + if (error.code === 'ACCOUNT_LOGIN_REQUIRED') { + window.location.hash = '#/login'; + return; + } + if (error.code === 'EMAIL_VERIFICATION_REQUIRED' || error.code === 'EMAIL_VERIFICATION_BINDING_REQUIRED') { + storePendingInvite(code); + window.location.hash = '#/verify-pending'; + return; + } + setAcceptError(translateApiError(error.message) || t('common.error')); + if (status === 400 || status === 403 || status === 404 || error.code === 'invite_unavailable') + clearPendingInvite(); + return; + } + const body = (await res.json().catch(() => ({}))) as { token?: string | null }; + clearPendingInvite(); + if (body.token) await storeDesktopAuthToken(body.token); + window.location.hash = '#/app'; + window.location.reload(); + } finally { + setAccepting(false); + } + }, [apiBase, code, storeDesktopAuthToken, t]); + useEffect(() => { + if (autoAccepted.current || state !== 'ready' || !loggedIn) return; + if (preview?.status !== 'pending' || readPendingInvite() !== code) return; + autoAccepted.current = true; + void accept(); + }, [state, loggedIn, preview, code, accept]); + const goLogin = useCallback((): void => { + storePendingInvite(code); + window.location.hash = '#/login'; + }, [code]); + const goRegister = useCallback((): void => { + storePendingInvite(code); + if (onRegisterWithInvite) onRegisterWithInvite(code); + else window.location.hash = '#/register'; + }, [code, onRegisterWithInvite]); + return { state, error, preview, loggedIn, accepting, acceptError, accept, goLogin, goRegister }; +} diff --git a/apps/web/src/ui/pub/billing/EmailVerifyPage.tsx b/apps/web/src/ui/pub/billing/EmailVerifyPage.tsx index 4598fe23..d57dea1e 100644 --- a/apps/web/src/ui/pub/billing/EmailVerifyPage.tsx +++ b/apps/web/src/ui/pub/billing/EmailVerifyPage.tsx @@ -1,4 +1,6 @@ import React from 'react'; +import { readAccountError, readProofResult } from '../../../lib/accountActionResponses'; +import { clearPendingInvite } from '../../../lib/pendingInvite'; import { useTranslation } from 'react-i18next'; import { PublicLayout } from '../layout/PublicLayout'; import { PubCard } from '../components/PubCard'; @@ -64,52 +66,57 @@ function Spinner() { type VerifyStatus = 'verifying' | 'success' | 'error'; -interface UseEmailVerifyArgs { - token: string | undefined; - apiBase: string; - onSuccess: () => void; -} - -function useEmailVerify({ token, apiBase, onSuccess }: UseEmailVerifyArgs) { +function useEmailVerify(token: string | undefined, apiBase: string) { const { t } = useTranslation('public'); const [status, setStatus] = React.useState('verifying'); const [message, setMessage] = React.useState(''); - + const [purpose, setPurpose] = React.useState<'invite' | 'verify' | 'email_change'>('verify'); + const inFlight = React.useRef<{ token: string; promise: Promise<{ ok: boolean; body: unknown }> } | null>(null); React.useEffect(() => { + let cancelled = false; if (!token) { setStatus('error'); setMessage(t('verify.noToken')); return; } - - const verify = async () => { - try { - const res = await fetch(`${apiBase}/auth/verify`, { + // Run once per mount, including React effect replays. Do not retry a single-use proof. + if (inFlight.current?.token !== token) + inFlight.current = { + token, + promise: fetch(`${apiBase}/auth/verify`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, credentials: 'include', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), - }); - - if (res.ok) { - setStatus('success'); - setMessage(t('verify.successText')); - setTimeout(onSuccess, 2000); - } else { - const data = (await res.json().catch(() => ({}))) as { error?: string }; - setStatus('error'); - setMessage(data.error || t('verify.errorTitle')); - } - } catch (e: unknown) { + }) + .then(async (response) => ({ ok: response.ok, body: await response.json().catch(() => null) as unknown })) + .finally(() => { if (inFlight.current?.token === token) window.history.replaceState(null, '', '#/verify'); }), + }; + const active = inFlight.current; + if (!active) return; + void active.promise.then(({ ok, body }) => { + if (cancelled) return; + const result = readProofResult(body); + if (ok && result) { + setPurpose(result.purpose); + setStatus('success'); + if (result.purpose === 'invite') clearPendingInvite(); + } else { setStatus('error'); - setMessage((e as Error)?.message || t('verify.errorTitle')); + const error = readAccountError(body); + setMessage( + error.code === 'EMAIL_PROOF_INVALID' ? t('verify.invalidLink') : error.message ?? t('verify.errorTitle'), + ); } - }; - - void verify(); - }, [token, apiBase, onSuccess, t]); - - return { status, message }; + }).catch(() => { + if (!cancelled) { + setStatus('error'); + setMessage(t('verify.errorTitle')); + } + }); + return () => { cancelled = true; }; + }, [token, apiBase, t]); + return { status, message, purpose }; } function VerifyingState() { @@ -124,17 +131,24 @@ function VerifyingState() { ); } -function SuccessState() { +function SuccessState({ + purpose, + onContinue, +}: { + purpose: 'invite' | 'verify' | 'email_change'; + onContinue: () => void; +}) { const { t } = useTranslation('public'); return ( <>

- {t('verify.successTitle')} + {t(`verify.${purpose}.title`)}

- {t('verify.successText')} + {t(`verify.${purpose}.text`)}

+ {t('verify.continue')} ); } @@ -177,7 +191,17 @@ const VERIFY_WRAPPER_STYLE: React.CSSProperties = { }; export function EmailVerifyPage({ token, apiBase, onSuccess, onBack }: EmailVerifyPageProps) { - const { status, message } = useEmailVerify({ token, apiBase, onSuccess }); + const { status, message, purpose } = useEmailVerify(token, apiBase); + const continueAfterProof = async () => { + try { + const response = await fetch(`${apiBase}/auth/me`, { credentials: 'include' }); + if (response.ok) { + window.location.hash = '#/app'; + return; + } + } catch { /* Require sign-in unless usable access has been proven. */ } + onSuccess(); + }; const navigate = (route: string) => { window.location.hash = `#/${route}`; @@ -194,7 +218,7 @@ export function EmailVerifyPage({ token, apiBase, onSuccess, onBack }: EmailVeri
{status === 'verifying' && } - {status === 'success' && } + {status === 'success' && { void continueAfterProof(); }} />} {status === 'error' && }
diff --git a/apps/web/src/ui/settings/ProfileEmailChangeSection.tsx b/apps/web/src/ui/settings/ProfileEmailChangeSection.tsx new file mode 100644 index 00000000..c85791b8 --- /dev/null +++ b/apps/web/src/ui/settings/ProfileEmailChangeSection.tsx @@ -0,0 +1,71 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Alert, Badge, Button, Input, Section } from '../system'; +import { readAccountError, readEmailChangePending } from '../../lib/accountActionResponses'; + +export function ProfileEmailChangeSection({ apiBase, activeEmail, verifiedAt, onRefresh }: { + apiBase: string; activeEmail: string; verifiedAt: string | null; onRefresh: () => Promise; +}) { + const { t } = useTranslation(); + const [email, setEmail] = useState(''); + const [pending, setPending] = useState(null); + const [message, setMessage] = useState(null); + const [sending, setSending] = useState(false); + useEffect(() => { + let cancelled = false; + void fetch(`${apiBase}/auth/verify/status`, { credentials: 'include' }) + .then(async (response) => { + if (!response.ok) return; + const target = readEmailChangePending(await response.json().catch(() => null)); + if (!cancelled && target) setPending((previous) => previous ?? target); + }).catch(() => {}); + return () => { cancelled = true; }; + }, [apiBase, activeEmail]); + async function submit(event: React.FormEvent) { + event.preventDefault(); + setSending(true); + setMessage(null); + try { + const response = await fetch(`${apiBase}/me`, { method: 'PATCH', credentials: 'include', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) }); + const body: unknown = await response.json().catch(() => null); + const target = readEmailChangePending(body); + if (response.ok && target) { + setPending(target); + setEmail(''); + } + else + setMessage( + response.status === 429 + ? t('profile.emailChange.cooldown') + : readAccountError(body).message ?? t('profile.emailChange.failed'), + ); + } catch { setMessage(t('profile.emailChange.failed')); } + finally { setSending(false); } + } + return
+

{t('profile.emailChange.active')}: {activeEmail}

+ + {t(verifiedAt ? 'profile.emailChange.verified' : 'profile.notVerified')} + + {pending && pending !== activeEmail && ( + {t('profile.emailChange.pending', { email: pending })} + )} + {pending === activeEmail && {t('profile.emailChange.completed')}} + {message && {message}} +
{ void submit(event); }} style={{ display: 'grid', gap: 12, marginTop: 16 }}> + + setEmail(event.target.value)} + /> + +
+ +
; +} diff --git a/apps/web/src/ui/settings/ProfileSettings.name.test.tsx b/apps/web/src/ui/settings/ProfileSettings.name.test.tsx index 9917a5d1..1b300843 100644 --- a/apps/web/src/ui/settings/ProfileSettings.name.test.tsx +++ b/apps/web/src/ui/settings/ProfileSettings.name.test.tsx @@ -46,11 +46,11 @@ function stubApi(user: StoredUser, reply: PatchReply) { // The real i18n instance, in English: the texts below come from the shipped locale files. const nameField = () => screen.getByPlaceholderText('Your name'); -const emailField = () => screen.getByPlaceholderText('your@email.com'); +const emailField = () => screen.getByLabelText('New email address'); async function renderLoaded(): Promise { render(); - await waitFor(() => expect(emailField().value).not.toBe('')); + await screen.findByLabelText('New email address'); } function save(): void { @@ -76,17 +76,28 @@ describe('ProfileSettings name field', () => { it('lets an account without a name change its e-mail address: no name is sent', async () => { const patches = stubApi( { id: 'u1', email: 'old@example.test', name: null }, - { status: 200, body: { id: 'u1', email: 'new@example.test', name: null } }, + { + status: 202, + body: { + id: 'u1', + email: 'old@example.test', + name: null, + emailChangePending: true, + pendingEmail: 'new@example.test', + sent: true, + }, + }, ); await renderLoaded(); expect(nameField().value).toBe(''); fireEvent.change(emailField(), { target: { value: 'new@example.test' } }); - save(); + fireEvent.click(screen.getByRole('button', { name: 'Request email change' })); await waitFor(() => expect(patches).toHaveLength(1)); expect(patches[0]).toEqual({ email: 'new@example.test' }); - expect(await screen.findByText('Profile updated successfully')).toBeTruthy(); + expect(await screen.findByText(/A confirmation link was sent/)).toBeTruthy(); + expect(screen.getByText('old@example.test')).toBeTruthy(); }); it('sends no name when the field only holds whitespace', async () => { @@ -99,23 +110,23 @@ describe('ProfileSettings name field', () => { fireEvent.change(nameField(), { target: { value: ' ' } }); save(); - await waitFor(() => expect(patches).toHaveLength(1)); - expect(patches[0]).toEqual({ email: 'a@example.test' }); + await screen.findByText('Profile updated successfully'); + expect(patches).toHaveLength(0); }); it('sends the trimmed name and shows the stored one afterwards', async () => { const patches = stubApi( { id: 'u1', email: 'a@example.test', name: null }, - { status: 200, body: { id: 'u1', email: 'a@example.test', name: 'Jörg Müller' } }, + { status: 200, body: { id: 'u1', email: 'a@example.test', name: 'Jorg Muller' } }, ); await renderLoaded(); - fireEvent.change(nameField(), { target: { value: ' Jörg Müller ' } }); + fireEvent.change(nameField(), { target: { value: ' Jorg Muller ' } }); save(); await waitFor(() => expect(patches).toHaveLength(1)); - expect(patches[0]).toEqual({ name: 'Jörg Müller', email: 'a@example.test' }); - await waitFor(() => expect(nameField().value).toBe('Jörg Müller')); + expect(patches[0]).toEqual({ name: 'Jorg Muller' }); + await waitFor(() => expect(nameField().value).toBe('Jorg Muller')); }); it('keeps the stored name when the field was cleared: the field shows it again after the save', async () => { @@ -129,8 +140,8 @@ describe('ProfileSettings name field', () => { fireEvent.change(nameField(), { target: { value: '' } }); save(); - await waitFor(() => expect(patches).toHaveLength(1)); - expect(patches[0]).toEqual({ email: 'a@example.test' }); + await screen.findByText('Profile updated successfully'); + expect(patches).toHaveLength(0); await waitFor(() => expect(nameField().value).toBe('Alice')); }); diff --git a/apps/web/src/ui/settings/ProfileSettings.tsx b/apps/web/src/ui/settings/ProfileSettings.tsx index 841e8b4b..a3c1c421 100644 --- a/apps/web/src/ui/settings/ProfileSettings.tsx +++ b/apps/web/src/ui/settings/ProfileSettings.tsx @@ -2,11 +2,12 @@ import React from 'react'; import { useTranslation } from 'react-i18next'; import { MAX_DISPLAY_NAME_LENGTH } from '@meetropolis/shared'; import { getApiBaseFromWindow } from '../../lib/apiBase'; +import { ProfileEmailChangeSection } from './ProfileEmailChangeSection'; import { ProfileAvatarSection } from './ProfileAvatarSection'; import { profilePatchBody } from './profilePatchBody'; import type { WorldRoom } from '../../types/colyseus'; import { translateApiError } from '../../lib/apiErrors'; -import { Button, Input, Alert, Section, Badge, Card } from '../system'; +import { Button, Input, Alert, Section, Card } from '../system'; interface UserProfile { id: string; @@ -51,13 +52,11 @@ function formatDate(iso: string | null): string { function useProfileLoader(apiBase: string, t: (k: string) => string) { const [profile, setProfile] = React.useState(null); const [name, setName] = React.useState(''); - const [email, setEmail] = React.useState(''); const [avatarId, setAvatarId] = React.useState(localStorage.getItem('avatarId') || 'default-characters:business_man'); const [loading, setLoading] = React.useState(true); const [error, setError] = React.useState(null); - React.useEffect(() => { - const fetchProfile = async () => { + const fetchProfile = React.useCallback(async () => { try { const res = await fetch(`${apiBase}/auth/me`, { credentials: 'include' }); if (res.ok) { @@ -74,7 +73,6 @@ function useProfileLoader(apiBase: string, t: (k: string) => string) { }); } setName(data.user?.name || data.name || ''); - setEmail(data.user?.email || data.email || ''); const serverAvatarId = data.user?.avatarId || data.avatarId; if (serverAvatarId) { setAvatarId(serverAvatarId); @@ -88,11 +86,15 @@ function useProfileLoader(apiBase: string, t: (k: string) => string) { } finally { setLoading(false); } - }; - void fetchProfile(); }, [apiBase, t]); + React.useEffect(() => { + void fetchProfile(); + const refresh = () => { void fetchProfile(); }; + window.addEventListener('focus', refresh); + return () => window.removeEventListener('focus', refresh); + }, [fetchProfile]); - return { profile, setProfile, name, setName, email, setEmail, avatarId, setAvatarId, loading, error, setError }; + return { profile, setProfile, name, setName, avatarId, setAvatarId, loading, error, setError, reload: fetchProfile }; } function PasswordChangeForm({ @@ -325,16 +327,12 @@ function PersonalInfoForm({ profile, name, setName, - email, - setEmail, saving, onSave, }: { profile: UserProfile | null; name: string; setName: (v: string) => void; - email: string; - setEmail: (v: string) => void; saving: boolean; onSave: (e: React.FormEvent) => void; }) { @@ -352,17 +350,6 @@ function PersonalInfoForm({ maxLength={MAX_DISPLAY_NAME_LENGTH} />
-
- - setEmail(e.target.value)} placeholder="your@email.com" /> -
- {profile?.emailVerifiedAt ? ( - {t('profile.verifiedOn', { date: formatDate(profile.emailVerifiedAt) })} - ) : ( - {t('profile.notVerified')} - )} -
-
{t('profile.memberSince')}: {formatDate(profile?.createdAt || null)} @@ -387,7 +374,7 @@ export function ProfileSettings({ }) { const { t } = useTranslation(); const apiBase = getApiBaseFromWindow(); - const { profile, setProfile, name, setName, email, setEmail, avatarId, setAvatarId, loading, error, setError } = + const { profile, setProfile, name, setName, avatarId, setAvatarId, loading, error, setError, reload } = useProfileLoader(apiBase, t); const [saving, setSaving] = React.useState(false); const [success, setSuccess] = React.useState(null); @@ -398,12 +385,18 @@ export function ProfileSettings({ setSaving(true); setError(null); setSuccess(null); + if (!name.trim()) { + await reload(); + setSuccess(t('profile.updateSuccess')); + setSaving(false); + return; + } try { const res = await fetch(`${apiBase}/me`, { method: 'PATCH', credentials: 'include', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(profilePatchBody(name, email)), + body: JSON.stringify(profilePatchBody(name)), }); if (res.ok) { const data = (await res.json()) as MeResponse; @@ -414,7 +407,7 @@ export function ProfileSettings({ email: userPayload.email, name: userPayload.name ?? null, imageUrl: userPayload.imageUrl ?? null, - emailVerifiedAt: userPayload.emailVerifiedAt ?? null, + emailVerifiedAt: userPayload.emailVerifiedAt ?? profile?.emailVerifiedAt ?? null, createdAt: userPayload.createdAt ?? '', }); } @@ -456,14 +449,18 @@ export function ProfileSettings({ profile={profile} name={name} setName={setName} - email={email} - setEmail={setEmail} saving={saving} onSave={(e) => { void handleSaveProfile(e); }} /> + diff --git a/apps/web/src/ui/settings/hooks/useTenantSettings.invite.test.tsx b/apps/web/src/ui/settings/hooks/useTenantSettings.invite.test.tsx new file mode 100644 index 00000000..b09580b0 --- /dev/null +++ b/apps/web/src/ui/settings/hooks/useTenantSettings.invite.test.tsx @@ -0,0 +1,68 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook } from '@testing-library/react'; +import '../../../app/providers/i18n'; +import { useTenantSettings } from './useTenantSettings'; + +vi.mock('../../../lib/apiBase', () => ({ getApiBaseFromWindow: () => 'http://api.test' })); + +function stubInviteApi(emailSent: boolean) { + const bodies: unknown[] = []; + vi.stubGlobal( + 'fetch', + vi.fn((url: string, init?: RequestInit) => { + if (init?.method === 'POST' && url.endsWith('/auth/invite')) { + bodies.push(JSON.parse(init.body as string)); + return Promise.resolve({ + ok: true, + status: 201, + json: () => + Promise.resolve({ + code: 'ABC123', + role: 'member', + inviteUrl: 'https://public.example/#/?invite=ABC123', + expiresAt: '2026-02-01T00:00:00.000Z', + emailSent, + }), + }); + } + return Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({}) }); + }), + ); + return bodies; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('useTenantSettings handleInvite delivery', () => { + it('always sends the email in the body and passes delivery fields through', async () => { + const bodies = stubInviteApi(true); + const { result } = renderHook(() => useTenantSettings()); + + let invite: Awaited> = null; + await act(async () => { + invite = await result.current.handleInvite('member@example.test', 'member'); + }); + + expect(bodies).toEqual([{ email: 'member@example.test', role: 'member' }]); + expect(invite).toEqual({ + email: 'member@example.test', + inviteUrl: 'https://public.example/#/?invite=ABC123', + emailSent: true, + expiresAt: '2026-02-01T00:00:00.000Z', + }); + }); + + it('still sends the email key when the field is empty', async () => { + const bodies = stubInviteApi(false); + const { result } = renderHook(() => useTenantSettings()); + + await act(async () => { + await result.current.handleInvite('', 'member'); + }); + + expect(bodies).toEqual([{ email: '', role: 'member' }]); + }); +}); diff --git a/apps/web/src/ui/settings/hooks/useTenantSettings.ts b/apps/web/src/ui/settings/hooks/useTenantSettings.ts index bd3ed541..3b90d0ba 100644 --- a/apps/web/src/ui/settings/hooks/useTenantSettings.ts +++ b/apps/web/src/ui/settings/hooks/useTenantSettings.ts @@ -21,7 +21,10 @@ interface UseTenantSettingsReturn { fetchData: () => Promise; handleChangeRole: (userId: string, newRole: 'admin' | 'member') => Promise; handleRemoveMember: (userId: string) => Promise; - handleInvite: (email: string, role: 'admin' | 'member') => Promise; + handleInvite: ( + email: string, + role: 'admin' | 'member', + ) => Promise<{ email: string; inviteUrl: string | null; emailSent: boolean; expiresAt: string | null } | null>; handleCreateGuest: (email: string, name: string, expiresAt: string) => Promise<{ magicLink: string } | null>; handleRevokeGuest: (membershipId: string) => Promise; handleResetPassword: (email: string) => Promise; @@ -112,6 +115,9 @@ interface ApiErrorBody { interface InviteResponse { code?: string; + inviteUrl?: string; + emailSent: boolean; + expiresAt: string | null; } interface GuestCreateResponse { @@ -243,7 +249,10 @@ function useMemberHandlers(state: TenantState, apiBase: string, t: (k: string) = ); const handleInvite = React.useCallback( - async (email: string, role: 'admin' | 'member'): Promise => { + async ( + email: string, + role: 'admin' | 'member', + ): Promise<{ email: string; inviteUrl: string | null; emailSent: boolean; expiresAt: string | null } | null> => { setSaving(true); setError(null); try { @@ -251,12 +260,16 @@ function useMemberHandlers(state: TenantState, apiBase: string, t: (k: string) = method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ email: email || undefined, role }), + body: JSON.stringify({ email, role }), }); if (res.ok) { const data = (await res.json()) as InviteResponse; - setSuccess(t('tenant.inviteCreated')); - return data.code ?? null; + return { + email, + inviteUrl: data.inviteUrl || null, + emailSent: data.emailSent, + expiresAt: data.expiresAt, + }; } else { const err = (await res.json().catch(() => ({}))) as ApiErrorBody; setError(translateApiError(err.error) || t('tenant.inviteFailed')); @@ -269,7 +282,7 @@ function useMemberHandlers(state: TenantState, apiBase: string, t: (k: string) = setSaving(false); } }, - [apiBase, t, setSaving, setError, setSuccess], + [apiBase, t, setSaving, setError], ); return { handleChangeRole, handleRemoveMember, handleInvite }; diff --git a/apps/web/src/ui/settings/profilePatchBody.test.ts b/apps/web/src/ui/settings/profilePatchBody.test.ts index 3732654d..55d765e5 100644 --- a/apps/web/src/ui/settings/profilePatchBody.test.ts +++ b/apps/web/src/ui/settings/profilePatchBody.test.ts @@ -1,29 +1,10 @@ -import { describe, expect, it } from 'vitest'; +import { expect, it } from 'vitest'; import { profilePatchBody } from './profilePatchBody'; -describe('profilePatchBody', () => { - it('sends the name and the e-mail address when there is a name', () => { - expect(profilePatchBody('Jörg Müller', 'joerg@example.test')).toEqual({ - name: 'Jörg Müller', - email: 'joerg@example.test', - }); - }); - - it('sends the name trimmed', () => { - expect(profilePatchBody(' Jörg Müller \t', 'joerg@example.test')).toEqual({ - name: 'Jörg Müller', - email: 'joerg@example.test', - }); - }); - - it.each([ - ['an empty name', ''], - ['a blank name', ' \t '], - ])('sends only the e-mail address for %s, so an account without a name can still change it', (_label, name) => { - const body = profilePatchBody(name, 'joerg@example.test'); +it('saves the trimmed name without resubmitting the active email address as a change request', () => { + expect(profilePatchBody(' Jorg Muller \t', 'joerg@example.test')).toEqual({ name: 'Jorg Muller' }); +}); - expect(body).toEqual({ email: 'joerg@example.test' }); - expect(body).not.toHaveProperty('name'); - expect(JSON.stringify(body)).toBe('{"email":"joerg@example.test"}'); - }); +it.each(['', ' \t '])('leaves a blank name and the email address unchanged', (name) => { + expect(profilePatchBody(name, 'joerg@example.test')).toEqual({}); }); diff --git a/apps/web/src/ui/settings/profilePatchBody.ts b/apps/web/src/ui/settings/profilePatchBody.ts index 0e6ab53d..d3863689 100644 --- a/apps/web/src/ui/settings/profilePatchBody.ts +++ b/apps/web/src/ui/settings/profilePatchBody.ts @@ -1,10 +1,5 @@ -/** - * The body of PATCH /me. The server rejects a blank name with `invalid name`, - * and an account without a name is legitimate (sign-up without one, guests), so - * a name is only sent when there is one: a blank field leaves the stored name - * as it is and the e-mail address can still be changed on its own. - */ -export function profilePatchBody(name: string, email: string): { name?: string; email: string } { - const trimmedName = name.trim(); - return trimmedName ? { name: trimmedName, email } : { email }; +/** Saving a name does not request an email change. Preserve blank names. */ +export function profilePatchBody(name: string, _email?: string): { name?: string } { + const trimmed = name.trim(); + return trimmed ? { name: trimmed } : {}; } diff --git a/apps/web/src/ui/settings/tenant/InviteMember.test.tsx b/apps/web/src/ui/settings/tenant/InviteMember.test.tsx new file mode 100644 index 00000000..99cee78c --- /dev/null +++ b/apps/web/src/ui/settings/tenant/InviteMember.test.tsx @@ -0,0 +1,140 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { translateApiError } from '../../../lib/apiErrors'; +import { InviteMember } from './InviteMember'; + +vi.mock('react-i18next', async (importOriginal) => ({ + ...(await importOriginal()), + useTranslation: () => ({ + t: (key: string, opts?: { email?: string }) => (opts?.email ? `${key}:${opts.email}` : key), + }), +})); + +let originalLocation: Location; +let originalClipboard: PropertyDescriptor | undefined; +const writeText = vi.fn<() => Promise>(); + +beforeEach(() => { + originalLocation = window.location; + Object.defineProperty(window, 'location', { + configurable: true, + value: { ...window.location, origin: 'tauri://localhost' }, + }); + originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); + writeText.mockReset().mockResolvedValue(); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }); +}); + +afterEach(() => { + Object.defineProperty(window, 'location', { configurable: true, value: originalLocation }); + if (originalClipboard) Object.defineProperty(navigator, 'clipboard', originalClipboard); + else Reflect.deleteProperty(navigator, 'clipboard'); +}); + +type InviteResult = { + email: string; + inviteUrl: string | null; + emailSent: boolean; + expiresAt: string | null; +}; + +const SENT: InviteResult = { + email: 'member@example.test', + inviteUrl: 'https://public.example/#/?invite=ABC123', + emailSent: true, + expiresAt: '2026-02-01T00:00:00.000Z', +}; + +function renderForm(result: InviteResult) { + const onInvite = vi.fn().mockResolvedValue(result); + const onSuccess = vi.fn(); + const onError = vi.fn(); + render(); + return { onInvite, onSuccess, onError }; +} + +function fillEmail(email: string) { + fireEvent.change(screen.getByPlaceholderText('tenant.emailPlaceholder'), { target: { value: email } }); +} + +function submitButton() { + return screen.getByText('tenant.createInvite').closest('button') as HTMLButtonElement; +} + +describe('InviteMember invite links', () => { + it('copies the URL supplied by the server and reports success afterward', async () => { + const { onSuccess } = renderForm(SENT); + + fillEmail('member@example.test'); + fireEvent.click(submitButton()); + await screen.findByText('tenant.copyLink'); + fireEvent.click(screen.getByText('tenant.copyLink')); + + await waitFor(() => expect(onSuccess).toHaveBeenCalledWith('tenant.linkCopied')); + expect(writeText).toHaveBeenCalledWith('https://public.example/#/?invite=ABC123'); + expect(writeText.mock.invocationCallOrder[0]).toBeLessThan(onSuccess.mock.invocationCallOrder[0]); + }); + + it('reports the public URL error and skips clipboard when the server has no URL', async () => { + const { onError, onSuccess } = renderForm({ ...SENT, inviteUrl: null }); + + fillEmail('member@example.test'); + fireEvent.click(submitButton()); + await screen.findByText('tenant.copyLink'); + fireEvent.click(screen.getByText('tenant.copyLink')); + + await waitFor(() => expect(onError).toHaveBeenCalledWith(translateApiError('public_base_url_missing'))); + expect(writeText).not.toHaveBeenCalled(); + expect(onSuccess).not.toHaveBeenCalled(); + }); + + it('reports a clipboard error and does not report success when copying fails', async () => { + writeText.mockRejectedValue(new Error('clipboard unavailable')); + const { onError, onSuccess } = renderForm(SENT); + + fillEmail('member@example.test'); + fireEvent.click(submitButton()); + await screen.findByText('tenant.copyLink'); + fireEvent.click(screen.getByText('tenant.copyLink')); + + await waitFor(() => expect(onError).toHaveBeenCalledWith('tenant.linkCopyFailed')); + expect(onSuccess).not.toHaveBeenCalled(); + }); +}); + +describe('InviteMember email requirement', () => { + it('disables the submit button while the email field is empty', () => { + const { onInvite } = renderForm(SENT); + + expect(submitButton()).toBeDisabled(); + fillEmail(' '); + expect(submitButton()).toBeDisabled(); + fillEmail('member@example.test'); + expect(submitButton()).not.toBeDisabled(); + expect(onInvite).not.toHaveBeenCalled(); + }); +}); + +describe('InviteMember delivery feedback', () => { + it('shows the sent message with the address when the email was sent', async () => { + renderForm(SENT); + + fillEmail('member@example.test'); + fireEvent.click(submitButton()); + + expect(await screen.findByText('tenant.inviteSentTo:member@example.test')).toBeTruthy(); + expect(screen.getByText('https://public.example/#/?invite=ABC123')).toBeTruthy(); + expect(screen.getByText('tenant.copyLink')).toBeTruthy(); + }); + + it('shows the not-delivered hint and the link when the email was not sent', async () => { + renderForm({ ...SENT, emailSent: false }); + + fillEmail('member@example.test'); + fireEvent.click(submitButton()); + + expect(await screen.findByText('tenant.inviteResendNotDelivered')).toBeTruthy(); + expect(screen.getByText('https://public.example/#/?invite=ABC123')).toBeTruthy(); + expect(screen.getByText('tenant.copyLink')).toBeTruthy(); + }); +}); diff --git a/apps/web/src/ui/settings/tenant/InviteMember.tsx b/apps/web/src/ui/settings/tenant/InviteMember.tsx index 16bac586..19abd72a 100644 --- a/apps/web/src/ui/settings/tenant/InviteMember.tsx +++ b/apps/web/src/ui/settings/tenant/InviteMember.tsx @@ -1,37 +1,52 @@ import React from 'react'; import { useTranslation } from 'react-i18next'; +import { translateApiError } from '../../../lib/apiErrors'; import { Button, Input, Select, Card } from '../../system'; interface InviteMemberProps { saving: boolean; - onInvite: (email: string, role: 'admin' | 'member') => Promise; + onInvite: ( + email: string, + role: 'admin' | 'member', + ) => Promise<{ email: string; inviteUrl: string | null; emailSent: boolean; expiresAt: string | null } | null>; onClose: () => void; onSuccess: (message: string) => void; + onError: (message: string) => void; } -export function InviteMember({ saving, onInvite, onClose, onSuccess }: InviteMemberProps) { +export function InviteMember({ saving, onInvite, onClose, onSuccess, onError }: InviteMemberProps) { const { t } = useTranslation(); const [inviteEmail, setInviteEmail] = React.useState(''); const [inviteRole, setInviteRole] = React.useState<'admin' | 'member'>('member'); - const [inviteCode, setInviteCode] = React.useState(null); + const [invite, setInvite] = React.useState<{ + email: string; + inviteUrl: string | null; + emailSent: boolean; + expiresAt: string | null; + } | null>(null); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - const code = await onInvite(inviteEmail, inviteRole); - if (code) { - setInviteCode(code); - } + const createdInvite = await onInvite(inviteEmail, inviteRole); + if (createdInvite) setInvite(createdInvite); }; - const copyInviteLink = () => { - if (!inviteCode) return; - const link = `${window.location.origin}/#/?invite=${inviteCode}`; - void navigator.clipboard.writeText(link); - onSuccess(t('tenant.linkCopied')); + const copyInviteLink = async () => { + if (!invite) return; + if (!invite.inviteUrl) { + onError(translateApiError('public_base_url_missing')); + return; + } + try { + await navigator.clipboard.writeText(invite.inviteUrl); + onSuccess(t('tenant.linkCopied')); + } catch { + onError(t('tenant.linkCopyFailed')); + } }; const handleClose = () => { - setInviteCode(null); + setInvite(null); setInviteEmail(''); setInviteRole('member'); onClose(); @@ -42,9 +57,13 @@ export function InviteMember({ saving, onInvite, onClose, onSuccess }: InviteMem

{t('tenant.inviteNewMember')}

- {inviteCode ? ( + {invite ? (
-

{t('tenant.shareInviteCode')}

+

+ {invite.emailSent + ? t('tenant.inviteSentTo', { email: invite.email }) + : t('tenant.inviteResendNotDelivered')} +

- {inviteCode} + {invite.inviteUrl} - @@ -84,7 +109,7 @@ export function InviteMember({ saving, onInvite, onClose, onSuccess }: InviteMem {t('tenant.cancel')} -
diff --git a/apps/web/src/ui/settings/tenant/InvitesTab.test.tsx b/apps/web/src/ui/settings/tenant/InvitesTab.test.tsx index 39c93c01..e17b9f5e 100644 --- a/apps/web/src/ui/settings/tenant/InvitesTab.test.tsx +++ b/apps/web/src/ui/settings/tenant/InvitesTab.test.tsx @@ -1,52 +1,228 @@ import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { InvitesTab } from './InvitesTab'; +import { translateApiError } from '../../../lib/apiErrors'; -vi.mock('react-i18next', () => ({ +vi.mock('react-i18next', async (importOriginal) => ({ + ...(await importOriginal()), useTranslation: () => ({ t: (k: string) => k }), })); -const INVITES = [{ code: 'abc123', email: 'new@example.test', usedAt: null, createdAt: '2026-01-01T00:00:00.000Z' }]; +type Invite = { + id: string; + email: string | null; + role: string; + status: 'pending' | 'accepted' | 'expired'; + expiresAt: string | null; + lastSentAt: string | null; + lastSendError: string | null; + createdAt: string; + usedAt: string | null; + url: string | null; +}; + +const BASE_INVITE: Invite = { + id: 'id-base', + email: 'base@example.test', + role: 'member', + status: 'pending', + expiresAt: '2026-02-01T00:00:00.000Z', + lastSentAt: '2026-01-01T10:00:00.000Z', + lastSendError: null, + createdAt: '2026-01-01T00:00:00.000Z', + usedAt: null, + url: 'https://public.example/#/?invite=XYZ', +}; + +const PENDING: Invite = { ...BASE_INVITE, id: 'id-pending', email: 'pending@example.test' }; +const ACCEPTED: Invite = { + ...BASE_INVITE, + id: 'id-accepted', + email: 'accepted@example.test', + status: 'accepted', + usedAt: '2026-01-02T00:00:00.000Z', +}; +const EXPIRED: Invite = { ...BASE_INVITE, id: 'id-expired', email: 'expired@example.test', status: 'expired' }; +const NOT_DELIVERED: Invite = { + ...BASE_INVITE, + id: 'id-notdelivered', + email: 'notdelivered@example.test', + lastSentAt: null, + lastSendError: 'not_delivered', +}; +const NEVER_SENT: Invite = { + ...BASE_INVITE, + id: 'id-never', + email: 'never@example.test', + expiresAt: null, + lastSentAt: null, + lastSendError: null, +}; + +let serverInvites: Invite[]; +let getStatus: number; +let getReject: boolean; +let resendEmailSent: boolean; function stubApi(del: { ok: boolean; status: number } | 'network-error' = { ok: true, status: 200 }) { - const fetchMock = vi.fn((_url: string, init?: RequestInit) => { + const fetchMock = vi.fn((url: string, init?: RequestInit) => { if (init?.method === 'DELETE') { - return del === 'network-error' - ? Promise.reject(new TypeError('offline')) - : Promise.resolve({ ...del, json: () => Promise.resolve({}) }); + if (del === 'network-error') return Promise.reject(new TypeError('offline')); + if (del.ok || del.status === 404) { + const id = String(url).split('/').pop() ?? ''; + serverInvites = serverInvites.filter((i) => i.id !== decodeURIComponent(id)); + } + return Promise.resolve({ ...del, json: () => Promise.resolve({}) }); } - return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(INVITES) }); + if (init?.method === 'POST' && String(url).includes('/resend')) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ emailSent: resendEmailSent }), + }); + } + if (getReject) return Promise.reject(new TypeError('offline')); + return Promise.resolve({ + ok: getStatus >= 200 && getStatus < 300, + status: getStatus, + json: () => Promise.resolve(serverInvites), + }); }); vi.stubGlobal('fetch', fetchMock); return fetchMock; } +const getCalls = (fetchMock: ReturnType) => + fetchMock.mock.calls.filter(([url, init]) => String(url).endsWith('/invites') && !init?.method); + const deletes = (fetchMock: ReturnType) => fetchMock.mock.calls.filter(([, init]) => init?.method === 'DELETE'); +const resends = (fetchMock: ReturnType) => + fetchMock.mock.calls.filter(([, init]) => init?.method === 'POST'); + +let originalLocation: Location; +let originalClipboard: PropertyDescriptor | undefined; +const writeText = vi.fn<() => Promise>(); + beforeEach(() => { + serverInvites = [PENDING, ACCEPTED, EXPIRED, NOT_DELIVERED, NEVER_SENT]; + getStatus = 200; + getReject = false; + resendEmailSent = true; // The desktop shell has no usable window.confirm; the tab must not call it. vi.stubGlobal('confirm', vi.fn()); + originalLocation = window.location; + Object.defineProperty(window, 'location', { + configurable: true, + value: { ...window.location, origin: 'tauri://localhost' }, + }); + originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); + writeText.mockReset().mockResolvedValue(); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }); }); afterEach(() => { + Object.defineProperty(window, 'location', { configurable: true, value: originalLocation }); + if (originalClipboard) Object.defineProperty(navigator, 'clipboard', originalClipboard); + else Reflect.deleteProperty(navigator, 'clipboard'); vi.unstubAllGlobals(); }); -describe('InvitesTab delete confirmation', () => { - it('deletes an invite only after the in-app confirmation', async () => { +describe('InvitesTab invite links', () => { + it('copies the URL supplied by the server', async () => { + stubApi(); + render(); + + const row = (await screen.findByText('pending@example.test')).closest('tr') as HTMLElement; + fireEvent.click(within(row).getByText('tenant.inviteCopy')); + + await waitFor(() => expect(writeText).toHaveBeenCalledWith('https://public.example/#/?invite=XYZ')); + }); + + it('shows a translated error and does not copy when the server has no URL', async () => { + serverInvites = [{ ...PENDING, url: null }]; + stubApi(); + render(); + + fireEvent.click(await screen.findByText('tenant.inviteCopy')); + + expect(writeText).not.toHaveBeenCalled(); + expect(await screen.findByText(translateApiError('public_base_url_missing'))).toBeTruthy(); + }); +}); + +describe('InvitesTab status badges', () => { + it('shows pending, accepted and expired badges', async () => { + stubApi(); + render(); + + expect(await screen.findByText('pending@example.test')).toBeTruthy(); + expect(screen.getAllByText('tenant.invitePending')).toHaveLength(3); + expect(screen.getByText('tenant.inviteAccepted')).toBeTruthy(); + expect(screen.getByText('tenant.inviteExpired')).toBeTruthy(); + }); +}); + +describe('InvitesTab validity and delivery', () => { + it('shows the valid-until column and delivery states', async () => { + stubApi(); + render(); + + expect(await screen.findByText('tenant.inviteValidUntil')).toBeTruthy(); + expect(screen.getByText('tenant.inviteNotDelivered')).toBeTruthy(); + expect(screen.getAllByText('tenant.inviteSentOn')).toHaveLength(3); + const neverRow = (await screen.findByText('never@example.test')).closest('tr') as HTMLElement; + expect(within(neverRow).getAllByText('\u2014')).toHaveLength(2); + }); +}); + +describe('InvitesTab resend', () => { + async function clickResend(email: string) { + const row = (await screen.findByText(email)).closest('tr') as HTMLElement; + fireEvent.click(within(row).getByText('tenant.inviteResend')); + } + + it('posts to the resend endpoint and reloads the list', async () => { + const fetchMock = stubApi(); + render(); + await screen.findByText('pending@example.test'); + expect(getCalls(fetchMock)).toHaveLength(1); + + await clickResend('pending@example.test'); + + await waitFor(() => expect(resends(fetchMock)).toHaveLength(1)); + expect(String(resends(fetchMock)[0][0])).toBe('/api/invites/id-pending/resend'); + expect(await screen.findByText('tenant.inviteResent')).toBeTruthy(); + await waitFor(() => expect(getCalls(fetchMock).length).toBeGreaterThan(1)); + }); + + it('shows the not-delivered hint when the email was not sent', async () => { + resendEmailSent = false; + stubApi(); + render(); + + await clickResend('pending@example.test'); + + expect(await screen.findByText('tenant.inviteResendNotDelivered')).toBeTruthy(); + }); +}); + +describe('InvitesTab revoke confirmation', () => { + it('revokes an invite by id only after the in-app confirmation', async () => { const fetchMock = stubApi(); render(); - fireEvent.click(await screen.findByText('tenant.inviteDelete')); + const row = (await screen.findByText('pending@example.test')).closest('tr') as HTMLElement; + fireEvent.click(within(row).getByText('tenant.inviteRevoke')); expect(screen.getByText('tenant.inviteDeleteConfirm')).toBeTruthy(); expect(deletes(fetchMock)).toHaveLength(0); fireEvent.click(screen.getByText('confirmDialog.confirm')); await waitFor(() => expect(deletes(fetchMock)).toHaveLength(1)); - expect(String(deletes(fetchMock)[0][0])).toBe('/api/invites/abc123'); - await waitFor(() => expect(screen.queryByText('abc123')).toBeNull()); + expect(String(deletes(fetchMock)[0][0])).toBe('/api/invites/id-pending'); + await waitFor(() => expect(screen.queryByText('pending@example.test')).toBeNull()); expect(confirm).not.toHaveBeenCalled(); }); @@ -54,48 +230,124 @@ describe('InvitesTab delete confirmation', () => { const fetchMock = stubApi(); render(); - fireEvent.click(await screen.findByText('tenant.inviteDelete')); + const row = (await screen.findByText('pending@example.test')).closest('tr') as HTMLElement; + fireEvent.click(within(row).getByText('tenant.inviteRevoke')); fireEvent.click(screen.getByText('confirmDialog.cancel')); await waitFor(() => expect(screen.queryByText('tenant.inviteDeleteConfirm')).toBeNull()); expect(deletes(fetchMock)).toHaveLength(0); - expect(screen.getByText('abc123')).toBeTruthy(); + expect(screen.getByText('pending@example.test')).toBeTruthy(); }); }); -describe('InvitesTab delete response', () => { - async function confirmDelete() { - fireEvent.click(await screen.findByText('tenant.inviteDelete')); +describe('InvitesTab revoke response', () => { + async function confirmRevoke() { + const row = (await screen.findByText('pending@example.test')).closest('tr') as HTMLElement; + fireEvent.click(within(row).getByText('tenant.inviteRevoke')); fireEvent.click(screen.getByText('confirmDialog.confirm')); } - it('shows an error and keeps the invite when the server rejects the delete', async () => { + it('shows an error and keeps the invite when the server rejects the revoke', async () => { stubApi({ ok: false, status: 500 }); render(); - await confirmDelete(); + await confirmRevoke(); - expect(await screen.findByText('tenant.inviteDeleteFailed')).toBeTruthy(); - expect(screen.getByText('abc123')).toBeTruthy(); + expect(await screen.findByText('tenant.inviteRevokeFailed')).toBeTruthy(); + expect(screen.getByText('pending@example.test')).toBeTruthy(); }); it('shows an error and keeps the invite on a network error', async () => { stubApi('network-error'); render(); - await confirmDelete(); + await confirmRevoke(); - expect(await screen.findByText('tenant.inviteDeleteFailed')).toBeTruthy(); - expect(screen.getByText('abc123')).toBeTruthy(); + expect(await screen.findByText('tenant.inviteRevokeFailed')).toBeTruthy(); + expect(screen.getByText('pending@example.test')).toBeTruthy(); }); - it('treats a 404 as already deleted', async () => { + it('treats a 404 as already revoked', async () => { stubApi({ ok: false, status: 404 }); render(); - await confirmDelete(); + await confirmRevoke(); + + await waitFor(() => expect(screen.queryByText('pending@example.test')).toBeNull()); + expect(screen.queryByText('tenant.inviteRevokeFailed')).toBeNull(); + }); +}); + +describe('InvitesTab accepted invites', () => { + it('offers neither resend nor revoke for accepted invites', async () => { + stubApi(); + render(); + + const row = (await screen.findByText('accepted@example.test')).closest('tr') as HTMLElement; + expect(within(row).queryByText('tenant.inviteResend')).toBeNull(); + expect(within(row).queryByText('tenant.inviteRevoke')).toBeNull(); + }); + + it('offers no link copy for accepted and expired invites', async () => { + stubApi(); + render(); + + const acceptedRow = (await screen.findByText('accepted@example.test')).closest('tr') as HTMLElement; + const expiredRow = (await screen.findByText('expired@example.test')).closest('tr') as HTMLElement; + expect(within(acceptedRow).queryByText('tenant.inviteCopy')).toBeNull(); + expect(within(expiredRow).queryByText('tenant.inviteCopy')).toBeNull(); + }); +}); + +describe('InvitesTab load errors', () => { + it('shows the load error with retry instead of the empty state on HTTP 500', async () => { + let failGet = true; + const fetchMock = vi.fn(() => { + if (failGet) return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve([]) }); + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(serverInvites) }); + }); + vi.stubGlobal('fetch', fetchMock); + render(); + + expect(await screen.findByText('tenant.invitesLoadFailed')).toBeTruthy(); + expect(screen.getByText('tenant.retry')).toBeTruthy(); + expect(screen.queryByText('tenant.noInvites')).toBeNull(); + + failGet = false; + fireEvent.click(screen.getByText('tenant.retry')); + + expect(await screen.findByText('pending@example.test')).toBeTruthy(); + expect(screen.queryByText('tenant.invitesLoadFailed')).toBeNull(); + }); + + it('shows the load error with retry on a network error and reloads on retry', async () => { + let failGet = true; + const fetchMock = vi.fn((_url: string, init?: RequestInit) => { + if (init?.method) return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) }); + if (failGet) return Promise.reject(new TypeError('offline')); + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(serverInvites) }); + }); + vi.stubGlobal('fetch', fetchMock); + render(); + + expect(await screen.findByText('tenant.invitesLoadFailed')).toBeTruthy(); + expect(screen.queryByText('tenant.noInvites')).toBeNull(); + + failGet = false; + fireEvent.click(screen.getByText('tenant.retry')); + + expect(await screen.findByText('pending@example.test')).toBeTruthy(); + expect(screen.queryByText('tenant.invitesLoadFailed')).toBeNull(); + }); +}); + +describe('InvitesTab empty list', () => { + it('shows the empty state only for a successfully loaded empty list', async () => { + serverInvites = []; + stubApi(); + render(); - await waitFor(() => expect(screen.queryByText('abc123')).toBeNull()); - expect(screen.queryByText('tenant.inviteDeleteFailed')).toBeNull(); + expect(await screen.findByText('tenant.noInvites')).toBeTruthy(); + expect(screen.queryByText('tenant.invitesLoadFailed')).toBeNull(); }); }); diff --git a/apps/web/src/ui/settings/tenant/InvitesTab.tsx b/apps/web/src/ui/settings/tenant/InvitesTab.tsx index 24d07417..7d4f730c 100644 --- a/apps/web/src/ui/settings/tenant/InvitesTab.tsx +++ b/apps/web/src/ui/settings/tenant/InvitesTab.tsx @@ -1,83 +1,145 @@ -import React from 'react'; +import * as React from 'react'; import { useTranslation } from 'react-i18next'; +import type { TFunction } from 'i18next'; +import { translateApiError } from '../../../lib/apiErrors'; import { Section, Button, Badge, Table, THead, TBody, Tr, Th, Td, Alert, useConfirmDialog } from '../../system'; +type InviteStatus = 'pending' | 'accepted' | 'expired'; + type Invite = { - code: string; + id: string; email?: string | null; - usedAt?: string | null; + role?: string; + status: InviteStatus; + expiresAt?: string | null; + lastSentAt?: string | null; + lastSendError?: string | null; createdAt?: string; + usedAt?: string | null; + url?: string | null; }; interface InvitesTabProps { apiBase: string; } -function useInvitesTab(apiBase: string, t: (k: string) => string) { +interface ApiErrorBody { + error?: unknown; +} + +type Notice = { text: string; intent: 'success' | 'warning' } | null; + +function useInvitesTab(apiBase: string, t: TFunction) { const [invites, setInvites] = React.useState([]); const [loading, setLoading] = React.useState(true); + const [loadFailed, setLoadFailed] = React.useState(false); const [error, setError] = React.useState(null); + const [notice, setNotice] = React.useState(null); const { confirm, dialog: confirmDialog } = useConfirmDialog(); - React.useEffect(() => { - let cancelled = false; - void (async () => { - setLoading(true); - try { - const res = await fetch(`${apiBase}/invites`, { credentials: 'include' }); - if (res.ok) { - const data = (await res.json()) as Invite[]; - if (!cancelled) setInvites(data); - } - } catch { - /* ignore */ + const load = React.useCallback(async () => { + setLoading(true); + setLoadFailed(false); + try { + const res = await fetch(`${apiBase}/invites`, { credentials: 'include' }); + if (!res.ok) { + setLoadFailed(true); + return; } - if (!cancelled) setLoading(false); - })(); - return () => { - cancelled = true; - }; + setInvites((await res.json()) as Invite[]); + } catch { + setLoadFailed(true); + } finally { + setLoading(false); + } }, [apiBase]); - const handleDelete = async (code: string) => { + React.useEffect(() => { + void load(); + }, [load]); + + const handleResend = async (id: string) => { + setError(null); + setNotice(null); + try { + const res = await fetch(`${apiBase}/invites/${encodeURIComponent(id)}/resend`, { + method: 'POST', + credentials: 'include', + }); + if (res.ok) { + const body = (await res.json()) as { emailSent?: boolean }; + setNotice({ + text: t(body.emailSent ? 'tenant.inviteResent' : 'tenant.inviteResendNotDelivered'), + intent: body.emailSent ? 'success' : 'warning', + }); + } else { + const err = (await res.json().catch(() => ({}))) as ApiErrorBody; + setError(translateApiError(err.error) || t('tenant.inviteResendFailed')); + } + } catch { + setError(t('tenant.inviteResendFailed')); + } + await load(); + }; + + const handleRevoke = async (id: string) => { if (!(await confirm(t('tenant.inviteDeleteConfirm')))) return; setError(null); + setNotice(null); try { - const res = await fetch(`${apiBase}/invites/${encodeURIComponent(code)}`, { + const res = await fetch(`${apiBase}/invites/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include', }); // 404 means the invite is already gone, which is what the user asked for. if (res.ok || res.status === 404) { - setInvites((prev) => prev.filter((i) => i.code !== code)); + setInvites((prev) => prev.filter((i) => i.id !== id)); } else { - setError(t('tenant.inviteDeleteFailed')); + const err = (await res.json().catch(() => ({}))) as ApiErrorBody; + setError(translateApiError(err.error) || t('tenant.inviteRevokeFailed')); } } catch { - setError(t('tenant.inviteDeleteFailed')); + setError(t('tenant.inviteRevokeFailed')); } + await load(); }; - const handleCopy = async (code: string) => { - const link = `${window.location.origin}/#/?invite=${code}`; + const handleCopy = async (invite: Invite) => { + if (!invite.url) { + setError(translateApiError('public_base_url_missing')); + return; + } try { - await navigator.clipboard.writeText(link); + await navigator.clipboard.writeText(invite.url); } catch { - /* clipboard not available */ + setError(t('tenant.linkCopyFailed')); } }; - return { invites, loading, error, setError, handleDelete, handleCopy, confirmDialog }; + return { + invites, + loading, + loadFailed, + error, + notice, + setError, + load, + handleResend, + handleRevoke, + handleCopy, + confirmDialog, + }; } -function InvitesHeader({ t }: { t: (k: string) => string }) { +function InvitesHeader({ t }: { t: TFunction }) { return ( - {t('tenant.inviteCode')} - {t('tenant.inviteEmail')} + {t('tenant.inviteEmail')} {t('tenant.inviteCreatedAt')} + {t('tenant.inviteValidUntil')} {t('tenant.inviteStatus')} + {t('tenant.inviteDelivery')} {null} @@ -89,7 +151,7 @@ function LoadingRows() { {[1, 2, 3].map((i) => ( - +
{t('tenant.inviteAccepted')}; + } + if (status === 'expired') { + return {t('tenant.inviteExpired')}; + } + return {t('tenant.invitePending')}; +} + +function DeliveryCell({ invite, t }: { invite: Invite; t: TFunction }) { + if (invite.lastSendError === 'not_delivered') { + return {t('tenant.inviteNotDelivered')}; + } + if (invite.lastSentAt) { + return <>{t('tenant.inviteSentOn', { date: new Date(invite.lastSentAt).toLocaleString() })}; + } + return <>{'\u2014'}; +} + function InviteRow({ inv, t, onCopy, - onDelete, + onResend, + onRevoke, }: { inv: Invite; - t: (k: string) => string; - onCopy: (code: string) => void | Promise; - onDelete: (code: string) => void | Promise; + t: TFunction; + onCopy: (invite: Invite) => void | Promise; + onResend: (id: string) => void | Promise; + onRevoke: (id: string) => void | Promise; }) { return ( - - - {inv.code} - - - {inv.email || '\u2014'} + {inv.email || '\u2014'} {inv.createdAt ? new Date(inv.createdAt).toLocaleString() : '\u2014'} + {inv.expiresAt ? new Date(inv.expiresAt).toLocaleString() : '\u2014'} - - {inv.usedAt ? t('tenant.inviteUsed') : t('tenant.invitePending')} - + + + + - - {!inv.usedAt && ( + {inv.status === 'pending' && ( + + )} + {inv.status !== 'accepted' && ( + + )} + {inv.status !== 'accepted' && ( )} @@ -167,7 +253,19 @@ function InviteRow({ export function InvitesTab({ apiBase }: InvitesTabProps) { const { t } = useTranslation(); - const { invites, loading, error, setError, handleDelete, handleCopy, confirmDialog } = useInvitesTab(apiBase, t); + const { + invites, + loading, + loadFailed, + error, + notice, + setError, + load, + handleResend, + handleRevoke, + handleCopy, + confirmDialog, + } = useInvitesTab(apiBase, t); return (
@@ -176,29 +274,59 @@ export function InvitesTab({ apiBase }: InvitesTabProps) { {error} )} - - - {loading && } - {!loading && invites.length === 0 && ( - - - - - - )} - {!loading && invites.length > 0 && ( - - {invites.map((inv) => ( - - ))} - - )} -
- {t('tenant.noInvites')} -
+ {notice && ( + + {notice.text} + + )} + {!loading && loadFailed && ( +
+ + {t('tenant.invitesLoadFailed')} + + +
+ )} + {!loadFailed && ( + + + {loading && } + {!loading && invites.length === 0 && ( + + + + + + )} + {!loading && invites.length > 0 && ( + + {invites.map((inv) => ( + + ))} + + )} +
+ {t('tenant.noInvites')} +
+ )} {confirmDialog}
); diff --git a/apps/web/src/ui/settings/tenant/MemberSettings.name.test.tsx b/apps/web/src/ui/settings/tenant/MemberSettings.name.test.tsx index 444194b4..a3add625 100644 --- a/apps/web/src/ui/settings/tenant/MemberSettings.name.test.tsx +++ b/apps/web/src/ui/settings/tenant/MemberSettings.name.test.tsx @@ -18,6 +18,7 @@ function renderEditScreen(onEditMember = vi.fn(() => Promise.resolve(true))) { onRemoveMember={vi.fn()} onInvite={vi.fn()} onSuccess={vi.fn()} + onError={vi.fn()} onResetPassword={vi.fn()} onEditMember={onEditMember} />, diff --git a/apps/web/src/ui/settings/tenant/MemberSettings.remove.test.tsx b/apps/web/src/ui/settings/tenant/MemberSettings.remove.test.tsx index daa8a0f5..91575592 100644 --- a/apps/web/src/ui/settings/tenant/MemberSettings.remove.test.tsx +++ b/apps/web/src/ui/settings/tenant/MemberSettings.remove.test.tsx @@ -17,6 +17,7 @@ function renderMembers(onRemoveMember = vi.fn()) { onRemoveMember={onRemoveMember} onInvite={vi.fn()} onSuccess={vi.fn()} + onError={vi.fn()} onResetPassword={vi.fn()} onEditMember={vi.fn()} />, diff --git a/apps/web/src/ui/settings/tenant/MemberSettings.tsx b/apps/web/src/ui/settings/tenant/MemberSettings.tsx index 05ae5308..d6640dcc 100644 --- a/apps/web/src/ui/settings/tenant/MemberSettings.tsx +++ b/apps/web/src/ui/settings/tenant/MemberSettings.tsx @@ -25,8 +25,12 @@ interface MemberSettingsProps { saving: boolean; onChangeRole: (userId: string, newRole: 'admin' | 'member') => void; onRemoveMember: (userId: string) => void; - onInvite: (email: string, role: 'admin' | 'member') => Promise; + onInvite: ( + email: string, + role: 'admin' | 'member', + ) => Promise<{ email: string; inviteUrl: string | null; emailSent: boolean; expiresAt: string | null } | null>; onSuccess: (message: string) => void; + onError: (message: string) => void; onResetPassword: (email: string) => Promise; onEditMember: (userId: string, data: { email?: string; name?: string }) => Promise; } @@ -330,7 +334,7 @@ function useMemberSettingsState(props: MemberSettingsProps) { export function MemberSettings(props: MemberSettingsProps) { const { t } = useTranslation(); - const { members, saving, onChangeRole, onRemoveMember, onInvite, onSuccess } = props; + const { members, saving, onChangeRole, onRemoveMember, onInvite, onSuccess, onError } = props; const state = useMemberSettingsState(props); const { screen, @@ -362,6 +366,7 @@ export function MemberSettings(props: MemberSettingsProps) { onInvite={onInvite} onClose={() => setScreen({ type: 'list' })} onSuccess={onSuccess} + onError={onError} /> ); diff --git a/apps/web/src/ui/user/RosterPanel.tsx b/apps/web/src/ui/user/RosterPanel.tsx index b5033e12..b7ca01be 100644 --- a/apps/web/src/ui/user/RosterPanel.tsx +++ b/apps/web/src/ui/user/RosterPanel.tsx @@ -90,6 +90,8 @@ function CollapsedRoster({ const { t } = useTranslation(); return (
void; }) { + const { t } = useTranslation(); const { roster, onJumpTo, collapsed, onToggleCollapse } = props; const [hoveredId, setHoveredId] = React.useState(null); const formatLastSeen = useFormatLastSeen(); @@ -511,6 +514,8 @@ export function RosterPanel(props: { return (
{ + it('uses the team translation as the complementary name in both states', () => { + const { rerender } = render(); + + expect(screen.getByRole('complementary', { name: 'roster.team' })).toBeInTheDocument(); + + rerender(); + + expect(screen.getByRole('complementary', { name: 'roster.team' })).toBeInTheDocument(); + }); +}); diff --git a/package-lock.json b/package-lock.json index f7916b78..2391cfcf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -166,6 +166,7 @@ "@testing-library/dom": "^10.4.2", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", + "@types/pg": "^8.21.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@vitejs/plugin-react": "^6.1.1", @@ -175,6 +176,7 @@ "eslint-plugin-react": "^7.37.5", "eslint-plugin-react-hooks": "^7.1.1", "jsdom": "^30.1.1", + "pg": "^8.23.0", "typescript": "^6.0.3", "vite": "~8.3.1", "vitest": "^5.0.2" From 6a0b61046baa6aa887c8d824ea6bb9e02b369d51 Mon Sep 17 00:00:00 2001 From: ricoroeder Date: Fri, 13 Nov 2026 03:24:00 +0000 Subject: [PATCH 002/379] test(server): cover the membership requirement of the auth helpers Signed-off-by: ricoroeder --- ...authHelpers.membership.integration.test.ts | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 apps/server/src/api/utils/authHelpers.membership.integration.test.ts diff --git a/apps/server/src/api/utils/authHelpers.membership.integration.test.ts b/apps/server/src/api/utils/authHelpers.membership.integration.test.ts new file mode 100644 index 00000000..2d7b7b5b --- /dev/null +++ b/apps/server/src/api/utils/authHelpers.membership.integration.test.ts @@ -0,0 +1,76 @@ +/** + * requireMembership with both rules in force: the membership gate (unconfirmed + * invite, ended access) and the access end in the result, which the LiveKit + * token lifetime reads (health.ts). Real PostgreSQL through db.js, no mocks. + */ + +import crypto from 'crypto'; +import type express from 'express'; +import { afterAll, describe, expect, it } from 'vitest'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { requireMembership } from './authHelpers.js'; + +if (!process.env.DATABASE_URL) { + throw new Error('authHelpers.membership.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; + +interface MembershipSeed { + role: Role; + expiresAt?: Date | null; + inviteVerificationRequired?: boolean; +} + +async function seedMembership(seed: MembershipSeed) { + const slug = `membership-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + const user = await prisma.user.create({ data: { email: `${slug}@example.test`, emailVerifiedAt: new Date() } }); + userIds.push(user.id); + await prisma.membership.create({ data: { tenantId: tenant.id, userId: user.id, ...seed } }); + // requireMembership reads only req.tenant, which the tenant middleware sets in production. + return { req: { tenant } as unknown as express.Request, userId: user.id }; +} + +afterAll(async () => { + await prisma.membership.deleteMany({ where: { tenantId: { in: tenantIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('requireMembership', () => { + it('returns the role and no access end for a confirmed permanent member', async () => { + const { req, userId } = await seedMembership({ role: 'member' }); + await expect(requireMembership(req, userId, prisma)).resolves.toEqual({ role: 'member', expiresAt: null }); + }); + + it('returns the access end of a guest whose access is still running', async () => { + const end = new Date(Date.now() + 3_600_000); + const { req, userId } = await seedMembership({ role: 'guest', expiresAt: end }); + await expect(requireMembership(req, userId, prisma)).resolves.toEqual({ role: 'guest', expiresAt: end }); + }); + + it('refuses a guest whose access has ended', async () => { + const { req, userId } = await seedMembership({ role: 'guest', expiresAt: new Date(Date.now() - 1_000) }); + await expect(requireMembership(req, userId, prisma)).resolves.toBeNull(); + }); + + it('refuses a membership that still waits for the invite confirmation, even with a running access end', async () => { + const { req, userId } = await seedMembership({ + role: 'guest', + expiresAt: new Date(Date.now() + 3_600_000), + inviteVerificationRequired: true, + }); + await expect(requireMembership(req, userId, prisma)).resolves.toBeNull(); + }); + + it('refuses a request without a resolved tenant', async () => { + const { userId } = await seedMembership({ role: 'member' }); + await expect(requireMembership({} as express.Request, userId, prisma)).resolves.toBeNull(); + }); +}); From d8cc24bd7de0e733cd528a4f5067c17c076ea4c2 Mon Sep 17 00:00:00 2001 From: ricoroeder Date: Fri, 13 Nov 2026 03:24:00 +0000 Subject: [PATCH 003/379] chore: apply 2a.2_05-server-blank-zone-name-default.patch Signed-off-by: ricoroeder --- .../src/api/routes/editorStateSchema.ts | 16 ++++++++++++- .../worldPayloads.integration.test.ts | 24 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/apps/server/src/api/routes/editorStateSchema.ts b/apps/server/src/api/routes/editorStateSchema.ts index 53690b29..d95563c2 100644 --- a/apps/server/src/api/routes/editorStateSchema.ts +++ b/apps/server/src/api/routes/editorStateSchema.ts @@ -33,9 +33,23 @@ export const editorTilesetSchema = z.object({ category: z.string().max(MAX_NAME_CHARS).optional(), }); +/** Name a zone gets when the editor sends none; the route stored it before the schema existed. */ +export const DEFAULT_ZONE_NAME = 'Zone'; + +// Released editors let a zone name be cleared, and the route used to store a +// zone without a name as DEFAULT_ZONE_NAME. A missing, null or blank name keeps +// that behaviour instead of failing the whole save; every other rule stays. +const zoneNameSchema = z.preprocess( + (value) => + value === undefined || value === null || (typeof value === 'string' && value.trim() === '') + ? DEFAULT_ZONE_NAME + : value, + z.string().min(1).max(MAX_NAME_CHARS), +); + export const editorZoneSchema = z.object({ id: z.string().max(MAX_NAME_CHARS).optional(), - name: z.string().min(1).max(MAX_NAME_CHARS), + name: zoneNameSchema, type: z.enum(['default', 'portal']).nullable().optional(), points: pointListSchema.optional(), polygon: polygonSchema.nullable().optional(), diff --git a/apps/server/src/rooms/validation/worldPayloads.integration.test.ts b/apps/server/src/rooms/validation/worldPayloads.integration.test.ts index 6dbfb769..8bf56bcd 100644 --- a/apps/server/src/rooms/validation/worldPayloads.integration.test.ts +++ b/apps/server/src/rooms/validation/worldPayloads.integration.test.ts @@ -21,6 +21,7 @@ import { Client, type Room } from '@colyseus/sdk'; import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared'; import { createPrismaClient } from '../../db.js'; import { registerApi } from '../../api.js'; +import { DEFAULT_ZONE_NAME } from '../../api/routes/editorStateSchema.js'; import { tenantMiddleware } from '../../tenancy.js'; import { registry } from '../../metrics.js'; import { cleanupTenants, seedMember, seedTenant, type SeededMember } from '../../testUtils/worldSeed.js'; @@ -630,6 +631,29 @@ describe('accepted payloads', () => { expect(stored[0]?.capacity).toBeNull(); }, 30_000); + it('accepted payloads > stores a missing, null or blank zone name as the default name', async () => { + const unnamedZones: Array> = [ + { name: '', points: triangle() }, + { name: ' ', points: triangle() }, + { name: null, points: triangle() }, + { points: triangle() }, + ]; + for (const unnamed of unnamedZones) { + await expectAcceptedEditor({ zones: [unnamed], replaceZones: true }); + const fetched = await getEditor(); + const zones = + typeof fetched === 'object' && fetched !== null && 'zones' in fetched && Array.isArray(fetched.zones) + ? fetched.zones + : []; + expect(zones).toHaveLength(1); + const zone: unknown = zones[0]; + const name = typeof zone === 'object' && zone !== null && 'name' in zone ? zone.name : undefined; + expect(name).toBe(DEFAULT_ZONE_NAME); + const stored = await prisma.zone.findMany({ where: { mapId } }); + expect(stored.map((row) => row.name)).toEqual([DEFAULT_ZONE_NAME]); + } + }, 30_000); + it('accepted payloads > accepts 256 tilesets', async () => { await expectAcceptedEditor({ tilesets: tilesetList(256) }); expect(await tilesetCount()).toBe(256); From 77de3e7c28813ded8aceda2e943ec9df7113d6cb Mon Sep 17 00:00:00 2001 From: ricoroeder Date: Fri, 13 Nov 2026 03:24:00 +0000 Subject: [PATCH 004/379] chore: dry-run state after step 4a (simulated) Signed-off-by: ricoroeder --- .env.example | 48 +- CHANGELOG.md | 12 + CONTRIBUTING.md | 4 + README.md | 90 +- TEST_STRATEGY.md | 28 +- apps/npc-service/package.json | 3 +- apps/npc-service/src/commandSchemas.ts | 115 ++ apps/npc-service/src/config.ts | 18 +- apps/npc-service/src/httpApi.ts | 78 +- apps/npc-service/src/index.ts | 4 +- apps/npc-service/src/npcHttpApi.test.ts | 296 +++ apps/npc-service/src/npcStartupSecret.test.ts | 84 + apps/npc-service/tsconfig.lint.json | 2 +- apps/npc-service/vitest.config.ts | 12 + apps/server/entrypoint.sh | 10 + apps/server/package.json | 3 +- .../migration.sql | 71 + apps/server/prisma/schema.prisma | 63 + apps/server/prisma/seed.ts | 32 +- apps/server/src/adminLoader.ts | 83 +- .../src/api.enterpriseDeletionConfig.test.ts | 184 ++ apps/server/src/api.ts | 67 +- apps/server/src/api/requestTelemetry.test.ts | 19 +- .../guestRevocation.integration.test.ts | 151 ++ apps/server/src/api/routes/guests.ts | 33 +- apps/server/src/api/routes/npcMedia.ts | 60 +- .../server/src/api/routes/npcMediaDir.test.ts | 49 + .../npcs.serviceAuth.integration.test.ts | 237 +++ apps/server/src/api/routes/npcs.ts | 11 +- .../src/api/utils/npcServiceClient.test.ts | 89 + apps/server/src/api/utils/npcServiceClient.ts | 8 +- apps/server/src/api/utils/requestRoute.ts | 11 +- apps/server/src/api/utils/serviceSecret.ts | 57 + apps/server/src/api/utils/sessionAuth.ts | 14 + apps/server/src/billingLoader.ts | 17 + .../server/src/guestSessionRevocation.test.ts | 46 +- apps/server/src/index.ts | 331 ++-- apps/server/src/matchmake/guard.test.ts | 18 +- apps/server/src/matchmake/guard.ts | 32 +- apps/server/src/metrics.ts | 2 +- apps/server/src/ops/credentialPolicy.ts | 95 + .../src/ops/metricsAccess.integration.test.ts | 373 ++++ apps/server/src/ops/metricsServer.ts | 110 ++ .../src/ops/originAccess.integration.test.ts | 527 ++++++ apps/server/src/ops/originGuard.ts | 79 + apps/server/src/ops/originPolicy.ts | 140 ++ .../seedAdminCredentials.integration.test.ts | 609 ++++++ apps/server/src/ops/seedAdminCredentials.ts | 211 +++ .../server/src/ops/startupCredentials.test.ts | 286 +++ apps/server/src/ops/startupCredentials.ts | 22 + apps/server/src/ops/toolsRoute.ts | 361 ++++ .../ops/wsUpgradeLimit.integration.test.ts | 349 ++++ apps/server/src/ops/wsUpgradeLimit.ts | 165 ++ .../src/scripts/replayTenantDeletions.ts | 153 ++ .../__testutils__/accountDeletionLegacy.ts | 225 +++ .../accountDeletion.integration.test.ts | 75 + apps/server/src/services/accountDeletion.ts | 218 ++- ...accountDeletionJournal.integration.test.ts | 510 +++++ .../src/services/accountDeletionJournal.ts | 228 +++ .../accountDeletionReplay.integration.test.ts | 377 ++++ .../src/services/accountDeletionReplay.ts | 130 ++ .../deletionJournalAccountEntry.test.ts | 267 +++ .../services/deletionJournalConfig.test.ts | 86 + .../src/services/deletionJournalConfig.ts | 25 + .../src/services/deletionJournalExpiry.ts | 179 ++ .../src/services/deletionTaskScheduler.ts | 46 + .../src/services/deletionTaskTargets.test.ts | 222 +++ .../src/services/deletionTaskTargets.ts | 167 ++ .../server/src/services/deletionTaskWorker.ts | 392 ++++ ...toreReplayTokenCleanup.integration.test.ts | 254 +++ .../src/services/sharedPlanResolver.test.ts | 52 + .../server/src/services/sharedPlanResolver.ts | 23 + .../src/services/tenantDeletionContract.ts | 76 + .../src/services/tenantDeletionFence.ts | 88 + .../src/services/tenantDeletionJournal.ts | 595 ++++++ .../tenantDeletionJournalCompaction.test.ts | 269 +++ .../tenantDeletionJournalCompaction.ts | 164 ++ .../src/services/tenantDeletionJournalLock.ts | 169 ++ .../src/services/tenantDeletionPlanning.ts | 424 +++++ .../src/services/tenantDeletionReplay.ts | 314 ++++ .../src/services/tenantDeletionReplayRun.ts | 267 +++ .../tenantDeletionRestoreMarker.test.ts | 128 ++ .../services/tenantDeletionRestoreMarker.ts | 126 ++ .../tenantDeletionTasks.integration.test.ts | 305 +++ apps/server/src/services/tenantFiles.test.ts | 89 + apps/server/src/services/tenantFiles.ts | 67 + .../src/services/tenantSlugReservation.ts | 15 + .../src/tenantIsolation.integration.test.ts | 7 +- apps/server/src/transcriptionLoader.ts | 68 +- .../src/transcriptionLoaderState.test.ts | 52 + apps/server/test/fixtures/requestTelemetry.ts | 16 +- apps/server/test/require-database-url.ts | 10 + apps/server/vitest.config.ts | 64 +- apps/web/e2e/ops-tools-security.spec.ts | 324 ++++ compose.yaml | 13 +- docs/metrics.md | 22 + docs/origin-allowlist.md | 74 + prometheus/prometheus.yml | 4 +- tools/avatar-pack-manager.html | 480 +++-- tools/map-editor.html | 697 ++++--- tools/npc-admin.html | 381 ++-- tools/sprite-asset-cutter.html | 208 ++- tools/super-admin.html | 1653 ++++++++++------- tools/ui-prototype.html | 118 +- 104 files changed, 15039 insertions(+), 1696 deletions(-) create mode 100644 apps/npc-service/src/commandSchemas.ts create mode 100644 apps/npc-service/src/npcHttpApi.test.ts create mode 100644 apps/npc-service/src/npcStartupSecret.test.ts create mode 100644 apps/npc-service/vitest.config.ts create mode 100644 apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql create mode 100644 apps/server/src/api.enterpriseDeletionConfig.test.ts create mode 100644 apps/server/src/api/routes/guestRevocation.integration.test.ts create mode 100644 apps/server/src/api/routes/npcMediaDir.test.ts create mode 100644 apps/server/src/api/routes/npcs.serviceAuth.integration.test.ts create mode 100644 apps/server/src/api/utils/npcServiceClient.test.ts create mode 100644 apps/server/src/api/utils/serviceSecret.ts create mode 100644 apps/server/src/ops/credentialPolicy.ts create mode 100644 apps/server/src/ops/metricsAccess.integration.test.ts create mode 100644 apps/server/src/ops/metricsServer.ts create mode 100644 apps/server/src/ops/originAccess.integration.test.ts create mode 100644 apps/server/src/ops/originGuard.ts create mode 100644 apps/server/src/ops/originPolicy.ts create mode 100644 apps/server/src/ops/seedAdminCredentials.integration.test.ts create mode 100644 apps/server/src/ops/seedAdminCredentials.ts create mode 100644 apps/server/src/ops/startupCredentials.test.ts create mode 100644 apps/server/src/ops/startupCredentials.ts create mode 100644 apps/server/src/ops/toolsRoute.ts create mode 100644 apps/server/src/ops/wsUpgradeLimit.integration.test.ts create mode 100644 apps/server/src/ops/wsUpgradeLimit.ts create mode 100644 apps/server/src/scripts/replayTenantDeletions.ts create mode 100644 apps/server/src/services/__testutils__/accountDeletionLegacy.ts create mode 100644 apps/server/src/services/accountDeletion.integration.test.ts create mode 100644 apps/server/src/services/accountDeletionJournal.integration.test.ts create mode 100644 apps/server/src/services/accountDeletionJournal.ts create mode 100644 apps/server/src/services/accountDeletionReplay.integration.test.ts create mode 100644 apps/server/src/services/accountDeletionReplay.ts create mode 100644 apps/server/src/services/deletionJournalAccountEntry.test.ts create mode 100644 apps/server/src/services/deletionJournalConfig.test.ts create mode 100644 apps/server/src/services/deletionJournalConfig.ts create mode 100644 apps/server/src/services/deletionJournalExpiry.ts create mode 100644 apps/server/src/services/deletionTaskScheduler.ts create mode 100644 apps/server/src/services/deletionTaskTargets.test.ts create mode 100644 apps/server/src/services/deletionTaskTargets.ts create mode 100644 apps/server/src/services/deletionTaskWorker.ts create mode 100644 apps/server/src/services/restoreReplayTokenCleanup.integration.test.ts create mode 100644 apps/server/src/services/sharedPlanResolver.test.ts create mode 100644 apps/server/src/services/sharedPlanResolver.ts create mode 100644 apps/server/src/services/tenantDeletionContract.ts create mode 100644 apps/server/src/services/tenantDeletionFence.ts create mode 100644 apps/server/src/services/tenantDeletionJournal.ts create mode 100644 apps/server/src/services/tenantDeletionJournalCompaction.test.ts create mode 100644 apps/server/src/services/tenantDeletionJournalCompaction.ts create mode 100644 apps/server/src/services/tenantDeletionJournalLock.ts create mode 100644 apps/server/src/services/tenantDeletionPlanning.ts create mode 100644 apps/server/src/services/tenantDeletionReplay.ts create mode 100644 apps/server/src/services/tenantDeletionReplayRun.ts create mode 100644 apps/server/src/services/tenantDeletionRestoreMarker.test.ts create mode 100644 apps/server/src/services/tenantDeletionRestoreMarker.ts create mode 100644 apps/server/src/services/tenantDeletionTasks.integration.test.ts create mode 100644 apps/server/src/services/tenantFiles.test.ts create mode 100644 apps/server/src/services/tenantFiles.ts create mode 100644 apps/server/src/services/tenantSlugReservation.ts create mode 100644 apps/server/src/transcriptionLoaderState.test.ts create mode 100644 apps/server/test/require-database-url.ts create mode 100644 apps/web/e2e/ops-tools-security.spec.ts create mode 100644 docs/metrics.md create mode 100644 docs/origin-allowlist.md diff --git a/.env.example b/.env.example index 6795eb4d..9e61a19b 100644 --- a/.env.example +++ b/.env.example @@ -22,13 +22,21 @@ # Node environment: development | production | test # Local-only default. The Docker stack in compose.yaml hard-codes -# NODE_ENV=production for the server and web services, so this value only +# NODE_ENV for the server and web services, so this value only # takes effect for a non-Docker `npm run dev` workflow. NODE_ENV=development # Server port (Colyseus + Express) PORT=2567 +# Optional Prometheus scrape listener. Unset or empty disables it. The +# public app always answers GET/HEAD /metrics with 404. Direct runs bind +# loopback by default. The bundled compose.yaml sets METRICS_HOST to the +# container interface and does not publish this port to the host, so a +# scraper must sit on the same container network. +# METRICS_PORT=9100 +# METRICS_HOST=127.0.0.1 + # Log level: trace | debug | info | warn | error | fatal LOG_LEVEL=info @@ -205,10 +213,17 @@ VITE_HMR_PROTOCOL=ws # CORS & Proxy # ----------------------------------------------------------------------------- -# Allowed origins (comma-separated) -# Development: http://localhost:5173,http://localhost:5174 -# Production: https://yourdomain.com,https://*.yourdomain.com,tauri://localhost,http://tauri.localhost -CORS_ORIGIN=http://localhost:5173,http://localhost:5174 +# Allowed browser origins, comma separated. Every entry must be an exact +# origin (`scheme://host[:port]`): wildcards, suffix rules and paths are +# refused, and the server refuses to start when the list is missing or +# malformed. The same list decides for the HTTP API, for the matchmaking route +# and for the websocket upgrade. +# Development: the local web dev server. +# Production: the public web origin plus both desktop origins of the official +# app (`tauri://localhost` on macOS/Linux, `http://tauri.localhost` on +# Windows). An operator who uses the /tools pages adds the API origin of the +# deployment to the list. +CORS_ORIGIN=http://localhost:5173,http://localhost:5174,tauri://localhost,http://tauri.localhost # Trust proxy headers. Set this to the NUMBER of reverse-proxy hops in front of # the server (e.g. 1 for a single Traefik). Express then derives the client IP @@ -306,6 +321,22 @@ COOKIE_SECURE=false # RATE_LIMIT_MATCHMAKE_WINDOW_MS=60000 # RATE_LIMIT_MATCHMAKE_MAX=120 +# ----------------------------------------------------------------------------- +# Rate limiting (websocket upgrades) +# ----------------------------------------------------------------------------- +# Every websocket upgrade attempt is counted per client address before the +# origin check, so a client that hammers the handshake path runs into a budget +# instead of into the origin policy. The address is resolved with the +# TRUST_PROXY setting above, so a forwarded address counts as the client only +# when the deployment trusts the proxy in front of it. An exhausted budget +# answers 429 with a Retry-After header instead of a handshake. +# +# The mobile gateway joins from inside the server process and the npc-service +# runs in its own container: both share the budget of their source address. +# Raise the budget for a very large NPC roster (default: 120 / 60s). +# WS_UPGRADE_RATE_LIMIT_MAX=120 +# WS_UPGRADE_RATE_LIMIT_WINDOW_MS=60000 + # Slug of the default tenant: the tenant a single-tenant (OSS) install runs as, # and the one a join without a tenant is filed under. It is the partition key of # that tenant's world room, so it must be a valid tenant slug: lower-case @@ -483,7 +514,7 @@ NPC_SERVICE_URL=http://npc-service:3100 # `dev-npc-secret` default. Generate with: openssl rand -hex 32 NPC_SERVICE_SECRET=dev-npc-secret -# Directory for NPC media file storage (shared volume between server and NPC service) +# Shared by the server (upload, serving, deletion) and the npc service. Default /data/npc-media. Set it to a writable directory for local runs without Docker. NPC_MEDIA_DIR=/data/npc-media # Server URL as seen from NPC service (internal Docker network) @@ -498,8 +529,11 @@ NPC_MEDIA_DIR=/data/npc-media # (gitignored, auto-merged by Docker Compose), not in this file. # ----------------------------------------------------------------------------- -# Seed Data (Development only) +# Seed Data # ----------------------------------------------------------------------------- +# Production requires SEED_ADMIN_EMAIL (set explicitly; the historical +# default address is allowed) and SEED_ADMIN_PASSWORD (non-template). +# Development may omit the keys and use the fallbacks below. SEED_ADMIN_EMAIL=admin@meetropolis.local SEED_ADMIN_PASSWORD=admin123 diff --git a/CHANGELOG.md b/CHANGELOG.md index 21a3fe7c..d0939a29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Breaking (enterprise integration):** The tenant deletion callback in + `adminLoader` now requires `deletionProtocol: 'tenant-delete-v2'` with a + managed prepare/cleanup pair and an explicit internal retention plan and + deadline. Upgrade the host and enterprise module together; mismatched + versions reject deletion before any database DELETE statement with + `tenant_deletion_contract_required`. Without a valid internal plan the + deletion is rejected with `retention_journal_unavailable` (HTTP 409) until P4. +- **Breaking (self-hosting):** NPC media now resolve from one directory. Without `NPC_MEDIA_DIR` the server uses `/data/npc-media`, the same default as the npc service; before, uploads defaulted to `/../../npc-media` and static serving to a directory next to the build output. If you did not set `NPC_MEDIA_DIR`, set it to your existing media directory or move its contents to `/data/npc-media`. When the directory cannot be created, the server logs `npc_media.dir_unavailable` at startup. - Web client: a terminal connection error (guest expiry, session takeover, rejected authentication, outdated client, billing and limit errors, and with the transcription module a missing consent) now leaves @@ -66,6 +74,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 tenant, which signs the user out everywhere), with 4401 `session_revoked`: at once on a revocation, otherwise at the next access check. +- Server: HTTP log fields and metric labels now use route templates + instead of concrete request paths. Early `http.request` logs no longer + include a `path` field; unmatched requests use ``. This + changes values consumed by dashboards and log parsers. ### Fixed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f321b01a..dea81aa1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -106,6 +106,10 @@ packages/ npm -w @meetropolis/server run test npm -w @meetropolis/web run test +# Server tests that need a database: set DATABASE_URL to a migrated, +# disposable test database first (see TEST_STRATEGY.md, "Database Tests") +npm -w @meetropolis/server run test:db + # Run specific test file npm -w @meetropolis/web run test -- src/lib/geom.test.ts ``` diff --git a/README.md b/README.md index d577a5dc..c07a712b 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,8 @@ override or in the (private) deploy repo. Requires a running PostgreSQL instance. Configure `DATABASE_URL` in `.env`. +Set `NPC_MEDIA_DIR` to a writable directory (for example `./.data/npc-media`); its default `/data/npc-media` is meant for the Docker volume, and the server logs `npc_media.dir_unavailable` if it cannot create it. + ```bash npm install npm run dev # starts server + web concurrently @@ -166,17 +168,20 @@ boundaries; the OSS build runs fully without them. Copy `.env.example` to `.env`. Key variables: -| Variable | Description | -| -------------------- | ----------------------------------------------------- | -| `DATABASE_URL` | PostgreSQL connection string | -| `JWT_SECRET` | JWT signing secret (32+ chars in production) | -| `LIVEKIT_URL` | LiveKit server URL | -| `LIVEKIT_API_KEY` | LiveKit API key | -| `LIVEKIT_API_SECRET` | LiveKit API secret | -| `HOST_IP` | Host LAN IP for LiveKit ICE (Docker Desktop on macOS) | -| `CORS_ORIGIN` | Allowed CORS origins (required in production) | -| `VITE_API_BASE` | Server URL baked into the web bundle at _build_ time | -| `VITE_LIVEKIT_URL` | LiveKit URL baked into the web bundle at _build_ time | +| Variable | Description | +| -------------------- | ---------------------------------------------------------------------------------------- | +| `DATABASE_URL` | PostgreSQL connection string | +| `JWT_SECRET` | JWT signing secret (32+ chars in production) | +| `LIVEKIT_URL` | LiveKit server URL | +| `LIVEKIT_API_KEY` | LiveKit API key | +| `LIVEKIT_API_SECRET` | LiveKit API secret | +| `HOST_IP` | Host LAN IP for LiveKit ICE (Docker Desktop on macOS) | +| `CORS_ORIGIN` | Exact list of allowed browser origins (required) | +| `METRICS_PORT` | Optional scrape listener; unset disables it | +| `METRICS_HOST` | Bind address for that listener (default loopback) | +| `VITE_API_BASE` | Server URL baked into the web bundle at _build_ time | +| `VITE_LIVEKIT_URL` | LiveKit URL baked into the web bundle at _build_ time | +| `NPC_MEDIA_DIR` | Storage directory for NPC media, shared with the npc service (default `/data/npc-media`) | See `.env.example` for the full list including optional variables. @@ -319,6 +324,69 @@ The bundled `compose.yaml` covers the minimum self-host case (Postgres | `CORS_ORIGIN` | Explicit list of allowed origins | | `COOKIE_SECURE` | `true` | +`CORS_ORIGIN` holds exact origins (`scheme://host[:port]`) and nothing else: +no wildcard, no suffix rule, no path, and `null` is not an origin. The server +refuses to start when the list is missing or malformed, in every mode. The +same list decides for the HTTP API, for the matchmaking route and for the +websocket upgrade: an origin that is not listed gets `403` and no CORS +headers, and `Origin: null` is refused as well. A request without an `Origin` +header is not a browser request: it stays possible for native clients, +webhooks and health checks, gets no CORS headers, and is decided by the +route's own auth. + +The official desktop app reports `tauri://localhost` on macOS/Linux and +`http://tauri.localhost` on Windows. Both must be listed explicitly, older +builds included. The same applies to the API origin of an operator who uses +the `/tools` pages: it is an ordinary origin now, there is no same-origin +exception any more. See [`docs/origin-allowlist.md`](docs/origin-allowlist.md). + +`GET`/`HEAD` `/metrics` on the public app port always returns 404. +Prometheus scrapes `METRICS_PORT` (compose default 9100) on the +container network. `compose.yaml` does not publish that port and does +not put a proxy route in front of it. Direct runs bind loopback unless +`METRICS_HOST` is set. See [`docs/metrics.md`](docs/metrics.md). + +Websocket upgrades are budgeted per client address: every upgrade +attempt is counted before the origin check, and an exhausted budget +answers `429` with a `Retry-After` header instead of a handshake. +`WS_UPGRADE_RATE_LIMIT_MAX` (default 120) sets the budget, +`WS_UPGRADE_RATE_LIMIT_WINDOW_MS` (default 60000) the window. The mobile +gateway joins from inside the server process and the npc-service runs in +its own container: both share the budget of their source address. + +Every production start path (server entrypoint, migration service, and +the server process itself) enforces the credential policy below before +any migration, seed, or listen work. A violation stops the start and +reports only the offending key name, never a value. `TOOLS_PASSWORD` +stays optional: unset or empty keeps the tools route disabled and the +start valid. + +| Variable | Production rule | +| -------------------- | ------------------------------------------- | +| `LIVEKIT_API_KEY` | Present, non-blank, not the template value | +| `LIVEKIT_API_SECRET` | Present, non-blank, not the template value | +| `DATABASE_URL` | Valid Postgres URL, password neither blank | +| | nor the template value | +| `POSTGRES_PASSWORD` | When set, non-blank and not the template | +| | value | +| `TOOLS_PASSWORD` | When set, non-blank and not the template | +| | value | + +The seed program additionally enforces `SEED_ADMIN_EMAIL` and +`SEED_ADMIN_PASSWORD` before it opens a database connection. It uses +the same production mode detection as the start path and does not +require LiveKit or tools credentials. + +| Variable | Production rule | +| --------------------- | ------------------------------------------ | +| `SEED_ADMIN_EMAIL` | Present and non-blank; an explicit | +| | historical default address is allowed | +| `SEED_ADMIN_PASSWORD` | Present, non-blank, and not the template | +| | value | + +Development keeps the previous fallbacks. A violation exits with +status 1 and prints only the offending key name. + See [`docs/livekit-production.md`](docs/livekit-production.md) for the LiveKit-specific hardening walkthrough (replacing `--dev`, rotating keys, ICE / NAT setup, verification). diff --git a/TEST_STRATEGY.md b/TEST_STRATEGY.md index 01cd7ad8..38e3a905 100644 --- a/TEST_STRATEGY.md +++ b/TEST_STRATEGY.md @@ -10,7 +10,7 @@ This file defines the test strategy for the Meetropolis monorepo. It is intended | Unit Tests (Server) | Vitest + Supertest | `apps/server/src/**/*.test.ts` | Active | | Unit Tests (Shared) | Vitest | `packages/shared/src/**/*.test.ts` | New | | E2E Tests | Playwright | `apps/web/e2e/*.spec.ts` | In Development | -| Integration Tests | Vitest | `apps/server/src/**/*.integration.test.ts` | Planned (none) | +| Integration Tests | Vitest | `apps/server/src/**/*.integration.test.ts` | Active (DB) | --- @@ -160,8 +160,34 @@ npm run ci:local npm run test -w @meetropolis/server npm run test -w @meetropolis/web npm run test -w @meetropolis/shared + +# Server tests that need a migrated database (see "Database Tests") +npm run test:db -w @meetropolis/server +``` + +### Database Tests + +`npm test` in `apps/server` never needs a database. Tests that need a +migrated PostgreSQL database run in their own Vitest projects through +`npm run test:db`: + +- File names end in `.integration.test.ts`. Exceptions are listed in + `databaseTestFiles` in `apps/server/vitest.config.ts`. +- `DATABASE_URL` must point at a migrated, disposable test database. Without + it the run fails at once with a clear message; nothing is skipped. +- The files run one at a time. Files with database-wide effects (triggers on + shared tables, deletes without a tenant filter) belong in + `exclusiveTestFiles` and run last. + +```bash +# Example with a local throwaway database +export DATABASE_URL=postgresql://user:password@localhost:5432/meetropolis_test +(cd apps/server && npx prisma migrate deploy) +npm run test:db -w @meetropolis/server ``` +Never point `DATABASE_URL` at a database whose data you want to keep. + --- ## 4. Mocking Strategies diff --git a/apps/npc-service/package.json b/apps/npc-service/package.json index 753e0a30..e60f049d 100644 --- a/apps/npc-service/package.json +++ b/apps/npc-service/package.json @@ -8,7 +8,8 @@ "dev": "tsx src/index.ts", "start": "node --enable-source-maps dist/index.js", "build": "tsc -p tsconfig.json", - "typecheck": "tsc -p tsconfig.json --noEmit" + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run --config vitest.config.ts" }, "dependencies": { "@meetropolis/shared": "*", diff --git a/apps/npc-service/src/commandSchemas.ts b/apps/npc-service/src/commandSchemas.ts new file mode 100644 index 00000000..bf9c50df --- /dev/null +++ b/apps/npc-service/src/commandSchemas.ts @@ -0,0 +1,115 @@ +import { z } from 'zod'; + +const MAX_IDENTIFIER_LENGTH = 128; +const MAX_NAME_LENGTH = 200; +const MAX_AVATAR_ID_LENGTH = 256; +const MAX_URL_LENGTH = 512; +const MAX_CREDENTIAL_LENGTH = 512; +const MAX_STORAGE_PATH_LENGTH = 512; +const MAX_MIME_TYPE_LENGTH = 128; +const MAX_MOVE_SPEED = 1000; + +const MIME_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*\/[a-zA-Z0-9+.-]+$/; +const WINDOWS_DRIVE_PATTERN = /^[a-zA-Z]:/; + +const identifier = z.string().min(1).max(MAX_IDENTIFIER_LENGTH); +export const tenantSlug = z.string().min(1).max(MAX_IDENTIFIER_LENGTH); +const finiteNumber = z.number().finite(); +const strictBoolean = z.boolean(); +const npcDirection = z.enum(['up', 'down', 'left', 'right']); + +function serviceUrl(protocols: readonly string[]): z.ZodString { + return z + .string() + .min(1) + .max(MAX_URL_LENGTH) + .refine((value) => { + try { + return protocols.includes(new URL(value).protocol); + } catch { + return false; + } + }); +} + +function isConfinedMediaPath(value: string): boolean { + if (value.startsWith('/') || value.startsWith('\\') || WINDOWS_DRIVE_PATTERN.test(value)) { + return false; + } + return value + .split('/') + .every((segment) => segment.length > 0 && segment !== '.' && segment !== '..' && !segment.includes('\\')); +} + +const npcDefinition = z.object({ + id: identifier, + tenantId: identifier, + identity: identifier, + name: z.string().min(1).max(MAX_NAME_LENGTH), + avatarId: z.string().min(1).max(MAX_AVATAR_ID_LENGTH), + spawnX: finiteNumber, + spawnY: finiteNumber, + spawnDirection: npcDirection, + enabled: strictBoolean, + showBadge: strictBoolean, + mapName: z.string().min(1).max(MAX_NAME_LENGTH).nullish(), + config: z.record(z.string(), z.unknown()).nullish(), +}); + +export const spawnCommand = z.object({ + npc: npcDefinition, + tenantSlug, + serverUrl: serviceUrl(['http:', 'https:']), + livekitUrl: serviceUrl(['ws:', 'wss:']), + livekitApiKey: z.string().min(1).max(MAX_CREDENTIAL_LENGTH), + livekitApiSecret: z.string().min(1).max(MAX_CREDENTIAL_LENGTH), +}); + +export const despawnCommand = z.object({ + identity: identifier, + tenantSlug, +}); + +export const tenantField = z.object({ + tenantSlug: tenantSlug.optional(), +}); + +const movePayload = z.object({ + x: finiteNumber, + y: finiteNumber, + speed: z.number().finite().positive().max(MAX_MOVE_SPEED).optional(), +}); + +const mediaPayload = z.object({ + mediaFileId: z.string().min(1).max(MAX_IDENTIFIER_LENGTH), + loop: strictBoolean.optional(), + storagePath: z + .string() + .min(1) + .max(MAX_STORAGE_PATH_LENGTH) + .refine(isConfinedMediaPath) + .optional(), + mimeType: z.string().min(1).max(MAX_MIME_TYPE_LENGTH).regex(MIME_TYPE_PATTERN).optional(), +}); + +const dndPayload = z.object({ + dnd: strictBoolean, +}); + +const avatarPayload = z.object({ + avatarId: z.string().min(1).max(MAX_AVATAR_ID_LENGTH), +}); + +export const roomCommand = z.discriminatedUnion('action', [ + z.object({ action: z.literal('move'), payload: movePayload }), + z.object({ action: z.literal('stop_movement') }), + z.object({ action: z.literal('play_audio'), payload: mediaPayload }), + z.object({ action: z.literal('play_video'), payload: mediaPayload }), + z.object({ action: z.literal('play_screenshare'), payload: mediaPayload }), + z.object({ action: z.literal('stop_media') }), + z.object({ action: z.literal('set_dnd'), payload: dndPayload }), + z.object({ action: z.literal('set_avatar'), payload: avatarPayload }), +]); + +export type ValidatedSpawnCommand = z.infer; +export type ValidatedRoomCommand = z.infer; diff --git a/apps/npc-service/src/config.ts b/apps/npc-service/src/config.ts index e4e1827a..81bb49f2 100644 --- a/apps/npc-service/src/config.ts +++ b/apps/npc-service/src/config.ts @@ -1,10 +1,26 @@ +// Comparison constant only: this value never passes validation. +const KNOWN_DEFAULT_SECRET = 'dev-npc-secret'; + +const MIN_SECRET_LENGTH = 32; + +function readNpcServiceSecret(): string { + const raw = process.env.NPC_SERVICE_SECRET; + if (raw === undefined || raw.length === 0) { + throw new Error('NPC_SERVICE_SECRET is missing: set it to a value of at least 32 characters.'); + } + if (raw.trim().length === 0 || raw === KNOWN_DEFAULT_SECRET || raw.length < MIN_SECRET_LENGTH) { + throw new Error('NPC_SERVICE_SECRET is invalid: provide at least 32 characters, not the documented placeholder.'); + } + return raw; +} + export const config = { port: Number(process.env.PORT || 3100), serverUrl: process.env.SERVER_URL || 'http://server:2567', livekitUrl: process.env.LIVEKIT_URL || 'ws://livekit:7880', livekitApiKey: process.env.LIVEKIT_API_KEY || 'devkey', livekitApiSecret: process.env.LIVEKIT_API_SECRET || 'secret', - npcServiceSecret: process.env.NPC_SERVICE_SECRET || 'dev-npc-secret', + npcServiceSecret: readNpcServiceSecret(), npcMediaDir: process.env.NPC_MEDIA_DIR || '/data/npc-media', logLevel: process.env.LOG_LEVEL || 'info', } as const; diff --git a/apps/npc-service/src/httpApi.ts b/apps/npc-service/src/httpApi.ts index ea76da26..c7673c04 100644 --- a/apps/npc-service/src/httpApi.ts +++ b/apps/npc-service/src/httpApi.ts @@ -1,19 +1,27 @@ -import type { Request, Response, NextFunction, Application } from 'express'; -import type { NpcSpawnCommand, NpcRoomCommand } from '@meetropolis/shared'; +import crypto from 'crypto'; +import express, { type Application, type NextFunction, type Request, type Response } from 'express'; +import type { NpcRoomCommand, NpcSpawnCommand } from '@meetropolis/shared'; +import { despawnCommand, roomCommand, spawnCommand, tenantSlug } from './commandSchemas.js'; import { config } from './config.js'; import { botManager } from './botManager.js'; import { logger } from './index.js'; -interface DespawnBody { - identity?: string; - tenantSlug?: string; -} +const NPC_BODY_LIMIT_BYTES = 16 * 1024; -type CommandBody = Partial & { tenantSlug?: string }; +function timingSafeEqualStrings(a: string, b: string): boolean { + const aBuf = Buffer.from(a, 'utf8'); + const bBuf = Buffer.from(b, 'utf8'); + return aBuf.length === bBuf.length && crypto.timingSafeEqual(aBuf, bBuf); +} function authMiddleware(req: Request, res: Response, next: NextFunction): void { - const secret = req.headers['x-npc-secret'] as string; - if (secret !== config.npcServiceSecret) { + const distinct = req.headersDistinct?.['x-npc-secret']; + const raw = req.headers['x-npc-secret']; + if (!Array.isArray(distinct) || distinct.length !== 1 || typeof raw !== 'string') { + res.status(401).json({ error: 'unauthorized' }); + return; + } + if (!timingSafeEqualStrings(raw, config.npcServiceSecret)) { res.status(401).json({ error: 'unauthorized' }); return; } @@ -21,12 +29,12 @@ function authMiddleware(req: Request, res: Response, next: NextFunction): void { } function handleSpawn(req: Request, res: Response): void { - const body = req.body as Partial | undefined; - if (!body?.npc?.identity || !body?.tenantSlug) { + const parsed = spawnCommand.safeParse(req.body); + if (!parsed.success) { res.status(400).json({ error: 'invalid_payload' }); return; } - const command = body as NpcSpawnCommand; + const command: NpcSpawnCommand = parsed.data; botManager .spawn(command) .then(() => { @@ -42,14 +50,14 @@ function handleSpawn(req: Request, res: Response): void { } function handleDespawn(req: Request, res: Response): void { - const body = (req.body || {}) as DespawnBody; - const { identity, tenantSlug } = body; - if (!identity || !tenantSlug) { - res.status(400).json({ error: 'identity and tenantSlug required' }); + const parsed = despawnCommand.safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'invalid_payload' }); return; } + const { identity, tenantSlug: slug } = parsed.data; botManager - .despawn(tenantSlug, identity) + .despawn(slug, identity) .then(() => { res.json({ ok: true }); }) @@ -62,17 +70,40 @@ function handleDespawn(req: Request, res: Response): void { }); } +function resolveTenantSlug(req: Request): string | null { + const queryTenant = req.query.tenant; + if (Array.isArray(queryTenant)) return null; + if (queryTenant !== undefined && typeof queryTenant !== 'string') return null; + const bodyTenant = (req.body as { tenantSlug?: unknown } | undefined)?.tenantSlug; + if (bodyTenant !== undefined && typeof bodyTenant !== 'string') return null; + if (queryTenant !== undefined && bodyTenant !== undefined && queryTenant !== bodyTenant) { + return null; + } + const merged = queryTenant ?? bodyTenant; + if (merged === undefined || !tenantSlug.safeParse(merged).success) return null; + return merged; +} + function handleCommand(req: Request, res: Response): void { const identityParam = req.params.identity; - const identity = Array.isArray(identityParam) ? (identityParam[0] ?? '') : (identityParam ?? ''); - const body = (req.body || {}) as CommandBody; - const tenantSlug = (req.query.tenant as string) || body.tenantSlug; - if (!tenantSlug) { - res.status(400).json({ error: 'tenantSlug required' }); + if (typeof identityParam !== 'string' || identityParam.length === 0) { + res.status(400).json({ error: 'invalid_payload' }); + return; + } + const slug = resolveTenantSlug(req); + if (slug === null) { + res.status(400).json({ error: 'invalid_payload' }); + return; + } + const body = (req.body ?? {}) as { action?: unknown; payload?: unknown }; + const parsed = roomCommand.safeParse({ action: body.action, payload: body.payload }); + if (!parsed.success) { + res.status(400).json({ error: 'invalid_payload' }); return; } + const command: NpcRoomCommand = parsed.data; try { - botManager.sendCommand(tenantSlug, identity, body as NpcRoomCommand); + botManager.sendCommand(slug, identityParam, command); res.json({ ok: true }); } catch (e: unknown) { logger.error({ err: e }, '[HTTP] command error'); @@ -89,6 +120,7 @@ function handleGetAll(_req: Request, res: Response): void { export function registerHttpApi(app: Application): void { app.use('/bots', authMiddleware); + app.use('/bots', express.json({ limit: NPC_BODY_LIMIT_BYTES })); app.post('/bots/spawn', handleSpawn); app.post('/bots/despawn', handleDespawn); diff --git a/apps/npc-service/src/index.ts b/apps/npc-service/src/index.ts index ac24a2a2..b2a6ec57 100644 --- a/apps/npc-service/src/index.ts +++ b/apps/npc-service/src/index.ts @@ -13,7 +13,9 @@ interface NpcListEntry extends NpcDefinition { export const logger = pino({ level: config.logLevel }); const app = express(); -app.use(express.json()); +// The config import above already enforces the service secret before the +// listener, timers, or auto-respawn start. JSON parsing stays scoped to /bots +// behind authentication (see registerHttpApi). // Health check app.get('/healthz', (_req, res) => { diff --git a/apps/npc-service/src/npcHttpApi.test.ts b/apps/npc-service/src/npcHttpApi.test.ts new file mode 100644 index 00000000..11879c1e --- /dev/null +++ b/apps/npc-service/src/npcHttpApi.test.ts @@ -0,0 +1,296 @@ +import { spawn, type ChildProcess } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { connect } from 'node:net'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const serviceDir = dirname(dirname(fileURLToPath(import.meta.url))); +const authHeader = 'x-npc-secret'; +const validSecret = `test-secret-${'x'.repeat(52)}`; +const testPortKey = 'NPC_TEST_PORT'; + +function getTestPort(): number { + const raw = process.env[testPortKey]; + const port = raw === undefined ? Number.NaN : Number(raw); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`${testPortKey} must be set to an integer between 1 and 65535`); + } + return port; +} + +function assertPortFree(port: number): Promise { + return new Promise((resolve, reject) => { + const socket = connect({ host: '127.0.0.1', port }); + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error(`test port ${port} did not refuse a connection in time`)); + }, 5000); + if (typeof timer.unref === 'function') timer.unref(); + socket.once('connect', () => { + clearTimeout(timer); + socket.destroy(); + reject(new Error(`test port ${port} is already in use; refusing a foreign process`)); + }); + socket.once('error', (error) => { + clearTimeout(timer); + if ((error as NodeJS.ErrnoException).code === 'ECONNREFUSED') { + resolve(); + } else { + reject(error); + } + }); + }); +} + +function resolveRunner(): string { + const scopedRequire = createRequire(join(serviceDir, 'package.json')); + const packagePath = scopedRequire.resolve('tsx/package.json'); + const cliPath = join(dirname(packagePath), 'dist', 'cli.mjs'); + if (!existsSync(cliPath)) { + throw new Error('tsx runner not found below the service directory'); + } + return cliPath; +} + +interface RunningService { + baseUrl: string; + stop: () => Promise; +} + +async function waitForHealth(baseUrl: string): Promise { + for (let attempt = 0; attempt < 240; attempt += 1) { + try { + const res = await fetch(`${baseUrl}/healthz`); + if (res.ok) return; + } catch { + // Not listening yet; retry below. + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error(`service did not become ready at ${baseUrl}`); +} + +function stopChild(child: ChildProcess): Promise { + if (child.exitCode !== null) return Promise.resolve(); + return new Promise((resolve) => { + const killTimer = setTimeout(() => { + child.kill('SIGKILL'); + const exitTimer = setTimeout(resolve, 5000); + if (typeof exitTimer.unref === 'function') exitTimer.unref(); + child.once('exit', () => { + clearTimeout(exitTimer); + resolve(); + }); + }, 10000); + if (typeof killTimer.unref === 'function') killTimer.unref(); + child.once('exit', () => { + clearTimeout(killTimer); + resolve(); + }); + child.kill('SIGTERM'); + }); +} + +async function startService(): Promise { + const port = getTestPort(); + await assertPortFree(port); + const child = spawn(process.execPath, [resolveRunner(), 'src/index.ts'], { + cwd: serviceDir, + env: { + ...process.env, + NODE_ENV: 'production', + PORT: String(port), + NPC_SERVICE_SECRET: validSecret, + SERVER_URL: 'http://127.0.0.1:9', + LOG_LEVEL: 'fatal', + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + child.stdout?.on('data', () => { + // Drain output so a chatty child never blocks on a full pipe. + }); + child.stderr?.on('data', () => { + // Drain output so a chatty child never blocks on a full pipe. + }); + const baseUrl = `http://127.0.0.1:${port}`; + await waitForHealth(baseUrl); + return { baseUrl, stop: () => stopChild(child) }; +} + +function postJson( + baseUrl: string, + path: string, + body: unknown, + secret: string | null = validSecret, +): Promise { + const headers: Record = { 'content-type': 'application/json' }; + if (secret !== null) headers[authHeader] = secret; + return fetch(`${baseUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body) }); +} + +describe('npc service command validation', () => { + it('rejects an incomplete spawn payload before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/spawn', { + npc: { identity: 'incomplete-spawn-probe' }, + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a mistyped despawn payload before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/despawn', { + identity: 123, + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects an unknown command action before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-unknown-action/command', { + action: 'teleport', + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects an invalid move payload before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-bad-move/command', { + action: 'move', + payload: { x: 'far', y: 10 }, + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a non-boolean dnd payload before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-bad-dnd/command', { + action: 'set_dnd', + payload: { dnd: 'yes' }, + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects an empty avatar payload before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-bad-avatar/command', { + action: 'set_avatar', + payload: { avatarId: '' }, + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a media payload outside the media root before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-bad-media/command', { + action: 'play_audio', + payload: { mediaFileId: 'clip', storagePath: '../../outside.mp3' }, + tenantSlug: 'probe-tenant', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a repeated query tenant before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-multi-tenant/command?tenant=alpha&tenant=beta', { + action: 'stop_movement', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a conflicting query and body tenant before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-split-tenant/command?tenant=alpha', { + action: 'stop_movement', + tenantSlug: 'beta', + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects an overlong tenant slug before execution', async () => { + const service = await startService(); + try { + const res = await postJson(service.baseUrl, '/bots/probe-long-tenant/command', { + action: 'stop_movement', + tenantSlug: 'a'.repeat(129), + }); + expect(res.status).toBe(400); + } finally { + await service.stop(); + } + }, 120000); + + it('accepts valid auth for status reads', async () => { + const service = await startService(); + try { + const res = await fetch(`${service.baseUrl}/bots`, { headers: { [authHeader]: validSecret } }); + expect(res.status).toBe(200); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a wrong secret', async () => { + const service = await startService(); + try { + const res = await fetch(`${service.baseUrl}/bots`, { headers: { [authHeader]: 'wrong-secret' } }); + expect(res.status).toBe(401); + } finally { + await service.stop(); + } + }, 120000); + + it('rejects a missing secret', async () => { + const service = await startService(); + try { + const res = await fetch(`${service.baseUrl}/bots`); + expect(res.status).toBe(401); + } finally { + await service.stop(); + } + }, 120000); +}); diff --git a/apps/npc-service/src/npcStartupSecret.test.ts b/apps/npc-service/src/npcStartupSecret.test.ts new file mode 100644 index 00000000..73b4e831 --- /dev/null +++ b/apps/npc-service/src/npcStartupSecret.test.ts @@ -0,0 +1,84 @@ +import { spawn } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const moduleDir = dirname(fileURLToPath(import.meta.url)); +const configPath = join(moduleDir, 'config.ts'); +const secretKey = 'NPC_SERVICE_SECRET'; + +function readKnownDefault(): string { + const source = readFileSync(configPath, 'utf8'); + const direct = source.match(/KNOWN_DEFAULT_SECRET\s*=\s*'([^']+)'/); + if (direct) return direct[1]; + const fallback = source.match(/NPC_SERVICE_SECRET[^\n]*\|\|\s*'([^']+)'/); + if (fallback) return fallback[1]; + throw new Error('known default placeholder not found in config source'); +} + +interface StartupProbe { + code: number | null; + output: string; +} + +function probeStartup(secret: string | undefined, nodeEnv: string): Promise { + const loader = + `import(${JSON.stringify(pathToFileURL(configPath).href)}).then(` + + `() => console.log('config loaded'),` + + `(error) => { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); });`; + const env: NodeJS.ProcessEnv = { ...process.env, NODE_ENV: nodeEnv }; + if (secret === undefined) { + delete env[secretKey]; + } else { + env[secretKey] = secret; + } + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['--input-type=module', '-e', loader], { + env, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let output = ''; + child.stdout?.on('data', (chunk) => { + output += String(chunk); + }); + child.stderr?.on('data', (chunk) => { + output += String(chunk); + }); + child.on('error', reject); + const timer = setTimeout(() => { + child.kill('SIGKILL'); + reject(new Error('config probe timed out')); + }, 20000); + if (typeof timer.unref === 'function') timer.unref(); + child.on('close', (code) => { + clearTimeout(timer); + resolve({ code, output }); + }); + }); +} + +describe('npc service startup secret', () => { + const knownDefault = readKnownDefault(); + const cases: Array<{ name: string; secret: string | undefined }> = [ + { name: 'rejects a missing secret', secret: undefined }, + { name: 'rejects an empty secret', secret: '' }, + { name: 'rejects a whitespace secret', secret: ' \t ' }, + { name: 'rejects the known default secret', secret: knownDefault }, + { name: 'rejects a short secret', secret: 'x'.repeat(31) }, + ]; + for (const mode of ['development', 'production']) { + describe(`in ${mode} mode`, () => { + for (const entry of cases) { + it(entry.name, async () => { + const probe = await probeStartup(entry.secret, mode); + expect(probe.code).not.toBe(0); + expect(probe.output).toContain(secretKey); + if (entry.secret) { + expect(probe.output).not.toContain(entry.secret); + } + }, 30000); + } + }); + } +}); diff --git a/apps/npc-service/tsconfig.lint.json b/apps/npc-service/tsconfig.lint.json index 40e72b9d..5102fa6e 100644 --- a/apps/npc-service/tsconfig.lint.json +++ b/apps/npc-service/tsconfig.lint.json @@ -3,6 +3,6 @@ "compilerOptions": { "noEmit": true }, - "include": ["src"], + "include": ["src", "vitest.config.ts"], "exclude": ["dist", "node_modules"] } diff --git a/apps/npc-service/vitest.config.ts b/apps/npc-service/vitest.config.ts new file mode 100644 index 00000000..b0b70489 --- /dev/null +++ b/apps/npc-service/vitest.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + environment: 'node', + include: ['src/**/*.test.ts'], + exclude: ['**/node_modules/**', '**/dist/**'], + testTimeout: 60000, + hookTimeout: 30000, + fileParallelism: false, + }, +}); diff --git a/apps/server/entrypoint.sh b/apps/server/entrypoint.sh index dcd213ff..977de8f5 100644 --- a/apps/server/entrypoint.sh +++ b/apps/server/entrypoint.sh @@ -7,6 +7,16 @@ set -e # container. PRISMA_SCHEMA="${PRISMA_SCHEMA:-/workspace/apps/server/prisma/schema.prisma}" +# Production credential policy: same checker the server runs at startup. +# Runs before migrations, seeding, or the server command. Fails closed when +# the compiled checker is missing, so a broken build never starts silently. +if [ -f dist/ops/startupCredentials.js ]; then + node dist/ops/startupCredentials.js || exit 1 +else + echo '[entrypoint] credential checker missing at dist/ops/startupCredentials.js; refusing to start' >&2 + exit 1 +fi + if [ "$RUN_MIGRATIONS" = "true" ]; then echo "[entrypoint] prisma migrate deploy --schema $PRISMA_SCHEMA" npx prisma migrate deploy --schema "$PRISMA_SCHEMA" diff --git a/apps/server/package.json b/apps/server/package.json index 29504baa..f56796d4 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -10,7 +10,8 @@ "build": "tsc -p tsconfig.json && node ./scripts/copy-generated.mjs && node ./scripts/copy-catalog.mjs", "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.seed.json", "start": "node dist/index.js", - "test": "vitest run", + "test": "vitest run --project server", + "test:db": "vitest run --project server-db --project server-db-exclusive", "map:import:v2": "tsx src/scripts/importMapV2.ts", "map:atelier:migrate": "tsx src/scripts/migrateAtelierStandardMap.ts", "map:autotiles:migrate": "tsx src/scripts/migrateAutotilePalettes.ts", diff --git a/apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql b/apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql new file mode 100644 index 00000000..441fbde4 --- /dev/null +++ b/apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql @@ -0,0 +1,71 @@ +-- CreateEnum +CREATE TYPE "DeletionJournalStatus" AS ENUM ('blocked', 'requested', 'db_deleted', 'cleanup_pending', 'completed'); + +-- CreateEnum +CREATE TYPE "DeletionTaskStatus" AS ENUM ('pending', 'leased', 'retry', 'manual_required', 'done', 'failed'); + +-- CreateTable +CREATE TABLE "DeletionJournal" ( + "id" TEXT NOT NULL, + "idempotencyKey" TEXT NOT NULL, + "generation" BIGSERIAL NOT NULL, + "scope" TEXT NOT NULL, + "tenantRef" TEXT, + "accountRefs" TEXT[] DEFAULT ARRAY[]::TEXT[], + "objectRefs" TEXT[] DEFAULT ARRAY[]::TEXT[], + "policyVersion" TEXT NOT NULL, + "requestedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "dbDeletedAt" TIMESTAMP(3), + "accessStatus" VARCHAR(64) NOT NULL DEFAULT 'pending', + "cleanupStatus" VARCHAR(64) NOT NULL DEFAULT 'pending', + "status" "DeletionJournalStatus" NOT NULL DEFAULT 'requested', + "completedAt" TIMESTAMP(3), + "journalUntil" TIMESTAMP(3) NOT NULL, + "lastErrorCode" VARCHAR(64), + + CONSTRAINT "DeletionJournal_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "DeletionTask" ( + "id" TEXT NOT NULL, + "journalId" TEXT NOT NULL, + "kind" VARCHAR(64) NOT NULL, + "targetSystem" VARCHAR(64) NOT NULL, + "objectId" TEXT NOT NULL, + "objectGeneration" TEXT NOT NULL, + "storageKey" TEXT, + "dedupeKey" TEXT NOT NULL, + "status" "DeletionTaskStatus" NOT NULL DEFAULT 'pending', + "attempts" INTEGER NOT NULL DEFAULT 0, + "nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "leaseToken" TEXT, + "leaseUntil" TIMESTAMP(3), + "lastErrorCode" VARCHAR(64), + "completedAt" TIMESTAMP(3), + "receiptCode" VARCHAR(64), + + CONSTRAINT "DeletionTask_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "DeletionJournal_idempotencyKey_key" ON "DeletionJournal"("idempotencyKey"); + +-- CreateIndex +CREATE UNIQUE INDEX "DeletionJournal_generation_key" ON "DeletionJournal"("generation"); + +-- CreateIndex +CREATE INDEX "DeletionJournal_status_journalUntil_idx" ON "DeletionJournal"("status", "journalUntil"); + +-- CreateIndex +CREATE UNIQUE INDEX "DeletionTask_dedupeKey_key" ON "DeletionTask"("dedupeKey"); + +-- CreateIndex +CREATE INDEX "DeletionTask_journalId_idx" ON "DeletionTask"("journalId"); + +-- CreateIndex +CREATE INDEX "DeletionTask_status_nextAttemptAt_idx" ON "DeletionTask"("status", "nextAttemptAt"); + +-- AddForeignKey +ALTER TABLE "DeletionTask" ADD CONSTRAINT "DeletionTask_journalId_fkey" FOREIGN KEY ("journalId") REFERENCES "DeletionJournal"("id") ON DELETE RESTRICT ON UPDATE RESTRICT; + diff --git a/apps/server/prisma/schema.prisma b/apps/server/prisma/schema.prisma index 77a81583..b6625916 100644 --- a/apps/server/prisma/schema.prisma +++ b/apps/server/prisma/schema.prisma @@ -588,5 +588,68 @@ model NpcMediaFile { @@index([npcId]) } +enum DeletionJournalStatus { + blocked + requested + db_deleted + cleanup_pending + completed +} + +enum DeletionTaskStatus { + pending + leased + retry + manual_required + done + failed +} + +// References intentionally survive removal of tenant and user rows. +model DeletionJournal { + id String @id @default(cuid()) + idempotencyKey String @unique + generation BigInt @unique @default(autoincrement()) + scope String + tenantRef String? + accountRefs String[] @default([]) + objectRefs String[] @default([]) + policyVersion String + requestedAt DateTime @default(now()) + dbDeletedAt DateTime? + accessStatus String @default("pending") @db.VarChar(64) + cleanupStatus String @default("pending") @db.VarChar(64) + status DeletionJournalStatus @default(requested) + completedAt DateTime? + journalUntil DateTime + lastErrorCode String? @db.VarChar(64) + tasks DeletionTask[] + + @@index([status, journalUntil]) +} + +model DeletionTask { + id String @id @default(cuid()) + journalId String + journal DeletionJournal @relation(fields: [journalId], references: [id], onDelete: Restrict, onUpdate: Restrict) + kind String @db.VarChar(64) + targetSystem String @db.VarChar(64) + objectId String + objectGeneration String + storageKey String? + dedupeKey String @unique + status DeletionTaskStatus @default(pending) + attempts Int @default(0) + nextAttemptAt DateTime @default(now()) + leaseToken String? + leaseUntil DateTime? + lastErrorCode String? @db.VarChar(64) + completedAt DateTime? + receiptCode String? @db.VarChar(64) + + @@index([journalId]) + @@index([status, nextAttemptAt]) +} + // Optional commercial modules can extend this schema at build time via // their own tooling. See docs/enterprise.md. diff --git a/apps/server/prisma/seed.ts b/apps/server/prisma/seed.ts index c8c07dbc..d4be2961 100644 --- a/apps/server/prisma/seed.ts +++ b/apps/server/prisma/seed.ts @@ -3,12 +3,16 @@ import path from 'path'; import { fileURLToPath } from 'url'; import { PrismaClient } from '../src/generated/prisma/index.js'; import { PrismaPg } from '@prisma/adapter-pg'; -import bcrypt from 'bcryptjs'; +import { applySeedAdminCredentials, enforceSeedAdminCredentials } from '../src/ops/seedAdminCredentials.js'; import { importTmjIntoMap } from '../src/scripts/importMapV2.lib.js'; import { resolveTemplateTenantSlug } from '../src/services/templateTenant.js'; import { ATELIER_STANDARD_MAP_FILE, ATELIER_STANDARD_MAP_NAME } from '../src/services/atelierStandardMap.js'; import { ATELIER_PACK_UUID, loadAtelierProductData } from './atelierCatalog.js'; +// Production seed-admin policy: fail closed on missing or public-template +// credentials before the driver adapter is constructed and before any write. +enforceSeedAdminCredentials(process.env); + // Prisma 7 requires a driver-adapter. The seed runs via `prisma db seed` // (outside the application's normal entrypoint) so we construct one here. const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }); @@ -123,25 +127,7 @@ async function main() { update: {}, }); - // Seed Root Admin (env-configurable) - const adminEmail = process.env.SEED_ADMIN_EMAIL || 'admin@meetropolis.local'; - const adminPass = process.env.SEED_ADMIN_PASSWORD || 'admin123'; - const adminName = process.env.SEED_ADMIN_NAME || 'Root Admin'; - - let admin = await prisma.user.findUnique({ where: { email: adminEmail } }); - const hash = await bcrypt.hash(adminPass, 10); - if (!admin) { - admin = await prisma.user.create({ - data: { email: adminEmail, name: adminName, passwordHash: hash, emailVerifiedAt: new Date() }, - }); - - console.log('Seeded admin user:', adminEmail); - } else { - // Update password hash (so seed always sets the expected password) - admin = await prisma.user.update({ where: { email: adminEmail }, data: { passwordHash: hash } }); - - console.log('Admin user exists, password updated:', adminEmail); - } + const admin = await applySeedAdminCredentials(prisma, process.env); // Ensure memberships if (admin) { @@ -436,14 +422,14 @@ async function main() { } // Create a default invite (for onboarding teammates) - const existingInvite = await prisma.invite.findFirst({ where: { email: adminEmail, tenantId: def.id } }); + const existingInvite = await prisma.invite.findFirst({ where: { email: admin.email, tenantId: def.id } }); if (!existingInvite) { const code = Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10); await prisma.invite.create({ - data: { code, email: adminEmail, createdBy: admin.id, tenantId: def.id, role: 'admin' as any }, + data: { code, email: admin.email, createdBy: admin.id, tenantId: def.id, role: 'admin' as any }, }); - console.log('Seeded invite for admin email (can be shared to teammates):', code); + console.log('Seeded invite for admin email'); } } diff --git a/apps/server/src/adminLoader.ts b/apps/server/src/adminLoader.ts index f2d3be6d..ab12985c 100644 --- a/apps/server/src/adminLoader.ts +++ b/apps/server/src/adminLoader.ts @@ -1,8 +1,35 @@ import type { Application, Request, Response } from 'express'; -import type { PrismaClient } from './generated/prisma/index.js'; +import type { Prisma, PrismaClient } from './generated/prisma/index.js'; +import type { + TenantDeletionContext, + TenantDeletionOptions, + TenantDeletionPlanInput, + TenantDeletionPreparationContext, + TenantDeletionTaskPlan, +} from './services/tenantDeletionContract.js'; +import { + TENANT_DELETION_PROTOCOL, + TenantDeletionContractError, + TenantDeletionJournalUnavailableError, + assertTenantDeletionProtocol, +} from './services/tenantDeletionContract.js'; import { z } from 'zod'; import { logger } from './logger.js'; +export { + TENANT_DELETION_PROTOCOL, + TenantDeletionContractError, + TenantDeletionJournalUnavailableError, + assertTenantDeletionProtocol, +}; +export type { + TenantDeletionContext, + TenantDeletionOptions, + TenantDeletionPlanInput, + TenantDeletionPreparationContext, + TenantDeletionTaskPlan, +}; + /** * Expected `version` of the shared `@meetropolis/billing` module. * @@ -104,6 +131,17 @@ export interface AdminEnterpriseModule { // optional config field does not change the module's function surface, so // it stays within schema version 2 (no version bump required). isNativeClientRequest?: (req: Request) => boolean; + // Optional: resolves the managed tenant-deletion plan for one tenant, + // persisting the intent to the file journal first. The host wires a + // cached resolver only when a journal directory is configured; without + // it the field stays undefined and the route answers 409. Optional + // field, no version bump. + resolveTenantDeletionPlan?: ( + tx: Prisma.TransactionClient, + input: { tenantId: string; transactionTime: Date }, + ) => Promise; + /** Optional: true while the NPC media folder of a deleted tenant with this slug is not cleared yet. */ + isTenantSlugReserved?: (slug: string) => Promise; // Optional: host-callback returning the telemetry activation block for // GET /public/config ({ enabled, environment }) or null when telemetry is // off. The enterprise /public/config handler wins over the OSS fallback @@ -113,6 +151,10 @@ export interface AdminEnterpriseModule { // an optional config field keeps the function surface unchanged, so no // schema version bump is required. getTelemetryPublicConfig?: () => { enabled: boolean; environment: string } | null; + deleteTenantWithMembers: ( + tenantId: string, + options?: TenantDeletionOptions, + ) => Promise<{ deletedAccounts: number }>; }, ): void; @@ -140,6 +182,7 @@ export interface AdminEnterpriseModule { }; requireSuperAdmin: (req: Request, prisma: PrismaClient) => Promise<{ userId: string } | null>; normalizeEmail: (email: string) => string; + removeMemberFromTenant: (params: { userId: string; tenantId: string }) => Promise<{ accountDeleted: boolean }>; }, ): void; @@ -177,6 +220,38 @@ export interface AdminEnterpriseModule { cacheTtlMs?: number; }, ): void; + + /** + * Managed deletion of one tenant outside the HTTP route, with the same + * guards and journal path as DELETE /admin/tenants/:id. Used by the restore + * replay tool. Optional: older enterprise builds do not export it. + */ + deleteManagedTenant?( + config: { + prisma: PrismaClient; + logger: { + info(obj: object): void; + error(obj: object): void; + warn(obj: object): void; + }; + deleteTenantWithMembers: ( + tenantId: string, + options?: TenantDeletionOptions, + ) => Promise<{ deletedAccounts: number }>; + resolveTenantDeletionPlan?: ( + tx: Prisma.TransactionClient, + input: { tenantId: string; transactionTime: Date }, + ) => Promise; + }, + id: string, + options: { actor: string }, + ): Promise<{ ok: true } | { ok: false; status: number; error: string }>; + + /** + * Codes of preconditions that must hold before a restored database may + * serve again; empty when none is open. Optional like deleteManagedTenant. + */ + pendingRestorePreconditions?(): string[]; } export const adminEnterpriseSchema = z.object({ @@ -190,6 +265,9 @@ export const adminEnterpriseSchema = z.object({ setupPackMarketplaceRoutes: z.function(), // Optional: older enterprise builds may not ship the desktop update routes. setupDesktopUpdateRoutes: z.function().optional(), + // Optional: restore replay hooks, absent in older enterprise builds. + deleteManagedTenant: z.function().optional(), + pendingRestorePreconditions: z.function().optional(), }); let cached: AdminEnterpriseModule | null = null; @@ -236,6 +314,9 @@ export async function getAdminEnterpriseModule(): Promise { + const captured: { config: object | undefined } = { config: undefined }; + const noop = (): void => undefined; + const billingFixture = { + version: 3 as const, + setupBillingRoutes: noop, + installEarlyMiddleware: noop, + getTrialStatus: noop, + startTrial: noop, + getDunningStatus: noop, + TRIAL_DAYS: 7, + GRACE_PERIOD_DAYS: 7, + CANCELLATION_DAYS: 14, + setupAdminRoutes: noop, + setupTenantAdminRoutes: (_app: unknown, config: object) => { + captured.config = config; + }, + setupPricingPlanRoutes: noop, + setupTenantUserRoutes: noop, + setupPackMarketplaceRoutes: noop, + setupDesktopUpdateRoutes: noop, + }; + return { captured, billingFixture }; +}); + +vi.mock('@meetropolis/billing', () => ({ + ...billingFixture, + default: billingFixture, +})); + +vi.mock('./db.js', () => ({ + createPrismaClient: () => ({}), +})); + +const { journalResolver } = vi.hoisted(() => ({ + journalResolver: vi.fn(), +})); + +// Der Resolver-Erzeuger ist die Verdrahtung, nicht die geprüfte Logik: er wird +// gezählt und steuerbar abgelehnt oder aufgelöst. +vi.mock('./services/tenantDeletionPlanning.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, createJournalPlanResolver: journalResolver }; +}); + +import { registerApi } from './api.js'; + +type ResolvePlan = (tx: unknown, input: { tenantId: string; transactionTime: Date }) => Promise; + +interface PlanInput { + idempotencyKey: string; + policyVersion: string; + journalUntil: Date; + tasks: unknown[]; +} + +function resolveTenantDeletionPlanOf(config: object): unknown { + return Reflect.get(config, 'resolveTenantDeletionPlan'); +} + +async function captureTenantAdminConfig(): Promise { + captured.config = undefined; + const app = express(); + app.use(cookieParser()); + app.use(express.json()); + await registerApi(app); + if (captured.config === undefined) { + throw new Error('enterprise admin fixture did not receive tenant admin config'); + } + return captured.config; +} + +const journalDirs: string[] = []; +const envSnapshot = { + journalDir: process.env.DELETION_JOURNAL_DIR, + retentionDays: process.env.BACKUP_RETENTION_DAYS, +}; + +function restoreDeletionEnv(): void { + if (envSnapshot.journalDir === undefined) delete process.env.DELETION_JOURNAL_DIR; + else process.env.DELETION_JOURNAL_DIR = envSnapshot.journalDir; + if (envSnapshot.retentionDays === undefined) delete process.env.BACKUP_RETENTION_DAYS; + else process.env.BACKUP_RETENTION_DAYS = envSnapshot.retentionDays; +} + +afterEach(async () => { + restoreDeletionEnv(); + captured.config = undefined; + const dirs = journalDirs.splice(0); + await Promise.all(dirs.map((dir) => fs.rm(dir, { recursive: true, force: true }))); +}); + +describe('enterprise admin deletion plan config', () => { + it('W1 registerApi passes resolveTenantDeletionPlan as a function when the journal directory is configured', async () => { + const journalDir = await fs.mkdtemp(path.join(os.tmpdir(), 'deletion-journal-')); + journalDirs.push(journalDir); + process.env.DELETION_JOURNAL_DIR = journalDir; + process.env.BACKUP_RETENTION_DAYS = '14'; + + const config = await captureTenantAdminConfig(); + expect(typeof resolveTenantDeletionPlanOf(config)).toBe('function'); + }); + + it('W2 registerApi leaves resolveTenantDeletionPlan undefined without DELETION_JOURNAL_DIR', async () => { + delete process.env.DELETION_JOURNAL_DIR; + process.env.BACKUP_RETENTION_DAYS = '14'; + + const config = await captureTenantAdminConfig(); + expect(resolveTenantDeletionPlanOf(config)).toBeUndefined(); + }); + + it('W3 two concurrent first calls create the resolver once and both get its result', async () => { + const journalDir = await fs.mkdtemp(path.join(os.tmpdir(), 'deletion-journal-')); + journalDirs.push(journalDir); + process.env.DELETION_JOURNAL_DIR = journalDir; + process.env.BACKUP_RETENTION_DAYS = '14'; + + const plan: PlanInput = { + idempotencyKey: 'w3-key', + policyVersion: 'w3-policy', + journalUntil: new Date('2026-12-01T00:00:00.000Z'), + tasks: [], + }; + const resolver = vi.fn(async () => plan); + journalResolver.mockReset(); + journalResolver.mockResolvedValue(resolver); + + const config = await captureTenantAdminConfig(); + const resolve = resolveTenantDeletionPlanOf(config); + expect(typeof resolve).toBe('function'); + if (typeof resolve !== 'function') return; + const call = resolve as unknown as ResolvePlan; + const input = { tenantId: 'w3-tenant', transactionTime: new Date('2026-11-08T00:00:00.000Z') }; + + const results = await Promise.all([call({}, input), call({}, input)]); + + expect(journalResolver).toHaveBeenCalledTimes(1); + expect(journalResolver).toHaveBeenCalledWith(expect.objectContaining({ journalDir })); + expect(results[0]).toEqual(plan); + expect(results[1]).toEqual(plan); + }); + + it('W4 a failed resolver creation returns undefined and the next call creates a new resolver', async () => { + const journalDir = await fs.mkdtemp(path.join(os.tmpdir(), 'deletion-journal-')); + journalDirs.push(journalDir); + process.env.DELETION_JOURNAL_DIR = journalDir; + process.env.BACKUP_RETENTION_DAYS = '14'; + + const plan: PlanInput = { + idempotencyKey: 'w4-key', + policyVersion: 'w4-policy', + journalUntil: new Date('2026-12-01T00:00:00.000Z'), + tasks: [], + }; + const resolver = vi.fn(async () => plan); + journalResolver.mockReset(); + journalResolver.mockRejectedValueOnce(new Error('journal unavailable')).mockResolvedValueOnce(resolver); + + const config = await captureTenantAdminConfig(); + const resolve = resolveTenantDeletionPlanOf(config); + expect(typeof resolve).toBe('function'); + if (typeof resolve !== 'function') return; + const call = resolve as unknown as ResolvePlan; + const input = { tenantId: 'w4-tenant', transactionTime: new Date('2026-11-08T00:00:00.000Z') }; + + const first = await call({}, input); + expect(first).toBeUndefined(); + expect(journalResolver).toHaveBeenCalledTimes(1); + + const second = await call({}, input); + expect(journalResolver).toHaveBeenCalledTimes(2); + expect(second).toEqual(plan); + }); +}); diff --git a/apps/server/src/api.ts b/apps/server/src/api.ts index 400fc6c5..95c0bc08 100644 --- a/apps/server/src/api.ts +++ b/apps/server/src/api.ts @@ -20,6 +20,7 @@ import { registerAdminMapRoutes } from './api/routes/adminMaps.js'; import { registerAdminPasswordResetRoutes } from './api/routes/admin.passwordReset.js'; import { copyMapToTenant } from './api/routes/adminMaps.js'; import { registerGuestRoutes } from './api/routes/guests.js'; +import { deleteTenantWithMembers, removeMemberFromTenant } from './services/accountDeletion.js'; import { registerTenantRoutes } from './api/routes/tenant.js'; import { registerContactRoutes } from './api/routes/contact.js'; import { registerMobileRoutes } from './mobile/routes.js'; @@ -55,7 +56,11 @@ import { isNativeClientRequest } from './api/routes/auth.helpers.js'; import { buildPublicWebLink, publicWebBase } from './api/utils/publicLinks.js'; // Enterprise module loaders -import { getAdminEnterpriseModule } from './adminLoader.js'; +import { assertTenantDeletionProtocol, getAdminEnterpriseModule } from './adminLoader.js'; +import { createJournalPlanResolver } from './services/tenantDeletionPlanning.js'; +import { createSharedPlanResolver } from './services/sharedPlanResolver.js'; +import { createAccountJournalPlanResolver, registerAccountDeletionJournal } from './services/accountDeletionJournal.js'; +import { isTenantSlugReserved } from './services/tenantSlugReservation.js'; import { getBillingModule } from './billingLoader.js'; import { getTenancyModule } from './tenancyLoader.js'; import { getTelemetryModule } from './telemetryLoader.js'; @@ -67,6 +72,55 @@ import { resolveTemplateTenantSlug } from './services/templateTenant.js'; const prisma = createPrismaClient(); +// File-backed deletion journal: one plan resolver per process, shared by the +// admin routes and the scheduled tenant deletion. It is created lazily on first +// use (route setup never touches the database or the filesystem for it) and +// created again after a failed attempt. Creation reconciles undecided intents, +// so no second resolver may exist in the process; see createSharedPlanResolver. +// The journal directory is trimmed here, the one place both callers pass. +const sharedPlanResolverForDir = createSharedPlanResolver( + (journalDir: string) => + createJournalPlanResolver({ prisma, journalDir, retentionDays: process.env.BACKUP_RETENTION_DAYS }), + (error) => logger.warn({ event: 'tenant_delete.journal_resolver_unavailable', error: String(error) }), +); +const sharedJournalPlanResolver = (journalDir: string) => sharedPlanResolverForDir(journalDir.trim()); +type JournalPlanResolver = NonNullable>>; + +/** Plan resolver for the admin routes; undefined without a journal directory. */ +function tenantDeletionPlanResolver(journalDir: string | undefined) { + if (journalDir === undefined || journalDir.trim() === '') return undefined; + return async (tx: Parameters[0], input: Parameters[1]) => { + const resolver = await sharedJournalPlanResolver(journalDir); + return resolver === undefined ? undefined : resolver(tx, input); + }; +} + +/** + * Registers the file-backed account deletion journal from the environment. The directory and + * the retention are read and trimmed exactly like the tenant plan resolver above. Without a + * directory nothing is registered. + */ +function registerAccountJournalFromEnv() { + const journalDir = process.env.DELETION_JOURNAL_DIR?.trim(); + registerAccountDeletionJournal( + journalDir + ? createAccountJournalPlanResolver({ prisma, journalDir, retentionDays: process.env.BACKUP_RETENTION_DAYS }) + : undefined, + ); +} + +/** Dependencies of the scheduled tenant deletion in the hourly billing pass. */ +function scheduledTenantDeletionDeps() { + return { + journalDir: process.env.DELETION_JOURNAL_DIR || undefined, + deleteTenantWithMembers: (tenantId: string, options?: Parameters[2]) => { + assertTenantDeletionProtocol(options?.deletionProtocol); + return deleteTenantWithMembers(prisma, tenantId, options); + }, + createPlanResolver: (journalDir: string) => sharedJournalPlanResolver(journalDir), + }; +} + /** The shared API client used by startup invariants before the server listens. */ export function getApiPrismaClient(): PrismaClient { return prisma; @@ -239,6 +293,8 @@ async function registerEnterpriseAdminRoutes(app: express.Express) { prisma, logger, requireSuperAdmin, + resolveTenantDeletionPlan: tenantDeletionPlanResolver(process.env.DELETION_JOURNAL_DIR), + isTenantSlugReserved: (slug) => isTenantSlugReserved(prisma, slug), computeOnlineUsageByTenantSlug, isMultiTenantEnabled: () => tenancy.isMultiTenantEnabled(), hashPassword: (password: string) => bcrypt.hash(password, 10), @@ -246,6 +302,10 @@ async function registerEnterpriseAdminRoutes(app: express.Express) { setAuthCookie, normalizeEmail: normalizeEmailForStorage, copyTemplateMaps: (p, tenantId) => copyTemplateMapsForSignup(p, tenantId), + deleteTenantWithMembers: (tenantId, options) => { + assertTenantDeletionProtocol(options?.deletionProtocol); + return deleteTenantWithMembers(prisma, tenantId, options); + }, sendWelcomeEmail: sendSignupWelcomeEmail, isNativeClientRequest, requireAuth, @@ -276,6 +336,7 @@ async function registerEnterpriseAdminRoutes(app: express.Express) { logger, requireSuperAdmin, normalizeEmail: normalizeEmailForStorage, + removeMemberFromTenant: (params) => removeMemberFromTenant(prisma, params), }); adminEnterprise.setupPackMarketplaceRoutes(app, { @@ -369,6 +430,8 @@ async function registerEnterpriseBillingRoutes(app: express.Express) { // event without billing importing the telemetry package. Undefined (inert) // in OSS-only builds or when telemetry is not configured. captureServerEvent: telemetryModule?.captureServerEvent, + // Scheduled tenant deletion in the hourly billing pass (same deletion path and resolver). + tenantDeletion: scheduledTenantDeletionDeps(), }); // The EE module is responsible for logging its own initialization // (billing.routes.initialized) or its disabled-state warning @@ -443,6 +506,8 @@ export async function registerApi(app: express.Express) { // tenant-scoped routes fail closed instead of serving a foreign tenant. app.use(createTenantAccessMiddleware(prisma)); + // Account deletion journal: registered on every call, independent of the enterprise module. + registerAccountJournalFromEnv(); registerHealthRoutes(app, prisma); registerAuthRoutes(app, prisma); diff --git a/apps/server/src/api/requestTelemetry.test.ts b/apps/server/src/api/requestTelemetry.test.ts index 6e5fe064..c0292070 100644 --- a/apps/server/src/api/requestTelemetry.test.ts +++ b/apps/server/src/api/requestTelemetry.test.ts @@ -1,12 +1,12 @@ /** - * Routenmetadaten in Request-Logs und Metriklabels (Q-DISC-12). + * Route metadata in request logs and metric labels (Q-DISC-12). * - * Führt test/fixtures/requestTelemetry.ts genau einmal als echten - * Node-Unterprozess aus und prüft nur dessen echte Ausgabe: Pino-Logzeilen - * plus eine JSON-Ergebniszeile. Erwartet: http.request ohne path-Feld, - * Response-/Labelpfad als baseUrl plus Routentemplate ("/api/invites/:code" - * bei Mounts, "" ohne Treffer), keine konkreten Parameter, - * Kennungen oder Querystrings in Logs oder Labels. + * Runs test/fixtures/requestTelemetry.ts exactly once as a real Node + * subprocess and asserts only on its real output: pino log lines plus one + * JSON result line. Expects: http.request without a path field, + * response/label path as baseUrl plus route template ("/api/invites/:code" + * for mounts, "" without a match), no concrete parameters, + * identifiers or query strings in logs or labels. */ import { spawnSync } from 'node:child_process'; import path from 'node:path'; @@ -119,10 +119,7 @@ describe('request route metadata', () => { }); it('leaks no concrete identifiers or query strings into logs or labels', () => { - const haystacks = [ - JSON.stringify(output.logs), - JSON.stringify(output.metricValues.map((v) => v.labels)), - ]; + const haystacks = [JSON.stringify(output.logs), JSON.stringify(output.metricValues.map((v) => v.labels))]; for (const haystack of haystacks) { for (const leak of LEAKS) { expect(haystack).not.toContain(leak); diff --git a/apps/server/src/api/routes/guestRevocation.integration.test.ts b/apps/server/src/api/routes/guestRevocation.integration.test.ts new file mode 100644 index 00000000..a36beee0 --- /dev/null +++ b/apps/server/src/api/routes/guestRevocation.integration.test.ts @@ -0,0 +1,151 @@ +import crypto from 'node:crypto'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'; +import type { Role } from '../../generated/prisma/index.js'; +import { createPrismaClient } from '../../db.js'; +import { registerGuestRoutes } from './guests.js'; +import { setAuthResolution } from '../utils/authState.js'; +import { getJwtSecret } from '../utils/authHelpers.js'; +import { hashSessionToken, validateSessionToken } from '../utils/sessionAuth.js'; +import { getCachedSession } from '../utils/sessionCache.js'; + +vi.mock('../../tenancyLoader.js', () => ({ + getTenancyModule: () => Promise.resolve({ version: 1, isMultiTenantEnabled: () => true }), +})); + +/** + * Q-ACC-19a: revoking a guest's last membership must delete the account. + * + * The revoke path in guests.ts deletes guest tokens, sessions and the + * membership, but never the user row itself — unlike the shared removal + * logic the member-removal routes use. These tests run against a real + * PostgreSQL database and assert the user row along with the sessions. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('guestRevocation.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const tenantsById = new Map(); + +/** Same x-user/x-tenant shim as userDeletion.integration.test.ts, backed by the real client. */ +function makeApp() { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + const rawUser = req.headers['x-user']; + const userId = typeof rawUser === 'string' ? rawUser : null; + setAuthResolution(req, { + auth: userId ? { userId, sessionId: `sess-${userId}`, tokenHash: `hash-${userId}` } : null, + }); + const rawTenant = req.headers['x-tenant']; + if (typeof rawTenant === 'string') { + const tenant = tenantsById.get(rawTenant); + if (tenant) req.tenant = tenant as never; + } + next(); + }); + registerGuestRoutes(app, prisma); + return app; +} + +async function createTenant(): Promise<{ id: string; slug: string }> { + const slug = `qacc-guest-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + tenantsById.set(tenant.id, { id: tenant.id, slug: tenant.slug, name: tenant.name }); + return { id: tenant.id, slug: tenant.slug }; +} + +async function createUser(memberships: Array<{ tenantId: string; role: Role }>): Promise { + const user = await prisma.user.create({ data: { email: `qacc-guest-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + for (const m of memberships) { + await prisma.membership.create({ data: { userId: user.id, tenantId: m.tenantId, role: m.role } }); + } + return user.id; +} + +/** A real login footprint: a signed session token with its Session row, without email verification. */ +async function addLoginFootprint(userId: string, tenantId: string): Promise { + const token = jwt.sign({ sub: userId, tid: tenantId, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { + userId, + tokenHash: hashSessionToken(token), + expiresAt: new Date(Date.now() + 3_600_000), + }, + }); + return token; +} + +afterEach(async () => { + const ids = userIds.splice(0); + await prisma.session.deleteMany({ where: { userId: { in: ids } } }); + await prisma.membership.deleteMany({ where: { userId: { in: ids } } }); + await prisma.user.deleteMany({ where: { id: { in: ids } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds.splice(0) } } }); + for (const id of [...tenantsById.keys()]) { + if (!tenantIds.includes(id)) tenantsById.delete(id); + } +}); + +afterAll(async () => { + await prisma.$disconnect(); +}); + +describe('Q-ACC-19a DELETE /guests/:membershipId — revoking the last membership deletes the account', () => { + it('deletes user and sessions when the revoked guest membership was the last one', async () => { + const tenant = await createTenant(); + const owner = await createUser([{ tenantId: tenant.id, role: 'owner' }]); + const guest = await createUser([{ tenantId: tenant.id, role: 'guest' }]); + const guestToken = await addLoginFootprint(guest, tenant.id); + const ownerToken = await addLoginFootprint(owner, tenant.id); + const membership = await prisma.membership.findUniqueOrThrow({ + where: { tenantId_userId: { tenantId: tenant.id, userId: guest } }, + }); + await expect(validateSessionToken(prisma, guestToken)).resolves.not.toBeNull(); + + const res = await request(makeApp()) + .delete(`/guests/${membership.id}`) + .set('x-user', owner) + .set('x-tenant', tenant.id); + + expect(res.status).toBe(200); + expect(await prisma.membership.count({ where: { userId: guest } })).toBe(0); + expect(await prisma.session.count({ where: { userId: guest } })).toBe(0); + expect(await prisma.user.count({ where: { id: guest } })).toBe(0); + expect(getCachedSession(hashSessionToken(guestToken))).toBeNull(); + await expect(validateSessionToken(prisma, guestToken)).resolves.toBeNull(); + await expect(validateSessionToken(prisma, ownerToken)).resolves.not.toBeNull(); + }); + + it('keeps the account when the guest still belongs to another tenant', async () => { + const tenantA = await createTenant(); + const tenantB = await createTenant(); + const ownerA = await createUser([{ tenantId: tenantA.id, role: 'owner' }]); + const guest = await createUser([ + { tenantId: tenantA.id, role: 'guest' }, + { tenantId: tenantB.id, role: 'member' }, + ]); + const membership = await prisma.membership.findUniqueOrThrow({ + where: { tenantId_userId: { tenantId: tenantA.id, userId: guest } }, + }); + + const res = await request(makeApp()) + .delete(`/guests/${membership.id}`) + .set('x-user', ownerA) + .set('x-tenant', tenantA.id); + + expect(res.status).toBe(200); + expect(await prisma.user.count({ where: { id: guest } })).toBe(1); + expect(await prisma.membership.count({ where: { userId: guest, tenantId: tenantB.id } })).toBe(1); + }); +}); diff --git a/apps/server/src/api/routes/guests.ts b/apps/server/src/api/routes/guests.ts index 3c07bcad..94e654c8 100644 --- a/apps/server/src/api/routes/guests.ts +++ b/apps/server/src/api/routes/guests.ts @@ -7,12 +7,12 @@ import { requireAuth, getTenantFromReq, requireMembership, normalizeEmailForStor import { buildPublicWebLink, requirePublicWebBase } from '../utils/publicLinks.js'; import { pathParam } from '../utils/requestHelpers.js'; import { displayNameSchema, invalidNameBodyFor } from '../utils/displayName.js'; -import { establishSession, revokeSessionsForUser } from '../utils/sessionAuth.js'; +import { establishSession } from '../utils/sessionAuth.js'; +import { MembershipNotFoundError, removeMemberFromTenant } from '../../services/accountDeletion.js'; import { getTenancyModule } from '../../tenancyLoader.js'; import { sendIfAvailable } from '../../emailLoader.js'; import { guestLoginRateLimiter } from '../middleware/rateLimit.js'; import { credentialRoute } from '../middleware/tenantAccess.js'; -import { revokeTenantAccess } from '../../services/tenantAccessRevocation.js'; type GuestAdminGate = | { @@ -256,16 +256,25 @@ async function handleRevokeGuest(prisma: PrismaClient, req: express.Request, res return; } - await prisma.guestToken.deleteMany({ where: { membershipId } }); - // Via the helper, never a raw `session.deleteMany`: deleting the rows alone - // leaves the resolved session in the in-process cache, and a revoked guest - // stayed authenticated for up to SESSION_CACHE_TTL_MS — long enough to enter - // the world (presence, camera, microphone), which onAuth admits on the same - // cache. revokeSessionsForUser drops the cache entries with the rows. - await revokeSessionsForUser(prisma, guestMembership.userId); - await prisma.membership.delete({ where: { id: membershipId } }); - // End the guest's open world and AV connections now, not at the next sweep. - await revokeTenantAccess(tenant.slug, guestMembership.userId); + // The shared removal (services/accountDeletion.ts) signs the guest out + // everywhere, deletes the account with its last membership and ends open + // world and AV connections after the commit. Guest tokens go with the + // membership (ON DELETE CASCADE). + try { + await removeMemberFromTenant(prisma, { userId: guestMembership.userId, tenantId: tenant.id }); + } catch (e: unknown) { + if (e instanceof MembershipNotFoundError) { + res.status(404).json({ error: 'guest_not_found' }); + return; + } + logger.error({ + event: 'guests.revoke_failed', + tenantId: tenant.id, + error: e instanceof Error ? e.message : String(e), + }); + res.status(500).json({ error: 'revoke_failed' }); + return; + } res.json({ ok: true }); } diff --git a/apps/server/src/api/routes/npcMedia.ts b/apps/server/src/api/routes/npcMedia.ts index 2e4d93b0..a56867ee 100644 --- a/apps/server/src/api/routes/npcMedia.ts +++ b/apps/server/src/api/routes/npcMedia.ts @@ -1,4 +1,4 @@ -import type express from 'express'; +import express from 'express'; import type { PrismaClient } from '../../generated/prisma/index.js'; import crypto from 'crypto'; import path from 'path'; @@ -157,17 +157,61 @@ async function handleDeleteMedia( // --- Route registration --- -export function registerNpcMediaRoutes(app: express.Application, prisma: PrismaClient) { - const npcMediaDir = process.env.NPC_MEDIA_DIR || path.resolve(process.cwd(), '../../npc-media'); +/** + * Shared with the npc service (apps/npc-service/src/config.ts) and mounted as + * one volume in compose; a local run without Docker sets NPC_MEDIA_DIR. + */ +export const NPC_MEDIA_DEFAULT_DIR = '/data/npc-media'; + +/** Storage root of NPC media files; shared with the tenant file cleanup. */ +export function npcMediaDir(): string { + return process.env.NPC_MEDIA_DIR || NPC_MEDIA_DEFAULT_DIR; +} + +/** Create the storage root; logs loudly instead of failing silently. */ +export function ensureNpcMediaDir(): boolean { try { - fs.mkdirSync(npcMediaDir, { recursive: true }); - } catch { - /* ignore */ + fs.mkdirSync(npcMediaDir(), { recursive: true }); + return true; + } catch (error) { + logger.error({ + event: 'npc_media.dir_unavailable', + hint: 'set NPC_MEDIA_DIR to a writable directory', + error: String(error), + }); + return false; } +} + +/** Serve NPC media files; mirrors the upload and deletion roots. */ +export function registerNpcMediaStatic(app: express.Application): void { + const mediaDir = npcMediaDir(); + ensureNpcMediaDir(); + app.use( + '/npc-media', + express.static(mediaDir, { + maxAge: '7d', + setHeaders: (res) => { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); + res.removeHeader('Access-Control-Allow-Credentials'); + }, + }), + ); +} + +/** Resolve a stored NPC media path below the storage root. */ +export function npcMediaFilePath(storagePath: string): string { + return path.join(npcMediaDir(), storagePath); +} + +export function registerNpcMediaRoutes(app: express.Application, prisma: PrismaClient) { + const mediaDir = npcMediaDir(); + ensureNpcMediaDir(); const upload = uploadParser('npc'); - app.post('/npcs/:id/media', uploadGuard(prisma, 'npc'), boundedMultipart(upload.single('file')), (req, res) => handleUploadMedia(req, res, prisma, npcMediaDir)); + app.post('/npcs/:id/media', uploadGuard(prisma, 'npc'), boundedMultipart(upload.single('file')), (req, res) => handleUploadMedia(req, res, prisma, mediaDir)); app.get('/npcs/:id/media', (req, res) => handleListMedia(req, res, prisma)); - app.delete('/npcs/:id/media/:mediaId', (req, res) => handleDeleteMedia(req, res, prisma, npcMediaDir)); + app.delete('/npcs/:id/media/:mediaId', (req, res) => handleDeleteMedia(req, res, prisma, mediaDir)); } diff --git a/apps/server/src/api/routes/npcMediaDir.test.ts b/apps/server/src/api/routes/npcMediaDir.test.ts new file mode 100644 index 00000000..aeec04cc --- /dev/null +++ b/apps/server/src/api/routes/npcMediaDir.test.ts @@ -0,0 +1,49 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import express from 'express'; +import request from 'supertest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { npcMediaDir, npcMediaFilePath, registerNpcMediaStatic } from './npcMedia.js'; + +describe('one npc media directory for upload, serving and deletion', () => { + const tempDirs: string[] = []; + + afterEach(async () => { + vi.unstubAllEnvs(); + for (const dir of tempDirs.splice(0)) { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + + it('defaults to the directory shared with the npc service', () => { + vi.stubEnv('NPC_MEDIA_DIR', ''); + expect(npcMediaDir()).toBe('/data/npc-media'); + }); + + it('serves npc media from the configured directory', async () => { + const base = await fs.mkdtemp(path.join(os.tmpdir(), 'qacc-npc-serve-')); + tempDirs.push(base); + vi.stubEnv('NPC_MEDIA_DIR', base); + await fs.mkdir(path.join(base, 'acme', 'npc1'), { recursive: true }); + await fs.writeFile(path.join(base, 'acme', 'npc1', 'a.png'), 'qacc'); + + const app = express(); + registerNpcMediaStatic(app); + const res = await request(app).get('/npc-media/acme/npc1/a.png'); + expect(res.status).toBe(200); + expect(Buffer.isBuffer(res.body)).toBe(true); + expect((res.body as Buffer).toString('utf8')).toBe('qacc'); + }); + + it('resolves npc media files below the same directory', async () => { + const base = await fs.mkdtemp(path.join(os.tmpdir(), 'qacc-npc-resolve-')); + tempDirs.push(base); + vi.stubEnv('NPC_MEDIA_DIR', base); + expect(npcMediaFilePath('acme/npc1/a.png')).toBe(path.join(base, 'acme/npc1/a.png')); + + vi.stubEnv('NPC_MEDIA_DIR', ''); + expect(npcMediaDir()).toBe('/data/npc-media'); + expect(npcMediaFilePath('acme/npc1/a.png')).toBe(path.join(npcMediaDir(), 'acme/npc1/a.png')); + }); +}); diff --git a/apps/server/src/api/routes/npcs.serviceAuth.integration.test.ts b/apps/server/src/api/routes/npcs.serviceAuth.integration.test.ts new file mode 100644 index 00000000..2aae1e6f --- /dev/null +++ b/apps/server/src/api/routes/npcs.serviceAuth.integration.test.ts @@ -0,0 +1,237 @@ +import crypto from 'crypto'; +import http from 'node:http'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import request from 'supertest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createPrismaClient } from '../../db.js'; +import { getJwtSecret } from '../utils/authHelpers.js'; +import { createSessionAuthMiddleware, hashSessionToken } from '../utils/sessionAuth.js'; +import { registerNpcRoutes } from './npcs.js'; + +/** + * Service-to-service auth on GET /npcs against a real PostgreSQL database. + * The list with tenant rows is the grant signal; session listing stays tenant-scoped. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('npcs.serviceAuth.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const SECRET_KEY = 'NPC_SERVICE_SECRET'; +const SECRET_HEADER = 'x-npc-secret'; +const prisma = createPrismaClient(); + +function readKnownDefaultSecret(): string { + const source = readFileSync(fileURLToPath(new URL('../../../../npc-service/src/config.ts', import.meta.url)), 'utf8'); + const named = source.match(/KNOWN_DEFAULT_SECRET\s*=\s*'([^']+)'/); + if (named?.[1]) return named[1]; + const fallback = source.match(/NPC_SERVICE_SECRET[^\n]*\|\|\s*'([^']+)'/); + if (fallback?.[1]) return fallback[1]; + throw new Error('NPC service config does not declare a documented secret placeholder'); +} + +function randomSecret(byteLength: number): string { + return crypto.randomBytes(byteLength).toString('hex'); +} + +function npcIds(body: unknown): string[] { + if (!Array.isArray(body)) return []; + return body.flatMap((row) => (row && typeof row === 'object' && 'id' in row ? [String(row.id)] : [])).sort(); +} + +function listsBothWithTenant(body: unknown, ids: readonly string[]): boolean { + if (!Array.isArray(body)) return false; + const got = new Set(npcIds(body)); + const withTenant = body.every( + (row) => + row && + typeof row === 'object' && + 'tenant' in row && + row.tenant && + typeof row.tenant === 'object' && + 'slug' in row.tenant, + ); + return ids.every((id) => got.has(id)) && withTenant; +} + +function makeApp(): express.Express { + const app = express(); + app.use(express.json()); + app.use(createSessionAuthMiddleware(prisma)); + app.use(async (req, _res, next) => { + const id = req.headers['x-tenant']; + const tenant = typeof id === 'string' ? await prisma.tenant.findUnique({ where: { id } }) : null; + if (tenant) req.tenant = tenant; + next(); + }); + registerNpcRoutes(app, prisma); + return app; +} + +async function getNpcsWithRepeatedSecret( + app: express.Express, + secret: string, +): Promise<{ status: number; body: unknown }> { + const server = app.listen(0, '127.0.0.1'); + await new Promise((resolve, reject) => { + server.once('listening', () => resolve()); + server.once('error', reject); + }); + try { + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('listening server has no port'); + } + return await new Promise((resolve, reject) => { + const req = http.request( + { + host: '127.0.0.1', + port: address.port, + path: '/npcs', + method: 'GET', + headers: { [SECRET_HEADER]: [secret, secret], connection: 'close' }, + }, + (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))); + res.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + let body: unknown = raw; + try { + body = JSON.parse(raw) as unknown; + } catch { + // Keep the raw body when the response is not JSON. + } + resolve({ status: res.statusCode ?? 0, body }); + }); + }, + ); + req.setTimeout(5000, () => req.destroy(new Error('repeated-header request timed out'))); + req.on('error', reject); + req.end(); + }); + } finally { + await new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }); + } +} + +const tenantIds: string[] = []; +const userIds: string[] = []; +const npcIdList: string[] = []; +let app: express.Express; +let tenantAId: string; +let npcAId: string; +let npcBId: string; +let memberSession: string; +let previousSecret: string | undefined; + +beforeAll(async () => { + const tenantA = await prisma.tenant.create({ + data: { slug: `npc-svc-${crypto.randomUUID()}`, name: 'Service list A' }, + }); + const tenantB = await prisma.tenant.create({ + data: { slug: `npc-svc-${crypto.randomUUID()}`, name: 'Service list B' }, + }); + tenantAId = tenantA.id; + tenantIds.push(tenantA.id, tenantB.id); + + const npcA = await prisma.npc.create({ + data: { tenantId: tenantA.id, identity: 'greeter-a', name: 'Greeter A' }, + }); + const npcB = await prisma.npc.create({ + data: { tenantId: tenantB.id, identity: 'greeter-b', name: 'Greeter B' }, + }); + npcAId = npcA.id; + npcBId = npcB.id; + npcIdList.push(npcA.id, npcB.id); + + const user = await prisma.user.create({ data: { email: `npc-svc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId: tenantA.id, role: 'member' } }); + memberSession = jwt.sign({ sub: user.id, tid: tenantA.id, jti: crypto.randomUUID() }, getJwtSecret(), { + expiresIn: '1h', + }); + await prisma.session.create({ + data: { userId: user.id, tokenHash: hashSessionToken(memberSession), expiresAt: new Date(Date.now() + 3_600_000) }, + }); + + app = makeApp(); +}); + +beforeEach(() => { + previousSecret = process.env[SECRET_KEY]; +}); + +afterEach(() => { + if (previousSecret === undefined) delete process.env[SECRET_KEY]; + else process.env[SECRET_KEY] = previousSecret; +}); + +afterAll(async () => { + await prisma.npc.deleteMany({ where: { id: { in: npcIdList } } }); + await prisma.session.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('GET /npcs service authentication', () => { + it('does not grant the cross-tenant list when the configured secret is the known default', async () => { + const configured = readKnownDefaultSecret(); + process.env[SECRET_KEY] = configured; + const res = await request(app).get('/npcs').set(SECRET_HEADER, configured); + expect(res.status).toBe(401); + expect(listsBothWithTenant(res.body, [npcAId, npcBId])).toBe(false); + }); + + it('does not grant the cross-tenant list when the configured secret is 16 characters', async () => { + const configured = randomSecret(8); + process.env[SECRET_KEY] = configured; + const res = await request(app).get('/npcs').set(SECRET_HEADER, configured); + expect(res.status).toBe(401); + expect(listsBothWithTenant(res.body, [npcAId, npcBId])).toBe(false); + }); + + it('grants the cross-tenant list when a valid secret matches the header', async () => { + const configured = randomSecret(16); + process.env[SECRET_KEY] = configured; + const res = await request(app).get('/npcs').set(SECRET_HEADER, configured); + expect(res.status).toBe(200); + expect(listsBothWithTenant(res.body, [npcAId, npcBId])).toBe(true); + }); + + it('does not grant the cross-tenant list for a same-length wrong secret', async () => { + const configured = randomSecret(16); + let provided = randomSecret(16); + while (provided === configured) provided = randomSecret(16); + process.env[SECRET_KEY] = configured; + const res = await request(app).get('/npcs').set(SECRET_HEADER, provided); + expect(res.status).toBe(401); + expect(listsBothWithTenant(res.body, [npcAId, npcBId])).toBe(false); + }); + + it('does not grant the cross-tenant list when the secret header is sent twice', async () => { + const configured = randomSecret(16); + process.env[SECRET_KEY] = configured; + const res = await getNpcsWithRepeatedSecret(app, configured); + expect(res.status).toBe(401); + expect(listsBothWithTenant(res.body, [npcAId, npcBId])).toBe(false); + }); + + it('lists only the session tenant when no service header is sent', async () => { + process.env[SECRET_KEY] = randomSecret(16); + const res = await request(app) + .get('/npcs') + .set('Authorization', `Bearer ${memberSession}`) + .set('x-tenant', tenantAId); + expect(res.status).toBe(200); + expect(npcIds(res.body)).toEqual([npcAId]); + expect(res.body[0]).not.toHaveProperty('tenant'); + }); +}); diff --git a/apps/server/src/api/routes/npcs.ts b/apps/server/src/api/routes/npcs.ts index 6112e5f8..44446209 100644 --- a/apps/server/src/api/routes/npcs.ts +++ b/apps/server/src/api/routes/npcs.ts @@ -3,9 +3,11 @@ import type { PrismaClient } from '../../generated/prisma/index.js'; import { z } from 'zod'; import { requireAuth, requireApiToken, getTenantFromReq, requireMembership } from '../utils/authHelpers.js'; import { pathParam } from '../utils/requestHelpers.js'; +import { requestMatchesServiceSecret } from '../utils/serviceSecret.js'; import { logger } from '../../logger.js'; import { npcServiceSpawn, npcServiceDespawn } from '../utils/npcServiceClient.js'; import { isAllowedAvatarId, isCustomAvatarId } from '../../services/avatarAccess.js'; +import { npcMediaFilePath } from './npcMedia.js'; import { resolvePackScope } from '../utils/resolvePackScope.js'; import { MAX_DISPLAY_NAME_LENGTH } from '../utils/displayName.js'; @@ -109,11 +111,7 @@ const commandSchema = z.discriminatedUnion('action', [ async function handleListNpcs(req: express.Request, res: express.Response, prisma: PrismaClient) { // Internal service auth via NPC_SERVICE_SECRET (service-to-service) - const npcSecret = process.env.NPC_SERVICE_SECRET; - const reqSecret = req.headers['x-npc-secret'] as string | undefined; - const isServiceAuth = !!(npcSecret && reqSecret && npcSecret === reqSecret); - - if (isServiceAuth) { + if (requestMatchesServiceSecret(req, 'NPC_SERVICE_SECRET', 'x-npc-secret')) { // Service-to-service: return all enabled NPCs across all tenants const enabledFilter = req.query.enabled === 'true' ? { enabled: true } : {}; const npcs = await prisma.npc.findMany({ @@ -231,10 +229,9 @@ async function handleDeleteNpc(req: express.Request, res: express.Response, pris try { const mediaFiles = await prisma.npcMediaFile.findMany({ where: { npcId: npc.id } }); const fsp = await import('fs/promises'); - const npcMediaDir = process.env.NPC_MEDIA_DIR || '/data/npc-media'; for (const mf of mediaFiles) { try { - await fsp.rm(`${npcMediaDir}/${mf.storagePath}`, { force: true }); + await fsp.rm(npcMediaFilePath(mf.storagePath), { force: true }); } catch { /* ignore */ } diff --git a/apps/server/src/api/utils/npcServiceClient.test.ts b/apps/server/src/api/utils/npcServiceClient.test.ts new file mode 100644 index 00000000..e557abe3 --- /dev/null +++ b/apps/server/src/api/utils/npcServiceClient.test.ts @@ -0,0 +1,89 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { npcServiceStatus } from './npcServiceClient.js'; + +const SECRET_KEY = 'NPC_SERVICE_SECRET'; +const URL_KEY = 'NPC_SERVICE_URL'; +const SECRET_HEADER = 'x-npc-secret'; +const CONFIG_ERROR = 'NPC service is not configured: NPC_SERVICE_SECRET is missing or invalid'; + +let server: http.Server; +let requestCount = 0; +let receivedSecrets: string[] = []; +let previousSecret: string | undefined; +let previousUrl: string | undefined; + +function readKnownDefaultSecret(): string { + const source = readFileSync(fileURLToPath(new URL('../../../../npc-service/src/config.ts', import.meta.url)), 'utf8'); + const named = source.match(/KNOWN_DEFAULT_SECRET\s*=\s*'([^']+)'/); + if (named?.[1]) return named[1]; + const fallback = source.match(/NPC_SERVICE_SECRET[^\n]*\|\|\s*'([^']+)'/); + if (fallback?.[1]) return fallback[1]; + throw new Error('NPC service config does not declare a documented secret placeholder'); +} + +function startServer(): Promise { + server = http.createServer((req, res) => { + requestCount += 1; + const secret = req.headers[SECRET_HEADER]; + receivedSecrets.push(typeof secret === 'string' ? secret : ''); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end('{}'); + }); + return new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + reject(new Error('listening server has no port')); + return; + } + resolve(`http://127.0.0.1:${address.port}`); + }); + }); +} + +beforeEach(async () => { + previousSecret = process.env[SECRET_KEY]; + previousUrl = process.env[URL_KEY]; + requestCount = 0; + receivedSecrets = []; + delete process.env[SECRET_KEY]; + process.env[URL_KEY] = await startServer(); +}); + +afterEach(async () => { + if (previousSecret === undefined) delete process.env[SECRET_KEY]; + else process.env[SECRET_KEY] = previousSecret; + if (previousUrl === undefined) delete process.env[URL_KEY]; + else process.env[URL_KEY] = previousUrl; + if (server?.listening) { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + } +}); + +describe('npc service client', () => { + it('does not call the npc service when the secret is missing', async () => { + await expect(npcServiceStatus()).rejects.toThrow(CONFIG_ERROR); + expect(requestCount).toBe(0); + }); + + it('does not call the npc service with the known default secret', async () => { + process.env[SECRET_KEY] = readKnownDefaultSecret(); + await expect(npcServiceStatus()).rejects.toThrow(CONFIG_ERROR); + expect(requestCount).toBe(0); + }); + + it('sends the configured secret once when it is valid', async () => { + const secret = crypto.randomBytes(16).toString('hex'); + process.env[SECRET_KEY] = secret; + await expect(npcServiceStatus()).resolves.toEqual({}); + expect(requestCount).toBe(1); + expect(receivedSecrets).toEqual([secret]); + }); +}); diff --git a/apps/server/src/api/utils/npcServiceClient.ts b/apps/server/src/api/utils/npcServiceClient.ts index 1504e965..269617ec 100644 --- a/apps/server/src/api/utils/npcServiceClient.ts +++ b/apps/server/src/api/utils/npcServiceClient.ts @@ -1,16 +1,20 @@ import { logger } from '../../logger.js'; import type { NpcSpawnCommand } from '@meetropolis/shared'; +import { usableServiceSecret } from './serviceSecret.js'; const NPC_SERVICE_URL = () => process.env.NPC_SERVICE_URL || 'http://npc-service:3100'; -const NPC_SERVICE_SECRET = () => process.env.NPC_SERVICE_SECRET || 'dev-npc-secret'; async function npcFetch(path: string, method: string, body?: unknown): Promise { + const secret = usableServiceSecret('NPC_SERVICE_SECRET'); + if (secret === null) { + throw new Error('NPC service is not configured: NPC_SERVICE_SECRET is missing or invalid'); + } const url = `${NPC_SERVICE_URL()}${path}`; const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json', - 'X-NPC-Secret': NPC_SERVICE_SECRET(), + 'X-NPC-Secret': secret, }, body: body ? JSON.stringify(body) : undefined, }); diff --git a/apps/server/src/api/utils/requestRoute.ts b/apps/server/src/api/utils/requestRoute.ts index fc3f7d7e..888a2605 100644 --- a/apps/server/src/api/utils/requestRoute.ts +++ b/apps/server/src/api/utils/requestRoute.ts @@ -1,13 +1,12 @@ import type { Request } from 'express'; /** - * Bestimmt das Routen-Template eines Requests für Logs und Metriklabels. + * Returns a route template for request logs and metric labels. * - * Gibt bei bekanntem Routen-Template `baseUrl + route.path` zurück, sonst - * exakt `""`. Es werden ausschließlich `baseUrl` und ein - * stringförmiges `route.path` gelesen; konkrete Pfade, URLs, Parameter und - * Querystrings fließen nie ein. Vor dem Routing ist die Route noch nicht - * bekannt, daher meldet ein früher Aufruf `""`. + * Uses only baseUrl and a string route.path; concrete request paths, URLs, + * parameters and query strings are never read. Requests without a route + * template produce `""`. Early http.request logs omit the path + * field. */ export function getRequestRouteTemplate(req: Pick): string { const route = req.route as { path?: unknown } | undefined; diff --git a/apps/server/src/api/utils/serviceSecret.ts b/apps/server/src/api/utils/serviceSecret.ts new file mode 100644 index 00000000..0a6a7efa --- /dev/null +++ b/apps/server/src/api/utils/serviceSecret.ts @@ -0,0 +1,57 @@ +import crypto from 'crypto'; +import type { IncomingMessage } from 'node:http'; +import { logger } from '../../logger.js'; + +// Comparison constant only: this value never passes validation. +const KNOWN_DEFAULT_SECRET = 'dev-npc-secret'; + +const MIN_SECRET_LENGTH = 32; + +const warnedKeys = new Set(); + +function isUsableSecret(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length >= MIN_SECRET_LENGTH && + value.trim().length > 0 && + value !== KNOWN_DEFAULT_SECRET + ); +} + +function warnInvalidOnce(envKey: string): void { + if (warnedKeys.has(envKey)) return; + warnedKeys.add(envKey); + logger.warn({ event: 'service_secret.invalid', key: envKey }); +} + +export function usableServiceSecret(envKey: string): string | null { + const raw = process.env[envKey]; + if (raw === undefined) return null; + if (isUsableSecret(raw)) return raw; + warnInvalidOnce(envKey); + return null; +} + +function headerValueOnce(req: IncomingMessage, headerName: string): string | null { + const distinct = req.headersDistinct?.[headerName]; + const raw = req.headers[headerName]; + if (!Array.isArray(distinct) || distinct.length !== 1 || typeof raw !== 'string') { + return null; + } + return raw; +} + +function timingSafeEqualStrings(a: string, b: string): boolean { + const aBuf = Buffer.from(a, 'utf8'); + const bBuf = Buffer.from(b, 'utf8'); + return aBuf.length === bBuf.length && crypto.timingSafeEqual(aBuf, bBuf); +} + +/** True when the header is present once and matches a usable configured secret. */ +export function requestMatchesServiceSecret(req: IncomingMessage, envKey: string, headerName: string): boolean { + const expected = usableServiceSecret(envKey); + if (expected === null) return false; + const provided = headerValueOnce(req, headerName); + if (provided === null) return false; + return timingSafeEqualStrings(provided, expected); +} diff --git a/apps/server/src/api/utils/sessionAuth.ts b/apps/server/src/api/utils/sessionAuth.ts index e87163d5..dab9830d 100644 --- a/apps/server/src/api/utils/sessionAuth.ts +++ b/apps/server/src/api/utils/sessionAuth.ts @@ -13,6 +13,7 @@ import { setCachedSession, invalidateSessionToken, invalidateSessionsForUser, + clearSessionCache, } from './sessionCache.js'; /** @@ -294,6 +295,19 @@ export async function revokeSessionsForUserInTx(tx: Prisma.TransactionClient, us return result.count; } +/** + * Delete every session row of every user. Used by the operator restore replay + * (services/tenantDeletionReplayRun.ts), which runs while the server is stopped. + * + * The auth cache of this process is cleared as well. A server running in another + * process keeps its own cache until those entries expire (sessionCache.ts). + */ +export async function revokeAllSessions(prisma: PrismaClient): Promise { + const result = await prisma.session.deleteMany({}); + clearSessionCache(); + return result.count; +} + /** * Drop `userId`'s already-expired session rows (housekeeping for the * active-sessions list, which must not show corpses). diff --git a/apps/server/src/billingLoader.ts b/apps/server/src/billingLoader.ts index cec9f460..ce20de19 100644 --- a/apps/server/src/billingLoader.ts +++ b/apps/server/src/billingLoader.ts @@ -2,6 +2,8 @@ import type { Router, Request, Response, NextFunction, Express } from 'express'; import type { PrismaClient } from './generated/prisma/index.js'; import { z } from 'zod'; import { logger } from './logger.js'; +import type { deleteTenantWithMembers } from './services/accountDeletion.js'; +import type { createJournalPlanResolver } from './services/tenantDeletionPlanning.js'; /** * Expected `version` of the `@meetropolis/billing` module. Single source of @@ -82,6 +84,21 @@ export interface BillingModule { * validates the module's exports, not this config object). */ captureServerEvent?: (event: { name: string; tenant?: string; properties?: Record }) => void; + /** + * Optional dependencies of the scheduled tenant deletion in the hourly + * billing pass: journal directory, deletion path and the shared plan + * resolver. Optional, so this is a backward-compatible config-shape addition. + */ + tenantDeletion?: { + journalDir: string | undefined; + deleteTenantWithMembers: ( + tenantId: string, + options?: Parameters[2], + ) => Promise<{ deletedAccounts: number }>; + createPlanResolver: ( + journalDir: string, + ) => Promise> | undefined>; + }; }, ): void; diff --git a/apps/server/src/guestSessionRevocation.test.ts b/apps/server/src/guestSessionRevocation.test.ts index c52980bf..04b6c37e 100644 --- a/apps/server/src/guestSessionRevocation.test.ts +++ b/apps/server/src/guestSessionRevocation.test.ts @@ -15,6 +15,9 @@ * Every test therefore asserts against `validateSessionToken` — the function * the world join calls — with real timers and no TTL advance: revocation has to * bite NOW, not in 30 seconds. + * + * The admin revocation is covered against a real database in + * api/routes/guestRevocation.integration.test.ts. */ import express from 'express'; import request from 'supertest'; @@ -137,7 +140,6 @@ vi.mock('./emailLoader.js', () => ({ sendIfAvailable: vi.fn() })); import { hashSessionToken, validateSessionToken } from './api/utils/sessionAuth.js'; import { clearSessionCache, getCachedSession } from './api/utils/sessionCache.js'; import { setAuthResolution } from './api/utils/authState.js'; -import { registerGuestRoutes } from './api/routes/guests.js'; import { guestExpiryMiddleware } from './api/middleware/guestExpiry.js'; import { startGuestExpiryInterval } from './rooms/lifecycle/guestExpiry.js'; import { createWorldAccess } from './rooms/lifecycle/worldAccess.js'; @@ -181,48 +183,6 @@ beforeEach(() => { vi.clearAllMocks(); }); -describe('admin revoke (DELETE /guests/:membershipId)', () => { - function makeApp(): express.Application { - const app = express(); - app.use(express.json()); - app.use((req, _res, next) => { - req.tenant = TENANT; - setAuthResolution(req, { - auth: { userId: ADMIN_USER, tenantId: TENANT.id, sessionId: 'admin-sess', tokenHash: 'admin-hash' }, - }); - next(); - }); - registerGuestRoutes(app, prisma); - return app; - } - - it('a revoked guest cannot authenticate any more — not even from the warm cache', async () => { - const token = seedSession(GUEST_USER); - await warmCache(token); - - const res = await request(makeApp()).delete('/guests/m-guest'); - expect(res.status).toBe(200); - - // Rows gone AND cache dropped. The row check alone was already true while - // the hole was open; the cache check is the regression guard. - expect(db.sessions.filter((s) => s.userId === GUEST_USER)).toHaveLength(0); - expect(getCachedSession(hashSessionToken(token))).toBeNull(); - // This is the call rooms/lifecycle/onAuth.ts makes on a world join. - await expect(validateSessionToken(prisma, token)).resolves.toBeNull(); - }); - - it('leaves another user’s session alone', async () => { - const guestToken = seedSession(GUEST_USER); - const adminToken = seedSession(ADMIN_USER); - await warmCache(guestToken); - await warmCache(adminToken); - - await request(makeApp()).delete('/guests/m-guest'); - - await expect(validateSessionToken(prisma, adminToken)).resolves.not.toBeNull(); - }); -}); - describe('guestExpiryMiddleware (REST)', () => { function makeApp(): express.Application { const app = express(); diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 47459654..ca5d252b 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -1,5 +1,10 @@ import 'dotenv/config'; +// Enforce the production credential policy before any application import +// below constructs clients (tenancy.ts and api.ts build database clients at +// import time), so an invalid production start stops before side effects. +import './ops/startupCredentials.js'; + // Express 5 catches async route handler rejections natively; no extra polyfill needed. import express from 'express'; @@ -17,7 +22,7 @@ import compression from 'compression'; // same Room class identity, so the heuristic passes and instance hooks work. import { Server as ColyseusServer, matchMaker } from 'colyseus'; import { WebSocketTransport } from '@colyseus/ws-transport'; -import { createServer } from 'http'; +import { createServer, type IncomingMessage, type OutgoingHttpHeaders } from 'http'; import path from 'path'; import fs from 'fs'; import crypto from 'crypto'; @@ -28,9 +33,27 @@ import { WorldRoom } from './rooms/WorldRoom.js'; import { getApiPrismaClient, registerApi } from './api.js'; import { warnIfPublicBaseUrlUnusable } from './api/utils/publicLinks.js'; import { logger } from './logger.js'; -import { registry, metricsMiddleware } from './metrics.js'; +import { metricsMiddleware } from './metrics.js'; +import { resolveMetricsBind, startMetricsServer, type MetricsServer } from './ops/metricsServer.js'; +import { createToolsRoute, parseToolsApiOrigins, toolsBaseCsp } from './ops/toolsRoute.js'; +import { installOriginGuard } from './ops/originGuard.js'; +import { createWsUpgradeLimiter, resolveWsUpgradeLimit, type WsUpgradeLimitSettings } from './ops/wsUpgradeLimit.js'; +import { + ALLOWED_MAX_AGE, + ALLOWED_REQUEST_HEADERS, + ALLOWED_REQUEST_METHODS, + EXPOSED_RESPONSE_HEADERS, + ORIGIN_ENV_KEY, + corsHeadersFor, + isUpgradeOriginAllowed, + keepsOwnCorsContract, + resolveOriginPolicy, +} from './ops/originPolicy.js'; +import { isRestorePending } from './services/tenantDeletionRestoreMarker.js'; +import { checkDeletionJournalConfig } from './services/deletionJournalConfig.js'; import { tenantMiddleware } from './tenancy.js'; import { requestLogger } from './api/requestLogger.js'; +import { registerNpcMediaStatic } from './api/routes/npcMedia.js'; import { errorHandler } from './api/errorHandler.js'; import { dynamicApiCacheControl } from './api/middleware/dynamicCacheControl.js'; import { getBillingModule } from './billingLoader.js'; @@ -43,47 +66,63 @@ import { installPartitionKeyValidation, } from './matchmake/tenantPartition.js'; import { assertBaseAvatarAvailable, listenAfterStartupChecks } from './services/startupInvariant.js'; +import { startDeletionTaskWorker } from './services/deletionTaskScheduler.js'; + +// The origin allowlist is read once, before anything is served. A missing or +// malformed list is not a startable configuration: the server refuses to start +// and names the key, never the value. Development needs an explicit local +// list as well - there is no automatic loopback or desktop allowance. +const originConfig = resolveOriginPolicy(process.env); +if (!originConfig.ok) { + process.stderr.write( + `${ORIGIN_ENV_KEY} is missing or invalid: list the exact allowed origins, ` + + 'comma-separated (scheme://host[:port]).\n', + ); + process.exit(1); +} +const originPolicy = originConfig.policy; + +// The official desktop app (Tauri) reports `tauri://localhost` on macOS/Linux +// and `http://tauri.localhost` on Windows. Both are ordinary origins now: the +// deployment lists them in CORS_ORIGIN, like every other client. // Colyseus 0.17 registers a prependListener('request', ...) on the HTTP server -// that answers CORS preflights directly with DEFAULT_CORS_HEADERS, before -// any Express middleware runs. As a result our custom headers -// (x-correlation-id, x-tenant, x-av-identity, x-av-room) do not appear on -// OPTIONS responses. Override getCorsHeaders so the custom headers are -// returned in the preflight response and the Origin is echoed correctly. -const ALLOWED_REQUEST_HEADERS = - 'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-tenant, x-correlation-id, x-av-identity, x-av-room'; -matchMaker.controller.getCorsHeaders = (headers) => { - const origin = headers.get('origin') || '*'; - const requested = headers.get('access-control-request-headers'); - return { - 'Access-Control-Allow-Origin': origin, - 'Access-Control-Allow-Credentials': 'true', - 'Access-Control-Allow-Headers': requested && requested.length > 0 ? requested : ALLOWED_REQUEST_HEADERS, - 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS', - 'Access-Control-Expose-Headers': 'x-correlation-id', - Vary: 'Origin', - }; +// that answers CORS preflights directly with its own headers, before any +// Express middleware runs. Those headers are replaced here: the origin policy +// decides what is echoed, and a request without an allowed origin gets no CORS +// headers at all. The defaults are emptied for the same reason - they carry a +// wildcard origin together with a credentials flag. +matchMaker.controller.DEFAULT_CORS_HEADERS = { + 'Access-Control-Allow-Headers': ALLOWED_REQUEST_HEADERS, + 'Access-Control-Allow-Methods': ALLOWED_REQUEST_METHODS, + 'Access-Control-Allow-Credentials': '', + 'Access-Control-Allow-Origin': '', + 'Access-Control-Max-Age': ALLOWED_MAX_AGE, }; +matchMaker.controller.getCorsHeaders = (headers) => ({ + ...corsHeadersFor(headers.get('origin'), originPolicy), + Vary: 'Origin', +}); // Refuse a malformed or unknown world partition key (`options.tenant`) before // Colyseus looks for or creates a room; see matchmake/tenantPartition.ts. installPartitionKeyValidation(createTenantExistsLookup(getApiPrismaClient)); const app = express(); -const allowedOrigins = (process.env.CORS_ORIGIN || '') - .split(',') - .map((s) => s.trim()) - .filter((s) => s.length > 0); - -// First-party origins for the official Meetropolis desktop app (Tauri). Windows -// WebView2 reports `http://tauri.localhost`; macOS/Linux report `tauri://localhost`. -// These are fixed origins a browser page cannot forge (only a Tauri shell emits -// them), so allow them by default - independent of CORS_ORIGIN - so the desktop -// client never breaks when the deployed env allowlist drifts. -const DESKTOP_CLIENT_ORIGINS = ['tauri://localhost', 'http://tauri.localhost']; const trustProxy = resolveTrustProxySetting(); app.set('trust proxy', trustProxy); +// The budget for websocket upgrades is resolved once, before the transport +// exists: a value that is set but unusable is not a startable configuration. +// The error names the key, never the value. +let wsUpgradeLimitSettings: WsUpgradeLimitSettings; +try { + wsUpgradeLimitSettings = resolveWsUpgradeLimit(process.env); +} catch (err) { + logger.error(err instanceof Error ? err.message : String(err), { event: 'startup.invalid_ws_upgrade_limit' }); + process.exit(1); +} + app.use(helmet({ contentSecurityPolicy: false })); // Force revalidation on dynamic public/billing/admin API responses (see // dynamicCacheControl.ts). Registered before the route table (registerApi @@ -94,80 +133,47 @@ app.use(compression()); // Prometheus HTTP metrics. app.use(metricsMiddleware()); -// CORS middleware with explicit OPTIONS handling +// CORS for the Express routes. The origin guard in front of every request +// listener has already refused a foreign origin; what is left here is the +// header contract for the allowed ones. A request without an origin is not a +// browser request: it gets no CORS headers and the route's own auth decides. app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { - // Static asset routes handle their own CORS headers; skip the global check. - if ( - req.path.startsWith('/packs') || - req.path.startsWith('/assets') || - req.path.startsWith('/npc-media') || - req.path.startsWith('/tools') - ) { + // Static asset routes and the operator tools handle their own CORS headers. + if (keepsOwnCorsContract(req.path)) { return next(); } - const origin = req.headers.origin as string; - - const isProduction = process.env.NODE_ENV === 'production'; - - // Same-origin requests (e.g. from /tools pages) are always allowed - const host = req.headers.host; - const isSameOrigin = origin && host && (origin === `https://${host}` || origin === `http://${host}`); - - const isDesktopClient = !!origin && DESKTOP_CLIENT_ORIGINS.includes(origin); - - if (isDesktopClient) { - // Official desktop app (Tauri): a fixed first-party origin, always allowed - // regardless of CORS_ORIGIN so an env-allowlist drift never locks it out. - res.setHeader('Access-Control-Allow-Origin', origin); - } else if (allowedOrigins.length > 0) { - if (isSameOrigin || (origin && allowedOrigins.includes(origin))) { - res.setHeader('Access-Control-Allow-Origin', origin); - } else if (isProduction && origin) { - // In production, block requests from non-whitelisted origins - logger.warn({ event: 'cors.origin_not_allowed', origin, allowedOrigins }); - return res.status(403).json({ error: 'cors_origin_not_allowed' }); - } else if (origin) { - // Development: allow any origin even if CORS_ORIGIN is set - res.setHeader('Access-Control-Allow-Origin', origin); - } - } else if (isProduction) { - // SECURITY: In production, CORS_ORIGIN must be configured - logger.error({ event: 'cors.no_whitelist_in_production', origin }); - return res.status(500).json({ error: 'cors_not_configured' }); - } else { - // Development only: allow any origin for easier local development - if (origin) { - res.setHeader('Access-Control-Allow-Origin', origin); - } else { - res.setHeader('Access-Control-Allow-Origin', '*'); - } + const origin = req.headers.origin; + + if (origin === undefined) { + res.removeHeader('Access-Control-Allow-Origin'); + res.removeHeader('Access-Control-Allow-Credentials'); + res.removeHeader('Access-Control-Allow-Headers'); + res.removeHeader('Access-Control-Allow-Methods'); + res.removeHeader('Access-Control-Expose-Headers'); + return next(); + } + + if (!originPolicy.isAllowed(origin)) { + logger.warn({ event: 'cors.origin_not_allowed', origin }); + return res.status(403).json({ error: 'cors_origin_not_allowed' }); } - // Always vary by Origin for proper CDN/proxy caching - res.setHeader('Vary', 'Origin'); - // Credentials are needed for cookie-based auth - // If no Origin is provided, some browsers may reject '*' with credentials. - // We only set '*' when there's no origin and rely on proxies to strip credentials in that case. + res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Access-Control-Allow-Credentials', 'true'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS'); - // Allow requested headers dynamically, fallback to known list including custom correlation headers - const reqHeaders = req.headers['access-control-request-headers']?.toString(); - const allowed = - reqHeaders && reqHeaders.length > 0 - ? reqHeaders - : 'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-tenant, x-correlation-id, x-av-identity, x-av-room'; - res.setHeader('Access-Control-Allow-Headers', allowed); - // Expose custom response headers so browsers can read them in CORS mode - res.setHeader('Access-Control-Expose-Headers', 'x-correlation-id'); + res.setHeader('Access-Control-Allow-Methods', ALLOWED_REQUEST_METHODS); + // A fixed list of request headers, never the ones the caller asked for. + res.setHeader('Access-Control-Allow-Headers', ALLOWED_REQUEST_HEADERS); + res.setHeader('Access-Control-Expose-Headers', EXPOSED_RESPONSE_HEADERS); + // The answer differs per origin: extend the existing Vary header. + res.vary('Origin'); if (req.method === 'OPTIONS') { // Cache preflight responses to reduce roundtrips (24h) - res.setHeader('Access-Control-Max-Age', '86400'); + res.setHeader('Access-Control-Max-Age', ALLOWED_MAX_AGE); return res.sendStatus(204); - } else { - next(); } + next(); }); app.use(cookieParser()); @@ -249,24 +255,7 @@ app.use( }), ); -// Static serving for NPC Media -const npcMediaDir = process.env.NPC_MEDIA_DIR || path.resolve(__dirname, '../../../npc-media'); -try { - fs.mkdirSync(npcMediaDir, { recursive: true }); -} catch (error) { - logger.error({ event: 'filesystem.mkdir_failed', path: npcMediaDir, error }); -} -app.use( - '/npc-media', - express.static(npcMediaDir, { - maxAge: '7d', - setHeaders: (res) => { - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); - res.removeHeader('Access-Control-Allow-Credentials'); - }, - }), -); +registerNpcMediaStatic(app); // ── Basic Auth Middleware for Admin Tools ── function basicAuthMiddleware( @@ -289,35 +278,48 @@ function basicAuthMiddleware( }; } -// Static serving for Admin Tools (Basic Auth protected) +function sendPublicMetricsNotFound(_req: express.Request, res: express.Response): void { + res.status(404).end(); +} + +// Admin Tools (Basic Auth protected). Only the six allowed tool files are +// served, every other path below /tools answers 404. Every response of the +// mount carries a Content-Security-Policy; the allowed file replaces the +// fallback policy with its own, computed from its own bytes. const toolsUser = process.env.TOOLS_USER; const toolsPassword = process.env.TOOLS_PASSWORD; if (toolsUser && toolsPassword) { const toolsDir = path.resolve(__dirname, '../../../tools'); - const htmlOnly = (req: express.Request, res: express.Response, next: express.NextFunction) => { - if (req.path !== '/' && !req.path.endsWith('.html')) { - return res.status(404).send('Not found'); - } - next(); - }; - app.use('/tools', basicAuthMiddleware(toolsUser, toolsPassword), htmlOnly, express.static(toolsDir)); + const toolsRoute = createToolsRoute({ + toolsDir, + apiOrigins: parseToolsApiOrigins(process.env.TOOLS_API_ORIGINS), + }); + app.use('/tools', toolsBaseCsp, basicAuthMiddleware(toolsUser, toolsPassword), toolsRoute); logger.info({ event: 'tools.route_enabled', path: '/tools' }); } else { logger.info({ event: 'tools.route_disabled', reason: 'TOOLS_USER or TOOLS_PASSWORD not set' }); } +// A restored database must not serve before the restore replay has run; +// scripts/replayTenantDeletions.js removes the marker when it is done. +const restoreJournalDir = process.env.DELETION_JOURNAL_DIR?.trim(); +if (restoreJournalDir && (await isRestorePending(restoreJournalDir))) { + logger.error({ event: 'tenant_delete.restore_pending' }); + process.exit(1); +} + +const journalConfig = checkDeletionJournalConfig(process.env); +if (!journalConfig.ok) { + logger.error({ event: 'deletion_journal.config_invalid', key: journalConfig.key }); + process.exit(1); +} + await registerApi(app); warnIfPublicBaseUrlUnusable(); -// Expose Prometheus Metriken -app.get('/metrics', async (_req, res) => { - try { - res.set('Content-Type', registry.contentType); - res.end(await registry.metrics()); - } catch (_e) { - res.status(500).send('metrics error'); - } -}); +// Public /metrics is never a scrape target. Prometheus uses METRICS_PORT. +app.head('/metrics', sendPublicMetricsNotFound); +app.get('/metrics', sendPublicMetricsNotFound); const port = Number(process.env.PORT ?? 2567); const httpServer = createServer(app); @@ -327,9 +329,40 @@ httpServer.on('error', (err) => { // Attach to existing HTTP server; compatible with Colyseus 0.15+ // Colyseus Server with WebSocketTransport +const wsUpgradeLimiter = createWsUpgradeLimiter(wsUpgradeLimitSettings, trustProxy); const gameServer = new ColyseusServer({ transport: new WebSocketTransport({ server: httpServer, + // Every upgrade attempt is counted first, so an exhausted budget answers + // 429 with a Retry-After instead of a handshake. Only then the origin + // policy decides: the upgrade is refused before the handshake when it + // carries an origin the policy does not allow. An upgrade without an + // origin stays bound to the matchmaking auth and the seat reservation. + verifyClient: ( + info: { origin: string | undefined; req: IncomingMessage }, + cb: (verified: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void, + ) => { + void wsUpgradeLimiter + .checkWsUpgrade(info.req) + .then((decision) => { + if (!decision.allowed) { + cb(false, 429, 'Too Many Requests', { 'Retry-After': String(decision.retryAfterSeconds) }); + return; + } + if (!isUpgradeOriginAllowed(originPolicy, info.origin)) { + cb(false); + return; + } + cb(true); + }) + .catch((error: unknown) => { + // The counter lives in memory and cannot fail in practice. If it + // does, the upgrade is refused instead of going uncounted; the + // record carries no data of the attempt. + logger.error('Websocket upgrade limit failed', error); + cb(false); + }); + }, }), }); @@ -359,7 +392,25 @@ try { process.exit(1); } +let metricsServer: MetricsServer | undefined; + +async function closeMetricsListener(): Promise { + if (metricsServer === undefined) return; + const pending = metricsServer; + metricsServer = undefined; + try { + await pending.close(); + } catch (error) { + logger.error('[Server] Error while closing metrics listener', error); + } +} + try { + const metricsBind = resolveMetricsBind(process.env, port); + if (metricsBind.listen) { + metricsServer = await startMetricsServer({ host: metricsBind.host, port: metricsBind.port }); + logger.info({ event: 'metrics.listening', port: metricsBind.port, host: metricsBind.host }); + } await listenAfterStartupChecks( () => assertBaseAvatarAvailable(getApiPrismaClient()), () => @@ -371,12 +422,23 @@ try { // the guard can only be put in front of it now. No request is served in // between: the continuation of the awaited listen() runs before the next I/O // event. See matchmake/guard.ts. - installMatchmakeGuard(httpServer, { trustProxy }); + installMatchmakeGuard(httpServer, { trustProxy, originPolicy }); + // The origin guard goes in front of every request listener, so a foreign + // origin reaches neither the matchmaking route nor the Express app. + installOriginGuard(httpServer, { policy: originPolicy }); } catch (err) { logger.error('Server startup failed before listening', err); + await closeMetricsListener(); process.exit(1); } +// The deletion task worker runs only when a journal directory is configured. +let deletionTaskWorker: ReturnType | undefined; +const deletionJournalDir = process.env.DELETION_JOURNAL_DIR; +if (deletionJournalDir) { + deletionTaskWorker = startDeletionTaskWorker({ prisma: getApiPrismaClient(), journalDir: deletionJournalDir }); +} + // Central error handler last app.use(errorHandler); @@ -407,12 +469,23 @@ async function gracefulShutdown(signal: string) { await new Promise((resolve) => setTimeout(resolve, 5000)); + try { + await deletionTaskWorker?.stop(); + } catch (e) { + logger.error({ + event: 'tenant_deletion.worker_stop_failed', + errorName: e instanceof Error ? e.name : 'NonError', + }); + } + try { await gameServer.gracefullyShutdown(false); } catch (e) { logger.error('[Server] Error during graceful shutdown', e); } + await closeMetricsListener(); + process.exit(0); } diff --git a/apps/server/src/matchmake/guard.test.ts b/apps/server/src/matchmake/guard.test.ts index 2adf0331..5f06435f 100644 --- a/apps/server/src/matchmake/guard.test.ts +++ b/apps/server/src/matchmake/guard.test.ts @@ -9,6 +9,20 @@ import net, { type AddressInfo } from 'node:net'; import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib'; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +// The guard takes its CORS headers from the origin policy. The harness server +// carries no allowlist of its own, so the environment provides the one origin +// the tests below send. +const previousCorsOrigin = process.env.CORS_ORIGIN; + +beforeAll(() => { + process.env.CORS_ORIGIN = 'https://app.example'; +}); + +afterAll(() => { + if (previousCorsOrigin === undefined) delete process.env.CORS_ORIGIN; + else process.env.CORS_ORIGIN = previousCorsOrigin; +}); + vi.mock('../logger.js', () => ({ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, })); @@ -273,7 +287,9 @@ describe('matchmake guard: rate limit', () => { const server = await startMatchmakeServer({ trustProxy: 1 }); try { const body = JSON.stringify({ tenant: 'acme' }); - const from = (ip: string) => ({ headers: { 'x-forwarded-for': ip } }); + // The origin is the one the allowlist above allows: a refusal must stay + // readable for the browser that sent it. + const from = (ip: string) => ({ headers: { 'x-forwarded-for': ip, origin: 'https://app.example' } }); for (let i = 0; i < 5; i++) { expect((await matchmake(server, body, from('203.0.113.7'))).status).toBe(200); } diff --git a/apps/server/src/matchmake/guard.ts b/apps/server/src/matchmake/guard.ts index 8419b369..385b9d2a 100644 --- a/apps/server/src/matchmake/guard.ts +++ b/apps/server/src/matchmake/guard.ts @@ -1,10 +1,10 @@ import express, { type ErrorRequestHandler, type RequestHandler } from 'express'; -import type { IncomingHttpHeaders, IncomingMessage, RequestListener, Server } from 'http'; +import type { IncomingMessage, RequestListener, Server } from 'http'; import { BlockList, isIP } from 'net'; -import { matchMaker } from 'colyseus'; import { createMatchmakeRateLimiter } from '../api/middleware/rateLimit.js'; import { AppError } from '../errors/AppError.js'; import { logger } from '../logger.js'; +import { corsHeadersFor, resolveOriginPolicy, type OriginPolicy } from '../ops/originPolicy.js'; import { resolveTrustProxySetting } from '../trustProxy.js'; /** @@ -173,27 +173,19 @@ class MatchmakeRejection extends Error { } } -function toFetchHeaders(headers: IncomingHttpHeaders): Headers { - const out = new Headers(); - for (const [name, value] of Object.entries(headers)) { - if (value === undefined) continue; - out.set(name, Array.isArray(value) ? value.join(', ') : value); - } - return out; -} - /** * The guard answers before Colyseus gets to set its CORS headers, so a refusal * must carry them itself or a browser could not read why a join was refused. + * The headers come from the origin policy and not from Colyseus: only an + * allowed origin is echoed, a request without an origin gets none at all. */ -const applyCorsHeaders: RequestHandler = (req, res, next) => { - const cors = { - ...matchMaker.controller.DEFAULT_CORS_HEADERS, - ...matchMaker.controller.getCorsHeaders(toFetchHeaders(req.headers)), +function applyCorsHeaders(policy: OriginPolicy): RequestHandler { + return (req, res, next) => { + for (const [name, value] of Object.entries(corsHeadersFor(req.headers.origin, policy))) res.setHeader(name, value); + res.vary('Origin'); + next(); }; - for (const [name, value] of Object.entries(cors)) res.setHeader(name, value); - next(); -}; +} // Refuse a body that announces itself as too large without reading any of it. // The streaming cap in express.json still covers chunked bodies and lying @@ -284,6 +276,8 @@ export interface MatchmakeGuardOptions { rateLimiter?: RequestHandler; /** Callers the rate limiter leaves alone. Defaults to {@link isInProcessCaller}; tests replace it. */ isInProcessCaller?: (req: Pick) => boolean; + /** The origin policy the CORS headers come from. Defaults to the environment. */ + originPolicy?: OriginPolicy; } /** Build the guard as a request listener that hands accepted requests to `forward`. */ @@ -291,7 +285,7 @@ export function createMatchmakeGuard(forward: RequestListener, options: Matchmak const guard = express(); guard.disable('x-powered-by'); guard.set('trust proxy', options.trustProxy ?? resolveTrustProxySetting()); - guard.use(applyCorsHeaders); + guard.use(applyCorsHeaders(options.originPolicy ?? resolveOriginPolicy(process.env).policy)); const rateLimiter = options.rateLimiter ?? createMatchmakeRateLimiter(); const inProcess = options.isInProcessCaller ?? isInProcessCaller; guard.use((req, res, next) => { diff --git a/apps/server/src/metrics.ts b/apps/server/src/metrics.ts index 5f858db3..ed13a050 100644 --- a/apps/server/src/metrics.ts +++ b/apps/server/src/metrics.ts @@ -75,7 +75,7 @@ registry.registerMetric(livekitPacketLossRatio); export function metricsMiddleware(): RequestHandler { return function (req: Request, res: Response, next: NextFunction) { const start = process.hrtime.bigint(); - // The route is only known after routing; unmatched requests are labelled "". + // The route becomes available after routing; unmatched requests use "". res.on('finish', () => { try { const end = process.hrtime.bigint(); diff --git a/apps/server/src/ops/credentialPolicy.ts b/apps/server/src/ops/credentialPolicy.ts new file mode 100644 index 00000000..a0fa4869 --- /dev/null +++ b/apps/server/src/ops/credentialPolicy.ts @@ -0,0 +1,95 @@ +/** + * Production credential policy for the main server start path. + * + * Pure helper: inspects only the given environment mapping and returns the + * names of keys that violate the production rules. It never prints values, + * never touches the database or the network, and never imports the + * application graph, so the boot adapter and later seed tooling can share + * the same mode detection and rules without side effects. + */ + +const PRODUCTION_MODE = 'production'; + +// Known public template placeholders. Derived once from the versioned +// template state (.env.example: key entries for the LiveKit pair, the +// database url, the database password, and the tools password) and kept in +// this single place instead of spreading a second list across readers. +const TEMPLATE_LIVEKIT_API_KEY = 'devkey'; +const TEMPLATE_LIVEKIT_API_SECRET = 'secret'; +const TEMPLATE_TOOLS_PASSWORD = 'changeme'; +// Password part shared by the versioned template entries for DATABASE_URL +// and POSTGRES_PASSWORD. +const TEMPLATE_DATABASE_PASSWORD = 'postgres'; + +export function isProductionEnvironment(env: Record): boolean { + return env.NODE_ENV === PRODUCTION_MODE; +} + +function isUsableSecret(value: string | undefined, blocked: readonly string[]): boolean { + if (value === undefined) { + return false; + } + const trimmed = value.trim(); + if (trimmed.length === 0) { + return false; + } + return !blocked.includes(trimmed); +} + +// Resolves the effective database password the driver would use: a password +// carried by the url query takes precedence over the userinfo password, and +// percent-encoding never bypasses the comparison. Returns null when no +// usable password can be determined. +function extractDatabasePassword(value: string): string | null { + let url: URL; + try { + url = new URL(value); + } catch { + return null; + } + if (url.protocol !== 'postgresql:' && url.protocol !== 'postgres:') { + return null; + } + const queryPassword = url.searchParams.get('password'); + if (queryPassword !== null) { + return queryPassword; + } + try { + return decodeURIComponent(url.password); + } catch { + return null; + } +} + +function isUsableDatabaseUrl(value: string | undefined): boolean { + if (value === undefined || value.trim().length === 0) { + return false; + } + const password = extractDatabasePassword(value); + return password !== null && isUsableSecret(password, [TEMPLATE_DATABASE_PASSWORD]); +} + +export function findInvalidCredentialKeys(env: Record): string[] { + if (!isProductionEnvironment(env)) { + return []; + } + const invalid: string[] = []; + if (!isUsableSecret(env.LIVEKIT_API_KEY, [TEMPLATE_LIVEKIT_API_KEY])) { + invalid.push('LIVEKIT_API_KEY'); + } + if (!isUsableSecret(env.LIVEKIT_API_SECRET, [TEMPLATE_LIVEKIT_API_SECRET])) { + invalid.push('LIVEKIT_API_SECRET'); + } + if (!isUsableDatabaseUrl(env.DATABASE_URL)) { + invalid.push('DATABASE_URL'); + } + const postgresPassword = env.POSTGRES_PASSWORD; + if (postgresPassword !== undefined && !isUsableSecret(postgresPassword, [TEMPLATE_DATABASE_PASSWORD])) { + invalid.push('POSTGRES_PASSWORD'); + } + const toolsPassword = env.TOOLS_PASSWORD; + if (toolsPassword !== undefined && toolsPassword !== '' && !isUsableSecret(toolsPassword, [TEMPLATE_TOOLS_PASSWORD])) { + invalid.push('TOOLS_PASSWORD'); + } + return invalid; +} diff --git a/apps/server/src/ops/metricsAccess.integration.test.ts b/apps/server/src/ops/metricsAccess.integration.test.ts new file mode 100644 index 00000000..2b92aa22 --- /dev/null +++ b/apps/server/src/ops/metricsAccess.integration.test.ts @@ -0,0 +1,373 @@ +/** + * Access boundary for Prometheus metrics: the public app answers 404 for + * GET/HEAD /metrics, and a separate listener (METRICS_PORT) serves scrape + * traffic. Spawns the real server process. Ports come from the environment + * or, if those keys are unset, from ephemeral loopback binds whose assigned + * ports are read back. Credentials are generated at runtime and never logged. + */ + +import { spawn, type ChildProcess } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, it } from 'vitest'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SERVER_DIR = path.resolve(HERE, '..', '..'); +const PUBLIC_PORT_KEY = 'METRICS_ACCESS_PUBLIC_PORT'; +const INTERNAL_PORT_KEY = 'METRICS_ACCESS_INTERNAL_PORT'; +const READY_PATH = '/healthz'; +const START_TIMEOUT_MS = 60_000; +const STOP_TIMEOUT_MS = 20_000; +const PORT_PROBE_MS = 5_000; + +interface HttpProbe { + kind: 'http'; + status: number; + contentType: string | null; + body: string; +} + +interface ConnectionProbe { + kind: 'connection'; + code: string; +} + +type Probe = HttpProbe | ConnectionProbe; + +interface RunningServer { + child: ChildProcess; + publicPort: number; + metricsPort: number; +} + +const children: ChildProcess[] = []; +const blockers: net.Server[] = []; + +afterEach(async () => { + while (children.length > 0) { + const child = children.pop(); + if (child) await stopChild(child); + } + while (blockers.length > 0) { + const blocker = blockers.pop(); + if (blocker) await closeServer(blocker); + } +}); + +describe('metrics access', { timeout: 180_000 }, () => { + it('returns 404 for GET /metrics on the public app', async () => { + const server = await startServer({ metrics: true }); + const result = expectHttp( + await probe('GET', publicUrl(server, '/metrics'), { + cookie: 'session=synthetic-session', + authorization: 'Basic c3ludGhldGljOnN5bnRoZXRpYw==', + }), + ); + expect(result.status).toBe(404); + }); + + it('returns 404 for HEAD /metrics on the public app', async () => { + const server = await startServer({ metrics: true }); + const result = expectHttp(await probe('HEAD', publicUrl(server, '/metrics'))); + expect(result.status).toBe(404); + }); + + it('serves Prometheus metrics on the internal listener', async () => { + const server = await startServer({ metrics: true }); + const result = expectHttp(await probe('GET', metricsUrl(server, '/metrics'))); + expect(result.status).toBe(200); + expect(result.contentType ?? '').toContain('text/plain'); + expect(result.body).toContain('meetropolis_'); + }); + + it('returns 404 for unknown paths on the internal listener', async () => { + const server = await startServer({ metrics: true }); + const result = expectHttp(await probe('GET', metricsUrl(server, '/healthz'))); + expect(result.status).toBe(404); + expect(result.body).not.toContain('meetropolis_'); + }); + + it('starts the public app without binding the metrics port when unset', async () => { + const server = await startServer({ metrics: false }); + const ready = expectHttp(await probe('GET', publicUrl(server, READY_PATH))); + expect(ready.status).toBe(200); + const metrics = await probe('GET', metricsUrl(server, '/metrics')); + expect(metrics.kind).toBe('connection'); + }); + + it('does not become ready with an invalid metrics listener configuration', async () => { + const publicPort = await allocatePort(PUBLIC_PORT_KEY); + const metricsPort = await allocatePort(INTERNAL_PORT_KEY); + expect(publicPort).not.toBe(metricsPort); + await assertPortFree(publicPort); + await assertPortFree(metricsPort); + + const invalidPort = startChild({ publicPort, metricsPort: 'not-a-port' }); + expect(await waitForListeningOrExit(invalidPort, publicPort)).toBe('exited'); + await stopChild(invalidPort); + + const samePort = startChild({ publicPort, metricsPort: String(publicPort) }); + expect(await waitForListeningOrExit(samePort, publicPort)).toBe('exited'); + await stopChild(samePort); + + const blocker = await occupyPort(metricsPort); + blockers.push(blocker); + const bindFail = startChild({ publicPort, metricsPort: String(metricsPort) }); + expect(await waitForListeningOrExit(bindFail, publicPort)).toBe('exited'); + await stopChild(bindFail); + }); + + it('closes both listeners after shutdown', async () => { + const server = await startServer({ metrics: true }); + await stopChild(server.child); + await assertPortFree(server.publicPort); + await assertPortFree(server.metricsPort); + }); +}); + +function expectHttp(result: Probe): HttpProbe { + expect(result.kind).toBe('http'); + if (result.kind !== 'http') { + throw new Error('expected an HTTP response'); + } + return result; +} + +function publicUrl(server: RunningServer, pathname: string): string { + return `http://127.0.0.1:${server.publicPort}${pathname}`; +} + +function metricsUrl(server: RunningServer, pathname: string): string { + return `http://127.0.0.1:${server.metricsPort}${pathname}`; +} + +async function startServer(options: { metrics: boolean }): Promise { + const publicPort = await allocatePort(PUBLIC_PORT_KEY); + const metricsPort = await allocatePort(INTERNAL_PORT_KEY); + expect(publicPort).not.toBe(metricsPort); + await assertPortFree(publicPort); + await assertPortFree(metricsPort); + const child = startChild({ + publicPort, + metricsPort: options.metrics ? String(metricsPort) : undefined, + }); + const outcome = await waitForListeningOrExit(child, publicPort); + expect(outcome).toBe('listening'); + return { child, publicPort, metricsPort }; +} + +function startChild(options: { publicPort: number; metricsPort: string | undefined }): ChildProcess { + const child = spawn(process.execPath, [resolveTsx(), 'src/index.ts'], { + cwd: SERVER_DIR, + env: childEnv(options), + stdio: ['ignore', 'pipe', 'pipe'], + }); + child.stdout?.on('data', () => { + // Drain so a chatty child never blocks on a full pipe. + }); + child.stderr?.on('data', () => { + // Drain; never echo. The child env holds runtime credentials. + }); + children.push(child); + return child; +} + +function childEnv(options: { publicPort: number; metricsPort: string | undefined }): Record { + const env: Record = { + PATH: process.env.PATH ?? '/usr/bin:/bin', + NODE_ENV: 'production', + NODE_OPTIONS: '--no-warnings', + PORT: String(options.publicPort), + // The server refuses to start without an origin allowlist. This test does + // not exercise the origin rules, it only needs the server to come up. + CORS_ORIGIN: 'https://app.example', + DATABASE_URL: requiredDatabaseUrl(), + LIVEKIT_API_KEY: syntheticSecret(), + LIVEKIT_API_SECRET: syntheticSecret(), + JWT_SECRET: syntheticSecret(), + API_TOKEN_PEPPER: syntheticSecret(), + DOTENV_CONFIG_PATH: emptyEnvFile(), + LOG_LEVEL: 'error', + }; + if (options.metricsPort !== undefined) { + env.METRICS_PORT = options.metricsPort; + env.METRICS_HOST = '127.0.0.1'; + } + if (process.env.HOME) env.HOME = process.env.HOME; + if (process.env.TMPDIR) env.TMPDIR = process.env.TMPDIR; + return env; +} + +function requiredDatabaseUrl(): string { + const url = process.env.DATABASE_URL; + if (typeof url !== 'string' || url.length === 0) { + throw new Error('DATABASE_URL is required'); + } + return url; +} + +function syntheticSecret(): string { + return randomBytes(32).toString('hex'); +} + +let emptyEnvPath: string | undefined; + +function emptyEnvFile(): string { + if (emptyEnvPath === undefined) { + emptyEnvPath = path.join(os.tmpdir(), `metrics-access-empty-env-${process.pid}`); + fs.writeFileSync(emptyEnvPath, ''); + } + return emptyEnvPath; +} + +function resolveTsx(): string { + const scopedRequire = createRequire(path.join(SERVER_DIR, 'package.json')); + const packagePath = scopedRequire.resolve('tsx/package.json'); + const cliPath = path.join(path.dirname(packagePath), 'dist', 'cli.mjs'); + if (!fs.existsSync(cliPath)) { + throw new Error('tsx runner is missing'); + } + return cliPath; +} + +async function allocatePort(key: string): Promise { + const raw = process.env[key]; + if (raw !== undefined && raw !== '') { + const port = Number(raw); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`${key} must be set to an integer between 1 and 65535`); + } + return port; + } + return reserveLoopbackPort(); +} + +function reserveLoopbackPort(): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (address === null || typeof address === 'string') { + server.close(); + reject(new Error('failed to reserve a loopback port')); + return; + } + const port = address.port; + server.close((err) => { + if (err) reject(err); + else resolve(port); + }); + }); + }); +} + +function assertPortFree(port: number): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host: '127.0.0.1', port }); + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error(`test port ${port} did not refuse a connection in time`)); + }, PORT_PROBE_MS); + if (typeof timer.unref === 'function') timer.unref(); + socket.once('connect', () => { + clearTimeout(timer); + socket.destroy(); + reject(new Error(`test port ${port} is already in use; refusing a foreign process`)); + }); + socket.once('error', (error) => { + clearTimeout(timer); + if (errnoCode(error) === 'ECONNREFUSED') { + resolve(); + } else { + reject(error); + } + }); + }); +} + +function occupyPort(port: number): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(port, '127.0.0.1', () => resolve(server)); + }); +} + +function closeServer(server: net.Server): Promise { + return new Promise((resolve) => { + server.close(() => resolve()); + }); +} + +async function waitForListeningOrExit(child: ChildProcess, publicPort: number): Promise<'listening' | 'exited'> { + const deadline = Date.now() + START_TIMEOUT_MS; + const healthUrl = `http://127.0.0.1:${publicPort}${READY_PATH}`; + while (Date.now() < deadline) { + if (child.exitCode !== null || child.signalCode !== null) return 'exited'; + const result = await probe('GET', healthUrl); + if (result.kind === 'http') return 'listening'; + await sleep(50); + } + throw new Error('server neither listened nor exited'); +} + +function stopChild(child: ChildProcess): Promise { + if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(); + return new Promise((resolve) => { + const killTimer = setTimeout(() => { + child.kill('SIGKILL'); + const exitTimer = setTimeout(resolve, 5_000); + if (typeof exitTimer.unref === 'function') exitTimer.unref(); + child.once('exit', () => { + clearTimeout(exitTimer); + resolve(); + }); + }, STOP_TIMEOUT_MS); + if (typeof killTimer.unref === 'function') killTimer.unref(); + child.once('exit', () => { + clearTimeout(killTimer); + resolve(); + }); + child.kill('SIGTERM'); + }); +} + +async function probe(method: string, url: string, headers?: Record): Promise { + try { + const res = await fetch(url, { method, headers }); + const body = method === 'HEAD' ? '' : await res.text(); + return { + kind: 'http', + status: res.status, + contentType: res.headers.get('content-type'), + body, + }; + } catch (error) { + return { kind: 'connection', code: connectionCode(error) }; + } +} + +function errnoCode(error: unknown): string | undefined { + if (typeof error !== 'object' || error === null || !('code' in error)) return undefined; + return typeof error.code === 'string' ? error.code : undefined; +} + +function connectionCode(error: unknown): string { + const direct = errnoCode(error); + if (direct !== undefined) return direct; + if (typeof error === 'object' && error !== null && 'cause' in error) { + const nested = errnoCode(error.cause); + if (nested !== undefined) return nested; + } + return 'unknown'; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/server/src/ops/metricsServer.ts b/apps/server/src/ops/metricsServer.ts new file mode 100644 index 00000000..ee845d71 --- /dev/null +++ b/apps/server/src/ops/metricsServer.ts @@ -0,0 +1,110 @@ +/** + * Dedicated scrape listener for Prometheus. + * + * The public Express app always answers GET/HEAD /metrics with 404. This + * module binds an optional second HTTP server that serves only those two + * methods on /metrics. Unset METRICS_PORT leaves the listener off. The + * default host is loopback; Docker compose sets METRICS_HOST to the + * container interface and does not publish the port to the host. + */ + +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { logger } from '../logger.js'; +import { registry } from '../metrics.js'; + +const DEFAULT_HOST = '127.0.0.1'; + +export type MetricsBind = { listen: false } | { listen: true; port: number; host: string }; + +export interface MetricsServer { + readonly address: AddressInfo; + close(): Promise; +} + +export function resolveMetricsBind(env: NodeJS.ProcessEnv, publicPort: number): MetricsBind { + const rawPort = env.METRICS_PORT; + if (rawPort === undefined || rawPort.trim() === '') { + return { listen: false }; + } + const port = Number(rawPort); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error('METRICS_PORT is not a valid TCP port'); + } + if (port === publicPort) { + throw new Error('METRICS_PORT must differ from PORT'); + } + const rawHost = env.METRICS_HOST; + const host = rawHost === undefined || rawHost.trim() === '' ? DEFAULT_HOST : rawHost.trim(); + return { listen: true, port, host }; +} + +function requestPath(url: string | undefined): string { + if (url === undefined) return ''; + const q = url.indexOf('?'); + return q === -1 ? url : url.slice(0, q); +} + +async function sendMetrics(req: http.IncomingMessage, res: http.ServerResponse): Promise { + try { + const body = await registry.metrics(); + res.statusCode = 200; + res.setHeader('Content-Type', registry.contentType); + if (req.method === 'HEAD') { + res.setHeader('Content-Length', Buffer.byteLength(body)); + res.end(); + return; + } + res.end(body); + } catch { + res.statusCode = 500; + res.end('metrics error'); + } +} + +function handleRequest(req: http.IncomingMessage, res: http.ServerResponse): void { + const method = req.method ?? ''; + if ((method === 'GET' || method === 'HEAD') && requestPath(req.url) === '/metrics') { + void sendMetrics(req, res).catch(() => { + if (!res.writableEnded) { + res.statusCode = 500; + res.end(); + } + }); + return; + } + res.statusCode = 404; + res.end(); +} + +export function startMetricsServer(bind: { port: number; host: string }): Promise { + return new Promise((resolve, reject) => { + const server = http.createServer(handleRequest); + const fail = (err: Error): void => { + server.close(); + reject(err); + }; + server.once('error', fail); + server.listen(bind.port, bind.host, () => { + server.off('error', fail); + const address = server.address(); + if (address === null || typeof address === 'string') { + fail(new Error('metrics listener bound without a TCP address')); + return; + } + server.on('error', (err) => { + logger.error('metrics listener error', err); + }); + resolve({ + address, + close: () => + new Promise((closeResolve, closeReject) => { + server.close((closeErr) => { + if (closeErr) closeReject(closeErr); + else closeResolve(); + }); + }), + }); + }); + }); +} diff --git a/apps/server/src/ops/originAccess.integration.test.ts b/apps/server/src/ops/originAccess.integration.test.ts new file mode 100644 index 00000000..08e4154f --- /dev/null +++ b/apps/server/src/ops/originAccess.integration.test.ts @@ -0,0 +1,527 @@ +/** + * Origin access over the real HTTP, matchmaking and websocket path: one + * allowlist (CORS_ORIGIN) decides for every entry point. + * + * The server runs as a real child process (the same pattern as + * metricsAccess.integration.test.ts), so the Express middleware, the Colyseus + * matchmaking route and the websocket upgrade are the production ones. The + * application port comes from the environment or, when that key is unset, from + * an ephemeral loopback bind whose port is read back. Credentials are + * generated at runtime and never logged. + */ + +import { spawn, type ChildProcess } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import { createRequire } from 'node:module'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import type { Duplex } from 'node:stream'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SERVER_DIR = path.resolve(HERE, '..', '..'); +const PORT_KEY = 'ORIGIN_ACCESS_PORT'; +const READY_PATH = '/healthz'; +const MATCHMAKE_PATH = '/matchmake/joinOrCreate/world'; +const START_TIMEOUT_MS = 60_000; +const STOP_TIMEOUT_MS = 20_000; +const PORT_PROBE_MS = 5_000; + +/** The web client origin a deployment allows. */ +const WEB_ORIGIN = 'https://app.example'; +/** An origin no deployment allows. */ +const FOREIGN_ORIGIN = 'https://foreign.example'; +/** The two origins the official desktop app reports. */ +const DESKTOP_ORIGINS: ReadonlyArray<[string, string]> = [ + ['the macOS desktop origin', 'tauri://localhost'], + ['the Windows desktop origin', 'http://tauri.localhost'], +]; + +interface RunningServer { + child: ChildProcess; + port: number; + metricsPort: number | undefined; +} + +interface HttpProbe { + status: number; + headers: http.IncomingHttpHeaders; + body: string; +} + +interface UpgradeOutcome { + /** The status the server answered with: 101 for an accepted handshake. */ + status: number; + /** The socket of an accepted handshake; the caller closes it. */ + socket: Duplex | undefined; +} + +describe('origin access', { timeout: 180_000 }, () => { + let development: RunningServer; + let production: RunningServer; + let withoutAllowlistPort: number; + + beforeAll(async () => { + // All listeners of this file get a port of their own: they run at the + // same time, so the ports are reserved together and read back. + const ports = await reserveLoopbackPorts(4); + withoutAllowlistPort = ports[2]; + development = await startServer({ + port: ports[0], + mode: 'development', + origins: [WEB_ORIGIN], + metrics: false, + }); + production = await startServer({ + port: configuredPort() ?? ports[1], + mode: 'production', + origins: [WEB_ORIGIN, ...DESKTOP_ORIGINS.map(([, origin]) => origin)], + metrics: true, + metricsPort: ports[3], + }); + }); + + afterAll(async () => { + await stopServer(development); + await stopServer(production); + }); + + it('refuses a foreign origin on an express route in development', async () => { + const result = await probe('GET', publicUrl(development, READY_PATH), { origin: FOREIGN_ORIGIN }); + expect(result.status).toBe(403); + expect(header(result, 'access-control-allow-origin')).toBe(''); + expect(header(result, 'access-control-allow-credentials')).toBe(''); + }); + + it('refuses a foreign origin on the matchmaking preflight', async () => { + const result = await probe('OPTIONS', publicUrl(production, MATCHMAKE_PATH), { + origin: FOREIGN_ORIGIN, + 'access-control-request-method': 'POST', + }); + expect(result.status).toBe(403); + expect(header(result, 'access-control-allow-origin')).toBe(''); + expect(header(result, 'access-control-allow-credentials')).toBe(''); + }); + + it('does not echo an arbitrary request header', async () => { + const result = await probe('GET', publicUrl(production, READY_PATH), { + origin: WEB_ORIGIN, + 'access-control-request-headers': 'x-injected-header', + }); + expect(result.status).toBe(200); + const allowed = header(result, 'access-control-allow-headers'); + expect(allowed).not.toContain('x-injected-header'); + expect(allowed).toContain('Authorization'); + }); + + it('allows the trace header the browser telemetry adds to every request', async () => { + for (const path of [READY_PATH, MATCHMAKE_PATH]) { + const result = await probe('OPTIONS', publicUrl(production, path), { + origin: WEB_ORIGIN, + 'access-control-request-method': 'POST', + 'access-control-request-headers': 'content-type,traceparent', + }); + expect(header(result, 'access-control-allow-headers').toLowerCase(), path).toContain('traceparent'); + } + }); + + it('refuses a desktop origin the allowlist does not name', async () => { + const result = await probe('GET', publicUrl(development, READY_PATH), { origin: 'tauri://localhost' }); + expect(result.status).toBe(403); + expect(header(result, 'access-control-allow-origin')).toBe(''); + }); + + it('refuses to start in production without an origin allowlist', async () => { + await assertPortFree(withoutAllowlistPort); + const child = startChild({ + port: withoutAllowlistPort, + metricsPort: undefined, + mode: 'production', + origins: undefined, + }); + let stderr = ''; + child.stderr?.on('data', (chunk: Buffer) => { + stderr += chunk.toString('utf8'); + }); + const outcome = await waitForListeningOrExit(child, withoutAllowlistPort); + await stopChild(child); + expect(outcome).toBe('exited'); + // Only a boolean, so a failure never prints what the child wrote. + expect(stderr.includes('CORS_ORIGIN')).toBe(true); + }); + + it('refuses a websocket upgrade from a foreign origin before the handshake', async () => { + const outcome = await upgradeHandshake(production.port, { origin: FOREIGN_ORIGIN }); + expect(outcome.status).not.toBe(101); + expect(outcome.status).toBeGreaterThanOrEqual(400); + }); + + it('refuses a websocket upgrade with a null origin before the handshake', async () => { + const outcome = await upgradeHandshake(production.port, { origin: 'null' }); + expect(outcome.status).not.toBe(101); + expect(outcome.status).toBeGreaterThanOrEqual(400); + }); + + it('serves an allowed web origin with the exact allow headers', async () => { + const result = await probe('GET', publicUrl(production, READY_PATH), { origin: WEB_ORIGIN }); + expect(result.status).toBe(200); + expect(header(result, 'access-control-allow-origin')).toBe(WEB_ORIGIN); + expect(header(result, 'access-control-allow-credentials')).toBe('true'); + expect(header(result, 'vary')).toContain('Origin'); + }); + + it.each(DESKTOP_ORIGINS)('serves %s when the allowlist names it', async (_label, origin) => { + const result = await probe('GET', publicUrl(production, READY_PATH), { origin }); + expect(result.status).toBe(200); + expect(header(result, 'access-control-allow-origin')).toBe(origin); + }); + + it('leaves an originless request to the auth of the route', async () => { + const result = await probe('GET', publicUrl(production, '/auth/me')); + expect(result.status).toBe(401); + expect(result.body).toContain('unauthorized'); + }); + + it('accepts an originless upgrade but lets it reach no room', async () => { + const roomsBefore = await roomCount(production); + const outcome = await upgradeHandshake(production.port, {}); + expect(outcome.status).toBe(101); + // The upgrade carries no seat reservation, so no room was joined and no + // world was touched: the room counter does not move. + expect(await roomCount(production)).toBe(roomsBefore); + outcome.socket?.destroy(); + }); + + it('serves an originless health check without cors headers', async () => { + const result = await probe('GET', publicUrl(production, READY_PATH)); + expect(result.status).toBe(200); + expect(header(result, 'access-control-allow-origin')).toBe(''); + }); + + it('passes an originless matchmaking request on to matchmaking', async () => { + // joinById of an unknown room: reaches matchmaking without creating a room. + const result = await probe('POST', publicUrl(production, '/matchmake/joinById/originless-probe'), { + 'content-type': 'application/json', + }); + expect(result.body).not.toContain('cors_origin_not_allowed'); + }); +}); + +function publicUrl(server: RunningServer, pathname: string): string { + return `http://127.0.0.1:${server.port}${pathname}`; +} + +/** + * A plain HTTP request with exactly the headers the test asks for. The raw + * client is used on purpose: a higher level client may drop or rewrite the + * headers this test is about. + */ +function probe(method: string, url: string, headers: Record = {}): Promise { + return new Promise((resolve, reject) => { + const target = new URL(url); + const request = http.request( + { + host: target.hostname, + port: target.port, + path: `${target.pathname}${target.search}`, + method, + headers, + }, + (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk: string) => { + body += chunk; + }); + response.on('end', () => { + resolve({ status: response.statusCode ?? 0, headers: response.headers, body }); + }); + }, + ); + request.on('error', reject); + request.end(); + }); +} + +function header(probeResult: HttpProbe, name: string): string { + const value = probeResult.headers[name]; + if (value === undefined) return ''; + return Array.isArray(value) ? value.join(', ') : value; +} + +/** The number of rooms the server currently holds, read from its metrics. */ +async function roomCount(server: RunningServer): Promise { + if (server.metricsPort === undefined) throw new Error('the server has no metrics listener'); + const res = await fetch(`http://127.0.0.1:${server.metricsPort}/metrics`); + const body = await res.text(); + const match = /^meetropolis_colyseus_rooms (\d+(?:\.\d+)?)$/m.exec(body); + if (match === null) throw new Error('the metrics carry no room counter'); + return Number(match[1]); +} + +/** + * A raw websocket handshake against the server: the answer tells whether the + * upgrade was accepted (101) or refused before the handshake. + */ +function upgradeHandshake(port: number, headers: Record): Promise { + return new Promise((resolve, reject) => { + const request = http.request({ + host: '127.0.0.1', + port, + path: '/', + method: 'GET', + headers: { + connection: 'Upgrade', + upgrade: 'websocket', + 'sec-websocket-key': randomBytes(16).toString('base64'), + 'sec-websocket-version': '13', + ...headers, + }, + }); + request.on('upgrade', (_response, socket) => { + // The frames of the server are of no interest here, but the socket has + // to be drained so that its events arrive. + socket.resume(); + resolve({ status: 101, socket }); + }); + request.on('response', (response) => { + response.resume(); + resolve({ status: response.statusCode ?? 0, socket: undefined }); + }); + request.on('error', reject); + request.end(); + }); +} + +interface ServerOptions { + port: number; + mode: 'development' | 'production'; + /** The allowlist of the server; absent means the key is not set at all. */ + origins: string[] | undefined; + /** Whether the server gets a scrape listener for the room counter. */ + metrics: boolean; + /** The port of that scrape listener. */ + metricsPort: number | undefined; +} + +async function startServer(options: ServerOptions): Promise { + await assertPortFree(options.port); + if (options.metricsPort !== undefined) await assertPortFree(options.metricsPort); + const child = startChild({ + port: options.port, + metricsPort: options.metricsPort, + mode: options.mode, + origins: options.origins, + }); + const outcome = await waitForListeningOrExit(child, options.port); + expect(outcome).toBe('listening'); + return { child, port: options.port, metricsPort: options.metricsPort }; +} + +async function stopServer(server: RunningServer | undefined): Promise { + if (server === undefined) return; + await stopChild(server.child); + await assertPortFree(server.port); +} + +function startChild(options: { + port: number; + metricsPort: number | undefined; + mode: 'development' | 'production'; + origins: string[] | undefined; +}): ChildProcess { + const child = spawn(process.execPath, [resolveTsx(), 'src/index.ts'], { + cwd: SERVER_DIR, + env: childEnv(options), + stdio: ['ignore', 'pipe', 'pipe'], + }); + child.stdout?.on('data', () => { + // Drain so a chatty child never blocks on a full pipe. + }); + child.stderr?.on('data', () => { + // Drain; never echo. The child env holds runtime credentials. + }); + return child; +} + +function childEnv(options: { + port: number; + metricsPort: number | undefined; + mode: 'development' | 'production'; + origins: string[] | undefined; +}): Record { + const env: Record = { + PATH: process.env.PATH ?? '/usr/bin:/bin', + NODE_ENV: options.mode, + NODE_OPTIONS: '--no-warnings', + PORT: String(options.port), + DATABASE_URL: requiredDatabaseUrl(), + LIVEKIT_API_KEY: syntheticSecret(), + LIVEKIT_API_SECRET: syntheticSecret(), + JWT_SECRET: syntheticSecret(), + API_TOKEN_PEPPER: syntheticSecret(), + DOTENV_CONFIG_PATH: emptyEnvFile(), + LOG_LEVEL: 'error', + }; + if (options.origins !== undefined) env.CORS_ORIGIN = options.origins.join(','); + if (options.metricsPort !== undefined) { + env.METRICS_PORT = String(options.metricsPort); + env.METRICS_HOST = '127.0.0.1'; + } + if (process.env.HOME) env.HOME = process.env.HOME; + if (process.env.TMPDIR) env.TMPDIR = process.env.TMPDIR; + return env; +} + +function requiredDatabaseUrl(): string { + const url = process.env.DATABASE_URL; + if (typeof url !== 'string' || url.length === 0) { + throw new Error('DATABASE_URL is required'); + } + return url; +} + +function syntheticSecret(): string { + return randomBytes(32).toString('hex'); +} + +let emptyEnvPath: string | undefined; + +function emptyEnvFile(): string { + if (emptyEnvPath === undefined) { + emptyEnvPath = path.join(os.tmpdir(), `origin-access-empty-env-${process.pid}`); + fs.writeFileSync(emptyEnvPath, ''); + } + return emptyEnvPath; +} + +function resolveTsx(): string { + const scopedRequire = createRequire(path.join(SERVER_DIR, 'package.json')); + const packagePath = scopedRequire.resolve('tsx/package.json'); + const cliPath = path.join(path.dirname(packagePath), 'dist', 'cli.mjs'); + if (!fs.existsSync(cliPath)) { + throw new Error('tsx runner is missing'); + } + return cliPath; +} + +/** The application port the environment names, if it names one. */ +function configuredPort(): number | undefined { + const raw = process.env[PORT_KEY]; + if (raw === undefined || raw === '') return undefined; + const port = Number(raw); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`${PORT_KEY} must be set to an integer between 1 and 65535`); + } + return port; +} + +/** + * Reserve `count` loopback ports of their own and read them back. They are + * held at the same time, so two listeners of this file never get the same + * port. + */ +async function reserveLoopbackPorts(count: number): Promise { + const servers: net.Server[] = []; + const ports: number[] = []; + try { + for (let index = 0; index < count; index++) { + const server = net.createServer(); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => resolve()); + }); + const address = server.address(); + if (address === null || typeof address === 'string') { + throw new Error('failed to reserve a loopback port'); + } + ports.push(address.port); + servers.push(server); + } + } finally { + await Promise.all( + servers.map( + (server) => + new Promise((resolve) => { + server.close(() => resolve()); + }), + ), + ); + } + return ports; +} + +async function assertPortFree(port: number): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host: '127.0.0.1', port }); + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error(`test port ${port} did not refuse a connection in time`)); + }, PORT_PROBE_MS); + if (typeof timer.unref === 'function') timer.unref(); + socket.once('connect', () => { + clearTimeout(timer); + socket.destroy(); + reject(new Error(`test port ${port} is already in use; refusing a foreign process`)); + }); + socket.once('error', (error) => { + clearTimeout(timer); + if (errnoCode(error) === 'ECONNREFUSED') { + resolve(); + } else { + reject(error); + } + }); + }); +} + +async function waitForListeningOrExit(child: ChildProcess, port: number): Promise<'listening' | 'exited'> { + const deadline = Date.now() + START_TIMEOUT_MS; + const healthUrl = `http://127.0.0.1:${port}${READY_PATH}`; + while (Date.now() < deadline) { + if (child.exitCode !== null || child.signalCode !== null) return 'exited'; + try { + const res = await fetch(healthUrl); + await res.text(); + return 'listening'; + } catch { + // Not up yet. + } + await sleep(50); + } + throw new Error('server neither listened nor exited'); +} + +async function stopChild(child: ChildProcess): Promise { + if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(); + return new Promise((resolve) => { + const killTimer = setTimeout(() => { + child.kill('SIGKILL'); + const exitTimer = setTimeout(resolve, 5_000); + if (typeof exitTimer.unref === 'function') exitTimer.unref(); + child.once('exit', () => { + clearTimeout(exitTimer); + resolve(); + }); + }, STOP_TIMEOUT_MS); + if (typeof killTimer.unref === 'function') killTimer.unref(); + child.once('exit', () => { + clearTimeout(killTimer); + resolve(); + }); + child.kill('SIGTERM'); + }); +} + +function errnoCode(error: unknown): string | undefined { + if (typeof error !== 'object' || error === null || !('code' in error)) return undefined; + return typeof error.code === 'string' ? error.code : undefined; +} + +async function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/server/src/ops/originGuard.ts b/apps/server/src/ops/originGuard.ts new file mode 100644 index 00000000..48284d2c --- /dev/null +++ b/apps/server/src/ops/originGuard.ts @@ -0,0 +1,79 @@ +/** + * Origin guard: refuses a request whose Origin is not allowed before any + * request listener sees it. + * + * Colyseus answers its matchmaking route from a request listener it prepends + * to the HTTP server, before Express runs. A CORS middleware inside Express + * therefore cannot protect that route, and the preflight it answers never + * reaches the Express app at all. This guard sits in front of every bound + * request listener: a foreign origin never reaches the matchmaking processing, + * and a preflight is answered here with the exact allowed origin. + * + * Requests without an Origin header are not a browser request and pass + * through: native clients, webhooks and health checks keep working, and the + * route's own auth still decides. + */ +import type { RequestListener, Server, ServerResponse } from 'node:http'; +import { logger } from '../logger.js'; +import { ALLOWED_MAX_AGE, corsHeadersFor, keepsOwnCorsContract, type OriginPolicy } from './originPolicy.js'; + +export interface OriginGuardOptions { + /** The policy every request is checked against. */ + policy: OriginPolicy; +} + +function requestPath(url: string | undefined): string { + if (url === undefined) return ''; + const query = url.indexOf('?'); + return query === -1 ? url : url.slice(0, query); +} + +function refuseForeignOrigin(res: ServerResponse, origin: string): void { + logger.warn({ event: 'cors.origin_not_allowed', origin }); + res.statusCode = 403; + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Vary', 'Origin'); + res.end(JSON.stringify({ error: 'cors_origin_not_allowed' })); +} + +function answerPreflight(res: ServerResponse, origin: string | undefined, policy: OriginPolicy): void { + res.statusCode = 204; + for (const [name, value] of Object.entries(corsHeadersFor(origin, policy))) res.setHeader(name, value); + res.setHeader('Access-Control-Max-Age', ALLOWED_MAX_AGE); + res.setHeader('Vary', 'Origin'); + res.end(); +} + +/** + * Put the guard in front of every `request` listener the HTTP server has. + * + * Call this after the matchmaking guard has been installed, so that the + * origin check runs before any listener - the matchmaking route included - + * can act on the request. + */ +export function installOriginGuard(server: Server, options: OriginGuardOptions): void { + const downstream = server.listeners('request') as RequestListener[]; + if (downstream.length === 0) { + throw new Error('Origin guard: the HTTP server has no request listener to protect'); + } + server.removeAllListeners('request'); + const forward: RequestListener = (req, res) => { + for (const listener of downstream) listener.call(server, req, res); + }; + server.on('request', (req, res) => { + if (keepsOwnCorsContract(requestPath(req.url))) { + forward(req, res); + return; + } + const origin = req.headers.origin; + if (origin !== undefined && !options.policy.isAllowed(origin)) { + refuseForeignOrigin(res, origin); + return; + } + if (req.method === 'OPTIONS') { + answerPreflight(res, origin, options.policy); + return; + } + forward(req, res); + }); +} diff --git a/apps/server/src/ops/originPolicy.ts b/apps/server/src/ops/originPolicy.ts new file mode 100644 index 00000000..ce1dd8f0 --- /dev/null +++ b/apps/server/src/ops/originPolicy.ts @@ -0,0 +1,140 @@ +/** + * Origin policy: the single place that decides whether a browser origin may + * talk to this server. + * + * The allowlist comes from CORS_ORIGIN and holds exact origins + * (`scheme://host[:port]`). There is no wildcard, no suffix rule, no host + * equality and no implicit allowance: an origin is served when it is listed + * and refused when it is not. Express, the Colyseus matchmaking route and the + * websocket upgrade all ask this module, so one request cannot be allowed on + * one path and refused on another. + * + * The module is pure: it parses, compares and renders headers. Deciding + * whether a deployment may start at all belongs to the caller (see + * `resolveOriginPolicy`). + */ + +/** Environment key that holds the comma separated allowlist. */ +export const ORIGIN_ENV_KEY = 'CORS_ORIGIN'; + +/** Request headers a cross-origin request may carry. A fixed list, never echoed. */ +// traceparent: the browser telemetry SDK adds it to every fetch and XHR, so a +// preflight without it would fail every API call while telemetry is active. +export const ALLOWED_REQUEST_HEADERS = + 'Origin, X-Requested-With, Content-Type, Accept, Authorization, ' + + 'x-tenant, x-correlation-id, x-av-identity, x-av-room, traceparent'; + +/** Methods a cross-origin request may use. */ +export const ALLOWED_REQUEST_METHODS = 'GET, POST, PUT, PATCH, DELETE, OPTIONS'; + +/** Response headers a browser may read from a cross-origin response. */ +export const EXPOSED_RESPONSE_HEADERS = 'x-correlation-id'; + +/** How long a browser may cache a preflight answer, in seconds. */ +export const ALLOWED_MAX_AGE = '86400'; + +/** + * Paths that keep their own CORS contract: the public static assets and the + * operator tools. They answer without the browser CORS handshake, so the + * origin policy does not apply to them. + */ +const OWN_CORS_CONTRACT_PREFIXES = ['/packs', '/assets', '/npc-media', '/tools']; + +export function keepsOwnCorsContract(pathname: string): boolean { + return OWN_CORS_CONTRACT_PREFIXES.some((prefix) => pathname.startsWith(prefix)); +} + +export interface OriginPolicy { + /** The configured origins, in configuration order. */ + readonly allowedOrigins: readonly string[]; + /** Whether a concrete Origin header value is allowed. */ + isAllowed(origin: string): boolean; +} + +export interface OriginPolicyResolution { + /** False when the allowlist is missing or invalid: the server must not start. */ + readonly ok: boolean; + /** The parsed policy. Nothing is allowed when `ok` is false. */ + readonly policy: OriginPolicy; +} + +/** + * `scheme://host[:port]` with a lowercase scheme and a plain host. No path, no + * query, no fragment, no wildcard, no userinfo and no `null`: a value that does + * not match is not an origin this server can compare exactly. + */ +const ORIGIN_PATTERN = /^[a-z][a-z0-9+.-]*:\/\/[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$/; + +export function isValidOrigin(value: string): boolean { + if (!ORIGIN_PATTERN.test(value)) return false; + const authority = value.slice(value.indexOf('://') + 3); + const separator = authority.lastIndexOf(':'); + if (separator === -1) return true; + const port = Number(authority.slice(separator + 1)); + return Number.isInteger(port) && port >= 1 && port <= 65535; +} + +export function parseOriginAllowlist(raw: string | undefined): { origins: string[]; invalid: string[] } { + const entries = (raw ?? '') + .split(',') + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0); + const origins: string[] = []; + const invalid: string[] = []; + for (const entry of entries) { + if (isValidOrigin(entry)) origins.push(entry); + else invalid.push(entry); + } + return { origins, invalid }; +} + +export function createOriginPolicy(origins: readonly string[]): OriginPolicy { + const allowed = new Set(origins); + return { + allowedOrigins: origins, + isAllowed: (origin: string) => allowed.has(origin), + }; +} + +/** + * Read the allowlist from the environment. A missing, empty or malformed list + * is not a startable configuration: the caller must refuse the start and name + * the key, never the value. + */ +export function resolveOriginPolicy(env: NodeJS.ProcessEnv): OriginPolicyResolution { + const raw = env[ORIGIN_ENV_KEY]; + const { origins, invalid } = parseOriginAllowlist(raw); + const usable = raw !== undefined && raw.trim() !== '' && origins.length > 0 && invalid.length === 0; + if (!usable) return { ok: false, policy: createOriginPolicy([]) }; + return { ok: true, policy: createOriginPolicy(origins) }; +} + +/** + * The CORS headers for a request that carries `origin`, or none at all when + * the origin is not allowed. A request without an origin (native clients, + * webhooks, health checks) gets no CORS headers: the route's own auth decides. + * + * `Vary: Origin` is not part of the record: the caller adds it, because the + * answer differs per origin and an existing Vary header must be extended + * rather than replaced. + */ +export function corsHeadersFor(origin: string | null | undefined, policy: OriginPolicy): Record { + if (origin === null || origin === undefined || origin === '' || !policy.isAllowed(origin)) return {}; + return { + 'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Allow-Headers': ALLOWED_REQUEST_HEADERS, + 'Access-Control-Allow-Methods': ALLOWED_REQUEST_METHODS, + 'Access-Control-Expose-Headers': EXPOSED_RESPONSE_HEADERS, + }; +} + +/** + * Whether a websocket upgrade may proceed. An upgrade without an origin is + * left to the matchmaking auth and the seat reservation; an upgrade that + * carries an origin is only allowed when the origin is listed. + */ +export function isUpgradeOriginAllowed(policy: OriginPolicy, origin: string | undefined): boolean { + if (origin === undefined || origin === '') return true; + return policy.isAllowed(origin); +} diff --git a/apps/server/src/ops/seedAdminCredentials.integration.test.ts b/apps/server/src/ops/seedAdminCredentials.integration.test.ts new file mode 100644 index 00000000..8a700583 --- /dev/null +++ b/apps/server/src/ops/seedAdminCredentials.integration.test.ts @@ -0,0 +1,609 @@ +/** + * Integration tests for the seed program's production admin-credential policy + * and default-account cleanup. Spawns the same tsx seed program the product + * uses. The database URL comes only from the process environment. + */ + +import { spawnSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import bcrypt from 'bcryptjs'; +import jwt from 'jsonwebtoken'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { getApiTokenPepper, getJwtSecret } from '../api/utils/authHelpers.js'; +import { claimPasswordResetToken, issuePasswordResetToken } from '../api/utils/passwordResetTokens.js'; +import { hashSessionToken, validateSessionToken } from '../api/utils/sessionAuth.js'; +import { clearSessionCache } from '../api/utils/sessionCache.js'; +import { createPrismaClient } from '../db.js'; +import type { PrismaClient } from '../generated/prisma/index.js'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SERVER_DIR = path.resolve(HERE, '..', '..'); +const TEMPLATE_PATH = path.resolve(SERVER_DIR, '..', '..', '.env.example'); +const PRODUCTION = 'production'; +const DEVELOPMENT = 'development'; +const SEED_TIMEOUT_MS = 180_000; +const CONFIGURED_EMAIL = 'configured-admin@seed-admin.test'; +const CONTROL_EMAIL = 'control-account@seed-admin.test'; +const STRONG_PASSWORD = 'synthetic-valid-admin-password'; +const OTHER_STRONG_PASSWORD = 'synthetic-other-admin-password'; + +process.env.JWT_SECRET = 'synthetic-jwt-secret-for-seed-admin-tests'; +process.env.API_TOKEN_PEPPER = 'synthetic-api-token-pepper-for-seed-admin-tests'; + +let prisma: PrismaClient; +let tsxBin: string; + +interface SeedResult { + status: number | null; + stdout: string; + stderr: string; +} + +interface UserSnap { + id: string; + email: string; + name: string | null; + passwordHash: string | null; +} + +describe('seed admin credentials', { timeout: 240_000 }, () => { + beforeAll(() => { + requiredDatabaseUrl(); + prisma = createPrismaClient(); + tsxBin = resolveTsx(); + }); + + afterEach(async () => { + clearSessionCache(); + await wipeEmail(CONFIGURED_EMAIL); + await wipeEmail(CONTROL_EMAIL); + await wipeEmail(templateAdminEmail()); + }); + + afterAll(async () => { + await prisma.$disconnect(); + }); + + it('production_seed_rejects_missing_email', async () => { + await expectRejectedWithoutWrites( + { NODE_ENV: PRODUCTION, SEED_ADMIN_PASSWORD: STRONG_PASSWORD }, + 'SEED_ADMIN_EMAIL', + ); + }); + + it('production_seed_rejects_empty_email', async () => { + for (const value of ['', ' ']) { + await expectRejectedWithoutWrites( + { NODE_ENV: PRODUCTION, SEED_ADMIN_EMAIL: value, SEED_ADMIN_PASSWORD: STRONG_PASSWORD }, + 'SEED_ADMIN_EMAIL', + ); + } + }); + + it('production_seed_rejects_missing_password', async () => { + await expectRejectedWithoutWrites( + { NODE_ENV: PRODUCTION, SEED_ADMIN_EMAIL: CONFIGURED_EMAIL }, + 'SEED_ADMIN_PASSWORD', + ); + }); + + it('production_seed_rejects_empty_password', async () => { + for (const value of ['', ' ']) { + await expectRejectedWithoutWrites( + { NODE_ENV: PRODUCTION, SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, SEED_ADMIN_PASSWORD: value }, + 'SEED_ADMIN_PASSWORD', + ); + } + }); + + it('production_seed_rejects_default_password', async () => { + await expectRejectedWithoutWrites( + { + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: templateAdminPassword(), + }, + 'SEED_ADMIN_PASSWORD', + ); + }); + + it('existing_nondefault_admin_hash_is_preserved', async () => { + const user = await createPasswordUser(CONFIGURED_EMAIL, STRONG_PASSWORD); + const hashBefore = await currentHash(user.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: OTHER_STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const hashAfter = await currentHash(user.id); + expect(hashBefore === hashAfter).toBe(true); + expect(await passwordMatches(user.id, STRONG_PASSWORD)).toBe(true); + expect(await passwordMatches(user.id, OTHER_STRONG_PASSWORD)).toBe(false); + }); + + it('configured_default_hash_is_migrated_only_once', { timeout: 400_000 }, async () => { + const user = await createPasswordUser(CONFIGURED_EMAIL, templateAdminPassword()); + const first = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(first.status).toBe(0); + const hashAfterFirstSeed = await currentHash(user.id); + const second = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(second.status).toBe(0); + const hashAfterSecondSeed = await currentHash(user.id); + expect(hashAfterFirstSeed === hashAfterSecondSeed).toBe(true); + expect(await passwordMatches(user.id, STRONG_PASSWORD)).toBe(true); + expect(await passwordMatches(user.id, templateAdminPassword())).toBe(false); + }); + + it('legacy_default_owner_is_disabled_when_email_differs', async () => { + const legacy = await createPasswordUser(templateAdminEmail(), templateAdminPassword()); + await grantInternalRole(legacy.id, 'owner'); + const idBefore = legacy.id; + const emailBefore = legacy.email; + const rolesBefore = await membershipRoles(legacy.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const after = await prisma.user.findUnique({ + where: { id: idBefore }, + select: { id: true, email: true }, + }); + expect(after !== null && after.id === idBefore && after.email === emailBefore).toBe(true); + const rolesAfter = await membershipRoles(idBefore); + expect(rolesBefore.join('|') === rolesAfter.join('|')).toBe(true); + expect(await passwordMatches(idBefore, templateAdminPassword())).toBe(false); + expect(await passwordMatches(idBefore, STRONG_PASSWORD)).toBe(false); + }); + + it('default_account_session_is_revoked_configured', async () => { + await expectDefaultAccountSecretRevoked('configured', 'session'); + }); + + it('default_account_session_is_revoked_legacy', async () => { + await expectDefaultAccountSecretRevoked('legacy', 'session'); + }); + + it('default_account_api_token_is_revoked_configured', async () => { + await expectDefaultAccountSecretRevoked('configured', 'api_token'); + }); + + it('default_account_api_token_is_revoked_legacy', async () => { + await expectDefaultAccountSecretRevoked('legacy', 'api_token'); + }); + + it('default_account_reset_token_is_revoked_configured', async () => { + await expectDefaultAccountSecretRevoked('configured', 'reset_token'); + }); + + it('default_account_reset_token_is_revoked_legacy', async () => { + await expectDefaultAccountSecretRevoked('legacy', 'reset_token'); + }); + + it('seed_diagnostics_contain_no_sensitive_values', async () => { + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const output = `${result.stdout}\n${result.stderr}`; + const invites = await prisma.invite.findMany({ select: { code: true } }); + const users = await prisma.user.findMany({ select: { email: true, passwordHash: true } }); + const leaked = outputContainsAny(output, [ + CONFIGURED_EMAIL, + CONTROL_EMAIL, + templateAdminEmail(), + templateAdminPassword(), + STRONG_PASSWORD, + OTHER_STRONG_PASSWORD, + ...users.map((row) => row.email), + ...users.map((row) => row.passwordHash), + ...invites.map((row) => row.code), + ]); + expect(leaked).toBe(false); + }); + + it('production_seed_accepts_valid_new_admin', async () => { + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const user = await prisma.user.findUnique({ where: { email: CONFIGURED_EMAIL }, select: { id: true } }); + const userId = user?.id ?? ''; + expect(userId.length > 0).toBe(true); + expect(await passwordMatches(userId, STRONG_PASSWORD)).toBe(true); + expect(await passwordMatches(userId, templateAdminPassword())).toBe(false); + }); + + it('production_seed_accepts_explicit_default_email', async () => { + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: templateAdminEmail(), + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const user = await prisma.user.findUnique({ + where: { email: templateAdminEmail() }, + select: { id: true }, + }); + const userId = user?.id ?? ''; + expect(userId.length > 0).toBe(true); + expect(await passwordMatches(userId, STRONG_PASSWORD)).toBe(true); + }); + + it('development_seed_keeps_fallbacks', async () => { + const result = runSeed({ NODE_ENV: DEVELOPMENT }); + expect(result.status).toBe(0); + const user = await prisma.user.findUnique({ + where: { email: templateAdminEmail() }, + select: { id: true }, + }); + const userId = user?.id ?? ''; + expect(userId.length > 0).toBe(true); + expect(await passwordMatches(userId, templateAdminPassword())).toBe(true); + }); + + it('development_seed_rerun_keeps_fallback_admin_session', { timeout: 400_000 }, async () => { + await wipeEmail(templateAdminEmail()); + expect(runSeed({ NODE_ENV: DEVELOPMENT }).status).toBe(0); + const user = await prisma.user.findUnique({ + where: { email: templateAdminEmail() }, + select: { id: true }, + }); + const userId = user?.id ?? ''; + expect(userId.length > 0).toBe(true); + const token = await issueLiveSession(userId); + expect(runSeed({ NODE_ENV: DEVELOPMENT }).status).toBe(0); + expect(await sessionIsValid(token)).toBe(true); + expect(await passwordMatches(userId, templateAdminPassword())).toBe(true); + }); + + it('legacy_account_with_nondefault_hash_is_untouched', async () => { + const legacy = await createPasswordUser(templateAdminEmail(), STRONG_PASSWORD); + await grantInternalRole(legacy.id, 'owner'); + const hashBefore = await currentHash(legacy.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: OTHER_STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const hashAfter = await currentHash(legacy.id); + expect(hashBefore === hashAfter).toBe(true); + expect(await passwordMatches(legacy.id, STRONG_PASSWORD)).toBe(true); + }); + + it('legacy_account_without_internal_owner_role_is_untouched', async () => { + const legacy = await createPasswordUser(templateAdminEmail(), templateAdminPassword()); + await grantInternalRole(legacy.id, 'member'); + const hashBefore = await currentHash(legacy.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + const hashAfter = await currentHash(legacy.id); + expect(hashBefore === hashAfter).toBe(true); + expect(await passwordMatches(legacy.id, templateAdminPassword())).toBe(true); + }); + + it('nondefault_account_session_stays_valid', async () => { + const control = await createPasswordUser(CONTROL_EMAIL, STRONG_PASSWORD); + const token = await issueLiveSession(control.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: OTHER_STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + expect(await sessionIsValid(token)).toBe(true); + }); + + it('nondefault_account_api_token_stays_valid', async () => { + const control = await createPasswordUser(CONTROL_EMAIL, STRONG_PASSWORD); + const raw = await issueApiToken(control.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: OTHER_STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + expect(await apiTokenIsValid(raw)).toBe(true); + }); + + it('nondefault_account_reset_token_stays_valid', async () => { + const control = await createPasswordUser(CONTROL_EMAIL, STRONG_PASSWORD); + const raw = await issueResetToken(control.id); + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: CONFIGURED_EMAIL, + SEED_ADMIN_PASSWORD: OTHER_STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + expect(await resetTokenIsValid(raw)).toBe(true); + }); +}); + +function readTemplateValue(key: string): string { + const text = fs.readFileSync(TEMPLATE_PATH, 'utf8'); + for (const line of text.split(/\r?\n/)) { + const match = /^\s*#?\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line); + if (match !== null && match[1] === key) { + return match[2]; + } + } + throw new Error(`template entry missing for key: ${key}`); +} + +function templateAdminEmail(): string { + return readTemplateValue('SEED_ADMIN_EMAIL'); +} + +function templateAdminPassword(): string { + return readTemplateValue('SEED_ADMIN_PASSWORD'); +} + +function requiredDatabaseUrl(): string { + const url = process.env.DATABASE_URL; + if (typeof url !== 'string' || url.length === 0) { + throw new Error('DATABASE_URL is required'); + } + return url; +} + +function resolveTsx(): string { + const names = process.platform === 'win32' ? ['tsx.cmd', 'tsx'] : ['tsx']; + const dirs = [ + path.resolve(SERVER_DIR, 'node_modules', '.bin'), + path.resolve(SERVER_DIR, '..', '..', 'node_modules', '.bin'), + ]; + for (const dir of dirs) { + for (const name of names) { + const candidate = path.join(dir, name); + if (fs.existsSync(candidate)) { + return candidate; + } + } + } + throw new Error('tsx executable is missing'); +} + +function baseSpawnEnv(): Record { + const env: Record = { + PATH: process.env.PATH ?? '/usr/bin:/bin', + DATABASE_URL: requiredDatabaseUrl(), + NODE_OPTIONS: '--no-warnings', + }; + if (process.env.HOME) { + env.HOME = process.env.HOME; + } + if (process.env.TMPDIR) { + env.TMPDIR = process.env.TMPDIR; + } + return env; +} + +function runSeed(overrides: Record): SeedResult { + const env = baseSpawnEnv(); + for (const [key, value] of Object.entries(overrides)) { + if (value !== undefined) { + env[key] = value; + } + } + const result = spawnSync(tsxBin, ['prisma/seed.ts'], { + cwd: SERVER_DIR, + env, + encoding: 'utf8', + timeout: SEED_TIMEOUT_MS, + maxBuffer: 20 * 1024 * 1024, + }); + if (result.error) { + throw result.error; + } + return { status: result.status, stdout: result.stdout, stderr: result.stderr }; +} + +function expectRejected(result: SeedResult, key: string): void { + expect(result.status).toBe(1); + expect(result.stderr.trim().split('\n')).toEqual([key]); + expect(result.stdout).toBe(''); +} + +async function expectRejectedWithoutWrites( + overrides: Record, + key: string, +): Promise { + const before = await snapshotUsers(); + const result = runSeed(overrides); + expectRejected(result, key); + const after = await snapshotUsers(); + expect(usersUnchanged(before, after)).toBe(true); +} + +async function snapshotUsers(): Promise { + return prisma.user.findMany({ + select: { id: true, email: true, name: true, passwordHash: true }, + orderBy: { id: 'asc' }, + }); +} + +function usersUnchanged(before: UserSnap[], after: UserSnap[]): boolean { + if (before.length !== after.length) { + return false; + } + return before.every((row, index) => { + const next = after[index]; + return ( + next !== undefined && + next.id === row.id && + next.email === row.email && + next.name === row.name && + next.passwordHash === row.passwordHash + ); + }); +} + +async function createPasswordUser(email: string, password: string): Promise<{ id: string; email: string }> { + return prisma.user.create({ + data: { + email, + name: 'Fixture Admin', + passwordHash: await bcrypt.hash(password, 10), + emailVerifiedAt: new Date(), + }, + select: { id: true, email: true }, + }); +} + +async function grantInternalRole(userId: string, role: 'owner' | 'member'): Promise { + const internal = await prisma.tenant.upsert({ + where: { slug: 'internal' }, + create: { + slug: 'internal', + name: 'Internal', + concurrentLimit: 999999, + bypassLimits: true, + isInternal: true, + publicRegistrationEnabled: true, + }, + update: {}, + select: { id: true }, + }); + await prisma.membership.upsert({ + where: { tenantId_userId: { tenantId: internal.id, userId } }, + update: { role }, + create: { tenantId: internal.id, userId, role }, + }); +} + +async function currentHash(userId: string): Promise { + const user = await prisma.user.findUnique({ where: { id: userId }, select: { passwordHash: true } }); + return user?.passwordHash ?? null; +} + +async function passwordMatches(userId: string, password: string): Promise { + const hash = await currentHash(userId); + if (!hash) { + return false; + } + return bcrypt.compare(password, hash); +} + +async function membershipRoles(userId: string): Promise { + const rows = await prisma.membership.findMany({ + where: { userId }, + select: { tenantId: true, role: true }, + orderBy: { tenantId: 'asc' }, + }); + return rows.map((row) => `${row.tenantId}:${row.role}`); +} + +async function issueLiveSession(userId: string): Promise { + const token = jwt.sign( + { sub: userId, tid: 'seed-admin-test-tenant', jti: crypto.randomUUID() }, + getJwtSecret(), + { expiresIn: '30d' }, + ); + await prisma.session.create({ + data: { + userId, + tokenHash: hashSessionToken(token), + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + }, + }); + return token; +} + +async function sessionIsValid(token: string): Promise { + clearSessionCache(); + const auth = await validateSessionToken(prisma, token); + return auth !== null; +} + +async function issueApiToken(userId: string): Promise { + const raw = crypto.randomBytes(32).toString('hex'); + const hash = crypto.createHash('sha256').update(getApiTokenPepper() + raw).digest('hex'); + await prisma.apiToken.create({ data: { userId, name: 'seed-admin-test', hash } }); + return raw; +} + +async function apiTokenIsValid(raw: string): Promise { + const hash = crypto.createHash('sha256').update(getApiTokenPepper() + raw).digest('hex'); + const found = await prisma.apiToken.findUnique({ where: { hash } }); + return found !== null; +} + +async function issueResetToken(userId: string): Promise { + const issued = await issuePasswordResetToken(prisma, userId); + return issued.token; +} + +async function resetTokenIsValid(raw: string): Promise { + const claimed = await claimPasswordResetToken(prisma, raw); + return claimed !== null; +} + +async function expectDefaultAccountSecretRevoked( + kind: 'configured' | 'legacy', + secret: 'session' | 'api_token' | 'reset_token', +): Promise { + const victim = await createPasswordUser(templateAdminEmail(), templateAdminPassword()); + if (kind === 'legacy') { + await grantInternalRole(victim.id, 'owner'); + } + const sessionToken = secret === 'session' ? await issueLiveSession(victim.id) : null; + const apiToken = secret === 'api_token' ? await issueApiToken(victim.id) : null; + const resetToken = secret === 'reset_token' ? await issueResetToken(victim.id) : null; + const seedEmail = kind === 'configured' ? templateAdminEmail() : CONFIGURED_EMAIL; + const result = runSeed({ + NODE_ENV: PRODUCTION, + SEED_ADMIN_EMAIL: seedEmail, + SEED_ADMIN_PASSWORD: STRONG_PASSWORD, + }); + expect(result.status).toBe(0); + if (sessionToken) { + expect(await sessionIsValid(sessionToken)).toBe(false); + } + if (apiToken) { + expect(await apiTokenIsValid(apiToken)).toBe(false); + } + if (resetToken) { + expect(await resetTokenIsValid(resetToken)).toBe(false); + } +} + +function outputContainsAny(output: string, values: Array): boolean { + return values.some((value) => typeof value === 'string' && value.length > 0 && output.includes(value)); +} + +async function wipeEmail(email: string): Promise { + const user = await prisma.user.findUnique({ where: { email }, select: { id: true } }); + if (user) { + await prisma.session.deleteMany({ where: { userId: user.id } }); + await prisma.apiToken.deleteMany({ where: { userId: user.id } }); + await prisma.passwordReset.deleteMany({ where: { userId: user.id } }); + await prisma.emailVerification.deleteMany({ where: { userId: user.id } }); + await prisma.presence.deleteMany({ where: { userId: user.id } }); + await prisma.membership.deleteMany({ where: { userId: user.id } }); + await prisma.invite.deleteMany({ where: { createdBy: user.id } }); + await prisma.user.delete({ where: { id: user.id } }); + } + await prisma.invite.deleteMany({ where: { email } }); +} diff --git a/apps/server/src/ops/seedAdminCredentials.ts b/apps/server/src/ops/seedAdminCredentials.ts new file mode 100644 index 00000000..81fe119d --- /dev/null +++ b/apps/server/src/ops/seedAdminCredentials.ts @@ -0,0 +1,211 @@ +/** + * Production policy for the seed-admin credential pair, plus the default-hash + * rotation the seed applies after that policy accepts a run. + * + * Mode detection is the shared helper in credentialPolicy.ts. This module only + * adds the seed-admin rules: a production seed refuses a missing or blank + * email and a missing, blank, or public-template password, and it never + * requires LiveKit or tools credentials. Development keeps the historical + * fallbacks. The helper never prints values, hashes, or identifiers. + */ + +import crypto from 'node:crypto'; +import bcrypt from 'bcryptjs'; +import { revokeSessionsForUserInTx } from '../api/utils/sessionAuth.js'; +import { invalidateSessionsForUser } from '../api/utils/sessionCache.js'; +import type { PrismaClient } from '../generated/prisma/index.js'; +import { isProductionEnvironment } from './credentialPolicy.js'; + +const INTERNAL_TENANT_SLUG = 'internal'; +const BCRYPT_ROUNDS = 10; +const FALLBACK_ADMIN_NAME = 'Root Admin'; + +// Known public seed-admin placeholders. Derived once from the versioned +// template keys SEED_ADMIN_EMAIL and SEED_ADMIN_PASSWORD so production +// comparison does not re-read the template file at runtime. +const TEMPLATE_SEED_ADMIN_EMAIL = 'admin@meetropolis.local'; +const TEMPLATE_SEED_ADMIN_PASSWORD = 'admin123'; + +export interface SeedAdminCredentials { + email: string; + password: string; + name: string; +} + +export function findInvalidSeedAdminKeys(env: Record): string[] { + if (!isProductionEnvironment(env)) { + return []; + } + const invalid: string[] = []; + if (!isPresentValue(env.SEED_ADMIN_EMAIL)) { + invalid.push('SEED_ADMIN_EMAIL'); + } + if (!isUsableAdminPassword(env.SEED_ADMIN_PASSWORD)) { + invalid.push('SEED_ADMIN_PASSWORD'); + } + return invalid; +} + +export function enforceSeedAdminCredentials(env: Record): void { + const invalidKeys = findInvalidSeedAdminKeys(env); + if (invalidKeys.length === 0) { + return; + } + for (const key of invalidKeys) { + process.stderr.write(`${key}\n`); + } + process.exit(1); +} + +export function resolveSeedAdminCredentials(env: Record): SeedAdminCredentials { + return { + email: presentOrFallback(env.SEED_ADMIN_EMAIL, TEMPLATE_SEED_ADMIN_EMAIL), + password: presentOrFallback(env.SEED_ADMIN_PASSWORD, TEMPLATE_SEED_ADMIN_PASSWORD), + name: presentOrFallback(env.SEED_ADMIN_NAME, FALLBACK_ADMIN_NAME), + }; +} + +export async function applySeedAdminCredentials( + prisma: PrismaClient, + env: Record, +): Promise<{ id: string; email: string }> { + const credentials = resolveSeedAdminCredentials(env); + const admin = await ensureConfiguredAdmin(prisma, credentials); + await disableLegacyDefaultOwner(prisma, credentials.email); + return admin; +} + +function isPresentValue(value: string | undefined): boolean { + return value !== undefined && value.trim().length > 0; +} + +function isUsableAdminPassword(value: string | undefined): boolean { + if (value === undefined) { + return false; + } + const trimmed = value.trim(); + if (trimmed.length === 0) { + return false; + } + return trimmed !== TEMPLATE_SEED_ADMIN_PASSWORD; +} + +function presentOrFallback(value: string | undefined, fallback: string): string { + if (value !== undefined && value.trim().length > 0) { + return value.trim(); + } + return fallback; +} + +async function ensureConfiguredAdmin( + prisma: PrismaClient, + credentials: SeedAdminCredentials, +): Promise<{ id: string; email: string }> { + const existing = await prisma.user.findUnique({ + where: { email: credentials.email }, + select: { id: true, email: true, passwordHash: true }, + }); + if (!existing) { + const created = await prisma.user.create({ + data: { + email: credentials.email, + name: credentials.name, + passwordHash: await bcrypt.hash(credentials.password, BCRYPT_ROUNDS), + emailVerifiedAt: new Date(), + }, + select: { id: true, email: true }, + }); + console.log('Seeded admin user'); + return created; + } + if (existing.passwordHash) { + await rotateDefaultHashIfNeeded(prisma, existing.id, existing.passwordHash, credentials.password); + } + return { id: existing.id, email: existing.email }; +} + +async function disableLegacyDefaultOwner(prisma: PrismaClient, configuredEmail: string): Promise { + if (configuredEmail === TEMPLATE_SEED_ADMIN_EMAIL) { + return; + } + const legacy = await prisma.user.findUnique({ + where: { email: TEMPLATE_SEED_ADMIN_EMAIL }, + select: { id: true, passwordHash: true }, + }); + if (!legacy?.passwordHash) { + return; + } + const isInternalOwner = await userIsInternalOwner(prisma, legacy.id); + if (!isInternalOwner) { + return; + } + const stillDefault = await bcrypt.compare(TEMPLATE_SEED_ADMIN_PASSWORD, legacy.passwordHash); + if (!stillDefault) { + return; + } + const nextHash = await bcrypt.hash(crypto.randomBytes(32).toString('hex'), BCRYPT_ROUNDS); + await applyAtomicCredentialRotation(prisma, legacy.id, legacy.passwordHash, nextHash); +} + +async function rotateDefaultHashIfNeeded( + prisma: PrismaClient, + userId: string, + currentHash: string, + nextPassword: string, +): Promise { + // A development re-run with the fallback password has nothing to rotate; + // rotating would only revoke the admin's sessions and tokens. + if (nextPassword === TEMPLATE_SEED_ADMIN_PASSWORD) { + return; + } + const stillDefault = await bcrypt.compare(TEMPLATE_SEED_ADMIN_PASSWORD, currentHash); + if (!stillDefault) { + return; + } + const nextHash = await bcrypt.hash(nextPassword, BCRYPT_ROUNDS); + await applyAtomicCredentialRotation(prisma, userId, currentHash, nextHash); +} + +async function userIsInternalOwner(prisma: PrismaClient, userId: string): Promise { + const internal = await prisma.tenant.findUnique({ where: { slug: INTERNAL_TENANT_SLUG } }); + if (!internal) { + return false; + } + const member = await prisma.membership.findUnique({ + where: { tenantId_userId: { tenantId: internal.id, userId } }, + select: { role: true }, + }); + return member?.role === 'owner'; +} + +async function applyAtomicCredentialRotation( + prisma: PrismaClient, + userId: string, + expectedHash: string, + nextHash: string, +): Promise { + const outcome = await prisma.$transaction(async (tx) => { + const updated = await tx.user.updateMany({ + where: { id: userId, passwordHash: expectedHash }, + data: { passwordHash: nextHash }, + }); + if (updated.count !== 1) { + return { rotated: false, sessions: 0, tokens: 0, resets: 0 }; + } + const sessions = await revokeSessionsForUserInTx(tx, userId); + const tokens = await tx.apiToken.deleteMany({ where: { userId } }); + const resets = await tx.passwordReset.deleteMany({ where: { userId, usedAt: null } }); + return { rotated: true, sessions, tokens: tokens.count, resets: resets.count }; + }); + if (!outcome.rotated) { + return; + } + // Required after the commit (see revokeSessionsForUserInTx). The seed runs as + // its own process, so this clears only its own cache; a running server drops + // the revoked sessions within SESSION_CACHE_TTL_MS. + invalidateSessionsForUser(userId); + console.log( + `Rotated a default admin credential; revoked sessions=${outcome.sessions} ` + + `apiTokens=${outcome.tokens} resetTokens=${outcome.resets}`, + ); +} diff --git a/apps/server/src/ops/startupCredentials.test.ts b/apps/server/src/ops/startupCredentials.test.ts new file mode 100644 index 00000000..43e31161 --- /dev/null +++ b/apps/server/src/ops/startupCredentials.test.ts @@ -0,0 +1,286 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, it } from 'vitest'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SERVER_DIR = path.resolve(HERE, '..', '..'); +const ENTRYPOINT = path.resolve(SERVER_DIR, 'entrypoint.sh'); +const TEMPLATE_PATH = path.resolve(SERVER_DIR, '..', '..', '.env.example'); + +const MARKER_TEXT = 'ready'; +const PRODUCTION = 'production'; +const DEVELOPMENT = 'development'; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +function readTemplateValue(key: string): string { + const text = fs.readFileSync(TEMPLATE_PATH, 'utf8'); + for (const line of text.split(/\r?\n/)) { + const match = /^\s*#?\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line); + if (match !== null && match[1] === key) { + return match[2]; + } + } + throw new Error(`template entry missing for key: ${key}`); +} + +function validEnv(mode: string): Record { + return { + PATH: process.env.PATH ?? '/usr/bin:/bin', + NODE_ENV: mode, + LIVEKIT_API_KEY: 'synthetic-valid-livekit-key', + LIVEKIT_API_SECRET: 'synthetic-valid-livekit-secret', + TOOLS_PASSWORD: 'synthetic-valid-tools-password', + DATABASE_URL: + 'postgresql://meetropolis:synthetic-valid-db-password@localhost:5432/meetropolis?schema=public', + }; +} + +interface StartResult { + status: number | null; + stdout: string; + stderr: string; + markerFound: boolean; + markerText: string | null; +} + +function startWithEnv(env: Record): StartResult { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'startup-credentials-')); + tempDirs.push(dir); + const marker = path.join(dir, 'started'); + const markerScript = `require("fs").writeFileSync(${JSON.stringify(marker)}, ${JSON.stringify(MARKER_TEXT)})`; + const result = spawnSync('sh', [ENTRYPOINT, 'node', '-e', markerScript], { + cwd: SERVER_DIR, + env: { ...env, RUN_MIGRATIONS: 'false', RUN_SEED: 'false' }, + encoding: 'utf8', + timeout: 30000, + }); + expect(result.error).toBeUndefined(); + const markerFound = fs.existsSync(marker); + return { + status: result.status, + stdout: result.stdout, + stderr: result.stderr, + markerFound, + markerText: markerFound ? fs.readFileSync(marker, 'utf8') : null, + }; +} + +function expectRejected(result: StartResult, key: string): void { + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr.trim().split('\n')).toEqual([key]); + expect(result.markerFound).toBe(false); +} + +function expectStarted(result: StartResult): void { + expect(result.status).toBe(0); + expect(result.stdout).toBe(''); + expect(result.markerFound).toBe(true); + expect(result.markerText).toBe(MARKER_TEXT); +} + +function urlWithPasswordPart(templateUrl: string): { prefix: string; password: string; suffix: string } { + const match = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^:/?#]+:)([^@/?#]*)(@.*)$/.exec(templateUrl); + if (match === null) { + throw new Error('template database url has no password part'); + } + let password = match[2]; + try { + password = decodeURIComponent(password); + } catch { + throw new Error('template database password is not decodable'); + } + if (password.length === 0) { + throw new Error('template database password is empty'); + } + return { prefix: match[1], password, suffix: match[3] }; +} + +function fullyEncoded(value: string): string { + return Array.from(Buffer.from(value, 'utf8')) + .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`) + .join(''); +} + +describe('startup credentials', () => { + describe('production mode', () => { + it('production_rejects_empty_LIVEKIT_API_KEY', () => { + const variants: Array = [undefined, '', ' ']; + for (const value of variants) { + const env = validEnv(PRODUCTION); + if (value === undefined) { + delete env.LIVEKIT_API_KEY; + } else { + env.LIVEKIT_API_KEY = value; + } + expectRejected(startWithEnv(env), 'LIVEKIT_API_KEY'); + } + }); + + it('production_rejects_example_LIVEKIT_API_KEY', () => { + const env = validEnv(PRODUCTION); + env.LIVEKIT_API_KEY = readTemplateValue('LIVEKIT_API_KEY'); + expectRejected(startWithEnv(env), 'LIVEKIT_API_KEY'); + }); + + it('production_accepts_valid_LIVEKIT_API_KEY', () => { + expectStarted(startWithEnv(validEnv(PRODUCTION))); + }); + + it('development_accepts_example_LIVEKIT_API_KEY', () => { + const env = validEnv(DEVELOPMENT); + env.LIVEKIT_API_KEY = readTemplateValue('LIVEKIT_API_KEY'); + expectStarted(startWithEnv(env)); + }); + + it('production_rejects_empty_LIVEKIT_API_SECRET', () => { + const variants: Array = [undefined, '', ' ']; + for (const value of variants) { + const env = validEnv(PRODUCTION); + if (value === undefined) { + delete env.LIVEKIT_API_SECRET; + } else { + env.LIVEKIT_API_SECRET = value; + } + expectRejected(startWithEnv(env), 'LIVEKIT_API_SECRET'); + } + }); + + it('production_rejects_example_LIVEKIT_API_SECRET', () => { + const env = validEnv(PRODUCTION); + env.LIVEKIT_API_SECRET = readTemplateValue('LIVEKIT_API_SECRET'); + expectRejected(startWithEnv(env), 'LIVEKIT_API_SECRET'); + }); + + it('production_accepts_valid_LIVEKIT_API_SECRET', () => { + expectStarted(startWithEnv(validEnv(PRODUCTION))); + }); + + it('development_accepts_example_LIVEKIT_API_SECRET', () => { + const env = validEnv(DEVELOPMENT); + env.LIVEKIT_API_SECRET = readTemplateValue('LIVEKIT_API_SECRET'); + expectStarted(startWithEnv(env)); + }); + + it('production_rejects_empty_TOOLS_PASSWORD', () => { + for (const value of [' ', '\t']) { + const env = validEnv(PRODUCTION); + env.TOOLS_PASSWORD = value; + expectRejected(startWithEnv(env), 'TOOLS_PASSWORD'); + } + }); + + it('production_rejects_example_TOOLS_PASSWORD', () => { + const env = validEnv(PRODUCTION); + env.TOOLS_PASSWORD = readTemplateValue('TOOLS_PASSWORD'); + expectRejected(startWithEnv(env), 'TOOLS_PASSWORD'); + }); + + it('production_accepts_valid_TOOLS_PASSWORD', () => { + expectStarted(startWithEnv(validEnv(PRODUCTION))); + }); + + it('development_accepts_example_TOOLS_PASSWORD', () => { + const env = validEnv(DEVELOPMENT); + env.TOOLS_PASSWORD = readTemplateValue('TOOLS_PASSWORD'); + expectStarted(startWithEnv(env)); + }); + + it('production_rejects_empty_DATABASE_URL', () => { + const variants: Array = [undefined, '', ' ']; + for (const value of variants) { + const env = validEnv(PRODUCTION); + if (value === undefined) { + delete env.DATABASE_URL; + } else { + env.DATABASE_URL = value; + } + expectRejected(startWithEnv(env), 'DATABASE_URL'); + } + const withoutPassword = [ + 'postgresql://meetropolis:@localhost:5432/meetropolis?schema=public', + 'postgresql://meetropolis@localhost:5432/meetropolis?schema=public', + ]; + for (const value of withoutPassword) { + const env = validEnv(PRODUCTION); + env.DATABASE_URL = value; + expectRejected(startWithEnv(env), 'DATABASE_URL'); + } + }); + + it('production_rejects_example_DATABASE_URL', () => { + const templateUrl = readTemplateValue('DATABASE_URL'); + const env = validEnv(PRODUCTION); + env.DATABASE_URL = templateUrl; + expectRejected(startWithEnv(env), 'DATABASE_URL'); + + const parts = urlWithPasswordPart(templateUrl); + const encodedEnv = validEnv(PRODUCTION); + encodedEnv.DATABASE_URL = `${parts.prefix}${fullyEncoded(parts.password)}${parts.suffix}`; + expectRejected(startWithEnv(encodedEnv), 'DATABASE_URL'); + + const base = validEnv(PRODUCTION).DATABASE_URL; + const queryEnv = validEnv(PRODUCTION); + queryEnv.DATABASE_URL = `${base}&password=${fullyEncoded(parts.password)}`; + expectRejected(startWithEnv(queryEnv), 'DATABASE_URL'); + }); + + it('production_accepts_valid_DATABASE_URL', () => { + const env = validEnv(PRODUCTION); + expect('POSTGRES_PASSWORD' in env).toBe(false); + expectStarted(startWithEnv(env)); + }); + + it('development_accepts_example_DATABASE_URL', () => { + const env = validEnv(DEVELOPMENT); + env.DATABASE_URL = readTemplateValue('DATABASE_URL'); + expectStarted(startWithEnv(env)); + }); + + it('production_rejects_empty_POSTGRES_PASSWORD', () => { + for (const value of ['', ' ']) { + const env = validEnv(PRODUCTION); + env.POSTGRES_PASSWORD = value; + expectRejected(startWithEnv(env), 'POSTGRES_PASSWORD'); + } + }); + + it('production_rejects_example_POSTGRES_PASSWORD', () => { + const env = validEnv(PRODUCTION); + env.POSTGRES_PASSWORD = readTemplateValue('POSTGRES_PASSWORD'); + expectRejected(startWithEnv(env), 'POSTGRES_PASSWORD'); + }); + + it('production_accepts_valid_POSTGRES_PASSWORD', () => { + const env = validEnv(PRODUCTION); + env.POSTGRES_PASSWORD = 'synthetic-valid-postgres-password'; + expectStarted(startWithEnv(env)); + }); + + it('development_accepts_example_POSTGRES_PASSWORD', () => { + const env = validEnv(DEVELOPMENT); + env.POSTGRES_PASSWORD = readTemplateValue('POSTGRES_PASSWORD'); + expectStarted(startWithEnv(env)); + }); + + it('production_accepts_unset_TOOLS_PASSWORD', () => { + const missing = validEnv(PRODUCTION); + delete missing.TOOLS_PASSWORD; + expectStarted(startWithEnv(missing)); + + const empty = validEnv(PRODUCTION); + empty.TOOLS_PASSWORD = ''; + expectStarted(startWithEnv(empty)); + }); + }); +}); diff --git a/apps/server/src/ops/startupCredentials.ts b/apps/server/src/ops/startupCredentials.ts new file mode 100644 index 00000000..cc9a1112 --- /dev/null +++ b/apps/server/src/ops/startupCredentials.ts @@ -0,0 +1,22 @@ +/** + * Startup adapter: enforces the production credential policy before the + * server builds its application graph. + * + * Imported for its side effect as the first import in index.ts, right after + * the environment file load and before the application imports (which build + * database clients at import time). Also executed directly by entrypoint.sh + * and the migration command, so every production start path fails closed + * before any migration, seed, or listen work. Prints one offending key name + * per line and exits with status 1. Silent on success. + */ + +import { findInvalidCredentialKeys } from './credentialPolicy.js'; + +const invalidKeys = findInvalidCredentialKeys(process.env); + +if (invalidKeys.length > 0) { + for (const key of invalidKeys) { + process.stderr.write(`${key}\n`); + } + process.exit(1); +} diff --git a/apps/server/src/ops/toolsRoute.ts b/apps/server/src/ops/toolsRoute.ts new file mode 100644 index 00000000..d459df93 --- /dev/null +++ b/apps/server/src/ops/toolsRoute.ts @@ -0,0 +1,361 @@ +/** + * Operator tools route. + * + * Serves the six allowed operator tools under /tools. Every response of that + * mount carries a Content-Security-Policy: a strict fallback for everything + * that is not an allowed file - including the 401 of the Basic Auth in front + * of the mount - and, for an allowed file, a policy computed from that + * file's own bytes: the SHA-256 hashes of its inline script and style blocks + * plus the exact URLs of its external script and stylesheet references. + * + * A file is read once, on the first request that asks for it, and then + * cached for the lifetime of the process. The delivered bytes and the + * allowed hashes therefore always belong to the same file version. + */ + +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { URL } from 'node:url'; +import express from 'express'; +import { logger } from '../logger.js'; + +/** + * The only files served under /tools. Every other path answers 404, in + * development and in production alike. + */ +const ALLOWED_TOOL_FILES = [ + 'super-admin.html', + 'map-editor.html', + 'avatar-pack-manager.html', + 'npc-admin.html', + 'sprite-asset-cutter.html', + 'ui-prototype.html', +] as const; + +type AllowedToolFile = (typeof ALLOWED_TOOL_FILES)[number]; + +/** + * Fallback policy for every response that is not an allowed tool file. It + * allows nothing and only states the directives that keep a response from + * being framed, based or plugin driven. + */ +const BASE_CONTENT_SECURITY_POLICY = "default-src 'none'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'"; + +/** + * Font sources per file. Five tools load the font files of their Google + * Fonts stylesheet from fonts.gstatic.com, the UI prototype loads the + * font-awesome webfonts from the cdnjs webfont directory. + */ +const FONT_SOURCES: Record = { + 'super-admin.html': ['https://fonts.gstatic.com'], + 'map-editor.html': ['https://fonts.gstatic.com'], + 'avatar-pack-manager.html': ['https://fonts.gstatic.com'], + 'npc-admin.html': ['https://fonts.gstatic.com'], + 'sprite-asset-cutter.html': ['https://fonts.gstatic.com'], + 'ui-prototype.html': ['https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/webfonts/'], +}; + +/** + * Additional connect sources, proven by the tool sources. + * + * avatar-pack-manager.html reads the selected spritesheet as a data: URL + * (tools/avatar-pack-manager.html:659) and fetches that URL back to turn it + * into the upload blob (tools/avatar-pack-manager.html:1071). + */ +const EXTRA_CONNECT_SOURCES: Partial> = { + 'avatar-pack-manager.html': ['data:'], +}; + +export interface ToolsRouteOptions { + /** Directory that holds the tool files. */ + readonly toolsDir: string; + /** Exact https origins the tools may talk to, see parseToolsApiOrigins. */ + readonly apiOrigins: readonly string[]; +} + +interface ScannedToolHtml { + /** Hash source expressions of the inline script and style blocks. */ + readonly inlineHashes: readonly string[]; + /** Exact URLs of the external script references. */ + readonly externalScripts: readonly string[]; + /** Exact URLs of the external stylesheet references. */ + readonly externalStyles: readonly string[]; +} + +interface LoadedToolFile { + readonly body: Buffer; + readonly contentSecurityPolicy: string; +} + +interface OpenTag { + readonly name: string; + readonly attributes: Map; + /** Index right behind the closing '>' of the tag. */ + readonly end: number; +} + +/** + * Parses TOOLS_API_ORIGINS. + * + * The value is a comma separated list of exact https origins + * (https://host[:port]) without a path and without a wildcard. An empty or + * missing value means that the tools may only talk to their own origin. An + * invalid value aborts the start of the server and names the key, never the + * value. + */ +export function parseToolsApiOrigins(raw: string | undefined): string[] { + const trimmed = (raw ?? '').trim(); + if (trimmed === '') return []; + const origins: string[] = []; + for (const entry of trimmed.split(',')) { + const candidate = entry.trim(); + if (!isExactHttpsOrigin(candidate)) { + throw new Error('TOOLS_API_ORIGINS must contain exact https origins (https://host[:port])'); + } + origins.push(candidate); + } + return origins; +} + +function isExactHttpsOrigin(value: string): boolean { + if (value === '' || value.includes('*')) return false; + let url: URL; + try { + url = new URL(value); + } catch { + return false; + } + if (url.protocol !== 'https:') return false; + if (url.username !== '' || url.password !== '') return false; + if (url.pathname !== '/' || url.search !== '' || url.hash !== '') return false; + return url.origin === value; +} + +/** + * Sets the fallback policy. It runs in front of the Basic Auth so that the + * 401 of the authentication also carries a policy. + */ +export function toolsBaseCsp(_req: express.Request, res: express.Response, next: express.NextFunction): void { + res.setHeader('Content-Security-Policy', BASE_CONTENT_SECURITY_POLICY); + next(); +} + +/** + * Builds the route that serves the allowed tool files. Files are read and + * hashed on the first request that asks for them and then cached. + */ +export function createToolsRoute(options: ToolsRouteOptions): express.RequestHandler { + const cache = new Map(); + return (req: express.Request, res: express.Response): void => { + const file = resolveAllowedToolFile(req.path); + if (file === null || (req.method !== 'GET' && req.method !== 'HEAD')) { + res.status(404).send('Not found'); + return; + } + let loaded: LoadedToolFile; + try { + loaded = getToolFile(cache, options, file); + } catch (error) { + logger.error({ event: 'tools.load_failed', file, err: error }); + if (isMissingFileError(error)) { + res.status(404).send('Not found'); + return; + } + res.status(500).send('Tool unavailable'); + return; + } + res.setHeader('Content-Security-Policy', loaded.contentSecurityPolicy); + res.setHeader('Cache-Control', 'no-store'); + res.status(200).type('text/html').send(loaded.body); + }; +} + +function getToolFile( + cache: Map, + options: ToolsRouteOptions, + file: AllowedToolFile, +): LoadedToolFile { + const cached = cache.get(file); + if (cached !== undefined) return cached; + const loaded = loadToolFile(options.toolsDir, file, options.apiOrigins); + cache.set(file, loaded); + logger.info({ event: 'tools.file_loaded', file }); + return loaded; +} + +function resolveAllowedToolFile(requestPath: string): AllowedToolFile | null { + const name = requestPath.startsWith('/') ? requestPath.slice(1) : requestPath; + if (name === '' || name.includes('/') || name.includes('\\')) return null; + return isAllowedToolFile(name) ? name : null; +} + +function isAllowedToolFile(name: string): name is AllowedToolFile { + return ALLOWED_TOOL_FILES.some((file) => file === name); +} + +function isMissingFileError(error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false; + return (error as NodeJS.ErrnoException).code === 'ENOENT'; +} + +function loadToolFile(toolsDir: string, file: AllowedToolFile, apiOrigins: readonly string[]): LoadedToolFile { + const body = fs.readFileSync(path.join(toolsDir, file)); + const scanned = scanToolHtml(body.toString('utf8'), file); + for (const url of [...scanned.externalScripts, ...scanned.externalStyles]) { + if (!url.startsWith('https://')) { + throw new Error(`Operator tool ${file} references ${url}, which is not served over https`); + } + } + return { body, contentSecurityPolicy: buildContentSecurityPolicy(file, scanned, apiOrigins) }; +} + +function buildContentSecurityPolicy( + file: AllowedToolFile, + scanned: ScannedToolHtml, + apiOrigins: readonly string[], +): string { + const connectSources = ["'self'", ...apiOrigins, ...(EXTRA_CONNECT_SOURCES[file] ?? [])]; + return [ + "default-src 'none'", + sourceList('script-src', [...scanned.inlineHashes, ...scanned.externalScripts]), + "script-src-attr 'none'", + sourceList('style-src', [...scanned.inlineHashes, ...scanned.externalStyles]), + sourceList('font-src', FONT_SOURCES[file]), + "img-src 'self' data: blob:", + sourceList('connect-src', connectSources), + "object-src 'none'", + "base-uri 'none'", + "frame-ancestors 'none'", + "form-action 'self'", + ].join('; '); +} + +function sourceList(directive: string, sources: readonly string[]): string { + return `${directive} ${sources.length > 0 ? sources.join(' ') : "'none'"}`; +} + +/** + * Collects the policy relevant parts of a tool file: the hashes of its inline + * script and style blocks and the exact URLs of its external script and + * stylesheet references. + */ +function scanToolHtml(html: string, file: AllowedToolFile): ScannedToolHtml { + const inlineHashes: string[] = []; + const externalScripts: string[] = []; + const externalStyles: string[] = []; + const openTagPattern = /<(script|style|link)(?=[\s/>])/gi; + let match = openTagPattern.exec(html); + while (match !== null) { + const tag = readOpenTag(html, match.index); + if (tag === null) { + openTagPattern.lastIndex = match.index + 1; + } else if (tag.name === 'script') { + const source = tag.attributes.get('src'); + if (source === undefined) { + const end = findClosingTag(html, tag.end, 'script', file); + inlineHashes.push(hashInlineContent(html.slice(tag.end, end))); + openTagPattern.lastIndex = end; + } else { + externalScripts.push(source); + } + } else if (tag.name === 'style') { + const end = findClosingTag(html, tag.end, 'style', file); + inlineHashes.push(hashInlineContent(html.slice(tag.end, end))); + openTagPattern.lastIndex = end; + } else { + const relation = tag.attributes.get('rel'); + const href = tag.attributes.get('href'); + if (href !== undefined && relation !== undefined && isStylesheetRelation(relation)) { + externalStyles.push(href); + } + } + // The scan must always move forward, also when a block ends before the + // tag that opened it. + if (openTagPattern.lastIndex <= match.index) { + openTagPattern.lastIndex = match.index + 1; + } + match = openTagPattern.exec(html); + } + return { inlineHashes, externalScripts, externalStyles }; +} + +function isStylesheetRelation(relation: string): boolean { + const tokens = relation.toLowerCase().split(/\s+/); + return tokens.includes('stylesheet'); +} + +/** + * Hashes the content of an inline script or style block. The hash covers the + * text exactly as the browser reads it: the characters between the tags, with + * the line endings normalized the way the HTML parser normalizes them. + */ +function hashInlineContent(content: string): string { + const normalized = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + const digest = crypto.createHash('sha256').update(normalized, 'utf8').digest('base64'); + return `'sha256-${digest}'`; +} + +/** + * Finds the closing tag of a script or style block. The search starts behind + * the opening tag; a block without a closing tag is a broken tool file and + * fails the load. + */ +function findClosingTag(html: string, from: number, name: string, file: AllowedToolFile): number { + const pattern = new RegExp(`'. Quoted attribute values may contain a '>'. + */ +function readOpenTag(html: string, start: number): OpenTag | null { + let index = start + 1; + const nameStart = index; + while (index < html.length && /[a-zA-Z]/.test(html[index])) index += 1; + const name = html.slice(nameStart, index).toLowerCase(); + if (name === '') return null; + const attributes = new Map(); + while (index < html.length) { + while (index < html.length && /\s/.test(html[index])) index += 1; + if (index >= html.length) break; + if (html[index] === '>') { + index += 1; + break; + } + if (html[index] === '/') { + index += 1; + continue; + } + const attributeStart = index; + while (index < html.length && !/[\s=>/]/.test(html[index])) index += 1; + const attribute = html.slice(attributeStart, index).toLowerCase(); + while (index < html.length && /\s/.test(html[index])) index += 1; + const value = readAttributeValue(html, index); + index = value.nextIndex; + if (attribute !== '' && !attributes.has(attribute)) attributes.set(attribute, value.text); + } + return { name, attributes, end: index }; +} + +function readAttributeValue(html: string, index: number): { text: string; nextIndex: number } { + if (html[index] !== '=') return { text: '', nextIndex: index }; + let cursor = index + 1; + while (cursor < html.length && /\s/.test(html[cursor])) cursor += 1; + const quote = html[cursor]; + if (quote === '"' || quote === "'") { + cursor += 1; + const textStart = cursor; + while (cursor < html.length && html[cursor] !== quote) cursor += 1; + return { text: html.slice(textStart, cursor), nextIndex: cursor + 1 }; + } + const textStart = cursor; + while (cursor < html.length && !/[\s>]/.test(html[cursor])) cursor += 1; + return { text: html.slice(textStart, cursor), nextIndex: cursor }; +} diff --git a/apps/server/src/ops/wsUpgradeLimit.integration.test.ts b/apps/server/src/ops/wsUpgradeLimit.integration.test.ts new file mode 100644 index 00000000..3046dae9 --- /dev/null +++ b/apps/server/src/ops/wsUpgradeLimit.integration.test.ts @@ -0,0 +1,349 @@ +/** + * Budget for the websocket upgrade path, exercised against the real server + * process. + * + * Every case starts its own server, so every case begins with an empty + * counter and the cases cannot influence each other. The server runs as a + * child process (the same pattern as metricsAccess.integration.test.ts), so + * the Express middleware, the Colyseus transport and the upgrade handshake + * are the production ones. The port comes from WS_UPGRADE_TEST_PORT and has + * to be set. Credentials are generated at runtime and never logged. + */ + +import { spawn, type ChildProcess } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import { createRequire } from 'node:module'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, it } from 'vitest'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SERVER_DIR = path.resolve(HERE, '..', '..'); +const PORT_KEY = 'WS_UPGRADE_TEST_PORT'; +const READY_PATH = '/healthz'; +const START_TIMEOUT_MS = 60_000; +const STOP_TIMEOUT_MS = 20_000; +const PORT_PROBE_MS = 5_000; +const CLOSE_GRACE_MS = 250; + +/** The origin every upgrade of this file carries; the server allows it. */ +const ALLOWED_ORIGIN = 'https://ws-limit.test'; + +/** The budget every case of this file runs with. */ +const ATTEMPT_LIMIT = 3; + +interface UpgradeOutcome { + /** The status the server answered with: 101 for an accepted handshake. */ + status: number; + /** The headers of the answer. */ + headers: http.IncomingHttpHeaders; + /** Whether the server closed the connection after its answer. */ + closed: boolean; +} + +interface ServerOptions { + /** The trust proxy setting of the server. */ + trustProxy: string; + /** The upgrade budget of the server. */ + max?: string; + /** The upgrade window of the server. */ + windowMs?: string; +} + +const children: ChildProcess[] = []; + +afterEach(async () => { + while (children.length > 0) { + const child = children.pop(); + if (child) await stopChild(child); + } +}); + +describe('websocket upgrade limit', { timeout: 180_000 }, () => { + it('refuses the upgrade that exceeds the budget', async () => { + const port = await startServer({ trustProxy: 'false' }); + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + expect((await upgradeHandshake(port)).status).toBe(101); + } + const refused = await upgradeHandshake(port); + expect(refused.status).toBe(429); + expect(refused.closed).toBe(true); + const retryAfter = refused.headers['retry-after']; + expect(retryAfter).toBeDefined(); + expect(Number.isInteger(Number(retryAfter))).toBe(true); + expect(Number(retryAfter)).toBeGreaterThan(0); + }); + + it('counts a forged forwarding header as the same client without proxy trust', async () => { + const port = await startServer({ trustProxy: 'false' }); + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + const outcome = await upgradeHandshake(port, { 'x-forwarded-for': `203.0.113.${attempt}` }); + expect(outcome.status).toBe(101); + } + const refused = await upgradeHandshake(port, { 'x-forwarded-for': '203.0.113.200' }); + expect(refused.status).toBe(429); + }); + + it('accepts the upgrades inside the budget', async () => { + const port = await startServer({ trustProxy: 'false' }); + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + expect((await upgradeHandshake(port)).status).toBe(101); + } + }); + + it('counts a trusted forwarded client apart from another one', async () => { + const port = await startServer({ trustProxy: '1' }); + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + const outcome = await upgradeHandshake(port, { 'x-forwarded-for': '198.51.100.7' }); + expect(outcome.status).toBe(101); + } + const other = await upgradeHandshake(port, { 'x-forwarded-for': '198.51.100.8' }); + expect(other.status).toBe(101); + }); + + it('counts ipv6 clients from different subnets apart', async () => { + const port = await startServer({ trustProxy: '1' }); + for (const address of ['2001:db8:1:2::1', '2001:db8:2:3::1']) { + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + const outcome = await upgradeHandshake(port, { 'x-forwarded-for': address }); + expect(outcome.status).toBe(101); + } + } + }); + + it('accepts upgrades again after the window has passed', async () => { + const port = await startServer({ trustProxy: 'false', windowMs: '1000' }); + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + expect((await upgradeHandshake(port)).status).toBe(101); + } + await sleep(1200); + for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) { + expect((await upgradeHandshake(port)).status).toBe(101); + } + }); +}); + +/** + * One upgrade attempt against the server. The socket of an accepted + * handshake is closed right away: the case is about the answer, not about + * the session. + */ +function upgradeHandshake(port: number, headers: Record = {}): Promise { + return new Promise((resolve, reject) => { + const request = http.request({ + host: '127.0.0.1', + port, + path: '/', + method: 'GET', + headers: { + connection: 'Upgrade', + upgrade: 'websocket', + 'sec-websocket-key': randomBytes(16).toString('base64'), + 'sec-websocket-version': '13', + origin: ALLOWED_ORIGIN, + ...headers, + }, + }); + request.on('upgrade', (response, socket) => { + socket.destroy(); + resolve({ status: 101, headers: response.headers, closed: false }); + }); + request.on('response', (response) => { + const socket = response.socket; + response.resume(); + let closed = socket.destroyed; + socket.once('close', () => { + closed = true; + }); + response.once('end', () => { + // The server closes the connection after a refusal; give the close + // event the moment it needs before the answer is reported. + setTimeout(() => { + resolve({ status: response.statusCode ?? 0, headers: response.headers, closed }); + }, CLOSE_GRACE_MS); + }); + }); + request.on('error', reject); + request.end(); + }); +} + +async function startServer(options: ServerOptions): Promise { + const port = configuredPort(); + await assertPortFree(port); + const child = startChild({ port, ...options }); + const outcome = await waitForListeningOrExit(child, port); + expect(outcome).toBe('listening'); + return port; +} + +function startChild(options: { + port: number; + trustProxy: string; + max?: string; + windowMs?: string; +}): ChildProcess { + const child = spawn(process.execPath, [resolveTsx(), 'src/index.ts'], { + cwd: SERVER_DIR, + env: childEnv(options), + stdio: ['ignore', 'pipe', 'pipe'], + }); + child.stdout?.on('data', () => { + // Drain so a chatty child never blocks on a full pipe. + }); + child.stderr?.on('data', () => { + // Drain; never echo. The child env holds runtime credentials. + }); + children.push(child); + return child; +} + +function childEnv(options: { + port: number; + trustProxy: string; + max?: string; + windowMs?: string; +}): Record { + const env: Record = { + PATH: process.env.PATH ?? '/usr/bin:/bin', + NODE_ENV: 'production', + NODE_OPTIONS: '--no-warnings', + PORT: String(options.port), + // The server refuses to start without an origin allowlist. This test does + // not exercise the origin rules, it only needs the server to come up. + CORS_ORIGIN: ALLOWED_ORIGIN, + TRUST_PROXY: options.trustProxy, + WS_UPGRADE_RATE_LIMIT_MAX: options.max ?? String(ATTEMPT_LIMIT), + DATABASE_URL: requiredDatabaseUrl(), + LIVEKIT_API_KEY: syntheticSecret(), + LIVEKIT_API_SECRET: syntheticSecret(), + JWT_SECRET: syntheticSecret(), + API_TOKEN_PEPPER: syntheticSecret(), + DOTENV_CONFIG_PATH: emptyEnvFile(), + LOG_LEVEL: 'error', + }; + if (options.windowMs !== undefined) env.WS_UPGRADE_RATE_LIMIT_WINDOW_MS = options.windowMs; + if (process.env.HOME) env.HOME = process.env.HOME; + if (process.env.TMPDIR) env.TMPDIR = process.env.TMPDIR; + return env; +} + +/** The port the environment names. The tests cannot run without it. */ +function configuredPort(): number { + const raw = process.env[PORT_KEY]; + if (raw === undefined || raw === '') { + throw new Error(`${PORT_KEY} must be set to a port for the websocket upgrade tests`); + } + const port = Number(raw); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`${PORT_KEY} must be set to an integer between 1 and 65535`); + } + return port; +} + +function requiredDatabaseUrl(): string { + const url = process.env.DATABASE_URL; + if (typeof url !== 'string' || url.length === 0) { + throw new Error('DATABASE_URL is required'); + } + return url; +} + +function syntheticSecret(): string { + return randomBytes(32).toString('hex'); +} + +let emptyEnvPath: string | undefined; + +function emptyEnvFile(): string { + if (emptyEnvPath === undefined) { + emptyEnvPath = path.join(os.tmpdir(), `ws-upgrade-limit-empty-env-${process.pid}`); + fs.writeFileSync(emptyEnvPath, ''); + } + return emptyEnvPath; +} + +function resolveTsx(): string { + const scopedRequire = createRequire(path.join(SERVER_DIR, 'package.json')); + const packagePath = scopedRequire.resolve('tsx/package.json'); + const cliPath = path.join(path.dirname(packagePath), 'dist', 'cli.mjs'); + if (!fs.existsSync(cliPath)) { + throw new Error('tsx runner is missing'); + } + return cliPath; +} + +async function assertPortFree(port: number): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host: '127.0.0.1', port }); + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error(`test port ${port} did not refuse a connection in time`)); + }, PORT_PROBE_MS); + if (typeof timer.unref === 'function') timer.unref(); + socket.once('connect', () => { + clearTimeout(timer); + socket.destroy(); + reject(new Error(`test port ${port} is already in use; refusing a foreign process`)); + }); + socket.once('error', (error) => { + clearTimeout(timer); + if (errnoCode(error) === 'ECONNREFUSED') { + resolve(); + } else { + reject(error); + } + }); + }); +} + +async function waitForListeningOrExit(child: ChildProcess, port: number): Promise<'listening' | 'exited'> { + const deadline = Date.now() + START_TIMEOUT_MS; + const healthUrl = `http://127.0.0.1:${port}${READY_PATH}`; + while (Date.now() < deadline) { + if (child.exitCode !== null || child.signalCode !== null) return 'exited'; + try { + const res = await fetch(healthUrl); + await res.text(); + return 'listening'; + } catch { + // Not up yet. + } + await sleep(50); + } + throw new Error('server neither listened nor exited'); +} + +function stopChild(child: ChildProcess): Promise { + if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(); + return new Promise((resolve) => { + const killTimer = setTimeout(() => { + child.kill('SIGKILL'); + const exitTimer = setTimeout(resolve, 5_000); + if (typeof exitTimer.unref === 'function') exitTimer.unref(); + child.once('exit', () => { + clearTimeout(exitTimer); + resolve(); + }); + }, STOP_TIMEOUT_MS); + if (typeof killTimer.unref === 'function') killTimer.unref(); + child.once('exit', () => { + clearTimeout(killTimer); + resolve(); + }); + child.kill('SIGTERM'); + }); +} + +function errnoCode(error: unknown): string | undefined { + if (typeof error !== 'object' || error === null || !('code' in error)) return undefined; + return typeof error.code === 'string' ? error.code : undefined; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/server/src/ops/wsUpgradeLimit.ts b/apps/server/src/ops/wsUpgradeLimit.ts new file mode 100644 index 00000000..1cd99976 --- /dev/null +++ b/apps/server/src/ops/wsUpgradeLimit.ts @@ -0,0 +1,165 @@ +/** + * Budget for the websocket upgrade path. + * + * Every upgrade attempt is counted before the origin check, so a client that + * hammers the handshake path runs into a budget instead of into the origin + * policy. The counter lives in the memory store of express-rate-limit: it + * expires on its own and holds nothing but a hit count and a reset time. + * + * The client address is resolved with the semantics the HTTP surface gives + * `req.ip`: the `trust proxy` setting decides how much of the forwarded chain + * is believed (see trustProxy.ts). There is no loopback exemption and no + * debug switch: the mobile gateway, which joins from inside the server + * process, and the npc-service, which runs in its own container, share the + * budget of their source address. A deployment that needs more raises + * WS_UPGRADE_RATE_LIMIT_MAX. + * + * Nothing about an attempt is logged: no address, no URL, no header and no + * query value. + */ + +import express from 'express'; +import type { IncomingMessage } from 'node:http'; +import { MemoryStore, ipKeyGenerator, type Options } from 'express-rate-limit'; +import { resolveTrustProxySetting } from '../trustProxy.js'; + +/** Environment key that holds the upgrade attempts one address may start per window. */ +export const WS_UPGRADE_LIMIT_MAX_KEY = 'WS_UPGRADE_RATE_LIMIT_MAX'; + +/** Environment key that holds the length of the upgrade window in milliseconds. */ +export const WS_UPGRADE_LIMIT_WINDOW_KEY = 'WS_UPGRADE_RATE_LIMIT_WINDOW_MS'; + +/** The default budget: 120 attempts per minute and address. */ +const DEFAULT_MAX = 120; + +/** The default window: one minute. */ +const DEFAULT_WINDOW_MS = 60_000; + +/** The shortest window a deployment may configure. */ +const MIN_WINDOW_MS = 1_000; + +/** The longest window a deployment may configure. */ +const MAX_WINDOW_MS = 3_600_000; + +/** The largest budget a deployment may configure. */ +const MAX_MAX = 100_000; + +/** Plain decimal integers without a sign; everything else is a configuration error. */ +const POSITIVE_INTEGER = /^[1-9][0-9]*$/; + +export interface WsUpgradeLimitSettings { + /** The upgrade attempts one client address may start per window. */ + readonly max: number; + /** The length of the window in milliseconds. */ + readonly windowMs: number; +} + +export interface WsUpgradeAllowed { + readonly allowed: true; +} + +export interface WsUpgradeDenied { + readonly allowed: false; + /** The seconds the client has to wait until the budget is available again. */ + readonly retryAfterSeconds: number; +} + +export type WsUpgradeDecision = WsUpgradeAllowed | WsUpgradeDenied; + +export interface WsUpgradeLimiter { + /** Count one upgrade attempt and decide whether it may proceed. */ + checkWsUpgrade(req: IncomingMessage): Promise; +} + +/** + * Read the upgrade budget from the environment. A missing or empty value takes + * the default; a value that is set but is not a plain decimal integer inside + * the allowed range is a configuration error, because a budget nobody can + * predict is worse than no budget at all. The error names the key, never the + * value. + */ +export function resolveWsUpgradeLimit(env: NodeJS.ProcessEnv): WsUpgradeLimitSettings { + return { + max: readSetting(env, WS_UPGRADE_LIMIT_MAX_KEY, DEFAULT_MAX, 1, MAX_MAX), + windowMs: readSetting(env, WS_UPGRADE_LIMIT_WINDOW_KEY, DEFAULT_WINDOW_MS, MIN_WINDOW_MS, MAX_WINDOW_MS), + }; +} + +function readSetting( + env: NodeJS.ProcessEnv, + key: string, + fallback: number, + lowerBound: number, + upperBound: number, +): number { + const raw = (env[key] ?? '').trim(); + if (raw === '') return fallback; + if (!POSITIVE_INTEGER.test(raw)) { + throw new Error(`${key} must be a decimal integer without a sign`); + } + const value = Number(raw); + if (value < lowerBound || value > upperBound) { + throw new Error(`${key} must be between ${lowerBound} and ${upperBound}`); + } + return value; +} + +/** + * Build the limiter that counts the upgrade attempts of one server process. + * + * The trust proxy setting is the one the HTTP surface uses; the caller passes + * it so both surfaces resolve the very same value. + */ +export function createWsUpgradeLimiter( + settings: WsUpgradeLimitSettings, + trustProxy: boolean | number = resolveTrustProxySetting(), +): WsUpgradeLimiter { + const store = new MemoryStore(); + // The store reads nothing but the window length; the rest of the options + // belong to the rate limit middleware, not to the store. The cast stays + // inside this one call. + store.init({ windowMs: settings.windowMs } as Partial as Options); + const resolveAddress = createAddressResolver(trustProxy); + + return { + async checkWsUpgrade(req: IncomingMessage): Promise { + const address = resolveAddress(req) ?? req.socket?.remoteAddress; + if (address === undefined || address === '') { + // Without an address there is no key to count under. The attempt is + // refused instead of going uncounted. + return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil(settings.windowMs / 1000)) }; + } + const { totalHits, resetTime } = await store.increment(ipKeyGenerator(address)); + if (totalHits <= settings.max) return { allowed: true }; + return { allowed: false, retryAfterSeconds: secondsUntilReset(resetTime) }; + }, + }; +} + +/** + * Resolve the client address of an upgrade with the semantics Express gives + * `req.ip`. The resolver is an Express application that never answers a + * request; it only provides the request prototype the address getter needs. + */ +function createAddressResolver(trustProxy: boolean | number): (req: IncomingMessage) => string | undefined { + const resolver = express(); + resolver.set('trust proxy', trustProxy); + return (req: IncomingMessage): string | undefined => { + // The view carries what Express reads to resolve an address: the headers + // and the socket. It inherits from the prototype of the resolver app, so + // the address getter and the app wide trust setting apply. + const view = Object.create(resolver.request) as express.Request; + view.headers = req.headers; + view.socket = req.socket; + view.connection = req.connection; + const address = view.ip; + return address !== undefined && address !== '' ? address : undefined; + }; +} + +/** The seconds until the counter resets, rounded up and never below one. */ +function secondsUntilReset(resetTime: Date | undefined): number { + if (resetTime === undefined) return 1; + const remainingMs = resetTime.getTime() - Date.now(); + return Math.max(1, Math.ceil(remainingMs / 1000)); +} diff --git a/apps/server/src/scripts/replayTenantDeletions.ts b/apps/server/src/scripts/replayTenantDeletions.ts new file mode 100644 index 00000000..1df04d1f --- /dev/null +++ b/apps/server/src/scripts/replayTenantDeletions.ts @@ -0,0 +1,153 @@ +import { pathToFileURL } from 'node:url'; +import { getAdminEnterpriseModule } from '../adminLoader.js'; +import { createPrismaClient } from '../db.js'; +import type { PrismaClient } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; +import { deleteAccount, deleteTenantWithMembers } from '../services/accountDeletion.js'; +import { + createAccountJournalPlanResolver, + registerAccountDeletionJournal, +} from '../services/accountDeletionJournal.js'; +import { assertTenantDeletionProtocol } from '../services/tenantDeletionContract.js'; +import { createJournalPlanResolver } from '../services/tenantDeletionPlanning.js'; +import type { ReplayDecision } from '../services/tenantDeletionReplay.js'; +import { REPLAY_EXIT, runRestoreReplay, type OAuthRefreshRevocation } from '../services/tenantDeletionReplayRun.js'; +import { getTranscriptionLoadState, getTranscriptionModule, type TranscriptionModule } from '../transcriptionLoader.js'; + +/** + * Restore replay tool. Run by an operator after scripts/restore.sh while the + * server is stopped: + * + * node dist/scripts/replayTenantDeletions.js [--decide =delete|keep]... + * + * Deletes tenants and accounts again that the deletion journal records as deleted after + * the restored copy was taken, through the same managed deletion paths as + * DELETE /admin/tenants/:id and the account deletion. Afterwards the token step drops + * sessions and unused reset and verification tokens. Exit codes: see services/tenantDeletionReplayRun.ts. + */ + +const USAGE = 'Usage: node dist/scripts/replayTenantDeletions.js [--decide =delete|keep]...'; + +type AdminModule = NonNullable>>; + +class ReplayDeleteRejectedError extends Error { + constructor(readonly code: string) { + super('managed tenant deletion rejected'); + this.name = 'ReplayDeleteRejectedError'; + } +} + +/** Parses repeated `--decide =delete|keep`; null for any other input. */ +export function parseDecisions(args: readonly string[]): Map | null { + const decisions = new Map(); + for (let index = 0; index < args.length; index += 2) { + if (args[index] !== '--decide') return null; + const match = /^([A-Za-z0-9_-]{1,128})=(delete|keep)$/.exec(args[index + 1] ?? ''); + if (!match || decisions.has(match[1])) return null; + decisions.set(match[1], match[2] === 'delete' ? 'delete' : 'keep'); + } + return decisions; +} + +function managedDeleter( + prisma: PrismaClient, + journalDir: string, + admin: AdminModule | null, +): ((tenantId: string) => Promise) | undefined { + const deleteManagedTenant = admin?.deleteManagedTenant; + if (!deleteManagedTenant) return undefined; + let resolver: ReturnType | undefined; + const config: Parameters[0] = { + prisma, + logger, + deleteTenantWithMembers: (tenantId, options) => { + assertTenantDeletionProtocol(options?.deletionProtocol); + return deleteTenantWithMembers(prisma, tenantId, options); + }, + // Own resolver with the restore pass: while the restore marker exists the + // shared resolver refuses every deletion, only this tool may delete. + resolveTenantDeletionPlan: async (tx, input) => { + resolver ??= createJournalPlanResolver({ + prisma, + journalDir, + retentionDays: process.env.BACKUP_RETENTION_DAYS, + allowDuringRestoreReplay: true, + }); + return (await resolver)(tx, input); + }, + }; + return async (tenantId) => { + const result = await deleteManagedTenant(config, tenantId, { actor: 'restore-replay' }); + if (!result.ok && result.status !== 404) throw new ReplayDeleteRejectedError(result.error); + }; +} + +/** The loaded transcription module with its OAuth refresh revocation present. */ +type RevokingTranscriptionModule = TranscriptionModule & { + revokeOAuthRefreshTokensAfterRestore: NonNullable; +}; + +/** Narrows the optional OAuth refresh revocation of a loaded module to a present one. */ +function hasOAuthRevocation(transcription: TranscriptionModule): transcription is RevokingTranscriptionModule { + return typeof transcription.revokeOAuthRefreshTokensAfterRestore === 'function'; +} + +/** OAuth refresh token revocation of the loaded transcription module, for the token step. */ +async function oauthRevocation(prisma: PrismaClient): Promise { + const transcription = await getTranscriptionModule(); + if (transcription === null) { + // Only an absent package counts as not loaded; an installed but rejected module fails the token step. + return getTranscriptionLoadState() === 'absent' ? { kind: 'module_not_loaded' } : { kind: 'module_rejected' }; + } + if (!hasOAuthRevocation(transcription)) return { kind: 'export_missing' }; + // Called on the module, so that the module keeps its receiver. + return { kind: 'available', revoke: (now) => transcription.revokeOAuthRefreshTokensAfterRestore(prisma, now) }; +} + +async function main(): Promise { + const decisions = parseDecisions(process.argv.slice(2)); + if (!decisions) { + console.error(USAGE); + process.exitCode = REPLAY_EXIT.invalid; + return; + } + const journalDir = process.env.DELETION_JOURNAL_DIR?.trim() ?? ''; + if (journalDir === '') { + console.error('restore replay: DELETION_JOURNAL_DIR is not set'); + process.exitCode = REPLAY_EXIT.invalid; + return; + } + const prisma = createPrismaClient(); + try { + registerAccountDeletionJournal( + createAccountJournalPlanResolver({ + prisma, + journalDir, + retentionDays: process.env.BACKUP_RETENTION_DAYS, + allowDuringRestoreReplay: true, + }), + ); + const admin = await getAdminEnterpriseModule(); + const result = await runRestoreReplay({ + prisma, + journalDir, + decisions, + deleteTenant: managedDeleter(prisma, journalDir, admin), + deleteAccount: (userId) => deleteAccount(prisma, userId), + pendingPreconditions: async () => admin?.pendingRestorePreconditions?.() ?? [], + oauthRefreshRevocation: await oauthRevocation(prisma), + }); + for (const line of result.lines) console.log(line); + process.exitCode = result.exitCode; + } finally { + await prisma.$disconnect(); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error: unknown) => { + const code = error instanceof Error ? error.name : 'unexpected'; + console.error(`restore replay: failed (${code})`); + process.exitCode = REPLAY_EXIT.invalid; + }); +} diff --git a/apps/server/src/services/__testutils__/accountDeletionLegacy.ts b/apps/server/src/services/__testutils__/accountDeletionLegacy.ts new file mode 100644 index 00000000..a1deb439 --- /dev/null +++ b/apps/server/src/services/__testutils__/accountDeletionLegacy.ts @@ -0,0 +1,225 @@ +/** + * Legacy OSS contract snapshot for R3.2b compatibility testing (PHASE1 red test). + * Origin: apps/server/src/services/accountDeletion.ts at commit + * e9e3817d935c25a7774d475361b8836dab6d8a7d (f0b43db9 working-tree SHA256). + * Implementation is unchanged; only relative import paths were shifted one + * directory level because this fixture lives in __testutils__/. + */ +import type { PrismaClient } from '../../generated/prisma/index.js'; +import { Prisma } from '../../generated/prisma/index.js'; +import { logger } from '../../logger.js'; +import { revokeSessionsForUserInTx } from '../../api/utils/sessionAuth.js'; +import { invalidateSessionsForUser } from '../../api/utils/sessionCache.js'; +import { customAvatarPacksDir, deleteCustomAvatarFiles } from '../avatarComposer.js'; +import { revokeTenantAccess } from '../tenantAccessRevocation.js'; +import { removeTenantFiles } from '../tenantFiles.js'; + +/** + * Account deletion and member removal. + * + * Every database change runs in ONE interactive transaction: either the whole + * deletion lands or nothing does. The previous implementation deleted rows one + * by one, swallowed every error and then failed on `user.delete` because + * `Session` and `EmailVerification` reference the user with ON DELETE RESTRICT, + * which left accounts without any membership behind while the client was told + * the deletion had failed. + * + * Semantics: + * - `deleteAccount`: removes the account and everything that references it. + * - `removeMemberFromTenant`: removes the membership in ONE tenant and signs the + * user out everywhere. If that was the user's last membership, the account is + * deleted in the same transaction (an account without any tenant has no use). + * + * Filesystem work (custom avatar sprites), cache invalidation and the + * revocation of open world and AV connections happen after the commit and never turn a committed deletion into an error. + */ + +export interface MemberRemovalResult { + accountDeleted: boolean; +} + +export class MembershipNotFoundError extends Error { + constructor(userId: string, tenantId: string) { + super(`membership of user ${userId} in tenant ${tenantId} not found`); + this.name = 'MembershipNotFoundError'; + } +} + +async function purgeAccountRows(tx: Prisma.TransactionClient, userId: string): Promise { + await revokeSessionsForUserInTx(tx, userId); + await tx.emailVerification.deleteMany({ where: { userId } }); + await tx.passwordReset.deleteMany({ where: { userId } }); + await tx.apiToken.deleteMany({ where: { userId } }); + await tx.presence.deleteMany({ where: { userId } }); + await tx.invite.updateMany({ where: { usedById: userId }, data: { usedById: null } }); + await tx.invite.updateMany({ where: { createdBy: userId }, data: { createdBy: null } }); + await tx.membership.deleteMany({ where: { userId } }); + // CustomAvatar and the enterprise transcription tables cascade from User. + await tx.user.delete({ where: { id: userId } }); +} + +async function readCustomAvatarUuid(prisma: PrismaClient, userId: string): Promise { + const avatar = await prisma.customAvatar.findUnique({ where: { userId }, select: { uuid: true } }); + return avatar?.uuid ?? null; +} + +async function removeCustomAvatarFiles(userId: string, uuid: string | null): Promise { + if (!uuid) return; + try { + await deleteCustomAvatarFiles(customAvatarPacksDir(), uuid); + } catch (err) { + // The rows are gone already; orphaned sprite files are a cleanup issue, + // not a reason to report the committed deletion as failed. + logger.warn({ event: 'user.delete.avatar_cleanup_failed', userId, error: String(err) }); + } +} + +/** Delete the account of `userId` with everything that references it. */ +export async function deleteAccount(prisma: PrismaClient, userId: string): Promise { + const avatarUuid = await readCustomAvatarUuid(prisma, userId); + const memberships = await prisma.membership.findMany({ + where: { userId }, + select: { tenant: { select: { slug: true } } }, + }); + await prisma.$transaction(async (tx) => { + await purgeAccountRows(tx, userId); + }); + invalidateSessionsForUser(userId); + for (const m of memberships) await revokeTenantAccess(m.tenant.slug, userId); + await removeCustomAvatarFiles(userId, avatarUuid); +} + +/** + * Remove `userId` from `tenantId`. Deletes the whole account when no other + * membership remains. Throws `MembershipNotFoundError` (nothing changed) when + * the membership does not exist. + */ +export async function removeMemberFromTenant( + prisma: PrismaClient, + params: { userId: string; tenantId: string }, +): Promise { + const { userId, tenantId } = params; + const avatarUuid = await readCustomAvatarUuid(prisma, userId); + const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); + const accountDeleted = await prisma.$transaction(async (tx) => { + // Serialize concurrent removals of the same user (S1-R7): without the row + // lock, two removals of the last two memberships each still see the + // other's membership, and both keep an account that ends up memberless. + await tx.$queryRaw`SELECT id FROM "User" WHERE id = ${userId} FOR UPDATE`; + const removed = await tx.membership.deleteMany({ where: { userId, tenantId } }); + if (removed.count === 0) throw new MembershipNotFoundError(userId, tenantId); + await tx.presence.deleteMany({ where: { userId, tenantId } }); + // Sign the user out everywhere: sessions are not bound to a tenant, and a + // removed member must not keep a live session in the tenant it left. + await revokeSessionsForUserInTx(tx, userId); + const remaining = await tx.membership.count({ where: { userId } }); + if (remaining > 0) return false; + await purgeAccountRows(tx, userId); + return true; + }); + invalidateSessionsForUser(userId); + if (tenant) await revokeTenantAccess(tenant.slug, userId); + if (accountDeleted) await removeCustomAvatarFiles(userId, avatarUuid); + return { accountDeleted }; +} + +/** + * Delete a tenant together with its memberships in ONE transaction. Members + * lose all their sessions (sessions are not tenant-bound); a member whose last + * membership this was loses the account. Rows that carry the tenant id without + * a foreign key go in the same transaction: CustomAvatar here, enterprise rows + * via `cleanupInTx`. Tenant content (maps, rooms, zones, NPCs) is not deleted: + * while it exists, the final tenant delete fails on its foreign keys and the + * whole transaction rolls back. World and AV access end after the commit. + */ +/** + * A tenant with large maps deletes tens of thousands of map chunks in this + * transaction; the Prisma default of 5 s is not enough (Q-ACC-19c large-map + * test). + */ +const TENANT_DELETION_TIMEOUT_MS = 120_000; + +export async function deleteTenantWithMembers( + prisma: PrismaClient, + tenantId: string, + options: { cleanupInTx?: (tx: Prisma.TransactionClient) => Promise } = {}, +): Promise<{ deletedAccounts: number }> { + const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); + if (!tenant) throw new Error('tenant not found'); + const memberIds = ( + await prisma.membership.findMany({ where: { tenantId }, select: { userId: true }, orderBy: { userId: 'asc' } }) + ).map((m) => m.userId); + const mapIds = (await prisma.map.findMany({ where: { tenantId }, select: { id: true } })).map((m) => m.id); + const layerIds = (await prisma.mapLayer.findMany({ where: { mapId: { in: mapIds } }, select: { id: true } })).map( + (l) => l.id, + ); + const roomIds = (await prisma.room.findMany({ where: { tenantId }, select: { id: true } })).map((r) => r.id); + const npcIds = (await prisma.npc.findMany({ where: { tenantId }, select: { id: true } })).map((n) => n.id); + const assetPackUuids = (await prisma.assetPack.findMany({ where: { tenantId }, select: { uuid: true } })).map( + (p) => p.uuid, + ); + const avatarPackUuids = (await prisma.avatarPack.findMany({ where: { tenantId }, select: { uuid: true } })).map( + (p) => p.uuid, + ); + const customAvatarUuids = (await prisma.customAvatar.findMany({ where: { tenantId }, select: { uuid: true } })).map( + (c) => c.uuid, + ); + const avatarUuids = new Map(); + for (const userId of memberIds) avatarUuids.set(userId, await readCustomAvatarUuid(prisma, userId)); + + const deletedUserIds = await prisma.$transaction( + async (tx) => { + // Same row lock as removeMemberFromTenant (S1-R7), in id order so that + // two deletions cannot deadlock each other. + if (memberIds.length > 0) { + await tx.$queryRaw`SELECT id FROM "User" WHERE id IN (${Prisma.join(memberIds)}) ORDER BY id FOR UPDATE`; + } + if (options.cleanupInTx) await options.cleanupInTx(tx); + await tx.presence.deleteMany({ where: { OR: [{ tenantId }, { roomId: { in: roomIds } }] } }); + await tx.zone.deleteMany({ + where: { OR: [{ tenantId }, { mapId: { in: mapIds } }, { roomId: { in: roomIds } }] }, + }); + await tx.room.deleteMany({ where: { OR: [{ tenantId }, { mapId: { in: mapIds } }] } }); + if (layerIds.length > 0) await tx.mapChunk.deleteMany({ where: { layerId: { in: layerIds } } }); + if (mapIds.length > 0) { + await tx.mapLayer.deleteMany({ where: { mapId: { in: mapIds } } }); + await tx.mapTileset.deleteMany({ where: { mapId: { in: mapIds } } }); + await tx.mapAutotile.deleteMany({ where: { mapId: { in: mapIds } } }); + await tx.mapObject.deleteMany({ where: { mapId: { in: mapIds } } }); + } + await tx.map.deleteMany({ where: { tenantId } }); + if (npcIds.length > 0) await tx.npcMediaFile.deleteMany({ where: { npcId: { in: npcIds } } }); + await tx.npc.deleteMany({ where: { tenantId } }); + await tx.assetPack.deleteMany({ where: { tenantId } }); + await tx.avatarPack.deleteMany({ where: { tenantId } }); + await tx.customAvatar.deleteMany({ where: { tenantId } }); + await tx.invite.deleteMany({ where: { tenantId } }); + await tx.membership.deleteMany({ where: { tenantId } }); + const deleted: string[] = []; + for (const userId of memberIds) { + await revokeSessionsForUserInTx(tx, userId); + if ((await tx.membership.count({ where: { userId } })) === 0) { + await purgeAccountRows(tx, userId); + deleted.push(userId); + } + } + await tx.tenant.delete({ where: { id: tenantId } }); + return deleted; + }, + { timeout: TENANT_DELETION_TIMEOUT_MS, maxWait: 10_000 }, + ); + + for (const userId of memberIds) { + invalidateSessionsForUser(userId); + await revokeTenantAccess(tenant.slug, userId); + } + await removeTenantFiles({ + tenantSlug: tenant.slug, + assetPackUuids, + avatarPackUuids, + customAvatarUuids, + npcIds, + }); + for (const userId of deletedUserIds) await removeCustomAvatarFiles(userId, avatarUuids.get(userId) ?? null); + return { deletedAccounts: deletedUserIds.length }; +} diff --git a/apps/server/src/services/accountDeletion.integration.test.ts b/apps/server/src/services/accountDeletion.integration.test.ts new file mode 100644 index 00000000..a1ffdbc2 --- /dev/null +++ b/apps/server/src/services/accountDeletion.integration.test.ts @@ -0,0 +1,75 @@ +import crypto from 'crypto'; +import { afterAll, describe, expect, it } from 'vitest'; +import { createPrismaClient } from '../db.js'; +import { removeMemberFromTenant } from './accountDeletion.js'; + +/** + * S1-R7: two admins of different tenants remove the same user's last two + * memberships at the same time. Each removal has to see the other's result, + * otherwise both keep the account and it is left without any membership. + * Runs against a REAL PostgreSQL database; a deferred trigger holds each + * commit for a second, so both removals count the remaining memberships + * before either commits. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('accountDeletion.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; + +async function createTenant(): Promise { + const slug = `qacc-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function dropSlowDeleteTrigger(): Promise { + await prisma.$executeRawUnsafe('DROP TRIGGER IF EXISTS qacc_r7_slow_delete ON "Membership"'); + await prisma.$executeRawUnsafe('DROP FUNCTION IF EXISTS qacc_r7_slow_delete()'); +} + +afterAll(async () => { + await dropSlowDeleteTrigger(); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + await prisma.$disconnect(); +}); + +describe('S1-R7 parallel removal of the last memberships (real database)', () => { + it('deletes the account when two tenants remove the user at the same time', async () => { + const tenantA = await createTenant(); + const tenantB = await createTenant(); + const user = await prisma.user.create({ data: { email: `qacc-${crypto.randomUUID()}@example.test` } }); + userIds.push(user.id); + await prisma.membership.create({ data: { userId: user.id, tenantId: tenantA, role: 'member' } }); + await prisma.membership.create({ data: { userId: user.id, tenantId: tenantB, role: 'member' } }); + + await prisma.$executeRawUnsafe(` + CREATE OR REPLACE FUNCTION qacc_r7_slow_delete() RETURNS trigger AS $$ + BEGIN + IF OLD."userId" = '${user.id}' THEN PERFORM pg_sleep(1); END IF; + RETURN OLD; + END $$ LANGUAGE plpgsql`); + await prisma.$executeRawUnsafe( + 'CREATE CONSTRAINT TRIGGER qacc_r7_slow_delete AFTER DELETE ON "Membership" DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION qacc_r7_slow_delete()', + ); + + try { + const results = await Promise.all([ + removeMemberFromTenant(prisma, { userId: user.id, tenantId: tenantA }), + removeMemberFromTenant(prisma, { userId: user.id, tenantId: tenantB }), + ]); + + expect(await prisma.membership.count({ where: { userId: user.id } })).toBe(0); + expect(await prisma.user.count({ where: { id: user.id } })).toBe(0); + expect(results.filter((result) => result.accountDeleted)).toHaveLength(1); + } finally { + await dropSlowDeleteTrigger(); + } + }); +}); diff --git a/apps/server/src/services/accountDeletion.ts b/apps/server/src/services/accountDeletion.ts index e950dbcf..808620d3 100644 --- a/apps/server/src/services/accountDeletion.ts +++ b/apps/server/src/services/accountDeletion.ts @@ -1,9 +1,29 @@ -import type { PrismaClient, Prisma } from '../generated/prisma/index.js'; +import type { PrismaClient } from '../generated/prisma/index.js'; +import { Prisma } from '../generated/prisma/index.js'; +import type { TenantDeletionOptions } from './tenantDeletionContract.js'; +import { + TENANT_DELETION_TX_MAX_WAIT_MS, + TENANT_DELETION_TX_TIMEOUT_MS, + completeTenantDeletionInTx, + prepareTenantDeletionInTx, + resolveTenantDeletionOptions, +} from './tenantDeletionPlanning.js'; import { logger } from '../logger.js'; import { revokeSessionsForUserInTx } from '../api/utils/sessionAuth.js'; import { invalidateSessionsForUser } from '../api/utils/sessionCache.js'; import { customAvatarPacksDir, deleteCustomAvatarFiles } from './avatarComposer.js'; import { revokeAccountAccess, revokeTenantAccess } from './tenantAccessRevocation.js'; +import { removeTenantFiles } from './tenantFiles.js'; +import { recordDeletionFailure, recordDeletionOutcome } from './tenantDeletionJournal.js'; +import type { AccountJournalPlan } from './accountDeletionJournal.js'; +import { + completeAccountJournalInTx, + getAccountDeletionJournal, + recordAccountDeletionCommitted, + recordAccountDeletionFailed, + resolveAccountJournalOrThrow, + writeAccountJournalInTx, +} from './accountDeletionJournal.js'; /** * Account deletion and member removal. @@ -36,7 +56,16 @@ export class MembershipNotFoundError extends Error { } } -async function purgeAccountRows(tx: Prisma.TransactionClient, userId: string): Promise { +/** + * Deletes the rows of one account. With `journal`, the account journal row is written before the + * deletions and completed once the user row is gone, inside the same transaction. + */ +async function purgeAccountRows( + tx: Prisma.TransactionClient, + userId: string, + journal?: { plan: AccountJournalPlan; avatarUuid: string | null }, +): Promise { + const journalId = journal ? await writeAccountJournalInTx(tx, journal.plan, userId, journal.avatarUuid) : undefined; await revokeSessionsForUserInTx(tx, userId); await tx.emailVerification.deleteMany({ where: { userId } }); await tx.passwordReset.deleteMany({ where: { userId } }); @@ -47,6 +76,7 @@ async function purgeAccountRows(tx: Prisma.TransactionClient, userId: string): P await tx.membership.deleteMany({ where: { userId } }); // CustomAvatar and the enterprise transcription tables cascade from User. await tx.user.delete({ where: { id: userId } }); + if (journalId !== undefined) await completeAccountJournalInTx(tx, journalId); } async function readCustomAvatarUuid(prisma: PrismaClient, userId: string): Promise { @@ -65,16 +95,42 @@ async function removeCustomAvatarFiles(userId: string, uuid: string | null): Pro } } +/** + * Runs an account deletion transaction. With a registered journal it gets the tenant deletion + * limits, which keep the undecided-intent abort threshold valid; without one it runs with the + * Prisma default, as before. + */ +function runAccountTransaction( + prisma: PrismaClient, + journalActive: boolean, + work: (tx: Prisma.TransactionClient) => Promise, +): Promise { + if (!journalActive) return prisma.$transaction(work); + return prisma.$transaction(work, { + timeout: TENANT_DELETION_TX_TIMEOUT_MS, + maxWait: TENANT_DELETION_TX_MAX_WAIT_MS, + }); +} + /** Delete the account of `userId` with everything that references it. */ export async function deleteAccount(prisma: PrismaClient, userId: string): Promise { + const journalActive = getAccountDeletionJournal() !== undefined; const avatarUuid = await readCustomAvatarUuid(prisma, userId); const memberships = await prisma.membership.findMany({ where: { userId }, select: { tenant: { select: { slug: true } } }, }); - await prisma.$transaction(async (tx) => { - await purgeAccountRows(tx, userId); - }); + let plan: AccountJournalPlan | undefined; + try { + await runAccountTransaction(prisma, journalActive, async (tx) => { + plan = await resolveAccountJournalOrThrow(tx, userId); + await purgeAccountRows(tx, userId, plan ? { plan, avatarUuid } : undefined); + }); + } catch (error) { + if (plan) await recordAccountDeletionFailed(prisma, plan, userId); + throw error; + } + if (plan) await recordAccountDeletionCommitted(prisma, plan, userId, avatarUuid !== null); invalidateSessionsForUser(userId); await revokeAccountAccess( userId, @@ -93,22 +149,150 @@ export async function removeMemberFromTenant( params: { userId: string; tenantId: string }, ): Promise { const { userId, tenantId } = params; + const journalActive = getAccountDeletionJournal() !== undefined; const avatarUuid = await readCustomAvatarUuid(prisma, userId); const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); - const accountDeleted = await prisma.$transaction(async (tx) => { - const removed = await tx.membership.deleteMany({ where: { userId, tenantId } }); - if (removed.count === 0) throw new MembershipNotFoundError(userId, tenantId); - await tx.presence.deleteMany({ where: { userId, tenantId } }); - // Sign the user out everywhere: sessions are not bound to a tenant, and a - // removed member must not keep a live session in the tenant it left. - await revokeSessionsForUserInTx(tx, userId); - const remaining = await tx.membership.count({ where: { userId } }); - if (remaining > 0) return false; - await purgeAccountRows(tx, userId); - return true; - }); + let plan: AccountJournalPlan | undefined; + let accountDeleted: boolean; + try { + accountDeleted = await runAccountTransaction(prisma, journalActive, async (tx) => { + // Serialize concurrent removals of the same user (S1-R7): without the row + // lock, two removals of the last two memberships each still see the + // other's membership, and both keep an account that ends up memberless. + await tx.$queryRaw`SELECT id FROM "User" WHERE id = ${userId} FOR UPDATE`; + const removed = await tx.membership.deleteMany({ where: { userId, tenantId } }); + if (removed.count === 0) throw new MembershipNotFoundError(userId, tenantId); + await tx.presence.deleteMany({ where: { userId, tenantId } }); + // Sign the user out everywhere: sessions are not bound to a tenant, and a + // removed member must not keep a live session in the tenant it left. + await revokeSessionsForUserInTx(tx, userId); + const remaining = await tx.membership.count({ where: { userId } }); + if (remaining > 0) return false; + plan = await resolveAccountJournalOrThrow(tx, userId); + await purgeAccountRows(tx, userId, plan ? { plan, avatarUuid } : undefined); + return true; + }); + } catch (error) { + if (plan) await recordAccountDeletionFailed(prisma, plan, userId); + throw error; + } + if (plan) await recordAccountDeletionCommitted(prisma, plan, userId, avatarUuid !== null); invalidateSessionsForUser(userId); if (tenant) await revokeTenantAccess(tenant.slug, userId); if (accountDeleted) await removeCustomAvatarFiles(userId, avatarUuid); return { accountDeleted }; } + +/** + * Delete a tenant together with its memberships in ONE transaction. Members + * lose all their sessions (sessions are not tenant-bound); a member whose last + * membership this was loses the account. Rows that carry the tenant id without + * a foreign key go in the same transaction: CustomAvatar here, enterprise rows + * via `cleanupInTx`. Tenant content (maps, rooms, zones, NPCs) is not deleted: + * while it exists, the final tenant delete fails on its foreign keys and the + * whole transaction rolls back. World and AV access end after the commit. + */ +export async function deleteTenantWithMembers( + prisma: PrismaClient, + tenantId: string, + options: TenantDeletionOptions = {}, +): Promise<{ deletedAccounts: number }> { + // Vertragliche Prüfung vor allen DB-Lesevorgängen; bare Aufrufe liefern undefined. + const managed = resolveTenantDeletionOptions(options); + const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { slug: true } }); + if (!tenant) throw new Error('tenant not found'); + const memberIds = ( + await prisma.membership.findMany({ where: { tenantId }, select: { userId: true }, orderBy: { userId: 'asc' } }) + ).map((m) => m.userId); + const mapIds = (await prisma.map.findMany({ where: { tenantId }, select: { id: true } })).map((m) => m.id); + const layerIds = (await prisma.mapLayer.findMany({ where: { mapId: { in: mapIds } }, select: { id: true } })).map( + (l) => l.id, + ); + const roomIds = (await prisma.room.findMany({ where: { tenantId }, select: { id: true } })).map((r) => r.id); + const npcIds = (await prisma.npc.findMany({ where: { tenantId }, select: { id: true } })).map((n) => n.id); + const assetPackUuids = (await prisma.assetPack.findMany({ where: { tenantId }, select: { uuid: true } })).map( + (p) => p.uuid, + ); + const avatarPackUuids = (await prisma.avatarPack.findMany({ where: { tenantId }, select: { uuid: true } })).map( + (p) => p.uuid, + ); + const customAvatarUuids = (await prisma.customAvatar.findMany({ where: { tenantId }, select: { uuid: true } })).map( + (c) => c.uuid, + ); + const avatarUuids = new Map(); + for (const userId of memberIds) avatarUuids.set(userId, await readCustomAvatarUuid(prisma, userId)); + + const deletedUserIds = await prisma + .$transaction( + async (tx) => { + // Same row lock as removeMemberFromTenant (S1-R7), in id order so that + // two deletions cannot deadlock each other. + if (memberIds.length > 0) { + await tx.$queryRaw`SELECT id FROM "User" WHERE id IN (${Prisma.join(memberIds)}) ORDER BY id FOR UPDATE`; + } + // Journal/Tasks stehen vor dem ersten operativen DELETE; danach läuft das EE-Cleanup. + const prepared = await prepareTenantDeletionInTx(tx, tenantId, memberIds, managed); + await tx.presence.deleteMany({ where: { OR: [{ tenantId }, { roomId: { in: roomIds } }] } }); + await tx.zone.deleteMany({ + where: { OR: [{ tenantId }, { mapId: { in: mapIds } }, { roomId: { in: roomIds } }] }, + }); + await tx.room.deleteMany({ where: { OR: [{ tenantId }, { mapId: { in: mapIds } }] } }); + if (layerIds.length > 0) await tx.mapChunk.deleteMany({ where: { layerId: { in: layerIds } } }); + if (mapIds.length > 0) { + await tx.mapLayer.deleteMany({ where: { mapId: { in: mapIds } } }); + await tx.mapTileset.deleteMany({ where: { mapId: { in: mapIds } } }); + await tx.mapAutotile.deleteMany({ where: { mapId: { in: mapIds } } }); + await tx.mapObject.deleteMany({ where: { mapId: { in: mapIds } } }); + } + await tx.map.deleteMany({ where: { tenantId } }); + if (npcIds.length > 0) await tx.npcMediaFile.deleteMany({ where: { npcId: { in: npcIds } } }); + await tx.npc.deleteMany({ where: { tenantId } }); + await tx.assetPack.deleteMany({ where: { tenantId } }); + await tx.avatarPack.deleteMany({ where: { tenantId } }); + await tx.customAvatar.deleteMany({ where: { tenantId } }); + await tx.invite.deleteMany({ where: { tenantId } }); + await tx.membership.deleteMany({ where: { tenantId } }); + const deleted: string[] = []; + for (const userId of memberIds) { + await revokeSessionsForUserInTx(tx, userId); + if ((await tx.membership.count({ where: { userId } })) === 0) { + await purgeAccountRows(tx, userId); + deleted.push(userId); + } + } + await tx.tenant.delete({ where: { id: tenantId } }); + await completeTenantDeletionInTx(tx, prepared); + return deleted; + }, + // A tenant with large maps deletes tens of thousands of map chunks in this + // transaction; the Prisma default of 5 s is not enough (Q-ACC-19c large-map + // test). + { timeout: TENANT_DELETION_TX_TIMEOUT_MS, maxWait: TENANT_DELETION_TX_MAX_WAIT_MS }, + ) + .then( + // The file journal records the outcome after the transaction settles. + // Without a remembered intent (bare OSS deletion) both are no-ops. + async (deleted) => { + await recordDeletionOutcome(tenantId, 'commit'); + return deleted; + }, + async (error: unknown) => { + await recordDeletionFailure(prisma, tenantId); + throw error; + }, + ); + + for (const userId of memberIds) { + invalidateSessionsForUser(userId); + await revokeTenantAccess(tenant.slug, userId); + } + await removeTenantFiles({ + tenantSlug: tenant.slug, + assetPackUuids, + avatarPackUuids, + customAvatarUuids, + npcIds, + }); + for (const userId of deletedUserIds) await removeCustomAvatarFiles(userId, avatarUuids.get(userId) ?? null); + return { deletedAccounts: deletedUserIds.length }; +} diff --git a/apps/server/src/services/accountDeletionJournal.integration.test.ts b/apps/server/src/services/accountDeletionJournal.integration.test.ts new file mode 100644 index 00000000..94d44466 --- /dev/null +++ b/apps/server/src/services/accountDeletionJournal.integration.test.ts @@ -0,0 +1,510 @@ +import crypto from 'crypto'; +import { mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises'; +import os from 'os'; +import path from 'path'; +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createPrismaClient } from '../db.js'; +import type { Role } from '../generated/prisma/index.js'; +import { deleteAccount, removeMemberFromTenant } from './accountDeletion.js'; +import { + AccountDeletionJournalUnavailableError, + completeAccountJournalInTx, + createAccountJournalPlanResolver, + registerAccountDeletionJournal, + writeAccountJournalInTx, +} from './accountDeletionJournal.js'; +import { runDeletionTasksOnce, undecidedIntentAbortAfterMs } from './tenantDeletionPlanning.js'; +import type { RestorePendingMarker } from './tenantDeletionRestoreMarker.js'; +import { RESTORE_PENDING_FILE, clearRestorePending } from './tenantDeletionRestoreMarker.js'; +import type { JournalEntry } from './tenantDeletionJournal.js'; +import { JOURNAL_FILE, decideJournalIntents, loadJournal } from './tenantDeletionJournal.js'; + +/** + * Account journal of deleteAccount and removeMemberFromTenant against a REAL PostgreSQL + * database. Each test writes its journal into a fresh temporary directory; the database + * side is read from the DeletionJournal and DeletionTask rows that reference the account. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('accountDeletionJournal.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +const journalKeys: string[] = []; +let journalDir = ''; + +/** Registers the account resolver for the test journal directory. */ +function registerTestJournal(): void { + registerAccountDeletionJournal(createAccountJournalPlanResolver({ prisma, journalDir, retentionDays: '7' })); +} + +async function createTenant(): Promise { + const slug = `account-journal-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser(): Promise { + const email = `account-journal-${crypto.randomUUID()}@example.test`; + const user = await prisma.user.create({ data: { email } }); + userIds.push(user.id); + return user.id; +} + +/** Custom avatar row without a sprite file: the journal and its file task need only the uuid. */ +async function createCustomAvatar(userId: string): Promise { + const uuid = crypto.randomUUID(); + const spriteUrl = `/packs/avatars/custom/${uuid}.png`; + await prisma.customAvatar.create({ + data: { uuid, userId, config: {}, spriteUrl, configHash: 'account-journal-test' }, + }); + return uuid; +} + +async function createMembership(userId: string, tenantId: string, role: Role): Promise { + await prisma.membership.create({ data: { userId, tenantId, role } }); +} + +/** Entries of the test journal from the public loader, which also verifies the hash chain. */ +async function readJournalEntries(): Promise { + const journal = await loadJournal(journalDir); + expect(journal).not.toBeNull(); + return journal?.entries ?? []; +} + +/** Raw journal file content; empty when no entry was written. */ +async function readJournalText(): Promise { + try { + return await readFile(path.join(journalDir, JOURNAL_FILE), 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return ''; + throw error; + } +} + +/** DeletionJournal rows whose account references contain the user. */ +async function findAccountJournalRows(userId: string) { + return prisma.deletionJournal.findMany({ where: { accountRefs: { has: userId } } }); +} + +/** DeletionTask rows of the account journals that contain the user. */ +async function findAccountTaskRows(userId: string) { + return prisma.deletionTask.findMany({ where: { journal: { accountRefs: { has: userId } } } }); +} + +/** Every entry of an account deletion names the account and no tenant; all entries share one key. */ +function expectAccountEntries(entries: JournalEntry[], userId: string): void { + for (const entry of entries) { + expect(entry.tenantRef).toBe(''); + expect(entry.accountRef).toBe(userId); + } + expect(new Set(entries.map((entry) => entry.key)).size).toBe(1); +} + +/** The single account row of a user with the given journal key and status. */ +async function expectAccountRow(userId: string, key: string | undefined, status: string): Promise { + const rows = await findAccountJournalRows(userId); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + scope: 'account', + tenantRef: null, + accountRefs: [userId], + idempotencyKey: key, + status, + }); + expect(rows[0]?.dbDeletedAt).toBeInstanceOf(Date); +} + +async function expectUserGone(userId: string): Promise { + expect(await prisma.user.count({ where: { id: userId } })).toBe(0); +} + +/** Deletion with a custom avatar: intent and commit, one pending file task, completion waits for the task. */ +async function expectAvatarDeletion(userId: string, avatarUuid: string): Promise { + const entries = await readJournalEntries(); + expect(entries.map((entry) => entry.type)).toEqual(['intent', 'commit']); + expectAccountEntries(entries, userId); + await expectAccountRow(userId, entries[0]?.key, 'cleanup_pending'); + const tasks = await findAccountTaskRows(userId); + expect(tasks).toHaveLength(1); + expect(tasks[0]).toMatchObject({ kind: 'file', targetSystem: 'custom_avatars', objectId: avatarUuid }); + await expectUserGone(userId); +} + +/** Deletion without a custom avatar: intent, commit and completed, no file task. */ +async function expectPlainDeletion(userId: string): Promise { + const entries = await readJournalEntries(); + expect(entries.map((entry) => entry.type)).toEqual(['intent', 'commit', 'completed']); + expectAccountEntries(entries, userId); + await expectAccountRow(userId, entries[0]?.key, 'completed'); + const [row] = await findAccountJournalRows(userId); + expect(row?.completedAt).toBeInstanceOf(Date); + expect(await findAccountTaskRows(userId)).toHaveLength(0); + await expectUserGone(userId); +} + +/** Filter for the journal rows this file creates: by account reference, or by the key of a blocked intent. */ +function journalOwnerFilter() { + const owners = [ + ...(userIds.length > 0 ? [{ accountRefs: { hasSome: userIds } }] : []), + ...(journalKeys.length > 0 ? [{ idempotencyKey: { in: journalKeys } }] : []), + ]; + return owners.length > 0 ? { OR: owners } : undefined; +} + +/** Makes the deletion of exactly this user fail with a database exception until the trigger is dropped. */ +async function createBlockingUserTrigger(userId: string): Promise { + await dropBlockingUserTrigger(); + await prisma.$executeRawUnsafe(` + CREATE OR REPLACE FUNCTION account_journal_test_block_user_delete() RETURNS trigger AS $$ + BEGIN + IF OLD.id = '${userId}' THEN RAISE EXCEPTION 'account journal test: user deletion blocked'; END IF; + RETURN OLD; + END $$ LANGUAGE plpgsql`); + await prisma.$executeRawUnsafe( + 'CREATE TRIGGER account_journal_test_block_user_delete BEFORE DELETE ON "User" FOR EACH ROW EXECUTE FUNCTION account_journal_test_block_user_delete()', + ); +} + +async function dropBlockingUserTrigger(): Promise { + await prisma.$executeRawUnsafe('DROP TRIGGER IF EXISTS account_journal_test_block_user_delete ON "User"'); + await prisma.$executeRawUnsafe('DROP FUNCTION IF EXISTS account_journal_test_block_user_delete()'); +} + +/** + * Plans an account deletion, removes the user and writes the rows in one transaction, without a commit + * entry: the state of a deletion whose commit was never recorded. Returns the journal key. + */ +async function openAccountIntent(userId: string, avatarUuid: string | null): Promise { + const key = await prisma.$transaction(async (tx) => { + const resolve = createAccountJournalPlanResolver({ prisma, journalDir, retentionDays: '7' }); + const plan = await resolve(tx, userId); + if (plan === undefined) throw new Error('account journal plan unavailable'); + const journalId = await writeAccountJournalInTx(tx, plan, userId, avatarUuid); + await tx.user.delete({ where: { id: userId } }); + await completeAccountJournalInTx(tx, journalId); + return plan.key; + }); + journalKeys.push(key); + return key; +} + +/** One pass of the production deletion worker over the test journal. */ +function runWorkerPass() { + return runDeletionTasksOnce({ prisma, journalDir, now: new Date() }); +} + +/** Passes per test: the worker takes at most 100 due tasks per pass, oldest first, in a shared database. */ +const WORKER_PASS_LIMIT = 20; + +/** Runs the production worker until `reached` holds, for at most WORKER_PASS_LIMIT passes. */ +async function runWorkerUntil(reached: () => Promise): Promise { + for (let pass = 0; pass < WORKER_PASS_LIMIT; pass += 1) { + if (await reached()) return; + await runWorkerPass(); + } +} + +/** True once the test journal holds an entry of the given type under the key. */ +async function journalHasEntry(key: string, type: string): Promise { + return typesOf(await readJournalEntries(), key).includes(type); +} + +/** True once the DeletionJournal row under the key has the given status. */ +async function rowHasStatus(key: string, status: string): Promise { + return (await findRowsByKey(key)).some((row) => row.status === status); +} + +/** Keys of all entries in the test journal, read without assertions so that cleanup can use them. */ +async function journalKeysOf(): Promise { + const journal = await loadJournal(journalDir); + return journal?.entries.map((entry) => entry.key) ?? []; +} + +/** deleteAccount must reject with the unavailable error of the account journal. */ +async function expectDeletionRefused(userId: string): Promise { + const failure = await deleteAccount(prisma, userId).then( + () => undefined, + (error: unknown) => error, + ); + expect(failure).toBeInstanceOf(AccountDeletionJournalUnavailableError); + expect(failure).toMatchObject({ code: 'account_deletion_journal_unavailable' }); +} + +/** The user and its membership in the tenant still exist. */ +async function expectAccountKept(userId: string, tenantId: string): Promise { + expect(await prisma.user.count({ where: { id: userId } })).toBe(1); + expect(await prisma.membership.count({ where: { userId, tenantId } })).toBe(1); +} + +/** Entry types of one key, in journal order. */ +function typesOf(entries: JournalEntry[], key: string): string[] { + return entries.filter((entry) => entry.key === key).map((entry) => entry.type); +} + +/** Key of the first journal entry, the intent of the deletion under test. */ +function keyOfFirstEntry(entries: JournalEntry[]): string { + const key = entries[0]?.key; + if (key === undefined) throw new Error('journal holds no entry'); + return key; +} + +/** DeletionJournal rows under one idempotency key. */ +async function findRowsByKey(key: string) { + return prisma.deletionJournal.findMany({ where: { idempotencyKey: key } }); +} + +/** + * Runs the work with ASSET_PACKS_DIR and NPC_MEDIA_DIR each set to a fresh directory. Both variables and + * both directories are restored afterwards, even when the work fails. + */ +async function withTemporaryFileDirs(work: () => Promise): Promise { + const packsDir = await mkdtemp(path.join(os.tmpdir(), 'account-journal-packs-')); + const npcMediaDir = await mkdtemp(path.join(os.tmpdir(), 'account-journal-npc-')); + const previousPacksDir = process.env.ASSET_PACKS_DIR; + const previousNpcMediaDir = process.env.NPC_MEDIA_DIR; + process.env.ASSET_PACKS_DIR = packsDir; + process.env.NPC_MEDIA_DIR = npcMediaDir; + try { + await work(); + } finally { + if (previousPacksDir === undefined) delete process.env.ASSET_PACKS_DIR; + else process.env.ASSET_PACKS_DIR = previousPacksDir; + if (previousNpcMediaDir === undefined) delete process.env.NPC_MEDIA_DIR; + else process.env.NPC_MEDIA_DIR = previousNpcMediaDir; + await rm(packsDir, { recursive: true, force: true }); + await rm(npcMediaDir, { recursive: true, force: true }); + } +} + +describe('account deletion journal (real database)', () => { + beforeEach(async () => { + journalDir = await mkdtemp(path.join(os.tmpdir(), 'account-journal-test-')); + }); + + afterEach(async () => { + registerAccountDeletionJournal(undefined); + await rm(journalDir, { recursive: true, force: true }); + }); + + afterAll(async () => { + try { + const journalOwners = journalOwnerFilter(); + if (journalOwners !== undefined) { + await prisma.deletionTask.deleteMany({ where: { journal: journalOwners } }); + await prisma.deletionJournal.deleteMany({ where: journalOwners }); + } + if (userIds.length > 0) { + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + } + if (tenantIds.length > 0) { + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + } + } finally { + await prisma.$disconnect(); + } + }); + + it('journals an account deletion with a custom avatar and leaves its file task pending', async () => { + registerTestJournal(); + const userId = await createUser(); + const avatarUuid = await createCustomAvatar(userId); + + await deleteAccount(prisma, userId); + + await expectAvatarDeletion(userId, avatarUuid); + }); + + it('journals an account deletion without a custom avatar and completes it at once', async () => { + registerTestJournal(); + const userId = await createUser(); + + await deleteAccount(prisma, userId); + + await expectPlainDeletion(userId); + }); + + it('writes no journal entry while the removed member keeps another membership', async () => { + registerTestJournal(); + const removedTenantId = await createTenant(); + const keptTenantId = await createTenant(); + const userId = await createUser(); + await createMembership(userId, removedTenantId, 'member'); + await createMembership(userId, keptTenantId, 'member'); + + const result = await removeMemberFromTenant(prisma, { userId, tenantId: removedTenantId }); + + expect(result).toEqual({ accountDeleted: false }); + expect(await readJournalText()).toBe(''); + expect(await findAccountJournalRows(userId)).toHaveLength(0); + const memberships = await prisma.membership.findMany({ where: { userId }, select: { tenantId: true } }); + expect(memberships).toEqual([{ tenantId: keptTenantId }]); + expect(await prisma.user.count({ where: { id: userId } })).toBe(1); + }); + + it.each<{ role: Role; withAvatar: boolean }>([ + { role: 'member', withAvatar: true }, + { role: 'guest', withAvatar: false }, + ])('removes the last membership of a $role user (avatar $withAvatar)', async ({ role, withAvatar }) => { + registerTestJournal(); + const tenantId = await createTenant(); + const userId = await createUser(); + await createMembership(userId, tenantId, role); + const avatarUuid = withAvatar ? await createCustomAvatar(userId) : null; + + const result = await removeMemberFromTenant(prisma, { userId, tenantId }); + + expect(result).toEqual({ accountDeleted: true }); + if (avatarUuid === null) { + await expectPlainDeletion(userId); + } else { + await expectAvatarDeletion(userId, avatarUuid); + } + }); + + it('deletes an account unjournaled when no journal is registered', async () => { + registerAccountDeletionJournal(undefined); + const userId = await createUser(); + const avatarUuid = await createCustomAvatar(userId); + + await deleteAccount(prisma, userId); + + expect(await readdir(journalDir)).toEqual([]); + expect(await findAccountJournalRows(userId)).toHaveLength(0); + expect(await prisma.deletionTask.count({ where: { objectId: avatarUuid } })).toBe(0); + await expectUserGone(userId); + }); + + it('blocks the intent key when the user row cannot be deleted', async () => { + registerTestJournal(); + const userId = await createUser(); + try { + await createBlockingUserTrigger(userId); + await expect(deleteAccount(prisma, userId)).rejects.toThrow('account journal test: user deletion blocked'); + } finally { + await dropBlockingUserTrigger(); + journalKeys.push(...(await journalKeysOf())); + } + + const entries = await readJournalEntries(); + expect(entries.map((entry) => entry.type)).toEqual(['intent', 'abort']); + expectAccountEntries(entries, userId); + const key = keyOfFirstEntry(entries); + const rows = await findRowsByKey(key); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ idempotencyKey: key, status: 'blocked', tenantRef: null }); + expect(await prisma.user.count({ where: { id: userId } })).toBe(1); + }); + + it('refuses the deletion and keeps a damaged journal file unchanged', async () => { + registerTestJournal(); + const tenantId = await createTenant(); + const userId = await createUser(); + await createMembership(userId, tenantId, 'member'); + const journalPath = path.join(journalDir, JOURNAL_FILE); + await writeFile(journalPath, 'damaged line without JSON\n'); + const before = await readFile(journalPath); + + await expectDeletionRefused(userId); + + expect(await readFile(journalPath)).toEqual(before); + expect(await findAccountJournalRows(userId)).toHaveLength(0); + await expectAccountKept(userId, tenantId); + }); + + it('refuses the deletion while a restore marker is present and clears it afterwards', async () => { + registerTestJournal(); + const tenantId = await createTenant(); + const userId = await createUser(); + await createMembership(userId, tenantId, 'member'); + const markerPath = path.join(journalDir, RESTORE_PENDING_FILE); + const marker: RestorePendingMarker = { + v: 1, + createdAt: '2026-11-12T00:00:00.000Z', + copyCreatedAt: null, + journalSeq: null, + }; + await writeFile(markerPath, JSON.stringify(marker)); + const before = await readFile(markerPath); + + await expectDeletionRefused(userId); + + expect(await readdir(journalDir)).toEqual([RESTORE_PENDING_FILE]); + expect(await readFile(markerPath)).toEqual(before); + await expectAccountKept(userId, tenantId); + await clearRestorePending(journalDir); + expect(await readdir(journalDir)).toEqual([]); + }); + + it('commits an open account intent whose database deletion is recorded', async () => { + const userId = await createUser(); + const key = await openAccountIntent(userId, null); + + const counts = await decideJournalIntents({ + prisma, + journalDir, + now: new Date(), + abortAfterMs: undecidedIntentAbortAfterMs(), + }); + + expect(counts).toEqual({ committed: 1, aborted: 0, open: 0 }); + const entries = await readJournalEntries(); + expect(entries.map((entry) => entry.type)).toEqual(['intent', 'commit']); + expect(entries[1]).toMatchObject({ key, tenantRef: '', accountRef: userId }); + await expectUserGone(userId); + }); + + it('completes an account journal without tasks only after its minimum age', async () => { + await withTemporaryFileDirs(async () => { + const userId = await createUser(); + const key = await openAccountIntent(userId, null); + + await runWorkerUntil(() => journalHasEntry(key, 'commit')); + expect(typesOf(await readJournalEntries(), key)).toEqual(['intent', 'commit']); + expect(await findRowsByKey(key)).toMatchObject([{ status: 'cleanup_pending' }]); + + // The age is set directly in the database; the clock is not overridden. + await prisma.deletionJournal.update({ + where: { idempotencyKey: key }, + data: { dbDeletedAt: new Date('2000-01-01T00:00:00Z') }, + }); + await runWorkerUntil(() => rowHasStatus(key, 'completed')); + + const entries = await readJournalEntries(); + expect(typesOf(entries, key)).toEqual(['intent', 'commit', 'completed']); + expect(entries.find((entry) => entry.key === key && entry.type === 'completed')).toMatchObject({ + tenantRef: '', + accountRef: userId, + }); + expect(await findRowsByKey(key)).toMatchObject([{ status: 'completed' }]); + }); + }); + + it('completes an account journal once its avatar file task is done', async () => { + await withTemporaryFileDirs(async () => { + registerTestJournal(); + const userId = await createUser(); + const avatarUuid = await createCustomAvatar(userId); + await deleteAccount(prisma, userId); + await expectAvatarDeletion(userId, avatarUuid); + const key = keyOfFirstEntry(await readJournalEntries()); + + await runWorkerUntil(() => rowHasStatus(key, 'completed')); + + const entries = await readJournalEntries(); + expect(typesOf(entries, key)).toEqual(['intent', 'commit', 'completed']); + expect(entries.find((entry) => entry.key === key && entry.type === 'completed')).toMatchObject({ + tenantRef: '', + accountRef: userId, + }); + expect(await findRowsByKey(key)).toMatchObject([{ status: 'completed' }]); + expect(await findAccountTaskRows(userId)).toMatchObject([ + { targetSystem: 'custom_avatars', objectId: avatarUuid, status: 'done' }, + ]); + }); + }); +}); diff --git a/apps/server/src/services/accountDeletionJournal.ts b/apps/server/src/services/accountDeletionJournal.ts new file mode 100644 index 00000000..1523d37b --- /dev/null +++ b/apps/server/src/services/accountDeletionJournal.ts @@ -0,0 +1,228 @@ +import type { Prisma, PrismaClient } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; +import type { PendingDeletionOutcome } from './tenantDeletionJournal.js'; +import { + JournalUnavailableError, + appendJournalEntry, + createIdempotencyKey, + parseRetentionDays, + prepareJournalForWrite, + recordPendingFailure, +} from './tenantDeletionJournal.js'; +import type { JournalPlanResolverOptions } from './tenantDeletionPlanning.js'; +import { + FILE_TASK_GENERATION, + TENANT_DELETION_JOURNAL_MAX_COPY_LIFETIME_MS, + dedupeKeyFor, + readTransactionTimeMs, +} from './tenantDeletionPlanning.js'; +import { isRestorePending } from './tenantDeletionRestoreMarker.js'; + +/** + * Journal entries for account deletions, that is deletions that are not tenant + * deletions. Such rows carry the account reference only; the tenant reference + * stays empty. The resolver runs inside the deletion transaction, the other + * functions write before and after it. + */ + +/** Journal state of one account deletion, planned inside its transaction. */ +export type AccountJournalPlan = { journalDir: string; key: string; journalUntil: string; at: string }; + +/** Plans one account deletion; undefined means the journal cannot record it. */ +export type AccountJournalResolver = ( + tx: Prisma.TransactionClient, + userId: string, +) => Promise; + +/** Policy marker stored on every account journal row. */ +const ACCOUNT_JOURNAL_POLICY_VERSION = 'account-deletion-journal-v1'; + +let accountJournalResolver: AccountJournalResolver | undefined; + +/** Thrown when a registered journal cannot record an account deletion. */ +export class AccountDeletionJournalUnavailableError extends Error { + readonly code = 'account_deletion_journal_unavailable' as const; + + constructor() { + super('account deletion blocked: no valid retention plan available'); + this.name = 'AccountDeletionJournalUnavailableError'; + } +} + +/** + * Builds the resolver for account deletions. Nothing is read or called here. Each call + * checks the restore marker, the retention setting and the journal state, then appends + * the intent, mirroring the tenant resolver. + */ +export function createAccountJournalPlanResolver(options: JournalPlanResolverOptions): AccountJournalResolver { + const { journalDir, allowDuringRestoreReplay } = options; + return async (tx, userId) => { + if (allowDuringRestoreReplay !== true && (await isRestorePending(journalDir))) return undefined; + if (parseRetentionDays(options.retentionDays) === undefined) return undefined; + try { + const transactionMs = await readTransactionTimeMs(tx, undefined); + if (!(await prepareJournalForWrite(journalDir))) return undefined; + const at = new Date(transactionMs).toISOString(); + const journalUntil = new Date(transactionMs + TENANT_DELETION_JOURNAL_MAX_COPY_LIFETIME_MS).toISOString(); + const key = createIdempotencyKey(); + await appendJournalEntry(journalDir, { + type: 'intent', + key, + tenantRef: '', + accountRef: userId, + at, + journalUntil, + }); + return { journalDir, key, journalUntil, at }; + } catch (error) { + if (error instanceof JournalUnavailableError) return undefined; + throw error; + } + }; +} + +/** Registers the account resolver; undefined clears it, which leaves account deletions unjournaled. */ +export function registerAccountDeletionJournal(resolver: AccountJournalResolver | undefined): void { + accountJournalResolver = resolver; +} + +/** The registered account resolver, if any. */ +export function getAccountDeletionJournal(): AccountJournalResolver | undefined { + return accountJournalResolver; +} + +/** + * Plans the journal entry of an account deletion inside its transaction. Without a + * registered resolver the deletion runs unjournaled; with one, a resolver that cannot + * plan blocks the deletion. The log line carries no user reference. + */ +export async function resolveAccountJournalOrThrow( + tx: Prisma.TransactionClient, + userId: string, +): Promise { + const resolver = getAccountDeletionJournal(); + if (resolver === undefined) return undefined; + const plan = await resolver(tx, userId); + if (plan === undefined) { + logger.warn({ event: 'account_delete.journal_unavailable' }); + throw new AccountDeletionJournalUnavailableError(); + } + return plan; +} + +/** + * Writes the account journal row and, for a custom avatar, its file task. Runs inside the + * deletion transaction. Returns the journal id. + */ +export async function writeAccountJournalInTx( + tx: Prisma.TransactionClient, + plan: AccountJournalPlan, + userId: string, + avatarUuid: string | null, +): Promise { + const journal = await tx.deletionJournal.create({ + data: { + idempotencyKey: plan.key, + scope: 'account', + tenantRef: null, + accountRefs: [userId], + objectRefs: avatarUuid === null ? [] : [avatarUuid], + policyVersion: ACCOUNT_JOURNAL_POLICY_VERSION, + requestedAt: new Date(plan.at), + journalUntil: new Date(plan.journalUntil), + }, + }); + if (avatarUuid !== null) { + const task = { + kind: 'file', + targetSystem: 'custom_avatars', + objectId: avatarUuid, + objectGeneration: FILE_TASK_GENERATION, + }; + await tx.deletionTask.create({ + data: { + ...task, + journalId: journal.id, + dedupeKey: dedupeKeyFor(journal.id, task), + status: 'pending', + attempts: 0, + nextAttemptAt: new Date(plan.at), + }, + }); + } + return journal.id; +} + +/** + * Records the database deletion time on the account row and sets it to cleanup_pending. + * transaction_timestamp() is fixed for the whole transaction, so the time equals the intent time. + */ +export async function completeAccountJournalInTx(tx: Prisma.TransactionClient, journalId: string): Promise { + const transactionMs = await readTransactionTimeMs(tx, undefined); + await tx.deletionJournal.update({ + where: { id: journalId }, + data: { dbDeletedAt: new Date(transactionMs), status: 'cleanup_pending' }, + }); +} + +/** Journal reference of one account intent; the tenant reference stays empty. */ +function pendingOf(plan: AccountJournalPlan, userId: string): PendingDeletionOutcome { + return { + journalDir: plan.journalDir, + key: plan.key, + tenantRef: '', + accountRef: userId, + journalUntil: plan.journalUntil, + }; +} + +/** + * Records the committed account deletion as a commit entry. If the commit cannot be written, + * nothing else is recorded. Otherwise, without file tasks, the row is completed right away; + * with file tasks, completion waits for the tasks. Never throws: the deletion is committed, + * and a missing record is healed by the next reconciliation. + */ +export async function recordAccountDeletionCommitted( + prisma: PrismaClient, + plan: AccountJournalPlan, + userId: string, + hasTasks: boolean, +): Promise { + try { + await appendJournalEntry(plan.journalDir, { + type: 'commit', + key: plan.key, + tenantRef: '', + accountRef: userId, + at: new Date().toISOString(), + }); + } catch { + // The open intent is decided by the next reconciliation and the worker completes the row later. + return; + } + if (hasTasks) return; + try { + await appendJournalEntry(plan.journalDir, { + type: 'completed', + key: plan.key, + tenantRef: '', + accountRef: userId, + at: new Date().toISOString(), + }); + await prisma.deletionJournal.update({ + where: { idempotencyKey: plan.key }, + data: { status: 'completed', completedAt: new Date() }, + }); + } catch { + // A missing completion is healed by the next reconciliation. + } +} + +/** Records a rolled-back account deletion. The caller rethrows the original error. */ +export async function recordAccountDeletionFailed( + prisma: PrismaClient, + plan: AccountJournalPlan, + userId: string, +): Promise { + await recordPendingFailure(prisma, pendingOf(plan, userId)); +} diff --git a/apps/server/src/services/accountDeletionReplay.integration.test.ts b/apps/server/src/services/accountDeletionReplay.integration.test.ts new file mode 100644 index 00000000..45981956 --- /dev/null +++ b/apps/server/src/services/accountDeletionReplay.integration.test.ts @@ -0,0 +1,377 @@ +import crypto from 'crypto'; +import { mkdtemp, readFile, rm } from 'fs/promises'; +import os from 'os'; +import path from 'path'; +import { afterAll, afterEach, beforeEach, expect, it } from 'vitest'; +import { createPrismaClient } from '../db.js'; +import { deleteAccount } from './accountDeletion.js'; +import type { AccountJournalResolver } from './accountDeletionJournal.js'; +import { createAccountJournalPlanResolver, registerAccountDeletionJournal } from './accountDeletionJournal.js'; +import type { JournalEntry } from './tenantDeletionJournal.js'; +import { JOURNAL_FILE, loadJournal } from './tenantDeletionJournal.js'; +import type { + ReplayCommittedDeletionsOptions, + ReplayCommittedDeletionsResult, + ReplayDecision, +} from './tenantDeletionReplay.js'; +import { replayCommittedDeletions } from './tenantDeletionReplay.js'; + +/** + * Restore replay of account deletions against a REAL PostgreSQL database. A restored copy brings an + * account back under its old id after its deletion was journaled; the replay deletes it again through + * the account deletion path. Each test journals into a fresh temporary directory. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('accountDeletionReplay.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const tenantIds: string[] = []; +const userIds: string[] = []; +let journalDir = ''; +/** Creation time of the simulated restored copy; every commit of a test happens after it. */ +let copyTakenAt = new Date(); + +interface TestUser { + id: string; + email: string; +} + +/** An account deleted through the registered journal, with the journal key of that deletion. */ +interface JournaledAccount { + user: TestUser; + key: string; +} + +/** The real account deletion, plus a record of the user ids it was called with. */ +interface CountingDeletion { + calls: string[]; + remove: (userId: string) => Promise; +} + +interface ReplayRun { + deleteAccount?: (userId: string) => Promise; + decisions?: ReadonlyMap; +} + +/** Thrown inside a transaction to leave it without a commit. */ +class AbandonedTransaction extends Error { + constructor() { + super('transaction left without commit'); + this.name = 'AbandonedTransaction'; + } +} + +/** The account resolver as the deletion tool registers it for the test journal directory. */ +function accountPlanResolver(): AccountJournalResolver { + return createAccountJournalPlanResolver({ prisma, journalDir, retentionDays: '7', allowDuringRestoreReplay: true }); +} + +/** No test in this file expects a tenant deletion, so the callback fails if one is attempted. */ +async function refuseTenantDeletion(): Promise { + throw new Error('tenant deletion is not expected in this test'); +} + +async function createTenant(): Promise { + const slug = `account-replay-${crypto.randomUUID()}`; + const tenant = await prisma.tenant.create({ data: { slug, name: slug } }); + tenantIds.push(tenant.id); + return tenant.id; +} + +async function createUser(): Promise { + const email = `account-replay-${crypto.randomUUID()}@example.test`; + const user = await prisma.user.create({ data: { email } }); + userIds.push(user.id); + return { id: user.id, email }; +} + +/** Brings the user back under the same id and email, as a restored copy does. */ +async function restoreUser(user: TestUser): Promise { + await prisma.user.create({ data: { id: user.id, email: user.email } }); +} + +async function makeOwner(userId: string, tenantId: string): Promise { + await prisma.membership.create({ data: { userId, tenantId, role: 'owner' } }); +} + +/** Custom avatar row without a sprite file; the file task needs only the uuid. */ +async function createCustomAvatar(userId: string): Promise { + const uuid = crypto.randomUUID(); + const spriteUrl = `/packs/avatars/custom/${uuid}.png`; + await prisma.customAvatar.create({ + data: { uuid, userId, config: {}, spriteUrl, configHash: 'account-replay-test' }, + }); + return uuid; +} + +/** Entries of the test journal from the public loader, which also verifies the hash chain. */ +async function readJournalEntries(): Promise { + const journal = await loadJournal(journalDir); + expect(journal).not.toBeNull(); + return journal?.entries ?? []; +} + +/** Sequence number of the last journal entry; entries written later carry a higher one. */ +async function journalSeq(): Promise { + const journal = await loadJournal(journalDir); + expect(journal).not.toBeNull(); + return journal?.checkpoint.seq ?? 0; +} + +async function readJournalText(): Promise { + return readFile(path.join(journalDir, JOURNAL_FILE), 'utf8'); +} + +/** Entry types written under one journal key, in journal order. */ +async function typesOf(key: string): Promise { + const entries = await readJournalEntries(); + return entries.filter((entry) => entry.key === key).map((entry) => entry.type); +} + +async function expectUserExists(userId: string): Promise { + expect(await prisma.user.count({ where: { id: userId } })).toBe(1); +} + +async function expectUserGone(userId: string): Promise { + expect(await prisma.user.count({ where: { id: userId } })).toBe(0); +} + +/** + * Deletes an account with a custom avatar through the registered journal. The deletion leaves an intent + * and a commit, plus a database row and a file task that wait for completion. + */ +async function deleteJournaledAccount(): Promise { + const user = await createUser(); + const avatarUuid = await createCustomAvatar(user.id); + await deleteAccount(prisma, user.id); + const entries = await readJournalEntries(); + expect(entries.map((entry) => entry.type)).toEqual(['intent', 'commit']); + const key = entries[0]?.key ?? ''; + const rows = await prisma.deletionJournal.findMany({ where: { idempotencyKey: key } }); + expect(rows).toMatchObject([{ scope: 'account', status: 'cleanup_pending' }]); + const tasks = await prisma.deletionTask.findMany({ where: { journal: { idempotencyKey: key } } }); + expect(tasks).toMatchObject([{ kind: 'file', targetSystem: 'custom_avatars', objectId: avatarUuid }]); + return { user, key }; +} + +/** + * The restored copy predates the deletion, so it has neither the database row of that deletion nor + * its file task. Both are removed for the journal key. + */ +async function dropDeletionRecord(key: string): Promise { + await prisma.deletionTask.deleteMany({ where: { journal: { idempotencyKey: key } } }); + await prisma.deletionJournal.deleteMany({ where: { idempotencyKey: key } }); +} + +function countingAccountDeletion(): CountingDeletion { + const calls: string[] = []; + return { + calls, + remove: async (userId) => { + calls.push(userId); + await deleteAccount(prisma, userId); + }, + }; +} + +/** Runs the replay after the restore; open intents up to the current journal sequence are the old timeline. */ +async function replayRestoredJournal(run: ReplayRun): Promise { + const options: ReplayCommittedDeletionsOptions = { + prisma, + journalDir, + since: copyTakenAt, + deleteTenant: refuseTenantDeletion, + restoredJournalSeq: await journalSeq(), + }; + if (run.deleteAccount !== undefined) options.deleteAccount = run.deleteAccount; + if (run.decisions !== undefined) options.decisions = run.decisions; + return replayCommittedDeletions(options); +} + +/** + * Writes an account intent through the resolver inside a database transaction that is never committed. + * The intent stays open in the journal, and the database holds no row for it. + */ +async function openIntentWithoutCommit(userId: string): Promise { + const resolver = accountPlanResolver(); + let key = ''; + try { + await prisma.$transaction(async (tx) => { + const plan = await resolver(tx, userId); + if (plan === undefined) throw new Error('account intent was not planned'); + key = plan.key; + throw new AbandonedTransaction(); + }); + } catch (error) { + if (!(error instanceof AbandonedTransaction)) throw error; + } + return key; +} + +/** Leaves an open intent of the old timeline in place and checks that it blocks the replay. */ +async function expectOpenIntentBlocks(user: TestUser, deleter: CountingDeletion): Promise { + const key = await openIntentWithoutCommit(user.id); + expect(await prisma.deletionJournal.count({ where: { accountRefs: { has: user.id } } })).toBe(0); + const before = await readJournalText(); + + const result = await replayRestoredJournal({ deleteAccount: deleter.remove }); + + expect(result.blocked).toBe('undecided_intent'); + expect(result.undecided).toEqual([ + expect.objectContaining({ key, tenantRef: '', accountRef: user.id, tenantExists: false, accountExists: true }), + ]); + expect(deleter.calls).toEqual([]); + expect(await readJournalText()).toBe(before); + await expectUserExists(user.id); + return key; +} + +beforeEach(async () => { + journalDir = await mkdtemp(path.join(os.tmpdir(), 'account-replay-test-')); + copyTakenAt = new Date(); + registerAccountDeletionJournal(accountPlanResolver()); +}); + +afterEach(async () => { + registerAccountDeletionJournal(undefined); + await rm(journalDir, { recursive: true, force: true }); +}); + +afterAll(async () => { + try { + if (userIds.length > 0) { + await prisma.deletionTask.deleteMany({ where: { journal: { accountRefs: { hasSome: userIds } } } }); + await prisma.deletionJournal.deleteMany({ where: { accountRefs: { hasSome: userIds } } }); + await prisma.membership.deleteMany({ where: { userId: { in: userIds } } }); + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + } + if (tenantIds.length > 0) { + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + } + } finally { + await prisma.$disconnect(); + } +}); + +it('replays a committed account deletion after the restore and closes its old key', async () => { + const account = await deleteJournaledAccount(); + await dropDeletionRecord(account.key); + await restoreUser(account.user); + const seqBefore = await journalSeq(); + const deleter = countingAccountDeletion(); + + const result = await replayRestoredJournal({ deleteAccount: deleter.remove }); + + expect(result).toEqual({ + blocked: null, + replayed: [], + undecided: [], + closed: [], + replayedAccounts: [account.user.id], + closedAccounts: [account.key], + ownerlessTenants: [], + }); + expect(deleter.calls).toEqual([account.user.id]); + await expectUserGone(account.user.id); + const added = (await readJournalEntries()).filter((entry) => entry.seq > seqBefore); + expect(added.map((entry) => entry.type)).toEqual(['intent', 'commit', 'completed', 'completed']); + expect(added.slice(-1)).toMatchObject([{ key: account.key, type: 'completed', accountRef: account.user.id }]); + expect(await typesOf(account.key)).toEqual(['intent', 'commit', 'completed']); +}); + +it('closes the old key of an account that no longer exists without deleting anything', async () => { + const account = await deleteJournaledAccount(); + await dropDeletionRecord(account.key); + const deleter = countingAccountDeletion(); + + const result = await replayRestoredJournal({ deleteAccount: deleter.remove }); + + expect(result).toMatchObject({ blocked: null, replayedAccounts: [], closedAccounts: [account.key] }); + expect(deleter.calls).toEqual([]); + expect(await typesOf(account.key)).toEqual(['intent', 'commit', 'completed']); + await expectUserGone(account.user.id); +}); + +it('deletes the account of an open intent once the operator decides to delete it', async () => { + const user = await createUser(); + const deleter = countingAccountDeletion(); + const key = await expectOpenIntentBlocks(user, deleter); + + const result = await replayRestoredJournal({ + deleteAccount: deleter.remove, + decisions: new Map([[key, 'delete']]), + }); + + expect(result).toMatchObject({ blocked: null, replayedAccounts: [user.id], closedAccounts: [key] }); + expect(deleter.calls).toEqual([user.id]); + expect(await typesOf(key)).toEqual(['intent', 'commit', 'completed']); + await expectUserGone(user.id); +}); + +it('keeps the account of an open intent once the operator decides to keep it', async () => { + const user = await createUser(); + const deleter = countingAccountDeletion(); + const key = await expectOpenIntentBlocks(user, deleter); + + const result = await replayRestoredJournal({ + deleteAccount: deleter.remove, + decisions: new Map([[key, 'keep']]), + }); + + expect(result).toMatchObject({ blocked: null, replayedAccounts: [], closedAccounts: [] }); + expect(deleter.calls).toEqual([]); + expect(await typesOf(key)).toEqual(['intent', 'abort']); + await expectUserExists(user.id); +}); + +it('reports the tenants that lost their only owner through a replayed account deletion', async () => { + const soleOwnerTenant = await createTenant(); + const sharedTenant = await createTenant(); + const coOwner = await createUser(); + const account = await deleteJournaledAccount(); + await dropDeletionRecord(account.key); + await restoreUser(account.user); + await makeOwner(account.user.id, soleOwnerTenant); + await makeOwner(account.user.id, sharedTenant); + await makeOwner(coOwner.id, sharedTenant); + const deleter = countingAccountDeletion(); + + const result = await replayRestoredJournal({ deleteAccount: deleter.remove }); + + expect(result).toMatchObject({ + blocked: null, + replayedAccounts: [account.user.id], + closedAccounts: [account.key], + ownerlessTenants: [soleOwnerTenant], + }); + await expectUserGone(account.user.id); + expect(await prisma.membership.count({ where: { tenantId: sharedTenant, role: 'owner' } })).toBe(1); + expect(await prisma.tenant.count({ where: { id: { in: [soleOwnerTenant, sharedTenant] } } })).toBe(2); +}); + +it('ignores committed account deletions when the replay has no deletion callback', async () => { + const tenantId = await createTenant(); + const account = await deleteJournaledAccount(); + await dropDeletionRecord(account.key); + await restoreUser(account.user); + await makeOwner(account.user.id, tenantId); + const before = await readJournalText(); + + const result = await replayRestoredJournal({}); + + expect(result).toEqual({ + blocked: null, + replayed: [], + undecided: [], + closed: [], + replayedAccounts: [], + closedAccounts: [], + ownerlessTenants: [], + }); + expect(await readJournalText()).toBe(before); + await expectUserExists(account.user.id); + expect(await prisma.membership.count({ where: { userId: account.user.id, tenantId, role: 'owner' } })).toBe(1); + expect(await prisma.tenant.count({ where: { id: tenantId } })).toBe(1); +}); diff --git a/apps/server/src/services/accountDeletionReplay.ts b/apps/server/src/services/accountDeletionReplay.ts new file mode 100644 index 00000000..94313efd --- /dev/null +++ b/apps/server/src/services/accountDeletionReplay.ts @@ -0,0 +1,130 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; +import { JournalUnavailableError } from './tenantDeletionJournal.js'; +import { + append, + coveredByLaterDeletion, + hasDatabaseRow, + isAccountEntry, + loadKeys, + type AccountJournalEntry, + type JournalKeys, +} from './tenantDeletionReplay.js'; + +/** + * Account part of the restore replay, run after the tenant part. + * + * An account key that was committed or completed, whose user still exists in the restored database + * is deleted again through the given callback, by user id only. The tenants the + * user owns are read before each deletion and reported at the end when no owner + * is left. Old account keys are closed once the account is gone, no database row + * exists for the key and a later deletion covers it. Logs never carry user ids. + */ + +export interface AccountReplayOptions { + prisma: PrismaClient; + journalDir: string; + /** Creation time of the restored copy; commits at or after it are replayed. */ + since: Date; + /** Deletes one account by user id through the managed account deletion path. */ + deleteAccount: (userId: string) => Promise; +} + +export interface AccountReplayResult { + /** User ids of accounts deleted by this run. */ + replayedAccounts: string[]; + /** Journal keys of accounts closed with a completed entry by this run. */ + closedAccounts: string[]; + /** Tenants that had a deleted account as owner and have no owner left. */ + ownerlessTenants: string[]; +} + +/** Whether a user with this id exists in the database. */ +export async function accountExists(prisma: PrismaClient, userId: string): Promise { + const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true } }); + return user !== null; +} + +/** Tenants in which the user is an owner; read before the account is deleted. */ +async function ownedTenantIds(prisma: PrismaClient, userId: string): Promise { + const memberships = await prisma.membership.findMany({ + where: { userId, role: 'owner' }, + select: { tenantId: true }, + }); + return memberships.map((membership) => membership.tenantId); +} + +/** + * Account keys to replay: no abort, and a commit or, without a commit, a completed entry. The time + * boundary is the time of the commit, or of the completed entry when no commit exists. + */ +function accountCandidates(keys: JournalKeys, since: Date): AccountJournalEntry[] { + const sinceMs = since.getTime(); + const candidates: AccountJournalEntry[] = []; + for (const state of keys.values()) { + const entry = state.commit ?? state.completed; + if (!entry || state.abort || !isAccountEntry(entry)) continue; + if (Date.parse(entry.at) >= sinceMs) candidates.push(entry); + } + return candidates.sort((a, b) => a.seq - b.seq); +} + +/** Deletes each candidate account once, if it exists, and collects the tenants it owned. */ +async function deleteRestoredAccounts( + opts: AccountReplayOptions, + candidates: AccountJournalEntry[], + owned: Set, +): Promise { + const replayed: string[] = []; + const seen = new Set(); + for (const commit of candidates) { + if (seen.has(commit.accountRef)) continue; + seen.add(commit.accountRef); + if (!(await accountExists(opts.prisma, commit.accountRef))) continue; + for (const tenantId of await ownedTenantIds(opts.prisma, commit.accountRef)) owned.add(tenantId); + await opts.deleteAccount(commit.accountRef); + replayed.push(commit.accountRef); + } + return replayed; +} + +/** The given tenants that have no owner membership left. */ +async function ownerlessAmong(prisma: PrismaClient, tenantIds: Set): Promise { + const ownerless: string[] = []; + for (const tenantId of tenantIds) { + const owners = await prisma.membership.count({ where: { tenantId, role: 'owner' } }); + if (owners === 0) ownerless.push(tenantId); + } + return ownerless; +} + +/** Closes old account keys once the account is gone, no database row exists and a later deletion covers them. */ +async function closeAccountKeys(opts: AccountReplayOptions, keys: JournalKeys): Promise { + const closed: string[] = []; + for (const commit of accountCandidates(keys, opts.since)) { + if (keys.get(commit.key)?.completed) continue; + if (await accountExists(opts.prisma, commit.accountRef)) continue; + if (await hasDatabaseRow(opts.prisma, commit.key)) continue; + if (!coveredByLaterDeletion(keys, commit)) continue; + await append(opts.journalDir, 'completed', commit); + closed.push(commit.key); + } + return closed; +} + +/** + * Replays committed account deletions. `keys` is the journal state after the tenant part; the closing + * step reads the journal again, because the deletions append entries of their own. + */ +export async function replayAccountDeletions( + opts: AccountReplayOptions, + keys: JournalKeys, +): Promise { + const candidates = accountCandidates(keys, opts.since); + const owned = new Set(); + const replayedAccounts = await deleteRestoredAccounts(opts, candidates, owned); + const current = await loadKeys(opts.journalDir); + if (!current) throw new JournalUnavailableError(); + const closedAccounts = await closeAccountKeys(opts, current); + const ownerlessTenants = await ownerlessAmong(opts.prisma, owned); + return { replayedAccounts, closedAccounts, ownerlessTenants }; +} diff --git a/apps/server/src/services/deletionJournalAccountEntry.test.ts b/apps/server/src/services/deletionJournalAccountEntry.test.ts new file mode 100644 index 00000000..3a9036ca --- /dev/null +++ b/apps/server/src/services/deletionJournalAccountEntry.test.ts @@ -0,0 +1,267 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { CHECKPOINT_FILE, JOURNAL_FILE, appendJournalEntry, loadJournal } from './tenantDeletionJournal.js'; +import type { JournalAppendInput, LoadedJournal } from './tenantDeletionJournal.js'; + +// Account lines of the deletion journal: the bytes the writer produces, the +// chains the loader accepts and the line shapes it must reject. Every test +// uses a real temporary directory; there is no database, no mock and no fake clock. + +const ZERO_PREV = '0'.repeat(64); +const TENANT_REF = 'cm3t000000000000000000001'; +const ACCOUNT_REF = 'cm3a000000000000000000001'; +const TENANT_KEY = '11111111-1111-4111-8111-111111111111'; +const ACCOUNT_KEY = '22222222-2222-4222-8222-222222222222'; +const HEAD_AFTER_FIVE_LINES = '42582e89efeeaadc062f31d5d826a01df7c827d14bd411b7f654cb3ba3521812'; + +// The five lines exactly as they must appear in journal.jsonl, one JSON object per line. +const TENANT_INTENT_LINE = + '{"v":1,"seq":1,"prev":"0000000000000000000000000000000000000000000000000000000000000000","type":"intent","key":"11111111-1111-4111-8111-111111111111","tenantRef":"cm3t000000000000000000001","at":"2026-11-12T10:00:00.000Z","journalUntil":"2026-11-26T10:00:00.000Z"}'; +const TENANT_COMMIT_LINE = + '{"v":1,"seq":2,"prev":"4d68c160e10a6a9f38dc5817a2c4c5a04e245152815e66bad694cfbd496d4e07","type":"commit","key":"11111111-1111-4111-8111-111111111111","tenantRef":"cm3t000000000000000000001","at":"2026-11-12T10:00:01.000Z"}'; +const ACCOUNT_INTENT_LINE = + '{"v":1,"seq":3,"prev":"7cd78b90ddee95d7b24ded0e41d02c75d8abbacea965fedb3f480b052624533d","type":"intent","key":"22222222-2222-4222-8222-222222222222","tenantRef":"","accountRef":"cm3a000000000000000000001","at":"2026-11-12T11:00:00.000Z","journalUntil":"2026-11-26T11:00:00.000Z"}'; +const ACCOUNT_COMMIT_LINE = + '{"v":1,"seq":4,"prev":"7500a48c9d7dabd8a5039fad5824c5b404013f2c45d7a8cf7117318747b93382","type":"commit","key":"22222222-2222-4222-8222-222222222222","tenantRef":"","accountRef":"cm3a000000000000000000001","at":"2026-11-12T11:00:00.250Z"}'; +const ACCOUNT_COMPLETED_LINE = + '{"v":1,"seq":5,"prev":"fc6e318a46c0b76884a81771824c8071af1c2462dc615692c2a97de6f1b0fbdf","type":"completed","key":"22222222-2222-4222-8222-222222222222","tenantRef":"","accountRef":"cm3a000000000000000000001","at":"2026-11-12T11:01:00.000Z"}'; + +const CHAIN_LINES = [ + TENANT_INTENT_LINE, + TENANT_COMMIT_LINE, + ACCOUNT_INTENT_LINE, + ACCOUNT_COMMIT_LINE, + ACCOUNT_COMPLETED_LINE, +]; + +// Inputs that the writer turns into CHAIN_LINES, in the same order. +const CHAIN_INPUTS: JournalAppendInput[] = [ + { + type: 'intent', + key: TENANT_KEY, + tenantRef: TENANT_REF, + at: '2026-11-12T10:00:00.000Z', + journalUntil: '2026-11-26T10:00:00.000Z', + }, + { type: 'commit', key: TENANT_KEY, tenantRef: TENANT_REF, at: '2026-11-12T10:00:01.000Z' }, + { + type: 'intent', + key: ACCOUNT_KEY, + tenantRef: '', + accountRef: ACCOUNT_REF, + at: '2026-11-12T11:00:00.000Z', + journalUntil: '2026-11-26T11:00:00.000Z', + }, + { type: 'commit', key: ACCOUNT_KEY, tenantRef: '', accountRef: ACCOUNT_REF, at: '2026-11-12T11:00:00.250Z' }, + { type: 'completed', key: ACCOUNT_KEY, tenantRef: '', accountRef: ACCOUNT_REF, at: '2026-11-12T11:01:00.000Z' }, +]; + +/** SHA-256 over a journal line including its newline; the next line carries this value as prev. */ +function hashLine(line: string): string { + return createHash('sha256').update(`${line}\n`, 'utf8').digest('hex'); +} + +// Line three of a chain that follows the two tenant lines. +const PREV_OF_THIRD_LINE = hashLine(TENANT_COMMIT_LINE); + +// Each case replaces line three with one shape that the loader must reject. +const THIRD_LINE_NEGATIVES: [string, string][] = [ + [ + 'rejects an account line that carries both references', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","tenantRef":"${TENANT_REF}","accountRef":"${ACCOUNT_REF}","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects an account line with an empty accountRef', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","tenantRef":"","accountRef":"","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects a line with neither tenantRef nor accountRef', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","tenantRef":"","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects an accountRef that contains a dot', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","tenantRef":"","accountRef":"a.b","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects an accountRef written before tenantRef', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","accountRef":"${ACCOUNT_REF}","tenantRef":"","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects an account intent without journalUntil', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"intent","key":"${ACCOUNT_KEY}","tenantRef":"","accountRef":"${ACCOUNT_REF}","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects an accountRef longer than 64 characters', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","tenantRef":"","accountRef":"${'a'.repeat(65)}","at":"2026-11-12T11:00:00.250Z"}`, + ], + [ + 'rejects journalUntil on an account commit', + `{"v":1,"seq":3,"prev":"${PREV_OF_THIRD_LINE}","type":"commit","key":"${ACCOUNT_KEY}","tenantRef":"","accountRef":"${ACCOUNT_REF}","at":"2026-11-12T11:00:00.250Z","journalUntil":"2026-11-26T11:00:00.000Z"}`, + ], +]; + +// Inputs that appendJournalEntry must refuse before it touches the journal. +const REJECTED_INPUTS: [string, JournalAppendInput][] = [ + [ + 'rejects an empty tenantRef without accountRef', + { type: 'commit', key: ACCOUNT_KEY, tenantRef: '', at: '2026-11-12T11:00:00.250Z' }, + ], + [ + 'rejects a line that carries both references', + { + type: 'commit', + key: ACCOUNT_KEY, + tenantRef: TENANT_REF, + accountRef: ACCOUNT_REF, + at: '2026-11-12T11:00:00.250Z', + }, + ], + [ + 'rejects an accountRef that contains a dot', + { type: 'commit', key: ACCOUNT_KEY, tenantRef: '', accountRef: 'a.b', at: '2026-11-12T11:00:00.250Z' }, + ], +]; + +async function readText(filePath: string): Promise { + return fs.readFile(filePath, 'utf8'); +} + +/** Writes journal.jsonl with the given lines and a checkpoint that points at the last of them. */ +async function writeChainFiles(journalDir: string, lines: string[]): Promise { + const checkpoint = { + v: 1, + seq: lines.length, + head: hashLine(lines[lines.length - 1]), + baseSeq: 0, + baseHead: ZERO_PREV, + }; + await fs.writeFile(path.join(journalDir, JOURNAL_FILE), lines.map((line) => `${line}\n`).join(''), 'utf8'); + await fs.writeFile(path.join(journalDir, CHECKPOINT_FILE), JSON.stringify(checkpoint), 'utf8'); +} + +async function loadRequired(journalDir: string): Promise { + const state = await loadJournal(journalDir); + if (state === null) throw new Error('journal is not loadable'); + return state; +} + +describe('deletion journal account lines', () => { + let dir: string; + + beforeEach(async () => { + // Every test gets its own empty temporary journal directory. + dir = await fs.mkdtemp(path.join(os.tmpdir(), 'deletion-journal-account-')); + }); + + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + describe('appendJournalEntry', () => { + it('writes the five chain lines byte for byte into an empty directory', async () => { + for (const input of CHAIN_INPUTS) { + await appendJournalEntry(dir, input); + } + + expect(await readText(path.join(dir, JOURNAL_FILE))).toBe(CHAIN_LINES.map((line) => `${line}\n`).join('')); + const checkpoint: unknown = JSON.parse(await readText(path.join(dir, CHECKPOINT_FILE))); + expect(checkpoint).toStrictEqual({ v: 1, seq: 5, head: HEAD_AFTER_FIVE_LINES, baseSeq: 0, baseHead: ZERO_PREV }); + // Only the two journal files remain, so the writer lock was released. + expect((await fs.readdir(dir)).sort()).toStrictEqual(['checkpoint.json', 'journal.jsonl']); + }); + }); + + describe('appendJournalEntry with an invalid reference', () => { + beforeEach(async () => { + for (const input of CHAIN_INPUTS) { + await appendJournalEntry(dir, input); + } + }); + + it.each(REJECTED_INPUTS)('%s', async (_description, input) => { + const journalBefore = await readText(path.join(dir, JOURNAL_FILE)); + const checkpointBefore = await readText(path.join(dir, CHECKPOINT_FILE)); + + await expect(appendJournalEntry(dir, input)).rejects.toThrow('invalid journal entry'); + + expect(await readText(path.join(dir, JOURNAL_FILE))).toBe(journalBefore); + expect(await readText(path.join(dir, CHECKPOINT_FILE))).toBe(checkpointBefore); + // No lock directory or other leftover: the listing still shows the two journal files only. + expect((await fs.readdir(dir)).sort()).toStrictEqual(['checkpoint.json', 'journal.jsonl']); + }); + }); + + describe('loadJournal', () => { + it('accepts the five chain lines and keeps accountRef only on the account lines', async () => { + await writeChainFiles(dir, CHAIN_LINES); + + const state = await loadRequired(dir); + + expect(state.entries).toStrictEqual([ + { + seq: 1, + prev: ZERO_PREV, + type: 'intent', + key: TENANT_KEY, + tenantRef: TENANT_REF, + at: '2026-11-12T10:00:00.000Z', + journalUntil: '2026-11-26T10:00:00.000Z', + }, + { + seq: 2, + prev: hashLine(TENANT_INTENT_LINE), + type: 'commit', + key: TENANT_KEY, + tenantRef: TENANT_REF, + at: '2026-11-12T10:00:01.000Z', + }, + { + seq: 3, + prev: hashLine(TENANT_COMMIT_LINE), + type: 'intent', + key: ACCOUNT_KEY, + tenantRef: '', + accountRef: ACCOUNT_REF, + at: '2026-11-12T11:00:00.000Z', + journalUntil: '2026-11-26T11:00:00.000Z', + }, + { + seq: 4, + prev: hashLine(ACCOUNT_INTENT_LINE), + type: 'commit', + key: ACCOUNT_KEY, + tenantRef: '', + accountRef: ACCOUNT_REF, + at: '2026-11-12T11:00:00.250Z', + }, + { + seq: 5, + prev: hashLine(ACCOUNT_COMMIT_LINE), + type: 'completed', + key: ACCOUNT_KEY, + tenantRef: '', + accountRef: ACCOUNT_REF, + at: '2026-11-12T11:01:00.000Z', + }, + ]); + expect(state.endHead).toBe(HEAD_AFTER_FIVE_LINES); + }); + + describe('third line of a chain', () => { + it.each(THIRD_LINE_NEGATIVES)('%s', async (_description, line) => { + await writeChainFiles(dir, [TENANT_INTENT_LINE, TENANT_COMMIT_LINE, line]); + + expect(await loadJournal(dir)).toBeNull(); + }); + + it('accepts the same chain when the third line is the valid account intent', async () => { + await writeChainFiles(dir, [TENANT_INTENT_LINE, TENANT_COMMIT_LINE, ACCOUNT_INTENT_LINE]); + + expect((await loadRequired(dir)).entries).toHaveLength(3); + }); + }); + }); +}); diff --git a/apps/server/src/services/deletionJournalConfig.test.ts b/apps/server/src/services/deletionJournalConfig.test.ts new file mode 100644 index 00000000..f62f0a8e --- /dev/null +++ b/apps/server/src/services/deletionJournalConfig.test.ts @@ -0,0 +1,86 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { checkDeletionJournalConfig, type DeletionJournalConfigResult } from './deletionJournalConfig.js'; + +// Startup check of the deletion journal configuration. Every test uses a real temporary directory +// and its own env object; process.env is never changed and nothing is mocked. + +// Runs the check and asserts that the watched directory lists the same entries before and after, +// so neither a valid nor an invalid configuration creates or writes anything. +async function checkWithoutWrites(watched: string, env: NodeJS.ProcessEnv): Promise { + const before = (await fs.readdir(watched)).sort(); + const result = checkDeletionJournalConfig(env); + expect((await fs.readdir(watched)).sort()).toEqual(before); + return result; +} + +describe('checkDeletionJournalConfig', () => { + let dir: string; + + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), 'deletion-journal-config-')); + }); + + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + describe('without a journal directory', () => { + it.each<[string, NodeJS.ProcessEnv]>([ + ['unset', {}], + ['empty', { DELETION_JOURNAL_DIR: '' }], + ['only spaces', { DELETION_JOURNAL_DIR: ' ' }], + ])('is valid when DELETION_JOURNAL_DIR is %s', async (_label, env) => { + expect(await checkWithoutWrites(dir, env)).toEqual({ ok: true }); + }); + }); + + describe('with a usable journal directory', () => { + it.each(['1', '13'])('is valid with BACKUP_RETENTION_DAYS %s', async (days) => { + const env = { DELETION_JOURNAL_DIR: dir, BACKUP_RETENTION_DAYS: days }; + expect(await checkWithoutWrites(dir, env)).toEqual({ ok: true }); + }); + + it.each(['0', '14', '', 'abc'])('rejects BACKUP_RETENTION_DAYS %j', async (days) => { + const env = { DELETION_JOURNAL_DIR: dir, BACKUP_RETENTION_DAYS: days }; + expect(await checkWithoutWrites(dir, env)).toEqual({ ok: false, key: 'BACKUP_RETENTION_DAYS' }); + }); + + it('rejects a missing BACKUP_RETENTION_DAYS', async () => { + expect(await checkWithoutWrites(dir, { DELETION_JOURNAL_DIR: dir })).toEqual({ + ok: false, + key: 'BACKUP_RETENTION_DAYS', + }); + }); + }); + + describe('with an unusable journal directory', () => { + it('rejects a directory that does not exist and does not create it', async () => { + const env = { DELETION_JOURNAL_DIR: path.join(dir, 'missing'), BACKUP_RETENTION_DAYS: '1' }; + expect(await checkWithoutWrites(dir, env)).toEqual({ ok: false, key: 'DELETION_JOURNAL_DIR' }); + }); + + it('rejects a path that is a regular file', async () => { + const file = path.join(dir, 'journal-file'); + await fs.writeFile(file, 'not a directory'); + const env = { DELETION_JOURNAL_DIR: file, BACKUP_RETENTION_DAYS: '1' }; + expect(await checkWithoutWrites(dir, env)).toEqual({ ok: false, key: 'DELETION_JOURNAL_DIR' }); + }); + + // Root ignores write permission bits, so this case runs only as a regular user. + it.skipIf(process.getuid?.() === 0)('rejects a directory without owner write permission', async () => { + const journal = path.join(dir, 'journal'); + await fs.mkdir(journal); + await fs.chmod(journal, 0o500); + try { + const env = { DELETION_JOURNAL_DIR: journal, BACKUP_RETENTION_DAYS: '1' }; + expect(await checkWithoutWrites(journal, env)).toEqual({ ok: false, key: 'DELETION_JOURNAL_DIR' }); + } finally { + // Restores write access so that the afterEach cleanup can remove the directory. + await fs.chmod(journal, 0o700); + } + }); + }); +}); diff --git a/apps/server/src/services/deletionJournalConfig.ts b/apps/server/src/services/deletionJournalConfig.ts new file mode 100644 index 00000000..95daed37 --- /dev/null +++ b/apps/server/src/services/deletionJournalConfig.ts @@ -0,0 +1,25 @@ +import { accessSync, constants, statSync } from 'node:fs'; +import { parseRetentionDays } from './tenantDeletionJournal.js'; + +export type DeletionJournalConfigResult = + { ok: true } | { ok: false; key: 'BACKUP_RETENTION_DAYS' | 'DELETION_JOURNAL_DIR' }; + +// Checks the static journal configuration at startup. It only reads: nothing is +// written or created, no lock is taken and prepareJournalForWrite is not called. +export function checkDeletionJournalConfig(env: NodeJS.ProcessEnv): DeletionJournalConfigResult { + const journalDir = env.DELETION_JOURNAL_DIR?.trim(); + if (!journalDir) return { ok: true }; + if (parseRetentionDays(env.BACKUP_RETENTION_DAYS) === undefined) { + return { ok: false, key: 'BACKUP_RETENTION_DAYS' }; + } + try { + const stats = statSync(journalDir); + // Same static condition as loadJournal: without the owner write bit the journal is + // unavailable, also under root, where accessSync with W_OK alone would pass. + if (!stats.isDirectory() || (stats.mode & 0o200) === 0) return { ok: false, key: 'DELETION_JOURNAL_DIR' }; + accessSync(journalDir, constants.W_OK); + } catch { + return { ok: false, key: 'DELETION_JOURNAL_DIR' }; + } + return { ok: true }; +} diff --git a/apps/server/src/services/deletionJournalExpiry.ts b/apps/server/src/services/deletionJournalExpiry.ts new file mode 100644 index 00000000..7857cc32 --- /dev/null +++ b/apps/server/src/services/deletionJournalExpiry.ts @@ -0,0 +1,179 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; +import type { JournalEntry } from './tenantDeletionJournal.js'; +import { compactJournalPrefix, readJournalSnapshot } from './tenantDeletionJournalCompaction.js'; +import { isRestorePending } from './tenantDeletionRestoreMarker.js'; + +/* + * Removes journal keys that are past their copy lifetime, from the journal file and from the database. + * + * limit = now - maxCopyLifetimeMs. A line or row whose time equals the limit counts as expired. + * + * A key of the snapshot is removable in one of two ways: + * - completed: the database row has status `completed` and completedAt <= limit (a key without a row + * needs only the file condition), the file holds at least one `completed` line, and every + * `completed` line has at <= limit. + * - aborted: the file holds no `commit` and no `completed` line, its last line that is not `intent` + * is `abort` with at <= limit, and the database row is absent or has status `blocked`. + * Other row statuses keep the key. Keys outside the snapshot are never removed, and a key whose line + * count changed after the snapshot is kept for this pass. + * + * Order within one pass: + * 1. delete the `blocked` rows of removable aborted keys, + * 2. compact the journal prefix, which switches the journal file, + * 3. delete the tasks and then the journal rows of the removed completed keys, and of completed rows + * past the limit whose key is missing from the snapshot, in one transaction. + * Step 1 runs before the switch on purpose: if the switch fails, the abort lines remain without a row, + * and the next pass removes them. An unavailable journal file ends the pass before step 3. + */ + +/** How a key may leave the journal: its completion or its abort has passed the limit. */ +type Verdict = 'completed' | 'aborted'; + +/** Completed rows without a snapshot key that one pass removes at most. */ +const LEFTOVER_ROW_BATCH = 100; + +function findRows(prisma: PrismaClient, keys: string[]) { + return prisma.deletionJournal.findMany({ + where: { idempotencyKey: { in: keys } }, + select: { id: true, idempotencyKey: true, status: true, completedAt: true }, + }); +} + +type KeyRow = Awaited>[number]; + +/** Groups the journal lines by key, in journal order. */ +function groupByKey(entries: readonly JournalEntry[]): Map { + const groups = new Map(); + for (const entry of entries) { + const group = groups.get(entry.key) ?? []; + group.push(entry); + groups.set(entry.key, group); + } + return groups; +} + +/** True when there is at least one `completed` line and every one of them is at or before the limit. */ +function completedLinesExpired(lines: readonly JournalEntry[], limit: number): boolean { + const completed = lines.filter((entry) => entry.type === 'completed'); + return completed.length > 0 && completed.every((entry) => Date.parse(entry.at) <= limit); +} + +/** True when nothing was committed or completed and the last decision is an abort at or before the limit. */ +function abortLinesExpired(lines: readonly JournalEntry[], limit: number): boolean { + if (lines.some((entry) => entry.type === 'commit' || entry.type === 'completed')) return false; + const decisions = lines.filter((entry) => entry.type !== 'intent'); + if (decisions.length === 0) return false; + const last = decisions[decisions.length - 1]; + return last.type === 'abort' && Date.parse(last.at) <= limit; +} + +/** The verdict of one key from its lines and its database row, or null when the key stays. */ +function verdictFor(lines: readonly JournalEntry[], row: KeyRow | undefined, limit: number): Verdict | null { + if (row === undefined) { + if (completedLinesExpired(lines, limit)) return 'completed'; + return abortLinesExpired(lines, limit) ? 'aborted' : null; + } + if (row.status === 'completed') { + const rowExpired = row.completedAt !== null && row.completedAt.getTime() <= limit; + return rowExpired && completedLinesExpired(lines, limit) ? 'completed' : null; + } + if (row.status === 'blocked') return abortLinesExpired(lines, limit) ? 'aborted' : null; + return null; +} + +/** The verdicts of all snapshot keys that may leave the journal file. */ +function decideVerdicts(groups: Map, rows: KeyRow[], limit: number): Map { + const rowByKey = new Map(rows.map((row): [string, KeyRow] => [row.idempotencyKey, row])); + const verdicts = new Map(); + for (const [key, lines] of groups) { + const verdict = verdictFor(lines, rowByKey.get(key), limit); + if (verdict !== null) verdicts.set(key, verdict); + } + return verdicts; +} + +/** + * Deletes the blocked rows of removable aborted keys before the journal file changes. A crash in + * between leaves abort lines without a row, which the next pass removes. + */ +async function deleteBlockedRows(prisma: PrismaClient, verdicts: Map): Promise { + const keys = [...verdicts].filter(([, verdict]) => verdict === 'aborted').map(([key]) => key); + if (keys.length === 0) return; + await prisma.deletionJournal.deleteMany({ where: { idempotencyKey: { in: keys }, status: 'blocked' } }); +} + +/** + * Deletes the tasks before the journal rows, in one transaction. The journal delete repeats the + * status and time conditions of the verdict. + */ +function deleteJournalRows(prisma: PrismaClient, ids: string[], limit: number): Promise { + return prisma.$transaction(async (tx) => { + await tx.deletionTask.deleteMany({ where: { journalId: { in: ids } } }); + await tx.deletionJournal.deleteMany({ + where: { id: { in: ids }, status: 'completed', completedAt: { lte: new Date(limit) } }, + }); + }); +} + +/** Ends a pass that a restore interrupted before its next deletion; returns the keys counted so far. */ +function pausedForRestore(counted: number): number { + logger.warn({ event: 'tenant_deletion.compaction_paused_for_restore' }); + return counted; +} + +/** + * Compacts the journal entries that are past their copy lifetime and deletes the matching database + * rows. Returns the number of keys whose file lines or database rows were removed in this pass. + * An unavailable journal file logs `tenant_deletion.journal_unavailable` and removes nothing. + * While a restore is pending, the pass logs `tenant_deletion.compaction_paused_for_restore` and stops + * before its next deletion. The marker is checked before each deletion block; a pass stopped this way + * returns the keys removed so far. + */ +export async function compactExpiredJournals( + prisma: PrismaClient, + journalDir: string, + now: Date, + maxCopyLifetimeMs: number, +): Promise { + if (await isRestorePending(journalDir)) return pausedForRestore(0); + const limit = now.getTime() - maxCopyLifetimeMs; + const snapshot = await readJournalSnapshot(journalDir); + if (snapshot === null) { + logger.warn({ event: 'tenant_deletion.journal_unavailable', code: 'snapshot_unavailable' }); + return 0; + } + const groups = groupByKey(snapshot.entries); + const rows = await findRows(prisma, [...groups.keys()]); + const verdicts = decideVerdicts(groups, rows, limit); + if (await isRestorePending(journalDir)) return pausedForRestore(0); + await deleteBlockedRows(prisma, verdicts); + if (await isRestorePending(journalDir)) return pausedForRestore(0); + const compacted = await compactJournalPrefix( + journalDir, + (key, entries) => verdicts.has(key) && groups.get(key)?.length === entries.length, + ); + if (compacted === null) { + logger.warn({ event: 'tenant_deletion.journal_unavailable', code: 'compaction_unavailable' }); + return 0; + } + const removed = new Set(compacted.removedKeys); + const rowIds = rows + .filter((row) => row.status === 'completed' && removed.has(row.idempotencyKey)) + .map((row) => row.id); + const leftovers = await prisma.deletionJournal.findMany({ + where: { + status: 'completed', + completedAt: { lte: new Date(limit) }, + idempotencyKey: { notIn: [...groups.keys()] }, + }, + select: { id: true }, + take: LEFTOVER_ROW_BATCH, + }); + const ids = [...rowIds, ...leftovers.map((row) => row.id)]; + if (ids.length > 0) { + if (await isRestorePending(journalDir)) return pausedForRestore(compacted.removedKeys.length); + await deleteJournalRows(prisma, ids, limit); + } + return compacted.removedKeys.length + leftovers.length; +} diff --git a/apps/server/src/services/deletionTaskScheduler.ts b/apps/server/src/services/deletionTaskScheduler.ts new file mode 100644 index 00000000..f290e394 --- /dev/null +++ b/apps/server/src/services/deletionTaskScheduler.ts @@ -0,0 +1,46 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; +import { runDeletionTasksOnce } from './tenantDeletionPlanning.js'; + +const DEFAULT_INTERVAL_MS = 60_000; + +function errorName(error: unknown): string { + return error instanceof Error ? error.name : 'NonError'; +} + +/** + * Starts the periodic pass over the deletion tasks. The first pass runs at once and later passes follow + * every `intervalMs`; a tick is skipped while a pass is still running. A failed pass is logged by its + * error name only and does not end the schedule. The timer is unref'd, so it never keeps the process alive. + */ +export function startDeletionTaskWorker(options: { prisma: PrismaClient; journalDir: string; intervalMs?: number }): { + stop(): Promise; +} { + let running: Promise | undefined; + + const runPass = async (): Promise => { + try { + await runDeletionTasksOnce({ prisma: options.prisma, journalDir: options.journalDir, now: new Date() }); + } catch (error) { + logger.error({ event: 'tenant_deletion.worker_run_failed', errorName: errorName(error) }); + } + }; + + const tick = (): void => { + if (running) return; + running = runPass().finally(() => { + running = undefined; + }); + }; + + tick(); + const timer = setInterval(tick, options.intervalMs ?? DEFAULT_INTERVAL_MS); + timer.unref(); + + return { + async stop(): Promise { + clearInterval(timer); + await running; + }, + }; +} diff --git a/apps/server/src/services/deletionTaskTargets.test.ts b/apps/server/src/services/deletionTaskTargets.test.ts new file mode 100644 index 00000000..9173d29f --- /dev/null +++ b/apps/server/src/services/deletionTaskTargets.test.ts @@ -0,0 +1,222 @@ +import path from 'node:path'; +import { promises as fsp } from 'node:fs'; +import os from 'node:os'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + type DeletionTaskTargetInput, + fsErrorCode, + removeTarget, + resolveTaskTargets, + targetExists, +} from './deletionTaskTargets.js'; + +const OBJECT_ID = '3f2c1d4e-5a6b-4c7d-8e9f-0a1b2c3d4e5f'; +const OTHER_ID = '9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d'; +const PACK_SYSTEMS = ['asset_packs', 'avatar_packs', 'custom_avatars']; +const INVALID_OBJECT_IDS = ['..', 'a/b', '']; + +let root = ''; +let packs = ''; +let npcDir = ''; +let savedAssetPacksDir: string | undefined; +let savedNpcMediaDir: string | undefined; + +function restoreEnv(key: 'ASSET_PACKS_DIR' | 'NPC_MEDIA_DIR', value: string | undefined): void { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; +} + +function task(overrides: Partial = {}): DeletionTaskTargetInput { + return { kind: 'file', targetSystem: 'asset_packs', objectId: OBJECT_ID, storageKey: null, ...overrides }; +} + +async function writeFile(file: string, content: string): Promise { + await fsp.mkdir(path.dirname(file), { recursive: true }); + await fsp.writeFile(file, content); +} + +async function isPresent(file: string): Promise { + try { + await fsp.lstat(file); + return true; + } catch { + return false; + } +} + +beforeEach(async () => { + root = await fsp.mkdtemp(path.join(os.tmpdir(), 'deletion-task-targets-')); + packs = path.join(root, 'packs'); + npcDir = path.join(root, 'npc-media'); + await fsp.mkdir(packs); + savedAssetPacksDir = process.env.ASSET_PACKS_DIR; + savedNpcMediaDir = process.env.NPC_MEDIA_DIR; + process.env.ASSET_PACKS_DIR = packs; + process.env.NPC_MEDIA_DIR = npcDir; +}); + +afterEach(async () => { + restoreEnv('ASSET_PACKS_DIR', savedAssetPacksDir); + restoreEnv('NPC_MEDIA_DIR', savedNpcMediaDir); + await fsp.rm(root, { recursive: true, force: true }); +}); + +describe('resolveTaskTargets rejects tasks that do not describe one owned file', () => { + it('maps each target system to its storage root and to the owned path', () => { + const customDir = path.join(packs, 'avatars', 'custom'); + expect(resolveTaskTargets(task({ targetSystem: 'asset_packs' }))).toEqual({ + ok: true, + targets: [{ base: packs, path: path.join(packs, OBJECT_ID) }], + }); + expect(resolveTaskTargets(task({ targetSystem: 'avatar_packs' }))).toEqual({ + ok: true, + targets: [{ base: packs, path: path.join(packs, 'avatars', OBJECT_ID) }], + }); + expect(resolveTaskTargets(task({ targetSystem: 'custom_avatars' }))).toEqual({ + ok: true, + targets: [ + { base: packs, path: path.join(customDir, `${OBJECT_ID}.png`) }, + { base: packs, path: path.join(customDir, `${OBJECT_ID}_p.png`) }, + ], + }); + expect(resolveTaskTargets(task({ targetSystem: 'npc_media', storageKey: 'acme' }))).toEqual({ + ok: true, + targets: [{ base: npcDir, path: path.join(npcDir, 'acme') }], + }); + }); + + it.each(PACK_SYSTEMS.flatMap((targetSystem) => INVALID_OBJECT_IDS.map((objectId) => ({ targetSystem, objectId }))))( + 'rejects $targetSystem with object id $objectId as invalid_target', + ({ targetSystem, objectId }) => { + expect(resolveTaskTargets(task({ targetSystem, objectId }))).toEqual({ ok: false, code: 'invalid_target' }); + }, + ); + + it.each(PACK_SYSTEMS)( + 'rejects a %s task whose storage key differs from the object id as inconsistent_target', + (targetSystem) => { + expect(resolveTaskTargets(task({ targetSystem, storageKey: 'other-key' }))).toEqual({ + ok: false, + code: 'inconsistent_target', + }); + }, + ); + + it.each([null, '..', 'a/b'])('rejects an npc media task with storage key %j as invalid_target', (storageKey) => { + expect(resolveTaskTargets(task({ targetSystem: 'npc_media', storageKey }))).toEqual({ + ok: false, + code: 'invalid_target', + }); + }); + + it('rejects an unknown target system as unknown_target_system', () => { + expect(resolveTaskTargets(task({ targetSystem: 'bogus_system' }))).toEqual({ + ok: false, + code: 'unknown_target_system', + }); + }); + + it.each(['directory', ''])('rejects the task kind %j as unknown_task_kind', (kind) => { + expect(resolveTaskTargets(task({ kind }))).toEqual({ ok: false, code: 'unknown_task_kind' }); + }); +}); + +describe('removeTarget removes only owned targets and refuses symbolic links', () => { + it('removes an existing asset pack directory with its contents and keeps other packs', async () => { + await writeFile(path.join(packs, OBJECT_ID, 'nested', 'sprite.png'), 'pack'); + await writeFile(path.join(packs, OTHER_ID, 'keep.txt'), 'other'); + const outcome = await removeTarget({ base: packs, path: path.join(packs, OBJECT_ID) }); + expect(outcome).toEqual({ kind: 'removed' }); + expect(await isPresent(path.join(packs, OBJECT_ID))).toBe(false); + expect(await fsp.readFile(path.join(packs, OTHER_ID, 'keep.txt'), 'utf8')).toBe('other'); + }); + + it('removes an avatar pack directory below the avatars folder and keeps the folder', async () => { + await writeFile(path.join(packs, 'avatars', OBJECT_ID, 'sprite.png'), 'pack'); + const outcome = await removeTarget({ base: packs, path: path.join(packs, 'avatars', OBJECT_ID) }); + expect(outcome).toEqual({ kind: 'removed' }); + expect(await isPresent(path.join(packs, 'avatars', OBJECT_ID))).toBe(false); + expect(await isPresent(path.join(packs, 'avatars'))).toBe(true); + }); + + it('reports a missing target as missing', async () => { + const outcome = await removeTarget({ base: packs, path: path.join(packs, OBJECT_ID) }); + expect(outcome).toEqual({ kind: 'missing' }); + }); + + it('reports a missing avatars folder as missing rather than as a missing storage root', async () => { + const outcome = await removeTarget({ base: packs, path: path.join(packs, 'avatars', OBJECT_ID) }); + expect(outcome).toEqual({ kind: 'missing' }); + }); + + it('reports a missing storage root as target_root_missing', async () => { + const base = path.join(root, 'no-such-root'); + const outcome = await removeTarget({ base, path: path.join(base, OBJECT_ID) }); + expect(outcome).toEqual({ kind: 'error', code: 'target_root_missing' }); + }); + + it('refuses a symbolic link at the target and leaves the link and its destination untouched', async () => { + const destination = path.join(root, 'outside', OBJECT_ID); + await writeFile(path.join(destination, 'keep.txt'), 'outside'); + const link = path.join(packs, OBJECT_ID); + await fsp.symlink(destination, link); + const outcome = await removeTarget({ base: packs, path: link }); + expect(outcome).toEqual({ kind: 'refused', code: 'target_is_symlink' }); + expect((await fsp.lstat(link)).isSymbolicLink()).toBe(true); + expect(await fsp.readFile(path.join(destination, 'keep.txt'), 'utf8')).toBe('outside'); + }); + + it('refuses a target whose parent folder is a symbolic link leaving the storage root', async () => { + const outsideAvatars = path.join(root, 'outside', 'avatars'); + await writeFile(path.join(outsideAvatars, OBJECT_ID, 'keep.txt'), 'outside'); + await fsp.symlink(outsideAvatars, path.join(packs, 'avatars')); + const outcome = await removeTarget({ base: packs, path: path.join(packs, 'avatars', OBJECT_ID) }); + expect(outcome).toEqual({ kind: 'refused', code: 'target_is_symlink' }); + expect((await fsp.lstat(path.join(packs, 'avatars'))).isSymbolicLink()).toBe(true); + expect(await fsp.readFile(path.join(outsideAvatars, OBJECT_ID, 'keep.txt'), 'utf8')).toBe('outside'); + }); +}); + +describe('fsErrorCode maps file system errors to short stable codes', () => { + it('maps an errno code to a lower case fs_ code', () => { + expect(fsErrorCode(Object.assign(new Error('denied'), { code: 'EACCES' }))).toBe('fs_eacces'); + }); + + it('maps an error without a code to fs_error', () => { + expect(fsErrorCode(new Error('no code'))).toBe('fs_error'); + }); + + it.each(['eacces', 'E-ACCES'])('maps the malformed code %j to fs_error', (code) => { + expect(fsErrorCode(Object.assign(new Error('malformed'), { code }))).toBe('fs_error'); + }); + + it('shortens long codes to 64 characters', () => { + const code = fsErrorCode(Object.assign(new Error('long'), { code: `E${'A'.repeat(100)}` })); + expect(code).toHaveLength(64); + expect(code).toMatch(/^fs_e[a-z]*$/); + }); +}); + +describe('targetExists reports what sits at the target path', () => { + it('reports an existing file as present', async () => { + const file = path.join(packs, OBJECT_ID); + await writeFile(file, 'pack'); + expect(await targetExists({ base: packs, path: file })).toBe(true); + }); + + it('reports a missing path as absent', async () => { + expect(await targetExists({ base: packs, path: path.join(packs, OBJECT_ID) })).toBe(false); + }); + + it('reports a dangling symbolic link as present', async () => { + const link = path.join(packs, OBJECT_ID); + await fsp.symlink(path.join(root, 'nowhere'), link); + expect(await targetExists({ base: packs, path: link })).toBe(true); + }); + + it('counts errors other than a missing path as present', async () => { + const plain = path.join(packs, 'plain.txt'); + await writeFile(plain, 'x'); + expect(await targetExists({ base: packs, path: path.join(plain, 'child') })).toBe(true); + }); +}); diff --git a/apps/server/src/services/deletionTaskTargets.ts b/apps/server/src/services/deletionTaskTargets.ts new file mode 100644 index 00000000..99ff5bde --- /dev/null +++ b/apps/server/src/services/deletionTaskTargets.ts @@ -0,0 +1,167 @@ +import path from 'node:path'; +import { promises as fsp } from 'node:fs'; +import type { PrismaClient } from '../generated/prisma/index.js'; +import { npcMediaDir } from '../api/routes/npcMedia.js'; +import { customAvatarDir, customAvatarPacksDir } from './avatarComposer.js'; +import { resolveInside, tenantNpcMediaDir } from './tenantFiles.js'; + +/** The fields of a deletion task that decide which files it owns. */ +export interface DeletionTaskTargetInput { + kind: string; + targetSystem: string; + objectId: string; + storageKey: string | null; +} + +/** One path to remove. `base` is the storage root that must contain the parent of `path`. */ +export interface ResolvedTarget { + base: string; + path: string; +} + +export type TargetDefectCode = 'unknown_task_kind' | 'unknown_target_system' | 'invalid_target' | 'inconsistent_target'; + +export type TargetResolution = { ok: true; targets: ResolvedTarget[] } | { ok: false; code: TargetDefectCode }; + +export type RemovalOutcome = + | { kind: 'removed' } + | { kind: 'missing' } + | { kind: 'refused'; code: 'target_is_symlink' } + | { kind: 'error'; code: string }; + +function storageKeyDefect(task: DeletionTaskTargetInput): TargetDefectCode | null { + return task.storageKey !== null && task.storageKey !== task.objectId ? 'inconsistent_target' : null; +} + +function singleTarget(base: string, target: string | null): TargetResolution { + if (target === null) return { ok: false, code: 'invalid_target' }; + return { ok: true, targets: [{ base, path: target }] }; +} + +function resolveAssetPack(task: DeletionTaskTargetInput, packsDir: string): TargetResolution { + const defect = storageKeyDefect(task); + if (defect !== null) return { ok: false, code: defect }; + return singleTarget(packsDir, resolveInside(packsDir, task.objectId)); +} + +function resolveAvatarPack(task: DeletionTaskTargetInput, packsDir: string): TargetResolution { + const defect = storageKeyDefect(task); + if (defect !== null) return { ok: false, code: defect }; + return singleTarget(packsDir, resolveInside(packsDir, 'avatars', task.objectId)); +} + +function resolveCustomAvatar(task: DeletionTaskTargetInput, packsDir: string): TargetResolution { + const defect = storageKeyDefect(task); + if (defect !== null) return { ok: false, code: defect }; + const dir = customAvatarDir(packsDir); + const owner = resolveInside(dir, task.objectId); + const sprite = resolveInside(dir, `${task.objectId}.png`); + const preview = resolveInside(dir, `${task.objectId}_p.png`); + if (owner === null || sprite === null || preview === null) return { ok: false, code: 'invalid_target' }; + return { + ok: true, + targets: [ + { base: packsDir, path: sprite }, + { base: packsDir, path: preview }, + ], + }; +} + +function resolveNpcMedia(task: DeletionTaskTargetInput): TargetResolution { + if (task.storageKey === null) return { ok: false, code: 'invalid_target' }; + return singleTarget(npcMediaDir(), tenantNpcMediaDir(task.storageKey)); +} + +/** + * Maps a task to the files it owns. Storage roots are read on every call, not at import time. + */ +export function resolveTaskTargets(task: DeletionTaskTargetInput): TargetResolution { + if (task.kind !== 'file') return { ok: false, code: 'unknown_task_kind' }; + const packsDir = customAvatarPacksDir(); + switch (task.targetSystem) { + case 'asset_packs': + return resolveAssetPack(task, packsDir); + case 'avatar_packs': + return resolveAvatarPack(task, packsDir); + case 'custom_avatars': + return resolveCustomAvatar(task, packsDir); + case 'npc_media': + return resolveNpcMedia(task); + default: + return { ok: false, code: 'unknown_target_system' }; + } +} + +/** + * True while a live row still points at the task's object. An unknown target system or a + * missing storage key counts as referenced (fail closed). + */ +export async function hasLiveReference(prisma: PrismaClient, task: DeletionTaskTargetInput): Promise { + const { objectId, storageKey } = task; + switch (task.targetSystem) { + case 'asset_packs': + return (await prisma.assetPack.findFirst({ where: { uuid: objectId }, select: { id: true } })) !== null; + case 'avatar_packs': + return (await prisma.avatarPack.findFirst({ where: { uuid: objectId }, select: { id: true } })) !== null; + case 'custom_avatars': + return (await prisma.customAvatar.findFirst({ where: { uuid: objectId }, select: { id: true } })) !== null; + case 'npc_media': + if (storageKey === null) return true; + return (await prisma.tenant.findFirst({ where: { slug: storageKey }, select: { id: true } })) !== null; + default: + return true; + } +} + +/** Codes of file system errors are short and lower case, for example `fs_enoent`. */ +export function fsErrorCode(error: unknown): string { + const code = errnoCode(error); + if (code === null || !/^E[A-Z0-9]+$/.test(code)) return 'fs_error'; + return `fs_${code.toLowerCase()}`.slice(0, 64); +} + +function errnoCode(error: unknown): string | null { + return error instanceof Error && 'code' in error && typeof error.code === 'string' ? error.code : null; +} + +async function realRoot(base: string): Promise { + try { + const real = await fsp.realpath(base); + const stat = await fsp.stat(real); + if (!stat.isDirectory()) return { kind: 'error', code: 'target_root_missing' }; + return real; + } catch (error) { + const code = fsErrorCode(error); + return { kind: 'error', code: code === 'fs_enoent' ? 'target_root_missing' : code }; + } +} + +/** + * Removes the target once its parent resolves to the expected place under the real storage + * root and the target itself is not a symbolic link. + */ +export async function removeTarget(target: ResolvedTarget): Promise { + const root = await realRoot(target.base); + if (typeof root !== 'string') return root; + const parent = path.dirname(target.path); + try { + const expected = path.join(root, path.relative(target.base, parent)); + if ((await fsp.realpath(parent)) !== expected) return { kind: 'refused', code: 'target_is_symlink' }; + if ((await fsp.lstat(target.path)).isSymbolicLink()) return { kind: 'refused', code: 'target_is_symlink' }; + await fsp.rm(target.path, { recursive: true, force: true }); + return { kind: 'removed' }; + } catch (error) { + if (errnoCode(error) === 'ENOENT') return { kind: 'missing' }; + return { kind: 'error', code: fsErrorCode(error) }; + } +} + +/** True when something sits at the target path. Errors other than ENOENT count as present (fail closed). */ +export async function targetExists(target: ResolvedTarget): Promise { + try { + await fsp.lstat(target.path); + return true; + } catch (error) { + return errnoCode(error) !== 'ENOENT'; + } +} diff --git a/apps/server/src/services/deletionTaskWorker.ts b/apps/server/src/services/deletionTaskWorker.ts new file mode 100644 index 00000000..5175f865 --- /dev/null +++ b/apps/server/src/services/deletionTaskWorker.ts @@ -0,0 +1,392 @@ +import { randomBytes } from 'node:crypto'; +import type { Prisma, PrismaClient } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; +import { appendJournalEntry, decideJournalIntents } from './tenantDeletionJournal.js'; +import { removeCompactionLeftovers } from './tenantDeletionJournalCompaction.js'; +import { compactExpiredJournals } from './deletionJournalExpiry.js'; +import { + fsErrorCode, + hasLiveReference, + removeTarget, + resolveTaskTargets, + targetExists, +} from './deletionTaskTargets.js'; + +const DEFAULT_MAX_ATTEMPTS = 10; +const DEFAULT_LEASE_MS = 300_000; +const TASK_BATCH_SIZE = 100; +const JOURNAL_BATCH_SIZE = 100; +const RETRY_BASE_MS = 60_000; + +/** Options of one pass over the due deletion tasks. `now` is the only clock the pass reads. */ +export interface RunDeletionTasksOptions { + prisma: PrismaClient; + journalDir: string; + now: Date; + maxAttempts?: number; + leaseMs?: number; + maxCopyLifetimeMs: number; + /** + * Age after which an undecided journal intent may be fenced, see decideJournalIntents. The same age is + * the minimum age of an account journal without tasks before it is completed. + */ + abortAfterMs: number; +} + +/** Counters of one pass. */ +export interface DeletionTaskRunResult { + done: number; + retried: number; + failed: number; + manual: number; + expired: number; +} + +interface TaskSettings { + maxAttempts: number; + leaseMs: number; +} + +/** A task as leased in this pass. */ +interface Lease { + taskId: string; + leaseToken: string; + attempts: number; + now: Date; +} + +type Settlement = { kind: 'done' } | { kind: 'retry' | 'failed' | 'manual_required'; code: string }; + +type TaskUpdate = Prisma.DeletionTaskUpdateManyMutationInput; + +function findDueTasks(prisma: PrismaClient, now: Date) { + return prisma.deletionTask.findMany({ + where: { + journal: { status: 'cleanup_pending', dbDeletedAt: { not: null } }, + OR: [ + { status: { in: ['pending', 'retry'] }, nextAttemptAt: { lte: now } }, + { status: 'leased', leaseUntil: { lte: now } }, + ], + }, + orderBy: [{ nextAttemptAt: 'asc' }, { id: 'asc' }], + take: TASK_BATCH_SIZE, + select: { + id: true, + status: true, + leaseToken: true, + attempts: true, + kind: true, + targetSystem: true, + objectId: true, + storageKey: true, + }, + }); +} + +type DueTask = Awaited>[number]; + +/** + * Runs one pass over the due deletion tasks, completes the journals whose tasks are all done, + * compacts the journal entries past their copy lifetime and then logs a single line when tasks need + * attention. Leftovers of an interrupted compaction are removed first, undecided journal intents are + * decided next. Due checks, leases, retry times, completion times and the compaction limit all derive + * from `options.now`. + */ +export async function runDeletionTasks(options: RunDeletionTasksOptions): Promise { + await removeLeftovers(options.journalDir); + await decideOpenIntents(options); + const settings: TaskSettings = { + maxAttempts: positiveInteger(options.maxAttempts, DEFAULT_MAX_ATTEMPTS, 'maxAttempts'), + leaseMs: positiveInteger(options.leaseMs, DEFAULT_LEASE_MS, 'leaseMs'), + }; + const result: DeletionTaskRunResult = { done: 0, retried: 0, failed: 0, manual: 0, expired: 0 }; + await processDueTasks(options.prisma, options.now, settings, result); + await completeJournals(options.prisma, options.journalDir, options.now, options.abortAfterMs); + result.expired = await compactExpired(options); + await warnAboutStuckTasks(options.prisma); + return result; +} + +/** Leftover files of an interrupted compaction are removed first. A failure does not stop the pass. */ +async function removeLeftovers(journalDir: string): Promise { + try { + if (await removeCompactionLeftovers(journalDir)) return; + logger.warn({ event: 'tenant_deletion.journal_unavailable', code: 'leftovers_not_removed' }); + } catch (error) { + logger.warn({ event: 'tenant_deletion.journal_unavailable', code: fsErrorCode(error) }); + } +} + +/** A failure is logged by its code and does not stop the pass. */ +async function decideOpenIntents(options: RunDeletionTasksOptions): Promise { + try { + await decideJournalIntents({ + prisma: options.prisma, + journalDir: options.journalDir, + now: options.now, + abortAfterMs: options.abortAfterMs, + }); + } catch (error) { + logger.error({ event: 'tenant_deletion.intent_decision_failed', code: fsErrorCode(error) }); + } +} + +/** A failed compaction is logged by its code and counts as no removed keys. */ +async function compactExpired(options: RunDeletionTasksOptions): Promise { + try { + return await compactExpiredJournals(options.prisma, options.journalDir, options.now, options.maxCopyLifetimeMs); + } catch (error) { + logger.error({ event: 'tenant_deletion.journal_compaction_failed', code: fsErrorCode(error) }); + return 0; + } +} + +function positiveInteger(value: number | undefined, fallback: number, name: string): number { + if (value === undefined) return fallback; + if (!Number.isInteger(value) || value < 1) throw new RangeError(`${name} must be an integer of at least 1`); + return value; +} + +async function processDueTasks( + prisma: PrismaClient, + now: Date, + settings: TaskSettings, + result: DeletionTaskRunResult, +): Promise { + const tasks = await findDueTasks(prisma, now); + for (const task of tasks) { + try { + await processTask(prisma, task, now, settings, result); + } catch (error) { + // The lease runs out on its own, so the task becomes due again in a later pass. + logger.error({ event: 'tenant_deletion.task_error', taskId: task.id, code: unexpectedErrorCode(error) }); + } + } +} + +/** File system codes stay visible; every other unexpected error is reported as `task_error`. */ +function unexpectedErrorCode(error: unknown): string { + const code = fsErrorCode(error); + return code === 'fs_error' ? 'task_error' : code; +} + +async function processTask( + prisma: PrismaClient, + task: DueTask, + now: Date, + settings: TaskSettings, + result: DeletionTaskRunResult, +): Promise { + const leaseToken = randomBytes(16).toString('hex'); + const claim = await prisma.deletionTask.updateMany({ + where: { id: task.id, status: task.status, leaseToken: task.leaseToken, attempts: task.attempts }, + data: { + status: 'leased', + leaseToken, + leaseUntil: new Date(now.getTime() + settings.leaseMs), + attempts: { increment: 1 }, + }, + }); + if (claim.count !== 1) return; + const lease: Lease = { taskId: task.id, leaseToken, attempts: task.attempts + 1, now }; + const settlement = finalize(await decideOutcome(prisma, task), lease.attempts, settings.maxAttempts); + await settle(prisma, lease, settlement, result); +} + +/** Runs the checks and removals of one task and says how the task should end. */ +async function decideOutcome(prisma: PrismaClient, task: DueTask): Promise { + const resolution = resolveTaskTargets(task); + if (!resolution.ok) return { kind: 'failed', code: resolution.code }; + if (await hasLiveReference(prisma, task)) return { kind: 'manual_required', code: 'target_still_referenced' }; + for (const target of resolution.targets) { + const outcome = await removeTarget(target); + if (outcome.kind === 'refused') return { kind: 'failed', code: outcome.code }; + if (outcome.kind === 'error') return { kind: 'retry', code: outcome.code }; + } + return { kind: 'done' }; +} + +/** A retryable error that has used up its attempts ends as failed. */ +function finalize(settlement: Settlement, attempts: number, maxAttempts: number): Settlement { + if (settlement.kind === 'retry' && attempts >= maxAttempts) return { kind: 'failed', code: settlement.code }; + return settlement; +} + +/** The row update that ends a lease. Every ending releases the lease. */ +function settlementData(settlement: Settlement, lease: Lease): TaskUpdate { + const released = { leaseToken: null, leaseUntil: null }; + switch (settlement.kind) { + case 'done': + return { ...released, status: 'done', completedAt: lease.now, lastErrorCode: null }; + case 'retry': + return { + ...released, + status: 'retry', + nextAttemptAt: new Date(lease.now.getTime() + 2 ** lease.attempts * RETRY_BASE_MS), + lastErrorCode: settlement.code, + }; + case 'failed': + case 'manual_required': + return { ...released, status: settlement.kind, lastErrorCode: settlement.code }; + } +} + +/** Writes the outcome under the lease token. A lost lease is logged and not counted. */ +async function settle( + prisma: PrismaClient, + lease: Lease, + settlement: Settlement, + result: DeletionTaskRunResult, +): Promise { + const written = await prisma.deletionTask.updateMany({ + where: { id: lease.taskId, status: 'leased', leaseToken: lease.leaseToken }, + data: settlementData(settlement, lease), + }); + if (written.count !== 1) { + logger.warn({ event: 'tenant_deletion.task_lease_lost', taskId: lease.taskId }); + return; + } + if (settlement.kind === 'done') { + result.done += 1; + } else if (settlement.kind === 'retry') { + result.retried += 1; + } else if (settlement.kind === 'failed') { + result.failed += 1; + logger.warn({ event: 'tenant_deletion.task_failed', taskId: lease.taskId, code: settlement.code }); + } else { + result.manual += 1; + logger.warn({ event: 'tenant_deletion.task_manual_required', taskId: lease.taskId, code: settlement.code }); + } +} + +/** + * Journals ready for completion: all tasks done, or, for an account journal without tasks, a database + * deletion older than the minimum age. The minimum age keeps the pass from racing the request that + * deletes the account. + */ +function findCompletableJournals(prisma: PrismaClient, accountCutoff: Date) { + return prisma.deletionJournal.findMany({ + where: { + status: 'cleanup_pending', + dbDeletedAt: { not: null }, + OR: [ + { tasks: { some: {}, every: { status: 'done' } } }, + { scope: 'account', tasks: { none: {} }, dbDeletedAt: { lte: accountCutoff } }, + ], + }, + orderBy: [{ dbDeletedAt: 'asc' }, { id: 'asc' }], + select: { id: true, idempotencyKey: true, scope: true, tenantRef: true, accountRefs: true }, + take: JOURNAL_BATCH_SIZE, + }); +} + +type CompletableJournal = Awaited>[number]; + +/** Reference fields of a completed entry: the tenant, or the account with an empty tenant reference. */ +type CompletionRefs = { tenantRef: string; accountRef?: string }; + +/** Undefined when the row does not carry the reference that its scope needs. */ +function completionRefs(journal: CompletableJournal): CompletionRefs | undefined { + if (journal.scope !== 'account') { + return journal.tenantRef === null ? undefined : { tenantRef: journal.tenantRef }; + } + const accountRef = journal.accountRefs[0]; + return accountRef === undefined ? undefined : { tenantRef: '', accountRef }; +} + +/** + * Completes the cleanup_pending journals that findCompletableJournals selects. The completed entry goes + * to the journal file before the database status changes. A failed journal write ends the pass, because + * the journal file is unavailable for the remaining journals as well. + */ +async function completeJournals( + prisma: PrismaClient, + journalDir: string, + now: Date, + abortAfterMs: number, +): Promise { + const journals = await findCompletableJournals(prisma, new Date(now.getTime() - abortAfterMs)); + for (const journal of journals) { + const refs = completionRefs(journal); + if (refs === undefined) { + const code = journal.scope === 'account' ? 'missing_account_ref' : 'missing_tenant_ref'; + logger.warn({ event: 'tenant_deletion.journal_not_completed', journalId: journal.id, code }); + continue; + } + if (!(await doneTasksAreSettled(prisma, journal.id, now))) continue; + if (!(await appendCompletedEntry(journalDir, journal, refs, now))) return; + await prisma.deletionJournal.updateMany({ + where: { id: journal.id, status: 'cleanup_pending' }, + data: { status: 'completed', completedAt: now }, + }); + } +} + +/** + * True when every done task of the journal still matches its files. A task with a file on disk is + * reopened, and a task that cannot be mapped to files or is not done keeps the journal open. + */ +async function doneTasksAreSettled(prisma: PrismaClient, journalId: string, now: Date): Promise { + const tasks = await prisma.deletionTask.findMany({ + where: { journalId }, + select: { id: true, status: true, kind: true, targetSystem: true, objectId: true, storageKey: true }, + }); + let settled = true; + for (const task of tasks) { + if (task.status !== 'done') { + settled = false; + continue; + } + const resolution = resolveTaskTargets(task); + if (!resolution.ok) { + logger.warn({ + event: 'tenant_deletion.journal_not_completed', + journalId, + taskId: task.id, + code: 'invalid_done_task', + }); + settled = false; + continue; + } + const present = await Promise.all(resolution.targets.map((target) => targetExists(target))); + if (present.includes(true)) { + const reopened = await prisma.deletionTask.updateMany({ + where: { id: task.id, status: 'done' }, + data: { status: 'pending', nextAttemptAt: now, completedAt: null }, + }); + if (reopened.count === 1) logger.warn({ event: 'tenant_deletion.task_reopened', taskId: task.id }); + settled = false; + } + } + return settled; +} + +/** Appends the completed entry of one journal. False when the journal file cannot be written. */ +async function appendCompletedEntry( + journalDir: string, + journal: CompletableJournal, + refs: CompletionRefs, + now: Date, +): Promise { + try { + await appendJournalEntry(journalDir, { + type: 'completed', + key: journal.idempotencyKey, + ...refs, + at: now.toISOString(), + }); + return true; + } catch (error) { + logger.error({ event: 'tenant_deletion.journal_unavailable', journalId: journal.id, code: fsErrorCode(error) }); + return false; + } +} + +/** One log line when tasks have failed or wait for a person. Counts only, no identifiers. */ +async function warnAboutStuckTasks(prisma: PrismaClient): Promise { + const failed = await prisma.deletionTask.count({ where: { status: 'failed' } }); + const manualRequired = await prisma.deletionTask.count({ where: { status: 'manual_required' } }); + if (failed > 0 || manualRequired > 0) { + logger.warn({ event: 'tenant_deletion.tasks_need_attention', failed, manualRequired }); + } +} diff --git a/apps/server/src/services/restoreReplayTokenCleanup.integration.test.ts b/apps/server/src/services/restoreReplayTokenCleanup.integration.test.ts new file mode 100644 index 00000000..91cc9403 --- /dev/null +++ b/apps/server/src/services/restoreReplayTokenCleanup.integration.test.ts @@ -0,0 +1,254 @@ +import crypto from 'crypto'; +import { mkdtemp, rm, writeFile } from 'fs/promises'; +import os from 'os'; +import path from 'path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { createPrismaClient } from '../db.js'; +import { CHECKPOINT_FILE, ZERO_HEAD, appendJournalEntry } from './tenantDeletionJournal.js'; +import { RESTORE_PENDING_FILE, isRestorePending, type RestorePendingMarker } from './tenantDeletionRestoreMarker.js'; +import { + REPLAY_EXIT, + runRestoreReplay, + type OAuthRefreshRevocation, + type RestoreReplayRunOptions, +} from './tenantDeletionReplayRun.js'; + +/** + * Token step at the end of the restore replay (runRestoreReplay) against a REAL PostgreSQL database. + * + * The token step deletes every Session row and every unused PasswordReset and EmailVerification row of the + * whole database, so this file must not run in parallel with other database test files. Each case creates + * its own user with tokens and checks only those rows and the counters in the output. The output is the list + * of lines that runRestoreReplay returns; the function itself prints nothing. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('restore replay token step test needs DATABASE_URL pointing at a migrated test database'); +} + +const prisma = createPrismaClient(); +const FAR_FUTURE = new Date('2099-01-01T00:00:00.000Z'); +const JOURNAL_UNTIL = '2099-01-01T00:00:00.000Z'; +const userIds: string[] = []; +const journalDirs: string[] = []; + +interface TokenFixture { + userId: string; + /** Values that must never appear in an output line. */ + secrets: string[]; +} + +interface OAuthCase { + label: string; + revocation: OAuthRefreshRevocation; + exitCode: number; + markerKept: boolean; + expectedLine: string; +} + +const oauthCases: OAuthCase[] = [ + { + label: 'transcription module not loaded', + revocation: { kind: 'module_not_loaded' }, + exitCode: REPLAY_EXIT.done, + markerKept: false, + expectedLine: 'oauth refresh tokens: skipped (transcription module not loaded)', + }, + { + label: 'transcription module without the revocation export', + revocation: { kind: 'export_missing' }, + exitCode: REPLAY_EXIT.deleteFailed, + markerKept: true, + expectedLine: 'oauth refresh token revocation unavailable', + }, + { + label: 'installed transcription module failed to load', + revocation: { kind: 'module_rejected' }, + exitCode: REPLAY_EXIT.deleteFailed, + markerKept: true, + expectedLine: 'the installed transcription module failed to load', + }, + { + label: 'revocation available', + revocation: { kind: 'available', revoke: async () => 3 }, + exitCode: REPLAY_EXIT.done, + markerKept: false, + expectedLine: 'oauth refresh tokens revoked: 3', + }, +]; + +function randomToken(): string { + return crypto.randomBytes(32).toString('hex'); +} + +/** One user with two sessions, and an unused and a used row each for reset and verification. */ +async function createTokenFixture(): Promise { + const email = `restore-token-step-${crypto.randomUUID()}@example.test`; + const user = await prisma.user.create({ data: { email } }); + userIds.push(user.id); + const sessionHashes = [randomToken(), randomToken()]; + await prisma.session.createMany({ + data: sessionHashes.map((tokenHash) => ({ userId: user.id, tokenHash, expiresAt: FAR_FUTURE })), + }); + const unusedReset = randomToken(); + const usedReset = randomToken(); + await prisma.passwordReset.createMany({ + data: [ + { userId: user.id, token: unusedReset, expiresAt: FAR_FUTURE }, + { userId: user.id, token: usedReset, expiresAt: FAR_FUTURE, usedAt: new Date() }, + ], + }); + const unusedVerification = randomToken(); + const usedVerification = randomToken(); + await prisma.emailVerification.createMany({ + data: [ + { userId: user.id, email, token: unusedVerification, expiresAt: FAR_FUTURE }, + { userId: user.id, email, token: usedVerification, expiresAt: FAR_FUTURE, usedAt: new Date() }, + ], + }); + const secrets = [user.id, ...sessionHashes, unusedReset, usedReset, unusedVerification, usedVerification]; + return { userId: user.id, secrets }; +} + +/** + * Operator options without decisions and without tenant deletions. No enterprise admin module is loaded + * here, so no precondition is open; the operator script reports the same empty list in OSS mode. + */ +function runOptions(journalDir: string, revocation: OAuthRefreshRevocation): RestoreReplayRunOptions { + return { + prisma, + journalDir, + decisions: new Map(), + deleteTenant: undefined, + pendingPreconditions: async () => [], + oauthRefreshRevocation: revocation, + }; +} + +/** Empty journal with a zero checkpoint, the state of a journal that has no entries. */ +async function createJournalDir(): Promise { + const dir = await mkdtemp(path.join(os.tmpdir(), 'restore-token-step-')); + journalDirs.push(dir); + const checkpoint = { v: 1, seq: 0, head: ZERO_HEAD, baseSeq: 0, baseHead: ZERO_HEAD }; + await writeFile(path.join(dir, CHECKPOINT_FILE), JSON.stringify(checkpoint), 'utf8'); + return dir; +} + +/** + * Restore marker in the file format the restore script writes. A null copy time makes the replay + * consider every commit of the journal. + */ +async function writeRestoreMarker(journalDir: string, journalSeq: number): Promise { + const marker: RestorePendingMarker = { v: 1, createdAt: new Date().toISOString(), copyCreatedAt: null, journalSeq }; + await writeFile(path.join(journalDir, RESTORE_PENDING_FILE), JSON.stringify(marker), 'utf8'); +} + +/** Open intent with no decision and no database row, as left by a deletion whose commit never got recorded. */ +async function appendOpenIntent(journalDir: string, key: string, tenantRef: string): Promise { + await appendJournalEntry(journalDir, { + type: 'intent', + key, + tenantRef, + at: new Date().toISOString(), + journalUntil: JOURNAL_UNTIL, + }); +} + +/** Value of a counter line such as "sessions deleted: 2"; fails when the output has no such line. */ +function counterOf(lines: string[], label: string): number { + const count = lines.find((entry) => entry.includes(`${label}: `))?.match(/(\d+)$/)?.[1]; + if (count === undefined) throw new Error(`output has no counter line for "${label}"`); + return Number(count); +} + +/** No output line carries a user id or a token value of the fixture. */ +function expectNoSecrets(lines: string[], fixture: TokenFixture): void { + expect(lines.length).toBeGreaterThan(0); + for (const line of lines) { + for (const secret of fixture.secrets) expect(line).not.toContain(secret); + } +} + +/** Own sessions and unused reset and verification rows are gone; the used rows remain. */ +async function expectOwnTokensCleared(fixture: TokenFixture): Promise { + const { userId } = fixture; + expect(await prisma.session.count({ where: { userId } })).toBe(0); + expect(await prisma.passwordReset.count({ where: { userId, usedAt: null } })).toBe(0); + expect(await prisma.emailVerification.count({ where: { userId, usedAt: null } })).toBe(0); + expect(await prisma.passwordReset.count({ where: { userId, usedAt: { not: null } } })).toBe(1); + expect(await prisma.emailVerification.count({ where: { userId, usedAt: { not: null } } })).toBe(1); +} + +/** Blocked run: both sessions and the unused reset and verification rows remain. */ +async function expectOwnTokensKept(fixture: TokenFixture): Promise { + const { userId } = fixture; + expect(await prisma.session.count({ where: { userId } })).toBe(2); + expect(await prisma.passwordReset.count({ where: { userId, usedAt: null } })).toBe(1); + expect(await prisma.emailVerification.count({ where: { userId, usedAt: null } })).toBe(1); +} + +describe('restore replay token step (real database)', () => { + it('clears own sessions and unused tokens, keeps used tokens, and removes the marker', async () => { + const fixture = await createTokenFixture(); + const journalDir = await createJournalDir(); + await writeRestoreMarker(journalDir, 0); + + const result = await runRestoreReplay(runOptions(journalDir, { kind: 'module_not_loaded' })); + + expect(result.exitCode).toBe(REPLAY_EXIT.done); + expect(counterOf(result.lines, 'sessions deleted')).toBeGreaterThanOrEqual(2); + expect(counterOf(result.lines, 'password reset tokens deleted')).toBeGreaterThanOrEqual(1); + expect(counterOf(result.lines, 'email verification tokens deleted')).toBeGreaterThanOrEqual(1); + expect(result.lines).toContain('restore replay: marker removed'); + expect(await isRestorePending(journalDir)).toBe(false); + await expectOwnTokensCleared(fixture); + // Runs alone after all other database test files: no session and no unused token row is left. + expect(await prisma.session.count()).toBe(0); + expect(await prisma.passwordReset.count({ where: { usedAt: null } })).toBe(0); + expect(await prisma.emailVerification.count({ where: { usedAt: null } })).toBe(0); + expectNoSecrets(result.lines, fixture); + }); + + it('keeps own tokens and the marker while an open intent without a decision blocks the replay', async () => { + const fixture = await createTokenFixture(); + const journalDir = await createJournalDir(); + const key = crypto.randomUUID(); + await appendOpenIntent(journalDir, key, crypto.randomUUID()); + await writeRestoreMarker(journalDir, 1); + + const result = await runRestoreReplay(runOptions(journalDir, { kind: 'module_not_loaded' })); + + expect(result.exitCode).toBe(REPLAY_EXIT.undecided); + expect(result.lines.some((line) => line.includes(`key=${key}`))).toBe(true); + expect(result.lines.some((line) => line.includes('sessions deleted'))).toBe(false); + expect(await isRestorePending(journalDir)).toBe(true); + await expectOwnTokensKept(fixture); + expectNoSecrets(result.lines, fixture); + }); + + it.each(oauthCases)('OAuth refresh step: $label', async (scenario) => { + const fixture = await createTokenFixture(); + const journalDir = await createJournalDir(); + await writeRestoreMarker(journalDir, 0); + + const result = await runRestoreReplay(runOptions(journalDir, scenario.revocation)); + + expect(result.exitCode).toBe(scenario.exitCode); + expect(result.lines.some((line) => line.includes(scenario.expectedLine))).toBe(true); + expect(await isRestorePending(journalDir)).toBe(scenario.markerKept); + expectNoSecrets(result.lines, fixture); + }); +}); + +afterAll(async () => { + try { + const ids = userIds.splice(0); + await prisma.session.deleteMany({ where: { userId: { in: ids } } }); + await prisma.passwordReset.deleteMany({ where: { userId: { in: ids } } }); + await prisma.emailVerification.deleteMany({ where: { userId: { in: ids } } }); + await prisma.user.deleteMany({ where: { id: { in: ids } } }); + } finally { + for (const dir of journalDirs.splice(0)) await rm(dir, { recursive: true, force: true }); + await prisma.$disconnect(); + } +}); diff --git a/apps/server/src/services/sharedPlanResolver.test.ts b/apps/server/src/services/sharedPlanResolver.test.ts new file mode 100644 index 00000000..09ec7f2d --- /dev/null +++ b/apps/server/src/services/sharedPlanResolver.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { createSharedPlanResolver } from './sharedPlanResolver.js'; + +describe('createSharedPlanResolver', () => { + it('creates the resolver once, also for concurrent first calls, and returns the same instance', async () => { + let created = 0; + const shared = createSharedPlanResolver( + async (dir: string) => { + created += 1; + return { dir }; + }, + () => undefined, + ); + const [first, second] = await Promise.all([shared('/journal'), shared('/journal')]); + const third = await shared('/journal'); + expect(created).toBe(1); + expect(first).toBe(second); + expect(third).toBe(first); + }); + + it('refuses a second, different journal directory', async () => { + let created = 0; + const shared = createSharedPlanResolver( + async (dir: string) => { + created += 1; + return { dir }; + }, + () => undefined, + ); + const first = await shared('/journal'); + expect(await shared('/other')).toBeUndefined(); + expect(await shared('/journal')).toBe(first); + expect(created).toBe(1); + }); + + it('forgets a failed creation and retries on the next call', async () => { + let attempts = 0; + const errors: unknown[] = []; + const shared = createSharedPlanResolver( + async (dir: string) => { + attempts += 1; + if (attempts === 1) throw new Error('journal unavailable'); + return { dir }; + }, + (error) => errors.push(error), + ); + expect(await shared('/journal')).toBeUndefined(); + expect(errors).toHaveLength(1); + expect(await shared('/journal')).toEqual({ dir: '/journal' }); + expect(attempts).toBe(2); + }); +}); diff --git a/apps/server/src/services/sharedPlanResolver.ts b/apps/server/src/services/sharedPlanResolver.ts new file mode 100644 index 00000000..5b3b1865 --- /dev/null +++ b/apps/server/src/services/sharedPlanResolver.ts @@ -0,0 +1,23 @@ +/** + * Keeps one plan resolver per process for one journal directory. Creating a + * resolver reconciles undecided journal intents, so every caller in the + * process shares the same instance instead of creating its own. + */ +export function createSharedPlanResolver( + create: (journalDir: string) => Promise, + onError: (error: unknown) => void, +): (journalDir: string) => Promise { + let cached: Promise | undefined; + let cachedDir: string | undefined; + return (journalDir) => { + // A second, different journal directory in the same process is refused. + if (cachedDir !== undefined && cachedDir !== journalDir) return Promise.resolve(undefined); + cachedDir = journalDir; + cached ??= create(journalDir).catch((error: unknown) => { + cached = undefined; + onError(error); + return undefined; + }); + return cached; + }; +} diff --git a/apps/server/src/services/tenantDeletionContract.ts b/apps/server/src/services/tenantDeletionContract.ts new file mode 100644 index 00000000..e76186b8 --- /dev/null +++ b/apps/server/src/services/tenantDeletionContract.ts @@ -0,0 +1,76 @@ +import type { Prisma } from '../generated/prisma/index.js'; + +/** + * Version token for the tenant deletion contract between host and callback. + * + * The OSS host checks the token before it calls the enterprise preparation, + * and the enterprise callback checks the passed context before its first + * DELETE; any other value (including `undefined`) aborts the deletion + * with `TenantDeletionContractError`. Bare OSS calls without enterprise options + * are exempt and keep the previous behavior. + */ +export const TENANT_DELETION_PROTOCOL = 'tenant-delete-v2' as const; + +/** A single internal deletion task with a stable object identity. */ +export interface TenantDeletionTaskPlan { + kind: string; + targetSystem: string; + objectId: string; + objectGeneration: string; + storageKey?: string; +} + +/** Internal plan input; `journalUntil` is checked as a real date at runtime. */ +export interface TenantDeletionPlanInput { + idempotencyKey: string; + policyVersion: string; + journalUntil: unknown; + tasks: readonly TenantDeletionTaskPlan[]; +} + +/** Context that the host passes as the second argument to `prepareInTx`. */ +export interface TenantDeletionPreparationContext { + deletionProtocol: typeof TENANT_DELETION_PROTOCOL; + transactionTime: Date; +} + +/** Context that the host passes as the second argument to `cleanupInTx`. */ +export interface TenantDeletionContext extends TenantDeletionPreparationContext { + journalId: string; +} + +/** Options accepted by `deleteTenantWithMembers`. */ +export interface TenantDeletionOptions { + deletionProtocol?: typeof TENANT_DELETION_PROTOCOL; + prepareInTx?: ( + tx: Prisma.TransactionClient, + context: TenantDeletionPreparationContext, + ) => Promise; + cleanupInTx?: (tx: Prisma.TransactionClient, context?: TenantDeletionContext) => Promise; + /** Internal test input for the transaction time only, not a production path. */ + transactionTime?: Date; +} + +export class TenantDeletionContractError extends Error { + readonly code = 'tenant_deletion_contract_required' as const; + + constructor() { + super('tenant deletion requires deletionProtocol tenant-delete-v2'); + this.name = 'TenantDeletionContractError'; + } +} + +/** Sanitized plan validation error without input data; maps to HTTP 409. */ +export class TenantDeletionJournalUnavailableError extends Error { + readonly code = 'retention_journal_unavailable' as const; + + constructor() { + super('tenant deletion blocked: no valid retention plan available'); + this.name = 'TenantDeletionJournalUnavailableError'; + } +} + +/** Throws `TenantDeletionContractError` unless `value` is the exact token. */ +export function assertTenantDeletionProtocol(value: unknown): void { + if (value !== TENANT_DELETION_PROTOCOL) throw new TenantDeletionContractError(); +} diff --git a/apps/server/src/services/tenantDeletionFence.ts b/apps/server/src/services/tenantDeletionFence.ts new file mode 100644 index 00000000..106faf9d --- /dev/null +++ b/apps/server/src/services/tenantDeletionFence.ts @@ -0,0 +1,88 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; +import { logger } from '../logger.js'; + +/** + * Fence for an intent that has no outcome yet. It inserts a blocked row under the intent's + * idempotency key. The unique index on that key decides the race with a deletion transaction that + * may still be running: a transaction that holds the key makes the insert wait and then fail, a + * transaction that has already ended lets the insert succeed and blocks every later attempt with + * the same key. The unique index decides instead of comparing timestamps, so a late transaction + * cannot slip through. The blocked row has no tenant reference and never counts as a tenant + * journal row. + */ + +export type FenceOutcome = 'abort' | 'commit' | 'open'; + +export interface FenceIntent { + key: string; + journalUntil: string; +} + +const POLICY_VERSION = 'tenant-deletion-fence-v1'; +const LOCK_TIMEOUT_SQL = "SET LOCAL lock_timeout = '5s'"; +const STATEMENT_TIMEOUT_SQL = "SET LOCAL statement_timeout = '10s'"; + +/** True for the Prisma error of a unique key conflict. */ +function isUniqueConflict(error: unknown): boolean { + return typeof error === 'object' && error !== null && 'code' in error && error.code === 'P2002'; +} + +/** Logs the failure by its code only, never by its message. */ +function logFenceFailure(error: unknown): void { + const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined; + logger.warn({ event: 'tenant_deletion.intent_fence_failed', code: typeof code === 'string' ? code : 'unknown' }); +} + +/** Inserts the blocked row in its own transaction. The timeouts are constant SQL and bound each statement. */ +async function insertBlockedRow(prisma: PrismaClient, intent: FenceIntent): Promise { + // Prisma's default 5 s transaction timeout would cut in before the 10 s statement timeout below. + await prisma.$transaction( + async (tx) => { + await tx.$executeRawUnsafe(LOCK_TIMEOUT_SQL); + await tx.$executeRawUnsafe(STATEMENT_TIMEOUT_SQL); + await tx.deletionJournal.create({ + data: { + idempotencyKey: intent.key, + scope: 'tenant', + tenantRef: null, + accountRefs: [], + objectRefs: [], + policyVersion: POLICY_VERSION, + status: 'blocked', + journalUntil: new Date(intent.journalUntil), + }, + }); + }, + { timeout: 15_000, maxWait: 5_000 }, + ); +} + +/** Reads the row that caused the unique conflict. A read error leaves the intent open. */ +async function settleConflict(prisma: PrismaClient, key: string): Promise { + try { + const row = await prisma.deletionJournal.findUnique({ + where: { idempotencyKey: key }, + select: { dbDeletedAt: true, status: true }, + }); + if (row?.dbDeletedAt) return 'commit'; + return row?.status === 'blocked' ? 'abort' : 'open'; + } catch (error) { + logFenceFailure(error); + return 'open'; + } +} + +/** + * Fences an intent without an outcome. 'abort': the key is blocked for every deletion transaction. + * 'commit': the database recorded a deletion time. 'open': no decision. Never throws. + */ +export async function fenceUndecidedIntent(prisma: PrismaClient, intent: FenceIntent): Promise { + try { + await insertBlockedRow(prisma, intent); + return 'abort'; + } catch (error) { + if (isUniqueConflict(error)) return settleConflict(prisma, intent.key); + logFenceFailure(error); + return 'open'; + } +} diff --git a/apps/server/src/services/tenantDeletionJournal.ts b/apps/server/src/services/tenantDeletionJournal.ts new file mode 100644 index 00000000..a52438a3 --- /dev/null +++ b/apps/server/src/services/tenantDeletionJournal.ts @@ -0,0 +1,595 @@ +import { createHash, randomUUID } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { logger } from '../logger.js'; +import type { PrismaClient } from '../generated/prisma/index.js'; +import { JournalUnavailableError, acquireLock, assertLockHeld, releaseLock } from './tenantDeletionJournalLock.js'; +import { fenceUndecidedIntent } from './tenantDeletionFence.js'; +import { isRestorePending } from './tenantDeletionRestoreMarker.js'; + +export { JournalUnavailableError } from './tenantDeletionJournalLock.js'; + +/** + * File adapter for the tenant deletion journal. + * + * The journal directory holds `journal.jsonl` (one entry per line, UTF-8, + * newline-terminated) and `checkpoint.json` (sequence and hash of the last + * line, written atomically via a temp file and rename). Every append is + * flushed to disk before the caller continues, so a recorded intent survives + * a crash and an undecided intent can later be reconciled against the + * database. Entries carry only opaque identifiers, never names, mails, + * slugs, tokens or error texts. + */ + +export const JOURNAL_FILE = 'journal.jsonl'; +export const CHECKPOINT_FILE = 'checkpoint.json'; +export const COMPACT_JOURNAL_FILE = 'journal.jsonl.compact'; +export const COMPACT_CHECKPOINT_FILE = 'checkpoint.compact.json'; +const CHECKPOINT_TMP_FILE = 'checkpoint.json.tmp'; + +/** Previous-hash of the first entry when no checkpoint exists yet. */ +export const ZERO_HEAD = '0'.repeat(64); + +const HEX64 = /^[0-9a-f]{64}$/; + +export type JournalEntryType = 'intent' | 'commit' | 'abort' | 'completed'; + +export interface JournalEntry { + seq: number; + prev: string; + type: JournalEntryType; + key: string; + tenantRef: string; + accountRef?: string; + at: string; + journalUntil?: string; +} + +interface Checkpoint { + seq: number; + head: string; + baseSeq: number; + baseHead: string; +} + +export interface LoadedJournal { + entries: JournalEntry[]; + checkpoint: Checkpoint; + /** Complete, chained lines behind the checkpoint, left by a crash. */ + trailing: JournalEntry[]; + /** Hash of the last line, or the base head of an empty journal. */ + endHead: string; + /** Raw lines including their newline, in the same order as `entries`. */ + lines: string[]; +} + +export function sha256Hex(payload: string): string { + return createHash('sha256').update(payload, 'utf8').digest('hex'); +} + +/** Serializes with a fixed field order so the file layout stays stable. */ +function serializeEntry(entry: JournalEntry): string { + const record: Record = { + v: 1, + seq: entry.seq, + prev: entry.prev, + type: entry.type, + key: entry.key, + ...journalRefs(entry), + at: entry.at, + }; + if (entry.type === 'intent') record.journalUntil = entry.journalUntil; + return `${JSON.stringify(record)}\n`; +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +function isValidDateString(value: unknown): value is string { + return isNonEmptyString(value) && !Number.isNaN(Date.parse(value)); +} + +/** One reference per line: a tenant (tenantRef set, no accountRef) or an account (tenantRef empty, accountRef). */ +function hasSingleJournalRef(tenantRef: string, accountRef: unknown): accountRef is string | undefined { + if (tenantRef !== '') return accountRef === undefined; + return typeof accountRef === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(accountRef); +} + +/** Reference fields of a journal line; accountRef is included only when set. */ +export function journalRefs(entry: { tenantRef: string; accountRef?: string }): { + tenantRef: string; + accountRef?: string; +} { + if (entry.accountRef === undefined) return { tenantRef: entry.tenantRef }; + return { tenantRef: entry.tenantRef, accountRef: entry.accountRef }; +} + +/** Strict parse; returns null for a malformed line. */ +function parseEntry(line: string): JournalEntry | null { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + return null; + } + if (typeof parsed !== 'object' || parsed === null) return null; + const record = parsed as Record; + const { seq, prev, type, key, tenantRef, accountRef, at, journalUntil } = record; + if (record.v !== 1 || !Number.isInteger(seq) || (seq as number) <= 0) return null; + if (typeof prev !== 'string' || !HEX64.test(prev)) return null; + if (type !== 'intent' && type !== 'commit' && type !== 'abort' && type !== 'completed') return null; + if (!isNonEmptyString(key) || !isValidDateString(at)) return null; + if (typeof tenantRef !== 'string' || !hasSingleJournalRef(tenantRef, accountRef)) return null; + if (type === 'intent') { + if (!isValidDateString(journalUntil)) return null; + return { seq: seq as number, prev, type, key, ...journalRefs({ tenantRef, accountRef }), at, journalUntil }; + } + if (journalUntil !== undefined) return null; + return { seq: seq as number, prev, type, key, ...journalRefs({ tenantRef, accountRef }), at }; +} + +function parseCheckpoint(parsed: unknown): Checkpoint | null { + if (typeof parsed !== 'object' || parsed === null) return null; + const record = parsed as Record; + const { seq, head, baseSeq, baseHead } = record; + if (record.v !== 1) return null; + if (!Number.isInteger(seq) || (seq as number) < 0) return null; + if (!Number.isInteger(baseSeq) || (baseSeq as number) < 0 || (seq as number) < (baseSeq as number)) { + return null; + } + if (typeof head !== 'string' || !HEX64.test(head)) return null; + if (typeof baseHead !== 'string' || !HEX64.test(baseHead)) return null; + return { seq: seq as number, head, baseSeq: baseSeq as number, baseHead }; +} + +/** Parses checkpoint.json content; null when it is not JSON or not a valid checkpoint. */ +function parseCheckpointText(raw: string): Checkpoint | null { + try { + return parseCheckpoint(JSON.parse(raw)); + } catch { + return null; + } +} + +/** + * Checks complete lines against a checkpoint. Without a checkpoint only an empty + * journal fits, starting from the zero base. Returns null when the chain does not + * run gap-free from the checkpoint base or the checkpoint is not on that chain. + */ +function verifyJournalText(journalText: string, checkpoint: Checkpoint | null): LoadedJournal | null { + if (checkpoint === null && journalText !== '') return null; + if (journalText !== '' && !journalText.endsWith('\n')) return null; + const lines = + journalText === '' + ? [] + : journalText + .slice(0, -1) + .split('\n') + .map((body) => `${body}\n`); + const base = checkpoint ?? { seq: 0, head: ZERO_HEAD, baseSeq: 0, baseHead: ZERO_HEAD }; + const entries: JournalEntry[] = []; + const heads: string[] = [base.baseHead]; + for (let index = 0; index < lines.length; index += 1) { + const entry = parseEntry(lines[index].slice(0, -1)); + if (entry === null || entry.seq !== base.baseSeq + index + 1 || entry.prev !== heads[index]) return null; + if (entry.accountRef !== undefined && serializeEntry(entry) !== lines[index]) return null; + entries.push(entry); + heads.push(sha256Hex(lines[index])); + } + // After a crash between the durable line and the checkpoint rename the + // checkpoint lags behind; it must never point past the end or at another head. + const position = base.seq - base.baseSeq; + if (position > entries.length || base.head !== heads[position]) return null; + return { entries, checkpoint: base, trailing: entries.slice(position), endHead: heads[entries.length], lines }; +} + +/** Reads the compact checkpoint of an interrupted compaction; null when missing or malformed. */ +async function readCompactCheckpoint(journalDir: string): Promise { + try { + const raw = await fs.readFile(path.join(journalDir, COMPACT_CHECKPOINT_FILE), 'utf8'); + return parseCheckpoint(JSON.parse(raw)); + } catch { + return null; + } +} + +/** + * Loads and validates the journal without writing it, except to adopt a compact + * checkpoint. Only call it while holding the journal lock, because the adoption + * renames a file. Returns null when the + * directory is missing, not a directory, or not writable for its owner — the + * permission check is explicit so read-only directories stay unavailable even + * for privileged processes. A leftover checkpoint temp file is ignored and + * removed. The chain must run gap-free from the checkpoint base, and the + * checkpoint must point at a line of that chain; complete lines behind it are + * returned as `trailing`. A torn or unparseable last line is never repaired. + */ +export async function loadJournal(journalDir: string): Promise { + let dirStat; + try { + dirStat = await fs.stat(journalDir); + } catch { + return null; + } + if (!dirStat.isDirectory() || (dirStat.mode & 0o200) === 0) return null; + // A crashed checkpoint rewrite leaves only the temp file behind; it never + // carries authority and is dropped on every load. + await fs.rm(path.join(journalDir, CHECKPOINT_TMP_FILE), { force: true }).catch(() => undefined); + let journalText: string; + try { + journalText = await fs.readFile(path.join(journalDir, JOURNAL_FILE), 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null; + journalText = ''; + } + let checkpoint: Checkpoint | null | undefined; + try { + checkpoint = parseCheckpointText(await fs.readFile(path.join(journalDir, CHECKPOINT_FILE), 'utf8')); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null; + } + // A missing checkpoint means the zero base. A present one that is unparseable or invalid never + // counts as that base: only the compact checkpoint below may take over. + const state = checkpoint === null ? null : verifyJournalText(journalText, checkpoint ?? null); + if (state !== null) return state; + // A compaction that crashed between its two renames leaves the new journal + // behind the old checkpoint. The compact checkpoint describes exactly that + // journal, so it takes over; otherwise the journal stays unavailable. + const compact = await readCompactCheckpoint(journalDir); + const adopted = compact === null ? null : verifyJournalText(journalText, compact); + if (adopted === null) return null; + await fs.rename(path.join(journalDir, COMPACT_CHECKPOINT_FILE), path.join(journalDir, CHECKPOINT_FILE)); + await syncDirectoryBestEffort(journalDir); + return adopted; +} + +/** Writes a file and flushes its content to disk before returning. */ +export async function writeFileDurably(filePath: string, content: string): Promise { + const handle = await fs.open(filePath, 'w'); + try { + await handle.writeFile(content, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** + * Flushes directory entries (created or renamed files) to disk. Best effort: + * a directory that cannot be opened is skipped without an error. + */ +export async function syncDirectoryBestEffort(dir: string): Promise { + await fs.open(dir, 'r').then( + async (handle) => { + try { + await handle.sync(); + } finally { + await handle.close(); + } + }, + () => undefined, + ); +} + +/** Writes the checkpoint atomically: temp file, flush, rename, directory flush. */ +async function writeCheckpoint(journalDir: string, checkpoint: Checkpoint): Promise { + const tmpPath = path.join(journalDir, CHECKPOINT_TMP_FILE); + await writeFileDurably(tmpPath, JSON.stringify({ v: 1, ...checkpoint })); + await fs.rename(tmpPath, path.join(journalDir, CHECKPOINT_FILE)); + await syncDirectoryBestEffort(journalDir); +} + +/** + * Loads the journal for a writer that holds the lock. Complete lines behind + * the checkpoint are durable already, so the checkpoint moves forward to the + * last of them before anything new is appended. + */ +export async function loadJournalForWrite(journalDir: string): Promise { + const state = await loadJournal(journalDir); + if (state === null || state.trailing.length === 0) return state; + const checkpoint: Checkpoint = { + seq: state.checkpoint.seq + state.trailing.length, + head: state.endHead, + baseSeq: state.checkpoint.baseSeq, + baseHead: state.checkpoint.baseHead, + }; + await writeCheckpoint(journalDir, checkpoint); + logger.warn({ event: 'tenant_delete.journal_checkpoint_rolled_forward', count: state.trailing.length }); + return { ...state, checkpoint, trailing: [] }; +} + +/** Serializes journal writers within one process so sequences stay gap-free. */ +let appendChain: Promise = Promise.resolve(); + +function enqueueAppend(task: () => Promise): Promise { + const run = appendChain.then(task); + appendChain = run.catch(() => undefined); + return run; +} + +/** Runs a writer task in the process chain and under the directory lock. */ +export function withJournalLock(journalDir: string, task: (token: string) => Promise): Promise { + return enqueueAppend(async () => { + const token = await acquireLock(journalDir); + try { + return await task(token); + } finally { + await releaseLock(journalDir, token); + } + }); +} + +/** Append body for a writer that already holds the lock with `token`. */ +async function appendLocked(journalDir: string, token: string, entry: JournalEntry): Promise { + const state = await loadJournalForWrite(journalDir); + if (state === null) throw new JournalUnavailableError(); + const line = serializeEntry({ ...entry, seq: state.checkpoint.seq + 1, prev: state.checkpoint.head }); + // The lock must be held before the line and before the checkpoint moves. + await assertLockHeld(journalDir, token); + const handle = await fs.open(path.join(journalDir, JOURNAL_FILE), 'a'); + try { + await handle.writeFile(line, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } + await assertLockHeld(journalDir, token); + await writeCheckpoint(journalDir, { + seq: state.checkpoint.seq + 1, + head: sha256Hex(line), + baseSeq: state.checkpoint.baseSeq, + baseHead: state.checkpoint.baseHead, + }); +} + +export interface JournalAppendInput { + type: JournalEntryType; + key: string; + tenantRef: string; + accountRef?: string; + at: string; + journalUntil?: string; +} + +/** Appends one entry and moves the checkpoint to it, both durable. A rejected entry never reaches the lock. */ +export async function appendJournalEntry(journalDir: string, input: JournalAppendInput): Promise { + const untilOk = input.accountRef === undefined || (input.type === 'intent') === (input.journalUntil !== undefined); + if (!hasSingleJournalRef(input.tenantRef, input.accountRef) || !untilOk) throw new Error('invalid journal entry'); + await withJournalLock(journalDir, (token) => appendLocked(journalDir, token, { seq: 0, prev: '', ...input })); +} + +/** + * Checks under the writer lock that the journal accepts the next entry and + * rolls a lagging checkpoint forward. False for an invalid journal state. + */ +export function prepareJournalForWrite(journalDir: string): Promise { + return withJournalLock(journalDir, async () => (await loadJournalForWrite(journalDir)) !== null); +} + +export function createIdempotencyKey(): string { + return randomUUID(); +} + +/** + * Parses the raw retention-days setting. Only whole numbers from 1 to 13 are + * valid: with daily backups a copy then lives at most 14 days, the maximum copy + * lifetime the journal relies on. Anything else (including missing values) + * yields undefined so the caller stays unavailable instead of inventing a default. + */ +export function parseRetentionDays(value: unknown): number | undefined { + if (typeof value === 'number') { + if (!Number.isInteger(value) || value < 1 || value > 13) return undefined; + return value; + } + if (typeof value === 'string') { + if (!/^(?:[1-9]|1[0-3])$/.test(value.trim())) return undefined; + return Number.parseInt(value.trim(), 10); + } + return undefined; +} + +export interface PendingDeletionOutcome { + journalDir: string; + key: string; + tenantRef: string; + accountRef?: string; + /** Copy-lifetime limit of the intent (ISO time), needed by the fence. */ + journalUntil: string; +} + +const pendingOutcomes = new Map(); + +/** Remembers a written intent until the database transaction settles. */ +export function notePendingDeletionOutcome(tenantId: string, outcome: PendingDeletionOutcome): void { + const existing = pendingOutcomes.get(tenantId) ?? []; + existing.push(outcome); + pendingOutcomes.set(tenantId, existing); +} + +/** Takes the oldest remembered intent for a tenant, if one exists. */ +export function takePendingDeletionOutcome(tenantId: string): PendingDeletionOutcome | undefined { + const existing = pendingOutcomes.get(tenantId); + const next = existing?.shift(); + if (existing !== undefined && existing.length === 0) pendingOutcomes.delete(tenantId); + return next; +} + +export interface UndecidedIntentCounts { + committed: number; + aborted: number; + open: number; +} + +/** Keys that already have an outcome entry, that is anything but an intent. */ +function decidedKeys(entries: readonly JournalEntry[]): Set { + const decided = new Set(); + for (const entry of entries) { + if (entry.type !== 'intent') decided.add(entry.key); + } + return decided; +} + +/** An intent together with its copy-lifetime limit, which the fence needs. */ +type OpenIntent = JournalEntry & { journalUntil: string }; + +/** Intents of the journal that have no outcome entry yet, once per key. */ +function undecidedIntents(entries: readonly JournalEntry[]): OpenIntent[] { + const decided = decidedKeys(entries); + const seen = new Set(); + return entries.filter((entry): entry is OpenIntent => { + if (entry.type !== 'intent' || entry.journalUntil === undefined) return false; + if (decided.has(entry.key) || seen.has(entry.key)) return false; + seen.add(entry.key); + return true; + }); +} + +type IntentDecision = 'commit' | 'abort' | 'open'; + +/** Whether the database row of the key has a deletion time. Undefined when the database cannot answer. */ +async function databaseDeletedAt(prisma: PrismaClient, key: string): Promise { + try { + const row = await prisma.deletionJournal.findFirst({ + where: { idempotencyKey: key }, + select: { dbDeletedAt: true }, + }); + return Boolean(row?.dbDeletedAt); + } catch { + return undefined; + } +} + +/** + * Decides one intent without the writer lock: a deletion time commits it. While a restore is pending, + * an intent without deletion time stays open and is never fenced. Otherwise an intent younger than + * `abortAfterMs` stays open, and anything older is fenced. + */ +async function decideIntent( + prisma: PrismaClient, + intent: OpenIntent, + now: Date, + abortAfterMs: number, + journalDir: string, +): Promise { + const deleted = await databaseDeletedAt(prisma, intent.key); + if (deleted === undefined) return 'open'; + if (deleted) return 'commit'; + if (now.getTime() - Date.parse(intent.at) < abortAfterMs) return 'open'; + // Read right before the fence: a restore that starts during the pass keeps the intent open. + if (await isRestorePending(journalDir)) return 'open'; + return fenceUndecidedIntent(prisma, { key: intent.key, journalUntil: intent.journalUntil }); +} + +/** + * Decides intents without an outcome, for example after a crash between the file and the database. + * The writer lock covers file access only: open intents are read under it, decided without it, and + * appended under it after a fresh reload, skipping keys decided meanwhile. A database error keeps an intent open. + * A restore marker is checked right before each fence and each abort; while it is pending, only commits are decided. + */ +export async function decideJournalIntents(options: { + prisma: PrismaClient; + journalDir: string; + now: Date; + abortAfterMs: number; +}): Promise { + const { prisma, journalDir, now, abortAfterMs } = options; + const intents = await withJournalLock(journalDir, async () => { + const state = await loadJournalForWrite(journalDir); + if (state === null) throw new JournalUnavailableError(); + return undecidedIntents(state.entries); + }); + const counts: UndecidedIntentCounts = { committed: 0, aborted: 0, open: 0 }; + const decisions: { intent: OpenIntent; outcome: 'commit' | 'abort' }[] = []; + for (const intent of intents) { + const decision = await decideIntent(prisma, intent, now, abortAfterMs, journalDir); + if (decision === 'open') counts.open += 1; + else decisions.push({ intent, outcome: decision }); + } + if (decisions.length === 0) return counts; + return withJournalLock(journalDir, async (token) => { + const state = await loadJournalForWrite(journalDir); + if (state === null) throw new JournalUnavailableError(); + const decided = decidedKeys(state.entries); + for (const { intent, outcome } of decisions) { + if (decided.has(intent.key)) continue; + if (outcome === 'abort' && (await isRestorePending(journalDir))) { + counts.open += 1; + continue; + } + await appendLocked(journalDir, token, { + seq: 0, + prev: '', + type: outcome, + key: intent.key, + ...journalRefs(intent), + at: now.toISOString(), + }); + if (outcome === 'commit') counts.committed += 1; + else counts.aborted += 1; + } + return counts; + }); +} + +/** Writes the commit for a known intent. Never throws. */ +export async function recordPendingOutcome(pending: PendingDeletionOutcome): Promise { + try { + await appendJournalEntry(pending.journalDir, { + type: 'commit', + key: pending.key, + ...journalRefs(pending), + at: new Date().toISOString(), + }); + } catch { + // A missing outcome is healed by the next reconciliation. + } +} + +/** + * Records the transaction outcome for a remembered intent. Never throws: + * the database already decided, and a missing outcome is healed by the next + * reconciliation. + */ +export async function recordDeletionOutcome(tenantId: string, _outcome: 'commit'): Promise { + const pending = takePendingDeletionOutcome(tenantId); + if (pending === undefined) return; + await recordPendingOutcome(pending); +} + +/** + * Records the outcome after a failed database transaction. The error may have been raised after the + * COMMIT was sent, so the database decides first: a recorded deletion time commits the intent. + * Otherwise the fence decides, unless a restore is pending. An open intent is left for reconciliation. Never throws. + */ +export async function recordDeletionFailure(prisma: PrismaClient, tenantId: string): Promise { + const pending = takePendingDeletionOutcome(tenantId); + if (pending === undefined) return; + await recordPendingFailure(prisma, pending); +} + +/** Failure outcome for a known intent; recordDeletionFailure delegates here after its take. */ +export async function recordPendingFailure(prisma: PrismaClient, pending: PendingDeletionOutcome): Promise { + const outcome = await failedIntentOutcome(prisma, pending); + if (outcome === 'open' || (outcome === 'abort' && (await isRestorePending(pending.journalDir)))) { + logger.warn({ event: 'tenant_deletion.intent_left_open' }); + return; + } + try { + await appendJournalEntry(pending.journalDir, { + type: outcome, + key: pending.key, + ...journalRefs(pending), + at: new Date().toISOString(), + }); + } catch { + // A missing outcome is healed by the next reconciliation. + } +} + +/** Database row first. Then the fence decides, unless a restore is pending: the intent stays open. */ +async function failedIntentOutcome(prisma: PrismaClient, pending: PendingDeletionOutcome): Promise { + if ((await databaseDeletedAt(prisma, pending.key)) === true) return 'commit'; + if (await isRestorePending(pending.journalDir)) return 'open'; + return fenceUndecidedIntent(prisma, { key: pending.key, journalUntil: pending.journalUntil }); +} diff --git a/apps/server/src/services/tenantDeletionJournalCompaction.test.ts b/apps/server/src/services/tenantDeletionJournalCompaction.test.ts new file mode 100644 index 00000000..f712aace --- /dev/null +++ b/apps/server/src/services/tenantDeletionJournalCompaction.test.ts @@ -0,0 +1,269 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + CHECKPOINT_FILE, + COMPACT_CHECKPOINT_FILE, + COMPACT_JOURNAL_FILE, + JOURNAL_FILE, + appendJournalEntry, + loadJournal, +} from './tenantDeletionJournal.js'; +import type { JournalEntryType, LoadedJournal } from './tenantDeletionJournal.js'; +import { + compactJournalPrefix, + readJournalSnapshot, + removeCompactionLeftovers, +} from './tenantDeletionJournalCompaction.js'; + +const TENANT_REF = 'tenant-ref-1'; +const KEY_A = 'deletion-key-a'; +const KEY_B = 'deletion-key-b'; +const KEY_X = 'deletion-key-x'; +const AT = '2026-03-01T10:00:00.000Z'; +const JOURNAL_UNTIL = '2026-03-02T10:00:00.000Z'; +const LIFECYCLE: JournalEntryType[] = ['intent', 'commit', 'completed']; +const PAIR: JournalEntryType[] = ['intent', 'commit']; + +interface JournalPaths { + journal: string; + checkpoint: string; + compactJournal: string; + compactCheckpoint: string; +} + +const createdDirs: string[] = []; + +afterEach(async () => { + await Promise.all(createdDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); +}); + +async function createJournalDir(): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'tenant-journal-compaction-')); + createdDirs.push(dir); + return dir; +} + +function journalPaths(dir: string): JournalPaths { + return { + journal: path.join(dir, JOURNAL_FILE), + checkpoint: path.join(dir, CHECKPOINT_FILE), + compactJournal: path.join(dir, COMPACT_JOURNAL_FILE), + compactCheckpoint: path.join(dir, COMPACT_CHECKPOINT_FILE), + }; +} + +/** Appends the entries of one key through the production writer, in the given order. */ +async function appendEntries(dir: string, key: string, types: JournalEntryType[]): Promise { + for (const type of types) { + await appendJournalEntry(dir, { + type, + key, + tenantRef: TENANT_REF, + at: AT, + ...(type === 'intent' ? { journalUntil: JOURNAL_UNTIL } : {}), + }); + } +} + +async function readText(filePath: string): Promise { + return fs.readFile(filePath, 'utf8'); +} + +async function exists(filePath: string): Promise { + try { + await fs.access(filePath); + return true; + } catch { + return false; + } +} + +/** Splits journal text into lines, each line keeping its trailing newline. */ +function splitLines(text: string): string[] { + return text.match(/[^\n]*\n/g) ?? []; +} + +/** Expected hash of a journal line, computed here and not with the product code. */ +function expectedLineHash(line: string): string { + return createHash('sha256').update(line, 'utf8').digest('hex'); +} + +async function loadRequired(dir: string): Promise { + const state = await loadJournal(dir); + if (state === null) throw new Error('journal is not loadable'); + return state; +} + +describe('compactJournalPrefix', () => { + it('drops a removable key prefix and keeps the remaining lines byte-identical', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, LIFECYCLE); + await appendEntries(dir, KEY_B, PAIR); + const before = await loadRequired(dir); + const originalLines = splitLines(await readText(paths.journal)); + expect(originalLines).toHaveLength(5); + + const result = await compactJournalPrefix(dir, (key) => key === KEY_A); + + expect(result).toEqual({ removedKeys: [KEY_A] }); + expect(await readText(paths.journal)).toBe(originalLines.slice(3).join('')); + const after = await loadRequired(dir); + expect(after.entries.map((entry) => entry.key)).toEqual([KEY_B, KEY_B]); + expect(after.checkpoint).toEqual({ + seq: before.checkpoint.seq, + head: before.checkpoint.head, + baseSeq: 3, + baseHead: expectedLineHash(originalLines[2]), + }); + expect(await exists(paths.compactJournal)).toBe(false); + expect(await exists(paths.compactCheckpoint)).toBe(false); + }); + + it('leaves both files untouched when the first journal key is kept', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, LIFECYCLE); + await appendEntries(dir, KEY_B, PAIR); + const journalBefore = await readText(paths.journal); + const checkpointBefore = await readText(paths.checkpoint); + + const result = await compactJournalPrefix(dir, (key) => key === KEY_B); + + expect(result).toEqual({ removedKeys: [] }); + expect(await readText(paths.journal)).toBe(journalBefore); + expect(await readText(paths.checkpoint)).toBe(checkpointBefore); + expect(await exists(paths.compactJournal)).toBe(false); + expect(await exists(paths.compactCheckpoint)).toBe(false); + }); + + it('keeps a removable key that still has a line behind a kept key', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, ['intent']); + await appendEntries(dir, KEY_B, ['intent']); + await appendEntries(dir, KEY_A, ['commit']); + const journalBefore = await readText(paths.journal); + const checkpointBefore = await readText(paths.checkpoint); + + const result = await compactJournalPrefix(dir, (key) => key === KEY_A); + + expect(result).toEqual({ removedKeys: [] }); + expect(await readText(paths.journal)).toBe(journalBefore); + expect(await readText(paths.checkpoint)).toBe(checkpointBefore); + expect(await exists(paths.compactJournal)).toBe(false); + }); +}); + +describe('compactJournalPrefix on a fully removable journal', () => { + it('empties the journal and keeps the chain appendable from the new base', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, LIFECYCLE); + const originalLines = splitLines(await readText(paths.journal)); + + const result = await compactJournalPrefix(dir, (key) => key === KEY_A); + + expect(result).toEqual({ removedKeys: [KEY_A] }); + expect(await readText(paths.journal)).toBe(''); + const emptied = await loadRequired(dir); + expect(emptied.entries).toHaveLength(0); + expect(emptied.checkpoint.baseSeq).toBe(3); + expect(emptied.checkpoint.seq).toBe(emptied.checkpoint.baseSeq); + expect(emptied.checkpoint.baseHead).toBe(expectedLineHash(originalLines[2])); + expect(emptied.checkpoint.head).toBe(emptied.checkpoint.baseHead); + + await appendEntries(dir, KEY_B, ['intent']); + + const appended = await loadRequired(dir); + expect(appended.entries).toHaveLength(1); + expect(appended.entries[0]).toMatchObject({ + seq: emptied.checkpoint.baseSeq + 1, + prev: emptied.checkpoint.baseHead, + key: KEY_B, + }); + expect(appended.checkpoint.baseSeq).toBe(3); + }); +}); + +describe('readJournalSnapshot after an interrupted compaction', () => { + it('adopts the compact checkpoint after a crash between the two renames', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, LIFECYCLE); + await appendEntries(dir, KEY_B, PAIR); + const oldCheckpoint = await readText(paths.checkpoint); + await compactJournalPrefix(dir, (key) => key === KEY_A); + // The compaction ran to completion. Rebuild the state of a crash after the + // journal rename: the new checkpoint is back in its compact file, the old one is restored. + const compactedJournal = await readText(paths.journal); + const compactCheckpoint = await readText(paths.checkpoint); + await fs.writeFile(paths.checkpoint, oldCheckpoint); + await fs.writeFile(paths.compactCheckpoint, compactCheckpoint); + + const snapshot = await readJournalSnapshot(dir); + + expect(snapshot).not.toBeNull(); + expect(snapshot?.entries.map((entry) => entry.key)).toEqual([KEY_B, KEY_B]); + const lines = splitLines(compactedJournal); + expect(snapshot?.endHead).toBe(expectedLineHash(lines[lines.length - 1])); + expect(await readText(paths.checkpoint)).toBe(compactCheckpoint); + expect(await exists(paths.compactCheckpoint)).toBe(false); + expect(await readText(paths.journal)).toBe(compactedJournal); + }); +}); + +describe('removeCompactionLeftovers', () => { + it('ignores a stale compact checkpoint next to a valid checkpoint and removes both leftovers', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, LIFECYCLE); + const staleCheckpoint = await readText(paths.checkpoint); + await appendEntries(dir, KEY_B, PAIR); + await fs.writeFile(paths.compactCheckpoint, staleCheckpoint); + await fs.copyFile(paths.journal, paths.compactJournal); + const journalBefore = await readText(paths.journal); + const checkpointBefore = await readText(paths.checkpoint); + + const snapshot = await readJournalSnapshot(dir); + + expect(snapshot?.entries).toHaveLength(5); + expect(await readText(paths.checkpoint)).toBe(checkpointBefore); + expect(await exists(paths.compactCheckpoint)).toBe(true); + + expect(await removeCompactionLeftovers(dir)).toBe(true); + expect(await exists(paths.compactCheckpoint)).toBe(false); + expect(await exists(paths.compactJournal)).toBe(false); + expect(await readText(paths.journal)).toBe(journalBefore); + expect(await readText(paths.checkpoint)).toBe(checkpointBefore); + }); + + it('keeps everything in place when neither checkpoint fits the journal', async () => { + const dir = await createJournalDir(); + const paths = journalPaths(dir); + await appendEntries(dir, KEY_A, LIFECYCLE); + await appendEntries(dir, KEY_B, PAIR); + const foreignLong = await createJournalDir(); + await appendEntries(foreignLong, KEY_X, PAIR); + const foreignShort = await createJournalDir(); + await appendEntries(foreignShort, KEY_X, ['intent']); + await fs.copyFile(path.join(foreignLong, CHECKPOINT_FILE), paths.checkpoint); + await fs.copyFile(path.join(foreignShort, CHECKPOINT_FILE), paths.compactCheckpoint); + await fs.copyFile(paths.journal, paths.compactJournal); + const journalBefore = await readText(paths.journal); + const checkpointBefore = await readText(paths.checkpoint); + const compactCheckpointBefore = await readText(paths.compactCheckpoint); + const compactJournalBefore = await readText(paths.compactJournal); + + expect(await readJournalSnapshot(dir)).toBeNull(); + expect(await removeCompactionLeftovers(dir)).toBe(false); + + expect(await readText(paths.journal)).toBe(journalBefore); + expect(await readText(paths.checkpoint)).toBe(checkpointBefore); + expect(await readText(paths.compactCheckpoint)).toBe(compactCheckpointBefore); + expect(await readText(paths.compactJournal)).toBe(compactJournalBefore); + }); +}); diff --git a/apps/server/src/services/tenantDeletionJournalCompaction.ts b/apps/server/src/services/tenantDeletionJournalCompaction.ts new file mode 100644 index 00000000..022fbd20 --- /dev/null +++ b/apps/server/src/services/tenantDeletionJournalCompaction.ts @@ -0,0 +1,164 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { assertLockHeld } from './tenantDeletionJournalLock.js'; +import { + CHECKPOINT_FILE, + COMPACT_CHECKPOINT_FILE, + COMPACT_JOURNAL_FILE, + JOURNAL_FILE, + loadJournalForWrite, + sha256Hex, + syncDirectoryBestEffort, + withJournalLock, + writeFileDurably, +} from './tenantDeletionJournal.js'; +import type { JournalEntry, LoadedJournal } from './tenantDeletionJournal.js'; + +/** + * Compacts the journal prefix that no longer has to be kept and removes the + * files an interrupted compaction leaves behind. Every function here runs under + * the journal writer lock. + * + * A compaction writes in four steps: + * (a) the compact checkpoint, describing the kept suffix; + * (b) the compact journal, holding only the kept suffix; + * (c) the compact journal is renamed over the journal; + * (d) the compact checkpoint is renamed over the checkpoint. + * Steps (a) and (b) are durable before the first rename, so a rename never + * exposes a file that is still unwritten. The journal is switched before the + * checkpoint: between (c) and (d) the checkpoint file still describes the old + * journal, which is gone, while the compact checkpoint describes the new journal + * exactly. The loader adopts that compact checkpoint in this case, so a crash in + * the window loses no kept entry. Reversing the renames would leave a checkpoint + * that fits neither file and no copy the loader can adopt. A crash before (c) + * leaves the old journal and checkpoint valid; the next writer removes the + * leftovers. + */ + +/** Journal state and the hash of its last line, read under the writer lock. */ +export interface JournalSnapshot { + entries: readonly JournalEntry[]; + endHead: string; +} + +/** Reads all entries under the writer lock. Only a checkpoint roll-forward can write. */ +export function readJournalSnapshot(journalDir: string): Promise { + return withJournalLock(journalDir, async () => { + const state = await loadJournalForWrite(journalDir); + if (state === null) return null; + return { entries: state.entries, endHead: state.endHead }; + }); +} + +/** Deletes the files of an interrupted compaction. They are never trusted. */ +async function removeCompactFiles(journalDir: string): Promise { + await fs.rm(path.join(journalDir, COMPACT_JOURNAL_FILE), { force: true }); + await fs.rm(path.join(journalDir, COMPACT_CHECKPOINT_FILE), { force: true }); +} + +/** + * Removes the files of an interrupted compaction under the writer lock. Returns + * false and removes nothing when the journal is unavailable, because a compact + * checkpoint may be the only copy that fits a journal that is already switched. + */ +export function removeCompactionLeftovers(journalDir: string): Promise { + return withJournalLock(journalDir, async () => { + const state = await loadJournalForWrite(journalDir); + if (state === null) return false; + await removeCompactFiles(journalDir); + await syncDirectoryBestEffort(journalDir); + return true; + }); +} + +/** Groups the positions of the entries by key, in journal order. */ +function indexesByKey(entries: readonly JournalEntry[]): Map { + const groups = new Map(); + entries.forEach((entry, index) => { + const group = groups.get(entry.key) ?? []; + group.push(index); + groups.set(entry.key, group); + }); + return groups; +} + +/** + * Finds the longest journal prefix that holds only removable keys completely. + * The cut starts before the first line of a kept key and moves back while a + * key still has lines on both sides of it, until no key straddles the cut. + */ +function removablePrefix( + entries: readonly JournalEntry[], + isRemovable: (key: string, entries: readonly JournalEntry[]) => boolean, +): { cut: number; removedKeys: string[] } { + const groups = indexesByKey(entries); + const kept = new Set(); + for (const [key, indexes] of groups) { + if ( + !isRemovable( + key, + indexes.map((index) => entries[index]), + ) + ) + kept.add(key); + } + const firstKept = entries.findIndex((entry) => kept.has(entry.key)); + let cut = firstKept === -1 ? entries.length : firstKept; + let moved = true; + while (moved) { + let next = cut; + for (const indexes of groups.values()) { + if (indexes[0] < cut && indexes[indexes.length - 1] >= cut) next = Math.min(next, indexes[0]); + } + moved = next < cut; + cut = next; + } + const removedKeys = [...new Set(entries.slice(0, cut).map((entry) => entry.key))]; + return { cut, removedKeys }; +} + +/** Steps (a) and (b): the compact checkpoint first, then the kept suffix as compact journal. */ +async function writeCompactCopies(journalDir: string, token: string, state: LoadedJournal, cut: number): Promise { + const { entries, lines, endHead } = state; + const baseSeq = entries[cut - 1].seq; + const baseHead = sha256Hex(lines[cut - 1]); + const checkpoint = + entries.length > cut ? { seq: entries[entries.length - 1].seq, head: endHead } : { seq: baseSeq, head: baseHead }; + await writeFileDurably( + path.join(journalDir, COMPACT_CHECKPOINT_FILE), + JSON.stringify({ v: 1, ...checkpoint, baseSeq, baseHead }), + ); + await writeFileDurably(path.join(journalDir, COMPACT_JOURNAL_FILE), lines.slice(cut).join('')); + await assertLockHeld(journalDir, token); +} + +/** Steps (c) and (d): the journal is switched first, the checkpoint second. */ +async function switchToCompactFiles(journalDir: string, token: string): Promise { + await fs.rename(path.join(journalDir, COMPACT_JOURNAL_FILE), path.join(journalDir, JOURNAL_FILE)); + await syncDirectoryBestEffort(journalDir); + await assertLockHeld(journalDir, token); + await fs.rename(path.join(journalDir, COMPACT_CHECKPOINT_FILE), path.join(journalDir, CHECKPOINT_FILE)); + await syncDirectoryBestEffort(journalDir); +} + +/** + * Drops the journal prefix whose keys are all removable, as decided by + * `isRemovable(key, entries of that key)`. Leftovers of an earlier attempt are + * removed first. Returns null, with nothing removed, when the journal is + * unavailable. Writes no compact files when no prefix can be dropped. + */ +export function compactJournalPrefix( + journalDir: string, + isRemovable: (key: string, entries: readonly JournalEntry[]) => boolean, +): Promise<{ removedKeys: string[] } | null> { + return withJournalLock(journalDir, async (token) => { + const state = await loadJournalForWrite(journalDir); + if (state === null) return null; + await removeCompactFiles(journalDir); + const { cut, removedKeys } = removablePrefix(state.entries, isRemovable); + if (cut === 0) return { removedKeys }; + await writeCompactCopies(journalDir, token, state, cut); + await switchToCompactFiles(journalDir, token); + return { removedKeys }; + }); +} diff --git a/apps/server/src/services/tenantDeletionJournalLock.ts b/apps/server/src/services/tenantDeletionJournalLock.ts new file mode 100644 index 00000000..edfb54c8 --- /dev/null +++ b/apps/server/src/services/tenantDeletionJournalLock.ts @@ -0,0 +1,169 @@ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { logger } from '../logger.js'; + +/** + * Writer lock of the tenant deletion journal directory: a lock directory + * created atomically with mkdir, an owner token inside it, and takeover of + * an orphaned lock only by rename plus token check. + */ + +/** Lock directory of the journal; only one writer at a time. */ +const LOCK_DIR_NAME = 'journal.lock'; +/** File inside the lock directory that holds the token of the holder. */ +const LOCK_OWNER_FILE = 'owner'; +/** Longest a writer waits for the lock before the journal is unavailable. */ +const LOCK_WAIT_MS = 10_000; +/** A lock that is older than this counts as orphaned. */ +const LOCK_STALE_MS = 30_000; +/** Pause between two attempts to take the lock. */ +const LOCK_POLL_MS = 50; + +/** Thrown for any unreadable, unwritable or inconsistent journal state. */ +export class JournalUnavailableError extends Error { + constructor() { + super('tenant deletion journal is unavailable'); + this.name = 'JournalUnavailableError'; + } +} + +function lockDirPath(journalDir: string): string { + return path.join(journalDir, LOCK_DIR_NAME); +} + +function lockOwnerPath(lockDir: string): string { + return path.join(lockDir, LOCK_OWNER_FILE); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Reads the owner token; a missing or unreadable file counts as empty. */ +async function readOwnerToken(lockDir: string): Promise { + try { + return await fs.readFile(lockOwnerPath(lockDir), 'utf8'); + } catch { + return ''; + } +} + +/** + * Creates the lock directory. The non-recursive mkdir is atomic, so exactly + * one process wins. Returns false when the directory already exists; a + * missing or unwritable journal directory leaves the journal unavailable. + */ +async function tryCreateLockDir(lockDir: string): Promise { + try { + await fs.mkdir(lockDir); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false; + throw new JournalUnavailableError(); + } +} + +/** Writes the owner token of the holder and flushes it to disk. */ +async function writeOwnerToken(lockDir: string, token: string): Promise { + const handle = await fs.open(lockOwnerPath(lockDir), 'w'); + try { + await handle.writeFile(token, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Reads the modification time of the lock directory; null when it is gone. */ +async function statLockDir(lockDir: string): Promise<{ mtimeMs: number } | null> { + try { + const stats = await fs.stat(lockDir); + return { mtimeMs: stats.mtimeMs }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw new JournalUnavailableError(); + } +} + +/** + * Takes over a lock that has been orphaned for longer than the stale window. + * The lock directory is renamed aside first; only when the owner file inside + * the moved directory still holds the token that was judged stale, the moved + * directory is removed. Every takeover is logged; a foreign lock is never + * removed. + */ +async function takeOverStaleLock(lockDir: string, seen: string): Promise { + const moved = `${lockDir}.stale-${randomBytes(8).toString('hex')}`; + try { + await fs.rename(lockDir, moved); + } catch { + // Another process was faster and moved the lock itself. + return false; + } + const movedOwner = await readOwnerToken(moved); + if (movedOwner !== seen) { + // Not the lock that was judged: back off, keep the directory and do not + // move it back. + return false; + } + logger.warn({ event: 'tenant_delete.journal_lock_taken_over' }); + // Only the directory that this process moved aside is removed. + await fs.rm(moved, { recursive: true, force: true }).catch(() => undefined); + return true; +} + +/** + * Takes the write lock of the journal directory and returns the owner token. + * The lock is held until releaseLock is called. A lock that is older than the + * stale window is taken over; otherwise the writer waits for the holder. + */ +export async function acquireLock(journalDir: string): Promise { + const lockDir = lockDirPath(journalDir); + const token = `${process.pid}-${randomBytes(16).toString('hex')}`; + const deadline = Date.now() + LOCK_WAIT_MS; + for (;;) { + if (await tryCreateLockDir(lockDir)) { + try { + await writeOwnerToken(lockDir, token); + } catch { + // The lock was created but cannot carry the owner token: remove the + // own empty lock and report the journal as unavailable. + await fs.rm(lockDir, { recursive: true, force: true }).catch(() => undefined); + throw new JournalUnavailableError(); + } + return token; + } + const stats = await statLockDir(lockDir); + if (stats === null) continue; + if (Date.now() - stats.mtimeMs > LOCK_STALE_MS) { + const seen = await readOwnerToken(lockDir); + if (await takeOverStaleLock(lockDir, seen)) continue; + } + // The deadline also bounds a takeover that keeps failing. + if (Date.now() > deadline) throw new JournalUnavailableError(); + await sleep(LOCK_POLL_MS); + } +} + +/** + * Checks that the lock is still held with the own token. Every other state + * fails closed: the journal is unavailable. + */ +export async function assertLockHeld(journalDir: string, token: string): Promise { + const owner = await readOwnerToken(lockDirPath(journalDir)); + if (owner !== token) throw new JournalUnavailableError(); +} + +/** + * Releases the lock. The lock directory is only removed when the owner file + * still holds the own token; a foreign lock is never removed. + */ +export async function releaseLock(journalDir: string, token: string): Promise { + const lockDir = lockDirPath(journalDir); + const owner = await readOwnerToken(lockDir); + if (owner !== token) return; + // A lock that cannot be removed stays behind and is taken over as stale + // later; it must not mask the outcome of the append. + await fs.rm(lockDir, { recursive: true, force: true }).catch(() => undefined); +} diff --git a/apps/server/src/services/tenantDeletionPlanning.ts b/apps/server/src/services/tenantDeletionPlanning.ts new file mode 100644 index 00000000..900fe410 --- /dev/null +++ b/apps/server/src/services/tenantDeletionPlanning.ts @@ -0,0 +1,424 @@ +import { createHash } from 'node:crypto'; +import type { Prisma, PrismaClient } from '../generated/prisma/index.js'; +import { + TENANT_DELETION_PROTOCOL, + TenantDeletionContractError, + TenantDeletionJournalUnavailableError, + assertTenantDeletionProtocol, +} from './tenantDeletionContract.js'; +import type { + TenantDeletionOptions, + TenantDeletionPlanInput, + TenantDeletionTaskPlan, +} from './tenantDeletionContract.js'; +import { + JournalUnavailableError, + appendJournalEntry, + createIdempotencyKey, + decideJournalIntents, + notePendingDeletionOutcome, + parseRetentionDays, + prepareJournalForWrite, + type UndecidedIntentCounts, +} from './tenantDeletionJournal.js'; +import { isRestorePending } from './tenantDeletionRestoreMarker.js'; +import { runDeletionTasks } from './deletionTaskWorker.js'; +import type { DeletionTaskRunResult } from './deletionTaskWorker.js'; + +// Restore replay, re-exported for callers that load this module as the entry +// point of the tenant deletion services. +export { replayCommittedDeletions } from './tenantDeletionReplay.js'; + +// A tenant with large maps deletes tens of thousands of map chunks in one transaction; the Prisma default of 5 s is not enough. +export const TENANT_DELETION_TX_TIMEOUT_MS = 120_000; +export const TENANT_DELETION_TX_MAX_WAIT_MS = 10_000; +export const UNDECIDED_INTENT_RESERVE_MS = 120_000; +export function undecidedIntentAbortAfterMs(): number { + return TENANT_DELETION_TX_TIMEOUT_MS + TENANT_DELETION_TX_MAX_WAIT_MS + UNDECIDED_INTENT_RESERVE_MS; +} + +/** Decides undecided journal intents with the abort threshold of this module. */ +export function decideUndecidedIntents(options: { + prisma: PrismaClient; + journalDir: string; + now: Date; +}): Promise { + return decideJournalIntents({ ...options, abortAfterMs: undecidedIntentAbortAfterMs() }); +} + +/** + * Managed tenant deletion plan. + * + * The host first resolves the contract state, then determines exactly one internal + * transaction time, validates the internal plan completely before the first + * write, writes journal and tasks, and only then calls the EE cleanup. + * Every validation error is sanitized (`retention_journal_unavailable`), + * while DB and callback errors propagate unchanged. No network, worker, + * or provider call; no fallback, no default, no deadline from env. + */ + +/** Validated callbacks; `undefined` means a bare OSS deletion without journal. */ +export interface ManagedTenantDeletionCallbacks { + prepareInTx: NonNullable; + cleanupInTx: NonNullable; + transactionTime?: Date; +} + +/** Result of the preparation; the time is a separate clone of the caller's value. */ +export interface TenantDeletionPrepared { + journalId: string; + transactionTime: Date; +} + +interface ValidatedTaskPlan { + kind: string; + targetSystem: string; + objectId: string; + objectGeneration: string; + storageKey?: string; +} + +interface ValidatedPlan { + idempotencyKey: string; + policyVersion: string; + journalUntilMs: number; + tasks: ValidatedTaskPlan[]; +} + +/** + * Only checks the contract state; calls no callbacks and reads no DB. + * Bare empty OSS options yield `undefined`. + */ +export function resolveTenantDeletionOptions( + options: TenantDeletionOptions = {}, +): ManagedTenantDeletionCallbacks | undefined { + const { deletionProtocol, prepareInTx, cleanupInTx, transactionTime } = options; + if ( + deletionProtocol === undefined && + prepareInTx === undefined && + cleanupInTx === undefined && + transactionTime === undefined + ) { + return undefined; + } + assertTenantDeletionProtocol(deletionProtocol); + if (typeof prepareInTx !== 'function' || typeof cleanupInTx !== 'function') { + throw new TenantDeletionContractError(); + } + return { prepareInTx, cleanupInTx, transactionTime }; +} + +/** Reads ms via the Date intrinsic; strings, numbers and invalid dates yield null. */ +function getTimeMs(value: unknown): number | null { + try { + const ms: unknown = Date.prototype.getTime.call(value); + return typeof ms === 'number' && Number.isFinite(ms) ? ms : null; + } catch { + return null; + } +} + +/** Internal transaction time: explicit test input, or DB time read via this host tx. */ +export async function readTransactionTimeMs(tx: Prisma.TransactionClient, explicit: Date | undefined): Promise { + if (explicit !== undefined) { + const ms = getTimeMs(explicit); + if (ms === null) throw new TenantDeletionJournalUnavailableError(); + return ms; + } + const rows = await tx.$queryRaw>` + SELECT transaction_timestamp() AS "transactionTime"`; + const ms = getTimeMs(rows[0]?.transactionTime); + if (ms === null) throw new TenantDeletionJournalUnavailableError(); + return ms; +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0; +} + +/** Validates a single task descriptor and copies it into its own values. */ +function validateTaskPlan(task: unknown): ValidatedTaskPlan { + if (typeof task !== 'object' || task === null) throw new TenantDeletionJournalUnavailableError(); + const record = task as Record; + const { kind, targetSystem, objectId, objectGeneration, storageKey } = record; + if (!isNonEmptyString(kind) || kind.length > 64) throw new TenantDeletionJournalUnavailableError(); + if (!isNonEmptyString(targetSystem) || targetSystem.length > 64) { + throw new TenantDeletionJournalUnavailableError(); + } + if (!isNonEmptyString(objectId)) throw new TenantDeletionJournalUnavailableError(); + if (!isNonEmptyString(objectGeneration)) throw new TenantDeletionJournalUnavailableError(); + if (storageKey !== undefined && !isNonEmptyString(storageKey)) { + throw new TenantDeletionJournalUnavailableError(); + } + return storageKey === undefined + ? { kind, targetSystem, objectId, objectGeneration } + : { kind, targetSystem, objectId, objectGeneration, storageKey }; +} + +/** Validates the plan completely before the first write; all errors are sanitized. */ +function validatePlanInput(plan: unknown, internalMs: number): ValidatedPlan { + if (typeof plan !== 'object' || plan === null) throw new TenantDeletionJournalUnavailableError(); + const record = plan as Record; + const { idempotencyKey, policyVersion, journalUntil, tasks } = record; + if (!isNonEmptyString(idempotencyKey)) throw new TenantDeletionJournalUnavailableError(); + if (!isNonEmptyString(policyVersion)) throw new TenantDeletionJournalUnavailableError(); + if (!Array.isArray(tasks)) throw new TenantDeletionJournalUnavailableError(); + const journalUntilMs = getTimeMs(journalUntil); + if (journalUntilMs === null || journalUntilMs <= internalMs) { + throw new TenantDeletionJournalUnavailableError(); + } + return { idempotencyKey, policyVersion, journalUntilMs, tasks: tasks.map(validateTaskPlan) }; +} + +/** Deduplicates per tuple; a differing storage key is a validation error. */ +function dedupeTaskPlans(tasks: ValidatedTaskPlan[]): ValidatedTaskPlan[] { + const seen = new Map(); + for (const task of tasks) { + const key = JSON.stringify([task.kind, task.targetSystem, task.objectId, task.objectGeneration]); + const existing = seen.get(key); + if (existing === undefined) { + seen.set(key, task); + } else if (existing.storageKey !== task.storageKey) { + throw new TenantDeletionJournalUnavailableError(); + } + } + return [...seen.values()]; +} + +/** Stable dedupe key across journal and task identity. */ +export function dedupeKeyFor(journalId: string, task: ValidatedTaskPlan): string { + return createHash('sha256') + .update(JSON.stringify([journalId, task.kind, task.targetSystem, task.objectId, task.objectGeneration])) + .digest('hex'); +} + +/** Writes the journal (no upsert) and the tasks; empty task lists are valid. */ +async function writeJournalAndTasks( + tx: Prisma.TransactionClient, + tenantId: string, + accountRefs: readonly string[], + plan: ValidatedPlan, + internalMs: number, +): Promise { + const journal = await tx.deletionJournal.create({ + data: { + idempotencyKey: plan.idempotencyKey, + scope: 'tenant', + tenantRef: tenantId, + accountRefs: [...new Set(accountRefs)].sort(), + objectRefs: [...new Set(plan.tasks.map((task) => task.objectId))].sort(), + policyVersion: plan.policyVersion, + requestedAt: new Date(internalMs), + journalUntil: new Date(plan.journalUntilMs), + }, + }); + if (plan.tasks.length > 0) { + await tx.deletionTask.createMany({ + data: plan.tasks.map((task) => ({ + journalId: journal.id, + kind: task.kind, + targetSystem: task.targetSystem, + objectId: task.objectId, + objectGeneration: task.objectGeneration, + storageKey: task.storageKey, + dedupeKey: dedupeKeyFor(journal.id, task), + status: 'pending', + attempts: 0, + nextAttemptAt: new Date(internalMs), + })), + }); + } + return journal.id; +} + +/** + * Prepares the managed deletion: determine the time, fetch the plan, + * validate, write journal/tasks, then call the EE cleanup. Bare + * calls are a no-op. DB and callback errors propagate unchanged. + */ +export async function prepareTenantDeletionInTx( + tx: Prisma.TransactionClient, + tenantId: string, + accountRefs: readonly string[], + managed: ManagedTenantDeletionCallbacks | undefined, +): Promise { + if (managed === undefined) return undefined; + const internalMs = await readTransactionTimeMs(tx, managed.transactionTime); + const plan = await managed.prepareInTx(tx, { + deletionProtocol: TENANT_DELETION_PROTOCOL, + transactionTime: new Date(internalMs), + }); + if (plan === undefined) throw new TenantDeletionJournalUnavailableError(); + const validated = validatePlanInput(plan, internalMs); + const journalId = await writeJournalAndTasks( + tx, + tenantId, + accountRefs, + { ...validated, tasks: dedupeTaskPlans(validated.tasks) }, + internalMs, + ); + await managed.cleanupInTx(tx, { + deletionProtocol: TENANT_DELETION_PROTOCOL, + transactionTime: new Date(internalMs), + journalId, + }); + return { journalId, transactionTime: new Date(internalMs) }; +} + +/** Policy marker stored on every journal row created through the resolver. */ +const JOURNAL_POLICY_VERSION = 'tenant-deletion-journal-v1'; + +/** Fixed object generation for file tasks: files carry no version counter. */ +export const FILE_TASK_GENERATION = '1'; + +/** + * Maximum lifetime of any backup copy. A journal intent stays valid this long + * after its deletion transaction, independent of the configured retention, so + * a restored copy can always be matched against the journal. + */ +export const TENANT_DELETION_JOURNAL_MAX_COPY_LIFETIME_MS = 14 * 24 * 60 * 60 * 1000; + +/** Options for the file-backed deletion plan resolver. */ +export interface JournalPlanResolverOptions { + prisma: PrismaClient; + journalDir: string; + retentionDays: unknown; + /** Only for the restore replay tool: lets the resolver run while a restore marker is present. */ + allowDuringRestoreReplay?: boolean; +} + +/** Plan callback handed to the enterprise deletion route. */ +export type JournalResolvePlan = ( + tx: Prisma.TransactionClient, + input: { tenantId: string; transactionTime: Date }, +) => Promise; + +interface JournalTaskSource { + targetSystem: string; + objectIds: string[]; + storageKey?: string; +} + +function toFileTasks(sources: JournalTaskSource[]): TenantDeletionTaskPlan[] { + const tasks: TenantDeletionTaskPlan[] = []; + for (const source of sources) { + for (const objectId of source.objectIds) { + tasks.push( + source.storageKey === undefined + ? { + kind: 'file', + targetSystem: source.targetSystem, + objectId, + objectGeneration: FILE_TASK_GENERATION, + } + : { + kind: 'file', + targetSystem: source.targetSystem, + objectId, + objectGeneration: FILE_TASK_GENERATION, + storageKey: source.storageKey, + }, + ); + } + } + return tasks; +} + +/** + * Builds a resolver that persists every deletion intent to the file journal + * before returning the plan. Unavailable journal state (missing or read-only + * directory, broken chain or checkpoint, invalid retention setting) yields + * undefined so the route answers 409; database errors propagate. While a restore is pending, every call + * yields undefined as well, unless the restore replay tool allows it. + */ +export async function createJournalPlanResolver(options: JournalPlanResolverOptions): Promise { + const { prisma, journalDir, allowDuringRestoreReplay } = options; + const retentionDays = parseRetentionDays(options.retentionDays); + try { + await decideUndecidedIntents({ prisma, journalDir, now: new Date() }); + } catch (error) { + if (!(error instanceof JournalUnavailableError)) throw error; + } + + return async (tx, input) => { + if (allowDuringRestoreReplay !== true && (await isRestorePending(journalDir))) return undefined; + if (retentionDays === undefined) return undefined; + const transactionMs = getTimeMs(input.transactionTime); + if (transactionMs === null) return undefined; + try { + if (!(await prepareJournalForWrite(journalDir))) return undefined; + const tenant = await tx.tenant.findUnique({ + where: { id: input.tenantId }, + select: { slug: true }, + }); + if (tenant === null) return undefined; + const [assetPacks, avatarPacks, customAvatars] = await Promise.all([ + tx.assetPack.findMany({ where: { tenantId: input.tenantId }, select: { uuid: true } }), + tx.avatarPack.findMany({ where: { tenantId: input.tenantId }, select: { uuid: true } }), + tx.customAvatar.findMany({ where: { tenantId: input.tenantId }, select: { uuid: true } }), + ]); + const journalUntil = new Date(transactionMs + TENANT_DELETION_JOURNAL_MAX_COPY_LIFETIME_MS); + const key = createIdempotencyKey(); + await appendJournalEntry(journalDir, { + type: 'intent', + key, + tenantRef: input.tenantId, + at: new Date(transactionMs).toISOString(), + journalUntil: journalUntil.toISOString(), + }); + notePendingDeletionOutcome(input.tenantId, { + journalDir, + key, + tenantRef: input.tenantId, + journalUntil: journalUntil.toISOString(), + }); + return { + idempotencyKey: key, + policyVersion: JOURNAL_POLICY_VERSION, + journalUntil, + tasks: toFileTasks([ + { targetSystem: 'asset_packs', objectIds: assetPacks.map((pack) => pack.uuid) }, + { targetSystem: 'avatar_packs', objectIds: avatarPacks.map((pack) => pack.uuid) }, + { targetSystem: 'custom_avatars', objectIds: customAvatars.map((avatar) => avatar.uuid) }, + { targetSystem: 'npc_media', objectIds: [input.tenantId], storageKey: tenant.slug }, + ]), + }; + } catch (error) { + if (error instanceof JournalUnavailableError) return undefined; + throw error; + } + }; +} + +/** + * After the tenant DELETE, records the journal state: no + * completed proof; tasks stay pending. Bare calls are a no-op. + */ +export async function completeTenantDeletionInTx( + tx: Prisma.TransactionClient, + prepared: TenantDeletionPrepared | undefined, +): Promise { + if (prepared === undefined) return; + await tx.deletionJournal.update({ + where: { id: prepared.journalId }, + data: { + dbDeletedAt: new Date(Date.prototype.getTime.call(prepared.transactionTime)), + status: 'cleanup_pending', + }, + }); +} + +/** Runs one pass over the due deletion tasks with the journal limits of this module. */ +export function runDeletionTasksOnce(options: { + prisma: PrismaClient; + journalDir: string; + now: Date; + maxAttempts?: number; + leaseMs?: number; +}): Promise { + return runDeletionTasks({ + ...options, + maxCopyLifetimeMs: TENANT_DELETION_JOURNAL_MAX_COPY_LIFETIME_MS, + abortAfterMs: undecidedIntentAbortAfterMs(), + }); +} diff --git a/apps/server/src/services/tenantDeletionReplay.ts b/apps/server/src/services/tenantDeletionReplay.ts new file mode 100644 index 00000000..959cd91c --- /dev/null +++ b/apps/server/src/services/tenantDeletionReplay.ts @@ -0,0 +1,314 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; +import { + appendJournalEntry, + journalRefs, + loadJournal, + type JournalEntry, + type JournalEntryType, +} from './tenantDeletionJournal.js'; +import { accountExists, replayAccountDeletions, type AccountReplayResult } from './accountDeletionReplay.js'; + +/** + * Restore replay for tenant deletions. + * + * After an older database copy has been restored, tenants deleted after the + * copy was taken exist again. The deletion journal lives outside the + * database and still records those deletions. The replay deletes such + * tenants again, strictly by tenant id and never by slug, and closes the old + * journal keys once the tenant is gone and a newer deletion covers it. + * + * Account deletions follow the same rules through accountDeletionReplay.ts, + * but only with a deletion callback for accounts. Without one, open account + * intents still block the replay, and account entries are never written to. + * + * Open intents of the restored timeline may have committed before the + * restore; a missing database row proves nothing here. They block the replay + * until an operator decides each key. Nothing is deleted while the journal is + * invalid or such an intent is open. + */ + +export type ReplayDecision = 'delete' | 'keep'; + +export interface UndecidedReplayIntent { + key: string; + tenantRef: string; + at: string; + /** False for account intents, which name no tenant. */ + tenantExists: boolean; + /** Account of an account intent; tenantRef is empty then. */ + accountRef?: string; + /** Whether that account exists in the restored database; account intents only. */ + accountExists?: boolean; +} + +export interface ReplayCommittedDeletionsOptions { + prisma: PrismaClient; + journalDir: string; + /** Creation time of the restored copy; commits at or after it are replayed. */ + since: Date; + /** Deletes one tenant by id through the managed deletion path. */ + deleteTenant: (tenantId: string) => Promise; + /** Deletes one account by user id. Without it, account entries are never written, replayed or decided. */ + deleteAccount?: (userId: string) => Promise; + /** Last journal sequence before the restore; later open intents stem from the replay itself. */ + restoredJournalSeq?: number | null; + /** Operator decisions for open intents, by journal key. */ + decisions?: ReadonlyMap; +} + +export interface ReplayCommittedDeletionsResult { + blocked: null | 'undecided_intent' | 'journal_invalid'; + /** Tenant ids deleted by this run. */ + replayed: string[]; + /** Open intents that block the replay. */ + undecided: UndecidedReplayIntent[]; + /** Tenant journal keys closed with a completed entry by this run. */ + closed: string[]; + /** User ids of accounts deleted by this run; empty without deleteAccount. */ + replayedAccounts: string[]; + /** Account journal keys closed with a completed entry by this run. */ + closedAccounts: string[]; + /** Tenants that lost their last owner through an account deleted by this run. */ + ownerlessTenants: string[]; +} + +export class ReplayDecisionError extends Error { + readonly code = 'replay_decision_invalid'; + + constructor() { + super('replay decision does not match an open intent'); + this.name = 'ReplayDecisionError'; + } +} + +interface KeyState { + intent?: JournalEntry; + commit?: JournalEntry; + abort?: JournalEntry; + completed?: JournalEntry; +} + +export type JournalKeys = Map; + +/** Journal entry of an account: it names the account by accountRef and no tenant. */ +export type AccountJournalEntry = JournalEntry & { accountRef: string }; + +export function isAccountEntry(entry: JournalEntry): entry is AccountJournalEntry { + return entry.accountRef !== undefined; +} + +export async function loadKeys(journalDir: string): Promise { + const journal = await loadJournal(journalDir); + if (!journal) return null; + const keys: JournalKeys = new Map(); + for (const entry of journal.entries) { + const state = keys.get(entry.key) ?? {}; + state[entry.type] ??= entry; + keys.set(entry.key, state); + } + return keys; +} + +function isOpen(state: KeyState): boolean { + return state.intent !== undefined && !state.commit && !state.abort && !state.completed; +} + +function openIntents(keys: JournalKeys): JournalEntry[] { + const open: JournalEntry[] = []; + for (const state of keys.values()) { + if (isOpen(state) && state.intent) open.push(state.intent); + } + return open.sort((a, b) => a.seq - b.seq); +} + +/** Appends an outcome for an entry; the references are copied so that account entries keep their accountRef. */ +export async function append(journalDir: string, type: JournalEntryType, entry: JournalEntry): Promise { + await appendJournalEntry(journalDir, { type, key: entry.key, ...journalRefs(entry), at: new Date().toISOString() }); +} + +async function tenantExists(prisma: PrismaClient, tenantId: string): Promise { + if (tenantId === '') return false; + const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, select: { id: true } }); + return tenant !== null; +} + +export async function hasDatabaseRow(prisma: PrismaClient, key: string): Promise { + const row = await prisma.deletionJournal.findFirst({ + where: { idempotencyKey: key }, + select: { idempotencyKey: true }, + }); + return row !== null; +} + +/** Open intents whose transaction committed in the restored database; account intents only with deleteAccount. */ +async function commitDatabaseBacked( + prisma: PrismaClient, + journalDir: string, + keys: JournalKeys, + withAccounts: boolean, +): Promise { + for (const intent of openIntents(keys)) { + if (isAccountEntry(intent) && !withAccounts) continue; + const row = await prisma.deletionJournal.findFirst({ + where: { idempotencyKey: intent.key }, + select: { dbDeletedAt: true }, + }); + if (row?.dbDeletedAt) await append(journalDir, 'commit', intent); + } +} + +function decisionAction( + state: KeyState | undefined, + decision: ReplayDecision, + withAccounts: boolean, +): 'apply' | 'skip' | 'invalid' { + if (!state?.intent) return 'invalid'; + if (isAccountEntry(state.intent) && !withAccounts) return 'invalid'; + if (isOpen(state)) return 'apply'; + if (decision === 'delete' && state.commit && !state.abort) return 'skip'; + if (decision === 'keep' && state.abort && !state.commit) return 'skip'; + return 'invalid'; +} + +async function applyDecisions(opts: ReplayCommittedDeletionsOptions, keys: JournalKeys): Promise { + const pending: Array<[KeyState, ReplayDecision]> = []; + for (const [key, decision] of opts.decisions ?? []) { + const state = keys.get(key); + const action = decisionAction(state, decision, opts.deleteAccount !== undefined); + if (action === 'invalid' || !state) throw new ReplayDecisionError(); + if (action === 'apply') pending.push([state, decision]); + } + for (const [state, decision] of pending) { + if (state.intent) await append(opts.journalDir, decision === 'delete' ? 'commit' : 'abort', state.intent); + } +} + +async function describeIntents(prisma: PrismaClient, intents: JournalEntry[]): Promise { + const described: UndecidedReplayIntent[] = []; + for (const intent of intents) { + if (isAccountEntry(intent)) { + const userExists = await accountExists(prisma, intent.accountRef); + described.push({ + key: intent.key, + tenantRef: intent.tenantRef, + accountRef: intent.accountRef, + at: intent.at, + tenantExists: false, + accountExists: userExists, + }); + } else { + const exists = await tenantExists(prisma, intent.tenantRef); + described.push({ key: intent.key, tenantRef: intent.tenantRef, at: intent.at, tenantExists: exists }); + } + } + return described; +} + +function replayCandidates(keys: JournalKeys, since: Date): JournalEntry[] { + const sinceMs = since.getTime(); + const commits: JournalEntry[] = []; + for (const state of keys.values()) { + const commit = state.commit; + if (commit && !state.abort && commit.tenantRef !== '' && Date.parse(commit.at) >= sinceMs) commits.push(commit); + } + return commits.sort((a, b) => a.seq - b.seq); +} + +async function deleteRestoredTenants( + opts: ReplayCommittedDeletionsOptions, + candidates: JournalEntry[], +): Promise { + const replayed: string[] = []; + const seen = new Set(); + for (const commit of candidates) { + if (seen.has(commit.tenantRef)) continue; + seen.add(commit.tenantRef); + if (!(await tenantExists(opts.prisma, commit.tenantRef))) continue; + await opts.deleteTenant(commit.tenantRef); + replayed.push(commit.tenantRef); + } + return replayed; +} + +/** Whether two entries name the same tenant and the same account. */ +function sameReference(a: JournalEntry, b: JournalEntry): boolean { + return a.tenantRef === b.tenantRef && a.accountRef === b.accountRef; +} + +/** True when a later deletion of the same tenant or account is committed, or none was attempted. */ +export function coveredByLaterDeletion(keys: JournalKeys, commit: JournalEntry): boolean { + let laterIntent = false; + for (const state of keys.values()) { + const intent = state.intent; + if (!intent || !sameReference(intent, commit) || intent.seq <= commit.seq) continue; + if (state.commit) return true; + laterIntent = true; + } + return !laterIntent; +} + +async function closeReplayedKeys(opts: ReplayCommittedDeletionsOptions, keys: JournalKeys): Promise { + const closed: string[] = []; + for (const commit of replayCandidates(keys, opts.since)) { + if (keys.get(commit.key)?.completed) continue; + if (await tenantExists(opts.prisma, commit.tenantRef)) continue; + if (await hasDatabaseRow(opts.prisma, commit.key)) continue; + if (!coveredByLaterDeletion(keys, commit)) continue; + await append(opts.journalDir, 'completed', commit); + closed.push(commit.key); + } + return closed; +} + +function blockedResult( + blocked: 'undecided_intent' | 'journal_invalid', + replayed: string[] = [], +): ReplayCommittedDeletionsResult { + return { + blocked, + replayed, + undecided: [], + closed: [], + replayedAccounts: [], + closedAccounts: [], + ownerlessTenants: [], + }; +} + +/** Account part of the replay; it runs only with a deletion callback for accounts. */ +async function replayAccounts(opts: ReplayCommittedDeletionsOptions, keys: JournalKeys): Promise { + if (opts.deleteAccount === undefined) return { replayedAccounts: [], closedAccounts: [], ownerlessTenants: [] }; + return replayAccountDeletions( + { prisma: opts.prisma, journalDir: opts.journalDir, since: opts.since, deleteAccount: opts.deleteAccount }, + keys, + ); +} + +/** + * Re-applies tenant and account deletions recorded in the journal after a database + * restore. Safe to run again: deleted tenants and accounts are skipped, closed keys stay + * closed, and decisions that are already recorded are not written twice. + */ +export async function replayCommittedDeletions( + opts: ReplayCommittedDeletionsOptions, +): Promise { + const withAccounts = opts.deleteAccount !== undefined; + const initial = await loadKeys(opts.journalDir); + if (!initial) return blockedResult('journal_invalid'); + await commitDatabaseBacked(opts.prisma, opts.journalDir, initial, withAccounts); + const decided = await loadKeys(opts.journalDir); + if (!decided) return blockedResult('journal_invalid'); + await applyDecisions(opts, decided); + const keys = await loadKeys(opts.journalDir); + if (!keys) return blockedResult('journal_invalid'); + const limit = opts.restoredJournalSeq ?? Number.POSITIVE_INFINITY; + const blocking = openIntents(keys).filter((intent) => intent.seq <= limit); + if (blocking.length > 0) { + return { ...blockedResult('undecided_intent'), undecided: await describeIntents(opts.prisma, blocking) }; + } + const replayed = await deleteRestoredTenants(opts, replayCandidates(keys, opts.since)); + const after = await loadKeys(opts.journalDir); + if (!after) return blockedResult('journal_invalid', replayed); + const closed = await closeReplayedKeys(opts, after); + return { blocked: null, replayed, undecided: [], closed, ...(await replayAccounts(opts, after)) }; +} diff --git a/apps/server/src/services/tenantDeletionReplayRun.ts b/apps/server/src/services/tenantDeletionReplayRun.ts new file mode 100644 index 00000000..c2ec136a --- /dev/null +++ b/apps/server/src/services/tenantDeletionReplayRun.ts @@ -0,0 +1,267 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; +import { revokeAllSessions } from '../api/utils/sessionAuth.js'; +import { + clearRestorePending, + readRestorePending, + RestorePendingUnreadableError, + type RestorePendingMarker, +} from './tenantDeletionRestoreMarker.js'; +import { + replayCommittedDeletions, + ReplayDecisionError, + type ReplayCommittedDeletionsResult, + type ReplayDecision, + type UndecidedReplayIntent, +} from './tenantDeletionReplay.js'; + +/** + * Operator run of the restore replay, without process or console access so + * that it can be tested against a real database. + * + * The restore marker supplies the replay boundary: commits at or after the + * creation time of the restored copy are replayed, and open intents up to the + * recorded journal sequence belong to the restored timeline. Without a value + * the whole journal is replayed, which is safe because tenants are deleted by + * id only. The marker is removed only after a complete replay and only when + * the admin module reports no open precondition, so the first server start + * after a restore runs with its preconditions met. Before the marker is removed, the token + * step drops sessions and unused reset and verification tokens and revokes OAuth refresh tokens. + * + * Output lines carry journal keys, tenant ids, intent times and counters, + * never names, slugs, mail addresses or error texts. + */ + +export const REPLAY_EXIT = { + done: 0, + deleteFailed: 1, + undecided: 2, + invalid: 3, + preconditions: 4, +} as const; + +/** OAuth refresh token revocation of the token step; the kind states why no revocation can run. */ +export type OAuthRefreshRevocation = + | { kind: 'module_not_loaded' } + | { kind: 'export_missing' } + | { kind: 'module_rejected' } + | { kind: 'available'; revoke: (now: Date) => Promise }; + +export interface RestoreReplayRunOptions { + prisma: PrismaClient; + journalDir: string; + decisions: ReadonlyMap; + /** Deletes one tenant through the managed path; undefined when no such path is loaded. */ + deleteTenant: ((tenantId: string) => Promise) | undefined; + /** Deletes one account by user id through the managed account path. */ + deleteAccount?: (userId: string) => Promise; + /** Codes of preconditions the admin module still reports as open. */ + pendingPreconditions: () => Promise; + /** OAuth refresh token step; absent means the step reports the transcription module as not loaded. */ + oauthRefreshRevocation?: OAuthRefreshRevocation; +} + +export interface RestoreReplayRunResult { + exitCode: number; + lines: string[]; +} + +export class ReplayDeletePathMissingError extends Error { + readonly code = 'replay_delete_path_missing'; + + constructor() { + super('no managed tenant deletion path loaded'); + this.name = 'ReplayDeletePathMissingError'; + } +} + +/** A failure of the account deletion callback itself; only the code of the original error is reported. */ +class AccountDeleteFailedError extends Error { + constructor(readonly original: unknown) { + super('account deletion failed'); + this.name = 'AccountDeleteFailedError'; + } +} + +class OAuthRevocationUnavailableError extends Error { + readonly code = 'oauth_revocation_unavailable'; + + constructor(message: string) { + super(message); + this.name = 'OAuthRevocationUnavailableError'; + } +} + +const PREFIX = 'restore replay:'; + +function done(exitCode: number, lines: string[]): RestoreReplayRunResult { + return { exitCode, lines }; +} + +function errorCode(error: unknown): string { + const code = typeof error === 'object' && error !== null ? (error as { code?: unknown }).code : undefined; + return typeof code === 'string' && /^[A-Za-z0-9_]{1,64}$/.test(code) ? code : 'unexpected'; +} + +/** Probes the tables the replay and the token step read; an older copy may predate the image schema. */ +async function schemaReady(prisma: PrismaClient): Promise { + try { + await prisma.tenant.findFirst({ select: { id: true } }); + await prisma.deletionJournal.findFirst({ select: { idempotencyKey: true, dbDeletedAt: true } }); + await prisma.user.findFirst({ select: { id: true } }); + await prisma.session.findFirst({ select: { id: true } }); + await prisma.passwordReset.findFirst({ select: { id: true } }); + await prisma.emailVerification.findFirst({ select: { id: true } }); + return true; + } catch { + return false; + } +} + +/** Account intents show no account id in the console; the key is enough for --decide. */ +function describe(intent: UndecidedReplayIntent): string { + if (intent.accountRef !== undefined) { + const accountExists = intent.accountExists ? 'yes' : 'no'; + return ` key=${intent.key} scope=account at=${intent.at} exists=${accountExists}`; + } + const exists = intent.tenantExists ? 'yes' : 'no'; + return ` key=${intent.key} tenant=${intent.tenantRef} at=${intent.at} exists=${exists}`; +} + +async function missingDeletePath(): Promise { + throw new ReplayDeletePathMissingError(); +} + +async function readMarker(journalDir: string): Promise { + try { + return await readRestorePending(journalDir); + } catch (error) { + if (error instanceof RestorePendingUnreadableError) return 'unreadable'; + throw error; + } +} + +/** Runs the account callback and marks its failures, so that the replay names the step that failed. */ +function reportingAccountDelete(deleteAccount: (userId: string) => Promise): (userId: string) => Promise { + return async (userId) => { + try { + await deleteAccount(userId); + } catch (error) { + throw new AccountDeleteFailedError(error); + } + }; +} + +async function replay( + opts: RestoreReplayRunOptions, + marker: RestorePendingMarker | null, +): Promise { + try { + return await replayCommittedDeletions({ + prisma: opts.prisma, + journalDir: opts.journalDir, + since: new Date((marker?.copyCreatedAt ?? 0) * 1000), + deleteTenant: opts.deleteTenant ?? missingDeletePath, + deleteAccount: opts.deleteAccount ? reportingAccountDelete(opts.deleteAccount) : undefined, + restoredJournalSeq: marker?.journalSeq ?? null, + decisions: opts.decisions, + }); + } catch (error) { + if (error instanceof ReplayDecisionError) { + return done(REPLAY_EXIT.invalid, [`${PREFIX} a decision does not match an open intent`]); + } + if (error instanceof ReplayDeletePathMissingError) { + return done(REPLAY_EXIT.invalid, [`${PREFIX} tenants to delete but no managed deletion path loaded`]); + } + if (error instanceof AccountDeleteFailedError) { + const code = errorCode(error.original); + return done(REPLAY_EXIT.deleteFailed, [`${PREFIX} account deletion failed (${code}); marker kept`]); + } + return done(REPLAY_EXIT.deleteFailed, [`${PREFIX} tenant deletion failed (${errorCode(error)}); marker kept`]); + } +} + +/** Summary of the replay in counters only. */ +function summaryLine(result: ReplayCommittedDeletionsResult): string { + const tenants = `replayed ${result.replayed.length} tenants, closed ${result.closed.length} journal keys`; + const accounts = `replayed ${result.replayedAccounts.length} accounts`; + const accountKeys = `closed ${result.closedAccounts.length} account keys`; + return `${PREFIX} ${tenants}, ${accounts}, ${accountKeys}`; +} + +/** One line per tenant without an owner after a replayed account deletion. */ +function ownerlessLines(tenantIds: string[]): string[] { + return tenantIds.map((tenantId) => ` tenant=${tenantId} owner=none`); +} + +/** Drops all sessions and the unused reset and verification tokens, then runs the OAuth refresh step. */ +async function dropTokens(opts: RestoreReplayRunOptions): Promise { + const sessionCount = await revokeAllSessions(opts.prisma); + const resets = await opts.prisma.passwordReset.deleteMany({ where: { usedAt: null } }); + const verifications = await opts.prisma.emailVerification.deleteMany({ where: { usedAt: null } }); + return [ + `${PREFIX} sessions deleted: ${sessionCount}`, + `${PREFIX} password reset tokens deleted: ${resets.count}`, + `${PREFIX} email verification tokens deleted: ${verifications.count}`, + ...(await revokeOAuthRefreshTokens(opts.oauthRefreshRevocation)), + ]; +} + +/** Revokes OAuth refresh tokens through the loaded module; only the count and the skip note are returned. */ +async function revokeOAuthRefreshTokens(revocation: OAuthRefreshRevocation | undefined): Promise { + if (revocation === undefined || revocation.kind === 'module_not_loaded') { + return [`${PREFIX} oauth refresh tokens: skipped (transcription module not loaded)`]; + } + if (revocation.kind === 'export_missing') { + throw new OAuthRevocationUnavailableError( + 'oauth refresh token revocation unavailable: the loaded transcription module is too old', + ); + } + if (revocation.kind === 'module_rejected') { + throw new OAuthRevocationUnavailableError( + 'oauth refresh token revocation unavailable: the installed transcription module failed to load', + ); + } + const n = await revocation.revoke(new Date()); + return [`${PREFIX} oauth refresh tokens revoked: ${n}`]; +} + +/** Token step before the marker is removed; any failure exits 1 and keeps the marker. */ +async function tokenStep(opts: RestoreReplayRunOptions): Promise { + try { + return await dropTokens(opts); + } catch (error) { + if (error instanceof OAuthRevocationUnavailableError) { + return done(REPLAY_EXIT.deleteFailed, [`${PREFIX} ${error.message}; marker kept`]); + } + return done(REPLAY_EXIT.deleteFailed, [`${PREFIX} token cleanup failed (${errorCode(error)}); marker kept`]); + } +} + +/** Runs the replay once and reports the outcome; never exits the process. */ +export async function runRestoreReplay(opts: RestoreReplayRunOptions): Promise { + const marker = await readMarker(opts.journalDir); + if (marker === 'unreadable') return done(REPLAY_EXIT.invalid, [`${PREFIX} restore marker unreadable`]); + if (!(await schemaReady(opts.prisma))) { + const hint = 'run the migration step (docker compose run --rm ee-migrate) first'; + return done(REPLAY_EXIT.invalid, [`${PREFIX} database unreachable or schema not current; ${hint}; marker kept`]); + } + const result = await replay(opts, marker); + if ('exitCode' in result) return result; + if (result.blocked === 'journal_invalid') + return done(REPLAY_EXIT.invalid, [`${PREFIX} journal invalid or unavailable`]); + if (result.blocked === 'undecided_intent') { + const head = `${PREFIX} ${result.undecided.length} open intents need --decide =delete|keep`; + return done(REPLAY_EXIT.undecided, [head, ...result.undecided.map(describe)]); + } + const replayLines = [summaryLine(result), ...ownerlessLines(result.ownerlessTenants)]; + if (marker === null) return done(REPLAY_EXIT.done, [...replayLines, `${PREFIX} no restore marker present`]); + const open = await opts.pendingPreconditions(); + if (open.length > 0) { + const reason = `${PREFIX} preconditions open: ${open.join(', ')}; marker kept`; + return done(REPLAY_EXIT.preconditions, [...replayLines, reason]); + } + const tokens = await tokenStep(opts); + if ('exitCode' in tokens) return done(tokens.exitCode, [...replayLines, ...tokens.lines]); + await clearRestorePending(opts.journalDir); + return done(REPLAY_EXIT.done, [...replayLines, ...tokens, `${PREFIX} marker removed`]); +} diff --git a/apps/server/src/services/tenantDeletionRestoreMarker.test.ts b/apps/server/src/services/tenantDeletionRestoreMarker.test.ts new file mode 100644 index 00000000..1fff402c --- /dev/null +++ b/apps/server/src/services/tenantDeletionRestoreMarker.test.ts @@ -0,0 +1,128 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + clearRestorePending, + isRestorePending, + readRestorePending, + RestorePendingUnreadableError, +} from './tenantDeletionRestoreMarker.js'; + +const MARKER_NAME = 'restore-pending.json'; + +const VALID_MARKER = { + v: 1, + createdAt: '2026-11-12T12:00:00.000Z', + copyCreatedAt: 1762948800, + journalSeq: 7, +}; + +async function expectUnreadable(journalDir: string): Promise { + await expect(readRestorePending(journalDir)).rejects.toBeInstanceOf(RestorePendingUnreadableError); + await expect(readRestorePending(journalDir)).rejects.toHaveProperty('code', 'restore_pending_unreadable'); +} + +describe('tenantDeletionRestoreMarker', () => { + let dir: string; + + beforeEach(async () => { + // Every test gets its own real temporary journal directory. + dir = await fs.mkdtemp(path.join(os.tmpdir(), 'restore-marker-')); + }); + + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + describe('isRestorePending', () => { + it('returns false when no marker exists', async () => { + await expect(isRestorePending(dir)).resolves.toBe(false); + }); + + it('returns true for a regular marker file with arbitrary content', async () => { + await fs.writeFile(path.join(dir, MARKER_NAME), 'arbitrary content, not even JSON'); + await expect(isRestorePending(dir)).resolves.toBe(true); + }); + + it('returns true when a directory carries the marker name', async () => { + await fs.mkdir(path.join(dir, MARKER_NAME)); + await expect(isRestorePending(dir)).resolves.toBe(true); + }); + + it('returns true for a dangling symlink, because the entry itself is inspected', async () => { + await fs.symlink(path.join(dir, 'missing-target.json'), path.join(dir, MARKER_NAME)); + await expect(isRestorePending(dir)).resolves.toBe(true); + }); + + it('returns false when the journal directory does not exist', async () => { + await expect(isRestorePending(path.join(dir, 'missing', 'journal'))).resolves.toBe(false); + }); + }); + + describe('readRestorePending', () => { + it('returns null when no marker exists', async () => { + await expect(readRestorePending(dir)).resolves.toBeNull(); + }); + + it('returns the marker content for a valid regular file', async () => { + await fs.writeFile(path.join(dir, MARKER_NAME), JSON.stringify(VALID_MARKER)); + await expect(readRestorePending(dir)).resolves.toEqual({ + v: 1, + createdAt: '2026-11-12T12:00:00.000Z', + copyCreatedAt: 1762948800, + journalSeq: 7, + }); + }); + + it('accepts null for copyCreatedAt and journalSeq when they are unknown', async () => { + await fs.writeFile( + path.join(dir, MARKER_NAME), + JSON.stringify({ ...VALID_MARKER, copyCreatedAt: null, journalSeq: null }), + ); + await expect(readRestorePending(dir)).resolves.toEqual({ + v: 1, + createdAt: '2026-11-12T12:00:00.000Z', + copyCreatedAt: null, + journalSeq: null, + }); + }); + + it.each([ + ['not JSON', 'not json'], + ['unsupported version', JSON.stringify({ ...VALID_MARKER, v: 2 })], + ['missing journalSeq', JSON.stringify({ v: 1, createdAt: VALID_MARKER.createdAt, copyCreatedAt: null })], + ['negative copyCreatedAt', JSON.stringify({ ...VALID_MARKER, copyCreatedAt: -1 })], + ['fractional journalSeq', JSON.stringify({ ...VALID_MARKER, journalSeq: 1.5 })], + ['invalid createdAt', JSON.stringify({ ...VALID_MARKER, createdAt: 'not a date' })], + ['JSON null', 'null'], + ])('rejects a regular file with invalid content: %s', async (_label, content) => { + await fs.writeFile(path.join(dir, MARKER_NAME), content); + await expectUnreadable(dir); + }); + + it('rejects a directory carrying the marker name', async () => { + await fs.mkdir(path.join(dir, MARKER_NAME)); + await expectUnreadable(dir); + }); + + it('rejects a symlink even when it points to a valid marker file', async () => { + const target = path.join(dir, 'target.json'); + await fs.writeFile(target, JSON.stringify(VALID_MARKER)); + await fs.symlink(target, path.join(dir, MARKER_NAME)); + await expectUnreadable(dir); + }); + }); + + describe('clearRestorePending', () => { + it('removes an existing marker', async () => { + await fs.writeFile(path.join(dir, MARKER_NAME), JSON.stringify(VALID_MARKER)); + await clearRestorePending(dir); + await expect(isRestorePending(dir)).resolves.toBe(false); + }); + + it('resolves without error when no marker exists', async () => { + await expect(clearRestorePending(dir)).resolves.toBeUndefined(); + }); + }); +}); diff --git a/apps/server/src/services/tenantDeletionRestoreMarker.ts b/apps/server/src/services/tenantDeletionRestoreMarker.ts new file mode 100644 index 00000000..c159d490 --- /dev/null +++ b/apps/server/src/services/tenantDeletionRestoreMarker.ts @@ -0,0 +1,126 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; + +/** + * Restore marker for the tenant deletion journal. + * + * `scripts/restore.sh` writes `restore-pending.json` into the journal + * directory before it touches the database. While the marker is present the + * restored database is older than the journal: no open intent may be decided + * from a missing database row and the journal must not be compacted. Only + * the restore replay tool removes the marker, as its last step. + * + * The marker carries no tenant reference. A marker that exists but cannot be + * read counts as present (fail closed); only a missing file means no marker. + */ + +export const RESTORE_PENDING_FILE = 'restore-pending.json'; + +export interface RestorePendingMarker { + v: 1; + /** ISO time at which the marker was written. */ + createdAt: string; + /** Creation time of the restored copy in epoch seconds, null if unknown. */ + copyCreatedAt: number | null; + /** Sequence of the last journal line when the marker was written, null if unknown. */ + journalSeq: number | null; +} + +export class RestorePendingUnreadableError extends Error { + readonly code = 'restore_pending_unreadable'; + + constructor() { + super('restore marker present but unreadable'); + this.name = 'RestorePendingUnreadableError'; + } +} + +function markerPath(journalDir: string): string { + return path.join(journalDir, RESTORE_PENDING_FILE); +} + +function isMissing(error: unknown): boolean { + return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT'; +} + +/** True while a restore replay is pending; any error other than ENOENT counts as pending. */ +export async function isRestorePending(journalDir: string): Promise { + try { + await fs.lstat(markerPath(journalDir)); + return true; + } catch (error) { + return !isMissing(error); + } +} + +function readCount(value: unknown): number | null | undefined { + if (value === null) return null; + if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value; + return undefined; +} + +function parseMarker(raw: string): RestorePendingMarker { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new RestorePendingUnreadableError(); + } + if (typeof parsed !== 'object' || parsed === null) throw new RestorePendingUnreadableError(); + const record = parsed as Record; + const createdAt = record.createdAt; + const copyCreatedAt = readCount(record.copyCreatedAt); + const journalSeq = readCount(record.journalSeq); + if ( + record.v !== 1 || + typeof createdAt !== 'string' || + Number.isNaN(Date.parse(createdAt)) || + copyCreatedAt === undefined || + journalSeq === undefined + ) { + throw new RestorePendingUnreadableError(); + } + return { v: 1, createdAt, copyCreatedAt, journalSeq }; +} + +/** + * Reads the marker. Returns null when no marker exists and throws + * RestorePendingUnreadableError when a marker exists but is not a regular + * file with valid content. + */ +export async function readRestorePending(journalDir: string): Promise { + const file = markerPath(journalDir); + let raw: string; + try { + const stat = await fs.lstat(file); + if (!stat.isFile()) throw new RestorePendingUnreadableError(); + raw = await fs.readFile(file, 'utf8'); + } catch (error) { + if (isMissing(error)) return null; + if (error instanceof RestorePendingUnreadableError) throw error; + throw new RestorePendingUnreadableError(); + } + return parseMarker(raw); +} + +/** Removes the marker; a missing marker is fine. */ +export async function clearRestorePending(journalDir: string): Promise { + try { + await fs.unlink(markerPath(journalDir)); + } catch (error) { + if (!isMissing(error)) throw error; + } + // Makes the removal durable before the caller reports success. As for the + // journal checkpoint, a directory that cannot be opened is skipped; a + // failed sync is reported to the caller. + await fs.open(journalDir, 'r').then( + async (dir) => { + try { + await dir.sync(); + } finally { + await dir.close(); + } + }, + () => undefined, + ); +} diff --git a/apps/server/src/services/tenantDeletionTasks.integration.test.ts b/apps/server/src/services/tenantDeletionTasks.integration.test.ts new file mode 100644 index 00000000..5e6b12e6 --- /dev/null +++ b/apps/server/src/services/tenantDeletionTasks.integration.test.ts @@ -0,0 +1,305 @@ +import crypto from 'crypto'; +import { afterAll, describe, expect, it } from 'vitest'; +import { createPrismaClient } from '../db.js'; +import type { PrismaClient } from '../generated/prisma/index.js'; + +/** + * Deletion model tests for the two future tables `DeletionJournal` and + * `DeletionTask` (see deletion specification, minimal data model). The model layer + * does not exist yet, so every fixture goes through typed + * `$queryRaw`/`$executeRaw` against the real PostgreSQL database. + * + * Until the schema fix lands, the `to_regclass` existence assertions at + * the start of each test are the failing (red) assertions. They are + * plain assertions, not setup errors. + */ + +if (!process.env.DATABASE_URL) { + throw new Error('tenantDeletionTasks.integration.test.ts needs DATABASE_URL pointing at a migrated test database'); +} + +// Fixed fixture clock. Not a retention rule: `journalUntil` is a +// synthetic schema-test deadline only. +const REQUESTED_AT = new Date('2026-11-07T00:00:00Z'); +const JOURNAL_UNTIL = new Date('2026-11-08T00:00:00Z'); + +const tenantIds: string[] = []; +const userIds: string[] = []; +const journalIds: string[] = []; +const taskIds: string[] = []; + +type TablePresence = { rel: string | null }; + +async function queryTablePresence(prisma: PrismaClient): Promise { + return prisma.$queryRaw` + SELECT to_regclass(${'\"DeletionJournal\"'})::text AS "rel" + UNION ALL + SELECT to_regclass(${'\"DeletionTask\"'})::text AS "rel"`; +} + +async function requireTables(prisma: PrismaClient): Promise { + const presence = await queryTablePresence(prisma); + expect(presence).toHaveLength(2); + expect(presence[0]?.rel).not.toBeNull(); + expect(presence[1]?.rel).not.toBeNull(); +} + +type JournalRow = { + id: string; + idempotencyKey: string; + scope: string; + tenantRef: string; + accountRefs: string[]; + objectRefs: string[]; + policyVersion: string; + requestedAt: Date; + journalUntil: Date; + generation: bigint; +}; + +type TaskRow = { + id: string; + journalId: string; + kind: string; + targetSystem: string; + objectId: string; + objectGeneration: string; + storageKey: string; + dedupeKey: string; +}; + +async function insertJournal( + prisma: PrismaClient, + journal: { id: string; idempotencyKey: string; tenantRef: string; accountRefs: string[] }, +): Promise { + const emptyObjectRefs: string[] = []; + journalIds.push(journal.id); + await prisma.$executeRaw` + INSERT INTO "DeletionJournal" + ("id", "idempotencyKey", "scope", "tenantRef", "accountRefs", "objectRefs", "policyVersion", "requestedAt", "journalUntil") + VALUES + (${journal.id}, ${journal.idempotencyKey}, ${'tenant'}, ${journal.tenantRef}, ${journal.accountRefs}, ${emptyObjectRefs}, ${'deletion-test-v1'}, ${REQUESTED_AT}, ${JOURNAL_UNTIL})`; +} + +async function insertTask( + prisma: PrismaClient, + task: { + id: string; + journalId: string; + objectId: string; + objectGeneration: string; + storageKey: string; + dedupeKey: string; + }, +): Promise { + taskIds.push(task.id); + await prisma.$executeRaw` + INSERT INTO "DeletionTask" + ("id", "journalId", "kind", "targetSystem", "objectId", "objectGeneration", "storageKey", "dedupeKey", "nextAttemptAt") + VALUES + (${task.id}, ${task.journalId}, ${'file'}, ${'asset_packs'}, ${task.objectId}, ${task.objectGeneration}, ${task.storageKey}, ${task.dedupeKey}, ${REQUESTED_AT})`; +} + +async function readJournal(prisma: PrismaClient, id: string): Promise { + return prisma.$queryRaw` + SELECT "id", "idempotencyKey", "scope", "tenantRef", "accountRefs", "objectRefs", + "policyVersion", "requestedAt", "journalUntil", "generation" + FROM "DeletionJournal" WHERE "id" = ${id}`; +} + +async function readTask(prisma: PrismaClient, id: string): Promise { + return prisma.$queryRaw` + SELECT "id", "journalId", "kind", "targetSystem", "objectId", "objectGeneration", + "storageKey", "dedupeKey" + FROM "DeletionTask" WHERE "id" = ${id}`; +} + +type ForeignKeyRef = { table: string; references: string }; + +async function queryTenantUserForeignKeys(prisma: PrismaClient): Promise { + return prisma.$queryRaw` + SELECT tc."table_name" AS "table", ccu."table_name" AS "references" + FROM information_schema.table_constraints tc + JOIN information_schema.key_column_usage kcu + ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema + JOIN information_schema.constraint_column_usage ccu + ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema + WHERE tc.constraint_type = 'FOREIGN KEY' + AND tc.table_name IN (${'DeletionJournal'}, ${'DeletionTask'}) + AND ccu.table_name IN (${'Tenant'}, ${'User'})`; +} + +describe('tenant deletion journal and tasks survive tenant/user removal (real database)', () => { + afterAll(async () => { + const prisma = createPrismaClient(); + try { + const presence = await queryTablePresence(prisma); + if (presence.length === 2 && presence.every((row) => row.rel !== null)) { + for (const id of taskIds) { + await prisma.$executeRaw`DELETE FROM "DeletionTask" WHERE "id" = ${id}`; + } + for (const id of journalIds) { + await prisma.$executeRaw`DELETE FROM "DeletionJournal" WHERE "id" = ${id}`; + } + } + if (userIds.length > 0) { + await prisma.user.deleteMany({ where: { id: { in: userIds } } }); + } + if (tenantIds.length > 0) { + await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } }); + } + } finally { + await prisma.$disconnect(); + } + }); + + it('keeps journal and task rows with unchanged references after tenant and user rows are deleted', async () => { + const prisma = createPrismaClient(); + try { + await requireTables(prisma); + + const suffix = crypto.randomUUID(); + const tenantId = `deletion_test_${crypto.randomUUID()}`; + const userId = `deletion_test_${crypto.randomUUID()}`; + tenantIds.push(tenantId); + userIds.push(userId); + const tenant = await prisma.tenant.create({ + data: { id: tenantId, slug: `deletion-test-${suffix}`, name: `deletion-test-${suffix}` }, + }); + const user = await prisma.user.create({ data: { id: userId, email: `deletion-test-${suffix}@example.test` } }); + + const journalId = crypto.randomUUID(); + const idempotencyKey = `deletion-test-${crypto.randomUUID()}`; + await insertJournal(prisma, { id: journalId, idempotencyKey, tenantRef: tenant.id, accountRefs: [user.id] }); + + const objectId = crypto.randomUUID(); + const objectGeneration = crypto.randomUUID(); + const taskId = crypto.randomUUID(); + const storageKey = `${tenant.id}/${objectId}/${objectGeneration}`; + const dedupeKey = `deletion-test-${crypto.randomUUID()}`; + await insertTask(prisma, { id: taskId, journalId, objectId, objectGeneration, storageKey, dedupeKey }); + + const journalBefore = await readJournal(prisma, journalId); + const taskBefore = await readTask(prisma, taskId); + expect(journalBefore).toHaveLength(1); + expect(taskBefore).toHaveLength(1); + + await prisma.user.delete({ where: { id: user.id } }); + await prisma.tenant.delete({ where: { id: tenant.id } }); + + const journalAfter = await readJournal(prisma, journalId); + const taskAfter = await readTask(prisma, taskId); + expect(journalAfter).toHaveLength(1); + expect(taskAfter).toHaveLength(1); + expect(journalAfter[0]?.tenantRef).toBe(tenant.id); + expect(journalAfter[0]?.accountRefs).toEqual([user.id]); + expect(journalAfter[0]?.objectRefs).toEqual([]); + expect(journalAfter[0]?.generation).toBe(journalBefore[0]?.generation); + expect(taskAfter[0]?.objectId).toBe(objectId); + expect(taskAfter[0]?.objectGeneration).toBe(objectGeneration); + expect(taskAfter[0]?.storageKey).toBe(storageKey); + + expect(await queryTenantUserForeignKeys(prisma)).toEqual([]); + await expect(prisma.$executeRaw`DELETE FROM "DeletionJournal" WHERE "id" = ${journalId}`).rejects.toMatchObject({ + code: 'P2010', + meta: { + driverAdapterError: { + cause: { + originalCode: '23503', + kind: 'ForeignKeyConstraintViolation', + constraint: { index: 'DeletionTask_journalId_fkey' }, + }, + }, + }, + }); + } finally { + await prisma.$disconnect(); + } + }); + + it('dedupes repeated journal and task inserts and orders generations monotonically', async () => { + const prisma = createPrismaClient(); + try { + await requireTables(prisma); + + const idempotencyKey = `deletion-test-${crypto.randomUUID()}`; + const emptyObjectRefs: string[] = []; + const firstJournalId = crypto.randomUUID(); + const duplicateJournalId = crypto.randomUUID(); + journalIds.push(firstJournalId, duplicateJournalId); + const firstJournal = await prisma.$queryRaw>` + INSERT INTO "DeletionJournal" + ("id", "idempotencyKey", "scope", "tenantRef", "accountRefs", "objectRefs", "policyVersion", "requestedAt", "journalUntil") + VALUES + (${firstJournalId}, ${idempotencyKey}, ${'tenant'}, ${`deletion-test-${crypto.randomUUID()}`}, ${[`deletion-test-${crypto.randomUUID()}`]}, ${emptyObjectRefs}, ${'deletion-test-v1'}, ${REQUESTED_AT}, ${JOURNAL_UNTIL}) + ON CONFLICT ("idempotencyKey") DO NOTHING RETURNING "id" AS "id"`; + expect(firstJournal).toHaveLength(1); + + const secondJournal = await prisma.$queryRaw>` + INSERT INTO "DeletionJournal" + ("id", "idempotencyKey", "scope", "tenantRef", "accountRefs", "objectRefs", "policyVersion", "requestedAt", "journalUntil") + VALUES + (${duplicateJournalId}, ${idempotencyKey}, ${'tenant'}, ${`deletion-test-${crypto.randomUUID()}`}, ${[`deletion-test-${crypto.randomUUID()}`]}, ${emptyObjectRefs}, ${'deletion-test-v1'}, ${REQUESTED_AT}, ${JOURNAL_UNTIL}) + ON CONFLICT ("idempotencyKey") DO NOTHING RETURNING "id" AS "id"`; + expect(secondJournal).toHaveLength(0); + + const journalCount = await prisma.$queryRaw>` + SELECT COUNT(*) AS "n" FROM "DeletionJournal" WHERE "idempotencyKey" = ${idempotencyKey}`; + expect(journalCount[0]?.n).toBe(1n); + + const journalId = firstJournal[0]?.id ?? ''; + const dedupeKey = `deletion-test-${crypto.randomUUID()}`; + const objectId = crypto.randomUUID(); + const objectGeneration = crypto.randomUUID(); + const storageKey = `deletion-test-fixture/${objectId}/${objectGeneration}`; + const firstTaskId = crypto.randomUUID(); + const duplicateTaskId = crypto.randomUUID(); + taskIds.push(firstTaskId, duplicateTaskId); + const firstTask = await prisma.$queryRaw>` + INSERT INTO "DeletionTask" + ("id", "journalId", "kind", "targetSystem", "objectId", "objectGeneration", "storageKey", "dedupeKey", "nextAttemptAt") + VALUES + (${firstTaskId}, ${journalId}, ${'file'}, ${'asset_packs'}, ${objectId}, ${objectGeneration}, ${storageKey}, ${dedupeKey}, ${REQUESTED_AT}) + ON CONFLICT ("dedupeKey") DO NOTHING RETURNING "id" AS "id"`; + expect(firstTask).toHaveLength(1); + + const secondTask = await prisma.$queryRaw>` + INSERT INTO "DeletionTask" + ("id", "journalId", "kind", "targetSystem", "objectId", "objectGeneration", "storageKey", "dedupeKey", "nextAttemptAt") + VALUES + (${duplicateTaskId}, ${journalId}, ${'file'}, ${'asset_packs'}, ${objectId}, ${objectGeneration}, ${storageKey}, ${dedupeKey}, ${REQUESTED_AT}) + ON CONFLICT ("dedupeKey") DO NOTHING RETURNING "id" AS "id"`; + expect(secondTask).toHaveLength(0); + + const storedTask = await readTask(prisma, firstTask[0]?.id ?? ''); + expect(storedTask).toHaveLength(1); + expect(storedTask[0]?.objectId).toBe(objectId); + expect(storedTask[0]?.objectGeneration).toBe(objectGeneration); + expect(storedTask[0]?.storageKey).toBe(storageKey); + expect(storedTask[0]?.dedupeKey).toBe(dedupeKey); + + const firstGenerationId = crypto.randomUUID(); + const secondGenerationId = crypto.randomUUID(); + journalIds.push(firstGenerationId, secondGenerationId); + const firstGeneration = await prisma.$queryRaw>` + INSERT INTO "DeletionJournal" + ("id", "idempotencyKey", "scope", "tenantRef", "accountRefs", "objectRefs", "policyVersion", "requestedAt", "journalUntil") + VALUES + (${firstGenerationId}, ${`deletion-test-${crypto.randomUUID()}`}, ${'tenant'}, ${`deletion-test-${crypto.randomUUID()}`}, ${[`deletion-test-${crypto.randomUUID()}`]}, ${emptyObjectRefs}, ${'deletion-test-v1'}, ${REQUESTED_AT}, ${JOURNAL_UNTIL}) + RETURNING "generation" AS "generation"`; + const secondGeneration = await prisma.$queryRaw>` + INSERT INTO "DeletionJournal" + ("id", "idempotencyKey", "scope", "tenantRef", "accountRefs", "objectRefs", "policyVersion", "requestedAt", "journalUntil") + VALUES + (${secondGenerationId}, ${`deletion-test-${crypto.randomUUID()}`}, ${'tenant'}, ${`deletion-test-${crypto.randomUUID()}`}, ${[`deletion-test-${crypto.randomUUID()}`]}, ${emptyObjectRefs}, ${'deletion-test-v1'}, ${REQUESTED_AT}, ${JOURNAL_UNTIL}) + RETURNING "generation" AS "generation"`; + expect(firstGeneration).toHaveLength(1); + expect(secondGeneration).toHaveLength(1); + expect(typeof firstGeneration[0]?.generation).toBe('bigint'); + expect(typeof secondGeneration[0]?.generation).toBe('bigint'); + expect((secondGeneration[0]?.generation ?? 0n) > (firstGeneration[0]?.generation ?? 0n)).toBe(true); + } finally { + await prisma.$disconnect(); + } + }); +}); diff --git a/apps/server/src/services/tenantFiles.test.ts b/apps/server/src/services/tenantFiles.test.ts new file mode 100644 index 00000000..19a5ee8b --- /dev/null +++ b/apps/server/src/services/tenantFiles.test.ts @@ -0,0 +1,89 @@ +import path from 'node:path'; +import { promises as fsp } from 'node:fs'; +import os from 'node:os'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { npcMediaDir } from '../api/routes/npcMedia.js'; +import { removeTenantFiles, tenantNpcMediaDir } from './tenantFiles.js'; + +describe('tenant file cleanup resolves the NPC media directory like the NPC media routes', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('uses the routes default when NPC_MEDIA_DIR is not set', () => { + vi.stubEnv('NPC_MEDIA_DIR', ''); + expect(tenantNpcMediaDir('acme')).toBe(path.join(npcMediaDir(), 'acme')); + }); + + it('uses NPC_MEDIA_DIR when it is set', () => { + vi.stubEnv('NPC_MEDIA_DIR', '/tmp/qacc-npc-media'); + expect(npcMediaDir()).toBe('/tmp/qacc-npc-media'); + expect(tenantNpcMediaDir('acme')).toBe(path.join('/tmp/qacc-npc-media', 'acme')); + }); + + it('refuses a slug that leaves the directory', () => { + vi.stubEnv('NPC_MEDIA_DIR', '/tmp/qacc-npc-media'); + expect(tenantNpcMediaDir('../qacc-decoy')).toBeNull(); + }); +}); + +describe('tenant file cleanup removes avatar-pack sprites, not catalogue packs', () => { + const avatarPackUuid = '123e4567-e89b-12d3-a456-426614174000'; + + it('removes packs/avatars/ for a deleted tenant avatar pack', async () => { + const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'qacc-tenant-avatar-')); + const packsDir = path.join(root, 'packs'); + const spriteDir = path.join(packsDir, 'avatars', avatarPackUuid); + const foreignDir = path.join(packsDir, avatarPackUuid); + await fsp.mkdir(spriteDir, { recursive: true }); + await fsp.writeFile(path.join(spriteDir, 'sprite.png'), 'sprite-bytes'); + await fsp.mkdir(foreignDir, { recursive: true }); + await fsp.writeFile(path.join(foreignDir, 'global-asset.txt'), 'global'); + vi.stubEnv('ASSET_PACKS_DIR', packsDir); + vi.stubEnv('NPC_MEDIA_DIR', path.join(root, 'npc-media')); + try { + await removeTenantFiles({ + tenantSlug: 'acme-fixture', + assetPackUuids: [], + avatarPackUuids: [avatarPackUuid], + customAvatarUuids: [], + npcIds: [], + }); + await expect(fsp.stat(spriteDir)).rejects.toMatchObject({ code: 'ENOENT' }); + } finally { + vi.unstubAllEnvs(); + if (root.startsWith(os.tmpdir() + path.sep)) { + await fsp.rm(root, { recursive: true, force: true }); + } + } + }); + + it('keeps packs/ catalogue assets untouched by avatar-pack cleanup', async () => { + const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'qacc-tenant-catalogue-')); + const packsDir = path.join(root, 'packs'); + const spriteDir = path.join(packsDir, 'avatars', avatarPackUuid); + const foreignDir = path.join(packsDir, avatarPackUuid); + await fsp.mkdir(spriteDir, { recursive: true }); + await fsp.writeFile(path.join(spriteDir, 'sprite.png'), 'sprite-bytes'); + await fsp.mkdir(foreignDir, { recursive: true }); + await fsp.writeFile(path.join(foreignDir, 'global-asset.txt'), 'global'); + vi.stubEnv('ASSET_PACKS_DIR', packsDir); + vi.stubEnv('NPC_MEDIA_DIR', path.join(root, 'npc-media')); + try { + await removeTenantFiles({ + tenantSlug: 'acme-fixture', + assetPackUuids: [], + avatarPackUuids: [avatarPackUuid], + customAvatarUuids: [], + npcIds: [], + }); + await expect(fsp.stat(foreignDir).then((s) => s.isDirectory())).resolves.toBe(true); + await expect(fsp.readFile(path.join(foreignDir, 'global-asset.txt'), 'utf8')).resolves.toBe('global'); + } finally { + vi.unstubAllEnvs(); + if (root.startsWith(os.tmpdir() + path.sep)) { + await fsp.rm(root, { recursive: true, force: true }); + } + } + }); +}); diff --git a/apps/server/src/services/tenantFiles.ts b/apps/server/src/services/tenantFiles.ts new file mode 100644 index 00000000..498b4c86 --- /dev/null +++ b/apps/server/src/services/tenantFiles.ts @@ -0,0 +1,67 @@ +import path from 'node:path'; +import { promises as fsp } from 'node:fs'; +import { logger } from '../logger.js'; +import { customAvatarPacksDir, customAvatarDir } from './avatarComposer.js'; +import { npcMediaDir } from '../api/routes/npcMedia.js'; + +/** The tenant's NPC media directory, or null when the slug would leave the storage root. */ +export function tenantNpcMediaDir(tenantSlug: string): string | null { + return resolveInside(npcMediaDir(), tenantSlug); +} + +/** + * File cleanup for a deleted tenant. Removes pack directories (tenant-owned + * packs only — catalogue packs belong to no tenant and are never passed in), + * the tenant's NPC media directory and the tenant-scoped custom avatar files. + * Storage roots are resolved exactly like the routes that write them + * (ASSET_PACKS_DIR like assetPacks.ts/avatarComposer.ts, NPC_MEDIA_DIR like + * npcMedia.ts); when resolution differs, files stay behind and are logged + * instead of deleted. + */ + +/** Resolve `segments` under `base`, or null when a segment escapes it. */ +export function resolveInside(base: string, ...segments: string[]): string | null { + if (segments.some((s) => s.length === 0 || s === '..' || s.includes('/') || s.includes('\\'))) { + return null; + } + const resolved = path.resolve(base, ...segments); + const relative = path.relative(base, resolved); + if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return null; + return resolved; +} + +async function removePath(resolved: string | null, tenantSlug: string, kind: string): Promise { + if (resolved === null) { + logger.warn({ event: 'tenant.files_cleanup_refused', tenantSlug, kind }); + return; + } + try { + await fsp.rm(resolved, { recursive: true, force: true }); + } catch (error) { + logger.warn({ event: 'tenant.files_cleanup_failed', tenantSlug, kind, error: String(error) }); + } +} + +/** Delete the tenant's files. Never throws. */ +export async function removeTenantFiles(params: { + tenantSlug: string; + assetPackUuids: string[]; + avatarPackUuids: string[]; + customAvatarUuids: string[]; + npcIds: string[]; +}): Promise { + const { tenantSlug } = params; + const packsDir = customAvatarPacksDir(); + for (const uuid of params.assetPackUuids) { + await removePath(resolveInside(packsDir, uuid), tenantSlug, 'pack'); + } + for (const uuid of params.avatarPackUuids) { + await removePath(resolveInside(packsDir, 'avatars', uuid), tenantSlug, 'pack'); + } + await removePath(tenantNpcMediaDir(tenantSlug), tenantSlug, 'npc'); + const avatarDir = customAvatarDir(packsDir); + for (const uuid of params.customAvatarUuids) { + await removePath(resolveInside(avatarDir, `${uuid}.png`), tenantSlug, 'avatar'); + await removePath(resolveInside(avatarDir, `${uuid}_p.png`), tenantSlug, 'avatar'); + } +} diff --git a/apps/server/src/services/tenantSlugReservation.ts b/apps/server/src/services/tenantSlugReservation.ts new file mode 100644 index 00000000..39c599c8 --- /dev/null +++ b/apps/server/src/services/tenantSlugReservation.ts @@ -0,0 +1,15 @@ +import type { PrismaClient } from '../generated/prisma/index.js'; + +/** + * True while the NPC media folder (`NPC_MEDIA_DIR/`) of a deleted tenant + * has not been cleared yet. Reusing the slug before that would place the old + * files into the folder of the new tenant. A task in status `done` no longer + * reserves the slug. + */ +export async function isTenantSlugReserved(prisma: PrismaClient, slug: string): Promise { + const pending = await prisma.deletionTask.findFirst({ + where: { targetSystem: 'npc_media', storageKey: slug, status: { not: 'done' } }, + select: { id: true }, + }); + return pending !== null; +} diff --git a/apps/server/src/tenantIsolation.integration.test.ts b/apps/server/src/tenantIsolation.integration.test.ts index 6ff9863c..872d7e49 100644 --- a/apps/server/src/tenantIsolation.integration.test.ts +++ b/apps/server/src/tenantIsolation.integration.test.ts @@ -4,7 +4,7 @@ import cookieParser from 'cookie-parser'; import express from 'express'; import jwt from 'jsonwebtoken'; import request from 'supertest'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import type { Role } from './generated/prisma/index.js'; import { createPrismaClient } from './db.js'; import { registerApi } from './api.js'; @@ -187,6 +187,11 @@ describe('flows that must keep working without a membership (real stack)', () => const created = await prisma.user.findUnique({ where: { email }, select: { id: true } }); expect(created).not.toBeNull(); if (created) userIds.push(created.id); + // Registration starts the email verification without awaiting it; wait for + // its row so that the cleanup does not race that write. + await vi.waitFor(async () => expect(await prisma.emailVerification.count({ where: { user: { email } } })).toBe(1), { + timeout: 5_000, + }); expect(await prisma.membership.count({ where: { tenantId, user: { email } } })).toBe(0); }); diff --git a/apps/server/src/transcriptionLoader.ts b/apps/server/src/transcriptionLoader.ts index 1c91fbd9..cd6139b9 100644 --- a/apps/server/src/transcriptionLoader.ts +++ b/apps/server/src/transcriptionLoader.ts @@ -52,6 +52,11 @@ export interface TranscriptionModule { * leaves the transcriber out of every allow-list (fail-closed). */ isTenantTranscriptionActive?(tenantId: string): boolean; + /** + * Optional: revokes every active OAuth refresh token after a database restore + * and returns how many were revoked. Absent in transcription builds without it. + */ + revokeOAuthRefreshTokensAfterRestore?(prisma: PrismaClient, now: Date): Promise; setupRoutes(app: Express, deps: TranscriptionRouteDeps): void; } @@ -62,11 +67,19 @@ export const transcriptionModuleSchema = z.object({ onGateChange: z.function(), evaluateJoin: z.function().optional(), isTenantTranscriptionActive: z.function().optional(), + // Optional: absent in transcription builds without OAuth restore revocation. + revokeOAuthRefreshTokensAfterRestore: z.function().optional(), setupRoutes: z.function(), }); +/** Outcome of the last load attempt: the package is absent, installed but rejected, or loaded. */ +export type TranscriptionLoadState = 'absent' | 'rejected' | 'loaded'; + +type TranscriptionImporter = () => Promise; + let cached: TranscriptionModule | null = null; let loadAttempted = false; +let loadState: TranscriptionLoadState | undefined; function unwrapDefaultExport(moduleValue: unknown): unknown { if (!moduleValue || typeof moduleValue !== 'object') return moduleValue; @@ -84,26 +97,63 @@ export function toTranscriptionModule(mod: z.infer { + const moduleName: string = '@meetropolis/transcription'; + return import(moduleName); +}; + +/** + * Loads and validates the optional module. The state separates an absent package, + * which selects OSS mode, from an installed package that fails to load or to validate. + */ +export async function resolveTranscriptionModule( + importModule: TranscriptionImporter = importTranscriptionPackage, +): Promise<{ state: TranscriptionLoadState; module: TranscriptionModule | null }> { + try { + const modUnknown: unknown = await importModule(); + const parsed = transcriptionModuleSchema.parse(unwrapDefaultExport(modUnknown)); + return { state: 'loaded', module: toTranscriptionModule(parsed) }; + } catch (error) { + return { state: isAbsentTranscriptionPackage(error) ? 'absent' : 'rejected', module: null }; + } +} + +/** Outcome of the last load attempt; undefined before the first one. */ +export function getTranscriptionLoadState(): TranscriptionLoadState | undefined { + return loadState; +} + export async function getTranscriptionModule(): Promise { if (loadAttempted) return cached; loadAttempted = true; - try { - const moduleName: string = '@meetropolis/transcription'; - const modUnknown: unknown = await import(moduleName); - cached = toTranscriptionModule(transcriptionModuleSchema.parse(unwrapDefaultExport(modUnknown))); - - logger.info({ event: 'transcription.module_loaded', version: EXPECTED_TRANSCRIPTION_MODULE_VERSION }); - return cached; - } catch (_error) { + const resolution = await resolveTranscriptionModule(); + loadState = resolution.state; + cached = resolution.module; + if (cached === null) { logger.debug({ event: 'transcription.module_not_available', message: 'Transcription disabled (OSS)' }); - cached = null; return null; } + logger.info({ event: 'transcription.module_loaded', version: EXPECTED_TRANSCRIPTION_MODULE_VERSION }); + return cached; } export function getTranscriptionModuleSync(): TranscriptionModule | null { diff --git a/apps/server/src/transcriptionLoaderState.test.ts b/apps/server/src/transcriptionLoaderState.test.ts new file mode 100644 index 00000000..f23a192c --- /dev/null +++ b/apps/server/src/transcriptionLoaderState.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { EXPECTED_TRANSCRIPTION_MODULE_VERSION, resolveTranscriptionModule } from './transcriptionLoader.js'; + +/** A module that satisfies the contract, as the optional package exports it. */ +function compatibleModule() { + return { + version: EXPECTED_TRANSCRIPTION_MODULE_VERSION, + publishIslandAttributes: false, + getJoinRequirement: () => Promise.resolve(null), + onGateChange: () => () => undefined, + setupRoutes: () => undefined, + }; +} + +/** Import failure with the code Node reports for an unresolvable package. */ +function importError(message: string): Error { + return Object.assign(new Error(message), { code: 'ERR_MODULE_NOT_FOUND' }); +} + +describe('resolveTranscriptionModule', () => { + it('reports the package as absent only when exactly @meetropolis/transcription is missing', async () => { + const missing = importError("Cannot find package '@meetropolis/transcription' imported from loader"); + + const resolution = await resolveTranscriptionModule(() => Promise.reject(missing)); + + expect(resolution).toEqual({ state: 'absent', module: null }); + }); + + it('rejects an installed module whose own dependency cannot be imported', async () => { + const missingDependency = importError("Cannot find package 'enterprise-db' imported from module"); + + const resolution = await resolveTranscriptionModule(() => Promise.reject(missingDependency)); + + expect(resolution).toEqual({ state: 'rejected', module: null }); + }); + + it('rejects an installed module that violates the runtime schema', async () => { + const wrongVersion = { ...compatibleModule(), version: 2 }; + + const resolution = await resolveTranscriptionModule(() => Promise.resolve(wrongVersion)); + + expect(resolution).toEqual({ state: 'rejected', module: null }); + }); + + it('loads a module that satisfies the contract', async () => { + const resolution = await resolveTranscriptionModule(() => Promise.resolve(compatibleModule())); + + expect(resolution.state).toBe('loaded'); + expect(resolution.module).not.toBeNull(); + expect(resolution.module?.version).toBe(EXPECTED_TRANSCRIPTION_MODULE_VERSION); + }); +}); diff --git a/apps/server/test/fixtures/requestTelemetry.ts b/apps/server/test/fixtures/requestTelemetry.ts index e84f2f54..526f3bc1 100644 --- a/apps/server/test/fixtures/requestTelemetry.ts +++ b/apps/server/test/fixtures/requestTelemetry.ts @@ -1,11 +1,11 @@ /** - * Kindprozess-Fixture für requestTelemetry.test.ts. + * Child-process fixture for requestTelemetry.test.ts. * - * Baut eine echte Express-App mit der echten metricsMiddleware und dem echten - * requestLogger, feuert drei echte HTTP-Requests über supertest und schreibt - * danach genau eine JSON-Ergebniszeile nach stdout. Die Pino-Logzeilen sind - * die eigene stdout-Ausgabe der Middleware und werden vom Elterntest geparst; - * hier wird nichts synthetisiert. + * Builds a real Express app with the real metricsMiddleware and the real + * requestLogger, fires three real HTTP requests via supertest, then writes + * exactly one JSON result line to stdout. The pino log lines are the + * middleware's own stdout output and are parsed by the parent test; + * nothing is synthesized here. */ import express from 'express'; import request from 'supertest'; @@ -88,8 +88,8 @@ async function main(): Promise { await waitForObservations(3); const metricValues = await readRouteLabels(); process.stdout.write(`${JSON.stringify({ marker: RESULT_MARKER, cases, metricValues })}\n`); - // main kehrt zurück; ohne offene Handles läuft der Prozess natürlich aus, - // stdout drainet dabei vollständig. + // main returns; with no open handles the process exits naturally while + // stdout fully drains. } void main(); diff --git a/apps/server/test/require-database-url.ts b/apps/server/test/require-database-url.ts new file mode 100644 index 00000000..8fb71928 --- /dev/null +++ b/apps/server/test/require-database-url.ts @@ -0,0 +1,10 @@ +// Global setup of the database test projects (see vitest.config.ts). +// Fails the run before any test file loads, so nothing is skipped silently. +export default function requireDatabaseUrl(): void { + if (!process.env.DATABASE_URL) { + throw new Error( + 'npm run test:db needs DATABASE_URL pointing at a migrated PostgreSQL test database ' + + '(run `npx prisma migrate deploy` in apps/server first). See TEST_STRATEGY.md.', + ); + } +} diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts index fe533e59..98e9c394 100644 --- a/apps/server/vitest.config.ts +++ b/apps/server/vitest.config.ts @@ -1,5 +1,26 @@ import { defineConfig } from 'vitest/config'; +// Tests that need a migrated PostgreSQL database (DATABASE_URL). They run only +// through `npm run test:db`, never through `npm test`. +const databaseTestFiles = [ + 'src/**/*.integration.test.ts', + // These two reach the database through test/fixtures/httpFixture.ts. + 'src/api/routes/auth.flow.test.ts', + 'src/api/routes/admin.passwordReset.test.ts', +]; + +// Database test files with database-wide effects (triggers on shared tables, +// deletes without a tenant filter). They run after all other database tests. +const exclusiveTestFiles = [ + 'src/services/restoreReplayTokenCleanup.integration.test.ts', + 'src/services/accountDeletionJournal.integration.test.ts', + 'src/services/accountDeletion.integration.test.ts', + 'src/api/routes/invites.integration.test.ts', + 'src/api/routes/auth.flow.test.ts', +]; + +const defaultExclude = ['**/node_modules/**', '**/dist/**', '**/.git/**']; + export default defineConfig({ test: { environment: 'node', @@ -8,11 +29,42 @@ export default defineConfig({ // errors / stray 404s under load — a mismatch invisible when a single file // runs in isolation. See test/setup-supertest.ts. setupFiles: ['./test/setup-supertest.ts'], - // Vitest 4 narrowed the default `exclude` to just node_modules + .git, so - // stale compiled tests in `dist/` (left over from earlier `tsc -b` runs) - // get picked up and crash on missing build-time relative imports. Restrict - // discovery to the source tree explicitly. - include: ['src/**/*.test.ts'], - exclude: ['**/node_modules/**', '**/dist/**', '**/.git/**'], + projects: [ + { + extends: true, + test: { + name: 'server', + // Vitest 4 narrowed the default `exclude` to just node_modules + .git, so + // stale compiled tests in `dist/` (left over from earlier `tsc -b` runs) + // get picked up and crash on missing build-time relative imports. Restrict + // discovery to the source tree explicitly. + include: ['src/**/*.test.ts'], + exclude: [...defaultExclude, ...databaseTestFiles], + }, + }, + // Database tests: one file at a time against the database in DATABASE_URL. + { + extends: true, + test: { + name: 'server-db', + sequence: { groupOrder: 0 }, + fileParallelism: false, + globalSetup: ['./test/require-database-url.ts'], + include: databaseTestFiles, + exclude: [...defaultExclude, ...exclusiveTestFiles], + }, + }, + // Runs after the 'server-db' group, one file at a time. + { + extends: true, + test: { + name: 'server-db-exclusive', + sequence: { groupOrder: 1 }, + fileParallelism: false, + globalSetup: ['./test/require-database-url.ts'], + include: exclusiveTestFiles, + }, + }, + ], }, }); diff --git a/apps/web/e2e/ops-tools-security.spec.ts b/apps/web/e2e/ops-tools-security.spec.ts new file mode 100644 index 00000000..d9bc5d8e --- /dev/null +++ b/apps/web/e2e/ops-tools-security.spec.ts @@ -0,0 +1,324 @@ +import { Buffer } from 'node:buffer'; +import { expect, test, type APIRequestContext, type Page } from '@playwright/test'; + +// Operator-tools security: HTML event attributes, map-name marker execution, +// Content-Security-Policy on /tools, and production 404s for atelier entries. +// Talks to the API server that mounts /tools (WEB_BASE_URL must be that origin). +// Credentials come from the environment; authentication uses the real API. No API route mocks. +// +// Runs only with E2E_RUN=true plus WEB_BASE_URL, TOOLS_USER, TOOLS_PASSWORD, +// E2E_ADMIN_EMAIL and E2E_ADMIN_PASSWORD. + +const SHOULD_RUN = + process.env.E2E_RUN === 'true' && + Boolean(process.env.WEB_BASE_URL) && + Boolean(process.env.TOOLS_USER) && + Boolean(process.env.TOOLS_PASSWORD); + +const it = SHOULD_RUN ? test : test.skip; + +const MARKER_PREFIX = "');window.__opsToolsMarker=1;//"; +const DELETE_LIST = /^L.schen$/; +const DELETE_DETAIL = /^Map l.schen$/; +let adminToken = ''; +let tenantId = ''; + +const EVENT_ATTR_TOOLS = [ + 'super-admin.html', + 'map-editor.html', + 'avatar-pack-manager.html', + 'npc-admin.html', +] as const; + +const ROOT_TOOLS = [ + ...EVENT_ATTR_TOOLS, + 'sprite-asset-cutter.html', + 'ui-prototype.html', +] as const; + +const ATELIER_PATHS = [ + '/tools/asset-lab/index.html', + '/tools/asset-lab/design/compact-collection.html', + '/tools/asset-lab/design/detail-study.html', +] as const; + +type MarkerAction = 'copy-list' | 'delete-list' | 'copy-detail' | 'delete-detail'; + +test.use({ + httpCredentials: { + username: process.env.TOOLS_USER ?? '', + password: process.env.TOOLS_PASSWORD ?? '', + }, +}); + +function toolsAuthorization(): string { + const user = process.env.TOOLS_USER ?? ''; + const password = process.env.TOOLS_PASSWORD ?? ''; + return `Basic ${Buffer.from(`${user}:${password}`, 'utf8').toString('base64')}`; +} + +function adminAuthorization(): string { + return `Bearer ${adminToken}`; +} + +test.beforeAll(async ({ playwright }) => { + const email = process.env.E2E_ADMIN_EMAIL; + const password = process.env.E2E_ADMIN_PASSWORD; + if (!email || !password) { + throw new Error('Missing required environment variables: E2E_ADMIN_EMAIL and E2E_ADMIN_PASSWORD'); + } + + const api = await playwright.request.newContext({ baseURL: process.env.WEB_BASE_URL }); + try { + const response = await api.post('/auth/login', { + headers: { Origin: 'tauri://localhost' }, + data: { email, password }, + }); + expect(response.status(), 'admin login must succeed').toBe(200); + const body = (await response.json()) as { token?: string }; + expect(body.token, 'admin login must return a session token').toBeTruthy(); + adminToken = body.token ?? ''; + const claims = JSON.parse(Buffer.from(adminToken.split('.')[1] ?? '', 'base64url').toString('utf8')) as { + tid?: string; + }; + expect(claims.tid, 'admin session must include a tenant claim').toBeTruthy(); + tenantId = claims.tid ?? ''; + } finally { + await api.dispose(); + } +}); + +function probeMapName(): string { + return `${MARKER_PREFIX}${crypto.randomUUID()}`; +} + +function countEventAttributesInBytes(html: string): number { + return [...html.matchAll(/<[^>]*\son[a-z]+\s*=/gi)].length; +} + +function parseCsp(header: string): Map { + const directives = new Map(); + for (const part of header.split(';')) { + const bits = part.trim().split(/\s+/).filter(Boolean); + if (bits.length === 0) continue; + directives.set(bits[0].toLowerCase(), bits.slice(1)); + } + return directives; +} + +function assertOperatorToolsCsp(header: string | undefined): void { + expect(header, 'Content-Security-Policy header is missing').toBeTruthy(); + const directives = parseCsp(header ?? ''); + const values = [...directives.values()].flat(); + expect(values).not.toContain("'unsafe-inline'"); + expect(values).not.toContain("'unsafe-hashes'"); + expect(values).not.toContain("'unsafe-eval'"); + expect(directives.get('script-src-attr')).toEqual(["'none'"]); + expect(directives.get('object-src')).toEqual(["'none'"]); + expect(directives.get('base-uri')).toEqual(["'none'"]); + expect(directives.get('frame-ancestors')).toEqual(["'none'"]); +} + +async function toolsGet(request: APIRequestContext, path: string) { + return request.get(path, { headers: { Authorization: toolsAuthorization() } }); +} + +async function countEventAttributesInDom(page: Page): Promise { + return page.evaluate(() => { + let count = 0; + for (const el of document.querySelectorAll('*')) { + for (const attr of el.attributes) { + if (/^on[a-z]+$/i.test(attr.name)) count += 1; + } + } + return count; + }); +} + +async function markerValue(page: Page): Promise { + return page.evaluate(() => { + const w: Window & { __opsToolsMarker?: unknown } = window; + return w.__opsToolsMarker; + }); +} + +function mapRow(page: Page, mapName: string) { + return page.getByRole('row').filter({ hasText: mapName }); +} + +async function createProbeMap(request: APIRequestContext): Promise<{ id: string; name: string }> { + const name = probeMapName(); + const res = await request.post('/admin/maps', { + headers: { + Authorization: adminAuthorization(), + 'Content-Type': 'application/json', + }, + data: { + tenantId, + name, + width: 8, + height: 8, + tileWidth: 16, + tileHeight: 16, + }, + }); + expect(res.status(), 'creating the probe map must succeed').toBe(200); + const body = (await res.json()) as { id: string; name: string }; + expect(body.name).toBe(name); + return { id: body.id, name }; +} + +async function deleteProbeMap(request: APIRequestContext, id: string): Promise { + await request.delete(`/admin/maps/${id}`, { headers: { Authorization: adminAuthorization() } }); +} + +async function openSuperAdmin(page: Page): Promise { + page.on('dialog', async (dialog) => { + await dialog.dismiss(); + }); + await page.goto('/tools/super-admin.html'); +} + +async function connectAndOpenMaps(page: Page): Promise { + await openSuperAdmin(page); + await page.getByPlaceholder('Auth Token (optional)').fill(adminToken); + await page.getByRole('button', { name: 'Test' }).click(); + await expect(page.getByText('Verbunden mit Server')).toBeVisible(); + await page.getByText('Maps', { exact: true }).click(); + await expect(page.getByText('Karten verwalten, importieren und zwischen Tenants kopieren')).toBeVisible(); +} + +async function expectProbeMapLiteral(page: Page, mapName: string): Promise { + await expect(mapRow(page, mapName).getByText(mapName, { exact: true })).toBeVisible(); +} + +async function runMarkerAction(page: Page, mapName: string, action: MarkerAction): Promise { + const row = mapRow(page, mapName); + if (action === 'copy-list') { + await row.getByRole('button', { name: 'Kopieren' }).click(); + return; + } + if (action === 'delete-list') { + await row.getByRole('button', { name: DELETE_LIST }).click(); + await page.getByRole('button', { name: 'Abbrechen' }).click(); + return; + } + await row.getByText(mapName, { exact: true }).click(); + if (action === 'copy-detail') { + await page.getByRole('button', { name: 'Map kopieren' }).click(); + return; + } + await page.getByRole('button', { name: DELETE_DETAIL }).click(); + await page.getByRole('button', { name: 'Abbrechen' }).click(); +} + +test.describe('operator tools security', () => { + for (const file of EVENT_ATTR_TOOLS) { + it(`${file} has no HTML event attributes in delivered bytes or rendered DOM`, async ({ page, request }) => { + const path = `/tools/${file}`; + const res = await toolsGet(request, path); + expect(res.status(), `${path} must be served`).toBe(200); + expect(countEventAttributesInBytes(await res.text())).toBe(0); + + if (file === 'super-admin.html') { + const map = await createProbeMap(request); + try { + await connectAndOpenMaps(page); + await expectProbeMapLiteral(page, map.name); + } finally { + await deleteProbeMap(request, map.id); + } + } else { + await page.goto(path); + } + + expect(await countEventAttributesInDom(page)).toBe(0); + }); + } + + const markerCases: Array<{ action: MarkerAction; title: string }> = [ + { action: 'copy-list', title: 'copying a map from the list' }, + { action: 'delete-list', title: 'deleting a map from the list' }, + { action: 'copy-detail', title: 'copying a map from the detail view' }, + { action: 'delete-detail', title: 'deleting a map from the detail view' }, + ]; + + for (const { action, title } of markerCases) { + it(`${title} does not run a name marker and shows the name as text`, async ({ page, request }) => { + const map = await createProbeMap(request); + try { + await connectAndOpenMaps(page); + await expectProbeMapLiteral(page, map.name); + await runMarkerAction(page, map.name, action); + expect(await markerValue(page)).toBeUndefined(); + await expectProbeMapLiteral(page, map.name); + } finally { + await deleteProbeMap(request, map.id); + } + }); + } + + for (const file of ROOT_TOOLS) { + it(`${file} response sends the operator tools Content-Security-Policy`, async ({ request }) => { + const path = `/tools/${file}`; + const res = await toolsGet(request, path); + expect(res.status(), `${path} must be served`).toBe(200); + assertOperatorToolsCsp(res.headers()['content-security-policy']); + }); + } + + for (const path of ATELIER_PATHS) { + it(`${path} is not served under /tools`, async ({ request }) => { + const res = await toolsGet(request, path); + expect(res.status()).toBe(404); + }); + } + + it('super-admin maps navigation still works', async ({ page }) => { + await openSuperAdmin(page); + await page.getByText('Maps', { exact: true }).click(); + await expect(page.getByText('Karten verwalten, importieren und zwischen Tenants kopieren')).toBeVisible(); + await expect(page.getByRole('button', { name: '+ Neue Map' })).toBeVisible(); + }); + + it('super-admin maps tenant filter still re-renders', async ({ page, request }) => { + const map = await createProbeMap(request); + try { + await connectAndOpenMaps(page); + await expectProbeMapLiteral(page, map.name); + await page.getByRole('combobox').selectOption({ index: 0 }); + await expectProbeMapLiteral(page, map.name); + await expect(mapRow(page, map.name).getByRole('button', { name: 'Kopieren' })).toBeVisible(); + } finally { + await deleteProbeMap(request, map.id); + } + }); + + it('super-admin new map form still accepts edits', async ({ page }) => { + await openSuperAdmin(page); + await page.getByText('Maps', { exact: true }).click(); + await page.getByRole('button', { name: '+ Neue Map' }).click(); + await expect(page.getByText('Neue Map erstellen')).toBeVisible(); + const nameField = page.getByPlaceholder('Meine Karte'); + await nameField.fill('ops-tools-form-probe'); + await expect(nameField).toHaveValue('ops-tools-form-probe'); + }); + + it('super-admin maps list still re-renders after a form toggle and section change', async ({ page, request }) => { + const map = await createProbeMap(request); + try { + await connectAndOpenMaps(page); + await expectProbeMapLiteral(page, map.name); + await page.getByRole('button', { name: '+ Neue Map' }).click(); + await expect(page.getByText('Neue Map erstellen')).toBeVisible(); + await page.getByRole('button', { name: 'Abbrechen' }).click(); + await expect(page.getByText('Neue Map erstellen')).toHaveCount(0); + await expectProbeMapLiteral(page, map.name); + await page.getByText('Mandanten', { exact: true }).click(); + await page.getByText('Maps', { exact: true }).click(); + await expectProbeMapLiteral(page, map.name); + } finally { + await deleteProbeMap(request, map.id); + } + }); +}); diff --git a/compose.yaml b/compose.yaml index ad45fe89..1fa0fa8e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -59,7 +59,7 @@ services: db: condition: service_healthy command: >- - sh -lc "npx prisma migrate deploy --schema \"$${PRISMA_SCHEMA}\" && (npx prisma db seed --schema \"$${PRISMA_SCHEMA}\" || true)" + sh -lc "node dist/ops/startupCredentials.js && npx prisma migrate deploy --schema \"$${PRISMA_SCHEMA}\" && (npx prisma db seed --schema \"$${PRISMA_SCHEMA}\" || true)" restart: 'no' db: @@ -98,6 +98,12 @@ services: environment: NODE_ENV: production PORT: 2567 + # Scrape listener: reachable on the compose network, never published + # to the host and never routed through a reverse proxy. Unset the + # port to disable it. METRICS_HOST must be the container interface so + # a sidecar scraper can connect; the process default is loopback. + METRICS_PORT: 9100 + METRICS_HOST: 0.0.0.0 TRUST_PROXY: ${TRUST_PROXY:-false} # The migrate service ran prisma migrate deploy before the server # came up. Skip the entrypoint pass to avoid a redundant migration @@ -110,7 +116,10 @@ services: LIVEKIT_API_SECRET: ${LIVEKIT_API_SECRET:-secret} API_TOKEN_PEPPER: ${API_TOKEN_PEPPER:?API_TOKEN_PEPPER is required} JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required} - CORS_ORIGIN: ${CORS_ORIGIN:-http://localhost:5173} + # Exact origins only, required: the web origin of this deployment, both + # desktop origins of the official app and, for the /tools pages, the API + # origin itself. See docs/origin-allowlist.md. + CORS_ORIGIN: ${CORS_ORIGIN:?CORS_ORIGIN is required} ASSET_PACKS_DIR: /workspace/apps/public/packs PRISMA_CLI_QUERY_ENGINE_TYPE: library PRISMA_CLIENT_ENGINE_TYPE: library diff --git a/docs/metrics.md b/docs/metrics.md new file mode 100644 index 00000000..fb277924 --- /dev/null +++ b/docs/metrics.md @@ -0,0 +1,22 @@ +# Prometheus scrape listener + +The public HTTP port (default 2567) answers `GET` and `HEAD` `/metrics` +with 404, with or without cookies or tools credentials. Scrapes go to a +separate listener. + +| Variable | Default | Role | +| -------------- | ------------------------------- | -------------------------------------------- | +| `METRICS_PORT` | unset (listener off) | TCP port of the scrape listener | +| `METRICS_HOST` | loopback | Bind address; compose sets the container NIC | + +The bundled `compose.yaml` sets `METRICS_PORT` and `METRICS_HOST` on the +server service and does **not** add a `ports` mapping for the scrape +listener. `prometheus/prometheus.yml` targets `server:9100`. A scraper +must share the compose network. Publishing the port to the host, or +proxying it, would expose the metrics surface; do not add either. + +An invalid `METRICS_PORT` (not a TCP port, equal to `PORT`, or a bind +failure) stops startup. Both listeners close on graceful shutdown. + +Self-hosters who already scrape `server:2567/metrics` must point the +scrape job at `server:9100` (or the `METRICS_PORT` they chose). diff --git a/docs/origin-allowlist.md b/docs/origin-allowlist.md new file mode 100644 index 00000000..277a7abe --- /dev/null +++ b/docs/origin-allowlist.md @@ -0,0 +1,74 @@ +# The origin allowlist + +One list, `CORS_ORIGIN`, decides which browser origins may talk to the +server. It is read once at start and used by every entry point: + +- the HTTP API (Express), +- the matchmaking route (Colyseus), which answers before Express runs, +- the websocket upgrade. + +There is no second rule anywhere. A request cannot be allowed on one path and +refused on another. + +## What an entry looks like + +An entry is an exact origin: `scheme://host` or `scheme://host:port`. + +- `https://app.example` - the web client on that host. +- `tauri://localhost` - the desktop app on macOS and Linux. +- `http://tauri.localhost` - the desktop app on Windows (WebView2). + +Refused at start, because they are not exact origins: + +- `*` and `https://*.example` - a wildcard or a suffix rule, +- `https://example/app` - a path, an origin never has one, +- `null` - the value a browser sends for a sandboxed document, +- `https://example:0` and `https://example:99999` - a port out of range, +- `HTTPS://example` - the scheme is lowercase in an origin. + +A list with one bad entry refuses the whole start: a typo must not silently +narrow the allowlist. + +## What the server does with a request + +- An allowed origin is served. The answer carries + `Access-Control-Allow-Origin` with exactly that origin, + `Access-Control-Allow-Credentials: true`, the fixed list of request + headers the server needs (never the headers the caller asked for) and a + `Vary: Origin` that is added to the existing one, not written over. +- An origin that is not listed gets `403` and no CORS headers at all. +- `Origin: null` gets `403` and no CORS headers at all. +- A request without an `Origin` header is not a browser request. It stays + possible for native clients, webhooks and health checks, gets no CORS + headers, and is decided by the route's own auth. +- A websocket upgrade with a listed origin proceeds. +- A websocket upgrade with a foreign origin is refused before the `101`. +- A websocket upgrade without an origin proceeds; the matchmaking auth and + the seat reservation decide whether it reaches a room. + +## The start refuses a missing list + +`CORS_ORIGIN` is required in every mode, development included. Without a +valid list the server writes a message that names the key to stderr and exits +with status 1 before it serves anything. The value is never printed. The +Compose file refuses to start the stack when the key is not set at all. + +Development therefore needs an explicit local list, for example the web dev +server of the Vite setup: + +``` +CORS_ORIGIN=http://localhost:5173,http://localhost:5174,tauri://localhost,http://tauri.localhost +``` + +## The public assets keep their own contract + +`/packs`, `/assets` and `/npc-media` are public static files and answer with +`Access-Control-Allow-Origin: *` of their own. The allowlist does not apply +to them. + +## The operator tools + +The `/tools` pages are served from the origin of the deployment itself. There +is no same-origin exception any more: a browser sends an `Origin` header with +every non-simple request, so an operator who uses the tools lists the API +origin of the deployment in `CORS_ORIGIN` as well. diff --git a/prometheus/prometheus.yml b/prometheus/prometheus.yml index 66438bb4..1bfb9203 100644 --- a/prometheus/prometheus.yml +++ b/prometheus/prometheus.yml @@ -2,10 +2,12 @@ global: scrape_interval: 5s scrape_configs: + # Internal metrics listener (METRICS_PORT). The public app port answers + # GET/HEAD /metrics with 404 and is not a scrape target. - job_name: 'meetropolis-server' metrics_path: /metrics static_configs: - - targets: ['server:2567'] + - targets: ['server:9100'] - job_name: 'livekit' metrics_path: /metrics diff --git a/tools/avatar-pack-manager.html b/tools/avatar-pack-manager.html index 23ec6215..f2a01dd8 100644 --- a/tools/avatar-pack-manager.html +++ b/tools/avatar-pack-manager.html @@ -323,6 +323,23 @@ .toast-item.ok{background:#1a2e1f;color:var(--green);border:1px solid rgba(59,165,93,0.3)} .toast-item.err{background:#2e1a1a;color:var(--red);border:1px solid rgba(237,66,69,0.3)} @keyframes toastIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}} + +/* Utility classes replacing former inline style attributes */ +.is-hidden{display:none!important} +.hint-muted{font-size:11px;color:var(--fg-muted)} +.mt-8{margin-top:8px} +.mt-6{margin-top:6px} +.mb-6{margin-bottom:6px} +.inline-row{display:flex;gap:6px;align-items:center} +.inline-row-sm{display:flex;gap:4px;align-items:center} +.inline-row-md{display:flex;gap:8px;align-items:center} +.status-mono{font-family:var(--font-mono);font-size:10px;color:var(--fg-dim)} +.btn-icon{padding:2px 6px} +.btn-icon-end{margin-left:auto;padding:2px 6px} +.state-count{font-size:9px;color:var(--fg-muted)} +.preview-thumb{margin-top:6px;max-width:64px;max-height:96px;image-rendering:pixelated;border:1px solid var(--border);border-radius:3px;background:var(--bg-deep)} +.preview-meta{margin-top:4px;font-family:var(--font-mono);font-size:10px;color:var(--fg-muted)} +#uploadMsg{margin-top:6px} @@ -351,7 +368,7 @@

AVATAR PACK MANAGER

- +
@@ -393,17 +410,17 @@

AVATAR PACK MANAGER

- +
- +
- @@ -422,25 +439,25 @@

AVATAR PACK MANAGER

-
Connect to server to load packs.
+
Connect to server to load packs.
- @@ -310,12 +358,12 @@

MAP EDITOR

-
- +
@@ -323,28 +371,28 @@

MAP EDITOR

- - - - - - - -
@@ -353,25 +401,25 @@

MAP EDITOR

-
-
Terrain
-
Structures
-
Objects
-
Autotiles
+
Terrain
+
Structures
+
Objects
+
Autotiles
Connect and select a pack.
- @@ -380,27 +428,27 @@

MAP EDITOR

- +
- +
- +
- +
- +
- - + + 2x
@@ -596,6 +644,58 @@

MAP EDITOR

return String(s).replace(/&/g,'&').replace(/'/g,''').replace(/"/g,'"').replace(//g,'>'); } +const ORIGIN_BLOCKED = 'The API origin is not in the allowed configuration.'; + +function requestErrorMessage(e, prefix) { + if (e instanceof TypeError) return ORIGIN_BLOCKED; + const msg = e && e.message ? e.message : 'Request failed'; + return prefix ? prefix + msg : msg; +} + +function h(tag, props, children) { + const n = document.createElement(tag); + if (props) { + Object.keys(props).forEach((k) => { + const v = props[k]; + if (v == null || v === false) return; + if (k === 'className') n.className = v; + else if (k === 'dataset') { + Object.keys(v).forEach((dk) => { + if (v[dk] != null) n.dataset[dk] = String(v[dk]); + }); + } else if (k === 'text') n.textContent = v; + else if (k === 'checked' || k === 'disabled' || k === 'selected') n[k] = true; + else if (k === 'value') n.value = v; + else if (k === 'colSpan') n.colSpan = v; + else if (k === 'id' || k === 'title') n[k] = v; + else n.setAttribute(k, String(v)); + }); + } + const list = children == null ? [] : Array.isArray(children) ? children : [children]; + list.forEach((c) => { + if (c == null || c === false) return; + n.appendChild(typeof c === 'string' || typeof c === 'number' ? document.createTextNode(String(c)) : c); + }); + return n; +} + +function emptyState(text) { + return h('div', { className: 'empty-state', text: text }); +} + +function propRow(label, value, valueClass) { + return h('div', { className: 'prop-row' }, [ + h('span', { className: 'prop-label', text: label }), + h('span', { className: 'prop-value' + (valueClass ? ' ' + valueClass : ''), text: String(value) }), + ]); +} + +function restoreSaveButtonLabel(btn) { + btn.replaceChildren(); + btn.appendChild(document.createTextNode('Save ')); + btn.appendChild(h('span', { id: 'saveBadge', className: 'save-badge' })); +} + // ============================================================================ // API // ============================================================================ @@ -637,12 +737,9 @@

MAP EDITOR

// Populate map dropdown const sel = document.getElementById('mapSelect'); - sel.innerHTML = ''; + sel.replaceChildren(h('option', { value: '', text: '-- select map --' })); for (const m of maps) { - const opt = document.createElement('option'); - opt.value = m.id; - opt.textContent = m.name; - sel.appendChild(opt); + sel.appendChild(h('option', { value: m.id, text: m.name })); } // Load asset packs @@ -658,20 +755,17 @@

MAP EDITOR

} catch (e) { dot.className = 'conn-dot err'; label.textContent = 'Error'; - showMsg(msg, 'err', e.message); + showMsg(msg, 'err', requestErrorMessage(e)); CFG.connected = false; } } function populatePackSelect() { const sel = document.getElementById('packSelect'); - sel.innerHTML = ''; + sel.replaceChildren(h('option', { value: '', text: '-- select pack --' })); for (let i = 0; i < assetPacks.length; i++) { const p = assetPacks[i]; - const opt = document.createElement('option'); - opt.value = i; - opt.textContent = p.name || p.uuid; - sel.appendChild(opt); + sel.appendChild(h('option', { value: String(i), text: p.name || p.uuid })); } } @@ -754,7 +848,7 @@

MAP EDITOR

markDirty(); toast('ok', `Loaded map: ${name}`); } catch (e) { - toast('err', `Failed to load map: ${e.message}`); + toast('err', requestErrorMessage(e, 'Failed to load map: ')); console.error(e); } } @@ -1606,7 +1700,7 @@

MAP EDITOR

function renderAssetBrowser() { const container = document.getElementById('assetBrowser'); if (selectedPackIdx < 0 || !assetPacks[selectedPackIdx]) { - container.innerHTML = '
Select an asset pack.
'; + container.replaceChildren(emptyState('Select an asset pack.')); return; } @@ -1616,20 +1710,19 @@

MAP EDITOR

if (currentCat === 'autotiles') { const autotiles = pack.autotiles || []; if (autotiles.length === 0) { - container.innerHTML = '
No autotile items in this pack.
'; + container.replaceChildren(emptyState('No autotile items in this pack.')); return; } - container.innerHTML = ''; - const grid = document.createElement('div'); - grid.className = 'asset-grid'; + container.replaceChildren(); + const grid = h('div', { className: 'asset-grid' }); autotiles.forEach((item, idx) => { const isSelected = selectedAutotile && selectedAutotile.packUuid === pack.uuid && selectedAutotile.autotileId === item.id; - const el = document.createElement('div'); - el.className = 'asset-item' + (isSelected ? ' selected' : ''); - el.onclick = () => selectAutotile(selectedPackIdx, idx); + const el = h('div', { + className: 'asset-item' + (isSelected ? ' selected' : ''), + dataset: { action: 'select-autotile', packIdx: String(selectedPackIdx), itemIdx: String(idx) }, + }); - const img = document.createElement('img'); - img.style.cssText = 'max-width:64px;max-height:64px;image-rendering:pixelated'; + const img = h('img', { className: 'asset-thumb' }); const url = item.dataURL || item.dataUrl; if (url && url.startsWith('/')) { img.src = CFG.server + url; @@ -1639,11 +1732,7 @@

MAP EDITOR

img.onerror = () => { img.style.display = 'none'; }; el.appendChild(img); - const label = document.createElement('div'); - label.className = 'asset-label'; - label.textContent = item.key || item.id; - el.appendChild(label); - + el.appendChild(h('div', { className: 'asset-label', text: item.key || item.id })); grid.appendChild(el); }); container.appendChild(grid); @@ -1653,21 +1742,19 @@

MAP EDITOR

const items = pack[currentCat] || []; if (items.length === 0) { - container.innerHTML = `
No ${currentCat} items in this pack.
`; + container.replaceChildren(emptyState('No ' + currentCat + ' items in this pack.')); return; } - container.innerHTML = ''; - const grid = document.createElement('div'); - grid.className = 'asset-grid'; + container.replaceChildren(); + const grid = h('div', { className: 'asset-grid' }); for (const item of items) { - const el = document.createElement('div'); - el.className = 'asset-item'; - if (selectedAssetItem && selectedAssetItem.item.id === item.id) { - el.classList.add('selected'); - } - el.title = item.key || item.id; + const el = h('div', { + className: 'asset-item' + (selectedAssetItem && selectedAssetItem.item.id === item.id ? ' selected' : ''), + title: item.key || item.id, + dataset: { action: 'select-asset-item', itemId: item.id, cat: currentCat }, + }); const img = document.createElement('img'); img.crossOrigin = 'anonymous'; @@ -1680,12 +1767,7 @@

MAP EDITOR

img.onerror = () => { img.style.display = 'none'; }; el.appendChild(img); - const label = document.createElement('div'); - label.className = 'asset-label'; - label.textContent = item.key || item.id; - el.appendChild(label); - - el.addEventListener('click', () => selectAssetItem(pack, item, currentCat)); + el.appendChild(h('div', { className: 'asset-label', text: item.key || item.id })); grid.appendChild(el); } container.appendChild(grid); @@ -1765,7 +1847,7 @@

MAP EDITOR

} toast('ok', `Tileset registered: ${tsKey}`); } catch (e) { - toast('err', `Failed to register tileset: ${e.message}`); + toast('err', requestErrorMessage(e, 'Failed to register tileset: ')); return; } } @@ -1776,7 +1858,7 @@

MAP EDITOR

if (!img) return; const wrap = document.getElementById('tilePickerWrap'); - wrap.style.display = 'block'; + wrap.classList.remove('is-hidden'); const pickerCanvas = document.getElementById('tilePickerCanvas'); const scale = 2; @@ -1829,7 +1911,7 @@

MAP EDITOR

} function hideTilePicker() { - document.getElementById('tilePickerWrap').style.display = 'none'; + document.getElementById('tilePickerWrap').classList.add('is-hidden'); } // Tile picker click handler @@ -2700,39 +2782,67 @@

MAP EDITOR

function updateMapInfo() { const el = document.getElementById('mapInfo'); if (!mapMeta) { - el.innerHTML = '
No map loaded.
'; + el.replaceChildren(emptyState('No map loaded.')); return; } - el.innerHTML = ` -
- Name -
- - -
-
-
- Size -
- - x - - -
-
-
Tile Size${mapMeta.tileWidth || '?'} x ${mapMeta.tileHeight || '?'} px
-
Chunk Size${mapMeta.chunkSize || 32}
-
Tilesets${tilesetRegistry.length}
-
Objects${mapObjects.length}
- `; + el.replaceChildren( + h('div', { className: 'prop-row align-center' }, [ + h('span', { className: 'prop-label', text: 'Name' }), + h('div', { className: 'inline-edit' }, [ + h('input', { + type: 'text', + id: 'mapNameInput', + className: 'inline-text-input', + value: currentMapName, + dataset: { action: 'map-name-input' }, + }), + h('button', { + id: 'renameBtn', + className: 'btn btn-sm btn-inline', + disabled: true, + dataset: { action: 'rename-map' }, + text: 'Rename', + }), + ]), + ]), + h('div', { className: 'prop-row align-center' }, [ + h('span', { className: 'prop-label', text: 'Size' }), + h('div', { className: 'inline-edit align-center' }, [ + h('input', { + type: 'number', + id: 'mapWidthInput', + className: 'inline-size-input', + value: String(mapMeta.width || 32), + min: '8', + max: '512', + step: '1', + dataset: { action: 'map-size-input' }, + }), + h('span', { className: 'size-sep', text: 'x' }), + h('input', { + type: 'number', + id: 'mapHeightInput', + className: 'inline-size-input', + value: String(mapMeta.height || 32), + min: '8', + max: '512', + step: '1', + dataset: { action: 'map-size-input' }, + }), + h('button', { + id: 'resizeBtn', + className: 'btn btn-sm btn-inline', + disabled: true, + dataset: { action: 'resize-map' }, + text: 'Resize', + }), + ]), + ]), + propRow('Tile Size', (mapMeta.tileWidth || '?') + ' x ' + (mapMeta.tileHeight || '?') + ' px'), + propRow('Chunk Size', mapMeta.chunkSize || 32), + propRow('Tilesets', tilesetRegistry.length), + propRow('Objects', mapObjects.length), + ); } function onMapNameInputChange() { @@ -2741,8 +2851,7 @@

MAP EDITOR

const newName = (input.value || '').trim(); const changed = newName.length > 0 && newName !== currentMapName; btn.disabled = !changed; - btn.style.background = changed ? 'var(--accent)' : ''; - btn.style.color = changed ? 'white' : ''; + btn.classList.toggle('btn-ready', changed); } function onMapSizeInputChange() { @@ -2755,35 +2864,40 @@

MAP EDITOR

const validH = Number.isInteger(h) && h >= 8 && h <= 512; const changed = validW && validH && (w !== (mapMeta.width || 32) || h !== (mapMeta.height || 32)); btn.disabled = !changed; - btn.style.background = changed ? 'var(--accent)' : ''; - btn.style.color = changed ? 'white' : ''; + btn.classList.toggle('btn-ready', changed); } function updateZoneList() { const el = document.getElementById('zoneList'); const zones = editorState ? (editorState.zones || []) : []; if (zones.length === 0) { - el.innerHTML = '
No zones defined.
'; + el.replaceChildren(emptyState('No zones defined.')); return; } - el.innerHTML = zones.map(z => { + el.replaceChildren(); + zones.forEach((z) => { const isPortal = z.type === 'portal'; - const dotColor = isPortal ? '#a855f7' : 'var(--accent)'; const metaText = isPortal - ? 'Portal \u2192 ' + esc(z.portalTarget || '?') + ? 'Portal \u2192 ' + (z.portalTarget || '?') : ('Cap: ' + (z.capacity || 'unlimited')); - return ` -
-
- -
-
${esc(z.name || 'Zone')}
-
${metaText}
-
-
- -
`; - }).join(''); + el.appendChild(h('div', { + className: 'zone-item' + (selectedZoneId === z.id ? ' selected' : ''), + dataset: { action: 'select-zone', zoneId: z.id }, + }, [ + h('div', { className: 'zone-item-main' }, [ + h('span', { className: 'zone-dot' + (isPortal ? ' portal' : '') }), + h('div', null, [ + h('div', { className: 'zone-name', text: z.name || 'Zone' }), + h('div', { className: 'zone-meta', text: metaText }), + ]), + ]), + h('button', { + className: 'btn btn-sm btn-danger', + dataset: { action: 'delete-zone', zoneId: z.id }, + text: 'Del', + }), + ])); + }); } function updateSpawnDisplay() { @@ -2814,125 +2928,152 @@

MAP EDITOR

const th = mapMeta ? (mapMeta.tileHeight || 16) : 16; const zoneType = zone.type || 'default'; const isPortal = zoneType === 'portal'; - const typeColor = isPortal ? '#a855f7' : 'var(--accent)'; const typeLabel = isPortal ? 'Portal' : 'Zone'; - const mapOptions = availableMaps - .filter(m => m.name !== currentMapName) - .map(m => ``) - .join(''); - const portalFieldsHtml = ` -
-
- - -
-
-
- - -
-
- - -
-
-
`; - el.innerHTML = ` -
Type${typeLabel}
-
ID${esc(zone.id)}
-
Name${esc(zone.name || 'Zone')}
-
Capacity${zone.capacity || 'unlimited'}
-
Bounds (px)${Math.round(minX)}, ${Math.round(minY)} \u2192 ${Math.round(maxX)}, ${Math.round(maxY)}
-
Size (tiles)${Math.round((maxX - minX) / tw)} x ${Math.round((maxY - minY) / th)}
-
- -
- - -
- ${portalFieldsHtml} -
-
- -
- -
-
- Switch to Zones tool and drag to extend this zone. -
-
- `; + const portalTarget = h('select', { + id: 'propPortalTarget', + dataset: { action: 'update-zone-portal', zoneId: zone.id, prop: 'portalTarget' }, + }, [ + h('option', { value: '', text: '-- Ziel wählen --' }), + ]); + availableMaps.filter((m) => m.name !== currentMapName).forEach((m) => { + portalTarget.appendChild(h('option', { + value: m.name, + text: m.name, + selected: zone.portalTarget === m.name, + })); + }); + const portalFields = h('div', { + id: 'portalFields', + className: 'mt-8' + (isPortal ? '' : ' is-hidden'), + }, [ + h('div', { className: 'field' }, [ + h('label', { text: 'Portal Target' }), + portalTarget, + ]), + h('div', { className: 'field-row' }, [ + h('div', { className: 'field' }, [ + h('label', { text: 'Spawn X' }), + h('input', { + type: 'number', + id: 'propPortalSpawnX', + value: zone.portalSpawnX != null ? String(zone.portalSpawnX) : '', + placeholder: 'opt', + dataset: { action: 'update-zone-portal', zoneId: zone.id, prop: 'portalSpawnX' }, + }), + ]), + h('div', { className: 'field' }, [ + h('label', { text: 'Spawn Y' }), + h('input', { + type: 'number', + id: 'propPortalSpawnY', + value: zone.portalSpawnY != null ? String(zone.portalSpawnY) : '', + placeholder: 'opt', + dataset: { action: 'update-zone-portal', zoneId: zone.id, prop: 'portalSpawnY' }, + }), + ]), + ]), + ]); + el.replaceChildren( + propRow('Type', typeLabel, isPortal ? 'portal-color' : 'zone-color'), + propRow('ID', zone.id), + propRow('Name', zone.name || 'Zone'), + propRow('Capacity', zone.capacity || 'unlimited'), + propRow('Bounds (px)', Math.round(minX) + ', ' + Math.round(minY) + ' \u2192 ' + Math.round(maxX) + ', ' + Math.round(maxY)), + propRow('Size (tiles)', Math.round((maxX - minX) / tw) + ' x ' + Math.round((maxY - minY) / th)), + h('div', { className: 'mt-8' }, [ + h('div', { className: 'section-label mb-6', text: 'Zone Settings' }), + h('div', { className: 'field' }, [ + h('label', { text: 'Zone Type' }), + h('select', { + id: 'propZoneType', + dataset: { action: 'update-zone-portal', zoneId: zone.id, prop: 'type' }, + }, [ + h('option', { value: 'default', text: 'default', selected: zoneType === 'default' }), + h('option', { value: 'portal', text: 'portal', selected: zoneType === 'portal' }), + ]), + ]), + portalFields, + ]), + h('div', { className: 'mt-8' }, [ + h('div', { className: 'section-label mb-6', text: 'Actions' }), + h('div', { className: 'btn-row' }, [ + h('button', { + className: 'btn btn-sm btn-danger', + dataset: { action: 'delete-zone', zoneId: zone.id }, + text: 'Delete Zone', + }), + ]), + h('div', { className: 'hint-text', text: 'Switch to Zones tool and drag to extend this zone.' }), + ]), + ); return; } } if (!selectedObjectId) { - el.innerHTML = '
Select an object or zone to view properties.
'; + el.replaceChildren(emptyState('Select an object or zone to view properties.')); return; } const obj = mapObjects.find(o => o.id === selectedObjectId); if (!obj) { - el.innerHTML = '
Object not found.
'; + el.replaceChildren(emptyState('Object not found.')); return; } - el.innerHTML = ` -
ID#${obj.id}
-
Item${esc(obj.itemId || '')}
-
Category${esc(obj.category || '')}
-
Pack${esc(obj.assetPackUuid || '')}
-
Position${obj.tileX}, ${obj.tileY}
-
Size${obj.width} x ${obj.height}
-
Collide${obj.collide ? 'Yes' : 'No'}
-
Z-Index${obj.zIndex || 0}
-
Rotation${obj.rotation || 0}
-
Flip X/Y${obj.flipX ? 'Y' : 'N'} / ${obj.flipY ? 'Y' : 'N'}
-
- -
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
- - -
-
- - -
-
- `; + el.replaceChildren( + propRow('ID', '#' + obj.id), + propRow('Item', obj.itemId || ''), + propRow('Category', obj.category || ''), + propRow('Pack', obj.assetPackUuid || ''), + propRow('Position', obj.tileX + ', ' + obj.tileY), + propRow('Size', obj.width + ' x ' + obj.height), + propRow('Collide', obj.collide ? 'Yes' : 'No'), + propRow('Z-Index', obj.zIndex || 0), + propRow('Rotation', obj.rotation || 0), + propRow('Flip X/Y', (obj.flipX ? 'Y' : 'N') + ' / ' + (obj.flipY ? 'Y' : 'N')), + h('div', { className: 'mt-8' }, [ + h('div', { className: 'section-label mb-6', text: 'Edit' }), + h('div', { className: 'field-row' }, [ + h('div', { className: 'field' }, [ + h('label', { text: 'Tile X' }), + h('input', { type: 'number', id: 'propTileX', value: String(obj.tileX) }), + ]), + h('div', { className: 'field' }, [ + h('label', { text: 'Tile Y' }), + h('input', { type: 'number', id: 'propTileY', value: String(obj.tileY) }), + ]), + ]), + h('div', { className: 'field-row' }, [ + h('div', { className: 'field' }, [ + h('label', { text: 'Z-Index' }), + h('input', { type: 'number', id: 'propZIndex', value: String(obj.zIndex || 0) }), + ]), + h('div', { className: 'field' }, [ + h('label', { text: 'Rotation' }), + h('input', { type: 'number', id: 'propRotation', value: String(obj.rotation || 0), step: '90' }), + ]), + ]), + h('div', { className: 'field-row mt-4' }, [ + h('label', { className: 'flip-label' }, [ + h('input', { type: 'checkbox', id: 'propFlipX', className: 'flip-check', checked: !!obj.flipX }), + ' Flip X', + ]), + h('label', { className: 'flip-label' }, [ + h('input', { type: 'checkbox', id: 'propFlipY', className: 'flip-check', checked: !!obj.flipY }), + ' Flip Y', + ]), + ]), + h('div', { className: 'btn-row' }, [ + h('button', { className: 'btn btn-accent btn-sm', dataset: { action: 'apply-prop-changes' }, text: 'Apply' }), + h('button', { + className: 'btn btn-danger btn-sm', + dataset: { action: 'delete-object', objectId: obj.id }, + text: 'Delete', + }), + ]), + ]), + ); } function applyPropChanges() { @@ -2990,7 +3131,7 @@

MAP EDITOR

} } } catch (e) { - errors.push(`Paint ${paint.layer}: ${e.message}`); + errors.push(`Paint ${paint.layer}: ${requestErrorMessage(e)}`); } } @@ -2999,7 +3140,7 @@

MAP EDITOR

try { await apiFetch(`/maps/${mapId}/objects/${objId}`, { method: 'DELETE' }); } catch (e) { - errors.push(`Delete object #${objId}: ${e.message}`); + errors.push(`Delete object #${objId}: ${requestErrorMessage(e)}`); } } @@ -3026,7 +3167,7 @@

MAP EDITOR

const idx = mapObjects.findIndex(o => o.id === obj.id); if (idx >= 0) mapObjects[idx] = created; } catch (e) { - errors.push(`Add object: ${e.message}`); + errors.push(`Add object: ${requestErrorMessage(e)}`); } } @@ -3040,7 +3181,7 @@

MAP EDITOR

const idx = mapObjects.findIndex(o => o.id === id); if (idx >= 0) mapObjects[idx] = updated; } catch (e) { - errors.push(`Update object #${id}: ${e.message}`); + errors.push(`Update object #${id}: ${requestErrorMessage(e)}`); } } @@ -3068,7 +3209,7 @@

MAP EDITOR

selectedZoneId = null; updateZoneList(); } catch (e) { - errors.push(`Zones: ${e.message}`); + errors.push(`Zones: ${requestErrorMessage(e)}`); } } @@ -3080,7 +3221,7 @@

MAP EDITOR

body: { spawn: pendingChanges.spawnUpdate }, }); } catch (e) { - errors.push(`Spawn: ${e.message}`); + errors.push(`Spawn: ${requestErrorMessage(e)}`); } } @@ -3104,7 +3245,7 @@

MAP EDITOR

} } finally { btn.disabled = !hasPendingChanges(); - btn.innerHTML = 'Save '; + restoreSaveButtonLabel(btn); updateSaveButton(); } } @@ -3138,7 +3279,7 @@

MAP EDITOR

if (!confirm(msg)) return; } } catch (e) { - toast('err', 'Resize dry-run failed: ' + (e.message || e)); + toast('err', requestErrorMessage(e, 'Resize dry-run failed: ')); return; } } @@ -3157,7 +3298,7 @@

MAP EDITOR

markDirty(); toast('ok', `Map resized to ${newWidth} x ${newHeight}`); } catch (e) { - toast('err', 'Resize failed: ' + (e.message || e)); + toast('err', requestErrorMessage(e, 'Resize failed: ')); } btn.textContent = 'Resize'; } @@ -3194,7 +3335,7 @@

MAP EDITOR

updateMapInfo(); toast('ok', `Map renamed to "${newName}"`); } catch (e) { - toast('err', 'Rename failed: ' + (e.message || e)); + toast('err', requestErrorMessage(e, 'Rename failed: ')); } btn.textContent = 'Rename'; } @@ -3239,6 +3380,80 @@

MAP EDITOR

window.addEventListener('resize', resizeCanvas); resizeCanvas(); renderLoop(); + +const actions = { + 'save-all-changes': () => { saveAllChanges(); }, + 'connect': () => { connect(); }, + 'reload-map': () => { reloadMap(); }, + 'set-tool': (el) => { setTool(el.dataset.tool); }, + 'set-cat': (el) => { setCat(el.dataset.cat); }, + 'select-zone': (el) => { selectZone(el.dataset.zoneId); }, + 'delete-zone': (el, event) => { event.stopPropagation(); deleteZone(el.dataset.zoneId); }, + 'apply-prop-changes': () => { applyPropChanges(); }, + 'delete-object': (el) => { + const obj = mapObjects.find((o) => String(o.id) === String(el.dataset.objectId)); + if (obj) deleteObject(obj); + }, + 'rename-map': () => { renameMap(); }, + 'resize-map': () => { resizeMap(); }, + 'select-autotile': (el) => { + selectAutotile(parseInt(el.dataset.packIdx, 10), parseInt(el.dataset.itemIdx, 10)); + }, + 'select-asset-item': (el) => { + const pack = assetPacks[selectedPackIdx]; + if (!pack) return; + const cat = el.dataset.cat; + const items = pack[cat] || []; + const item = items.find((it) => String(it.id) === String(el.dataset.itemId)); + if (item) selectAssetItem(pack, item, cat); + }, + 'map-select': () => { onMapSelect(); }, + 'pack-select': () => { onPackSelect(); }, + 'mark-dirty': () => { markDirty(); }, + 'update-zone-portal': (el) => { + const field = el.dataset.prop; + let value; + if (field === 'portalTarget') value = el.value || null; + else if (field === 'portalSpawnX' || field === 'portalSpawnY') { + value = el.value !== '' ? parseInt(el.value, 10) : null; + } else { + value = el.value; + } + updateZonePortalProp(el.dataset.zoneId, field, value); + if (field === 'type') { + const pf = document.getElementById('portalFields'); + if (pf) pf.classList.toggle('is-hidden', el.value !== 'portal'); + } + }, + 'zoom-slider': () => { onZoomSlider(); }, + 'map-name-input': () => { onMapNameInputChange(); }, + 'map-size-input': () => { onMapSizeInputChange(); }, +}; + +const clickActionNames = new Set([ + 'save-all-changes', 'connect', 'reload-map', 'set-tool', 'set-cat', + 'select-zone', 'delete-zone', 'apply-prop-changes', 'delete-object', + 'rename-map', 'resize-map', 'select-autotile', 'select-asset-item', +]); +const changeActionNames = new Set([ + 'map-select', 'pack-select', 'mark-dirty', 'update-zone-portal', +]); +const inputActionNames = new Set([ + 'zoom-slider', 'map-name-input', 'map-size-input', +]); + +function dispatchAction(event, allowed) { + const el = event.target.closest('[data-action]'); + if (!el) return; + const name = el.dataset.action; + if (!allowed.has(name)) return; + const fn = actions[name]; + if (fn) fn(el, event); +} + +document.addEventListener('click', (event) => dispatchAction(event, clickActionNames)); +document.addEventListener('change', (event) => dispatchAction(event, changeActionNames)); +document.addEventListener('input', (event) => dispatchAction(event, inputActionNames)); diff --git a/tools/npc-admin.html b/tools/npc-admin.html index 5158016b..a643afa3 100644 --- a/tools/npc-admin.html +++ b/tools/npc-admin.html @@ -324,6 +324,20 @@ 0%, 100% { box-shadow: 0 0 0 0 rgba(88,101,242,0.4) } 50% { box-shadow: 0 0 0 6px rgba(88,101,242,0) } } + +/* Utility classes replacing former inline style attributes */ +.grow{flex:1} +.spread{justify-content:space-between} +.label-inline{display:flex;align-items:center;gap:8px} +.label-dot{flex:0 0 3px;height:3px;background:var(--accent);border-radius:1px} +.muted{font-size:11px;color:var(--fg-muted)} +.is-hidden{display:none!important} +.tight{margin-top:4px} +.pixel-hint{font-family:var(--font-mono);font-size:10px;color:var(--fg-muted);margin-bottom:8px} +.mt-16{margin-top:16px} +.file-input{font-size:11px} +.flush{margin-top:0} +.mt-8{margin-top:8px} @@ -352,18 +366,18 @@

NPC ADMIN

- +
-
- @@ -373,11 +387,11 @@

NPC ADMIN

Select an NPC from the list or create a new one.
- @@ -451,13 +465,13 @@

NPC ADMIN

- Loading... + Loading...
-
+
Upload Media
- +
@@ -468,7 +482,7 @@

NPC ADMIN

- +
@@ -479,9 +493,9 @@

NPC ADMIN

Lifecycle
-
- - +
+ +
@@ -502,9 +516,9 @@

NPC ADMIN

-
- - +
+ +
@@ -519,7 +533,7 @@

NPC ADMIN

- + @@ -533,7 +547,7 @@

NPC ADMIN

- + @@ -547,21 +561,21 @@

NPC ADMIN

- +
Stop Media
- +
Do Not Disturb
-
- - +
+ +
@@ -569,16 +583,16 @@

NPC ADMIN

Set Avatar (Live)
- +
+ data-action="sync-avatar-fallback" data-target="cmdAvatarId">
- +
@@ -586,7 +600,7 @@

NPC ADMIN

- @@ -654,6 +668,45 @@

Create NPC

let mapTileWidth = 16; // default fallback let mapTileHeight = 16; +const ORIGIN_BLOCKED = 'The API origin is not in the allowed configuration.'; + +function h(tag, props, children) { + const n = document.createElement(tag); + if (props) { + Object.keys(props).forEach((k) => { + const v = props[k]; + if (v == null || v === false) return; + if (k === 'className') n.className = v; + else if (k === 'dataset') { + Object.keys(v).forEach((dk) => { + if (v[dk] != null) n.dataset[dk] = String(v[dk]); + }); + } else if (k === 'text') n.textContent = v; + else if (k === 'checked' || k === 'disabled' || k === 'selected') n[k] = true; + else if (k === 'value') n.value = v; + else if (k === 'id' || k === 'title') n[k] = v; + else n.setAttribute(k, String(v)); + }); + } + const list = children == null ? [] : Array.isArray(children) ? children : [children]; + list.forEach((c) => { + if (c == null || c === false) return; + n.appendChild(typeof c === 'string' || typeof c === 'number' ? document.createTextNode(String(c)) : c); + }); + return n; +} + +function requestErrorMessage(e, prefix) { + if (e instanceof TypeError) return ORIGIN_BLOCKED; + const msg = e && e.message ? e.message : 'Request failed'; + return prefix ? prefix + msg : msg; +} + +function textOrEmpty(v) { + if (v == null) return ''; + return typeof v === 'string' ? v : String(v); +} + // Default API URL to current origin (tools are served from the same server) document.addEventListener('DOMContentLoaded', () => { const el = document.getElementById('apiUrl'); @@ -719,7 +772,7 @@

Create NPC

} catch (e) { dot.className = 'conn-dot err'; label.textContent = 'Error'; - toast('err', `Connection failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Connection failed: ')); } } @@ -727,18 +780,25 @@

Create NPC

function renderNpcList() { const el = document.getElementById('npcList'); if (npcs.length === 0) { - el.innerHTML = 'No NPCs found.'; + el.replaceChildren(h('span', { className: 'muted', text: 'No NPCs found.' })); return; } - el.innerHTML = npcs.map(npc => ` -
-
${esc(npc.name)}
-
- ${esc(npc.identity)} - ${npc.enabled ? 'Enabled' : 'Disabled'} -
-
- `).join(''); + el.replaceChildren(); + npcs.forEach((npc) => { + el.appendChild(h('div', { + className: 'npc-item' + (npc.id === selectedNpcId ? ' active' : ''), + dataset: { action: 'select-npc', npcId: npc.id }, + }, [ + h('div', { className: 'npc-name', text: textOrEmpty(npc.name) }), + h('div', { className: 'npc-meta' }, [ + h('span', { text: textOrEmpty(npc.identity) }), + h('span', { + className: 'badge ' + (npc.enabled ? 'badge-enabled' : 'badge-disabled'), + text: npc.enabled ? 'Enabled' : 'Disabled', + }), + ]), + ])); + }); } // ── NPC Selection ── @@ -758,12 +818,12 @@

Create NPC

} selectedNpc = await res.json(); } catch (e) { - toast('err', `Failed to load NPC: ${e.message}`); + toast('err', requestErrorMessage(e, 'Failed to load NPC: ')); return; } - document.getElementById('detailEmpty').style.display = 'none'; - document.getElementById('detailContent').style.display = 'block'; + document.getElementById('detailEmpty').classList.add('is-hidden'); + document.getElementById('detailContent').classList.remove('is-hidden'); // Populate info tab document.getElementById('npcIdentity').value = selectedNpc.identity || ''; @@ -803,8 +863,8 @@

Create NPC

selectedNpc = null; npcMediaFiles = []; setDirty(false); - document.getElementById('detailEmpty').style.display = 'flex'; - document.getElementById('detailContent').style.display = 'none'; + document.getElementById('detailEmpty').classList.remove('is-hidden'); + document.getElementById('detailContent').classList.add('is-hidden'); renderNpcList(); } @@ -861,7 +921,7 @@

Create NPC

toast('err', `Save failed: ${err.error || res.statusText}`); } } catch (e) { - toast('err', `Save failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Save failed: ')); } } @@ -880,7 +940,7 @@

Create NPC

toast('err', `Delete failed: ${err.error || res.statusText}`); } } catch (e) { - toast('err', `Delete failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Delete failed: ')); } } @@ -941,15 +1001,10 @@

Create NPC

toast('err', `Create failed: ${err.error || res.statusText}`); } } catch (e) { - toast('err', `Create failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Create failed: ')); } } -// Close modal on overlay click -document.getElementById('createModal').addEventListener('click', function(e) { - if (e.target === this) closeCreateModal(); -}); - // ── Media ── async function loadMedia() { if (!selectedNpc) return; @@ -961,8 +1016,9 @@

Create NPC

} else { npcMediaFiles = selectedNpc.mediaFiles || []; } - } catch { + } catch (e) { npcMediaFiles = selectedNpc.mediaFiles || []; + if (e instanceof TypeError) toast('err', ORIGIN_BLOCKED); } renderMediaList(); } @@ -970,20 +1026,24 @@

Create NPC

function renderMediaList() { const el = document.getElementById('mediaList'); if (npcMediaFiles.length === 0) { - el.innerHTML = 'No media files uploaded.'; + el.replaceChildren(h('span', { className: 'muted', text: 'No media files uploaded.' })); return; } - el.innerHTML = npcMediaFiles.map(mf => ` -
-
-
${esc(mf.filename)}
-
- ${esc(mf.mediaType)} / ${esc(mf.mimeType)} / ${formatBytes(mf.sizeBytes)} -
-
- -
- `).join(''); + el.replaceChildren(); + npcMediaFiles.forEach((mf) => { + const metaText = `${textOrEmpty(mf.mediaType)} / ${textOrEmpty(mf.mimeType)} / ${formatBytes(mf.sizeBytes)}`; + el.appendChild(h('div', { className: 'media-item' }, [ + h('div', { className: 'media-info' }, [ + h('div', { className: 'media-name', text: textOrEmpty(mf.filename) }), + h('div', { className: 'media-meta', text: metaText }), + ]), + h('button', { + className: 'btn btn-sm btn-danger', + dataset: { action: 'delete-media', mediaId: mf.id }, + text: 'Del', + }), + ])); + }); } function populateMediaDropdowns() { @@ -998,9 +1058,14 @@

Create NPC

function populateSelect(selectId, files) { const sel = document.getElementById(selectId); - sel.innerHTML = files.length === 0 - ? '' - : files.map(f => ``).join(''); + sel.replaceChildren(); + if (files.length === 0) { + sel.appendChild(h('option', { value: '', text: 'No files' })); + return; + } + files.forEach((f) => { + sel.appendChild(h('option', { value: textOrEmpty(f.id), text: textOrEmpty(f.filename) })); + }); } async function uploadMedia() { @@ -1031,7 +1096,7 @@

Create NPC

toast('err', `Upload failed: ${err.error || res.statusText}`); } } catch (e) { - toast('err', `Upload failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Upload failed: ')); } } @@ -1049,7 +1114,7 @@

Create NPC

toast('err', `Delete failed: ${err.error || res.statusText}`); } } catch (e) { - toast('err', `Delete failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Delete failed: ')); } } @@ -1065,7 +1130,7 @@

Create NPC

toast('err', `Spawn failed: ${err.error || err.message || res.statusText}`); } } catch (e) { - toast('err', `Spawn failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Spawn failed: ')); } } @@ -1080,7 +1145,7 @@

Create NPC

toast('err', `Despawn failed: ${err.error || err.message || res.statusText}`); } } catch (e) { - toast('err', `Despawn failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Despawn failed: ')); } } @@ -1101,7 +1166,7 @@

Create NPC

toast('err', `Command failed: ${err.error || res.statusText}`); } } catch (e) { - toast('err', `Command failed: ${e.message}`); + toast('err', requestErrorMessage(e, 'Command failed: ')); } } @@ -1188,6 +1253,7 @@

Create NPC

} catch (e) { console.warn('Failed to fetch avatar packs:', e); avatarCache = []; + if (e instanceof TypeError) toast('err', ORIGIN_BLOCKED); } // Render all avatar grids after fetch renderAllAvatarGrids(); @@ -1207,35 +1273,31 @@

Create NPC

const targetInputId = gridEl.dataset.target; if (avatarCache.length === 0) { - gridEl.innerHTML = ''; - gridEl.style.display = 'none'; + gridEl.replaceChildren(); + gridEl.classList.add('is-hidden'); if (fallbackEl) fallbackEl.classList.add('show'); return; } - gridEl.style.display = ''; + gridEl.classList.remove('is-hidden'); if (fallbackEl) fallbackEl.classList.remove('show'); const currentVal = document.getElementById(targetInputId)?.value || ''; - gridEl.innerHTML = ''; + gridEl.replaceChildren(); for (const av of avatarCache) { - const card = document.createElement('div'); - card.className = 'avatar-card' + (av.id === currentVal ? ' selected' : ''); - card.title = av.displayName; - card.onclick = () => selectAvatarInGrid(gridId, av.id); + const card = h('div', { + className: 'avatar-card' + (av.id === currentVal ? ' selected' : ''), + title: av.displayName, + dataset: { action: 'select-avatar', avatarId: av.id }, + }); const canvas = document.createElement('canvas'); canvas.width = 64; canvas.height = 96; renderAvatarCanvas(canvas, av); card.appendChild(canvas); - - const label = document.createElement('div'); - label.className = 'avatar-label'; - label.textContent = av.displayName; - card.appendChild(label); - + card.appendChild(h('div', { className: 'avatar-label', text: av.displayName })); gridEl.appendChild(card); } } @@ -1335,30 +1397,18 @@

Create NPC

if (hint) hint.classList.toggle('show', dirty); } -function attachDirtyListeners() { - const fields = ['npcName', 'npcSpawnX', 'npcSpawnY', 'npcSpawnDir', 'npcMapName', 'npcEnabled', 'npcShowBadge', 'npcConfig']; - for (const id of fields) { - const el = document.getElementById(id); - if (!el) continue; - el.addEventListener('input', checkDirty); - el.addEventListener('change', checkDirty); - } - // Update pixel hint when spawn fields change - const spawnFields = ['npcSpawnX', 'npcSpawnY']; - for (const id of spawnFields) { - const el = document.getElementById(id); - if (!el) continue; - el.addEventListener('input', updateSpawnPixelHint); - el.addEventListener('change', updateSpawnPixelHint); - } - // Update pixel hint and dirty state when map selection changes - document.getElementById('npcMapName').addEventListener('change', () => { +function onInfoField(el) { + checkDirty(); + if (el.id === 'npcSpawnX' || el.id === 'npcSpawnY' || el.id === 'npcMapName') { updateSpawnPixelHint(); - }); + } } -// Attach dirty listeners once on load -document.addEventListener('DOMContentLoaded', attachDirtyListeners); +function syncAvatarFallback(el) { + const target = document.getElementById(el.dataset.target); + if (target) target.value = el.value; + if (el.dataset.target === 'npcAvatarId') checkDirty(); +} // ── Spawn Pixel Hint ── function updateSpawnPixelHint() { @@ -1384,12 +1434,10 @@

Create NPC

for (const id of selectors) { const sel = document.getElementById(id); if (!sel) continue; - sel.innerHTML = ''; + sel.replaceChildren(); + sel.appendChild(h('option', { value: '', text: '(Default)' })); for (const map of maps) { - const opt = document.createElement('option'); - opt.value = map.name; - opt.textContent = map.name; - sel.appendChild(opt); + sel.appendChild(h('option', { value: map.name, text: map.name })); } } } @@ -1419,18 +1467,73 @@

Create NPC

}, 3000); } -function esc(s) { - if (s == null) return ''; - if (typeof s !== 'string') s = String(s); - return s.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,'''); -} - function formatBytes(bytes) { if (bytes == null) return '?'; if (bytes < 1024) return bytes + ' B'; if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; } + +const clickActions = { + 'test-connection': () => { testConnection(); }, + 'open-create-modal': () => { openCreateModal(); }, + 'switch-tab': (el) => { switchTab(el.dataset.tab); }, + 'save-npc': () => { saveNpc(); }, + 'delete-npc': () => { deleteNpc(); }, + 'upload-media': () => { uploadMedia(); }, + 'spawn-npc': () => { spawnNpc(); }, + 'despawn-npc': () => { despawnNpc(); }, + 'cmd-move': () => { cmdMove(); }, + 'cmd-stop-movement': () => { cmdStopMovement(); }, + 'cmd-play-audio': () => { cmdPlayAudio(); }, + 'cmd-play-video': () => { cmdPlayVideo(); }, + 'cmd-play-screenshare': () => { cmdPlayScreenshare(); }, + 'cmd-stop-media': () => { cmdStopMedia(); }, + 'cmd-set-dnd': (el) => { cmdSetDnd(el.dataset.dnd === 'true'); }, + 'cmd-set-avatar': () => { cmdSetAvatar(); }, + 'create-npc': () => { createNpc(); }, + 'close-create-modal': (el, event) => { + if (el.id === 'createModal' && event.target !== el) return; + closeCreateModal(); + }, + 'select-npc': (el) => { selectNpc(el.dataset.npcId); }, + 'delete-media': (el) => { deleteMedia(el.dataset.mediaId); }, + 'select-avatar': (el) => { + const grid = el.closest('.avatar-grid'); + if (!grid) return; + selectAvatarInGrid(grid.id, el.dataset.avatarId); + }, +}; + +const inputActions = { + 'sync-avatar-fallback': (el) => { syncAvatarFallback(el); }, + 'info-field': (el) => { onInfoField(el); }, +}; + +const changeActions = { + 'info-field': (el) => { onInfoField(el); }, +}; + +document.addEventListener('click', (event) => { + const el = event.target.closest('[data-action]'); + if (!el) return; + const fn = clickActions[el.dataset.action]; + if (fn) fn(el, event); +}); + +document.addEventListener('input', (event) => { + const el = event.target.closest('[data-action]'); + if (!el) return; + const fn = inputActions[el.dataset.action]; + if (fn) fn(el, event); +}); + +document.addEventListener('change', (event) => { + const el = event.target.closest('[data-action]'); + if (!el) return; + const fn = changeActions[el.dataset.action]; + if (fn) fn(el, event); +}); diff --git a/tools/sprite-asset-cutter.html b/tools/sprite-asset-cutter.html index 33900345..4a857e0d 100644 --- a/tools/sprite-asset-cutter.html +++ b/tools/sprite-asset-cutter.html @@ -6,7 +6,7 @@ Sprite Asset Cutter — Meetropolis - + @@ -350,7 +368,7 @@

SPRITE ASSET CUTTER

Meetropolis -
@@ -365,7 +383,7 @@

Drop PNG / WEBP / .mepack

or click to browse

- - +
@@ -508,7 +526,7 @@

Drop PNG / WEBP / .mepack

-