aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests/test_phone_sync.py
blob: 0798ef0b517f6239f8aef107dd5a2b7ae379b983 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""
The phone's contacts backup, as the page runs it (docs/MESHBAY_DESIGN.md §9.13).

Run under Node against the real `phone-sync.js`, with what it talks to
replaced: the Android bridge (`window.meshbay.contactSync`, which writes the
file and remembers what the node took), the hub's member list, and the group
connection (`connection-pool.js`, swapped in the copy). What is pinned is what
the person was promised: once a day, one dated file into
`<folder>/<account>-contacts`, only while they are alone in the group, nothing
ever deleted on the node, and a lasting refusal said once.
"""

import json
import re
import shutil
import subprocess
from pathlib import Path

import pytest

STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
SYNC = STATIC / "phone-sync.js"

pytestmark = pytest.mark.skipif(
    shutil.which("node") is None or not SYNC.exists(),
    reason="node or the SPA sources are not available")

DAY = 24 * 3600 * 1000

FAKE_POOL = r"""
export class ConnectionPool {
  constructor(hub) { globalThis.fake.pools.push(hub); }
  async connect(groupId) {
    if (globalThis.fake.refuseConnect) {
      const e = new Error('refused'); e.reason = globalThis.fake.refuseConnect; throw e;
    }
    globalThis.fake.log.push(['connect', groupId]);
    return { transport: globalThis.fake.transport, ack: {} };
  }
  closeAll() { globalThis.fake.log.push(['close']); }
}
"""

PRELUDE = r"""
const fake = globalThis.fake = { log: [], pools: [], refuseConnect: null, uploadError: null,
                                 members: [{ user_id: 'u-bob', username: 'bob' }], invited: [],
                                 adminId: 'u-bob', membersError: null };
const win = new EventTarget();
const doc = new EventTarget();
doc.visibilityState = 'visible';
globalThis.window = win;
globalThis.document = doc;
globalThis.localStorage = { getItem() { return null; }, setItem() {}, removeItem() {} };
globalThis.fetch = async (url) => {
  fake.log.push(['fetch', url]);
  return { ok: true, blob: async () => new Blob([new Uint8Array(4)]) };
};

fake.status = {
  permission: 'granted', sent: 0, now: Date.now(), on: true,
  destination: { account: 'bob', groupId: 'g1', groupName: 'Mine', folder: 'Backups' },
  dir: 'Backups/bob-contacts',
  lastCompleted: null, lastSent: null, failure: null, failureAt: null,
};
fake.item = { token: 't1', name: 'contacts-2026-10-10-0900.vcf', dir: 'Backups/bob-contacts',
              size: 4, count: 12 };
fake.index = {
  roots: [{ name: 'Backups', writable: true, available: true }],
  dirs: [],
  entries: [],
};
fake.transport = {
  connected: true,
  async fetchIndex() { return fake.index; },
  async createDirectory(at, name) { fake.log.push(['mkdir', `${at}/${name}`]); return {}; },
  openTransfer({ kind, bytes }) {
    fake.log.push(['lease', kind, bytes]);
    return { tr: 'tr-' + bytes, acquire: async () => {},
             release: () => fake.log.push(['release', bytes]) };
  },
  async uploadFile(file, opts) {
    fake.log.push(['upload', opts.dir, file.name, opts.tr]);
    if (fake.uploadError) { const e = new Error('refused'); e.code = fake.uploadError; throw e; }
    return { stored_as: file.name, dir: opts.dir };
  },
};
const hubFetch = async (path) => {
  fake.log.push(['hub', path]);
  if (fake.membersError) throw new Error(fake.membersError);
  return { admin_id: fake.adminId, members: fake.members, invited: fake.invited };
};
win.meshbay = { contactSync: {
  status: async () => fake.status,
  plan: async () => { fake.log.push(['plan']); return { item: fake.item }; },
  sent: async (token, dir, name) => { fake.log.push(['sent', token, dir, name]); return true; },
  completed: async () => {
    fake.log.push(['completed']);
    fake.status.lastCompleted = Date.now();
    return fake.status;
  },
  failed: async (code, text) => { fake.log.push(['failed', code, text]); return true; },
}, messageSync: {
  status: async () => ({ ...fake.status, on: !!fake.messagesOn, dir: 'Backups/bob-messages' }),
  plan: async () => ({ item: { token: 'm1', name: 'sms-2026-10-10-0900.xml',
                               dir: 'Backups/bob-messages/2026', size: 4, count: 300 } }),
  sent: async (token, dir, name) => { fake.log.push(['sent', token, dir, name]); return true; },
  completed: async () => { fake.log.push(['completed']); return fake.status; },
  failed: async (code, text) => { fake.log.push(['failed', code, text]); return true; },
} };
"""


def _run(body, tmp_path):
    root = tmp_path / "static"
    shutil.copytree(STATIC, root)
    (root / "package.json").write_text('{"type":"module"}', encoding="utf-8")
    (root / "connection-pool.js").write_text(FAKE_POOL, encoding="utf-8")
    script = tmp_path / "case.mjs"
    script.write_text(
        PRELUDE
        + f"const m = await import('{(root / 'phone-sync.js').as_uri()}');\n"
        + f"const d = await import('{(root / 'sync-destination.js').as_uri()}');\n"
        + "const ctx = { hub: 'https://hub.invalid', hubFetch, getUser: () => ({ username: 'bob', "
          "userId: 'u-bob', token: 'tok' }), getBundleKey: async () => 'bk' };\n"
        + body
        # The next run's timer would keep Node alive for a day.
        + "\nm.stopPhoneSync();\nconsole.log(JSON.stringify(fake.log));\n",
        encoding="utf-8")
    proc = subprocess.run(["node", str(script)], capture_output=True, text=True,
                          encoding="utf-8", timeout=30)
    assert proc.returncode == 0, proc.stderr
    return json.loads(proc.stdout.strip().splitlines()[-1])


def _start(extra=""):
    return extra + "\nm.startPhoneSync(ctx);\nawait m.runDocSync('contacts');\n"


def _of(log, kind):
    return [e[1:] for e in log if e[0] == kind]


# ── a run ───────────────────────────────────────────────────────────────────

def test_a_due_run_sends_one_dated_file_into_the_account_folder(tmp_path):
    log = _run(_start(), tmp_path)
    assert _of(log, "mkdir") == [["Backups/bob-contacts"]]
    assert _of(log, "upload") == [["Backups/bob-contacts", "contacts-2026-10-10-0900.vcf", "tr-4"]]
    assert _of(log, "fetch") == [["/phonesync/t1"]]
    assert _of(log, "sent") == [["t1", "Backups/bob-contacts", "contacts-2026-10-10-0900.vcf"]]
    assert ["completed"] in log
    assert _of(log, "release") == [[4]]


def test_a_folder_already_there_is_not_made_again(tmp_path):
    log = _run(_start("fake.index.dirs = ['Backups/bob-contacts'];"), tmp_path)
    assert _of(log, "mkdir") == []
    assert len(_of(log, "upload")) == 1


def test_nothing_new_finishes_the_run_without_connecting(tmp_path):
    log = _run(_start("fake.item = null;"), tmp_path)
    assert ["completed"] in log
    assert _of(log, "connect") == []


def test_nothing_happens_before_a_day_has_passed(tmp_path):
    log = _run(_start("fake.status.lastCompleted = Date.now() - 3600 * 1000;"), tmp_path)
    assert _of(log, "plan") == [] and _of(log, "hub") == []


def test_a_day_later_it_runs(tmp_path):
    log = _run(_start(f"fake.status.lastCompleted = Date.now() - {DAY + 1000};"), tmp_path)
    assert len(_of(log, "upload")) == 1


def test_back_up_now_runs_whenever(tmp_path):
    log = _run("""
fake.status.lastCompleted = Date.now() - 1000;
m.startPhoneSync(ctx);
await m.runDocSync('contacts');
await m.runDocSync('contacts', { force: true });
""", tmp_path)
    assert len(_of(log, "upload")) == 1


def test_messages_go_under_the_year_in_their_own_folder(tmp_path):
    log = _run("""
fake.messagesOn = true;
m.startPhoneSync(ctx);
await m.runDocSync('contacts');
await m.runDocSync('messages');
""", tmp_path)
    assert _of(log, "mkdir")[-2:] == [["Backups/bob-messages"], ["Backups/bob-messages/2026"]]
    assert ["upload", "Backups/bob-messages/2026", "sms-2026-10-10-0900.xml", "tr-4"] in log
    assert ["sent", "m1", "Backups/bob-messages/2026", "sms-2026-10-10-0900.xml"] in log


# ── alone in the group, at every run ────────────────────────────────────────

def test_the_group_is_asked_about_at_every_run(tmp_path):
    log = _run(_start(), tmp_path)
    assert _of(log, "hub") == [["/v1/groups/g1/members"]]


@pytest.mark.parametrize("setup", [
    "fake.members.push({ user_id: 'u-carol', username: 'carol' });",
    "fake.invited = [{ user_id: 'u-carol', username: 'carol' }];",
    "fake.adminId = 'u-carol';",
])
def test_somebody_else_in_the_group_stops_it_before_anything_is_read(tmp_path, setup):
    log = _run(_start(setup), tmp_path)
    assert [e[0] for e in _of(log, "failed")] == ["not_private"]
    assert _of(log, "plan") == [] and _of(log, "upload") == []


def test_a_member_removed_from_the_group_is_told_once(tmp_path):
    log = _run(_start("fake.membersError = 'Not a member';"), tmp_path)
    assert [e[0] for e in _of(log, "failed")] == ["not_a_member"]


def test_an_unreachable_hub_is_not_a_lasting_refusal(tmp_path):
    log = _run(_start("fake.membersError = 'Failed to fetch';"), tmp_path)
    assert _of(log, "failed") == [] and _of(log, "plan") == []


def test_only_groups_this_account_owns_and_is_alone_in_are_offered(tmp_path):
    log = _run("""
m.startPhoneSync(ctx);
const real = ctx.hubFetch;
ctx.hubFetch = async (path) => path.includes('/g2/')
  ? { admin_id: 'u-bob', members: [{ user_id: 'u-bob' }, { user_id: 'u-carol' }] }
  : path.includes('/g3/') ? Promise.reject(new Error('offline'))
  : path.includes('/g4/') ? { admin_id: 'u-carol', members: [{ user_id: 'u-bob' }] }
  : real(path);
fake.log.push(['offered', (await d.privateGroups(
  [{ id: 'g1', name: 'Mine' }, { id: 'g2', name: 'Family' }, { id: 'g3', name: 'Far' },
   { id: 'g4', name: 'Given' }]))
  .map((g) => g.id)]);
""", tmp_path)
    assert _of(log, "offered") == [[["g1"]]]


# ── refusals ────────────────────────────────────────────────────────────────

@pytest.mark.parametrize("code", ["disk_full", "root_read_only"])
def test_a_lasting_refusal_stops_and_is_said(tmp_path, code):
    log = _run(_start(f"fake.uploadError = '{code}';"), tmp_path)
    failed = _of(log, "failed")
    assert [e[0] for e in failed] == [code]
    assert failed[0][1], "the phone is given nothing to say"
    assert ["completed"] not in log


def test_a_folder_gone_is_found_before_sending(tmp_path):
    log = _run(_start("fake.index.roots = [];"), tmp_path)
    assert [e[0] for e in _of(log, "failed")] == ["no_such_root"]
    assert _of(log, "upload") == []


def test_without_the_permission_it_stops_and_says_so(tmp_path):
    log = _run(_start("fake.status.permission = 'denied';"), tmp_path)
    assert [e[0] for e in _of(log, "failed")] == ["permission"]


def test_another_account_on_the_phone_sends_nothing(tmp_path):
    log = _run(_start("fake.status.destination.account = 'alice';"), tmp_path)
    assert _of(log, "plan") == [] and _of(log, "hub") == []


# ── folders offered ─────────────────────────────────────────────────────────

def test_every_writable_folder_is_offered_not_only_photo_ones(tmp_path):
    log = _run("""
fake.log.push(['folders', d.writableFolders(
  { roots: [{ name: 'Media', writable: true, available: true },
            { name: 'Archive', writable: false, available: true },
            { name: 'Ejected', writable: true, available: false }],
    dirs: ['Media/Films', 'Media/Photos', 'Archive/Old', 'Ejected/Stuff'] })]);
""", tmp_path)
    assert _of(log, "folders") == [[["Media", "Media/Films", "Media/Photos"]]]


def test_photos_outside_the_photos_tab_folders_are_said(tmp_path):
    log = _run("""
fake.log.push(['shows', ['Media/Photos/bob-photos', 'Media/Other/bob-photos', 'Media/PhotosX']
  .map((dir) => d.photosTabShows(dir, ['Media/Photos']))]);
""", tmp_path)
    assert _of(log, "shows") == [[[True, False, False]]]


def test_turned_off_it_sends_nothing(tmp_path):
    log = _run(_start("fake.status.on = false;"), tmp_path)
    assert _of(log, "plan") == [] and _of(log, "hub") == []


# ── nothing is ever removed ─────────────────────────────────────────────────

def test_the_backup_has_no_way_to_remove_anything_on_the_node():
    """Every copy is a new file; the property is the absence of a call."""
    src = SYNC.read_text(encoding="utf-8")
    for op in ("deleteFile", "deleteDirectory", "removeRoot", "file_delete", "dir_delete",
               "root_remove", "rename"):
        assert not re.search(rf"\b{op}\b", src), f"phone-sync.js reaches {op}"