@secure-signing/react-native 0.0.0-stage → 0.1.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.
@@ -0,0 +1,403 @@
1
+ import CryptoKit
2
+ import ExpoModulesCore
3
+ import Foundation
4
+ import LocalAuthentication
5
+ import Security
6
+
7
+ struct CreateKeyArgs: Record {
8
+ @Field var keyId: String = ""
9
+ @Field var authPolicy: String = "biometry-current-set"
10
+ @Field var hardware: String = "strongbox-preferred"
11
+ @Field var attestationChallenge: String? = nil
12
+ @Field var allowNonHardwareKey: Bool = false
13
+ }
14
+
15
+ struct SignArgs: Record {
16
+ @Field var keyId: String = ""
17
+ @Field var payload: String = ""
18
+ @Field var promptMessage: String = ""
19
+ @Field var promptTitle: String = ""
20
+ @Field var cancelLabel: String = "Cancel"
21
+ }
22
+
23
+ /// Non-secret per-key metadata stored next to the key. Never contains key material.
24
+ private struct KeyMetadata: Codable {
25
+ var version: Int = 1
26
+ var authPolicy: String
27
+ var domainStateHash: String?
28
+ }
29
+
30
+ public final class SecureSignerModule: Module {
31
+ private let signLock = NSLock()
32
+ private var signInFlight = false
33
+ private static let metadataService = "secure-signing.metadata"
34
+
35
+ public func definition() -> ModuleDefinition {
36
+ Name("SecureSigner")
37
+
38
+ AsyncFunction("isAvailable") { () -> Bool in
39
+ guard SecureEnclave.isAvailable else { return false }
40
+ let ctx = LAContext()
41
+ var error: NSError?
42
+ if ctx.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { return true }
43
+ // Hardware is present even if not enrolled or locked out.
44
+ if let code = error.flatMap({ LAError.Code(rawValue: $0.code) }) {
45
+ return code == .biometryNotEnrolled || code == .biometryLockout
46
+ }
47
+ return false
48
+ }
49
+
50
+ AsyncFunction("getCapabilities") { () -> [String: Any] in
51
+ let ctx = LAContext()
52
+ var error: NSError?
53
+ let ok = ctx.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
54
+ let code = error.flatMap { LAError.Code(rawValue: $0.code) }
55
+ let available = ok || code == .biometryNotEnrolled || code == .biometryLockout
56
+ let enrolled = ok || code == .biometryLockout
57
+ let deviceSecure = LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)
58
+ return [
59
+ "platform": "ios",
60
+ "secureEnclaveAvailable": SecureEnclave.isAvailable,
61
+ "strongBoxAvailable": false,
62
+ "biometricAuthenticationAvailable": available,
63
+ "biometricAuthenticationEnrolled": enrolled,
64
+ "deviceSecure": deviceSecure,
65
+ ]
66
+ }
67
+
68
+ AsyncFunction("createKey") { (args: CreateKeyArgs, promise: Promise) in
69
+ self.run(promise) { try self.createKey(args) }
70
+ }
71
+
72
+ AsyncFunction("getKeyInfo") { (keyId: String, promise: Promise) in
73
+ self.run(promise) { try self.keyInfo(keyId: keyId) }
74
+ }
75
+
76
+ AsyncFunction("hasKey") { (keyId: String, promise: Promise) in
77
+ self.run(promise) {
78
+ try self.requireValidKeyId(keyId)
79
+ return try self.copyPrivateKey(keyId: keyId, context: nil) != nil
80
+ }
81
+ }
82
+
83
+ AsyncFunction("deleteKey") { (keyId: String, promise: Promise) in
84
+ self.run(promise) {
85
+ try self.requireValidKeyId(keyId)
86
+ try self.deleteKeyItems(keyId: keyId)
87
+ return nil
88
+ }
89
+ }
90
+
91
+ AsyncFunction("sign") { (args: SignArgs, promise: Promise) in
92
+ self.sign(args, promise: promise)
93
+ }
94
+ }
95
+
96
+ // MARK: - Helpers
97
+
98
+ private func run(_ promise: Promise, _ body: () throws -> Any?) {
99
+ do {
100
+ promise.resolve(try body())
101
+ } catch let e as SignerError {
102
+ promise.reject(e.code.rawValue, e.jsMessage)
103
+ } catch {
104
+ promise.reject(SignerErrorCode.unknown.rawValue, "unexpected error")
105
+ }
106
+ }
107
+
108
+ private func requireValidKeyId(_ keyId: String) throws {
109
+ guard SecureSignerCore.isValidKeyId(keyId) else {
110
+ throw SignerError(.invalidArgument, "keyId must match /^[A-Za-z0-9._-]{1,64}$/")
111
+ }
112
+ }
113
+
114
+ private var bundleId: String { Bundle.main.bundleIdentifier ?? "unknown-bundle" }
115
+
116
+ private func tag(_ keyId: String) -> Data {
117
+ Data(SecureSignerCore.tagString(bundleId: bundleId, keyId: keyId).utf8)
118
+ }
119
+
120
+ private func privateKeyQuery(keyId: String) -> [String: Any] {
121
+ [
122
+ kSecClass as String: kSecClassKey,
123
+ kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
124
+ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
125
+ kSecAttrApplicationTag as String: tag(keyId),
126
+ ]
127
+ }
128
+
129
+ /// Returns the key reference without triggering authentication UI.
130
+ private func copyPrivateKey(keyId: String, context: LAContext?) throws -> SecKey? {
131
+ var query = privateKeyQuery(keyId: keyId)
132
+ query[kSecReturnRef as String] = true
133
+ let ctx = context ?? {
134
+ let c = LAContext()
135
+ c.interactionNotAllowed = true
136
+ return c
137
+ }()
138
+ query[kSecUseAuthenticationContext as String] = ctx
139
+ var item: CFTypeRef?
140
+ let status = SecItemCopyMatching(query as CFDictionary, &item)
141
+ if status == errSecItemNotFound { return nil }
142
+ guard status == errSecSuccess, let item = item, CFGetTypeID(item) == SecKeyGetTypeID() else {
143
+ throw SecureSignerCore.mapOSStatus(status, during: .lookup)
144
+ }
145
+ return (item as! SecKey)
146
+ }
147
+
148
+ private func isSecureEnclaveKey(keyId: String) throws -> Bool {
149
+ var query = privateKeyQuery(keyId: keyId)
150
+ query[kSecReturnAttributes as String] = true
151
+ let ctx = LAContext()
152
+ ctx.interactionNotAllowed = true
153
+ query[kSecUseAuthenticationContext as String] = ctx
154
+ var item: CFTypeRef?
155
+ let status = SecItemCopyMatching(query as CFDictionary, &item)
156
+ guard status == errSecSuccess, let attrs = item as? [String: Any] else {
157
+ throw SecureSignerCore.mapOSStatus(status, during: .lookup)
158
+ }
159
+ return (attrs[kSecAttrTokenID as String] as? String) == (kSecAttrTokenIDSecureEnclave as String)
160
+ }
161
+
162
+ private func metadataQuery(keyId: String) -> [String: Any] {
163
+ [
164
+ kSecClass as String: kSecClassGenericPassword,
165
+ kSecAttrService as String: Self.metadataService,
166
+ kSecAttrAccount as String: SecureSignerCore.tagString(bundleId: bundleId, keyId: keyId),
167
+ ]
168
+ }
169
+
170
+ private func saveMetadata(_ meta: KeyMetadata, keyId: String) throws {
171
+ SecItemDelete(metadataQuery(keyId: keyId) as CFDictionary)
172
+ var query = metadataQuery(keyId: keyId)
173
+ query[kSecValueData as String] = try JSONEncoder().encode(meta)
174
+ query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
175
+ let status = SecItemAdd(query as CFDictionary, nil)
176
+ guard status == errSecSuccess else { throw SecureSignerCore.mapOSStatus(status, during: .create) }
177
+ }
178
+
179
+ private func loadMetadata(keyId: String) throws -> KeyMetadata? {
180
+ var query = metadataQuery(keyId: keyId)
181
+ query[kSecReturnData as String] = true
182
+ var item: CFTypeRef?
183
+ let status = SecItemCopyMatching(query as CFDictionary, &item)
184
+ if status == errSecItemNotFound { return nil }
185
+ guard status == errSecSuccess, let data = item as? Data else {
186
+ throw SecureSignerCore.mapOSStatus(status, during: .lookup)
187
+ }
188
+ return try? JSONDecoder().decode(KeyMetadata.self, from: data)
189
+ }
190
+
191
+ private func deleteKeyItems(keyId: String) throws {
192
+ let s1 = SecItemDelete(privateKeyQuery(keyId: keyId) as CFDictionary)
193
+ let s2 = SecItemDelete(metadataQuery(keyId: keyId) as CFDictionary)
194
+ for s in [s1, s2] where s != errSecSuccess && s != errSecItemNotFound {
195
+ throw SecureSignerCore.mapOSStatus(s, during: .lookup)
196
+ }
197
+ }
198
+
199
+ private func publicKeySpkiBase64(_ privateKey: SecKey) throws -> String {
200
+ guard let pub = SecKeyCopyPublicKey(privateKey) else {
201
+ throw SignerError(.unknown, "could not derive public key")
202
+ }
203
+ var error: Unmanaged<CFError>?
204
+ guard let raw = SecKeyCopyExternalRepresentation(pub, &error) as Data? else {
205
+ throw SecureSignerCore.mapCFError(error?.takeRetainedValue(), during: .lookup)
206
+ }
207
+ return try SecureSignerCore.spki(fromX963: raw).base64EncodedString()
208
+ }
209
+
210
+ /// Checks biometric state before key use or creation. Returns the current domain-state hash.
211
+ private func checkBiometrics(policy: AuthPolicy?) throws -> String? {
212
+ let ctx = LAContext()
213
+ var error: NSError?
214
+ if !ctx.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
215
+ let mapped = SecureSignerCore.mapLAError(error ?? NSError(domain: LAError.errorDomain, code: LAError.Code.biometryNotAvailable.rawValue), policy: policy)
216
+ // Lockout does not prevent key creation, and is reported at prompt time for signing.
217
+ if mapped.code != .authenticationLockedOut { throw mapped }
218
+ }
219
+ return SecureSignerCore.domainStateHash(ctx.evaluatedPolicyDomainState)
220
+ }
221
+
222
+ // MARK: - createKey
223
+
224
+ private func createKey(_ args: CreateKeyArgs) throws -> [String: Any] {
225
+ try requireValidKeyId(args.keyId)
226
+ guard let policy = AuthPolicy(rawValue: args.authPolicy) else {
227
+ throw SignerError(.invalidArgument, "unknown authPolicy")
228
+ }
229
+ guard ["strongbox-required", "strongbox-preferred", "secure-hardware"].contains(args.hardware) else {
230
+ throw SignerError(.invalidArgument, "unknown hardware preference")
231
+ }
232
+ // attestationChallenge is accepted for API symmetry; iOS has no Secure Enclave key attestation.
233
+
234
+ if try copyPrivateKey(keyId: args.keyId, context: nil) != nil {
235
+ throw SignerError(.keyAlreadyExists, "a key already exists for this keyId")
236
+ }
237
+ let domainStateHash = try checkBiometrics(policy: nil)
238
+
239
+ let useSecureEnclave = SecureEnclave.isAvailable
240
+ if !useSecureEnclave && !args.allowNonHardwareKey {
241
+ throw SignerError(.secureHardwareUnavailable, "Secure Enclave is not available on this device")
242
+ }
243
+
244
+ var flags: SecAccessControlCreateFlags = [policy.accessControlFlag]
245
+ if useSecureEnclave { flags.insert(.privateKeyUsage) }
246
+ var acError: Unmanaged<CFError>?
247
+ guard let access = SecAccessControlCreateWithFlags(
248
+ kCFAllocatorDefault, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, flags, &acError)
249
+ else {
250
+ throw SecureSignerCore.mapCFError(acError?.takeRetainedValue(), during: .create)
251
+ }
252
+
253
+ let attributes = SecureSignerCore.keyGenerationAttributes(
254
+ tag: tag(args.keyId), access: access, secureEnclave: useSecureEnclave)
255
+
256
+ var genError: Unmanaged<CFError>?
257
+ // Fail closed: if Secure Enclave generation fails we do NOT retry in software.
258
+ guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &genError) else {
259
+ throw SecureSignerCore.mapCFError(genError?.takeRetainedValue(), during: .create)
260
+ }
261
+
262
+ do {
263
+ let publicKey = try publicKeySpkiBase64(privateKey)
264
+ try saveMetadata(KeyMetadata(authPolicy: policy.rawValue, domainStateHash: domainStateHash), keyId: args.keyId)
265
+ return [
266
+ "keyId": args.keyId,
267
+ "publicKey": publicKey,
268
+ "authPolicy": policy.rawValue,
269
+ "hardwareBacked": useSecureEnclave,
270
+ "securityLevel": useSecureEnclave ? "secure-enclave" : "software",
271
+ "attestationChain": NSNull(),
272
+ ]
273
+ } catch {
274
+ try? deleteKeyItems(keyId: args.keyId)
275
+ throw error
276
+ }
277
+ }
278
+
279
+ // MARK: - getKeyInfo
280
+
281
+ private func keyInfo(keyId: String) throws -> [String: Any]? {
282
+ try requireValidKeyId(keyId)
283
+ guard let key = try copyPrivateKey(keyId: keyId, context: nil) else { return nil }
284
+ guard let meta = try loadMetadata(keyId: keyId), AuthPolicy(rawValue: meta.authPolicy) != nil else {
285
+ throw SignerError(.unknown, "key metadata is missing or corrupt; delete the key and re-enroll")
286
+ }
287
+ let se = try isSecureEnclaveKey(keyId: keyId)
288
+ return [
289
+ "keyId": keyId,
290
+ "publicKey": try publicKeySpkiBase64(key),
291
+ "authPolicy": meta.authPolicy,
292
+ "hardwareBacked": se,
293
+ "securityLevel": se ? "secure-enclave" : "software",
294
+ "attestationChain": NSNull(),
295
+ ]
296
+ }
297
+
298
+ // MARK: - sign
299
+
300
+ private func sign(_ args: SignArgs, promise: Promise) {
301
+ let fail: (SignerError) -> Void = { promise.reject($0.code.rawValue, $0.jsMessage) }
302
+
303
+ guard SecureSignerCore.isValidKeyId(args.keyId) else {
304
+ return fail(SignerError(.invalidArgument, "keyId must match /^[A-Za-z0-9._-]{1,64}$/"))
305
+ }
306
+ guard !args.promptMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
307
+ return fail(SignerError(.invalidArgument, "promptMessage is required"))
308
+ }
309
+ guard let payload = Data(base64Encoded: args.payload), !payload.isEmpty else {
310
+ return fail(SignerError(.invalidArgument, "payload must be non-empty"))
311
+ }
312
+ guard payload.count <= SecureSignerCore.maxPayloadBytes else {
313
+ return fail(SignerError(.payloadTooLarge, "payload is too large"))
314
+ }
315
+
316
+ signLock.lock()
317
+ if signInFlight {
318
+ signLock.unlock()
319
+ return fail(SignerError(.authenticationInProgress, "another signing operation is in progress"))
320
+ }
321
+ signInFlight = true
322
+ signLock.unlock()
323
+
324
+ let finish: (Result<String, SignerError>) -> Void = { [weak self] result in
325
+ if let self = self {
326
+ self.signLock.lock()
327
+ self.signInFlight = false
328
+ self.signLock.unlock()
329
+ }
330
+ switch result {
331
+ case .success(let sig): promise.resolve(["signature": sig])
332
+ case .failure(let e): fail(e)
333
+ }
334
+ }
335
+
336
+ let policy: AuthPolicy
337
+ let isSE: Bool
338
+ do {
339
+ guard try copyPrivateKey(keyId: args.keyId, context: nil) != nil else {
340
+ return finish(.failure(SignerError(.keyNotFound, "no key exists for this keyId")))
341
+ }
342
+ guard let meta = try loadMetadata(keyId: args.keyId), let p = AuthPolicy(rawValue: meta.authPolicy) else {
343
+ return finish(.failure(SignerError(.unknown, "key metadata is missing or corrupt; delete the key and re-enroll")))
344
+ }
345
+ policy = p
346
+ isSE = try isSecureEnclaveKey(keyId: args.keyId)
347
+ let currentHash = try checkBiometrics(policy: policy)
348
+ if policy == .biometryCurrentSet, let stored = meta.domainStateHash, let current = currentHash, stored != current {
349
+ return finish(.failure(SignerError(.keyInvalidated, "biometric enrollment changed; the key is no longer usable")))
350
+ }
351
+ } catch let e as SignerError {
352
+ return finish(.failure(e))
353
+ } catch {
354
+ return finish(.failure(SignerError(.unknown, "unexpected error")))
355
+ }
356
+
357
+ // A fresh context per signature, with no reuse window: every signature needs a new biometric match.
358
+ let context = LAContext()
359
+ context.touchIDAuthenticationAllowableReuseDuration = 0
360
+ context.localizedFallbackTitle = ""
361
+ context.localizedCancelTitle = args.cancelLabel
362
+
363
+ let afterAuth: (Bool, Error?) -> Void = { [weak self] success, error in
364
+ defer { context.invalidate() }
365
+ guard let self = self else { return finish(.failure(SignerError(.unknown, "module was released"))) }
366
+ guard success else {
367
+ return finish(.failure(error.map { SecureSignerCore.mapLAError($0, policy: policy) }
368
+ ?? SignerError(.authenticationFailed, "authentication failed")))
369
+ }
370
+ do {
371
+ guard let key = try self.copyPrivateKey(keyId: args.keyId, context: context) else {
372
+ return finish(.failure(SignerError(.keyNotFound, "no key exists for this keyId")))
373
+ }
374
+ let algorithm = SecKeyAlgorithm.ecdsaSignatureMessageX962SHA256
375
+ guard SecKeyIsAlgorithmSupported(key, .sign, algorithm) else {
376
+ return finish(.failure(SignerError(.signingFailed, "key does not support ECDSA-P256-SHA256")))
377
+ }
378
+ var sigError: Unmanaged<CFError>?
379
+ guard let signature = SecKeyCreateSignature(key, algorithm, payload as CFData, &sigError) as Data? else {
380
+ return finish(.failure(SecureSignerCore.mapCFError(sigError?.takeRetainedValue(), during: .sign, policy: policy)))
381
+ }
382
+ finish(.success(signature.base64EncodedString()))
383
+ } catch let e as SignerError {
384
+ finish(.failure(e))
385
+ } catch {
386
+ finish(.failure(SignerError(.signingFailed, "signing failed")))
387
+ }
388
+ }
389
+
390
+ if isSE {
391
+ var acError: Unmanaged<CFError>?
392
+ guard let access = SecAccessControlCreateWithFlags(
393
+ kCFAllocatorDefault, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
394
+ [.privateKeyUsage, policy.accessControlFlag], &acError)
395
+ else {
396
+ return finish(.failure(SecureSignerCore.mapCFError(acError?.takeRetainedValue(), during: .sign)))
397
+ }
398
+ context.evaluateAccessControl(access, operation: .useKeySign, localizedReason: args.promptMessage, reply: afterAuth)
399
+ } else {
400
+ context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: args.promptMessage, reply: afterAuth)
401
+ }
402
+ }
403
+ }
@@ -0,0 +1,30 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = 'SecureSigning'
7
+ s.version = package['version']
8
+ s.summary = package['description']
9
+ s.description = package['description']
10
+ s.license = package['license']
11
+ s.author = 'secure-signing contributors'
12
+ s.homepage = 'https://github.com/olukayode-oluseyi/secure-signing'
13
+ s.platforms = { :ios => '16.4' }
14
+ s.swift_version = '5.9'
15
+ s.source = { git: 'https://github.com/olukayode-oluseyi/secure-signing.git' }
16
+ s.static_framework = true
17
+
18
+ s.dependency 'ExpoModulesCore'
19
+ s.frameworks = 'Security', 'LocalAuthentication', 'CryptoKit'
20
+
21
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
22
+
23
+ s.source_files = '*.{h,m,swift}'
24
+
25
+ # Pure-logic tests (no Secure Enclave, no biometrics). Run with:
26
+ # pod lib testing / Xcode test target generated by `test_spec`.
27
+ s.test_spec 'Tests' do |test_spec|
28
+ test_spec.source_files = 'Tests/*.swift'
29
+ end
30
+ end
@@ -0,0 +1,143 @@
1
+ import CryptoKit
2
+ import LocalAuthentication
3
+ import Security
4
+ import XCTest
5
+
6
+ @testable import SecureSigning
7
+
8
+ /// Pure-logic tests. Hardware tests (Secure Enclave generation, biometric prompt)
9
+ /// live in the example app's device E2E suite; see docs/TESTING.md.
10
+ final class SecureSignerCoreTests: XCTestCase {
11
+ func testSpkiHeaderWrapsX963Point() throws {
12
+ var raw = Data([0x04])
13
+ raw.append(Data(repeating: 0xAB, count: 64))
14
+ let spki = try SecureSignerCore.spki(fromX963: raw)
15
+ XCTAssertEqual(spki.count, 91)
16
+ XCTAssertEqual(Array(spki.prefix(26)), SecureSignerCore.p256SpkiHeader)
17
+ XCTAssertEqual(spki.suffix(65), raw)
18
+ }
19
+
20
+ func testSpkiRejectsCompressedOrWrongLength() {
21
+ XCTAssertThrowsError(try SecureSignerCore.spki(fromX963: Data([0x02] + [UInt8](repeating: 1, count: 32))))
22
+ XCTAssertThrowsError(try SecureSignerCore.spki(fromX963: Data(repeating: 4, count: 64)))
23
+ }
24
+
25
+ /// Software P-256 key (not Secure Enclave) to check the SPKI conversion against the Security framework.
26
+ func testSpkiMatchesSecurityFrameworkKeyAndSignatureIsDer() throws {
27
+ let attrs: [String: Any] = [
28
+ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
29
+ kSecAttrKeySizeInBits as String: 256,
30
+ ]
31
+ var error: Unmanaged<CFError>?
32
+ let priv = try XCTUnwrap(SecKeyCreateRandomKey(attrs as CFDictionary, &error))
33
+ let pub = try XCTUnwrap(SecKeyCopyPublicKey(priv))
34
+ let raw = try XCTUnwrap(SecKeyCopyExternalRepresentation(pub, &error) as Data?)
35
+ let spki = try SecureSignerCore.spki(fromX963: raw)
36
+ XCTAssertEqual(spki.first, 0x30)
37
+
38
+ let msg = Data("secure-signing/test\n".utf8)
39
+ let sig = try XCTUnwrap(SecKeyCreateSignature(priv, .ecdsaSignatureMessageX962SHA256, msg as CFData, &error) as Data?)
40
+ XCTAssertEqual(sig.first, 0x30, "signature must be DER SEQUENCE")
41
+ XCTAssertTrue(SecKeyVerifySignature(pub, .ecdsaSignatureMessageX962SHA256, msg as CFData, sig as CFData, &error))
42
+ }
43
+
44
+ func testKeyIdValidation() {
45
+ XCTAssertTrue(SecureSignerCore.isValidKeyId("device-1.payout_key"))
46
+ XCTAssertFalse(SecureSignerCore.isValidKeyId(""))
47
+ XCTAssertFalse(SecureSignerCore.isValidKeyId(String(repeating: "a", count: 65)))
48
+ XCTAssertFalse(SecureSignerCore.isValidKeyId("bad/id"))
49
+ XCTAssertFalse(SecureSignerCore.isValidKeyId("ключ"))
50
+ }
51
+
52
+ func testLAErrorMapping() {
53
+ func map(_ c: LAError.Code, _ p: AuthPolicy? = nil) -> SignerErrorCode {
54
+ SecureSignerCore.mapLAError(NSError(domain: LAError.errorDomain, code: c.rawValue), policy: p).code
55
+ }
56
+ XCTAssertEqual(map(.userCancel), .authenticationCancelled)
57
+ XCTAssertEqual(map(.systemCancel), .authenticationCancelled)
58
+ XCTAssertEqual(map(.appCancel), .authenticationCancelled)
59
+ XCTAssertEqual(map(.authenticationFailed), .authenticationFailed)
60
+ XCTAssertEqual(map(.biometryLockout), .authenticationLockedOut)
61
+ XCTAssertEqual(map(.biometryNotEnrolled), .biometricsNotEnrolled)
62
+ XCTAssertEqual(map(.biometryNotEnrolled, .biometryCurrentSet), .keyInvalidated)
63
+ XCTAssertEqual(map(.biometryNotAvailable), .biometricsUnavailable)
64
+ XCTAssertEqual(map(.passcodeNotSet), .passcodeNotSet)
65
+ }
66
+
67
+ func testOSStatusMapping() {
68
+ XCTAssertEqual(SecureSignerCore.mapOSStatus(errSecUserCanceled, during: .sign).code, .authenticationCancelled)
69
+ XCTAssertEqual(SecureSignerCore.mapOSStatus(errSecAuthFailed, during: .sign).code, .authenticationFailed)
70
+ XCTAssertEqual(SecureSignerCore.mapOSStatus(errSecInteractionNotAllowed, during: .sign).code, .deviceLocked)
71
+ XCTAssertEqual(SecureSignerCore.mapOSStatus(errSecItemNotFound, during: .sign).code, .keyNotFound)
72
+ XCTAssertEqual(SecureSignerCore.mapOSStatus(errSecUnimplemented, during: .create).code, .secureHardwareUnavailable)
73
+ XCTAssertEqual(SecureSignerCore.mapOSStatus(-1, during: .sign).code, .signingFailed)
74
+ }
75
+
76
+ func testErrorMessagesCarryPlatformSuffix() {
77
+ let e = SignerError(.authenticationCancelled, "cancelled", platform: "LAError.-2")
78
+ XCTAssertEqual(e.jsMessage, "cancelled [platform:LAError.-2]")
79
+ }
80
+
81
+ func testDomainStateHash() {
82
+ XCTAssertNil(SecureSignerCore.domainStateHash(nil))
83
+ XCTAssertNil(SecureSignerCore.domainStateHash(Data()))
84
+ let a = SecureSignerCore.domainStateHash(Data([1, 2, 3]))
85
+ XCTAssertEqual(a?.count, 64)
86
+ XCTAssertNotEqual(a, SecureSignerCore.domainStateHash(Data([1, 2, 4])))
87
+ }
88
+
89
+ // MARK: key generation attributes
90
+
91
+ private func accessControl(_ flags: SecAccessControlCreateFlags) throws -> SecAccessControl {
92
+ var error: Unmanaged<CFError>?
93
+ guard let access = SecAccessControlCreateWithFlags(
94
+ nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, flags, &error)
95
+ else { throw error!.takeRetainedValue() as Error }
96
+ return access
97
+ }
98
+
99
+ func testSoftwareKeyAttributesForbidDeriveAndDecrypt() throws {
100
+ let attrs = SecureSignerCore.keyGenerationAttributes(
101
+ tag: Data("test.software".utf8), access: try accessControl([]), secureEnclave: false, permanent: false)
102
+ let priv = try XCTUnwrap(attrs[kSecPrivateKeyAttrs as String] as? [String: Any])
103
+ XCTAssertNil(attrs[kSecAttrTokenID as String])
104
+ XCTAssertEqual(priv[kSecAttrCanDerive as String] as? Bool, false)
105
+ XCTAssertEqual(priv[kSecAttrCanDecrypt as String] as? Bool, false)
106
+ XCTAssertEqual(priv[kSecAttrCanSign as String] as? Bool, true)
107
+ var error: Unmanaged<CFError>?
108
+ XCTAssertNotNil(SecKeyCreateRandomKey(attrs as CFDictionary, &error), "\(String(describing: error?.takeRetainedValue()))")
109
+ }
110
+
111
+ private func generateSecureEnclaveKey(_ flags: SecAccessControlCreateFlags, tag: String) throws {
112
+ let attrs = SecureSignerCore.keyGenerationAttributes(
113
+ tag: Data(tag.utf8), access: try accessControl(flags), secureEnclave: true, permanent: false)
114
+ let priv = try XCTUnwrap(attrs[kSecPrivateKeyAttrs as String] as? [String: Any])
115
+ XCTAssertNil(priv[kSecAttrCanDerive as String])
116
+ var error: Unmanaged<CFError>?
117
+ guard let key = SecKeyCreateRandomKey(attrs as CFDictionary, &error) else {
118
+ return XCTFail("Secure Enclave key generation failed: \(error!.takeRetainedValue())")
119
+ }
120
+ let publicKey = try XCTUnwrap(SecKeyCopyPublicKey(key))
121
+ let raw = try XCTUnwrap(SecKeyCopyExternalRepresentation(publicKey, nil) as Data?)
122
+ XCTAssertEqual(try SecureSignerCore.spki(fromX963: raw).count, 91)
123
+ }
124
+
125
+ /// Regression: the Secure Enclave rejects kSecAttrCanDerive=false with errSecParam (-50).
126
+ /// The parameter check happens regardless of the biometric flag, so this runs on any Mac
127
+ /// with a Secure Enclave, including CI runners without enrolled biometrics.
128
+ func testSecureEnclaveAcceptsGenerationAttributes() throws {
129
+ try XCTSkipUnless(SecureEnclave.isAvailable, "no Secure Enclave on this machine")
130
+ try generateSecureEnclaveKey([.privateKeyUsage], tag: "test.secure-enclave")
131
+ }
132
+
133
+ /// Same, with the production biometric policy. Needs enrolled biometrics (Touch ID);
134
+ /// without them generation fails with errSecAuthFailed, so it is skipped.
135
+ func testSecureEnclaveAcceptsGenerationAttributesWithBiometryCurrentSet() throws {
136
+ try XCTSkipUnless(SecureEnclave.isAvailable, "no Secure Enclave on this machine")
137
+ var laError: NSError?
138
+ try XCTSkipUnless(
139
+ LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &laError),
140
+ "no enrolled biometrics on this machine")
141
+ try generateSecureEnclaveKey([.privateKeyUsage, .biometryCurrentSet], tag: "test.secure-enclave.bio")
142
+ }
143
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@secure-signing/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Hardware-backed, biometric-gated ECDSA P-256 transaction signing for Expo (Secure Enclave / Android Keystore + StrongBox).",
5
+ "main": "build/index.js",
6
+ "types": "build/index.d.ts",
7
+ "files": [
8
+ "build",
9
+ "src",
10
+ "ios",
11
+ "android/build.gradle",
12
+ "android/src/main",
13
+ "plugin/build",
14
+ "app.plugin.js",
15
+ "expo-module.config.json",
16
+ "!**/__tests__",
17
+ "!**/androidTest",
18
+ "!**/test"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.build.json && tsc -p plugin/tsconfig.json",
22
+ "clean": "rm -rf build plugin/build",
23
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p plugin/tsconfig.json --noEmit",
24
+ "test": "jest"
25
+ },
26
+ "keywords": [
27
+ "react-native",
28
+ "expo",
29
+ "secure-enclave",
30
+ "android-keystore",
31
+ "strongbox",
32
+ "biometrics",
33
+ "ecdsa",
34
+ "transaction-signing"
35
+ ],
36
+ "license": "MIT",
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ },
41
+ "peerDependencies": {
42
+ "expo": ">=58.0.0",
43
+ "react-native": "*"
44
+ },
45
+ "devDependencies": {
46
+ "@expo/config-plugins": "~58.0.14",
47
+ "@types/jest": "^29.5.0",
48
+ "@types/node": "^24.0.0",
49
+ "expo": "~58.1.1",
50
+ "expo-modules-core": "~58.2.1",
51
+ "jest": "^29.7.0",
52
+ "react-native": "0.88.1",
53
+ "ts-jest": "^29.2.0",
54
+ "typescript": "~5.9.0"
55
+ },
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/olukayode-oluseyi/secure-signing.git",
59
+ "directory": "packages/react-native"
60
+ },
61
+ "homepage": "https://github.com/olukayode-oluseyi/secure-signing#readme",
62
+ "bugs": {
63
+ "url": "https://github.com/olukayode-oluseyi/secure-signing/issues"
64
+ }
65
+ }
@@ -0,0 +1,14 @@
1
+ import { ConfigPlugin, InfoPlist } from '@expo/config-plugins';
2
+ export declare const DEFAULT_FACE_ID_USAGE = "Allow $(PRODUCT_NAME) to use Face ID to approve sensitive transactions.";
3
+ export declare const ANDROID_PERMISSIONS: string[];
4
+ export type SecureSignerPluginProps = {
5
+ /**
6
+ * iOS NSFaceIDUsageDescription. Required by Apple for any Face ID use.
7
+ * Pass `false` to leave the existing value untouched (e.g. another plugin sets it).
8
+ */
9
+ faceIDPermission?: string | false;
10
+ };
11
+ /** Pure and idempotent: an explicit string wins; otherwise keep an existing value or set the default. */
12
+ export declare function applyFaceIdUsage(plist: InfoPlist, props?: SecureSignerPluginProps): InfoPlist;
13
+ declare const _default: ConfigPlugin<void | SecureSignerPluginProps>;
14
+ export default _default;