@robono/messaging-react-native 0.24.0 → 0.25.1

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.
Files changed (110) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +77 -1
  3. package/RobonoMessagingRuntime.podspec +2 -0
  4. package/SBOM.spdx.json +1832 -560
  5. package/android/build.gradle +4 -1
  6. package/android/src/main/java/com/robono/messaging/RobonoBackupGoogle.java +76 -0
  7. package/android/src/main/java/com/robono/messaging/RobonoHistoryStore.java +173 -0
  8. package/android/src/main/java/com/robono/messaging/RobonoMessagingPackage.java +1 -1
  9. package/app.plugin.cjs +14 -1
  10. package/cloudkit/backup-schema.ckdb +13 -0
  11. package/dist/account-pages.d.ts +51 -0
  12. package/dist/account-pages.js +65 -0
  13. package/dist/account.d.ts +2 -1
  14. package/dist/account.js +6 -2
  15. package/dist/backup-background.d.ts +25 -0
  16. package/dist/backup-background.js +71 -0
  17. package/dist/backup-base64.d.ts +3 -0
  18. package/dist/backup-base64.js +41 -0
  19. package/dist/backup-google-authorization.d.ts +23 -0
  20. package/dist/backup-google-authorization.js +95 -0
  21. package/dist/backup.js +61 -16
  22. package/dist/bubble-design.d.ts +1 -1
  23. package/dist/cloudkit-backup.d.ts +14 -0
  24. package/dist/cloudkit-backup.js +193 -0
  25. package/dist/conversation-details.js +1 -1
  26. package/dist/customization.d.ts +1 -0
  27. package/dist/delivery-bar.d.ts +1 -1
  28. package/dist/delivery-bar.js +5 -2
  29. package/dist/delivery-notice.d.ts +9 -0
  30. package/dist/delivery-notice.js +15 -0
  31. package/dist/expo-backup-background.d.ts +17 -0
  32. package/dist/expo-backup-background.js +57 -0
  33. package/dist/expo-backup-cloudkit.d.ts +6 -0
  34. package/dist/expo-backup-cloudkit.js +11 -0
  35. package/dist/expo-backup-google.d.ts +7 -0
  36. package/dist/expo-backup-google.js +16 -0
  37. package/dist/expo-backup-network.d.ts +8 -0
  38. package/dist/expo-backup-network.js +18 -0
  39. package/dist/expo-backup-passkeys.d.ts +7 -0
  40. package/dist/expo-backup-passkeys.js +31 -7
  41. package/dist/expo-backup-settings.js +26 -8
  42. package/dist/expo-backup.d.ts +14 -0
  43. package/dist/expo-backup.js +22 -0
  44. package/dist/expo-bridge.d.ts +2 -0
  45. package/dist/expo-bridge.js +3 -1
  46. package/dist/expo-cache.js +20 -1
  47. package/dist/expo-connected-calling.d.ts +1 -0
  48. package/dist/expo-connected-calling.js +13 -2
  49. package/dist/expo-device-history.d.ts +24 -0
  50. package/dist/expo-device-history.js +88 -0
  51. package/dist/expo-durable-history.d.ts +26 -0
  52. package/dist/expo-durable-history.js +56 -0
  53. package/dist/expo-history-backup.d.ts +3 -0
  54. package/dist/expo-history-backup.js +79 -0
  55. package/dist/expo-history-maintenance.d.ts +4 -0
  56. package/dist/expo-history-maintenance.js +23 -0
  57. package/dist/expo-history-previews.d.ts +5 -0
  58. package/dist/expo-history-previews.js +57 -0
  59. package/dist/expo-history.d.ts +1 -1
  60. package/dist/expo-history.js +2 -2
  61. package/dist/expo-media.d.ts +2 -0
  62. package/dist/expo-media.js +15 -21
  63. package/dist/expo-messenger.d.ts +10 -0
  64. package/dist/expo-messenger.js +18 -7
  65. package/dist/expo-notifications.d.ts +17 -1
  66. package/dist/expo-notifications.js +36 -16
  67. package/dist/expo-outbox.d.ts +2 -0
  68. package/dist/expo-outbox.js +1 -1
  69. package/dist/expo-oversight.d.ts +15 -0
  70. package/dist/expo-oversight.js +15 -0
  71. package/dist/expo-reviews.d.ts +4 -1
  72. package/dist/expo-reviews.js +122 -17
  73. package/dist/expo-screen.js +5 -4
  74. package/dist/expo-thumbnails.d.ts +2 -2
  75. package/dist/expo-thumbnails.js +48 -5
  76. package/dist/expo.d.ts +10 -0
  77. package/dist/expo.js +8 -0
  78. package/dist/header-calls.js +1 -1
  79. package/dist/inbox-search.d.ts +1 -1
  80. package/dist/inbox-search.js +7 -3
  81. package/dist/inbox.d.ts +1 -0
  82. package/dist/inbox.js +5 -5
  83. package/dist/index.d.ts +8 -3
  84. package/dist/index.js +138 -63
  85. package/dist/linked-apps.d.ts +45 -0
  86. package/dist/linked-apps.js +40 -0
  87. package/dist/loading-messages.d.ts +1 -1
  88. package/dist/loading-messages.js +1 -1
  89. package/dist/media-controller.d.ts +2 -0
  90. package/dist/native-history-authorization.d.ts +4 -0
  91. package/dist/native-history-authorization.js +69 -0
  92. package/dist/native-history-backup.d.ts +16 -0
  93. package/dist/native-history-backup.js +144 -0
  94. package/dist/native-history.d.ts +14 -0
  95. package/dist/native-history.js +186 -0
  96. package/dist/native-outbox.d.ts +2 -0
  97. package/dist/oversight-session.d.ts +4 -0
  98. package/dist/oversight-session.js +14 -0
  99. package/dist/preview-layout.d.ts +12 -0
  100. package/dist/preview-layout.js +102 -0
  101. package/dist/recent-media.js +2 -1
  102. package/dist/reviews.d.ts +8 -4
  103. package/dist/reviews.js +53 -26
  104. package/dist/scheduled.js +2 -2
  105. package/dist/search.js +18 -8
  106. package/ios/RobonoBackupCloudKit.m +96 -0
  107. package/ios/RobonoHistoryStore.m +170 -0
  108. package/package.json +23 -5
  109. package/plugin/backup-expiration.cjs +23 -0
  110. package/plugin/prepare-native.cjs +12 -0
@@ -0,0 +1,56 @@
1
+ import { NativeModules } from 'react-native';
2
+ import { storageDigest } from './expo-storage-digest.js';
3
+ import { saveExpoHistoryPreview } from './expo-history-previews.js';
4
+ import { createNativeHistoryStore } from './native-history.js';
5
+ import { cleanExpoHistoryRestoreSessions } from './expo-history-maintenance.js';
6
+ /** Separate private SQLite database per endpoint, tenant and authenticated user.
7
+ * A native rebuild is required. Missing durable support must never silently
8
+ * fall back to an expiring cache and acknowledge delivery. */
9
+ export async function createExpoDurableHistoryStore(endpoint, userId, namespace = 'default') {
10
+ if (!NativeModules.RobonoHistoryStore?.executeAndPruneOriginals)
11
+ throw Error('Update this app to enable device history.');
12
+ const scope = await storageDigest(JSON.stringify([new URL(endpoint).href, namespace, userId]));
13
+ const database = commands => NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify(commands));
14
+ return createNativeHistoryStore(database, {
15
+ clearAll: async (commands) => { const result = await NativeModules.RobonoHistoryStore.executeAndClearOriginals(scope, JSON.stringify(commands)); await cleanExpoHistoryRestoreSessions(scope, database, true); return result; },
16
+ clearConversation: async (commands) => { const result = await NativeModules.RobonoHistoryStore.executeAndPruneOriginals(scope, JSON.stringify(commands)); await cleanExpoHistoryRestoreSessions(scope, database); return result; },
17
+ });
18
+ }
19
+ /** Bounded original-file reads for backup/export; never route private bytes
20
+ * through a network URL or depend on Expo access to Android no_backup files. */
21
+ export async function readExpoDurableHistoryOriginal(options) {
22
+ const scope = await storageDigest(JSON.stringify([new URL(options.endpoint).href, options.namespace ?? 'default', options.userId]));
23
+ return NativeModules.RobonoHistoryStore.readOriginal(scope, options.sha256, options.offset, options.length);
24
+ }
25
+ /** Download uses the normal authenticated media adapter. Native copying streams,
26
+ * hashes and syncs the original before the history transaction can acknowledge it. */
27
+ export async function createExpoDurableHistoryMedia(options) {
28
+ if (!NativeModules.RobonoHistoryStore?.saveOriginalGuarded)
29
+ throw Error('Update this app to save device history.');
30
+ const scope = await storageDigest(JSON.stringify([new URL(options.endpoint).href, options.namespace ?? 'default', options.userId]));
31
+ const account = createNativeHistoryStore(commands => NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify(commands)));
32
+ return {
33
+ async verify(original, signal) { if (signal.aborted || !NativeModules.RobonoHistoryStore?.verifyOriginal)
34
+ return false; const valid = await NativeModules.RobonoHistoryStore.verifyOriginal(scope, original.sha256, original.byteSize); return !signal.aborted && (valid === true || valid === 1); },
35
+ async save(change, signal, expectedGeneration) {
36
+ if (signal.aborted || !change.message.media || !change.mediaSha256)
37
+ throw Error('This attachment is unavailable.');
38
+ const epoch = expectedGeneration ?? await account.generation();
39
+ if (await account.generation() !== epoch)
40
+ throw Error('The account changed.');
41
+ const source = await options.download(change, signal);
42
+ try {
43
+ if (signal.aborted || await account.generation() !== epoch)
44
+ throw Error('The account changed.');
45
+ const original = await NativeModules.RobonoHistoryStore.saveOriginalGuarded(scope, source.uri, change.mediaSha256, change.message.media.byteSize, epoch);
46
+ await saveExpoHistoryPreview(scope, change.mediaSha256, epoch, change.message.kind, source.uri, signal);
47
+ if (signal.aborted || await account.generation() !== epoch)
48
+ throw Error('The account changed.');
49
+ return original;
50
+ }
51
+ finally {
52
+ await source.release();
53
+ }
54
+ }
55
+ };
56
+ }
@@ -0,0 +1,3 @@
1
+ /** Real durable history, not the expiring UI cache. Only the encrypted archive
2
+ * leaves the device; temporary restore files stay in the app's private cache. */
3
+ export declare function createExpoDurableHistoryBackupSource(endpoint: string, userId: string, namespace?: string): Promise<import("@robono/messaging").MessagingBackupSource>;
@@ -0,0 +1,79 @@
1
+ import { NativeModules } from 'react-native';
2
+ import { Directory, File, Paths } from 'expo-file-system';
3
+ import { randomUUID } from 'expo-crypto';
4
+ import { storageDigest } from './expo-storage-digest.js';
5
+ import { createNativeHistoryBackupSource } from './native-history-backup.js';
6
+ /** Real durable history, not the expiring UI cache. Only the encrypted archive
7
+ * leaves the device; temporary restore files stay in the app's private cache. */
8
+ export async function createExpoDurableHistoryBackupSource(endpoint, userId, namespace = 'default') {
9
+ const native = NativeModules.RobonoHistoryStore;
10
+ if (!native?.executeAndClearOriginals || !native?.readOriginal || !native?.saveOriginalGuarded)
11
+ throw Error('Update this app to enable history backups.');
12
+ const scope = await storageDigest(JSON.stringify([new URL(endpoint).href, namespace, userId]));
13
+ return createNativeHistoryBackupSource(commands => native.execute(scope, JSON.stringify(commands)), {
14
+ async read(sha, offset, length) { const encoded = await native.readOriginal(scope, sha, offset, length); return decodeOriginal(encoded); },
15
+ async stage(session) {
16
+ const directory = new Directory(Paths.cache, 'robono-history-restore', scope, session);
17
+ directory.create({ intermediates: true });
18
+ const files = new Map();
19
+ let closed = false;
20
+ return {
21
+ async write(sha, size, offset, bytes) {
22
+ if (closed || !/^[a-f0-9]{64}$/.test(sha) || bytes.length > 1024 * 1024)
23
+ throw Error('Invalid backup original.');
24
+ let row = files.get(sha);
25
+ if (!row) {
26
+ if (offset !== 0)
27
+ throw Error('Missing backup original part.');
28
+ const file = new File(directory, sha);
29
+ file.create();
30
+ row = { file, received: 0, size };
31
+ files.set(sha, row);
32
+ }
33
+ if (row.received !== offset || row.size !== size || offset + bytes.length > size)
34
+ throw Error('Invalid backup original order.');
35
+ const handle = row.file.open();
36
+ try {
37
+ handle.offset = offset;
38
+ handle.writeBytes(bytes);
39
+ }
40
+ finally {
41
+ handle.close();
42
+ }
43
+ row.received += bytes.length;
44
+ },
45
+ async promote(sha, size, epoch) {
46
+ const row = files.get(sha);
47
+ if (closed || !row || row.received !== size || row.size !== size)
48
+ throw Error('The backup original is incomplete.');
49
+ if (!native.saveOriginalGuarded)
50
+ throw Error('Update this app to restore message history.');
51
+ return native.saveOriginalGuarded(scope, row.file.uri, sha, size, epoch);
52
+ },
53
+ async discard() { closed = true; if (directory.exists)
54
+ directory.delete(); files.clear(); },
55
+ };
56
+ },
57
+ }, randomUUID);
58
+ }
59
+ // Hermes does not consistently expose atob. Decode at most one native 1 MiB
60
+ // chunk without allocating a JavaScript string/array for every decoded byte.
61
+ function decodeOriginal(input) {
62
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', length = input.length;
63
+ if (length > 1398104 || length % 4 !== 0)
64
+ throw Error('Invalid saved original.');
65
+ const padding = input.endsWith('==') ? 2 : input.endsWith('=') ? 1 : 0, out = new Uint8Array(length / 4 * 3 - padding);
66
+ let position = 0;
67
+ for (let i = 0; i < length; i += 4) {
68
+ let value = 0;
69
+ for (let j = 0; j < 4; j++) {
70
+ const char = input[i + j], digit = char === '=' && i + j >= length - padding ? 0 : alphabet.indexOf(char);
71
+ if (digit < 0)
72
+ throw Error('Invalid saved original.');
73
+ value = (value << 6) | digit;
74
+ }
75
+ for (let shift = 16; shift >= 0 && position < out.length; shift -= 8)
76
+ out[position++] = (value >> shift) & 255;
77
+ }
78
+ return out;
79
+ }
@@ -0,0 +1,4 @@
1
+ import type { NativeHistoryDatabase } from './native-history.js';
2
+ /** Only this account's SDK-owned restore scratch files. A fresh or active
3
+ * session is protected; session UUIDs are never reused by another restore. */
4
+ export declare function cleanExpoHistoryRestoreSessions(scope: string, database: NativeHistoryDatabase, cleared?: boolean): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import * as FS from 'expo-file-system/legacy';
2
+ /** Only this account's SDK-owned restore scratch files. A fresh or active
3
+ * session is protected; session UUIDs are never reused by another restore. */
4
+ export async function cleanExpoHistoryRestoreSessions(scope, database, cleared = false) {
5
+ if (!/^[a-f0-9]{64}$/.test(scope) || !FS.cacheDirectory)
6
+ return;
7
+ const root = FS.cacheDirectory + 'robono-history-restore/' + scope + '/';
8
+ if (!(await FS.getInfoAsync(root)).exists)
9
+ return;
10
+ const names = (await FS.readDirectoryAsync(root)).filter(name => /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(name)).slice(0, 100);
11
+ if (!names.length)
12
+ return;
13
+ const rows = await database([{ sql: `SELECT session FROM backup_sessions WHERE session IN(${names.map(() => '?').join(',')})`, args: names }]);
14
+ const active = new Set(rows[0].map(row => row.session));
15
+ for (const name of names) {
16
+ if (active.has(name))
17
+ continue;
18
+ const path = root + name + '/', info = await FS.getInfoAsync(path);
19
+ if (!info.exists || !info.isDirectory || !cleared && (!Number.isFinite(info.modificationTime) || info.modificationTime * 1000 > Date.now() - 86400000))
20
+ continue;
21
+ await FS.deleteAsync(path, { idempotent: true });
22
+ }
23
+ }
@@ -0,0 +1,5 @@
1
+ import type { LocalMessagingMedia } from './media-controller.js';
2
+ /** Disposable derived previews, scoped with private history. Generated only
3
+ * while receiving a sent original, never while browsing a media picker. */
4
+ export declare function saveExpoHistoryPreview(scope: string, sha256: string, epoch: number, kind: string, source: string, parent: AbortSignal): Promise<void>;
5
+ export declare function readExpoHistoryPreview(scope: string, sha256: string): Promise<LocalMessagingMedia | null>;
@@ -0,0 +1,57 @@
1
+ import { Image, NativeModules } from 'react-native';
2
+ import * as FS from 'expo-file-system/legacy';
3
+ import * as Images from 'expo-image-manipulator';
4
+ import * as Videos from 'expo-video-thumbnails';
5
+ import { withMessagingDeadline } from '@robono/messaging';
6
+ import { nativeHistoryPreviewTable } from './native-history.js';
7
+ /** Disposable derived previews, scoped with private history. Generated only
8
+ * while receiving a sent original, never while browsing a media picker. */
9
+ export async function saveExpoHistoryPreview(scope, sha256, epoch, kind, source, parent) {
10
+ if (!['image', 'video'].includes(kind))
11
+ return;
12
+ await withMessagingDeadline(async (signal) => {
13
+ let poster, output;
14
+ try {
15
+ if (signal.aborted)
16
+ return;
17
+ if (kind === 'video')
18
+ poster = (await Videos.getThumbnailAsync(source, { time: 0, quality: .6 })).uri;
19
+ if (signal.aborted)
20
+ return;
21
+ const dimensions = await new Promise((resolve, reject) => Image.getSize(poster ?? source, (width, height) => resolve({ width, height }), reject));
22
+ if (!Number.isFinite(dimensions.width) || !Number.isFinite(dimensions.height) || dimensions.width < 1 || dimensions.height < 1 || signal.aborted)
23
+ return;
24
+ const scale = Math.min(1, 320 / dimensions.width, 320 / dimensions.height);
25
+ const image = await Images.manipulateAsync(poster ?? source, [{ resize: { width: Math.max(1, Math.round(dimensions.width * scale)), height: Math.max(1, Math.round(dimensions.height * scale)) } }], { compress: .6, format: Images.SaveFormat.JPEG, base64: true });
26
+ output = image.uri;
27
+ if (signal.aborted || !image.base64 || image.base64.length > 65536)
28
+ return;
29
+ const preview = { uri: 'data:image/jpeg;base64,' + image.base64, mimeType: 'image/jpeg', fileName: 'Preview.jpg', byteSize: image.base64.length * 3 / 4 - (image.base64.endsWith('==') ? 2 : image.base64.endsWith('=') ? 1 : 0) };
30
+ await NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify([
31
+ nativeHistoryPreviewTable,
32
+ { sql: 'UPDATE history_control SET epoch=CASE WHEN epoch=? THEN epoch ELSE NULL END WHERE id=1', args: [epoch] },
33
+ { sql: 'INSERT OR REPLACE INTO history_previews(sha,preview) VALUES(?,?)', args: [sha256, JSON.stringify(preview)] },
34
+ ]));
35
+ }
36
+ finally {
37
+ for (const uri of [poster, output])
38
+ if (uri && FS.cacheDirectory && uri.startsWith(FS.cacheDirectory))
39
+ await FS.deleteAsync(uri, { idempotent: true }).catch(() => { });
40
+ }
41
+ }, { signal: parent, timeoutMs: 3000 }).catch(() => { }); // A preview failure never invalidates a verified original.
42
+ }
43
+ export async function readExpoHistoryPreview(scope, sha256) {
44
+ const results = await NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify([nativeHistoryPreviewTable, { sql: 'SELECT preview FROM history_previews WHERE sha=?', args: [sha256] }]));
45
+ const raw = results[1]?.[0]?.preview;
46
+ if (typeof raw !== 'string' || raw.length > 66000)
47
+ return null;
48
+ try {
49
+ const preview = JSON.parse(raw);
50
+ if (preview.mimeType !== 'image/jpeg' || typeof preview.uri !== 'string' || !/^data:image\/jpeg;base64,[a-zA-Z0-9+/]+={0,2}$/.test(preview.uri) || !Number.isSafeInteger(preview.byteSize) || preview.byteSize < 1 || preview.byteSize > 49152)
51
+ return null;
52
+ return preview;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
@@ -1,3 +1,3 @@
1
1
  import { MessagingHistoryCache } from '@robono/messaging';
2
- /** App-private recent history; no downloaded attachments or access tokens. */
2
+ /** App-private recent history and bounded thumbnails; no originals or tokens. */
3
3
  export declare function createExpoMessagingHistory(endpoint: string, userId: string, namespace?: string): MessagingHistoryCache;
@@ -2,7 +2,7 @@ import * as FS from 'expo-file-system/legacy';
2
2
  import * as Crypto from 'expo-crypto';
3
3
  import { MessagingHistoryCache } from '@robono/messaging';
4
4
  import { storageDigest as digest } from './expo-storage-digest.js';
5
- /** App-private recent history; no downloaded attachments or access tokens. */
5
+ /** App-private recent history and bounded thumbnails; no originals or tokens. */
6
6
  export function createExpoMessagingHistory(endpoint, userId, namespace = 'default') {
7
7
  const directory = async () => {
8
8
  if (!FS.documentDirectory)
@@ -16,7 +16,7 @@ export function createExpoMessagingHistory(endpoint, userId, namespace = 'defaul
16
16
  if (!file)
17
17
  return null;
18
18
  const info = await FS.getInfoAsync(dir + file);
19
- if (!info.exists || info.isDirectory || info.size > 200000) {
19
+ if (!info.exists || info.isDirectory || info.size > 1048576) {
20
20
  await FS.deleteAsync(dir + file, { idempotent: true });
21
21
  return null;
22
22
  }
@@ -1,3 +1,4 @@
1
+ import { type MessagingRequest } from '@robono/messaging';
1
2
  import { type AudioMode } from 'expo-audio';
2
3
  import type { LocalMessagingMedia, MessagingMediaDevice, MessagingMediaStorage } from './media-controller.js';
3
4
  export interface MessagingAudioSession {
@@ -17,4 +18,5 @@ export declare function createExpoMessagingStorage(options: {
17
18
  getAccessToken: () => Promise<string>;
18
19
  streaming?: boolean;
19
20
  fetch?: typeof fetch;
21
+ request?: MessagingRequest;
20
22
  }): MessagingMediaStorage;
@@ -1,5 +1,5 @@
1
1
  import { allocateMessagingCache, removeMessagingCacheUri } from './expo-cache.js';
2
- import { MessagingError } from '@robono/messaging';
2
+ import { MessagingError, withMessagingDeadline } from '@robono/messaging';
3
3
  import { MessagingMediaAccess, isRemoteMessagingAsset } from './media-access.js';
4
4
  import { awaitMediaScreening } from './media-screening';
5
5
  import { AppState } from 'react-native';
@@ -252,36 +252,30 @@ export function createExpoMessagingStorage(options) {
252
252
  const endpoint = https(options.url);
253
253
  const access = new MessagingMediaAccess();
254
254
  async function request(operation, input, signal) {
255
- const token = await options.getAccessToken();
256
- if (!token)
257
- throw new MessagingError('Sign in to continue.', 'authentication_required', 401);
258
- const bounded = new AbortController();
259
- const cancel = () => bounded.abort();
260
- signal?.addEventListener('abort', cancel, { once: true });
261
- if (signal?.aborted)
262
- bounded.abort();
263
- const timeout = setTimeout(cancel, operation === 'complete' ? 120000 : 15000);
264
255
  try {
265
- const response = await (options.fetch ?? fetch)(endpoint, { method: 'POST', redirect: 'error', signal: bounded.signal, headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, body: JSON.stringify({ ...input, operation }) });
266
- const result = await response.json();
267
- if (!response.ok || result?.error) {
268
- throw new MessagingError(result?.error?.message ?? 'The file could not be transferred. Try again.', result?.error?.code ?? 'media_unavailable', response.status);
269
- }
270
- return result;
256
+ return await withMessagingDeadline(async (bounded) => {
257
+ if (options.request)
258
+ return options.request(operation, input, { signal: bounded });
259
+ const token = await options.getAccessToken();
260
+ check(bounded);
261
+ if (!token)
262
+ throw new MessagingError('Sign in to continue.', 'authentication_required', 401);
263
+ const response = await (options.fetch ?? fetch)(endpoint, { method: 'POST', redirect: 'error', signal: bounded, headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, body: JSON.stringify({ ...input, operation }) });
264
+ const result = await response.json();
265
+ if (!response.ok || result?.error)
266
+ throw new MessagingError(result?.error?.message ?? 'The file could not be transferred. Try again.', result?.error?.code ?? 'media_unavailable', response.status);
267
+ return result;
268
+ }, { signal, timeoutMs: operation === 'complete' ? 120000 : 15000 });
271
269
  }
272
270
  catch (error) {
273
271
  if (signal?.aborted)
274
272
  throw error;
275
- if (bounded.signal.aborted)
273
+ if (error instanceof Error && error.name === 'TimeoutError')
276
274
  throw new MessagingError('Connection timed out.', 'request_timeout');
277
275
  if (error instanceof TypeError)
278
276
  throw new MessagingError('Connect to send your attachment.', 'network_unavailable');
279
277
  throw error;
280
278
  }
281
- finally {
282
- clearTimeout(timeout);
283
- signal?.removeEventListener('abort', cancel);
284
- }
285
279
  }
286
280
  async function playbackPlan(message, signal, reauthorize = false) {
287
281
  check(signal);
@@ -1,3 +1,4 @@
1
+ import type { MessageReviewNotificationOptions } from '@robono/messaging';
1
2
  import type { MessagingDirectoryOptions } from './contact-directory.js';
2
3
  import { createExpoMessengerCalling } from './expo-connected-calling.js';
3
4
  import type { LocationWorkspace } from '@robono/location';
@@ -13,6 +14,9 @@ export declare function createExpoMessenger(options: {
13
14
  fetch?: typeof fetch;
14
15
  /** Host-authorized transcription/translation, including any credit checks. */
15
16
  transformRequest?: import('@robono/messaging').MessagingRequest;
17
+ reviewNotifications?: MessageReviewNotificationOptions;
18
+ onNotificationRegistered?: import('./expo-notifications.js').ExpoMessagingNotificationOptions['onRegistered'];
19
+ onNotificationDiagnostic?: import('./expo-notifications.js').ExpoMessagingNotificationOptions['onDiagnostic'];
16
20
  availability?: false;
17
21
  notifications?: false;
18
22
  extras?: false;
@@ -26,6 +30,9 @@ export declare function createExpoMessenger(options: {
26
30
  namespace?: string;
27
31
  audioSession?: MessagingAudioSession;
28
32
  isCallActive?: () => boolean;
33
+ /** Show unexpired authorized local history immediately while refreshing access. */
34
+ historyAccess?: 'authorized-cache' | 'online';
35
+ deviceHistory?: import('@robono/messaging').MessagingDeviceHistory;
29
36
  }): {
30
37
  signOut(): Promise<void>;
31
38
  dispose(): void;
@@ -58,6 +65,7 @@ export declare function createExpoMessenger(options: {
58
65
  dispose(): Promise<void>;
59
66
  } | undefined;
60
67
  start: () => Promise<void>;
68
+ refreshAppearance: () => Promise<void>;
61
69
  getSnapshot: () => import("@robono/calling-react-native/messenger").MessengerCallingState;
62
70
  subscribe(fn: () => void): () => void;
63
71
  isActive: () => boolean;
@@ -103,6 +111,7 @@ export declare function createHostedExpoMessenger(options: Omit<Parameters<typeo
103
111
  dispose(): Promise<void>;
104
112
  } | undefined;
105
113
  start: () => Promise<void>;
114
+ refreshAppearance: () => Promise<void>;
106
115
  getSnapshot: () => import("@robono/calling-react-native/messenger").MessengerCallingState;
107
116
  subscribe(fn: () => void): () => void;
108
117
  isActive: () => boolean;
@@ -129,6 +138,7 @@ export interface ExpoMessengerProps extends Omit<ExpoMessagingScreenProps, 'cont
129
138
  contacts?: Record<string, {
130
139
  name: string;
131
140
  avatarUrl?: string;
141
+ networkName?: string;
132
142
  phoneNumber?: string;
133
143
  groupEligible?: boolean;
134
144
  }>;
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { createExpoInboxPreferences } from './expo-inbox-preferences.js';
3
+ import { withExpoDeviceHistoryStorage } from './expo-device-history.js';
3
4
  import { useDirectoryNavigation, MessagingDirectoryConversation } from './directory-navigation.js';
4
5
  import { renderNativeCallVideo } from '@robono/calling-react-native/native-video';
5
6
  import { createInboxViewMemory } from './inbox-view.js';
@@ -38,8 +39,10 @@ export function createExpoMessenger(options) {
38
39
  void availability?.stop(); };
39
40
  const activitySubscription = availability ? AppState.addEventListener('change', activityChanged) : undefined;
40
41
  activityChanged(AppState.currentState);
41
- const inbox = new MessagingInboxClient({ request: createMessagingTransport({ ...options, url: endpoint.href }), userId: options.userId, preferences: options.persistence === false ? undefined : createExpoInboxPreferences(endpoint.href, options.userId, options.namespace) });
42
- const storage = createExpoMessagingStorage({ url: media.href, getAccessToken: options.getAccessToken, ...(options.fetch ? { fetch: options.fetch } : {}) });
42
+ const inboxRequest = createMessagingTransport({ ...options, url: endpoint.href });
43
+ const inbox = new MessagingInboxClient({ request: options.deviceHistory?.wrap(inboxRequest) ?? inboxRequest, userId: options.userId, preferences: options.persistence === false ? undefined : createExpoInboxPreferences(endpoint.href, options.userId, options.namespace) });
44
+ const remoteStorage = createExpoMessagingStorage({ url: media.href, getAccessToken: options.getAccessToken, ...(options.fetch ? { fetch: options.fetch } : {}) });
45
+ const storage = options.deviceHistory ? withExpoDeviceHistoryStorage(remoteStorage, client, options) : remoteStorage;
43
46
  const outgoing = expoOutbox(client);
44
47
  if (outgoing)
45
48
  client.setRecoveryAdapter(worker => {
@@ -64,6 +67,10 @@ export function createExpoMessenger(options) {
64
67
  } });
65
68
  let connection = null, pending = null, closed = false;
66
69
  let openNotification;
70
+ const diagnostic = (event) => { try {
71
+ options.onNotificationDiagnostic?.(event);
72
+ }
73
+ catch { } };
67
74
  const notifications = options.notifications === false ? undefined : {
68
75
  async start(open) {
69
76
  openNotification = open;
@@ -75,14 +82,18 @@ export function createExpoMessenger(options) {
75
82
  url.searchParams.set('service', 'notifications');
76
83
  const request = createMessagingTransport({ ...options, url: endpoint.href });
77
84
  pending = (async () => {
78
- const n = await connectExpoMessagingNotifications({ url: url.href, userId: options.userId, getAccessToken: options.getAccessToken, ...(options.fetch ? { fetch: options.fetch } : {}),
85
+ const n = await connectExpoMessagingNotifications({ reviews: options.reviewNotifications, onRegistered: options.onNotificationRegistered, onDiagnostic: diagnostic, url: url.href, userId: options.userId, getAccessToken: options.getAccessToken, ...(options.fetch ? { fetch: options.fetch } : {}),
79
86
  authorize: async (e) => { try {
80
- return (await request('list', { conversationId: e.conversationId, messageIds: [e.messageId], notificationMessageId: e.messageId })).notificationAllowed === true;
87
+ const allowed = (await request('list', { conversationId: e.conversationId, messageIds: [e.messageId], notificationMessageId: e.messageId })).notificationAllowed === true;
88
+ diagnostic({ stage: 'authorization', accepted: allowed });
89
+ return allowed;
81
90
  }
82
91
  catch {
92
+ diagnostic({ stage: 'error' });
83
93
  return false;
84
94
  } },
85
- onCall: calling?.notification, systemCalls: calling?.systemNotifications, open: e => open(e.conversationId, e.messageId), refresh: () => inbox.refresh().then(() => { }), onError: () => { },
95
+ onCall: calling?.notification, systemCalls: calling?.systemNotifications, open: async (e) => { if (closed || !openNotification)
96
+ throw Error('The messenger is not available.'); await openNotification(e.conversationId, e.messageId); }, refresh: () => inbox.refresh().then(() => { }), onError: () => diagnostic({ stage: 'error' }),
86
97
  });
87
98
  if (closed) {
88
99
  await n.signOut();
@@ -193,8 +204,8 @@ function ExpoMessengerContent({ inbox, contacts = emptyContacts, initialConversa
193
204
  await props.client.focusMessage(messageId); }).catch(() => { });
194
205
  };
195
206
  const directoryNavigation = useDirectoryNavigation({ directory: props.directory, onOpenDirectoryContact: props.onOpenDirectoryContact, scope: inbox, userId: props.userId, active: props.active, onOpen: open });
196
- useEffect(() => { void notifications?.start(async (id, message) => { await inbox.refresh(); const row = inbox.getSnapshot().conversations.find(c => c.id === id); if (row)
197
- open(row, message); }).catch(() => { }); }, [notifications, inbox]);
207
+ useEffect(() => { void notifications?.start(async (id, message) => { await inbox.refresh(); const row = inbox.getSnapshot().conversations.find(c => c.id === id); if (!row)
208
+ throw Error('This conversation is not available.'); open(row, message); }).catch(() => { }); }, [notifications, inbox]);
198
209
  const notificationAccount = notifications ? { name: props.account?.name ?? 'Your account', ...props.account, onEnableNotifications: () => notifications.enable() } : props.account;
199
210
  const account = calling?.deviceCheck ? { name: 'Your account', ...notificationAccount, deviceCheck: calling.deviceCheck, renderCallPreview: (stream) => renderNativeCallVideo({ stream, local: true, style: { width: '100%', height: '100%' } }) } : notificationAccount;
200
211
  const knownContact = contacts[selected?.contactId ?? ''] ?? props.directory?.find(entry => entry.contactId === selected?.contactId);
@@ -1,7 +1,13 @@
1
1
  import * as Notifications from 'expo-notifications';
2
2
  import type { SystemCallNotifications } from '@robono/calling-react-native/system-calling';
3
- import { type MessagingNotification } from '@robono/messaging';
3
+ import { type MessageReviewNotificationOptions, type MessagingNotification } from '@robono/messaging';
4
4
  export interface ExpoMessagingNotificationOptions {
5
+ /** Optional content-free integration diagnostics. Never includes tokens or message contents. */
6
+ onDiagnostic?: (event: {
7
+ stage: 'response' | 'handled' | 'authorization' | 'error';
8
+ accepted?: boolean;
9
+ hasData?: boolean;
10
+ }) => void;
5
11
  /** The combined server route, with service=notifications. */
6
12
  url: string;
7
13
  userId: string;
@@ -10,8 +16,18 @@ export interface ExpoMessagingNotificationOptions {
10
16
  open: (event: MessagingNotification) => void | Promise<void>;
11
17
  refresh: () => void | Promise<void>;
12
18
  onError: (error: Error) => void;
19
+ /** Retire this installation's previous host alert registration only after the
20
+ * new authenticated registration succeeds. Failures retry on foreground. */
21
+ onRegistered?: (registration: {
22
+ deviceId: string;
23
+ userId: string;
24
+ accountScope: string;
25
+ signal: AbortSignal;
26
+ }) => Promise<void>;
13
27
  fetch?: typeof fetch;
14
28
  onCall?: (data: unknown, opened: boolean) => Promise<boolean>;
29
+ /** Optional assigned-reviewer notifications, using the authenticated review client. */
30
+ reviews?: MessageReviewNotificationOptions;
15
31
  systemCalls?: SystemCallNotifications;
16
32
  }
17
33
  /** One restored account. Never prompts on mount, replaces a global handler or opens an unverified call. */
@@ -4,15 +4,19 @@ import * as Crypto from 'expo-crypto';
4
4
  import * as SecureStore from 'expo-secure-store';
5
5
  import { Platform, AppState } from 'react-native';
6
6
  import { notificationData, presentedNotificationData, dismissReadNotification, notificationWasRead, rememberNotificationAccount, registerNotificationCleanup } from './expo-notification-cleanup.js';
7
- import { createMessagingNotificationRouter, parseMessagingNotification, parseMessagingReadNotification } from '@robono/messaging';
7
+ import { createMessageReviewNotificationRouter, parseMessageReviewNotification, withMessagingDeadline, createMessagingNotificationRouter, parseMessagingNotification, parseMessagingReadNotification } from '@robono/messaging';
8
8
  /** One restored account. Never prompts on mount, replaces a global handler or opens an unverified call. */
9
9
  export async function connectExpoMessagingNotifications(options) {
10
+ const diagnostic = (event) => { try {
11
+ options.onDiagnostic?.(event);
12
+ }
13
+ catch { } };
10
14
  if (!['ios', 'android'].includes(Platform.OS))
11
15
  throw Error('Mobile notification registration requires iPhone or Android.');
12
16
  const endpoint = new URL(options.url);
13
17
  if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password)
14
18
  throw Error('Use your authenticated HTTPS notification endpoint.');
15
- let disposed = false, closing = false, registerQueue = Promise.resolve(), accountScope, lastToken;
19
+ let disposed = false, closing = false, registerQueue = Promise.resolve(), accountScope, lastToken, cutoverPending = false;
16
20
  const key = 'robono.messaging.device.' + await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, endpoint.origin + endpoint.pathname);
17
21
  let deviceId = await SecureStore.getItemAsync(key);
18
22
  if (!deviceId) {
@@ -20,14 +24,16 @@ export async function connectExpoMessagingNotifications(options) {
20
24
  await SecureStore.setItemAsync(key, deviceId);
21
25
  }
22
26
  async function request(input) {
23
- const token = await options.getAccessToken();
24
- if (disposed)
25
- throw Error('Notification session has ended.');
26
- const response = await (options.fetch ?? fetch)(endpoint.href, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15000), headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, body: JSON.stringify({ ...input, ...(accountScope ? { accountScope } : {}) }) });
27
- const data = await response.json();
28
- if (!response.ok)
29
- throw Error(data?.error?.message ?? 'Notification setup is unavailable. Check your app’s Apple/Google credentials.');
30
- return data;
27
+ return withMessagingDeadline(async (signal) => {
28
+ const token = await options.getAccessToken();
29
+ if (disposed || signal.aborted)
30
+ throw Error('Notification session has ended or timed out.');
31
+ const response = await (options.fetch ?? fetch)(endpoint.href, { method: 'POST', redirect: 'error', signal, headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, body: JSON.stringify({ ...input, ...(accountScope ? { accountScope } : {}) }) });
32
+ const data = await response.json();
33
+ if (!response.ok)
34
+ throw Error(data?.error?.message ?? 'Notification setup is unavailable. Check your app’s Apple/Google credentials.');
35
+ return data;
36
+ });
31
37
  }
32
38
  const status = await request({ operation: 'notification-status' });
33
39
  if (status.userId !== options.userId || typeof status.accountScope !== 'string' || !/^[a-f\d]{64}$/.test(status.accountScope))
@@ -35,6 +41,7 @@ export async function connectExpoMessagingNotifications(options) {
35
41
  accountScope = status.accountScope;
36
42
  await rememberNotificationAccount(status.accountScope, true);
37
43
  const router = createMessagingNotificationRouter({ accountScope: status.accountScope, authorize: options.authorize, open: options.open, refresh: options.refresh });
44
+ const reviewRouter = options.reviews ? createMessageReviewNotificationRouter({ ...options.reviews, accountScope: status.accountScope }) : undefined;
38
45
  const register = (token) => {
39
46
  lastToken = token;
40
47
  const work = registerQueue.then(async () => {
@@ -47,6 +54,11 @@ export async function connectExpoMessagingNotifications(options) {
47
54
  const data = await request({ operation: 'register-device', calling: !!options.onCall, ...system, ...(appleEnvironment ? { appleEnvironment } : {}), deviceId, provider: Platform.OS === 'ios' ? 'apns' : 'fcm', token: String(token.data) });
48
55
  if (data.accountScope !== status.accountScope)
49
56
  throw Error('The signed-in account changed. Reconnect notifications for the new account.');
57
+ if (options.onRegistered && !disposed && !closing) {
58
+ cutoverPending = true;
59
+ await withMessagingDeadline(signal => options.onRegistered({ deviceId: deviceId, userId: options.userId, accountScope: status.accountScope, signal }));
60
+ cutoverPending = false;
61
+ }
50
62
  });
51
63
  registerQueue = work.catch(() => { });
52
64
  return work;
@@ -65,12 +77,17 @@ export async function connectExpoMessagingNotifications(options) {
65
77
  await Promise.all(shown.filter(n => n.request.content.data?.accountScope === accountScope && n.request.content.data?.call_id === data.call_id).map(n => Notifications.dismissNotificationAsync(n.request.identifier)));
66
78
  }
67
79
  return options.onCall(data, opened);
68
- } return router.handle(data, opened); };
80
+ } if (parseMessageReviewNotification(data))
81
+ return reviewRouter?.handle(data, opened) ?? false; return router.handle(data, opened); };
69
82
  const received = Notifications.addNotificationReceivedListener(notification => { void handle(notification.request.content.data).catch(options.onError); });
70
83
  const response = async (value) => {
84
+ if (value)
85
+ diagnostic({ stage: 'response', accepted: value.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER, hasData: !!notificationData(value.notification.request.content.data) });
71
86
  if (disposed || closing || !value || value.actionIdentifier !== Notifications.DEFAULT_ACTION_IDENTIFIER)
72
87
  return;
73
- if (await handle(value.notification.request.content.data, true)) {
88
+ const handled = await handle(value.notification.request.content.data, true);
89
+ diagnostic({ stage: 'handled', accepted: handled });
90
+ if (handled) {
74
91
  const last = await Notifications.getLastNotificationResponseAsync();
75
92
  if (!disposed && last?.notification.request.identifier === value.notification.request.identifier)
76
93
  await Notifications.clearLastNotificationResponseAsync();
@@ -91,8 +108,11 @@ export async function connectExpoMessagingNotifications(options) {
91
108
  await Notifications.dismissNotificationAsync(n.id);
92
109
  }
93
110
  })().finally(() => { reconciling = undefined; });
94
- const foreground = AppState.addEventListener('change', state => { if (state === 'active')
95
- void reconcile().catch(options.onError); });
111
+ const foreground = AppState.addEventListener('change', state => { if (state === 'active') {
112
+ void reconcile().catch(options.onError);
113
+ if (cutoverPending && lastToken && !disposed && !closing)
114
+ void register(lastToken).catch(options.onError);
115
+ } });
96
116
  const ready = (async () => {
97
117
  if (Platform.OS === 'android') {
98
118
  await Notifications.setNotificationChannelAsync('robono-messages', { name: 'Messages', importance: Notifications.AndroidImportance.HIGH });
@@ -106,7 +126,7 @@ export async function connectExpoMessagingNotifications(options) {
106
126
  await reconcile();
107
127
  })();
108
128
  void ready.catch(options.onError);
109
- const dispose = () => { disposed = true; router.dispose(); tokenListener.remove(); received.remove(); opened.remove(); foreground.remove(); void options.systemCalls?.disconnect().catch(options.onError); };
129
+ const dispose = () => { disposed = true; router.dispose(); reviewRouter?.dispose(); tokenListener.remove(); received.remove(); opened.remove(); foreground.remove(); void options.systemCalls?.disconnect().catch(options.onError); };
110
130
  return {
111
131
  ready, reconcile,
112
132
  /** Call only after the user chooses Enable notifications in your interface. */
@@ -114,7 +134,7 @@ export async function connectExpoMessagingNotifications(options) {
114
134
  return false; const permission = await Notifications.requestPermissionsAsync(); if (!permission.granted)
115
135
  return false; await register(await Notifications.getDevicePushTokenAsync()); return true; },
116
136
  /** Await before revoking your login session, so the old account's token is removed. */
117
- async signOut() { closing = true; router.dispose(); try {
137
+ async signOut() { closing = true; router.dispose(); reviewRouter?.dispose(); try {
118
138
  await registerQueue;
119
139
  await request({ operation: 'remove-device', deviceId });
120
140
  }
@@ -9,5 +9,7 @@ export declare function createExpoMessagingClient(options: {
9
9
  fetch?: typeof fetch;
10
10
  persistence?: false;
11
11
  namespace?: string;
12
+ historyAccess?: 'authorized-cache' | 'online';
13
+ deviceHistory?: import('@robono/messaging').MessagingDeviceHistory;
12
14
  transformRequest?: MessagingRequest;
13
15
  }): MessagingClient;
@@ -94,7 +94,7 @@ const files = {
94
94
  export function createExpoMessagingClient(options) {
95
95
  const request = createMessagingTransport(options), store = options.persistence === false ? undefined : new NativeMessagingOutbox(options.url, options.userId, files, options.namespace);
96
96
  const saved = store ? new ExpoSavedMessages(options.url, options.userId, options.namespace) : undefined;
97
- const client = new MessagingClient({ request, userId: options.userId, createMessageId: Crypto.randomUUID, outbox: store, saved, historyCache: store ? createExpoMessagingHistory(options.url, options.userId, options.namespace) : undefined, transformRequest: options.transformRequest });
97
+ const client = new MessagingClient({ request, historyAccess: options.historyAccess, deviceHistory: options.deviceHistory, userId: options.userId, createMessageId: Crypto.randomUUID, outbox: store, saved, historyCache: store ? createExpoMessagingHistory(options.url, options.userId, options.namespace) : undefined, transformRequest: options.transformRequest });
98
98
  if (store)
99
99
  stores.set(client, store);
100
100
  if (saved)