@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,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ANDROID_PERMISSIONS = exports.DEFAULT_FACE_ID_USAGE = void 0;
4
+ exports.applyFaceIdUsage = applyFaceIdUsage;
5
+ const config_plugins_1 = require("@expo/config-plugins");
6
+ const PACKAGE_NAME = '@secure-signing/react-native';
7
+ const PACKAGE_VERSION = '0.1.0';
8
+ exports.DEFAULT_FACE_ID_USAGE = 'Allow $(PRODUCT_NAME) to use Face ID to approve sensitive transactions.';
9
+ exports.ANDROID_PERMISSIONS = ['android.permission.USE_BIOMETRIC'];
10
+ /** Pure and idempotent: an explicit string wins; otherwise keep an existing value or set the default. */
11
+ function applyFaceIdUsage(plist, props = {}) {
12
+ var _a, _b;
13
+ if (props.faceIDPermission === false)
14
+ return plist;
15
+ const value = (_b = (_a = props.faceIDPermission) !== null && _a !== void 0 ? _a : plist.NSFaceIDUsageDescription) !== null && _b !== void 0 ? _b : exports.DEFAULT_FACE_ID_USAGE;
16
+ if (typeof value !== 'string' || value.trim() === '') {
17
+ throw new Error(`${PACKAGE_NAME}: faceIDPermission must be a non-empty string`);
18
+ }
19
+ return { ...plist, NSFaceIDUsageDescription: value };
20
+ }
21
+ const withSecureSigner = (config, props) => {
22
+ const p = props !== null && props !== void 0 ? props : {};
23
+ config = (0, config_plugins_1.withInfoPlist)(config, (c) => {
24
+ c.modResults = applyFaceIdUsage(c.modResults, p);
25
+ return c;
26
+ });
27
+ // The library manifest also declares USE_BIOMETRIC; declaring it in the app keeps it visible and survives manifest merging rules.
28
+ config = config_plugins_1.AndroidConfig.Permissions.withPermissions(config, exports.ANDROID_PERMISSIONS);
29
+ return config;
30
+ };
31
+ exports.default = (0, config_plugins_1.createRunOncePlugin)(withSecureSigner, PACKAGE_NAME, PACKAGE_VERSION);
@@ -0,0 +1,65 @@
1
+ import { SecureSignerError } from './errors';
2
+
3
+ /**
4
+ * Strict UTF-8 encoder. Unlike TextEncoder, lone surrogates are rejected instead
5
+ * of being silently replaced with U+FFFD, so the signed bytes always correspond
6
+ * exactly to the string the caller passed. No Unicode normalization is applied.
7
+ */
8
+ export function utf8Encode(input: string): Uint8Array {
9
+ const out: number[] = [];
10
+ for (let i = 0; i < input.length; i++) {
11
+ let cp = input.charCodeAt(i);
12
+ if (cp >= 0xd800 && cp <= 0xdbff) {
13
+ const next = i + 1 < input.length ? input.charCodeAt(i + 1) : -1;
14
+ if (next < 0xdc00 || next > 0xdfff) {
15
+ throw new SecureSignerError('INVALID_ARGUMENT', 'payload contains an unpaired surrogate and is not valid UTF-16');
16
+ }
17
+ cp = 0x10000 + ((cp - 0xd800) << 10) + (next - 0xdc00);
18
+ i++;
19
+ } else if (cp >= 0xdc00 && cp <= 0xdfff) {
20
+ throw new SecureSignerError('INVALID_ARGUMENT', 'payload contains an unpaired surrogate and is not valid UTF-16');
21
+ }
22
+ if (cp < 0x80) out.push(cp);
23
+ else if (cp < 0x800) out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
24
+ else if (cp < 0x10000) out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
25
+ else out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
26
+ }
27
+ return Uint8Array.from(out);
28
+ }
29
+
30
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
31
+
32
+ /** Standard base64 with padding. Transport encoding only; not cryptography. */
33
+ export function base64Encode(bytes: Uint8Array): string {
34
+ let out = '';
35
+ let i = 0;
36
+ for (; i + 2 < bytes.length; i += 3) {
37
+ const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!;
38
+ out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + B64[n & 63]!;
39
+ }
40
+ const rem = bytes.length - i;
41
+ if (rem === 1) {
42
+ const n = bytes[i]! << 16;
43
+ out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + '==';
44
+ } else if (rem === 2) {
45
+ const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8);
46
+ out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + '=';
47
+ }
48
+ return out;
49
+ }
50
+
51
+ const B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
52
+
53
+ export function isCanonicalBase64(s: unknown): s is string {
54
+ return typeof s === 'string' && s.length > 0 && B64_RE.test(s);
55
+ }
56
+
57
+ /** Convert the caller's payload to bytes. Only `string` and `Uint8Array` are accepted: objects are never JSON-serialized. */
58
+ export function payloadToBytes(payload: unknown): Uint8Array {
59
+ if (typeof payload === 'string') return utf8Encode(payload);
60
+ if (payload instanceof Uint8Array) return new Uint8Array(payload); // defensive copy
61
+ throw new SecureSignerError(
62
+ 'INVALID_ARGUMENT',
63
+ 'payload must be a string or Uint8Array; objects are not serialized automatically (sign the server-provided bytes)',
64
+ );
65
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,66 @@
1
+ export const SECURE_SIGNER_ERROR_CODES = [
2
+ 'NOT_AVAILABLE',
3
+ 'BIOMETRICS_UNAVAILABLE',
4
+ 'BIOMETRICS_NOT_ENROLLED',
5
+ 'PASSCODE_NOT_SET',
6
+ 'AUTHENTICATION_CANCELLED',
7
+ 'AUTHENTICATION_FAILED',
8
+ 'AUTHENTICATION_LOCKED_OUT',
9
+ 'AUTHENTICATION_IN_PROGRESS',
10
+ 'KEY_NOT_FOUND',
11
+ 'KEY_ALREADY_EXISTS',
12
+ 'KEY_INVALIDATED',
13
+ 'SECURE_HARDWARE_UNAVAILABLE',
14
+ 'STRONGBOX_UNAVAILABLE',
15
+ 'DEVICE_LOCKED',
16
+ 'ACTIVITY_UNAVAILABLE',
17
+ 'INVALID_ARGUMENT',
18
+ 'PAYLOAD_TOO_LARGE',
19
+ 'SIGNING_FAILED',
20
+ 'UNKNOWN',
21
+ ] as const;
22
+
23
+ export type SecureSignerErrorCode = (typeof SECURE_SIGNER_ERROR_CODES)[number];
24
+
25
+ const CODE_SET: ReadonlySet<string> = new Set(SECURE_SIGNER_ERROR_CODES);
26
+
27
+ export class SecureSignerError extends Error {
28
+ readonly code: SecureSignerErrorCode;
29
+ /** Platform-specific detail (e.g. "LAError.userCancel", "BiometricPrompt.ERROR_LOCKOUT_PERMANENT"). Informational only. */
30
+ readonly platformCode?: string;
31
+
32
+ constructor(code: SecureSignerErrorCode, message: string, platformCode?: string) {
33
+ super(message);
34
+ this.name = 'SecureSignerError';
35
+ this.code = code;
36
+ if (platformCode !== undefined) this.platformCode = platformCode;
37
+ Object.setPrototypeOf(this, SecureSignerError.prototype);
38
+ }
39
+ }
40
+
41
+ export function isSecureSignerError(e: unknown): e is SecureSignerError {
42
+ return e instanceof SecureSignerError;
43
+ }
44
+
45
+ /**
46
+ * Normalize anything thrown by the native layer into a SecureSignerError.
47
+ * Native modules reject with `code` = one of SECURE_SIGNER_ERROR_CODES and a
48
+ * message of the form "<text> [platform:<detail>]". Unknown codes become UNKNOWN
49
+ * so the machine-readable contract never leaks raw platform codes.
50
+ */
51
+ export function toSecureSignerError(e: unknown): SecureSignerError {
52
+ if (e instanceof SecureSignerError) return e;
53
+ const raw = (e ?? {}) as { code?: unknown; message?: unknown };
54
+ const rawCode = typeof raw.code === 'string' ? raw.code.replace(/^ERR_/, '') : '';
55
+ let message = typeof raw.message === 'string' ? raw.message : 'Unknown native error';
56
+ let platformCode: string | undefined;
57
+ const m = /\s*\[platform:([^\]]+)\]\s*$/.exec(message);
58
+ if (m) {
59
+ platformCode = m[1];
60
+ message = message.slice(0, m.index);
61
+ }
62
+ if (CODE_SET.has(rawCode)) {
63
+ return new SecureSignerError(rawCode as SecureSignerErrorCode, message, platformCode);
64
+ }
65
+ return new SecureSignerError('UNKNOWN', message, platformCode ?? (rawCode || undefined));
66
+ }
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { Platform, requireOptionalNativeModule } from 'expo-modules-core';
2
+
3
+ import { createSecureSigner, Platform as SignerPlatform } from './signer';
4
+ import type { NativeSecureSigner } from './types';
5
+
6
+ const platform: SignerPlatform =
7
+ Platform.OS === 'ios' || Platform.OS === 'android' || Platform.OS === 'web' ? Platform.OS : 'unknown';
8
+
9
+ // Optional: returns null in Expo Go / web / tests, which maps to NOT_AVAILABLE.
10
+ const native =
11
+ platform === 'ios' || platform === 'android'
12
+ ? requireOptionalNativeModule<NativeSecureSigner>('SecureSigner')
13
+ : null;
14
+
15
+ const signer = createSecureSigner(native, platform);
16
+
17
+ export const isAvailable = signer.isAvailable;
18
+ export const getCapabilities = signer.getCapabilities;
19
+ export const createKey = signer.createKey;
20
+ export const getKeyInfo = signer.getKeyInfo;
21
+ export const hasKey = signer.hasKey;
22
+ export const sign = signer.sign;
23
+ export const deleteKey = signer.deleteKey;
24
+
25
+ export { SecureSignerError, isSecureSignerError, SECURE_SIGNER_ERROR_CODES } from './errors';
26
+ export type { SecureSignerErrorCode } from './errors';
27
+ export {
28
+ SIGNING_ALGORITHM,
29
+ PUBLIC_KEY_ENCODING,
30
+ SIGNATURE_ENCODING,
31
+ MAX_PAYLOAD_BYTES,
32
+ } from './types';
33
+ export type {
34
+ AuthPolicy,
35
+ Capabilities,
36
+ CreateKeyOptions,
37
+ HardwarePreference,
38
+ KeyAttestation,
39
+ KeyInfo,
40
+ PublicKeyEncoding,
41
+ SecurityLevel,
42
+ SignatureEncoding,
43
+ SignatureResult,
44
+ SigningAlgorithm,
45
+ SignOptions,
46
+ } from './types';
package/src/signer.ts ADDED
@@ -0,0 +1,241 @@
1
+ import { base64Encode, isCanonicalBase64, payloadToBytes, utf8Encode } from './encoding';
2
+ import { SecureSignerError, toSecureSignerError } from './errors';
3
+ import {
4
+ AuthPolicy,
5
+ Capabilities,
6
+ CreateKeyOptions,
7
+ HardwarePreference,
8
+ KEY_ID_PATTERN,
9
+ KeyInfo,
10
+ MAX_PAYLOAD_BYTES,
11
+ MAX_PROMPT_LENGTH,
12
+ NativeKeyInfo,
13
+ NativeSecureSigner,
14
+ PUBLIC_KEY_ENCODING,
15
+ SecurityLevel,
16
+ SIGNATURE_ENCODING,
17
+ SIGNING_ALGORITHM,
18
+ SignatureResult,
19
+ SignOptions,
20
+ } from './types';
21
+
22
+ const AUTH_POLICIES: readonly AuthPolicy[] = ['biometry-current-set', 'biometry-any'];
23
+ const HARDWARE: readonly HardwarePreference[] = ['strongbox-required', 'strongbox-preferred', 'secure-hardware'];
24
+ const SECURITY_LEVELS: readonly SecurityLevel[] = ['secure-enclave', 'strongbox', 'tee', 'software', 'unknown'];
25
+ const MAX_CHALLENGE_BYTES = 128;
26
+
27
+ export type Platform = Capabilities['platform'];
28
+
29
+ export interface SecureSigner {
30
+ isAvailable(): Promise<boolean>;
31
+ getCapabilities(): Promise<Capabilities>;
32
+ createKey(options: CreateKeyOptions): Promise<KeyInfo>;
33
+ getKeyInfo(keyId: string): Promise<KeyInfo | null>;
34
+ hasKey(keyId: string): Promise<boolean>;
35
+ sign(options: SignOptions): Promise<SignatureResult>;
36
+ deleteKey(keyId: string): Promise<void>;
37
+ }
38
+
39
+ function invalid(message: string): never {
40
+ throw new SecureSignerError('INVALID_ARGUMENT', message);
41
+ }
42
+
43
+ export function assertKeyId(keyId: unknown): asserts keyId is string {
44
+ if (typeof keyId !== 'string' || !KEY_ID_PATTERN.test(keyId)) {
45
+ invalid('keyId must match /^[A-Za-z0-9._-]{1,64}$/');
46
+ }
47
+ }
48
+
49
+ function assertPrompt(name: string, value: unknown, required: boolean): string | undefined {
50
+ if (value === undefined && !required) return undefined;
51
+ if (typeof value !== 'string' || value.trim().length === 0 || value.length > MAX_PROMPT_LENGTH) {
52
+ invalid(`${name} must be a non-empty string of at most ${MAX_PROMPT_LENGTH} characters`);
53
+ }
54
+ return value;
55
+ }
56
+
57
+ function assertPlainObject(o: unknown, name: string): asserts o is Record<string, unknown> {
58
+ if (typeof o !== 'object' || o === null || Array.isArray(o)) invalid(`${name} must be an object`);
59
+ }
60
+
61
+ /**
62
+ * Copy only the documented fields from native output. This guarantees the
63
+ * public result can never carry anything else (e.g. key material) even if a
64
+ * native bug added extra properties.
65
+ */
66
+ function toKeyInfo(n: NativeKeyInfo | null | undefined, expectedKeyId: string): KeyInfo {
67
+ if (!n || n.keyId !== expectedKeyId || !isCanonicalBase64(n.publicKey)) {
68
+ throw new SecureSignerError('UNKNOWN', 'native module returned malformed key info');
69
+ }
70
+ const authPolicy = (AUTH_POLICIES as readonly string[]).includes(n.authPolicy)
71
+ ? (n.authPolicy as AuthPolicy)
72
+ : null;
73
+ if (!authPolicy) throw new SecureSignerError('UNKNOWN', 'native module returned unknown authPolicy');
74
+ const securityLevel = (SECURITY_LEVELS as readonly string[]).includes(n.securityLevel)
75
+ ? (n.securityLevel as SecurityLevel)
76
+ : 'unknown';
77
+ const hardwareBacked = n.hardwareBacked === true || n.hardwareBacked === false ? n.hardwareBacked : 'unknown';
78
+ const chain = Array.isArray(n.attestationChain) ? n.attestationChain : null;
79
+ if (chain && !chain.every(isCanonicalBase64)) {
80
+ throw new SecureSignerError('UNKNOWN', 'native module returned malformed attestation chain');
81
+ }
82
+ return {
83
+ keyId: n.keyId,
84
+ publicKey: n.publicKey,
85
+ algorithm: SIGNING_ALGORITHM,
86
+ publicKeyEncoding: PUBLIC_KEY_ENCODING,
87
+ signatureEncoding: SIGNATURE_ENCODING,
88
+ authPolicy,
89
+ hardwareBacked,
90
+ securityLevel,
91
+ attestation: chain && chain.length > 0 ? { format: 'android-key', certificateChain: [...chain] } : null,
92
+ };
93
+ }
94
+
95
+ function notAvailable(platform: Platform): SecureSignerError {
96
+ const hint =
97
+ platform === 'web'
98
+ ? '@secure-signing/react-native does not support web'
99
+ : '@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)';
100
+ return new SecureSignerError('NOT_AVAILABLE', hint);
101
+ }
102
+
103
+ /**
104
+ * Build the public API around a native implementation. Exposed for testing and
105
+ * for advanced integrations; apps should use the default exports in index.ts.
106
+ */
107
+ export function createSecureSigner(native: NativeSecureSigner | null, platform: Platform): SecureSigner {
108
+ let signInFlight = false;
109
+
110
+ const requireNative = (): NativeSecureSigner => {
111
+ if (!native) throw notAvailable(platform);
112
+ return native;
113
+ };
114
+
115
+ const call = async <T>(fn: (n: NativeSecureSigner) => Promise<T>): Promise<T> => {
116
+ const n = requireNative();
117
+ try {
118
+ return await fn(n);
119
+ } catch (e) {
120
+ throw toSecureSignerError(e);
121
+ }
122
+ };
123
+
124
+ return {
125
+ async isAvailable() {
126
+ if (!native) return false;
127
+ try {
128
+ return (await native.isAvailable()) === true;
129
+ } catch {
130
+ return false;
131
+ }
132
+ },
133
+
134
+ async getCapabilities() {
135
+ if (!native) {
136
+ return {
137
+ platform,
138
+ secureEnclaveAvailable: false,
139
+ strongBoxAvailable: false,
140
+ biometricAuthenticationAvailable: false,
141
+ biometricAuthenticationEnrolled: false,
142
+ deviceSecure: false,
143
+ };
144
+ }
145
+ const c = await call((n) => n.getCapabilities());
146
+ return {
147
+ platform: c.platform === 'ios' || c.platform === 'android' ? c.platform : 'unknown',
148
+ secureEnclaveAvailable: c.secureEnclaveAvailable === true,
149
+ strongBoxAvailable: c.strongBoxAvailable === true,
150
+ biometricAuthenticationAvailable: c.biometricAuthenticationAvailable === true,
151
+ biometricAuthenticationEnrolled: c.biometricAuthenticationEnrolled === true,
152
+ deviceSecure: c.deviceSecure === true,
153
+ };
154
+ },
155
+
156
+ async createKey(options) {
157
+ assertPlainObject(options, 'options');
158
+ assertKeyId(options.keyId);
159
+ const authPolicy = options.authPolicy ?? 'biometry-current-set';
160
+ if (!AUTH_POLICIES.includes(authPolicy)) invalid(`authPolicy must be one of ${AUTH_POLICIES.join(', ')}`);
161
+ const hardware = options.hardware ?? 'strongbox-preferred';
162
+ if (!HARDWARE.includes(hardware)) invalid(`hardware must be one of ${HARDWARE.join(', ')}`);
163
+ if (options.allowNonHardwareKey !== undefined && typeof options.allowNonHardwareKey !== 'boolean') {
164
+ invalid('allowNonHardwareKey must be a boolean');
165
+ }
166
+ let attestationChallenge: string | null = null;
167
+ if (options.attestationChallenge !== undefined) {
168
+ const c = options.attestationChallenge;
169
+ const bytes = typeof c === 'string' ? utf8Encode(c) : c instanceof Uint8Array ? new Uint8Array(c) : null;
170
+ if (!bytes || bytes.length === 0 || bytes.length > MAX_CHALLENGE_BYTES) {
171
+ invalid(`attestationChallenge must be a non-empty string or Uint8Array of at most ${MAX_CHALLENGE_BYTES} bytes`);
172
+ }
173
+ attestationChallenge = base64Encode(bytes);
174
+ }
175
+ const keyId = options.keyId;
176
+ const result = await call((n) =>
177
+ n.createKey({
178
+ keyId,
179
+ authPolicy,
180
+ hardware,
181
+ attestationChallenge,
182
+ allowNonHardwareKey: options.allowNonHardwareKey === true,
183
+ }),
184
+ );
185
+ return toKeyInfo(result, keyId);
186
+ },
187
+
188
+ async getKeyInfo(keyId) {
189
+ assertKeyId(keyId);
190
+ const result = await call((n) => n.getKeyInfo(keyId));
191
+ if (result === null || result === undefined) return null;
192
+ const info = toKeyInfo(result, keyId);
193
+ return { ...info, attestation: null };
194
+ },
195
+
196
+ async hasKey(keyId) {
197
+ assertKeyId(keyId);
198
+ return (await call((n) => n.hasKey(keyId))) === true;
199
+ },
200
+
201
+ async sign(options) {
202
+ assertPlainObject(options, 'options');
203
+ assertKeyId(options.keyId);
204
+ const promptMessage = assertPrompt('promptMessage', options.promptMessage, true)!;
205
+ const promptTitle = assertPrompt('promptTitle', options.promptTitle, false) ?? promptMessage;
206
+ const cancelLabel = assertPrompt('cancelLabel', options.cancelLabel, false) ?? 'Cancel';
207
+ const bytes = payloadToBytes(options.payload);
208
+ if (bytes.length === 0) invalid('payload must not be empty');
209
+ if (bytes.length > MAX_PAYLOAD_BYTES) {
210
+ throw new SecureSignerError('PAYLOAD_TOO_LARGE', `payload exceeds ${MAX_PAYLOAD_BYTES} bytes`);
211
+ }
212
+ const n = requireNative();
213
+ if (signInFlight) {
214
+ throw new SecureSignerError('AUTHENTICATION_IN_PROGRESS', 'another sign() call is awaiting authentication');
215
+ }
216
+ const keyId = options.keyId;
217
+ signInFlight = true;
218
+ try {
219
+ const result = await n.sign({ keyId, payload: base64Encode(bytes), promptMessage, promptTitle, cancelLabel });
220
+ if (!result || !isCanonicalBase64(result.signature)) {
221
+ throw new SecureSignerError('SIGNING_FAILED', 'native module returned a malformed signature');
222
+ }
223
+ return {
224
+ keyId,
225
+ signature: result.signature,
226
+ algorithm: SIGNING_ALGORITHM,
227
+ signatureEncoding: SIGNATURE_ENCODING,
228
+ };
229
+ } catch (e) {
230
+ throw toSecureSignerError(e);
231
+ } finally {
232
+ signInFlight = false;
233
+ }
234
+ },
235
+
236
+ async deleteKey(keyId) {
237
+ assertKeyId(keyId);
238
+ await call((n) => n.deleteKey(keyId));
239
+ },
240
+ };
241
+ }
package/src/types.ts ADDED
@@ -0,0 +1,123 @@
1
+ export const SIGNING_ALGORITHM = 'ECDSA-P256-SHA256' as const;
2
+ export const PUBLIC_KEY_ENCODING = 'spki-der-base64' as const;
3
+ export const SIGNATURE_ENCODING = 'ecdsa-der-base64' as const;
4
+
5
+ /** Maximum payload size in bytes. Approval payloads are small; anything larger is a bug. */
6
+ export const MAX_PAYLOAD_BYTES = 16 * 1024;
7
+ export const MAX_PROMPT_LENGTH = 256;
8
+ export const KEY_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
9
+
10
+ export type SigningAlgorithm = typeof SIGNING_ALGORITHM;
11
+ export type PublicKeyEncoding = typeof PUBLIC_KEY_ENCODING;
12
+ export type SignatureEncoding = typeof SIGNATURE_ENCODING;
13
+
14
+ /**
15
+ * Which biometric enrollment state the key is bound to.
16
+ * - `biometry-current-set`: key is permanently invalidated if biometrics are added or removed (recommended).
17
+ * - `biometry-any`: key survives enrollment changes; any enrolled biometric can authorize.
18
+ * There is deliberately no policy without authentication.
19
+ */
20
+ export type AuthPolicy = 'biometry-current-set' | 'biometry-any';
21
+
22
+ /**
23
+ * Hardware requirement. iOS always uses the Secure Enclave (StrongBox options map to it).
24
+ * - `strongbox-required`: Android fails with STRONGBOX_UNAVAILABLE if no StrongBox.
25
+ * - `strongbox-preferred`: Android tries StrongBox, then TEE. Reported in `securityLevel`.
26
+ * - `secure-hardware`: Android TEE or better, StrongBox not requested.
27
+ */
28
+ export type HardwarePreference = 'strongbox-required' | 'strongbox-preferred' | 'secure-hardware';
29
+
30
+ export type SecurityLevel = 'secure-enclave' | 'strongbox' | 'tee' | 'software' | 'unknown';
31
+
32
+ export type CreateKeyOptions = {
33
+ keyId: string;
34
+ authPolicy?: AuthPolicy;
35
+ hardware?: HardwarePreference;
36
+ /** Server-issued, single-use challenge embedded in the Android key attestation certificate. */
37
+ attestationChallenge?: string | Uint8Array;
38
+ /**
39
+ * Allow a key that is NOT protected by secure hardware (emulators/simulators).
40
+ * The key still requires biometric authentication, and is reported as
41
+ * `hardwareBacked: false`, `securityLevel: "software"`. Never enable in production builds.
42
+ */
43
+ allowNonHardwareKey?: boolean;
44
+ };
45
+
46
+ export type KeyAttestation = {
47
+ format: 'android-key';
48
+ /** DER X.509 certificates, base64, leaf first. */
49
+ certificateChain: string[];
50
+ };
51
+
52
+ export type KeyInfo = {
53
+ keyId: string;
54
+ publicKey: string;
55
+ algorithm: SigningAlgorithm;
56
+ publicKeyEncoding: PublicKeyEncoding;
57
+ signatureEncoding: SignatureEncoding;
58
+ authPolicy: AuthPolicy;
59
+ hardwareBacked: boolean | 'unknown';
60
+ securityLevel: SecurityLevel;
61
+ /** Present only in the result of `createKey` on Android when a challenge was supplied. */
62
+ attestation: KeyAttestation | null;
63
+ };
64
+
65
+ export type SignOptions = {
66
+ keyId: string;
67
+ /** Exact bytes to sign. Strings are encoded as UTF-8 without normalization. */
68
+ payload: string | Uint8Array;
69
+ /** Shown in the biometric prompt (iOS reason / Android subtitle). Required. */
70
+ promptMessage: string;
71
+ /** Android prompt title. Defaults to promptMessage. */
72
+ promptTitle?: string;
73
+ /** Android negative button label. Defaults to "Cancel". */
74
+ cancelLabel?: string;
75
+ };
76
+
77
+ export type SignatureResult = {
78
+ keyId: string;
79
+ signature: string;
80
+ algorithm: SigningAlgorithm;
81
+ signatureEncoding: SignatureEncoding;
82
+ };
83
+
84
+ export type Capabilities = {
85
+ platform: 'ios' | 'android' | 'web' | 'unknown';
86
+ secureEnclaveAvailable: boolean;
87
+ strongBoxAvailable: boolean;
88
+ biometricAuthenticationAvailable: boolean;
89
+ biometricAuthenticationEnrolled: boolean;
90
+ deviceSecure: boolean;
91
+ };
92
+
93
+ /** Shape exchanged with the native module. Binary values cross the bridge as base64. */
94
+ export type NativeKeyInfo = {
95
+ keyId: string;
96
+ publicKey: string;
97
+ authPolicy: string;
98
+ hardwareBacked: boolean | 'unknown';
99
+ securityLevel: string;
100
+ attestationChain?: string[] | null;
101
+ };
102
+
103
+ export interface NativeSecureSigner {
104
+ isAvailable(): Promise<boolean>;
105
+ getCapabilities(): Promise<Omit<Capabilities, 'platform'> & { platform: string }>;
106
+ createKey(options: {
107
+ keyId: string;
108
+ authPolicy: AuthPolicy;
109
+ hardware: HardwarePreference;
110
+ attestationChallenge: string | null;
111
+ allowNonHardwareKey: boolean;
112
+ }): Promise<NativeKeyInfo>;
113
+ getKeyInfo(keyId: string): Promise<NativeKeyInfo | null>;
114
+ hasKey(keyId: string): Promise<boolean>;
115
+ sign(options: {
116
+ keyId: string;
117
+ payload: string;
118
+ promptMessage: string;
119
+ promptTitle: string;
120
+ cancelLabel: string;
121
+ }): Promise<{ signature: string }>;
122
+ deleteKey(keyId: string): Promise<void>;
123
+ }