-
Notifications
You must be signed in to change notification settings - Fork 7
feat(kilo-pass): add Google Play purchase verifier #5586
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+295
−0
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
21e05a1
feat(kilo-pass): add Google Play purchase verifier
iscekic 4957657
Merge branch 'android-iap-e895-s2' into android-iap-e895-s3
iscekic 27ca659
fix(kilo-pass): type Play verifier test mock
iscekic 4d253e8
fix(kilo-pass): correct Play verifier mock generic
iscekic cd690cd
fix(kilo-pass): reject non-finite Play timestamps
iscekic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
197 changes: 197 additions & 0 deletions
197
apps/web/src/lib/kilo-pass/google-play-verifier.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,197 @@ | ||
| import { describe, expect, it, jest } from '@jest/globals'; | ||
| import type { androidpublisher_v3 } from '@googleapis/androidpublisher'; | ||
|
|
||
| import { KiloPassCadence, KiloPassPaymentProvider, KiloPassTier } from './enums'; | ||
| import type * as GooglePlayVerifier from './google-play-verifier'; | ||
|
|
||
| const mockGetGooglePlaySubscriptionPurchase = jest.fn<(purchaseToken: string) => Promise<androidpublisher_v3.Schema$SubscriptionPurchaseV2>>(); | ||
|
|
||
| jest.mock('./google-play-sdk', () => ({ | ||
| getGooglePlaySubscriptionPurchase: mockGetGooglePlaySubscriptionPurchase, | ||
| })); | ||
|
|
||
| function loadVerifier(): typeof GooglePlayVerifier { | ||
| return jest.requireActual<typeof GooglePlayVerifier>('./google-play-verifier'); | ||
| } | ||
|
|
||
| function decoded( | ||
| overrides: Partial<GooglePlayVerifier.GooglePlayDecodedPurchase> = {} | ||
| ): GooglePlayVerifier.GooglePlayDecodedPurchase { | ||
| return { | ||
| purchaseToken: 'play-token-1', | ||
| productId: 'kilopass_tier19', | ||
| latestOrderId: 'GPA.1234', | ||
| startTimeMs: 1_777_626_000_000, | ||
| expiryTimeMs: 4_102_444_800_000, | ||
| obfuscatedExternalAccountId: '550e8400-e29b-41d4-a716-446655440000', | ||
| environment: 'Sandbox', | ||
| subscriptionState: 'SUBSCRIPTION_STATE_ACTIVE', | ||
| rawPayload: { purchaseToken: 'play-token-1' }, | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| function apiData( | ||
| overrides: Partial<androidpublisher_v3.Schema$SubscriptionPurchaseV2> = {} | ||
| ): androidpublisher_v3.Schema$SubscriptionPurchaseV2 { | ||
| return { | ||
| startTime: '2026-05-01T09:00:00.000Z', | ||
| subscriptionState: 'SUBSCRIPTION_STATE_ACTIVE', | ||
| externalAccountIdentifiers: { | ||
| obfuscatedExternalAccountId: '550e8400-e29b-41d4-a716-446655440000', | ||
| }, | ||
| lineItems: [ | ||
| { | ||
| productId: 'kilopass_tier19', | ||
| expiryTime: '2100-01-01T00:00:00.000Z', | ||
| latestSuccessfulOrderId: 'GPA.1234', | ||
| }, | ||
| ], | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| describe('mapGooglePlayKiloPassPurchase', () => { | ||
| it('maps a valid Play subscription purchase to a validated Kilo Pass purchase', () => { | ||
| const { mapGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| expect(mapGooglePlayKiloPassPurchase(decoded())).toMatchObject({ | ||
| paymentProvider: KiloPassPaymentProvider.GooglePlay, | ||
| productId: 'kilopass_tier19', | ||
| providerTransactionId: 'GPA.1234', | ||
| providerOriginalTransactionId: 'play-token-1', | ||
| providerSubscriptionId: 'play-token-1', | ||
| appAccountToken: '550e8400-e29b-41d4-a716-446655440000', | ||
| purchaseToken: 'play-token-1', | ||
| expiresAtIso: '2100-01-01T00:00:00.000Z', | ||
| environment: 'Sandbox', | ||
| tier: KiloPassTier.Tier19, | ||
| cadence: KiloPassCadence.Monthly, | ||
| }); | ||
| }); | ||
|
|
||
| it('rejects an empty latest order id', () => { | ||
| const { mapGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => mapGooglePlayKiloPassPurchase(decoded({ latestOrderId: '' }))).toThrow( | ||
| 'Google Play purchase payload missing required identifiers' | ||
| ); | ||
| }); | ||
|
|
||
| it('rejects a non-finite start time', () => { | ||
| const { mapGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => mapGooglePlayKiloPassPurchase(decoded({ startTimeMs: NaN }))).toThrow( | ||
| 'Google Play subscription purchase has invalid timestamps' | ||
| ); | ||
| }); | ||
|
|
||
| it('rejects a non-finite expiry time', () => { | ||
| const { mapGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => mapGooglePlayKiloPassPurchase(decoded({ expiryTimeMs: NaN }))).toThrow( | ||
| 'Google Play subscription purchase has invalid timestamps' | ||
| ); | ||
| }); | ||
|
|
||
| it('rejects expired subscriptions', () => { | ||
| const { mapGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => | ||
| mapGooglePlayKiloPassPurchase(decoded({ expiryTimeMs: Date.now() - 1_000 })) | ||
| ).toThrow('Google Play subscription purchase has expired'); | ||
| }); | ||
|
|
||
| it('rejects unknown products', () => { | ||
| const { mapGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => mapGooglePlayKiloPassPurchase(decoded({ productId: 'unknown' }))).toThrow( | ||
| 'Google Play Kilo Pass product is not enabled' | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('decodeGooglePlaySubscriptionPurchase', () => { | ||
| it('marks a test purchase as Sandbox', () => { | ||
| const { decodeGooglePlaySubscriptionPurchase } = loadVerifier(); | ||
|
|
||
| const result = decodeGooglePlaySubscriptionPurchase( | ||
| apiData({ testPurchase: {} }), | ||
| 'play-token-1' | ||
| ); | ||
|
|
||
| expect(result.environment).toBe('Sandbox'); | ||
| expect(result.purchaseToken).toBe('play-token-1'); | ||
| expect(result.productId).toBe('kilopass_tier19'); | ||
| expect(result.latestOrderId).toBe('GPA.1234'); | ||
| expect(result.startTimeMs).toBe(1_777_626_000_000); | ||
| expect(result.expiryTimeMs).toBe(4_102_444_800_000); | ||
| expect(result.obfuscatedExternalAccountId).toBe('550e8400-e29b-41d4-a716-446655440000'); | ||
| }); | ||
|
|
||
| it('marks a non-test purchase as Production', () => { | ||
| const { decodeGooglePlaySubscriptionPurchase } = loadVerifier(); | ||
|
|
||
| const result = decodeGooglePlaySubscriptionPurchase(apiData(), 'play-token-1'); | ||
|
|
||
| expect(result.environment).toBe('Production'); | ||
| }); | ||
|
|
||
| it('throws when lineItems is empty', () => { | ||
| const { decodeGooglePlaySubscriptionPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => | ||
| decodeGooglePlaySubscriptionPurchase(apiData({ lineItems: [] }), 'play-token-1') | ||
| ).toThrow('Google Play subscription purchase missing line items'); | ||
| }); | ||
|
|
||
| it('throws when lineItems is missing', () => { | ||
| const { decodeGooglePlaySubscriptionPurchase } = loadVerifier(); | ||
|
|
||
| expect(() => | ||
| decodeGooglePlaySubscriptionPurchase(apiData({ lineItems: undefined }), 'play-token-1') | ||
| ).toThrow('Google Play subscription purchase missing line items'); | ||
| }); | ||
|
|
||
| it('falls back to the top-level latest order id when the line item has none', () => { | ||
| const { decodeGooglePlaySubscriptionPurchase } = loadVerifier(); | ||
|
|
||
| const data = { | ||
| startTime: '2026-05-01T09:00:00.000Z', | ||
| subscriptionState: 'SUBSCRIPTION_STATE_ACTIVE', | ||
| lineItems: [ | ||
| { | ||
| productId: 'kilopass_tier19', | ||
| expiryTime: '2100-01-01T00:00:00.000Z', | ||
| }, | ||
| ], | ||
| latestOrderId: 'GPA.fallback', | ||
| } as androidpublisher_v3.Schema$SubscriptionPurchaseV2; | ||
|
|
||
| const result = decodeGooglePlaySubscriptionPurchase(data, 'play-token-1'); | ||
|
|
||
| expect(result.latestOrderId).toBe('GPA.fallback'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('verifyGooglePlayKiloPassPurchase', () => { | ||
| it('returns a validated purchase for the fixture payload', async () => { | ||
| const { verifyGooglePlayKiloPassPurchase } = loadVerifier(); | ||
|
|
||
| mockGetGooglePlaySubscriptionPurchase.mockResolvedValue(apiData({ testPurchase: {} })); | ||
|
|
||
| const result = await verifyGooglePlayKiloPassPurchase('play-token-1'); | ||
|
|
||
| expect(mockGetGooglePlaySubscriptionPurchase).toHaveBeenCalledWith('play-token-1'); | ||
| expect(result).toMatchObject({ | ||
| paymentProvider: KiloPassPaymentProvider.GooglePlay, | ||
| productId: 'kilopass_tier19', | ||
| providerTransactionId: 'GPA.1234', | ||
| providerSubscriptionId: 'play-token-1', | ||
| purchaseToken: 'play-token-1', | ||
| environment: 'Sandbox', | ||
| tier: KiloPassTier.Tier19, | ||
| cadence: KiloPassCadence.Monthly, | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import type { androidpublisher_v3 } from '@googleapis/androidpublisher'; | ||
|
|
||
| import type { ValidatedStoreKiloPassPurchase } from './store-subscription-completion'; | ||
| import { KiloPassPaymentProvider } from './enums'; | ||
| import { getMobileStoreKiloPassProductByGoogleProductId } from './mobile-store-products'; | ||
| import { getGooglePlaySubscriptionPurchase } from './google-play-sdk'; | ||
|
|
||
| export type GooglePlayEnvironment = 'Sandbox' | 'Production'; | ||
|
|
||
| export type GooglePlayDecodedPurchase = { | ||
| purchaseToken: string; | ||
| productId: string; | ||
| latestOrderId: string; | ||
| startTimeMs: number; | ||
| expiryTimeMs: number; | ||
| obfuscatedExternalAccountId?: string; | ||
| environment: GooglePlayEnvironment; | ||
| subscriptionState: string; | ||
| rawPayload: Record<string, unknown>; | ||
| }; | ||
|
|
||
| export function mapGooglePlayKiloPassPurchase( | ||
| decoded: GooglePlayDecodedPurchase | ||
| ): ValidatedStoreKiloPassPurchase { | ||
| if (!decoded.purchaseToken || !decoded.productId || !decoded.latestOrderId) { | ||
| throw new Error('Google Play purchase payload missing required identifiers'); | ||
| } | ||
| if (!Number.isFinite(decoded.startTimeMs) || !Number.isFinite(decoded.expiryTimeMs)) { | ||
| throw new Error('Google Play subscription purchase has invalid timestamps'); | ||
| } | ||
| // Called only from the tRPC purchase-completion path; renewals and refunds enter via | ||
| // the Play notifications handler, which intentionally allows expired purchases. | ||
| if (decoded.expiryTimeMs <= Date.now()) { | ||
| throw new Error('Google Play subscription purchase has expired'); | ||
| } | ||
|
|
||
| const product = getMobileStoreKiloPassProductByGoogleProductId(decoded.productId); | ||
| if (!product) { | ||
| throw new Error('Google Play Kilo Pass product is not enabled'); | ||
| } | ||
|
|
||
| return { | ||
| paymentProvider: KiloPassPaymentProvider.GooglePlay, | ||
| productId: decoded.productId, | ||
| providerTransactionId: decoded.latestOrderId, | ||
| providerOriginalTransactionId: decoded.purchaseToken, | ||
| providerSubscriptionId: decoded.purchaseToken, | ||
| appAccountToken: decoded.obfuscatedExternalAccountId ?? null, | ||
| purchaseToken: decoded.purchaseToken, | ||
| environment: decoded.environment, | ||
| purchasedAtIso: new Date(decoded.startTimeMs).toISOString(), | ||
| expiresAtIso: new Date(decoded.expiryTimeMs).toISOString(), | ||
| tier: product.tier, | ||
| cadence: product.cadence, | ||
| rawPayload: decoded.rawPayload, | ||
| }; | ||
| } | ||
|
|
||
| export function decodeGooglePlaySubscriptionPurchase( | ||
| apiData: androidpublisher_v3.Schema$SubscriptionPurchaseV2, | ||
| purchaseToken: string | ||
| ): GooglePlayDecodedPurchase { | ||
| const lineItems = apiData.lineItems ?? []; | ||
| if (lineItems.length === 0) { | ||
| throw new Error('Google Play subscription purchase missing line items'); | ||
| } | ||
| const lineItem = lineItems[0]; | ||
|
|
||
| const latestOrderId = | ||
| lineItem.latestSuccessfulOrderId ?? | ||
| (apiData as { latestOrderId?: string | null }).latestOrderId ?? | ||
| ''; | ||
| if (!latestOrderId) { | ||
| throw new Error('Google Play purchase payload missing required identifiers'); | ||
| } | ||
|
|
||
| return { | ||
| purchaseToken, | ||
| productId: lineItem.productId ?? '', | ||
| latestOrderId, | ||
| startTimeMs: Date.parse(apiData.startTime ?? ''), | ||
|
iscekic marked this conversation as resolved.
|
||
| expiryTimeMs: Date.parse(lineItem.expiryTime ?? ''), | ||
| obfuscatedExternalAccountId: | ||
| apiData.externalAccountIdentifiers?.obfuscatedExternalAccountId ?? undefined, | ||
| environment: apiData.testPurchase != null ? 'Sandbox' : 'Production', | ||
| subscriptionState: apiData.subscriptionState ?? '', | ||
| rawPayload: apiData as unknown as Record<string, unknown>, | ||
| }; | ||
| } | ||
|
|
||
| export async function verifyGooglePlayKiloPassPurchase( | ||
| purchaseToken: string | ||
| ): Promise<ValidatedStoreKiloPassPurchase> { | ||
| const apiData = await getGooglePlaySubscriptionPurchase(purchaseToken); | ||
| return mapGooglePlayKiloPassPurchase( | ||
| decodeGooglePlaySubscriptionPurchase(apiData, purchaseToken) | ||
| ); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
bot: Reject non-entitled Google subscription states before mapping the purchase.
Suggested fix: Validate
decoded.subscriptionStatebefore returning a purchase. Permit only states that Google considers entitled for this completion flow (for example, active and any explicitly supported canceled-but-unexpired state), and rejectON_HOLD,PAUSED, pending, expired, and unknown states. Add mapper tests for at least on-hold and paused fixtures. The current expiry-only gate allows those states while their expiry remains future-dated, and downstream completion persists accepted purchases asactive.