From 8da867a2d1c7f081b0a16d30d2f888a4c5efcd0e Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 15:48:26 +0100 Subject: [PATCH 1/9] Web app: a shared collection never reaches the library while the app starts or when its list or files are damaged Signed-off-by: Bohdan Tsap --- CHANGELOG.md | 4 ++ webapp/src/library.js | 32 +++++++++- webapp/src/store.js | 12 +++- webapp/src/store/folders.js | 15 ++++- webapp/src/store/shared.js | 2 +- webapp/src/sync.js | 16 +++++ webapp/tests/run-e2e.mjs | 2 +- webapp/tests/shared-library.cjs | 110 ++++++++++++++++++++++++++++++++ 8 files changed, 188 insertions(+), 5 deletions(-) create mode 100644 webapp/tests/shared-library.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 40c9862..febe66d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,10 @@ Releases before 1.2 are listed in ROADMAP.md (section 5) and on the GitHub Relea ### Web and desktop +- **Security, web app:** signed in, a page load could upload an end-to-end encrypted shared collection to your own library, which the server + can read, before the app knew it was shared (and then delete it there). Nothing is saved to the library now until shared collections are + open, and one that was shared never goes there by itself, also when its files or the list of shared collections are damaged. +- A shared collection whose files are gone from the browser is read from the server again instead of being deleted for everyone. - Desktop: Settings → Network: certificate authorities, a client certificate and a proxy for requests (never HITOP Cloud). While they can't be used, requests fail with the reason. Certificate checks can be skipped only in the CLI (`--insecure`). - Desktop: event streams show live (Stop ends them) and OAuth 2.0 authorization code signs in in the system browser (not in the Mac diff --git a/webapp/src/library.js b/webapp/src/library.js index e9bc407..dfc3912 100644 --- a/webapp/src/library.js +++ b/webapp/src/library.js @@ -259,6 +259,16 @@ export class Library extends EventTarget { attach(store) { this.store = store; + // Which collections are in folders (shared ones are end-to-end encrypted): not known before they + // are restored, and nothing is pushed or pulled until then, nor if that fails. + this.settled = false; + this.foldersReady = Promise.resolve(store.ready).then( + () => { + this.settled = true; + this.keepSharedHere(); + }, + (e) => this.setStatus({ error: `Folders and shared collections couldn't be opened, so nothing is saved to HITOP Cloud: ${e?.message || e}` }), + ); const st = platform().storage; // Every save goes through these three: push what changed a moment later. for (const name of ["saveCollections", "saveEnvironments", "saveGlobals"]) { @@ -278,7 +288,19 @@ export class Library extends EventTarget { if (this.signedIn) this.schedulePush(0); } + /** What was shared and isn't open as a shared collection now stays in this browser only. */ + keepSharedHere() { + const s = this.store; + if (!this.state) return; + const add = s.collections.filter((c) => s.sharedIds?.has(c.id) && !s.folders.has(c.id) && !this.state.localOnly.includes(idOf(c))).map(idOf); + if (!add.length) return; + this.state.localOnly = [...this.state.localOnly, ...add]; + writeState(this.state); + } + async checkAccount() { + await this.foldersReady; + if (!this.settled) return; const key = this.signedIn ? this.accountKey() : ""; if (!key) { if (this.status.on) this.setStatus({ on: false, error: "" }); @@ -287,6 +309,7 @@ export class Library extends EventTarget { if (this.state?.account === key) return; // Signed in just now: link this browser's library and pull it into the app. this.state = this.loadState(this.store.collections.filter((c) => !this.store.folders.has(c.id))); + this.keepSharedHere(); this.setStatus({ on: true, error: "" }); await this.pull(); this.schedulePush(0); @@ -312,6 +335,9 @@ export class Library extends EventTarget { async upload(collectionId) { if (!this.state) return; this.state.localOnly = this.state.localOnly.filter((x) => x !== String(collectionId)); + // The person's own choice: it isn't a shared one any more. + this.store?.sharedIds?.delete(collectionId); + this.store?.save(); writeState(this.state); this.setStatus({}); await this.flush(); @@ -331,7 +357,7 @@ export class Library extends EventTarget { const out = {}; const localOnly = new Set(this.state.localOnly); for (const c of s.collections) { - if (s.folders.has(c.id) || localOnly.has(idOf(c))) continue; + if (s.folders.has(c.id) || s.sharedIds?.has(c.id) || localOnly.has(idOf(c))) continue; out[`collection/${idOf(c)}`] = { kind: "collection", id: idOf(c), data: c, secrets: {} }; } const envs = s.environments.filter((e) => !s.folderEnvs.has(e.id) && !e.team); @@ -342,6 +368,8 @@ export class Library extends EventTarget { } async push() { + await this.foldersReady; + if (!this.settled) return; if (!this.store || !this.signedIn || !this.state || this.state.account !== this.accountKey()) return; if (this.pushing) return this.schedulePush(); this.pushing = true; @@ -427,6 +455,8 @@ export class Library extends EventTarget { if (this.pulling) return this.pulling; this.pulling = (async () => { try { + await this.foldersReady; + if (!this.settled) return; const r = await this.pullRaw(); const fresh = r.items.filter((it) => !(this.state.known[`${it.kind}/${it.id}`]?.version >= it.version)); if (!fresh.length) return; diff --git a/webapp/src/store.js b/webapp/src/store.js index 3e48cfb..6c3dff1 100644 --- a/webapp/src/store.js +++ b/webapp/src/store.js @@ -35,6 +35,9 @@ const Parts = [CookiesPart, FormFieldsPart, TabsPart, RequestsPart, Organization export class Store extends Parts { constructor() { super(); + // Shared (end-to-end encrypted) collections by id, as saved (`sharedIn`): they never go to the + // library by themselves, also when the app's list of shared collections can't be read. + this.sharedIds = new Map((storage().loadCollections() || []).filter((c) => c?.sharedIn).map((c) => [c.id, c.sharedIn])); const s = initialState(); this.collections = s.collections; this.tabs = s.tabs; @@ -132,12 +135,19 @@ export class Store extends Parts { this.dispatchEvent(new Event("change")); } + /** The collections as they are saved: the shared ones say so. */ + markShared(collections) { + const prefix = "hitop-sync:"; + for (const [id, f] of this.folders) if (String(f.ref ?? "").startsWith(prefix)) this.sharedIds.set(id, f.ref.slice(prefix.length)); + return collections.map((c) => (this.sharedIds.has(c.id) ? { ...c, sharedIn: this.sharedIds.get(c.id) } : c)); + } + save() { clearTimeout(this.saveTimer); const st = storage(); // Adapters return false when the browser refused a write (storage full). const failed = []; - if (st.saveCollections(this.collections) === false) failed.push("collections"); + if (st.saveCollections(this.markShared(this.collections)) === false) failed.push("collections"); if (st.saveTabs(this.storedTabs()) === false) failed.push("tabs"); st.saveCurrentTab(this.currentTab); if (st.saveHistory(this.history) === false) failed.push("history"); diff --git a/webapp/src/store/folders.js b/webapp/src/store/folders.js index ffe45aa..b2291c6 100644 --- a/webapp/src/store/folders.js +++ b/webapp/src/store/folders.js @@ -143,6 +143,16 @@ export const FoldersPart = (Base) => await this.attachFolder(entry.ref, await f.read(entry.ref), { remember: false }); this.notify(`Reconnected ${entry.label}`); } catch (e) { + // A shared collection's files here are gone: from the server again. + if (String(entry.ref).startsWith("hitop-sync:") && this.syncClient?.link?.(collectionId)) { + try { + await this.syncClient.syncNow(collectionId); + this.notify(`Reconnected ${entry.label}`); + return; + } catch { + // said below + } + } this.notify(`Couldn't read ${entry.label}: ${errorText(e)}`); } } @@ -178,7 +188,10 @@ export const FoldersPart = (Base) => try { await this.attachFolder(ref, await f.read(ref), { remember: false }); } catch (e) { - f.forget(collectionId); + // Still a folder's (or a shared, end-to-end encrypted) collection: never taken for one of the + // person's own, which the library keeps. + if (this.collection(collectionId)) this.folders.set(collectionId, { ref, label: f.label(ref), connected: false, error: null, written: null, secrets: {} }); + else f.forget(collectionId); this.notify(`Couldn't open the folder ${f.label(ref)}: ${errorText(e)}. Open it again with Open folder.`); } } diff --git a/webapp/src/store/shared.js b/webapp/src/store/shared.js index b4b6eae..52c1c81 100644 --- a/webapp/src/store/shared.js +++ b/webapp/src/store/shared.js @@ -214,7 +214,7 @@ export function fileDrafts(collections, tabs) { } export function initialState() { - const collections = storage().loadCollections(); + const collections = storage().loadCollections()?.map(({ sharedIn: _, ...c }) => c); const tabs = storage().loadTabs(); const current = storage().loadCurrentTab(); // FV1 first visit (nothing stored at all): the sample with "List posts" open, and an empty diff --git a/webapp/src/sync.js b/webapp/src/sync.js index cd26757..fb33f2d 100644 --- a/webapp/src/sync.js +++ b/webapp/src/sync.js @@ -137,6 +137,19 @@ const splitComments = (files) => { // Folders under "hitop-sync:" refs next to the platform's own (disk, File System Access). export function withSyncFolders(base) { + // A list of shared collections that can't be read is kept beside before anything replaces it. + try { + const text = localStorage.getItem(STATE_KEY); + if (text) { + try { + JSON.parse(text); + } catch { + localStorage.setItem(`${STATE_KEY}_damaged`, text); + } + } + } catch { + // storage blocked + } const sync = { async read(ref) { const ws = ref.slice(SYNC_REF.length); @@ -1094,6 +1107,9 @@ export class SyncClient { if (u.upgraded) this.notices.push({ kind: "upgraded", message: `Upgraded ${u.upgraded} workspace key wrap(s) to authenticated ones. Members confirm your fingerprint once.` }); if (u.untrusted.length) this.notices.push({ kind: "notUpgraded", message: `Not upgraded, devices you haven't trusted: ${u.untrusted.join(", ")}` }); } + // The files kept here are gone or damaged: start over from the server's, deleting nothing (an + // empty folder would read as everything deleted, for every member). + if (isSyncRef(l.ref) && !syncFiles.get(ws)["hitop.yaml"]) this.saveState(ws, { seq: 0, entries: {}, conflicts: {}, losers: {} }); for (let attempt = 0; attempt < 5; attempt++) { let state = this.state(ws); const { remote, seq } = await this.changes(ws, state.seq, keys); diff --git a/webapp/tests/run-e2e.mjs b/webapp/tests/run-e2e.mjs index a746262..56f06aa 100644 --- a/webapp/tests/run-e2e.mjs +++ b/webapp/tests/run-e2e.mjs @@ -11,7 +11,7 @@ const SUITES = [ "e2e", "editing", "features", "extras", "folders", "postman", "settings", "globals", "graphql", "diff-code", "websocket", "grpc", "openapi", "git", "secret-refs", "ux", "ux12", "onboarding", - "sse", "ai", "sync", "library", "devices", "account-delete", + "sse", "ai", "sync", "library", "shared-library", "devices", "account-delete", "limits", "github", "next", "collections-ux", "stories", "first-visit", "ux2", "tree-dnd", "tabs-dnd", "ux3", "updater", "store-mode", "run-cancel", ]; diff --git a/webapp/tests/shared-library.cjs b/webapp/tests/shared-library.cjs new file mode 100644 index 0000000..e6af93f --- /dev/null +++ b/webapp/tests/shared-library.cjs @@ -0,0 +1,110 @@ +// A shared collection is end-to-end encrypted; the personal library is readable by the server. With +// both on (as people have them) nothing of a shared collection may reach the library: while the app +// starts, when the app's own list of shared collections is damaged or gone, when its files are. +// Both modes; a real sync server (HITOP_SYNC_SERVER_BIN). +const { spawn } = require('child_process'); +const crypto = require('crypto'); +const fs = require('fs'); +const net = require('net'); +const os = require('os'); +const path = require('path'); +const { launch, checker, inApp, signInByCode, BASE } = require('./harness.cjs'); +const { results, check } = checker(); +const MARK = 'shared-e2e-mark.test'; + +const freePort = () => new Promise((resolve) => { + const s = net.createServer().listen(0, '127.0.0.1', () => { + const { port } = s.address(); + s.close(() => resolve(port)); + }); +}); + +(async () => { + const bin = process.env.HITOP_SYNC_SERVER_BIN; + if (!bin) { + if (process.env.CI) throw new Error('HITOP_SYNC_SERVER_BIN must be set on CI'); + console.log('[shared-library] HITOP_SYNC_SERVER_BIN not set: skipped'); + return; + } + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hitop-shared-library-')); + const port = await freePort(); + const url = `http://127.0.0.1:${port}`; + let log = ''; + const child = spawn(path.resolve(bin), [], { + cwd: dir, + env: { + ...process.env, RWS_CONFIG_IP: '127.0.0.1', RWS_CONFIG_PORT: String(port), HITOP_SYNC_PUBLIC_URL: url, HITOP_SYNC_RP_ID: 'localhost', + HITOP_SYNC_RP_ORIGINS: `http://localhost:${port}`, HITOP_SYNC_DATABASE: `sqlite:${path.join(dir, 'sync.db')}`, HITOP_SYNC_MAIL: 'log', + HITOP_SYNC_ALLOWED_ORIGINS: new URL(BASE).origin, HITOP_SYNC_HOST_KEY: crypto.randomBytes(32).toString('hex'), + }, + stdio: ['ignore', 'ignore', 'pipe'], + }); + child.stderr.on('data', (d) => (log += d)); + for (let i = 0; i < 100; i++) { + if (await fetch(`${url}/healthz`).then((r) => r.ok, () => false)) break; + await new Promise((r) => setTimeout(r, 100)); + } + const code = async () => { + for (let i = 0; i < 100 && !log.includes('/signin#'); i++) await new Promise((r) => setTimeout(r, 100)); + return log.split('\n').filter((l) => l.includes('/signin#')).pop().trim().split('#').pop(); + }; + // Everything the server keeps, in the clear or not: plaintext of a shared collection must not be there. + const leaked = () => Buffer.concat(fs.readdirSync(dir).map((f) => fs.readFileSync(path.join(dir, f)))).includes(Buffer.from(MARK)); + + const h = await launch({ results }); + const errors = []; + h.page.on('pageerror', (e) => errors.push(e.message)); + const store = (fn, arg) => h.page.evaluate(([f, a]) => new Function('s', 'a', f)(document.querySelector('hitop-app').store, a), [fn, arg]); + // Every library write, as the browser sent it (web; the desktop's go through Rust: the database check). + const puts = []; + h.page.on('request', (r) => r.method() === 'PUT' && r.url().includes('/v1/library/collection/') && puts.push(r.postData() || '')); + const quiet = async () => { + await h.page.waitForFunction(() => document.querySelector('hitop-app')?.store?.library?.state, null, { timeout: 20000 }); + await store('return s.ready;'); + await store('return s.library.flush();'); + }; + const reload = async () => { + await h.page.goto('about:blank'); + await h.page.goto(h.url, { waitUntil: 'networkidle' }); + await quiet(); + }; + const clean = (name) => check(name, !leaked() && !puts.some((p) => p.includes(MARK)), `${puts.filter((p) => p.includes(MARK)).length} writes`); + try { + await h.page.goto(h.url, { waitUntil: 'networkidle' }); + await signInByCode(h.page, url, 'ada@example.com', code); + await quiet(); + // Shared before its content is written, so the mark was never in the library. + await store('s.addCollection("Shared API");'); + const id = await store('return s.collections.find((c) => c.name === "Shared API").id;'); + await quiet(); + const shared = await inApp(h.page, 'await c.share(a);', id); + if (!shared.ok) throw new Error(shared.error); + await quiet(); + await store('s.collections = s.collections.map((x) => x.id === a[0] ? { ...x, requests: [{ id: 901, name: "Secret request", method: "GET", url: "https://" + a[1] + "/x", headers: [], body: "" }] } : x); s.emit(); s.save();', [id, MARK]); + await quiet(); + check('it is shared', await store('return s.folders.has(a);', id)); + clean('nothing of it in the library while it is open'); + for (let i = 0; i < 3; i++) await reload(); + check('still shared after a reload', await store('return s.folders.has(a);', id)); + clean('nor while the app starts'); + + const files = () => h.page.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith('hitop_sync_files:'))); + const save = await h.page.evaluate(() => ({ ...localStorage })); + const damage = async (key, value) => { + await h.page.evaluate(([k, v]) => (v === null ? localStorage.removeItem(k) : localStorage.setItem(k, v)), [key, value]); + await reload(); + }; + for (const [what, key, value] of [['its files are damaged', (await files())[0], '{'], ['its files are gone', (await files())[0], null], ['the list is damaged', 'hitop_sync', '{'], ['the list is gone', 'hitop_sync', null]]) { + await damage(key, value); + await reload(); + clean(`nor when ${what}`); + await h.page.evaluate((all) => { localStorage.clear(); for (const [k, v] of Object.entries(all)) localStorage.setItem(k, v); }, save); + } + check('no page errors', errors.length === 0, errors.join(' | ')); + } catch (e) { + check('the suite ran', false, `${e.stack} ${errors.join(' | ')}`); + } + child.kill(); + await h.finish(); + fs.rmSync(dir, { recursive: true, force: true }); +})(); From 4048d2da1131c3ee703d35bd9fa5ae13144fa9da Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 14:50:52 +0100 Subject: [PATCH 2/9] C6: iOS background sync, scheduled runs, share extension; unreadable sync files stop the sync Signed-off-by: Bohdan Tsap --- CHANGELOG.md | 5 + docs/PLAN.md | 7 +- ios/APP_STORE.md | 5 +- ios/HITOP/App/Core/AppModel.swift | 6 + ios/HITOP/App/Core/LibrarySync.swift | 117 ++++++-- ios/HITOP/App/Core/Navigator.swift | 21 ++ ios/HITOP/App/Core/Runs.swift | 35 ++- ios/HITOP/App/Core/Schedules.swift | 140 ++++++++++ ios/HITOP/App/Core/Secrets.swift | 6 + ios/HITOP/App/Core/Settings.swift | 3 + ios/HITOP/App/Core/SharedInbox.swift | 84 ++++++ ios/HITOP/App/Core/SharedSync.swift | 90 +++++- ios/HITOP/App/HITOPApp.swift | 20 +- ios/HITOP/App/Info.plist | 10 + ios/HITOP/App/Platform/Background.swift | 162 +++++++++++ ios/HITOP/App/UI/ImportViews.swift | 1 + ios/HITOP/App/UI/IntelligenceViews.swift | 4 + ios/HITOP/App/UI/RootView.swift | 11 + ios/HITOP/App/UI/RunsScreen.swift | 52 ++++ ios/HITOP/App/UI/SettingsView.swift | 10 + ios/HITOP/App/UI/SystemBridge.swift | 6 + ios/HITOP/Share/HITOPShare.entitlements | 10 + ios/HITOP/Share/Info.plist | 43 +++ ios/HITOP/Share/ShareViewController.swift | 91 ++++++ ios/HITOP/UITests/WorkflowTests.swift | 21 ++ ios/HITOP/UnitTests/BackgroundTests.swift | 306 +++++++++++++++++++++ ios/HITOP/UnitTests/RunsTests.swift | 1 + ios/HITOP/project.yml | 20 ++ ios/HITOP/scripts/build-appstore.sh | 9 +- ios/HitopKit/Sources/HitopKit/Runner.swift | 2 + 30 files changed, 1250 insertions(+), 48 deletions(-) create mode 100644 ios/HITOP/App/Core/Schedules.swift create mode 100644 ios/HITOP/App/Core/SharedInbox.swift create mode 100644 ios/HITOP/App/Platform/Background.swift create mode 100644 ios/HITOP/Share/HITOPShare.entitlements create mode 100644 ios/HITOP/Share/Info.plist create mode 100644 ios/HITOP/Share/ShareViewController.swift create mode 100644 ios/HITOP/UnitTests/BackgroundTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index febe66d..cf3b60c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,11 @@ Releases before 1.2 are listed in ROADMAP.md (section 5) and on the GitHub Relea - OAuth 2.0 (client credentials, password, authorization code with PKCE and refresh), AWS Signature and Digest. Before, a request with one of these was sent without it; a preset the app doesn't know now stops the request and says so. +- HITOP in the share sheet (text, an address, a file), HITOP Cloud syncing in the background, and collection runs on a schedule with a + notification when one fails. iOS decides when background work happens. +- **Security:** when the list of shared collections on the device can't be read, nothing is synced. Before, an end-to-end encrypted collection + could have been taken for an ordinary one and uploaded to the library, which the server can read. Secret values the Keychain can't show + at that moment are no longer pushed as deleted. - Settings: the time limit of a request, certificate authorities to trust for requests, and client certificates (.p12), each for one server. - File uploads: multipart rows take a file (a copy up to 50 MB stays on the device and goes out only with that request). - Compare two responses (the current one, saved examples, earlier answers), Undo after a delete or a move, and runs over a CSV or JSON data file. diff --git a/docs/PLAN.md b/docs/PLAN.md index 6f2447b..9dfe12b 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -50,7 +50,7 @@ Status is kept in the table at the end; choices made on the way go under "Decisi | C3 | on main 193350a (PRs 23-27, every check green): run cancel, OAuth windows, desktop streams and OAuth, dialogs, portal (deployed), store.js and hitop-app.js split | | C4 | in progress: CLI TLS options on main a9c1a18 (PR 28); gRPC client/bidi streaming on main 5801dac (PR 29); MCP gRPC tools and sync --json on main 2dc2dc8 (PR 30); OAuth refresh in core, Android and desktop (PR 31), desktop network settings and WebSocket/gRPC TLS tests built (CI pending); open: interactive streaming in the apps (they send all messages, then close), iOS TLS | | C5 | core, CLI, web, desktop and Android on main 17ab888 (PR 33); iOS in C6 | -| C6 | in progress: import and export (PR 34), OAuth/SigV4/Digest (PR 35) on main; uploads, data files, compare/undo (PR 36) on main; settings and TLS built (CI pending); open: share extension, background sync, schedules, roles, comments, team environments, SSO | +| C6 | in progress: import and export (PR 34), OAuth/SigV4/Digest (PR 35) on main; uploads, data files, compare/undo (PR 36) on main; settings and TLS (PR 37), share extension, background sync and schedules built (CI pending); open: roles, comments, team environments, SSO | | C7–C9 | not started | ## Decisions @@ -69,3 +69,8 @@ Status is kept in the table at the end; choices made on the way go under "Decisi | 2026-11-25 | Insomnia, Bruno and HAR are turned into Postman's shape and go through its importer. | One importer and report for every app. Bruno's newer YAML layout (opencollection) is not read. | | 2026-11-25 | Bruno scripts are kept as comments; simple assertions become tests. | Its script API is not HITOP's; running it would fail every request. | | 2026-11-25 | Main b8a2300 (PR 34) was merged with a failed iOS check, against the rule: the merge command did not stop on it. Merges now go through a script that asks GitHub for every check run. | The failure was the new import UI test; fixed with PR 35. | +- iOS schedules: BGTaskScheduler, so a run is "not before", often much later; a run known to take under 8 s also goes in the short refresh. + A run iOS stops is not recorded and counts as started (its requests aren't sent again at once). It never runs with another environment + or without secrets the Keychain can't show. +- iOS share extension only puts the item in the app group (an extension can't open its app); the app shows it before anything is added. +- A damaged list of shared collections is set aside only after every collection the library doesn't hold is marked "this device only". diff --git a/ios/APP_STORE.md b/ios/APP_STORE.md index e5d5020..a4f4d47 100644 --- a/ios/APP_STORE.md +++ b/ios/APP_STORE.md @@ -46,8 +46,9 @@ unsigned Release archive (job `archive`). Signing, upload and App Store Connect - **XcodeGen**: `brew install xcodegen`. - **Signing**: automatic. With `-allowProvisioningUpdates` Xcode makes the Apple Distribution certificate (if there is none) and the App Store profiles for `hitop.rws8.tech.HiTop` and the - widget extension `hitop.rws8.tech.HiTop.Widgets`. The app group `group.hitop.rws8.tech.HiTop` was - registered on 2026-11-19; App Groups must be on for both ids (developer.apple.com → Identifiers). + widget extension `hitop.rws8.tech.HiTop.Widgets` and the share extension + `hitop.rws8.tech.HiTop.Share` (new: register it, with the app group). The app group `group.hitop.rws8.tech.HiTop` was + registered on 2026-11-19; App Groups must be on for all three ids (developer.apple.com → Identifiers). ## 2. Build and upload diff --git a/ios/HITOP/App/Core/AppModel.swift b/ios/HITOP/App/Core/AppModel.swift index ce7a063..a88bd24 100644 --- a/ios/HITOP/App/Core/AppModel.swift +++ b/ios/HITOP/App/Core/AppModel.swift @@ -53,6 +53,12 @@ final class AppModel { /// Called when a collection is deleted here (a shared one stops syncing on this device). @ObservationIgnored var onCollectionDeleted: (@MainActor (UInt64) -> Void)? + /// Which collections are shared isn't known (the list can't be used): nothing syncs until it is. + var sharingProblem: StateFileProblem? + @ObservationIgnored var reloadSharing: (@MainActor () -> Void)? + /// Sets a damaged list aside (LibrarySync, once no collection can reach the library by it). + @ObservationIgnored var startSharingOver: (@MainActor () throws -> Void)? + func isShared(_ collectionID: UInt64?) -> Bool { collectionID.map { sharedRoles[$0] != nil } ?? false } /// A collection this account may only read (a viewer of its shared workspace). diff --git a/ios/HITOP/App/Core/LibrarySync.swift b/ios/HITOP/App/Core/LibrarySync.swift index 4635547..85edd9d 100644 --- a/ios/HITOP/App/Core/LibrarySync.swift +++ b/ios/HITOP/App/Core/LibrarySync.swift @@ -89,7 +89,8 @@ final class LibrarySync { self.model = model self.stateStore = stateStore self.deviceLabel = deviceLabel - state = stateStore.load() + state = State() + loadState() forgetDamaged() status.lastSync = state.lastSync model.onLibraryChange = { [weak self] in self?.changed() } @@ -100,8 +101,26 @@ final class LibrarySync { refreshBadges() } + /// The state file can't be opened now: nothing syncs and nothing is written over it. + @ObservationIgnored private var stateUnreadable = false + + private func loadState() { + do { + state = try stateStore.load() + stateUnreadable = false + } catch StateFileProblem.damaged { + // Which collections stay on this device only isn't known any more: as for another + // account, none is uploaded by itself (what the library has comes back by the pull). + state = State(account: "damaged") + stateUnreadable = false + } catch { + state = State() + stateUnreadable = true + } + } + private func save() { - try? stateStore.save(state) + if !stateUnreadable { try? stateStore.save(state) } } /// Files on this device that couldn't be used (`LibraryStore.damagedFiles`) aren't deleted data: @@ -133,6 +152,14 @@ final class LibrarySync { forgetDamaged() if !model.store.unreadableFiles.isEmpty { return false } } + if stateUnreadable { + loadState() + if stateUnreadable { return false } + } + if model.sharingProblem == .unreadable { + model.reloadSharing?() + if model.sharingProblem == .unreadable { return false } + } guard !key.isEmpty else { if status.on { status.on = false } pushTask?.cancel() @@ -143,10 +170,30 @@ final class LibrarySync { state = Self.firstLink(account: key, previous: state, collections: model.collections) save() } + if model.sharingProblem == .damaged && !startSharingOver() { + status.error = "The list of shared collections can't be read, so nothing is synced." + return false + } status.on = true return true } + /// The list of shared collections is damaged: every collection the library doesn't hold already + /// stays on this device only (it may be a shared one), and that is saved before the list goes. + private func startSharingOver() -> Bool { + let keep = model.collections.map { String($0.id) }.filter { state.known["collection/\($0)"] == nil && !state.localOnly.contains($0) } + var next = state + next.localOnly += keep + do { + try stateStore.save(next) + state = next + try model.startSharingOver?() + } catch { + return false + } + return model.sharingProblem == nil + } + /// A new account's state. The first account this device links uploads what is here, except /// what nobody filled in (an empty My requests, the untouched sample); a different account /// later uploads nothing (those collections stay on this device). @@ -163,6 +210,8 @@ final class LibrarySync { var id: String var data: JSONAny var secrets: [String: JSONAny] + /// A secret's value couldn't be read now: not pushed, or the library would lose it. + var incomplete = false var key: String { "\(kind)/\(id)" } @@ -192,41 +241,53 @@ final class LibrarySync { } /// An environment as the library keeps it: secret values empty, the values apart. - private func split(_ e: SavedEnvironment, vaultID: String) -> (JSONAny, [String: JSONAny]) { + private func split(_ e: SavedEnvironment, vaultID: String) -> (JSONAny, [String: JSONAny], Bool) { var json = ((try? JSONAny.from(e)) ?? .null).object ?? [:] var variables = json["variables"]?.object ?? [:] var secrets: [String: JSONAny] = [:] + var incomplete = false for n in e.secrets { variables[n] = .string("") - if let v = model.vault.value(environment: vaultID, name: n), !v.isEmpty { secrets[n] = .string(v) } + do { + if let v = try model.vault.read(environment: vaultID, name: n), !v.isEmpty { secrets[n] = .string(v) } + } catch { + incomplete = true + } } json["variables"] = .object(variables) - return (.object(json), secrets) + return (.object(json), secrets, incomplete) } var environmentsItem: Item { let envs = model.environments.filter { !isTeam($0) } var list: [JSONAny] = [] var secrets: [String: JSONAny] = [:] + var incomplete = false for e in envs { - let (data, s) = split(e, vaultID: e.id) + let (data, s, missing) = split(e, vaultID: e.id) + incomplete = incomplete || missing list.append(data) if !s.isEmpty { secrets[e.id] = .object(s) } } let activeEnv = envs.first { $0.id == model.state.activeEnvironmentID } let active: JSONAny = activeEnv.map { e in e.numericID ? .number(Double(e.id) ?? 0) : .string(e.id) } ?? .null - return Item(kind: "environments", id: "all", data: .object(["environments": .array(list), "activeEnvironmentId": active]), secrets: secrets) + return Item(kind: "environments", id: "all", data: .object(["environments": .array(list), "activeEnvironmentId": active]), secrets: secrets, incomplete: incomplete) } var globalsItem: Item { let g = model.globals var variables = g.variables.mapValues(JSONAny.string) var secrets: [String: JSONAny] = [:] + var incomplete = false for n in g.secrets { variables[n] = .string("") - if let v = model.vault.value(environment: globalsVaultID, name: n), !v.isEmpty { secrets[n] = .string(v) } + do { + if let v = try model.vault.read(environment: globalsVaultID, name: n), !v.isEmpty { secrets[n] = .string(v) } + } catch { + incomplete = true + } } - return Item(kind: "globals", id: "all", data: .object(["variables": .object(variables), "secrets": .array(g.secrets.map(JSONAny.string))]), secrets: secrets) + return Item(kind: "globals", id: "all", data: .object(["variables": .object(variables), "secrets": .array(g.secrets.map(JSONAny.string))]), secrets: secrets, incomplete: incomplete) } /// What the library should hold now, by key. @@ -287,8 +348,10 @@ final class LibrarySync { guard var e = try? j.decode(SavedEnvironment.self) else { return nil } // Secret values: the server's, else the ones this device already has. for n in e.secrets { - let value = secrets[e.id]?[n]?.string ?? model.vault.value(environment: e.id, name: n) ?? e.variables[n] ?? "" - model.vault.setValue(value, environment: e.id, name: n) + // A value the server doesn't hold and the vault can't show now is left as it is. + if let value = secrets[e.id]?[n]?.string ?? kept(e.id, n, else: e.variables[n]) { + model.vault.setValue(value, environment: e.id, name: n) + } e.variables.removeValue(forKey: n) } return e @@ -301,14 +364,20 @@ final class LibrarySync { model.applyRemote(environments: list + kept, active: active) } + /// The value this device has (nil: the vault can't be read now). + private func kept(_ environment: String, _ name: String, else other: String?) -> String? { + do { return try model.vault.read(environment: environment, name: name) ?? other ?? "" } catch { return nil } + } + private func applyGlobals(_ it: JSONAny) { let data = it["data"] ?? .null let names = (data["secrets"]?.array ?? []).compactMap(\.string) var variables: [String: String] = [:] for (k, v) in data["variables"]?.object ?? [:] { variables[k] = v.string ?? "" } for n in names { - let value = it["secrets"]?[n]?.string ?? model.vault.value(environment: globalsVaultID, name: n) ?? variables[n] ?? "" - model.vault.setValue(value, environment: globalsVaultID, name: n) + if let value = it["secrets"]?[n]?.string ?? kept(globalsVaultID, n, else: variables[n]) { + model.vault.setValue(value, environment: globalsVaultID, name: n) + } variables.removeValue(forKey: n) } var g = model.globals @@ -441,6 +510,7 @@ final class LibrarySync { let known = state.known[key] if known?.hash == h || state.refused[key] == h { continue } if known == nil && item.isEmptySettings { continue } + if item.incomplete { continue } let body = JSONAny.object(["data": item.data, "secrets": .object(item.secrets), "baseVersion": .number(Double(known?.version ?? 0))]) let r = try await send("PUT", "/v1/library/\(item.kind)/\(item.id)", body) switch r.status { @@ -643,8 +713,20 @@ enum LibraryRules { ] } +extension LibrarySync.State { + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.init(account: try c.decode(String.self, forKey: .account), cursor: try c.decodeIfPresent(Int.self, forKey: .cursor), + known: try c.decodeIfPresent([String: LibrarySync.Known].self, forKey: .known) ?? [:], + localOnly: try c.decodeIfPresent([String].self, forKey: .localOnly) ?? [], + refused: try c.decodeIfPresent([String: String].self, forKey: .refused) ?? [:], + lastSync: try c.decodeIfPresent(Date.self, forKey: .lastSync)) + } +} + protocol LibrarySyncStateStore: Sendable { - func load() -> LibrarySync.State + /// Throws `StateFileProblem`. + func load() throws -> LibrarySync.State func save(_ state: LibrarySync.State) throws } @@ -653,10 +735,7 @@ struct FileLibrarySyncStateStore: LibrarySyncStateStore { init(root: URL) { file = root.appendingPathComponent("library-sync.json") } - func load() -> LibrarySync.State { - guard let data = try? Data(contentsOf: file) else { return LibrarySync.State() } - return (try? JSONDecoder().decode(LibrarySync.State.self, from: data)) ?? LibrarySync.State() - } + func load() throws -> LibrarySync.State { try StateFileProblem.read(LibrarySync.State.self, file) ?? LibrarySync.State() } func save(_ state: LibrarySync.State) throws { let e = JSONEncoder() @@ -672,6 +751,6 @@ final class MemoryLibrarySyncStateStore: LibrarySyncStateStore, @unchecked Senda init() {} - func load() -> LibrarySync.State { lock.lock(); defer { lock.unlock() }; return value } + func load() throws -> LibrarySync.State { lock.lock(); defer { lock.unlock() }; return value } func save(_ state: LibrarySync.State) throws { lock.lock(); defer { lock.unlock() }; value = state } } diff --git a/ios/HITOP/App/Core/Navigator.swift b/ios/HITOP/App/Core/Navigator.swift index 3ef02e7..4742360 100644 --- a/ios/HITOP/App/Core/Navigator.swift +++ b/ios/HITOP/App/Core/Navigator.swift @@ -7,6 +7,7 @@ enum AppTab: Hashable { case collections, history, environments, runs, search } struct ImportTarget: Identifiable, Hashable, Sendable { var id = UUID() var file: URL? + var text: String? } /// The request whose response is being explained. @@ -46,6 +47,8 @@ final class Navigator { /// I5: "New request from text or curl" (Collections +, the iPad sidebar, ⇧⌘N). var showRequestFromText = false + /// What it starts with (shared text). + var requestText = "" /// The Import sheet: picked from a menu (nil file), or a file another app handed over. var importing: ImportTarget? /// I5: the "Explain response" sheet of an open request (the response's button; ⇧⌘E on iPad). @@ -98,6 +101,24 @@ final class Navigator { runSheet = RunTarget(id: id, showLast: showLast) } + /// What another app shared: a file or a document to import, a curl command, or an address, which + /// becomes a request (nothing is sent). Anything else starts as a request's text. + func receive(_ item: SharedInbox.Item, _ model: AppModel) { + switch item { + case let .file(url): importing = ImportTarget(file: url) + case let .text(text): + let t = text.trimmingCharacters(in: .whitespacesAndNewlines) + if !t.contains(where: \.isWhitespace), let u = URL(string: t), u.scheme == "https" || u.scheme == "http", u.host != nil { + open(request: model.newRequest(from: SavedRequest(name: AutoName.name(method: "GET", url: t), url: t, method: "GET")).id) + } else if t.hasPrefix("{") || t.hasPrefix("[") || t.hasPrefix("openapi:") || t.hasPrefix("swagger:") { + importing = ImportTarget(text: t) + } else { + requestText = t + showRequestFromText = true + } + } + } + /// hitop://runs (the failing widget) and hitop://run/ (the last-run widget, the /// Live Activity). func open(url: URL) { diff --git a/ios/HITOP/App/Core/Runs.swift b/ios/HITOP/App/Core/Runs.swift index 1bd5da7..dd7735c 100644 --- a/ios/HITOP/App/Core/Runs.swift +++ b/ios/HITOP/App/Core/Runs.swift @@ -275,6 +275,7 @@ extension Sender { options.overrides = row ?? [:] let steps = await runner.run(kit, environment: env, secrets: secrets, options: options) { onStep($0) } builder.iteration(data: row, steps: steps) + if Task.isCancelled { break } if bail && steps.contains(where: { !$0.passed }) { bailed = steps.count < runnable || round < rounds - 1 break @@ -289,6 +290,8 @@ enum RunEvent: Sendable { case started(ActiveRun) case progress(ActiveRun) case finished(ActiveRun, RunRecord) + /// Cancelled before its end: no record. + case stopped(ActiveRun) } /// The run going on now. @@ -362,6 +365,28 @@ final class RunCenter { continuation.finish() return report } + // A cancelled run (iOS took a background run's time back) ends after the request in flight. + // Not the stream's loop itself: what was done is still counted. + let record = await withTaskCancellationHandler { + await follow(stream, &run) + return RunRecord(collectionID: collectionID, report: await task.value) + } onCancel: { task.cancel() } + if Task.isCancelled { + active = nil + onEvent?(.stopped(run)) + return nil + } + run.progress.elapsedMs = record.durationMs + runs.insert(record, at: 0) + if runs.count > FileRunStore.limit { runs.removeLast(runs.count - FileRunStore.limit) } + persist() + lastFinished = record + active = nil + onEvent?(.finished(run, record)) + return record + } + + private func follow(_ stream: AsyncStream, _ run: inout ActiveRun) async { for await step in stream { run.progress.done += 1 if step.passed { run.progress.passed += 1 } else { run.progress.failed += 1 } @@ -372,16 +397,6 @@ final class RunCenter { active = run onEvent?(.progress(run)) } - let report = await task.value - let record = RunRecord(collectionID: collectionID, report: report) - run.progress.elapsedMs = report.durationMs - runs.insert(record, at: 0) - if runs.count > FileRunStore.limit { runs.removeLast(runs.count - FileRunStore.limit) } - persist() - lastFinished = record - active = nil - onEvent?(.finished(run, record)) - return record } func delete(_ id: UInt64) { diff --git a/ios/HITOP/App/Core/Schedules.swift b/ios/HITOP/App/Core/Schedules.swift new file mode 100644 index 0000000..6fa46e2 --- /dev/null +++ b/ios/HITOP/App/Core/Schedules.swift @@ -0,0 +1,140 @@ +import Foundation +import Observation + +/// A collection run every so often while HITOP is closed. iOS decides when: never before the time +/// is up, often much later. +struct RunSchedule: Codable, Hashable, Sendable, Identifiable { + var collectionID: UInt64 + /// nil: no environment. + var environmentID: String? + var everyMinutes: Int + /// The interval counts from here: when it was chosen, then when it last started. + var since: Date + /// Why the last one didn't finish. + var note: String? + var id: UInt64 { collectionID } + + var due: Date { since.addingTimeInterval(Double(everyMinutes) * 60) } + + static let choices: [(minutes: Int, name: String)] = [(60, "hour"), (360, "6 hours"), (1440, "day")] +} + +/// schedules.json (this device only, never synced). +protocol ScheduleStore: Sendable { + func load() throws -> [RunSchedule] + func save(_ list: [RunSchedule]) throws +} + +struct FileScheduleStore: ScheduleStore { + let file: URL + + init(root: URL) { file = root.appendingPathComponent("schedules.json") } + + func load() throws -> [RunSchedule] { try StateFileProblem.read([RunSchedule].self, file) ?? [] } + + func save(_ list: [RunSchedule]) throws { + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(list).write(to: file, options: [.atomic]) + } +} + +/// The schedules and what is due. +@MainActor +@Observable +final class Schedules { + private(set) var list: [RunSchedule] = [] + @ObservationIgnored let store: ScheduleStore + @ObservationIgnored let runs: RunCenter + @ObservationIgnored private var usable = false + /// The system's timer is set again after every change. + @ObservationIgnored var onChange: (@MainActor () -> Void)? + + init(store: ScheduleStore, runs: RunCenter) { + self.store = store + self.runs = runs + load() + } + + /// A file that can't be opened now is read again later; a damaged one is replaced by the next change. + private func load() { + do { + list = try store.load() + usable = true + } catch { + usable = error as? StateFileProblem == .damaged + } + } + + func schedule(of collectionID: UInt64) -> RunSchedule? { list.first { $0.collectionID == collectionID } } + + func set(_ collectionID: UInt64, environmentID: String?, everyMinutes: Int?, now: Date = Date()) throws { + if !usable { load() } + guard usable else { throw StateFileProblem.unreadable } + var next = list.filter { $0.collectionID != collectionID } + if let m = everyMinutes { next.append(RunSchedule(collectionID: collectionID, environmentID: environmentID, everyMinutes: m, since: now)) } + try store.save(next) + list = next + onChange?() + } + + private func change(_ id: UInt64, _ f: (inout RunSchedule) -> Void) throws { + guard let i = list.firstIndex(where: { $0.collectionID == id }) else { return } + var next = list + f(&next[i]) + try store.save(next) + list = next + } + + /// When the next one may run; nil: none. + var next: Date? { list.map(\.due).min() } + + /// Runs what is due, the longest waiting first, and stops when the task is cancelled. `fits` + /// leaves out those that won't finish in the time there is. Each counts as started before its + /// first request, so one iOS stops isn't sent again at once. + func runDue(now: Date = Date(), fits: (RunSchedule) -> Bool = { _ in true }) async -> [RunRecord] { + if !usable { load() } + guard usable, runs.model.store.unreadableFiles.isEmpty else { return [] } + var records: [RunRecord] = [] + for s in list.filter({ $0.due <= now }).sorted(by: { $0.due < $1.due }) { + if Task.isCancelled || runs.isRunning { break } + guard fits(s) else { continue } + guard runs.model.collection(s.collectionID) != nil else { + try? set(s.collectionID, environmentID: nil, everyMinutes: nil) + continue + } + if let problem = problem(s) { + try? change(s.collectionID) { $0.note = problem; $0.since = now } + continue + } + // Not written down: it would run again and again. + do { try change(s.collectionID) { $0.since = now; $0.note = nil } } catch { break } + if let r = await runs.start(collectionID: s.collectionID, settings: RunSettings(environmentID: s.environmentID)) { + records.append(r) + } else { + try? change(s.collectionID) { $0.note = "iOS stopped the last scheduled run before it finished." } + } + } + onChange?() + return records + } + + /// Why it can't run as it was set up: never with other values than the ones it was meant for. + private func problem(_ s: RunSchedule) -> String? { + let m = runs.model + var envs = [(globalsVaultID, m.globals)] + if let id = s.environmentID { + guard let e = m.environments.first(where: { $0.id == id }) else { return "The environment it runs with is gone: choose the schedule again." } + envs.append((e.id, e)) + } + for (vault, e) in envs { + for n in e.secrets where !readable(m, vault, n) { + return "The Keychain couldn't be read for the last scheduled run." + } + } + return nil + } + + private func readable(_ m: AppModel, _ vault: String, _ name: String) -> Bool { + do { _ = try m.vault.read(environment: vault, name: name); return true } catch { return false } + } +} diff --git a/ios/HITOP/App/Core/Secrets.swift b/ios/HITOP/App/Core/Secrets.swift index 05159e5..54bed6d 100644 --- a/ios/HITOP/App/Core/Secrets.swift +++ b/ios/HITOP/App/Core/Secrets.swift @@ -6,9 +6,13 @@ import HitopKit protocol SecretVault: Sendable { func value(environment: String, name: String) -> String? func setValue(_ value: String?, environment: String, name: String) + /// `value`, but a vault that can't be read now throws (it isn't "no value"). + func read(environment: String, name: String) throws -> String? } extension SecretVault { + func read(environment: String, name: String) throws -> String? { value(environment: environment, name: name) } + static func account(_ environment: String, _ name: String) -> String { "ios/\(environment)/\(name)" } } @@ -21,6 +25,8 @@ struct KeychainVault: SecretVault { (try? store.get(account: Self.account(environment, name))) ?? nil } + func read(environment: String, name: String) throws -> String? { try store.get(account: Self.account(environment, name)) } + func setValue(_ value: String?, environment: String, name: String) { let account = Self.account(environment, name) if let value, !value.isEmpty { diff --git a/ios/HITOP/App/Core/Settings.swift b/ios/HITOP/App/Core/Settings.swift index 1d39886..e0f36ac 100644 --- a/ios/HITOP/App/Core/Settings.swift +++ b/ios/HITOP/App/Core/Settings.swift @@ -30,6 +30,8 @@ struct AppSettings: Codable, Hashable, Sendable { var timeout = 60 var authorities: [Authority] = [] var clientCertificates: [ClientCertificate] = [] + /// HITOP Cloud also syncs while the app is closed. + var backgroundSync = true static let timeouts = [10, 30, 60, 120, 300] @@ -40,6 +42,7 @@ struct AppSettings: Codable, Hashable, Sendable { timeout = min(600, max(1, c.value("timeout", 60))) authorities = c.value("authorities", []) clientCertificates = c.value("clientCertificates", []) + backgroundSync = c.value("backgroundSync", true) } /// A host as people type it ("https://API.example:8443/x" → "api.example"). diff --git a/ios/HITOP/App/Core/SharedInbox.swift b/ios/HITOP/App/Core/SharedInbox.swift new file mode 100644 index 0000000..46d223c --- /dev/null +++ b/ios/HITOP/App/Core/SharedInbox.swift @@ -0,0 +1,84 @@ +import Foundation + +/// What another app shared to HITOP: the share extension leaves it in the app group's folder, the +/// app takes it when it comes to the screen. Self-contained (compiled into the extension too). +struct SharedInbox: Sendable { + static let maxBytes = 25 * 1024 * 1024 + /// Nobody opened HITOP after sharing this many times. + static let maxItems = 20 + + enum Item: Equatable, Sendable { + case text(String) + /// A copy outside the inbox, its own folder, the name as shared. + case file(URL) + } + + struct Failure: Error, LocalizedError, Equatable { + var message: String + var errorDescription: String? { message } + } + + let folder: URL + + init(root: URL) { folder = root.appendingPathComponent("inbox", isDirectory: true) } + + /// A name that stays in its folder. + static func safe(_ name: String) -> String { + let n = name.components(separatedBy: CharacterSet(charactersIn: "/\\:\0").union(.controlCharacters)).joined(separator: "-") + .trimmingCharacters(in: .whitespacesAndNewlines) + let cut = String(n.suffix(100)) + return cut.isEmpty || cut.allSatisfy({ $0 == "." }) ? "file" : cut + } + + private func entries() -> [URL] { + let all = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? [] + return all.filter { !$0.lastPathComponent.hasPrefix(".") }.sorted { $0.lastPathComponent < $1.lastPathComponent } + } + + /// Written beside and moved in, so a half-written item is never taken. + private func put(_ kind: String, _ name: String, _ write: (URL) throws -> Void) throws { + let fm = FileManager.default + guard entries().count < Self.maxItems else { throw Failure(message: "HITOP has \(Self.maxItems) shared items waiting. Open it first.") } + try fm.createDirectory(at: folder, withIntermediateDirectories: true) + let id = String(format: "%015.0f", Date().timeIntervalSince1970 * 1000) + "-" + UUID().uuidString + let part = folder.appendingPathComponent(".\(id)", isDirectory: true) + let content = part.appendingPathComponent(kind, isDirectory: true) + do { + try fm.createDirectory(at: content, withIntermediateDirectories: true) + try write(content.appendingPathComponent(name)) + try fm.moveItem(at: part, to: folder.appendingPathComponent(id, isDirectory: true)) + } catch { + try? fm.removeItem(at: part) + throw error + } + } + + func add(text: String) throws { + let t = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !t.isEmpty else { throw Failure(message: "There is no text in it.") } + guard t.utf8.count <= Self.maxBytes else { throw Failure(message: "It is larger than 25 MB.") } + try put("text", "text") { try Data(t.utf8).write(to: $0) } + } + + func add(file: URL, name: String? = nil) throws { + let v = try file.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]) + guard v.isRegularFile == true, let size = v.fileSize else { throw Failure(message: "HITOP takes files, not folders.") } + guard size <= Self.maxBytes else { throw Failure(message: "The file is larger than 25 MB.") } + try put("file", Self.safe(name ?? file.lastPathComponent)) { try FileManager.default.copyItem(at: file, to: $0) } + } + + /// The oldest item, taken out (an unusable one is dropped); nil when there is none. + func take() -> Item? { + let fm = FileManager.default + for e in entries() { + defer { try? fm.removeItem(at: e) } + if let data = try? Data(contentsOf: e.appendingPathComponent("text/text")) { return .text(String(decoding: data, as: UTF8.self)) } + guard let f = (try? fm.contentsOfDirectory(at: e.appendingPathComponent("file"), includingPropertiesForKeys: nil))?.first else { continue } + let to = fm.temporaryDirectory.appendingPathComponent("shared-\(UUID().uuidString)/Inbox", isDirectory: true) + guard (try? fm.createDirectory(at: to, withIntermediateDirectories: true)) != nil else { continue } + let copy = to.appendingPathComponent(f.lastPathComponent) + if (try? fm.moveItem(at: f, to: copy)) != nil { return .file(copy) } + } + return nil + } +} diff --git a/ios/HITOP/App/Core/SharedSync.swift b/ios/HITOP/App/Core/SharedSync.swift index 64fde91..c038124 100644 --- a/ios/HITOP/App/Core/SharedSync.swift +++ b/ios/HITOP/App/Core/SharedSync.swift @@ -43,8 +43,60 @@ struct SharedState: Codable, Hashable, Sendable { var shareVersions: [String: [String: Int]] = [:] } +// A key another version didn't write takes its default; a wrong type is a damaged file. +extension SharedLink { + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.init(workspace: try c.decode(String.self, forKey: .workspace), role: try c.decode(String.self, forKey: .role), + org: try c.decodeIfPresent(String.self, forKey: .org), orgName: try c.decodeIfPresent(String.self, forKey: .orgName), + orgPersonal: try c.decodeIfPresent(Bool.self, forKey: .orgPersonal) ?? false, gone: try c.decodeIfPresent(Bool.self, forKey: .gone) ?? false) + } +} + +extension SharedState { + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.init(account: try c.decodeIfPresent(String.self, forKey: .account) ?? "", + pins: try c.decodeIfPresent([String: String].self, forKey: .pins) ?? [:], + memory: try c.decodeIfPresent([String: JSONAny].self, forKey: .memory) ?? [:], + links: try c.decode([String: SharedLink].self, forKey: .links), + states: try c.decodeIfPresent([String: JSONAny].self, forKey: .states) ?? [:], + shareVersions: try c.decodeIfPresent([String: [String: Int]].self, forKey: .shareVersions) ?? [:]) + } +} + +/// A sync's own file is there but can't be used. Never taken as empty: without the list of shared +/// collections an end-to-end encrypted one would look like any other, and go to the library, +/// which the server can read. +enum StateFileProblem: Error, Equatable { + /// Can't be opened now (the phone hasn't been unlocked since it started): later. + case unreadable + /// Holds something else. + case damaged + + /// The file's value; nil when there is no file. + static func read(_ type: T.Type, _ file: URL) throws -> T? { + let data: Data + do { + data = try Data(contentsOf: file) + } catch { + if FileManager.default.fileExists(atPath: file.path) { throw StateFileProblem.unreadable } + return nil + } + do { return try JSONDecoder().decode(type, from: data) } catch { throw StateFileProblem.damaged } + } + + static func setAside(_ file: URL) throws { + let stamp = Int(Date().timeIntervalSince1970 * 1000) + try FileManager.default.moveItem(at: file, to: file.appendingPathExtension("damaged-\(stamp)")) + } +} + protocol SharedSyncStore: Sendable { - func load() -> SharedState + /// Throws `StateFileProblem`. + func load() throws -> SharedState + /// A damaged file out of the way, kept beside. + func setAsideDamaged() throws func save(_ state: SharedState) throws func files(_ workspace: String) -> [String: String] func saveFiles(_ workspace: String, _ files: [String: String]) throws @@ -57,10 +109,9 @@ struct FileSharedSyncStore: SharedSyncStore { private var stateFile: URL { root.appendingPathComponent("shared-sync.json") } private func filesURL(_ ws: String) -> URL { root.appendingPathComponent("shared").appendingPathComponent("\(ws).json") } - func load() -> SharedState { - guard let data = try? Data(contentsOf: stateFile) else { return SharedState() } - return (try? JSONDecoder().decode(SharedState.self, from: data)) ?? SharedState() - } + func load() throws -> SharedState { try StateFileProblem.read(SharedState.self, stateFile) ?? SharedState() } + + func setAsideDamaged() throws { try StateFileProblem.setAside(stateFile) } func save(_ state: SharedState) throws { let e = JSONEncoder() @@ -91,7 +142,8 @@ final class MemorySharedSyncStore: SharedSyncStore, @unchecked Sendable { init() {} - func load() -> SharedState { lock.lock(); defer { lock.unlock() }; return state } + func load() throws -> SharedState { lock.lock(); defer { lock.unlock() }; return state } + func setAsideDamaged() throws {} func save(_ s: SharedState) throws { lock.lock(); defer { lock.unlock() }; state = s } func files(_ ws: String) -> [String: String] { lock.lock(); defer { lock.unlock() }; return all[ws] ?? [:] } func saveFiles(_ ws: String, _ files: [String: String]) throws { lock.lock(); defer { lock.unlock() }; all[ws] = files } @@ -244,15 +296,36 @@ final class SharedSync { self.cloud = cloud self.model = model self.store = store - state = store.load() + state = SharedState() + loadState() model.onSharedChange = { [weak self] id in self?.schedule(id) } model.onCollectionDeleted = { [weak self] id in self?.forget(id) } cloud.onAccountDeleted = { [weak self] a in self?.accountDeleted(a) } + model.reloadSharing = { [weak self] in self?.loadState() } + model.startSharingOver = { [weak self] in + guard let self, model.sharingProblem == .damaged else { return } + try store.setAsideDamaged() + loadState() + notices.insert(SharedNotice("The list of shared collections on this device was damaged", detail: "Their copies here are kept on this device only. Open them again under Shared with you."), at: 0) + } + applyRoles() + } + + private func loadState() { + do { + state = try store.load() + model.sharingProblem = nil + } catch { + state = SharedState() + model.sharingProblem = error as? StateFileProblem ?? .unreadable + } applyRoles() + conflicts = [:] for (id, l) in state.links { if let cid = UInt64(id) { conflicts[cid] = conflictList(cid, l) } } } private func save() { + guard model.sharingProblem == nil else { return } try? store.save(state) } @@ -296,7 +369,8 @@ final class SharedSync { /// device's own key is pinned (it authenticates the wraps it makes and opens its own). @discardableResult func checkAccount() -> Bool { - guard let a = cloud.account, let secret = cloud.credentials.load(a.server)?.secret else { return false } + if model.sharingProblem == .unreadable { loadState() } + guard model.sharingProblem == nil, let a = cloud.account, let secret = cloud.credentials.load(a.server)?.secret else { return false } let key = cloud.accountKey if state.account != key { if !state.account.isEmpty { diff --git a/ios/HITOP/App/HITOPApp.swift b/ios/HITOP/App/HITOPApp.swift index a5ee7ea..656540a 100644 --- a/ios/HITOP/App/HITOPApp.swift +++ b/ios/HITOP/App/HITOPApp.swift @@ -11,6 +11,8 @@ struct HITOPApp: App { @State private var cloudUI: CloudUI @State private var shared: SharedSync @State private var runs: RunCenter + @State private var schedules: Schedules + private let background: Background @State private var ai: Intelligence private let system: SystemBridge /// UI tests of shared collections: the scenario prepared before the first sync. @@ -27,12 +29,13 @@ struct HITOPApp: App { let syncState: LibrarySyncStateStore let sharedStore: SharedSyncStore let runStore: RunStore + let root: URL if uiTest { // UI tests and screenshots: a fresh library, the shop-api sample, secrets in memory and // every request answered in-process by StubURLProtocol (no network), HITOP Cloud // included (FakeCloud at cloud.hitop.test, signed out, the provider page approving at once). StubURLProtocol.enabled = true - let root = FileManager.default.temporaryDirectory.appendingPathComponent("hitop-uitest-\(UUID().uuidString)") + root = FileManager.default.temporaryDirectory.appendingPathComponent("hitop-uitest-\(UUID().uuidString)") var sender = Sender(configuration: StubURLProtocol.configuration) sender.uploads = Uploads(root: root) sender.settings = SettingsStore(root: root) @@ -60,7 +63,7 @@ struct HITOPApp: App { sharedStore = MemorySharedSyncStore() runStore = FileRunStore(root: root) } else { - let root = FileLibraryStore.defaultRoot() + root = FileLibraryStore.defaultRoot() var sender = Sender() sender.browser = SystemOAuthBrowser() sender.uploads = Uploads(root: root) @@ -86,14 +89,21 @@ struct HITOPApp: App { scenario = uiTest ? ["-UITestSharedInvite", "-UITestSharedJoined"].first { args.contains($0) } : nil _model = State(initialValue: model) _cloud = State(initialValue: cloud) - _sync = State(initialValue: LibrarySync(cloud: cloud, model: model, stateStore: syncState, deviceLabel: DeviceInfo.label)) + let sync = LibrarySync(cloud: cloud, model: model, stateStore: syncState, deviceLabel: DeviceInfo.label) + _sync = State(initialValue: sync) _cloudUI = State(initialValue: CloudUI(web: web)) - _shared = State(initialValue: SharedSync(cloud: cloud, model: model, store: sharedStore)) + let shared = SharedSync(cloud: cloud, model: model, store: sharedStore) + _shared = State(initialValue: shared) let runs = RunCenter(model: model, store: runStore) _runs = State(initialValue: runs) + let schedules = Schedules(store: FileScheduleStore(root: root), runs: runs) + _schedules = State(initialValue: schedules) system = SystemBridge(model: model, runs: runs) // UI tests: no Live Activity over the screenshots, no snapshot for the real widgets. system.liveActivities = !uiTest + background = Background(model: model, cloud: cloud, sync: sync, shared: shared, schedules: schedules, system: system, nav: nav) + // UI tests never sync or run by themselves. + if !uiTest { background.register() } IntentBridge.services = IntentBridge.Services(model: model, runs: runs, system: system, nav: nav) Self.styleNavigationBars() } @@ -130,6 +140,8 @@ struct HITOPApp: App { .environment(sync) .environment(cloudUI) .environment(runs) + .environment(schedules) + .environment(\.backgroundWork, background) .environment(ai) .onOpenURL { nav.open(url: $0) } .preferredColorScheme(.dark) diff --git a/ios/HITOP/App/Info.plist b/ios/HITOP/App/Info.plist index fd3abf8..ce1f6db 100644 --- a/ios/HITOP/App/Info.plist +++ b/ios/HITOP/App/Info.plist @@ -68,6 +68,16 @@ NSLocalNetworkUsageDescription HITOP sends the requests you write, including to servers on your local network. + UIBackgroundModes + + fetch + processing + + BGTaskSchedulerPermittedIdentifiers + + hitop.rws8.tech.HiTop.sync + hitop.rws8.tech.HiTop.runs + NSSupportsLiveActivities CFBundleDocumentTypes diff --git a/ios/HITOP/App/Platform/Background.swift b/ios/HITOP/App/Platform/Background.swift new file mode 100644 index 0000000..37f908a --- /dev/null +++ b/ios/HITOP/App/Platform/Background.swift @@ -0,0 +1,162 @@ +import BackgroundTasks +import SwiftUI +import UIKit +import UserNotifications + +/// Work while HITOP is closed: HITOP Cloud's sync (an app refresh, seconds long) and scheduled runs +/// (a processing task, minutes long; a run known to be short also in a refresh). iOS decides when. +@MainActor +final class Background: NSObject, UNUserNotificationCenterDelegate { + static let sync = "hitop.rws8.tech.HiTop.sync" + static let runs = "hitop.rws8.tech.HiTop.runs" + /// A refresh has about 30 seconds. + static let shortRunMs = 8000 + + private let model: AppModel + private let cloud: HitopCloud + private let library: LibrarySync + private let shared: SharedSync + private let schedules: Schedules + private let system: SystemBridge + private let nav: Navigator + private var registered = false + private var leaving = UIBackgroundTaskIdentifier.invalid + + init(model: AppModel, cloud: HitopCloud, sync: LibrarySync, shared: SharedSync, schedules: Schedules, system: SystemBridge, nav: Navigator) { + self.model = model + self.cloud = cloud + library = sync + self.shared = shared + self.schedules = schedules + self.system = system + self.nav = nav + } + + /// Once, before the app has finished launching. + func register() { + registered = true + UNUserNotificationCenter.current().delegate = self + schedules.onChange = { [weak self] in self?.plan() } + for id in [Self.sync, Self.runs] { + BGTaskScheduler.shared.register(forTaskWithIdentifier: id, using: .main) { @Sendable [weak self] task in + // Called on the main queue, as asked. + nonisolated(unsafe) let t = task + MainActor.assumeIsolated { self?.begin(t, id) } + } + } + } + + private func begin(_ task: BGTask, _ id: String) { + // The next one first: iOS may end this one at any time. + plan() + let work = Task { @MainActor in + if id == Self.sync { + await syncNow() + await runDue { s in self.schedules.runs.lastRun(of: s.collectionID).map { $0.durationMs < Self.shortRunMs } ?? false } + } else { + await runDue() + } + } + task.expirationHandler = { @Sendable in work.cancel() } + nonisolated(unsafe) let t = task + Task { @MainActor in + await work.value + t.setTaskCompleted(success: !work.isCancelled) + } + } + + private var syncs: Bool { cloud.signedIn && (model.sender.settings?.shown.backgroundSync ?? true) } + + private func syncNow() async { + guard syncs else { return } + await library.sync() + if Task.isCancelled { return } + await shared.syncAll() + system.refreshWidgets() + } + + private func runDue(_ fits: @escaping (RunSchedule) -> Bool = { _ in true }) async { + for r in await schedules.runDue(fits: fits) where !r.passed { await notify(r) } + } + + /// Asks iOS for the next times. + func plan() { + guard registered else { return } + let scheduler = BGTaskScheduler.shared + scheduler.cancel(taskRequestWithIdentifier: Self.sync) + scheduler.cancel(taskRequestWithIdentifier: Self.runs) + let due = schedules.next + if syncs || due != nil { + let r = BGAppRefreshTaskRequest(identifier: Self.sync) + let sync = syncs ? Date(timeIntervalSinceNow: library.dirty ? 15 * 60 : 6 * 3600) : .distantFuture + r.earliestBeginDate = min(sync, due ?? .distantFuture) + try? scheduler.submit(r) + } + if let due { + let r = BGProcessingTaskRequest(identifier: Self.runs) + r.requiresNetworkConnectivity = true + r.earliestBeginDate = due + try? scheduler.submit(r) + } + } + + /// The app left the screen: what waits for HITOP Cloud goes now if it can, the rest later. + func left() { + guard registered else { return } + plan() + guard cloud.signedIn, library.dirty else { return } + let push = Task { @MainActor in + await library.flush() + await shared.flush() + plan() + endLeaving() + } + guard leaving == .invalid else { return } + leaving = UIApplication.shared.beginBackgroundTask { [weak self] in + push.cancel() + self?.endLeaving() + } + } + + private func endLeaving() { + guard leaving != .invalid else { return } + UIApplication.shared.endBackgroundTask(leaving) + leaving = .invalid + } + + // MARK: Notifications + + /// Whether failed runs may be shown; asks the first time. + static func askToNotify() async -> Bool { + if ProcessInfo.processInfo.arguments.contains("-UITestSeed") { return true } + return (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound])) ?? false + } + + private func notify(_ r: RunRecord) async { + let c = UNMutableNotificationContent() + c.title = "\(r.collectionName): \(r.requestsPassed) of \(r.requestsTotal) passed" + c.body = r.firstFailure ?? "The scheduled run failed." + c.userInfo = ["collection": String(r.collectionID)] + // One per collection: the newest failure replaces the one before. + try? await UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "run-\(r.collectionID)", content: c, trigger: nil)) + } + + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { + let id = (response.notification.request.content.userInfo["collection"] as? String).flatMap(UInt64.init) + await MainActor.run { + guard let id, let url = URL(string: "hitop://run/\(id)") else { return } + nav.open(url: url) + } + } +} + +private struct BackgroundWorkKey: EnvironmentKey { + static let defaultValue: Background? = nil +} + +extension EnvironmentValues { + var backgroundWork: Background? { + get { self[BackgroundWorkKey.self] } + set { self[BackgroundWorkKey.self] = newValue } + } +} diff --git a/ios/HITOP/App/UI/ImportViews.swift b/ios/HITOP/App/UI/ImportViews.swift index 8c44d0d..f6e2f27 100644 --- a/ios/HITOP/App/UI/ImportViews.swift +++ b/ios/HITOP/App/UI/ImportViews.swift @@ -56,6 +56,7 @@ struct ImportSheet: View { case let .failure(e): failure = e.localizedDescription } } + .task { if let t = target.text, plan == nil { text = t; readText() } } .task { if let f = target.file, plan == nil { readFile(f) } } } diff --git a/ios/HITOP/App/UI/IntelligenceViews.swift b/ios/HITOP/App/UI/IntelligenceViews.swift index 46aea51..cf2734e 100644 --- a/ios/HITOP/App/UI/IntelligenceViews.swift +++ b/ios/HITOP/App/UI/IntelligenceViews.swift @@ -289,6 +289,10 @@ struct RequestFromTextSheet: View { .padding(16) } .background(Theme.ground.ignoresSafeArea()) + .onAppear { + if text.isEmpty { text = nav.requestText } + nav.requestText = "" + } .navigationTitle("New request from text") .navigationBarTitleDisplayMode(.inline) .toolbar { diff --git a/ios/HITOP/App/UI/RootView.swift b/ios/HITOP/App/UI/RootView.swift index 0212d0e..c5abd23 100644 --- a/ios/HITOP/App/UI/RootView.swift +++ b/ios/HITOP/App/UI/RootView.swift @@ -8,6 +8,7 @@ struct RootView: View { @Environment(HitopCloud.self) private var cloud @Environment(LibrarySync.self) private var sync @Environment(SharedSync.self) private var shared + @Environment(\.backgroundWork) private var background var body: some View { @Bindable var nav = nav @@ -28,6 +29,7 @@ struct RootView: View { .onChange(of: sizeClass) { _, c in nav.isPad = c == .regular } // HITOP Cloud: pull on launch and whenever the app comes to the foreground. .task { + takeShared() applyScope() await sync.sync() if cloud.signedIn { _ = try? await cloud.loadOrgs() } @@ -38,8 +40,10 @@ struct RootView: View { .onChange(of: scenePhase) { _, phase in // Widgets and intents see what changed here (pins, environment, sends) when the app leaves. if phase != .active { sync.model.saveDrafts() } + if phase == .background { background?.left() } if phase == .background { IntentBridge.services?.system.refreshWidgets() } if phase == .active { + takeShared() if model.sender.settings?.problem != nil { model.sender.settings?.load() } Task { await sync.sync() @@ -53,6 +57,13 @@ struct RootView: View { } } + /// What the share extension left: one at a time, when no sheet is in the way. + private func takeShared() { + guard nav.importing == nil, !nav.showRequestFromText, nav.runSheet == nil, !nav.showAccount, !nav.showAbout, + model.store.unreadableFiles.isEmpty, let root = SharedContainer.directory(), let item = SharedInbox(root: root).take() else { return } + nav.receive(item, model) + } + /// Collections shows the current organization's collections (the web app's `visibleCollections`). private func applyScope() { model.orgScope = cloud.signedIn && !cloud.settings.orgs.isEmpty ? OrgScope(current: cloud.settings.org, personal: cloud.personalOrg?.id) : nil diff --git a/ios/HITOP/App/UI/RunsScreen.swift b/ios/HITOP/App/UI/RunsScreen.swift index 69b16eb..df54c97 100644 --- a/ios/HITOP/App/UI/RunsScreen.swift +++ b/ios/HITOP/App/UI/RunsScreen.swift @@ -264,6 +264,7 @@ struct RunSheet: View { .padding(.horizontal, 14) .card(radius: 18) if let dataError { Text(dataError).font(Typo.caption).foregroundStyle(Theme.danger).accessibilityIdentifier("run-data-error") } + ScheduleCard(collectionID: target.id, environmentID: settings.environmentID) if let last = runs.lastRun(of: target.id) { NavigationLink(value: RunRoute.report(last.id)) { HStack { Text("Last run").foregroundStyle(Theme.textSoft); Spacer(); RunRow(record: last) } @@ -591,3 +592,54 @@ struct RunReportView: View { } } } + +/// Runs on a schedule, while HITOP is closed. +struct ScheduleCard: View { + var collectionID: UInt64 + var environmentID: String? + @Environment(AppModel.self) private var model + @Environment(Schedules.self) private var schedules + @State private var failure: String? + @State private var silent = false + + private var mine: RunSchedule? { schedules.schedule(of: collectionID) } + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Picker(selection: Binding(get: { mine?.everyMinutes ?? 0 }, set: choose)) { + Text("Off").tag(0) + ForEach(RunSchedule.choices, id: \.minutes) { c in Text("Every \(c.name)").tag(c.minutes) } + } label: { + Label("Run on a schedule", systemImage: "calendar.badge.clock").foregroundStyle(Theme.text) + } + .frame(minHeight: 48) + .accessibilityIdentifier("run-schedule") + Text(words).font(Typo.caption).foregroundStyle(Theme.textMuted).accessibilityIdentifier("run-schedule-text") + if let note = mine?.note { Text(note).font(Typo.caption).foregroundStyle(Theme.warning) } + if silent && mine != nil { Text("Notifications are off for HITOP: failed runs only show in Runs.").font(Typo.caption).foregroundStyle(Theme.warning) } + if let failure { Text(failure).font(Typo.caption).foregroundStyle(Theme.danger) } + } + .font(Typo.row) + .tint(Theme.success) + .padding(.horizontal, 14) + .padding(.bottom, 12) + .card(radius: 18) + } + + private var words: String { + guard let mine else { return "Runs in the background while HITOP is closed, and tells you when one fails." } + let env = mine.environmentID.map { id in model.environments.first { $0.id == id }?.name ?? "a deleted environment" } ?? "no environment" + return "With \(env). Not before the time is up; iOS decides when, often much later." + } + + private func choose(_ minutes: Int) { + failure = nil + do { + try schedules.set(collectionID, environmentID: environmentID, everyMinutes: minutes == 0 ? nil : minutes) + } catch { + failure = "The schedule couldn't be saved: \(error.localizedDescription)" + return + } + if minutes > 0 { Task { silent = !(await Background.askToNotify()) } } + } +} diff --git a/ios/HITOP/App/UI/SettingsView.swift b/ios/HITOP/App/UI/SettingsView.swift index a3e06bd..cedecb0 100644 --- a/ios/HITOP/App/UI/SettingsView.swift +++ b/ios/HITOP/App/UI/SettingsView.swift @@ -49,6 +49,16 @@ struct SettingsView: View { .accessibilityIdentifier("settings-timeout") } .listRowBackground(Theme.surface) + Section { + Toggle("Sync in the background", isOn: Binding(get: { store.shown.backgroundSync }, set: { on in attempt { try store.update { $0.backgroundSync = on } } })) + .tint(Theme.success) + .accessibilityIdentifier("settings-background-sync") + } header: { + Text("HITOP Cloud") + } footer: { + Text("While you are signed in. iOS decides when, often a few times a day.") + } + .listRowBackground(Theme.surface) Section { ForEach(store.shown.authorities) { a in row(a.name, nil) { attempt { try store.update { $0.authorities.removeAll { $0.id == a.id } } } } diff --git a/ios/HITOP/App/UI/SystemBridge.swift b/ios/HITOP/App/UI/SystemBridge.swift index 0c80ec7..7390ceb 100644 --- a/ios/HITOP/App/UI/SystemBridge.swift +++ b/ios/HITOP/App/UI/SystemBridge.swift @@ -63,6 +63,12 @@ final class SystemBridge { self.activity = nil } refreshWidgets() + case let .stopped(run): + guard let activity else { return } + let content = ActivityContent(state: Self.state(run, finished: true), staleDate: nil) + nonisolated(unsafe) let a = activity + Task { await a.end(content, dismissalPolicy: .immediate) } + self.activity = nil } } diff --git a/ios/HITOP/Share/HITOPShare.entitlements b/ios/HITOP/Share/HITOPShare.entitlements new file mode 100644 index 0000000..5cd963f --- /dev/null +++ b/ios/HITOP/Share/HITOPShare.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.hitop.rws8.tech.HiTop + + + diff --git a/ios/HITOP/Share/Info.plist b/ios/HITOP/Share/Info.plist new file mode 100644 index 0000000..ebb8d75 --- /dev/null +++ b/ios/HITOP/Share/Info.plist @@ -0,0 +1,43 @@ + + + + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleName + $(PRODUCT_NAME) + CFBundleDisplayName + HITOP + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleDevelopmentRegion + en + NSExtension + + NSExtensionPointIdentifier + com.apple.share-services + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionAttributes + + NSExtensionActivationRule + + NSExtensionActivationSupportsText + + NSExtensionActivationSupportsWebURLWithMaxCount + 1 + NSExtensionActivationSupportsFileWithMaxCount + 1 + + + + + diff --git a/ios/HITOP/Share/ShareViewController.swift b/ios/HITOP/Share/ShareViewController.swift new file mode 100644 index 0000000..e33bd6d --- /dev/null +++ b/ios/HITOP/Share/ShareViewController.swift @@ -0,0 +1,91 @@ +import UIKit +import UniformTypeIdentifiers + +/// "HITOP" in the share sheet: keeps what was shared for the app, which takes it when it opens (an +/// extension can't open its app). Nothing is sent anywhere. +final class ShareViewController: UIViewController { + private let label = UILabel() + private let detail = UILabel() + private let done = UIButton(configuration: .borderedProminent()) + private var started = false + + override func viewDidLoad() { + super.viewDidLoad() + overrideUserInterfaceStyle = .dark + view.backgroundColor = .systemBackground + label.font = .preferredFont(forTextStyle: .headline) + detail.font = .preferredFont(forTextStyle: .subheadline) + detail.textColor = .secondaryLabel + for l in [label, detail] { + l.adjustsFontForContentSizeCategory = true + l.numberOfLines = 0 + l.textAlignment = .center + } + label.text = "Adding to HITOP…" + done.setTitle("Done", for: .normal) + done.addAction(UIAction { [weak self] _ in self?.extensionContext?.completeRequest(returningItems: nil) }, for: .touchUpInside) + let stack = UIStackView(arrangedSubviews: [label, detail, done]) + stack.axis = .vertical + stack.spacing = 16 + stack.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor, constant: 8), + stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor, constant: -8), + done.heightAnchor.constraint(greaterThanOrEqualToConstant: 48), + ]) + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + guard !started else { return } + started = true + keep() + } + + private func keep() { + guard let root = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.hitop.rws8.tech.HiTop") else { + return show("HITOP can't take this now", "Its shared folder isn't there.") + } + let inbox = SharedInbox(root: root) + let providers = (extensionContext?.inputItems ?? []).compactMap { $0 as? NSExtensionItem }.flatMap { $0.attachments ?? [] } + let finish: @Sendable ((any Error)?) -> Void = { [weak self] error in + DispatchQueue.main.async { + if let error { self?.show("HITOP can't take this", error.localizedDescription) } else { self?.show("Added", "Open HITOP to look at it and add it.") } + } + } + // A web address before its page's text, a file before its text. + if let p = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.url.identifier) && !$0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }) { + _ = p.loadObject(ofClass: URL.self) { url, error in + finish(Self.attempt(error) { if let url { try inbox.add(text: url.absoluteString) } }) + } + } else if let p = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) || ($0.suggestedName != nil && $0.hasItemConformingToTypeIdentifier(UTType.data.identifier)) }) { + let type = p.registeredTypeIdentifiers.first { $0 != UTType.fileURL.identifier } ?? UTType.data.identifier + let name = p.suggestedName + _ = p.loadFileRepresentation(forTypeIdentifier: type) { url, error in + // The file is there until this returns. + finish(Self.attempt(error) { + if let url { try inbox.add(file: url, name: name.map { url.pathExtension.isEmpty || $0.hasSuffix(".\(url.pathExtension)") ? $0 : "\($0).\(url.pathExtension)" }) } + }) + } + } else if let p = providers.first(where: { $0.canLoadObject(ofClass: String.self) }) { + _ = p.loadObject(ofClass: String.self) { text, error in + finish(Self.attempt(error) { if let text { try inbox.add(text: text) } }) + } + } else { + show("HITOP can't take this", "It takes text, addresses and files.") + } + } + + nonisolated private static func attempt(_ error: (any Error)?, _ work: () throws -> Void) -> (any Error)? { + if let error { return error } + do { try work(); return nil } catch { return error } + } + + private func show(_ title: String, _ text: String) { + label.text = title + detail.text = text + UIAccessibility.post(notification: .screenChanged, argument: label) + } +} diff --git a/ios/HITOP/UITests/WorkflowTests.swift b/ios/HITOP/UITests/WorkflowTests.swift index 426b118..ea53071 100644 --- a/ios/HITOP/UITests/WorkflowTests.swift +++ b/ios/HITOP/UITests/WorkflowTests.swift @@ -44,6 +44,27 @@ final class WorkflowTests: XCTestCase { wait(app.el("status")) } + @MainActor + func testARunIsPutOnASchedule() { + guard UIDevice.current.userInterfaceIdiom == .phone else { return } + let app = XCUIApplication.seeded() + app.launch() + app.tabBars.buttons["Runs"].tap() + let run = app.el("run-collection-shop-api") + wait(run) + run.tap() + let picker = app.el("run-schedule") + wait(picker) + if !picker.isHittable { app.swipeUp() } + picker.tap() + let hour = app.buttons["Every hour"].firstMatch + wait(hour) + hour.tap() + let chosen = expectation(for: NSPredicate(format: "label CONTAINS 'Not before the time is up'"), evaluatedWith: app.el("run-schedule-text")) + wait(for: [chosen], timeout: 15) + shot(app, "44-schedule") + } + @MainActor func testAFileRowAsksForItsFile() { guard UIDevice.current.userInterfaceIdiom == .phone else { return } diff --git a/ios/HITOP/UnitTests/BackgroundTests.swift b/ios/HITOP/UnitTests/BackgroundTests.swift new file mode 100644 index 0000000..e38fb97 --- /dev/null +++ b/ios/HITOP/UnitTests/BackgroundTests.swift @@ -0,0 +1,306 @@ +import Foundation +import HitopKit +import XCTest +@testable import HITOP + +/// Scheduled runs, what another app shared, and files that can't be used while nobody looks. +@MainActor +final class BackgroundTests: XCTestCase { + private var root: URL! + private var model: AppModel! + private var vault: BrokenVault! + private var runs: RunCenter! + + override func setUp() async throws { + StubURLProtocol.enabled = true + root = FileManager.default.temporaryDirectory.appendingPathComponent("background-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + vault = BrokenVault() + model = AppModel(store: MemoryLibraryStore(), vault: vault, sender: Sender(configuration: StubURLProtocol.configuration)) + model.load() + model.seed() + runs = RunCenter(model: model, store: MemoryRunStore()) + } + + override func tearDown() async throws { try? FileManager.default.removeItem(at: root) } + + private var shop: UInt64 { model.collections.first { $0.name == "shop-api" }!.id } + private func schedules() -> Schedules { Schedules(store: FileScheduleStore(root: root), runs: runs) } + + func testADueRunGoesOnceAndIsKept() async throws { + let s = schedules() + let start = Date(timeIntervalSince1970: 1_000_000) + try s.set(shop, environmentID: "env-staging", everyMinutes: 60, now: start) + XCTAssertEqual(schedules().list, s.list) + let early = await s.runDue(now: start.addingTimeInterval(3599)) + XCTAssertTrue(early.isEmpty) + let late = start.addingTimeInterval(3600) + let left = await s.runDue(now: late, fits: { _ in false }) + XCTAssertTrue(left.isEmpty) + let done = await s.runDue(now: late) + XCTAssertEqual(done.map(\.environmentName), ["Staging"]) + XCTAssertEqual(schedules().next, late.addingTimeInterval(3600)) + let again = await s.runDue(now: late) + XCTAssertTrue(again.isEmpty) + try s.set(shop, environmentID: nil, everyMinutes: nil) + XCTAssertNil(schedules().next) + } + + func testARunNeverGoesWithOtherValues() async throws { + let s = schedules() + let start = Date(timeIntervalSince1970: 1_000_000) + try s.set(shop, environmentID: "env-gone", everyMinutes: 60, now: start) + var r = await s.runDue(now: start.addingTimeInterval(7200)) + XCTAssertTrue(r.isEmpty) + XCTAssertTrue(s.schedule(of: shop)!.note!.contains("environment")) + try s.set(shop, environmentID: "env-staging", everyMinutes: 60, now: start) + vault.broken = true + r = await s.runDue(now: start.addingTimeInterval(7200)) + XCTAssertTrue(r.isEmpty) + XCTAssertTrue(s.schedule(of: shop)!.note!.contains("Keychain")) + XCTAssertTrue(runs.runs.isEmpty) + } + + func testACollectionThatIsGoneLosesItsSchedule() async throws { + let s = schedules() + try s.set(42, environmentID: nil, everyMinutes: 60, now: .distantPast) + let r = await s.runDue() + XCTAssertTrue(r.isEmpty) + XCTAssertTrue(s.list.isEmpty) + } + + func testAStoppedRunIsNotARecord() async throws { + let s = schedules() + let id = shop + try s.set(id, environmentID: "env-staging", everyMinutes: 60, now: .distantPast) + var stopped = false + var work: Task<[RunRecord], Never>? + runs.onEvent = { e in + if case .started = e { work?.cancel() } + if case .stopped = e { stopped = true } + } + work = Task { await s.runDue() } + let r = await work!.value + XCTAssertTrue(r.isEmpty) + XCTAssertTrue(stopped) + XCTAssertFalse(runs.isRunning) + XCTAssertTrue(runs.runs.isEmpty) + XCTAssertNotNil(s.schedule(of: id)!.note) + XCTAssertGreaterThan(s.schedule(of: id)!.due, Date()) + } + + func testADamagedScheduleFileIsReplacedByTheNextChange() throws { + try Data("{".utf8).write(to: root.appendingPathComponent("schedules.json")) + let s = schedules() + XCTAssertTrue(s.list.isEmpty) + try s.set(shop, environmentID: nil, everyMinutes: 60) + XCTAssertEqual(schedules().list.count, 1) + } + + // MARK: Shared to HITOP + + func testSharedItemsAreTakenOnceOldestFirst() throws { + let inbox = SharedInbox(root: root) + XCTAssertNil(inbox.take()) + try inbox.add(text: " curl https://api.example/x \n") + let f = root.appendingPathComponent("a.json") + try Data("[]".utf8).write(to: f) + Thread.sleep(forTimeInterval: 0.005) + try inbox.add(file: f, name: "../../b.json") + XCTAssertEqual(inbox.take(), .text("curl https://api.example/x")) + guard case let .file(url)? = inbox.take() else { return XCTFail("no file") } + XCTAssertEqual(url.lastPathComponent, "..-..-b.json") + XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "[]") + XCTAssertNil(inbox.take()) + XCTAssertTrue(FileManager.default.fileExists(atPath: f.path)) + try? FileManager.default.removeItem(at: url.deletingLastPathComponent().deletingLastPathComponent()) + } + + func testWhatCannotBeShared() throws { + let inbox = SharedInbox(root: root) + XCTAssertThrowsError(try inbox.add(text: " \n")) + XCTAssertThrowsError(try inbox.add(file: root)) + XCTAssertThrowsError(try inbox.add(text: String(repeating: "x", count: SharedInbox.maxBytes + 1))) + XCTAssertEqual(SharedInbox.safe(".."), "file") + XCTAssertEqual(SharedInbox.safe("a/b\\c:d"), "a-b-c-d") + for i in 0.. String? { broken ? nil : inner.value(environment: environment, name: name) } + func read(environment: String, name: String) throws -> String? { + if broken { throw Locked() } + return inner.value(environment: environment, name: name) + } + func setValue(_ value: String?, environment: String, name: String) { inner.setValue(value, environment: environment, name: name) } +} + +/// A sync's own files that can't be used: nothing is uploaded or lost by it. +@MainActor +final class SyncFileTests: XCTestCase { + private var root: URL! + private var fake: FakeCloud! + private var library: MemoryLibraryStore! + private var vault: BrokenVault! + private var cloud: HitopCloud! + private var model: AppModel! + private var sync: LibrarySync! + private var shared: SharedSync! + private let keys = MemorySecretStore() + private let settings = MemoryCloudSettingsStore(CloudSettings(server: FakeCloud.server)) + + override func setUp() async throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("syncfiles-\(UUID().uuidString)") + fake = FakeCloud() + library = MemoryLibraryStore() + vault = BrokenVault() + launch() + } + + override func tearDown() async throws { try? FileManager.default.removeItem(at: root) } + + private func launch() { + model = AppModel(store: library, vault: vault) + model.load() + cloud = HitopCloud(transport: fake, credentials: CloudCredentials(store: keys), settingsStore: settings) + sync = LibrarySync(cloud: cloud, model: model, stateStore: FileLibrarySyncStateStore(root: root)) + shared = SharedSync(cloud: cloud, model: model, store: FileSharedSyncStore(root: root)) + cloud.onAccountChange = nil + sync.pushDelay = .seconds(3600) + sync.retryDelay = .seconds(3600) + } + + private func signIn() async throws { + let start = try await cloud.startBrowserSignIn("google", server: FakeCloud.server) + let code = URLComponents(url: start.url, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "code" }!.value! + try await cloud.finishBrowserSignIn(code) + await sync.sync() + } + + private func collection(_ name: String) -> SavedCollection { + var c = SavedCollection(name: name) + c.requests = [SavedRequest(name: "x", url: "https://api.example/x", method: "GET")] + return c + } + + private var uploaded: [String] { sync.state.known.keys.filter { $0.hasPrefix("collection/") } } + + /// Two collections: one in the library, one shared (end-to-end encrypted). + private func both() async throws -> (plain: UInt64, secret: UInt64) { + let plain = collection("plain") + try library.saveCollection(plain) + launch() + try await signIn() + XCTAssertTrue(uploaded.contains("collection/\(plain.id)")) + let secret = collection("secret") + try library.saveCollection(secret) + var state = try FileSharedSyncStore(root: root).load() + state.account = cloud.accountKey + state.links[String(secret.id)] = SharedLink(workspace: "ws", role: "owner") + try FileSharedSyncStore(root: root).save(state) + launch() + XCTAssertTrue(model.isShared(secret.id)) + return (plain.id, secret.id) + } + + func testADamagedListOfSharedCollectionsUploadsNone() async throws { + let (plain, secret) = try await both() + try Data("{".utf8).write(to: root.appendingPathComponent("shared-sync.json")) + launch() + await sync.push() + XCTAssertFalse(uploaded.contains("collection/\(secret)")) + XCTAssertTrue(uploaded.contains("collection/\(plain)")) + XCTAssertTrue(sync.isLocalOnly(secret)) + XCTAssertFalse(sync.isLocalOnly(plain)) + XCTAssertNil(model.sharingProblem) + XCTAssertFalse(shared.notices.isEmpty) + launch() + await sync.sync() + XCTAssertFalse(uploaded.contains("collection/\(secret)"), "nor after another start") + XCTAssertNotNil(model.collection(secret)) + } + + func testKeysAnotherVersionDidNotWrite() throws { + let d = JSONDecoder() + let s = try d.decode(SharedState.self, from: Data(#"{"links":{"1":{"workspace":"w","role":"viewer"}}}"#.utf8)) + XCTAssertEqual(s.links["1"], SharedLink(workspace: "w", role: "viewer")) + XCTAssertThrowsError(try d.decode(SharedState.self, from: Data("{}".utf8))) + XCTAssertThrowsError(try d.decode(SharedState.self, from: Data(#"{"links":[]}"#.utf8))) + XCTAssertEqual(try d.decode(LibrarySync.State.self, from: Data(#"{"account":"a"}"#.utf8)), LibrarySync.State(account: "a")) + XCTAssertThrowsError(try d.decode(LibrarySync.State.self, from: Data(#"{"account":"a","localOnly":1}"#.utf8))) + } + + func testAListThatCannotBeOpenedWaits() async throws { + let (_, secret) = try await both() + let file = root.appendingPathComponent("shared-sync.json") + let kept = try Data(contentsOf: file) + // A folder in its place: there, but not to be read. + try FileManager.default.removeItem(at: file) + try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true) + launch() + XCTAssertEqual(model.sharingProblem, .unreadable) + await sync.sync() + XCTAssertFalse(uploaded.contains("collection/\(secret)")) + XCTAssertFalse(sync.isLocalOnly(secret)) + try FileManager.default.removeItem(at: file) + try kept.write(to: file) + await sync.sync() + XCTAssertNil(model.sharingProblem) + XCTAssertTrue(model.isShared(secret)) + XCTAssertFalse(uploaded.contains("collection/\(secret)")) + } + + func testADamagedLibraryStateUploadsNothingByItself() async throws { + let (plain, secret) = try await both() + let mine = collection("only here") + try library.saveCollection(mine) + try Data("{".utf8).write(to: root.appendingPathComponent("library-sync.json")) + launch() + await sync.sync() + XCTAssertTrue(uploaded.contains("collection/\(plain)"), "the library brought it back") + XCTAssertFalse(uploaded.contains("collection/\(mine.id)")) + XCTAssertFalse(uploaded.contains("collection/\(secret)")) + } + + func testSecretsThatCannotBeReadAreNotPushedAsGone() async throws { + var env = SavedEnvironment(id: "e1", name: "Prod") + env.secrets = ["token"] + try library.saveEnvironments([env]) + vault.setValue("s3cret-value", environment: "e1", name: "token") + launch() + try await signIn() + let known = sync.state.known["environments/all"] + XCTAssertNotNil(known) + vault.broken = true + await sync.push() + XCTAssertEqual(sync.state.known["environments/all"], known) + vault.broken = false + await sync.push() + XCTAssertEqual(sync.state.known["environments/all"], known) + } +} diff --git a/ios/HITOP/UnitTests/RunsTests.swift b/ios/HITOP/UnitTests/RunsTests.swift index 3a44fea..10daa7c 100644 --- a/ios/HITOP/UnitTests/RunsTests.swift +++ b/ios/HITOP/UnitTests/RunsTests.swift @@ -47,6 +47,7 @@ final class RunsTests: XCTestCase { case .started: events.append("started") case .progress: events.append("progress") case .finished: events.append("finished") + case .stopped: events.append("stopped") } } let record = try await runShop(staging()) diff --git a/ios/HITOP/project.yml b/ios/HITOP/project.yml index 8a2ca2b..aa4200d 100644 --- a/ios/HITOP/project.yml +++ b/ios/HITOP/project.yml @@ -44,6 +44,8 @@ targets: embed: false - target: HITOPWidgets embed: true + - target: HITOPShare + embed: true settings: base: PRODUCT_BUNDLE_IDENTIFIER: hitop.rws8.tech.HiTop @@ -84,6 +86,24 @@ targets: SKIP_INSTALL: YES APPLICATION_EXTENSION_API_ONLY: YES ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS: NO + # HITOP in the share sheet: leaves what was shared in the app group for the app. + HITOPShare: + type: app-extension + platform: iOS + sources: + - path: Share + - path: App/Core/SharedInbox.swift + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: hitop.rws8.tech.HiTop.Share + PRODUCT_NAME: HITOPShare + PRODUCT_MODULE_NAME: HITOPShare + INFOPLIST_FILE: Share/Info.plist + CODE_SIGN_ENTITLEMENTS: Share/HITOPShare.entitlements + CODE_SIGN_STYLE: Automatic + SKIP_INSTALL: YES + APPLICATION_EXTENSION_API_ONLY: YES + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS: NO HITOPTests: type: bundle.unit-test platform: iOS diff --git a/ios/HITOP/scripts/build-appstore.sh b/ios/HITOP/scripts/build-appstore.sh index 25d2d11..8f9191e 100755 --- a/ios/HITOP/scripts/build-appstore.sh +++ b/ios/HITOP/scripts/build-appstore.sh @@ -15,7 +15,7 @@ # Needs: Xcode 26 (xcode-select), rustup's Rust (not Homebrew's; this adds the two iOS targets), # XcodeGen (brew install xcodegen), Xcode signed in to the team's Apple ID (Settings → Accounts): # automatic signing makes the distribution certificate and the App Store profiles for the app and -# the widget extension (-allowProvisioningUpdates). The app group group.hitop.rws8.tech.HiTop is +# the widget and share extensions (-allowProvisioningUpdates). The app group group.hitop.rws8.tech.HiTop is # registered (2026-11-19). set -euo pipefail BUILD="${1:?build number, e.g. 2}" @@ -60,8 +60,9 @@ grep -q 'ARCHIVE SUCCEEDED' build/archive.log || { echo "archive failed: see ios APP=build/HITOP.xcarchive/Products/Applications/HITOP.app EXT="$APP/PlugIns/HITOPWidgets.appex" +SHARE="$APP/PlugIns/HITOPShare.appex" plist() { /usr/libexec/PlistBuddy -c "Print :$2" "$1/Info.plist"; } -for b in "$APP" "$EXT"; do +for b in "$APP" "$EXT" "$SHARE"; do test -d "$b" || { echo "missing $b" >&2; exit 1; } test "$(plist "$b" CFBundleShortVersionString)" = "$VERSION" || { echo "$b: version $(plist "$b" CFBundleShortVersionString), want $VERSION" >&2; exit 1; } test "$(plist "$b" CFBundleVersion)" = "$BUILD" || { echo "$b: build $(plist "$b" CFBundleVersion), want $BUILD" >&2; exit 1; } @@ -76,8 +77,8 @@ if [ "$MODE" = --unsigned ]; then exit 0 fi -# Signed with the app group (widgets, intents) in both targets. -for b in "$APP" "$EXT"; do +# Signed with the app group (widgets, intents) in every target. +for b in "$APP" "$EXT" "$SHARE"; do codesign -d --entitlements - "$b" 2>/dev/null | grep -q group.hitop.rws8.tech.HiTop \ || { echo "$b is not signed with the app group group.hitop.rws8.tech.HiTop" >&2; exit 1; } done diff --git a/ios/HitopKit/Sources/HitopKit/Runner.swift b/ios/HitopKit/Sources/HitopKit/Runner.swift index a2f2655..3281bd8 100644 --- a/ios/HitopKit/Sources/HitopKit/Runner.swift +++ b/ios/HitopKit/Sources/HitopKit/Runner.swift @@ -102,6 +102,8 @@ public struct Runner: Sendable { var results: [StepResult] = [] for request in collection.requests where !request.isWebSocket && !request.isGRPC { + // Cancelled (the system took the time back): nothing more is sent. + if Task.isCancelled { break } let started = Date() var step = StepResult(requestName: request.name, method: request.method, url: request.url, response: nil, error: nil, tests: [], durationMs: 0, notes: [], path: request.path, fileExtension: request.fileExtension) From a350c5ba11d5ffa2d096155e55ecdd91709dadf4 Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 15:13:15 +0100 Subject: [PATCH 3/9] iOS library: the closure's type is written out Signed-off-by: Bohdan Tsap --- ios/HITOP/App/Core/LibrarySync.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/HITOP/App/Core/LibrarySync.swift b/ios/HITOP/App/Core/LibrarySync.swift index 85edd9d..4f3cd69 100644 --- a/ios/HITOP/App/Core/LibrarySync.swift +++ b/ios/HITOP/App/Core/LibrarySync.swift @@ -344,7 +344,7 @@ final class LibrarySync { private func applyEnvironments(_ it: JSONAny) { let data = it["data"] ?? .null let secrets = it["secrets"] ?? .null - let list: [SavedEnvironment] = (data["environments"]?.array ?? []).compactMap { j in + let list: [SavedEnvironment] = (data["environments"]?.array ?? []).compactMap { j -> SavedEnvironment? in guard var e = try? j.decode(SavedEnvironment.self) else { return nil } // Secret values: the server's, else the ones this device already has. for n in e.secrets { From 01d958105221801391e02eb5a01178e35e174552 Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 15:48:49 +0100 Subject: [PATCH 4/9] iOS library: a helper's name no longer clashes Signed-off-by: Bohdan Tsap --- ios/HITOP/App/Core/LibrarySync.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ios/HITOP/App/Core/LibrarySync.swift b/ios/HITOP/App/Core/LibrarySync.swift index 4f3cd69..621adee 100644 --- a/ios/HITOP/App/Core/LibrarySync.swift +++ b/ios/HITOP/App/Core/LibrarySync.swift @@ -349,7 +349,7 @@ final class LibrarySync { // Secret values: the server's, else the ones this device already has. for n in e.secrets { // A value the server doesn't hold and the vault can't show now is left as it is. - if let value = secrets[e.id]?[n]?.string ?? kept(e.id, n, else: e.variables[n]) { + if let value = secrets[e.id]?[n]?.string ?? valueHere(e.id, n, else: e.variables[n]) { model.vault.setValue(value, environment: e.id, name: n) } e.variables.removeValue(forKey: n) @@ -365,7 +365,7 @@ final class LibrarySync { } /// The value this device has (nil: the vault can't be read now). - private func kept(_ environment: String, _ name: String, else other: String?) -> String? { + private func valueHere(_ environment: String, _ name: String, else other: String?) -> String? { do { return try model.vault.read(environment: environment, name: name) ?? other ?? "" } catch { return nil } } @@ -375,7 +375,7 @@ final class LibrarySync { var variables: [String: String] = [:] for (k, v) in data["variables"]?.object ?? [:] { variables[k] = v.string ?? "" } for n in names { - if let value = it["secrets"]?[n]?.string ?? kept(globalsVaultID, n, else: variables[n]) { + if let value = it["secrets"]?[n]?.string ?? valueHere(globalsVaultID, n, else: variables[n]) { model.vault.setValue(value, environment: globalsVaultID, name: n) } variables.removeValue(forKey: n) From 8746e1484527eb90688e42b56204de2142213af8 Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 15:19:56 +0100 Subject: [PATCH 5/9] C6: iOS roles, comments, team environments, company single sign-on Signed-off-by: Bohdan Tsap --- CHANGELOG.md | 3 + docs/PLAN.md | 2 +- ios/HITOP/App/Core/AppModel.swift | 42 ++++- ios/HITOP/App/Core/Cloud.swift | 8 +- ios/HITOP/App/Core/FakeCloud.swift | 37 +++- ios/HITOP/App/Core/LibrarySync.swift | 5 + ios/HITOP/App/Core/SharedSync.swift | 115 +++++++++--- ios/HITOP/App/Core/TeamEnvironments.swift | 210 ++++++++++++++++++++++ ios/HITOP/App/HITOPApp.swift | 2 +- ios/HITOP/App/UI/AccountView.swift | 37 +++- ios/HITOP/App/UI/EnvironmentsScreen.swift | 41 +++-- ios/HITOP/App/UI/RequestEditorView.swift | 7 + ios/HITOP/App/UI/SharedViews.swift | 131 +++++++++++++- ios/HITOP/UITests/SharedFlowTests.swift | 24 +++ ios/HITOP/UnitTests/SharedSyncTests.swift | 170 ++++++++++++++++++ 15 files changed, 784 insertions(+), 50 deletions(-) create mode 100644 ios/HITOP/App/Core/TeamEnvironments.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index cf3b60c..41ca9fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ Releases before 1.2 are listed in ROADMAP.md (section 5) and on the GitHub Relea - OAuth 2.0 (client credentials, password, authorization code with PKCE and refresh), AWS Signature and Digest. Before, a request with one of these was sent without it; a preset the app doesn't know now stops the request and says so. +- Shared collections: comments on requests, changing a member's role, deleting one for everyone (it stays on this device only), and secret + values shared with the collection fill secrets that have no value here. Team environments can be shared, changed and deleted. +- Company single sign-on (by work email). - HITOP in the share sheet (text, an address, a file), HITOP Cloud syncing in the background, and collection runs on a schedule with a notification when one fails. iOS decides when background work happens. - **Security:** when the list of shared collections on the device can't be read, nothing is synced. Before, an end-to-end encrypted collection diff --git a/docs/PLAN.md b/docs/PLAN.md index 9dfe12b..6909370 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -50,7 +50,7 @@ Status is kept in the table at the end; choices made on the way go under "Decisi | C3 | on main 193350a (PRs 23-27, every check green): run cancel, OAuth windows, desktop streams and OAuth, dialogs, portal (deployed), store.js and hitop-app.js split | | C4 | in progress: CLI TLS options on main a9c1a18 (PR 28); gRPC client/bidi streaming on main 5801dac (PR 29); MCP gRPC tools and sync --json on main 2dc2dc8 (PR 30); OAuth refresh in core, Android and desktop (PR 31), desktop network settings and WebSocket/gRPC TLS tests built (CI pending); open: interactive streaming in the apps (they send all messages, then close), iOS TLS | | C5 | core, CLI, web, desktop and Android on main 17ab888 (PR 33); iOS in C6 | -| C6 | in progress: import and export (PR 34), OAuth/SigV4/Digest (PR 35) on main; uploads, data files, compare/undo (PR 36) on main; settings and TLS (PR 37), share extension, background sync and schedules built (CI pending); open: roles, comments, team environments, SSO | +| C6 | in progress: import and export (PR 34), OAuth/SigV4/Digest (PR 35) on main; uploads, data files, compare/undo (PR 36) on main; settings and TLS (PR 37), share extension, background sync and schedules (PR 38), roles, comments, team environments, SSO built (CI pending) | | C7–C9 | not started | ## Decisions diff --git a/ios/HITOP/App/Core/AppModel.swift b/ios/HITOP/App/Core/AppModel.swift index a88bd24..4add748 100644 --- a/ios/HITOP/App/Core/AppModel.swift +++ b/ios/HITOP/App/Core/AppModel.swift @@ -55,6 +55,14 @@ final class AppModel { /// Which collections are shared isn't known (the list can't be used): nothing syncs until it is. var sharingProblem: StateFileProblem? + /// A team environment was changed or deleted here (`TeamEnvironments` sends it). + @ObservationIgnored var onTeamChange: (@MainActor (String) -> Void)? + @ObservationIgnored var onTeamGone: (@MainActor (String) -> Void)? + /// A collection that stays on this device only (LibrarySync). + @ObservationIgnored var keepHere: (@MainActor (UInt64) -> Void)? + /// Secret values shared end to end with a collection, by environment name: in memory only. They + /// fill a secret only where this device has no value of its own (as the web app). + @ObservationIgnored var sharedValues: [UInt64: [String: [String: String]]] = [:] @ObservationIgnored var reloadSharing: (@MainActor () -> Void)? /// Sets a damaged list aside (LibrarySync, once no collection can reach the library by it). @ObservationIgnored var startSharingOver: (@MainActor () throws -> Void)? @@ -574,14 +582,45 @@ final class AppModel { return } guard let i = environments.firstIndex(where: { $0.id == e.id }) else { return } + let before = environments[i] environments[i] = e persistEnvironments() + if e.extras["team"] != nil && TeamEnvironments.data(of: e, over: nil) != TeamEnvironments.data(of: before, over: nil) { onTeamChange?(e.id) } + } + + /// The team's version, or none, in place of the one here. + func replaceTeam(_ id: String, with e: SavedEnvironment?) { + guard let i = environments.firstIndex(where: { $0.id == id }) else { return } + fromCloud { + if let e { environments[i] = e } else { environments.remove(at: i) } + if e == nil && state.activeEnvironmentID == id { + state.activeEnvironmentID = nil + persistState() + } + persistEnvironments() + } + // One that is this person's own again goes to their library. + if let e, e.extras["team"] == nil { onLibraryChange?() } + } + + /// Shares an environment with an organization (nil: stops; it stays this person's own). Secret + /// values stay on this device. + func share(environment id: String, with org: String?) { + guard let i = environments.firstIndex(where: { $0.id == id }), environments[i].extras["team"]?.string != org else { return } + let stopped = environments[i].extras["team"] != nil + environments[i].extras["team"] = org.map(JSONAny.string) + environments[i].extras["org"] = org.map(JSONAny.string) + environments[i].extras["updatedBy"] = nil + if org != nil { environments[i].numericID = false } + persistEnvironments() + if org != nil { onTeamChange?(id) } else if stopped { onTeamGone?(id) } } func deleteEnvironment(_ id: String) { guard let e = environments.first(where: { $0.id == id }) else { return } for name in e.secrets { vault.setValue(nil, environment: id, name: name) } environments.removeAll { $0.id == id } + if e.extras["team"] != nil { onTeamGone?(id) } if state.activeEnvironmentID == id { state.activeEnvironmentID = nil } persistEnvironments() persistState() @@ -641,7 +680,8 @@ final class AppModel { ctx.environmentName = env.name ctx.environment = env.variables for n in env.secrets { - ctx.environmentSecrets[n] = vault.value(environment: env.id, name: n) ?? "" + let own = vault.value(environment: env.id, name: n) ?? "" + ctx.environmentSecrets[n] = own.isEmpty ? collectionID.flatMap { sharedValues[$0]?[env.name]?[n] } ?? "" : own ctx.environment.removeValue(forKey: n) } ctx.secretNames = Set(env.secrets) diff --git a/ios/HITOP/App/Core/Cloud.swift b/ios/HITOP/App/Core/Cloud.swift index 7bf2fb9..a4bc76b 100644 --- a/ios/HITOP/App/Core/Cloud.swift +++ b/ios/HITOP/App/Core/Cloud.swift @@ -251,6 +251,7 @@ struct AuthMethods: Hashable, Sendable { case "apple": "Apple" case "google": "Google" case "github": "GitHub" + case "sso": "your company" default: kind } } @@ -457,10 +458,12 @@ final class HitopCloud { /// Starts Continue with Apple/Google/GitHub: the provider page to open. `paste`: the server /// didn't take the app's return address (one older than this app), so its page shows a code to /// paste instead. - func startBrowserSignIn(_ kind: String, server: String, returnTo: String? = HitopCloud.returnTo) async throws -> (url: URL, paste: Bool) { + func startBrowserSignIn(_ kind: String, server: String, returnTo: String? = HitopCloud.returnTo, email: String? = nil) async throws -> (url: URL, paste: Bool) { let server = try Self.normalize(server) let (verifier, challenge) = CloudCrypto.verifier() var body: [String: JSONAny] = ["challenge": .string(challenge)] + // Company sign-in: the address finds the organization's provider. + if kind == "sso", let email, !email.isEmpty { body["email"] = .string(email) } if let returnTo { body["returnTo"] = .string(returnTo) } var r = try await http(server, "POST", "/v1/auth/\(kind)/start", body: .object(body)) var paste = returnTo == nil @@ -469,6 +472,9 @@ final class HitopCloud { r = try await http(server, "POST", "/v1/auth/\(kind)/start", body: .object(body)) paste = true } + if r.status == 404, kind == "sso" { + throw CloudError.http(status: 404, code: "no_sso", message: (email ?? "").isEmpty ? "This server has no single sign-on." : "There is no single sign-on for this address's organization here.") + } if r.status == 404 { throw CloudError.http(status: 404, code: "no_provider", message: "This server has no sign-in with \(AuthMethods.name(kind)).") } guard r.status == 200 else { throw Self.error(r) } // Only a web page goes to the browser. diff --git a/ios/HITOP/App/Core/FakeCloud.swift b/ios/HITOP/App/Core/FakeCloud.swift index eb3fae3..07c2e8e 100644 --- a/ios/HITOP/App/Core/FakeCloud.swift +++ b/ios/HITOP/App/Core/FakeCloud.swift @@ -210,17 +210,18 @@ final class FakeCloud: CloudTransport, @unchecked Sendable { } else if at("GET /v1/auth/methods") != nil { return reply(200, .object(["password": .object(["enabled": .bool(false)]), "emailCode": .bool(true), "passkey": .bool(true), "sso": .null, "google": .bool(methods.google), "github": .bool(methods.github), "apple": .bool(methods.apple)])) - } else if let a = at("POST /v1/auth/:/start"), case let kind = a[0], ["google", "github", "apple"].contains(kind) { - guard let b = body?.object, Set(b.keys).isSubset(of: ["challenge", "returnTo"]), let challenge = b["challenge"]?.string else { + } else if let a = at("POST /v1/auth/:/start"), case let kind = a[0], ["google", "github", "apple", "sso"].contains(kind) { + guard let b = body?.object, Set(b.keys).isSubset(of: kind == "sso" ? ["challenge", "returnTo", "email"] : ["challenge", "returnTo"]), let challenge = b["challenge"]?.string else { return fail(400, "bad_request", "invalid JSON body") } - let off = kind == "google" ? !methods.google : kind == "github" ? !methods.github : !methods.apple + if kind == "sso", !(b["email"]?.string ?? "").hasSuffix("@acme.test") { return fail(404, "org_sso_off", "no organization signs in with single sign-on for this address") } + let off = kind == "sso" ? false : kind == "google" ? !methods.google : kind == "github" ? !methods.github : !methods.apple if off { return fail(404, "provider_off", "sign-in with \(kind) isn't configured on this server") } if let r = b["returnTo"]?.string, !r.isEmpty, refusesAppReturn || r != HitopCloud.returnTo { return fail(400, "bad_request", "returnTo must be http://127.0.0.1:/... or a page of an allowed web origin") } let code = "code-\(next())" - flows[code] = (challenge, signInEmail) + flows[code] = (challenge, kind == "sso" ? b["email"]!.string! : signInEmail) return reply(200, .object(["url": .string("\(Self.server)/authorize/\(kind)?code=\(code)"), "expiresAt": .number(Double(now + 600))])) } else if let a = at("POST /v1/auth/:/finish"), case let kind = a[0] { guard let b = body?.object, Set(b.keys) == ["code", "verifier"], let code = b["code"]?.string, let verifier = b["verifier"]?.string else { @@ -648,6 +649,14 @@ extension FakeCloud { } } } + if let a = at("DELETE /v1/workspaces/:") { + switch space(a[0], "owner") { + case let .failure(r): return r + case .success: + spaces[a[0]] = nil + return reply(200, .object(["deleted": .string(a[0])])) + } + } if let a = at("DELETE /v1/workspaces/:/members/:") { guard keys(["epoch", "wraps"], required: ["epoch", "wraps"]) == nil else { return fail(400, "bad_request", "removing a member needs the rotated key: {\"epoch\": current + 1, \"wraps\": [...]}") @@ -789,6 +798,26 @@ extension FakeCloud { if a[0].hasPrefix("personal-") { return fail(400, "bad_request", "a personal organization has no team environments: your own are in your library") } return reply(200, .object(["environments": .array(a[0] == "org-acme" ? teamEnvironments : [])])) } + if let a = at("PUT /v1/orgs/:/environments/:") ?? at("DELETE /v1/orgs/:/environments/:") { + if a[0] != "org-acme" { return fail(404, "not_found", "no such organization") } + let i = teamEnvironments.firstIndex { $0["id"]?.string == a[1] } + let cur = i.map { teamEnvironments[$0] } + let seen = cur?["version"]?.int ?? 0 + if at("DELETE /v1/orgs/:/environments/:") != nil { + guard let i else { return reply(200, .object(["deleted": .bool(true)])) } + if query["baseVersion"].flatMap({ Int($0) }) != seen { return fail(409, "conflict", "changed", ["current": cur!]) } + teamEnvironments.remove(at: i) + return reply(200, .object(["deleted": .bool(true)])) + } + guard let data = body?["data"] else { return fail(400, "bad_request", "data") } + for n in data["secrets"]?.array ?? [] { + if let n = n.string, let v = data["variables"]?[n]?.string, !v.isEmpty { return fail(400, "bad_request", "secret values stay on your devices: send secret variables empty") } + } + if body?["baseVersion"]?.int != seen { return fail(409, "conflict", "changed", ["current": cur ?? .null]) } + let item: JSONAny = .object(["id": .string(a[1]), "version": .number(Double(seen + 1)), "updatedBy": .string(users[uid]?.email ?? ""), "data": data]) + if let i { teamEnvironments[i] = item } else { teamEnvironments.append(item) } + return reply(200, .object(["id": .string(a[1]), "version": .number(Double(seen + 1))])) + } return nil } } diff --git a/ios/HITOP/App/Core/LibrarySync.swift b/ios/HITOP/App/Core/LibrarySync.swift index 621adee..2cf49ec 100644 --- a/ios/HITOP/App/Core/LibrarySync.swift +++ b/ios/HITOP/App/Core/LibrarySync.swift @@ -93,6 +93,11 @@ final class LibrarySync { loadState() forgetDamaged() status.lastSync = state.lastSync + model.keepHere = { [weak self] id in + guard let self, !isLocalOnly(id) else { return } + state.localOnly.append(String(id)) + save() + } model.onLibraryChange = { [weak self] in self?.changed() } cloud.onAccountChange = { [weak self] in guard let self else { return } diff --git a/ios/HITOP/App/Core/SharedSync.swift b/ios/HITOP/App/Core/SharedSync.swift index c038124..89ae59c 100644 --- a/ios/HITOP/App/Core/SharedSync.swift +++ b/ios/HITOP/App/Core/SharedSync.swift @@ -292,11 +292,17 @@ final class SharedSync { @ObservationIgnored private var running: Set = [] @ObservationIgnored private var again: Set = [] - init(cloud: HitopCloud, model: AppModel, store: SharedSyncStore) { + @ObservationIgnored private(set) var team: TeamEnvironments! + + /// `teamFile`: team-environments.json (nil: in memory, tests). + init(cloud: HitopCloud, model: AppModel, store: SharedSyncStore, teamFile: URL? = nil) { self.cloud = cloud self.model = model self.store = store state = SharedState() + team = TeamEnvironments(cloud: cloud, model: model, file: teamFile) { [weak self] n in + if let self, !notices.contains(n) { notices.insert(n, at: 0) } + } loadState() model.onSharedChange = { [weak self] id in self?.schedule(id) } model.onCollectionDeleted = { [weak self] id in self?.forget(id) } @@ -359,6 +365,7 @@ final class SharedSync { for (id, l) in state.links { guard let cid = UInt64(id) else { continue } roles[cid] = l.gone ? "removed" : l.role + if l.gone { model.sharedValues[cid] = nil } orgs[cid] = .some(l.org.flatMap { teams.contains($0) ? $0 : nil }) } if model.sharedRoles != roles { model.sharedRoles = roles } @@ -700,7 +707,7 @@ final class SharedSync { } if !retry { synced(cid) - try? await refreshShares(ws) + try? await refreshShares(ws, id) return result } } @@ -917,6 +924,7 @@ final class SharedSync { pending[id]?.cancel() statuses[id] = nil conflicts[id] = nil + model.sharedValues[id] = nil save() } @@ -1026,6 +1034,82 @@ final class SharedSync { func setRole(_ id: UInt64, userId: String, role: String) async throws { let ws = try live(id).workspace _ = try await api("PUT", "/v1/workspaces/\(ws)/members/\(userId)", .object(["role": .string(role)])) + try? await refreshWorkspaces() + } + + /// Deletes the shared collection for everyone. It stays on this device only: it was end-to-end + /// encrypted, so it doesn't go to the library by itself. + func deleteWorkspace(_ id: UInt64) async throws { + let ws = try live(id).workspace + _ = try await api("DELETE", "/v1/workspaces/\(ws)") + model.keepHere?(id) + forget(id) + applyRoles() + try? await refreshWorkspaces() + } + + // MARK: Comments (`comments//.yaml`, one file each, as the web app) + + struct Comment: Hashable, Sendable, Identifiable { + var path: String + var author: String + var at: String + var text: String + var mine: Bool + var id: String { path } + } + + static let maxComment = 10_000 + + /// The request's path in the folder (`orders/create-order`), as hitop-core names its file. + private func requestPath(_ id: UInt64, _ request: UInt64) throws -> String? { + guard var c = model.collection(id), let i = c.requests.firstIndex(where: { $0.id == request }) else { return nil } + if let f = c.requests[i].file, !f.isEmpty { return f } + // Its file is the one that holds a mark put in its URL (names don't depend on the URL). + let mark = "https://mark.invalid/\(try SyncCore.randomId())" + c.requests[i].url = mark + return try SyncCore.toFiles(c).first { $0.key.hasPrefix("requests/") && $0.value.contains(mark) }.map { String($0.key.dropFirst("requests/".count).dropLast(".yaml".count)) } + } + + func comments(_ id: UInt64, request: UInt64) -> [Comment] { + guard let l = link(id), let file = (try? requestPath(id, request)) ?? nil else { return [] } + let prefix = "comments/\(file)/" + let me = cloud.account?.email + return store.files(l.workspace).filter { $0.key.hasPrefix(prefix) && !$0.key.dropFirst(prefix.count).contains("/") }.map { path, text in + // Written by hand: shown as text. + let o = (try? JSONDecoder().decode(JSONAny.self, from: Data(text.utf8))).flatMap { $0.object != nil ? $0 : nil } ?? .object(["text": .string(text)]) + let author = o["author"]?.string + return Comment(path: path, author: author ?? "?", at: o["at"]?.string ?? "", text: o["text"]?.string ?? "", mine: me != nil && author == me) + }.sorted { ($0.at, $0.path) < ($1.at, $1.path) } + } + + func addComment(_ id: UInt64, request: UInt64, _ text: String) async throws { + let l = try live(id) + guard l.role != "viewer" else { throw SharedError.message("Viewers can read comments but not write them") } + guard let file = try requestPath(id, request) else { throw SharedError.message("Save the request first: comments belong to a saved request") } + let body = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !body.isEmpty else { return } + guard body.count <= Self.maxComment else { throw SharedError.message("A comment is at most 10,000 characters") } + let (a, _) = try me() + let now = Date() + let comment: JSONAny = .object(["author": .string(a.email), "at": .string(now.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true))), + "request": .string(model.request(request)?.name ?? ""), "text": .string(body)]) + // YAML is a superset of JSON: the file is JSON, readable as YAML by every hitop. + let e = JSONEncoder() + e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + var files = try localFiles(id) + files["comments/\(file)/\(Int(now.timeIntervalSince1970 * 1000))-\(try SyncCore.randomId().prefix(8)).yaml"] = String(decoding: try e.encode(comment), as: UTF8.self) + "\n" + try store.saveFiles(l.workspace, files) + try await syncNow(id) + } + + func deleteComment(_ id: UInt64, _ c: Comment) async throws { + let l = try live(id) + guard c.mine, l.role != "viewer" else { throw SharedError.message("Only your own comments can be deleted") } + var files = try localFiles(id) + files[c.path] = nil + try store.saveFiles(l.workspace, files) + try await syncNow(id) } // MARK: Shared environment values (HITOP Cloud C4) @@ -1127,33 +1211,20 @@ final class SharedSync { } /// After a sync: as a sharer, hand shared environment values to new devices. - private func refreshShares(_ ws: String) async throws { + private func refreshShares(_ ws: String, _ id: UInt64) async throws { let (opened, _) = try await openShares(ws) + model.sharedValues[id] = Dictionary(opened.compactMap { o in + o.content["environment"]?.string.map { ($0, (o.content["values"]?.object ?? [:]).compactMapValues(\.string)) } + }) { _, newer in newer } if !opened.isEmpty { _ = try await resealShares(ws) } } // MARK: Team environments (sync-server teamenvs.rs) - /// The current organization's team environments (`GET /v1/orgs/:org/environments`, secret - /// values never there: each member keeps theirs in this device's Keychain), shown in the - /// environment pill. Read here; edited in the web app. + /// The current organization's team environments (`TeamEnvironments`), in the environment pill. func loadTeamEnvironments() async { - // Only the current organization's team environments are in the pill. - let current = cloud.signedIn ? cloud.currentOrg.flatMap { $0.personal ? nil : $0.id } : nil - model.dropTeamEnvironments(except: current) - guard cloud.signedIn, let org = cloud.currentOrg, !org.personal else { return } - guard let r = try? await api("GET", "/v1/orgs/\(org.id)/environments", allow: [400, 403, 404]), r.status == 200, let j = r.json else { return } - let list: [SavedEnvironment] = (j["environments"]?.array ?? []).compactMap { e in - guard let id = e["id"]?.string, var env = try? (e["data"] ?? .object([:])).decode(SavedEnvironment.self) else { return nil } - env.id = id - env.numericID = false - for n in env.secrets { env.variables[n] = nil } - env.extras["team"] = .string(org.id) - env.extras["org"] = .string(org.id) - if let by = e["updatedBy"]?.string { env.extras["updatedBy"] = .string(by) } - return env - } - model.applyTeam(environments: list, org: org.id) + team.pushDelay = pushDelay + await team.load() } func dismissNotice(_ notice: SharedNotice) { notices.removeAll { $0 == notice } } diff --git a/ios/HITOP/App/Core/TeamEnvironments.swift b/ios/HITOP/App/Core/TeamEnvironments.swift new file mode 100644 index 0000000..8d8b38d --- /dev/null +++ b/ios/HITOP/App/Core/TeamEnvironments.swift @@ -0,0 +1,210 @@ +import Foundation + +/// An organization's environments (sync-server teamenvs.rs), read and changed here. Secret values +/// never go: each member keeps theirs in their own Keychain. Only what was changed or deleted here +/// is sent (`dirty`, `deleted`), so a lost file never deletes or overwrites anything for the team. +@MainActor +final class TeamEnvironments { + struct Known: Codable, Hashable, Sendable { + var org: String + var version: Int + /// As the server has it, keys this app doesn't know included. + var data: JSONAny + } + + /// team-environments.json. + struct State: Codable, Hashable, Sendable { + var account = "" + var known: [String: Known] = [:] + var dirty: Set = [] + var deleted: [String: Known] = [:] + } + + private let cloud: HitopCloud + private let model: AppModel + private let file: URL? + private let notice: (SharedNotice) -> Void + private(set) var state = State() + var pushDelay: Duration = .seconds(1) + private var pushTask: Task? + private var last: Task? + + init(cloud: HitopCloud, model: AppModel, file: URL?, notice: @escaping (SharedNotice) -> Void) { + self.cloud = cloud + self.model = model + self.file = file + self.notice = notice + if let file { state = ((try? StateFileProblem.read(State.self, file)) ?? nil) ?? State() } + model.onTeamChange = { [weak self] id in self?.changed(id) } + model.onTeamGone = { [weak self] id in self?.gone(id) } + } + + private func save() { + guard let file, let data = try? JSONEncoder().encode(state) else { return } + try? data.write(to: file, options: [.atomic]) + } + + private func changed(_ id: String) { + claim() + state.dirty.insert(id) + state.deleted[id] = nil + save() + schedule() + } + + private func gone(_ id: String) { + claim() + state.dirty.remove(id) + if let k = state.known.removeValue(forKey: id) { state.deleted[id] = k } + save() + schedule() + } + + /// What was noted for another account is never sent with this one's. + private func claim() { + guard state.account != cloud.accountKey else { return } + state = State(account: cloud.accountKey) + } + + private func schedule() { + guard cloud.signedIn else { return } + pushTask?.cancel() + pushTask = Task { [weak self, pushDelay] in + try? await Task.sleep(for: pushDelay) + guard !Task.isCancelled else { return } + await self?.one { await self?.trySend() } + } + } + + /// One round at a time. + private func one(_ f: @escaping @MainActor () async -> Void) async { + let before = last + let t = Task { @MainActor in + await before?.value + await f() + } + last = t + await t.value + } + + /// Sends what waits (tests, Sync now). + func flush() async { + pushTask?.cancel() + await one { await self.trySend() } + } + + private func trySend() async { + do { try await send() } catch { + notice(SharedNotice("Team environments aren't saved yet: \(StoreText.withoutPlanLink(error.localizedDescription)) They go with the next sync.")) + } + } + + // MARK: Data + + /// What the server keeps of `e`: its secret variables empty. + static func data(of e: SavedEnvironment, over known: JSONAny?) -> JSONAny { + var o = known?.object ?? [:] + var variables = e.variables.mapValues(JSONAny.string) + for n in e.secrets { variables[n] = .string("") } + o["name"] = .string(e.name) + o["variables"] = .object(variables) + o["secrets"] = .array(e.secrets.map(JSONAny.string)) + return .object(o) + } + + static func environment(_ id: String, _ org: String, _ data: JSONAny, by: String?) -> SavedEnvironment? { + guard var e = try? data.decode(SavedEnvironment.self) else { return nil } + e.id = id + e.numericID = false + for n in e.secrets { e.variables[n] = nil } + e.extras["team"] = .string(org) + e.extras["org"] = .string(org) + if let by, !by.isEmpty { e.extras["updatedBy"] = .string(by) } + return e + } + + private func here(_ id: String) -> SavedEnvironment? { model.environments.first { $0.id == id && $0.extras["team"] != nil } } + + // MARK: Sending + + private func send() async throws { + guard cloud.signedIn, state.account == cloud.accountKey, model.store.unreadableFiles.isEmpty else { return } + for id in state.dirty.sorted() { + guard let e = here(id), let org = e.extras["team"]?.string else { + state.dirty.remove(id) + continue + } + let k = state.known[id].flatMap { $0.org == org ? $0 : nil } + let data = Self.data(of: e, over: k?.data) + let r = try await cloud.call("PUT", "/v1/orgs/\(org)/environments/\(id)", body: .object(["data": data, "baseVersion": .number(Double(k?.version ?? 0))]), + allow: [400, 402, 403, 404, 409, 413]) + if r.status == 200 { + state.known[id] = Known(org: org, version: r.json?["version"]?.int ?? (k?.version ?? 0) + 1, data: data) + // Changed again while it was on its way: that goes too. + if here(id).map({ Self.data(of: $0, over: k?.data) }) == data { state.dirty.remove(id) } + } else if r.status == 409 { + state.dirty.remove(id) + if let cur = r.json?["current"], !cur.isNull, let theirs = cur["data"] { + let by = cur["updatedBy"]?.string + state.known[id] = Known(org: org, version: cur["version"]?.int ?? 0, data: theirs) + model.replaceTeam(id, with: Self.environment(id, org, theirs, by: by)) + notice(SharedNotice("\(e.name) was changed by \(by.flatMap { $0.isEmpty ? nil : $0 } ?? "someone in the organization"): showing theirs.")) + } else { + state.known[id] = nil + model.replaceTeam(id, with: nil) + notice(SharedNotice("\(e.name) was deleted by someone in the organization.")) + } + } else { + // Refused: the team's stays, a new one stays this person's own. + state.dirty.remove(id) + if let k { + model.replaceTeam(id, with: Self.environment(id, org, k.data, by: nil)) + } else { + var own = e + own.extras["team"] = nil + own.extras["org"] = nil + model.replaceTeam(id, with: own) + } + notice(SharedNotice("\(e.name) wasn't saved for the organization: \(StoreText.withoutPlanLink(HitopCloud.error(r).localizedDescription))")) + } + save() + } + for (id, k) in state.deleted.sorted(by: { $0.key < $1.key }) { + let r = try await cloud.call("DELETE", "/v1/orgs/\(k.org)/environments/\(id)?baseVersion=\(k.version)", allow: [400, 403, 404, 409]) + state.deleted[id] = nil + save() + if r.status == 409 || r.status == 403 { + notice(SharedNotice("\(k.data["name"]?.string ?? "An environment") wasn't deleted for the organization: \(r.status == 409 ? "someone changed it meanwhile" : "it isn't allowed").")) + } + } + save() + } + + // MARK: Loading + + /// The current organization's: what was changed here first, then the server's. + func load() async { await one { await self.loadNow() } } + + private func loadNow() async { + let org = cloud.signedIn ? cloud.currentOrg.flatMap { $0.personal ? nil : $0.id } : nil + claim() + // Not sent yet (offline): what is here stays. + do { try await send() } catch { if !state.dirty.isEmpty || !state.deleted.isEmpty { return } } + model.dropTeamEnvironments(except: org) + state.known = state.known.filter { $0.value.org == org } + save() + guard let org else { return } + guard let r = try? await cloud.call("GET", "/v1/orgs/\(org)/environments", allow: [400, 403, 404]), r.status == 200, let j = r.json else { return } + // Changed here, or another organization chosen, while the answer was on its way: next time. + guard state.account == cloud.accountKey, cloud.currentOrg?.id == org, state.dirty.isEmpty, state.deleted.isEmpty else { return schedule() } + var list: [SavedEnvironment] = [] + state.known = [:] + for e in j["environments"]?.array ?? [] { + guard let id = e["id"]?.string, let data = e["data"], let env = Self.environment(id, org, data, by: e["updatedBy"]?.string) else { continue } + state.known[id] = Known(org: org, version: e["version"]?.int ?? 0, data: data) + list.append(env) + } + model.applyTeam(environments: list, org: org) + save() + } +} diff --git a/ios/HITOP/App/HITOPApp.swift b/ios/HITOP/App/HITOPApp.swift index 656540a..8f910e9 100644 --- a/ios/HITOP/App/HITOPApp.swift +++ b/ios/HITOP/App/HITOPApp.swift @@ -92,7 +92,7 @@ struct HITOPApp: App { let sync = LibrarySync(cloud: cloud, model: model, stateStore: syncState, deviceLabel: DeviceInfo.label) _sync = State(initialValue: sync) _cloudUI = State(initialValue: CloudUI(web: web)) - let shared = SharedSync(cloud: cloud, model: model, store: sharedStore) + let shared = SharedSync(cloud: cloud, model: model, store: sharedStore, teamFile: root.appendingPathComponent("team-environments.json")) _shared = State(initialValue: shared) let runs = RunCenter(model: model, store: runStore) _runs = State(initialValue: runs) diff --git a/ios/HITOP/App/UI/AccountView.swift b/ios/HITOP/App/UI/AccountView.swift index 6d96f35..6d57b1c 100644 --- a/ios/HITOP/App/UI/AccountView.swift +++ b/ios/HITOP/App/UI/AccountView.swift @@ -399,7 +399,7 @@ struct SignInSheet: View { @Environment(CloudUI.self) private var ui @Environment(\.dismiss) private var dismiss - enum Step: Equatable { case providers, server, paste, finishing, devices } + enum Step: Equatable { case providers, server, sso, paste, finishing, devices } @State private var step: Step = .providers @State private var methods: AuthMethods? @@ -410,6 +410,7 @@ struct SignInSheet: View { @State private var pageURL: URL? @State private var code = "" @State private var serverText = "" + @State private var workEmail = "" @State private var limit: DeviceLimit? @State private var deviceErrors: [String: String] = [:] @State private var busy = false @@ -421,6 +422,7 @@ struct SignInSheet: View { switch step { case .providers: providers case .server: serverStep + case .sso: ssoStep case .paste: pasteStep case .finishing: finishing case .devices: devicesStep @@ -464,10 +466,17 @@ struct SignInSheet: View { ForEach(methods.providers, id: \.self) { k in providerButton(k) } } } else { - Text("\(host) offers no sign-in this app has (Apple, Google or GitHub). Company single sign-on comes in a later version; until then sign in with the web or desktop app.") + Text("\(host) offers no sign-in this app has (Apple, Google or GitHub). If your company has single sign-on here, use that.") .font(Typo.caption).foregroundStyle(Theme.textMuted) .accessibilityIdentifier("no-methods") } + Button("Company single sign-on…") { + error = nil + step = .sso + } + .font(Typo.geist(14, .medium)) + .frame(minHeight: 44) + .accessibilityIdentifier("company-sso") if let error { Text(error).font(Typo.caption).foregroundStyle(Theme.danger).accessibilityIdentifier("sign-in-error") } @@ -529,6 +538,26 @@ struct SignInSheet: View { .accessibilityIdentifier("use-server") } + @ViewBuilder + private var ssoStep: some View { + Button("‹ Back") { step = .providers }.font(Typo.geist(14, .medium)) + Text("Company single sign-on").font(Typo.geist(22, .bold)) + Text("Your work email finds your company's sign-in on \(host).") + .font(Typo.caption).foregroundStyle(Theme.textMuted) + TextField("you@company.com", text: $workEmail) + .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.emailAddress).textContentType(.emailAddress) + .font(Typo.mono(14)) + .padding(12).card(radius: 14) + .accessibilityIdentifier("work-email") + if let error { Text(error).font(Typo.caption).foregroundStyle(Theme.danger).accessibilityIdentifier("sign-in-error") } + Button { Task { await begin("sso") } } label: { + Text("Continue").frame(maxWidth: .infinity, minHeight: 44) + } + .buttonStyle(.glassProminent).tint(Theme.accent) + .disabled(!workEmail.contains("@") || busy) + .accessibilityIdentifier("sso-continue") + } + @ViewBuilder private var pasteStep: some View { Text("Finish in your browser").font(Typo.geist(22, .bold)) @@ -612,7 +641,7 @@ struct SignInSheet: View { busy = true defer { busy = false } do { - let start = try await cloud.startBrowserSignIn(k, server: cloud.settings.server) + let start = try await cloud.startBrowserSignIn(k, server: cloud.settings.server, email: k == "sso" ? workEmail.trimmingCharacters(in: .whitespaces) : nil) pageURL = start.url if start.paste { step = .paste @@ -642,7 +671,7 @@ struct SignInSheet: View { step = .devices } catch { self.error = error.localizedDescription - step = was == .paste ? .paste : .providers + step = was == .paste || was == .sso ? was : .providers } } diff --git a/ios/HITOP/App/UI/EnvironmentsScreen.swift b/ios/HITOP/App/UI/EnvironmentsScreen.swift index 0008185..018ce7f 100644 --- a/ios/HITOP/App/UI/EnvironmentsScreen.swift +++ b/ios/HITOP/App/UI/EnvironmentsScreen.swift @@ -5,6 +5,11 @@ struct EnvironmentsScreen: View { @Environment(Navigator.self) private var nav @State private var adding = false @State private var newName = "" + @State private var deleting: SavedEnvironment? + @Environment(HitopCloud.self) private var cloud + + /// The organization shown now, when it is a team's. + private var org: CloudOrg? { cloud.signedIn ? cloud.currentOrg.flatMap { $0.personal ? nil : $0 } : nil } var body: some View { List { @@ -61,6 +66,14 @@ struct EnvironmentsScreen: View { .accessibilityLabel("New environment") } } + .confirmationDialog("Delete \(deleting?.name ?? "") for everyone?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) { + Button("Delete for everyone", role: .destructive) { + if let e = deleting { model.deleteEnvironment(e.id) } + deleting = nil + } + } message: { + Text("It goes from the organization's environments, for every member.") + } .alert("New environment", isPresented: $adding) { TextField("Name", text: $newName) Button("Cancel", role: .cancel) {} @@ -114,7 +127,11 @@ struct EnvironmentsScreen: View { .contextMenu { Button("Use this environment", systemImage: "checkmark") { model.setActiveEnvironment(e.id) } if e.extras["team"] == nil { + if let org { Button("Share with \(org.name)", systemImage: "person.2") { model.share(environment: e.id, with: org.id) } } Button("Delete", systemImage: "trash", role: .destructive) { model.deleteEnvironment(e.id) } + } else { + Button("Stop sharing", systemImage: "person.2.slash") { model.share(environment: e.id, with: nil) } + Button("Delete for everyone", systemImage: "trash", role: .destructive) { deleting = e } } } } @@ -139,8 +156,7 @@ struct EnvironmentDetail: View { private var env: SavedEnvironment? { id == model.globals.id ? model.globals : model.environments.first { $0.id == id } } - /// A team environment (the organization's, I2b): read here, edited in the web app; only secret - /// values can be entered (they stay in this device's Keychain). + /// A team environment: changes go to every member; secret values stay in this device's Keychain. private var team: Bool { env?.extras["team"] != nil } var body: some View { @@ -172,33 +188,28 @@ struct EnvironmentDetail: View { .contentShape(Rectangle()) } .buttonStyle(.plain) - .disabled(team && !secret) .accessibilityIdentifier("variable-\(name)") .swipeActions { - if !team { - Button("Delete", systemImage: "trash", role: .destructive) { model.removeVariable(env, name: name) } - } + Button("Delete", systemImage: "trash", role: .destructive) { model.removeVariable(env, name: name) } } } } header: { Text("VARIABLES").font(Typo.label).tracking(0.9).foregroundStyle(Theme.textFaint).accessibilityAddTraits(.isHeader) } footer: { if team { - Text("A team environment of your organization: change it in the web app. Secret values you enter stay in this device's Keychain.") + Text("Your organization's: changes go to every member. Secret values stay in this device's Keychain." + (env.extras["updatedBy"]?.string.map { " Last changed by \($0)." } ?? "")) .font(Typo.caption).foregroundStyle(Theme.textMuted) } } .listRowBackground(Theme.surface) .listRowSeparatorTint(Theme.separator) Section { - if !team { - Button { - editing = VariableDraft(original: nil, name: "", value: "", secret: false) - } label: { - Label("Add variable", systemImage: "plus").font(Typo.row).frame(minHeight: 44) - } - .accessibilityIdentifier("add-variable") + Button { + editing = VariableDraft(original: nil, name: "", value: "", secret: false) + } label: { + Label("Add variable", systemImage: "plus").font(Typo.row).frame(minHeight: 44) } + .accessibilityIdentifier("add-variable") if id != model.globals.id, model.state.activeEnvironmentID != id { Button { model.setActiveEnvironment(id) } label: { Label("Use this environment", systemImage: "checkmark.circle").font(Typo.row).frame(minHeight: 44) @@ -212,7 +223,7 @@ struct EnvironmentDetail: View { .background(Theme.ground.ignoresSafeArea()) .navigationTitle(env.name) .toolbar { - if id != model.globals.id && !team { + if id != model.globals.id { ToolbarItem(placement: .topBarTrailing) { Button("Rename") { newName = env.name; renaming = true } } diff --git a/ios/HITOP/App/UI/RequestEditorView.swift b/ios/HITOP/App/UI/RequestEditorView.swift index c3f036d..7c8f4f6 100644 --- a/ios/HITOP/App/UI/RequestEditorView.swift +++ b/ios/HITOP/App/UI/RequestEditorView.swift @@ -14,6 +14,7 @@ struct RequestScreen: View { @Environment(AppModel.self) private var model @Environment(\.dismiss) private var dismiss @State private var showResponse = false + @State private var commenting = false @State private var detent: PresentationDetent = .fraction(0.86) @State private var naming: NameTarget? @State private var moving: UInt64? @@ -59,6 +60,9 @@ struct RequestScreen: View { Button("Duplicate", systemImage: "plus.square.on.square") { model.duplicateRequest(id) } Button("Move to…", systemImage: "folder") { moving = id } } + if model.isShared(model.collectionOf(request: id)?.id) { + Button("Comments", systemImage: "bubble.left") { commenting = true } + } Button(model.isPinned(request: id) ? "Unpin" : "Pin", systemImage: "pin") { model.togglePin(request: id) } if editor.isDirty { Button("Discard changes", systemImage: "arrow.uturn.backward") { editor.revert() } @@ -106,6 +110,9 @@ struct RequestScreen: View { .safeAreaBar(edge: .bottom) { if !keyboardUp { bottomBar(editor) } } + .sheet(isPresented: $commenting) { + if let c = model.collectionOf(request: id) { CommentsSheet(collectionID: c.id, requestID: id) } + } .sheet(isPresented: $showResponse) { ResponseSheet(editor: editor) .presentationDetents([.medium, .fraction(0.86), .large], selection: $detent) diff --git a/ios/HITOP/App/UI/SharedViews.swift b/ios/HITOP/App/UI/SharedViews.swift index 1d4199a..1fd3450 100644 --- a/ios/HITOP/App/UI/SharedViews.swift +++ b/ios/HITOP/App/UI/SharedViews.swift @@ -98,6 +98,7 @@ struct ShareSheet: View { @State private var code: String? @State private var removing: WorkspaceMember? @State private var trusting: MemberKey? + @State private var deleting = false private var name: String { model.collection(collectionID)?.name ?? "Collection" } private var link: SharedLink? { shared.link(collectionID) } @@ -122,6 +123,24 @@ struct ShareSheet: View { if owner { inviteSection } membersSection(info) if owner { invitesSection(info) } + if owner { + Section { + Button("Delete for everyone", role: .destructive) { deleting = true }.frame(minHeight: 44).disabled(busy) + .accessibilityIdentifier("delete-shared") + .confirmationDialog("Delete \(name) for everyone?", isPresented: $deleting, titleVisibility: .visible) { + Button("Delete for everyone", role: .destructive) { + run("delete") { + try await shared.deleteWorkspace(collectionID) + note = "Deleted for everyone. It stays on this device only." + self.info = nil + } + } + } message: { + Text("It is gone from the server for every member. Copies on their devices stay there. Here it stays on this device only.") + } + } + .listRowBackground(Theme.surface) + } } else if link?.gone ?? false { Text("This collection is no longer shared with you: its copy stays on this device.").font(Typo.caption).foregroundStyle(Theme.textMuted) .listRowBackground(Theme.surface) @@ -254,7 +273,22 @@ struct ShareSheet: View { HStack { Text(m.email).font(Typo.row).foregroundStyle(Theme.textRow) Spacer() - Text(m.role.capitalized).font(Typo.geist(12, .semibold)).foregroundStyle(Theme.textMuted) + if owner && !m.runner && m.email != cloud.account?.email { + Menu { + Picker("Role", selection: Binding(get: { m.role }, set: { r in changeRole(m, r) })) { + Text("Editor").tag("editor") + Text("Viewer").tag("viewer") + Text("Owner").tag("owner") + } + } label: { + Text("\(m.role.capitalized) ▾").font(Typo.geist(12, .semibold)).frame(minWidth: 44, minHeight: 44) + } + .disabled(busy) + .accessibilityLabel("Role of \(m.email): \(m.role)") + .accessibilityIdentifier("role-\(m.email)") + } else { + Text(m.role.capitalized).font(Typo.geist(12, .semibold)).foregroundStyle(Theme.textMuted) + } } ForEach(m.keys) { k in keyRow(k, owner: m.email) } } @@ -355,6 +389,14 @@ struct ShareSheet: View { } } + private func changeRole(_ m: WorkspaceMember, _ role: String) { + guard role != m.role else { return } + run("role") { + try await shared.setRole(collectionID, userId: m.userId, role: role) + note = "\(m.email) is now \(role)." + } + } + private func remove() { guard let m = removing else { return } removing = nil @@ -677,3 +719,90 @@ struct NoticeText: View { .accessibilityElement(children: .combine) } } + +// MARK: - Comments + +/// Comments on a request of a shared collection: end-to-end encrypted files that sync with it. +struct CommentsSheet: View { + var collectionID: UInt64 + var requestID: UInt64 + @Environment(SharedSync.self) private var shared + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + @State private var list: [SharedSync.Comment] = [] + @State private var text = "" + @State private var error: String? + @State private var busy = false + + private var viewer: Bool { model.isReadOnly(collectionID) || (shared.link(collectionID)?.gone ?? true) } + + var body: some View { + NavigationStack { + List { + if let error { + Text(error).font(Typo.caption).foregroundStyle(Theme.danger).accessibilityIdentifier("comment-error").listRowBackground(Theme.surface) + } + Section { + if list.isEmpty { Text("No comments yet.").font(Typo.caption).foregroundStyle(Theme.textMuted).frame(minHeight: 44) } + ForEach(list) { c in + VStack(alignment: .leading, spacing: 4) { + HStack { + Text(c.author).font(Typo.geist(12, .semibold)).foregroundStyle(Theme.textSoft) + Spacer() + Text(when(c.at)).font(Typo.caption).foregroundStyle(Theme.textMuted) + } + Text(c.text).font(Typo.body).foregroundStyle(Theme.text).textSelection(.enabled) + if c.mine && !viewer { + Button("Delete", role: .destructive) { act { try await shared.deleteComment(collectionID, c) } } + .font(Typo.caption).buttonStyle(.borderless).frame(minHeight: 44).disabled(busy) + .accessibilityLabel("Delete your comment") + } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("comment") + } + } + .listRowBackground(Theme.surface) + if !viewer { + Section { + TextField("Add a comment", text: $text, axis: .vertical).lineLimit(2...6).accessibilityIdentifier("comment-text") + Button("Send") { act { try await shared.addComment(collectionID, request: requestID, text); text = "" } } + .frame(minHeight: 44) + .disabled(busy || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .accessibilityIdentifier("comment-send") + } footer: { + Text("Everyone the collection is shared with reads it. End-to-end encrypted.").font(Typo.caption) + } + .listRowBackground(Theme.surface) + } + } + .scrollContentBackground(.hidden) + .background(Theme.ground.ignoresSafeArea()) + .navigationTitle("Comments") + .navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("comments-done") } } + .task { + load() + _ = try? await shared.syncNow(collectionID) + load() + } + } + } + + private func load() { list = shared.comments(collectionID, request: requestID) } + + private func when(_ at: String) -> String { + guard let d = try? Date(at, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) else { return at } + return d.formatted(date: .abbreviated, time: .shortened) + } + + private func act(_ f: @escaping @MainActor () async throws -> Void) { + busy = true + error = nil + Task { + do { try await f() } catch { self.error = StoreText.withoutPlanLink(error.localizedDescription) } + busy = false + load() + } + } +} diff --git a/ios/HITOP/UITests/SharedFlowTests.swift b/ios/HITOP/UITests/SharedFlowTests.swift index ba53be8..99d3769 100644 --- a/ios/HITOP/UITests/SharedFlowTests.swift +++ b/ios/HITOP/UITests/SharedFlowTests.swift @@ -89,6 +89,30 @@ final class SharedFlowTests: XCTestCase { shot(app, "12-shared-collections") } + @MainActor + func testACommentIsWritten() { + guard UIDevice.current.userInterfaceIdiom == .phone else { return } + let app = launch("-UITestSharedJoined") + let team = app.el("collection-Team API") + wait(team, 60) + waitLabel(team, contains: "Shared with Acme") + if team.value as? String != "expanded" { team.tap() } + let list = app.el("request-List orders") + wait(list) + list.tap() + app.buttons["More"].firstMatch.tap() + let comments = app.buttons["Comments"].firstMatch + wait(comments) + comments.tap() + let field = app.el("comment-text") + wait(field) + field.tap() + field.typeText("Looks right") + app.el("comment-send").tap() + wait(app.staticTexts["Looks right"].firstMatch, 30) + shot(app, "45-comments") + } + @MainActor func testAConflictChoiceAndAViewerReadsOnly() { guard UIDevice.current.userInterfaceIdiom == .phone else { return } diff --git a/ios/HITOP/UnitTests/SharedSyncTests.swift b/ios/HITOP/UnitTests/SharedSyncTests.swift index b725b89..038b605 100644 --- a/ios/HITOP/UnitTests/SharedSyncTests.swift +++ b/ios/HITOP/UnitTests/SharedSyncTests.swift @@ -407,4 +407,174 @@ final class SharedSyncTests: XCTestCase { XCTAssertEqual(ada.model.collection(aid), before) XCTAssertFalse(ada.model.collections.contains { $0.name.contains("(this iPhone)") }) } + + // MARK: Roles, comments, team environments, company sign-in + + func testCommentsGoBothWaysAndOnlyTheAuthorDeletes() async throws { + let (aid, gid, _) = try await shareWithGrace() + let mine = try XCTUnwrap(request(ada, aid, "List orders")) + let hers = try XCTUnwrap(request(grace, gid, "List orders")) + try await ada.shared.addComment(aid, request: mine.id, " Why \"GET\"?\nhttps://x.example ") + try await grace.shared.syncNow(gid) + let seen = grace.shared.comments(gid, request: hers.id) + XCTAssertEqual(seen.map(\.text), ["Why \"GET\"?\nhttps://x.example"]) + XCTAssertEqual(seen.map(\.author), [ada.email]) + XCTAssertEqual(seen.map(\.mine), [false]) + XCTAssertTrue(grace.shared.comments(gid, request: request(grace, gid, "Create order")!.id).isEmpty) + do { + try await grace.shared.deleteComment(gid, seen[0]) + XCTFail("another person's comment") + } catch {} + try await grace.shared.addComment(gid, request: hers.id, "Because") + try await ada.shared.syncNow(aid) + let both = ada.shared.comments(aid, request: mine.id) + XCTAssertEqual(both.map(\.text), ["Why \"GET\"?\nhttps://x.example", "Because"]) + // Editing the request keeps them. + var edited = mine + edited.url = "https://api.example.com/v2/orders" + ada.model.save(edited) + try await ada.shared.syncNow(aid) + XCTAssertEqual(ada.shared.comments(aid, request: mine.id).count, 2) + try await ada.shared.deleteComment(aid, both[0]) + try await grace.shared.syncNow(gid) + XCTAssertEqual(grace.shared.comments(gid, request: hers.id).map(\.text), ["Because"]) + XCTAssertEqual(grace.model.collection(gid)?.requests.count, 2, "comments are not requests") + } + + func testAViewerReadsCommentsOnly() async throws { + let (aid, gid, _) = try await shareWithGrace("viewer") + try await ada.shared.addComment(aid, request: request(ada, aid, "List orders")!.id, "hello") + try await grace.shared.syncNow(gid) + let r = request(grace, gid, "List orders")!.id + XCTAssertEqual(grace.shared.comments(gid, request: r).count, 1) + do { + try await grace.shared.addComment(gid, request: r, "no") + XCTFail("a viewer wrote") + } catch {} + } + + func testARoleChangesAndTheCollectionIsDeletedForEveryone() async throws { + let (aid, gid, _) = try await shareWithGrace("viewer") + let info = try await ada.shared.members(aid) + let g = try XCTUnwrap(info.members.first { $0.email == grace.email }) + try await ada.shared.setRole(aid, userId: g.userId, role: "editor") + try await grace.shared.refreshWorkspaces() + XCTAssertFalse(grace.model.isReadOnly(gid)) + do { + try await grace.shared.deleteWorkspace(gid) + XCTFail("an editor deleted it") + } catch {} + try await ada.shared.deleteWorkspace(aid) + XCTAssertNotNil(ada.model.collection(aid)) + XCTAssertFalse(ada.model.isShared(aid)) + await ada.library.sync() + XCTAssertTrue(ada.library.isLocalOnly(aid)) + XCTAssertNil(ada.library.state.known["collection/\(aid)"], "it was end-to-end encrypted: not uploaded by itself") + } + + private func acme(_ p: Phone) async throws { + try await p.signIn() + try await p.cloud.loadOrgs() + p.cloud.selectOrg("org-acme") + await p.shared.loadTeamEnvironments() + } + + private func teamEnv(_ p: Phone) -> SavedEnvironment? { p.model.environments.first { $0.extras["team"] != nil } } + + func testATeamEnvironmentIsSharedChangedAndDeleted() async throws { + try await acme(ada) + let e = ada.model.addEnvironment(name: "Staging") + ada.model.setVariable(e, name: "baseUrl", value: "https://one.test", secret: false) + ada.model.setVariable(ada.model.environments.first { $0.id == e.id }!, name: "token", value: "ada-only-secret", secret: true) + ada.model.share(environment: e.id, with: "org-acme") + await ada.shared.team.flush() + XCTAssertFalse(String(decoding: fake.teamEnvironments[0].canonical, as: UTF8.self).contains("ada-only-secret")) + XCTAssertFalse((ada.library.environmentsItem.data["environments"]?.array ?? []).contains { $0["id"]?.string == e.id }) + + try await acme(grace) + var g = try XCTUnwrap(teamEnv(grace)) + XCTAssertEqual(g.variables["baseUrl"], "https://one.test") + XCTAssertEqual(g.secrets, ["token"]) + XCTAssertEqual(grace.model.secretValue(g, "token"), "") + grace.model.setVariable(g, name: "baseUrl", value: "https://two.test", secret: false) + await grace.shared.team.flush() + await ada.shared.loadTeamEnvironments() + XCTAssertEqual(teamEnv(ada)?.variables["baseUrl"], "https://two.test") + XCTAssertEqual(ada.model.secretValue(teamEnv(ada)!, "token"), "ada-only-secret") + + // Both change it: the first one stays, the other is told. + grace.model.setVariable(teamEnv(grace)!, name: "baseUrl", value: "https://grace.test", secret: false) + ada.model.setVariable(teamEnv(ada)!, name: "baseUrl", value: "https://ada.test", secret: false) + await grace.shared.team.flush() + await ada.shared.team.flush() + XCTAssertEqual(teamEnv(ada)?.variables["baseUrl"], "https://grace.test") + XCTAssertTrue(ada.shared.notices.contains { $0.text.contains("changed by \(grace.email)") }) + + g = teamEnv(grace)! + grace.model.deleteEnvironment(g.id) + await grace.shared.team.flush() + XCTAssertTrue(fake.teamEnvironments.isEmpty) + await ada.shared.loadTeamEnvironments() + XCTAssertNil(teamEnv(ada)) + } + + func testStoppingLeavesItToThePersonAndOthersLoseIt() async throws { + try await acme(ada) + let e = ada.model.addEnvironment(name: "Mine") + ada.model.share(environment: e.id, with: "org-acme") + await ada.shared.team.flush() + XCTAssertEqual(fake.teamEnvironments.count, 1) + ada.model.share(environment: e.id, with: nil) + await ada.shared.team.flush() + XCTAssertTrue(fake.teamEnvironments.isEmpty) + XCTAssertTrue((ada.library.environmentsItem.data["environments"]?.array ?? []).contains { $0["id"]?.string == e.id }) + } + + func testARefusedTeamEnvironmentStaysThePersonsOwn() async throws { + try await acme(ada) + let e = ada.model.addEnvironment(name: "Mine") + ada.model.share(environment: e.id, with: "org-other") + await ada.shared.team.flush() + XCTAssertNil(teamEnv(ada)) + XCTAssertNotNil(ada.model.environments.first { $0.id == e.id }) + XCTAssertTrue(ada.shared.notices.contains { $0.text.contains("wasn't saved") }) + } + + /// A team environment missing here (a lost file) is never deleted for the team. + func testNothingIsDeletedForTheTeamByALostFile() async throws { + fake.teamEnvironments = [.object(["id": .string("t1"), "version": .number(1), "data": .object(["name": .string("Acme"), "variables": .object([:]), "extra": .string("kept")])])] + try await acme(ada) + ada.model.applyTeam(environments: [], org: "org-acme") + await ada.shared.team.flush() + await ada.shared.loadTeamEnvironments() + XCTAssertEqual(fake.teamEnvironments.count, 1) + XCTAssertNotNil(teamEnv(ada)) + ada.model.setVariable(teamEnv(ada)!, name: "a", value: "b", secret: false) + await ada.shared.team.flush() + XCTAssertEqual(fake.teamEnvironments[0]["data"]?["extra"]?.string, "kept", "keys this app doesn't know stay") + } + + func testSharedValuesFillOnlyMissingSecrets() async throws { + let c = ada.model.addCollection(name: "c") + let e = ada.model.addEnvironment(name: "Prod") + ada.model.setVariable(e, name: "token", value: "", secret: true) + ada.model.sharedValues[c.id] = ["Prod": ["token": "from-share", "plain": "x"]] + let env = ada.model.environments.first { $0.id == e.id }! + let ctx = ada.model.context(for: c.id, environment: env) + XCTAssertEqual(ctx.environmentSecrets, ["token": "from-share"]) + XCTAssertEqual(ada.model.context(for: nil, environment: env).environmentSecrets["token"], "") + ada.model.setVariable(env, name: "token", value: "own", secret: true) + XCTAssertEqual(ada.model.context(for: c.id, environment: env).environmentSecrets["token"], "own") + } + + func testCompanySignInGoesByTheAddress() async throws { + do { + _ = try await ada.cloud.startBrowserSignIn("sso", server: FakeCloud.server, email: "ada@nowhere.test") + XCTFail("no such organization") + } catch let e as CloudError { XCTAssertEqual(e.code, "no_sso") } + let start = try await ada.cloud.startBrowserSignIn("sso", server: FakeCloud.server, email: "ada@acme.test") + let code = URLComponents(url: start.url, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "code" }!.value! + try await ada.cloud.finishBrowserSignIn(code) + XCTAssertEqual(ada.cloud.account?.email, "ada@acme.test") + } } From 1f073b77b5b1779c39129ae6e6d35c947e060475 Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 15:22:27 +0100 Subject: [PATCH 6/9] Android: a list of shared collections that can't be read stops the sync; a collection deleted for everyone stays here only Signed-off-by: Bohdan Tsap --- CHANGELOG.md | 5 ++ .../tech/rws8/hitop/cloud/LibrarySync.kt | 34 +++++++++- .../kotlin/tech/rws8/hitop/core/Library.kt | 8 +++ .../kotlin/tech/rws8/hitop/sync/SharedSync.kt | 49 ++++++++++++-- .../tech/rws8/hitop/core/ReliabilityTest.kt | 64 +++++++++++++++++++ 5 files changed, 154 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41ca9fc..fe8dce8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,11 @@ Releases before 1.2 are listed in ROADMAP.md (section 5) and on the GitHub Relea - Compare two responses (the current one, saved examples, earlier answers), Undo after a delete or a move, and runs over a CSV or JSON data file. - Import (Postman, Insomnia, Bruno, HAR, OpenAPI, HITOP files, a collection folder's zip; pasted, picked or opened from another app) and export. +### Android + +- **Security:** when the list of shared collections on the phone can't be read, nothing is synced, and a shared collection deleted for everyone + stays on this phone only. Before, such an end-to-end encrypted collection could have been uploaded to the library, which the server can read. + ### Web and desktop - **Security, web app:** signed in, a page load could upload an end-to-end encrypted shared collection to your own library, which the server diff --git a/android/core/src/main/kotlin/tech/rws8/hitop/cloud/LibrarySync.kt b/android/core/src/main/kotlin/tech/rws8/hitop/cloud/LibrarySync.kt index dd95aa6..44bed2a 100644 --- a/android/core/src/main/kotlin/tech/rws8/hitop/cloud/LibrarySync.kt +++ b/android/core/src/main/kotlin/tech/rws8/hitop/cloud/LibrarySync.kt @@ -105,20 +105,38 @@ class LibrarySync( var pushDelayMs = 1_000L var retryDelayMs = 15_000L - var state: State = State.of(stateFile?.takeIf { it.exists() }?.let { runCatching { HitopJson.parseToJsonElement(it.readText()).jsonObject }.getOrNull() }) + var state: State = State() private set + /** The state file can't be opened now: nothing syncs and nothing is written over it. */ + private var stateUnreadable = false + + private fun loadState() { + stateUnreadable = false + val f = stateFile?.takeIf { it.exists() } ?: return + val text = try { f.readText() } catch (_: java.io.IOException) { stateUnreadable = true; return } + // Damaged: which collections stay on this phone only isn't known any more. As for another + // account, none is uploaded by itself (what the library has comes back by the pull). + state = runCatching { State.of(HitopJson.parseToJsonElement(text).jsonObject) }.getOrElse { State(account = "damaged") } + } private var pushJob: Job? = null private val roundLock = Mutex() private var pushAgain = false init { + loadState() + library.keepHere = { id -> + if (!isLocalOnly(id)) { + state = state.copy(localOnly = state.localOnly + id) + save() + } + } _status.update { it.copy(lastSync = state.lastSync) } library.onLibraryChange = { changed() } refreshBadges() } private fun save() { - val f = stateFile ?: return + val f = stateFile?.takeIf { !stateUnreadable } ?: return tech.rws8.hitop.core.SafeFiles.write(f, state.toJson().toString()) } @@ -152,10 +170,22 @@ class LibrarySync( refreshBadges() return false } + if (stateUnreadable) loadState() + if (library.sharingProblem?.damaged == false) library.reloadSharing?.invoke() + if (stateUnreadable || library.sharingProblem?.damaged == false) return false if (state.account != key) { state = firstLink(key, state, library.state.value.collections) save() } + library.sharingProblem?.let { p -> + // Every collection the library doesn't hold already may be a shared one: it stays on this + // phone only, and that is saved before the damaged list goes. + state = state.copy(localOnly = (state.localOnly + library.state.value.collections.map { it.id }.filter { "collection/$it" !in state.known }).distinct()) + if (runCatching { save(); library.startSharingOver?.invoke() }.isFailure || library.sharingProblem != null) { + _status.update { it.copy(on = false, error = p.message) } + return false + } + } _status.update { it.copy(on = true) } return true } diff --git a/android/core/src/main/kotlin/tech/rws8/hitop/core/Library.kt b/android/core/src/main/kotlin/tech/rws8/hitop/core/Library.kt index 17fb087..02b1cc0 100644 --- a/android/core/src/main/kotlin/tech/rws8/hitop/core/Library.kt +++ b/android/core/src/main/kotlin/tech/rws8/hitop/core/Library.kt @@ -105,6 +105,14 @@ class Library(private val store: LibraryStore, private val secrets: SecretStore) return v.filterKeys { n -> n in e!!.secrets && secrets.get(SecretStore.envKey(e.id, n)).isNullOrEmpty() } } + /** Which collections are shared isn't known: nothing syncs until it is. */ + @Volatile var sharingProblem: tech.rws8.hitop.sync.SharedListProblem? = null + var reloadSharing: (() -> Unit)? = null + /** Sets a damaged list aside (LibrarySync, once no collection can reach the library by it). */ + var startSharingOver: (() -> Unit)? = null + /** A collection that stays on this phone only (LibrarySync). */ + var keepHere: ((String) -> Unit)? = null + /** A collection was deleted here (SharedSync forgets its link). */ var onCollectionDeleted: ((String) -> Unit)? = null /** The organization a new collection is filed under (null: personal). */ diff --git a/android/core/src/main/kotlin/tech/rws8/hitop/sync/SharedSync.kt b/android/core/src/main/kotlin/tech/rws8/hitop/sync/SharedSync.kt index 44c56dc..25eaf1f 100644 --- a/android/core/src/main/kotlin/tech/rws8/hitop/sync/SharedSync.kt +++ b/android/core/src/main/kotlin/tech/rws8/hitop/sync/SharedSync.kt @@ -88,8 +88,17 @@ data class SharedState( } } +/** + * The list of shared collections is there but can't be used. Never taken as empty: an end-to-end + * encrypted collection would look like any other and go to the library, which the server can read. + */ +class SharedListProblem(val damaged: Boolean, cause: Throwable) : Exception("The list of shared collections can't be read, so nothing is synced.", cause) + interface SharedSyncStore { + /** Throws [SharedListProblem]. */ fun load(): SharedState + /** A damaged list out of the way, kept beside. */ + fun setAsideDamaged() {} fun save(s: SharedState) fun files(ws: String): Map fun saveFiles(ws: String, files: Map) @@ -107,7 +116,18 @@ class FileSharedSyncStore(private val root: File) : SharedSyncStore { tech.rws8.hitop.core.SafeFiles.write(f, text) } - override fun load() = SharedState.of(runCatching { HitopJson.parseToJsonElement(stateFile.readText()).jsonObject }.getOrNull()) + override fun load(): SharedState { + if (!stateFile.exists()) return SharedState() + val text = try { stateFile.readText() } catch (e: java.io.IOException) { throw SharedListProblem(false, e) } + return try { + val o = HitopJson.parseToJsonElement(text).jsonObject + o.getValue("links").jsonObject.values.forEach { require(it.jsonObject.str("workspace").isNotEmpty()) } + SharedState.of(o) + } catch (e: RuntimeException) { + throw SharedListProblem(true, e) + } + } + override fun setAsideDamaged() { tech.rws8.hitop.core.SafeFiles.setAside(stateFile) } override fun save(s: SharedState) = write(stateFile, s.toJson().toString()) override fun files(ws: String) = runCatching { HitopJson.parseToJsonElement(filesFile(ws).readText()).jsonObject.mapValues { (it.value as JsonPrimitive).content } }.getOrDefault(emptyMap()) override fun saveFiles(ws: String, files: Map) = write(filesFile(ws), JsonObject(files.mapValues { JsonPrimitive(it.value) }).toString()) @@ -182,7 +202,7 @@ class SharedSync(private val cloud: HitopCloud, private val library: Library, pr val pendingTrust = MutableStateFlow(null) var pushDelayMs = 1_000L - var state: SharedState = store.load() + var state: SharedState = SharedState() private set private val pending = HashMap() private val running = HashSet() @@ -204,7 +224,25 @@ class SharedSync(private val cloud: HitopCloud, private val library: Library, pr saveTeamState() } + private fun loadList() { + try { + state = store.load() + library.sharingProblem = null + } catch (e: SharedListProblem) { + state = SharedState() + library.sharingProblem = e + } + applyRoles() + } + init { + loadList() + library.reloadSharing = { loadList() } + library.startSharingOver = { + store.setAsideDamaged() + loadList() + notice(SharedNotice("The list of shared collections on this phone was damaged", "Their copies here are kept on this phone only. Open them again under Shared with you.")) + } loadTeamState() library.onTeamChange = { saveTeamState(); scheduleTeam() } library.onSharedChange = { schedule(it) } @@ -214,7 +252,7 @@ class SharedSync(private val cloud: HitopCloud, private val library: Library, pr state.links.forEach { (id, l) -> setConflicts(id, conflictList(id, l)) } } - private fun save() = store.save(state) + private fun save() { if (library.sharingProblem == null) store.save(state) } private fun status(id: String, f: (Status) -> Status) = _statuses.update { it + (id to f(it[id] ?: Status())) } private fun setConflicts(id: String, list: List?) = _conflicts.update { if (list == null) it - id else it + (id to list) } private fun notice(n: SharedNotice) = _notices.update { if (n in it) it else listOf(n) + it } @@ -252,6 +290,8 @@ class SharedSync(private val cloud: HitopCloud, private val library: Library, pr /** The signed-in account's links; another account's are kept, not synced (`gone`). This device's own key is pinned. */ fun checkAccount(): Boolean { + if (library.sharingProblem?.damaged == false) loadList() + if (library.sharingProblem != null) return false val a = cloud.account ?: return false val secret = cloud.deviceSecret() ?: return false val key = cloud.accountKey @@ -1006,10 +1046,11 @@ class SharedSync(private val cloud: HitopCloud, private val library: Library, pr syncNow(id) } - /** Deletes the shared collection for everyone; it stays on this phone as an unshared one. */ + /** Deletes the shared collection for everyone. It was end-to-end encrypted: it stays on this phone only, not in the library. */ suspend fun deleteWorkspace(id: String) { val l = live(id) api("DELETE", "/v1/workspaces/${l.workspace}") + library.keepHere?.invoke(id) forget(id) library.onLibraryChange?.invoke() runCatching { refreshWorkspaces() } diff --git a/android/core/src/test/kotlin/tech/rws8/hitop/core/ReliabilityTest.kt b/android/core/src/test/kotlin/tech/rws8/hitop/core/ReliabilityTest.kt index fc670f6..7c7b8ac 100644 --- a/android/core/src/test/kotlin/tech/rws8/hitop/core/ReliabilityTest.kt +++ b/android/core/src/test/kotlin/tech/rws8/hitop/core/ReliabilityTest.kt @@ -116,4 +116,68 @@ class ReliabilityTest { assertNotNull(other.lib.state.value.collection(c.id)) assertEquals(2, dir.walkTopDown().count { it.name.contains(".damaged-") }) } + + /** A list of shared collections that can't be used never lets one reach the readable library. */ + @Test + fun aDamagedListOfSharedCollectionsUploadsNone() = runBlocking { + val dir = Files.createTempDirectory("lib").toFile() + val fake = FakeCloud() + val secrets = MemorySecretStore() + val settings = MemoryCloudSettingsStore(CloudSettings(server = FakeCloud.SERVER)) + fun shared(p: Phone) = tech.rws8.hitop.sync.SharedSync(p.cloud, p.lib, tech.rws8.hitop.sync.FileSharedSyncStore(dir), CoroutineScope(SupervisorJob() + Dispatchers.Default)).also { it.pushDelayMs = 3_600_000 } + val one = Phone(dir, fake, secrets, settings) + one.lib.seedShopApi() + one.cloud.startBrowserSignIn("github", FakeCloud.SERVER) + one.cloud.finishBrowserSignIn(fake.approve()) + one.sync.sync() + one.sync.flush() + val plain = one.lib.state.value.collections.first { it.name == "shop-api" }.id + val secret = one.lib.addCollection("secret") + val store = tech.rws8.hitop.sync.FileSharedSyncStore(dir) + store.save(tech.rws8.hitop.sync.SharedState(account = one.cloud.accountKey, links = mapOf(secret.id to tech.rws8.hitop.sync.SharedLink("ws", "owner")))) + val file = File(dir, "shared-sync.json") + val good = file.readText() + + // Can't be opened now (a folder in its place): nothing syncs until it can. + file.delete() + file.mkdir() + val two = Phone(dir, fake, secrets, settings) + shared(two) + assertEquals(false, two.lib.sharingProblem?.damaged) + two.sync.sync() + assertFalse("collection/${secret.id}" in two.sync.state.known) + file.delete() + file.writeText(good) + two.sync.sync() + assertNull(two.lib.sharingProblem) + assertTrue(two.lib.isShared(secret.id)) + assertFalse("collection/${secret.id}" in two.sync.state.known) + + // Damaged: kept beside, and the collection stays on this phone only, also after another start. + for (bad in listOf("{", "{}", """{"links":{"1":3}}""")) { + file.writeText(bad) + val three = Phone(dir, fake, secrets, settings) + val s = shared(three) + assertEquals(true, three.lib.sharingProblem?.damaged) + three.sync.sync() + three.sync.flush() + assertNull(three.lib.sharingProblem) + assertTrue(s.notices.value.isNotEmpty()) + assertFalse("collection/${secret.id}" in three.sync.state.known) + assertTrue(three.sync.isLocalOnly(secret.id)) + assertTrue("collection/$plain" in three.sync.state.known) + assertFalse(three.sync.isLocalOnly(plain)) + } + assertEquals(3, dir.listFiles()!!.count { it.name.startsWith("shared-sync.json.damaged-") }) + // The library's own state damaged: nothing new goes by itself. + val mine = two.lib.addCollection("only here") + File(dir, "library-sync.json").writeText("{") + val four = Phone(dir, fake, secrets, settings) + shared(four) + four.sync.sync() + four.sync.flush() + assertFalse("collection/${mine.id}" in four.sync.state.known) + assertFalse("collection/${secret.id}" in four.sync.state.known) + assertTrue("collection/$plain" in four.sync.state.known) + } } From 85453067d958505557fc667ed341cbc332ac09fb Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 16:18:32 +0100 Subject: [PATCH 7/9] iOS: the schedule picker's setter is a closure (the method reference crashed Apple's compiler) Signed-off-by: Bohdan Tsap --- ios/HITOP/App/UI/RunsScreen.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/HITOP/App/UI/RunsScreen.swift b/ios/HITOP/App/UI/RunsScreen.swift index df54c97..31070d9 100644 --- a/ios/HITOP/App/UI/RunsScreen.swift +++ b/ios/HITOP/App/UI/RunsScreen.swift @@ -606,7 +606,7 @@ struct ScheduleCard: View { var body: some View { VStack(alignment: .leading, spacing: 4) { - Picker(selection: Binding(get: { mine?.everyMinutes ?? 0 }, set: choose)) { + Picker(selection: Binding(get: { mine?.everyMinutes ?? 0 }, set: { m in choose(m) })) { Text("Off").tag(0) ForEach(RunSchedule.choices, id: \.minutes) { c in Text("Every \(c.name)").tag(c.minutes) } } label: { From 675fd2b17572c316544aab07fc73a8b27291a37c Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 16:33:16 +0100 Subject: [PATCH 8/9] Plan: open problems Signed-off-by: Bohdan Tsap --- docs/PLAN.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/PLAN.md b/docs/PLAN.md index 6909370..b2d7f00 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -74,3 +74,10 @@ Status is kept in the table at the end; choices made on the way go under "Decisi or without secrets the Keychain can't show. - iOS share extension only puts the item in the app group (an extension can't open its app); the app shows it before anything is added. - A damaged list of shared collections is set aside only after every collection the library doesn't hold is marked "this device only". + +## Open problems + +- Android `ProtocolFlowTest.grpcFieldsAndAnUnreachableServer` (API 31 emulator), failed once on main 8da867a (2026-11-25): "Calling…" for more than + 30 s although hitop-core's connect limit is 10 s (6c94353). Not reproduced and not explained; not to be hidden by a longer wait. +- Leaked copies of shared collections (web app before PR 40): `request_history` on the server keeps them after the library item is deleted. + Nothing is done on production without the owner's answer. From dd7ff78c5f4fe50a3008151ba60113eaa0a5808b Mon Sep 17 00:00:00 2001 From: Bohdan Tsap Date: Wed, 25 Nov 2026 17:14:53 +0100 Subject: [PATCH 9/9] Ops log: the web app's privacy fix is live Signed-off-by: Bohdan Tsap --- cloud/ops-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cloud/ops-log.md b/cloud/ops-log.md index ec04402..5a3ea35 100644 --- a/cloud/ops-log.md +++ b/cloud/ops-log.md @@ -443,3 +443,11 @@ and on hitop.rws8.tech/cloud/healthz. --> - Portal from 2f69a78 (`cloud/portal` dist only; the rest of /var/www/hitop checked byte for byte untouched; old assets kept). A `?server=` link asks before signing out and the sign-in page names a server that isn't HITOP Cloud: checked live in a browser. Backup `/var/www/hitop-cloud.bak-20261125-033333`. + +## 2026-11-25 Web app: shared collections never reach the library (security) + +- Web app only, from 8da867a (PR 40; the owner's OK the same day), 16:14 UTC; backup `/var/www/hitop-app.bak-20261125-161434`. Old assets + kept; the rest of /var/www/hitop checked untouched; every file live equals the build, which passed the `shared-library` and `library` suites. +- It carries everything in the web app since 96f90df. gRPC calls with several client messages from the web need the newer hitop-server (C9). +- Not cleaned: `request_history` rows of leaked copies, and backups. +- Rollback (brings the leak back): `sudo rsync -a --delete /var/www/hitop-app.bak-20261125-161434/ /var/www/hitop/app/`.