@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 +21 -0
- package/README.md +204 -0
- package/package.json +41 -0
- package/src/api.js +181 -0
- package/src/biometric.js +126 -0
- package/src/checkout.js +75 -0
- package/src/glass.js +44 -0
- package/src/index.d.ts +282 -0
- package/src/index.js +12 -0
- package/src/keystore.js +83 -0
- package/src/pushPolicy.js +83 -0
- package/src/pushService.js +389 -0
- package/src/pushSettings.js +109 -0
- package/src/pushWatch.js +61 -0
- package/src/session.js +114 -0
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registering a phone for push, and the six ways it goes wrong.
|
|
3
|
+
*
|
|
4
|
+
* The state machine itself is small. What earns its keep here is everything
|
|
5
|
+
* around it — each rule below came from a defect that shipped.
|
|
6
|
+
*
|
|
7
|
+
* A DEVICE NEEDS A STABLE IDENTITY. The push token changes: on reinstall, on
|
|
8
|
+
* restore, whenever the OS feels like it. Keyed on the token, a server ends up
|
|
9
|
+
* with six rows for one phone, all but one dead. The installation id is minted
|
|
10
|
+
* once and kept in the keystore; the token is just its current address.
|
|
11
|
+
*
|
|
12
|
+
* THE STATE IS READ FROM BOTH SIDES. The OS permission is half the answer; the
|
|
13
|
+
* server's record is the other half. Granted-but-unregistered is `disabled`,
|
|
14
|
+
* not `enabled` — a switch showing "on" above notifications nobody will receive
|
|
15
|
+
* is worse than one showing "off".
|
|
16
|
+
*
|
|
17
|
+
* A REFUSAL UNREGISTERS. Leaving a registration behind after the person says no
|
|
18
|
+
* keeps the server sending to a phone that will never display anything.
|
|
19
|
+
*
|
|
20
|
+
* A COLD-START NOTIFICATION OPENS ONCE. The platform hands back the last tapped
|
|
21
|
+
* notification, and clearing that cache is not reliable. Without a persisted
|
|
22
|
+
* mark, every launch replays the same notification and hijacks the home screen.
|
|
23
|
+
*
|
|
24
|
+
* LOGOUT WAITS FOR REGISTRATIONS IN FLIGHT, THEN BLOCKS THEM. A registration
|
|
25
|
+
* that started before logout and lands after it re-registers the device to an
|
|
26
|
+
* account that just left — the next notification goes to the wrong person.
|
|
27
|
+
*
|
|
28
|
+
* LOGOUT NEVER FAILS. Offline, or on a cleanup that errors, signing out still
|
|
29
|
+
* happens. An app that cannot sign out because the network is down is a trap.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const INSTALLATION_ID = 'notifications.installationId';
|
|
33
|
+
const LAST_HANDLED = 'notifications.lastHandledId';
|
|
34
|
+
|
|
35
|
+
function supported(deps) {
|
|
36
|
+
return Boolean(deps.isDevice) && (deps.platform === 'ios' || deps.platform === 'android');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The OS answer, normalized. iOS reports its own enum and it disagrees with the
|
|
41
|
+
* cross-platform field: provisional and ephemeral both deliver notifications
|
|
42
|
+
* while `status` reads denied.
|
|
43
|
+
*/
|
|
44
|
+
function readPermission(status, notifications) {
|
|
45
|
+
const ios = status && status.ios ? status.ios.status : undefined;
|
|
46
|
+
const levels = notifications.IosAuthorizationStatus || {};
|
|
47
|
+
if (ios !== undefined) {
|
|
48
|
+
if (ios === levels.AUTHORIZED || ios === levels.PROVISIONAL || ios === levels.EPHEMERAL) return 'granted';
|
|
49
|
+
if (ios === levels.NOT_DETERMINED) return 'undetermined';
|
|
50
|
+
if (ios === levels.DENIED) return 'denied';
|
|
51
|
+
}
|
|
52
|
+
if (status && (status.granted || status.status === 'granted')) return 'granted';
|
|
53
|
+
return status && status.status === 'undetermined' ? 'undetermined' : 'denied';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function dataOf(response) {
|
|
57
|
+
const content = response && response.notification && response.notification.request
|
|
58
|
+
? response.notification.request.content
|
|
59
|
+
: null;
|
|
60
|
+
return (content && content.data) || {};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const { decideRegistrationAction } = require('./pushPolicy');
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param {object} options
|
|
67
|
+
* @param {Function} options.load async () => dependencies (see README).
|
|
68
|
+
* @param {string} [options.namespace='app'] Prefixes the stored keys.
|
|
69
|
+
*/
|
|
70
|
+
function createPushService(options = {}) {
|
|
71
|
+
const load = options.load;
|
|
72
|
+
if (typeof load !== 'function') throw new Error('createPushService requires options.load.');
|
|
73
|
+
const namespace = options.namespace || 'app';
|
|
74
|
+
const installationKey = `${namespace}.${INSTALLATION_ID}`;
|
|
75
|
+
const handledKey = `${namespace}.${LAST_HANDLED}`;
|
|
76
|
+
|
|
77
|
+
let installationIdPromise = null;
|
|
78
|
+
let handlerInstalled = false;
|
|
79
|
+
let categoriesInstalled = false;
|
|
80
|
+
let coldStartHandled = false;
|
|
81
|
+
let registrationBlocked = false;
|
|
82
|
+
let logoutInProgress = false;
|
|
83
|
+
let logoutPromise = null;
|
|
84
|
+
const inFlight = new Set();
|
|
85
|
+
|
|
86
|
+
function getInstallationId() {
|
|
87
|
+
if (!installationIdPromise) {
|
|
88
|
+
installationIdPromise = Promise.resolve(load())
|
|
89
|
+
.then(async ({ randomUUID, keystore }) => {
|
|
90
|
+
const stored = await keystore.getItemAsync(installationKey);
|
|
91
|
+
if (stored) return stored;
|
|
92
|
+
const created = randomUUID();
|
|
93
|
+
await keystore.setItemAsync(installationKey, created);
|
|
94
|
+
return created;
|
|
95
|
+
})
|
|
96
|
+
.catch((error) => {
|
|
97
|
+
installationIdPromise = null;
|
|
98
|
+
throw error;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return installationIdPromise;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function unregister() {
|
|
105
|
+
const deps = await load();
|
|
106
|
+
if (!supported(deps)) return;
|
|
107
|
+
await deps.api.unregister(await getInstallationId());
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function declareChannels(deps) {
|
|
111
|
+
if (deps.platform !== 'android') return;
|
|
112
|
+
for (const channel of deps.channels || []) {
|
|
113
|
+
await deps.notifications.setNotificationChannelAsync(channel.id, {
|
|
114
|
+
name: channel.name,
|
|
115
|
+
importance: deps.notifications.AndroidImportance.HIGH,
|
|
116
|
+
enableVibrate: true,
|
|
117
|
+
sound: 'default',
|
|
118
|
+
...channel.config
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function declareCategories(deps) {
|
|
124
|
+
if (categoriesInstalled) return;
|
|
125
|
+
for (const category of deps.categories || []) {
|
|
126
|
+
await deps.notifications.setNotificationCategoryAsync(category.id, category.actions);
|
|
127
|
+
}
|
|
128
|
+
categoriesInstalled = true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The project id may be a value or something that has to be looked up. */
|
|
132
|
+
async function projectIdOf(deps) {
|
|
133
|
+
const value = typeof deps.projectId === 'function' ? await deps.projectId() : deps.projectId;
|
|
134
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error('PUSH_PROJECT_ID_MISSING');
|
|
135
|
+
return value;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function registerNow(deps, channelsReady) {
|
|
139
|
+
if (!channelsReady) await declareChannels(deps);
|
|
140
|
+
const projectId = await projectIdOf(deps);
|
|
141
|
+
const { data: pushToken } = await deps.notifications.getExpoPushTokenAsync({ projectId });
|
|
142
|
+
const installationId = await getInstallationId();
|
|
143
|
+
const device = await deps.api.register({
|
|
144
|
+
installationId,
|
|
145
|
+
pushToken,
|
|
146
|
+
platform: deps.platform,
|
|
147
|
+
...(deps.deviceName ? { deviceName: deps.deviceName } : {})
|
|
148
|
+
});
|
|
149
|
+
return device && device.registered && device.enabled ? 'enabled' : 'disabled';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Tracked, so logout can wait for it instead of racing it. */
|
|
153
|
+
async function guardedRegister(deps, channelsReady) {
|
|
154
|
+
if (registrationBlocked) return 'disabled';
|
|
155
|
+
const registration = registerNow(deps, channelsReady);
|
|
156
|
+
inFlight.add(registration);
|
|
157
|
+
try {
|
|
158
|
+
return await registration;
|
|
159
|
+
} finally {
|
|
160
|
+
inFlight.delete(registration);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function getState() {
|
|
165
|
+
try {
|
|
166
|
+
const deps = await load();
|
|
167
|
+
if (!supported(deps)) return 'unsupported';
|
|
168
|
+
const permission = readPermission(await deps.notifications.getPermissionsAsync(), deps.notifications);
|
|
169
|
+
if (permission !== 'granted') return permission;
|
|
170
|
+
const device = await deps.api.current(await getInstallationId());
|
|
171
|
+
return device && device.registered && device.enabled ? 'enabled' : 'disabled';
|
|
172
|
+
} catch {
|
|
173
|
+
return 'error';
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The person tapped the switch: prompting is allowed here, and only here. */
|
|
178
|
+
async function enable() {
|
|
179
|
+
try {
|
|
180
|
+
const deps = await load();
|
|
181
|
+
if (!supported(deps)) return 'unsupported';
|
|
182
|
+
|
|
183
|
+
let channelsReady = false;
|
|
184
|
+
if (deps.platform === 'android') {
|
|
185
|
+
await declareChannels(deps);
|
|
186
|
+
channelsReady = true;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
let permission = readPermission(await deps.notifications.getPermissionsAsync(), deps.notifications);
|
|
190
|
+
const action = decideRegistrationAction({ explicit: true, permission });
|
|
191
|
+
if (action === 'open-settings') {
|
|
192
|
+
await unregister();
|
|
193
|
+
return 'denied';
|
|
194
|
+
}
|
|
195
|
+
if (action === 'request') {
|
|
196
|
+
permission = readPermission(await deps.notifications.requestPermissionsAsync(), deps.notifications);
|
|
197
|
+
}
|
|
198
|
+
if (permission === 'denied') {
|
|
199
|
+
await unregister();
|
|
200
|
+
return 'denied';
|
|
201
|
+
}
|
|
202
|
+
if (permission !== 'granted') return permission;
|
|
203
|
+
return await guardedRegister(deps, channelsReady);
|
|
204
|
+
} catch {
|
|
205
|
+
return 'error';
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Startup and token rotation: refresh the registration, never prompt. */
|
|
210
|
+
async function sync() {
|
|
211
|
+
try {
|
|
212
|
+
const deps = await load();
|
|
213
|
+
if (!supported(deps)) return 'unsupported';
|
|
214
|
+
if (registrationBlocked) return 'disabled';
|
|
215
|
+
const permission = readPermission(await deps.notifications.getPermissionsAsync(), deps.notifications);
|
|
216
|
+
if (permission === 'denied') {
|
|
217
|
+
await unregister();
|
|
218
|
+
return 'denied';
|
|
219
|
+
}
|
|
220
|
+
if (decideRegistrationAction({ explicit: false, permission }) === 'none') {
|
|
221
|
+
return permission === 'undetermined' ? 'undetermined' : 'error';
|
|
222
|
+
}
|
|
223
|
+
return await guardedRegister(deps);
|
|
224
|
+
} catch {
|
|
225
|
+
return 'error';
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function disable() {
|
|
230
|
+
try {
|
|
231
|
+
const deps = await load();
|
|
232
|
+
if (!supported(deps)) return 'unsupported';
|
|
233
|
+
await unregister();
|
|
234
|
+
return 'disabled';
|
|
235
|
+
} catch {
|
|
236
|
+
return 'error';
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function allowRegistration() {
|
|
241
|
+
if (!logoutInProgress) registrationBlocked = false;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function installForegroundHandler(deps) {
|
|
245
|
+
if (handlerInstalled) return;
|
|
246
|
+
deps.notifications.setNotificationHandler({
|
|
247
|
+
handleNotification: async () => ({
|
|
248
|
+
shouldShowBanner: true,
|
|
249
|
+
shouldShowList: true,
|
|
250
|
+
shouldPlaySound: true,
|
|
251
|
+
shouldSetBadge: true
|
|
252
|
+
})
|
|
253
|
+
});
|
|
254
|
+
handlerInstalled = true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Start listening. Returns the function that stops it — call it on unmount.
|
|
259
|
+
* @param {*} recipient Passed to the router: who is looking at the phone.
|
|
260
|
+
*/
|
|
261
|
+
async function startListeners(recipient) {
|
|
262
|
+
const deps = await load();
|
|
263
|
+
if (!supported(deps)) return () => undefined;
|
|
264
|
+
|
|
265
|
+
await declareCategories(deps);
|
|
266
|
+
installForegroundHandler(deps);
|
|
267
|
+
|
|
268
|
+
let active = true;
|
|
269
|
+
|
|
270
|
+
function handle(response) {
|
|
271
|
+
if (!active) return;
|
|
272
|
+
const data = dataOf(response);
|
|
273
|
+
const payload = { ...data, actionIdentifier: response && response.actionIdentifier };
|
|
274
|
+
|
|
275
|
+
/* An action button may be answered in place — approving from the banner,
|
|
276
|
+
without opening the app and hijacking whatever is on screen. */
|
|
277
|
+
if (typeof deps.onAction === 'function') {
|
|
278
|
+
const handled = deps.onAction(payload);
|
|
279
|
+
if (handled === true) return;
|
|
280
|
+
if (handled && typeof handled.then === 'function') {
|
|
281
|
+
void handled.then((done) => {
|
|
282
|
+
if (done || !active) return;
|
|
283
|
+
deps.navigate(deps.router.resolveAction(payload, recipient));
|
|
284
|
+
}).catch(() => undefined);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
deps.navigate(deps.router.resolveAction(payload, recipient));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const subscriptions = [];
|
|
292
|
+
try {
|
|
293
|
+
subscriptions.push(deps.notifications.addNotificationReceivedListener(() => {
|
|
294
|
+
/* The foreground handler already presents it. Scheduling a local copy
|
|
295
|
+
here is how a notification arrives twice. */
|
|
296
|
+
}));
|
|
297
|
+
subscriptions.push(deps.notifications.addNotificationResponseReceivedListener(handle));
|
|
298
|
+
subscriptions.push(deps.notifications.addPushTokenListener(() => {
|
|
299
|
+
/* The raw APNs/FCM token is of no use to us: the same silent path that
|
|
300
|
+
runs at startup fetches a fresh one and registers it. */
|
|
301
|
+
void sync();
|
|
302
|
+
}));
|
|
303
|
+
} catch (error) {
|
|
304
|
+
for (const subscription of subscriptions) subscription.remove();
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (!coldStartHandled) {
|
|
309
|
+
coldStartHandled = true;
|
|
310
|
+
void (async () => {
|
|
311
|
+
try {
|
|
312
|
+
const response = await deps.notifications.getLastNotificationResponseAsync();
|
|
313
|
+
if (!response) return;
|
|
314
|
+
const id = response.notification && response.notification.request
|
|
315
|
+
? response.notification.request.identifier
|
|
316
|
+
: null;
|
|
317
|
+
if (id) {
|
|
318
|
+
const handled = await deps.keystore.getItemAsync(handledKey);
|
|
319
|
+
if (handled === id) return;
|
|
320
|
+
await deps.keystore.setItemAsync(handledKey, id);
|
|
321
|
+
}
|
|
322
|
+
handle(response);
|
|
323
|
+
} finally {
|
|
324
|
+
try {
|
|
325
|
+
await deps.notifications.clearLastNotificationResponseAsync();
|
|
326
|
+
} catch {
|
|
327
|
+
/* best effort: the persisted mark is what actually prevents replay */
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
})().catch(() => undefined);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return () => {
|
|
334
|
+
active = false;
|
|
335
|
+
for (const subscription of subscriptions) subscription.remove();
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Sign out, push cleanup included.
|
|
341
|
+
* @param {Function} signOut The app's own sign-out. Always called, last.
|
|
342
|
+
*/
|
|
343
|
+
function logout(signOut) {
|
|
344
|
+
if (logoutPromise) return logoutPromise;
|
|
345
|
+
|
|
346
|
+
logoutInProgress = true;
|
|
347
|
+
registrationBlocked = true;
|
|
348
|
+
|
|
349
|
+
const operation = (async () => {
|
|
350
|
+
await Promise.allSettled([...inFlight]);
|
|
351
|
+
try {
|
|
352
|
+
await unregister();
|
|
353
|
+
} catch {
|
|
354
|
+
/* signing out offline must stay possible */
|
|
355
|
+
}
|
|
356
|
+
try {
|
|
357
|
+
/* An account can sign in on a phone that already received a
|
|
358
|
+
notification for ANOTHER account. Without this, the next launch
|
|
359
|
+
replays it and opens someone else's content. */
|
|
360
|
+
const deps = await load();
|
|
361
|
+
if (supported(deps)) await deps.notifications.clearLastNotificationResponseAsync();
|
|
362
|
+
} catch {
|
|
363
|
+
/* cleanup must never hold sign-out hostage */
|
|
364
|
+
}
|
|
365
|
+
coldStartHandled = false;
|
|
366
|
+
if (typeof signOut === 'function') await signOut();
|
|
367
|
+
})();
|
|
368
|
+
|
|
369
|
+
logoutPromise = operation.finally(() => {
|
|
370
|
+
logoutInProgress = false;
|
|
371
|
+
logoutPromise = null;
|
|
372
|
+
});
|
|
373
|
+
return logoutPromise;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return {
|
|
377
|
+
getInstallationId,
|
|
378
|
+
getState,
|
|
379
|
+
enable,
|
|
380
|
+
sync,
|
|
381
|
+
disable,
|
|
382
|
+
unregister,
|
|
383
|
+
allowRegistration,
|
|
384
|
+
startListeners,
|
|
385
|
+
logout
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
module.exports = { createPushService, readPermission };
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The push switch in the settings screen, and the two bugs it always has.
|
|
3
|
+
*
|
|
4
|
+
* A NETWORK ANSWER OUTLIVES THE SCREEN. Tap the switch, leave immediately: the
|
|
5
|
+
* request lands on a screen that no longer exists. In React that is a warning;
|
|
6
|
+
* in a state machine it is worse — the stale answer overwrites the state of
|
|
7
|
+
* whoever came after. Each activation gets a GENERATION, and a generation that
|
|
8
|
+
* is no longer current publishes nothing.
|
|
9
|
+
*
|
|
10
|
+
* THE SWITCH LIES ABOUT WHAT IT WILL DO. "Enabled/disabled" is not the whole
|
|
11
|
+
* story: a permission the person denied once cannot be re-requested, so the
|
|
12
|
+
* button must open the settings app instead of pretending to toggle. Five
|
|
13
|
+
* states, one action each, decided in one place.
|
|
14
|
+
*
|
|
15
|
+
* The state is never inferred from what we just did — it is RE-READ from the
|
|
16
|
+
* device afterwards. Assuming "enable succeeded, so it is enabled" is how a
|
|
17
|
+
* switch ends up on while notifications are off.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {'loading'|'enabled'|'disabled'|'undetermined'|'denied'|'error'} state
|
|
22
|
+
* @returns {'enable'|'disable'|'open-settings'|'retry'|null}
|
|
23
|
+
*/
|
|
24
|
+
function resolvePushAction(state) {
|
|
25
|
+
if (state === 'enabled') return 'disable';
|
|
26
|
+
if (state === 'disabled' || state === 'undetermined') return 'enable';
|
|
27
|
+
if (state === 'denied') return 'open-settings';
|
|
28
|
+
if (state === 'error') return 'retry';
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isPushEnabled(state) {
|
|
33
|
+
return state === 'enabled';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {object} operations getState/enable/disable/openSettings, all async.
|
|
38
|
+
* @param {Function} onChange Called with {state, busy} on every change.
|
|
39
|
+
* @returns {{activate: Function, refresh: Function, act: Function}}
|
|
40
|
+
* `activate()` returns {ready, dispose} — dispose on unmount.
|
|
41
|
+
*/
|
|
42
|
+
function createPushSettingsController(operations, onChange) {
|
|
43
|
+
if (!operations || typeof operations.getState !== 'function') {
|
|
44
|
+
throw new Error('createPushSettingsController requires operations.getState.');
|
|
45
|
+
}
|
|
46
|
+
const publishTo = typeof onChange === 'function' ? onChange : () => {};
|
|
47
|
+
let current = null;
|
|
48
|
+
|
|
49
|
+
const isCurrent = (generation) => generation.active && current === generation;
|
|
50
|
+
|
|
51
|
+
const publish = (generation) => {
|
|
52
|
+
if (!isCurrent(generation)) return;
|
|
53
|
+
publishTo({ state: generation.state, busy: generation.busy });
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
async function run(generation, operation) {
|
|
57
|
+
if (!isCurrent(generation) || generation.busy) return;
|
|
58
|
+
generation.busy = true;
|
|
59
|
+
publish(generation);
|
|
60
|
+
try {
|
|
61
|
+
if (operation) await operation();
|
|
62
|
+
if (!isCurrent(generation)) return;
|
|
63
|
+
const state = await operations.getState();
|
|
64
|
+
if (!isCurrent(generation)) return;
|
|
65
|
+
generation.state = state;
|
|
66
|
+
} catch {
|
|
67
|
+
if (isCurrent(generation)) generation.state = 'error';
|
|
68
|
+
} finally {
|
|
69
|
+
if (isCurrent(generation)) {
|
|
70
|
+
generation.busy = false;
|
|
71
|
+
publish(generation);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function refresh() {
|
|
77
|
+
if (!current) return Promise.resolve();
|
|
78
|
+
return run(current);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function act() {
|
|
82
|
+
if (!current || current.busy) return Promise.resolve();
|
|
83
|
+
const action = resolvePushAction(current.state);
|
|
84
|
+
if (!action) return Promise.resolve();
|
|
85
|
+
const operation = action === 'enable' ? operations.enable
|
|
86
|
+
: action === 'disable' ? operations.disable
|
|
87
|
+
: action === 'open-settings' ? operations.openSettings
|
|
88
|
+
: undefined;
|
|
89
|
+
return run(current, operation);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function activate() {
|
|
93
|
+
if (current) current.active = false;
|
|
94
|
+
const generation = { state: 'loading', busy: false, active: true };
|
|
95
|
+
current = generation;
|
|
96
|
+
const ready = run(generation);
|
|
97
|
+
return {
|
|
98
|
+
ready,
|
|
99
|
+
dispose() {
|
|
100
|
+
generation.active = false;
|
|
101
|
+
if (current === generation) current = null;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return { activate, refresh, act };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = { resolvePushAction, isPushEnabled, createPushSettingsController };
|
package/src/pushWatch.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Watching for what arrived while the app was open.
|
|
3
|
+
*
|
|
4
|
+
* Push handles a closed app. An OPEN app receives nothing: the bell sat there
|
|
5
|
+
* stale until the person navigated away and back. So the foreground sweeps the
|
|
6
|
+
* server on a timer — and the three rules below are what keep that from
|
|
7
|
+
* becoming an annoyance.
|
|
8
|
+
*
|
|
9
|
+
* THE FIRST SWEEP RAISES NOTHING. On launch every unread item is "new" from
|
|
10
|
+
* the phone's point of view. Twenty banners at once is how an app gets its
|
|
11
|
+
* notifications switched off for good.
|
|
12
|
+
*
|
|
13
|
+
* THE MARK NEVER MOVES BACKWARDS. Otherwise the same item banners again on the
|
|
14
|
+
* next sweep, and the one after.
|
|
15
|
+
*
|
|
16
|
+
* AN UNREADABLE DATE IS NOT NOW. Treating a malformed date as the current time
|
|
17
|
+
* would banner the entire backlog.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Half a minute: often enough to feel live, rare enough to ignore on battery. */
|
|
21
|
+
const FOREGROUND_POLL_MS = 30_000;
|
|
22
|
+
|
|
23
|
+
function timeOf(value) {
|
|
24
|
+
return Date.parse(typeof value === 'string' ? value : '');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The items worth a banner: unread, and newer than the last sweep.
|
|
29
|
+
* @param {Array<{createdAt?: string, read?: boolean}>} items
|
|
30
|
+
* @param {string|null} lastSeenISO Null on the first sweep.
|
|
31
|
+
*/
|
|
32
|
+
function freshItems(items, lastSeenISO) {
|
|
33
|
+
if (!Array.isArray(items) || !lastSeenISO) return [];
|
|
34
|
+
const lastSeen = timeOf(lastSeenISO);
|
|
35
|
+
if (Number.isNaN(lastSeen)) return [];
|
|
36
|
+
return items.filter((item) => {
|
|
37
|
+
if (!item || item.read) return false;
|
|
38
|
+
const created = timeOf(item.createdAt);
|
|
39
|
+
return !Number.isNaN(created) && created > lastSeen;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The new mark: the latest arrival seen, or the old mark if nothing is newer. */
|
|
44
|
+
function nextStamp(items, previous) {
|
|
45
|
+
let best = previous ? timeOf(previous) : Number.NaN;
|
|
46
|
+
for (const item of Array.isArray(items) ? items : []) {
|
|
47
|
+
const created = timeOf(item && item.createdAt);
|
|
48
|
+
if (!Number.isNaN(created) && (Number.isNaN(best) || created > best)) best = created;
|
|
49
|
+
}
|
|
50
|
+
return Number.isNaN(best) ? (previous ?? null) : new Date(best).toISOString();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Sweep only in the foreground, only for someone signed in.
|
|
55
|
+
* In the background push takes over, and the OS would kill the timer anyway.
|
|
56
|
+
*/
|
|
57
|
+
function shouldPoll(appState, hasUser) {
|
|
58
|
+
return appState === 'active' && Boolean(hasUser);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = { FOREGROUND_POLL_MS, freshItems, nextStamp, shouldPoll };
|
package/src/session.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pair of tokens, kept where a phone keeps secrets.
|
|
3
|
+
*
|
|
4
|
+
* Two decisions here are worth stating, because both came from a real defect.
|
|
5
|
+
*
|
|
6
|
+
* THE ACCESS TOKEN IS CACHED IN MEMORY. Reading the keystore is a native
|
|
7
|
+
* round-trip, and every single request needs the token. Reading it from the
|
|
8
|
+
* Keychain on each call turned a list screen's twelve parallel requests into
|
|
9
|
+
* twelve Keychain reads.
|
|
10
|
+
*
|
|
11
|
+
* CLEARING TAKES THE BIOMETRIC FLAG WITH IT. The flag says "this person chose
|
|
12
|
+
* to unlock with their face" — it belongs to the session that enabled it. Left
|
|
13
|
+
* behind at logout, it stays on for whoever signs in next on the same device,
|
|
14
|
+
* a stranger included.
|
|
15
|
+
*
|
|
16
|
+
* The keystore may fail: a locked Keychain, a revoked permission, a browser
|
|
17
|
+
* with storage disabled. A read that throws is answered as "no session" — the
|
|
18
|
+
* person signs in again, which is bad, while a crash at launch is worse.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const ACCESS = 'auth.token';
|
|
22
|
+
const REFRESH = 'auth.refreshToken';
|
|
23
|
+
const BIOMETRIC = 'biometric.enabled';
|
|
24
|
+
|
|
25
|
+
/** Namespaced so two apps — or an app and its staging twin — never collide. */
|
|
26
|
+
function keyOf(namespace, suffix) {
|
|
27
|
+
return `${namespace}.${suffix}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} options
|
|
32
|
+
* @param {object} options.keystore getItemAsync/setItemAsync/deleteItemAsync.
|
|
33
|
+
* expo-secure-store as-is, or one of this package's adapters.
|
|
34
|
+
* @param {string} [options.namespace='app'] Prefix for every stored key.
|
|
35
|
+
* @returns {object} the session handle.
|
|
36
|
+
*/
|
|
37
|
+
function createSecureSession(options = {}) {
|
|
38
|
+
const keystore = options.keystore;
|
|
39
|
+
if (!keystore || typeof keystore.getItemAsync !== 'function') {
|
|
40
|
+
throw new Error('createSecureSession requires options.keystore with getItemAsync/setItemAsync/deleteItemAsync.');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const namespace = options.namespace || 'app';
|
|
44
|
+
const accessKey = keyOf(namespace, ACCESS);
|
|
45
|
+
const refreshKey = keyOf(namespace, REFRESH);
|
|
46
|
+
const biometricKey = keyOf(namespace, BIOMETRIC);
|
|
47
|
+
|
|
48
|
+
let cachedAccess = null;
|
|
49
|
+
|
|
50
|
+
async function read(key) {
|
|
51
|
+
try {
|
|
52
|
+
const value = await keystore.getItemAsync(key);
|
|
53
|
+
return value === undefined ? null : value;
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function write(key, value) {
|
|
60
|
+
try {
|
|
61
|
+
await keystore.setItemAsync(key, value);
|
|
62
|
+
} catch {
|
|
63
|
+
/* an unwritable keystore costs the next launch, not this one */
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function remove(key) {
|
|
68
|
+
try {
|
|
69
|
+
await keystore.deleteItemAsync(key);
|
|
70
|
+
} catch {
|
|
71
|
+
/* same */
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
keys: Object.freeze({ access: accessKey, refresh: refreshKey, biometric: biometricKey }),
|
|
77
|
+
|
|
78
|
+
/** The bearer token, from memory after the first read. */
|
|
79
|
+
async getAccessToken() {
|
|
80
|
+
if (cachedAccess === null) cachedAccess = await read(accessKey);
|
|
81
|
+
return cachedAccess;
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
/** The refresh token. Never cached: it is used once, when a request 401s. */
|
|
85
|
+
async getRefreshToken() {
|
|
86
|
+
return read(refreshKey);
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Store a fresh pair. A refresh response that returns only an access token
|
|
91
|
+
* must NOT wipe the refresh token — omitting it leaves the stored one.
|
|
92
|
+
*/
|
|
93
|
+
async save({ accessToken, refreshToken } = {}) {
|
|
94
|
+
if (accessToken) {
|
|
95
|
+
cachedAccess = String(accessToken);
|
|
96
|
+
await write(accessKey, cachedAccess);
|
|
97
|
+
}
|
|
98
|
+
if (refreshToken) await write(refreshKey, String(refreshToken));
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
/** Sign out: both tokens and the biometric choice, everywhere. */
|
|
102
|
+
async clear() {
|
|
103
|
+
cachedAccess = null;
|
|
104
|
+
await Promise.all([remove(accessKey), remove(refreshKey), remove(biometricKey)]);
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
/** Drop the in-memory copy without touching the keystore. Tests, mostly. */
|
|
108
|
+
forget() {
|
|
109
|
+
cachedAccess = null;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
module.exports = { createSecureSession };
|