-
-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy patherrors.ts
More file actions
478 lines (457 loc) · 16.2 KB
/
Copy patherrors.ts
File metadata and controls
478 lines (457 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/**
* # Typed errors
*
* Canonical error surface for `react-native-sensitive-info`. Every failure thrown by the library
* is an instance of {@link SensitiveInfoError} or one of its subclasses, classified by a stable
* {@link ErrorCode} discriminant.
*
* Use `instanceof` (preferred) or the `is*Error` predicates to branch in catch blocks. Legacy
* string-marker matching (`error.message.includes('[E_NOT_FOUND]')`) is still supported via
* {@link toSensitiveInfoError} but considered legacy.
*
* @packageDocumentation
*/
/**
* Stable discriminant codes emitted by the native layer.
*
* @remarks
* | Code | Meaning |
* | -------------------------- | -------------------------------------------------------------------- |
* | `E_NOT_FOUND` | The requested key does not exist. |
* | `E_AUTH_CANCELED` | User dismissed the biometric / device-credential prompt. |
* | `E_INTEGRITY_VIOLATION` | HMAC verification failed — entry should be treated as tampered. |
* | `E_KEY_INVALIDATED` | Hardware key was invalidated (e.g. biometric re-enrollment). |
* | `E_ROTATION_FAILED` | `rotateKeys()` could not complete. |
* | `E_UNKNOWN` | Catch-all for unclassified failures. |
*/
export const ErrorCode = {
NotFound: 'E_NOT_FOUND',
AuthenticationCanceled: 'E_AUTH_CANCELED',
IntegrityViolation: 'E_INTEGRITY_VIOLATION',
KeyInvalidated: 'E_KEY_INVALIDATED',
RotationFailed: 'E_ROTATION_FAILED',
InvalidArgument: 'E_INVALID_ARGUMENT',
Unknown: 'E_UNKNOWN',
} as const
/**
* Union of every value in {@link ErrorCode}. Use this to type variables that hold an error code.
*
* @see {@link ErrorCode}
*/
export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]
/**
* Base class for every typed error thrown by the library.
*
* All `is*Error` predicates and the `toSensitiveInfoError` adapter funnel into subclasses of this
* type, so a single `instanceof SensitiveInfoError` check is sufficient to identify any failure
* originating from secure storage.
*
* @example
* ```ts
* try {
* await getItem('session-token', { service: 'com.example.auth' })
* } catch (e) {
* if (e instanceof SensitiveInfoError) console.log(e.code)
* }
* ```
*/
export class SensitiveInfoError extends Error {
/** Stable discriminant identifying the failure mode. */
readonly code: ErrorCodeValue
/**
* @param code - Stable {@link ErrorCodeValue} for the failure.
* @param message - Human-readable description.
* @param options - Optional `cause` for error chaining (see ECMAScript 2022 `Error` cause).
*/
constructor(
code: ErrorCodeValue,
message: string,
options?: { cause?: unknown }
) {
super(message)
this.name = 'SensitiveInfoError'
this.code = code
// Assign `cause` directly instead of passing it to `super()` so this
// compiles cleanly under TS configs whose `lib` predates ES2022 (where
// the second `Error` constructor argument was introduced).
if (options && 'cause' in options) {
;(this as { cause?: unknown }).cause = options.cause
}
}
}
/**
* The requested key does not exist in the secure store.
*
* Note: {@link getItem} swallows this error and returns `null` instead. You will only observe
* `NotFoundError` directly when bypassing the wrapper or when implementing a custom layer atop
* the native HybridObject.
*
* @example
* ```ts
* try { await native.getItem({ key: 'missing' }) }
* catch (e) { if (isNotFoundError(e)) return null }
* ```
*/
export class NotFoundError extends SensitiveInfoError {
/**
* @param message - Defaults to `'Secret not found.'`.
* @param options - Optional `cause` for error chaining.
*/
constructor(message = 'Secret not found.', options?: { cause?: unknown }) {
super(ErrorCode.NotFound, message, options)
this.name = 'NotFoundError'
}
}
/**
* The user dismissed the biometric / device-credential prompt.
*
* @remarks Treat this as a normal user gesture rather than a bug — do not retry automatically;
* surface a clear UI affordance for the user to re-attempt.
*
* @example
* ```ts
* try { await getItem('token', { service: 'auth' }) }
* catch (e) { if (isAuthenticationCanceledError(e)) showUnlockButton() }
* ```
*/
export class AuthenticationCanceledError extends SensitiveInfoError {
/**
* @param message - Defaults to `'Authentication prompt canceled by the user.'`.
* @param options - Optional `cause` for error chaining.
*/
constructor(
message = 'Authentication prompt canceled by the user.',
options?: { cause?: unknown }
) {
super(ErrorCode.AuthenticationCanceled, message, options)
this.name = 'AuthenticationCanceledError'
}
}
/**
* HMAC verification of the stored metadata/ciphertext failed. This strongly suggests tampering at
* rest and the affected entry should be treated as untrustworthy.
*
* @remarks Recommended remediation: delete the affected entry, force the user to re-authenticate
* with the upstream service, and report telemetry so you can detect device-level compromise.
*
* @example
* ```ts
* try { await getItem('token', { service: 'auth' }) }
* catch (e) {
* if (isIntegrityViolationError(e)) {
* await deleteItem('token', { service: 'auth' })
* forceReauth()
* }
* }
* ```
*/
export class IntegrityViolationError extends SensitiveInfoError {
/** Key whose ciphertext failed verification, when known. */
readonly key?: string | undefined
/**
* @param message - Defaults to `'Integrity check failed for stored secret.'`.
* @param options - `cause` for error chaining and `key` for the affected identifier.
*/
constructor(
message = 'Integrity check failed for stored secret.',
options?: { cause?: unknown; key?: string }
) {
super(ErrorCode.IntegrityViolation, message, options)
this.name = 'IntegrityViolationError'
this.key = options?.key
}
}
/**
* The hardware-backed key tied to this entry was permanently invalidated (for example, because
* biometrics were re-enrolled). The entry must be deleted and re-created.
*
* @remarks This is the expected error after a user adds/removes a fingerprint or re-enrolls Face
* ID on entries written with `accessControl: 'biometryCurrentSet'` or `'secureEnclaveBiometry'`.
*
* @example
* ```ts
* try { await getItem('token', { service: 'auth' }) }
* catch (e) {
* if (isKeyInvalidatedError(e)) {
* await deleteItem('token', { service: 'auth' })
* promptUserToSetUpAgain()
* }
* }
* ```
*/
export class KeyInvalidatedError extends SensitiveInfoError {
/** Native keystore alias that was invalidated, when known. */
readonly alias?: string | undefined
/**
* @param message - Defaults to `'The hardware key backing this entry was permanently invalidated.'`.
* @param options - `cause` for error chaining and `alias` for the affected keystore entry.
*/
constructor(
message = 'The hardware key backing this entry was permanently invalidated.',
options?: { cause?: unknown; alias?: string }
) {
super(ErrorCode.KeyInvalidated, message, options)
this.name = 'KeyInvalidatedError'
this.alias = options?.alias
}
}
/**
* {@link rotateKeys} could not complete for the given service.
*
* @example
* ```ts
* try { await rotateKeys({ service: 'auth' }) }
* catch (e) { if (isRotationFailedError(e)) reportTelemetry(e) }
* ```
*/
export class RotationFailedError extends SensitiveInfoError {
/**
* @param message - Defaults to `'Key rotation failed.'`.
* @param options - Optional `cause` for error chaining.
*/
constructor(message = 'Key rotation failed.', options?: { cause?: unknown }) {
super(ErrorCode.RotationFailed, message, options)
this.name = 'RotationFailedError'
}
}
/**
* Indicates that a TS-side input violated the library's contract — for example, an empty `key`,
* a service name longer than the supported limit, or a value whose serialized size exceeds the
* configured ceiling.
*
* @remarks
* This error is raised **before** any native call is made, so no biometric prompt is shown and
* no on-disk state is touched. Treat it as a programmer error and fix the call site.
*
* @example
* ```ts
* try { await setItem('', value, { service: 'auth' }) }
* catch (e) { if (isInvalidArgumentError(e)) console.warn(e.argument, e.message) }
* ```
*/
export class InvalidArgumentError extends SensitiveInfoError {
/** Name of the argument that failed validation, when known (e.g. `'key'`, `'value'`). */
readonly argument?: string | undefined
/**
* @param message - Human-readable description of the violation.
* @param options - `cause` for error chaining and `argument` for the offending field name.
*/
constructor(
message = 'Invalid argument supplied to secure storage.',
options?: { cause?: unknown; argument?: string }
) {
super(ErrorCode.InvalidArgument, message, options)
this.name = 'InvalidArgumentError'
this.argument = options?.argument
}
}
// ---------------------------------------------------------------------------
// Adapters — bridge raw native errors (string markers + code fields) to typed
// classes. Kept pure so consumers can tree-shake these helpers.
// ---------------------------------------------------------------------------
const MARKER_TO_CODE: readonly [string, ErrorCodeValue][] = [
['[E_NOT_FOUND]', ErrorCode.NotFound],
['[E_AUTH_CANCELED]', ErrorCode.AuthenticationCanceled],
['[E_INTEGRITY_VIOLATION]', ErrorCode.IntegrityViolation],
['[E_KEY_INVALIDATED]', ErrorCode.KeyInvalidated],
['[E_ROTATION_FAILED]', ErrorCode.RotationFailed],
['[E_INVALID_ARGUMENT]', ErrorCode.InvalidArgument],
]
const extractCode = (error: unknown): ErrorCodeValue | null => {
if (error instanceof SensitiveInfoError) {
return error.code
}
if (
error != null &&
typeof error === 'object' &&
'code' in error &&
typeof (error as { code: unknown }).code === 'string'
) {
const raw = (error as { code: string }).code
const known = Object.values(ErrorCode).find((c) => c === raw)
if (known) return known as ErrorCodeValue
}
const message =
error instanceof Error
? error.message
: typeof error === 'string'
? error
: ''
for (const [marker, code] of MARKER_TO_CODE) {
if (message.includes(marker)) return code
}
return null
}
const extractMessage = (error: unknown, fallback: string): string => {
if (error instanceof Error && error.message) return error.message
if (typeof error === 'string' && error.length > 0) return error
if (error !== null && typeof error === 'object' && 'message' in error) {
const candidate = (error as { message?: unknown }).message
if (typeof candidate === 'string' && candidate.length > 0) return candidate
}
return fallback
}
/**
* Convert a raw native/unknown error into a typed {@link SensitiveInfoError} subclass.
*
* @param error - Anything caught from a native call — typically an `Error` with a `code` field or
* a legacy string-marker message such as `'[E_NOT_FOUND] missing key'`.
* @returns The corresponding typed error subclass when classifiable, otherwise the original
* error untouched (so consumers can decide how to handle unknown failures).
*
* @remarks Already-typed `SensitiveInfoError` instances are returned as-is. The legacy
* string-marker path exists purely for back-compat with pre-typed-error releases; new code should
* rely on `instanceof` against the exported subclasses.
*
* @example
* ```ts
* try { await native.setItem(req) }
* catch (raw) {
* const e = toSensitiveInfoError(raw)
* if (e instanceof KeyInvalidatedError) await reset()
* else throw e
* }
* ```
*
* @see {@link SensitiveInfoError}
*/
export function toSensitiveInfoError(error: unknown): unknown {
if (error instanceof SensitiveInfoError) return error
const code = extractCode(error)
if (code == null) return error
const message = extractMessage(error, 'Secure storage error.')
switch (code) {
case ErrorCode.NotFound:
return new NotFoundError(message, { cause: error })
case ErrorCode.AuthenticationCanceled:
return new AuthenticationCanceledError(message, { cause: error })
case ErrorCode.IntegrityViolation:
return new IntegrityViolationError(message, { cause: error })
case ErrorCode.KeyInvalidated:
return new KeyInvalidatedError(message, { cause: error })
case ErrorCode.RotationFailed:
return new RotationFailedError(message, { cause: error })
case ErrorCode.InvalidArgument:
return new InvalidArgumentError(message, { cause: error })
default:
return error
}
}
/**
* Type guard that narrows `error` to {@link NotFoundError}.
*
* @param error - Anything thrown from a `react-native-sensitive-info` call.
* @returns `true` when the error matches the {@link ErrorCode.NotFound} discriminant.
*
* @example
* ```ts
* try { await native.getItem({ key: 'missing' }) }
* catch (e) { if (isNotFoundError(e)) return null; throw e }
* ```
*
* @see {@link NotFoundError}
*/
export const isNotFoundError = (error: unknown): error is NotFoundError =>
error instanceof NotFoundError || extractCode(error) === ErrorCode.NotFound
/**
* Type guard that narrows `error` to {@link AuthenticationCanceledError}.
*
* @param error - Anything thrown from a `react-native-sensitive-info` call.
* @returns `true` when the user dismissed the biometric / device-credential prompt.
*
* @example
* ```ts
* try { await getItem('token', { service: 'auth' }) }
* catch (e) { if (isAuthenticationCanceledError(e)) showRetry(); else throw e }
* ```
*
* @see {@link AuthenticationCanceledError}
*/
export const isAuthenticationCanceledError = (
error: unknown
): error is AuthenticationCanceledError =>
error instanceof AuthenticationCanceledError ||
extractCode(error) === ErrorCode.AuthenticationCanceled
/**
* Type guard that narrows `error` to {@link IntegrityViolationError}.
*
* @param error - Anything thrown from a `react-native-sensitive-info` call.
* @returns `true` when HMAC verification failed for the stored ciphertext.
*
* @example
* ```ts
* try { await getItem('token', { service: 'auth' }) }
* catch (e) {
* if (isIntegrityViolationError(e)) await deleteItem('token', { service: 'auth' })
* else throw e
* }
* ```
*
* @see {@link IntegrityViolationError}
*/
export const isIntegrityViolationError = (
error: unknown
): error is IntegrityViolationError =>
error instanceof IntegrityViolationError ||
extractCode(error) === ErrorCode.IntegrityViolation
/**
* Type guard that narrows `error` to {@link KeyInvalidatedError}.
*
* @param error - Anything thrown from a `react-native-sensitive-info` call.
* @returns `true` when the hardware key backing the entry was invalidated (e.g. biometric
* re-enrollment).
*
* @example
* ```ts
* try { await getItem('token', { service: 'auth' }) }
* catch (e) {
* if (isKeyInvalidatedError(e)) await deleteItem('token', { service: 'auth' })
* else throw e
* }
* ```
*
* @see {@link KeyInvalidatedError}
*/
export const isKeyInvalidatedError = (
error: unknown
): error is KeyInvalidatedError =>
error instanceof KeyInvalidatedError ||
extractCode(error) === ErrorCode.KeyInvalidated
/**
* Type guard that narrows `error` to {@link RotationFailedError}.
*
* @param error - Anything thrown from a `react-native-sensitive-info` call.
* @returns `true` when {@link rotateKeys} could not complete.
*
* @example
* ```ts
* try { await rotateKeys({ service: 'auth' }) }
* catch (e) { if (isRotationFailedError(e)) report(e); else throw e }
* ```
*
* @see {@link RotationFailedError}
*/
export const isRotationFailedError = (
error: unknown
): error is RotationFailedError =>
error instanceof RotationFailedError ||
extractCode(error) === ErrorCode.RotationFailed
/**
* Type guard that narrows `error` to {@link InvalidArgumentError}.
*
* @param error - Anything thrown from a `react-native-sensitive-info` call.
* @returns `true` when a TS-side input violated the library's contract.
*
* @example
* ```ts
* try { await setItem('', value, { service: 'auth' }) }
* catch (e) { if (isInvalidArgumentError(e)) showFormError(e.argument) }
* ```
*
* @see {@link InvalidArgumentError}
*/
export const isInvalidArgumentError = (
error: unknown
): error is InvalidArgumentError =>
error instanceof InvalidArgumentError ||
extractCode(error) === ErrorCode.InvalidArgument