Securityのロゴ

Security

組織
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.

概要

公開者RevenueCat
リポジトリplay-billing-skills
スキル名security
スター
58
フォーク
0
同梱ファイル
指示のみ
ライセンスApache-2.0
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    RevenueCatがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルSecurityをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/security
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでSecurityを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にSecurityを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Securityは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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

よくある質問

AIスキル「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.

TypingMindでSecurityを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Securityはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにSecurityをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/securityを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Securityを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Securityは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもSecurityを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Security」は無料ですか?

はい。RevenueCatがGitHubでApache-2.0ライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇