mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 17:38:12 +00:00
feat: ( redirect ) add redirect url based on the domain name
This commit is contained in:
@@ -3,6 +3,7 @@ import {
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Patch,
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
} from "./payments.dto";
|
||||
import { PassengerStaff } from "../../common/passenger-guards";
|
||||
import { PASSENGER_PERMS } from "../../seed/passenger-permissions.registry";
|
||||
import { resolveAllowedOrigin } from "../../common/utils/redirect-origin.util";
|
||||
|
||||
@ApiTags("Payment")
|
||||
@Controller("payments")
|
||||
@@ -83,8 +85,19 @@ export class PaymentsController {
|
||||
summary: "Initiate payment with nationality-based payment methods",
|
||||
description: `Initiates payment for a booking with support for multiple payment providers:\n\n**Ethiopian Payment Methods:**\n- TELEBIRR - Ethiopia's leading mobile money\n- CBE_BIRR - Commercial Bank of Ethiopia\n- EBIRR - Electronic payment gateway\n\n**Djiboutian Payment Methods:**\n- WAAFI - Djibouti's mobile money service\n\n**International Payment Methods:**\n- CARD - Visa, Mastercard\n- WALLET - Internal wallet balance\n\n**Multi-Currency:**\n- All transactions processed in ETB\n- Display amounts in ETB, DJF, or USD\n- Real-time exchange rate conversion`,
|
||||
})
|
||||
initiatePayment(@Body() dto: InitiatePaymentDto) {
|
||||
return this.service.initiatePayment(dto);
|
||||
initiatePayment(
|
||||
@Body() dto: InitiatePaymentDto,
|
||||
@Headers("origin") origin?: string,
|
||||
@Headers("referer") referer?: string,
|
||||
@Headers("x-frontend-base-url") frontendBaseUrl?: string,
|
||||
) {
|
||||
// Browser-facing return URLs (telebirr/waafi) follow the domain the user is
|
||||
// on — derived from Origin, then Referer, then the X-Frontend-Base-URL
|
||||
// header the portal sets, all validated against the allowlist.
|
||||
return this.service.initiatePayment(
|
||||
dto,
|
||||
resolveAllowedOrigin(origin, referer, frontendBaseUrl),
|
||||
);
|
||||
}
|
||||
|
||||
@Get("intents/:bookingId")
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
import { PaymentEventDto, MarkPaidResponseDto } from "./internal-payments.dto";
|
||||
import { PaymentClientService } from "./payment-client.service";
|
||||
import { CurrencyService } from "../currency/currency.service";
|
||||
import { rebaseUrlOrigin } from "../../common/utils/redirect-origin.util";
|
||||
import {
|
||||
PaymentService as PaymentServiceEnum,
|
||||
PaymentReferenceType,
|
||||
@@ -41,6 +42,15 @@ const NON_TERMINAL_STATUSES: PaymentIntentStatus[] = [
|
||||
PaymentIntentStatus.SUCCEEDED,
|
||||
];
|
||||
|
||||
// Methods whose return/failure URLs are browser-facing pages on the passenger
|
||||
// portal, so they should follow whichever domain the user came in on. DMONEY is
|
||||
// deliberately excluded — its return URL is a server-to-server webhook host, not
|
||||
// a page the browser lands on.
|
||||
const DOMAIN_AWARE_METHODS = new Set<PaymentMethodType>([
|
||||
PaymentMethodType.TELEBIRR,
|
||||
PaymentMethodType.WAAFI,
|
||||
]);
|
||||
|
||||
@Injectable()
|
||||
export class PaymentsService {
|
||||
private readonly logger = new Logger(PaymentsService.name);
|
||||
@@ -172,7 +182,10 @@ export class PaymentsService {
|
||||
return correctTotal;
|
||||
}
|
||||
|
||||
async initiatePayment(dto: InitiatePaymentDto): Promise<InitiateResponseDto> {
|
||||
async initiatePayment(
|
||||
dto: InitiatePaymentDto,
|
||||
requestOrigin?: string | null,
|
||||
): Promise<InitiateResponseDto> {
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { id: dto.bookingId },
|
||||
include: { seats: true },
|
||||
@@ -213,7 +226,10 @@ export class PaymentsService {
|
||||
return this.initiateWalletPayment(booking);
|
||||
}
|
||||
|
||||
const { returnUrl, failureUrl } = this.resolveReturnUrls(method);
|
||||
const { returnUrl, failureUrl } = this.resolveReturnUrls(
|
||||
method,
|
||||
requestOrigin,
|
||||
);
|
||||
|
||||
// The selected method's settlement currency lives in the PaymentMethod table (WAAFI/DMONEY
|
||||
// settle in DJF, CARD in USD, Ethiopian wallets in ETB). Convert the ETB booking total into
|
||||
@@ -294,7 +310,10 @@ export class PaymentsService {
|
||||
return this.formatIntentStatus(intent);
|
||||
}
|
||||
|
||||
private resolveReturnUrls(method: PaymentMethodType): {
|
||||
private resolveReturnUrls(
|
||||
method: PaymentMethodType,
|
||||
requestOrigin?: string | null,
|
||||
): {
|
||||
returnUrl?: string;
|
||||
failureUrl?: string;
|
||||
} {
|
||||
@@ -323,9 +342,18 @@ export class PaymentsService {
|
||||
};
|
||||
|
||||
const m = perMethod[method] ?? {};
|
||||
const returnUrl = m.returnUrl || process.env.PAYMENT_RETURN_URL || undefined;
|
||||
const failureUrl =
|
||||
let returnUrl = m.returnUrl || process.env.PAYMENT_RETURN_URL || undefined;
|
||||
let failureUrl =
|
||||
m.failureUrl || process.env.PAYMENT_FAILURE_URL || returnUrl;
|
||||
|
||||
// For browser-facing methods, swap the configured URL's host for whichever
|
||||
// allowlisted domain the user is currently on (bookingedr.et vs
|
||||
// passenger.edrsc.com). `requestOrigin` is already validated against the
|
||||
// allowlist by the controller; when it's null the configured URL is kept.
|
||||
if (DOMAIN_AWARE_METHODS.has(method) && requestOrigin) {
|
||||
returnUrl = rebaseUrlOrigin(returnUrl, requestOrigin);
|
||||
failureUrl = rebaseUrlOrigin(failureUrl, requestOrigin);
|
||||
}
|
||||
return { returnUrl, failureUrl };
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Post,
|
||||
@@ -19,6 +20,7 @@ import type { TCurrentUser } from "@tria-plc/api-common/modules/auth/types/curre
|
||||
import { IsPublic } from "@tria-plc/api-common/modules/auth/decorators/public.decorator";
|
||||
import { JwtGuard } from "../../common/jwt.guard";
|
||||
import { OptionalJwtGuard } from "./optional-jwt.guard";
|
||||
import { resolveAllowedOrigin } from "../../common/utils/redirect-origin.util";
|
||||
import {
|
||||
CompleteVerificationResultDto,
|
||||
StartVerificationDto,
|
||||
@@ -68,12 +70,20 @@ export class VerifaydaController {
|
||||
async start(
|
||||
@Body() dto: StartVerificationDto,
|
||||
@Req() req: RequestWithOptionalUser,
|
||||
@Headers("origin") origin?: string,
|
||||
@Headers("referer") referer?: string,
|
||||
@Headers("x-frontend-base-url") frontendBaseUrl?: string,
|
||||
): Promise<{ authorizationUrl: string }> {
|
||||
const authorizationUrl = await this.service.startVerification({
|
||||
purpose: dto.purpose ?? "VERIFY",
|
||||
platform: dto.platform ?? "WEB",
|
||||
userId: req.user?.id,
|
||||
wantsPasswordSetup: dto.wantsPasswordSetup ?? false,
|
||||
// WEB redirect_uri host follows the domain the user is on — Origin, then
|
||||
// Referer, then the X-Frontend-Base-URL header — validated against the
|
||||
// allowlist. Both domain variants must be registered with eSignet or the
|
||||
// login is rejected.
|
||||
requestOrigin: resolveAllowedOrigin(origin, referer, frontendBaseUrl),
|
||||
});
|
||||
return { authorizationUrl };
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
generateState,
|
||||
} from './utils/pkce.util';
|
||||
import { generateClientAssertion } from './utils/client-assertion.util';
|
||||
import { rebaseUrlOrigin } from '../../common/utils/redirect-origin.util';
|
||||
import { VerifaydaCallbackDto, VerificationStatusDto } from './verifayda.dto';
|
||||
import {
|
||||
FaydaTokenExchangeException,
|
||||
@@ -49,6 +50,13 @@ export interface StartVerificationInput {
|
||||
platform?: FaydaPlatform;
|
||||
userId?: string; // iamUserId of the authenticated user, if any
|
||||
wantsPasswordSetup?: boolean;
|
||||
/**
|
||||
* Allowlisted browser origin the request came from (e.g. https://bookingedr.et
|
||||
* or https://passenger.edrsc.com), already validated by the controller. For
|
||||
* WEB sessions the eSignet redirect_uri host is swapped to this so the user
|
||||
* lands back on the same domain. Null/undefined keeps the configured default.
|
||||
*/
|
||||
requestOrigin?: string | null;
|
||||
}
|
||||
|
||||
export interface FaydaUserSummary {
|
||||
@@ -145,12 +153,26 @@ export class VerifaydaService {
|
||||
Date.now() + this.faydaConfig.sessionTtlMinutes * 60_000,
|
||||
);
|
||||
|
||||
const platform = input.platform ?? 'WEB';
|
||||
// WEB sessions follow the domain the user came in on (bookingedr.et vs
|
||||
// passenger.edrsc.com); MOBILE always uses the native base redirect_uri.
|
||||
// Persist the exact URI so token exchange at /complete reuses it verbatim —
|
||||
// eSignet requires the redirect_uri to match between authorize and token.
|
||||
const redirectUri =
|
||||
platform === 'MOBILE'
|
||||
? this.redirectUriForPlatform('MOBILE')
|
||||
: rebaseUrlOrigin(
|
||||
this.faydaConfig.webRedirectUri,
|
||||
input.requestOrigin ?? null,
|
||||
) ?? this.faydaConfig.webRedirectUri;
|
||||
|
||||
await this.prisma.faydaVerificationSession.create({
|
||||
data: {
|
||||
state,
|
||||
codeVerifier,
|
||||
purpose: input.purpose,
|
||||
platform: input.platform ?? 'WEB',
|
||||
platform,
|
||||
redirectUri,
|
||||
saveToAccount: input.wantsPasswordSetup ?? false,
|
||||
iamUserId: input.userId ?? null,
|
||||
expiresAt,
|
||||
@@ -158,13 +180,13 @@ export class VerifaydaService {
|
||||
});
|
||||
|
||||
this.logger.log(
|
||||
`Fayda verification started: purpose=${input.purpose} platform=${input.platform ?? 'WEB'} userId=${input.userId ?? 'none'}`,
|
||||
`Fayda verification started: purpose=${input.purpose} platform=${platform} userId=${input.userId ?? 'none'} redirectUri=${redirectUri}`,
|
||||
);
|
||||
|
||||
return this.buildAuthorizationUrl({
|
||||
state,
|
||||
codeChallenge,
|
||||
redirectUri: this.redirectUriForPlatform(input.platform ?? 'WEB'),
|
||||
redirectUri,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -224,7 +246,11 @@ export class VerifaydaService {
|
||||
const tokens = await this.exchangeCodeForTokens(
|
||||
query.code,
|
||||
session.codeVerifier,
|
||||
this.redirectUriForPlatform(session.platform as FaydaPlatform),
|
||||
// Reuse the exact redirect_uri sent at authorize (persisted on the
|
||||
// session). Fall back to the platform default for sessions created
|
||||
// before this column existed.
|
||||
session.redirectUri ??
|
||||
this.redirectUriForPlatform(session.platform as FaydaPlatform),
|
||||
);
|
||||
const userInfo = await this.fetchUserInfo(tokens.access_token);
|
||||
const normalized = this.normalizeUserInfo(userInfo);
|
||||
|
||||
Reference in New Issue
Block a user