@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,197 @@
1
+ package expo.modules.securesigner
2
+
3
+ import androidx.biometric.BiometricManager
4
+ import androidx.biometric.BiometricPrompt
5
+
6
+ /** Stable error codes shared with JS (src/errors.ts). Never change a value. */
7
+ enum class SignerErrorCode(val value: String) {
8
+ NOT_AVAILABLE("NOT_AVAILABLE"),
9
+ BIOMETRICS_UNAVAILABLE("BIOMETRICS_UNAVAILABLE"),
10
+ BIOMETRICS_NOT_ENROLLED("BIOMETRICS_NOT_ENROLLED"),
11
+ PASSCODE_NOT_SET("PASSCODE_NOT_SET"),
12
+ AUTHENTICATION_CANCELLED("AUTHENTICATION_CANCELLED"),
13
+ AUTHENTICATION_FAILED("AUTHENTICATION_FAILED"),
14
+ AUTHENTICATION_LOCKED_OUT("AUTHENTICATION_LOCKED_OUT"),
15
+ AUTHENTICATION_IN_PROGRESS("AUTHENTICATION_IN_PROGRESS"),
16
+ KEY_NOT_FOUND("KEY_NOT_FOUND"),
17
+ KEY_ALREADY_EXISTS("KEY_ALREADY_EXISTS"),
18
+ KEY_INVALIDATED("KEY_INVALIDATED"),
19
+ SECURE_HARDWARE_UNAVAILABLE("SECURE_HARDWARE_UNAVAILABLE"),
20
+ STRONGBOX_UNAVAILABLE("STRONGBOX_UNAVAILABLE"),
21
+ DEVICE_LOCKED("DEVICE_LOCKED"),
22
+ ACTIVITY_UNAVAILABLE("ACTIVITY_UNAVAILABLE"),
23
+ INVALID_ARGUMENT("INVALID_ARGUMENT"),
24
+ PAYLOAD_TOO_LARGE("PAYLOAD_TOO_LARGE"),
25
+ SIGNING_FAILED("SIGNING_FAILED"),
26
+ UNKNOWN("UNKNOWN"),
27
+ }
28
+
29
+ /** Never put payloads, key IDs or key material in [message]. */
30
+ class SignerException(
31
+ val code: SignerErrorCode,
32
+ message: String,
33
+ val platform: String? = null,
34
+ cause: Throwable? = null,
35
+ ) : Exception(message, cause) {
36
+ val jsMessage: String get() = if (platform != null) "$message [platform:$platform]" else (message ?: "")
37
+ }
38
+
39
+ enum class AuthPolicy(val value: String) {
40
+ BIOMETRY_CURRENT_SET("biometry-current-set"),
41
+ BIOMETRY_ANY("biometry-any");
42
+
43
+ companion object {
44
+ fun from(v: String): AuthPolicy =
45
+ values().firstOrNull { it.value == v }
46
+ ?: throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "unknown authPolicy")
47
+ }
48
+ }
49
+
50
+ enum class HardwarePreference(val value: String) {
51
+ STRONGBOX_REQUIRED("strongbox-required"),
52
+ STRONGBOX_PREFERRED("strongbox-preferred"),
53
+ SECURE_HARDWARE("secure-hardware");
54
+
55
+ companion object {
56
+ fun from(v: String): HardwarePreference =
57
+ values().firstOrNull { it.value == v }
58
+ ?: throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "unknown hardware preference")
59
+ }
60
+ }
61
+
62
+ enum class StrongBoxPlan { STRONGBOX_ONLY, STRONGBOX_THEN_TEE, TEE_ONLY }
63
+
64
+ /** Reported security level, matching the JS `SecurityLevel` union. */
65
+ enum class SecurityLevelName(val value: String) {
66
+ STRONGBOX("strongbox"),
67
+ TEE("tee"),
68
+ SOFTWARE("software"),
69
+ UNKNOWN("unknown"),
70
+ }
71
+
72
+ object SignerPolicy {
73
+ const val MAX_PAYLOAD_BYTES = 16 * 1024
74
+ const val MAX_CHALLENGE_BYTES = 128
75
+ const val ALIAS_PREFIX = "secure-signing."
76
+ private val KEY_ID = Regex("^[A-Za-z0-9._-]{1,64}$")
77
+
78
+ // android.security.keystore.KeyProperties.SECURITY_LEVEL_* (API 31). Duplicated so this file is JVM-testable.
79
+ const val LEVEL_UNKNOWN = -2
80
+ const val LEVEL_UNKNOWN_SECURE = -1
81
+ const val LEVEL_SOFTWARE = 0
82
+ const val LEVEL_TRUSTED_ENVIRONMENT = 1
83
+ const val LEVEL_STRONGBOX = 2
84
+
85
+ fun isValidKeyId(keyId: String): Boolean = KEY_ID.matches(keyId)
86
+
87
+ fun requireValidKeyId(keyId: String) {
88
+ if (!isValidKeyId(keyId)) {
89
+ throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "keyId must match /^[A-Za-z0-9._-]{1,64}$/")
90
+ }
91
+ }
92
+
93
+ fun alias(keyId: String): String = ALIAS_PREFIX + keyId
94
+
95
+ /** Decide how to request StrongBox. StrongBox needs API 28+ and the FEATURE_STRONGBOX_KEYSTORE feature. */
96
+ fun strongBoxPlan(pref: HardwarePreference, sdkInt: Int, hasStrongBoxFeature: Boolean): StrongBoxPlan {
97
+ val supported = sdkInt >= 28 && hasStrongBoxFeature
98
+ return when (pref) {
99
+ HardwarePreference.STRONGBOX_REQUIRED ->
100
+ if (supported) StrongBoxPlan.STRONGBOX_ONLY
101
+ else throw SignerException(SignerErrorCode.STRONGBOX_UNAVAILABLE, "StrongBox is not available on this device")
102
+ HardwarePreference.STRONGBOX_PREFERRED -> if (supported) StrongBoxPlan.STRONGBOX_THEN_TEE else StrongBoxPlan.TEE_ONLY
103
+ HardwarePreference.SECURE_HARDWARE -> StrongBoxPlan.TEE_ONLY
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Classify a generated key. [securityLevel] is KeyInfo.getSecurityLevel() on API 31+ (else null);
109
+ * [insideSecureHardware] is KeyInfo.isInsideSecureHardware() (used below API 31);
110
+ * [requestedStrongBox] is true when generation succeeded with setIsStrongBoxBacked(true).
111
+ */
112
+ fun classify(securityLevel: Int?, insideSecureHardware: Boolean, requestedStrongBox: Boolean): SecurityLevelName {
113
+ if (securityLevel != null) {
114
+ return when (securityLevel) {
115
+ LEVEL_STRONGBOX -> SecurityLevelName.STRONGBOX
116
+ LEVEL_TRUSTED_ENVIRONMENT -> SecurityLevelName.TEE
117
+ LEVEL_SOFTWARE -> SecurityLevelName.SOFTWARE
118
+ else -> SecurityLevelName.UNKNOWN // LEVEL_UNKNOWN_SECURE / LEVEL_UNKNOWN
119
+ }
120
+ }
121
+ if (!insideSecureHardware) return SecurityLevelName.SOFTWARE
122
+ // Below API 31 we cannot distinguish TEE from StrongBox via KeyInfo; only trust what we requested.
123
+ return if (requestedStrongBox) SecurityLevelName.STRONGBOX else SecurityLevelName.UNKNOWN
124
+ }
125
+
126
+ /** `true`, `false`, or null for "unknown". */
127
+ fun hardwareBacked(securityLevel: Int?, insideSecureHardware: Boolean): Boolean? {
128
+ if (securityLevel != null) {
129
+ return when (securityLevel) {
130
+ LEVEL_STRONGBOX, LEVEL_TRUSTED_ENVIRONMENT, LEVEL_UNKNOWN_SECURE -> true
131
+ LEVEL_SOFTWARE -> false
132
+ else -> null
133
+ }
134
+ }
135
+ return insideSecureHardware
136
+ }
137
+
138
+ /** Throws if a freshly generated key does not meet the caller's requirements. The caller deletes the key. */
139
+ fun enforceGeneratedKey(
140
+ level: SecurityLevelName,
141
+ hardwareBacked: Boolean?,
142
+ pref: HardwarePreference,
143
+ allowNonHardwareKey: Boolean,
144
+ ) {
145
+ if (hardwareBacked != true && !allowNonHardwareKey) {
146
+ throw SignerException(
147
+ SignerErrorCode.SECURE_HARDWARE_UNAVAILABLE,
148
+ "key is not confirmed to be in secure hardware",
149
+ platform = "securityLevel=${level.value}",
150
+ )
151
+ }
152
+ if (pref == HardwarePreference.STRONGBOX_REQUIRED && level != SecurityLevelName.STRONGBOX) {
153
+ throw SignerException(SignerErrorCode.STRONGBOX_UNAVAILABLE, "key was not created in StrongBox")
154
+ }
155
+ }
156
+
157
+ /** Map BiometricManager.canAuthenticate(BIOMETRIC_STRONG) to an error, or null when usable. */
158
+ fun mapCanAuthenticate(result: Int): SignerException? = when (result) {
159
+ BiometricManager.BIOMETRIC_SUCCESS -> null
160
+ BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->
161
+ SignerException(SignerErrorCode.BIOMETRICS_NOT_ENROLLED, "no strong biometrics are enrolled", "canAuthenticate=$result")
162
+ BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,
163
+ BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE,
164
+ BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED,
165
+ BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED ->
166
+ SignerException(SignerErrorCode.BIOMETRICS_UNAVAILABLE, "strong biometric authentication is not available", "canAuthenticate=$result")
167
+ else -> SignerException(SignerErrorCode.BIOMETRICS_UNAVAILABLE, "biometric status unknown", "canAuthenticate=$result")
168
+ }
169
+
170
+ /** Map a terminal BiometricPrompt error. Non-terminal failures (onAuthenticationFailed) are not errors. */
171
+ fun mapPromptError(errorCode: Int): SignerException {
172
+ val p = "BiometricPrompt.$errorCode"
173
+ return when (errorCode) {
174
+ BiometricPrompt.ERROR_USER_CANCELED,
175
+ BiometricPrompt.ERROR_NEGATIVE_BUTTON,
176
+ BiometricPrompt.ERROR_CANCELED,
177
+ BiometricPrompt.ERROR_TIMEOUT ->
178
+ SignerException(SignerErrorCode.AUTHENTICATION_CANCELLED, "authentication was cancelled", p)
179
+ BiometricPrompt.ERROR_LOCKOUT ->
180
+ SignerException(SignerErrorCode.AUTHENTICATION_LOCKED_OUT, "too many attempts; try again later", p)
181
+ BiometricPrompt.ERROR_LOCKOUT_PERMANENT ->
182
+ SignerException(SignerErrorCode.AUTHENTICATION_LOCKED_OUT, "biometrics locked; unlock the device with its PIN, pattern or password", p)
183
+ BiometricPrompt.ERROR_NO_BIOMETRICS ->
184
+ SignerException(SignerErrorCode.BIOMETRICS_NOT_ENROLLED, "no biometrics are enrolled", p)
185
+ BiometricPrompt.ERROR_HW_NOT_PRESENT,
186
+ BiometricPrompt.ERROR_HW_UNAVAILABLE,
187
+ BiometricPrompt.ERROR_SECURITY_UPDATE_REQUIRED ->
188
+ SignerException(SignerErrorCode.BIOMETRICS_UNAVAILABLE, "biometric hardware is unavailable", p)
189
+ BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL ->
190
+ SignerException(SignerErrorCode.PASSCODE_NOT_SET, "device has no screen lock", p)
191
+ BiometricPrompt.ERROR_UNABLE_TO_PROCESS,
192
+ BiometricPrompt.ERROR_VENDOR ->
193
+ SignerException(SignerErrorCode.AUTHENTICATION_FAILED, "biometric authentication failed", p)
194
+ else -> SignerException(SignerErrorCode.UNKNOWN, "authentication error", p)
195
+ }
196
+ }
197
+ }
package/app.plugin.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./plugin/build');
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Strict UTF-8 encoder. Unlike TextEncoder, lone surrogates are rejected instead
3
+ * of being silently replaced with U+FFFD, so the signed bytes always correspond
4
+ * exactly to the string the caller passed. No Unicode normalization is applied.
5
+ */
6
+ export declare function utf8Encode(input: string): Uint8Array;
7
+ /** Standard base64 with padding. Transport encoding only; not cryptography. */
8
+ export declare function base64Encode(bytes: Uint8Array): string;
9
+ export declare function isCanonicalBase64(s: unknown): s is string;
10
+ /** Convert the caller's payload to bytes. Only `string` and `Uint8Array` are accepted: objects are never JSON-serialized. */
11
+ export declare function payloadToBytes(payload: unknown): Uint8Array;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.utf8Encode = utf8Encode;
4
+ exports.base64Encode = base64Encode;
5
+ exports.isCanonicalBase64 = isCanonicalBase64;
6
+ exports.payloadToBytes = payloadToBytes;
7
+ const errors_1 = require("./errors");
8
+ /**
9
+ * Strict UTF-8 encoder. Unlike TextEncoder, lone surrogates are rejected instead
10
+ * of being silently replaced with U+FFFD, so the signed bytes always correspond
11
+ * exactly to the string the caller passed. No Unicode normalization is applied.
12
+ */
13
+ function utf8Encode(input) {
14
+ const out = [];
15
+ for (let i = 0; i < input.length; i++) {
16
+ let cp = input.charCodeAt(i);
17
+ if (cp >= 0xd800 && cp <= 0xdbff) {
18
+ const next = i + 1 < input.length ? input.charCodeAt(i + 1) : -1;
19
+ if (next < 0xdc00 || next > 0xdfff) {
20
+ throw new errors_1.SecureSignerError('INVALID_ARGUMENT', 'payload contains an unpaired surrogate and is not valid UTF-16');
21
+ }
22
+ cp = 0x10000 + ((cp - 0xd800) << 10) + (next - 0xdc00);
23
+ i++;
24
+ }
25
+ else if (cp >= 0xdc00 && cp <= 0xdfff) {
26
+ throw new errors_1.SecureSignerError('INVALID_ARGUMENT', 'payload contains an unpaired surrogate and is not valid UTF-16');
27
+ }
28
+ if (cp < 0x80)
29
+ out.push(cp);
30
+ else if (cp < 0x800)
31
+ out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
32
+ else if (cp < 0x10000)
33
+ out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
34
+ else
35
+ out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
36
+ }
37
+ return Uint8Array.from(out);
38
+ }
39
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
40
+ /** Standard base64 with padding. Transport encoding only; not cryptography. */
41
+ function base64Encode(bytes) {
42
+ let out = '';
43
+ let i = 0;
44
+ for (; i + 2 < bytes.length; i += 3) {
45
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
46
+ out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + B64[n & 63];
47
+ }
48
+ const rem = bytes.length - i;
49
+ if (rem === 1) {
50
+ const n = bytes[i] << 16;
51
+ out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + '==';
52
+ }
53
+ else if (rem === 2) {
54
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
55
+ out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + '=';
56
+ }
57
+ return out;
58
+ }
59
+ const B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
60
+ function isCanonicalBase64(s) {
61
+ return typeof s === 'string' && s.length > 0 && B64_RE.test(s);
62
+ }
63
+ /** Convert the caller's payload to bytes. Only `string` and `Uint8Array` are accepted: objects are never JSON-serialized. */
64
+ function payloadToBytes(payload) {
65
+ if (typeof payload === 'string')
66
+ return utf8Encode(payload);
67
+ if (payload instanceof Uint8Array)
68
+ return new Uint8Array(payload); // defensive copy
69
+ throw new errors_1.SecureSignerError('INVALID_ARGUMENT', 'payload must be a string or Uint8Array; objects are not serialized automatically (sign the server-provided bytes)');
70
+ }
71
+ //# sourceMappingURL=encoding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoding.js","sourceRoot":"","sources":["../src/encoding.ts"],"names":[],"mappings":";;AAOA,gCAoBC;AAKD,oCAgBC;AAID,8CAEC;AAGD,wCAOC;AAhED,qCAA6C;AAE7C;;;;GAIG;AACH,SAAgB,UAAU,CAAC,KAAa;IACtC,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,IAAI,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,EAAE,IAAI,MAAM,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC;YACjC,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACjE,IAAI,IAAI,GAAG,MAAM,IAAI,IAAI,GAAG,MAAM,EAAE,CAAC;gBACnC,MAAM,IAAI,0BAAiB,CAAC,kBAAkB,EAAE,gEAAgE,CAAC,CAAC;YACpH,CAAC;YACD,EAAE,GAAG,OAAO,GAAG,CAAC,CAAC,EAAE,GAAG,MAA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GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAE,GAAG,GAAG,CAAC;IACjF,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,MAAM,GAAG,kEAAkE,CAAC;AAElF,SAAgB,iBAAiB,CAAC,CAAU;IAC1C,OAAO,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjE,CAAC;AAED,6HAA6H;AAC7H,SAAgB,cAAc,CAAC,OAAgB;IAC7C,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC;IAC5D,IAAI,OAAO,YAAY,UAAU;QAAE,OAAO,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,iBAAiB;IACpF,MAAM,IAAI,0BAAiB,CACzB,kBAAkB,EAClB,mHAAmH,CACpH,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ export declare const SECURE_SIGNER_ERROR_CODES: readonly ["NOT_AVAILABLE", "BIOMETRICS_UNAVAILABLE", "BIOMETRICS_NOT_ENROLLED", "PASSCODE_NOT_SET", "AUTHENTICATION_CANCELLED", "AUTHENTICATION_FAILED", "AUTHENTICATION_LOCKED_OUT", "AUTHENTICATION_IN_PROGRESS", "KEY_NOT_FOUND", "KEY_ALREADY_EXISTS", "KEY_INVALIDATED", "SECURE_HARDWARE_UNAVAILABLE", "STRONGBOX_UNAVAILABLE", "DEVICE_LOCKED", "ACTIVITY_UNAVAILABLE", "INVALID_ARGUMENT", "PAYLOAD_TOO_LARGE", "SIGNING_FAILED", "UNKNOWN"];
2
+ export type SecureSignerErrorCode = (typeof SECURE_SIGNER_ERROR_CODES)[number];
3
+ export declare class SecureSignerError extends Error {
4
+ readonly code: SecureSignerErrorCode;
5
+ /** Platform-specific detail (e.g. "LAError.userCancel", "BiometricPrompt.ERROR_LOCKOUT_PERMANENT"). Informational only. */
6
+ readonly platformCode?: string;
7
+ constructor(code: SecureSignerErrorCode, message: string, platformCode?: string);
8
+ }
9
+ export declare function isSecureSignerError(e: unknown): e is SecureSignerError;
10
+ /**
11
+ * Normalize anything thrown by the native layer into a SecureSignerError.
12
+ * Native modules reject with `code` = one of SECURE_SIGNER_ERROR_CODES and a
13
+ * message of the form "<text> [platform:<detail>]". Unknown codes become UNKNOWN
14
+ * so the machine-readable contract never leaks raw platform codes.
15
+ */
16
+ export declare function toSecureSignerError(e: unknown): SecureSignerError;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SecureSignerError = exports.SECURE_SIGNER_ERROR_CODES = void 0;
4
+ exports.isSecureSignerError = isSecureSignerError;
5
+ exports.toSecureSignerError = toSecureSignerError;
6
+ exports.SECURE_SIGNER_ERROR_CODES = [
7
+ 'NOT_AVAILABLE',
8
+ 'BIOMETRICS_UNAVAILABLE',
9
+ 'BIOMETRICS_NOT_ENROLLED',
10
+ 'PASSCODE_NOT_SET',
11
+ 'AUTHENTICATION_CANCELLED',
12
+ 'AUTHENTICATION_FAILED',
13
+ 'AUTHENTICATION_LOCKED_OUT',
14
+ 'AUTHENTICATION_IN_PROGRESS',
15
+ 'KEY_NOT_FOUND',
16
+ 'KEY_ALREADY_EXISTS',
17
+ 'KEY_INVALIDATED',
18
+ 'SECURE_HARDWARE_UNAVAILABLE',
19
+ 'STRONGBOX_UNAVAILABLE',
20
+ 'DEVICE_LOCKED',
21
+ 'ACTIVITY_UNAVAILABLE',
22
+ 'INVALID_ARGUMENT',
23
+ 'PAYLOAD_TOO_LARGE',
24
+ 'SIGNING_FAILED',
25
+ 'UNKNOWN',
26
+ ];
27
+ const CODE_SET = new Set(exports.SECURE_SIGNER_ERROR_CODES);
28
+ class SecureSignerError extends Error {
29
+ constructor(code, message, platformCode) {
30
+ super(message);
31
+ this.name = 'SecureSignerError';
32
+ this.code = code;
33
+ if (platformCode !== undefined)
34
+ this.platformCode = platformCode;
35
+ Object.setPrototypeOf(this, SecureSignerError.prototype);
36
+ }
37
+ }
38
+ exports.SecureSignerError = SecureSignerError;
39
+ function isSecureSignerError(e) {
40
+ return e instanceof SecureSignerError;
41
+ }
42
+ /**
43
+ * Normalize anything thrown by the native layer into a SecureSignerError.
44
+ * Native modules reject with `code` = one of SECURE_SIGNER_ERROR_CODES and a
45
+ * message of the form "<text> [platform:<detail>]". Unknown codes become UNKNOWN
46
+ * so the machine-readable contract never leaks raw platform codes.
47
+ */
48
+ function toSecureSignerError(e) {
49
+ if (e instanceof SecureSignerError)
50
+ return e;
51
+ const raw = (e ?? {});
52
+ const rawCode = typeof raw.code === 'string' ? raw.code.replace(/^ERR_/, '') : '';
53
+ let message = typeof raw.message === 'string' ? raw.message : 'Unknown native error';
54
+ let platformCode;
55
+ const m = /\s*\[platform:([^\]]+)\]\s*$/.exec(message);
56
+ if (m) {
57
+ platformCode = m[1];
58
+ message = message.slice(0, m.index);
59
+ }
60
+ if (CODE_SET.has(rawCode)) {
61
+ return new SecureSignerError(rawCode, message, platformCode);
62
+ }
63
+ return new SecureSignerError('UNKNOWN', message, platformCode ?? (rawCode || undefined));
64
+ }
65
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAwCA,kDAEC;AAQD,kDAeC;AAjEY,QAAA,yBAAyB,GAAG;IACvC,eAAe;IACf,wBAAwB;IACxB,yBAAyB;IACzB,kBAAkB;IAClB,0BAA0B;IAC1B,uBAAuB;IACvB,2BAA2B;IAC3B,4BAA4B;IAC5B,eAAe;IACf,oBAAoB;IACpB,iBAAiB;IACjB,6BAA6B;IAC7B,uBAAuB;IACvB,eAAe;IACf,sBAAsB;IACtB,kBAAkB;IAClB,mBAAmB;IACnB,gBAAgB;IAChB,SAAS;CACD,CAAC;AAIX,MAAM,QAAQ,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AC;IACtC,CAAC;IACD,IAAI,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QAC1B,OAAO,IAAI,iBAAiB,CAAC,OAAgC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,IAAI,iBAAiB,CAAC,SAAS,EAAE,OAAO,EAAE,YAAY,IAAI,CAAC,OAAO,IAAI,SAAS,CAAC,CAAC,CAAC;AAC3F,CAAC"}
@@ -0,0 +1,11 @@
1
+ export declare const isAvailable: () => Promise<boolean>;
2
+ export declare const getCapabilities: () => Promise<import("./types").Capabilities>;
3
+ export declare const createKey: (options: import("./types").CreateKeyOptions) => Promise<import("./types").KeyInfo>;
4
+ export declare const getKeyInfo: (keyId: string) => Promise<import("./types").KeyInfo | null>;
5
+ export declare const hasKey: (keyId: string) => Promise<boolean>;
6
+ export declare const sign: (options: import("./types").SignOptions) => Promise<import("./types").SignatureResult>;
7
+ export declare const deleteKey: (keyId: string) => Promise<void>;
8
+ export { SecureSignerError, isSecureSignerError, SECURE_SIGNER_ERROR_CODES } from './errors';
9
+ export type { SecureSignerErrorCode } from './errors';
10
+ export { SIGNING_ALGORITHM, PUBLIC_KEY_ENCODING, SIGNATURE_ENCODING, MAX_PAYLOAD_BYTES, } from './types';
11
+ export type { AuthPolicy, Capabilities, CreateKeyOptions, HardwarePreference, KeyAttestation, KeyInfo, PublicKeyEncoding, SecurityLevel, SignatureEncoding, SignatureResult, SigningAlgorithm, SignOptions, } from './types';
package/build/index.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_PAYLOAD_BYTES = exports.SIGNATURE_ENCODING = exports.PUBLIC_KEY_ENCODING = exports.SIGNING_ALGORITHM = exports.SECURE_SIGNER_ERROR_CODES = exports.isSecureSignerError = exports.SecureSignerError = exports.deleteKey = exports.sign = exports.hasKey = exports.getKeyInfo = exports.createKey = exports.getCapabilities = exports.isAvailable = void 0;
4
+ const expo_modules_core_1 = require("expo-modules-core");
5
+ const signer_1 = require("./signer");
6
+ const platform = expo_modules_core_1.Platform.OS === 'ios' || expo_modules_core_1.Platform.OS === 'android' || expo_modules_core_1.Platform.OS === 'web' ? expo_modules_core_1.Platform.OS : 'unknown';
7
+ // Optional: returns null in Expo Go / web / tests, which maps to NOT_AVAILABLE.
8
+ const native = platform === 'ios' || platform === 'android'
9
+ ? (0, expo_modules_core_1.requireOptionalNativeModule)('SecureSigner')
10
+ : null;
11
+ const signer = (0, signer_1.createSecureSigner)(native, platform);
12
+ exports.isAvailable = signer.isAvailable;
13
+ exports.getCapabilities = signer.getCapabilities;
14
+ exports.createKey = signer.createKey;
15
+ exports.getKeyInfo = signer.getKeyInfo;
16
+ exports.hasKey = signer.hasKey;
17
+ exports.sign = signer.sign;
18
+ exports.deleteKey = signer.deleteKey;
19
+ var errors_1 = require("./errors");
20
+ Object.defineProperty(exports, "SecureSignerError", { enumerable: true, get: function () { return errors_1.SecureSignerError; } });
21
+ Object.defineProperty(exports, "isSecureSignerError", { enumerable: true, get: function () { return errors_1.isSecureSignerError; } });
22
+ Object.defineProperty(exports, "SECURE_SIGNER_ERROR_CODES", { enumerable: true, get: function () { return errors_1.SECURE_SIGNER_ERROR_CODES; } });
23
+ var types_1 = require("./types");
24
+ Object.defineProperty(exports, "SIGNING_ALGORITHM", { enumerable: true, get: function () { return types_1.SIGNING_ALGORITHM; } });
25
+ Object.defineProperty(exports, "PUBLIC_KEY_ENCODING", { enumerable: true, get: function () { return types_1.PUBLIC_KEY_ENCODING; } });
26
+ Object.defineProperty(exports, "SIGNATURE_ENCODING", { enumerable: true, get: function () { return types_1.SIGNATURE_ENCODING; } });
27
+ Object.defineProperty(exports, "MAX_PAYLOAD_BYTES", { enumerable: true, get: function () { return types_1.MAX_PAYLOAD_BYTES; } });
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,yDAA0E;AAE1E,qCAA0E;AAG1E,MAAM,QAAQ,GACZ,4BAAQ,CAAC,EAAE,KAAK,KAAK,IAAI,4BAAQ,CAAC,EAAE,KAAK,SAAS,IAAI,4BAAQ,CAAC,EAAE,KAAK,KAAK,CAAC,CAAC,CAAC,4BAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAExG,gFAAgF;AAChF,MAAM,MAAM,GACV,QAAQ,KAAK,KAAK,IAAI,QAAQ,KAAK,SAAS;IAC1C,CAAC,CAAC,IAAA,+CAA2B,EAAqB,cAAc,CAAC;IACjE,CAAC,CAAC,IAAI,CAAC;AAEX,MAAM,MAAM,GAAG,IAAA,2BAAkB,EAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAEvC,QAAA,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;AACjC,QAAA,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC;AACzC,QAAA,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;AAC7B,QAAA,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;AAC/B,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;AACvB,QAAA,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AACnB,QAAA,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;AAE1C,mCAA6F;AAApF,2GAAA,iBAAiB,OAAA;AAAE,6GAAA,mBAAmB,OAAA;AAAE,mHAAA,yBAAyB,OAAA;AAE1E,iCAKiB;AAJf,0GAAA,iBAAiB,OAAA;AACjB,4GAAA,mBAAmB,OAAA;AACnB,2GAAA,kBAAkB,OAAA;AAClB,0GAAA,iBAAiB,OAAA"}
@@ -0,0 +1,17 @@
1
+ import { Capabilities, CreateKeyOptions, KeyInfo, NativeSecureSigner, SignatureResult, SignOptions } from './types';
2
+ export type Platform = Capabilities['platform'];
3
+ export interface SecureSigner {
4
+ isAvailable(): Promise<boolean>;
5
+ getCapabilities(): Promise<Capabilities>;
6
+ createKey(options: CreateKeyOptions): Promise<KeyInfo>;
7
+ getKeyInfo(keyId: string): Promise<KeyInfo | null>;
8
+ hasKey(keyId: string): Promise<boolean>;
9
+ sign(options: SignOptions): Promise<SignatureResult>;
10
+ deleteKey(keyId: string): Promise<void>;
11
+ }
12
+ export declare function assertKeyId(keyId: unknown): asserts keyId is string;
13
+ /**
14
+ * Build the public API around a native implementation. Exposed for testing and
15
+ * for advanced integrations; apps should use the default exports in index.ts.
16
+ */
17
+ export declare function createSecureSigner(native: NativeSecureSigner | null, platform: Platform): SecureSigner;
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertKeyId = assertKeyId;
4
+ exports.createSecureSigner = createSecureSigner;
5
+ const encoding_1 = require("./encoding");
6
+ const errors_1 = require("./errors");
7
+ const types_1 = require("./types");
8
+ const AUTH_POLICIES = ['biometry-current-set', 'biometry-any'];
9
+ const HARDWARE = ['strongbox-required', 'strongbox-preferred', 'secure-hardware'];
10
+ const SECURITY_LEVELS = ['secure-enclave', 'strongbox', 'tee', 'software', 'unknown'];
11
+ const MAX_CHALLENGE_BYTES = 128;
12
+ function invalid(message) {
13
+ throw new errors_1.SecureSignerError('INVALID_ARGUMENT', message);
14
+ }
15
+ function assertKeyId(keyId) {
16
+ if (typeof keyId !== 'string' || !types_1.KEY_ID_PATTERN.test(keyId)) {
17
+ invalid('keyId must match /^[A-Za-z0-9._-]{1,64}$/');
18
+ }
19
+ }
20
+ function assertPrompt(name, value, required) {
21
+ if (value === undefined && !required)
22
+ return undefined;
23
+ if (typeof value !== 'string' || value.trim().length === 0 || value.length > types_1.MAX_PROMPT_LENGTH) {
24
+ invalid(`${name} must be a non-empty string of at most ${types_1.MAX_PROMPT_LENGTH} characters`);
25
+ }
26
+ return value;
27
+ }
28
+ function assertPlainObject(o, name) {
29
+ if (typeof o !== 'object' || o === null || Array.isArray(o))
30
+ invalid(`${name} must be an object`);
31
+ }
32
+ /**
33
+ * Copy only the documented fields from native output. This guarantees the
34
+ * public result can never carry anything else (e.g. key material) even if a
35
+ * native bug added extra properties.
36
+ */
37
+ function toKeyInfo(n, expectedKeyId) {
38
+ if (!n || n.keyId !== expectedKeyId || !(0, encoding_1.isCanonicalBase64)(n.publicKey)) {
39
+ throw new errors_1.SecureSignerError('UNKNOWN', 'native module returned malformed key info');
40
+ }
41
+ const authPolicy = AUTH_POLICIES.includes(n.authPolicy)
42
+ ? n.authPolicy
43
+ : null;
44
+ if (!authPolicy)
45
+ throw new errors_1.SecureSignerError('UNKNOWN', 'native module returned unknown authPolicy');
46
+ const securityLevel = SECURITY_LEVELS.includes(n.securityLevel)
47
+ ? n.securityLevel
48
+ : 'unknown';
49
+ const hardwareBacked = n.hardwareBacked === true || n.hardwareBacked === false ? n.hardwareBacked : 'unknown';
50
+ const chain = Array.isArray(n.attestationChain) ? n.attestationChain : null;
51
+ if (chain && !chain.every(encoding_1.isCanonicalBase64)) {
52
+ throw new errors_1.SecureSignerError('UNKNOWN', 'native module returned malformed attestation chain');
53
+ }
54
+ return {
55
+ keyId: n.keyId,
56
+ publicKey: n.publicKey,
57
+ algorithm: types_1.SIGNING_ALGORITHM,
58
+ publicKeyEncoding: types_1.PUBLIC_KEY_ENCODING,
59
+ signatureEncoding: types_1.SIGNATURE_ENCODING,
60
+ authPolicy,
61
+ hardwareBacked,
62
+ securityLevel,
63
+ attestation: chain && chain.length > 0 ? { format: 'android-key', certificateChain: [...chain] } : null,
64
+ };
65
+ }
66
+ function notAvailable(platform) {
67
+ const hint = platform === 'web'
68
+ ? '@secure-signing/react-native does not support web'
69
+ : '@secure-signing/react-native native module not found. It does not run in Expo Go; use a development build (npx expo run:ios|run:android or EAS Build)';
70
+ return new errors_1.SecureSignerError('NOT_AVAILABLE', hint);
71
+ }
72
+ /**
73
+ * Build the public API around a native implementation. Exposed for testing and
74
+ * for advanced integrations; apps should use the default exports in index.ts.
75
+ */
76
+ function createSecureSigner(native, platform) {
77
+ let signInFlight = false;
78
+ const requireNative = () => {
79
+ if (!native)
80
+ throw notAvailable(platform);
81
+ return native;
82
+ };
83
+ const call = async (fn) => {
84
+ const n = requireNative();
85
+ try {
86
+ return await fn(n);
87
+ }
88
+ catch (e) {
89
+ throw (0, errors_1.toSecureSignerError)(e);
90
+ }
91
+ };
92
+ return {
93
+ async isAvailable() {
94
+ if (!native)
95
+ return false;
96
+ try {
97
+ return (await native.isAvailable()) === true;
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ },
103
+ async getCapabilities() {
104
+ if (!native) {
105
+ return {
106
+ platform,
107
+ secureEnclaveAvailable: false,
108
+ strongBoxAvailable: false,
109
+ biometricAuthenticationAvailable: false,
110
+ biometricAuthenticationEnrolled: false,
111
+ deviceSecure: false,
112
+ };
113
+ }
114
+ const c = await call((n) => n.getCapabilities());
115
+ return {
116
+ platform: c.platform === 'ios' || c.platform === 'android' ? c.platform : 'unknown',
117
+ secureEnclaveAvailable: c.secureEnclaveAvailable === true,
118
+ strongBoxAvailable: c.strongBoxAvailable === true,
119
+ biometricAuthenticationAvailable: c.biometricAuthenticationAvailable === true,
120
+ biometricAuthenticationEnrolled: c.biometricAuthenticationEnrolled === true,
121
+ deviceSecure: c.deviceSecure === true,
122
+ };
123
+ },
124
+ async createKey(options) {
125
+ assertPlainObject(options, 'options');
126
+ assertKeyId(options.keyId);
127
+ const authPolicy = options.authPolicy ?? 'biometry-current-set';
128
+ if (!AUTH_POLICIES.includes(authPolicy))
129
+ invalid(`authPolicy must be one of ${AUTH_POLICIES.join(', ')}`);
130
+ const hardware = options.hardware ?? 'strongbox-preferred';
131
+ if (!HARDWARE.includes(hardware))
132
+ invalid(`hardware must be one of ${HARDWARE.join(', ')}`);
133
+ if (options.allowNonHardwareKey !== undefined && typeof options.allowNonHardwareKey !== 'boolean') {
134
+ invalid('allowNonHardwareKey must be a boolean');
135
+ }
136
+ let attestationChallenge = null;
137
+ if (options.attestationChallenge !== undefined) {
138
+ const c = options.attestationChallenge;
139
+ const bytes = typeof c === 'string' ? (0, encoding_1.utf8Encode)(c) : c instanceof Uint8Array ? new Uint8Array(c) : null;
140
+ if (!bytes || bytes.length === 0 || bytes.length > MAX_CHALLENGE_BYTES) {
141
+ invalid(`attestationChallenge must be a non-empty string or Uint8Array of at most ${MAX_CHALLENGE_BYTES} bytes`);
142
+ }
143
+ attestationChallenge = (0, encoding_1.base64Encode)(bytes);
144
+ }
145
+ const keyId = options.keyId;
146
+ const result = await call((n) => n.createKey({
147
+ keyId,
148
+ authPolicy,
149
+ hardware,
150
+ attestationChallenge,
151
+ allowNonHardwareKey: options.allowNonHardwareKey === true,
152
+ }));
153
+ return toKeyInfo(result, keyId);
154
+ },
155
+ async getKeyInfo(keyId) {
156
+ assertKeyId(keyId);
157
+ const result = await call((n) => n.getKeyInfo(keyId));
158
+ if (result === null || result === undefined)
159
+ return null;
160
+ const info = toKeyInfo(result, keyId);
161
+ return { ...info, attestation: null };
162
+ },
163
+ async hasKey(keyId) {
164
+ assertKeyId(keyId);
165
+ return (await call((n) => n.hasKey(keyId))) === true;
166
+ },
167
+ async sign(options) {
168
+ assertPlainObject(options, 'options');
169
+ assertKeyId(options.keyId);
170
+ const promptMessage = assertPrompt('promptMessage', options.promptMessage, true);
171
+ const promptTitle = assertPrompt('promptTitle', options.promptTitle, false) ?? promptMessage;
172
+ const cancelLabel = assertPrompt('cancelLabel', options.cancelLabel, false) ?? 'Cancel';
173
+ const bytes = (0, encoding_1.payloadToBytes)(options.payload);
174
+ if (bytes.length === 0)
175
+ invalid('payload must not be empty');
176
+ if (bytes.length > types_1.MAX_PAYLOAD_BYTES) {
177
+ throw new errors_1.SecureSignerError('PAYLOAD_TOO_LARGE', `payload exceeds ${types_1.MAX_PAYLOAD_BYTES} bytes`);
178
+ }
179
+ const n = requireNative();
180
+ if (signInFlight) {
181
+ throw new errors_1.SecureSignerError('AUTHENTICATION_IN_PROGRESS', 'another sign() call is awaiting authentication');
182
+ }
183
+ const keyId = options.keyId;
184
+ signInFlight = true;
185
+ try {
186
+ const result = await n.sign({ keyId, payload: (0, encoding_1.base64Encode)(bytes), promptMessage, promptTitle, cancelLabel });
187
+ if (!result || !(0, encoding_1.isCanonicalBase64)(result.signature)) {
188
+ throw new errors_1.SecureSignerError('SIGNING_FAILED', 'native module returned a malformed signature');
189
+ }
190
+ return {
191
+ keyId,
192
+ signature: result.signature,
193
+ algorithm: types_1.SIGNING_ALGORITHM,
194
+ signatureEncoding: types_1.SIGNATURE_ENCODING,
195
+ };
196
+ }
197
+ catch (e) {
198
+ throw (0, errors_1.toSecureSignerError)(e);
199
+ }
200
+ finally {
201
+ signInFlight = false;
202
+ }
203
+ },
204
+ async deleteKey(keyId) {
205
+ assertKeyId(keyId);
206
+ await call((n) => n.deleteKey(keyId));
207
+ },
208
+ };
209
+ }
210
+ //# sourceMappingURL=signer.js.map