@h1r-ai/croche-react-native 0.5.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +90 -451
- package/THIRD-PARTY-NOTICES +906 -14
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
- package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
- package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -0
- package/dist/package.json +1 -0
- package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
- package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
- package/dist/react-native/src/core-native.d.ts +6 -0
- package/dist/react-native/src/core-native.js +316 -0
- package/dist/react-native/src/core-wire.d.ts +55 -0
- package/dist/react-native/src/core-wire.js +1 -0
- package/dist/react-native/src/native-module.d.ts +8 -0
- package/dist/react-native/src/native-module.js +53 -0
- package/dist/rn-shared-build.json +16 -0
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +91 -0
- package/dist/runtime/src/agent.js +137 -0
- package/dist/runtime/src/app-api.d.ts +572 -0
- package/dist/runtime/src/app-api.js +1 -0
- package/dist/runtime/src/cancel.d.ts +9 -0
- package/dist/runtime/src/cancel.js +27 -0
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +247 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -0
- package/dist/runtime/src/core/wasm.d.ts +1 -0
- package/dist/runtime/src/core/wasm.js +2 -0
- package/dist/runtime/src/croche.d.ts +97 -0
- package/dist/runtime/src/croche.js +172 -0
- package/dist/runtime/src/errors.d.ts +33 -0
- package/dist/runtime/src/errors.js +63 -0
- package/dist/runtime/src/events.d.ts +5 -0
- package/dist/runtime/src/events.js +31 -0
- package/dist/runtime/src/generated/app-stream.d.ts +328 -0
- package/dist/runtime/src/generated/app-stream.js +127 -0
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -0
- package/dist/runtime/src/index.native.js +2 -0
- package/dist/runtime/src/json.d.ts +13 -0
- package/dist/runtime/src/json.js +120 -0
- package/dist/runtime/src/native-adapter.d.ts +3 -0
- package/dist/runtime/src/native-adapter.js +30 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +60 -0
- package/dist/runtime/src/pal/platform.d.ts +21 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -0
- package/dist/runtime/src/rn-entry.d.ts +1 -0
- package/dist/runtime/src/rn-entry.js +4 -0
- package/dist/runtime/src/run-tool.d.ts +33 -0
- package/dist/runtime/src/run-tool.js +7 -0
- package/dist/runtime/src/tools.d.ts +35 -0
- package/dist/runtime/src/tools.js +94 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +98 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +122 -0
- package/ios/CoreWireSupport.swift +286 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +49 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +18 -8
- package/scripts/README.md +11 -0
- package/scripts/build-shared.mjs +46 -0
- package/scripts/build.mjs +11 -0
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +8 -6
- package/src/NativeCrocheRuntime.ts +12 -159
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -1,132 +1,4 @@
|
|
|
1
1
|
import Foundation
|
|
2
|
-
#if canImport(CryptoKit)
|
|
3
|
-
import CryptoKit
|
|
4
|
-
#endif
|
|
5
|
-
|
|
6
|
-
public enum DebugVisibility: String, Sendable { case runtime }
|
|
7
|
-
public enum Attestation: String, Sendable { case platform, off }
|
|
8
|
-
// Q9 recommendation: backgroundDelivery is deferred until the per-agent identifier rule.
|
|
9
|
-
public struct OpenOptions: Sendable {
|
|
10
|
-
public var cloudUrl: String?
|
|
11
|
-
public var projectKey: String
|
|
12
|
-
/// App configuration. `temperature`: number 0...2, absent uses a tuned default, `.null` = omit.
|
|
13
|
-
/// Structured calls always omit it. Remote temperature configs require schema 4 / 0.5.3+.
|
|
14
|
-
public var config: JSON
|
|
15
|
-
public var user: String?
|
|
16
|
-
public var handlers: [String: ToolHandler]
|
|
17
|
-
public var language: String?
|
|
18
|
-
public var timeZone: String?
|
|
19
|
-
public var streaming: Bool?
|
|
20
|
-
public var backgroundSync: Bool?
|
|
21
|
-
public var maintenanceIntervalMs: Double?
|
|
22
|
-
public var debugKey: String?
|
|
23
|
-
public var requestTimeoutMs: Double?
|
|
24
|
-
public var maxPendingEvents: Int?
|
|
25
|
-
public var syncIntervalMs: Double?
|
|
26
|
-
public var maintenanceBackoffMs: Double?
|
|
27
|
-
public var retentionBytes: Int?
|
|
28
|
-
public var onUsage: (@Sendable (ProjectUsageEvent) -> Void)?
|
|
29
|
-
public var onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)?
|
|
30
|
-
public var debugVisibility: DebugVisibility?
|
|
31
|
-
public var attestation: Attestation?
|
|
32
|
-
public var projectDirectory: URL?
|
|
33
|
-
public var http: RuntimeHTTP?
|
|
34
|
-
public init(cloudUrl: String? = nil,
|
|
35
|
-
projectKey: String,
|
|
36
|
-
config: JSON,
|
|
37
|
-
user: String? = nil,
|
|
38
|
-
handlers: [String: ToolHandler] = [:],
|
|
39
|
-
language: String? = nil,
|
|
40
|
-
timeZone: String? = nil,
|
|
41
|
-
streaming: Bool? = nil,
|
|
42
|
-
backgroundSync: Bool? = nil,
|
|
43
|
-
maintenanceIntervalMs: Double? = nil,
|
|
44
|
-
debugKey: String? = nil,
|
|
45
|
-
requestTimeoutMs: Double? = nil,
|
|
46
|
-
maxPendingEvents: Int? = nil,
|
|
47
|
-
syncIntervalMs: Double? = nil,
|
|
48
|
-
maintenanceBackoffMs: Double? = nil,
|
|
49
|
-
retentionBytes: Int? = nil,
|
|
50
|
-
onUsage: (@Sendable (ProjectUsageEvent) -> Void)? = nil,
|
|
51
|
-
onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)? = nil,
|
|
52
|
-
debugVisibility: DebugVisibility? = nil,
|
|
53
|
-
attestation: Attestation? = nil,
|
|
54
|
-
projectDirectory: URL? = nil,
|
|
55
|
-
http: RuntimeHTTP? = nil) {
|
|
56
|
-
self.cloudUrl = cloudUrl
|
|
57
|
-
self.projectKey = projectKey
|
|
58
|
-
self.config = config
|
|
59
|
-
self.user = user
|
|
60
|
-
self.handlers = handlers
|
|
61
|
-
self.language = language
|
|
62
|
-
self.timeZone = timeZone
|
|
63
|
-
self.streaming = streaming
|
|
64
|
-
self.backgroundSync = backgroundSync
|
|
65
|
-
self.maintenanceIntervalMs = maintenanceIntervalMs
|
|
66
|
-
self.debugKey = debugKey
|
|
67
|
-
self.requestTimeoutMs = requestTimeoutMs
|
|
68
|
-
self.maxPendingEvents = maxPendingEvents
|
|
69
|
-
self.syncIntervalMs = syncIntervalMs
|
|
70
|
-
self.maintenanceBackoffMs = maintenanceBackoffMs
|
|
71
|
-
self.retentionBytes = retentionBytes
|
|
72
|
-
self.onUsage = onUsage
|
|
73
|
-
self.onDebugEvent = onDebugEvent
|
|
74
|
-
self.debugVisibility = debugVisibility
|
|
75
|
-
self.attestation = attestation
|
|
76
|
-
self.projectDirectory = projectDirectory
|
|
77
|
-
self.http = http
|
|
78
|
-
}
|
|
79
|
-
func hostJSON() -> JSON {
|
|
80
|
-
var host: JSON = .object(["projectKey": .string(projectKey)])
|
|
81
|
-
if let cloudUrl { host["cloudUrl"] = .string(cloudUrl) }
|
|
82
|
-
if let debugKey { host["debugKey"] = .string(debugKey) }
|
|
83
|
-
if let debugVisibility { host["debugVisibility"] = .string(debugVisibility.rawValue) }
|
|
84
|
-
if let requestTimeoutMs { host["requestTimeoutMs"] = .number(requestTimeoutMs) }
|
|
85
|
-
if let maxPendingEvents { host["maxPendingEvents"] = .number(Double(maxPendingEvents)) }
|
|
86
|
-
if let syncIntervalMs { host["syncIntervalMs"] = .number(syncIntervalMs) }
|
|
87
|
-
if let maintenanceBackoffMs { host["maintenanceBackoffMs"] = .number(maintenanceBackoffMs) }
|
|
88
|
-
if let retentionBytes { host["retentionBytes"] = .number(Double(retentionBytes)) }
|
|
89
|
-
return host
|
|
90
|
-
}
|
|
91
|
-
func resolvedLanguage(preferredLanguages: [String] = Locale.preferredLanguages) -> String? {
|
|
92
|
-
language ?? preferredLanguages.first
|
|
93
|
-
}
|
|
94
|
-
func native() throws -> NativeProjectOptions {
|
|
95
|
-
do { _ = try hostJSON().encoded(); _ = try config.encoded() }
|
|
96
|
-
catch { throw CrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
|
|
97
|
-
let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
|
|
98
|
-
let directory = try NativeProjectFiles.directory(projectDirectory: projectDirectory)
|
|
99
|
-
var identity = hostJSON(); identity["user"] = user.map(JSON.string) ?? .null
|
|
100
|
-
let namespace = try CrocheRuntime.identity(config: identity)["storageKey"].string ?? "croche.runtime"
|
|
101
|
-
let zone: TimeZone?
|
|
102
|
-
if let timeZone {
|
|
103
|
-
guard let parsed = TimeZone(identifier: timeZone) else { throw CrocheError("invalid_configuration", "timeZone must name an IANA time zone") }
|
|
104
|
-
zone = parsed
|
|
105
|
-
} else { zone = nil }
|
|
106
|
-
let attestor: (any RuntimeAttestor)?
|
|
107
|
-
#if canImport(DeviceCheck) && os(iOS) && !targetEnvironment(simulator)
|
|
108
|
-
attestor = attestation == .off ? nil : AppAttestAttestor()
|
|
109
|
-
#else
|
|
110
|
-
attestor = nil
|
|
111
|
-
#endif
|
|
112
|
-
let test = NativeProjectFiles.testing
|
|
113
|
-
return NativeProjectOptions(host: hostJSON(), config: config, user: user,
|
|
114
|
-
language: resolvedLanguage(), handlers: handlers, streaming: streaming ?? true,
|
|
115
|
-
backgroundSync: backgroundSync ?? true, maintenanceIntervalMs: maintenanceIntervalMs ?? 60_000,
|
|
116
|
-
storage: { slot in FileRuntimeStorage(url: NativeProjectFiles.file(directory: directory, namespace: namespace, slot: slot)) },
|
|
117
|
-
secretStorage: { slot in
|
|
118
|
-
let key = NativeProjectFiles.key(namespace: namespace, slot: slot)
|
|
119
|
-
if let test { return FileRuntimeSecretStore(url: test.appendingPathComponent(key + ".secrets")) }
|
|
120
|
-
#if canImport(Security) && !os(Linux)
|
|
121
|
-
return KeychainSecretStore(account: key)
|
|
122
|
-
#else
|
|
123
|
-
return FileRuntimeSecretStore(url: directory.appendingPathComponent(key + ".secrets"))
|
|
124
|
-
#endif
|
|
125
|
-
}, attestor: attestor, fetch: http, timeZone: zone,
|
|
126
|
-
records: { test.map { dir in ProjectRecordFiles(directory: { dir }) } ?? records },
|
|
127
|
-
onUsage: onUsage, onDebugEvent: onDebugEvent)
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
2
|
|
|
131
3
|
// Test-only redirection keeps host gates inside their own worktree, out of Keychain/private app storage.
|
|
132
4
|
enum NativeProjectFiles {
|
|
@@ -134,7 +6,7 @@ enum NativeProjectFiles {
|
|
|
134
6
|
static func directory(projectDirectory: URL?) throws -> URL {
|
|
135
7
|
if let testing { return testing }
|
|
136
8
|
#if os(Linux)
|
|
137
|
-
guard let projectDirectory else { throw
|
|
9
|
+
guard let projectDirectory else { throw LegacyCrocheError("storage_error", "This platform requires projectDirectory") }
|
|
138
10
|
return projectDirectory
|
|
139
11
|
#else
|
|
140
12
|
let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
|
@@ -145,30 +17,4 @@ enum NativeProjectFiles {
|
|
|
145
17
|
return url
|
|
146
18
|
#endif
|
|
147
19
|
}
|
|
148
|
-
static func file(directory: URL, namespace: String, slot: String) -> URL {
|
|
149
|
-
directory.appendingPathComponent(key(namespace: namespace, slot: slot) + ".json")
|
|
150
|
-
}
|
|
151
|
-
static func key(namespace: String, slot: String) -> String {
|
|
152
|
-
namespace + ".agent." + slotHash(slot)
|
|
153
|
-
}
|
|
154
|
-
static func slotHash(_ slot: String) -> String {
|
|
155
|
-
#if canImport(CryptoKit)
|
|
156
|
-
SHA256.hash(data: Data(slot.utf8)).map { String(format: "%02x", $0) }.joined()
|
|
157
|
-
#else
|
|
158
|
-
PortableSHA256.hex(Array(slot.utf8))
|
|
159
|
-
#endif
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// Core's maintenance label selects the instance's physical store, never its live handle.
|
|
164
|
-
enum NativeProjectSlot {
|
|
165
|
-
static func isMaintenance(_ label: String) -> Bool {
|
|
166
|
-
(try? JSON(label).array?.first?.string) == "$gc"
|
|
167
|
-
}
|
|
168
|
-
static func storageLabel(_ label: String) -> String {
|
|
169
|
-
guard let parts = try? JSON(label).array, parts.count == 3,
|
|
170
|
-
parts[0].string == "$gc", parts[1].string != nil, parts[2].string != nil else { return label }
|
|
171
|
-
let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
|
|
172
|
-
return String(decoding: try! encoder.encode(JSON.array(Array(parts.dropFirst()))), as: UTF8.self)
|
|
173
|
-
}
|
|
174
20
|
}
|
|
@@ -7,11 +7,11 @@ import Darwin
|
|
|
7
7
|
|
|
8
8
|
// Platform Abstraction Layer. The Rust Core decides; these perform what only the platform
|
|
9
9
|
// can: keep a credential in hardware-backed storage, and vouch for the app binary.
|
|
10
|
-
// See docs/
|
|
10
|
+
// See docs/hld/surface-and-hosts.md.
|
|
11
11
|
|
|
12
12
|
/// Where the Runtime credential lives, apart from the general state file. load returns an
|
|
13
13
|
/// object (empty when nothing is stored). save replaces the whole object atomically.
|
|
14
|
-
|
|
14
|
+
protocol RuntimeSecretStore: Sendable {
|
|
15
15
|
func load() throws -> JSON
|
|
16
16
|
func save(_ secrets: JSON) throws
|
|
17
17
|
/// Removes the credential item for real; absence succeeds. No default implementation.
|
|
@@ -19,13 +19,13 @@ public protocol RuntimeSecretStore: Sendable {
|
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
/// The platform's attestation of this app binary, bound to `clientDataHash`.
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
struct RuntimeAttestation: Sendable {
|
|
23
|
+
let token: String
|
|
24
|
+
let keyId: String?
|
|
25
|
+
init(token: String, keyId: String?) { self.token = token; self.keyId = keyId }
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
protocol RuntimeAttestor: Sendable {
|
|
29
29
|
/// "ios-app-attest" or "android-play-integrity"; declared to the Core in config.
|
|
30
30
|
var platform: String { get }
|
|
31
31
|
/// `clientDataHash` is SHA-256(`clientData`), exactly as Cloud recomputes it.
|
|
@@ -37,7 +37,7 @@ public protocol RuntimeAttestor: Sendable {
|
|
|
37
37
|
/// pending note after every change, at every open, and after every `deliverDue()`. The work it
|
|
38
38
|
/// registers runs `deliverDue()`: inexact, never before that time. No exact alarms,
|
|
39
39
|
/// notifications or permissions.
|
|
40
|
-
|
|
40
|
+
protocol RuntimeScheduler: Sendable {
|
|
41
41
|
/// Replaces any earlier request with one at or after `earliest`. Idempotent: one request at a
|
|
42
42
|
/// time, by identifier. Throw `CrocheError("not_configured", ...)` when the app is not set up
|
|
43
43
|
/// for it: the Runtime reports `schedule.degraded` with that code and still delivers while
|
|
@@ -54,7 +54,7 @@ public protocol RuntimeScheduler: Sendable {
|
|
|
54
54
|
/// this at most once per successful `attach`, however often it is closed.
|
|
55
55
|
func detach()
|
|
56
56
|
}
|
|
57
|
-
|
|
57
|
+
extension RuntimeScheduler {
|
|
58
58
|
func attach() throws {}
|
|
59
59
|
func detach() {}
|
|
60
60
|
}
|
|
@@ -72,7 +72,7 @@ final class SchedulerClaims: @unchecked Sendable {
|
|
|
72
72
|
func claim(_ identity: String, by: AnyObject) throws {
|
|
73
73
|
try lock.withLock {
|
|
74
74
|
if holders[identity] != nil {
|
|
75
|
-
throw
|
|
75
|
+
throw LegacyCrocheError("scheduler_conflict", "Another open Runtime uses the \(what) \(identity); give each Runtime its own, or close it first")
|
|
76
76
|
}
|
|
77
77
|
holders[identity] = by
|
|
78
78
|
}
|
|
@@ -81,56 +81,30 @@ final class SchedulerClaims: @unchecked Sendable {
|
|
|
81
81
|
func held(_ identity: String) -> Bool { lock.withLock { holders[identity] != nil } }
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
/// One background run the OS granted (a BGTaskScheduler launch): opens or reaches the app's
|
|
85
|
-
/// Runtime, delivers what is due, and reports whether that finished. `expire()` (the OS ending
|
|
86
|
-
/// background time) cancels this run's own delivery, waiting behind another turn or running,
|
|
87
|
-
/// never another turn of the Runtime (Atlas, #323 P1-1); after the run ended it does nothing.
|
|
88
|
-
/// The delivery's notes stay pending, registered again, for the next run or foreground.
|
|
89
|
-
final class BackgroundDelivery: @unchecked Sendable {
|
|
90
|
-
private let open: @Sendable () async throws -> CrocheRuntime
|
|
91
|
-
private let lock = NSLock()
|
|
92
|
-
private var task: Task<Void, Never>?
|
|
93
|
-
private var expired = false
|
|
94
|
-
init(open: @escaping @Sendable () async throws -> CrocheRuntime) { self.open = open }
|
|
95
|
-
func start(_ done: @escaping @Sendable (Bool) -> Void) {
|
|
96
|
-
let open = self.open
|
|
97
|
-
let task = Task {
|
|
98
|
-
let runtime: CrocheRuntime
|
|
99
|
-
do { runtime = try await open() } catch { done(false); return }
|
|
100
|
-
// Cancelling this Task cancels this delivery only (`deliverDue`). Expired before it
|
|
101
|
-
// began, it is cancelled at once, and its notes are registered again.
|
|
102
|
-
let result = try? await runtime.deliverDue()
|
|
103
|
-
done(!Task.isCancelled && (result.map { $0["ran"].bool != true || $0["delivered"].bool == true } ?? false))
|
|
104
|
-
}
|
|
105
|
-
if lock.withLock({ self.task = task; return expired }) { task.cancel() }
|
|
106
|
-
}
|
|
107
|
-
func expire() { lock.withLock { expired = true; return task }?.cancel() }
|
|
108
|
-
}
|
|
109
|
-
|
|
110
84
|
/// A 0600 file beside the state file. For hosts without a secret store (Linux, tests,
|
|
111
85
|
/// command-line tools). On iOS and macOS apps, use KeychainSecretStore.
|
|
112
|
-
|
|
86
|
+
final class FileRuntimeSecretStore: RuntimeSecretStore, @unchecked Sendable {
|
|
113
87
|
private let url: URL
|
|
114
88
|
private let mutex = NSLock()
|
|
115
|
-
|
|
116
|
-
|
|
89
|
+
init(url: URL) { self.url = url }
|
|
90
|
+
func load() throws -> JSON {
|
|
117
91
|
mutex.lock(); defer { mutex.unlock() }
|
|
118
92
|
guard FileManager.default.fileExists(atPath: url.path) else { return .object([:]) }
|
|
119
93
|
let saved: JSON
|
|
120
94
|
do { saved = try JSON(data: Data(contentsOf: url)) }
|
|
121
|
-
catch { throw
|
|
122
|
-
guard saved.object != nil else { throw
|
|
95
|
+
catch { throw LegacyCrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again") }
|
|
96
|
+
guard saved.object != nil else { throw LegacyCrocheError("corrupt_store", "Runtime credentials must be an object") }
|
|
123
97
|
return saved
|
|
124
98
|
}
|
|
125
|
-
|
|
99
|
+
func save(_ secrets: JSON) throws {
|
|
126
100
|
mutex.lock(); defer { mutex.unlock() }
|
|
127
101
|
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
128
102
|
try secrets.encoded().write(to: url, options: .atomic)
|
|
129
103
|
_ = chmod(url.path, S_IRUSR | S_IWUSR)
|
|
130
104
|
}
|
|
131
|
-
|
|
105
|
+
func remove() throws {
|
|
132
106
|
try mutex.withLock {
|
|
133
|
-
if unlink(url.path) != 0 && errno != ENOENT { throw
|
|
107
|
+
if unlink(url.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Could not remove Runtime credentials") }
|
|
134
108
|
}
|
|
135
109
|
}
|
|
136
110
|
|
|
@@ -143,11 +117,11 @@ import Security
|
|
|
143
117
|
/// after the first unlock, never synced or restored to another device. It survives app
|
|
144
118
|
/// reinstall on iOS, so a reinstall keeps the same Runtime (and its credit) rather than
|
|
145
119
|
/// minting a new one.
|
|
146
|
-
|
|
120
|
+
final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable {
|
|
147
121
|
private let service: String
|
|
148
122
|
private let account: String
|
|
149
123
|
/// `account` should be the Runtime's storage key, so each agent's store has its own item.
|
|
150
|
-
|
|
124
|
+
init(service: String = "ai.croche.runtime", account: String) {
|
|
151
125
|
self.service = service; self.account = account
|
|
152
126
|
}
|
|
153
127
|
private var query: [String: Any] {
|
|
@@ -155,7 +129,7 @@ public final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable
|
|
|
155
129
|
kSecAttrService as String: service,
|
|
156
130
|
kSecAttrAccount as String: account]
|
|
157
131
|
}
|
|
158
|
-
|
|
132
|
+
func load() throws -> JSON {
|
|
159
133
|
var lookup = query
|
|
160
134
|
lookup[kSecReturnData as String] = true
|
|
161
135
|
lookup[kSecMatchLimit as String] = kSecMatchLimitOne
|
|
@@ -163,28 +137,28 @@ public final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable
|
|
|
163
137
|
let status = SecItemCopyMatching(lookup as CFDictionary, &item)
|
|
164
138
|
if status == errSecItemNotFound { return .object([:]) }
|
|
165
139
|
guard status == errSecSuccess, let data = item as? Data else {
|
|
166
|
-
throw
|
|
140
|
+
throw LegacyCrocheError("storage_error", "Keychain read failed (\(status))")
|
|
167
141
|
}
|
|
168
142
|
guard let saved = try? JSON(data: data), saved.object != nil else {
|
|
169
|
-
throw
|
|
143
|
+
throw LegacyCrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again")
|
|
170
144
|
}
|
|
171
145
|
return saved
|
|
172
146
|
}
|
|
173
|
-
|
|
147
|
+
func save(_ secrets: JSON) throws {
|
|
174
148
|
let data = try secrets.encoded()
|
|
175
149
|
let update = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)
|
|
176
150
|
if update == errSecSuccess { return }
|
|
177
|
-
guard update == errSecItemNotFound else { throw
|
|
151
|
+
guard update == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(update))") }
|
|
178
152
|
var add = query
|
|
179
153
|
add[kSecValueData as String] = data
|
|
180
154
|
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
|
181
155
|
let status = SecItemAdd(add as CFDictionary, nil)
|
|
182
|
-
guard status == errSecSuccess else { throw
|
|
156
|
+
guard status == errSecSuccess else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(status))") }
|
|
183
157
|
}
|
|
184
|
-
|
|
158
|
+
func remove() throws {
|
|
185
159
|
let status = SecItemDelete(query as CFDictionary)
|
|
186
160
|
guard status == errSecSuccess || status == errSecItemNotFound else {
|
|
187
|
-
throw
|
|
161
|
+
throw LegacyCrocheError("storage_error", "Keychain delete failed (\(status))")
|
|
188
162
|
}
|
|
189
163
|
}
|
|
190
164
|
|
|
@@ -197,13 +171,13 @@ import DeviceCheck
|
|
|
197
171
|
/// Apple App Attest. Each registration generates a fresh key and attests it against the
|
|
198
172
|
/// Cloud challenge; Cloud checks the chain to Apple's root, the app id, and the nonce.
|
|
199
173
|
/// Simulators cannot attest: use a development project with attestation off there.
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
174
|
+
struct AppAttestAttestor: RuntimeAttestor {
|
|
175
|
+
let platform = "ios-app-attest"
|
|
176
|
+
init() {}
|
|
177
|
+
func attest(clientData: String, clientDataHash: Data) async throws -> RuntimeAttestation {
|
|
204
178
|
let service = DCAppAttestService.shared
|
|
205
179
|
guard service.isSupported else {
|
|
206
|
-
throw
|
|
180
|
+
throw LegacyCrocheError("attestation_unsupported", "App Attest is not available here (simulators cannot attest)")
|
|
207
181
|
}
|
|
208
182
|
let keyId = try await service.generateKey()
|
|
209
183
|
let object = try await service.attestKey(keyId, clientDataHash: clientDataHash)
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(BackgroundTasks) && os(iOS)
|
|
3
|
+
import BackgroundTasks
|
|
4
|
+
#endif
|
|
5
|
+
#if canImport(DeviceCheck) && os(iOS)
|
|
6
|
+
import DeviceCheck
|
|
7
|
+
#endif
|
|
8
|
+
|
|
9
|
+
// MARK: Background (APP-API: registerBackground, OS identifier ai.croche.background)
|
|
10
|
+
|
|
11
|
+
/// The OS's deferred work for the background wake: one request at a time.
|
|
12
|
+
protocol BackgroundRequests: Sendable {
|
|
13
|
+
/// Replaces any earlier request with one at or after `earliest`. A refusal throws
|
|
14
|
+
/// `CorePalError` with `capability_unsupported` (the app is not set up for it) or
|
|
15
|
+
/// `host_unavailable` (the OS will not run it now); Core reports it and still delivers in the
|
|
16
|
+
/// foreground and at the next open.
|
|
17
|
+
func submit(earliest: Date) throws
|
|
18
|
+
/// Nothing is pending: withdraw the request.
|
|
19
|
+
func cancel()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
#if canImport(BackgroundTasks) && os(iOS)
|
|
23
|
+
/// BGTaskScheduler. App setup: `ai.croche.background` in `BGTaskSchedulerPermittedIdentifiers`
|
|
24
|
+
/// (Info.plist) and the Background fetch mode.
|
|
25
|
+
struct AppRefreshRequests: BackgroundRequests {
|
|
26
|
+
static let identifier = "ai.croche.background"
|
|
27
|
+
func submit(earliest: Date) throws {
|
|
28
|
+
let request = BGAppRefreshTaskRequest(identifier: Self.identifier)
|
|
29
|
+
request.earliestBeginDate = earliest
|
|
30
|
+
do { try BGTaskScheduler.shared.submit(request) }
|
|
31
|
+
catch let error as BGTaskScheduler.Error where error.code == .notPermitted {
|
|
32
|
+
throw CorePalError.Failure(code: "capability_unsupported",
|
|
33
|
+
detail: "Add \(Self.identifier) to BGTaskSchedulerPermittedIdentifiers and enable Background fetch.")
|
|
34
|
+
} catch {
|
|
35
|
+
throw CorePalError.Failure(code: "host_unavailable", detail: "BGTaskScheduler refused the request: \(error)")
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
func cancel() { BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: Self.identifier) }
|
|
39
|
+
}
|
|
40
|
+
#endif
|
|
41
|
+
|
|
42
|
+
/// The pending set Core hands `schedule` (`[{id, at}]`, `at` ISO UTC): a timer while the app
|
|
43
|
+
/// runs, and the OS request for after. The timer fires `onDue` at the earliest `at`, never
|
|
44
|
+
/// before it and once per time; with no `onDue` yet it arms nothing (the notes still come at the
|
|
45
|
+
/// next `deliverDue`). The OS request follows the earliest `at` and is withdrawn when nothing is
|
|
46
|
+
/// pending. A refused request fails `schedule`; the timer stays armed.
|
|
47
|
+
final class PlatformSchedule: @unchecked Sendable {
|
|
48
|
+
private let requests: (any BackgroundRequests)?
|
|
49
|
+
private let clock: @Sendable () -> Double
|
|
50
|
+
private let lock = NSLock()
|
|
51
|
+
private var target: Double?, fired: Double?, timer: DispatchWorkItem?, closed = false
|
|
52
|
+
private var due: (@Sendable () -> Void)?
|
|
53
|
+
|
|
54
|
+
init(requests: (any BackgroundRequests)?, clock: @escaping @Sendable () -> Double = { Date().timeIntervalSince1970 * 1000 }) {
|
|
55
|
+
self.requests = requests; self.clock = clock
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// What runs a due delivery in this process (the factory sets it to `deliverDue`).
|
|
59
|
+
var onDue: (@Sendable () -> Void)? {
|
|
60
|
+
get { lock.withLock { due } }
|
|
61
|
+
set { lock.withLock { due = newValue }; arm() }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
func apply(_ entries: String) throws {
|
|
65
|
+
guard let list = try? JSON(entries).array else {
|
|
66
|
+
throw CorePalError.Failure(code: "internal", detail: "Core's schedule entries are malformed.")
|
|
67
|
+
}
|
|
68
|
+
let times = try list.map { entry -> Double in
|
|
69
|
+
guard let text = entry["at"].string, let at = Self.epochMs(text) else {
|
|
70
|
+
throw CorePalError.Failure(code: "internal", detail: "Core's schedule entry has no valid at.")
|
|
71
|
+
}
|
|
72
|
+
return at
|
|
73
|
+
}
|
|
74
|
+
let earliest = times.min()
|
|
75
|
+
lock.withLock { target = earliest }
|
|
76
|
+
arm()
|
|
77
|
+
guard let requests else { return }
|
|
78
|
+
if let earliest { try requests.submit(earliest: Date(timeIntervalSince1970: earliest / 1000)) } else { requests.cancel() }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
func close() { lock.withLock { closed = true; timer?.cancel(); timer = nil } }
|
|
82
|
+
|
|
83
|
+
/// One timer at the target; a timer that ends early re-arms, and a target already fired
|
|
84
|
+
/// never fires again.
|
|
85
|
+
private func arm() {
|
|
86
|
+
let now = clock()
|
|
87
|
+
let work: DispatchWorkItem? = lock.withLock {
|
|
88
|
+
timer?.cancel(); timer = nil
|
|
89
|
+
guard !closed, due != nil, let target, !(fired.map { target <= $0 } ?? false) else { return nil }
|
|
90
|
+
let item = DispatchWorkItem { [weak self] in self?.fire(target) }
|
|
91
|
+
timer = item
|
|
92
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(Int(max(0, target - now).rounded(.up))), execute: item)
|
|
93
|
+
return item
|
|
94
|
+
}
|
|
95
|
+
_ = work
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private func fire(_ at: Double) {
|
|
99
|
+
if clock() < at { arm(); return }
|
|
100
|
+
let run: (@Sendable () -> Void)? = lock.withLock {
|
|
101
|
+
guard !closed, target == at, !(fired.map { at <= $0 } ?? false) else { return nil }
|
|
102
|
+
fired = at; timer = nil
|
|
103
|
+
return due
|
|
104
|
+
}
|
|
105
|
+
run?()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
static func epochMs(_ text: String) -> Double? {
|
|
109
|
+
let parse = ISO8601DateFormatter()
|
|
110
|
+
parse.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
111
|
+
if let date = parse.date(from: text) { return date.timeIntervalSince1970 * 1000 }
|
|
112
|
+
parse.formatOptions = [.withInternetDateTime]
|
|
113
|
+
return parse.date(from: text).map { $0.timeIntervalSince1970 * 1000 }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// One OS launch of the background task. `deliver` runs once (Core's `deliverDue`); the OS's
|
|
118
|
+
/// expiration cancels THIS launch's delivery only, including one that has not begun, and a
|
|
119
|
+
/// launch that already finished owns nothing to cancel. `done(true)` = it finished delivering.
|
|
120
|
+
final class BackgroundLaunch: @unchecked Sendable {
|
|
121
|
+
private let deliver: @Sendable () async -> Bool
|
|
122
|
+
private let lock = NSLock()
|
|
123
|
+
private var task: Task<Void, Never>?, expired = false
|
|
124
|
+
init(deliver: @escaping @Sendable () async -> Bool) { self.deliver = deliver }
|
|
125
|
+
|
|
126
|
+
func start(_ done: @escaping @Sendable (Bool) -> Void) {
|
|
127
|
+
let deliver = self.deliver
|
|
128
|
+
let started = lock.withLock { () -> Bool in
|
|
129
|
+
guard !expired else { return false }
|
|
130
|
+
task = Task {
|
|
131
|
+
let finished = await deliver()
|
|
132
|
+
done(finished && !Task.isCancelled)
|
|
133
|
+
}
|
|
134
|
+
return true
|
|
135
|
+
}
|
|
136
|
+
if !started { done(false) }
|
|
137
|
+
}
|
|
138
|
+
func expire() { lock.withLock { expired = true; return task }?.cancel() }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/// One OS launch as the handler sees it: the OS's expiration, and the completion it waits for.
|
|
142
|
+
protocol BackgroundLaunchTask: AnyObject, Sendable {
|
|
143
|
+
func onExpire(_ body: @escaping @Sendable () -> Void)
|
|
144
|
+
func complete(success: Bool)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/// The OS's launch handlers for the background wake.
|
|
148
|
+
protocol BackgroundLaunches: Sendable {
|
|
149
|
+
/// Installs `handler` for every launch of `identifier`; false = the OS refused it.
|
|
150
|
+
func register(_ identifier: String, _ handler: @escaping @Sendable (any BackgroundLaunchTask) -> Void) -> Bool
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
#if canImport(BackgroundTasks) && os(iOS)
|
|
154
|
+
/// BGTaskScheduler. It refuses (false) an identifier missing from
|
|
155
|
+
/// `BGTaskSchedulerPermittedIdentifiers`; registering after launch finishes is an app bug the OS
|
|
156
|
+
/// traps, so `Croche.registerBackground` runs before `application(_:didFinishLaunchingWithOptions:)` returns.
|
|
157
|
+
struct AppRefreshLaunches: BackgroundLaunches {
|
|
158
|
+
func register(_ identifier: String, _ handler: @escaping @Sendable (any BackgroundLaunchTask) -> Void) -> Bool {
|
|
159
|
+
BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { handler(OSLaunchTask($0)) }
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
private final class OSLaunchTask: BackgroundLaunchTask, @unchecked Sendable {
|
|
163
|
+
private let task: BGTask
|
|
164
|
+
init(_ task: BGTask) { self.task = task }
|
|
165
|
+
func onExpire(_ body: @escaping @Sendable () -> Void) { task.expirationHandler = body }
|
|
166
|
+
func complete(success: Bool) { task.setTaskCompleted(success: success) }
|
|
167
|
+
}
|
|
168
|
+
#endif
|
|
169
|
+
|
|
170
|
+
/// Core's `register_background`: install the launch handler for Core's identifier, then submit
|
|
171
|
+
/// the first request (Core's `schedule` moves it later). Each launch runs Core's wake once; the
|
|
172
|
+
/// OS's expiration cancels it. Any refusal is `host_unavailable` (Keel 22:08Z), never a silent Ok;
|
|
173
|
+
/// a platform with no OS launch is `capability_unsupported`. The OS keeps the first handler for
|
|
174
|
+
/// the process, so a later registration only replaces the wake it runs.
|
|
175
|
+
final class PlatformRegistration: @unchecked Sendable {
|
|
176
|
+
private let launches: (any BackgroundLaunches)?
|
|
177
|
+
private let requests: (any BackgroundRequests)?
|
|
178
|
+
private let lock = NSLock()
|
|
179
|
+
private var installed: Set<String> = [], wakes: [String: CoreBackgroundWake] = [:]
|
|
180
|
+
|
|
181
|
+
init(launches: (any BackgroundLaunches)?, requests: (any BackgroundRequests)?) {
|
|
182
|
+
self.launches = launches; self.requests = requests
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
func register(_ identifier: String, _ wake: CoreBackgroundWake) throws {
|
|
186
|
+
guard let launches else {
|
|
187
|
+
throw CorePalError.Failure(code: "capability_unsupported", detail: "This platform has no OS background launch.")
|
|
188
|
+
}
|
|
189
|
+
let install = lock.withLock { () -> Bool in
|
|
190
|
+
wakes[identifier] = wake
|
|
191
|
+
return !installed.contains(identifier)
|
|
192
|
+
}
|
|
193
|
+
if install {
|
|
194
|
+
// The OS keeps the handler for the process, so it keeps this registration too.
|
|
195
|
+
guard launches.register(identifier, { task in self.launch(identifier, task) }) else {
|
|
196
|
+
lock.withLock { _ = wakes.removeValue(forKey: identifier) }
|
|
197
|
+
throw CorePalError.Failure(code: "host_unavailable",
|
|
198
|
+
detail: "The OS refused the launch handler for \(identifier): list it in BGTaskSchedulerPermittedIdentifiers and register before launch finishes.")
|
|
199
|
+
}
|
|
200
|
+
lock.withLock { _ = installed.insert(identifier) }
|
|
201
|
+
}
|
|
202
|
+
do { try requests?.submit(earliest: Date()) } catch let CorePalError.Failure(_, detail) {
|
|
203
|
+
throw CorePalError.Failure(code: "host_unavailable", detail: detail)
|
|
204
|
+
} catch {
|
|
205
|
+
throw CorePalError.Failure(code: "host_unavailable", detail: "The OS refused the request: \(error)")
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private func launch(_ identifier: String, _ task: any BackgroundLaunchTask) {
|
|
210
|
+
guard let wake = lock.withLock({ wakes[identifier] }) else { task.complete(success: false); return }
|
|
211
|
+
let cancel = CancelToken()
|
|
212
|
+
let launch = BackgroundLaunch {
|
|
213
|
+
if Task.isCancelled { return false }
|
|
214
|
+
return await withCheckedContinuation { (done: CheckedContinuation<Bool, Never>) in
|
|
215
|
+
DispatchQueue.global().async { done.resume(returning: (try? wake.run(deadlineMs: nil, cancel: cancel)) != nil) }
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
task.onExpire { cancel.cancel(); launch.expire() }
|
|
219
|
+
launch.start { task.complete(success: $0) }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// MARK: Attestation (ARCHITECTURE §2: a PAL effect)
|
|
224
|
+
|
|
225
|
+
/// The platform's attestation of this app binary, bound to `clientDataHash`.
|
|
226
|
+
protocol PlatformAttestor: Sendable {
|
|
227
|
+
/// What Core declares: "ios-app-attest".
|
|
228
|
+
var platform: String { get }
|
|
229
|
+
func attest(clientData: String, clientDataHash: Data) async throws -> (token: String, keyId: String?)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
#if canImport(DeviceCheck) && os(iOS)
|
|
233
|
+
/// Apple App Attest: a fresh key per registration, attested against Cloud's challenge.
|
|
234
|
+
/// Simulators cannot attest (`attestation_unsupported`).
|
|
235
|
+
struct AppAttest: PlatformAttestor {
|
|
236
|
+
let platform = "ios-app-attest"
|
|
237
|
+
static var supported: Bool { DCAppAttestService.shared.isSupported }
|
|
238
|
+
func attest(clientData: String, clientDataHash: Data) async throws -> (token: String, keyId: String?) {
|
|
239
|
+
let service = DCAppAttestService.shared
|
|
240
|
+
guard service.isSupported else {
|
|
241
|
+
throw CorePalError.Failure(code: "attestation_unsupported", detail: "App Attest is not available here (simulators cannot attest).")
|
|
242
|
+
}
|
|
243
|
+
do {
|
|
244
|
+
let keyId = try await service.generateKey()
|
|
245
|
+
let object = try await service.attestKey(keyId, clientDataHash: clientDataHash)
|
|
246
|
+
return (object.base64EncodedString(), keyId)
|
|
247
|
+
} catch {
|
|
248
|
+
throw CorePalError.Failure(code: "attestation_failed", detail: "App Attest failed: \(error)")
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
#endif
|
|
253
|
+
|
|
254
|
+
enum PlatformAttestation {
|
|
255
|
+
/// Core's attest effect (`{clientData, clientDataHash, platform}`) through `attestor`, bounded
|
|
256
|
+
/// by `timeoutMs`. No attestor: `attestation_unavailable`.
|
|
257
|
+
static func run(_ attestor: (any PlatformAttestor)?, request: String, timeoutMs: UInt64) throws -> String {
|
|
258
|
+
guard let attestor else {
|
|
259
|
+
throw CorePalError.Failure(code: "attestation_unavailable", detail: "This host cannot attest.")
|
|
260
|
+
}
|
|
261
|
+
let call = try? JSON(request)
|
|
262
|
+
// A malformed call is Core's bug, not an attestation fact.
|
|
263
|
+
guard let clientData = call?["clientData"].string, let hash = base64URLDecode(call?["clientDataHash"].string ?? "") else {
|
|
264
|
+
throw CorePalError.Failure(code: "internal", detail: "Core's attest effect is malformed.")
|
|
265
|
+
}
|
|
266
|
+
let box = AttestBox(), done = DispatchSemaphore(value: 0)
|
|
267
|
+
let task = Task.detached {
|
|
268
|
+
do { box.set(.success(try await attestor.attest(clientData: clientData, clientDataHash: hash))) }
|
|
269
|
+
catch { box.set(.failure(error)) }
|
|
270
|
+
done.signal()
|
|
271
|
+
}
|
|
272
|
+
guard done.wait(timeout: .now() + .milliseconds(Int(min(timeoutMs, UInt64(Int.max))))) == .success else {
|
|
273
|
+
task.cancel()
|
|
274
|
+
throw CorePalError.Failure(code: "attestation_timeout", detail: "The attestor did not answer in \(timeoutMs) ms.")
|
|
275
|
+
}
|
|
276
|
+
let proof: (token: String, keyId: String?)
|
|
277
|
+
do { proof = try box.get() } catch { throw effectFailure(error) }
|
|
278
|
+
let reply: JSON = .object(["platform": .string(attestor.platform), "token": .string(proof.token),
|
|
279
|
+
"keyId": proof.keyId.map(JSON.string) ?? .null])
|
|
280
|
+
return String(decoding: try reply.encoded(), as: UTF8.self)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private final class AttestBox: @unchecked Sendable {
|
|
285
|
+
private let lock = NSLock()
|
|
286
|
+
private var value: Result<(token: String, keyId: String?), Error>?
|
|
287
|
+
func set(_ result: Result<(token: String, keyId: String?), Error>) { lock.withLock { value = result } }
|
|
288
|
+
func get() throws -> (token: String, keyId: String?) { try lock.withLock { value! }.get() }
|
|
289
|
+
}
|