Token导航 LogoToken导航TokenDH.com
开发敏感数据github未标认证来源可访问许可证需确认审计通过

device-integrity设备完整性

Agent Skill

device-integrity 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

26,136

周安装

1,072

GitHub Stars

467

下载量

9,152
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:device-integrity(设备完整性)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/device-integrity
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill device-integrity
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill device-integrity

简介

该技能验证请求来自真实未篡改的 Apple 设备,保障 app 安全性。

  • DeviceCheck 提供 per-device 标记位,App Attest 使用 Secure Enclave 密钥。
  • 需区分简单促销标记与高强度防篡改验证两种使用场景。
  • 服务器端必须实现完整的令牌解析与苹果签名校验流程。
  • device-integrity 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Device Integrity

Verify that requests to your server come from a genuine Apple device running your unmodified app. DeviceCheck provides per-device bits for simple flags (e.g., "claimed promo offer"). App Attest uses Secure Enclave keys and Apple attestation to cryptographically prove app legitimacy on each request.

Contents

DCDevice (DeviceCheck Tokens)

DCDevice generates a unique, ephemeral token that identifies a device. The token is sent to your server, which then communicates with Apple's servers to read or set two per-device bits. Available on iOS 11+.

Token Generation

import DeviceCheck

func generateDeviceToken() async throws -> Data {
    guard DCDevice.current.isSupported else {
        throw DeviceIntegrityError.deviceCheckUnsupported
    }

    return try await DCDevice.current.generateToken()
}

Sending the Token to Your Server

func sendTokenToServer(_ token: Data) async throws {
    let tokenString = token.base64EncodedString()

    var request = URLRequest(url: serverURL.appending(path: "verify-device"))
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(["device_token": tokenString])

    let (_, response) = try await URLSession.shared.data(for: request)
    guard let httpResponse = response as? HTTPURLResponse,
          httpResponse.statusCode == 200 else {
        throw DeviceIntegrityError.serverVerificationFailed
    }
}

Server-Side Overview

Your server uses the device token to call Apple's DeviceCheck API endpoints:

EndpointPurpose
https://api.devicecheck.apple.com/v1/query_two_bitsRead the two bits for a device
https://api.devicecheck.apple.com/v1/update_two_bitsSet the two bits for a device
https://api.devicecheck.apple.com/v1/validate_device_tokenValidate a device token without reading bits

The server authenticates with a DeviceCheck private key from the Apple Developer portal, creating a signed JWT for each request.

What the Two Bits Are For

Apple stores two Boolean values per device per developer team. You decide what they mean. Common uses:

  • Bit 0: Device has claimed a promotional offer.
  • Bit 1: Device has been flagged for fraud.

Bits persist across app reinstall. You control when to reset them via the server API.

DCAppAttestService (App Attest)

DCAppAttestService validates that a specific instance of your app on a specific device is legitimate. It uses a hardware-backed key in the Secure Enclave to create cryptographic attestations and assertions. Available on iOS 14+.

The flow has three phases:

  1. Key generation -- create a key pair in the Secure Enclave.
  2. Attestation -- Apple certifies the key belongs to a genuine Apple device running your app.
  3. Assertion -- sign server requests with the attested key to prove ongoing legitimacy.

Checking Support

import DeviceCheck

let attestService = DCAppAttestService.shared

guard attestService.isSupported else {
    // Fall back to DCDevice token or other risk assessment.
    // App Attest is not available on simulators or all device models.
    return
}

App Attest Key Generation

Generate a cryptographic key pair stored in the Secure Enclave. The returned keyId is a string identifier you persist (e.g., in Keychain) for later attestation and assertion calls.

import DeviceCheck

actor AppAttestManager {
    private let service = DCAppAttestService.shared
    private var keyId: String?

    /// Generate and persist a key pair for App Attest.
    func generateKeyIfNeeded() async throws -> String {
        if let existingKeyId = loadKeyIdFromKeychain() {
            self.keyId = existingKeyId
            return existingKeyId
        }

        let newKeyId = try await service.generateKey()
        saveKeyIdToKeychain(newKeyId)
        self.keyId = newKeyId
        return newKeyId
    }

    // MARK: - Keychain helpers (simplified)

    private func saveKeyIdToKeychain(_ keyId: String) {
        let data = Data(keyId.utf8)
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: "app-attest-key-id",
            kSecAttrService as String: Bundle.main.bundleIdentifier ?? "",
            kSecValueData as String: data,
            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
        ]
        SecItemDelete(query as CFDictionary) // Remove old if exists
        SecItemAdd(query as CFDictionary, nil)
    }

    private func loadKeyIdFromKeychain() -> String? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: "app-attest-key-id",
            kSecAttrService as String: Bundle.main.bundleIdentifier ?? "",
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        guard status == errSecSuccess, let data = result as? Data else { return nil }
        return String(data: data, encoding: .utf8)
    }
}

Important: Generate the key once and persist the keyId. Generating a new key invalidates any previous attestation.

App Attest Attestation Flow

Attestation proves that the key was generated on a genuine Apple device running your unmodified app. You perform attestation once per key, then store the attestation object on your server.

Client-Side Attestation

import DeviceCheck
import CryptoKit

extension AppAttestManager {
    /// Attest the key with Apple. Send the attestation object to your server.
    func attestKey() async throws -> Data {
        guard let keyId else {
            throw DeviceIntegrityError.keyNotGenerated
        }

        // 1. Request a one-time challenge from your server
        let challenge = try await fetchServerChallenge()

        // 2. Hash the challenge (Apple requires a SHA-256 hash)
        let challengeHash = Data(SHA256.hash(data: challenge))

        // 3. Ask Apple to attest the key
        let attestation = try await service.attestKey(keyId, clientDataHash: challengeHash)

        // 4. Send the attestation object to your server for verification
        try await sendAttestationToServer(
            keyId: keyId,
            attestation: attestation,
            challenge: challenge
        )

        return attestation
    }

    private func fetchServerChallenge() async throws -> Data {
        let url = serverURL.appending(path: "attest/challenge")
        let (data, _) = try await URLSession.shared.data(from: url)
        return data
    }

    private func sendAttestationToServer(
        keyId: String,
        attestation: Data,
        challenge: Data
    ) async throws {
        var request = URLRequest(url: serverURL.appending(path: "attest/verify"))
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let payload: [String: String] = [
            "key_id": keyId,
            "attestation": attestation.base64EncodedString(),
            "challenge": challenge.base64EncodedString()
        ]
        request.httpBody = try JSONEncoder().encode(payload)

        let (_, response) = try await URLSession.shared.data(for: request)
        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw DeviceIntegrityError.attestationVerificationFailed
        }
    }
}

Server-Side Attestation Verification

Your server validates the attestation object (CBOR), verifies the certificate chain against Apple's App Attest root CA, and stores the public key and receipt for future assertion verification. See references/device-integrity-patterns.md for the full server verification flow.

App Attest Assertion Flow

After attestation, use assertions to sign individual requests. Each assertion proves the request came from the attested app instance.

Client-Side Assertion

import DeviceCheck
import CryptoKit

extension AppAttestManager {
    /// Generate an assertion to accompany a server request.
    /// - Parameter requestData: The request payload to sign (e.g., JSON body).
    /// - Returns: The assertion data to include with the request.
    func generateAssertion(for requestData: Data) async throws -> Data {
        guard let keyId else {
            throw DeviceIntegrityError.keyNotGenerated
        }

        // Hash the request data -- the server will verify this matches
        let clientDataHash = Data(SHA256.hash(data: requestData))

        return try await service.generateAssertion(keyId, clientDataHash: clientDataHash)
    }
}

Using Assertions in Network Requests

extension AppAttestManager {
    /// Perform an attested API request.
    func makeAttestedRequest(
        to url: URL,
        method: String = "POST",
        body: Data
    ) async throws -> (Data, URLResponse) {
        let assertion = try await generateAssertion(for: body)

        var request = URLRequest(url: url)
        request.httpMethod = method
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(assertion.base64EncodedString(), forHTTPHeaderField: "X-App-Assertion")
        request.httpBody = body

        return try await URLSession.shared.data(for: request)
    }
}

Server-Side Assertion Verification

Your server decodes the assertion (CBOR), verifies the authenticator data and counter, checks the signature against the stored public key, and confirms the clientDataHash. See references/device-integrity-patterns.md for step-by-step server verification.

Server Verification Guidance

See references/device-integrity-patterns.md for full server architecture guidance including attestation vs. assertion comparison, recommended endpoint design, and risk assessment.

Error Handling

Handle DCError codes from DeviceCheck operations. Key cases:

  • .serverUnavailable — retry with exponential backoff
  • .invalidKey — key invalidated (OS update, Secure Enclave reset); regenerate and re-attest
  • .featureUnsupported — fall back to DCDevice tokens
  • .invalidInput — malformed clientDataHash or keyId

See references/device-integrity-patterns.md for full error handling code, retry strategy, and key invalidation recovery.

Common Patterns

Environment Entitlement

Set the App Attest environment in your entitlements file. Use development during testing and production for App Store builds:

<key>com.apple.developer.devicecheck.appattest-environment</key>
<string>production</string>

When the entitlement is missing, the system uses development in debug builds and production for App Store and TestFlight builds.

See references/device-integrity-patterns.md for the full integration manager pattern, gradual rollout guidance, and error type definition.

Common Mistakes

  1. Generating a new key on every launch. Generate once, persist the keyId in Keychain.
  2. Skipping the fallback for unsupported devices. Not all devices support App Attest. Use DCDevice tokens as fallback.
  3. Trusting attestation client-side. All verification must happen on your server.
  4. Not implementing replay protection. The server must track and increment the assertion counter.
  5. Missing the environment entitlement. Without it, debug builds use development and App Store uses production. Mismatches cause attestation failures.
  6. Not handling DCError.invalidKey. Keys can be invalidated by OS updates. Detect and regenerate.

Review Checklist

  • DCAppAttestService.isSupported checked before use; fallback to DCDevice when unsupported
  • Key generated once and keyId persisted in Keychain
  • Attestation performed once per key; attestation object sent to server
  • Server validates attestation against Apple's App Attest root CA
  • Assertions generated for each sensitive request; server verifies signature and counter
  • DCError cases handled: .serverUnavailable with retry, .invalidKey with key regeneration
  • App Attest environment entitlement set correctly for debug vs. production
  • Gradual rollout considered; feature flag in place for enabling/disabling

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.44%
按下载量换算3,243

Claude

32.79%
按下载量换算3,001

Cursor

17.52%
按下载量换算1,603

Gemini CLI

9.24%
按下载量换算846

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills