@qntx/wallet-native 0.13.0 → 0.14.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.
Files changed (135) hide show
  1. package/README.md +184 -31
  2. package/WalletNative.podspec +11 -2
  3. package/android/CMakeLists.txt +7 -1
  4. package/android/build.gradle +4 -0
  5. package/android/src/main/AndroidManifest.xml +1 -2
  6. package/android/src/main/cpp/cpp-adapter.cpp +9 -0
  7. package/android/src/main/java/com/margelo/nitro/qntxwallet/CardReader.kt +316 -0
  8. package/android/src/main/java/com/margelo/nitro/qntxwallet/HybridGoogleDriveAuth.kt +142 -0
  9. package/android/src/main/java/com/margelo/nitro/qntxwallet/HybridSecureInputView.kt +25 -0
  10. package/android/src/main/java/com/margelo/nitro/qntxwallet/Keystore.kt +148 -9
  11. package/android/src/main/java/com/margelo/nitro/qntxwallet/SecureInputField.kt +422 -0
  12. package/android/src/main/java/com/margelo/nitro/qntxwallet/VaultAnchor.kt +90 -0
  13. package/android/src/main/java/com/margelo/nitro/qntxwallet/WalletNativePackage.java +10 -0
  14. package/cpp/host/CardReader.hpp +70 -0
  15. package/cpp/host/HybridKernelHost.cpp +90 -15
  16. package/cpp/host/HybridKernelHost.hpp +21 -5
  17. package/cpp/host/KernelFile.cpp +79 -15
  18. package/cpp/host/KernelFile.hpp +17 -6
  19. package/cpp/host/KernelSlot.hpp +103 -0
  20. package/cpp/host/Keystore.hpp +35 -11
  21. package/cpp/host/Lifecycle.cpp +11 -0
  22. package/cpp/host/Lifecycle.hpp +3 -0
  23. package/cpp/host/Passkey.hpp +8 -0
  24. package/cpp/host/SecureInput.cpp +233 -0
  25. package/cpp/host/SecureInput.hpp +103 -0
  26. package/cpp/host/VaultAnchor.cpp +39 -0
  27. package/cpp/host/VaultAnchor.hpp +28 -0
  28. package/cpp/host/VaultDirectory.hpp +1 -1
  29. package/cpp/platform/CardReaderAndroid.cpp +146 -0
  30. package/cpp/platform/CardReaderIos.mm +318 -0
  31. package/cpp/platform/KeystoreAndroid.cpp +48 -1
  32. package/cpp/platform/KeystoreIos.mm +109 -19
  33. package/cpp/platform/PasskeyAndroid.cpp +2 -0
  34. package/cpp/platform/PasskeyIos.mm +20 -18
  35. package/cpp/platform/QntxSecureInputField.h +24 -0
  36. package/cpp/platform/SecureInputAndroid.cpp +110 -0
  37. package/cpp/platform/SecureInputIos.mm +282 -0
  38. package/cpp/platform/VaultAnchorAndroid.cpp +76 -0
  39. package/cpp/platform/VaultAnchorIos.mm +76 -0
  40. package/cpp/runtime/KernelBackends.cpp +35 -28
  41. package/cpp/runtime/KernelBuffer.hpp +2 -5
  42. package/cpp/runtime/KernelCardReader.cpp +385 -0
  43. package/cpp/runtime/KernelCardReader.hpp +27 -0
  44. package/cpp/runtime/KernelGlobals.cpp +176 -63
  45. package/cpp/runtime/KernelGlobals.hpp +13 -7
  46. package/cpp/runtime/KernelJs.cpp +14 -0
  47. package/cpp/runtime/KernelJs.hpp +4 -0
  48. package/cpp/runtime/KernelKeystore.cpp +78 -2
  49. package/cpp/runtime/KernelKeystore.hpp +1 -0
  50. package/cpp/runtime/KernelPasskey.cpp +15 -12
  51. package/cpp/runtime/KernelRuntime.cpp +24 -7
  52. package/cpp/runtime/KernelRuntime.hpp +14 -6
  53. package/cpp/runtime/KernelSecureInput.cpp +154 -0
  54. package/cpp/runtime/KernelSecureInput.hpp +25 -0
  55. package/cpp/runtime/platform/KernelArgon2.cpp +34 -0
  56. package/cpp/runtime/platform/KernelArgon2.hpp +23 -0
  57. package/cpp/vendor/argon2/LICENSE +314 -0
  58. package/cpp/vendor/argon2/README.md +20 -0
  59. package/cpp/vendor/argon2/include/argon2.h +437 -0
  60. package/cpp/vendor/argon2/src/argon2.c +452 -0
  61. package/cpp/vendor/argon2/src/blake2/blake2-impl.h +156 -0
  62. package/cpp/vendor/argon2/src/blake2/blake2.h +89 -0
  63. package/cpp/vendor/argon2/src/blake2/blake2b.c +390 -0
  64. package/cpp/vendor/argon2/src/blake2/blamka-round-ref.h +56 -0
  65. package/cpp/vendor/argon2/src/core.c +648 -0
  66. package/cpp/vendor/argon2/src/core.h +228 -0
  67. package/cpp/vendor/argon2/src/encoding.c +463 -0
  68. package/cpp/vendor/argon2/src/encoding.h +57 -0
  69. package/cpp/vendor/argon2/src/ref.c +194 -0
  70. package/cpp/vendor/argon2/src/thread.c +57 -0
  71. package/cpp/vendor/argon2/src/thread.h +67 -0
  72. package/dist/cloud.d.mts +58 -0
  73. package/dist/cloud.mjs +114 -0
  74. package/dist/cloud.mjs.map +1 -0
  75. package/dist/index.d.mts +13 -4
  76. package/dist/index.mjs +89 -14
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/secure-input.d.mts +24 -0
  79. package/dist/secure-input.mjs +25 -0
  80. package/dist/secure-input.mjs.map +1 -0
  81. package/ios/HybridCloudKitStore.swift +159 -0
  82. package/ios/HybridSecureInputView.swift +35 -0
  83. package/ios/cloud/CloudKitEnvelopeStore.swift +179 -0
  84. package/kernel/generated/kernel-entry.js +42170 -12741
  85. package/kernel/generated/kernel.manifest.json +17 -7
  86. package/nitrogen/generated/android/WalletNative+autolinking.cmake +7 -1
  87. package/nitrogen/generated/android/WalletNativeOnLoad.cpp +37 -2
  88. package/nitrogen/generated/android/c++/JFunc_void_SecureInputState.hpp +77 -0
  89. package/nitrogen/generated/android/c++/JHybridGoogleDriveAuthSpec.cpp +82 -0
  90. package/nitrogen/generated/android/c++/JHybridGoogleDriveAuthSpec.hpp +64 -0
  91. package/nitrogen/generated/android/c++/JHybridSecureInputViewSpec.cpp +70 -0
  92. package/nitrogen/generated/android/c++/JHybridSecureInputViewSpec.hpp +64 -0
  93. package/nitrogen/generated/android/c++/JSecureInputState.hpp +64 -0
  94. package/nitrogen/generated/android/c++/views/JHybridSecureInputViewStateUpdater.cpp +74 -0
  95. package/nitrogen/generated/android/c++/views/JHybridSecureInputViewStateUpdater.hpp +54 -0
  96. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/Func_void_SecureInputState.kt +78 -0
  97. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/HybridGoogleDriveAuthSpec.kt +61 -0
  98. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/HybridSecureInputViewSpec.kt +67 -0
  99. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/SecureInputState.kt +25 -0
  100. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/views/HybridSecureInputViewManager.kt +96 -0
  101. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/views/HybridSecureInputViewStateUpdater.kt +23 -0
  102. package/nitrogen/generated/ios/WalletNative-Swift-Cxx-Bridge.cpp +74 -1
  103. package/nitrogen/generated/ios/WalletNative-Swift-Cxx-Bridge.hpp +252 -3
  104. package/nitrogen/generated/ios/WalletNative-Swift-Cxx-Umbrella.hpp +21 -3
  105. package/nitrogen/generated/ios/WalletNativeAutolinking.mm +17 -1
  106. package/nitrogen/generated/ios/WalletNativeAutolinking.swift +22 -0
  107. package/nitrogen/generated/ios/c++/HybridCloudKitStoreSpecSwift.cpp +11 -0
  108. package/nitrogen/generated/ios/c++/HybridCloudKitStoreSpecSwift.hpp +116 -0
  109. package/nitrogen/generated/ios/c++/HybridSecureInputViewSpecSwift.cpp +11 -0
  110. package/nitrogen/generated/ios/c++/HybridSecureInputViewSpecSwift.hpp +83 -0
  111. package/nitrogen/generated/ios/c++/views/HybridSecureInputViewComponent.mm +144 -0
  112. package/nitrogen/generated/ios/swift/Func_void.swift +46 -0
  113. package/nitrogen/generated/ios/swift/Func_void_SecureInputState.swift +46 -0
  114. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  115. package/nitrogen/generated/ios/swift/Func_void_std__optional_std__string_.swift +53 -0
  116. package/nitrogen/generated/ios/swift/Func_void_std__vector_std__string_.swift +46 -0
  117. package/nitrogen/generated/ios/swift/HybridCloudKitStoreSpec.swift +59 -0
  118. package/nitrogen/generated/ios/swift/HybridCloudKitStoreSpec_cxx.swift +230 -0
  119. package/nitrogen/generated/ios/swift/HybridSecureInputViewSpec.swift +55 -0
  120. package/nitrogen/generated/ios/swift/HybridSecureInputViewSpec_cxx.swift +164 -0
  121. package/nitrogen/generated/ios/swift/SecureInputState.swift +48 -0
  122. package/nitrogen/generated/shared/c++/HybridCloudKitStoreSpec.cpp +25 -0
  123. package/nitrogen/generated/shared/c++/HybridCloudKitStoreSpec.hpp +70 -0
  124. package/nitrogen/generated/shared/c++/HybridGoogleDriveAuthSpec.cpp +22 -0
  125. package/nitrogen/generated/shared/c++/HybridGoogleDriveAuthSpec.hpp +64 -0
  126. package/nitrogen/generated/shared/c++/HybridKernelHostSpec.cpp +1 -0
  127. package/nitrogen/generated/shared/c++/HybridKernelHostSpec.hpp +1 -0
  128. package/nitrogen/generated/shared/c++/HybridSecureInputViewSpec.cpp +22 -0
  129. package/nitrogen/generated/shared/c++/HybridSecureInputViewSpec.hpp +65 -0
  130. package/nitrogen/generated/shared/c++/SecureInputState.hpp +84 -0
  131. package/nitrogen/generated/shared/c++/views/HybridSecureInputViewComponent.cpp +34 -0
  132. package/nitrogen/generated/shared/c++/views/HybridSecureInputViewComponent.hpp +85 -0
  133. package/nitrogen/generated/shared/json/SecureInputViewConfig.json +10 -0
  134. package/package.json +24 -6
  135. package/scripts/compile-kernel.mjs +7 -3
@@ -13,46 +13,81 @@ namespace margelo::nitro::qntxwallet {
13
13
 
14
14
  namespace {
15
15
 
16
- // A kernel crash reaches JS only as "crashed"; the reason goes to the system
17
- // log so field reports and device runs can tell causes apart. Kernel error
18
- // messages are static strings that never echo input or secrets.
16
+ // A kernel crash reaches JS only as "crashed"; the fact goes to the system log
17
+ // so field reports can tell crashes apart. The reason can carry third-party
18
+ // error text or an unhandled rejection's message, so it is private on iOS
19
+ // (redacted unless a debugger or profile unlocks it) and debug-only on
20
+ // Android, whose logcat has no redaction.
19
21
  void logKernelCrash(const std::string& reason) {
20
22
  #if defined(__ANDROID__)
23
+ #ifdef NDEBUG
24
+ (void)reason;
25
+ __android_log_print(ANDROID_LOG_ERROR, "QntxKernel", "kernel runtime crashed");
26
+ #else
21
27
  __android_log_print(ANDROID_LOG_ERROR, "QntxKernel", "kernel runtime crashed: %s", reason.c_str());
28
+ #endif
22
29
  #elif defined(__APPLE__)
23
- os_log_error(OS_LOG_DEFAULT, "qntx kernel runtime crashed: %{public}s", reason.c_str());
30
+ os_log_error(OS_LOG_DEFAULT, "qntx kernel runtime crashed: %{private}s", reason.c_str());
24
31
  #else
25
32
  (void)reason;
26
33
  #endif
27
34
  }
28
35
 
36
+ // Compare as doubles before converting: casting NaN or an out-of-range value
37
+ // to int is undefined behaviour.
38
+ int validBackgroundSeconds(double value) {
39
+ if (value != 0 && value != 60 && value != 300 && value != 900) {
40
+ throw std::runtime_error("backgroundLockSeconds must be one of 0, 60, 300, 900");
41
+ }
42
+ return static_cast<int>(value);
43
+ }
44
+
29
45
  } // namespace
30
46
 
31
47
  HybridKernelHost::~HybridKernelHost() {
32
48
  std::shared_ptr<qntx::KernelRuntime> runtime;
49
+ qntx::KernelSlot::Claim claim;
33
50
  {
34
51
  std::lock_guard<std::mutex> lock(mutex_);
35
52
  runtime = std::move(runtime_);
53
+ claim = std::move(slotClaim_);
36
54
  }
37
55
  if (runtime) {
38
56
  runtime->destroy();
39
57
  }
58
+ claim.release(runtime);
40
59
  }
41
60
 
42
61
  void HybridKernelHost::start(double backgroundLockSeconds) {
43
- // Compare as doubles before converting: casting NaN or an out-of-range value
44
- // to int is undefined behaviour.
45
- if (backgroundLockSeconds != 0 && backgroundLockSeconds != 60 &&
46
- backgroundLockSeconds != 300 && backgroundLockSeconds != 900) {
47
- throw std::runtime_error("backgroundLockSeconds must be one of 0, 60, 300, 900");
48
- }
49
- const int seconds = static_cast<int>(backgroundLockSeconds);
62
+ const int seconds = validBackgroundSeconds(backgroundLockSeconds);
63
+ qntx::KernelSlot::Claim claim;
64
+ std::shared_ptr<qntx::KernelRuntime> predecessor;
50
65
  {
51
66
  std::lock_guard<std::mutex> lock(mutex_);
52
67
  if (runtime_ || exited_) {
53
68
  return;
54
69
  }
70
+ // One live kernel runtime per process: a second start throws, so two
71
+ // kernels can never write the same vault file.
72
+ claim = qntx::KernelSlot::shared().claim();
73
+ predecessor = claim.predecessor();
55
74
  }
75
+ try {
76
+ startRuntime(seconds, claim, predecessor);
77
+ } catch (...) {
78
+ // Nothing runs: drop the lifecycle registration, and free the slot naming
79
+ // the predecessor again — it may still be stopping, and the next start must
80
+ // wait it out exactly as this one would have.
81
+ qntx::KernelLifecycleDispatcher::shared().unregister(this);
82
+ claim.release(predecessor);
83
+ throw;
84
+ }
85
+ }
86
+
87
+ void HybridKernelHost::startRuntime(
88
+ int seconds,
89
+ qntx::KernelSlot::Claim& claim,
90
+ const std::shared_ptr<qntx::KernelRuntime>& predecessor) {
56
91
  // The platform observer installs once; this host registers its deadline so
57
92
  // the dispatcher can stamp or lock it on background/foreground transitions.
58
93
  qntx::installLifecycleObserver();
@@ -65,7 +100,25 @@ void HybridKernelHost::start(double backgroundLockSeconds) {
65
100
  std::weak_ptr<HybridKernelHost> weak =
66
101
  std::dynamic_pointer_cast<HybridKernelHost>(shared_from_this());
67
102
  qntx::KernelRuntime::Hooks hooks;
68
- hooks.onPost = [weak](std::vector<uint8_t> bytes) {
103
+ // Copy through `auto`: the parameter's const would otherwise make the
104
+ // captured member const and reset() would not compile.
105
+ hooks.beforeEvaluate = [predecessor = predecessor](facebook::jsi::Runtime&) mutable {
106
+ // The predecessor's runtime may still be tearing down: wait on this kernel
107
+ // thread — never the JS thread — so the first file read follows its last
108
+ // write. The wait has no deadline: a predecessor is itself held here until
109
+ // its own predecessor stopped, so the wait covers the whole chain of
110
+ // stopping runtimes, and giving up would either let two writers overlap or
111
+ // leave the session dead until the app restarts.
112
+ if (predecessor != nullptr) {
113
+ while (!predecessor->waitUntilStopped(std::chrono::seconds(1))) {
114
+ }
115
+ // Once waited out, the capture is the predecessor's last reason to stay
116
+ // alive — held for the life of this runtime, it chains every runtime
117
+ // ever started.
118
+ predecessor.reset();
119
+ }
120
+ };
121
+ hooks.onPost = [weak](qntx::SecretBytes bytes) {
69
122
  if (const auto self = weak.lock()) {
70
123
  std::function<void(const std::shared_ptr<ArrayBuffer>&)> listener;
71
124
  {
@@ -73,6 +126,8 @@ void HybridKernelHost::start(double backgroundLockSeconds) {
73
126
  listener = self->messageListener_;
74
127
  }
75
128
  if (listener) {
129
+ // The listener's ArrayBuffer is a fresh copy — `bytes` wipes itself on
130
+ // scope exit whether the listener ran or not.
76
131
  listener(ArrayBuffer::copy(bytes.data(), bytes.size()));
77
132
  }
78
133
  }
@@ -98,12 +153,15 @@ void HybridKernelHost::start(double backgroundLockSeconds) {
98
153
  {
99
154
  std::lock_guard<std::mutex> lock(mutex_);
100
155
  if (exited_) {
101
- // An exit (integrity hash check raced a lock) already fired — drop the
102
- // fresh runtime instead of resurrecting a dead host.
156
+ // An exit raced start — drop the fresh runtime instead of resurrecting
157
+ // a dead host, and release the slot naming it as the still-stopping
158
+ // predecessor for the next start.
103
159
  runtime->destroy();
160
+ claim.release(runtime);
104
161
  return;
105
162
  }
106
163
  runtime_ = runtime;
164
+ slotClaim_ = std::move(claim);
107
165
  }
108
166
  }
109
167
 
@@ -119,7 +177,7 @@ void HybridKernelHost::post(const std::shared_ptr<ArrayBuffer>& frame) {
119
177
  }
120
178
  if (runtime) {
121
179
  const auto* data = static_cast<const uint8_t*>(frame->data());
122
- runtime->post(std::vector<uint8_t>(data, data + frame->size()));
180
+ runtime->post(qntx::SecretBytes(data, frame->size()));
123
181
  }
124
182
  }
125
183
 
@@ -134,12 +192,24 @@ void HybridKernelHost::onExit(const std::function<void(KernelExitReason)>& liste
134
192
  exitListener_ = listener;
135
193
  }
136
194
 
195
+ void HybridKernelHost::setBackgroundLock(double backgroundLockSeconds) {
196
+ const int seconds = validBackgroundSeconds(backgroundLockSeconds);
197
+ {
198
+ std::lock_guard<std::mutex> lock(mutex_);
199
+ if (!runtime_ || exited_) {
200
+ return;
201
+ }
202
+ }
203
+ qntx::KernelLifecycleDispatcher::shared().update(this, seconds);
204
+ }
205
+
137
206
  void HybridKernelHost::lock() {
138
207
  exit(KernelExitReason::LOCKED);
139
208
  }
140
209
 
141
210
  void HybridKernelHost::exit(KernelExitReason reason) {
142
211
  std::shared_ptr<qntx::KernelRuntime> runtime;
212
+ qntx::KernelSlot::Claim claim;
143
213
  std::function<void(KernelExitReason)> listener;
144
214
  {
145
215
  std::lock_guard<std::mutex> lock(mutex_);
@@ -148,11 +218,16 @@ void HybridKernelHost::exit(KernelExitReason reason) {
148
218
  }
149
219
  exited_ = true;
150
220
  runtime = std::move(runtime_);
221
+ claim = std::move(slotClaim_);
151
222
  listener = exitListener_;
152
223
  }
153
224
  if (runtime) {
154
225
  runtime->destroy();
155
226
  }
227
+ // The slot frees for a successor here — the still-stopping runtime becomes
228
+ // its predecessor, which it waits out on its kernel thread before
229
+ // evaluating.
230
+ claim.release(runtime);
156
231
  qntx::KernelLifecycleDispatcher::shared().unregister(this);
157
232
  if (listener) {
158
233
  listener(reason);
@@ -7,16 +7,19 @@
7
7
  #include <mutex>
8
8
 
9
9
  #include "host/Lifecycle.hpp"
10
+ #include "KernelSlot.hpp"
10
11
 
11
12
  #include "../runtime/KernelRuntime.hpp"
12
13
 
13
14
  namespace margelo::nitro::qntxwallet {
14
15
 
15
- // The only Nitro-registered object: drives one kernel runtime. `start`
16
- // verifies the embedded bytecode's SHA-256 before loading; `post` enforces the
17
- // 1 MiB frame cap (the inbound queue cap lives inside KernelRuntime::post and
18
- // reports through the same integrity exit); `lock` destroys the runtime. Exit
19
- // reasons reach JS through the `onExit` listener, at most once.
16
+ // The only Nitro-registered object: drives one kernel runtime. `start` loads
17
+ // the kernel bytecode compiled into the signed app binary as a constexpr array
18
+ // (the build-time manifest check only catches a stale artifact); `post`
19
+ // enforces the 1 MiB frame cap (the inbound queue cap lives inside
20
+ // KernelRuntime::post and reports through the same integrity exit); `lock`
21
+ // destroys the runtime. Exit reasons reach JS through the `onExit` listener,
22
+ // at most once.
20
23
  class HybridKernelHost final : public HybridKernelHostSpec,
21
24
  public qntx::LifecycleLockTarget {
22
25
  public:
@@ -30,6 +33,9 @@ class HybridKernelHost final : public HybridKernelHostSpec,
30
33
  void onMessage(const std::function<void(const std::shared_ptr<ArrayBuffer>&)>& listener)
31
34
  override;
32
35
  void onExit(const std::function<void(KernelExitReason)>& listener) override;
36
+ // Updates this host's background-lock budget; a no-op before start or after
37
+ // exit. The dispatcher keeps any background stamp it already recorded.
38
+ void setBackgroundLock(double backgroundLockSeconds) override;
33
39
  void lock() override;
34
40
 
35
41
  private:
@@ -38,8 +44,18 @@ class HybridKernelHost final : public HybridKernelHostSpec,
38
44
  // Reports `reason` through onExit once, then tears the runtime down unless
39
45
  // the exit was itself the lock report (the runtime is already gone).
40
46
  void exit(KernelExitReason reason);
47
+ // Everything start does after claiming the slot; start undoes the
48
+ // registration and hands the predecessor back to the slot if it throws.
49
+ void startRuntime(
50
+ int seconds,
51
+ qntx::KernelSlot::Claim& claim,
52
+ const std::shared_ptr<qntx::KernelRuntime>& predecessor);
41
53
 
42
54
  std::mutex mutex_;
55
+ // Held while this host owns the process's one live kernel runtime; released
56
+ // on exit or destruction, naming the still-stopping runtime as the next
57
+ // start's predecessor.
58
+ qntx::KernelSlot::Claim slotClaim_;
43
59
  std::shared_ptr<qntx::KernelRuntime> runtime_;
44
60
  std::function<void(const std::shared_ptr<ArrayBuffer>&)> messageListener_;
45
61
  std::function<void(KernelExitReason)> exitListener_;
@@ -8,6 +8,7 @@
8
8
  #error "KernelFile has no Windows implementation"
9
9
  #else
10
10
  #include <fcntl.h>
11
+ #include <sys/file.h>
11
12
  #include <sys/stat.h>
12
13
  #include <sys/types.h>
13
14
  #include <unistd.h>
@@ -40,9 +41,22 @@ std::string pathFor(const std::string& directory, const char* leaf) {
40
41
  return directory + "/" + leaf;
41
42
  }
42
43
 
43
- } // namespace
44
+ // Closes fd on every path, including exceptions mid-write.
45
+ struct ScopedFd {
46
+ explicit ScopedFd(int fd) : fd(fd) {}
47
+ ~ScopedFd() {
48
+ if (fd >= 0) {
49
+ ::close(fd);
50
+ }
51
+ }
52
+ ScopedFd(const ScopedFd&) = delete;
53
+ ScopedFd& operator=(const ScopedFd&) = delete;
54
+ int fd;
55
+ };
44
56
 
45
- std::optional<std::vector<uint8_t>> kernelFileRead(const std::string& directory) {
57
+ // Reads an already-open lock file's sibling: the whole vault.cbor, or nullopt
58
+ // when it does not exist. Called with the lock held.
59
+ std::optional<std::vector<uint8_t>> readImage(const std::string& directory) {
46
60
  const std::string path = pathFor(directory, "vault.cbor");
47
61
  const int fd = ::open(path.c_str(), O_RDONLY);
48
62
  if (fd < 0) {
@@ -51,14 +65,12 @@ std::optional<std::vector<uint8_t>> kernelFileRead(const std::string& directory)
51
65
  }
52
66
  fail("open vault file");
53
67
  }
68
+ const ScopedFd guard(fd);
54
69
  std::vector<uint8_t> bytes;
55
70
  uint8_t chunk[65536];
56
71
  for (;;) {
57
72
  const ssize_t n = ::read(fd, chunk, sizeof(chunk));
58
73
  if (n < 0) {
59
- const int saved = errno;
60
- ::close(fd);
61
- errno = saved;
62
74
  fail("read vault file");
63
75
  }
64
76
  if (n == 0) {
@@ -66,11 +78,12 @@ std::optional<std::vector<uint8_t>> kernelFileRead(const std::string& directory)
66
78
  }
67
79
  bytes.insert(bytes.end(), chunk, chunk + n);
68
80
  }
69
- ::close(fd);
70
81
  return bytes;
71
82
  }
72
83
 
73
- void kernelFileWrite(const std::string& directory, const std::vector<uint8_t>& bytes) {
84
+ // Temp + fsync + rename + directory fsync. Called with the lock held, so the
85
+ // shared temp name belongs to one writer at a time.
86
+ void writeImage(const std::string& directory, const uint8_t* bytes, size_t size) {
74
87
  const std::string tmp = pathFor(directory, "vault.cbor.tmp");
75
88
  const std::string final = pathFor(directory, "vault.cbor");
76
89
  const int fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
@@ -78,8 +91,8 @@ void kernelFileWrite(const std::string& directory, const std::vector<uint8_t>& b
78
91
  fail("open temp vault file");
79
92
  }
80
93
  size_t off = 0;
81
- while (off < bytes.size()) {
82
- const ssize_t n = ::write(fd, bytes.data() + off, bytes.size() - off);
94
+ while (off < size) {
95
+ const ssize_t n = ::write(fd, bytes + off, size - off);
83
96
  if (n <= 0) {
84
97
  const int saved = errno;
85
98
  ::close(fd);
@@ -108,13 +121,64 @@ void kernelFileWrite(const std::string& directory, const std::vector<uint8_t>& b
108
121
  if (dirFd < 0) {
109
122
  fail("open vault directory");
110
123
  }
111
- try {
112
- fsyncOrFail(dirFd, "fsync vault directory");
113
- } catch (...) {
114
- ::close(dirFd);
115
- throw;
124
+ const ScopedFd dirGuard(dirFd);
125
+ fsyncOrFail(dirFd, "fsync vault directory");
126
+ }
127
+
128
+ // Exclusive flock on the vault lock file for the whole read-modify-write.
129
+ // flock (not a std::mutex) because it excludes separate open file descriptions
130
+ // — a second KernelRuntime in this process holds a different fd — and other
131
+ // processes sharing the vault directory alike.
132
+ struct VaultLock {
133
+ explicit VaultLock(const std::string& directory) {
134
+ const std::string lockPath = pathFor(directory, "vault.cbor.lock");
135
+ fd = ::open(lockPath.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
136
+ if (fd < 0) {
137
+ fail("open vault lock file");
138
+ }
139
+ if (::flock(fd, LOCK_EX) != 0) {
140
+ const int saved = errno;
141
+ ::close(fd);
142
+ fd = -1;
143
+ errno = saved;
144
+ fail("lock vault file");
145
+ }
146
+ }
147
+ ~VaultLock() {
148
+ if (fd >= 0) {
149
+ ::flock(fd, LOCK_UN);
150
+ ::close(fd);
151
+ }
152
+ }
153
+ VaultLock(const VaultLock&) = delete;
154
+ VaultLock& operator=(const VaultLock&) = delete;
155
+ int fd = -1;
156
+ };
157
+
158
+ } // namespace
159
+
160
+ std::optional<std::vector<uint8_t>> kernelFileRead(const std::string& directory) {
161
+ // Read outside the lock: the image is a whole-file atomic rename, so readers
162
+ // always see one complete generation or the other. Writers serialize through
163
+ // kernelFileReplace.
164
+ return readImage(directory);
165
+ }
166
+
167
+ bool kernelFileReplace(
168
+ const std::string& directory,
169
+ const uint8_t* next,
170
+ size_t size,
171
+ const std::optional<std::vector<uint8_t>>& expected) {
172
+ const VaultLock lock(directory);
173
+ const auto current = readImage(directory);
174
+ const bool matches = expected.has_value()
175
+ ? (current.has_value() && *current == *expected)
176
+ : !current.has_value();
177
+ if (!matches) {
178
+ return false;
116
179
  }
117
- ::close(dirFd);
180
+ writeImage(directory, next, size);
181
+ return true;
118
182
  }
119
183
 
120
184
  } // namespace qntx
@@ -1,5 +1,7 @@
1
1
  #pragma once
2
2
 
3
+ #include <cstddef>
4
+ #include <cstdint>
3
5
  #include <optional>
4
6
  #include <string>
5
7
  #include <vector>
@@ -14,11 +16,20 @@ namespace qntx {
14
16
  // rejection and never silently treats it as an empty vault.
15
17
  std::optional<std::vector<uint8_t>> kernelFileRead(const std::string& directory);
16
18
 
17
- // Atomic replace of vault.cbor in `directory`: write vault.cbor.tmp in the
18
- // same directory, fsync it, rename it over the target, then fsync the
19
- // directory so the rename itself is durable. Throws std::runtime_error naming
20
- // the failing step and errno; a failed write leaves the previous file intact
21
- // and unlinks the temp file.
22
- void kernelFileWrite(const std::string& directory, const std::vector<uint8_t>& bytes);
19
+ // Compare-and-swap whole-file replace of vault.cbor in `directory`. An
20
+ // exclusive flock on <directory>/vault.cbor.lock serializes writers across
21
+ // open file descriptions and processes; inside the lock the current file is
22
+ // re-read and byte-compared with `expected` (nullopt = the file must not
23
+ // exist). On a match the file is replaced atomically (vault.cbor.tmp + fsync +
24
+ // rename + directory fsync — the shared temp name is safe because writers are
25
+ // serialized) and true is returned. On a mismatch nothing is written and false
26
+ // is returned; the caller fails closed instead of clobbering a concurrent
27
+ // commit. Throws std::runtime_error naming the failing step and errno; a
28
+ // failed write leaves the previous file intact and unlinks the temp file.
29
+ bool kernelFileReplace(
30
+ const std::string& directory,
31
+ const uint8_t* next,
32
+ size_t size,
33
+ const std::optional<std::vector<uint8_t>>& expected);
23
34
 
24
35
  } // namespace qntx
@@ -0,0 +1,103 @@
1
+ #pragma once
2
+
3
+ #include <memory>
4
+ #include <mutex>
5
+ #include <stdexcept>
6
+
7
+ namespace qntx {
8
+
9
+ class KernelRuntime;
10
+
11
+ // One live kernel runtime per process: at most one Claim is outstanding, so
12
+ // two hosts can never run two kernels over the same vault file. The holder
13
+ // releases the slot when its runtime exits or is destroyed, handing the
14
+ // still-stopping runtime to the next claim as its predecessor — the successor
15
+ // waits on it (KernelRuntime::waitUntilStopped) inside Hooks.beforeEvaluate,
16
+ // so the successor's first file read follows the predecessor's last write and
17
+ // the JS thread never blocks.
18
+ class KernelSlot {
19
+ public:
20
+ KernelSlot() = default;
21
+ KernelSlot(const KernelSlot&) = delete;
22
+ KernelSlot& operator=(const KernelSlot&) = delete;
23
+
24
+ // RAII admission token: while one is alive, claim() throws. Destruction
25
+ // frees the slot with no predecessor; holders call release() instead, which
26
+ // names their still-stopping runtime for the next claim.
27
+ class Claim {
28
+ public:
29
+ Claim() = default;
30
+ ~Claim() {
31
+ release(nullptr);
32
+ }
33
+ Claim(Claim&& other) noexcept
34
+ : slot_(other.slot_), predecessor_(std::move(other.predecessor_)) {
35
+ other.slot_ = nullptr;
36
+ }
37
+ Claim& operator=(Claim&& other) noexcept {
38
+ if (this != &other) {
39
+ release(nullptr);
40
+ slot_ = other.slot_;
41
+ predecessor_ = std::move(other.predecessor_);
42
+ other.slot_ = nullptr;
43
+ }
44
+ return *this;
45
+ }
46
+ Claim(const Claim&) = delete;
47
+ Claim& operator=(const Claim&) = delete;
48
+
49
+ // The runtime the previous holder left stopping, or nullptr.
50
+ const std::shared_ptr<KernelRuntime>& predecessor() const {
51
+ return predecessor_;
52
+ }
53
+
54
+ // Free the slot; `stopping` — the holder's runtime mid-teardown, or
55
+ // nullptr — becomes the predecessor the next claim must wait out before
56
+ // evaluating its script.
57
+ void release(std::shared_ptr<KernelRuntime> stopping) {
58
+ KernelSlot* slot = slot_;
59
+ if (slot == nullptr) {
60
+ return;
61
+ }
62
+ slot_ = nullptr;
63
+ predecessor_.reset();
64
+ std::lock_guard<std::mutex> lock(slot->mutex_);
65
+ slot->held_ = false;
66
+ if (stopping != nullptr) {
67
+ slot->predecessor_ = std::move(stopping);
68
+ }
69
+ }
70
+
71
+ private:
72
+ friend class KernelSlot;
73
+ Claim(KernelSlot* slot, std::shared_ptr<KernelRuntime> predecessor)
74
+ : slot_(slot), predecessor_(std::move(predecessor)) {}
75
+ KernelSlot* slot_ = nullptr;
76
+ std::shared_ptr<KernelRuntime> predecessor_;
77
+ };
78
+
79
+ // Throws std::runtime_error while another claim is live; Nitro surfaces it
80
+ // to JS as a start() failure and the caller's session fails closed. On
81
+ // success the claim carries the previous holder's still-stopping runtime,
82
+ // or nullptr.
83
+ Claim claim() {
84
+ std::lock_guard<std::mutex> lock(mutex_);
85
+ if (held_) {
86
+ throw std::runtime_error("another kernel runtime is live in this process");
87
+ }
88
+ held_ = true;
89
+ return Claim(this, std::move(predecessor_));
90
+ }
91
+
92
+ static KernelSlot& shared() {
93
+ static KernelSlot slot;
94
+ return slot;
95
+ }
96
+
97
+ private:
98
+ std::mutex mutex_;
99
+ bool held_ = false;
100
+ std::shared_ptr<KernelRuntime> predecessor_;
101
+ };
102
+
103
+ } // namespace qntx
@@ -9,21 +9,25 @@
9
9
  namespace qntx {
10
10
 
11
11
  // The platform keystore behind `__qntx.keystore` (W5): a hardware key per
12
- // vault factor that seals and opens the factor's KEK behind a system user
13
- // verification. iOS: Secure Enclave P-256 + ECIES; Android: Keystore
14
- // AES-256-GCM behind BiometricPrompt. Each function has exactly one strong
15
- // definition per platform (KeystoreIos.mm, KeystoreAndroid.cpp); host tests
16
- // link a fake.
12
+ // vault factor. A `presence` key seals and opens the factor's KEK behind a
13
+ // system user verification; a `device` key seals and opens with no UI and is
14
+ // the silent unlock factor. iOS: Secure Enclave P-256 + ECIES; Android:
15
+ // Keystore AES-256-GCM (presence behind BiometricPrompt). Each function has
16
+ // exactly one strong definition per platform (KeystoreIos.mm,
17
+ // KeystoreAndroid.cpp); host tests link a fake.
17
18
 
18
19
  struct KeystorePrompt {
19
20
  std::string title;
20
21
  std::string description;
21
22
  };
22
23
 
24
+ // Which kind of key a probe is about.
25
+ enum class KeyProtection { device, presence };
26
+
23
27
  // How a keystore call ended. The binding maps each status to the kernel's
24
28
  // error code: cancelled → "cancelled", invalidated → "factor-invalidated",
25
29
  // unavailable → "unavailable", failed → "unavailable",
26
- // noDeviceCredential → "no-device-credential". The values are part of the
30
+ // noLockScreen → "verification-unavailable". The values are part of the
27
31
  // Android JNI contract (Keystore.kt).
28
32
  enum class KeystoreStatus {
29
33
  ok = 0,
@@ -31,7 +35,7 @@ enum class KeystoreStatus {
31
35
  invalidated = 2,
32
36
  unavailable = 3,
33
37
  failed = 4,
34
- noDeviceCredential = 5,
38
+ noLockScreen = 5,
35
39
  };
36
40
 
37
41
  struct KeystoreResult {
@@ -45,7 +49,7 @@ struct KeystoreResult {
45
49
  // Completion callbacks run exactly once, on any thread.
46
50
  using KeystoreDone = std::function<void(KeystoreResult)>;
47
51
 
48
- // Creates the hardware key for vault factor `id` and encrypts `secret` under
52
+ // Creates the presence key for vault factor `id` and encrypts `secret` under
49
53
  // it. Android prompts (encryption needs the authenticated cipher); iOS does
50
54
  // not (ECIES encrypts with the public key).
51
55
  void keystoreSeal(
@@ -54,15 +58,31 @@ void keystoreSeal(
54
58
  KeystorePrompt prompt,
55
59
  KeystoreDone done);
56
60
 
57
- // Decrypts `sealed` with factor `id`'s key after a fresh system verification
58
- // that shows `prompt`. A key the system removed (lock screen disabled,
59
- // device restored) completes `invalidated`.
61
+ // Decrypts `sealed` with factor `id`'s presence key after a fresh system
62
+ // verification that shows `prompt`. A key the system removed (lock screen
63
+ // disabled, device restored) completes `invalidated`.
60
64
  void keystoreOpen(
61
65
  const std::string& id,
62
66
  std::vector<uint8_t> sealed,
63
67
  KeystorePrompt prompt,
64
68
  KeystoreDone done);
65
69
 
70
+ // Creates the device key for vault factor `id` and encrypts `secret` under
71
+ // it. Never shows UI.
72
+ void keystoreSealDevice(const std::string& id, SecretBytes secret, KeystoreDone done);
73
+
74
+ // Decrypts `sealed` with factor `id`'s device key. Never shows UI; a gone key
75
+ // completes `invalidated`.
76
+ void keystoreOpenDevice(const std::string& id, std::vector<uint8_t> sealed, KeystoreDone done);
77
+
78
+ // Reports `ok` when key `id` is alive and `invalidated` when it is gone for
79
+ // good (deleted, permanently invalidated, or — presence — no lock screen).
80
+ // Never shows UI; any other outcome is a failure.
81
+ void keystoreProbe(const std::string& id, KeyProtection protection, KeystoreDone done);
82
+
83
+ // Deletes key `id`; a missing key is `ok`. Never shows UI.
84
+ void keystoreRemove(const std::string& id, KeystoreDone done);
85
+
66
86
  // A device-owner check with no key involved (vault reset, WD-055).
67
87
  void keystoreAuthenticate(KeystorePrompt prompt, KeystoreDone done);
68
88
 
@@ -77,4 +97,8 @@ void keystoreCancel();
77
97
  // main runtime cannot choose the prompt language.
78
98
  std::string keystoreLocale();
79
99
 
100
+ // Which OS this build's keystore renders its system prompt on: "ios" or
101
+ // "android". Compiled in, so the kernel's prompt bound cannot be spoofed.
102
+ std::string keystorePlatform();
103
+
80
104
  } // namespace qntx
@@ -15,6 +15,17 @@ void KernelLifecycleDispatcher::registerHost(
15
15
  entries_.push_back(Entry{host, seconds, std::nullopt});
16
16
  }
17
17
 
18
+ void KernelLifecycleDispatcher::update(const LifecycleLockTarget* host, int seconds) {
19
+ std::lock_guard<std::mutex> lock(mutex_);
20
+ for (auto& entry : entries_) {
21
+ const auto target = entry.host.lock();
22
+ if (target && target.get() == host) {
23
+ entry.seconds = seconds;
24
+ return;
25
+ }
26
+ }
27
+ }
28
+
18
29
  void KernelLifecycleDispatcher::unregister(const LifecycleLockTarget* host) {
19
30
  std::lock_guard<std::mutex> lock(mutex_);
20
31
  std::erase_if(entries_, [&](const Entry& entry) {
@@ -44,6 +44,9 @@ class KernelLifecycleDispatcher {
44
44
  static KernelLifecycleDispatcher& shared();
45
45
 
46
46
  void registerHost(const std::weak_ptr<LifecycleLockTarget>& host, int seconds);
47
+ /** Change one registration's seconds, keeping a recorded background stamp;
48
+ * an unknown host is a no-op. */
49
+ void update(const LifecycleLockTarget* host, int seconds);
47
50
  /** Drop the registration — called on every host exit. */
48
51
  void unregister(const LifecycleLockTarget* host);
49
52