@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,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
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier, type Reconcilable } from '../port.js';
|
|
2
|
+
import { type PubSubAuth, type ServiceAccount } from './api.js';
|
|
3
|
+
import { type GoogleProduct } from './events.js';
|
|
4
|
+
export { GooglePlayApiError, type PubSubAuth, type ServiceAccount } from './api.js';
|
|
5
|
+
export { GOOGLE_PURCHASE_EVENT, GOOGLE_RTDN_EVENT, GOOGLE_VOIDED_EVENT, type GoogleProduct } from './events.js';
|
|
6
|
+
export interface GoogleAdapterOptions {
|
|
7
|
+
/** Required. `production` ignores license testers' purchases; `sandbox` credits them. */
|
|
8
|
+
environment: ProviderEnvironment;
|
|
9
|
+
/** This app's package name: a notification for any other package is refused. */
|
|
10
|
+
packageName: string;
|
|
11
|
+
/** Play product id → what it means here. */
|
|
12
|
+
products: Readonly<Record<string, GoogleProduct>>;
|
|
13
|
+
/** Who signs the Pub/Sub push: the subscription's audience and service account. */
|
|
14
|
+
pubsub: PubSubAuth;
|
|
15
|
+
/** Service account with Play Console access, for the Play Developer API. */
|
|
16
|
+
serviceAccount: ServiceAccount;
|
|
17
|
+
/** Our checkout session ids as carried in `obfuscatedExternalAccountId`. Default: UUID. */
|
|
18
|
+
checkoutPattern?: RegExp;
|
|
19
|
+
/** Wall clock for token lifetimes and the reconcile window. Default `new Date()`. */
|
|
20
|
+
clock?: () => Date;
|
|
21
|
+
fetch?: typeof fetch;
|
|
22
|
+
/** API timeout. Default 10 s. */
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
}
|
|
25
|
+
/** A purchase the app reports from Play Billing, bound to the host's checkout session. */
|
|
26
|
+
export interface GooglePurchaseProof {
|
|
27
|
+
productId: string;
|
|
28
|
+
purchaseToken: string;
|
|
29
|
+
/** The checkout session the host created for this purchase (server-priced). */
|
|
30
|
+
checkoutRef?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface GoogleAdapter extends ProviderAdapter, PurchaseVerifier<GooglePurchaseProof>, Reconcilable {
|
|
33
|
+
readonly id: 'google';
|
|
34
|
+
}
|
|
35
|
+
export declare function createGoogleAdapter(options: GoogleAdapterOptions): GoogleAdapter;
|
|
36
|
+
/** Pub/Sub redelivers any non-2xx with backoff; acknowledge everything a retry cannot change. */
|
|
37
|
+
export declare function respondGoogle(outcome: IngestOutcome): ProviderResponse;
|