@robono/messaging-react-native 0.24.0 → 0.25.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +75 -1
  3. package/RobonoMessagingRuntime.podspec +2 -0
  4. package/SBOM.spdx.json +1829 -557
  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-device-history.d.ts +24 -0
  48. package/dist/expo-device-history.js +88 -0
  49. package/dist/expo-durable-history.d.ts +26 -0
  50. package/dist/expo-durable-history.js +56 -0
  51. package/dist/expo-history-backup.d.ts +3 -0
  52. package/dist/expo-history-backup.js +79 -0
  53. package/dist/expo-history-maintenance.d.ts +4 -0
  54. package/dist/expo-history-maintenance.js +23 -0
  55. package/dist/expo-history-previews.d.ts +5 -0
  56. package/dist/expo-history-previews.js +57 -0
  57. package/dist/expo-history.d.ts +1 -1
  58. package/dist/expo-history.js +2 -2
  59. package/dist/expo-media.d.ts +2 -0
  60. package/dist/expo-media.js +15 -21
  61. package/dist/expo-messenger.d.ts +8 -0
  62. package/dist/expo-messenger.js +18 -7
  63. package/dist/expo-notifications.d.ts +17 -1
  64. package/dist/expo-notifications.js +36 -16
  65. package/dist/expo-outbox.d.ts +2 -0
  66. package/dist/expo-outbox.js +1 -1
  67. package/dist/expo-oversight.d.ts +15 -0
  68. package/dist/expo-oversight.js +15 -0
  69. package/dist/expo-reviews.d.ts +4 -1
  70. package/dist/expo-reviews.js +122 -17
  71. package/dist/expo-screen.js +5 -4
  72. package/dist/expo-thumbnails.d.ts +2 -2
  73. package/dist/expo-thumbnails.js +48 -5
  74. package/dist/expo.d.ts +10 -0
  75. package/dist/expo.js +8 -0
  76. package/dist/header-calls.js +1 -1
  77. package/dist/inbox-search.d.ts +1 -1
  78. package/dist/inbox-search.js +7 -3
  79. package/dist/inbox.d.ts +1 -0
  80. package/dist/inbox.js +5 -5
  81. package/dist/index.d.ts +8 -3
  82. package/dist/index.js +138 -63
  83. package/dist/linked-apps.d.ts +45 -0
  84. package/dist/linked-apps.js +40 -0
  85. package/dist/loading-messages.d.ts +1 -1
  86. package/dist/loading-messages.js +1 -1
  87. package/dist/media-controller.d.ts +2 -0
  88. package/dist/native-history-authorization.d.ts +4 -0
  89. package/dist/native-history-authorization.js +69 -0
  90. package/dist/native-history-backup.d.ts +16 -0
  91. package/dist/native-history-backup.js +144 -0
  92. package/dist/native-history.d.ts +14 -0
  93. package/dist/native-history.js +186 -0
  94. package/dist/native-outbox.d.ts +2 -0
  95. package/dist/oversight-session.d.ts +4 -0
  96. package/dist/oversight-session.js +14 -0
  97. package/dist/preview-layout.d.ts +12 -0
  98. package/dist/preview-layout.js +102 -0
  99. package/dist/recent-media.js +2 -1
  100. package/dist/reviews.d.ts +8 -4
  101. package/dist/reviews.js +53 -26
  102. package/dist/scheduled.js +2 -2
  103. package/dist/search.js +18 -8
  104. package/ios/RobonoBackupCloudKit.m +96 -0
  105. package/ios/RobonoHistoryStore.m +170 -0
  106. package/package.json +22 -4
  107. package/plugin/backup-expiration.cjs +23 -0
  108. package/plugin/prepare-native.cjs +12 -0
@@ -4,4 +4,7 @@ android {
4
4
  compileSdkVersion rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
5
5
  defaultConfig { minSdkVersion 24 }
6
6
  }
7
- dependencies { implementation 'com.facebook.react:react-android' }
7
+ dependencies {
8
+ implementation 'com.facebook.react:react-android'
9
+ implementation 'com.google.android.gms:play-services-auth:21.5.0'
10
+ }
@@ -0,0 +1,76 @@
1
+ package com.robono.messaging;
2
+
3
+ import android.app.Activity;
4
+ import android.content.Intent;
5
+ import com.facebook.react.bridge.*;
6
+ import com.facebook.react.common.LifecycleState;
7
+ import com.google.android.gms.auth.api.identity.*;
8
+ import com.google.android.gms.common.api.Scope;
9
+ import com.google.android.gms.common.api.ApiException;
10
+ import java.util.Collections;
11
+ import java.util.HashMap;
12
+ import java.util.Map;
13
+
14
+ /** User-owned Drive app-data authorization. No refresh token or app credentials. */
15
+ public final class RobonoBackupGoogle extends ReactContextBaseJavaModule {
16
+ private static final String SCOPE="https://www.googleapis.com/auth/drive.appdata";
17
+ private final Map<String,Pending> pending=new HashMap<>();
18
+ private final Map<Integer,String> resolutions=new HashMap<>();
19
+ private int nextCode=56000;
20
+ private final BaseActivityEventListener listener=new BaseActivityEventListener(){
21
+ @Override public void onActivityResult(Activity activity,int code,int result,Intent data){
22
+ String id=resolutions.remove(code);Pending request=id==null?null:pending.get(id);
23
+ if(request==null)return;
24
+ if(data==null){finish(id,null,result==Activity.RESULT_CANCELED?"cancelled":"connection");return;}
25
+ try{complete(id,Identity.getAuthorizationClient(activity).getAuthorizationResultFromIntent(data));}
26
+ catch(Exception e){fail(id,e);}
27
+ }
28
+ };
29
+ private static final class Pending{final Promise promise;final boolean interactive;Pending(Promise p,boolean i){promise=p;interactive=i;}}
30
+ public RobonoBackupGoogle(ReactApplicationContext context){super(context);context.addActivityEventListener(listener);}
31
+ @Override public String getName(){return "RobonoBackupGoogle";}
32
+ private void finish(String id,WritableMap value,String error){
33
+ Pending p=pending.remove(id);resolutions.values().removeIf(valueId->valueId.equals(id));
34
+ if(p==null)return;if(error==null)p.promise.resolve(value);else p.promise.reject(error,"Google backup authorization could not finish.");
35
+ }
36
+ private void fail(String id,Exception error){
37
+ int status=error instanceof ApiException?((ApiException)error).getStatusCode():-1;
38
+ Pending p=pending.remove(id);resolutions.values().removeIf(valueId->valueId.equals(id));if(p==null)return;
39
+ WritableMap diagnostic=Arguments.createMap();diagnostic.putInt("googleStatus",status);
40
+ String code=status==16||status==12501?"cancelled":status==10?"unavailable":"connection";
41
+ p.promise.reject(code,"Google backup authorization could not finish.",diagnostic);
42
+ }
43
+ private void complete(String id,AuthorizationResult result){
44
+ Pending p=pending.get(id);if(p==null)return;
45
+ if(result.hasResolution()){
46
+ if(!p.interactive){finish(id,null,null);return;}
47
+ Activity activity=getReactApplicationContext().getCurrentActivity();
48
+ if(activity==null||getReactApplicationContext().getLifecycleState()!=LifecycleState.RESUMED||!resolutions.isEmpty()||nextCode>65000){finish(id,null,"connection");return;}
49
+ int code=nextCode++;resolutions.put(code,id);
50
+ try{activity.startIntentSenderForResult(result.getPendingIntent().getIntentSender(),code,null,0,0,0);}
51
+ catch(Exception e){finish(id,null,"connection");}return;
52
+ }
53
+ String token=result.getAccessToken();
54
+ if(token==null||token.isEmpty()||!result.getGrantedScopes().contains(SCOPE)){finish(id,null,"connection");return;}
55
+ WritableMap value=Arguments.createMap();value.putString("accessToken",token);finish(id,value,null);
56
+ }
57
+ @ReactMethod public void authorize(String id,boolean interactive,Promise promise){getReactApplicationContext().runOnUiQueueThread(()->{
58
+ if(id==null||!id.matches("[a-zA-Z0-9_-]{1,100}")||pending.containsKey(id)){promise.reject("connection","Invalid authorization request.");return;}
59
+ if(interactive&&getReactApplicationContext().getLifecycleState()!=LifecycleState.RESUMED){promise.reject("connection","Open the app to connect Google backup.");return;}
60
+ pending.put(id,new Pending(promise,interactive));
61
+ AuthorizationRequest.Builder builder=AuthorizationRequest.builder().setRequestedScopes(Collections.singletonList(new Scope(SCOPE)));
62
+ // A deliberate tap on Google Account must offer the person's accounts again.
63
+ // Silent background checks keep Google's default and never open a chooser.
64
+ if(interactive)builder.setPrompt(AuthorizationRequest.Prompt.SELECT_ACCOUNT);
65
+ AuthorizationRequest request=builder.build();
66
+ Identity.getAuthorizationClient(getReactApplicationContext()).authorize(request)
67
+ .addOnSuccessListener(result->complete(id,result)).addOnFailureListener(error->fail(id,error));
68
+ });}
69
+ @ReactMethod public void cancel(String id){getReactApplicationContext().runOnUiQueueThread(()->finish(id,null,"cancelled"));}
70
+ @ReactMethod public void invalidateToken(String token,Promise promise){
71
+ if(token==null||token.isEmpty()||token.length()>16384){promise.reject("connection","Invalid authorization token.");return;}
72
+ Identity.getAuthorizationClient(getReactApplicationContext()).clearToken(ClearTokenRequest.builder().setToken(token).build())
73
+ .addOnSuccessListener(result->promise.resolve(null)).addOnFailureListener(error->promise.reject("connection","Google backup authorization could not refresh."));
74
+ }
75
+ @Override public void invalidate(){getReactApplicationContext().removeActivityEventListener(listener);getReactApplicationContext().runOnUiQueueThread(()->{for(String id:new java.util.ArrayList<>(pending.keySet()))finish(id,null,"cancelled");});super.invalidate();}
76
+ }
@@ -0,0 +1,173 @@
1
+ package com.robono.messaging;
2
+ import com.facebook.react.bridge.*;
3
+ import android.database.Cursor;
4
+ import android.database.sqlite.SQLiteDatabase;
5
+ import android.database.sqlite.SQLiteStatement;
6
+ import java.io.File;
7
+ import java.io.FileInputStream;
8
+ import java.io.FileOutputStream;
9
+ import java.io.FileDescriptor;
10
+ import java.io.RandomAccessFile;
11
+ import android.util.Base64;
12
+ import java.security.MessageDigest;
13
+ import android.net.Uri;
14
+ import android.system.Os;
15
+ import android.system.OsConstants;
16
+ import java.util.concurrent.ExecutorService;
17
+ import java.util.concurrent.Executors;
18
+ import org.json.*;
19
+
20
+ /** Private per-account SQLite with committed writes before delivery acknowledgements. */
21
+ public final class RobonoHistoryStore extends ReactContextBaseJavaModule {
22
+ private final ExecutorService worker=Executors.newSingleThreadExecutor();
23
+ public RobonoHistoryStore(ReactApplicationContext context){super(context);}
24
+ @Override public String getName(){return "RobonoHistoryStore";}
25
+ @Override public void invalidate(){worker.shutdown();super.invalidate();}
26
+ @ReactMethod public void verifyOriginal(String scope,String hash,double expectedBytes,Promise promise){
27
+ worker.execute(()->{try{
28
+ if(!scope.matches("[a-f0-9]{64}")||!hash.matches("[a-f0-9]{64}")||expectedBytes<1||expectedBytes>104857600||Math.floor(expectedBytes)!=expectedBytes)throw new IllegalArgumentException();
29
+ File file=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media/"+hash);
30
+ if(file.length()!=(long)expectedBytes){promise.resolve(false);return;}
31
+ MessageDigest digest=MessageDigest.getInstance("SHA-256");long total=0;
32
+ try(FileInputStream input=new FileInputStream(file)){byte[] buffer=new byte[65536];int count;while((count=input.read(buffer))!=-1){total+=count;if(total>(long)expectedBytes){promise.resolve(false);return;}digest.update(buffer,0,count);}}
33
+ StringBuilder actual=new StringBuilder(64);for(byte value:digest.digest())actual.append(String.format(java.util.Locale.ROOT,"%02x",value&255));
34
+ promise.resolve(total==(long)expectedBytes&&hash.equals(actual.toString()));
35
+ }catch(Exception error){promise.resolve(false);}});
36
+ }
37
+ @ReactMethod public void readOriginal(String scope,String hash,double offset,double length,Promise promise){
38
+ worker.execute(()->{try{
39
+ if(!scope.matches("[a-f0-9]{64}")||!hash.matches("[a-f0-9]{64}")||offset<0||offset>104857600||Math.floor(offset)!=offset||length<1||length>1048576||Math.floor(length)!=length)throw new IllegalArgumentException();
40
+ File file=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media/"+hash);
41
+ try(RandomAccessFile input=new RandomAccessFile(file,"r")){
42
+ if(offset>input.length())throw new IllegalArgumentException();input.seek((long)offset);
43
+ byte[] bytes=new byte[(int)Math.min((long)length,input.length()-(long)offset)];input.readFully(bytes);promise.resolve(Base64.encodeToString(bytes,Base64.NO_WRAP));
44
+ }
45
+ }catch(Exception error){promise.reject("history_original_unavailable","The saved original is unavailable.");}});
46
+ }
47
+ @ReactMethod public void clearOriginals(String scope,Promise promise){
48
+ worker.execute(()->{try{
49
+ if(!scope.matches("[a-f0-9]{64}"))throw new IllegalArgumentException();
50
+ File root=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media");File[] files=root.listFiles();
51
+ if(files!=null)for(File file:files)if(!file.delete())throw new IllegalStateException();
52
+ promise.resolve(null);
53
+ }catch(Exception error){promise.reject("history_cleanup","Saved attachments could not be cleared.");}});
54
+ }
55
+ /** Read-only private original -> owned viewer cache; never delete the source. */
56
+ @ReactMethod public void copyOriginal(String scope,String hash,double expectedBytes,double epoch,String destination,Promise promise){
57
+ worker.execute(()->{File target=null;boolean created=false;try{
58
+ if(!scope.matches("[a-f0-9]{64}")||!hash.matches("[a-f0-9]{64}")||expectedBytes<1||expectedBytes>104857600||Math.floor(expectedBytes)!=expectedBytes||epoch<0||Math.floor(epoch)!=epoch)throw new IllegalArgumentException();
59
+ File database=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+".sqlite");
60
+ try(SQLiteDatabase db=SQLiteDatabase.openDatabase(database.getPath(),null,SQLiteDatabase.OPEN_READONLY);Cursor current=db.rawQuery("SELECT epoch FROM history_control WHERE id=1",null)){
61
+ if(!current.moveToFirst()||current.getDouble(0)!=epoch)throw new IllegalStateException("History account changed");
62
+ }
63
+ Uri uri=Uri.parse(destination);if(!"file".equals(uri.getScheme()))throw new IllegalArgumentException();
64
+ target=new File(uri.getPath()).getCanonicalFile();
65
+ if(!target.getPath().startsWith(new File(getReactApplicationContext().getCacheDir(),"robono-messaging").getCanonicalPath()+File.separator)||!target.createNewFile())throw new IllegalArgumentException();created=true;
66
+ File original=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media/"+hash);
67
+ MessageDigest digest=MessageDigest.getInstance("SHA-256");long total=0;
68
+ try(FileInputStream input=new FileInputStream(original);FileOutputStream output=new FileOutputStream(target)){
69
+ byte[] buffer=new byte[65536];int count;while((count=input.read(buffer))!=-1){total+=count;if(total>(long)expectedBytes)throw new IllegalArgumentException();digest.update(buffer,0,count);output.write(buffer,0,count);}
70
+ }
71
+ StringBuilder actual=new StringBuilder(64);for(byte value:digest.digest())actual.append(String.format(java.util.Locale.ROOT,"%02x",value&255));
72
+ if(total!=(long)expectedBytes||!hash.equals(actual.toString()))throw new IllegalArgumentException();
73
+ promise.resolve(Uri.fromFile(target).toString());
74
+ }catch(Exception error){if(created&&target!=null)target.delete();promise.reject("history_original_unavailable","The saved original could not be opened.");}});
75
+ }
76
+ @ReactMethod public void saveOriginal(String scope,String source,String expectedHash,double expectedBytes,Promise promise){
77
+ saveOriginalWork(scope,source,expectedHash,expectedBytes,null,promise);
78
+ }
79
+ @ReactMethod public void saveOriginalGuarded(String scope,String source,String expectedHash,double expectedBytes,double epoch,Promise promise){
80
+ saveOriginalWork(scope,source,expectedHash,expectedBytes,epoch,promise);
81
+ }
82
+ private void saveOriginalWork(String scope,String source,String expectedHash,double expectedBytes,Double epoch,Promise promise){
83
+ worker.execute(()->{
84
+ File temporary=null;
85
+ try{
86
+ if(!scope.matches("[a-f0-9]{64}")||!expectedHash.matches("[a-f0-9]{64}")||expectedBytes<1||expectedBytes>104857600||Math.floor(expectedBytes)!=expectedBytes)throw new IllegalArgumentException();
87
+ if(epoch!=null){
88
+ if(epoch<0||Math.floor(epoch)!=epoch)throw new IllegalArgumentException();
89
+ File database=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+".sqlite");
90
+ try(SQLiteDatabase db=SQLiteDatabase.openDatabase(database.getPath(),null,SQLiteDatabase.OPEN_READONLY);Cursor current=db.rawQuery("SELECT epoch FROM history_control WHERE id=1",null)){
91
+ if(!current.moveToFirst()||current.getDouble(0)!=epoch)throw new IllegalStateException("History account changed");
92
+ }
93
+ }
94
+ Uri uri=Uri.parse(source);if(!"file".equals(uri.getScheme()))throw new IllegalArgumentException();File original=new File(uri.getPath()).getCanonicalFile();
95
+ if(!original.getPath().startsWith(getReactApplicationContext().getDataDir().getCanonicalPath()+File.separator))throw new IllegalArgumentException();
96
+ File directory=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media");if(!directory.isDirectory()&&!directory.mkdirs())throw new IllegalStateException();
97
+ temporary=File.createTempFile("original-",".tmp",directory);MessageDigest digest=MessageDigest.getInstance("SHA-256");long total=0;
98
+ try(FileInputStream input=new FileInputStream(original);FileOutputStream output=new FileOutputStream(temporary)){
99
+ byte[] buffer=new byte[65536];int count;while((count=input.read(buffer))!=-1){total+=count;if(total>(long)expectedBytes)throw new IllegalArgumentException();digest.update(buffer,0,count);output.write(buffer,0,count);}output.getFD().sync();
100
+ }
101
+ StringBuilder actual=new StringBuilder(64);for(byte value:digest.digest())actual.append(String.format(java.util.Locale.ROOT,"%02x",value&255));
102
+ if(total!=(long)expectedBytes||!expectedHash.equals(actual.toString()))throw new IllegalArgumentException();
103
+ File target=new File(directory,expectedHash);Os.rename(temporary.getPath(),target.getPath());temporary=null;
104
+ FileDescriptor dir=Os.open(directory.getPath(),OsConstants.O_RDONLY,0);try{Os.fsync(dir);}finally{Os.close(dir);}
105
+ WritableMap result=Arguments.createMap();result.putString("reference",Uri.fromFile(target).toString());result.putString("sha256",actual.toString());result.putDouble("byteSize",total);promise.resolve(result);
106
+ }catch(Exception error){if(temporary!=null)temporary.delete();promise.reject("history_original","The original attachment could not be verified and saved. Delivery was not acknowledged.");}
107
+ });
108
+ }
109
+ @ReactMethod public void execute(String scope,String raw,Promise promise){
110
+ executeWork(scope,raw,false,false,promise);
111
+ }
112
+ @ReactMethod public void executeAndClearOriginals(String scope,String raw,Promise promise){
113
+ executeWork(scope,raw,true,false,promise);
114
+ }
115
+ @ReactMethod public void executeAndPruneOriginals(String scope,String raw,Promise promise){
116
+ executeWork(scope,raw,false,true,promise);
117
+ }
118
+ private void executeWork(String scope,String raw,boolean clearOriginals,boolean pruneOriginals,Promise promise){
119
+ worker.execute(()->{
120
+ SQLiteDatabase db=null;
121
+ try{
122
+ if(!scope.matches("[a-f0-9]{64}")||raw.length()>4000000)throw new IllegalArgumentException();
123
+ JSONArray commands=new JSONArray(raw);if(commands.length()>250)throw new IllegalArgumentException();
124
+ File directory=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory");
125
+ if(!directory.isDirectory()&&!directory.mkdirs())throw new IllegalStateException();
126
+ db=SQLiteDatabase.openOrCreateDatabase(new File(directory,scope+".sqlite"),null);
127
+ db.enableWriteAheadLogging();db.execSQL("PRAGMA synchronous=FULL");
128
+ // secure_delete returns a row on Android SQLite; execSQL rejects it.
129
+ try(Cursor pragma=db.rawQuery("PRAGMA secure_delete=ON",null)){if(!pragma.moveToFirst()||pragma.getInt(0)!=1)throw new IllegalStateException("secure_delete");}
130
+ db.execSQL("CREATE TABLE IF NOT EXISTS records(conversation TEXT NOT NULL,id TEXT NOT NULL,sort_key TEXT NOT NULL,revision INTEGER NOT NULL,deleted INTEGER NOT NULL,record TEXT NOT NULL,receipt TEXT,ack_pending INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(conversation,id))");
131
+ db.execSQL("CREATE INDEX IF NOT EXISTS history_order ON records(conversation,sort_key)");
132
+ db.execSQL("CREATE INDEX IF NOT EXISTS history_ack ON records(ack_pending)");
133
+ db.execSQL("CREATE TABLE IF NOT EXISTS cursors(conversation TEXT PRIMARY KEY,cursor TEXT NOT NULL)");
134
+ db.beginTransaction();WritableArray results=Arguments.createArray();
135
+ for(int i=0;i<commands.length();i++){
136
+ JSONObject command=commands.getJSONObject(i);String sql=command.getString("sql");JSONArray args=command.getJSONArray("args");
137
+ if(sql.length()>8192||args.length()>1000)throw new IllegalArgumentException();
138
+ WritableArray rows=Arguments.createArray();
139
+ if(sql.trim().toUpperCase(java.util.Locale.ROOT).startsWith("SELECT ")){
140
+ String[] values=new String[args.length()];for(int j=0;j<args.length();j++)values[j]=args.isNull(j)?null:args.get(j).toString();
141
+ try(Cursor cursor=db.rawQuery(sql,values)){
142
+ while(cursor.moveToNext()){
143
+ WritableMap row=Arguments.createMap();for(int col=0;col<cursor.getColumnCount();col++){
144
+ String name=cursor.getColumnName(col);switch(cursor.getType(col)){
145
+ case Cursor.FIELD_TYPE_NULL:row.putNull(name);break;
146
+ case Cursor.FIELD_TYPE_INTEGER:case Cursor.FIELD_TYPE_FLOAT:row.putDouble(name,cursor.getDouble(col));break;
147
+ default:row.putString(name,cursor.getString(col));
148
+ }
149
+ }rows.pushMap(row);if(rows.size()>1000)throw new IllegalArgumentException();
150
+ }
151
+ }
152
+ }else try(SQLiteStatement statement=db.compileStatement(sql)){
153
+ for(int j=0;j<args.length();j++){Object value=args.get(j);if(value==JSONObject.NULL)statement.bindNull(j+1);else if(value instanceof Number)statement.bindDouble(j+1,((Number)value).doubleValue());else if(value instanceof String)statement.bindString(j+1,(String)value);else throw new IllegalArgumentException();}
154
+ statement.execute();
155
+ }
156
+ results.pushArray(rows);
157
+ }
158
+ java.util.Set<String> keep=new java.util.HashSet<>();
159
+ if(pruneOriginals)try(Cursor records=db.rawQuery("SELECT record FROM records UNION ALL SELECT record FROM backup_records",null)){
160
+ while(records.moveToNext()){JSONObject record=new JSONObject(records.getString(0));JSONObject original=record.optJSONObject("original");if(original!=null){String hash=original.getString("sha256");if(!hash.matches("[a-f0-9]{64}"))throw new IllegalStateException("Invalid original reference");keep.add(hash);}}
161
+ }
162
+ db.setTransactionSuccessful();db.endTransaction();db.close();db=null;
163
+ // One queue operation prevents a new generation saving between SQL clear
164
+ // and file removal. Old queued promotions fail their generation check.
165
+ if(clearOriginals){File media=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media");File[] files=media.listFiles();if(files!=null)for(File file:files)if(!file.delete())throw new IllegalStateException("History original cleanup failed");}
166
+ // Conversation clearing advances the epoch in the same transaction. No
167
+ // new-generation save can interleave on this queue; old saves are rejected.
168
+ if(pruneOriginals){File media=new File(getReactApplicationContext().getNoBackupFilesDir(),"RobonoHistory/"+scope+"/media");File[] files=media.listFiles();if(files!=null)for(File file:files){String name=file.getName();if((name.matches("[a-f0-9]{64}")&&!keep.contains(name)||name.matches("[a-fA-F0-9-]{36}\\.tmp"))&&!file.delete())throw new IllegalStateException("History original cleanup failed");}}
169
+ promise.resolve(results);
170
+ }catch(Exception error){if(db!=null){if(db.inTransaction())db.endTransaction();db.close();}promise.reject("history_storage","History could not be saved; check available device space. Delivery was not acknowledged.");}
171
+ });
172
+ }
173
+ }
@@ -6,6 +6,6 @@ import com.facebook.react.uimanager.ViewManager;
6
6
  import java.util.Collections;
7
7
  import java.util.List;
8
8
  public final class RobonoMessagingPackage implements ReactPackage {
9
- @Override public List<NativeModule> createNativeModules(ReactApplicationContext context){return Collections.singletonList(new RobonoBackupCrypto(context));}
9
+ @Override public List<NativeModule> createNativeModules(ReactApplicationContext context){return java.util.Arrays.asList(new RobonoBackupCrypto(context),new RobonoHistoryStore(context),new RobonoBackupGoogle(context));}
10
10
  @Override public List<ViewManager> createViewManagers(ReactApplicationContext context){return Collections.emptyList();}
11
11
  }
package/app.plugin.cjs CHANGED
@@ -1,5 +1,14 @@
1
1
  const {withDangerousMod,withInfoPlist,withEntitlementsPlist,createRunOncePlugin} = require('expo/config-plugins');
2
2
  module.exports=createRunOncePlugin((config,options={})=>{
3
+ if(options.backupICloudContainer){
4
+ const container=options.backupICloudContainer;
5
+ if(typeof container!=='string'||!/^iCloud\.[A-Za-z0-9.-]{1,180}$/.test(container))throw Error('backupICloudContainer must be your provisioned iCloud container identifier.');
6
+ config=withEntitlementsPlist(config,value=>{
7
+ value.modResults['com.apple.developer.icloud-container-identifiers']=[...new Set([...(value.modResults['com.apple.developer.icloud-container-identifiers']??[]),container])];
8
+ value.modResults['com.apple.developer.icloud-services']=[...new Set([...(value.modResults['com.apple.developer.icloud-services']??[]),'CloudKit'])];
9
+ return value;
10
+ });
11
+ }
3
12
  if(options.backupPasskeyRpId){
4
13
  const rp=options.backupPasskeyRpId;
5
14
  if(typeof rp!=='string'||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(rp)||rp.length>253)throw Error('backupPasskeyRpId must be a domain name.');
@@ -8,10 +17,14 @@ module.exports=createRunOncePlugin((config,options={})=>{
8
17
 
9
18
  config=withInfoPlist(config,value=>{
10
19
  value.modResults.UIBackgroundModes=[...new Set([...(value.modResults.UIBackgroundModes??[]),'remote-notification'])];
20
+ if(options.backupBackgroundTasks){
21
+ value.modResults.UIBackgroundModes=[...new Set([...value.modResults.UIBackgroundModes,'processing'])];
22
+ value.modResults.BGTaskSchedulerPermittedIdentifiers=[...new Set([...(value.modResults.BGTaskSchedulerPermittedIdentifiers??[]),'com.expo.modules.backgroundtask.processing'])];
23
+ }
11
24
  return value;
12
25
  });
13
26
  return withDangerousMod(config,['ios',async value=>{
14
- require('./plugin/preserve-call-audio.cjs').install(value.modRequest.projectRoot);
27
+ require('./plugin/prepare-native.cjs').prepareNativeDependencies(value.modRequest.projectRoot,options);
15
28
  return value;
16
29
  }]);
17
30
  },'@robono/messaging-react-native',require('./package.json').version);
@@ -0,0 +1,13 @@
1
+ // Shared Messenger encrypted backups, stored in each user's private database.
2
+ // Import into a new backup container, then deploy its schema to Production.
3
+ // For an existing container, merge with its exported schema before importing.
4
+ // No public-database permissions are granted.
5
+ DEFINE SCHEMA
6
+
7
+ RECORD TYPE RobonoChatBackup (
8
+ scope STRING QUERYABLE,
9
+ snapshot STRING,
10
+ part STRING,
11
+ length INT64,
12
+ bytes ASSET
13
+ );
@@ -0,0 +1,51 @@
1
+ import { type MessagingLinkedApps } from './linked-apps.js';
2
+ import React from 'react';
3
+ import type { MessagingInboxClient } from '@robono/messaging';
4
+ import type { MessagingAccount } from './account.js';
5
+ export declare const messagingAccountPages: readonly ["language", "stats", "blocked", "linkedApps", "transfer", "about"];
6
+ export type MessagingAccountPage = typeof messagingAccountPages[number];
7
+ export declare const messagingAccountPageLabels: Record<MessagingAccountPage, string>;
8
+ export declare const messagingLanguages: readonly [readonly ["en", "English"], readonly ["es", "Español"], readonly ["fr", "Français"], readonly ["de", "Deutsch"], readonly ["it", "Italiano"], readonly ["pt", "Português"], readonly ["nl", "Nederlands"], readonly ["pl", "Polski"], readonly ["ru", "Русский"], readonly ["uk", "Українська"], readonly ["tr", "Türkçe"], readonly ["vi", "Tiếng Việt"], readonly ["id", "Bahasa Indonesia"], readonly ["ja", "日本語"], readonly ["ko", "한국어"], readonly ["zh", "简体中文"], readonly ["zh-Hant", "繁體中文"], readonly ["hi", "हिन्दी"], readonly ["th", "ไทย"], readonly ["ar", "العربية"], readonly ["he", "עברית"], readonly ["sv", "Svenska"], readonly ["ms", "Bahasa Melayu"]];
9
+ /** Authenticated host data; presentation and recovery stay in the shared screens. */
10
+ export interface MessagingAccountPages {
11
+ language?: {
12
+ value: string;
13
+ onChange: (language: string) => Promise<void>;
14
+ choices?: readonly (readonly [string, string])[];
15
+ };
16
+ stats?: {
17
+ load: (signal: AbortSignal) => Promise<{
18
+ description: string;
19
+ items: {
20
+ label: string;
21
+ value: string | number;
22
+ }[];
23
+ }>;
24
+ };
25
+ blocked?: {
26
+ list: (signal: AbortSignal, cursor?: string) => Promise<{
27
+ contacts: {
28
+ id: string;
29
+ name: string;
30
+ networkName?: string;
31
+ }[];
32
+ nextCursor?: string;
33
+ }>;
34
+ unblock: (id: string) => Promise<void>;
35
+ };
36
+ /** Navigation to the host's authorized network directory, never a saved website permission. */
37
+ linkedApps?: MessagingLinkedApps;
38
+ onLinkedApps?: () => void;
39
+ onPhoneTransfer?: () => void;
40
+ about?: {
41
+ description: string;
42
+ version?: string;
43
+ };
44
+ }
45
+ export declare function MessagingAccountPageScreen({ page, account, inbox, companyName, onClose }: {
46
+ page: MessagingAccountPage;
47
+ account?: MessagingAccount;
48
+ inbox?: MessagingInboxClient;
49
+ companyName: string;
50
+ onClose: () => void;
51
+ }): React.JSX.Element;
@@ -0,0 +1,65 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useMessagingAppearance } from './appearance-context.js';
3
+ import { MessagingLinkedAppsScreen } from './linked-apps.js';
4
+ import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react';
5
+ import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native';
6
+ import { Text } from './typography.js';
7
+ import { MessagingPopup, useMessagingPopupColors } from './popup.js';
8
+ import { useRobonoLocale } from './localization.js';
9
+ import { MessagingBackupPage } from './backup.js';
10
+ export const messagingAccountPages = ['language', 'stats', 'blocked', 'linkedApps', 'transfer', 'about'];
11
+ export const messagingAccountPageLabels = { language: 'Language', stats: 'Stats', blocked: 'Blocked', linkedApps: 'Linked Apps', transfer: 'Phone Transfer', about: 'About' };
12
+ export const messagingLanguages = [['en', 'English'], ['es', 'Español'], ['fr', 'Français'], ['de', 'Deutsch'], ['it', 'Italiano'], ['pt', 'Português'], ['nl', 'Nederlands'], ['pl', 'Polski'], ['ru', 'Русский'], ['uk', 'Українська'], ['tr', 'Türkçe'], ['vi', 'Tiếng Việt'], ['id', 'Bahasa Indonesia'], ['ja', '日本語'], ['ko', '한국어'], ['zh', '简体中文'], ['zh-Hant', '繁體中文'], ['hi', 'हिन्दी'], ['th', 'ไทย'], ['ar', 'العربية'], ['he', 'עברית'], ['sv', 'Svenska'], ['ms', 'Bahasa Melayu']];
13
+ function InboxStats({ inbox }) {
14
+ const state = useSyncExternalStore(inbox.subscribe, inbox.getSnapshot, inbox.getSnapshot), c = useMessagingPopupColors(undefined, 'stats'), { text, number } = useRobonoLocale();
15
+ const features = useMessagingAppearance()?.screenFeatures?.stats;
16
+ const chats = state.conversations.filter(row => !row.self), unread = chats.reduce((sum, row) => sum + row.unreadCount, 0);
17
+ return _jsxs(View, { style: { gap: 16 }, children: [_jsx(Text, { style: { color: c.secondary }, children: text(state.hasMore ? 'Activity in the chats currently loaded on this device.' : 'Activity in your chat list.') }), [...(features?.chats !== false ? [[text('Chats'), chats.length]] : []), ...(features?.unread !== false ? [[text('Unread messages'), unread]] : []), ...(features?.groups !== false ? [[text('Groups'), chats.filter(row => row.kind === 'group').length]] : [])].map(([label, value]) => _jsxs(View, { style: { flexDirection: 'row', justifyContent: 'space-between', gap: 16 }, children: [_jsx(Text, { style: { color: c.foreground, fontSize: 17 }, children: label }), _jsx(Text, { style: { color: c.foreground, fontSize: 20, fontWeight: '700' }, children: number(Number(value)) })] }, label))] });
18
+ }
19
+ export function MessagingAccountPageScreen({ page, account, inbox, companyName, onClose }) {
20
+ const screen = page === 'language' ? 'accountLanguage' : page, c = useMessagingPopupColors(undefined, screen), { text, locale, number } = useRobonoLocale();
21
+ const features = useMessagingAppearance()?.screenFeatures;
22
+ const languageEditable = !!account?.language && features?.accountLanguage?.changeLanguage !== false;
23
+ const [busy, setBusy] = useState(null), [error, setError] = useState(''), [attempt, setAttempt] = useState(0), [ready, setReady] = useState(false);
24
+ const [stats, setStats] = useState(null);
25
+ const [contacts, setContacts] = useState([]), [cursor, setCursor] = useState();
26
+ const [language, setLanguage] = useState(account?.language?.value ?? locale), [backupOpen, setBackupOpen] = useState(false);
27
+ const live = useRef(true), request = useRef(null);
28
+ useEffect(() => { live.current = true; return () => { live.current = false; request.current?.abort(); }; }, []);
29
+ useEffect(() => { setLanguage(account?.language?.value ?? locale); }, [account?.language?.value, locale]);
30
+ const run = async (key, action) => { if (busy)
31
+ return; setBusy(key); setError(''); try {
32
+ await action();
33
+ }
34
+ catch {
35
+ if (live.current)
36
+ setError(text('The change could not be completed. Please try again.'));
37
+ }
38
+ finally {
39
+ if (live.current)
40
+ setBusy(null);
41
+ } };
42
+ const load = async (signal, more) => {
43
+ if (page === 'stats' && account?.stats) {
44
+ const result = await account.stats.load(signal);
45
+ if (!signal.aborted)
46
+ setStats(result);
47
+ }
48
+ if (page === 'blocked' && account?.blocked) {
49
+ const result = await account.blocked.list(signal, more);
50
+ if (!signal.aborted) {
51
+ setContacts(previous => more ? [...new Map([...previous, ...result.contacts].map(row => [row.id, row])).values()] : result.contacts);
52
+ setCursor(result.nextCursor);
53
+ }
54
+ }
55
+ };
56
+ useEffect(() => { const controller = new AbortController(); request.current = controller; setReady(false); setError(''); void load(controller.signal).then(() => { if (!controller.signal.aborted)
57
+ setReady(true); }).catch(() => { if (!controller.signal.aborted)
58
+ setError(text('This page could not load. Please try again.')); }); return () => controller.abort(); }, [page, account?.stats, account?.blocked, attempt]);
59
+ const button = (label, key, action, selected = false) => _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: label, "aria-pressed": page === 'language' ? selected : undefined, accessibilityState: { busy: busy === key, selected: page === 'language' ? selected : undefined, disabled: !!busy }, disabled: !!busy, onPress: () => void run(key, action), style: { minHeight: 48, paddingHorizontal: 12, borderRadius: 10, backgroundColor: selected ? c.accent + '22' : c.incoming, justifyContent: 'center' }, children: busy === key ? _jsx(ActivityIndicator, { color: c.accent }) : _jsx(Text, { style: { color: c.foreground, fontSize: 16, fontWeight: selected ? '700' : '400' }, children: label }) });
60
+ if (backupOpen && account?.backup)
61
+ return _jsx(MessagingBackupPage, { client: account.backup, active: true, onClose: () => setBackupOpen(false), render: state => _jsx(MessagingPopup, { title: state.title, description: state.description, form: state.form, headerBack: true, onClose: state.onClose, background: c.background, children: state.content }) });
62
+ return _jsx(MessagingPopup, { screen: screen, title: text(messagingAccountPageLabels[page]), onClose: onClose, closeDisabled: !!busy, background: c.background, contentWidth: 640, children: _jsxs(ScrollView, { contentContainerStyle: { gap: 16, paddingBottom: 16 }, children: [page === 'language' && _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: c.secondary }, children: text(languageEditable ? 'Choose the language for your account.' : 'The language follows your account settings.') }), languageEditable ? (account.language.choices ?? messagingLanguages).map(([code, label]) => _jsx(React.Fragment, { children: button(label, code, async () => { await account.language.onChange(code); if (live.current)
63
+ setLanguage(code); }, language.toLowerCase() === code.toLowerCase()) }, code)) : _jsx(Text, { style: { color: c.foreground, fontSize: 18 }, children: messagingLanguages.find(([code]) => code.toLowerCase() === language.toLowerCase())?.[1] ?? language })] }), page === 'stats' && (account?.stats ? (stats ? _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: c.secondary }, children: stats.description }), stats.items.map((item, index) => _jsxs(View, { style: { flexDirection: 'row', justifyContent: 'space-between', gap: 16 }, children: [_jsx(Text, { style: { color: c.foreground, fontSize: 17, flex: 1 }, children: text(item.label) }), _jsx(Text, { style: { color: c.foreground, fontSize: 20, fontWeight: '700' }, children: typeof item.value === 'number' ? number(item.value) : item.value })] }, index))] }) : _jsx(View, { style: { height: 160, justifyContent: 'center' }, accessibilityState: { busy: !error }, children: !error && _jsx(ActivityIndicator, { color: c.accent }) })) : inbox ? _jsx(InboxStats, { inbox: inbox }) : null), page === 'blocked' && _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: c.secondary }, children: text('Blocked people are not notified.') }), _jsxs(View, { style: { minHeight: 160, gap: 12 }, children: [!ready && !error ? _jsx(ActivityIndicator, { color: c.accent }) : contacts.map(contact => _jsxs(View, { style: { gap: 8, paddingVertical: 8 }, children: [_jsx(Text, { style: { color: c.foreground, fontSize: 18 }, children: contact.name }), contact.networkName && _jsx(Text, { style: { color: c.secondary }, children: contact.networkName }), features?.blocked?.unblock !== false && button(text('Unblock {name}', { name: contact.name }), contact.id, async () => { await account.blocked.unblock(contact.id); if (live.current)
64
+ setContacts(rows => rows.filter(row => row.id !== contact.id)); })] }, contact.id)), ready && !contacts.length && _jsx(Text, { style: { color: c.foreground }, children: text('Blocked contacts will appear here.') })] }), cursor && button(text('Load more'), 'more', async () => { const controller = new AbortController(); request.current = controller; await load(controller.signal, cursor); })] }), page === 'linkedApps' && account?.linkedApps && _jsx(MessagingLinkedAppsScreen, { service: account.linkedApps }), page === 'transfer' && _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: c.foreground, fontSize: 17 }, children: text('Save a protected copy of your chats before changing phones. Sign in on your new phone and restore it with the same backup account and recovery method.') }), account?.backup && features?.transfer?.backup !== false && button(text('Open chat backup'), 'backup', async () => setBackupOpen(true))] }), page === 'about' && _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: c.foreground, fontSize: 24, fontWeight: '700' }, children: companyName }), _jsx(Text, { style: { color: c.foreground, fontSize: 17 }, children: account?.about?.description ?? text('Share messages, voice notes, photos, videos and files with the people and networks you connect to.') }), features?.about?.version !== false && account?.about?.version && _jsx(Text, { style: { color: c.secondary }, children: account.about.version })] }), !!error && _jsxs(View, { style: { gap: 8 }, children: [_jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground }, children: error }), !ready && button(text('Try again'), 'retry', async () => setAttempt(value => value + 1))] })] }) });
65
+ }
package/dist/account.d.ts CHANGED
@@ -1,8 +1,9 @@
1
+ import type { MessagingAccountPages } from './account-pages.js';
1
2
  import { type CallDeviceCheck } from '@robono/calling-react-native';
2
3
  import type { MessagingInboxClient } from '@robono/messaging';
3
4
  import React from 'react';
4
5
  /** Profile and account actions belong to the customer's sign-in system. */
5
- export interface MessagingAccount {
6
+ export interface MessagingAccount extends MessagingAccountPages {
6
7
  backup?: import('@robono/messaging').MessagingBackupClient;
7
8
  deviceCheck?: CallDeviceCheck;
8
9
  renderCallPreview?: (stream: MediaStream) => React.ReactNode;
package/dist/account.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useMessagingAppearance } from './appearance-context.js';
2
3
  import { CallDeviceCheckPanel, callDeviceCheckText } from '@robono/calling-react-native';
3
4
  import { Text } from './typography.js';
4
5
  import { useRobonoLocale } from './localization.js';
@@ -25,11 +26,14 @@ function SelfChatSetting({ inbox }) {
25
26
  } }, trackColor: { true: c.accent } })] }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground }, children: error })] });
26
27
  }
27
28
  export function MessagingAccountScreen({ account, companyName, onClose, inbox }) {
29
+ const features = useMessagingAppearance()?.screenFeatures?.account;
28
30
  const deviceColors = useMessagingPopupColors(undefined, 'deviceCheck');
29
31
  const c = useMessagingPopupColors(undefined, 'account');
30
32
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
31
33
  const [checking, setChecking] = useState(false);
32
- const [backupOpen, setBackupOpen] = useState(false);
34
+ const [requestedBackup, setBackupOpen] = useState(false);
35
+ const backupOpen = requestedBackup && !!account?.backup;
36
+ useEffect(() => { setBackupOpen(false); const backup = account?.backup; return () => backup?.cancel(); }, [account?.backup]);
33
37
  useEffect(() => { const sub = AppState.addEventListener('change', value => { if (value !== 'active')
34
38
  void account?.deviceCheck?.close(); }); return () => { sub.remove(); void account?.deviceCheck?.close(); }; }, [account?.deviceCheck]);
35
39
  const [busy, setBusy] = useState(false), [error, setError] = useState(''), [visible, setVisible] = useState(true), pending = useRef(null);
@@ -60,5 +64,5 @@ export function MessagingAccountScreen({ account, companyName, onClose, inbox })
60
64
  }
61
65
  else
62
66
  onClose();
63
- } }, children: [_jsx(View, { style: { flex: 1, minHeight: 0, display: backupOpen ? 'none' : 'flex' }, accessibilityElementsHidden: backupOpen, importantForAccessibility: backupOpen ? 'no-hide-descendants' : 'auto', children: _jsx(ScrollView, { contentContainerStyle: { gap: 16, paddingBottom: 12 }, children: checking && account?.deviceCheck ? _jsx(CallDeviceCheckPanel, { TextComponent: Text, colors: { foreground: deviceColors.foreground, secondary: deviceColors.secondary, controls: deviceColors.incoming }, accent: deviceColors.accent, check: account.deviceCheck, renderVideo: account.renderCallPreview, labels: Object.fromEntries(Object.entries(callDeviceCheckText).map(([key, value]) => [key, uiText(value)])) }) : _jsxs(_Fragment, { children: [_jsxs(View, { style: { backgroundColor: c.incoming, borderRadius: 16, padding: 16, gap: 14 }, children: [_jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 14 }, children: [account?.avatarUrl ? _jsx(Image, { source: { uri: account.avatarUrl }, style: { width: 56, height: 56, borderRadius: 28 } }) : _jsx(View, { style: { width: 56, height: 56, borderRadius: 28, backgroundColor: c.incoming, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "person-circle-outline", color: c.foreground, size: 36 }) }), _jsxs(View, { style: { flex: 1, gap: 4 }, children: [_jsx(Text, { style: { color: c.foreground, fontSize: 20, fontWeight: '600' }, children: account?.name ?? uiText("Your account") }), _jsx(Text, { style: { color: c.secondary, fontSize: 14 }, children: companyName })] })] }), account?.phone && _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: account.phone }), account?.email && _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: account.email }), account?.onEditProfile && _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Edit profile"), disabled: busy, onPress: () => begin(account.onEditProfile), style: { minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: 10 }, children: [_jsx(MessageIcon, { name: "edit", color: c.foreground, size: 20 }), _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Edit profile") })] })] }), inbox && _jsx(SelfChatSetting, { inbox: inbox }), account?.backup && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText('Chat backup'), onPress: () => setBackupOpen(true), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText('Chat backup') }) }), account?.deviceCheck && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Check call devices"), disabled: busy, onPress: () => setChecking(true), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Check call devices") }) }), account?.onEnableNotifications && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Enable notifications"), disabled: busy, onPress: () => void run(account.onEnableNotifications), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Enable notifications") }) }), account?.onDeleteAccount && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Delete account"), disabled: busy, onPress: () => begin(account.onDeleteAccount), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.danger, fontSize: 16 }, children: uiText("Delete account") }) }), account?.onSignOut && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Sign out"), disabled: busy, onPress: () => begin(account.onSignOut), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Sign out") }) }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground, fontSize: 15 }, children: error })] }) }) }), backupOpen && page ? page.content : null] }) });
67
+ } }, children: [_jsx(View, { style: { flex: 1, minHeight: 0, display: backupOpen ? 'none' : 'flex' }, accessibilityElementsHidden: backupOpen, importantForAccessibility: backupOpen ? 'no-hide-descendants' : 'auto', children: _jsx(ScrollView, { contentContainerStyle: { gap: 16, paddingBottom: 12 }, children: checking && account?.deviceCheck ? _jsx(CallDeviceCheckPanel, { TextComponent: Text, colors: { foreground: deviceColors.foreground, secondary: deviceColors.secondary, controls: deviceColors.incoming }, accent: deviceColors.accent, check: account.deviceCheck, renderVideo: account.renderCallPreview, labels: Object.fromEntries(Object.entries(callDeviceCheckText).map(([key, value]) => [key, uiText(value)])) }) : _jsxs(_Fragment, { children: [_jsxs(View, { style: { backgroundColor: c.incoming, borderRadius: 16, padding: 16, gap: 14 }, children: [_jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 14 }, children: [account?.avatarUrl ? _jsx(Image, { source: { uri: account.avatarUrl }, style: { width: 56, height: 56, borderRadius: 28 } }) : _jsx(View, { style: { width: 56, height: 56, borderRadius: 28, backgroundColor: c.incoming, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "person-circle-outline", color: c.foreground, size: 36 }) }), _jsxs(View, { style: { flex: 1, gap: 4 }, children: [_jsx(Text, { style: { color: c.foreground, fontSize: 20, fontWeight: '600' }, children: account?.name ?? uiText("Your account") }), _jsx(Text, { style: { color: c.secondary, fontSize: 14 }, children: companyName })] })] }), account?.phone && _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: account.phone }), account?.email && _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: account.email }), features?.editProfile !== false && account?.onEditProfile && _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Edit profile"), disabled: busy, onPress: () => begin(account.onEditProfile), style: { minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: 10 }, children: [_jsx(MessageIcon, { name: "edit", color: c.foreground, size: 20 }), _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Edit profile") })] })] }), features?.showSelf !== false && inbox && _jsx(SelfChatSetting, { inbox: inbox }), account?.backup && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText('Chat backup'), onPress: () => setBackupOpen(true), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText('Chat backup') }) }), features?.callDevices !== false && account?.deviceCheck && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Check call devices"), disabled: busy, onPress: () => setChecking(true), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Check call devices") }) }), features?.notifications !== false && account?.onEnableNotifications && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Enable notifications"), disabled: busy, onPress: () => void run(account.onEnableNotifications), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Enable notifications") }) }), features?.deleteAccount !== false && account?.onDeleteAccount && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Delete account"), disabled: busy, onPress: () => begin(account.onDeleteAccount), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.danger, fontSize: 16 }, children: uiText("Delete account") }) }), features?.signOut !== false && account?.onSignOut && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Sign out"), disabled: busy, onPress: () => begin(account.onSignOut), style: { backgroundColor: c.incoming, borderRadius: 12, minHeight: 52, paddingHorizontal: 16, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.foreground, fontSize: 16 }, children: uiText("Sign out") }) }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground, fontSize: 15 }, children: error })] }) }) }), backupOpen && page ? page.content : null] }) });
64
68
  }
@@ -0,0 +1,25 @@
1
+ import type { MessagingBackupClient } from '@robono/messaging';
2
+ export interface MessagingBackgroundBackupSession {
3
+ /** The same opaque endpoint/tenant/user scope used by durable history. */
4
+ accountScope: string;
5
+ client: Pick<MessagingBackupClient, 'runScheduled' | 'getSnapshot' | 'dispose'>;
6
+ /** Release any history/network resources owned by this headless session. */
7
+ close(): void;
8
+ }
9
+ export interface MessagingBackgroundBackupOptions {
10
+ /** Restore the host's current authenticated identity, without prompting. */
11
+ accountScope(): Promise<string | null>;
12
+ /** Notify synchronously on sign-out/account replacement, before changing stores. */
13
+ subscribeAccountChange(listener: () => void): () => void;
14
+ /** Create a fresh, exclusively owned client; never return the screen's client.
15
+ * Do not prompt for sign-in or key setup from a background launch. */
16
+ openSession(signal: AbortSignal): Promise<MessagingBackgroundBackupSession | null>;
17
+ /** Bound each OS wake. Defaults to two minutes; never more than four minutes. */
18
+ timeoutMs?: number;
19
+ }
20
+ /** One current account per wake, with cancellation even during authentication.
21
+ * OS launches and foreground resumes share this runner to avoid duplicate work. */
22
+ export declare function createMessagingBackgroundBackupRunner(options: MessagingBackgroundBackupOptions): {
23
+ run: () => Promise<boolean>;
24
+ cancel: () => void | undefined;
25
+ };
@@ -0,0 +1,71 @@
1
+ /** One current account per wake, with cancellation even during authentication.
2
+ * OS launches and foreground resumes share this runner to avoid duplicate work. */
3
+ export function createMessagingBackgroundBackupRunner(options) {
4
+ const timeout = options.timeoutMs ?? 120000;
5
+ if (!Number.isFinite(timeout) || timeout < 1 || timeout > 240000)
6
+ throw Error('Invalid background backup deadline.');
7
+ let active = null, abort = null;
8
+ const cancel = () => abort?.abort();
9
+ const run = () => {
10
+ if (active)
11
+ return active;
12
+ const controller = new AbortController();
13
+ abort = controller;
14
+ let session = null, closed = false;
15
+ const close = () => { if (!session || closed)
16
+ return; closed = true; try {
17
+ session.client.dispose();
18
+ }
19
+ catch { } try {
20
+ session.close();
21
+ }
22
+ catch { } };
23
+ let release = () => { }, timer;
24
+ const cancelled = new Promise(resolve => controller.signal.addEventListener('abort', () => { try {
25
+ close();
26
+ }
27
+ finally {
28
+ resolve(false);
29
+ } }, { once: true }));
30
+ const work = (async () => {
31
+ try {
32
+ release = options.subscribeAccountChange(() => controller.abort());
33
+ timer = setTimeout(() => controller.abort(), timeout);
34
+ const scope = await options.accountScope();
35
+ if (!scope || controller.signal.aborted)
36
+ return true;
37
+ session = await options.openSession(controller.signal);
38
+ if (controller.signal.aborted) {
39
+ close();
40
+ return false;
41
+ }
42
+ if (!session)
43
+ return true; // Signed out, locked keychain or no backup setup: no prompt.
44
+ if (session.accountScope !== scope || await options.accountScope() !== scope || controller.signal.aborted) {
45
+ controller.abort();
46
+ return false;
47
+ }
48
+ await session.client.runScheduled();
49
+ return !controller.signal.aborted && !session.client.getSnapshot().error;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ })();
55
+ active = Promise.race([work, cancelled]).finally(() => {
56
+ if (timer)
57
+ clearTimeout(timer);
58
+ try {
59
+ release();
60
+ }
61
+ catch { }
62
+ close();
63
+ if (abort === controller) {
64
+ abort = null;
65
+ active = null;
66
+ }
67
+ });
68
+ return active;
69
+ };
70
+ return { run, cancel };
71
+ }
@@ -0,0 +1,3 @@
1
+ /** Bounded bridge encoding that does not depend on browser atob/btoa in Hermes. */
2
+ export declare function encodeBackupBase64(bytes: Uint8Array): string;
3
+ export declare function decodeBackupBase64(text: string, maximum: number): Uint8Array;