@astratra/native 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,204 @@
1
+ # @astratra/native
2
+
3
+ La plomberie mobile, sans le moteur mobile : **session sécurisée, verrou
4
+ biométrique, notifications natives, retour de paiement**.
5
+
6
+ Le package ne charge ni `expo-secure-store`, ni `expo-local-authentication`,
7
+ ni `expo-web-browser`. Il les **reçoit**. Même règle que `@astratra/notify`
8
+ avec son transport, et même bénéfice : tout ce qui suit se teste en Node, sans
9
+ simulateur ni build natif.
10
+
11
+ Aucune dépendance à l'exécution.
12
+
13
+ ---
14
+
15
+ # Session
16
+
17
+ Le trousseau du téléphone est un module natif : l'importer ici ferait entrer un
18
+ build natif dans chaque test, et rendrait le package inutilisable partout où le
19
+ module manque — un aperçu navigateur, un client de développement compilé avant
20
+ son installation.
21
+
22
+ Le trousseau est donc injecté. Le contrat est celui d'`expo-secure-store`, noms
23
+ de méthodes compris — le renommer aurait obligé chaque appelant à écrire une
24
+ enveloppe pour la seule implémentation que tout le monde utilise.
25
+
26
+ ```js
27
+ import * as SecureStore from 'expo-secure-store';
28
+ import { createSecureSession } from '@astratra/native';
29
+
30
+ const session = createSecureSession({ keystore: SecureStore, namespace: 'acme' });
31
+
32
+ await session.save({ accessToken, refreshToken });
33
+ const token = await session.getAccessToken();
34
+ ```
35
+
36
+ Deux décisions, chacune née d'un vrai défaut.
37
+
38
+ **Le jeton d'accès est gardé en mémoire.** Lire le trousseau est un aller-retour
39
+ natif, et chaque requête a besoin du jeton : un écran de liste et ses douze
40
+ requêtes parallèles faisaient douze lectures du Keychain.
41
+
42
+ **Effacer emporte le drapeau biométrique.** Ce drapeau dit « cette personne a
43
+ choisi de déverrouiller par son visage » — il appartient à la session qui l'a
44
+ activé. Laissé derrière à la déconnexion, il reste actif pour le compte suivant
45
+ sur le même appareil, un inconnu compris.
46
+
47
+ Un trousseau peut échouer : Keychain verrouillé, permission révoquée, stockage
48
+ navigateur désactivé. Une lecture qui lève est répondue « pas de session » — la
49
+ personne se reconnecte, ce qui est mauvais, quand un plantage au lancement est
50
+ pire.
51
+
52
+ Deux adaptateurs accompagnent le contrat : `createMemoryKeystore()` pour les
53
+ tests, `createWebKeystore(localStorage)` pour l'aperçu navigateur — jamais pour
54
+ un build web livré : `localStorage` n'est pas un trousseau, n'importe quel
55
+ script de la page le lit.
56
+
57
+ # Verrou biométrique
58
+
59
+ Trois faits, et une règle par fait.
60
+
61
+ ```js
62
+ import * as LocalAuthentication from 'expo-local-authentication';
63
+ import { createBiometricGate } from '@astratra/native';
64
+
65
+ const gate = createBiometricGate({
66
+ keystore: SecureStore,
67
+ authenticator: LocalAuthentication,
68
+ namespace: 'acme',
69
+ promptMessage: 'Acme'
70
+ });
71
+
72
+ const { supported, enabled } = await gate.read();
73
+ await gate.enable(); // demande, PUIS retient
74
+ const unlocked = await gate.confirm();
75
+ ```
76
+
77
+ **« Pris en charge » demande les deux faits de l'appareil** — un capteur, et une
78
+ empreinte enregistrée. Un téléphone avec capteur et rien d'enregistré affiche
79
+ l'invite et refuse aussitôt : l'utilisateur y lit une fonction cassée.
80
+
81
+ **Activer demande d'abord, retient ensuite.** L'inverse laisserait l'application
82
+ prétendre un déverrouillage que personne n'a accordé.
83
+
84
+ **Un drapeau ne survit pas à l'empreinte qu'il désigne.** Si l'empreinte a été
85
+ retirée du téléphone depuis, `enabled` retombe à faux tout seul.
86
+
87
+ **`confirm()` ne propose rien quand le verrou n'a pas été activé** — une invite
88
+ biométrique que personne n'a demandée est ce qui fait signaler une application
89
+ comme hameçonnage.
90
+
91
+ Rien ne lève ici. Un capteur peut être occupé, une permission révoquée entre
92
+ deux écrans : l'appelant reçoit un état à afficher, jamais une exception à
93
+ rattraper.
94
+
95
+ # Notifications
96
+
97
+ ## Quand demander
98
+
99
+ L'invite système ne se lève **qu'une fois**. La lever au lancement, avant que la
100
+ personne sache ce que l'application envoie, transforme un « non » réflexe en
101
+ refus définitif : le système ne redemande jamais, et le seul retour possible est
102
+ un détour par les réglages que presque personne ne fait.
103
+
104
+ ```js
105
+ decideRegistrationAction({ explicit: false, permission: 'undetermined' }); // 'none'
106
+ decideRegistrationAction({ explicit: true, permission: 'undetermined' }); // 'request'
107
+ decideRegistrationAction({ explicit: true, permission: 'denied' }); // 'open-settings'
108
+ decideRegistrationAction({ explicit: false, permission: 'granted' }); // 'register'
109
+ ```
110
+
111
+ ## Où mène un appui
112
+
113
+ Une notification porte une route venue du serveur. La suivre à l'aveugle ouvre
114
+ des écrans que le destinataire n'a pas à voir : cette route est une donnée du
115
+ réseau, et les rôles changent entre l'envoi et l'appui.
116
+
117
+ Les règles se déclarent **par autorisation**, jamais par exclusion — une liste
118
+ de routes interdites admet en silence chaque écran ajouté ensuite et oublié.
119
+
120
+ ```js
121
+ const router = createNotificationRouter({
122
+ fallback: '/notifications',
123
+ routes: [
124
+ { pattern: /^\/orders$/, allow: (role) => role === 'seller' },
125
+ { pattern: /^\/billing$/, allow: (role) => role === 'owner', to: '/billing/overview' }
126
+ ],
127
+ actions: { REFUND: (payload) => `/orders/${payload.orderId}/refund` }
128
+ });
129
+
130
+ router.resolve('/orders?from=push', 'courier'); // '/notifications'
131
+ ```
132
+
133
+ ## La veille au premier plan
134
+
135
+ Le push traite l'application fermée. Une application **ouverte** ne reçoit
136
+ rien : la cloche restait figée jusqu'à ce qu'on quitte l'écran et qu'on y
137
+ revienne.
138
+
139
+ ```js
140
+ if (shouldPoll(appState, Boolean(user)) ) {
141
+ const items = await fetchNotifications();
142
+ for (const item of freshItems(items, lastSeen)) banner(item);
143
+ lastSeen = nextStamp(items, lastSeen);
144
+ }
145
+ ```
146
+
147
+ **Le premier relevé ne lève rien** : au démarrage, tout l'historique non lu
148
+ « vient d'arriver » du point de vue du téléphone, et vingt bannières d'un coup
149
+ font couper les notifications pour de bon. **Le repère ne recule jamais**, sinon
150
+ la même notification re-bannère au relevé suivant. **Une date illisible n'est
151
+ pas maintenant** — la traiter comme l'instant présent bannèrerait tout
152
+ l'arriéré.
153
+
154
+ ## L'interrupteur des réglages
155
+
156
+ ```js
157
+ const controller = createPushSettingsController(operations, setSnapshot);
158
+ const screen = controller.activate();
159
+ // à la sortie de l'écran :
160
+ screen.dispose();
161
+ ```
162
+
163
+ **Une réponse réseau survit à l'écran qui l'a demandée.** Appuyez, quittez : la
164
+ réponse arrive sur un écran disparu et écrase l'état de celui qui a suivi.
165
+ Chaque activation reçoit une génération ; une génération qui n'est plus la
166
+ courante ne publie rien.
167
+
168
+ **L'état n'est jamais déduit de l'action** — il est **relu** de l'appareil
169
+ ensuite. Supposer « l'activation a réussi, donc c'est actif » est ce qui laisse
170
+ un interrupteur allumé au-dessus de notifications éteintes.
171
+
172
+ # Retour de paiement
173
+
174
+ ```js
175
+ const openCheckout = createCheckoutOpener({
176
+ linking: Linking,
177
+ loadBrowser: () => (requireOptionalNativeModule('ExpoWebBrowser') ? require('expo-web-browser') : null)
178
+ });
179
+
180
+ const returned = await openCheckout(url, 'acme://paid');
181
+ ```
182
+
183
+ **Le module natif peut ne pas être là.** Un client de développement compilé
184
+ avant son installation ne le contient pas, et le seul fait de l'importer lève —
185
+ une erreur qu'un `try` rattrape, mais que l'écran rouge affiche quand même. Son
186
+ absence est un cas prévu : le navigateur du téléphone prend le relais, le
187
+ paiement aboutit, le retour est juste moins fluide.
188
+
189
+ **La passerelle renvoie vers le site, pas vers l'application.** Sans lien de
190
+ retour, la personne reste échouée sur une page web, son achat quelque part
191
+ derrière.
192
+
193
+ `true` signifie **la personne est revenue par le lien de retour**, jamais « le
194
+ paiement a réussi ». Seul le serveur le sait, et un client qui en décide seul
195
+ finit par offrir quelque chose.
196
+
197
+ # Effet de verre
198
+
199
+ ```js
200
+ resolveGlassMode({ platform, apiAvailable, effectAvailable }); // 'native' | 'fallback'
201
+ ```
202
+
203
+ Décidé une fois, pour que toutes les surfaces répondent pareil : un en-tête qui
204
+ floute au-dessus d'une carte qui ne floute pas est pire que ni l'un ni l'autre.
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@astratra/native",
3
+ "version": "0.1.0",
4
+ "description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching, and a checkout round-trip that survives a missing native module. Adapters injected, so it tests in plain Node.",
5
+ "engines": {
6
+ "node": ">=20"
7
+ },
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "type": "commonjs",
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "test": "jest"
16
+ },
17
+ "jest": {
18
+ "testMatch": [
19
+ "**/__tests__/**/*.test.js"
20
+ ]
21
+ },
22
+ "keywords": [
23
+ "astratra",
24
+ "mobile",
25
+ "react-native",
26
+ "expo",
27
+ "session",
28
+ "biometric",
29
+ "push"
30
+ ],
31
+ "license": "MIT",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "devDependencies": {
36
+ "jest": "30.4.2"
37
+ },
38
+ "dependencies": {
39
+ "@astratra/client": "^0.3.0"
40
+ }
41
+ }
package/src/api.js ADDED
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Talking to the API from a phone.
3
+ *
4
+ * The transport itself is unremarkable — fetch, a bearer token, a JSON
5
+ * envelope. What is worth writing once is the handful of things a mobile
6
+ * client gets wrong.
7
+ *
8
+ * THE REFRESH IS NOT REDONE HERE. Five requests fail together when a token
9
+ * dies, five refreshes race, and four of them spend a rotated refresh token —
10
+ * signing the person out at the exact moment everything was recoverable.
11
+ * `@astratra/client` already solves that, single-flight and replay-once
12
+ * included; this module wires the mobile pieces into it instead of writing a
13
+ * fourth version of the same bug. The three call shapes below share ONE
14
+ * refresh: a JSON call and a download racing the same dead token must not
15
+ * renew twice.
16
+ *
17
+ * THE LANGUAGE IS READ PER CALL, NEVER CACHED. Server messages are displayed
18
+ * as they arrive. Cache the header at construction and an app switched to
19
+ * English keeps receiving French errors until it is restarted.
20
+ *
21
+ * MULTIPART MUST NOT BE GIVEN A CONTENT TYPE. Setting `application/json` on a
22
+ * FormData body — or setting multipart by hand, without the boundary the
23
+ * runtime generates — makes the upload fail server-side with no useful message.
24
+ *
25
+ * BINARY IS HANDED BACK, NOT WRITTEN. Saving to disk needs a filesystem module
26
+ * this package refuses to import. `raw()` returns the response, already
27
+ * checked; where the bytes go is the app's business.
28
+ */
29
+
30
+ const { createSessionClient } = require('@astratra/client');
31
+
32
+ class ApiError extends Error {
33
+ /**
34
+ * @param {string} message The server's own message, shown to the person.
35
+ * @param {number} status
36
+ * @param {*} [data] Failures stay actionable: a 409 on an existing
37
+ * subscription carries the billing portal URL to open.
38
+ */
39
+ constructor(message, status, data) {
40
+ super(message);
41
+ this.name = 'ApiError';
42
+ this.status = status;
43
+ this.data = data;
44
+ }
45
+ }
46
+
47
+ function messageOf(payload) {
48
+ if (payload && typeof payload === 'object') {
49
+ if (typeof payload.message === 'string' && payload.message) return payload.message;
50
+ if (typeof payload.error === 'string' && payload.error) return payload.error;
51
+ }
52
+ return 'REQUEST_FAILED';
53
+ }
54
+
55
+ /**
56
+ * @param {object} options
57
+ * @param {string} options.baseUrl e.g. https://api.acme.com/api
58
+ * @param {object} options.session A createSecureSession handle.
59
+ * @param {Function} [options.fetch] Defaults to the global fetch.
60
+ * @param {Function} [options.language] () => 'fr'. Read on every call.
61
+ * @param {string} [options.platform='mobile'] Sent as X-Client-Platform.
62
+ * @param {Function} [options.refresh] async () => void. Omit it and a 401 is
63
+ * just an error — no refresh is invented on the app's behalf.
64
+ * @param {string[]} [options.excluded] Extra paths that never refresh. The
65
+ * login and refresh endpoints are excluded whether you list them or not.
66
+ * @param {Function} [options.onSessionExpired] Called once, after the session
67
+ * has been cleared: route to the sign-in screen from here.
68
+ */
69
+ function createApiClient(options = {}) {
70
+ const baseUrl = options.baseUrl;
71
+ if (typeof baseUrl !== 'string' || !baseUrl) throw new Error('createApiClient requires options.baseUrl.');
72
+
73
+ const session = options.session;
74
+ if (!session || typeof session.getAccessToken !== 'function') {
75
+ throw new Error('createApiClient requires options.session (see createSecureSession).');
76
+ }
77
+
78
+ const doFetch = options.fetch || (typeof fetch === 'function' ? fetch : null);
79
+ if (typeof doFetch !== 'function') throw new Error('createApiClient requires a fetch implementation.');
80
+
81
+ const language = typeof options.language === 'function' ? options.language : () => null;
82
+ const platform = options.platform || 'mobile';
83
+ const loginPath = options.loginPath || '/auth/login';
84
+ const refreshPath = options.refreshPath || '/auth/refresh';
85
+
86
+ /* Assets live on the ORIGIN, not under /api: the web serves /uploads on the
87
+ same domain through a reverse proxy, a phone has no such luxury. */
88
+ const origin = baseUrl.replace(/\/api\/?$/, '').replace(/\/$/, '');
89
+
90
+ function resolveAssetUrl(path) {
91
+ if (!path) return undefined;
92
+ if (/^https?:\/\//.test(path)) return path;
93
+ return `${origin}${String(path).startsWith('/') ? path : `/${path}`}`;
94
+ }
95
+
96
+ async function headersFor(init, accept) {
97
+ const headers = new Headers(init.headers || {});
98
+ headers.set('X-Client-Platform', platform);
99
+ headers.set('Accept', accept);
100
+
101
+ const lang = language();
102
+ if (lang) headers.set('Accept-Language', lang);
103
+
104
+ const multipart = typeof FormData !== 'undefined' && init.body instanceof FormData;
105
+ if (init.body && !multipart && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
106
+
107
+ const token = await session.getAccessToken();
108
+ if (token) headers.set('Authorization', `Bearer ${token}`);
109
+ return headers;
110
+ }
111
+
112
+ async function send(path, init, accept) {
113
+ const headers = await headersFor(init || {}, accept);
114
+ return doFetch(`${baseUrl}${path}`, { ...init, headers });
115
+ }
116
+
117
+ /** JSON call: unwraps `data`, throws ApiError on anything but 2xx. */
118
+ async function jsonCall(path, init = {}) {
119
+ const response = await send(path, init, 'application/json');
120
+ const payload = await response.json().catch(() => null);
121
+ if (!response.ok) throw new ApiError(messageOf(payload), response.status, payload && payload.data);
122
+ return payload ? payload.data : undefined;
123
+ }
124
+
125
+ /** Server-sent events: the response is handed over unread. */
126
+ async function streamCall(path, init = {}) {
127
+ const response = await send(path, init, 'text/event-stream');
128
+ if (!response.ok) throw new ApiError('REQUEST_FAILED', response.status);
129
+ return response;
130
+ }
131
+
132
+ /** Bytes: checked, then handed over for the caller to write somewhere. */
133
+ async function rawCall(path, init = {}) {
134
+ const response = await send(path, init, '*/*');
135
+ if (!response.ok) throw new ApiError('REQUEST_FAILED', response.status);
136
+ return response;
137
+ }
138
+
139
+ const plain = { request: jsonCall, stream: streamCall, raw: rawCall, resolveAssetUrl, ApiError };
140
+ if (typeof options.refresh !== 'function') return plain;
141
+
142
+ const excluded = [loginPath, refreshPath, ...(options.excluded || [])];
143
+
144
+ /* One promise for the whole client. createSessionClient makes each shape
145
+ single-flight on its own; sharing this makes them single-flight together. */
146
+ let pending = null;
147
+ function refreshOnce() {
148
+ if (!pending) {
149
+ pending = Promise.resolve()
150
+ .then(() => options.refresh())
151
+ .finally(() => { pending = null; });
152
+ }
153
+ return pending;
154
+ }
155
+
156
+ function expired(cause) {
157
+ void session.clear();
158
+ if (typeof options.onSessionExpired === 'function') options.onSessionExpired(cause);
159
+ }
160
+
161
+ function guard(call) {
162
+ const client = createSessionClient({
163
+ request: (path, init) => call(path, init),
164
+ refresh: refreshOnce,
165
+ excluded,
166
+ isAuthError: (error) => error instanceof ApiError && error.status === 401,
167
+ onSessionExpired: expired
168
+ });
169
+ return (path, init) => client.call(path, init);
170
+ }
171
+
172
+ return {
173
+ request: guard(jsonCall),
174
+ stream: guard(streamCall),
175
+ raw: guard(rawCall),
176
+ resolveAssetUrl,
177
+ ApiError
178
+ };
179
+ }
180
+
181
+ module.exports = { createApiClient, ApiError };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Unlocking with a face or a finger — the state, not the screen.
3
+ *
4
+ * The original lived in a React hook, which made it untestable without a
5
+ * renderer and unusable outside React. What actually matters is a small state
6
+ * machine over two facts the device reports and one flag the person chose:
7
+ *
8
+ * hardware — the sensor exists;
9
+ * enrolled — a face or finger is registered on the device;
10
+ * enabled — this person asked for it, in this app.
11
+ *
12
+ * SUPPORTED IS BOTH DEVICE FACTS. A phone with a sensor and nothing enrolled
13
+ * shows the prompt and refuses instantly, which reads to the user as a broken
14
+ * feature. Offering the switch at all requires both.
15
+ *
16
+ * ENABLE PROMPTS FIRST, STORES SECOND. Storing the flag then prompting would
17
+ * leave the app claiming an unlock the person never granted.
18
+ *
19
+ * NOTHING HERE THROWS. A sensor can be busy, a permission revoked between two
20
+ * screens. The caller gets a result to display, never an exception to catch.
21
+ */
22
+
23
+ const BIOMETRIC = 'biometric.enabled';
24
+
25
+ /**
26
+ * @param {object} options
27
+ * @param {object} options.keystore Same contract as createSecureSession's.
28
+ * @param {object} options.authenticator hasHardwareAsync/isEnrolledAsync/
29
+ * authenticateAsync — expo-local-authentication passes as-is.
30
+ * @param {string} [options.namespace='app']
31
+ * @param {string} [options.promptMessage] Default prompt title.
32
+ */
33
+ function createBiometricGate(options = {}) {
34
+ const keystore = options.keystore;
35
+ const authenticator = options.authenticator;
36
+ if (!keystore || typeof keystore.getItemAsync !== 'function') {
37
+ throw new Error('createBiometricGate requires options.keystore.');
38
+ }
39
+ if (!authenticator || typeof authenticator.authenticateAsync !== 'function') {
40
+ throw new Error('createBiometricGate requires options.authenticator with authenticateAsync.');
41
+ }
42
+
43
+ const key = `${options.namespace || 'app'}.${BIOMETRIC}`;
44
+ const defaultPrompt = options.promptMessage || '';
45
+
46
+ async function ask(fn) {
47
+ try {
48
+ return await fn();
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ /** The three facts, read together. Never throws. */
55
+ async function read() {
56
+ const [flag, hardware, enrolled] = await Promise.all([
57
+ ask(() => keystore.getItemAsync(key)),
58
+ ask(() => authenticator.hasHardwareAsync()),
59
+ ask(() => authenticator.isEnrolledAsync())
60
+ ]);
61
+ const supported = Boolean(hardware) && Boolean(enrolled);
62
+ return {
63
+ enabled: flag === 'true' && supported,
64
+ hardware: Boolean(hardware),
65
+ enrolled: Boolean(enrolled),
66
+ supported
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Ask the person, then remember the answer.
72
+ * @returns {Promise<{enabled: boolean, supported: boolean, failed: boolean}>}
73
+ * `failed` separates "the sensor errored" from "the person said no" — the
74
+ * first deserves a message, the second does not.
75
+ */
76
+ async function enable({ promptMessage } = {}) {
77
+ const state = await read();
78
+ if (!state.supported) return { enabled: false, supported: false, failed: false };
79
+
80
+ let result;
81
+ try {
82
+ result = await authenticator.authenticateAsync({ promptMessage: promptMessage || defaultPrompt });
83
+ } catch {
84
+ return { enabled: false, supported: true, failed: true };
85
+ }
86
+
87
+ if (!result || !result.success) return { enabled: false, supported: true, failed: false };
88
+
89
+ try {
90
+ await keystore.setItemAsync(key, 'true');
91
+ } catch {
92
+ return { enabled: false, supported: true, failed: true };
93
+ }
94
+ return { enabled: true, supported: true, failed: false };
95
+ }
96
+
97
+ /** Turn it off. No prompt: refusing to disable would trap the person. */
98
+ async function disable() {
99
+ try {
100
+ await keystore.deleteItemAsync(key);
101
+ } catch {
102
+ /* the flag is re-checked against the device on every read anyway */
103
+ }
104
+ return { enabled: false };
105
+ }
106
+
107
+ /**
108
+ * Unlock now — the sign-in screen's Face ID button.
109
+ * Answers false when the gate was never enabled, WITHOUT prompting: a prompt
110
+ * nobody asked for is how an app gets reported for phishing a fingerprint.
111
+ */
112
+ async function confirm({ promptMessage } = {}) {
113
+ const state = await read();
114
+ if (!state.enabled) return false;
115
+ try {
116
+ const result = await authenticator.authenticateAsync({ promptMessage: promptMessage || defaultPrompt });
117
+ return Boolean(result && result.success);
118
+ } catch {
119
+ return false;
120
+ }
121
+ }
122
+
123
+ return { read, enable, disable, confirm, key };
124
+ }
125
+
126
+ module.exports = { createBiometricGate };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Sending someone out to pay, and getting them back.
3
+ *
4
+ * Two failures hide behind one innocent-looking call.
5
+ *
6
+ * THE NATIVE MODULE MAY NOT BE THERE. An in-app browser is a native module: a
7
+ * development client built before it was installed does not contain it, and
8
+ * merely importing it throws — an error a `try` catches while the red screen
9
+ * shows it anyway. So the module is LOADED THROUGH AN INJECTED FUNCTION, and
10
+ * its absence is an expected case, not an incident.
11
+ *
12
+ * THE GATEWAY RETURNS TO THE WEB, NOT TO THE APP. Payment done, the person sat
13
+ * stranded on a web page with their purchase somewhere behind it. Handing the
14
+ * browser a return link — the app's own deep link — lets the session recognise
15
+ * the come-back and close itself, which `openBrowserAsync` never does on its
16
+ * own: it waits for a manual tap on "Done".
17
+ *
18
+ * The answer is deliberately narrow: `true` means THE PERSON CAME BACK THROUGH
19
+ * THE RETURN LINK, never "the payment succeeded". Only the server knows that,
20
+ * and a client that decides it on its own eventually grants something free.
21
+ */
22
+
23
+ /**
24
+ * @param {object} options
25
+ * @param {{openURL: Function}} options.linking react-native's Linking.
26
+ * @param {Function} [options.loadBrowser] Returns the in-app browser module,
27
+ * or null when it is absent. Must not throw — but a thrower is tolerated.
28
+ * @param {object} [options.browserOptions] Passed to openBrowserAsync.
29
+ * @returns {(url: string, returnUrl?: string) => Promise<boolean>}
30
+ */
31
+ function createCheckoutOpener(options = {}) {
32
+ const linking = options.linking;
33
+ if (!linking || typeof linking.openURL !== 'function') {
34
+ throw new Error('createCheckoutOpener requires options.linking with openURL.');
35
+ }
36
+ const loadBrowser = typeof options.loadBrowser === 'function' ? options.loadBrowser : () => null;
37
+ const browserOptions = options.browserOptions || { dismissButtonStyle: 'done', showTitle: true };
38
+
39
+ function browser() {
40
+ try {
41
+ return loadBrowser() || null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ async function elsewhere(url) {
48
+ try {
49
+ await linking.openURL(url);
50
+ } catch {
51
+ /* no browser at all on the device: nothing left to try */
52
+ }
53
+ return false;
54
+ }
55
+
56
+ return async function openCheckout(url, returnUrl) {
57
+ if (typeof url !== 'string' || !url) return false;
58
+
59
+ const web = browser();
60
+ if (!web) return elsewhere(url);
61
+
62
+ try {
63
+ if (returnUrl && typeof web.openAuthSessionAsync === 'function') {
64
+ const result = await web.openAuthSessionAsync(url, returnUrl);
65
+ return Boolean(result && result.type === 'success');
66
+ }
67
+ await web.openBrowserAsync(url, browserOptions);
68
+ return false;
69
+ } catch {
70
+ return elsewhere(url);
71
+ }
72
+ };
73
+ }
74
+
75
+ module.exports = { createCheckoutOpener };