Logo di Security

Security

Organizzazione
RevenueCat
security

Use this skill when hardening a Google Play Billing integration against fraud. Covers server side receipt verification, replay attack protection, device fingerprinting, velocity checks, and the most common billing fraud patterns.

Panoramica

AutoreRevenueCat
Repositoryplay-billing-skills
Nome della skillsecurity
Stelle
58
Fork
0
File inclusi
Solo istruzioni
LicenzaApache-2.0
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da RevenueCat su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Security in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/security
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/RevenueCat/play-billing-skills.git /tmp/play-billing-skills
mkdir -p .claude/skills
cp -r /tmp/play-billing-skills/google-play/security .claude/skills/security
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Security in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Security non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Security non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

Securing Google Play Billing

Anything running on the user device can be tampered with. If your trust model lives in the client, you have already lost. This skill shows you how to move trust to your backend and defend against the attack patterns you will actually see in production.

Phase 1: Assess

Before you write a line of defensive code, answer these questions about your current integration:

  • Where does purchase verification happen today? Client, backend, or both?
  • Does your database enforce a unique constraint on purchaseToken?
  • Do you set obfuscatedAccountId and obfuscatedProfileId on every purchase flow?
  • Do you poll the Voided Purchases API on a schedule?
  • Do any access decisions rely on System.currentTimeMillis() from the device?

Any "no" answer maps to a layer you are missing below.

Phase 2: Plan the Layered Defense

Fraud prevention is not a single check. It is a stack of controls where each layer catches a different attack class. Plan all of them, even if you ship them incrementally.

LayerPurposeWhere it runs
1. Backend receipt verificationConfirm the purchase exists in Google's recordsYour server, via purchases.products.get / purchases.subscriptionsv2.get
2. Response field validationCatch product swaps and cross app token reuseYour server (check productId and purchaseState; the package is bound by the request path)
3. Purchase state checkReject PENDING and expired purchasesYour server
4. Replay protectionBlock reuse of valid tokensUnique constraint on purchase token column; for subscriptions, once a new token is verified as purchased (not while it is SUBSCRIPTION_STATE_PENDING), revoke the entitlement on its linkedPurchaseToken
5. Token to user bindingDetect token sharing across accountsYour server (store and compare userId on duplicates)
6. AcknowledgementPrevent auto refund at 3 day markYour server, after entitlement grant
7. Voided purchase syncRevoke access on refunds and chargebacksvoidedPurchaseNotification RTDN in real time, plus a daily purchases.voidedpurchases.list backfill with type=1 (includes subscriptions; key by orderId) over the last 30 days
8. Device and profile signalsGive Google and yourself correlation dataClient sets obfuscatedAccountId / obfuscatedProfileId before launching the flow
9. Integrity and pinningRaise the cost of modified APKsPlay Integrity API plus TLS certificate pinning
10. Server time of recordDefeat timezone manipulationAll time decisions use server clock

Decide the order based on risk. For most apps: layers 1 through 6 are non negotiable for launch. Layer 7 follows within the first week. Layers 8 through 10 harden against the targeted attacks you will see later.

Phase 3: Execute

Step 1: Send the token from client to backend

Keep the client thin. Its only job is to hand the token to your server along with the current user identifier.

kotlin
override fun onPurchasesUpdated(
    result: BillingResult,
    purchases: List<Purchase>?
) {
    if (result.responseCode != BillingResponseCode.OK) return
    purchases?.forEach { p ->
        if (p.purchaseState == PurchaseState.PURCHASED) {
            api.verify(p.purchaseToken, p.products, currentUserId)
        }
    }
}

Send over HTTPS. Pin the server certificate if you can. Include your own auth token so the server knows which user is claiming the purchase.

Step 2: Verify on the backend and bind the token to the user

The server is the only place that decides whether a purchase is real. Call the Google Play Developer API, validate the response, then atomically insert the entitlement under a unique constraint on purchase_token. That constraint is your replay defense.

python
def grant_entitlement(token, claimed_product, user_id):
    # The package is bound by the request path: Google rejects a token from another app.
    record = play_api.get_purchase(PACKAGE, claimed_product, token)
    if record.get("productId", claimed_product) != claimed_product:
        raise PurchaseRejected("product mismatch")
    state = record["purchaseState"]
    if state == 2:  # PENDING (includes pre orders): not a rejection, do not refund; grant after ONE_TIME_PRODUCT_PURCHASED
        raise PurchasePending("pending")  # a separate exception from PurchaseRejected
    if state != 0:  # 1 = CANCELED
        raise PurchaseRejected("not purchased")
    existing = db.entitlements.find_by_token(token)
    if existing:
        if existing.user_id != user_id:
            security_log.flag("token_reuse", token, user_id)
        return existing
    db.entitlements.insert_unique(token, user_id, record.get("orderId"))  # promo code purchases have no orderId
    play_api.acknowledge(PACKAGE, claimed_product, token)

Two things do the real work here. First, the unique insert on token means a replayed token from any account is a database conflict, not a second grant. Second, comparing the claiming user_id against the original owner on every lookup surfaces token sharing and account abuse patterns that a naive "already processed, return success" path would hide.

If a purchase fails validation or abuse checks (for example a product mismatch; a PENDING purchase is not a failure), do not grant it and do not leave it to expire unacknowledged: call orders.refund with revoke=true for its orderId so Google records that you rejected it.

Step 3: Add device and profile signals before the purchase

Set both obfuscated identifiers on every purchase flow. They cost nothing and give Google, and you, a way to correlate across sessions and Google accounts.

kotlin
val params = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(productParams))
    .setObfuscatedAccountId(sha256(currentUser.id))
    .setObfuscatedProfileId(sha256(currentUser.activeProfileId))
    .build()
billingClient.launchBillingFlow(activity, params)

Both values come back in the purchase record, so your backend can reconcile them with your user database even if the user switches Google accounts.

Fraud Pattern to Mitigation Reference

Fraud patternPrimary mitigationBackstop
Modified APK removes client checksBackend receipt verificationPlay Integrity API, R8 obfuscation
Fabricated purchase tokenspurchases.products.get returns error, server rejectsPackage name and product ID checks
Stolen token from another appThe API call scoped to your packageName rejects foreign tokensToken to user binding
Product swap (cheap token, expensive claim)productId validation against client claimPrice recorded from API response, not client
Replayed token on same accountUnique constraint on purchase_tokenIdempotent grant returns existing record
Replayed token across accountsToken to user binding with alert on mismatchDevice fingerprint correlation
Pending payment treated as paidReject purchaseState == 2, wait for RTDNAcknowledge only after state becomes PURCHASED
Missed acknowledgement triggers auto refundServer side acknowledge after grant with retryMonitor acknowledgement failures as high priority
Refund abuse and chargebacksvoidedPurchaseNotification RTDN plus daily voidedpurchases.list?type=1 backfillGraduated enforcement (warn, restrict, ban)
Consumable refund after spendDeduct refunded amount from user balanceRestrict access until balance is non negative
Account sharing across many devicesConcurrent device limit, device fingerprintingFlag high distinct device count per token
Timezone and clock manipulationServer clock is the only clock for access decisionsSystemClock.elapsedRealtime() for offline grace
Ban evasion via new accountStore device and account identifiers of banned usersApply restrictions on first matching signal
Double entitlement after upgrade or resubscribeRevoke the linkedPurchaseToken entitlement once the new purchase is completedAlert when the linked token belongs to another user

Common Pitfalls

  • Acknowledging from the client. If the client acknowledges before your server grants entitlement, a failure leaves the user charged with no access. Acknowledge on the server, after the grant.
  • Returning 200 on duplicate tokens without checking the original owner. You miss token sharing entirely.
  • Bundling premium assets in assets/ or res/. Any APK extractor pulls them out. Host premium content on your server and gate downloads on verified entitlement.
  • Waiting for a daily batch to revoke a voided purchase. Revoke as soon as the voidedPurchaseNotification or SUBSCRIPTION_REVOKED RTDN arrives, and apply graduated enforcement (warn, restrict, ban) to the account, not delayed revocation.
  • Using System.currentTimeMillis() for trial eligibility or offer windows. The device clock is user controlled.

References

Domande frequenti

Cosa fa la skill IA Security?

Use this skill when hardening a Google Play Billing integration against fraud. Covers server side receipt verification, replay attack protection, device fingerprinting, velocity checks, and the most common billing fraud patterns.

Perché usare Security su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Security è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Security in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/security. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Security?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Security?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Security: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Security è gratuita?

Sì. È pubblicata su GitHub da RevenueCat con licenza Apache-2.0. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇