@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
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useState } from 'react';
3
3
  import { View } from 'react-native';
4
4
  import Svg, { Path, G } from 'react-native-svg';
5
- /** A two-pixel inside edge, narrowing to a point at both bubble corners. */
5
+ /** A two-pixel inside edge with short, tapered curves at both bubble corners. */
6
6
  export function DeliveryBar({ color, topRadius, bottomRadius, roundedStart = false }) {
7
7
  const [height, setHeight] = useState(0);
8
8
  const scale = height ? Math.min(1, height / Math.max(1, topRadius + bottomRadius)) : 1;
@@ -10,8 +10,11 @@ export function DeliveryBar({ color, topRadius, bottomRadius, roundedStart = fal
10
10
  const capHeight = (radius) => radius > 0 ? radius : Math.min(8, height ? height / 2 : 8);
11
11
  const cap = (radius, bottom = false) => {
12
12
  const width = Math.max(2, radius), height = capHeight(radius);
13
+ // Keep the side-facing half of each corner. The curve still follows the
14
+ // bubble's radius, but ends before wrapping onto its top or bottom edge.
15
+ const tipX = radius * .7071125, tipY = radius * .2928875;
13
16
  const path = radius > 0
14
- ? `M 0 0 C ${radius * .5523} 0 ${radius} ${radius * .4477} ${radius} ${radius} L ${Math.max(0, radius - 2)} ${radius} C ${Math.max(0, radius - 2)} ${radius * .4477} ${radius * .5523} 1 0 0 Z`
17
+ ? `M ${tipX} ${tipY} C ${radius * .888075} ${radius * .473275} ${radius} ${radius * .72385} ${radius} ${radius} L ${Math.max(0, radius - 2)} ${radius} C ${Math.max(0, radius - 2)} ${radius * .72385} ${radius * .888075} ${radius * .473275 + 1} ${tipX} ${tipY} Z`
15
18
  : `M 2 0 L 2 ${height} L 0 ${height} Z`;
16
19
  return _jsx(Svg, { width: width, height: height, viewBox: `0 0 ${width} ${height}`, style: { position: 'absolute', right: 0, ...(bottom ? { bottom: 0 } : { top: 0 }) }, accessible: false, children: _jsx(G, { transform: bottom ? `translate(0 ${height}) scale(1 -1)` : undefined, children: _jsx(Path, { d: path, fill: color }) }) });
17
20
  };
@@ -0,0 +1,9 @@
1
+ import type { MessagingMessage } from '@robono/messaging';
2
+ /** Used by the shared native and web bubble. Diagnostics stay out of the UI. */
3
+ export declare function deliveryNotice(message: MessagingMessage): {
4
+ text: string;
5
+ retry: boolean;
6
+ } | {
7
+ text: undefined;
8
+ retry: boolean;
9
+ };
@@ -0,0 +1,15 @@
1
+ /** Used by the shared native and web bubble. Diagnostics stay out of the UI. */
2
+ export function deliveryNotice(message) {
3
+ const delivery = message.delivery, code = delivery?.error;
4
+ if (delivery?.state === 'pending' && code === 'message_review_pending')
5
+ return { text: 'Waiting for safety check or review', retry: false };
6
+ if (delivery?.state !== 'failed')
7
+ return { text: undefined, retry: false };
8
+ if (code === 'message_screening_failed')
9
+ return { text: 'Safety check unavailable', retry: true };
10
+ if (['message_review_rejected', 'message_screening_blocked', 'message_rule_blocked'].includes(code ?? ''))
11
+ return { text: 'Not approved for delivery', retry: false };
12
+ if (['review_expired', 'review_source_unavailable', 'bridge_message_expired', 'history_content_expired'].includes(code ?? ''))
13
+ return { text: 'This unsent message has expired', retry: false };
14
+ return { text: undefined, retry: true };
15
+ }
@@ -0,0 +1,17 @@
1
+ import { type MessagingBackupPreferences } from '@robono/messaging';
2
+ import { type MessagingBackgroundBackupOptions } from './backup-background.js';
3
+ export type { MessagingBackgroundBackupOptions, MessagingBackgroundBackupSession } from './backup-background.js';
4
+ /** Call once at module scope in the host entry point, before registering React.
5
+ * This optional entry point requires expo-background-task and expo-task-manager.
6
+ * One task restores whichever host account is current; no identity/token is saved
7
+ * in the scheduler. Actual backup cadence comes from that account's preferences. */
8
+ export declare function defineExpoMessagingBackupTask(options: MessagingBackgroundBackupOptions & {
9
+ taskName?: string;
10
+ }): {
11
+ schedule: (preferences: MessagingBackupPreferences) => Promise<void>;
12
+ /** Sign-out must cancel active work and remove future OS wakes. */
13
+ stop: () => Promise<void>;
14
+ /** Also call on foreground resume; does nothing until a backup is due. */
15
+ run: () => Promise<boolean>;
16
+ cancel: () => void | undefined;
17
+ };
@@ -0,0 +1,57 @@
1
+ import * as BackgroundTask from 'expo-background-task';
2
+ import * as TaskManager from 'expo-task-manager';
3
+ import { MessagingBackupError } from '@robono/messaging';
4
+ import { createMessagingBackgroundBackupRunner } from './backup-background.js';
5
+ /** Call once at module scope in the host entry point, before registering React.
6
+ * This optional entry point requires expo-background-task and expo-task-manager.
7
+ * One task restores whichever host account is current; no identity/token is saved
8
+ * in the scheduler. Actual backup cadence comes from that account's preferences. */
9
+ export function defineExpoMessagingBackupTask(options) {
10
+ const name = options.taskName ?? 'robono.messaging.backup.v1';
11
+ if (!/^[a-zA-Z0-9._-]{1,160}$/.test(name))
12
+ throw Error('Invalid backup task name.');
13
+ if (TaskManager.isTaskDefined(name))
14
+ throw Error('Define the backup task only once, at the application entry point.');
15
+ const runner = createMessagingBackgroundBackupRunner(options);
16
+ let pending = Promise.resolve();
17
+ TaskManager.defineTask(name, async ({ error }) => {
18
+ if (error)
19
+ return BackgroundTask.BackgroundTaskResult.Failed;
20
+ const expiration = BackgroundTask.addExpirationListener(runner.cancel);
21
+ try {
22
+ return await runner.run() ? BackgroundTask.BackgroundTaskResult.Success : BackgroundTask.BackgroundTaskResult.Failed;
23
+ }
24
+ finally {
25
+ expiration.remove();
26
+ }
27
+ });
28
+ const schedule = (preferences) => {
29
+ if (!['off', 'daily', 'weekly', 'monthly'].includes(preferences.frequency))
30
+ return Promise.reject(Error('Invalid backup frequency.'));
31
+ if (preferences.frequency === 'off')
32
+ runner.cancel();
33
+ const next = pending.catch(() => { }).then(async () => {
34
+ if (preferences.frequency === 'off') {
35
+ if (await TaskManager.isTaskRegisteredAsync(name))
36
+ await BackgroundTask.unregisterTaskAsync(name);
37
+ }
38
+ else {
39
+ if (await BackgroundTask.getStatusAsync() !== BackgroundTask.BackgroundTaskStatus.Available)
40
+ throw new MessagingBackupError('background_unavailable');
41
+ // Check daily even for monthly schedules, so OS delays cannot postpone a
42
+ // missed month by another full month. runScheduled checks the calendar due date.
43
+ await BackgroundTask.registerTaskAsync(name, { minimumInterval: 12 * 60 });
44
+ }
45
+ });
46
+ pending = next;
47
+ return next;
48
+ };
49
+ return {
50
+ schedule,
51
+ /** Sign-out must cancel active work and remove future OS wakes. */
52
+ stop: () => schedule({ frequency: 'off', cellular: false, includeVideos: false }),
53
+ /** Also call on foreground resume; does nothing until a backup is due. */
54
+ run: runner.run,
55
+ cancel: runner.cancel,
56
+ };
57
+ }
@@ -0,0 +1,6 @@
1
+ /** The host must provision this private iCloud container in its signed app. */
2
+ export declare function createExpoCloudKitMessagingBackup(options: {
3
+ container: string;
4
+ openSettings: () => Promise<void>;
5
+ retainedSnapshots?: number;
6
+ }): import("@robono/messaging").MessagingBackupCloud;
@@ -0,0 +1,11 @@
1
+ import { NativeModules, Platform } from 'react-native';
2
+ import { randomUUID } from 'expo-crypto';
3
+ import { MessagingBackupError } from '@robono/messaging';
4
+ import { createCloudKitMessagingBackupCloud } from './cloudkit-backup.js';
5
+ /** The host must provision this private iCloud container in its signed app. */
6
+ export function createExpoCloudKitMessagingBackup(options) {
7
+ const native = NativeModules.RobonoBackupCloudKit;
8
+ if (Platform.OS !== 'ios' || !native)
9
+ throw new MessagingBackupError('unavailable');
10
+ return createCloudKitMessagingBackupCloud({ ...options, transport: native, randomId: randomUUID });
11
+ }
@@ -0,0 +1,7 @@
1
+ /** Requires a Google Android OAuth client for this package and signing SHA-1,
2
+ * Drive API enabled, and consent-screen configuration in the host's project.
3
+ * Only connect() may present consent; background account checks never do. */
4
+ export declare function createExpoGoogleMessagingBackup(options?: {
5
+ retainedSnapshots?: number;
6
+ openStorage?: () => Promise<void>;
7
+ }): import("@robono/messaging").MessagingBackupCloud;
@@ -0,0 +1,16 @@
1
+ import { NativeModules, Platform, Linking } from 'react-native';
2
+ import { randomUUID } from 'expo-crypto';
3
+ import { fetch as streamingFetch } from 'expo/fetch';
4
+ import { createGoogleMessagingBackupCloud, MessagingBackupError } from '@robono/messaging';
5
+ import { createMessagingGoogleBackupAuthorization } from './backup-google-authorization.js';
6
+ /** Requires a Google Android OAuth client for this package and signing SHA-1,
7
+ * Drive API enabled, and consent-screen configuration in the host's project.
8
+ * Only connect() may present consent; background account checks never do. */
9
+ export function createExpoGoogleMessagingBackup(options = {}) {
10
+ const transport = NativeModules.RobonoBackupGoogle;
11
+ if (Platform.OS !== 'android' || !transport)
12
+ throw new MessagingBackupError('unavailable');
13
+ const fetch = streamingFetch;
14
+ const authorization = createMessagingGoogleBackupAuthorization({ transport, fetch, randomId: randomUUID });
15
+ return createGoogleMessagingBackupCloud({ ...authorization, fetch, retainedSnapshots: options.retainedSnapshots, openStorage: options.openStorage ?? (async () => { await Linking.openURL('https://one.google.com/storage'); }) });
16
+ }
@@ -0,0 +1,8 @@
1
+ import type { MessagingBackupDriver } from '@robono/messaging';
2
+ type BackupNetwork = Awaited<ReturnType<MessagingBackupDriver['network']>>;
3
+ /** Network events cancel transfers when the user's current policy forbids them. */
4
+ export declare function createExpoMessagingBackupNetwork(): {
5
+ network: () => Promise<BackupNetwork>;
6
+ subscribeNetwork(listener: (network: BackupNetwork) => void): () => void;
7
+ };
8
+ export {};
@@ -0,0 +1,18 @@
1
+ import * as Network from 'expo-network';
2
+ function classify(state) {
3
+ if (state.isConnected === false || state.isInternetReachable === false)
4
+ return 'offline';
5
+ if (state.type === Network.NetworkStateType.WIFI)
6
+ return 'wifi';
7
+ if (state.type === Network.NetworkStateType.CELLULAR)
8
+ return 'cellular';
9
+ // Unknown/VPN/wired interfaces cannot silently override Wi-Fi-only consent.
10
+ return 'unknown';
11
+ }
12
+ /** Network events cancel transfers when the user's current policy forbids them. */
13
+ export function createExpoMessagingBackupNetwork() {
14
+ return {
15
+ network: async () => classify(await Network.getNetworkStateAsync()),
16
+ subscribeNetwork(listener) { const subscription = Network.addNetworkStateListener(state => listener(classify(state))); return () => subscription.remove(); },
17
+ };
18
+ }
@@ -1,7 +1,14 @@
1
1
  import { type MessagingBackupPasskeys } from '@robono/messaging';
2
2
  /** Requires react-native-passkey, iOS associated domains and Android Digital Asset
3
3
  * Links for the same RP ID. Unsupported providers never fall back to weaker keys. */
4
+ export interface MessagingNativePasskeyDiagnostic {
5
+ operation: 'create' | 'get';
6
+ code: string;
7
+ nativeCode: number | null;
8
+ reason: 'domain-association' | 'request-format' | 'provider-unavailable' | 'cancelled' | 'other';
9
+ }
4
10
  export declare function createExpoMessagingBackupPasskeys(options: {
5
11
  rpId: string;
6
12
  name: string;
13
+ onDiagnostic?: (diagnostic: MessagingNativePasskeyDiagnostic) => void;
7
14
  }): MessagingBackupPasskeys;
@@ -1,8 +1,12 @@
1
1
  import { NativeModules, Platform } from 'react-native';
2
2
  import { getRandomBytes } from 'expo-crypto';
3
- import { createMessagingBackupPasskeys } from '@robono/messaging';
4
- /** Requires react-native-passkey, iOS associated domains and Android Digital Asset
5
- * Links for the same RP ID. Unsupported providers never fall back to weaker keys. */
3
+ import { backupUnbase64, createMessagingBackupPasskeys } from '@robono/messaging';
4
+ // react-native-passkey's iOS bridge decodes PRF inputs as byte dictionaries;
5
+ // Android accepts their base64url JSON representation. Keep the shared/web
6
+ // protocol unchanged and translate only at this native transport boundary.
7
+ function nativeRequest(request) {
8
+ return { ...request, extensions: { ...request.extensions, prf: { eval: { first: Platform.OS === 'ios' ? backupUnbase64(request.extensions.prf.eval.first) : request.extensions.prf.eval.first } } } };
9
+ }
6
10
  export function createExpoMessagingBackupPasskeys(options) {
7
11
  const load = async () => { try {
8
12
  return (await import('react-native-passkey')).Passkey;
@@ -10,13 +14,33 @@ export function createExpoMessagingBackupPasskeys(options) {
10
14
  catch {
11
15
  return null;
12
16
  } };
17
+ const invoke = async (operation, request) => {
18
+ try {
19
+ const passkey = await load();
20
+ if (!passkey)
21
+ throw { error: 'ModuleUnavailable' };
22
+ return operation === 'create' ? await passkey.create(nativeRequest(request)) : await passkey.get(nativeRequest(request));
23
+ }
24
+ catch (error) {
25
+ const e = error;
26
+ const value = String(e?.error ?? e?.code ?? 'UnknownError'), message = String(e?.message ?? '');
27
+ const code = /^[A-Za-z ]{1,40}$/.test(value) ? value : 'UnknownError';
28
+ const number = message.match(/(?:error|code)\s*[:=]?\s*(-?\d{1,8})\b/i);
29
+ const reason = /associat|domain|rp id|relying party/i.test(message) ? 'domain-association' : /decod|format|data couldn.t be read|missing/i.test(message) ? 'request-format' : /provider|keychain|no credentials/i.test(message) ? 'provider-unavailable' : code === 'UserCancelled' ? 'cancelled' : 'other';
30
+ // Only bounded categorical metadata reaches host diagnostics, never the
31
+ // request, credential, salts, PRF result, account name or native message.
32
+ try {
33
+ options.onDiagnostic?.({ operation, code, nativeCode: number ? Number(number[1]) : null, reason });
34
+ }
35
+ catch { }
36
+ throw error;
37
+ }
38
+ };
13
39
  return createMessagingBackupPasskeys({ ...options, random: getRandomBytes, transport: {
14
40
  async available() { if (!NativeModules.Passkey)
15
41
  return false; if (Platform.OS === 'ios' && Number.parseInt(String(Platform.Version), 10) < 18)
16
42
  return false; const passkey = await load(); return !!passkey?.isSupported(); },
17
- async create(request) { const passkey = await load(); if (!passkey)
18
- throw Error('Passkeys unavailable'); return passkey.create(request); },
19
- async get(request) { const passkey = await load(); if (!passkey)
20
- throw Error('Passkeys unavailable'); return passkey.get(request); },
43
+ create: request => invoke('create', request),
44
+ get: request => invoke('get', request),
21
45
  } });
22
46
  }
@@ -5,19 +5,33 @@ import { storageDigest } from './expo-storage-digest.js';
5
5
  /** Recovery keys stay in Keychain/Keystore. Preferences contain no credentials.
6
6
  * The scope must be identical to the durable history's endpoint/tenant/account scope. */
7
7
  export function createExpoMessagingBackupSettings(endpoint, userId, namespace = 'default') {
8
- const scope = storageDigest(JSON.stringify([endpoint, namespace, userId]));
9
- const directory = async () => {
8
+ const scope = storageDigest(JSON.stringify([new URL(endpoint).href, namespace, userId]));
9
+ // Preserve protection configured by earlier SDKs that hashed the raw URL.
10
+ const legacyScope = storageDigest(JSON.stringify([endpoint, namespace, userId]));
11
+ const scopes = async () => [...new Set(await Promise.all([scope, legacyScope]))];
12
+ const directory = async (value) => {
10
13
  if (!FS.documentDirectory)
11
14
  throw Error('Private backup settings are unavailable.');
12
- return FS.documentDirectory + 'robono-backup-settings/' + await scope + '/';
15
+ return FS.documentDirectory + 'robono-backup-settings/' + (value ?? await scope) + '/';
13
16
  };
14
17
  const keyOptions = { keychainService: 'robono-messaging-backup', keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY };
15
- const readEncryption = async () => { const raw = await SecureStore.getItemAsync('encryption-' + await scope, keyOptions); return raw ? JSON.parse(raw) : null; };
18
+ const secret = async (prefix) => { for (const value of await scopes()) {
19
+ const raw = await SecureStore.getItemAsync(prefix + value, keyOptions);
20
+ if (raw !== null)
21
+ return raw;
22
+ } return null; };
23
+ const readEncryption = async () => { const raw = await secret('encryption-'); return raw ? JSON.parse(raw) : null; };
16
24
  let pending = Promise.resolve();
17
25
  return {
18
- async readPreferences() { await pending.catch(() => { }); const file = await directory() + 'preferences.json'; const info = await FS.getInfoAsync(file); if (!info.exists)
19
- return null; if (info.isDirectory || info.size > 4096)
20
- throw Error('Backup settings could not be read.'); return JSON.parse(await FS.readAsStringAsync(file)); },
26
+ async readPreferences() { await pending.catch(() => { }); for (const value of await scopes()) {
27
+ const file = await directory(value) + 'preferences.json';
28
+ const info = await FS.getInfoAsync(file);
29
+ if (!info.exists)
30
+ continue;
31
+ if (info.isDirectory || info.size > 4096)
32
+ throw Error('Backup settings could not be read.');
33
+ return JSON.parse(await FS.readAsStringAsync(file));
34
+ } return null; },
21
35
  writePreferences(value) {
22
36
  const work = pending.catch(() => { }).then(async () => {
23
37
  const dir = await directory(), temp = dir + randomUUID() + '.tmp';
@@ -34,8 +48,12 @@ export function createExpoMessagingBackupSettings(endpoint, userId, namespace =
34
48
  return work;
35
49
  },
36
50
  readEncryption,
51
+ async readCloudAccount() { const raw = await secret('cloud-account-'); if (!raw)
52
+ return null; const value = JSON.parse(raw); if (typeof value?.id !== 'string' || !value.id || value.id.length > 1024 || !['google', 'icloud', 'custom'].includes(value.provider))
53
+ throw Error('Backup account settings could not be read.'); return { id: value.id, provider: value.provider }; },
54
+ async writeCloudAccount(value) { await SecureStore.setItemAsync('cloud-account-' + await scope, JSON.stringify({ id: value.id, provider: value.provider }), keyOptions); },
37
55
  async writeEncryption(value) { await SecureStore.setItemAsync('encryption-' + await scope, JSON.stringify(value), keyOptions); },
38
- async readRecoveryKey() { return (await readEncryption())?.key ?? SecureStore.getItemAsync('recovery-' + await scope, keyOptions); },
56
+ async readRecoveryKey() { return (await readEncryption())?.key ?? secret('recovery-'); },
39
57
  async writeRecoveryKey(value) { await SecureStore.setItemAsync('recovery-' + await scope, value, keyOptions); },
40
58
  };
41
59
  }
@@ -0,0 +1,14 @@
1
+ import { MessagingBackupClient, type MessagingBackupCloud, type MessagingBackupDriver, type MessagingBackupPasskeys } from '@robono/messaging';
2
+ /** Complete local backup plumbing for the shared Account → Chat backup screen.
3
+ * The host supplies its user's cloud authorization and OS scheduling. This must
4
+ * use the same identity as the durable received-history connection. */
5
+ export declare function createExpoMessagingBackup(options: {
6
+ endpoint: string;
7
+ userId: string;
8
+ namespace?: string;
9
+ cloud: MessagingBackupCloud | (() => MessagingBackupCloud);
10
+ network: MessagingBackupDriver['network'];
11
+ schedule: MessagingBackupDriver['schedule'];
12
+ subscribeNetwork?: MessagingBackupDriver['subscribeNetwork'];
13
+ passkeys?: MessagingBackupPasskeys;
14
+ }): Promise<MessagingBackupClient>;
@@ -0,0 +1,22 @@
1
+ import { MessagingBackupClient, createMessagingBackupDriver } from '@robono/messaging';
2
+ import { createExpoDurableHistoryBackupSource } from './expo-history-backup.js';
3
+ import { createExpoMessagingBackupCrypto } from './expo-backup-crypto.js';
4
+ import { createExpoMessagingBackupSettings } from './expo-backup-settings.js';
5
+ import { storageDigest } from './expo-storage-digest.js';
6
+ /** Complete local backup plumbing for the shared Account → Chat backup screen.
7
+ * The host supplies its user's cloud authorization and OS scheduling. This must
8
+ * use the same identity as the durable received-history connection. */
9
+ export async function createExpoMessagingBackup(options) {
10
+ const endpoint = new URL(options.endpoint).href, namespace = options.namespace ?? 'default';
11
+ if (!options.userId.trim() || options.userId.length > 200 || !namespace || namespace.length > 200)
12
+ throw Error('Choose a signed-in history account.');
13
+ const scope = await storageDigest(JSON.stringify([endpoint, namespace, options.userId]));
14
+ const source = await createExpoDurableHistoryBackupSource(endpoint, options.userId, namespace);
15
+ // Defer provider setup until the screen refreshes. A missing native module or
16
+ // account configuration becomes the shared screen's normal recoverable error,
17
+ // rather than removing Account → Chat backup or breaking Messenger startup.
18
+ let provider;
19
+ const get = () => provider ??= (typeof options.cloud === 'function' ? options.cloud() : options.cloud);
20
+ const cloud = { account: async (signal) => get().account(signal), connect: async (signal) => get().connect(signal), manageStorage: async () => get().manageStorage(), latest: async (...args) => get().latest(...args), read: async (...args) => get().read(...args), write: async (...args) => get().write(...args), commit: async (...args) => get().commit(...args), discard: async (...args) => get().discard(...args), maintain: async (...args) => { await get().maintain?.(...args); } };
21
+ return new MessagingBackupClient(createMessagingBackupDriver({ scope, source, cloud, crypto: createExpoMessagingBackupCrypto(), local: createExpoMessagingBackupSettings(endpoint, options.userId, namespace), network: options.network, subscribeNetwork: options.subscribeNetwork, schedule: options.schedule, passkeys: options.passkeys }));
22
+ }
@@ -5,6 +5,8 @@ export declare function createExpoBridgeMessenger(options: {
5
5
  userId: string;
6
6
  connectionId: string;
7
7
  getAccessToken: () => Promise<string>;
8
+ deviceHistory?: import('@robono/messaging').MessagingDeviceHistory;
9
+ historyAccess?: 'authorized-cache' | 'online';
8
10
  foregroundPresence?: boolean;
9
11
  fetch?: typeof fetch;
10
12
  namespace?: string;
@@ -4,11 +4,13 @@ import { createBridgePresenceSession } from '@robono/messaging';
4
4
  import { bridgeMessengerFetch, bridgeLanguageRequest, createMessagingTransport, refreshBridgeMessengerFromPush } from '@robono/messaging';
5
5
  import { createExpoMessagingClient, expoOutbox } from './expo-outbox.js';
6
6
  import { createExpoMessagingStorage, createExpoMessagingAudioSession } from './expo-media.js';
7
+ import { withExpoDeviceHistoryStorage } from './expo-device-history.js';
7
8
  /** Standard ExpoMessagingScreen connection for an already accepted Bridge friend. */
8
9
  export function createExpoBridgeMessenger(options) {
9
10
  const transportFetch = bridgeMessengerFetch(options.connectionId, options.fetch);
10
11
  const client = createExpoMessagingClient({ ...options, fetch: transportFetch, transformRequest: bridgeLanguageRequest(createMessagingTransport({ ...options, fetch: transportFetch })), namespace: (options.namespace ?? '') + ':bridge:' + options.connectionId });
11
- const storage = createExpoMessagingStorage({ url: options.url, getAccessToken: options.getAccessToken, fetch: transportFetch });
12
+ const remoteStorage = createExpoMessagingStorage({ url: options.url, getAccessToken: options.getAccessToken, fetch: transportFetch });
13
+ const storage = options.deviceHistory ? withExpoDeviceHistoryStorage(remoteStorage, client, { endpoint: options.url, userId: options.userId, namespace: options.namespace }) : remoteStorage;
12
14
  const outgoing = expoOutbox(client);
13
15
  if (outgoing)
14
16
  client.setRecoveryAdapter(worker => {
@@ -6,6 +6,19 @@ let limits = { ...defaultMessagingDiskCacheLimits };
6
6
  // selected attachments stay protected until their existing remove() lifecycle.
7
7
  const active = new Set();
8
8
  let maintenance, started = false, lastMaintenance = 0;
9
+ let scheduled = false;
10
+ function scheduleMaintenance() {
11
+ if (scheduled)
12
+ return;
13
+ scheduled = true;
14
+ const run = () => { scheduled = false; if (maintenance || Date.now() - lastMaintenance < 60000)
15
+ return; void maintainExpoMessagingCache().catch(() => { started = false; }); };
16
+ const idle = globalThis.requestIdleCallback;
17
+ if (idle)
18
+ idle(run, { timeout: 5000 });
19
+ else
20
+ setTimeout(run, 1000);
21
+ }
9
22
  export function configureExpoMessagingCache(options) {
10
23
  for (const [key, value] of Object.entries(options))
11
24
  if (!Object.prototype.hasOwnProperty.call(limits, key) || !Number.isSafeInteger(value) || value < 0)
@@ -81,10 +94,16 @@ export async function maintainExpoMessagingCache(options = {}) {
81
94
  }
82
95
  export async function allocateMessagingCache(requiredBytes = 0, draft = false) {
83
96
  const low = requiredBytes > 0 && (await FS.getFreeDiskStorageAsync()) < limits.minFreeBytes + requiredBytes;
84
- if (!started || low || Date.now() - lastMaintenance > 60000) {
97
+ // Low space must be resolved before writing. Routine age/size housekeeping
98
+ // waits for idle time, so opening a chat never waits for a scan of old files.
99
+ if (low) {
85
100
  await maintainExpoMessagingCache({ requiredBytes });
86
101
  started = true;
87
102
  }
103
+ else if (!started || Date.now() - lastMaintenance > 60000) {
104
+ started = true;
105
+ scheduleMaintenance();
106
+ }
88
107
  const dir = messagingCacheRoot() + Crypto.randomUUID() + '/';
89
108
  active.add(dir);
90
109
  try {
@@ -27,6 +27,7 @@ export declare function createExpoMessengerCalling(options: {
27
27
  dispose(): Promise<void>;
28
28
  } | undefined;
29
29
  start: () => Promise<void>;
30
+ refreshAppearance: () => Promise<void>;
30
31
  getSnapshot: () => MessengerCallingState;
31
32
  subscribe(fn: () => void): () => void;
32
33
  isActive: () => boolean;
@@ -4,7 +4,7 @@ import { Text } from './typography.js';
4
4
  import { callingText } from '@robono/calling-react-native/appearance';
5
5
  import { useRobonoLocale } from './localization.js';
6
6
  import { useEffect, useSyncExternalStore } from 'react';
7
- import { Pressable, View } from 'react-native';
7
+ import { AppState, Pressable, View } from 'react-native';
8
8
  import { setAudioModeAsync } from 'expo-audio';
9
9
  import { createMessengerCalling } from '@robono/calling-react-native/messenger';
10
10
  import { createNativeCallAdapters, createNativeCallDeviceCheck } from '@robono/calling-react-native/native';
@@ -18,6 +18,7 @@ export function createExpoMessengerCalling(options) {
18
18
  let people = {};
19
19
  const system = createNativeSystemCalling({ start: () => calling.start(), onError: () => calling.reportError('The incoming call could not connect. Open the app and check microphone access and your connection.') });
20
20
  const calling = createMessengerCalling({
21
+ onAppearance: appearance => system.updateAppearance(appearance),
21
22
  deviceCheck: active => createNativeCallDeviceCheck({ active, restoreAudio: () => setAudioModeAsync({ allowsRecording: false, playsInSilentMode: true, shouldPlayInBackground: false, shouldRouteThroughEarpiece: false, interruptionMode: 'mixWithOthers' }) }),
22
23
  request: createMessagingTransport({ ...options, url: url.href }),
23
24
  resolveContact: id => {
@@ -36,9 +37,19 @@ export function createExpoMessengerCalling(options) {
36
37
  return { ...adapter, attach(value) { controller = value; const a = runtime.attach(value), b = system.attach(value); return () => { b(); a(); controller = undefined; }; }, dispose: runtime.dispose };
37
38
  },
38
39
  });
40
+ // Branding refresh is independent of call/session renewal, and never ends an
41
+ // active call. Stop polling in the background; locked launches use native cache.
42
+ let brandingTimer;
43
+ const refreshBranding = () => { void calling.refreshAppearance().catch(() => { }); };
44
+ const brandingState = (state) => { clearInterval(brandingTimer); if (state === 'active') {
45
+ refreshBranding();
46
+ brandingTimer = setInterval(refreshBranding, 60000);
47
+ } };
48
+ const brandingSubscription = AppState.addEventListener('change', brandingState);
49
+ brandingState(AppState.currentState);
39
50
  return { ...calling, systemNotifications: system.notifications,
40
51
  async notification(data, opened = false) { await system.receive(data); return calling.notification(data, opened); },
41
- async dispose() { await system.dispose(); await calling.dispose(); },
52
+ async dispose() { brandingSubscription.remove(); clearInterval(brandingTimer); await system.dispose(); await calling.dispose(); },
42
53
  updateContacts(next) { people = next; const names = {}; for (const row of options.inbox.getSnapshot().conversations) {
43
54
  const person = next[row.contactId ?? ''];
44
55
  const name = row.kind === 'group' ? row.name : person?.name;
@@ -0,0 +1,24 @@
1
+ import { MessagingDeviceHistory, type MessagingClient } from '@robono/messaging';
2
+ import type { MessagingMediaStorage } from './media-controller.js';
3
+ type Account = {
4
+ endpoint: string;
5
+ userId: string;
6
+ namespace?: string;
7
+ };
8
+ /** Explicit opt-in for the authenticated device-history route. This does not
9
+ * change the server's retention policy or enroll any other integration. */
10
+ export declare function createExpoDeviceHistory(options: Account & {
11
+ getAccessToken: () => Promise<string>;
12
+ fetch?: typeof fetch;
13
+ onError?: (error: unknown) => void;
14
+ historyRequest?: import('@robono/messaging').MessagingRequest;
15
+ localAccess?: import('@robono/messaging').MessagingRequest;
16
+ download?: (change: import('@robono/messaging').DurableHistoryChange, signal: AbortSignal) => Promise<{
17
+ uri: string;
18
+ release(): Promise<void>;
19
+ }>;
20
+ }): Promise<MessagingDeviceHistory>;
21
+ /** Viewer/forward/export copies use the established bounded private cache. The
22
+ * durable source is never passed to cleanup code or copied through JS base64. */
23
+ export declare function withExpoDeviceHistoryStorage(storage: MessagingMediaStorage, client: MessagingClient, account: Account): MessagingMediaStorage;
24
+ export {};
@@ -0,0 +1,88 @@
1
+ import { NativeModules } from 'react-native';
2
+ import { MessagingDeviceHistory, MessagingHistorySync, createMessagingTransport } from '@robono/messaging';
3
+ import { createExpoDurableHistoryStore, createExpoDurableHistoryMedia } from './expo-durable-history.js';
4
+ import { createExpoMessagingStorage, createExpoMessagingDevice, createExpoMessagingAudioSession } from './expo-media.js';
5
+ import { storageDigest } from './expo-storage-digest.js';
6
+ import { allocateMessagingCache, removeMessagingCacheUri } from './expo-cache.js';
7
+ import { readExpoHistoryPreview, saveExpoHistoryPreview } from './expo-history-previews.js';
8
+ /** Explicit opt-in for the authenticated device-history route. This does not
9
+ * change the server's retention policy or enroll any other integration. */
10
+ export async function createExpoDeviceHistory(options) {
11
+ if (!NativeModules.RobonoHistoryStore?.copyOriginal)
12
+ throw Error('Update this app to open saved device history.');
13
+ const historyUrl = new URL(options.endpoint);
14
+ historyUrl.searchParams.set('service', 'history');
15
+ const mediaUrl = new URL(options.endpoint);
16
+ mediaUrl.searchParams.set('service', 'media');
17
+ const storage = createExpoMessagingStorage({ ...options, url: mediaUrl.href });
18
+ const device = createExpoMessagingDevice(createExpoMessagingAudioSession());
19
+ const store = await createExpoDurableHistoryStore(options.endpoint, options.userId, options.namespace);
20
+ const media = await createExpoDurableHistoryMedia({ ...options, download: options.download ?? (async (change, signal) => {
21
+ const file = await storage.download(change.message, { signal, onProgress: () => { } });
22
+ return { uri: file.uri, release: () => device.remove(file) };
23
+ }) });
24
+ const sync = new MessagingHistorySync({ store, media, request: options.historyRequest ?? createMessagingTransport({ ...options, url: historyUrl.href }) });
25
+ return new MessagingDeviceHistory({ store, sync, localAccess: options.localAccess, onError: options.onError });
26
+ }
27
+ /** Viewer/forward/export copies use the established bounded private cache. The
28
+ * durable source is never passed to cleanup code or copied through JS base64. */
29
+ export function withExpoDeviceHistoryStorage(storage, client, account) {
30
+ const scope = storageDigest(JSON.stringify([new URL(account.endpoint).href, account.namespace ?? 'default', account.userId]));
31
+ const local = async (message, context) => {
32
+ if (!message.media)
33
+ return null;
34
+ const original = await client.deviceHistoryOriginal(message, context.signal);
35
+ if (!original)
36
+ return null;
37
+ if (!NativeModules.RobonoHistoryStore?.copyOriginal)
38
+ throw Error('Update this app to open saved device history.');
39
+ if (original.byteSize !== message.media.byteSize)
40
+ throw Error('This attachment changed. Refresh the conversation.');
41
+ const directory = await allocateMessagingCache(original.byteSize), name = message.media.fileName.replace(/[^a-zA-Z0-9._-]/g, '_').slice(-90) || 'Attachment';
42
+ const destination = directory + (['__draft__', '.', '..'].includes(name) ? 'Attachment' : name);
43
+ try {
44
+ // copyOriginal checks the account epoch on its serialized native queue.
45
+ // The exact revision is checked after copying and before exposing the URI.
46
+ if (context.signal.aborted)
47
+ throw Error('The history account changed.');
48
+ await NativeModules.RobonoHistoryStore.copyOriginal(await scope, original.sha256, original.byteSize, original.generation, destination);
49
+ if (context.signal.aborted || !await client.deviceHistoryOriginalCurrent(message, original))
50
+ throw Error('The history account changed.');
51
+ // Keep the cache allocator's URI spelling. Android canonicalizes /data/user
52
+ // to /data/data; returning that alias bypasses the cache ownership matcher.
53
+ const { assetId, ...metadata } = message.media;
54
+ context.onProgress(1);
55
+ return { ...metadata, uri: destination };
56
+ }
57
+ catch (error) {
58
+ await removeMessagingCacheUri(destination).catch(() => { });
59
+ throw error;
60
+ }
61
+ };
62
+ return { ...storage,
63
+ download: async (message, context) => await local(message, context) ?? storage.download(message, context),
64
+ stream: async (message, context) => await local(message, context) ?? storage.stream?.(message, context) ?? null,
65
+ // Let the standard preview generator handle a local image/video. Returning
66
+ // a full image as a dedicated thumbnail would misreport its dimensions/size.
67
+ thumbnail: async (message, context) => {
68
+ const original = await client.deviceHistoryOriginal(message, context.signal);
69
+ if (!original)
70
+ return storage.thumbnail?.(message, context) ?? null;
71
+ let preview = await readExpoHistoryPreview(await scope, original.sha256);
72
+ if (!preview && ['image', 'video'].includes(message.kind)) {
73
+ const copy = await local(message, context);
74
+ if (copy)
75
+ try {
76
+ await saveExpoHistoryPreview(await scope, original.sha256, original.generation, message.kind, copy.uri, context.signal);
77
+ preview = await readExpoHistoryPreview(await scope, original.sha256);
78
+ }
79
+ finally {
80
+ await removeMessagingCacheUri(copy.uri).catch(() => { });
81
+ }
82
+ }
83
+ if (context.signal.aborted || !await client.deviceHistoryOriginalCurrent(message, original))
84
+ throw Error('The history account changed.');
85
+ return preview;
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,26 @@
1
+ import type { MessagingDurableHistoryStore, MessagingDurableMedia, DurableHistoryChange } from '@robono/messaging';
2
+ /** Separate private SQLite database per endpoint, tenant and authenticated user.
3
+ * A native rebuild is required. Missing durable support must never silently
4
+ * fall back to an expiring cache and acknowledge delivery. */
5
+ export declare function createExpoDurableHistoryStore(endpoint: string, userId: string, namespace?: string): Promise<MessagingDurableHistoryStore>;
6
+ /** Bounded original-file reads for backup/export; never route private bytes
7
+ * through a network URL or depend on Expo access to Android no_backup files. */
8
+ export declare function readExpoDurableHistoryOriginal(options: {
9
+ endpoint: string;
10
+ userId: string;
11
+ namespace?: string;
12
+ sha256: string;
13
+ offset: number;
14
+ length: number;
15
+ }): Promise<string>;
16
+ /** Download uses the normal authenticated media adapter. Native copying streams,
17
+ * hashes and syncs the original before the history transaction can acknowledge it. */
18
+ export declare function createExpoDurableHistoryMedia(options: {
19
+ endpoint: string;
20
+ userId: string;
21
+ namespace?: string;
22
+ download: (change: DurableHistoryChange, signal: AbortSignal) => Promise<{
23
+ uri: string;
24
+ release(): Promise<void>;
25
+ }>;
26
+ }): Promise<MessagingDurableMedia>;