mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
Merge PR #3300: Native Cloud trials and password recovery
This commit is contained in:
@@ -11,3 +11,4 @@ e2e/help/media.env
|
||||
# The native apps' address screen (npm run build:native), copied into
|
||||
# android/ and ios/ by `cap sync`
|
||||
native-dist/
|
||||
native-sandbox-dist/
|
||||
|
||||
@@ -102,21 +102,61 @@ object TrekBilling {
|
||||
return offers.firstOrNull { it.offerId == null } ?: offers.firstOrNull()
|
||||
}
|
||||
|
||||
/** Play returns eligible offers. The named offer must be configured with Play's new-customer eligibility. */
|
||||
private fun trialOffer(product: ProductDetails): ProductDetails.SubscriptionOfferDetails? {
|
||||
val base = baseOffer(product)?.takeIf { it.offerId == null } ?: return null
|
||||
val recurring = base.pricingPhases.pricingPhaseList.singleOrNull() ?: return null
|
||||
return product.subscriptionOfferDetails?.firstOrNull { offer ->
|
||||
offer.offerId == TRIAL_OFFER_ID && offer.basePlanId == base.basePlanId &&
|
||||
isSevenDayTrial(offer.pricingPhases.pricingPhaseList, recurring)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isSevenDayTrial(
|
||||
phases: List<ProductDetails.PricingPhase>,
|
||||
recurring: ProductDetails.PricingPhase,
|
||||
): Boolean {
|
||||
if (phases.size != 2) return false
|
||||
val (trial, renewal) = phases
|
||||
val once = trial.recurrenceMode == ProductDetails.RecurrenceMode.NON_RECURRING ||
|
||||
(trial.recurrenceMode == ProductDetails.RecurrenceMode.FINITE_RECURRING && trial.billingCycleCount == 1)
|
||||
return once && trial.priceAmountMicros == 0L && trial.billingPeriod in listOf("P1W", "P7D") &&
|
||||
renewal.recurrenceMode == ProductDetails.RecurrenceMode.INFINITE_RECURRING &&
|
||||
renewal.billingPeriod == recurring.billingPeriod && renewal.priceAmountMicros == recurring.priceAmountMicros &&
|
||||
renewal.priceCurrencyCode == recurring.priceCurrencyCode
|
||||
}
|
||||
|
||||
fun products(context: Context, call: PluginCall) {
|
||||
val ids = call.getArray("ids")?.toList<String>().orEmpty()
|
||||
ready(context) { ok ->
|
||||
val result = JSObject().put("sandbox", BuildConfig.DEBUG)
|
||||
if (!ok) return@ready call.resolve(result.put("products", JSArray()))
|
||||
if (!ok || ids.isEmpty()) return@ready call.resolve(result.put("products", JSArray()))
|
||||
details(context, ids) { found ->
|
||||
val list = JSArray()
|
||||
for (product in found) displayPrice(product)?.let { list.put(JSObject().put("id", product.productId).put("displayPrice", it)) }
|
||||
call.resolve(result.put("products", list))
|
||||
val candidates = found.filter { trialOffer(it) != null }.map { it.productId }.toSet()
|
||||
if (candidates.isEmpty()) {
|
||||
call.resolve(result.put("products", productList(found, emptySet())))
|
||||
return@details
|
||||
}
|
||||
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
|
||||
client(context).queryPurchasesAsync(params) { status, purchases ->
|
||||
val eligible = status.responseCode == BillingClient.BillingResponseCode.OK && purchases.none { purchase ->
|
||||
purchase.products.any { it.startsWith(PREFIX) }
|
||||
}
|
||||
call.resolve(result.put("products", productList(found, if (eligible) candidates else emptySet())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun productList(products: List<ProductDetails>, freeTrials: Set<String>): JSArray = JSArray().apply {
|
||||
for (product in products) displayPrice(product)?.let { price ->
|
||||
put(JSObject().put("id", product.productId).put("displayPrice", price).put("freeTrial", product.productId in freeTrials))
|
||||
}
|
||||
}
|
||||
|
||||
fun purchase(activity: Activity, call: PluginCall) {
|
||||
val id = call.getString("productId") ?: return call.reject("productId is required")
|
||||
val trialRenewalPrice = call.getString("trialRenewalPrice")
|
||||
ready(activity) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
|
||||
// One subscription per Google account: a second plan would run beside the first.
|
||||
@@ -126,19 +166,28 @@ object TrekBilling {
|
||||
client(activity).queryPurchasesAsync(params) { result, purchases ->
|
||||
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
|
||||
when {
|
||||
held == null -> launchPurchase(activity, call, id)
|
||||
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
else -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
held?.isAcknowledged == true -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
held != null -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
trialRenewalPrice != null && result.responseCode != BillingClient.BillingResponseCode.OK ->
|
||||
call.resolve(JSObject().put("kind", "offer-changed"))
|
||||
purchases.any { p -> p.purchaseState == Purchase.PurchaseState.PENDING && p.products.any { it.startsWith(PREFIX) } } ->
|
||||
call.resolve(JSObject().put("kind", "pending"))
|
||||
else -> launchPurchase(activity, call, id, trialRenewalPrice)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) {
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String, trialRenewalPrice: String?) {
|
||||
details(activity, listOf(id)) { found ->
|
||||
val product = found.firstOrNull()
|
||||
val offer = product?.let(::baseOffer)
|
||||
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
|
||||
val offer = product?.let { listed ->
|
||||
if (trialRenewalPrice == null) baseOffer(listed)
|
||||
else trialOffer(listed)?.takeIf { displayPrice(listed) == trialRenewalPrice }
|
||||
}
|
||||
if (product == null || offer == null) {
|
||||
return@details call.resolve(JSObject().put("kind", if (trialRenewalPrice != null) "offer-changed" else "failed"))
|
||||
}
|
||||
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
|
||||
pendingPurchase = call
|
||||
pendingProduct = id
|
||||
@@ -275,6 +324,7 @@ object TrekBilling {
|
||||
newest(purchases.filter { !it.isAcknowledged }, prefix)
|
||||
|
||||
private const val PREFIX = "cloud."
|
||||
private const val TRIAL_OFFER_ID = "trek-trial-7-days"
|
||||
|
||||
internal fun newest(purchases: List<Purchase>, prefix: String): Purchase? = purchases
|
||||
.filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } }
|
||||
|
||||
@@ -688,14 +688,40 @@ extension TrekShellPlugin {
|
||||
let ids = call.getArray("ids", String.self) ?? []
|
||||
Task {
|
||||
let sandbox = await Self.buysInSandbox()
|
||||
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
guard !ids.isEmpty, AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
call.resolve(["products": [], "sandbox": sandbox])
|
||||
return
|
||||
}
|
||||
call.resolve(["products": products.map { ["id": $0.id, "displayPrice": $0.displayPrice] }, "sandbox": sandbox])
|
||||
var canStartTrial = false
|
||||
if products.contains(where: Self.hasSevenDayFreeTrial) {
|
||||
canStartTrial = await TrekStore.currentEntitlement(prefix: "cloud.") == nil
|
||||
}
|
||||
var groupEligibility: [String: Bool] = [:]
|
||||
var rows: [[String: Any]] = []
|
||||
for product in products {
|
||||
var freeTrial = false
|
||||
if canStartTrial, Self.hasSevenDayFreeTrial(product), let subscription = product.subscription {
|
||||
let group = subscription.subscriptionGroupID
|
||||
if let cached = groupEligibility[group] {
|
||||
freeTrial = cached
|
||||
} else {
|
||||
freeTrial = await subscription.isEligibleForIntroOffer
|
||||
groupEligibility[group] = freeTrial
|
||||
}
|
||||
}
|
||||
rows.append(["id": product.id, "displayPrice": product.displayPrice, "freeTrial": freeTrial])
|
||||
}
|
||||
call.resolve(["products": rows, "sandbox": sandbox])
|
||||
}
|
||||
}
|
||||
|
||||
private static func hasSevenDayFreeTrial(_ product: Product) -> Bool {
|
||||
guard let offer = product.subscription?.introductoryOffer,
|
||||
offer.paymentMode == .freeTrial, offer.price == 0, offer.periodCount == 1 else { return false }
|
||||
return (offer.period.unit == .week && offer.period.value == 1)
|
||||
|| (offer.period.unit == .day && offer.period.value == 7)
|
||||
}
|
||||
|
||||
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
|
||||
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
|
||||
/// The signed app transaction names its environment; the receipt's file name,
|
||||
@@ -726,6 +752,7 @@ extension TrekShellPlugin {
|
||||
call.reject("productId is required")
|
||||
return
|
||||
}
|
||||
let trialRenewalPrice = call.getString("trialRenewalPrice")
|
||||
Task {
|
||||
// One subscription per Apple ID: another plan would change it, not add one.
|
||||
// A held one that was delivered stops the purchase here. One that was paid
|
||||
@@ -740,9 +767,18 @@ extension TrekShellPlugin {
|
||||
}
|
||||
do {
|
||||
guard let product = try await Product.products(for: [id]).first else {
|
||||
call.resolve(["kind": "failed"])
|
||||
call.resolve(["kind": trialRenewalPrice == nil ? "failed" : "offer-changed"])
|
||||
return
|
||||
}
|
||||
if let trialRenewalPrice {
|
||||
guard product.displayPrice == trialRenewalPrice, Self.hasSevenDayFreeTrial(product),
|
||||
let subscription = product.subscription,
|
||||
await subscription.isEligibleForIntroOffer else {
|
||||
call.resolve(["kind": "offer-changed"])
|
||||
return
|
||||
}
|
||||
}
|
||||
// StoreKit applies an eligible introductory offer in its purchase sheet.
|
||||
switch try await product.purchase() {
|
||||
case .success(let verification):
|
||||
guard case .verified(let transaction) = verification else {
|
||||
|
||||
+210
-140
@@ -7,14 +7,21 @@ import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../
|
||||
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
|
||||
import { pageUnderStatusBar } from '../src/native/appBoot';
|
||||
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
isNewCloudPlan,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
type CloudPurchaseAgreement,
|
||||
} from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type IapProduct, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
APP_STORE_SUBSCRIPTIONS_URL,
|
||||
AUTH_PROXY_DOCS_URL,
|
||||
CLIENT_CERT_DOCS_URL,
|
||||
CLOUD_TERMS_URL,
|
||||
CLOUD_URL,
|
||||
CLOUD_URL as PRODUCTION_CLOUD_URL,
|
||||
PLAY_SUBSCRIPTIONS_URL,
|
||||
PRIVACY_URL,
|
||||
STORE_TERMS_URL,
|
||||
@@ -50,6 +57,13 @@ document.documentElement.dir = directionOf(locale);
|
||||
|
||||
const root = document.getElementById('shell')!;
|
||||
const PROBE_TIMEOUT_MS = 8000;
|
||||
const cloudSandbox = typeof __TREK_STORE_SANDBOX_ORIGIN__ === 'string' ? __TREK_STORE_SANDBOX_ORIGIN__ : undefined;
|
||||
const CLOUD_URL = cloudSandbox ?? PRODUCTION_CLOUD_URL;
|
||||
const cloudHttpOptions = {
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...(cloudSandbox ? { disableRedirects: true } : {}),
|
||||
};
|
||||
|
||||
const iap = getIapClient();
|
||||
/**
|
||||
@@ -98,6 +112,30 @@ const get: ProbeGet = async (url) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Keep Cloud sandbox requests on their requested host, including during tenant provisioning.
|
||||
const cloudGet: ProbeGet = cloudSandbox ? (url) => CapacitorHttp.get({ url, ...cloudHttpOptions }) : get;
|
||||
|
||||
function isCloudSandboxTenant(address: string, sandboxOrigin: string): boolean {
|
||||
let tenant: URL;
|
||||
try {
|
||||
tenant = new URL(address);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const suffix = `.${new URL(sandboxOrigin).hostname}`;
|
||||
const slug = tenant.hostname.slice(0, -suffix.length);
|
||||
return (
|
||||
tenant.origin === `https://${tenant.hostname}` &&
|
||||
!tenant.username &&
|
||||
!tenant.password &&
|
||||
tenant.hostname.endsWith(suffix) &&
|
||||
/^[a-z0-9-]+$/.test(slug) &&
|
||||
tenant.pathname === '/' &&
|
||||
!tenant.search &&
|
||||
!tenant.hash
|
||||
);
|
||||
}
|
||||
|
||||
function failureMessage(reason: ProbeFailure): string {
|
||||
switch (reason) {
|
||||
case 'invalid':
|
||||
@@ -151,12 +189,11 @@ const I = {
|
||||
globe: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20',
|
||||
image:
|
||||
'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21',
|
||||
spark: 'M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z',
|
||||
mail: 'M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM3 7l9 6 9-6',
|
||||
people:
|
||||
'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75',
|
||||
shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10',
|
||||
check: 'M20 6 9 17l-5-5',
|
||||
cross: 'M6 6l12 12M18 6 6 18',
|
||||
lock: 'M6 11h12a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3',
|
||||
key: 'M7.5 20a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.7 12.3 21 2M16 7l3 3M14 9l2 2',
|
||||
alert: 'M12 21.5a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zM12 7.5v5.5M12 16.5h.01',
|
||||
@@ -315,7 +352,8 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
const perk = (glyph: string, title: string, sub: string) =>
|
||||
el('div', {}, el('i', {}, icon(glyph, 17)), el('span', {}, el('b', {}, title), el('small', {}, sub)));
|
||||
|
||||
const discover = el('button', { type: 'button', className: 'cta' }, t('native.welcome.discover'));
|
||||
const trial = el('span', { className: 'trial-badge', hidden: true }, t('native.trial.badge'));
|
||||
const discover = el('button', { type: 'button', className: 'cta discover' }, t('native.welcome.discover'), trial);
|
||||
discover.addEventListener('click', () => {
|
||||
void tap();
|
||||
showPlans();
|
||||
@@ -326,7 +364,7 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
showConnect();
|
||||
});
|
||||
|
||||
show(
|
||||
const screen = show(
|
||||
'welcome',
|
||||
WELCOME_CAMERA,
|
||||
{
|
||||
@@ -351,6 +389,9 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
},
|
||||
opts
|
||||
);
|
||||
void availableWelcomeTrial().then((available) => {
|
||||
if (screen.node.isConnected) trial.hidden = !available;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Connect (address) ───────────────────────────────────────────────────────
|
||||
@@ -664,7 +705,7 @@ interface CloudPlan {
|
||||
yearlyCents?: number;
|
||||
currency?: 'EUR' | 'USD';
|
||||
aiDocuments: number;
|
||||
aiDocumentLimit?: 0 | null;
|
||||
aiDocumentLimit?: number | null;
|
||||
aiAssistant?: 'planned' | 'included' | 'unavailable';
|
||||
bookingMailImport?: boolean;
|
||||
storageGb: number;
|
||||
@@ -681,24 +722,24 @@ const SAMPLE_PLANS: CloudPlan[] = [
|
||||
{
|
||||
id: 'start',
|
||||
name: 'Start',
|
||||
monthlyCents: 499,
|
||||
monthlyCents: 599,
|
||||
yearlyCents: 4899,
|
||||
currency: 'USD',
|
||||
aiDocuments: 0,
|
||||
aiDocumentLimit: 0,
|
||||
storageGb: 200,
|
||||
storageGb: 50,
|
||||
},
|
||||
{
|
||||
id: 'plus',
|
||||
name: 'Plus',
|
||||
monthlyCents: 999,
|
||||
monthlyCents: 1199,
|
||||
yearlyCents: 9900,
|
||||
currency: 'USD',
|
||||
aiDocuments: 100,
|
||||
aiDocumentLimit: null,
|
||||
aiAssistant: 'planned',
|
||||
aiAssistant: 'included',
|
||||
bookingMailImport: true,
|
||||
storageGb: 200,
|
||||
storageGb: 50,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -706,15 +747,18 @@ interface CloudPlans {
|
||||
plans: CloudPlan[];
|
||||
/** Orders are closed: only a test build may buy, and the store charges it nothing. */
|
||||
closed: boolean;
|
||||
/** Only the live catalogue's explicit opening permits customer trial advertising. */
|
||||
open?: boolean;
|
||||
}
|
||||
|
||||
async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
try {
|
||||
const res = await get(`${CLOUD_URL}/api/plans`);
|
||||
const res = await cloudGet(`${CLOUD_URL}/api/plans`);
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string };
|
||||
const plans = Array.isArray(body.plans) ? body.plans.filter((plan) => isNewCloudPlan(plan.id)) : [];
|
||||
if (plans.length) return { plans, closed: body.ordering === 'closed' };
|
||||
if (plans.length)
|
||||
return { plans, closed: body.ordering === 'closed', open: res.status === 200 && body.ordering === 'open' };
|
||||
} catch {
|
||||
// Fall through to the preview fallback.
|
||||
}
|
||||
@@ -730,22 +774,44 @@ async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
*/
|
||||
interface Offer {
|
||||
canBuy: boolean;
|
||||
storePrices: Map<string, string> | null;
|
||||
storeProducts: Map<string, IapProduct> | null;
|
||||
canShowTrial: boolean;
|
||||
/** Orders are closed and this is no test build: the plans show, nothing is for sale yet. */
|
||||
opensSoon: boolean;
|
||||
}
|
||||
|
||||
function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false };
|
||||
function offerFor(
|
||||
offer: Offer,
|
||||
plan: CloudPlan,
|
||||
interval: 'month' | 'year'
|
||||
): { label: string; buyable: boolean; freeTrial: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false, freeTrial: false };
|
||||
if (iap !== fakeIapClient) {
|
||||
const label = offer.storePrices?.get(productIdFor(plan.id, interval)) ?? '';
|
||||
return { label, buyable: label !== '' };
|
||||
const product = offer.storeProducts?.get(productIdFor(plan.id, interval));
|
||||
const label = product?.displayPrice ?? '';
|
||||
return {
|
||||
label,
|
||||
buyable: label !== '',
|
||||
freeTrial: label !== '' && offer.canShowTrial && product?.freeTrial === true,
|
||||
};
|
||||
}
|
||||
const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents;
|
||||
const currency = plan.currency ?? 'EUR';
|
||||
const label =
|
||||
typeof cents === 'number' ? new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100) : '';
|
||||
return { label, buyable: label !== '' };
|
||||
return { label, buyable: label !== '', freeTrial: false };
|
||||
}
|
||||
|
||||
function storeIds(plans: CloudPlan[]): string[] {
|
||||
return plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]);
|
||||
}
|
||||
|
||||
async function availableWelcomeTrial(): Promise<boolean> {
|
||||
if (iap === fakeIapClient || !(await iapReady)) return false;
|
||||
const list = await fetchPlans();
|
||||
if (!list?.open) return false;
|
||||
const products = await iap.products(storeIds(list.plans));
|
||||
return Array.from(products.values()).some((product) => product.freeTrial && product.displayPrice !== '');
|
||||
}
|
||||
|
||||
async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
@@ -755,39 +821,61 @@ async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
const sandbox = list.closed && !onPlay ? await iap.isSandbox().catch(() => false) : false;
|
||||
const soon = opensSoon({ available, closed: list.closed, sandbox, onPlay });
|
||||
const canBuy = available && !soon;
|
||||
if (!canBuy || iap === fakeIapClient) return { canBuy, storePrices: null, opensSoon: soon };
|
||||
const ids = list.plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]);
|
||||
return { canBuy, storePrices: await iap.prices(ids), opensSoon: soon };
|
||||
if (!canBuy || iap === fakeIapClient) return { canBuy, storeProducts: null, canShowTrial: false, opensSoon: soon };
|
||||
return {
|
||||
canBuy,
|
||||
storeProducts: await iap.products(storeIds(list.plans)),
|
||||
canShowTrial: list.open === true,
|
||||
opensSoon: soon,
|
||||
};
|
||||
}
|
||||
|
||||
/** The plan the picker starts on and marks: the smallest one with AI documents, the one most trips want. */
|
||||
function recommendedPlan(plans: CloudPlan[]): CloudPlan | undefined {
|
||||
return plans.find((p) => p.aiDocuments > 0) ?? plans[0];
|
||||
}
|
||||
function planFeatures(plan: CloudPlan): HTMLLIElement[] {
|
||||
const row = (label: string, value: string, glyph: string, unavailable = false) =>
|
||||
el(
|
||||
'li',
|
||||
{ className: unavailable ? 'spec off' : 'spec' },
|
||||
el('i', {}, icon(glyph, 16)),
|
||||
el('b', {}, label),
|
||||
el('bdi', {}, value)
|
||||
);
|
||||
const feature = (label: string, included: boolean) =>
|
||||
row(
|
||||
label,
|
||||
t(included ? 'native.plans.included' : 'native.plans.notIncluded'),
|
||||
included ? I.check : I.cross,
|
||||
!included
|
||||
);
|
||||
|
||||
/** The kind of trip each plan is for: a weekend away, a round trip, a long journey, the whole world. */
|
||||
const TRIPS: Record<string, { titleKey: string; textKey: string }> = {
|
||||
start: { titleKey: 'native.trip.start.title', textKey: 'native.trip.start.text' },
|
||||
basis: { titleKey: 'native.trip.basis.title', textKey: 'native.trip.basis.text' },
|
||||
plus: { titleKey: 'native.trip.plus.title', textKey: 'native.trip.plus.text' },
|
||||
pro: { titleKey: 'native.trip.pro.title', textKey: 'native.trip.pro.text' },
|
||||
};
|
||||
/** A plan's trip, its title and one line; a plan the app does not know keeps its own name. */
|
||||
function tripOf(plan: CloudPlan): { title: string; text: string } {
|
||||
const trip = TRIPS[plan.id];
|
||||
return trip ? { title: t(trip.titleKey), text: t(trip.textKey) } : { title: plan.name, text: '' };
|
||||
const storage = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
|
||||
const aiDocuments = plan.aiDocumentLimit === null || (plan.aiDocumentLimit ?? plan.aiDocuments) > 0;
|
||||
return [
|
||||
row(t('native.plans.storage'), storage, I.image),
|
||||
feature(t('native.plans.aiLabel'), aiDocuments),
|
||||
feature(t('native.plans.assistant'), plan.aiAssistant === 'included'),
|
||||
feature(t('native.plans.mailImport'), plan.bookingMailImport === true),
|
||||
row(t('native.plans.unlimitedSub'), t('native.plans.unlimited'), I.people),
|
||||
];
|
||||
}
|
||||
|
||||
function per(interval: 'month' | 'year'): string {
|
||||
return interval === 'year' ? t('native.plans.perYear') : t('native.plans.perMonth');
|
||||
}
|
||||
|
||||
function trialPrice(price: string, interval: 'month' | 'year'): string {
|
||||
return t('native.trial.price', { price, period: per(interval) });
|
||||
}
|
||||
|
||||
function trialCancellation(): string {
|
||||
return t(onPlay ? 'native.trial.cancelPlay' : 'native.trial.cancelApple');
|
||||
}
|
||||
|
||||
/** The restore button of the plans on screen, which redeems a payment that cleared later. */
|
||||
let resumeRestore: (() => void) | null = null;
|
||||
let watchingTransactions = false;
|
||||
/** Where the camera stood on the plan chosen last, for the screens that follow it. */
|
||||
let chosenCamera: Camera = cameraForPlan(1);
|
||||
/** The plan chosen last, so coming back to the plans finds it still chosen. */
|
||||
/** Restore a choice when returning from setup. A fresh entry opens Plus. */
|
||||
let chosenPlanId: string | null = null;
|
||||
let chosenInterval: 'month' | 'year' = 'month';
|
||||
|
||||
@@ -852,14 +940,11 @@ function restoreButton(plans: CloudPlan[]): HTMLButtonElement {
|
||||
function showPlans(opts: { back?: boolean } = {}): void {
|
||||
let interval: 'month' | 'year' = chosenInterval;
|
||||
let plans: CloudPlan[] = [];
|
||||
let offer: Offer = { canBuy: false, storePrices: null, opensSoon: false };
|
||||
let offer: Offer = { canBuy: false, storeProducts: null, canShowTrial: false, opensSoon: false };
|
||||
let selectedId: string | null = null;
|
||||
|
||||
const tiers = el('div', { className: 'tiers', role: 'radiogroup', hidden: true });
|
||||
tiers.setAttribute('aria-label', t('native.plans.title'));
|
||||
const title = el('h1', {});
|
||||
const text = el('p', {});
|
||||
const trip = el('div', { className: 'trip' }, title, text);
|
||||
|
||||
const monthBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.monthly'));
|
||||
const yearBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.yearly'));
|
||||
@@ -876,18 +961,20 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
const pricePer = el('span', {});
|
||||
const price = el('div', { className: 'price' }, priceValue, pricePer);
|
||||
const equals = el('div', { className: 'equals' });
|
||||
const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals);
|
||||
const specs = el('div', { className: 'specs' });
|
||||
const trial = el('p', { className: 'trial-price', hidden: true });
|
||||
const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals, trial);
|
||||
const specs = el('ul', { className: 'specs', role: 'list' });
|
||||
const foot = el('div', { className: 'pad', hidden: true });
|
||||
const legal = el('p', { className: 'legal' });
|
||||
|
||||
const loading = el('div', { className: 'loading' }, el('span', { className: 'spin' }));
|
||||
const details = el('div', { className: 'stack', hidden: true }, trip, pricebox, specs);
|
||||
const details = el('div', { className: 'stack', hidden: true }, pricebox, specs);
|
||||
const choose = el('button', { type: 'button', className: 'cta', hidden: true });
|
||||
const dock = el('div', { className: 'dock' }, choose);
|
||||
|
||||
const screen = show(
|
||||
'plain',
|
||||
chosenCamera,
|
||||
opts.back ? chosenCamera : cameraForPlan(1),
|
||||
{
|
||||
back: () => showWelcome({ back: true }),
|
||||
content: [el('div', { className: 'pad lift' }, tiers, loading, details), foot, dock],
|
||||
@@ -934,20 +1021,11 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.setAttribute('aria-checked', String(interval === 'year'));
|
||||
cycle.dataset.year = String(interval === 'year');
|
||||
|
||||
const { title: tripTitle, text: tripText } = tripOf(plan);
|
||||
const recommended = recommendedPlan(plans)?.id === plan.id;
|
||||
title.replaceChildren(
|
||||
tripTitle,
|
||||
...(recommended ? [el('span', { className: 'badge' }, t('native.plans.recommended'))] : [])
|
||||
);
|
||||
text.textContent = tripText;
|
||||
text.hidden = !tripText;
|
||||
|
||||
const { label, buyable } = interval === 'month' ? month : year;
|
||||
// No price yet (orders not open): the plan shows without one rather than with an empty one.
|
||||
price.hidden = !label;
|
||||
const { label, buyable, freeTrial } = interval === 'month' ? month : year;
|
||||
// An introductory offer states the free period and renewal price together.
|
||||
price.hidden = !label || freeTrial;
|
||||
pricePer.textContent = per(interval);
|
||||
if (label) paintPrice(label, animate);
|
||||
if (label && !freeTrial) paintPrice(label, animate);
|
||||
|
||||
// Without a price in either period (orders not open yet) the switch would choose between nothing.
|
||||
pricebox.hidden = !month.label && !year.label;
|
||||
@@ -955,59 +1033,23 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.disabled = !year.label;
|
||||
const yearAmount = amountIn(year.label);
|
||||
equals.textContent =
|
||||
!label || !year.label
|
||||
!label || !year.label || freeTrial
|
||||
? ''
|
||||
: interval === 'month'
|
||||
? t('native.plans.yearlyIs', { price: year.label })
|
||||
: yearAmount
|
||||
? t('native.plans.monthlyIs', { price: yearAmount.render(yearAmount.value / 12) })
|
||||
: '';
|
||||
trial.hidden = !freeTrial;
|
||||
trial.textContent = freeTrial ? trialPrice(label, interval) : '';
|
||||
legal.textContent = freeTrial
|
||||
? trialCancellation()
|
||||
: t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal');
|
||||
|
||||
const gb = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
|
||||
const notIncluded = t('native.plans.aiNone');
|
||||
const included = t('native.plans.included');
|
||||
const assistant = plan.aiAssistant === 'included';
|
||||
const tile = (glyph: string, big: string, small: string, off = false) =>
|
||||
el(
|
||||
'span',
|
||||
{ className: off ? 'spec off' : 'spec' },
|
||||
el('i', {}, icon(glyph, 17)),
|
||||
el('span', {}, el('b', {}, big), el('small', {}, small))
|
||||
);
|
||||
specs.replaceChildren(
|
||||
tile(I.image, gb, t('native.plans.storageFairUse')),
|
||||
plan.aiDocuments > 0
|
||||
? tile(
|
||||
I.spark,
|
||||
plan.aiDocumentLimit === null
|
||||
? t('native.plans.unlimited')
|
||||
: t('native.plans.aiPerMonth', { n: count(plan.aiDocuments) }),
|
||||
t('native.plans.aiLabel')
|
||||
)
|
||||
: tile(I.spark, notIncluded, t('native.plans.aiLabel'), true),
|
||||
tile(
|
||||
I.spark,
|
||||
assistant ? included : plan.aiAssistant === 'planned' ? t('native.plans.planned') : notIncluded,
|
||||
t('native.plans.assistant'),
|
||||
!assistant
|
||||
),
|
||||
tile(
|
||||
I.mail,
|
||||
plan.bookingMailImport ? included : notIncluded,
|
||||
t('native.plans.mailImport'),
|
||||
!plan.bookingMailImport
|
||||
),
|
||||
el(
|
||||
'span',
|
||||
{ className: 'spec wide' },
|
||||
el('i', {}, icon(I.people, 17)),
|
||||
el('span', {}, el('b', {}, t('native.plans.unlimited')), el('small', {}, t('native.plans.unlimitedSub'))),
|
||||
el('em', {}, t('native.plans.inEveryPlan'))
|
||||
)
|
||||
);
|
||||
specs.replaceChildren(...planFeatures(plan));
|
||||
|
||||
choose.hidden = !buyable;
|
||||
choose.textContent = t('native.plans.choose', { trip: tripTitle });
|
||||
choose.textContent = t('native.plans.choose', { plan: plan.name });
|
||||
chosenCamera = cameraForPlan(index);
|
||||
chosenPlanId = plan.id;
|
||||
chosenInterval = interval;
|
||||
@@ -1042,7 +1084,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
showSubscribed();
|
||||
return;
|
||||
}
|
||||
showClaim(plan, selectedInterval, price.label);
|
||||
showClaim(plan, selectedInterval, price.label, { freeTrial: price.freeTrial });
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
@@ -1060,7 +1102,9 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
}
|
||||
offer = await loadOffer(list);
|
||||
plans = list.plans;
|
||||
selectedId = plans.find((p) => p.id === chosenPlanId)?.id ?? recommendedPlan(plans)?.id ?? null;
|
||||
const previousId = opts.back ? chosenPlanId : null;
|
||||
selectedId =
|
||||
plans.find((p) => p.id === previousId)?.id ?? plans.find((p) => p.id === 'plus')?.id ?? plans[0]?.id ?? null;
|
||||
tiers.replaceChildren(
|
||||
...plans.map((p) => {
|
||||
const b = el('button', { type: 'button', role: 'radio', dataset: { plan: p.id } }, p.name);
|
||||
@@ -1083,7 +1127,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
);
|
||||
} else {
|
||||
foot.replaceChildren(
|
||||
el('p', { className: 'legal' }, t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal')),
|
||||
legal,
|
||||
el(
|
||||
'div',
|
||||
{ className: 'legal-links' },
|
||||
@@ -1105,7 +1149,7 @@ type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error';
|
||||
|
||||
async function slugStatus(slug: string): Promise<SlugStatus> {
|
||||
try {
|
||||
const res = await get(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
|
||||
const res = await cloudGet(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const status = (data as { status?: string })?.status;
|
||||
if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status;
|
||||
@@ -1120,21 +1164,17 @@ async function slugStatus(slug: string): Promise<SlugStatus> {
|
||||
* (terms § 2 (1a), § 327h BGB), as the control plane words and versions it. The
|
||||
* app shows the server's text, never its own, and sends back the version it showed.
|
||||
*/
|
||||
interface DeviationsConsent {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
async function fetchConsent(): Promise<DeviationsConsent | null> {
|
||||
async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
|
||||
try {
|
||||
const res = await CapacitorHttp.get({
|
||||
url: `${CLOUD_URL}/api/iap/consent`,
|
||||
params: { lang: locale === 'de' ? 'de' : 'en' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...cloudHttpOptions,
|
||||
});
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { version?: unknown; deviations?: unknown };
|
||||
const body = (data ?? {}) as { version?: unknown; deviations?: unknown; iapEnvironment?: unknown };
|
||||
if (res.status !== 200 || typeof body.version !== 'string' || typeof body.deviations !== 'string') return null;
|
||||
if (cloudSandbox && body.iapEnvironment !== 'sandbox') return null;
|
||||
if (!body.version || !body.deviations) return null;
|
||||
return { version: body.version, text: body.deviations };
|
||||
} catch {
|
||||
@@ -1162,8 +1202,7 @@ async function redeemPurchase(
|
||||
const res = await CapacitorHttp.post({
|
||||
url: `${CLOUD_URL}/api/iap/redeem`,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...cloudHttpOptions,
|
||||
// The language of the contract confirmation mail.
|
||||
data: {
|
||||
platform: purchase.platform,
|
||||
@@ -1181,6 +1220,9 @@ async function redeemPurchase(
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: string };
|
||||
if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') {
|
||||
if (cloudSandbox && !isCloudSandboxTenant(body.instanceUrl, cloudSandbox)) {
|
||||
return { ok: false, code: 'redeem-failed' };
|
||||
}
|
||||
const welcome =
|
||||
typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined;
|
||||
return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) };
|
||||
@@ -1195,7 +1237,7 @@ function showClaim(
|
||||
plan: Pick<CloudPlan, 'id' | 'name'>,
|
||||
interval: 'month' | 'year',
|
||||
priceLabel: string,
|
||||
opts: { back?: boolean; bought?: Purchase } = {}
|
||||
opts: { back?: boolean; bought?: Purchase; freeTrial?: boolean } = {}
|
||||
): void {
|
||||
/** A purchase that went through but whose redeem did not: a retry redeems it again instead of buying twice. */
|
||||
let bought: Purchase | null = opts.bought ?? null;
|
||||
@@ -1279,7 +1321,7 @@ function showClaim(
|
||||
};
|
||||
|
||||
// The § 327h agreement, asked on its own before anything is bought.
|
||||
let consent: DeviationsConsent | null = null;
|
||||
let consent: CloudPurchaseAgreement | null = null;
|
||||
const consentBox = el('input', { type: 'checkbox' });
|
||||
const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading'));
|
||||
const consentField = el(
|
||||
@@ -1288,19 +1330,26 @@ function showClaim(
|
||||
consentBox,
|
||||
el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText)
|
||||
);
|
||||
const loadConsent = async (): Promise<DeviationsConsent | null> => {
|
||||
const showConsent = (current: CloudPurchaseAgreement | null): void => {
|
||||
consent = current;
|
||||
consentBox.checked = false;
|
||||
consentBox.disabled = true;
|
||||
consentText.textContent = t('native.claim.consentLoading');
|
||||
consent = await fetchConsent();
|
||||
consentBox.disabled = consent === null;
|
||||
consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable');
|
||||
};
|
||||
const loadConsent = async (): Promise<CloudPurchaseAgreement | null> => {
|
||||
consentBox.disabled = true;
|
||||
consentText.textContent = t('native.claim.consentLoading');
|
||||
showConsent(await fetchConsent());
|
||||
return consent;
|
||||
};
|
||||
void loadConsent();
|
||||
|
||||
const subscribeLabel = () =>
|
||||
bought ? t('native.claim.completeSetup') : t('native.claim.subscribe', { price: priceLabel });
|
||||
bought
|
||||
? t('native.claim.completeSetup')
|
||||
: opts.freeTrial
|
||||
? t('native.trial.badge')
|
||||
: t('native.claim.subscribe', { price: priceLabel });
|
||||
const submit = el('button', { type: 'button', className: 'cta' }, subscribeLabel());
|
||||
// What is about to be bought, so nobody pays for a plan they did not mean.
|
||||
const change = el('button', { type: 'button' }, t('native.claim.change'));
|
||||
@@ -1308,19 +1357,25 @@ function showClaim(
|
||||
void tap();
|
||||
showPlans({ back: true });
|
||||
});
|
||||
const planPrice = !priceLabel
|
||||
? null
|
||||
: opts.freeTrial
|
||||
? el('small', {}, trialPrice(priceLabel, interval))
|
||||
: el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`);
|
||||
const planRow = el(
|
||||
'div',
|
||||
{ className: 'plan-row' },
|
||||
el(
|
||||
'span',
|
||||
{},
|
||||
el('b', {}, plan.name),
|
||||
...(priceLabel ? [el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)] : [])
|
||||
),
|
||||
el('span', {}, el('b', {}, plan.name), ...(planPrice ? [planPrice] : [])),
|
||||
// A purchase already made is not a choice any more.
|
||||
...(bought ? [] : [change])
|
||||
);
|
||||
const error = notice('');
|
||||
const checkoutDock = el(
|
||||
'div',
|
||||
{ className: 'dock' },
|
||||
submit,
|
||||
el('p', { className: 'fine' }, opts.freeTrial ? trialCancellation() : t('native.claim.renews'))
|
||||
);
|
||||
const form = el(
|
||||
'form',
|
||||
{ className: 'pad form', noValidate: true },
|
||||
@@ -1347,10 +1402,7 @@ function showClaim(
|
||||
{
|
||||
back: () => showPlans({ back: true }),
|
||||
overlay: [card.node],
|
||||
content: [
|
||||
form,
|
||||
el('div', { className: 'dock' }, submit, el('p', { className: 'fine' }, t('native.claim.renews'))),
|
||||
],
|
||||
content: [form, checkoutDock],
|
||||
},
|
||||
opts
|
||||
);
|
||||
@@ -1440,7 +1492,8 @@ function showClaim(
|
||||
consentBox.focus();
|
||||
return;
|
||||
}
|
||||
const consentVersion = consent ? consent.version : null;
|
||||
const acceptedConsent = consent;
|
||||
const consentVersion = acceptedConsent?.version ?? null;
|
||||
|
||||
void tap(ImpactStyle.Medium);
|
||||
// The purchase sheet and the progress want the whole screen, not the keyboard.
|
||||
@@ -1460,7 +1513,24 @@ function showClaim(
|
||||
};
|
||||
|
||||
if (!bought) {
|
||||
const outcome = await iap.purchase(productIdFor(plan.id, interval));
|
||||
const currentConsent = await fetchConsent();
|
||||
if (!form.isConnected) return;
|
||||
if (!matchesPurchaseAgreement(acceptedConsent, currentConsent)) {
|
||||
restore();
|
||||
showConsent(currentConsent);
|
||||
setNotice(error, t(currentConsent ? 'native.claim.consentRequired' : 'native.claim.consentUnavailable'));
|
||||
if (currentConsent) consentBox.focus();
|
||||
return;
|
||||
}
|
||||
const trialRenewalPrice = opts.freeTrial ? priceLabel : undefined;
|
||||
const outcome = await iap.purchase(productIdFor(plan.id, interval), trialRenewalPrice);
|
||||
if (outcome.kind === 'offer-changed') {
|
||||
restore();
|
||||
planPrice?.remove();
|
||||
checkoutDock.hidden = true;
|
||||
setNotice(error, t('native.trial.changed'));
|
||||
return;
|
||||
}
|
||||
if (outcome.kind === 'cancelled') {
|
||||
restore();
|
||||
setNotice(error, t('native.claim.cancelled'));
|
||||
@@ -1650,8 +1720,8 @@ function showProvisioning(instanceUrl: string, welcome?: string): void {
|
||||
const deadline = Date.now() + 180_000;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (!view.screen.node.isConnected) return;
|
||||
const result = await probeServer(instanceUrl, get);
|
||||
if (result.ok) {
|
||||
const result = await probeServer(instanceUrl, cloudGet);
|
||||
if (result.ok && (!cloudSandbox || new URL(result.url).origin === new URL(instanceUrl).origin)) {
|
||||
await ready(result.url);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -320,14 +320,14 @@ input {
|
||||
overflow: hidden;
|
||||
background: var(--sea);
|
||||
margin-bottom: -1px;
|
||||
height: min(300px, 36svh);
|
||||
height: max(calc(var(--safe-top) + 68px), min(252px, 30svh));
|
||||
}
|
||||
.hero.tall {
|
||||
height: min(320px, 38svh);
|
||||
}
|
||||
.hero.welcome {
|
||||
height: min(376px, 44.5svh);
|
||||
min-height: 250px;
|
||||
height: min(352px, 42svh);
|
||||
min-height: 236px;
|
||||
}
|
||||
.hero .scenery {
|
||||
position: absolute;
|
||||
@@ -529,7 +529,7 @@ input {
|
||||
}
|
||||
.push {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: clamp(10px, 2svh, 16px);
|
||||
}
|
||||
h1 {
|
||||
margin: 0;
|
||||
@@ -628,6 +628,39 @@ h1 {
|
||||
font: 700 17px var(--text-face);
|
||||
box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55);
|
||||
}
|
||||
.discover {
|
||||
position: relative;
|
||||
padding-inline: 16px;
|
||||
}
|
||||
.trial-badge,
|
||||
.trial-price {
|
||||
border: 1px solid #bee3d7;
|
||||
background: #e7f6ef;
|
||||
color: #195247;
|
||||
}
|
||||
.trial-badge {
|
||||
position: absolute;
|
||||
inset-block-start: 0;
|
||||
inset-inline: 0;
|
||||
inline-size: max-content;
|
||||
max-inline-size: calc(100% - 20px);
|
||||
margin-inline: auto;
|
||||
padding: 3px 8px;
|
||||
border-radius: 999px;
|
||||
box-shadow: 0 2px 6px #11182720;
|
||||
font: 700 11px/1.4 var(--text-face);
|
||||
transform: translateY(calc(-100% + 6px));
|
||||
}
|
||||
.trial-price {
|
||||
margin: 8px 6px 0;
|
||||
padding: 10px 6px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.cta2 {
|
||||
min-height: 52px;
|
||||
background: #fff;
|
||||
@@ -715,33 +748,6 @@ h1 {
|
||||
color: var(--ink);
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
.trip {
|
||||
min-width: 0;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.trip h1 {
|
||||
font-size: 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.trip p {
|
||||
margin: 6px 0 0;
|
||||
color: var(--text);
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.badge {
|
||||
font-family: var(--text-face);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--dark);
|
||||
color: #fff;
|
||||
}
|
||||
.pricebox {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -823,64 +829,52 @@ h1 {
|
||||
display: none;
|
||||
}
|
||||
.specs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.spec {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 14px;
|
||||
margin: 0;
|
||||
padding: 0 12px;
|
||||
list-style: none;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 0 1px var(--line);
|
||||
}
|
||||
.spec {
|
||||
display: grid;
|
||||
grid-template-columns: 28px minmax(0, 1.6fr) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 44px;
|
||||
padding-block: 8px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.spec + .spec {
|
||||
border-block-start: 1px solid var(--line-soft);
|
||||
}
|
||||
.spec i {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
border-radius: 10px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--sand);
|
||||
color: var(--dark);
|
||||
}
|
||||
.spec b {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spec small {
|
||||
display: block;
|
||||
font-size: 11.5px;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
white-space: nowrap;
|
||||
.spec bdi {
|
||||
justify-self: end;
|
||||
text-align: end;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spec.off {
|
||||
color: #626672;
|
||||
}
|
||||
.spec.off i {
|
||||
color: var(--faint);
|
||||
}
|
||||
.spec.off b {
|
||||
color: var(--muted);
|
||||
}
|
||||
.spec.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.spec.wide em {
|
||||
margin-inline-start: auto;
|
||||
font-style: normal;
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
background: var(--sand);
|
||||
padding: 4px 9px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
background: #f0f1f3;
|
||||
color: inherit;
|
||||
}
|
||||
.legal {
|
||||
margin: 2px 0 0;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { basename } from 'node:path';
|
||||
import { test } from 'node:test';
|
||||
import config from '../vite.native.config.js';
|
||||
|
||||
const variable = 'TREK_CLOUD_SANDBOX_ORIGIN';
|
||||
|
||||
function setOrigin(context, origin) {
|
||||
const previous = process.env[variable];
|
||||
process.env[variable] = origin;
|
||||
context.after(() => {
|
||||
if (previous === undefined) delete process.env[variable];
|
||||
else process.env[variable] = previous;
|
||||
});
|
||||
}
|
||||
|
||||
test('isolates the sandbox output and keeps the ordinary app on the production configuration', (context) => {
|
||||
const origin = 'https://store-sandbox.example.com';
|
||||
setOrigin(context, origin);
|
||||
const sandbox = config({ command: 'build', mode: 'store-sandbox' });
|
||||
assert.deepEqual(sandbox.define, { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(origin) });
|
||||
assert.equal(basename(sandbox.build.outDir), 'native-sandbox-dist');
|
||||
|
||||
for (const input of [
|
||||
{ command: 'build', mode: 'production' },
|
||||
{ command: 'serve', mode: 'store-sandbox' },
|
||||
]) {
|
||||
const regular = config(input);
|
||||
assert.deepEqual(regular.define, {});
|
||||
assert.equal(basename(regular.build.outDir), 'native-dist');
|
||||
}
|
||||
});
|
||||
|
||||
for (const origin of [
|
||||
'',
|
||||
'http://qa.example.com',
|
||||
'https://qa.example.com/path',
|
||||
'https://liketrek.com',
|
||||
'https://www.liketrek.com',
|
||||
]) {
|
||||
test(`refuses a sandbox configuration with origin ${JSON.stringify(origin)}`, (context) => {
|
||||
setOrigin(context, origin);
|
||||
assert.throws(() => config({ command: 'build', mode: 'store-sandbox' }), { message: new RegExp(variable) });
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from './cloudOrders';
|
||||
import {
|
||||
isNewCloudPlan,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
} from './cloudOrders';
|
||||
|
||||
describe('opensSoon', () => {
|
||||
const base = { available: true, closed: true, sandbox: false, onPlay: false };
|
||||
@@ -35,6 +41,15 @@ describe('refundedBeforeOpening', () => {
|
||||
});
|
||||
|
||||
describe('Cloud catalog and purchase recovery', () => {
|
||||
it('only carries the accepted agreement into a new purchase if the current version and text still match', () => {
|
||||
const accepted = { version: '2026-12-01', text: 'Agreed changes' };
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted })).toBe(true);
|
||||
expect(matchesPurchaseAgreement(accepted, null)).toBe(false);
|
||||
expect(matchesPurchaseAgreement(null, accepted)).toBe(false);
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted, version: '2026-12-02' })).toBe(false);
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted, text: 'Changed conditions' })).toBe(false);
|
||||
});
|
||||
|
||||
it('only offers Start and Plus even when the server still lists retired plans', () => {
|
||||
expect(['start', 'basis', 'plus', 'pro'].filter(isNewCloudPlan)).toEqual(['start', 'plus']);
|
||||
});
|
||||
|
||||
@@ -29,6 +29,21 @@ export function isNewCloudPlan(id: string): boolean {
|
||||
return id === 'start' || id === 'plus';
|
||||
}
|
||||
|
||||
export interface CloudPurchaseAgreement {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** Recheck the agreement before opening the store sheet. No agreement means no new purchase. */
|
||||
export function matchesPurchaseAgreement(
|
||||
accepted: CloudPurchaseAgreement | null,
|
||||
current: CloudPurchaseAgreement | null
|
||||
): boolean {
|
||||
return (
|
||||
accepted !== null && current !== null && accepted.version === current.version && accepted.text === current.text
|
||||
);
|
||||
}
|
||||
|
||||
const PLAN_NAMES: Record<string, string> = { start: 'Start', basis: 'Basis', plus: 'Plus', pro: 'Pro' };
|
||||
|
||||
/** A verified purchase can predate the current offer and still need its instance set up. */
|
||||
|
||||
@@ -84,15 +84,22 @@ describe('native client', () => {
|
||||
expect(await fakeIapClient.isSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('maps the store price strings by product', async () => {
|
||||
shell.storeProducts.mockResolvedValue({ products: [{ id: 'cloud.plus.monthly', displayPrice: '9,99 €' }] });
|
||||
const prices = await nativeIapClient.prices(['cloud.plus.monthly', 'cloud.pro.monthly']);
|
||||
expect(shell.storeProducts).toHaveBeenCalledWith({ ids: ['cloud.plus.monthly', 'cloud.pro.monthly'] });
|
||||
expect(prices.get('cloud.plus.monthly')).toBe('9,99 €');
|
||||
expect(prices.has('cloud.pro.monthly')).toBe(false);
|
||||
it('maps the regular price and explicitly confirmed trial by product', async () => {
|
||||
shell.storeProducts.mockResolvedValue({
|
||||
products: [
|
||||
{ id: 'cloud.plus.monthly', displayPrice: '9,99 €', freeTrial: true },
|
||||
{ id: 'cloud.start.monthly', displayPrice: '4,99 €' },
|
||||
],
|
||||
});
|
||||
const ids = ['cloud.plus.monthly', 'cloud.start.monthly', 'cloud.plus.yearly'];
|
||||
const products = await nativeIapClient.products(ids);
|
||||
expect(shell.storeProducts).toHaveBeenCalledWith({ ids });
|
||||
expect(products.get('cloud.plus.monthly')).toEqual({ displayPrice: '9,99 €', freeTrial: true });
|
||||
expect(products.get('cloud.start.monthly')).toEqual({ displayPrice: '4,99 €', freeTrial: false });
|
||||
expect(products.has('cloud.plus.yearly')).toBe(false);
|
||||
|
||||
shell.storeProducts.mockRejectedValue(new Error('down'));
|
||||
expect((await nativeIapClient.prices(['cloud.plus.monthly'])).size).toBe(0);
|
||||
expect((await nativeIapClient.products(['cloud.plus.monthly'])).size).toBe(0);
|
||||
});
|
||||
|
||||
it('turns a bought transaction into a receipt', async () => {
|
||||
@@ -124,6 +131,15 @@ describe('native client', () => {
|
||||
expect(await nativeIapClient.held()).toBe(false);
|
||||
});
|
||||
|
||||
it('asks the store to preserve an advertised trial and reports a changed offer without retrying as paid', async () => {
|
||||
shell.storePurchase.mockResolvedValue({ kind: 'offer-changed' });
|
||||
expect(await nativeIapClient.purchase('cloud.plus.monthly', '9,99 €')).toEqual({ kind: 'offer-changed' });
|
||||
expect(shell.storePurchase).toHaveBeenCalledExactlyOnceWith({
|
||||
productId: 'cloud.plus.monthly',
|
||||
trialRenewalPrice: '9,99 €',
|
||||
});
|
||||
});
|
||||
|
||||
it('a build without storeHeld counts as holding nothing; the purchase still guards', async () => {
|
||||
shell.storeHeld.mockRejectedValue(new Error('not implemented'));
|
||||
expect(await nativeIapClient.held()).toBe(false);
|
||||
|
||||
+22
-11
@@ -38,17 +38,23 @@ type PurchaseOutcome =
|
||||
| { kind: 'cancelled' }
|
||||
| { kind: 'pending' }
|
||||
| { kind: 'failed' }
|
||||
| { kind: 'offer-changed' }
|
||||
| { kind: 'subscribed' };
|
||||
|
||||
export interface IapProduct {
|
||||
displayPrice: string;
|
||||
/** The store confirms an eligible first week at no charge. */
|
||||
freeTrial: boolean;
|
||||
}
|
||||
|
||||
export interface IapClient {
|
||||
/** Whether this build can take a payment. */
|
||||
isAvailable(): Promise<boolean>;
|
||||
/**
|
||||
* The store's own price strings by product id, in the buyer's currency. A
|
||||
* product missing from the map cannot be bought here. Empty for the fake, whose
|
||||
* prices come from the plan list.
|
||||
* Store pricing and offer eligibility by product id. A missing product cannot
|
||||
* be bought. Empty for the fake, whose prices come from the plan list.
|
||||
*/
|
||||
prices(productIds: string[]): Promise<Map<string, string>>;
|
||||
products(productIds: string[]): Promise<Map<string, IapProduct>>;
|
||||
/** A test build (TestFlight, App Review), whose purchases cost nothing and may go ahead before the opening. */
|
||||
isSandbox(): Promise<boolean>;
|
||||
/**
|
||||
@@ -58,7 +64,7 @@ export interface IapClient {
|
||||
*/
|
||||
held(): Promise<boolean>;
|
||||
/** Runs the platform's purchase sheet for a product and resolves with what became of it. */
|
||||
purchase(productId: string): Promise<PurchaseOutcome>;
|
||||
purchase(productId: string, trialRenewalPrice?: string): Promise<PurchaseOutcome>;
|
||||
/** Tells the store a purchase was delivered, once its instance exists. */
|
||||
finish(purchase: Purchase): Promise<void>;
|
||||
/** The subscription this store account already holds, for a reinstall or a new device. */
|
||||
@@ -94,7 +100,7 @@ export const fakeIapClient: IapClient = {
|
||||
async isAvailable() {
|
||||
return true;
|
||||
},
|
||||
async prices() {
|
||||
async products() {
|
||||
return new Map();
|
||||
},
|
||||
async isSandbox() {
|
||||
@@ -151,10 +157,10 @@ export const nativeIapClient: IapClient = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async prices(productIds) {
|
||||
async products(productIds) {
|
||||
try {
|
||||
const { products } = await TrekShell.storeProducts({ ids: productIds });
|
||||
return new Map(products.map((p) => [p.id, p.displayPrice]));
|
||||
return new Map(products.map((p) => [p.id, { displayPrice: p.displayPrice, freeTrial: p.freeTrial === true }]));
|
||||
} catch {
|
||||
return new Map();
|
||||
}
|
||||
@@ -166,9 +172,9 @@ export const nativeIapClient: IapClient = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async purchase(productId) {
|
||||
async purchase(productId, trialRenewalPrice) {
|
||||
try {
|
||||
const result = await TrekShell.storePurchase({ productId });
|
||||
const result = await TrekShell.storePurchase({ productId, ...(trialRenewalPrice ? { trialRenewalPrice } : {}) });
|
||||
const receipt = result.jws ?? result.purchaseToken;
|
||||
if (result.kind === 'bought' && receipt && result.transactionId) {
|
||||
return {
|
||||
@@ -181,7 +187,12 @@ export const nativeIapClient: IapClient = {
|
||||
},
|
||||
};
|
||||
}
|
||||
if (result.kind === 'cancelled' || result.kind === 'pending' || result.kind === 'subscribed') {
|
||||
if (
|
||||
result.kind === 'cancelled' ||
|
||||
result.kind === 'pending' ||
|
||||
result.kind === 'subscribed' ||
|
||||
result.kind === 'offer-changed'
|
||||
) {
|
||||
return { kind: result.kind };
|
||||
}
|
||||
return { kind: 'failed' };
|
||||
|
||||
@@ -128,14 +128,14 @@ export interface TrekShellPlugin {
|
||||
/** Feature storeKit (iOS) or playBilling (Android): the store's price strings for the products it knows. */
|
||||
storeProducts(options: {
|
||||
ids: string[];
|
||||
}): Promise<{ products: { id: string; displayPrice: string }[]; sandbox?: boolean }>;
|
||||
}): Promise<{ products: { id: string; displayPrice: string; freeTrial?: boolean }[]; sandbox?: boolean }>;
|
||||
/**
|
||||
* The purchase sheet. Set when bought: on iOS `jws`, the signed transaction; on
|
||||
* Android `purchaseToken`, which the control plane verifies with Google Play.
|
||||
*/
|
||||
storePurchase(options: { productId: string }): Promise<{
|
||||
storePurchase(options: { productId: string; trialRenewalPrice?: string }): Promise<{
|
||||
/** `subscribed`: this store account already holds a delivered subscription, so nothing was bought. */
|
||||
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed';
|
||||
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed' | 'offer-changed';
|
||||
jws?: string;
|
||||
purchaseToken?: string;
|
||||
productId?: string;
|
||||
|
||||
@@ -9,9 +9,14 @@ import ForgotPasswordPage from './ForgotPasswordPage'
|
||||
// forgotPassword/useForgotPassword.test.ts). The hook is mocked so the form,
|
||||
// the sent screen and the SMTP hint can each be rendered on demand.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown> }))
|
||||
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown>, native: false }))
|
||||
|
||||
vi.mock('./forgotPassword/useForgotPassword', () => ({ useForgotPassword: () => mocks.forgot }))
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => mocks.native,
|
||||
}))
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
|
||||
|
||||
const navigate = vi.fn((_to: string) => {})
|
||||
const setEmail = vi.fn((_v: string) => {})
|
||||
@@ -32,6 +37,7 @@ function setForgot(over: Record<string, unknown> = {}) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.native = false
|
||||
setForgot()
|
||||
})
|
||||
|
||||
@@ -124,4 +130,28 @@ describe('ForgotPasswordPage', () => {
|
||||
expect(screen.getByRole('heading', { name: 'Check your email' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/console/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the SMTP warning visible throughout native password recovery', () => {
|
||||
mocks.native = true
|
||||
setForgot({ smtpConfigured: false })
|
||||
const { rerender } = render(<ForgotPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('main')).toHaveClass('al-body')
|
||||
expect(screen.getByRole('textbox', { name: 'Email' })).toHaveAttribute('autocomplete', 'email')
|
||||
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
|
||||
|
||||
setForgot({ smtpConfigured: false, submitted: true })
|
||||
rerender(<ForgotPasswordPage />)
|
||||
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
|
||||
expect(screen.queryByRole('heading', { name: 'Check your email' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lets a native user try again after a requester-wide rate limit', () => {
|
||||
mocks.native = true
|
||||
setForgot({ submitted: true, deliveryIssue: 'rateLimit' })
|
||||
render(<ForgotPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Too many attempts')
|
||||
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeEnabled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Mail, ArrowLeft, CheckCircle2, Terminal } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
import AppForgotPassword from './forgotPassword/AppForgotPassword'
|
||||
import { useForgotPassword } from './forgotPassword/useForgotPassword'
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
@@ -13,7 +15,9 @@ const inputBase: React.CSSProperties = {
|
||||
function ForgotPasswordPage() {
|
||||
const { t } = useTranslation()
|
||||
// Page = wiring container: form state, the SMTP probe and submit live in the hook.
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = useForgotPassword()
|
||||
const forgot = useForgotPassword()
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = forgot
|
||||
if (isNativeApp()) return <AppForgotPassword forgot={forgot} />
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
|
||||
@@ -9,9 +9,14 @@ import ResetPasswordPage from './ResetPasswordPage'
|
||||
// resetPassword/useResetPassword.test.ts). The hook is mocked so the success,
|
||||
// broken-link, password and MFA screens can each be rendered directly.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown> }))
|
||||
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown>, native: false }))
|
||||
|
||||
vi.mock('./resetPassword/useResetPassword', () => ({ useResetPassword: () => mocks.reset }))
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => mocks.native,
|
||||
}))
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
|
||||
|
||||
const navigate = vi.fn((_to: string) => {})
|
||||
const setPw = vi.fn((_v: string) => {})
|
||||
@@ -43,10 +48,35 @@ function setReset(over: Record<string, unknown> = {}) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.native = false
|
||||
setReset()
|
||||
})
|
||||
|
||||
describe('ResetPasswordPage', () => {
|
||||
it('announces reset errors and supports backup codes on the native screen', () => {
|
||||
mocks.native = true
|
||||
setReset({ mfaRequired: true, error: 'The security code was rejected' })
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('main')).toHaveClass('al-body')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('The security code was rejected')
|
||||
const code = screen.getByRole('textbox', { name: '2FA code' })
|
||||
expect(code).toHaveAttribute('autocomplete', 'one-time-code')
|
||||
fireEvent.change(code, { target: { value: 'ABCD-EFGH' } })
|
||||
expect(setMfaCode).toHaveBeenCalledWith('ABCD-EFGH')
|
||||
})
|
||||
|
||||
it('lets the native user request another link when the server rejects the current one', () => {
|
||||
mocks.native = true
|
||||
setReset({ linkInvalid: true })
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Invalid reset link' })).toBeVisible()
|
||||
expect(screen.queryByLabelText('New password')).not.toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Send reset link' }))
|
||||
expect(navigate).toHaveBeenCalledWith('/forgot-password')
|
||||
})
|
||||
|
||||
it('FE-PAGE-RESETUI-001: renders the password form for a valid token', () => {
|
||||
setReset()
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Lock, KeyRound, CheckCircle2, AlertTriangle, Eye, EyeOff } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
import AppResetPassword from './resetPassword/AppResetPassword'
|
||||
import { useResetPassword } from './resetPassword/useResetPassword'
|
||||
import PasswordChecklist from '../components/shared/PasswordChecklist'
|
||||
|
||||
@@ -14,12 +16,14 @@ const inputBase: React.CSSProperties = {
|
||||
function ResetPasswordPage() {
|
||||
const { t } = useTranslation()
|
||||
// Page = wiring container: token, form state, validation + submit live in the hook.
|
||||
const reset = useResetPassword()
|
||||
const {
|
||||
navigate, token,
|
||||
navigate, token, linkInvalid,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
} = useResetPassword()
|
||||
} = reset
|
||||
if (isNativeApp()) return <AppResetPassword reset={reset} />
|
||||
|
||||
const shell = (inner: React.ReactNode) => (
|
||||
<div style={{
|
||||
@@ -57,7 +61,7 @@ function ResetPasswordPage() {
|
||||
)
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
if (!token || linkInvalid) {
|
||||
return shell(
|
||||
<div style={{ textAlign: 'center', padding: '12px 0' }}>
|
||||
<div style={{
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CheckCircle2 } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
|
||||
import type { useForgotPassword } from './useForgotPassword';
|
||||
|
||||
export default function AppForgotPassword({ forgot }: { forgot: ReturnType<typeof useForgotPassword> }) {
|
||||
const { t } = useTranslation();
|
||||
const back = () => void forgot.navigate('/login');
|
||||
const smtpOff = forgot.smtpConfigured === false;
|
||||
const smtpNotice = smtpOff && <Notice tone="warn">{t('login.forgotPasswordSmtpHintOff')}</Notice>;
|
||||
|
||||
return (
|
||||
<AppAuthScreen>
|
||||
{forgot.submitted && !forgot.deliveryIssue ? (
|
||||
<div className="al-form">
|
||||
<div className="al-recovery-feedback" role="status">
|
||||
{!smtpOff && <CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />}
|
||||
<h1 className="al-title">{t(smtpOff ? 'login.forgotPasswordTitle' : 'login.forgotPasswordSentTitle')}</h1>
|
||||
{!smtpOff && <p className="al-sub">{t('login.forgotPasswordSentBody')}</p>}
|
||||
</div>
|
||||
{smtpNotice}
|
||||
<button type="button" className="al-cta" onClick={back}>
|
||||
{t('login.backToLogin')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<form className="al-form" onSubmit={(event) => void forgot.handleSubmit(event)}>
|
||||
<h1 className="al-title">{t('login.forgotPasswordTitle')}</h1>
|
||||
<p className="al-sub">{t('login.forgotPasswordBody')}</p>
|
||||
{smtpNotice}
|
||||
{forgot.deliveryIssue && (
|
||||
<Notice>
|
||||
{t(forgot.deliveryIssue === 'rateLimit' ? 'common.tooManyAttempts' : 'native.connect.errorUnreachable')}
|
||||
</Notice>
|
||||
)}
|
||||
<Field
|
||||
label={t('common.email')}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
autoCapitalize="none"
|
||||
enterKeyHint="send"
|
||||
value={forgot.email}
|
||||
onChange={(event) => forgot.setEmail(event.target.value)}
|
||||
placeholder={t('login.emailPlaceholder')}
|
||||
required
|
||||
/>
|
||||
<button type="submit" className="al-cta" disabled={forgot.isLoading}>
|
||||
{forgot.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{forgot.isLoading ? t('common.loading') : t('login.forgotPasswordSubmit')}
|
||||
</button>
|
||||
</form>
|
||||
<button type="button" className="al-forgot" onClick={back}>
|
||||
{t('login.backToLogin')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// FE-PAGE-FORGOT-001 to FE-PAGE-FORGOT-008
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { AxiosError } from 'axios';
|
||||
import type { FormEvent } from 'react';
|
||||
import { authApi } from '../../api/client';
|
||||
import { useForgotPassword } from './useForgotPassword';
|
||||
@@ -72,6 +73,18 @@ describe('useForgotPassword', () => {
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
|
||||
expect(result.current.submitted).toBe(true);
|
||||
expect(result.current.deliveryIssue).toBeNull();
|
||||
});
|
||||
|
||||
it('distinguishes a lost connection without revealing information about the address', async () => {
|
||||
vi.mocked(authApi.forgotPassword).mockRejectedValueOnce(new AxiosError('Lost connection', 'ERR_NETWORK'));
|
||||
const { result } = renderHook(() => useForgotPassword());
|
||||
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(result.current.deliveryIssue).toBe('connection');
|
||||
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(result.current.deliveryIssue).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PAGE-FORGOT-007: ignores a second submit while the first is in flight', async () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { isAxiosError } from 'axios'
|
||||
import { authApi } from '../../api/client'
|
||||
|
||||
/**
|
||||
@@ -14,6 +15,7 @@ export function useForgotPassword() {
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [smtpConfigured, setSmtpConfigured] = useState<boolean | null>(null)
|
||||
const [deliveryIssue, setDeliveryIssue] = useState<'connection' | 'rateLimit' | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Probe whether SMTP is configured so we can warn the user up-front that the
|
||||
@@ -29,15 +31,21 @@ export function useForgotPassword() {
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setDeliveryIssue(null)
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await authApi.forgotPassword({ email: email.trim() })
|
||||
} catch {
|
||||
// Enumeration-safe: success UX regardless of server outcome.
|
||||
} catch (error) {
|
||||
// These errors apply to the connection or requester, not to the mailbox.
|
||||
// Keep every other outcome indistinguishable from an accepted request.
|
||||
if (isAxiosError(error)) {
|
||||
if (error.response?.status === 429) setDeliveryIssue('rateLimit')
|
||||
else if (!error.response) setDeliveryIssue('connection')
|
||||
}
|
||||
}
|
||||
setSubmitted(true)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit }
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, deliveryIssue, handleSubmit }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { AlertCircle, Globe, Lock } from 'lucide-react';
|
||||
import { useEffect, useRef, type InputHTMLAttributes, type ReactNode } from 'react';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
|
||||
export function AppAuthScreen({ children, leaving }: { children: ReactNode; leaving?: boolean }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<div className={leaving ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppAuthHero />
|
||||
<main className="al-body">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AppAuthHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// Keep the landscape in the position where the address screen leaves it.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Notice({ tone, children }: { tone?: 'warn'; children: ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? 'status' : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: ReactNode } & InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { Eye, EyeOff, Fingerprint, Shield } from 'lucide-react';
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
import { AppAuthScreen, Field, Notice } from './AppAuthScreen';
|
||||
import { heading as headingOf, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
|
||||
import { mfaCodeInputProps } from './mfaCodeInput';
|
||||
import { IDP_LOGIN_URL, type useLogin } from './useLogin';
|
||||
@@ -22,14 +18,10 @@ type Login = ReturnType<typeof useLogin>;
|
||||
* (the device decides, see useLogin) differ.
|
||||
*/
|
||||
export default function AppLogin({ login }: { login: Login }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<div className={login.showTakeoff ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppLoginHero />
|
||||
<main className="al-body">
|
||||
<AppLoginContent login={login} />
|
||||
</main>
|
||||
</div>
|
||||
<AppAuthScreen leaving={login.showTakeoff}>
|
||||
<AppLoginContent login={login} />
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,85 +51,6 @@ function AppLoginContent({ login }: { login: Login }) {
|
||||
return <Credentials login={login} />;
|
||||
}
|
||||
|
||||
/** The landscape of the address screen, with the server this screen signs in to. */
|
||||
function AppLoginHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// The same camera the address screen ends on, so the picture holds still
|
||||
// across the change of screens. The scene stops drawing once its canvas
|
||||
// has left the page.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
// Without the landscape the box keeps its plain sea colour.
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? undefined : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A field on a white card, the label above the input, as on the address screen.
|
||||
* A control beside the input (the password's eye) sits outside the label, so
|
||||
* the label names the input alone.
|
||||
*/
|
||||
function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OidcOnly({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the
|
||||
* The sign-in and password recovery screens inside the iOS and Android app. The sign-in is the
|
||||
* next screen after the app's own address screen (native-shell/), so it wears
|
||||
* that screen's look: the same landscape on top, the same glass card with the
|
||||
* server on it, the same type, fields and buttons on the same warm page. The
|
||||
@@ -295,6 +295,14 @@
|
||||
line-height: 1.5;
|
||||
color: var(--al-text);
|
||||
}
|
||||
.al-recovery-feedback {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
justify-items: start;
|
||||
}
|
||||
.al-recovery-icon {
|
||||
color: var(--al-good);
|
||||
}
|
||||
|
||||
/* A field on a white card: the label above, the input below it. */
|
||||
.al-fld {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { CheckCircle2, Eye, EyeOff } from 'lucide-react';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
|
||||
import { mfaCodeInputProps } from '../login/mfaCodeInput';
|
||||
import type { useResetPassword } from './useResetPassword';
|
||||
|
||||
type Reset = ReturnType<typeof useResetPassword>;
|
||||
|
||||
export default function AppResetPassword({ reset }: { reset: Reset }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<AppAuthScreen>
|
||||
{reset.success ? (
|
||||
<div className="al-form">
|
||||
<div className="al-recovery-feedback" role="status">
|
||||
<CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />
|
||||
<h1 className="al-title">{t('login.resetPasswordSuccessTitle')}</h1>
|
||||
<p className="al-sub">{t('login.resetPasswordSuccessBody')}</p>
|
||||
</div>
|
||||
<button type="button" className="al-cta" onClick={() => void reset.navigate('/login')}>
|
||||
{t('login.signIn')}
|
||||
</button>
|
||||
</div>
|
||||
) : !reset.token || reset.linkInvalid ? (
|
||||
<div className="al-form">
|
||||
<h1 className="al-title">{t('login.resetPasswordInvalidLink')}</h1>
|
||||
<Notice>{t('login.resetPasswordInvalidLinkBody')}</Notice>
|
||||
<button type="button" className="al-cta" onClick={() => void reset.navigate('/forgot-password')}>
|
||||
{t('login.forgotPasswordSubmit')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<ResetForm reset={reset} />
|
||||
)}
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
|
||||
function ResetForm({ reset }: { reset: Reset }) {
|
||||
const { t } = useTranslation();
|
||||
const inputType = reset.showPw ? 'text' : 'password';
|
||||
const title = reset.mfaRequired ? t('login.mfaTitle') : t('login.resetPasswordTitle');
|
||||
const action = reset.mfaRequired ? t('login.resetPasswordVerify') : t('login.resetPasswordSubmit');
|
||||
return (
|
||||
<form className="al-form" onSubmit={(event) => void reset.handleSubmit(event)}>
|
||||
<h1 className="al-title">{title}</h1>
|
||||
<p className="al-sub">{t(reset.mfaRequired ? 'login.resetPasswordMfaBody' : 'login.resetPasswordBody')}</p>
|
||||
{reset.error && <Notice>{reset.error}</Notice>}
|
||||
{reset.mfaRequired ? (
|
||||
<Field
|
||||
label={t('login.mfaCode')}
|
||||
{...mfaCodeInputProps(reset.mfaCode, reset.setMfaCode, t('login.mfaPlaceholder'))}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Field
|
||||
label={t('login.newPassword')}
|
||||
type={inputType}
|
||||
name="new-password"
|
||||
autoComplete="new-password"
|
||||
value={reset.pw}
|
||||
onChange={(event) => reset.setPw(event.target.value)}
|
||||
required
|
||||
after={
|
||||
<button
|
||||
type="button"
|
||||
className="al-eye"
|
||||
aria-label={t('native.claim.showPassword')}
|
||||
aria-pressed={reset.showPw}
|
||||
onClick={() => reset.setShowPw((visible) => !visible)}
|
||||
>
|
||||
{reset.showPw ? <EyeOff size={18} aria-hidden="true" /> : <Eye size={18} aria-hidden="true" />}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<PasswordChecklist password={reset.pw} className="al-check" tone="light" />
|
||||
<Field
|
||||
label={t('login.confirmPassword')}
|
||||
type={inputType}
|
||||
name="confirm-password"
|
||||
autoComplete="new-password"
|
||||
value={reset.pw2}
|
||||
onChange={(event) => reset.setPw2(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<button type="submit" className="al-cta" disabled={reset.isLoading}>
|
||||
{reset.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{reset.isLoading ? t('common.loading') : action}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -132,6 +132,32 @@ describe('useResetPassword', () => {
|
||||
expect(result.current.success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'Invalid or expired reset link',
|
||||
'This reset link has already been used',
|
||||
'Reset link has expired. Please request a new one.',
|
||||
])('stops retrying a link refused by the server (%s)', async (error) => {
|
||||
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ mfa_required: true } as never);
|
||||
vi.mocked(authApi.resetPassword).mockRejectedValueOnce({ response: { data: { error } } });
|
||||
const { result, rerender } = renderHook(() => useResetPassword());
|
||||
|
||||
await submit(result, 'Longenough1!');
|
||||
act(() => result.current.setMfaCode('123456'));
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
|
||||
expect(result.current.linkInvalid).toBe(true);
|
||||
expect(result.current.pw).toBe('');
|
||||
expect(result.current.pw2).toBe('');
|
||||
expect(result.current.mfaCode).toBe('');
|
||||
expect(result.current.mfaRequired).toBe(false);
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(authApi.resetPassword).toHaveBeenCalledTimes(2);
|
||||
|
||||
search = new URLSearchParams('token=fresh-link');
|
||||
rerender();
|
||||
expect(result.current.linkInvalid).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PAGE-RESET-011: surfaces a plain Error message as-is', async () => {
|
||||
vi.mocked(authApi.resetPassword).mockRejectedValueOnce(new Error('Network Error'));
|
||||
const { result } = renderHook(() => useResetPassword());
|
||||
|
||||
@@ -5,11 +5,17 @@ import { getApiErrorMessage } from '../../types'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { passwordErrorKey } from '../../utils/passwordError'
|
||||
|
||||
// Published TREK servers report these refusals as messages, without an error code.
|
||||
const unusableLinkErrors = new Set([
|
||||
'Invalid or expired reset link',
|
||||
'This reset link has already been used',
|
||||
'Reset link has expired. Please request a new one.',
|
||||
])
|
||||
|
||||
/**
|
||||
* Reset-password data hook — owns the token lookup, the form state, the
|
||||
* client-side validation and the submit (incl. the MFA step-up branch).
|
||||
* ResetPasswordPage is a pure wiring container. Behaviour is identical to the
|
||||
* previous in-component logic.
|
||||
* ResetPasswordPage is a pure wiring container.
|
||||
*/
|
||||
export function useResetPassword() {
|
||||
const { t } = useTranslation()
|
||||
@@ -23,8 +29,10 @@ export function useResetPassword() {
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [mfaRequired, setMfaRequired] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [unusableToken, setUnusableToken] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const linkInvalid = unusableToken === token
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) setError(t('login.resetPasswordInvalidLink'))
|
||||
@@ -34,7 +42,7 @@ export function useResetPassword() {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setError('')
|
||||
if (!token) return
|
||||
if (!token || linkInvalid) return
|
||||
const weak = passwordErrorKey(pw)
|
||||
if (weak) { setError(t(weak)); return }
|
||||
if (pw !== pw2) { setError(t('login.passwordsDontMatch')); return }
|
||||
@@ -54,13 +62,23 @@ export function useResetPassword() {
|
||||
setSuccess(true)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(getApiErrorMessage(err, t('login.resetPasswordFailed')))
|
||||
const message = getApiErrorMessage(err, t('login.resetPasswordFailed'))
|
||||
if (unusableLinkErrors.has(message)) {
|
||||
setUnusableToken(token)
|
||||
setPw('')
|
||||
setPw2('')
|
||||
setShowPw(false)
|
||||
setMfaCode('')
|
||||
setMfaRequired(false)
|
||||
} else {
|
||||
setError(message)
|
||||
}
|
||||
}
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return {
|
||||
navigate, token,
|
||||
navigate, token, linkInvalid,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
|
||||
Vendored
+3
@@ -4,6 +4,9 @@
|
||||
/** The version this bundle was built as (client/package.json), set by `define` in vite.config.js. */
|
||||
declare const __TREK_UI_VERSION__: string;
|
||||
|
||||
/** Defined only for the native store-sandbox build. */
|
||||
declare const __TREK_STORE_SANDBOX_ORIGIN__: string | undefined;
|
||||
|
||||
/**
|
||||
* Big Shoulders Display's weights, imported for their stylesheets alone
|
||||
* (components/Studio/bookFontFaces.ts). Its package maps `./*` to `./*.css`
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { fireEvent, waitFor } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
agreement: vi.fn(),
|
||||
purchase: vi.fn().mockResolvedValue({ kind: 'cancelled' }),
|
||||
}));
|
||||
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn() } }));
|
||||
vi.mock('@capacitor/core', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@capacitor/core')>()),
|
||||
CapacitorHttp: { get: mocks.agreement },
|
||||
}));
|
||||
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn().mockResolvedValue(undefined) } }));
|
||||
vi.mock('../../../native-shell/scenery', () => ({
|
||||
WELCOME_CAMERA: [0, 0],
|
||||
cameraForPlan: () => [0, 0],
|
||||
startScenery: () => null,
|
||||
}));
|
||||
vi.mock('../../../src/native/trekShell', () => ({
|
||||
TrekShell: {
|
||||
getServer: vi.fn().mockResolvedValue({ url: null }),
|
||||
requestServer: vi.fn(async ({ url }: { url: string }) => ({
|
||||
status: 200,
|
||||
url,
|
||||
data:
|
||||
new URL(url).pathname === '/api/plans'
|
||||
? {
|
||||
ordering: 'open',
|
||||
plans: [{ id: 'plus', name: 'Plus', storageGb: 50, aiDocumentLimit: null }],
|
||||
}
|
||||
: { available: true },
|
||||
})),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../../src/native/iap', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../src/native/iap')>()),
|
||||
getIapClient: () => ({
|
||||
isAvailable: async () => true,
|
||||
products: async () => new Map([['cloud.plus.monthly', { displayPrice: '$11.99', freeTrial: true }]]),
|
||||
held: async () => false,
|
||||
onTransaction: vi.fn(),
|
||||
unfinished: async () => null,
|
||||
purchase: mocks.purchase,
|
||||
}),
|
||||
}));
|
||||
|
||||
const agreement = { status: 200, data: { version: '2026-12-01', deviations: 'First agreement' } };
|
||||
|
||||
function element<T extends HTMLElement>(selector: string): T {
|
||||
const found = document.querySelector<T>(selector);
|
||||
if (!found) throw new Error(`The app did not show ${selector}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
function mountShell(): void {
|
||||
vi.resetModules();
|
||||
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn() }));
|
||||
vi.stubGlobal('cancelAnimationFrame', vi.fn());
|
||||
document.body.append(Object.assign(document.createElement('main'), { id: 'shell' }));
|
||||
mocks.agreement.mockReset();
|
||||
mocks.purchase.mockClear();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it('keeps the store closed for a withdrawn agreement and asks again when the version changes', async () => {
|
||||
mountShell();
|
||||
const changed = { status: 200, data: { version: '2026-12-02', deviations: 'Updated agreement' } };
|
||||
mocks.agreement
|
||||
.mockResolvedValueOnce(agreement)
|
||||
.mockResolvedValueOnce({ status: 503, data: { code: 'ordering-closed' } })
|
||||
.mockResolvedValueOnce(agreement)
|
||||
.mockResolvedValue(changed);
|
||||
|
||||
await import('../../../native-shell/main');
|
||||
await waitFor(() => expect(element<HTMLElement>('.trial-badge').hidden).toBe(false));
|
||||
fireEvent.click(element('button.discover'));
|
||||
await waitFor(() => expect(element<HTMLButtonElement>('.dock button.cta').hidden).toBe(false));
|
||||
fireEvent.click(element('.dock button.cta'));
|
||||
|
||||
const consent = await waitFor(() => {
|
||||
expect(element('.consent-text').textContent).toBe(agreement.data.deviations);
|
||||
return element<HTMLInputElement>('.consent input');
|
||||
});
|
||||
fireEvent.input(element('.form input[type="text"]'), { target: { value: 'sample-journey' } });
|
||||
fireEvent.input(element('.form input[type="email"]'), { target: { value: 'buyer@example.invalid' } });
|
||||
fireEvent.input(element('.form input[type="password"]'), { target: { value: 'Training#Pass123' } });
|
||||
const submit = element<HTMLButtonElement>('.dock button.cta');
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => {
|
||||
expect(consent.disabled).toBe(true);
|
||||
expect(consent.checked).toBe(false);
|
||||
});
|
||||
expect(mocks.purchase).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(element('.consent-text').textContent).toBe(agreement.data.deviations));
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(element('.consent-text').textContent).toBe(changed.data.deviations));
|
||||
expect(consent.checked).toBe(false);
|
||||
expect(mocks.purchase).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
|
||||
});
|
||||
|
||||
it('requires a sandbox agreement before presenting a store purchase', async () => {
|
||||
mountShell();
|
||||
const sandbox = 'https://store-sandbox.example.com';
|
||||
vi.stubGlobal('__TREK_STORE_SANDBOX_ORIGIN__', sandbox);
|
||||
const sandboxAgreement = {
|
||||
status: 200,
|
||||
data: { ...agreement.data, iapEnvironment: 'sandbox' },
|
||||
};
|
||||
mocks.agreement.mockImplementation(async ({ url }: { url: string }) => {
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/api/plans') {
|
||||
return {
|
||||
status: 200,
|
||||
data: { ordering: 'open', plans: [{ id: 'plus', name: 'Plus', storageGb: 50, aiDocumentLimit: null }] },
|
||||
};
|
||||
}
|
||||
if (path === '/api/slug/check') return { status: 200, data: { status: 'available' } };
|
||||
return agreement;
|
||||
});
|
||||
|
||||
await import('../../../native-shell/main');
|
||||
await waitFor(() => expect(element<HTMLElement>('.trial-badge').hidden).toBe(false));
|
||||
fireEvent.click(element('button.discover'));
|
||||
await waitFor(() => expect(element<HTMLButtonElement>('.dock button.cta').hidden).toBe(false));
|
||||
fireEvent.click(element('.dock button.cta'));
|
||||
|
||||
const consent = await waitFor(() => {
|
||||
const input = element<HTMLInputElement>('.consent input');
|
||||
expect(input.disabled).toBe(true);
|
||||
return input;
|
||||
});
|
||||
const submit = element<HTMLButtonElement>('.dock button.cta');
|
||||
fireEvent.input(element('.form input[type="text"]'), { target: { value: 'sample-journey' } });
|
||||
fireEvent.input(element('.form input[type="email"]'), { target: { value: 'buyer@example.invalid' } });
|
||||
fireEvent.input(element('.form input[type="password"]'), { target: { value: 'Training#Pass123' } });
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(element('.notice').textContent).toBeTruthy());
|
||||
expect(mocks.purchase).not.toHaveBeenCalled();
|
||||
|
||||
mocks.agreement.mockImplementation(async ({ url }: { url: string }) =>
|
||||
new URL(url).pathname === '/api/slug/check' ? { status: 200, data: { status: 'available' } } : sandboxAgreement
|
||||
);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(consent.disabled).toBe(false));
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
|
||||
for (const [options] of mocks.agreement.mock.calls) {
|
||||
expect(new URL(options.url).origin).toBe(sandbox);
|
||||
expect(options.disableRedirects).toBe(true);
|
||||
}
|
||||
});
|
||||
@@ -1,16 +1,40 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
function sandboxOrigin(mode) {
|
||||
const envDir = fileURLToPath(new URL('.', import.meta.url))
|
||||
const { TREK_CLOUD_SANDBOX_ORIGIN: origin } = loadEnv(mode, envDir, 'TREK_CLOUD_SANDBOX_')
|
||||
const url = URL.canParse(origin) ? new URL(origin) : null
|
||||
// The host must also support a wildcard certificate for its tenant subdomains.
|
||||
const dnsName = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*[a-z0-9]$/
|
||||
if (
|
||||
url?.origin !== origin ||
|
||||
url?.protocol !== 'https:' ||
|
||||
url.port ||
|
||||
!dnsName.test(url.hostname) ||
|
||||
url.hostname === 'liketrek.com' ||
|
||||
url.hostname === 'www.liketrek.com'
|
||||
) {
|
||||
throw new Error('TREK_CLOUD_SANDBOX_ORIGIN must be a dedicated sandbox HTTPS origin without a path or port')
|
||||
}
|
||||
return origin
|
||||
}
|
||||
|
||||
// The address screen the native apps ship (native-shell/). Everything past it
|
||||
// is the UI of the server the user picks, so this build stays tiny and apart
|
||||
// from the main one: no PWA, no React, only the native strings of each locale.
|
||||
export default defineConfig({
|
||||
root: fileURLToPath(new URL('./native-shell', import.meta.url)),
|
||||
base: './',
|
||||
publicDir: false,
|
||||
build: {
|
||||
outDir: fileURLToPath(new URL('./native-dist', import.meta.url)),
|
||||
emptyOutDir: true,
|
||||
target: ['es2020', 'safari15', 'chrome100'],
|
||||
},
|
||||
export default defineConfig(({ command, mode }) => {
|
||||
const sandbox = command === 'build' && mode === 'store-sandbox'
|
||||
const output = sandbox ? './native-sandbox-dist' : './native-dist'
|
||||
return {
|
||||
root: fileURLToPath(new URL('./native-shell', import.meta.url)),
|
||||
base: './',
|
||||
publicDir: false,
|
||||
define: sandbox ? { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(sandboxOrigin(mode)) } : {},
|
||||
build: {
|
||||
outDir: fileURLToPath(new URL(output, import.meta.url)),
|
||||
emptyOutDir: true,
|
||||
target: ['es2020', 'safari15', 'chrome100'],
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user