feat(native): TREK Cloud subscriptions through the App Store

The plan picker sent buyers to the website, which the App Store does not allow.
It now sells through StoreKit 2 in the TrekShell plugin (feature storeKit):
App Store price strings in the buyer's currency, the purchase sheet, the signed
transaction redeemed at the control plane, and the transaction finished only
once the instance exists. A purchase whose redeem failed is redeemed again on
retry, never bought twice.

Restore purchases, the auto-renewal terms and the links to the terms of use and
the privacy policy sit under the plans. Where no store purchase is possible
(Android, an older binary) the picker shows the plans with no way to buy and no
pointer to the web.
This commit is contained in:
Maurice
2026-11-07 09:54:16 +01:00
parent ede54d10cd
commit 5462bce9c3
35 changed files with 723 additions and 97 deletions
+96 -6
View File
@@ -1,17 +1,36 @@
import { describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const platform = vi.hoisted(() => ({ ios: true }));
const shell = vi.hoisted(() => ({
getCapabilities: vi.fn(),
storeProducts: vi.fn(),
storePurchase: vi.fn(),
storeFinish: vi.fn(),
storeRestore: vi.fn(),
}));
vi.mock('./platform', () => ({ isNativeIos: () => platform.ios }));
vi.mock('./trekShell', () => ({ TrekShell: shell }));
import { fakeIapClient, nativeIapClient, productIdFor } from './iap';
/** A signed transaction as far as the client reads it: only the payload matters here. */
function jwsFor(productId: string): string {
const payload = btoa(JSON.stringify({ productId })).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
return `header.${payload}.signature`;
}
beforeEach(() => {
platform.ios = true;
for (const fn of Object.values(shell)) fn.mockReset();
});
describe('in-app purchase client', () => {
it('names store products by the shared scheme', () => {
expect(productIdFor('start', 'month')).toBe('cloud.start.monthly');
expect(productIdFor('pro', 'year')).toBe('cloud.pro.yearly');
});
it('the native client is unavailable until the purchase plugin is wired', async () => {
expect(await nativeIapClient.isAvailable()).toBe(false);
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'failed' });
});
it('the fake client yields a receipt for the product asked for', async () => {
expect(await fakeIapClient.isAvailable()).toBe(true);
const outcome = await fakeIapClient.purchase('cloud.plus.monthly');
@@ -22,3 +41,74 @@ describe('in-app purchase client', () => {
expect(outcome.purchase.receipt).toContain('cloud.plus.monthly');
});
});
describe('native client', () => {
it('is available only on iOS with the storeKit feature', async () => {
shell.getCapabilities.mockResolvedValue({ features: ['storeKit'] });
expect(await nativeIapClient.isAvailable()).toBe(true);
shell.getCapabilities.mockResolvedValue({ features: ['widgets'] });
expect(await nativeIapClient.isAvailable()).toBe(false);
shell.getCapabilities.mockRejectedValue({ code: 'UNIMPLEMENTED' });
expect(await nativeIapClient.isAvailable()).toBe(false);
platform.ios = false;
shell.getCapabilities.mockResolvedValue({ features: ['storeKit'] });
expect(await nativeIapClient.isAvailable()).toBe(false);
});
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);
shell.storeProducts.mockRejectedValue(new Error('down'));
expect((await nativeIapClient.prices(['cloud.plus.monthly'])).size).toBe(0);
});
it('turns a bought transaction into a receipt', async () => {
shell.storePurchase.mockResolvedValue({ kind: 'bought', jws: 'signed', transactionId: '42' });
expect(await nativeIapClient.purchase('cloud.plus.yearly')).toEqual({
kind: 'bought',
purchase: { platform: 'apple', productId: 'cloud.plus.yearly', receipt: 'signed', transactionId: '42' },
});
});
it('passes cancel and pending through, and fails on anything else', async () => {
shell.storePurchase.mockResolvedValue({ kind: 'cancelled' });
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'cancelled' });
shell.storePurchase.mockResolvedValue({ kind: 'pending' });
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'pending' });
shell.storePurchase.mockResolvedValue({ kind: 'bought' });
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'failed' });
shell.storePurchase.mockRejectedValue(new Error('boom'));
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'failed' });
});
it('finishes by transaction id and swallows a failure', async () => {
const purchase = { platform: 'apple' as const, productId: 'cloud.plus.monthly', receipt: 'x', transactionId: '7' };
shell.storeFinish.mockResolvedValue(undefined);
await nativeIapClient.finish(purchase);
expect(shell.storeFinish).toHaveBeenCalledWith({ transactionId: '7' });
shell.storeFinish.mockRejectedValue(new Error('gone'));
await expect(nativeIapClient.finish(purchase)).resolves.toBeUndefined();
});
it('restores the subscription the Apple ID holds, with its product', async () => {
const jws = jwsFor('cloud.pro.yearly');
shell.storeRestore.mockResolvedValue({ jws, transactionId: '9' });
expect(await nativeIapClient.restore()).toEqual({
platform: 'apple',
productId: 'cloud.pro.yearly',
receipt: jws,
transactionId: '9',
});
expect(shell.storeRestore).toHaveBeenCalledWith({ prefix: 'cloud.' });
shell.storeRestore.mockResolvedValue({});
expect(await nativeIapClient.restore()).toBeNull();
});
});
+110 -19
View File
@@ -1,12 +1,15 @@
import { isNativeIos } from './platform';
import { TrekShell } from './trekShell';
/**
* In-app purchase, from the app's side. A seam, like {@link TrekShell}: the
* screens drive a plan to a receipt through this, and never touch the store
* plugin directly. Two implementations stand behind it — a fake one for
* development and preview, so the whole subscription flow can be walked without a
* store, and the native one that will call the platform plugin once the store
* products and accounts exist. Until then the native client reports itself
* unavailable and the plan picker falls back to finishing on the web, so nothing
* half-wired ever faces a customer.
* screens drive a plan to a receipt through this, and never touch StoreKit
* directly. Two implementations stand behind it: a fake one for development and
* preview, so the whole subscription flow can be walked without a store, and the
* native one that runs StoreKit 2 through TrekShell (feature storeKit). Where
* neither can take a payment (Android until Play Billing is wired, a binary from
* before storeKit) the client reports itself unavailable and the shell offers no
* purchase at all: the store rules leave no room for sending buyers to the web.
*/
type IapPlatform = 'apple' | 'google';
@@ -15,26 +18,50 @@ type IapPlatform = 'apple' | 'google';
export interface Purchase {
platform: IapPlatform;
productId: string;
/** Apple: the signed transaction (JWS) the control plane verifies. */
receipt: string;
/** The store's id for this transaction, handed back to {@link IapClient.finish}. */
transactionId: string;
}
/** What a purchase attempt came to. `cancelled` is the customer backing out, not an error. */
type PurchaseOutcome = { kind: 'bought'; purchase: Purchase } | { kind: 'cancelled' } | { kind: 'failed' };
/**
* What a purchase attempt came to. `cancelled` is the customer backing out, not
* an error; `pending` is a purchase waiting on someone else (Ask to Buy, a bank),
* which a restore picks up once it goes through.
*/
type PurchaseOutcome =
| { kind: 'bought'; purchase: Purchase }
| { kind: 'cancelled' }
| { kind: 'pending' }
| { kind: 'failed' };
export interface IapClient {
/** Whether this build can take a payment: the plugin is present and the store products exist. */
/** 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.
*/
prices(productIds: string[]): Promise<Map<string, string>>;
/** Runs the platform's purchase sheet for a product and resolves with what became of it. */
purchase(productId: 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. */
restore(): Promise<Purchase | null>;
}
/** Every store product of the cloud starts with this. */
const PRODUCT_PREFIX = 'cloud.';
/**
* The store product id for a plan and interval. Must match the identifiers created
* in App Store Connect and the Play Console, and the control plane's catalog
* (`cloud.<plan>.<monthly|yearly>`); kept here as the one place the app names them.
*/
export function productIdFor(planId: string, interval: 'month' | 'year'): string {
return `cloud.${planId}.${interval === 'year' ? 'yearly' : 'monthly'}`;
return `${PRODUCT_PREFIX}${planId}.${interval === 'year' ? 'yearly' : 'monthly'}`;
}
/**
@@ -46,30 +73,94 @@ export const fakeIapClient: IapClient = {
async isAvailable() {
return true;
},
async prices() {
return new Map();
},
async purchase(productId) {
await new Promise((resolve) => setTimeout(resolve, 900));
const nonce = String(Date.now());
return {
kind: 'bought',
purchase: { platform: 'apple', productId, receipt: `fake-receipt:${productId}:${Date.now()}` },
purchase: { platform: 'apple', productId, receipt: `fake-receipt:${productId}:${nonce}`, transactionId: nonce },
};
},
async finish() {},
async restore() {
return null;
},
};
/**
* The store client. A stub until the purchase plugin is a dependency and the
* products exist: it reports itself unavailable, so the plan picker finishes on
* the web instead of offering a payment it cannot take. When the plugin lands,
* this is where it is wired; the screens do not change.
* StoreKit 2 through TrekShell. Available on iOS when the binary has the
* storeKit feature; everywhere else (Android, the web, an older binary) it
* reports itself unavailable and every call comes to nothing.
*/
export const nativeIapClient: IapClient = {
async isAvailable() {
return false;
if (!isNativeIos()) return false;
try {
const caps = await TrekShell.getCapabilities();
return caps.features.includes('storeKit');
} catch {
return false;
}
},
async purchase() {
return { kind: 'failed' };
async prices(productIds) {
try {
const { products } = await TrekShell.storeProducts({ ids: productIds });
return new Map(products.map((p) => [p.id, p.displayPrice]));
} catch {
return new Map();
}
},
async purchase(productId) {
try {
const result = await TrekShell.storePurchase({ productId });
if (result.kind === 'bought' && result.jws && result.transactionId) {
return {
kind: 'bought',
purchase: { platform: 'apple', productId, receipt: result.jws, transactionId: result.transactionId },
};
}
if (result.kind === 'cancelled' || result.kind === 'pending') return { kind: result.kind };
return { kind: 'failed' };
} catch {
return { kind: 'failed' };
}
},
async finish(purchase) {
try {
await TrekShell.storeFinish({ transactionId: purchase.transactionId });
} catch {
// Left unfinished, the store hands the transaction over again; a restore redeems it idempotently.
}
},
async restore() {
try {
const { jws, transactionId } = await TrekShell.storeRestore({ prefix: PRODUCT_PREFIX });
if (!jws || !transactionId) return null;
return { platform: 'apple', productId: productIdOf(jws), receipt: jws, transactionId };
} catch {
return null;
}
},
};
/**
* The product id inside a signed transaction, read for display and routing only:
* the control plane verifies the signature and takes the product from there.
*/
function productIdOf(jws: string): string {
try {
const part = jws.split('.')[1] ?? '';
const json = atob(part.replace(/-/g, '+').replace(/_/g, '/'));
const id = (JSON.parse(json) as { productId?: unknown }).productId;
return typeof id === 'string' ? id : '';
} catch {
return '';
}
}
/**
* Whether to use the fake. On in a development build, and switchable on in a
* preview build with `localStorage['trek-iap-fake'] = '1'`, so the flow can be
+7
View File
@@ -14,3 +14,10 @@ export const DEMO_SERVER_URL = 'https://demo.liketrek.com';
/** TREK Cloud, for someone who wants a hosted TREK rather than running their own. */
export const CLOUD_URL = 'https://liketrek.com';
/**
* The terms an in-app subscription is sold under: Apple's standard licence
* agreement, which the App Store applies when an app names no own EULA. The
* store rules ask for it next to the purchase, together with the privacy policy.
*/
export const STORE_TERMS_URL = 'https://www.apple.com/legal/internet-services/itunes/dev/stdeula/';
+10
View File
@@ -73,6 +73,16 @@ export interface TrekShellPlugin {
total: number;
}): Promise<{ running: boolean }>;
endTripDay(): Promise<void>;
/** iOS, feature storeKit: the App Store's price strings for the products it knows. */
storeProducts(options: { ids: string[] }): Promise<{ products: { id: string; displayPrice: string }[] }>;
/** iOS, feature storeKit: the purchase sheet; `jws` is the signed transaction, set when bought. */
storePurchase(options: {
productId: string;
}): Promise<{ kind: 'bought' | 'cancelled' | 'pending' | 'failed'; jws?: string; transactionId?: string }>;
/** iOS, feature storeKit: marks a purchase delivered once its instance exists. */
storeFinish(options: { transactionId: string }): Promise<void>;
/** iOS, feature storeKit: the newest active subscription under `prefix` on this Apple ID, if any. */
storeRestore(options: { prefix: string }): Promise<{ jws?: string; transactionId?: string }>;
addListener(
event: 'pushOpened',
listener: (payload: { url: string }) => void