feat(native): a notification extension that decrypts TREK pushes on the device

The relay hands APNs the encrypted record with a placeholder text and
mutable-content set; the new Notification Service Extension opens it with
the device's Web Push keys from the shared keychain group (RFC 8291 on
CryptoKit) and shows the real title, text and link. Without the keys the
placeholder stays, so a notification arrives either way and nothing on the
way reads it.

The target came in through ios/scripts/add-extension.rb (kept, idempotent),
its App ID is registered, and the release lane signs every target with its
own App Store profile. Web Push payloads now stop at 2800 bytes so the
encrypted, base64-encoded record still fits Apple's 4 KB.
This commit is contained in:
Maurice
2026-11-06 13:41:42 +01:00
parent ad69bbf4a9
commit c6f91716a4
8 changed files with 436 additions and 22 deletions
+1 -1
View File
@@ -103,7 +103,7 @@ jobs:
xcodebuild -version
- name: Check the property lists
run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist
run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements
- uses: actions/setup-node@v6
with:
+29 -17
View File
@@ -18,6 +18,14 @@ default_platform(:ios)
APP_IDENTIFIER = "com.liketrek.trek"
PROJECT = "ios/App/App.xcodeproj"
# Every signed target with its bundle identifier: the app and its extensions
# (ios/scripts/add-extension.rb put them in the project). Each gets its own App
# Store profile, created or reused through the API key like the app's.
SIGNED_TARGETS = {
"App" => APP_IDENTIFIER,
"NotificationService" => "com.liketrek.trek.notifications",
}
platform :ios do
desc "Build the signed Release app and upload it to TestFlight (internal testing)."
lane :beta do
@@ -54,23 +62,27 @@ platform :ios do
keychain_path: keychain_path,
keychain_password: keychain_password,
)
get_provisioning_profile(
api_key: key,
app_identifier: APP_IDENTIFIER,
development: false,
)
profiles = {}
SIGNED_TARGETS.each do |target, identifier|
get_provisioning_profile(
api_key: key,
app_identifier: identifier,
development: false,
)
profiles[identifier] = lane_context[SharedValues::SIGH_NAME]
# Pin the project to that profile for this build; automatic signing stays the default
# a developer sees when they open the project in Xcode.
update_code_signing_settings(
path: PROJECT,
use_automatic_signing: false,
team_id: ENV.fetch("APPLE_TEAM_ID"),
code_sign_identity: "Apple Distribution",
bundle_identifier: APP_IDENTIFIER,
profile_name: lane_context[SharedValues::SIGH_NAME],
targets: ["App"],
)
# Pin each target to its profile for this build; automatic signing stays the
# default a developer sees when they open the project in Xcode.
update_code_signing_settings(
path: PROJECT,
use_automatic_signing: false,
team_id: ENV.fetch("APPLE_TEAM_ID"),
code_sign_identity: "Apple Distribution",
bundle_identifier: identifier,
profile_name: profiles[identifier],
targets: [target],
)
end
build_app(
project: PROJECT,
@@ -84,7 +96,7 @@ platform :ios do
].join(" "),
export_options: {
signingStyle: "manual",
provisioningProfiles: { APP_IDENTIFIER => lane_context[SharedValues::SIGH_NAME] },
provisioningProfiles: profiles,
},
)
+177 -3
View File
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
2CFE220A73ACB585F3D4CB8F /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2EE43D236E661AA975612A4B /* UserNotifications.framework */; };
2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; };
4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; };
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; };
@@ -15,14 +16,43 @@
504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; };
7A1E00032C0000000000A003 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */; };
7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */; };
7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */; };
84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; };
A8FDD4DBE3F078BF935CC4B9 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFA8802204810ED580DE46F3 /* NotificationService.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
3BB8A38B2B2C8614B24CF2AD /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 504EC2FC1FED79650016851F /* Project object */;
proxyType = 1;
remoteGlobalIDString = 9480DFBC2C2A112973DA468A;
remoteInfo = NotificationService;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
A8F12B42B22FCA041C6AA0DA /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
1E7522315D47F086145DC4B8 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
2EE43D236E661AA975612A4B /* UserNotifications.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UserNotifications.framework; path = System/Library/Frameworks/UserNotifications.framework; sourceTree = SDKROOT; };
2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = "<group>"; };
3DF4F4305878F949DD09193F /* NotificationService.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = "<group>"; };
50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = "<group>"; };
504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; };
504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
@@ -31,12 +61,14 @@
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; };
7A1E00012C0000000000A001 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = "<group>"; };
7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekBridgeViewController.swift; sourceTree = "<group>"; };
7A1E00062C0000000000A006 /* TrekShellPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekShellPlugin.swift; sourceTree = "<group>"; };
9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; };
A03A384FE54FAD1ED68E12DC /* NotificationService.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };
FFA8802204810ED580DE46F3 /* NotificationService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -48,15 +80,32 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
C9AA4ADC0D397C620A35B6A3 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2CFE220A73ACB585F3D4CB8F /* UserNotifications.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
0FC8613857BD976EB58ECE0B /* iOS */ = {
isa = PBXGroup;
children = (
);
name = iOS;
sourceTree = "<group>";
};
504EC2FB1FED79650016851F = {
isa = PBXGroup;
children = (
958DCC722DB07C7200EA8C5F /* debug.xcconfig */,
504EC3061FED79650016851F /* App */,
504EC3051FED79650016851F /* Products */,
5198C9768EB9762A60701C92 /* Frameworks */,
74C1FC6022E562372A71EEC9 /* NotificationService */,
);
sourceTree = "<group>";
};
@@ -64,6 +113,7 @@
isa = PBXGroup;
children = (
504EC3041FED79650016851F /* App.app */,
A03A384FE54FAD1ED68E12DC /* NotificationService.appex */,
);
name = Products;
sourceTree = "<group>";
@@ -88,6 +138,26 @@
path = App;
sourceTree = "<group>";
};
5198C9768EB9762A60701C92 /* Frameworks */ = {
isa = PBXGroup;
children = (
0FC8613857BD976EB58ECE0B /* iOS */,
2EE43D236E661AA975612A4B /* UserNotifications.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
74C1FC6022E562372A71EEC9 /* NotificationService */ = {
isa = PBXGroup;
children = (
1E7522315D47F086145DC4B8 /* Info.plist */,
3DF4F4305878F949DD09193F /* NotificationService.entitlements */,
FFA8802204810ED580DE46F3 /* NotificationService.swift */,
);
name = NotificationService;
path = NotificationService;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -98,10 +168,12 @@
504EC3001FED79650016851F /* Sources */,
504EC3011FED79650016851F /* Frameworks */,
504EC3021FED79650016851F /* Resources */,
A8F12B42B22FCA041C6AA0DA /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
E23A0A46599B8EE7A5B74F45 /* PBXTargetDependency */,
);
name = App;
packageProductDependencies = (
@@ -111,6 +183,23 @@
productReference = 504EC3041FED79650016851F /* App.app */;
productType = "com.apple.product-type.application";
};
9480DFBC2C2A112973DA468A /* NotificationService */ = {
isa = PBXNativeTarget;
buildConfigurationList = 4E3E5FA93A15425251E22D48 /* Build configuration list for PBXNativeTarget "NotificationService" */;
buildPhases = (
1EA0B85A2E70AC56F83C09C9 /* Sources */,
C9AA4ADC0D397C620A35B6A3 /* Frameworks */,
9706E0B1D8DD6E0542723B5D /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = NotificationService;
productName = NotificationService;
productReference = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -149,6 +238,7 @@
projectRoot = "";
targets = (
504EC3031FED79650016851F /* App */,
9480DFBC2C2A112973DA468A /* NotificationService */,
);
};
/* End PBXProject section */
@@ -168,9 +258,24 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
9706E0B1D8DD6E0542723B5D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
1EA0B85A2E70AC56F83C09C9 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A8FDD4DBE3F078BF935CC4B9 /* NotificationService.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
504EC3001FED79650016851F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -184,6 +289,15 @@
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
E23A0A46599B8EE7A5B74F45 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = NotificationService;
target = 9480DFBC2C2A112973DA468A /* NotificationService */;
targetProxy = 3BB8A38B2B2C8614B24CF2AD /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
504EC30B1FED79650016851F /* Main.storyboard */ = {
isa = PBXVariantGroup;
@@ -359,9 +473,69 @@
};
name = Release;
};
686FA31AEC6FE5BA3EF95E99 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_ENTITLEMENTS = NotificationService/NotificationService.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = NotificationService/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek.notifications;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
A475CD70019910612C4D523B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_ENTITLEMENTS = NotificationService/NotificationService.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = NotificationService/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek.notifications;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
4E3E5FA93A15425251E22D48 /* Build configuration list for PBXNativeTarget "NotificationService" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A475CD70019910612C4D523B /* Release */,
686FA31AEC6FE5BA3EF95E99 /* Debug */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>TREK Notifications</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.usernotifications.service</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).NotificationService</string>
</dict>
</dict>
</plist>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)com.liketrek.trek.shared</string>
</array>
</dict>
</plist>
@@ -0,0 +1,109 @@
import CryptoKit
import Security
import UserNotifications
/// Decrypts a TREK push before iOS shows it.
///
/// The user's server encrypts each notification for this device exactly as Web
/// Push does for a browser (RFC 8291, aes128gcm), and liketrek's relay hands the
/// ciphertext to APNs as `enc`, with a placeholder text and mutable-content set.
/// Here the device's keys (the app made them, TrekPushKeys in the app target)
/// open it, and the real title, text and link replace the placeholder. Without
/// the keys, or if anything does not add up, the placeholder stays: a
/// notification arrives either way, and nothing on the way could read it.
final class NotificationService: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var content: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
let content = (request.content.mutableCopy() as? UNMutableNotificationContent) ?? UNMutableNotificationContent()
self.content = content
if let encoded = request.content.userInfo["enc"] as? String,
let record = Data(base64Encoded: encoded),
let keys = PushKeys.load(),
let plaintext = WebPushRecord.open(record, keys: keys),
let payload = try? JSONSerialization.jsonObject(with: plaintext) as? [String: Any] {
if let title = payload["title"] as? String, !title.isEmpty { content.title = title }
if let body = payload["body"] as? String { content.body = body }
if let url = payload["url"] as? String { content.userInfo["url"] = url }
if let tag = payload["tag"] as? String { content.threadIdentifier = tag }
}
contentHandler(content)
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler, let content { contentHandler(content) }
}
}
/// The device's Web Push keys, from the keychain group it shares with the app.
struct PushKeys {
let privateKey: P256.KeyAgreement.PrivateKey
let auth: Data
static func load() -> PushKeys? {
guard let raw = read("push.privateKey"), let auth = read("push.auth"),
let key = try? P256.KeyAgreement.PrivateKey(rawRepresentation: raw) else { return nil }
return PushKeys(privateKey: key, auth: auth)
}
private static func read(_ account: String) -> Data? {
// No access group named: the extension's first keychain group is the
// shared one (its entitlements list only that), where the app stored them.
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.liketrek.trek.push",
kSecAttrAccount as String: account,
kSecReturnData as String: true,
]
var result: CFTypeRef?
return SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess ? result as? Data : nil
}
}
/// One aes128gcm record (RFC 8188) with Web Push keys (RFC 8291), opened.
enum WebPushRecord {
static func open(_ record: Data, keys: PushKeys) -> Data? {
let bytes = [UInt8](record)
// salt (16) | record size (4) | key id length (1) | key id (the sender's public key)
guard bytes.count > 21 else { return nil }
let salt = Data(bytes[0..<16])
let idLength = Int(bytes[20])
guard bytes.count > 21 + idLength + 16 else { return nil }
let senderKeyBytes = Data(bytes[21..<(21 + idLength)])
let ciphertext = Data(bytes[(21 + idLength)...])
guard let senderKey = try? P256.KeyAgreement.PublicKey(x963Representation: senderKeyBytes),
let shared = try? keys.privateKey.sharedSecretFromKeyAgreement(with: senderKey) else { return nil }
let sharedBytes = shared.withUnsafeBytes { Data($0) }
let receiverKey = keys.privateKey.publicKey.x963Representation
// IKM = HKDF(auth, ecdh, "WebPush: info" 0 receiver sender, 32)
var keyInfo = Data("WebPush: info".utf8)
keyInfo.append(0)
keyInfo.append(receiverKey)
keyInfo.append(senderKeyBytes)
let prkKey = HKDF<SHA256>.extract(inputKeyMaterial: SymmetricKey(data: sharedBytes), salt: keys.auth)
let ikm = HKDF<SHA256>.expand(pseudoRandomKey: prkKey, info: keyInfo, outputByteCount: 32)
let prk = HKDF<SHA256>.extract(inputKeyMaterial: ikm, salt: salt)
var cekInfo = Data("Content-Encoding: aes128gcm".utf8)
cekInfo.append(0)
var nonceInfo = Data("Content-Encoding: nonce".utf8)
nonceInfo.append(0)
let cek = HKDF<SHA256>.expand(pseudoRandomKey: prk, info: cekInfo, outputByteCount: 16)
let nonceKey = HKDF<SHA256>.expand(pseudoRandomKey: prk, info: nonceInfo, outputByteCount: 12)
let nonceBytes = nonceKey.withUnsafeBytes { Data($0) }
guard let nonce = try? AES.GCM.Nonce(data: nonceBytes),
let box = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext.dropLast(16), tag: ciphertext.suffix(16)),
let padded = try? AES.GCM.open(box, using: cek) else { return nil }
// The last record ends in 0x02 and optional zero padding.
var end = padded.count
while end > 0 && padded[padded.startIndex + end - 1] == 0 { end -= 1 }
guard end > 0, padded[padded.startIndex + end - 1] == 2 else { return nil }
return padded.prefix(end - 1)
}
}
+74
View File
@@ -0,0 +1,74 @@
# Adds an app extension target to App.xcodeproj and embeds it in the app.
#
# ruby ios/scripts/add-extension.rb <name> <bundle-id> <type> [extra frameworks...]
#
# type is "notification" (Notification Service Extension) or "widget" (WidgetKit,
# which also carries the Live Activities). The extension's sources live in
# ios/App/<name>/ with an Info.plist and <name>.entitlements next to them. The
# project file stays checked in, so the targets show in Xcode like any other;
# this script is how they got there, and running it again changes nothing.
require 'xcodeproj'
name, bundle_id, type, *frameworks = ARGV
abort 'usage: add-extension.rb <name> <bundle-id> <notification|widget> [frameworks...]' unless name && bundle_id && type
project_path = File.expand_path('../App/App.xcodeproj', __dir__)
project = Xcodeproj::Project.open(project_path)
app = project.targets.find { |t| t.name == 'App' } or abort 'no App target'
if project.targets.any? { |t| t.name == name }
puts "#{name} is already in the project"
exit 0
end
target = project.new_target(:app_extension, name, :ios, '15.0', nil, :swift)
# new_target links Foundation by a path into one SDK version; it is linked
# implicitly anyway, and a pinned SDK path breaks on the next Xcode.
target.frameworks_build_phase.files.select { |f| f.display_name.to_s.include?('Foundation') }.each do |f|
ref = f.file_ref
f.remove_from_project
ref&.remove_from_project
end
group = project.main_group.find_subpath(name, true)
group.set_source_tree('<group>')
group.set_path(name)
sources = Dir.children(File.expand_path("../App/#{name}", __dir__)).sort
sources.each do |file|
ref = group.new_reference(file)
target.add_file_references([ref]) if file.end_with?('.swift')
end
frameworks.each do |framework|
ref = project.frameworks_group.new_file("System/Library/Frameworks/#{framework}.framework", :sdk_root)
target.frameworks_build_phase.add_file_reference(ref, true)
end
app_settings = app.build_configurations.first.build_settings
target.build_configurations.each do |config|
s = config.build_settings
s['PRODUCT_BUNDLE_IDENTIFIER'] = bundle_id
s['PRODUCT_NAME'] = '$(TARGET_NAME)'
s['INFOPLIST_FILE'] = "#{name}/Info.plist"
s['GENERATE_INFOPLIST_FILE'] = 'NO'
s['CODE_SIGN_ENTITLEMENTS'] = "#{name}/#{name}.entitlements"
s['CODE_SIGN_STYLE'] = 'Automatic'
s['DEVELOPMENT_TEAM'] = app_settings['DEVELOPMENT_TEAM'] if app_settings['DEVELOPMENT_TEAM']
s['SWIFT_VERSION'] = '5.0'
s['TARGETED_DEVICE_FAMILY'] = '1,2'
s['IPHONEOS_DEPLOYMENT_TARGET'] = type == 'widget' ? '16.2' : '15.0'
s['MARKETING_VERSION'] = app_settings['MARKETING_VERSION'] || '1.0'
s['CURRENT_PROJECT_VERSION'] = app_settings['CURRENT_PROJECT_VERSION'] || '1'
s['SKIP_INSTALL'] = 'YES'
s['LD_RUNPATH_SEARCH_PATHS'] = ['$(inherited)', '@executable_path/Frameworks', '@executable_path/../../Frameworks']
end
embed = app.copy_files_build_phases.find { |p| p.name == 'Embed Foundation Extensions' } ||
app.new_copy_files_build_phase('Embed Foundation Extensions')
embed.symbol_dst_subfolder_spec = :plug_ins
build_file = embed.add_file_reference(target.product_reference, true)
build_file.settings = { 'ATTRIBUTES' => ['RemoveHeadersOnCopy'] }
app.add_dependency(target)
project.save
puts "added #{name} (#{bundle_id})"
@@ -14,8 +14,12 @@ import type { ChannelTestResult, PushPayload } from '@trek/shared';
* Ceiling for the JSON the service worker receives. A single aes128gcm record
* can carry just under 4 KB and some push services refuse anything larger, so
* the payload stays well clear of that and the body gives way first.
*
* The apps' relay (push.liketrek.com) is the tightest: it carries the encrypted
* record base64-encoded inside an APNs payload, which Apple caps at 4096 bytes.
* 2800 bytes of JSON become about 3870 there, with room for the APNs envelope.
*/
export const MAX_PUSH_PAYLOAD_BYTES = 3000;
export const MAX_PUSH_PAYLOAD_BYTES = 2800;
const TITLE_MAX_CHARS = 120;
/** A navigate target is an app path like /trips/12; anything longer is not one. */