@tofound/billing 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,232 @@
1
+ /**
2
+ * App Store event → normalized events, the pure half of the adapter.
3
+ * Deterministic over the stored (decoded, redacted) payload, the delivery's
4
+ * `subjectRef` and the adapter's product map, so a replay normalizes like the
5
+ * first run.
6
+ *
7
+ * - One-time products (consumable, non-consumable) are purchases keyed by
8
+ * `transactionId`: `ONE_TIME_CHARGE` or a client-posted transaction
9
+ * completes one, `REFUND` / `REVOKE` reverse it and `REFUND_REVERSED`
10
+ * reinstates it. Their `signedDate` is the watermark, so the newest word
11
+ * wins whatever order they arrive in (design §6).
12
+ * - Auto-renewable subscriptions become `subscription.snapshot`s keyed by
13
+ * `originalTransactionId`; the notification's `status` decides the term
14
+ * status, a refund or revoke ends access now (design §4.6).
15
+ * - A purchase names our checkout session either through the host's client
16
+ * proof or because its `appAccountToken` is a session id (`checkoutPattern`);
17
+ * the library credits checkout-bound purchases only.
18
+ * - Store prices vary per storefront and are not ours to check: the product
19
+ * id is the price authority, and the amount reported is the configured
20
+ * product amount × quantity, which is what the host's session holds.
21
+ */
22
+ import { CURRENCY_EXPONENT } from '../../domain/money.js';
23
+ /** Event type of a client-posted StoreKit transaction (not a notification type). */
24
+ export const APPLE_TRANSACTION_EVENT = 'TRANSACTION';
25
+ export const rec = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
26
+ const str = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
27
+ /** Apple timestamps are epoch milliseconds. */
28
+ export function msDate(value) {
29
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0)
30
+ return null;
31
+ return new Date(value);
32
+ }
33
+ const own = (map, key) => (key !== null && Object.hasOwn(map, key) ? map[key] : undefined);
34
+ const ONE_TIME_TYPES = new Set(['Consumable', 'Non-Consumable']);
35
+ const SUBSCRIPTION_TYPE = 'Auto-Renewable Subscription';
36
+ /** Notification types that describe an auto-renewable subscription's state. */
37
+ const SUBSCRIPTION_NOTIFICATIONS = new Set([
38
+ 'SUBSCRIBED',
39
+ 'DID_RENEW',
40
+ 'DID_FAIL_TO_RENEW',
41
+ 'GRACE_PERIOD_EXPIRED',
42
+ 'EXPIRED',
43
+ 'DID_CHANGE_RENEWAL_STATUS',
44
+ 'DID_CHANGE_RENEWAL_PREF',
45
+ 'RENEWAL_EXTENDED',
46
+ 'OFFER_REDEEMED',
47
+ 'REFUND',
48
+ 'REFUND_REVERSED',
49
+ 'REVOKE',
50
+ ]);
51
+ /** Two snapshots signed the same millisecond: the later lifecycle state wins. */
52
+ const TIE_ORDER = ['active', 'grace', 'past_due', 'expired', 'revoked'];
53
+ /** `data.status` of a subscription notification. */
54
+ const STATUS = { 1: 'active', 2: 'expired', 3: 'past_due', 4: 'grace', 5: 'revoked' };
55
+ /** A price in Apple's milliunits as minor units, when it is one exactly. */
56
+ function priceOf(txn) {
57
+ const currency = str(txn['currency'])?.toUpperCase();
58
+ const price = txn['price'];
59
+ if (!currency || !Object.hasOwn(CURRENCY_EXPONENT, currency) || typeof price !== 'number' || !Number.isSafeInteger(price) || price < 0)
60
+ return undefined;
61
+ const divisor = 10 ** (3 - CURRENCY_EXPONENT[currency]);
62
+ return price % divisor === 0 ? { currency, amountMinor: price / divisor } : undefined;
63
+ }
64
+ function bindingOf(token, hostCheckoutRef, options) {
65
+ const checkoutRef = hostCheckoutRef ?? (token && options.checkoutPattern.test(token) ? token : null);
66
+ const account = token
67
+ ? { kind: 'apple_app_account_token', value: token }
68
+ : checkoutRef
69
+ ? { kind: 'checkout', value: checkoutRef }
70
+ : null;
71
+ return { account, checkoutRef };
72
+ }
73
+ function completed(txn, binding, occurredAt, proof, options) {
74
+ const transactionId = str(txn['transactionId']);
75
+ if (!transactionId)
76
+ return { kind: 'needs_review', reason: 'missing_transaction_id' };
77
+ // A notification that names no checkout of ours is settled by the host's
78
+ // client proof; parking every such purchase for a human would only be noise.
79
+ if (!proof && !binding.checkoutRef)
80
+ return { kind: 'ignored', reason: 'unbound_purchase' };
81
+ if (!binding.account)
82
+ return { kind: 'needs_review', reason: 'unbound_purchase' };
83
+ const productId = str(txn['productId']);
84
+ const product = own(options.products, productId);
85
+ if (!product)
86
+ return { kind: 'needs_review', reason: 'unknown_product', detail: { productId } };
87
+ if (!product.amount)
88
+ return { kind: 'needs_review', reason: 'product_amount_missing', detail: { productId } };
89
+ const quantity = txn['quantity'] === undefined ? 1 : txn['quantity'];
90
+ const total = typeof quantity === 'number' ? product.amount.amountMinor * quantity : NaN;
91
+ if (!Number.isSafeInteger(quantity) || quantity < 1 || !Number.isSafeInteger(total)) {
92
+ return { kind: 'needs_review', reason: 'invalid_quantity', detail: { quantity: quantity ?? null } };
93
+ }
94
+ return {
95
+ kind: 'purchase.completed',
96
+ account: binding.account,
97
+ externalId: transactionId,
98
+ productRef: product.productRef,
99
+ quantity: quantity,
100
+ amount: { currency: product.amount.currency, amountMinor: total },
101
+ ...(binding.checkoutRef ? { checkoutRef: binding.checkoutRef } : {}),
102
+ occurredAt,
103
+ };
104
+ }
105
+ function changed(kind, txn, binding, occurredAt, reason) {
106
+ const transactionId = str(txn['transactionId']);
107
+ if (!transactionId)
108
+ return { kind: 'needs_review', reason: 'missing_transaction_id' };
109
+ return {
110
+ kind,
111
+ externalId: transactionId,
112
+ ...(reason ? { reason } : {}),
113
+ ...(binding.checkoutRef ? { checkoutRef: binding.checkoutRef } : {}),
114
+ occurredAt,
115
+ };
116
+ }
117
+ function snapshot(type, data, txn, renewal, token, occurredAt, options) {
118
+ if (!token)
119
+ return { kind: 'ignored', reason: 'no_account_token' };
120
+ const externalId = str(txn['originalTransactionId']);
121
+ if (!externalId)
122
+ return { kind: 'needs_review', reason: 'missing_original_transaction_id' };
123
+ const product = own(options.products, str(txn['productId']));
124
+ if (!product)
125
+ return { kind: 'ignored', reason: 'unknown_product' };
126
+ const subtype = str(data['subtype']);
127
+ const revokedAt = msDate(txn['revocationDate']);
128
+ let status;
129
+ if (type === 'REFUND' || type === 'REVOKE' || revokedAt)
130
+ status = 'revoked';
131
+ else if (typeof data['status'] === 'number' && Object.hasOwn(STATUS, data['status']))
132
+ status = STATUS[data['status']];
133
+ else if (type === 'EXPIRED')
134
+ status = 'expired';
135
+ else if (type === 'GRACE_PERIOD_EXPIRED')
136
+ status = 'past_due';
137
+ else if (type === 'DID_FAIL_TO_RENEW')
138
+ status = subtype === 'GRACE_PERIOD' ? 'grace' : 'past_due';
139
+ else
140
+ status = 'active';
141
+ const periodStart = msDate(txn['purchaseDate']);
142
+ const expires = msDate(txn['expiresDate']);
143
+ // A revocation ends access when it happened, not when the period would have.
144
+ const endedAt = status === 'revoked' ? (revokedAt ?? occurredAt) : null;
145
+ const periodEnd = expires && endedAt ? (endedAt < expires ? endedAt : expires) : (expires ?? endedAt);
146
+ if (!periodStart || !periodEnd)
147
+ return { kind: 'needs_review', reason: 'missing_period' };
148
+ const live = status === 'active' || status === 'grace' || status === 'past_due';
149
+ const renewing = renewal?.['autoRenewStatus'] === 1;
150
+ const graceUntil = status === 'grace' ? msDate(renewal?.['gracePeriodExpiresDate']) : null;
151
+ const nextProductId = str(renewal?.['autoRenewProductId']);
152
+ const next = nextProductId && nextProductId !== str(txn['productId']) ? own(options.products, nextProductId) : undefined;
153
+ const price = priceOf(txn);
154
+ return {
155
+ kind: 'subscription.snapshot',
156
+ account: { kind: 'apple_app_account_token', value: token },
157
+ externalId,
158
+ planRef: product.productRef,
159
+ status,
160
+ periodStart,
161
+ periodEnd,
162
+ autoRenew: live && renewing,
163
+ cancelAtPeriodEnd: live && renewal !== null && !renewing,
164
+ ...(graceUntil ? { graceUntil } : {}),
165
+ ...(next ? { nextPlanRef: next.productRef } : {}),
166
+ ...(price ? { price } : {}),
167
+ occurredAt,
168
+ tieBreak: String(TIE_ORDER.indexOf(status) + 1),
169
+ };
170
+ }
171
+ /**
172
+ * Normalize one stored App Store delivery. `payload` is what the adapter
173
+ * stored: a decoded notification (`data.transaction`, `data.renewal`) or,
174
+ * for a client proof, `{ transaction, checkoutRef? }`.
175
+ */
176
+ export function normalizeAppleEvent(eventType, payload, subjectRef, occurredAt, options) {
177
+ const body = rec(payload) ?? {};
178
+ if (eventType === APPLE_TRANSACTION_EVENT) {
179
+ const txn = rec(body['transaction']);
180
+ if (!txn)
181
+ return { kind: 'needs_review', reason: 'missing_transaction' };
182
+ const binding = bindingOf(subjectRef, str(body['checkoutRef']), options);
183
+ const type = str(txn['type']);
184
+ if (type === SUBSCRIPTION_TYPE)
185
+ return { kind: 'ignored', reason: 'subscription_transaction' };
186
+ if (!type || !ONE_TIME_TYPES.has(type))
187
+ return { kind: 'ignored', reason: `unsupported_type:${type ?? 'none'}` };
188
+ // Refunded before it reached us: record the reversal so it never credits.
189
+ if (msDate(txn['revocationDate']))
190
+ return changed('purchase.reversed', txn, binding, occurredAt, 'refund');
191
+ return completed(txn, binding, occurredAt, true, options);
192
+ }
193
+ const data = rec(body['data']) ?? {};
194
+ const txn = rec(data['transaction']);
195
+ const renewal = rec(data['renewal']);
196
+ const view = { ...data, subtype: body['subtype'] };
197
+ if (eventType === 'TEST')
198
+ return { kind: 'ignored', reason: 'test_notification' };
199
+ if (!txn)
200
+ return { kind: 'ignored', reason: `no_transaction:${eventType}` };
201
+ const type = str(txn['type']);
202
+ if (type === SUBSCRIPTION_TYPE) {
203
+ if (eventType === 'CONSUMPTION_REQUEST')
204
+ return consumption(txn, occurredAt);
205
+ if (!SUBSCRIPTION_NOTIFICATIONS.has(eventType))
206
+ return { kind: 'ignored', reason: `unhandled_type:${eventType}` };
207
+ return snapshot(eventType, view, txn, renewal, subjectRef, occurredAt, options);
208
+ }
209
+ if (!type || !ONE_TIME_TYPES.has(type))
210
+ return { kind: 'ignored', reason: `unsupported_type:${type ?? 'none'}` };
211
+ const binding = bindingOf(subjectRef, null, options);
212
+ switch (eventType) {
213
+ case 'ONE_TIME_CHARGE':
214
+ return completed(txn, binding, occurredAt, false, options);
215
+ case 'REFUND':
216
+ return changed('purchase.reversed', txn, binding, occurredAt, 'refund');
217
+ case 'REVOKE':
218
+ return changed('purchase.reversed', txn, binding, occurredAt, 'revoke');
219
+ case 'REFUND_REVERSED':
220
+ return changed('purchase.reinstated', txn, binding, occurredAt);
221
+ case 'CONSUMPTION_REQUEST':
222
+ return consumption(txn, occurredAt);
223
+ default:
224
+ return { kind: 'ignored', reason: `unhandled_type:${eventType}` };
225
+ }
226
+ }
227
+ function consumption(txn, occurredAt) {
228
+ const transactionId = str(txn['transactionId']);
229
+ if (!transactionId)
230
+ return { kind: 'needs_review', reason: 'missing_transaction_id' };
231
+ return { kind: 'consumption.requested', externalId: transactionId, occurredAt };
232
+ }
@@ -0,0 +1,54 @@
1
+ import { type ConsumptionReporter, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier } from '../port.js';
2
+ import { type AppleProduct } from './events.js';
3
+ export { APPLE_RECEIPT_SIGNING_OID, APPLE_ROOT_CA_G3_PEM, APPLE_ROOT_CA_G3_SHA256, APPLE_WWDR_INTERMEDIATE_OID, } from './jws.js';
4
+ export { APPLE_TRANSACTION_EVENT, type AppleProduct } from './events.js';
5
+ /** App Store Server API credentials (an In-App Purchase key from App Store Connect). */
6
+ export interface AppleServerApiCredentials {
7
+ issuerId: string;
8
+ keyId: string;
9
+ /** The `.p8` key, PEM. */
10
+ privateKey: string;
11
+ }
12
+ export interface AppleAdapterOptions {
13
+ /** Required. `production` accepts only Production payloads, `sandbox` only Sandbox. */
14
+ environment: ProviderEnvironment;
15
+ /** This app's bundle id: a payload signed for any other app is refused. */
16
+ bundleId: string;
17
+ /** This app's Apple id; checked when the notification carries one. Production only. */
18
+ appAppleId?: number;
19
+ /** App Store product id → what it means here. */
20
+ products: Readonly<Record<string, AppleProduct>>;
21
+ /** Our checkout session ids as carried in `appAccountToken`. Default: UUID. */
22
+ checkoutPattern?: RegExp;
23
+ /**
24
+ * Trusted roots (PEM). **Tests only** — production leaves it unset and
25
+ * trusts the pinned Apple Root CA G3 alone.
26
+ */
27
+ trustedRoots?: readonly string[];
28
+ /** Needed only for `reportConsumption`. */
29
+ serverApi?: AppleServerApiCredentials;
30
+ /** Wall clock for certificate validity and API tokens. Default `new Date()`. */
31
+ clock?: () => Date;
32
+ fetch?: typeof fetch;
33
+ /** API timeout. Default 10 s. */
34
+ timeoutMs?: number;
35
+ }
36
+ /** A StoreKit 2 transaction posted by the app, bound to the host's checkout session. */
37
+ export interface AppleTransactionProof {
38
+ signedTransaction: string;
39
+ /** The checkout session the host created for this purchase (server-priced). */
40
+ checkoutRef?: string;
41
+ }
42
+ export interface AppleAdapter extends ProviderAdapter, PurchaseVerifier<AppleTransactionProof>, ConsumptionReporter {
43
+ readonly id: 'apple';
44
+ }
45
+ /** An App Store Server API call failed. Never carries the token or the response body. */
46
+ export declare class AppleApiError extends Error {
47
+ readonly name = "AppleApiError";
48
+ readonly code: 'apple_unreachable' | 'apple_error';
49
+ readonly status: number | null;
50
+ constructor(code: AppleApiError['code'], message: string, status?: number | null);
51
+ }
52
+ export declare function createAppleAdapter(options: AppleAdapterOptions): AppleAdapter;
53
+ /** Apple retries any non-2xx for days; acknowledge everything a retry cannot change. */
54
+ export declare function respondApple(outcome: IngestOutcome): ProviderResponse;
@@ -0,0 +1,231 @@
1
+ /**
2
+ * App Store adapter (`@tofound/billing/providers/apple`), ported from Lohi
3
+ * `lib/apple-iap.ts` and `lib/apple-server-api.ts`:
4
+ * - App Store Server Notifications V2 and client-posted StoreKit 2
5
+ * transactions are verified as JWS chained to the pinned Apple Root CA G3
6
+ * (`jws.ts`), the nested transaction and renewal info included, and must
7
+ * name this app's bundle id and this adapter's environment — nothing is
8
+ * stored otherwise;
9
+ * - notifications dedup on `notificationUUID`, client proofs on
10
+ * `apple:txn:<transactionId>`, and both take the inbox's one apply path, so
11
+ * one transaction credits once; `signedDate` is the watermark;
12
+ * - only the decoded payloads are stored, never the raw JWS or certificates.
13
+ * No SDK, no env reads, no logging; the environment is required and a
14
+ * production adapter refuses sandbox payloads (App Review buys in sandbox:
15
+ * the host decides how to route those).
16
+ */
17
+ import { createHash, createPrivateKey, sign, X509Certificate } from 'node:crypto';
18
+ import { ProviderConfigError, VerifyError, } from '../port.js';
19
+ import { APPLE_TRANSACTION_EVENT, msDate, normalizeAppleEvent, rec } from './events.js';
20
+ import { pinnedAppleRoot, verifyAppleJws } from './jws.js';
21
+ export { APPLE_RECEIPT_SIGNING_OID, APPLE_ROOT_CA_G3_PEM, APPLE_ROOT_CA_G3_SHA256, APPLE_WWDR_INTERMEDIATE_OID, } from './jws.js';
22
+ export { APPLE_TRANSACTION_EVENT } from './events.js';
23
+ /** Apple's `environment` value for each rail. */
24
+ const APPLE_ENVIRONMENT = { production: 'Production', sandbox: 'Sandbox' };
25
+ const SERVER_API_BASE = {
26
+ production: 'https://api.storekit.apple.com',
27
+ sandbox: 'https://api.storekit-sandbox.apple.com',
28
+ };
29
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
30
+ const MAX_BODY = 128 * 1024;
31
+ const MAX_ID = 128;
32
+ const stateless = (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
33
+ /** An App Store Server API call failed. Never carries the token or the response body. */
34
+ export class AppleApiError extends Error {
35
+ name = 'AppleApiError';
36
+ code;
37
+ status;
38
+ constructor(code, message, status = null) {
39
+ super(message);
40
+ this.code = code;
41
+ this.status = status;
42
+ }
43
+ }
44
+ const boundedId = (value) => (typeof value === 'string' && value.length > 0 && value.length <= MAX_ID ? value : null);
45
+ /** A client proof's event id: the purchase, plus what could change its outcome. */
46
+ function proofEventId(base, checkoutRef, reversed) {
47
+ const session = checkoutRef ? `:c${createHash('sha256').update(checkoutRef).digest('hex').slice(0, 16)}` : '';
48
+ return `${base}${session}${reversed ? ':reversed' : ''}`;
49
+ }
50
+ export function createAppleAdapter(options) {
51
+ const { environment } = options;
52
+ if (environment !== 'production' && environment !== 'sandbox') {
53
+ throw new ProviderConfigError('apple_environment_required', 'App Store environment must be passed explicitly: production | sandbox');
54
+ }
55
+ if (!options.bundleId)
56
+ throw new ProviderConfigError('apple_bundle_id_required', 'the app bundle id is required');
57
+ let roots;
58
+ try {
59
+ roots = options.trustedRoots ? options.trustedRoots.map((pem) => new X509Certificate(pem)) : [pinnedAppleRoot()];
60
+ }
61
+ catch {
62
+ throw new ProviderConfigError('apple_invalid_root', 'trusted root certificate does not load');
63
+ }
64
+ if (roots.length === 0)
65
+ throw new ProviderConfigError('apple_invalid_root', 'at least one trusted root is required');
66
+ const normalizeOptions = { products: { ...options.products }, checkoutPattern: stateless(options.checkoutPattern ?? UUID_RE) };
67
+ const clock = options.clock ?? (() => new Date());
68
+ const fetchImpl = options.fetch ?? globalThis.fetch;
69
+ const timeoutMs = options.timeoutMs ?? 10_000;
70
+ let serverKey = null;
71
+ const expectedEnvironment = APPLE_ENVIRONMENT[environment];
72
+ const jws = (value) => verifyAppleJws(value, { roots, at: clock() });
73
+ /** Tenancy and rail: a payload for another app or the other environment is not ours. */
74
+ function checkOwnership(subject, what, rail = true) {
75
+ if (subject['bundleId'] !== options.bundleId)
76
+ throw new VerifyError('unauthorized', `Apple ${what} is for another bundle`);
77
+ if (rail && subject['environment'] !== expectedEnvironment)
78
+ throw new VerifyError('unauthorized', `Apple ${what} is for another environment`);
79
+ }
80
+ function decodeTransaction(signed) {
81
+ const txn = jws(signed);
82
+ checkOwnership(txn, 'transaction');
83
+ return txn;
84
+ }
85
+ function serverToken() {
86
+ const creds = options.serverApi;
87
+ if (!creds)
88
+ throw new ProviderConfigError('apple_server_api_not_configured', 'App Store Server API credentials are required');
89
+ try {
90
+ serverKey ??= createPrivateKey(creds.privateKey);
91
+ }
92
+ catch {
93
+ throw new ProviderConfigError('apple_server_api_invalid_key', 'App Store Server API key does not load');
94
+ }
95
+ const iat = Math.floor(clock().getTime() / 1000);
96
+ const b64 = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
97
+ const input = `${b64({ alg: 'ES256', kid: creds.keyId, typ: 'JWT' })}.${b64({ iss: creds.issuerId, iat, exp: iat + 900, aud: 'appstoreconnect-v1', bid: options.bundleId })}`;
98
+ return `${input}.${sign('sha256', Buffer.from(input), { key: serverKey, dsaEncoding: 'ieee-p1363' }).toString('base64url')}`;
99
+ }
100
+ const adapter = {
101
+ id: 'apple',
102
+ environment,
103
+ async verify(req) {
104
+ if (req.rawBody.length > MAX_BODY)
105
+ throw new VerifyError('malformed', 'Apple notification body oversized');
106
+ let body;
107
+ try {
108
+ body = JSON.parse(req.rawBody);
109
+ }
110
+ catch {
111
+ throw new VerifyError('malformed', 'Apple notification body is not JSON');
112
+ }
113
+ const signedPayload = rec(body)?.['signedPayload'];
114
+ if (typeof signedPayload !== 'string')
115
+ throw new VerifyError('malformed', 'Apple notification body has no signedPayload');
116
+ const notification = jws(signedPayload);
117
+ const notificationType = boundedId(notification['notificationType']);
118
+ const uuid = boundedId(notification['notificationUUID']);
119
+ const signedDate = msDate(notification['signedDate']);
120
+ if (!notificationType || !uuid || !signedDate)
121
+ throw new VerifyError('malformed', 'Apple notification lacks its type, id or signedDate');
122
+ const data = rec(notification['data']);
123
+ // Summary-style notifications carry the app in `summary` instead of `data`.
124
+ const summary = data ?? rec(notification['summary']);
125
+ // External purchase token notifications name the app but no environment;
126
+ // nothing in them credits, so the bundle is proof enough.
127
+ const subject = summary ?? rec(notification['externalPurchaseToken']);
128
+ if (!subject)
129
+ throw new VerifyError('unauthorized', 'Apple notification names no app');
130
+ checkOwnership(subject, 'notification', summary !== null);
131
+ const appAppleId = subject['appAppleId'];
132
+ if (options.appAppleId !== undefined && appAppleId !== undefined && appAppleId !== options.appAppleId) {
133
+ throw new VerifyError('unauthorized', 'Apple notification is for another app id');
134
+ }
135
+ let stored;
136
+ let token = null;
137
+ if (data) {
138
+ const { signedTransactionInfo, signedRenewalInfo, ...rest } = data;
139
+ stored = { ...rest };
140
+ if (signedTransactionInfo !== undefined) {
141
+ const transaction = decodeTransaction(signedTransactionInfo);
142
+ token = boundedId(transaction['appAccountToken']);
143
+ stored['transaction'] = transaction;
144
+ }
145
+ // Renewal info carries no bundle id; its signature and environment are the proof.
146
+ if (signedRenewalInfo !== undefined) {
147
+ const renewal = jws(signedRenewalInfo);
148
+ if (renewal['environment'] !== expectedEnvironment)
149
+ throw new VerifyError('unauthorized', 'Apple renewal info is for another environment');
150
+ stored['renewal'] = renewal;
151
+ }
152
+ }
153
+ const { data: _, ...envelope } = notification;
154
+ return {
155
+ provider: 'apple',
156
+ environment,
157
+ eventId: `apple:${uuid}`,
158
+ eventType: notificationType,
159
+ occurredAt: signedDate,
160
+ payload: { ...envelope, ...(stored ? { data: stored } : {}) },
161
+ ...(token ? { subjectRef: token } : {}),
162
+ };
163
+ },
164
+ async normalize(delivery) {
165
+ return [normalizeAppleEvent(delivery.eventType, delivery.payload, delivery.subjectRef ?? null, delivery.occurredAt, normalizeOptions)];
166
+ },
167
+ respond: respondApple,
168
+ // No `redact`: the inbox's generic rules already drop `appAccountToken`.
169
+ async verifyPurchase(proof) {
170
+ if (proof.checkoutRef !== undefined && !normalizeOptions.checkoutPattern.test(proof.checkoutRef)) {
171
+ throw new ProviderConfigError('apple_invalid_checkout_id', 'checkoutRef does not match the adapter checkoutPattern');
172
+ }
173
+ const transaction = decodeTransaction(proof.signedTransaction);
174
+ const transactionId = boundedId(transaction['transactionId']);
175
+ const occurredAt = msDate(transaction['signedDate']) ?? msDate(transaction['purchaseDate']);
176
+ if (!transactionId || !occurredAt)
177
+ throw new VerifyError('malformed', 'Apple transaction lacks its id or dates');
178
+ const token = boundedId(transaction['appAccountToken']);
179
+ return {
180
+ provider: 'apple',
181
+ environment,
182
+ // The same id whoever posts it, so the app's retry is a duplicate; a
183
+ // proof that can end differently (another session, now revoked) is new.
184
+ eventId: proofEventId(`apple:txn:${transactionId}`, proof.checkoutRef, transaction['revocationDate'] !== undefined),
185
+ eventType: APPLE_TRANSACTION_EVENT,
186
+ occurredAt,
187
+ payload: { transaction, ...(proof.checkoutRef ? { checkoutRef: proof.checkoutRef } : {}) },
188
+ ...(token ? { subjectRef: token } : {}),
189
+ };
190
+ },
191
+ async reportConsumption(transactionId, info) {
192
+ const token = serverToken();
193
+ let response;
194
+ try {
195
+ response = await fetchImpl(`${SERVER_API_BASE[environment]}/inApps/v2/transactions/consumption/${encodeURIComponent(transactionId)}`, {
196
+ method: 'PUT',
197
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
198
+ body: JSON.stringify(info),
199
+ signal: AbortSignal.timeout(timeoutMs),
200
+ });
201
+ }
202
+ catch {
203
+ throw new AppleApiError('apple_unreachable', 'App Store Server API unreachable');
204
+ }
205
+ if (response.status !== 202 && response.status !== 200) {
206
+ throw new AppleApiError('apple_error', `App Store Server API answered ${response.status}`, response.status);
207
+ }
208
+ },
209
+ };
210
+ return adapter;
211
+ }
212
+ const json = (status, body) => ({
213
+ status,
214
+ headers: { 'content-type': 'application/json' },
215
+ body: JSON.stringify(body),
216
+ });
217
+ /** Apple retries any non-2xx for days; acknowledge everything a retry cannot change. */
218
+ export function respondApple(outcome) {
219
+ if (outcome.relay)
220
+ return outcome.relay;
221
+ switch (outcome.status) {
222
+ case 'unauthorized':
223
+ return json(401, { error: 'Unauthorized' });
224
+ case 'malformed':
225
+ return json(400, { error: 'Invalid payload' });
226
+ case 'failed':
227
+ return json(500, { error: 'Internal error' });
228
+ default:
229
+ return json(200, { received: true, outcome: outcome.status, ...(outcome.reason ? { reason: outcome.reason } : {}) });
230
+ }
231
+ }
@@ -0,0 +1,50 @@
1
+ import { X509Certificate } from 'node:crypto';
2
+ /**
3
+ * Apple signed payloads (ported from Lohi `lib/apple-iap.ts`, hardened).
4
+ * Everything Apple sends about a purchase — an App Store Server Notification
5
+ * V2, the transaction and renewal info inside it, a StoreKit 2 transaction
6
+ * posted by the app — is a compact JWS whose `x5c` header carries the chain
7
+ * leaf → Apple WWDR intermediate → Apple Root CA G3. The payload is the
8
+ * attacker-controlled part; the signature, chained to the pinned root, is the
9
+ * only thing that makes it evidence. Verifying one means all of:
10
+ *
11
+ * 1. `alg` is ES256 — nothing else Apple signs, and never `none` or an HMAC;
12
+ * 2. every certificate is inside its validity window;
13
+ * 3. each certificate verifies under the next one's key, and the last one is
14
+ * the pinned root byte for byte or is signed by it — the system trust
15
+ * store is never consulted, since it trusts any CA the host does;
16
+ * 4. the leaf carries Apple's receipt-signing marker OID and the intermediate
17
+ * the WWDR marker, so another certificate Apple issued under the same root
18
+ * (a developer's, a web server's) cannot sign a purchase;
19
+ * 5. the signature verifies under the leaf's key.
20
+ */
21
+ /**
22
+ * Apple Root CA G3, pinned, from <https://www.apple.com/certificateauthority/>
23
+ * (expires 2039-04-30). Its SHA-256 fingerprint is checked against
24
+ * `APPLE_ROOT_CA_G3_SHA256` when the adapter is built, so an edit to either
25
+ * fails closed.
26
+ */
27
+ export declare const APPLE_ROOT_CA_G3_PEM = "-----BEGIN CERTIFICATE-----\nMIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwS\nQXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9u\nIEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcN\nMTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBS\nb290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9y\naXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49\nAgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtf\nTjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517\nIDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySr\nMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gA\nMGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4\nat+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM\n6BgD56KyKA==\n-----END CERTIFICATE-----";
28
+ /** SHA-256 of Apple Root CA G3's DER, as Apple publishes it (lower-case hex, no separators). */
29
+ export declare const APPLE_ROOT_CA_G3_SHA256 = "63343abfb89a6a03ebb57e9b3f5fa7be7c4f5c756f3017b3a8c488c3653e9179";
30
+ /** Marker on the leaf that signs App Store receipts and notifications. */
31
+ export declare const APPLE_RECEIPT_SIGNING_OID = "1.2.840.113635.100.6.11.1";
32
+ /** Marker on the Apple Worldwide Developer Relations intermediate. */
33
+ export declare const APPLE_WWDR_INTERMEDIATE_OID = "1.2.840.113635.100.6.2.1";
34
+ /** The pinned root, refusing to load when its bytes no longer match the published fingerprint. */
35
+ export declare function pinnedAppleRoot(): X509Certificate;
36
+ /** The extension OIDs of an X.509 certificate (`tbsCertificate [3] extensions`). */
37
+ export declare function extensionOids(der: Buffer): string[];
38
+ export interface AppleJwsOptions {
39
+ /** Trusted roots. Production passes only the pinned Apple Root CA G3. */
40
+ roots: readonly X509Certificate[];
41
+ /** Validity instant for the chain. */
42
+ at: Date;
43
+ }
44
+ /**
45
+ * Verify one Apple JWS and return its decoded payload. Throws
46
+ * `VerifyError('malformed')` for something that is not a JWS at all and
47
+ * `VerifyError('unauthorized')` for every failed proof; messages name the
48
+ * failed check, never the payload.
49
+ */
50
+ export declare function verifyAppleJws(jws: unknown, options: AppleJwsOptions): Record<string, unknown>;