diff --git a/packages/core/src/middleware/koa-spa-session-guard.test.ts b/packages/core/src/middleware/koa-spa-session-guard.test.ts index 164b1e103..9a68c290e 100644 --- a/packages/core/src/middleware/koa-spa-session-guard.test.ts +++ b/packages/core/src/middleware/koa-spa-session-guard.test.ts @@ -1,7 +1,8 @@ import { createMockUtils } from '@logto/shared/esm'; import Provider from 'oidc-provider'; +import Sinon from 'sinon'; -import { UserApps } from '#src/env-set/index.js'; +import { EnvSet, UserApps } from '#src/env-set/index.js'; import { MockQueries } from '#src/test-utils/tenant.js'; import { createContextWithRouteParameters } from '#src/utils/test-utils.js'; @@ -100,4 +101,18 @@ describe('koaSpaSessionGuard', () => { await koaSpaSessionGuard(provider, queries)(ctx, next); expect(ctx.redirect).toBeCalledWith('https://foo.bar'); }); + + it(`should redirect to current hostname if isDomainBasedMultiTenancy`, async () => { + const stub = Sinon.stub(EnvSet, 'values').value({ + ...EnvSet.values, + isDomainBasedMultiTenancy: true, + }); + interactionDetails.mockRejectedValue(new Error('session not found')); + const ctx = createContextWithRouteParameters({ + url: '/sign-in/foo', + }); + await koaSpaSessionGuard(provider, queries)(ctx, next); + expect(ctx.redirect).toBeCalledWith('https://test.com/unknown-session'); + stub.restore(); + }); }); diff --git a/packages/core/src/middleware/koa-spa-session-guard.ts b/packages/core/src/middleware/koa-spa-session-guard.ts index 0d0177bb5..a76c60752 100644 --- a/packages/core/src/middleware/koa-spa-session-guard.ts +++ b/packages/core/src/middleware/koa-spa-session-guard.ts @@ -55,9 +55,15 @@ export default function koaSpaSessionGuard< throw new RequestError({ code: 'session.not_found', status: 404 }); } - ctx.redirect( - appendPath(getTenantEndpoint(tenantId, EnvSet.values), sessionNotFoundPath).href - ); + const tenantEndpoint = getTenantEndpoint(tenantId, EnvSet.values); + + if (EnvSet.values.isDomainBasedMultiTenancy) { + // Replace to current hostname (if custom domain is used) + // eslint-disable-next-line @silverhand/fp/no-mutation + tenantEndpoint.hostname = ctx.request.hostname; + } + + ctx.redirect(appendPath(tenantEndpoint, sessionNotFoundPath).href); return; }