Skip to main content
ClaudeWave
Skill732 repo starsupdated 15d ago

cryptotokenkit

CryptoTokenKit enables apps and system extensions to access cryptographic operations from hardware security tokens and smart cards across Apple platforms. Use it when building token driver extensions, communicating with smart cards via NFC or readers, integrating token-backed items with the system keychain, or implementing certificate-based authentication for login and keychain unlock on macOS and iOS 26 and later.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/dpearson2699/swift-ios-skills /tmp/cryptotokenkit && cp -r /tmp/cryptotokenkit/skills/cryptotokenkit ~/.claude/skills/cryptotokenkit
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# CryptoTokenKit

Use CryptoTokenKit for token driver extensions, smart-card communication,
token sessions, token-backed keychain integration, and certificate-based
authentication in Swift 6.3 apps.

**Platform availability:** CryptoTokenKit classes are available across Apple
platforms, but capability depends on extension point, entitlement, hardware, and
OS version. The smart-card app extension flow for login/keychain unlock is macOS.
`TKSmartCardSlotManager.default` is optional and returns `nil` unless smart-card
access is enabled. iOS/iPadOS 26+ add NFC smart-card slots and registration.

## Contents

- [Architecture Overview](#architecture-overview)
- [Token Extensions](#token-extensions)
- [Token Sessions](#token-sessions)
- [Smart Card Communication](#smart-card-communication)
- [Keychain Integration](#keychain-integration)
- [Certificate Authentication](#certificate-authentication)
- [Token Watching](#token-watching)
- [Error Handling](#error-handling)
- [Common Mistakes](#common-mistakes)
- [Review Checklist](#review-checklist)
- [References](#references)

## Architecture Overview

CryptoTokenKit bridges hardware security tokens (smart cards, USB tokens)
with authentication and keychain services. The framework has three main usage
modes:

**Smart-card token extensions** -- macOS app extensions that make a hardware
token's cryptographic items available to system login and keychain unlock. The
driver handles token lifecycle, session management, and cryptographic operations.

**Client-side token access** -- Apps query the keychain for items backed by
tokens. CryptoTokenKit exposes token items as standard keychain entries when a
token is present.

**NFC smart-card access** -- iOS/iPadOS 26+ apps create a temporary NFC smart
card slot and communicate with the presented contactless card through
`TKSmartCard`.

**Boundary routing:** Own token/smart-card sessions, token-backed keychain
items, and certificate-based smart-card auth. Route passkeys/WebAuthn and
account sign-in to `authentication`; route Secure Enclave, CryptoKit primitives,
keychain architecture, certificate pinning, and trust policy to `swift-security`.

### Key Types

| Type | Role | Platform |
|---|---|---|
| `TKTokenDriver` / `TKToken` / `TKTokenSession` | Token driver, token, and session primitives | iOS 10+, macOS 10.12+ |
| `TKSmartCardTokenDriver` | Entry point for smart card token extensions | iOS 10+, macOS 10.12+; macOS extension flow |
| `TKSmartCard` / `TKSmartCardSlotManager` | Low-level APDU communication and slot discovery | iOS 9+, macOS 10.10+; `default` is optional |
| `TKTokenWatcher` | Observes token insertion and removal | iOS 10+, macOS 10.12+ |
| `TKSmartCardSlotNFCSession` | NFC-backed smart card slot session | iOS/iPadOS 26+ |
| `TKSmartCardTokenRegistrationManager` | Registers NFC smart cards for later keychain use | iOS/iPadOS 26+ |

## Token Extensions

For system login and keychain unlock on macOS, a token driver is an app
extension that makes a hardware token's cryptographic capabilities available to
the system. The host app exists only as a delivery mechanism for the extension.

A smart card token extension has three core classes:

1. **TokenDriver** (subclass of `TKSmartCardTokenDriver`) -- entry point
2. **Token** (subclass of `TKSmartCardToken`) -- represents the token
3. **TokenSession** (subclass of `TKSmartCardTokenSession`) -- handles operations

### Driver Class

```swift
import CryptoTokenKit

final class TokenDriver: TKSmartCardTokenDriver, TKSmartCardTokenDriverDelegate {
    func tokenDriver(
        _ driver: TKSmartCardTokenDriver,
        createTokenFor smartCard: TKSmartCard,
        aid: Data?
    ) throws -> TKSmartCardToken {
        return try Token(
            smartCard: smartCard,
            aid: aid,
            instanceID: "com.example.token:\(smartCard.slot.name)",
            tokenDriver: driver
        )
    }
}
```

### Token Class

The token reads certificates and keys from hardware and populates its
keychain contents:

```swift
final class Token: TKSmartCardToken, TKTokenDelegate {
    init(
        smartCard: TKSmartCard, aid: Data?,
        instanceID: String, tokenDriver: TKSmartCardTokenDriver
    ) throws {
        try super.init(
            smartCard: smartCard, aid: aid,
            instanceID: instanceID, tokenDriver: tokenDriver
        )
        self.delegate = self

        let certData = try readCertificate(from: smartCard)
        guard let cert = SecCertificateCreateWithData(nil, certData as CFData) else {
            throw TKError(.corruptedData)
        }

        let certItem = TKTokenKeychainCertificate(certificate: cert, objectID: "cert-auth")
        let keyItem = TKTokenKeychainKey(certificate: cert, objectID: "key-auth")
        keyItem?.canSign = true
        keyItem?.canDecrypt = false
        keyItem?.isSuitableForLogin = true

        self.keychainContents?.fill(with: [certItem!, keyItem!])
    }

    func createSession(_ token: TKToken) throws -> TKTokenSession {
        TokenSession(token: token)
    }
}
```

### Info.plist and Registration

The extension's `Info.plist` must name the driver class:

```
NSExtension
  NSExtensionAttributes
    com.apple.ctk.driver-class = $(PRODUCT_MODULE_NAME).TokenDriver
  NSExtensionPointIdentifier = com.apple.ctk-tokens
```

Register the extension once by launching the host app as `_securityagent`:

```shell
sudo -u _securityagent /Applications/TokenHost.app/Contents/MacOS/TokenHost
```

## Token Sessions

`TKTokenSession` manages authentication state and performs cryptographic
operations via its delegate.

```swift
final class TokenSession: TKSmartCardTokenSession, TKTokenSessionDelegate {
    func tokenSession(
        _ session: TKTokenSession,
        supports operation: TKTokenOperation,
        keyObjectID: TKToken.ObjectID,
        algorithm: TKTokenKeyAlgorithm
    ) -> Bool {
        switch operation {
        case .signData:
            return algorithm.isAlgorithm(.rsaSignatureDigestPK
accessorysetupkitSkill

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

activitykitSkill

Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media playback, or any time-sensitive information that updates in real time. Also use when working with ActivityKit, ActivityAttributes, Activity lifecycle (request/update/end), Dynamic Island layouts (compact/minimal/expanded), push-to-update Live Activities, or Lock Screen live widgets.

adattributionkitSkill

Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing SKAdNetwork with AdAttributionKit for ad measurement.

alarmkitSkill

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, StandBy, and paired Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, AlarmButton stop and snooze actions, authorization, state observation, countdown widget-extension handoff, and Live Activity integration. Use when building wake-up alarms, countdown timers, or alarm-style alerts that need Apple's system alarm experience.

app-clipsSkill

Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications, location confirmation, and full-app migration. Use when creating App Clips or wiring App Clip invocation, experience configuration, or full-app handoff.

app-intentsSkill

Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and assistant schemas. Use when exposing app actions or entities to system surfaces.

app-store-optimizationSkill

Optimize App Store product pages for search visibility and conversion. Use for App Store Optimization (ASO), keyword research, app name/subtitle/keyword-field strategy, conversion-focused descriptions and promotional text, screenshot captions and ordering, Custom Product Pages with assigned search keywords, In-App Events, Product Page Optimization tests, localized metadata, ratings/review strategy, and in-app review prompt timing with RequestReviewAction or AppStore.requestReview. Also use when routing ASO vs App Store review, privacy/ATT, or StoreKit implementation boundaries.

app-store-reviewSkill

Prepare for App Store review and prevent rejections. Covers App Store review guidelines, app rejection reasons, PrivacyInfo.xcprivacy privacy manifest requirements, required API reason codes, in-app purchase IAP and StoreKit rules, App Store Guidelines compliance, ATT App Tracking Transparency, EU DMA Digital Markets Act, HIG compliance checklist, app submission preparation, review preparation, metadata requirements, entitlements, widgets, and Live Activities review rules. Use when preparing for App Store submission, fixing rejection reasons, auditing privacy manifests, implementing ATT consent flow, configuring StoreKit IAP, or checking HIG compliance.