Integrating LicenseSeat in a Swift macOS App
Integrating LicenseSeat in a Swift macOS App
The Swift/Xcode lane end to end: pinning the SDK, configuring it, the two failure modes that ship a licensing-dead binary that launches perfectly, sandbox specifics, testing on a headless runner, and the Sparkle rail.
Everything here was learned taking a production Swift + Sparkle macOS app — an existing product with a shipped fleet, three distribution channels, a sandboxed direct build, and a legacy licensing cache — to full LicenseSeat parity, and then proving the update rail against production. Nothing in it is hypothetical, and the parts that read like paranoia are the parts that cost a release.
Companions, none of which this guide repeats: the Swift SDK reference is the API surface; Shipping Desktop Updates owns feeds, packaging and the Sparkle appcast contract; CI-Notarized macOS Releases owns signing, notarization and the release workflow (including its Swift/Xcode section).
Pin the SDK, and mean it
Use an exact version, not a range. A licensing SDK is not a place where an unattended minor bump should be able to change offline semantics between one release build and the next — and 0.5.0 changed exactly that (see below).
In an Xcode project, the pin lives in project.pbxproj and the grammar is
version-kind specific:
/* XCRemoteSwiftPackageReference "licenseseat-swift" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/licenseseat/licenseseat-swift";
requirement = {
kind = exactVersion;
version = 0.5.2;
};
};
exactVersion takes version. upToNextMajorVersion takes minimumVersion.
The keys are not interchangeable, and a pin written with the wrong key for its
kind does not fail loudly — it fails as a resolution that quietly does
something else.
Never hand-edit Package.resolved
The lockfile is at
MyApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
and carries an originHash over the declared dependency graph plus, per pin, a
revision (the commit the tag points at). Neither is something you can type.
Bump the pin in the pbxproj, then regenerate:
xcodebuild -resolvePackageDependencies -project MyApp.xcodeproj
and commit what that writes. This matters because the release lane runs with
-onlyUsePackageVersionsFromResolvedFile: a stale or hand-patched lockfile
makes the build fail instead of silently resolving around you. That flag is
doing its job; the fix is regeneration, never deletion of the flag.
Any xcodebuild invocation can rewrite the lockfile
Including -showBuildSettings. An unpinned read of build settings can perform
implicit package resolution and move Package.resolved underneath a release
job that has already decided which versions it is shipping. Pass the isolation
flags to every invocation, reads included, and assert the file did not move:
xcodebuild -project MyApp.xcodeproj -scheme MyApp -configuration Release \
-destination 'generic/platform=macOS' \
-onlyUsePackageVersionsFromResolvedFile \
-skipPackageUpdates \
-disablePackageRepositoryCache \
-showBuildSettings > settings.txt
git diff --quiet -- '*Package.resolved' \
|| { echo "::error::Reading build settings modified the lockfile"; exit 1; }
Configuration essentials
Configure once, at launch, before anything asks about licensing:
LicenseSeatStore.shared.configure(
apiKey: apiKey, // the publishable pk_ key
productSlug: "your-product"
) { config in
config.telemetryEnabled = true // this is the default — see below
}
Four defaults are worth knowing before you ship, because each one is a decision whether or not you make it:
telemetryEnableddefaults totrue. The SDK sends device and app telemetry with licensing calls unless you turn it off. That is a privacy-policy commitment, not a config flag — SDK Telemetry & Version Adoption covers the exact field list and the sequencing trap (your published policy has to describe this before the first build that ships with it enabled, not after).appVersion/appBuildauto-fill fromCFBundleShortVersionStringandCFBundleVersion. An app bundle needs to set neither. Only hosts without anInfo.plist— command-line tools, SPM executables — need to supply them explicitly.- Offline authority is ON by default as of 0.5.0, and
maxOfflineDays == 0now means "no additional host-side age cap", not "offline disabled". In 0.4.2 the same value fail-closed. An app that upgrades and leaves the value at 0 therefore switches from "every validation needs the network" to "the signed grant's own expiry governs" without a line of code changing. If you want an online decision every time, setofflineFallbackEnabled = falseexplicitly. See Offline Licensing. configureis first-wins. A second call withoutforce: trueis ignored (0.5.0 logs a warning and returnsfalserather than failing silently). This has a sharp consequence — see the API-key section below.
Migrating an app that already has a licensing system
If the app has a shipped fleet with cached activations from an older SDK or a homegrown licensing layer, the migration path is where the de-licensing happens.
Trim every identifier you migrate
v0.4.2+ input validation fail-closes on surrounding whitespace. A license
key or fingerprint with a trailing newline is not trimmed for you — it is
rejected, as an opaque invalid_identity, on every subsequent call. A legacy
cache written by a older codepath that stored "KEY\n" therefore turns into a
hard de-licensing of every existing customer the moment they update, with an
error message that names nothing you can act on.
Trim at every boundary where an identifier enters the SDK:
let normalizedKey = key.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedKey.isEmpty else { throw LicensingError.invalidLicenseKey }
That means the activation text field (users paste keys with spaces), the migrated cache blob, and anything read from a file or environment variable. Trim it on the way in, once, rather than defending against it everywhere.
Two rules for the migration itself
- Keep the "already migrated" marker outside the SDK's storage namespace.
Put it under the SDK's
licenseseat_prefix and a deactivation or cache purge deletes it — which makes the obsolete legacy blob eligible again on the next launch and resurrects a dead activation. - Fail closed. A blob that matches neither the legacy schema nor the current one gets the migration path retired and is left for the SDK to judge. A migration routine must never be a code path that grants a license.
The locked-Keychain failure (map it, don't swallow it)
On Apple platforms the SDK's installation identity is Keychain-protected. When the login keychain is locked, identity acquisition fails rather than silently minting a new identifier. That is deliberate: a silent fallback would consume a second seat and strand the first one, permanently, on a machine whose only problem was a locked keychain.
Which makes it your job to say so:
if let seatError = error as? LicenseSeatError,
case .deviceIdentifierError = seatError {
return .activationFailed(
"We couldn't read this Mac's device identity because your Keychain is "
+ "locked. Unlock your login keychain (or log out and back in) and try again."
)
}
A generic "could not generate a device identifier" turns a user who is thirty seconds from fixing it into a support ticket.
The API key is only as real as the injection behind it
The house pattern is an Info.plist reference resolved at build time:
<key>LICENSESEAT_API_KEY</key>
<string>$(LICENSESEAT_API_KEY)</string>
That line is a reference. It is worth exactly as much as the build setting
behind it — an xcconfig, an xcodebuild argument, or a CI variable. A
release lane that forgets the injection produces a signed, notarized,
perfectly launchable binary in which licensing can never work. No crash, no
visible defect: a log line, a 401, and every activation failing.
Defend on both sides.
In the app, guard for both shapes of "not injected":
let bundled = Bundle.main.object(forInfoDictionaryKey: "LICENSESEAT_API_KEY") as? String ?? ""
let hasAPIKey = !bundled.isEmpty && !bundled.contains("$(")
The unexpanded $(…) placeholder is a real state, not a theoretical one —
which of the two you get depends on how the plist reached the bundle, so a
check for empty alone misses half the cases.
And when the key is missing, leave the SDK unconfigured. Do not configure
it with "" to keep the code path uniform: configure is first-wins, so an
empty-key configuration poisons the shared instance and a later, correct
configuration is ignored. Unconfigured is recoverable and loud; configured
with a bad key is a permanent 401 that looks like a server problem.
In CI, hard-fail before the archive rather than after the notarization:
if [ -z "$LICENSESEAT_API_KEY" ]; then
echo "::error::The publishable key variable is not configured. Without it the \
archive ships an empty LICENSESEAT_API_KEY and licensing is dead on arrival."
exit 1
fi
Then inject it through a scratch xcconfig written 0600 outside the checkout,
pass it with -xcconfig, delete it in an always() step, and — the part
people skip — assert the value in the exported bundle afterwards:
plutil -extract LICENSESEAT_API_KEY raw -o - "$APP/Contents/Info.plist"
Store the publishable key as an Actions variable, not a secret. It ships
inside every binary, so it is not confidential, and leaving it unmasked is what
lets the verification step print the mismatch instead of printing ***.
Sandboxed apps
Sparkle needs two mach-lookup exceptions
A sandboxed app that updates itself through Sparkle needs the installer
launcher service enabled in Info.plist:
<key>SUEnableInstallerLauncherService</key>
<true/>
and two temporary-exception entitlements naming Sparkle's XPC services:
<key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spks</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spki</string>
</array>
Nothing validates the contents of that array. A typo compiles, signs, notarizes and ships, and disables updates in the release build only — the place you are least likely to test it. Assert them in CI, where a one-line check costs nothing:
expected_spks="\$(PRODUCT_BUNDLE_IDENTIFIER)-spks"
test "$(plutil -extract 'com\.apple\.security\.temporary-exception\.mach-lookup\.global-name.0' \
raw -o - MyApp/MyApp.entitlements)" = "$expected_spks"
The same check is worth writing in the negative for other channels: if you also
ship a Mac App Store or Setapp target, assert those Info.plist files contain
no SUFeedURL. A Sparkle key leaking into an App Store build is a review
rejection.
While you are there: com.apple.security.network.client is what lets the SDK
reach the API at all. Its absence looks exactly like the user being offline.
User defaults live in the container
For a sandboxed app, preferences are at:
~/Library/Containers/<bundle-id>/Data/Library/Preferences/<bundle-id>.plist
defaults write <bundle-id> SUFeedURL … writes the non-sandboxed location,
which the app will never read. Every "I overrode the feed URL / cleared the
update throttle and nothing changed" on a sandboxed app is this. Write to the
container path, with the app not running:
defaults write ~/Library/Containers/<bundle-id>/Data/Library/Preferences/<bundle-id> \
SUScheduledCheckInterval -int 60
Note that SUPublicEDKey has no user-defaults override — it comes from
Info.plist only. Rehearsal builds are built with the rehearsal public key;
they cannot be patched afterwards.
Testing on a headless runner
xcodebuild test launches the TEST_HOST app. For a sandboxed, unsigned app
on a headless CI runner, that launch hangs — no failure, no output, just a job
that burns its timeout.
The recipe that works: build the test bundle, then run it directly.
xcodebuild -project MyApp.xcodeproj -scheme MyApp -configuration Debug \
-destination "platform=macOS" \
-derivedDataPath "$DERIVED_DATA" \
-only-testing:MyAppTests \
CODE_SIGNING_ALLOWED=NO CODE_SIGN_IDENTITY="" \
ONLY_ACTIVE_ARCH=YES \
build-for-testing
APP="$DERIVED_DATA/Build/Products/Debug/MyApp.app"
TEST_BUNDLE="$APP/Contents/PlugIns/MyAppTests.xctest"
TEST_FRAMEWORKS="$TEST_BUNDLE/Contents/Frameworks"
mkdir -p "$TEST_FRAMEWORKS"
# The hosted bundle resolves its @rpath dependencies relative to the host app.
# Run it standalone and those lookups have to be satisfied where it looks.
ln -sfn ../../../../MacOS/MyApp.debug.dylib "$TEST_FRAMEWORKS/MyApp.debug.dylib"
for dependency in "$APP/Contents/Frameworks/"*; do
ln -sfn "../../../../Frameworks/$(basename "$dependency")" \
"$TEST_FRAMEWORKS/$(basename "$dependency")"
done
xcrun xctest "$TEST_BUNDLE" > "$XCTEST_LOG" 2>&1
Capture to a file and upload it on failure — see
[[guides/zero-to-shipped#process-pitfalls-for-agents|why piping through grep
or tail swallows the exit code]].
Locally, pass -derivedDataPath (and -clonedSourcePackagesDirPath)
inside the workspace when the environment restricts writes outside it — agent
sandboxes routinely do. The default
~/Library/Developer/Xcode/DerivedData is outside the project, and the
resulting permission failure reads like a toolchain problem rather than a
sandbox one.
Toolchain selection is a real dependency. A pinned transitive package that
declares swift-tools-version 6.1 cannot be loaded by Xcode 16.2 — package
resolution fails before a single file compiles. Select Xcode explicitly, with a
fallback chain, in both the CI and release lanes:
sudo xcode-select -s /Applications/Xcode_26.3.app \
|| sudo xcode-select -s /Applications/Xcode_16.4.app \
|| sudo xcode-select -s /Applications/Xcode_16.3.app \
|| sudo xcode-select -s /Applications/Xcode.app
Swift 6 strict concurrency on Linux (for SDK contributors)
Skip this unless you are contributing to the SDK itself — but if you are, this
is the section that will otherwise cost you an evening. The SDK's Linux lane
builds and tests with -strict-concurrency=complete -warnings-as-errors inside
a digest-pinned Swift container, and the failures there have nothing to do with
your code's concurrency.
SwiftPM's generated Linux discovery tables send the test-case instance into
the test method. For a @MainActor test class, that is a sending self
error, and one poisoned entry cascades across the whole array literal — so the
compiler points at a line unrelated to the actual problem.
Two moves are required, both mechanical:
-
A test-only
@unchecked Sendableconformance for every@MainActorsuite, registered in one place:extension APIClientTests: @unchecked Sendable {} extension MachineFileTests: @unchecked Sendable {} extension ReleasesTests: @unchecked Sendable {}XCTest creates one case instance per invocation and does not access it concurrently, so the conformance makes an existing runner guarantee explicit rather than papering over a race. Every new suite has to be added to that list — forgetting one breaks the Linux lane and nothing else, so it is invisible until CI.
-
Every test method on a
@MainActorsuite must beasync. Synchronous ones land in the nonisolated discovery table and fail.func testX()→func testX() async; no other change.
A synchronous wait(for:) inside an async main-actor test deadlocks. The
wait blocks the main actor, so the fulfill() queued on the main queue can
never run, and the test hangs until the runner kills it. When all you need is
to drain a main-queue hop, hop explicitly:
// wait(for:) would block the main actor this async test runs on,
// and the queued fulfill could never execute.
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
DispatchQueue.main.async { continuation.resume() }
}
Finally, know what the runner is doing: corelibs XCTest 6.2/6.3 can strand its
internal async-teardown bridge after a test has genuinely finished. The SDK
runs each discovered case in a fresh process and requires a zero-failure
attestation marker emitted from tearDownWithError(); only an external timeout
that arrives after that marker is accepted, and a missing, duplicated, or
non-zero marker fails closed. If you are debugging a Linux hang, that marker is
how you tell "the test body never finished" from "the runner would not let go".
Sparkle, in one plist key
The whole updater integration is:
<key>SUFeedURL</key>
<string>https://licenseseat.com/p/your-product/appcast.xml</string>
<key>SUPublicEDKey</key>
<string><the Ed25519 public key from your dashboard></string>
This rail needs no SDK code at all and works whether or not the app links
LicenseSeat. The appcast contract — channels, bundle_version, element form,
signing, the silent auto-update path and how to diagnose it — lives in
Shipping Desktop Updates. Two
Swift-side notes that belong here:
Wire an updater delegate before you need one. If your
SPUStandardUpdaterController passes updaterDelegate: nil, you have no beta
channel (Sparkle discards channel-tagged items unless a delegate opts in) and
no way to attach a license to the feed request. Both arrive later; the delegate
is cheap now.
License-gated feeds need the credential on two requests, the feed and the enclosure:
final class UpdateGate: NSObject, SPUUpdaterDelegate {
private var licenseKey: String? {
LicenseSeatStore.shared.seat?.currentLicense()?.licenseKey
}
func feedParameters(
for updater: SPUUpdater,
sendingSystemProfile sendingProfile: Bool
) -> [[String: String]] {
guard let licenseKey else { return [] }
return [["key": "license_key", "value": licenseKey]]
}
func updater(
_ updater: SPUUpdater,
willDownloadUpdate item: SUAppcastItem,
with request: NSMutableURLRequest
) {
guard let licenseKey else { return }
request.setValue("Bearer \(licenseKey)", forHTTPHeaderField: "Authorization")
}
}
An unidentified request to a licensed feed receives an empty feed, never a 4xx — an unlicensed user sees "no updates", which is the intended behavior, rather than an error dialog. If your product's feed policy is open, skip the delegate entirely.
The checklist an agent should actually run
Before calling a Swift integration done:
git diff --quiet -- '*Package.resolved'after a-showBuildSettingsread — the lockfile must be immutable in the release lane.plutil -extract LICENSESEAT_API_KEY raw -o - <exported app>/Contents/Info.plistequals the configured publishable key, byte for byte. Not "the variable is set" — the built bundle carries it.plutil -extracton both mach-lookup exception entries andSUEnableInstallerLauncherServicefor the sandboxed target; and the absence ofSUFeedURLin any store-channel plist.- Activation succeeds with a real key from the product's demo plan, and the resulting entitlements match the plan (see [[guides/zero-to-shipped#the-entitlement-contract-get-this-exactly-right|the entitlement contract]]).
- Paste a key with a leading space into the activation field and confirm it still activates. That is the whitespace fail-closed behavior, tested from the outside.
- Lock the login keychain and confirm the error message names the keychain.
- An older build, run for real, updates itself through the production feed. Nothing short of that proves the rail.
Next steps
- CI-Notarized macOS Releases — the Swift/Xcode release lane: archive, export, dual notarization, the identity gate
- Shipping Desktop Updates — the appcast contract and every packaging trap
- Zero to Shipped — the map across LicenseSeat, CI, Apple and the money path
- Swift SDK reference — the full API surface