@tofound/billing 0.2.0 → 1.1.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.
- package/CHANGELOG.md +90 -1
- package/README.md +20 -5
- package/dist/hostkit/adjustments.d.ts +65 -0
- package/dist/hostkit/adjustments.js +84 -0
- package/dist/hostkit/index.d.ts +9 -0
- package/dist/hostkit/index.js +9 -0
- package/dist/hostkit/legacy-ledger.d.ts +87 -0
- package/dist/hostkit/legacy-ledger.js +111 -0
- package/dist/hostkit/quote-wire.d.ts +73 -0
- package/dist/hostkit/quote-wire.js +50 -0
- package/dist/inbox/apply.d.ts +47 -1
- package/dist/inbox/apply.js +32 -1
- package/dist/inbox/ingest.d.ts +33 -3
- package/dist/inbox/ingest.js +42 -5
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -0
- package/dist/providers/apple/events.d.ts +24 -0
- package/dist/providers/apple/events.js +232 -0
- package/dist/providers/apple/index.d.ts +54 -0
- package/dist/providers/apple/index.js +231 -0
- package/dist/providers/apple/jws.d.ts +50 -0
- package/dist/providers/apple/jws.js +206 -0
- package/dist/providers/google/api.d.ts +57 -0
- package/dist/providers/google/api.js +226 -0
- package/dist/providers/google/events.d.ts +46 -0
- package/dist/providers/google/events.js +135 -0
- package/dist/providers/google/index.d.ts +37 -0
- package/dist/providers/google/index.js +228 -0
- package/dist/providers/polar/index.d.ts +1 -1
- package/dist/providers/port.d.ts +2 -0
- package/dist/providers/sepay/index.js +29 -0
- package/docs/API.md +226 -9
- package/docs/GUIDE.md +254 -0
- package/docs/MIGRATION-LOHI.md +237 -0
- package/package.json +18 -1
|
@@ -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>;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHash, verify as verifySignature, X509Certificate } from 'node:crypto';
|
|
2
|
+
import { VerifyError } from '../port.js';
|
|
3
|
+
/**
|
|
4
|
+
* Apple signed payloads (ported from Lohi `lib/apple-iap.ts`, hardened).
|
|
5
|
+
* Everything Apple sends about a purchase — an App Store Server Notification
|
|
6
|
+
* V2, the transaction and renewal info inside it, a StoreKit 2 transaction
|
|
7
|
+
* posted by the app — is a compact JWS whose `x5c` header carries the chain
|
|
8
|
+
* leaf → Apple WWDR intermediate → Apple Root CA G3. The payload is the
|
|
9
|
+
* attacker-controlled part; the signature, chained to the pinned root, is the
|
|
10
|
+
* only thing that makes it evidence. Verifying one means all of:
|
|
11
|
+
*
|
|
12
|
+
* 1. `alg` is ES256 — nothing else Apple signs, and never `none` or an HMAC;
|
|
13
|
+
* 2. every certificate is inside its validity window;
|
|
14
|
+
* 3. each certificate verifies under the next one's key, and the last one is
|
|
15
|
+
* the pinned root byte for byte or is signed by it — the system trust
|
|
16
|
+
* store is never consulted, since it trusts any CA the host does;
|
|
17
|
+
* 4. the leaf carries Apple's receipt-signing marker OID and the intermediate
|
|
18
|
+
* the WWDR marker, so another certificate Apple issued under the same root
|
|
19
|
+
* (a developer's, a web server's) cannot sign a purchase;
|
|
20
|
+
* 5. the signature verifies under the leaf's key.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Apple Root CA G3, pinned, from <https://www.apple.com/certificateauthority/>
|
|
24
|
+
* (expires 2039-04-30). Its SHA-256 fingerprint is checked against
|
|
25
|
+
* `APPLE_ROOT_CA_G3_SHA256` when the adapter is built, so an edit to either
|
|
26
|
+
* fails closed.
|
|
27
|
+
*/
|
|
28
|
+
export const APPLE_ROOT_CA_G3_PEM = `-----BEGIN CERTIFICATE-----
|
|
29
|
+
MIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwS
|
|
30
|
+
QXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9u
|
|
31
|
+
IEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcN
|
|
32
|
+
MTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBS
|
|
33
|
+
b290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9y
|
|
34
|
+
aXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49
|
|
35
|
+
AgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtf
|
|
36
|
+
TjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517
|
|
37
|
+
IDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySr
|
|
38
|
+
MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gA
|
|
39
|
+
MGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4
|
|
40
|
+
at+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM
|
|
41
|
+
6BgD56KyKA==
|
|
42
|
+
-----END CERTIFICATE-----`;
|
|
43
|
+
/** SHA-256 of Apple Root CA G3's DER, as Apple publishes it (lower-case hex, no separators). */
|
|
44
|
+
export const APPLE_ROOT_CA_G3_SHA256 = '63343abfb89a6a03ebb57e9b3f5fa7be7c4f5c756f3017b3a8c488c3653e9179';
|
|
45
|
+
/** Marker on the leaf that signs App Store receipts and notifications. */
|
|
46
|
+
export const APPLE_RECEIPT_SIGNING_OID = '1.2.840.113635.100.6.11.1';
|
|
47
|
+
/** Marker on the Apple Worldwide Developer Relations intermediate. */
|
|
48
|
+
export const APPLE_WWDR_INTERMEDIATE_OID = '1.2.840.113635.100.6.2.1';
|
|
49
|
+
/** A JWS is a few KB; anything far past that is not Apple's. */
|
|
50
|
+
const MAX_JWS_LENGTH = 64 * 1024;
|
|
51
|
+
function sha256Hex(der) {
|
|
52
|
+
return createHash('sha256').update(der).digest('hex');
|
|
53
|
+
}
|
|
54
|
+
/** The pinned root, refusing to load when its bytes no longer match the published fingerprint. */
|
|
55
|
+
export function pinnedAppleRoot() {
|
|
56
|
+
const root = new X509Certificate(APPLE_ROOT_CA_G3_PEM);
|
|
57
|
+
if (sha256Hex(root.raw) !== APPLE_ROOT_CA_G3_SHA256)
|
|
58
|
+
throw new Error('Apple Root CA G3 does not match its pinned fingerprint');
|
|
59
|
+
return root;
|
|
60
|
+
}
|
|
61
|
+
function readTlv(der, offset, limit) {
|
|
62
|
+
if (offset + 2 > limit)
|
|
63
|
+
throw new Error('truncated DER');
|
|
64
|
+
const tag = der[offset];
|
|
65
|
+
let length = der[offset + 1];
|
|
66
|
+
let start = offset + 2;
|
|
67
|
+
if (length & 0x80) {
|
|
68
|
+
const bytes = length & 0x7f;
|
|
69
|
+
if (bytes === 0 || bytes > 4 || start + bytes > limit)
|
|
70
|
+
throw new Error('bad DER length');
|
|
71
|
+
length = 0;
|
|
72
|
+
for (let i = 0; i < bytes; i++)
|
|
73
|
+
length = length * 256 + der[start + i];
|
|
74
|
+
start += bytes;
|
|
75
|
+
}
|
|
76
|
+
const end = start + length;
|
|
77
|
+
if (end > limit)
|
|
78
|
+
throw new Error('truncated DER');
|
|
79
|
+
return { tag, start, end };
|
|
80
|
+
}
|
|
81
|
+
function children(der, parent) {
|
|
82
|
+
const out = [];
|
|
83
|
+
for (let offset = parent.start; offset < parent.end;) {
|
|
84
|
+
const child = readTlv(der, offset, parent.end);
|
|
85
|
+
out.push(child);
|
|
86
|
+
offset = child.end;
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
function decodeOid(bytes) {
|
|
91
|
+
const parts = [];
|
|
92
|
+
let value = 0;
|
|
93
|
+
for (const byte of bytes) {
|
|
94
|
+
value = value * 128 + (byte & 0x7f);
|
|
95
|
+
if (!(byte & 0x80)) {
|
|
96
|
+
parts.push(value);
|
|
97
|
+
value = 0;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const [first = 0, ...rest] = parts;
|
|
101
|
+
const head = first < 80 ? [Math.floor(first / 40), first % 40] : [2, first - 80];
|
|
102
|
+
return [...head, ...rest].join('.');
|
|
103
|
+
}
|
|
104
|
+
/** The extension OIDs of an X.509 certificate (`tbsCertificate [3] extensions`). */
|
|
105
|
+
export function extensionOids(der) {
|
|
106
|
+
const certificate = readTlv(der, 0, der.length);
|
|
107
|
+
const tbs = children(der, certificate)[0];
|
|
108
|
+
if (!tbs || tbs.tag !== 0x30)
|
|
109
|
+
throw new Error('not a certificate');
|
|
110
|
+
const explicit = children(der, tbs).find((t) => t.tag === 0xa3);
|
|
111
|
+
if (!explicit)
|
|
112
|
+
return [];
|
|
113
|
+
const list = children(der, explicit)[0];
|
|
114
|
+
if (!list)
|
|
115
|
+
return [];
|
|
116
|
+
return children(der, list).map((extension) => {
|
|
117
|
+
const id = children(der, extension)[0];
|
|
118
|
+
if (!id || id.tag !== 0x06)
|
|
119
|
+
throw new Error('bad extension');
|
|
120
|
+
return decodeOid(der.subarray(id.start, id.end));
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// Verification
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
function decodeSegment(segment) {
|
|
127
|
+
if (!/^[A-Za-z0-9_-]+$/.test(segment))
|
|
128
|
+
throw new Error('not base64url');
|
|
129
|
+
return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
|
|
130
|
+
}
|
|
131
|
+
const refuse = (message) => new VerifyError('unauthorized', message);
|
|
132
|
+
const inside = (cert, at) => new Date(cert.validFrom) <= at && at <= new Date(cert.validTo);
|
|
133
|
+
/**
|
|
134
|
+
* Verify one Apple JWS and return its decoded payload. Throws
|
|
135
|
+
* `VerifyError('malformed')` for something that is not a JWS at all and
|
|
136
|
+
* `VerifyError('unauthorized')` for every failed proof; messages name the
|
|
137
|
+
* failed check, never the payload.
|
|
138
|
+
*/
|
|
139
|
+
export function verifyAppleJws(jws, options) {
|
|
140
|
+
if (typeof jws !== 'string' || jws.length === 0 || jws.length > MAX_JWS_LENGTH)
|
|
141
|
+
throw new VerifyError('malformed', 'Apple JWS missing or oversized');
|
|
142
|
+
const parts = jws.split('.');
|
|
143
|
+
if (parts.length !== 3)
|
|
144
|
+
throw new VerifyError('malformed', 'Apple JWS is not compact JWS');
|
|
145
|
+
const [headerB64, payloadB64, signatureB64] = parts;
|
|
146
|
+
let header;
|
|
147
|
+
let payload;
|
|
148
|
+
try {
|
|
149
|
+
header = decodeSegment(headerB64);
|
|
150
|
+
payload = decodeSegment(payloadB64);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
throw new VerifyError('malformed', 'Apple JWS segments do not decode');
|
|
154
|
+
}
|
|
155
|
+
if (!header || typeof header !== 'object' || Array.isArray(header) || !payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
156
|
+
throw new VerifyError('malformed', 'Apple JWS header or payload is not an object');
|
|
157
|
+
}
|
|
158
|
+
if (header.alg !== 'ES256')
|
|
159
|
+
throw refuse('Apple JWS alg is not ES256');
|
|
160
|
+
// Leaf, intermediate, root: Apple always sends all three.
|
|
161
|
+
if (!Array.isArray(header.x5c) || header.x5c.length !== 3 || !header.x5c.every((c) => typeof c === 'string')) {
|
|
162
|
+
throw refuse('Apple JWS x5c chain must hold three certificates');
|
|
163
|
+
}
|
|
164
|
+
let chain;
|
|
165
|
+
try {
|
|
166
|
+
chain = header.x5c.map((der) => new X509Certificate(Buffer.from(der, 'base64')));
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
throw refuse('Apple JWS x5c certificate does not parse');
|
|
170
|
+
}
|
|
171
|
+
const [leaf, intermediate, last] = chain;
|
|
172
|
+
for (const cert of chain)
|
|
173
|
+
if (!inside(cert, options.at))
|
|
174
|
+
throw refuse('Apple JWS certificate outside its validity window');
|
|
175
|
+
if (!leaf.verify(intermediate.publicKey) || !intermediate.verify(last.publicKey))
|
|
176
|
+
throw refuse('Apple JWS chain does not link');
|
|
177
|
+
// A self-signed stranger in x5c[2] links too; only the pin decides.
|
|
178
|
+
const anchored = options.roots.some((root) => last.raw.equals(root.raw) || last.verify(root.publicKey));
|
|
179
|
+
if (!anchored)
|
|
180
|
+
throw refuse('Apple JWS chain is not anchored at the pinned root');
|
|
181
|
+
try {
|
|
182
|
+
if (!extensionOids(leaf.raw).includes(APPLE_RECEIPT_SIGNING_OID))
|
|
183
|
+
throw refuse('Apple JWS leaf lacks the receipt-signing marker');
|
|
184
|
+
if (!extensionOids(intermediate.raw).includes(APPLE_WWDR_INTERMEDIATE_OID))
|
|
185
|
+
throw refuse('Apple JWS intermediate lacks the WWDR marker');
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (error instanceof VerifyError)
|
|
189
|
+
throw error;
|
|
190
|
+
throw refuse('Apple JWS certificate extensions do not parse');
|
|
191
|
+
}
|
|
192
|
+
// ES256 signatures are the raw 64-byte r‖s (IEEE P1363), not DER.
|
|
193
|
+
const signature = Buffer.from(signatureB64, 'base64url');
|
|
194
|
+
let valid = false;
|
|
195
|
+
try {
|
|
196
|
+
valid =
|
|
197
|
+
signature.length === 64 &&
|
|
198
|
+
verifySignature('sha256', Buffer.from(`${headerB64}.${payloadB64}`), { key: leaf.publicKey, dsaEncoding: 'ieee-p1363' }, signature);
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
valid = false;
|
|
202
|
+
}
|
|
203
|
+
if (!valid)
|
|
204
|
+
throw refuse('Apple JWS signature does not verify');
|
|
205
|
+
return payload;
|
|
206
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Google transport, no SDK (ported from Lohi `lib/google-play-iap.ts`):
|
|
4
|
+
* - Pub/Sub push authenticity: the OIDC JWT Pub/Sub attaches, verified
|
|
5
|
+
* against Google's published keys (cached by their max-age);
|
|
6
|
+
* - the Play Developer API with a service-account token minted by the
|
|
7
|
+
* JWT-bearer grant and cached until shortly before it expires.
|
|
8
|
+
* Errors carry a code and status, never a token or a response body.
|
|
9
|
+
*/
|
|
10
|
+
export declare const GOOGLE_CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs";
|
|
11
|
+
export declare const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
12
|
+
export declare const ANDROIDPUBLISHER_SCOPE = "https://www.googleapis.com/auth/androidpublisher";
|
|
13
|
+
/** A Google API call failed: transient for the inbox (5xx, redelivered). */
|
|
14
|
+
export declare class GooglePlayApiError extends Error {
|
|
15
|
+
readonly name = "GooglePlayApiError";
|
|
16
|
+
readonly code: 'google_unreachable' | 'google_error' | 'google_bad_response' | 'google_auth_failed' | 'google_not_found';
|
|
17
|
+
readonly status: number | null;
|
|
18
|
+
constructor(code: GooglePlayApiError['code'], message: string, status?: number | null);
|
|
19
|
+
}
|
|
20
|
+
export interface Transport {
|
|
21
|
+
fetch: typeof fetch;
|
|
22
|
+
timeoutMs: number;
|
|
23
|
+
clock: () => Date;
|
|
24
|
+
}
|
|
25
|
+
export interface PubSubAuth {
|
|
26
|
+
/** The `aud` the push subscription was created with — normally the endpoint URL. */
|
|
27
|
+
audience: string;
|
|
28
|
+
/** The service account the push subscription signs as. */
|
|
29
|
+
serviceAccountEmail: string;
|
|
30
|
+
}
|
|
31
|
+
/** Google's signing keys by `kid`, refreshed by max-age and on an unknown `kid`. */
|
|
32
|
+
export declare function createGoogleKeyCache(t: Transport): (kid: string) => Promise<KeyObject | null>;
|
|
33
|
+
/**
|
|
34
|
+
* Prove a Pub/Sub push came from our push subscription: an RS256 JWT signed
|
|
35
|
+
* by Google, issued by `accounts.google.com`, for our audience, as our
|
|
36
|
+
* service account, within its lifetime. A key fetch failure is not a
|
|
37
|
+
* refusal: it throws `GooglePlayApiError` so the delivery is retried.
|
|
38
|
+
*/
|
|
39
|
+
export declare function verifyPubSubToken(authorization: string | null, auth: PubSubAuth, keyFor: (kid: string) => Promise<KeyObject | null>, now: Date): Promise<void>;
|
|
40
|
+
export interface ServiceAccount {
|
|
41
|
+
clientEmail: string;
|
|
42
|
+
/** PEM private key from the service-account JSON. */
|
|
43
|
+
privateKey: string;
|
|
44
|
+
}
|
|
45
|
+
export declare function createPlayApi(t: Transport, packageName: string, account: ServiceAccount): {
|
|
46
|
+
/** `purchases.products.get`; `null` when Play has no such purchase (unknown, foreign or expired token). */
|
|
47
|
+
getProductPurchase(productId: string, purchaseToken: string): Promise<Record<string, unknown> | null>;
|
|
48
|
+
/** `purchases.voidedpurchases.list` for one-time products. */
|
|
49
|
+
listVoided(input: {
|
|
50
|
+
startTime: number;
|
|
51
|
+
pageToken?: string;
|
|
52
|
+
maxResults: number;
|
|
53
|
+
}): Promise<{
|
|
54
|
+
voided: Record<string, unknown>[];
|
|
55
|
+
nextPageToken: string | null;
|
|
56
|
+
}>;
|
|
57
|
+
};
|