@h1r-ai/croche-react-native 0.5.4 → 0.6.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/README.md +69 -458
- package/THIRD-PARTY-NOTICES +7 -8
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -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/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -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/WorkManagerScheduler.kt +8 -8
- 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 +121 -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/AndroidStoragePal.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -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 +31 -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 +128 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -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 +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -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/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 +3 -0
- package/dist/react-native/src/core-native.js +193 -0
- package/dist/react-native/src/core-wire.d.ts +38 -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/agent.d.ts +43 -0
- package/dist/runtime/src/agent.js +75 -0
- package/dist/runtime/src/app-api.d.ts +284 -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 +24 -0
- package/dist/runtime/src/core/port.d.ts +234 -0
- package/dist/runtime/src/core/port.js +1 -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 +42 -0
- package/dist/runtime/src/croche.js +111 -0
- package/dist/runtime/src/errors.d.ts +26 -0
- package/dist/runtime/src/errors.js +49 -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 +174 -0
- package/dist/runtime/src/generated/app-stream.js +124 -0
- package/dist/runtime/src/index.native.d.ts +21 -0
- package/dist/runtime/src/index.native.js +8 -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 +24 -0
- package/dist/runtime/src/pal/codec.d.ts +15 -0
- package/dist/runtime/src/pal/codec.js +52 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +35 -0
- package/dist/runtime/src/pal/platform.d.ts +16 -0
- package/dist/runtime/src/pal/platform.js +7 -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 +19 -0
- package/dist/runtime/src/tools.js +70 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +93 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +92 -0
- package/ios/CoreWireSupport.swift +111 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +46 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
- 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 +1342 -218
- 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/vendor-native.sh +5 -4
- 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/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- 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
|
@@ -11,7 +11,7 @@ import Darwin
|
|
|
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
|
}
|
|
@@ -87,15 +87,15 @@ final class SchedulerClaims: @unchecked Sendable {
|
|
|
87
87
|
/// never another turn of the Runtime (Atlas, #323 P1-1); after the run ended it does nothing.
|
|
88
88
|
/// The delivery's notes stay pending, registered again, for the next run or foreground.
|
|
89
89
|
final class BackgroundDelivery: @unchecked Sendable {
|
|
90
|
-
private let open: @Sendable () async throws ->
|
|
90
|
+
private let open: @Sendable () async throws -> AgentEngine
|
|
91
91
|
private let lock = NSLock()
|
|
92
92
|
private var task: Task<Void, Never>?
|
|
93
93
|
private var expired = false
|
|
94
|
-
init(open: @escaping @Sendable () async throws ->
|
|
94
|
+
init(open: @escaping @Sendable () async throws -> AgentEngine) { self.open = open }
|
|
95
95
|
func start(_ done: @escaping @Sendable (Bool) -> Void) {
|
|
96
96
|
let open = self.open
|
|
97
97
|
let task = Task {
|
|
98
|
-
let runtime:
|
|
98
|
+
let runtime: AgentEngine
|
|
99
99
|
do { runtime = try await open() } catch { done(false); return }
|
|
100
100
|
// Cancelling this Task cancels this delivery only (`deliverDue`). Expired before it
|
|
101
101
|
// began, it is cancelled at once, and its notes are registered again.
|
|
@@ -109,28 +109,28 @@ final class BackgroundDelivery: @unchecked Sendable {
|
|
|
109
109
|
|
|
110
110
|
/// A 0600 file beside the state file. For hosts without a secret store (Linux, tests,
|
|
111
111
|
/// command-line tools). On iOS and macOS apps, use KeychainSecretStore.
|
|
112
|
-
|
|
112
|
+
final class FileRuntimeSecretStore: RuntimeSecretStore, @unchecked Sendable {
|
|
113
113
|
private let url: URL
|
|
114
114
|
private let mutex = NSLock()
|
|
115
|
-
|
|
116
|
-
|
|
115
|
+
init(url: URL) { self.url = url }
|
|
116
|
+
func load() throws -> JSON {
|
|
117
117
|
mutex.lock(); defer { mutex.unlock() }
|
|
118
118
|
guard FileManager.default.fileExists(atPath: url.path) else { return .object([:]) }
|
|
119
119
|
let saved: JSON
|
|
120
120
|
do { saved = try JSON(data: Data(contentsOf: url)) }
|
|
121
|
-
catch { throw
|
|
122
|
-
guard saved.object != nil else { throw
|
|
121
|
+
catch { throw LegacyCrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again") }
|
|
122
|
+
guard saved.object != nil else { throw LegacyCrocheError("corrupt_store", "Runtime credentials must be an object") }
|
|
123
123
|
return saved
|
|
124
124
|
}
|
|
125
|
-
|
|
125
|
+
func save(_ secrets: JSON) throws {
|
|
126
126
|
mutex.lock(); defer { mutex.unlock() }
|
|
127
127
|
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
128
128
|
try secrets.encoded().write(to: url, options: .atomic)
|
|
129
129
|
_ = chmod(url.path, S_IRUSR | S_IWUSR)
|
|
130
130
|
}
|
|
131
|
-
|
|
131
|
+
func remove() throws {
|
|
132
132
|
try mutex.withLock {
|
|
133
|
-
if unlink(url.path) != 0 && errno != ENOENT { throw
|
|
133
|
+
if unlink(url.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Could not remove Runtime credentials") }
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
136
|
|
|
@@ -143,11 +143,11 @@ import Security
|
|
|
143
143
|
/// after the first unlock, never synced or restored to another device. It survives app
|
|
144
144
|
/// reinstall on iOS, so a reinstall keeps the same Runtime (and its credit) rather than
|
|
145
145
|
/// minting a new one.
|
|
146
|
-
|
|
146
|
+
final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable {
|
|
147
147
|
private let service: String
|
|
148
148
|
private let account: String
|
|
149
149
|
/// `account` should be the Runtime's storage key, so each agent's store has its own item.
|
|
150
|
-
|
|
150
|
+
init(service: String = "ai.croche.runtime", account: String) {
|
|
151
151
|
self.service = service; self.account = account
|
|
152
152
|
}
|
|
153
153
|
private var query: [String: Any] {
|
|
@@ -155,7 +155,7 @@ public final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable
|
|
|
155
155
|
kSecAttrService as String: service,
|
|
156
156
|
kSecAttrAccount as String: account]
|
|
157
157
|
}
|
|
158
|
-
|
|
158
|
+
func load() throws -> JSON {
|
|
159
159
|
var lookup = query
|
|
160
160
|
lookup[kSecReturnData as String] = true
|
|
161
161
|
lookup[kSecMatchLimit as String] = kSecMatchLimitOne
|
|
@@ -163,28 +163,28 @@ public final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable
|
|
|
163
163
|
let status = SecItemCopyMatching(lookup as CFDictionary, &item)
|
|
164
164
|
if status == errSecItemNotFound { return .object([:]) }
|
|
165
165
|
guard status == errSecSuccess, let data = item as? Data else {
|
|
166
|
-
throw
|
|
166
|
+
throw LegacyCrocheError("storage_error", "Keychain read failed (\(status))")
|
|
167
167
|
}
|
|
168
168
|
guard let saved = try? JSON(data: data), saved.object != nil else {
|
|
169
|
-
throw
|
|
169
|
+
throw LegacyCrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again")
|
|
170
170
|
}
|
|
171
171
|
return saved
|
|
172
172
|
}
|
|
173
|
-
|
|
173
|
+
func save(_ secrets: JSON) throws {
|
|
174
174
|
let data = try secrets.encoded()
|
|
175
175
|
let update = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)
|
|
176
176
|
if update == errSecSuccess { return }
|
|
177
|
-
guard update == errSecItemNotFound else { throw
|
|
177
|
+
guard update == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(update))") }
|
|
178
178
|
var add = query
|
|
179
179
|
add[kSecValueData as String] = data
|
|
180
180
|
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
|
181
181
|
let status = SecItemAdd(add as CFDictionary, nil)
|
|
182
|
-
guard status == errSecSuccess else { throw
|
|
182
|
+
guard status == errSecSuccess else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(status))") }
|
|
183
183
|
}
|
|
184
|
-
|
|
184
|
+
func remove() throws {
|
|
185
185
|
let status = SecItemDelete(query as CFDictionary)
|
|
186
186
|
guard status == errSecSuccess || status == errSecItemNotFound else {
|
|
187
|
-
throw
|
|
187
|
+
throw LegacyCrocheError("storage_error", "Keychain delete failed (\(status))")
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
190
|
|
|
@@ -197,13 +197,13 @@ import DeviceCheck
|
|
|
197
197
|
/// Apple App Attest. Each registration generates a fresh key and attests it against the
|
|
198
198
|
/// Cloud challenge; Cloud checks the chain to Apple's root, the app id, and the nonce.
|
|
199
199
|
/// Simulators cannot attest: use a development project with attestation off there.
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
200
|
+
struct AppAttestAttestor: RuntimeAttestor {
|
|
201
|
+
let platform = "ios-app-attest"
|
|
202
|
+
init() {}
|
|
203
|
+
func attest(clientData: String, clientDataHash: Data) async throws -> RuntimeAttestation {
|
|
204
204
|
let service = DCAppAttestService.shared
|
|
205
205
|
guard service.isSupported else {
|
|
206
|
-
throw
|
|
206
|
+
throw LegacyCrocheError("attestation_unsupported", "App Attest is not available here (simulators cannot attest)")
|
|
207
207
|
}
|
|
208
208
|
let keyId = try await service.generateKey()
|
|
209
209
|
let object = try await service.attestKey(keyId, clientDataHash: clientDataHash)
|
|
@@ -0,0 +1,285 @@
|
|
|
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 task = Task {
|
|
129
|
+
let finished = await deliver()
|
|
130
|
+
done(finished && !Task.isCancelled)
|
|
131
|
+
}
|
|
132
|
+
if lock.withLock({ self.task = task; return expired }) { task.cancel() }
|
|
133
|
+
}
|
|
134
|
+
func expire() { lock.withLock { expired = true; return task }?.cancel() }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// One OS launch as the handler sees it: the OS's expiration, and the completion it waits for.
|
|
138
|
+
protocol BackgroundLaunchTask: AnyObject, Sendable {
|
|
139
|
+
func onExpire(_ body: @escaping @Sendable () -> Void)
|
|
140
|
+
func complete(success: Bool)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// The OS's launch handlers for the background wake.
|
|
144
|
+
protocol BackgroundLaunches: Sendable {
|
|
145
|
+
/// Installs `handler` for every launch of `identifier`; false = the OS refused it.
|
|
146
|
+
func register(_ identifier: String, _ handler: @escaping @Sendable (any BackgroundLaunchTask) -> Void) -> Bool
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
#if canImport(BackgroundTasks) && os(iOS)
|
|
150
|
+
/// BGTaskScheduler. It refuses (false) an identifier missing from
|
|
151
|
+
/// `BGTaskSchedulerPermittedIdentifiers`; registering after launch finishes is an app bug the OS
|
|
152
|
+
/// traps, so `Croche.registerBackground` runs before `application(_:didFinishLaunchingWithOptions:)` returns.
|
|
153
|
+
struct AppRefreshLaunches: BackgroundLaunches {
|
|
154
|
+
func register(_ identifier: String, _ handler: @escaping @Sendable (any BackgroundLaunchTask) -> Void) -> Bool {
|
|
155
|
+
BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { handler(OSLaunchTask($0)) }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
private final class OSLaunchTask: BackgroundLaunchTask, @unchecked Sendable {
|
|
159
|
+
private let task: BGTask
|
|
160
|
+
init(_ task: BGTask) { self.task = task }
|
|
161
|
+
func onExpire(_ body: @escaping @Sendable () -> Void) { task.expirationHandler = body }
|
|
162
|
+
func complete(success: Bool) { task.setTaskCompleted(success: success) }
|
|
163
|
+
}
|
|
164
|
+
#endif
|
|
165
|
+
|
|
166
|
+
/// Core's `register_background`: install the launch handler for Core's identifier, then submit
|
|
167
|
+
/// the first request (Core's `schedule` moves it later). Each launch runs Core's wake once; the
|
|
168
|
+
/// OS's expiration cancels it. Any refusal is `host_unavailable` (Keel 22:08Z), never a silent Ok;
|
|
169
|
+
/// a platform with no OS launch is `capability_unsupported`. The OS keeps the first handler for
|
|
170
|
+
/// the process, so a later registration only replaces the wake it runs.
|
|
171
|
+
final class PlatformRegistration: @unchecked Sendable {
|
|
172
|
+
private let launches: (any BackgroundLaunches)?
|
|
173
|
+
private let requests: (any BackgroundRequests)?
|
|
174
|
+
private let lock = NSLock()
|
|
175
|
+
private var installed: Set<String> = [], wakes: [String: CoreBackgroundWake] = [:]
|
|
176
|
+
|
|
177
|
+
init(launches: (any BackgroundLaunches)?, requests: (any BackgroundRequests)?) {
|
|
178
|
+
self.launches = launches; self.requests = requests
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
func register(_ identifier: String, _ wake: CoreBackgroundWake) throws {
|
|
182
|
+
guard let launches else {
|
|
183
|
+
throw CorePalError.Failure(code: "capability_unsupported", detail: "This platform has no OS background launch.")
|
|
184
|
+
}
|
|
185
|
+
let install = lock.withLock { () -> Bool in
|
|
186
|
+
wakes[identifier] = wake
|
|
187
|
+
return !installed.contains(identifier)
|
|
188
|
+
}
|
|
189
|
+
if install {
|
|
190
|
+
// The OS keeps the handler for the process, so it keeps this registration too.
|
|
191
|
+
guard launches.register(identifier, { task in self.launch(identifier, task) }) else {
|
|
192
|
+
lock.withLock { _ = wakes.removeValue(forKey: identifier) }
|
|
193
|
+
throw CorePalError.Failure(code: "host_unavailable",
|
|
194
|
+
detail: "The OS refused the launch handler for \(identifier): list it in BGTaskSchedulerPermittedIdentifiers and register before launch finishes.")
|
|
195
|
+
}
|
|
196
|
+
lock.withLock { _ = installed.insert(identifier) }
|
|
197
|
+
}
|
|
198
|
+
do { try requests?.submit(earliest: Date()) } catch let CorePalError.Failure(_, detail) {
|
|
199
|
+
throw CorePalError.Failure(code: "host_unavailable", detail: detail)
|
|
200
|
+
} catch {
|
|
201
|
+
throw CorePalError.Failure(code: "host_unavailable", detail: "The OS refused the request: \(error)")
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private func launch(_ identifier: String, _ task: any BackgroundLaunchTask) {
|
|
206
|
+
guard let wake = lock.withLock({ wakes[identifier] }) else { task.complete(success: false); return }
|
|
207
|
+
let cancel = CancelToken()
|
|
208
|
+
let launch = BackgroundLaunch {
|
|
209
|
+
if Task.isCancelled { return false }
|
|
210
|
+
return await withCheckedContinuation { (done: CheckedContinuation<Bool, Never>) in
|
|
211
|
+
DispatchQueue.global().async { done.resume(returning: (try? wake.run(deadlineMs: nil, cancel: cancel)) != nil) }
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
task.onExpire { cancel.cancel(); launch.expire() }
|
|
215
|
+
launch.start { task.complete(success: $0) }
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// MARK: Attestation (ARCHITECTURE §2: a PAL effect)
|
|
220
|
+
|
|
221
|
+
/// The platform's attestation of this app binary, bound to `clientDataHash`.
|
|
222
|
+
protocol PlatformAttestor: Sendable {
|
|
223
|
+
/// What Core declares: "ios-app-attest".
|
|
224
|
+
var platform: String { get }
|
|
225
|
+
func attest(clientData: String, clientDataHash: Data) async throws -> (token: String, keyId: String?)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
#if canImport(DeviceCheck) && os(iOS)
|
|
229
|
+
/// Apple App Attest: a fresh key per registration, attested against Cloud's challenge.
|
|
230
|
+
/// Simulators cannot attest (`attestation_unsupported`).
|
|
231
|
+
struct AppAttest: PlatformAttestor {
|
|
232
|
+
let platform = "ios-app-attest"
|
|
233
|
+
static var supported: Bool { DCAppAttestService.shared.isSupported }
|
|
234
|
+
func attest(clientData: String, clientDataHash: Data) async throws -> (token: String, keyId: String?) {
|
|
235
|
+
let service = DCAppAttestService.shared
|
|
236
|
+
guard service.isSupported else {
|
|
237
|
+
throw CorePalError.Failure(code: "attestation_unsupported", detail: "App Attest is not available here (simulators cannot attest).")
|
|
238
|
+
}
|
|
239
|
+
do {
|
|
240
|
+
let keyId = try await service.generateKey()
|
|
241
|
+
let object = try await service.attestKey(keyId, clientDataHash: clientDataHash)
|
|
242
|
+
return (object.base64EncodedString(), keyId)
|
|
243
|
+
} catch {
|
|
244
|
+
throw CorePalError.Failure(code: "attestation_failed", detail: "App Attest failed: \(error)")
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
#endif
|
|
249
|
+
|
|
250
|
+
enum PlatformAttestation {
|
|
251
|
+
/// Core's attest effect (`{clientData, clientDataHash, platform}`) through `attestor`, bounded
|
|
252
|
+
/// by `timeoutMs`. No attestor: `attestation_unavailable`.
|
|
253
|
+
static func run(_ attestor: (any PlatformAttestor)?, request: String, timeoutMs: UInt64) throws -> String {
|
|
254
|
+
guard let attestor else {
|
|
255
|
+
throw CorePalError.Failure(code: "attestation_unavailable", detail: "This host cannot attest.")
|
|
256
|
+
}
|
|
257
|
+
let call = try? JSON(request)
|
|
258
|
+
// A malformed call is Core's bug, not an attestation fact.
|
|
259
|
+
guard let clientData = call?["clientData"].string, let hash = base64URLDecode(call?["clientDataHash"].string ?? "") else {
|
|
260
|
+
throw CorePalError.Failure(code: "internal", detail: "Core's attest effect is malformed.")
|
|
261
|
+
}
|
|
262
|
+
let box = AttestBox(), done = DispatchSemaphore(value: 0)
|
|
263
|
+
let task = Task.detached {
|
|
264
|
+
do { box.set(.success(try await attestor.attest(clientData: clientData, clientDataHash: hash))) }
|
|
265
|
+
catch { box.set(.failure(error)) }
|
|
266
|
+
done.signal()
|
|
267
|
+
}
|
|
268
|
+
guard done.wait(timeout: .now() + .milliseconds(Int(min(timeoutMs, UInt64(Int.max))))) == .success else {
|
|
269
|
+
task.cancel()
|
|
270
|
+
throw CorePalError.Failure(code: "attestation_timeout", detail: "The attestor did not answer in \(timeoutMs) ms.")
|
|
271
|
+
}
|
|
272
|
+
let proof: (token: String, keyId: String?)
|
|
273
|
+
do { proof = try box.get() } catch { throw effectFailure(error) }
|
|
274
|
+
let reply: JSON = .object(["platform": .string(attestor.platform), "token": .string(proof.token),
|
|
275
|
+
"keyId": proof.keyId.map(JSON.string) ?? .null])
|
|
276
|
+
return String(decoding: try reply.encoded(), as: UTF8.self)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
private final class AttestBox: @unchecked Sendable {
|
|
281
|
+
private let lock = NSLock()
|
|
282
|
+
private var value: Result<(token: String, keyId: String?), Error>?
|
|
283
|
+
func set(_ result: Result<(token: String, keyId: String?), Error>) { lock.withLock { value = result } }
|
|
284
|
+
func get() throws -> (token: String, keyId: String?) { try lock.withLock { value! }.get() }
|
|
285
|
+
}
|