|
| 1 | +export const DEFAULT_RETURN_PATH = "/wix/osmf/"; |
| 2 | +export const STATE_COOKIE = "osmf_state"; |
| 3 | +export const RETURN_COOKIE = "osmf_return"; |
| 4 | + |
| 5 | +export function safeDecode(value) { |
| 6 | + try { |
| 7 | + return decodeURIComponent(value); |
| 8 | + } catch { |
| 9 | + return value; |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +export function normalizeReturnPath(value, fallback) { |
| 14 | + if (!value) return fallback; |
| 15 | + |
| 16 | + const decoded = safeDecode(value); |
| 17 | + if (!decoded.startsWith("/")) return fallback; |
| 18 | + if (decoded.startsWith("//")) return fallback; |
| 19 | + if (decoded.includes("://")) return fallback; |
| 20 | + |
| 21 | + return decoded; |
| 22 | +} |
| 23 | + |
| 24 | +export function parseCookies(header) { |
| 25 | + const cookies = {}; |
| 26 | + if (!header) return cookies; |
| 27 | + const parts = header.split(";").map((part) => part.trim()); |
| 28 | + for (const part of parts) { |
| 29 | + const [name, ...rest] = part.split("="); |
| 30 | + if (!name) continue; |
| 31 | + cookies[name] = safeDecode(rest.join("=")); |
| 32 | + } |
| 33 | + return cookies; |
| 34 | +} |
| 35 | + |
| 36 | +export function buildSetCookie(name, value, { maxAgeSeconds, secure }) { |
| 37 | + const parts = [ |
| 38 | + `${name}=${encodeURIComponent(value)}`, |
| 39 | + "Path=/", |
| 40 | + "HttpOnly", |
| 41 | + "SameSite=Lax", |
| 42 | + ]; |
| 43 | + |
| 44 | + if (typeof maxAgeSeconds === "number") { |
| 45 | + parts.push(`Max-Age=${maxAgeSeconds}`); |
| 46 | + } |
| 47 | + |
| 48 | + if (secure) { |
| 49 | + parts.push("Secure"); |
| 50 | + } |
| 51 | + |
| 52 | + return parts.join("; "); |
| 53 | +} |
| 54 | + |
| 55 | +export function clearCookie(name, secure) { |
| 56 | + return buildSetCookie(name, "", { maxAgeSeconds: 0, secure }); |
| 57 | +} |
| 58 | + |
| 59 | +export function buildReturnUrl(origin, returnPath, params) { |
| 60 | + const destination = new URL(returnPath, origin); |
| 61 | + for (const [key, value] of Object.entries(params)) { |
| 62 | + if (value !== undefined && value !== null) { |
| 63 | + destination.searchParams.set(key, value); |
| 64 | + } |
| 65 | + } |
| 66 | + return destination.toString(); |
| 67 | +} |
| 68 | + |
| 69 | +export function getRequestOrigin(request) { |
| 70 | + const url = new URL(request.url); |
| 71 | + const host = request.headers.get("host") || ""; |
| 72 | + const isLocalhost = host.startsWith("localhost"); |
| 73 | + |
| 74 | + if (isLocalhost) { |
| 75 | + const forwardedProto = request.headers.get("x-forwarded-proto"); |
| 76 | + const forwardedHost = request.headers.get("x-forwarded-host"); |
| 77 | + if (forwardedHost) { |
| 78 | + const proto = forwardedProto || url.protocol.replace(":", ""); |
| 79 | + return `${proto}://${forwardedHost}`; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + return url.origin; |
| 84 | +} |
0 commit comments