@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,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
+ };
@@ -0,0 +1,226 @@
1
+ import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
2
+ import { ProviderConfigError, VerifyError } from '../port.js';
3
+ /**
4
+ * Google transport, no SDK (ported from Lohi `lib/google-play-iap.ts`):
5
+ * - Pub/Sub push authenticity: the OIDC JWT Pub/Sub attaches, verified
6
+ * against Google's published keys (cached by their max-age);
7
+ * - the Play Developer API with a service-account token minted by the
8
+ * JWT-bearer grant and cached until shortly before it expires.
9
+ * Errors carry a code and status, never a token or a response body.
10
+ */
11
+ export const GOOGLE_CERTS_URL = 'https://www.googleapis.com/oauth2/v3/certs';
12
+ export const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
13
+ export const ANDROIDPUBLISHER_SCOPE = 'https://www.googleapis.com/auth/androidpublisher';
14
+ const PLAY_API = 'https://androidpublisher.googleapis.com/androidpublisher/v3';
15
+ const ISSUERS = new Set(['accounts.google.com', 'https://accounts.google.com']);
16
+ /** Clock skew tolerated on `iat` / `exp`. */
17
+ const SKEW_MS = 60_000;
18
+ /** An unknown `kid` refetches the keys, at most this often. */
19
+ const REFETCH_MS = 60_000;
20
+ const DEFAULT_CERTS_TTL_MS = 3_600_000;
21
+ const MAX_JWT = 8 * 1024;
22
+ /** A Google API call failed: transient for the inbox (5xx, redelivered). */
23
+ export class GooglePlayApiError extends Error {
24
+ name = 'GooglePlayApiError';
25
+ code;
26
+ status;
27
+ constructor(code, message, status = null) {
28
+ super(message);
29
+ this.code = code;
30
+ this.status = status;
31
+ }
32
+ }
33
+ async function call(t, url, init = {}) {
34
+ try {
35
+ return await t.fetch(url, { ...init, signal: AbortSignal.timeout(t.timeoutMs) });
36
+ }
37
+ catch {
38
+ throw new GooglePlayApiError('google_unreachable', 'Google API unreachable');
39
+ }
40
+ }
41
+ async function jsonOf(response) {
42
+ let parsed;
43
+ try {
44
+ parsed = await response.json();
45
+ }
46
+ catch {
47
+ throw new GooglePlayApiError('google_bad_response', 'Google API answered non-JSON', response.status);
48
+ }
49
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
50
+ throw new GooglePlayApiError('google_bad_response', 'Google API answered an unexpected body', response.status);
51
+ }
52
+ return parsed;
53
+ }
54
+ const b64json = (segment) => {
55
+ if (!/^[A-Za-z0-9_-]+$/.test(segment))
56
+ throw new Error('not base64url');
57
+ const value = JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
58
+ if (!value || typeof value !== 'object' || Array.isArray(value))
59
+ throw new Error('not an object');
60
+ return value;
61
+ };
62
+ /** Google's signing keys by `kid`, refreshed by max-age and on an unknown `kid`. */
63
+ export function createGoogleKeyCache(t) {
64
+ let keys = new Map();
65
+ let expiresAt = 0;
66
+ let fetchedAt = -Infinity;
67
+ let pending = null;
68
+ async function refresh() {
69
+ // Stamped before the fetch, so an outage throttles unknown-kid refetches too.
70
+ fetchedAt = t.clock().getTime();
71
+ const response = await call(t, GOOGLE_CERTS_URL);
72
+ if (!response.ok)
73
+ throw new GooglePlayApiError('google_error', `Google certs answered ${response.status}`, response.status);
74
+ const body = await jsonOf(response);
75
+ const next = new Map();
76
+ for (const jwk of Array.isArray(body['keys']) ? body['keys'] : []) {
77
+ const k = jwk;
78
+ if (k['kty'] !== 'RSA' || typeof k['kid'] !== 'string')
79
+ continue;
80
+ try {
81
+ next.set(k['kid'], createPublicKey({ key: { kty: 'RSA', n: k['n'], e: k['e'] }, format: 'jwk' }));
82
+ }
83
+ catch {
84
+ // An unreadable key signs nothing we accept.
85
+ }
86
+ }
87
+ if (next.size === 0)
88
+ throw new GooglePlayApiError('google_bad_response', 'Google certs held no RSA key', response.status);
89
+ const maxAge = /max-age=(\d+)/.exec(response.headers.get('cache-control') ?? '');
90
+ keys = next;
91
+ expiresAt = t.clock().getTime() + (maxAge ? Number(maxAge[1]) * 1000 : DEFAULT_CERTS_TTL_MS);
92
+ }
93
+ return async function keyFor(kid) {
94
+ const now = t.clock().getTime();
95
+ if (now >= expiresAt || (!keys.has(kid) && now - fetchedAt >= REFETCH_MS)) {
96
+ // A burst of pushes shares one fetch.
97
+ pending ??= refresh().finally(() => {
98
+ pending = null;
99
+ });
100
+ await pending;
101
+ }
102
+ else if (pending) {
103
+ await pending;
104
+ }
105
+ return keys.get(kid) ?? null;
106
+ };
107
+ }
108
+ const refuse = (message) => new VerifyError('unauthorized', message);
109
+ /**
110
+ * Prove a Pub/Sub push came from our push subscription: an RS256 JWT signed
111
+ * by Google, issued by `accounts.google.com`, for our audience, as our
112
+ * service account, within its lifetime. A key fetch failure is not a
113
+ * refusal: it throws `GooglePlayApiError` so the delivery is retried.
114
+ */
115
+ export async function verifyPubSubToken(authorization, auth, keyFor, now) {
116
+ const match = /^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(authorization ?? '');
117
+ if (!match || match[1].length > MAX_JWT)
118
+ throw refuse('Pub/Sub push carries no bearer token');
119
+ const [h, p, s] = match[1].split('.');
120
+ let header;
121
+ let claims;
122
+ try {
123
+ header = b64json(h);
124
+ claims = b64json(p);
125
+ }
126
+ catch {
127
+ throw refuse('Pub/Sub token does not decode');
128
+ }
129
+ if (header['alg'] !== 'RS256' || typeof header['kid'] !== 'string')
130
+ throw refuse('Pub/Sub token alg is not RS256');
131
+ const key = await keyFor(header['kid']);
132
+ if (!key)
133
+ throw refuse('Pub/Sub token signed by an unknown key');
134
+ let valid = false;
135
+ try {
136
+ valid = verify('sha256', Buffer.from(`${h}.${p}`), key, Buffer.from(s, 'base64url'));
137
+ }
138
+ catch {
139
+ valid = false;
140
+ }
141
+ if (!valid)
142
+ throw refuse('Pub/Sub token signature does not verify');
143
+ if (!ISSUERS.has(claims['iss']))
144
+ throw refuse('Pub/Sub token issuer is not Google');
145
+ if (claims['aud'] !== auth.audience)
146
+ throw refuse('Pub/Sub token is for another audience');
147
+ if (claims['email'] !== auth.serviceAccountEmail || claims['email_verified'] !== true)
148
+ throw refuse('Pub/Sub token is for another service account');
149
+ const at = now.getTime();
150
+ if (typeof claims['exp'] !== 'number' || claims['exp'] * 1000 + SKEW_MS < at)
151
+ throw refuse('Pub/Sub token expired');
152
+ if (typeof claims['iat'] !== 'number' || claims['iat'] * 1000 - SKEW_MS > at)
153
+ throw refuse('Pub/Sub token issued in the future');
154
+ }
155
+ export function createPlayApi(t, packageName, account) {
156
+ let cached = null;
157
+ let pending = null;
158
+ let key = null;
159
+ async function accessToken() {
160
+ if (cached && t.clock().getTime() < cached.until)
161
+ return cached.token;
162
+ // Concurrent lookups share one exchange.
163
+ pending ??= exchange().finally(() => {
164
+ pending = null;
165
+ });
166
+ return pending;
167
+ }
168
+ async function exchange() {
169
+ const now = t.clock().getTime();
170
+ try {
171
+ key ??= createPrivateKey(account.privateKey);
172
+ }
173
+ catch {
174
+ throw new ProviderConfigError('google_invalid_key', 'service-account private key does not load');
175
+ }
176
+ const iat = Math.floor(now / 1000);
177
+ const enc = (v) => Buffer.from(JSON.stringify(v)).toString('base64url');
178
+ const input = `${enc({ alg: 'RS256', typ: 'JWT' })}.${enc({ iss: account.clientEmail, scope: ANDROIDPUBLISHER_SCOPE, aud: GOOGLE_TOKEN_URL, iat, exp: iat + 3600 })}`;
179
+ const assertion = `${input}.${sign('sha256', Buffer.from(input), key).toString('base64url')}`;
180
+ const response = await call(t, GOOGLE_TOKEN_URL, {
181
+ method: 'POST',
182
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
183
+ body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString(),
184
+ });
185
+ if (!response.ok)
186
+ throw new GooglePlayApiError('google_auth_failed', `Google token exchange answered ${response.status}`, response.status);
187
+ const body = await jsonOf(response);
188
+ const token = body['access_token'];
189
+ if (typeof token !== 'string' || token.length === 0)
190
+ throw new GooglePlayApiError('google_auth_failed', 'Google token exchange returned no access token', response.status);
191
+ const ttl = typeof body['expires_in'] === 'number' ? body['expires_in'] * 1000 : 3_600_000;
192
+ cached = { token, until: now + Math.max(0, ttl - 60_000) };
193
+ return token;
194
+ }
195
+ async function get(path) {
196
+ const token = await accessToken();
197
+ return call(t, `${PLAY_API}/applications/${encodeURIComponent(packageName)}${path}`, { headers: { Authorization: `Bearer ${token}` } });
198
+ }
199
+ return {
200
+ /** `purchases.products.get`; `null` when Play has no such purchase (unknown, foreign or expired token). */
201
+ async getProductPurchase(productId, purchaseToken) {
202
+ const response = await get(`/purchases/products/${encodeURIComponent(productId)}/tokens/${encodeURIComponent(purchaseToken)}`);
203
+ if (response.status === 404 || response.status === 410)
204
+ return null;
205
+ if (!response.ok)
206
+ throw new GooglePlayApiError('google_error', `Play API answered ${response.status}`, response.status);
207
+ const body = await jsonOf(response);
208
+ if (typeof body['purchaseState'] !== 'number')
209
+ throw new GooglePlayApiError('google_bad_response', 'Play purchase lacks a purchaseState', response.status);
210
+ return body;
211
+ },
212
+ /** `purchases.voidedpurchases.list` for one-time products. */
213
+ async listVoided(input) {
214
+ const query = new URLSearchParams({ startTime: String(input.startTime), maxResults: String(input.maxResults), type: '0' });
215
+ if (input.pageToken)
216
+ query.set('token', input.pageToken);
217
+ const response = await get(`/purchases/voidedpurchases?${query.toString()}`);
218
+ if (!response.ok)
219
+ throw new GooglePlayApiError('google_error', `Play API answered ${response.status}`, response.status);
220
+ const body = await jsonOf(response);
221
+ const voided = Array.isArray(body['voidedPurchases']) ? body['voidedPurchases'].filter((v) => !!v && typeof v === 'object') : [];
222
+ const page = body['tokenPagination']?.['nextPageToken'];
223
+ return { voided, nextPageToken: typeof page === 'string' && page.length > 0 ? page : null };
224
+ },
225
+ };
226
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Google Play event → normalized events, the pure half of the adapter.
3
+ * Deterministic over the stored (redacted) payload, the delivery's
4
+ * environment and the adapter's product map, so a replay normalizes like the
5
+ * first run.
6
+ *
7
+ * - One-time products are purchases keyed by Play's `orderId`. A purchase is
8
+ * only ever trusted as Play's own `purchases.products.get` answer, which
9
+ * `verify` / `verifyPurchase` fetched and stored; the notification merely
10
+ * says where to look.
11
+ * - `voidedPurchaseNotification`s and `voidedpurchases.list` entries reverse
12
+ * a purchase; both name it by `orderId`, so either credits back once.
13
+ * Play never reinstates a voided purchase.
14
+ * - Subscriptions are out of scope for this adapter: their notifications are
15
+ * acknowledged as ignored.
16
+ * - A purchase names our checkout session either through the host's client
17
+ * proof or because its `obfuscatedExternalAccountId` is a session id
18
+ * (`checkoutPattern`); the library credits checkout-bound purchases only.
19
+ * The product id is the price authority (amount = product amount × quantity).
20
+ */
21
+ import type { Money } from '../../domain/types.js';
22
+ import type { NormalizedEvent, ProviderEnvironment } from '../port.js';
23
+ /** What a Play product id means to this host. */
24
+ export interface GoogleProduct {
25
+ /** Catalog productRef (a pack). */
26
+ productRef: string;
27
+ /** What one unit costs in the catalog. */
28
+ amount: Money;
29
+ }
30
+ export interface GoogleNormalizeOptions {
31
+ products: Readonly<Record<string, GoogleProduct>>;
32
+ checkoutPattern: RegExp;
33
+ }
34
+ /** Event type of a Real-time Developer Notification delivered by Pub/Sub. */
35
+ export declare const GOOGLE_RTDN_EVENT = "RTDN";
36
+ /** Event type of a client-posted purchase the adapter looked up itself. */
37
+ export declare const GOOGLE_PURCHASE_EVENT = "PURCHASE";
38
+ /** Event type of a `voidedpurchases.list` entry. */
39
+ export declare const GOOGLE_VOIDED_EVENT = "VOIDED_PURCHASE";
40
+ /** `oneTimeProductNotification.notificationType`. */
41
+ export declare const ONE_TIME_PRODUCT_PURCHASED = 1;
42
+ export declare const ONE_TIME_PRODUCT_CANCELED = 2;
43
+ export declare const rec: (value: unknown) => Record<string, unknown> | null;
44
+ /** Google timestamps are epoch milliseconds, as numbers or decimal strings. */
45
+ export declare function millisDate(value: unknown): Date | null;
46
+ export declare function normalizeGoogleEvent(eventType: string, payload: unknown, occurredAt: Date, environment: ProviderEnvironment, options: GoogleNormalizeOptions): NormalizedEvent;
@@ -0,0 +1,135 @@
1
+ /** Event type of a Real-time Developer Notification delivered by Pub/Sub. */
2
+ export const GOOGLE_RTDN_EVENT = 'RTDN';
3
+ /** Event type of a client-posted purchase the adapter looked up itself. */
4
+ export const GOOGLE_PURCHASE_EVENT = 'PURCHASE';
5
+ /** Event type of a `voidedpurchases.list` entry. */
6
+ export const GOOGLE_VOIDED_EVENT = 'VOIDED_PURCHASE';
7
+ /** `oneTimeProductNotification.notificationType`. */
8
+ export const ONE_TIME_PRODUCT_PURCHASED = 1;
9
+ export const ONE_TIME_PRODUCT_CANCELED = 2;
10
+ const PURCHASED = 0;
11
+ const CANCELED = 1;
12
+ const PENDING = 2;
13
+ /** `purchaseType` of a license tester's purchase: no money moved. */
14
+ const TEST_PURCHASE = 0;
15
+ /** `productType` / `refundType` of a voided purchase. */
16
+ const VOIDED_ONE_TIME = 2;
17
+ const FULL_REFUND = 1;
18
+ /** `voidedReason` Chargeback. */
19
+ const CHARGEBACK = 7;
20
+ export const rec = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
21
+ const str = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
22
+ const own = (map, key) => (key !== null && Object.hasOwn(map, key) ? map[key] : undefined);
23
+ /** Google timestamps are epoch milliseconds, as numbers or decimal strings. */
24
+ export function millisDate(value) {
25
+ const n = typeof value === 'string' && /^\d{1,16}$/.test(value) ? Number(value) : value;
26
+ if (typeof n !== 'number' || !Number.isSafeInteger(n) || n <= 0)
27
+ return null;
28
+ return new Date(n);
29
+ }
30
+ function bindingOf(purchase, hostCheckoutRef, options) {
31
+ const obfuscated = str(purchase['obfuscatedExternalAccountId']);
32
+ const checkoutRef = hostCheckoutRef ?? (obfuscated && options.checkoutPattern.test(obfuscated) ? obfuscated : null);
33
+ const account = obfuscated
34
+ ? { kind: 'google_obfuscated_account', value: obfuscated }
35
+ : checkoutRef
36
+ ? { kind: 'checkout', value: checkoutRef }
37
+ : null;
38
+ return { account, checkoutRef };
39
+ }
40
+ /** A stored `products.get` answer (or the client proof's) → the purchase it describes. */
41
+ function fromPurchase(purchase, productId, hostCheckoutRef, occurredAt, proof, environment, options) {
42
+ if (!purchase)
43
+ return { kind: 'needs_review', reason: 'purchase_lookup_missing' };
44
+ if (purchase['notFound'] === true)
45
+ return { kind: 'needs_review', reason: 'purchase_not_found', detail: { productId } };
46
+ if (environment === 'production' && purchase['purchaseType'] === TEST_PURCHASE)
47
+ return { kind: 'ignored', reason: 'test_purchase' };
48
+ const state = purchase['purchaseState'];
49
+ if (state === PENDING)
50
+ return { kind: 'ignored', reason: 'purchase_pending' };
51
+ const orderId = str(purchase['orderId']);
52
+ const binding = bindingOf(purchase, hostCheckoutRef, options);
53
+ if (state === CANCELED) {
54
+ if (!orderId)
55
+ return { kind: 'ignored', reason: 'purchase_canceled' };
56
+ return { kind: 'purchase.reversed', externalId: orderId, reason: 'void', ...(binding.checkoutRef ? { checkoutRef: binding.checkoutRef } : {}), occurredAt };
57
+ }
58
+ if (state !== PURCHASED)
59
+ return { kind: 'needs_review', reason: 'unknown_purchase_state', detail: { purchaseState: state ?? null } };
60
+ if (!orderId)
61
+ return { kind: 'needs_review', reason: 'missing_order_id' };
62
+ // A notification that names no checkout of ours is settled by the host's
63
+ // client proof; parking every such purchase for a human would only be noise.
64
+ if (!proof && !binding.checkoutRef)
65
+ return { kind: 'ignored', reason: 'unbound_purchase' };
66
+ if (!binding.account)
67
+ return { kind: 'needs_review', reason: 'unbound_purchase' };
68
+ // The price follows the product id the caller named; Play's answer must agree.
69
+ const answered = str(purchase['productId']);
70
+ if (answered && answered !== productId)
71
+ return { kind: 'needs_review', reason: 'product_mismatch', detail: { productId, answered } };
72
+ const product = own(options.products, productId);
73
+ if (!product)
74
+ return { kind: 'needs_review', reason: 'unknown_product', detail: { productId } };
75
+ const quantity = purchase['quantity'] === undefined ? 1 : purchase['quantity'];
76
+ const total = typeof quantity === 'number' ? product.amount.amountMinor * quantity : NaN;
77
+ if (!Number.isSafeInteger(quantity) || quantity < 1 || !Number.isSafeInteger(total)) {
78
+ return { kind: 'needs_review', reason: 'invalid_quantity', detail: { quantity: quantity ?? null } };
79
+ }
80
+ return {
81
+ kind: 'purchase.completed',
82
+ account: binding.account,
83
+ externalId: orderId,
84
+ productRef: product.productRef,
85
+ quantity: quantity,
86
+ amount: { currency: product.amount.currency, amountMinor: total },
87
+ ...(binding.checkoutRef ? { checkoutRef: binding.checkoutRef } : {}),
88
+ occurredAt,
89
+ };
90
+ }
91
+ function voided(entry, occurredAt, reason) {
92
+ if (entry['productType'] !== undefined && entry['productType'] !== VOIDED_ONE_TIME)
93
+ return { kind: 'ignored', reason: 'subscription_unsupported' };
94
+ const orderId = str(entry['orderId']);
95
+ if (!orderId)
96
+ return { kind: 'needs_review', reason: 'missing_order_id' };
97
+ if (entry['refundType'] !== undefined && entry['refundType'] !== FULL_REFUND) {
98
+ return { kind: 'needs_review', reason: 'partial_refund', detail: { orderId, refundType: entry['refundType'] ?? null } };
99
+ }
100
+ return { kind: 'purchase.reversed', externalId: orderId, reason, occurredAt };
101
+ }
102
+ export function normalizeGoogleEvent(eventType, payload, occurredAt, environment, options) {
103
+ const body = rec(payload) ?? {};
104
+ if (eventType === GOOGLE_PURCHASE_EVENT) {
105
+ return fromPurchase(rec(body['purchase']), str(body['productId']), str(body['checkoutRef']), occurredAt, true, environment, options);
106
+ }
107
+ if (eventType === GOOGLE_VOIDED_EVENT) {
108
+ const entry = rec(body['voided']) ?? {};
109
+ // The list only returns one-time voids when asked with `type=0`.
110
+ return voided({ ...entry, productType: entry['productType'] ?? VOIDED_ONE_TIME }, occurredAt, entry['voidedReason'] === CHARGEBACK ? 'chargeback' : 'void');
111
+ }
112
+ if (eventType !== GOOGLE_RTDN_EVENT)
113
+ return { kind: 'ignored', reason: `unhandled_event:${eventType}` };
114
+ const oneTime = rec(body['oneTimeProductNotification']);
115
+ if (oneTime) {
116
+ const type = oneTime['notificationType'];
117
+ if (type === ONE_TIME_PRODUCT_CANCELED)
118
+ return { kind: 'ignored', reason: 'purchase_canceled' };
119
+ if (type !== ONE_TIME_PRODUCT_PURCHASED)
120
+ return { kind: 'ignored', reason: `unhandled_one_time_type:${String(type)}` };
121
+ return fromPurchase(rec(body['purchase']), str(oneTime['sku']), null, occurredAt, false, environment, options);
122
+ }
123
+ const voidedNotification = rec(body['voidedPurchaseNotification']);
124
+ if (voidedNotification) {
125
+ // RTDN voids carry the product type as a required field.
126
+ if (voidedNotification['productType'] !== VOIDED_ONE_TIME)
127
+ return { kind: 'ignored', reason: 'subscription_unsupported' };
128
+ return voided(voidedNotification, occurredAt, 'void');
129
+ }
130
+ if (rec(body['subscriptionNotification']))
131
+ return { kind: 'ignored', reason: 'subscription_unsupported' };
132
+ if (rec(body['testNotification']))
133
+ return { kind: 'ignored', reason: 'test_notification' };
134
+ return { kind: 'ignored', reason: 'unhandled_notification' };
135
+ }