diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 065ab7d..a2848fd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -81,6 +81,9 @@ jobs: holmes/tests/run-text-entry-tests.sh holmes/tests/run-model-json-tests.sh + - name: Test sign in validation and install tracking + run: holmes/tests/run-auth-validation-tests.sh + - name: Test browser bridge reliability run: | holmes/tests/run-browser-bridge-extension-tests.sh diff --git a/README.md b/README.md index 7ebbc9b..16e9a6b 100644 --- a/README.md +++ b/README.md @@ -105,8 +105,9 @@ Holmes picks one automatically based on your Mac's memory. Change it anytime in ## ➤ Privacy -Everything stays on your Mac by default. No telemetry, no analytics, no account. +What you do stays on your Mac. Holmes requires a free account, and the only data it sends is what counts users: your email, region, macOS version, and Holmes version. +- Account: email and password sign in through Appwrite. A daily install ping sends a random install id, the Holmes and macOS versions, Mac model, region and locale. Nothing from your screen, voice or tasks is included - Screen capture, Accessibility reads, OCR, dictation: on device, always - Screen context during a task: sent to the local model on your Mac (or wherever you point Ollama) - Spoken text: sent to ElevenLabs only if you add a key diff --git a/blueprint.md b/blueprint.md index a4d3060..0fd4eb8 100644 --- a/blueprint.md +++ b/blueprint.md @@ -1,6 +1,6 @@ # Holmes -Autonomous desktop agent for macOS. Runs entirely on your Mac, no cloud, no account. +Autonomous desktop agent for macOS. Runs on your Mac with a local model; the only cloud piece is your account. > **Beta.** This is Holmes Local, the open source build. It uses an open weights vision model served by [Ollama](https://ollama.com). The hosted version lives in a separate, private repo. @@ -73,8 +73,9 @@ Holmes picks one automatically based on your Mac's memory. Change it anytime in ## Privacy -Everything stays on your Mac by default. No telemetry, no analytics, no account. +What you do stays on your Mac. Holmes requires a free account, and the only data it sends is what counts users: your email, region, macOS version, and Holmes version. +- Account: email and password sign in through Appwrite. A daily install ping sends a random install id, the Holmes and macOS versions, Mac model, region and locale. Nothing from your screen, voice or tasks is included - Screen capture, Accessibility reads, OCR, dictation: on device, always - Screen context during a task: sent to the local model on your Mac (or wherever you point Ollama) - Spoken text: sent to ElevenLabs only if you add a key diff --git a/holmes/cloud/README.md b/holmes/cloud/README.md new file mode 100644 index 0000000..55f17a5 --- /dev/null +++ b/holmes/cloud/README.md @@ -0,0 +1,19 @@ +# Holmes cloud + +Everything Holmes sends off the Mac lives in one Appwrite Cloud project (`holmes`, region San Francisco). + +| Piece | Where it runs | What it does | +|---|---|---| +| `functions/download` | https://holmes-download.appwrite.network | The website's Download buttons open this. It records the click (country, referrer, browser) in the `downloads` table, then redirects to the GitHub releases page. Crawlers are redirected but not counted. | +| `functions/track` | Called by the app through the Appwrite SDK | `install` events keep one row per Mac in `installs` (Holmes version, macOS version, Mac model, Region setting, country, first and last seen, launches). `signin` events also keep one row per account in `users`, reading the email and name from the verified Appwrite account, never from the request. | +| `dashboard` | https://holmes-analytics.appwrite.network | Admin analytics in three sections: website download tracking, accounts (sign ups and sign ins), and installs (current Macs running Holmes), each with regions, versions, and daily charts. Sign in with an emailed code; only members of the `admins` team can see data. | + +## Data and access + +* Database `holmes` with tables `downloads`, `installs`, `users`, and `sign_ins` (one row per sign in, so sign ins can be counted per day). Each table grants read to `team:admins` only; nothing is readable or writable by the app or the public directly. The functions write with the per execution key Appwrite provides. +* Country comes from Appwrite's country header when present, otherwise from a short lookup of the caller's IP at country.is. The app separately reports the Mac's Region setting. +* Add an admin by adding their account to the `admins` team in the Appwrite console. + +## Deploying + +Each folder is deployed as is. Functions use the Node 22 runtime with entrypoint `src/main.js` and build command `npm install`. The dashboard is a static site served from its folder root. diff --git a/holmes/cloud/dashboard/holmes.png b/holmes/cloud/dashboard/holmes.png new file mode 100644 index 0000000..42ddea7 Binary files /dev/null and b/holmes/cloud/dashboard/holmes.png differ diff --git a/holmes/cloud/dashboard/index.html b/holmes/cloud/dashboard/index.html new file mode 100644 index 0000000..37d5398 --- /dev/null +++ b/holmes/cloud/dashboard/index.html @@ -0,0 +1,765 @@ + + + + + + +Holmes analytics + + + + + + + + + + + + + + + + + + diff --git a/holmes/cloud/dashboard/wordmark.svg b/holmes/cloud/dashboard/wordmark.svg new file mode 100644 index 0000000..ea02c96 --- /dev/null +++ b/holmes/cloud/dashboard/wordmark.svg @@ -0,0 +1,6 @@ + + Holmes + Holmes wordmark. + + + diff --git a/holmes/cloud/functions/download/package.json b/holmes/cloud/functions/download/package.json new file mode 100644 index 0000000..3a54e55 --- /dev/null +++ b/holmes/cloud/functions/download/package.json @@ -0,0 +1,10 @@ +{ + "name": "holmes-download-counter", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "src/main.js", + "dependencies": { + "node-appwrite": "29.0.0" + } +} diff --git a/holmes/cloud/functions/download/src/main.js b/holmes/cloud/functions/download/src/main.js new file mode 100644 index 0000000..d7c73bd --- /dev/null +++ b/holmes/cloud/functions/download/src/main.js @@ -0,0 +1,73 @@ +import { Client, TablesDB, ID } from 'node-appwrite'; + +// Every Download button on the Holmes website points here. The click is +// recorded, then the visitor lands on the releases page to pick a version. +const RELEASES_URL = 'https://github.com/tryholmes/holmes-local/releases'; + +// Link previews and crawlers should still be redirected, but not counted. +const AUTOMATED_AGENT = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|curl|wget|python|headless/i; + +const clip = (value, max) => { + if (value === undefined || value === null) return null; + const text = String(value).trim().slice(0, max); + return text.length > 0 ? text : null; +}; + +// Appwrite only fills the country header for some requests, so fall back to +// country.is (open source) using the visitor's IP. Never waits long. +async function countryFor(headers, log) { + const known = clip(headers['x-appwrite-country-code'], 8); + if (known) return known.toUpperCase(); + // The CDN puts the real visitor address in its own headers; x-forwarded-for can start with a proxy. + const ip = String(headers['fastly-client-ip'] ?? headers['x-cdn-client-ip'] ?? headers['x-real-ip'] + ?? headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + if (!ip) { + log('country lookup skipped: no client address header'); + return null; + } + try { + const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(2500) }); + if (!response.ok) { + log(`country lookup failed: status ${response.status}`); + return null; + } + const { country } = await response.json(); + return clip(country, 8); + } catch (err) { + log(`country lookup failed: ${err.name}`); + return null; + } +} + +export default async ({ req, res, log, error }) => { + const headers = req.headers ?? {}; + const agent = String(headers['user-agent'] ?? ''); + + if (req.method === 'GET' && !AUTOMATED_AGENT.test(agent)) { + try { + const country = await countryFor(headers, log); + const client = new Client() + .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT) + .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID) + .setKey(headers['x-appwrite-key'] ?? ''); + + await new TablesDB(client).createRow({ + databaseId: 'holmes', + tableId: 'downloads', + rowId: ID.unique(), + data: { + country, + continent: clip(headers['x-appwrite-continent-code'], 8), + referrer: clip(headers['referer'] ?? headers['referrer'], 512), + user_agent: clip(agent, 512), + source: clip(req.query?.source ?? 'website', 64), + }, + }); + } catch (err) { + // Never block the download because the counter failed. + error(`Could not record the download: ${err.message}`); + } + } + + return res.redirect(RELEASES_URL, 302); +}; diff --git a/holmes/cloud/functions/track/package.json b/holmes/cloud/functions/track/package.json new file mode 100644 index 0000000..6392fc6 --- /dev/null +++ b/holmes/cloud/functions/track/package.json @@ -0,0 +1,10 @@ +{ + "name": "holmes-install-tracker", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "src/main.js", + "dependencies": { + "node-appwrite": "29.0.0" + } +} diff --git a/holmes/cloud/functions/track/src/main.js b/holmes/cloud/functions/track/src/main.js new file mode 100644 index 0000000..736b29f --- /dev/null +++ b/holmes/cloud/functions/track/src/main.js @@ -0,0 +1,139 @@ +import { Client, TablesDB, Users, ID } from 'node-appwrite'; + +// Holmes calls this on launch ("install") and after signing in ("signin"). +// The email always comes from the verified Appwrite account, never the body. +const DATABASE_ID = 'holmes'; +const INSTALL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const clip = (value, max) => { + if (value === undefined || value === null) return null; + const text = String(value).trim().slice(0, max); + return text.length > 0 ? text : null; +}; + +// Same fallback as the download counter: Appwrite's country header when it is +// present, otherwise a short country.is lookup of the caller's IP. +async function countryFor(headers) { + const known = clip(headers['x-appwrite-country-code'], 8); + if (known) return known.toUpperCase(); + const ip = String(headers['fastly-client-ip'] ?? headers['x-cdn-client-ip'] ?? headers['x-real-ip'] + ?? headers['x-appwrite-client-ip'] ?? headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + if (!ip) return null; + try { + const response = await fetch(`https://api.country.is/${encodeURIComponent(ip)}`, { signal: AbortSignal.timeout(1500) }); + if (!response.ok) return null; + const { country } = await response.json(); + return clip(country, 8); + } catch { + return null; + } +} + +function parseBody(req) { + if (req.bodyJson && typeof req.bodyJson === 'object') return req.bodyJson; + const raw = req.bodyText ?? req.body ?? ''; + if (typeof raw === 'object' && raw !== null) return raw; + return raw ? JSON.parse(raw) : {}; +} + +// Creates the row the first time and updates it afterwards, so first seen and +// sign up dates are kept while counters and versions move forward. +async function upsert(db, tableId, rowId, build) { + let existing = null; + try { + existing = await db.getRow({ databaseId: DATABASE_ID, tableId, rowId }); + } catch (err) { + if (err.code !== 404) throw err; + } + const data = build(existing); + return existing + ? db.updateRow({ databaseId: DATABASE_ID, tableId, rowId, data }) + : db.createRow({ databaseId: DATABASE_ID, tableId, rowId, data }); +} + +export default async ({ req, res, error }) => { + if (req.method !== 'POST') return res.json({ ok: false, error: 'Send a POST request.' }, 405); + + let body; + try { + body = parseBody(req); + } catch { + return res.json({ ok: false, error: 'The request body must be JSON.' }, 400); + } + + const event = body.event; + if (event !== 'install' && event !== 'signin') { + return res.json({ ok: false, error: 'event must be install or signin.' }, 400); + } + const installId = String(body.install_id ?? '').toLowerCase(); + if (!INSTALL_ID.test(installId)) { + return res.json({ ok: false, error: 'install_id must be a UUID.' }, 400); + } + + const headers = req.headers ?? {}; + const userId = clip(headers['x-appwrite-user-id'], 36); + if (event === 'signin' && !userId) { + return res.json({ ok: false, error: 'Sign in before sending a signin event.' }, 401); + } + + const client = new Client() + .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT) + .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID) + .setKey(headers['x-appwrite-key'] ?? ''); + const db = new TablesDB(client); + const now = new Date().toISOString(); + + const device = { + holmes_version: clip(body.holmes_version, 32), + macos_version: clip(body.macos_version, 32), + mac_model: clip(body.mac_model, 64), + region: clip(body.region, 8), + country: await countryFor(headers), + }; + + try { + await upsert(db, 'installs', installId, (existing) => ({ + ...device, + locale: clip(body.locale, 32), + last_seen: now, + launches: (existing?.launches ?? 0) + 1, + ...(existing ? {} : { first_seen: now }), + })); + + if (event === 'signin') { + const user = await new Users(client).get(userId); + let isNewAccount = false; + await upsert(db, 'users', userId, (existing) => { + isNewAccount = !existing; + return { + ...device, + email: clip(user.email, 320), + name: clip(user.name, 128), + install_id: installId, + last_sign_in_at: now, + sign_ins: (existing?.sign_ins ?? 0) + 1, + ...(existing ? {} : { signed_up_at: user.$createdAt ?? now }), + }; + }); + // One row per sign in, so the dashboard can chart sign ins per day. + await db.createRow({ + databaseId: DATABASE_ID, + tableId: 'sign_ins', + rowId: ID.unique(), + data: { + user_id: userId, + new_account: isNewAccount, + region: device.region, + country: device.country, + holmes_version: device.holmes_version, + macos_version: device.macos_version, + }, + }); + } + + return res.json({ ok: true }); + } catch (err) { + error(`Could not record the ${event} event: ${err.message}`); + return res.json({ ok: false, error: 'Holmes could not record this event.' }, 500); + } +}; diff --git a/holmes/holmes.xcodeproj/project.pbxproj b/holmes/holmes.xcodeproj/project.pbxproj index 9cdb43a..f26a88a 100644 --- a/holmes/holmes.xcodeproj/project.pbxproj +++ b/holmes/holmes.xcodeproj/project.pbxproj @@ -13,6 +13,11 @@ AA000001000000000000117 /* EmailPredictionSources.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000117 /* EmailPredictionSources.swift */; }; AA000001000000000000118 /* EmailPredictionActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000118 /* EmailPredictionActions.swift */; }; AA000001000000000000119 /* EmailUndoToast.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000119 /* EmailUndoToast.swift */; }; + AA000001000000000000120 /* AuthSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000120 /* AuthSupport.swift */; }; + AA000001000000000000121 /* HolmesCloud.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000121 /* HolmesCloud.swift */; }; + AA000001000000000000122 /* AuthService.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000122 /* AuthService.swift */; }; + AA000001000000000000124 /* SignInScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000124 /* SignInScreen.swift */; }; + AA000001000000000000123 /* Appwrite in Frameworks */ = {isa = PBXBuildFile; productRef = AA00000A000000000000002 /* Appwrite */; }; B7A500010000000000000006 /* ModelJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000006 /* ModelJSON.swift */; }; B7A500010000000000000005 /* TextEntrySupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000005 /* TextEntrySupport.swift */; }; B7A500010000000000000004 /* AutonomousRunTally.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000004 /* AutonomousRunTally.swift */; }; @@ -137,6 +142,10 @@ AA000002000000000000117 /* EmailPredictionSources.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailPredictionSources.swift; sourceTree = ""; }; AA000002000000000000118 /* EmailPredictionActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailPredictionActions.swift; sourceTree = ""; }; AA000002000000000000119 /* EmailUndoToast.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailUndoToast.swift; sourceTree = ""; }; + AA000002000000000000120 /* AuthSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthSupport.swift; sourceTree = ""; }; + AA000002000000000000121 /* HolmesCloud.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HolmesCloud.swift; sourceTree = ""; }; + AA000002000000000000122 /* AuthService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthService.swift; sourceTree = ""; }; + AA000002000000000000124 /* SignInScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInScreen.swift; sourceTree = ""; }; B7A500020000000000000006 /* ModelJSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelJSON.swift; sourceTree = ""; }; B7A500020000000000000005 /* TextEntrySupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextEntrySupport.swift; sourceTree = ""; }; B7A500020000000000000004 /* AutonomousRunTally.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutonomousRunTally.swift; sourceTree = ""; }; @@ -262,6 +271,7 @@ buildActionMask = 2147483647; files = ( AA000001000000000000039 /* Lottie in Frameworks */, + AA000001000000000000123 /* Appwrite in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -398,6 +408,9 @@ AA000002000000000000116 /* MailComposeMatcher.swift */, AA000002000000000000117 /* EmailPredictionSources.swift */, AA000002000000000000118 /* EmailPredictionActions.swift */, + AA000002000000000000120 /* AuthSupport.swift */, + AA000002000000000000121 /* HolmesCloud.swift */, + AA000002000000000000122 /* AuthService.swift */, B7A500020000000000000006 /* ModelJSON.swift */, B7A500020000000000000005 /* TextEntrySupport.swift */, B7A500020000000000000004 /* AutonomousRunTally.swift */, @@ -491,6 +504,7 @@ children = ( AA000002000000000000107 /* GuidedDemoWindow.swift */, B7A500020000000000000F01 /* LaunchIntroView.swift */, + AA000002000000000000124 /* SignInScreen.swift */, AA000002000000000000106 /* GuidedDemoView.swift */, AA000002000000000000011 /* OnboardingFlow.swift */, AA000002000000000000012 /* OnboardingViewModel.swift */, @@ -567,6 +581,7 @@ name = holmes; packageProductDependencies = ( AA00000A000000000000001 /* Lottie */, + AA00000A000000000000002 /* Appwrite */, ); productName = holmes; productReference = AA000003000000000000000 /* holmes.app */; @@ -598,6 +613,7 @@ mainGroup = AA000005000000000000000; packageReferences = ( AA00000B000000000000001 /* XCRemoteSwiftPackageReference "lottie-ios" */, + AA00000B000000000000002 /* XCRemoteSwiftPackageReference "sdk-for-apple" */, ); productRefGroup = AA000005000000000000002 /* Products */; projectDirPath = ""; @@ -667,6 +683,10 @@ AA000001000000000000011 /* OnboardingFlow.swift in Sources */, AA000001000000000000012 /* OnboardingViewModel.swift in Sources */, AA000001000000000000013 /* WelcomeScreen.swift in Sources */, + AA000001000000000000120 /* AuthSupport.swift in Sources */, + AA000001000000000000121 /* HolmesCloud.swift in Sources */, + AA000001000000000000122 /* AuthService.swift in Sources */, + AA000001000000000000124 /* SignInScreen.swift in Sources */, AA000001000000000000014 /* HowItWorksScreen.swift in Sources */, AA000001000000000000015 /* PermissionsScreen.swift in Sources */, AA000001000000000000016 /* ReadyScreen.swift in Sources */, @@ -959,6 +979,14 @@ minimumVersion = 4.4.0; }; }; + AA00000B000000000000002 /* XCRemoteSwiftPackageReference "sdk-for-apple" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/appwrite/sdk-for-apple.git"; + requirement = { + kind = exactVersion; + version = 19.0.0; + }; + }; /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ @@ -967,6 +995,11 @@ package = AA00000B000000000000001 /* XCRemoteSwiftPackageReference "lottie-ios" */; productName = Lottie; }; + AA00000A000000000000002 /* Appwrite */ = { + isa = XCSwiftPackageProductDependency; + package = AA00000B000000000000002 /* XCRemoteSwiftPackageReference "sdk-for-apple" */; + productName = Appwrite; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = AA000008000000000000000 /* Project object */; diff --git a/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 1ebf5d3..7b5cca7 100644 --- a/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/holmes/holmes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,6 +1,15 @@ { - "originHash" : "0271592b24e5dc1185a09e3f2d980d55521827815d397c9bce8e63d502a51e84", + "originHash" : "0a14469a4b5e4b54376f903fc8d8bdbef5b871bf414067dd084750072bc67f01", "pins" : [ + { + "identity" : "async-http-client", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swift-server/async-http-client.git", + "state" : { + "revision" : "f95c908967e98c68c5ce3fd61a7974e7e869e303", + "version" : "1.36.1" + } + }, { "identity" : "lottie-ios", "kind" : "remoteSourceControl", @@ -9,6 +18,204 @@ "revision" : "a004050748dc197c56256a14dca49a035d74726c", "version" : "4.5.2" } + }, + { + "identity" : "sdk-for-apple", + "kind" : "remoteSourceControl", + "location" : "https://github.com/appwrite/sdk-for-apple.git", + "state" : { + "revision" : "7f801a9ed5f32dbf3febff374fcadb58a6447f0c", + "version" : "19.0.0" + } + }, + { + "identity" : "swift-algorithms", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-algorithms.git", + "state" : { + "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023", + "version" : "1.2.1" + } + }, + { + "identity" : "swift-asn1", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-asn1.git", + "state" : { + "revision" : "d9a5b37470adc940d22c3bcd5ca6953a516b727f", + "version" : "1.7.2" + } + }, + { + "identity" : "swift-async-algorithms", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-async-algorithms.git", + "state" : { + "revision" : "3da39bbc4e687d4192af7c9cf4eab805745a0b9c", + "version" : "1.1.5" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", + "version" : "1.3.1" + } + }, + { + "identity" : "swift-certificates", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-certificates.git", + "state" : { + "revision" : "c8aece90ea05f9866bd392a5bf13b5cae56c0e03", + "version" : "1.20.0" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", + "version" : "1.6.0" + } + }, + { + "identity" : "swift-configuration", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-configuration.git", + "state" : { + "revision" : "be76c4ad929eb6c4bcaf3351799f2adf9e6848a9", + "version" : "1.2.0" + } + }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f", + "version" : "4.5.2" + } + }, + { + "identity" : "swift-distributed-tracing", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-distributed-tracing.git", + "state" : { + "revision" : "dc4030184203ffafbb2ec614352487235d747fe0", + "version" : "1.4.1" + } + }, + { + "identity" : "swift-http-structured-headers", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-http-structured-headers.git", + "state" : { + "revision" : "933538faa42c432d385f02e07df0ace7c5ecfc47", + "version" : "1.7.0" + } + }, + { + "identity" : "swift-http-types", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-http-types.git", + "state" : { + "revision" : "bff4b6903cdc99dda49649dd52f46c11cfd3ed50", + "version" : "1.8.0" + } + }, + { + "identity" : "swift-log", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-log.git", + "state" : { + "revision" : "9c6fb14227f55d8f711ce3847dc2f419fb0ecacb", + "version" : "1.15.1" + } + }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "a931f2c1de8dd49381ce3bf2e279d033f68d8865", + "version" : "2.102.0" + } + }, + { + "identity" : "swift-nio-extras", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-extras.git", + "state" : { + "revision" : "41449336c8ecfadac6b4b5be75f9c3c306e61ced", + "version" : "1.35.1" + } + }, + { + "identity" : "swift-nio-http2", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-http2.git", + "state" : { + "revision" : "0f3e54e29c944c2e835ad52159da7d9e1c94ac69", + "version" : "1.46.0" + } + }, + { + "identity" : "swift-nio-ssl", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-ssl.git", + "state" : { + "revision" : "03827c1a9fdb2b6b00a4e93ede8861520263af8c", + "version" : "2.37.4" + } + }, + { + "identity" : "swift-nio-transport-services", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio-transport-services.git", + "state" : { + "revision" : "67787bb645a5e67d2edcdfbe48a216cc549222d5", + "version" : "1.28.0" + } + }, + { + "identity" : "swift-numerics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-numerics.git", + "state" : { + "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2", + "version" : "1.1.1" + } + }, + { + "identity" : "swift-service-context", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-service-context.git", + "state" : { + "revision" : "d0997351b0c7779017f88e7a93bc30a1878d7f29", + "version" : "1.3.0" + } + }, + { + "identity" : "swift-service-lifecycle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swift-server/swift-service-lifecycle", + "state" : { + "revision" : "7f9326b0326ff86e3646295ea6e891f68c471c5e", + "version" : "2.12.0" + } + }, + { + "identity" : "swift-system", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-system.git", + "state" : { + "revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750", + "version" : "1.8.1" + } } ], "version" : 3 diff --git a/holmes/holmes/App/AppDelegate.swift b/holmes/holmes/App/AppDelegate.swift index 129b4f4..344132e 100644 --- a/holmes/holmes/App/AppDelegate.swift +++ b/holmes/holmes/App/AppDelegate.swift @@ -17,6 +17,10 @@ class AppDelegate: NSObject, NSApplicationDelegate { // FileHandle.write then throws EPIPE, which MCPClient already handles. signal(SIGPIPE, SIG_IGN) + // Fire and forget: the service sends once per install, then at most + // once a day, and never blocks launch. + HolmesCloud.sendInstallPing() + do { if let folder = try ExtensionInstaller.refreshInstalledIfNeeded() { extensionUpdateNeedsNotice = true @@ -88,17 +92,38 @@ class AppDelegate: NSObject, NSApplicationDelegate { @MainActor private func handleAuthAndLaunch() async { - // There is no account in Holmes Local: nothing to sign in to, so launch - // goes straight to onboarding (first run) or the main app. - launch() - } - - private func launch() { + // Holmes requires an account. The SDK keeps the session between + // launches, so this only asks when no valid session exists. + let signedIn = await AuthService.shared.restoreSession() + observeSignOut() let hasCompletedOnboarding = UserDefaults.standard.bool(forKey: "hasCompletedOnboarding") - if hasCompletedOnboarding { - startMainApp() + if !hasCompletedOnboarding { + showOnboarding(requiresSignIn: !signedIn) + } else if signedIn { + startMainAppOnce() } else { - showOnboarding() + // Finished onboarding before accounts existed, or signed out. + SignInWindowController.shared.show { [weak self] in + self?.startMainAppOnce() + } + } + } + + private var signOutObserver: NSObjectProtocol? + + private func observeSignOut() { + guard signOutObserver == nil else { return } + signOutObserver = NotificationCenter.default.addObserver( + forName: .holmesDidSignOut, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + for window in NSApp.windows where window.identifier?.rawValue.contains("Settings") == true { + window.close() + } + SignInWindowController.shared.show { + self?.startMainAppOnce() + } + } } } @@ -183,8 +208,8 @@ class AppDelegate: NSObject, NSApplicationDelegate { HotkeyManager.shared.registerHotkeys() } - private func showOnboarding() { - let onboardingView = OnboardingFlow { + private func showOnboarding(requiresSignIn: Bool) { + let onboardingView = OnboardingFlow(requiresSignIn: requiresSignIn) { DispatchQueue.main.async { [weak self] in self?.finishOnboarding() } @@ -238,6 +263,16 @@ class AppDelegate: NSObject, NSApplicationDelegate { onboardingWindow = nil if window.isVisible { window.close() } } + guard AuthService.shared.isSignedIn else { + // Closed before signing in. Sign in is required, so quit; + // onboarding shows again next launch. + NSApp.terminate(nil) + return + } + startMainAppOnce() + } + + private func startMainAppOnce() { guard !mainAppStarted else { return } mainAppStarted = true startMainApp() diff --git a/holmes/holmes/App/holmesApp.swift b/holmes/holmes/App/holmesApp.swift index a826025..34f18c2 100644 --- a/holmes/holmes/App/holmesApp.swift +++ b/holmes/holmes/App/holmesApp.swift @@ -362,26 +362,48 @@ struct PlaybookToggleRow: View { struct GeneralSettingsView: View { @Binding var launchAtLogin: Bool @Binding var showNotchAnimation: Bool - + @ObservedObject private var auth = AuthService.shared + var body: some View { Form { Toggle("Launch at Login", isOn: $launchAtLogin) - + if NotchDetector.hasNotch { Toggle("Show Notch Animation", isOn: $showNotchAnimation) } - + Divider() - + LabeledContent("Side Icon Position") { Button("Reset to Default") { UserDefaults.standard.removeObject(forKey: "SideIconPosition") } } + + Divider() + + LabeledContent("Account") { + HStack(spacing: 10) { + Text(accountLabel) + .foregroundStyle(NoirColors.textSecondary) + Button("Sign Out") { + Task { @MainActor in + await auth.signOut() + NotificationCenter.default.post(name: .holmesDidSignOut, object: nil) + } + } + .disabled(!auth.isSignedIn || auth.isWorking) + } + } } .scrollContentBackground(.hidden) .padding() } + + private var accountLabel: String { + guard let user = auth.currentUser else { return "Not signed in" } + return user.email.isEmpty ? "Signed in" : user.email + } } // MARK: - Voice & Guidance (the Clicky experience) @@ -1022,7 +1044,7 @@ struct AboutSettingsView: View { .font(NoirFonts.font(size: 11, weight: .regular, design: .monospaced)) .foregroundStyle(NoirColors.textTertiary) - Text("Runs entirely on this Mac through Ollama — no account, no API key, nothing leaves the machine.") + Text("Thinks with a local model through Ollama, no API key. Your screen, voice, and tasks stay on this Mac; your account stores only your email, region, macOS version, and Holmes version to count users.") .font(NoirFonts.caption()) .foregroundStyle(NoirColors.textTertiary) .multilineTextAlignment(.center) diff --git a/holmes/holmes/Core/AuthService.swift b/holmes/holmes/Core/AuthService.swift new file mode 100644 index 0000000..69b6c7e --- /dev/null +++ b/holmes/holmes/Core/AuthService.swift @@ -0,0 +1,143 @@ +import Foundation +import Appwrite + +struct AuthUser: Equatable { + let id: String + let name: String + let email: String +} + +struct AuthFailure: LocalizedError, Equatable { + let message: String + var errorDescription: String? { message } +} + +extension Notification.Name { + /// Posted after Settings signs the user out; AppDelegate shows sign in again. + static let holmesDidSignOut = Notification.Name("HolmesDidSignOut") +} + +/// Email and password accounts through Appwrite. Signing in is required to use +/// Holmes; the SDK persists the session, so this only asks once per Mac. +@MainActor +final class AuthService: ObservableObject { + static let shared = AuthService() + + @Published private(set) var currentUser: AuthUser? + @Published private(set) var isWorking = false + + private let account = Account(HolmesCloud.client) + private static let lastEmailKey = "HolmesCloud.lastSignedInEmail" + + var isSignedIn: Bool { currentUser != nil } + + /// Restores the session the SDK stored on a previous launch. Returns true + /// when the user is signed in. Offline with a stored session counts as + /// signed in so Holmes still works without a connection. + @discardableResult + func restoreSession() async -> Bool { + do { + currentUser = try await fetchUser() + return true + } catch let error as AppwriteError where (error.code ?? 0) > 0 && (error.code ?? 0) < 500 { + currentUser = nil + return false + } catch { + guard HolmesCloud.hasStoredSession else { + currentUser = nil + return false + } + let email = UserDefaults.standard.string(forKey: Self.lastEmailKey) ?? "" + currentUser = AuthUser(id: "", name: "", email: email) + return true + } + } + + func signIn(email: String, password: String) async throws { + try validate(mode: .signIn, name: "", email: email, password: password) + isWorking = true + defer { isWorking = false } + try await createSession(email: normalized(email), password: password, mode: .signIn) + try await finishSignIn(mode: .signIn) + } + + func signUp(name: String, email: String, password: String) async throws { + try validate(mode: .createAccount, name: name, email: email, password: password) + isWorking = true + defer { isWorking = false } + do { + _ = try await account.create( + userId: ID.unique(), + email: normalized(email), + password: password, + name: name.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } catch { + throw Self.failure(for: error, mode: .createAccount) + } + try await createSession(email: normalized(email), password: password, mode: .createAccount) + try await finishSignIn(mode: .createAccount) + } + + func signOut() async { + do { + _ = try await account.deleteSession(sessionId: "current") + } catch { + print("[Auth] Remote sign out failed, clearing the local session anyway: \(error.localizedDescription)") + } + HolmesCloud.clearStoredSession() + currentUser = nil + } + + // MARK: Helpers + + private func validate(mode: AuthMode, name: String, email: String, password: String) throws { + if let problem = AuthValidation.problem(mode: mode, name: name, email: email, password: password) { + throw AuthFailure(message: problem) + } + } + + private func normalized(_ email: String) -> String { + email.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private func createSession(email: String, password: String, mode: AuthMode) async throws { + do { + _ = try await account.createEmailPasswordSession(email: email, password: password) + } catch let error as AppwriteError where error.type == "user_session_already_exists" { + // A stale session is still stored; replace it with this account's. + _ = try? await account.deleteSession(sessionId: "current") + do { + _ = try await account.createEmailPasswordSession(email: email, password: password) + } catch { + throw Self.failure(for: error, mode: mode) + } + } catch { + throw Self.failure(for: error, mode: mode) + } + } + + private func finishSignIn(mode: AuthMode) async throws { + do { + currentUser = try await fetchUser() + } catch { + throw Self.failure(for: error, mode: mode) + } + HolmesCloud.sendSignInEvent() + } + + private func fetchUser() async throws -> AuthUser { + let user = try await account.get() + UserDefaults.standard.set(user.email, forKey: Self.lastEmailKey) + return AuthUser(id: user.id, name: user.name, email: user.email) + } + + nonisolated static func failure(for error: Error, mode: AuthMode) -> AuthFailure { + if let failure = error as? AuthFailure { return failure } + if let appwrite = error as? AppwriteError { + return AuthFailure(message: AuthErrorMessages.message(code: appwrite.code, type: appwrite.type, mode: mode)) + } + // Anything that isn't an Appwrite response is a transport failure. + return AuthFailure(message: AuthErrorMessages.offline) + } +} diff --git a/holmes/holmes/Core/AuthSupport.swift b/holmes/holmes/Core/AuthSupport.swift new file mode 100644 index 0000000..f890060 --- /dev/null +++ b/holmes/holmes/Core/AuthSupport.swift @@ -0,0 +1,218 @@ +import Foundation + +// Pure helpers behind sign in and install tracking. Nothing here imports the +// Appwrite SDK, so holmes/tests/run-auth-validation-tests.sh can compile this +// file on its own. + +// MARK: - Input validation + +enum AuthMode: String, CaseIterable { + case signIn + case createAccount +} + +enum AuthValidation { + static let minimumPasswordLength = 8 + + static func isValidEmail(_ raw: String) -> Bool { + let email = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard email.count <= 254, !email.contains(" ") else { return false } + let parts = email.split(separator: "@", omittingEmptySubsequences: false) + guard parts.count == 2 else { return false } + let local = parts[0], domain = parts[1] + guard !local.isEmpty, local.count <= 64 else { return false } + let labels = domain.split(separator: ".", omittingEmptySubsequences: false) + guard labels.count >= 2, labels.allSatisfy({ !$0.isEmpty }) else { return false } + guard let tld = labels.last, tld.count >= 2, tld.allSatisfy({ $0.isLetter }) else { return false } + return true + } + + /// The first problem with the form, phrased for the user, or nil when the + /// input is fine to send. + static func problem(mode: AuthMode, name: String, email: String, password: String) -> String? { + if mode == .createAccount, name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return "Enter your name." + } + let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedEmail.isEmpty { return "Enter your email address." } + if !isValidEmail(trimmedEmail) { return "That email address doesn\u{2019}t look right." } + if password.isEmpty { return "Enter your password." } + if mode == .createAccount, password.count < minimumPasswordLength { + return "Use a password of at least \(minimumPasswordLength) characters." + } + return nil + } +} + +// MARK: - Error messages + +enum AuthErrorMessages { + static let offline = "Holmes can\u{2019}t reach the sign in server. Check your internet connection and try again." + static let generic = "Something went wrong signing you in. Please try again." + + /// Maps an Appwrite error code and type to a user facing message. `code` + /// is nil or 0 when the request never got an HTTP response. + static func message(code: Int?, type: String?, mode: AuthMode) -> String { + let type = type ?? "" + switch type { + case "user_invalid_credentials", "user_password_mismatch": + return "That email and password don\u{2019}t match. Check them and try again." + case "user_already_exists", "user_email_already_exists": + return "An account with this email already exists. Sign in instead." + case "password_recently_used", "password_personal_data": + return "Choose a different password." + case "user_blocked": + return "This account has been disabled." + case "general_rate_limit_exceeded": + return "Too many attempts. Wait a minute, then try again." + case "user_session_already_exists": + return "You\u{2019}re already signed in." + default: + break + } + switch code ?? 0 { + case 0: + return offline + case 401: + return mode == .signIn + ? "That email and password don\u{2019}t match. Check them and try again." + : generic + case 409: + return "An account with this email already exists. Sign in instead." + case 400: + if type == "general_argument_invalid" || type.isEmpty { + return mode == .createAccount + ? "Check your details. Passwords need at least \(AuthValidation.minimumPasswordLength) characters." + : "Check your email and password, then try again." + } + return generic + case 429: + return "Too many attempts. Wait a minute, then try again." + case 500...599: + return "The sign in server is having trouble. Try again in a moment." + default: + return generic + } + } +} + +// MARK: - Device facts + +struct DeviceFacts: Equatable { + var holmesVersion: String + var macosVersion: String + var macModel: String + var region: String + var locale: String + + static func formatOSVersion(major: Int, minor: Int, patch: Int) -> String { + "\(major).\(minor).\(patch)" + } + + /// sysctl returns a NUL terminated C string; keep what precedes the first NUL. + static func modelString(fromSysctlBytes bytes: [CChar]) -> String { + let prefix = bytes.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) } + let value = String(decoding: prefix, as: UTF8.self).trimmingCharacters(in: .whitespaces) + return value.isEmpty ? "unknown" : value + } + + static func normalized(_ value: String?, fallback: String = "unknown") -> String { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? fallback : trimmed + } + + /// The JSON body for the "track" function. Email is never included; the + /// function reads the verified user server side. + func trackBody(event: String, installID: String) -> String { + let payload: [String: String] = [ + "event": event, + "install_id": installID, + "holmes_version": holmesVersion, + "macos_version": macosVersion, + "mac_model": macModel, + "region": region, + "locale": locale, + ] + guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]), + let json = String(data: data, encoding: .utf8) else { return "{}" } + return json + } +} + +// MARK: - Install ping throttle + +protocol CloudKeyValueStore: AnyObject { + func string(forKey key: String) -> String? + func date(forKey key: String) -> Date? + func set(_ value: Any?, forKey key: String) +} + +final class UserDefaultsCloudStore: CloudKeyValueStore { + private let defaults: UserDefaults + init(_ defaults: UserDefaults = .standard) { self.defaults = defaults } + func string(forKey key: String) -> String? { defaults.string(forKey: key) } + func date(forKey key: String) -> Date? { defaults.object(forKey: key) as? Date } + func set(_ value: Any?, forKey key: String) { defaults.set(value, forKey: key) } +} + +/// Decides when the install ping is due and records success. The first ping +/// goes out as soon as possible; after that at most once every 24 hours. A +/// failed send records nothing, so the next launch simply tries again. +final class InstallPingThrottle { + static let installIDKey = "HolmesCloud.installID" + static let lastSentKey = "HolmesCloud.installPingLastSent" + static let interval: TimeInterval = 24 * 60 * 60 + + private let store: CloudKeyValueStore + private let now: () -> Date + private let lock = NSLock() + private var inFlight = false + + init(store: CloudKeyValueStore, now: @escaping () -> Date = Date.init) { + self.store = store + self.now = now + } + + /// A random UUID created the first time it is asked for, then reused. + var installID: String { + lock.lock(); defer { lock.unlock() } + if let existing = store.string(forKey: Self.installIDKey), UUID(uuidString: existing) != nil { + return existing + } + let fresh = UUID().uuidString + store.set(fresh, forKey: Self.installIDKey) + return fresh + } + + var isDue: Bool { + guard let last = store.date(forKey: Self.lastSentKey) else { return true } + let elapsed = now().timeIntervalSince(last) + // A clock moved backwards counts as due, so a bad date can't mute pings forever. + return elapsed >= Self.interval || elapsed < 0 + } + + /// Runs `send` when due and not already running. Returns true only when a + /// send happened and succeeded. Never throws. + @discardableResult + func runIfDue(_ send: () async -> Bool) async -> Bool { + guard claim() else { return false } + let ok = await send() + release(succeeded: ok) + return ok + } + + private func claim() -> Bool { + lock.withLock { + guard !inFlight, isDue else { return false } + inFlight = true + return true + } + } + + private func release(succeeded: Bool) { + lock.withLock { + if succeeded { store.set(now(), forKey: Self.lastSentKey) } + inFlight = false + } + } +} diff --git a/holmes/holmes/Core/HolmesCloud.swift b/holmes/holmes/Core/HolmesCloud.swift new file mode 100644 index 0000000..709b2b2 --- /dev/null +++ b/holmes/holmes/Core/HolmesCloud.swift @@ -0,0 +1,106 @@ +import Foundation +import Appwrite +import AppwriteEnums + +/// The only network service Holmes talks to besides the local model: Appwrite, +/// for the account and a tiny usage count. What is sent is exactly +/// `DeviceFacts.trackBody`: an install id, the Holmes and macOS versions, the +/// Mac model, region and locale. Screen, voice and task content never leave +/// this Mac. +enum HolmesCloud { + static let endpoint = "https://sfo.cloud.appwrite.io/v1" + static let projectID = "holmes" + static let trackFunctionID = "track" + + static let client: Client = Client() + .setEndpoint(endpoint) + .setProject(projectID) + + private static let throttle = InstallPingThrottle(store: UserDefaultsCloudStore()) + + static var installID: String { throttle.installID } + + // MARK: Device facts + + static var deviceFacts: DeviceFacts { + let os = ProcessInfo.processInfo.operatingSystemVersion + return DeviceFacts( + holmesVersion: DeviceFacts.normalized( + Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String), + macosVersion: DeviceFacts.formatOSVersion( + major: os.majorVersion, minor: os.minorVersion, patch: os.patchVersion), + macModel: macModel(), + region: DeviceFacts.normalized(Locale.current.region?.identifier), + locale: DeviceFacts.normalized(Locale.current.identifier) + ) + } + + private static func macModel() -> String { + var size = 0 + guard sysctlbyname("hw.model", nil, &size, nil, 0) == 0, size > 0 else { return "unknown" } + var bytes = [CChar](repeating: 0, count: size) + guard sysctlbyname("hw.model", &bytes, &size, nil, 0) == 0 else { return "unknown" } + return DeviceFacts.modelString(fromSysctlBytes: bytes) + } + + // MARK: Events + + /// Fire and forget. Sends once per install, then at most once a day. A + /// failure is only logged; the next launch tries again. + static func sendInstallPing() { + Task.detached(priority: .utility) { + await throttle.runIfDue { await track(event: "install") } + } + } + + /// Fire and forget, after a successful sign in or account creation. + static func sendSignInEvent() { + Task.detached(priority: .utility) { + _ = await track(event: "signin") + } + } + + @discardableResult + static func track(event: String) async -> Bool { + let body = deviceFacts.trackBody(event: event, installID: installID) + do { + let execution = try await Functions(client).createExecution( + functionId: trackFunctionID, + body: body, + async: false, + path: "/", + method: .pOST, + headers: ["content-type": "application/json"] + ) + let ok = (200..<300).contains(execution.responseStatusCode) + && execution.responseBody.replacingOccurrences(of: " ", with: "").contains("\"ok\":true") + if !ok { + print("[HolmesCloud] \(event) event not accepted (status \(execution.responseStatusCode))") + } + return ok + } catch { + print("[HolmesCloud] \(event) event failed: \(error.localizedDescription)") + return false + } + } + + // MARK: Stored session + + /// The SDK keeps the session cookie in UserDefaults under the endpoint host. + private static var cookieKey: String { URL(string: endpoint)?.host ?? "" } + + /// True when a session cookie is stored locally. Used only when the server + /// can't be reached, so an offline launch doesn't lock a signed in user out. + static var hasStoredSession: Bool { + let cookies = UserDefaults.standard.stringArray(forKey: cookieKey) ?? [] + return cookies.contains { cookie in + cookie.hasPrefix("a_session_\(projectID)=") + && !cookie.hasPrefix("a_session_\(projectID)=;") + && !cookie.lowercased().contains("max-age=0") + } + } + + static func clearStoredSession() { + UserDefaults.standard.removeObject(forKey: cookieKey) + } +} diff --git a/holmes/holmes/Views/Onboarding/OnboardingFlow.swift b/holmes/holmes/Views/Onboarding/OnboardingFlow.swift index 855a6ef..2929a3b 100644 --- a/holmes/holmes/Views/Onboarding/OnboardingFlow.swift +++ b/holmes/holmes/Views/Onboarding/OnboardingFlow.swift @@ -1,11 +1,17 @@ import SwiftUI struct OnboardingFlow: View { - @StateObject private var viewModel = OnboardingViewModel() - // The brand intro plays once before Welcome; Reduce Motion skips it. + @StateObject private var viewModel: OnboardingViewModel + // The brand intro plays once before the first screen; Reduce Motion skips it. @State private var showLaunchIntro = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion let onComplete: () -> Void - + + /// `requiresSignIn` is false when a valid session was restored at launch. + init(requiresSignIn: Bool = false, onComplete: @escaping () -> Void) { + _viewModel = StateObject(wrappedValue: OnboardingViewModel(startStep: requiresSignIn ? .signIn : .welcome)) + self.onComplete = onComplete + } + var body: some View { ZStack { VisualEffectBlur(material: .hudWindow, blendingMode: .behindWindow) @@ -13,21 +19,28 @@ struct OnboardingFlow: View { VStack(spacing: 0) { HStack { Spacer() - - if viewModel.currentStep != .welcome { + + if viewModel.currentStep.showsStepIndicator { StepIndicator( - currentStep: viewModel.currentStep.rawValue, - totalSteps: OnboardingStep.allCases.count + currentStep: viewModel.currentStep.indicatorIndex, + totalSteps: OnboardingStep.indicatorSteps.count ) } - + Spacer() } .padding(.top, 40) .padding(.horizontal, 40) - + Group { switch viewModel.currentStep { + case .signIn: + // Held back until the intro ends, like Welcome. + if !showLaunchIntro { + SignInScreen(auth: .shared) { + viewModel.goToStep(.welcome) + } + } case .welcome: // Held back until the intro ends so its entrance animation plays. if !showLaunchIntro { @@ -101,7 +114,7 @@ struct LocalModelScreen: View { .font(NoirFonts.headline()) .foregroundColor(NoirColors.textPrimary) - Text("Holmes thinks with an open model that runs on this Mac\nthrough Ollama. Nothing you do is sent to a server.") + Text("Holmes thinks with an open model that runs on this Mac\nthrough Ollama. What you do on screen is never sent to a server.") .font(NoirFonts.caption()) .foregroundColor(NoirColors.textSecondary) .multilineTextAlignment(.center) diff --git a/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift b/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift index 9deb54d..12af74f 100644 --- a/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift +++ b/holmes/holmes/Views/Onboarding/OnboardingViewModel.swift @@ -4,21 +4,35 @@ import AppKit import ScreenCaptureKit enum OnboardingStep: Int, CaseIterable { - case welcome = 0 - case howItWorks = 1 - case permissions = 2 + /// Required account step, skipped when a session already exists. + case signIn = 0 + case welcome = 1 + case howItWorks = 2 + case permissions = 3 /// "Your local model": get Ollama running and the default model pulled, /// so a first-run user leaves onboarding with a working local brain. - case localModel = 3 + case localModel = 4 /// Install + pair the bundled browser extension (exact page reads). - case browser = 4 + case browser = 5 /// Optional Composio connection for the read-only playbook tools. - case integrations = 5 - case ready = 6 + case integrations = 6 + case ready = 7 + + /// Sign in and Welcome are entry screens without progress dots. + var showsStepIndicator: Bool { self != .signIn && self != .welcome } + + /// The steps the progress dots count. Sign in is not one of them. + static var indicatorSteps: [OnboardingStep] { allCases.filter { $0 != .signIn } } + + var indicatorIndex: Int { Self.indicatorSteps.firstIndex(of: self) ?? 0 } } class OnboardingViewModel: ObservableObject { - @Published var currentStep: OnboardingStep = .welcome + @Published var currentStep: OnboardingStep + + init(startStep: OnboardingStep = .welcome) { + currentStep = startStep + } @Published var hasScreenRecordingPermission = false @Published var hasAccessibilityPermission = false @Published var hasAutomationPermission = false diff --git a/holmes/holmes/Views/Onboarding/SignInScreen.swift b/holmes/holmes/Views/Onboarding/SignInScreen.swift new file mode 100644 index 0000000..5d3299f --- /dev/null +++ b/holmes/holmes/Views/Onboarding/SignInScreen.swift @@ -0,0 +1,242 @@ +import SwiftUI +import AppKit + +/// Required account step. Used as the first onboarding step and, for people +/// who finished onboarding before accounts existed or who signed out, inside +/// its own small window at launch. There is no skip. +struct SignInScreen: View { + @ObservedObject var auth: AuthService + let onSignedIn: () -> Void + + @State private var mode: AuthMode + @State private var name = "" + @State private var email = "" + @State private var password = "" + @State private var errorMessage: String? + @State private var contentOpacity: CGFloat = 0 + + static let privacyLine = "Holmes stores your email, region, macOS version, and Holmes version to count users. Everything else stays on this Mac." + + init(auth: AuthService, initialMode: AuthMode = .createAccount, onSignedIn: @escaping () -> Void) { + self.auth = auth + self._mode = State(initialValue: initialMode) + self.onSignedIn = onSignedIn + } + + var body: some View { + VStack(spacing: 0) { + Spacer() + + VStack(spacing: 24) { + VStack(spacing: 10) { + Text("holmes") + .font(NoirFonts.brand(size: 48)) + .foregroundStyle(NoirColors.charcoalDark) + + Text(mode == .signIn ? "Sign in to continue" : "Create your Holmes account") + .font(NoirFonts.body()) + .foregroundStyle(NoirColors.deepTeal) + } + + modePicker + + VStack(spacing: 10) { + if mode == .createAccount { + NoirFormField("Name", text: $name) + } + NoirFormField("Email", text: $email) + NoirFormField("Password", text: $password, isSecure: true) + + if mode == .createAccount { + Text("At least \(AuthValidation.minimumPasswordLength) characters.") + .font(NoirFonts.caption()) + .foregroundStyle(NoirColors.textTertiary) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .onSubmit(submit) + .disabled(auth.isWorking) + + if let errorMessage { + Text(errorMessage) + .font(NoirFonts.caption()) + .foregroundStyle(NoirColors.error) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .transition(.opacity) + } + } + .frame(maxWidth: 340) + .opacity(contentOpacity) + + Spacer() + + VStack(spacing: 16) { + HStack(spacing: 12) { + if auth.isWorking { + ProgressView() + .controlSize(.small) + .tint(NoirColors.accent) + } + NoirButton(auth.isWorking ? workingTitle : primaryTitle, icon: "arrow.right", action: submit) + .disabled(auth.isWorking) + } + + Text(Self.privacyLine) + .font(NoirFonts.caption()) + .foregroundStyle(NoirColors.textTertiary) + .multilineTextAlignment(.center) + .lineSpacing(3) + .frame(maxWidth: 380) + .fixedSize(horizontal: false, vertical: true) + } + .opacity(contentOpacity) + .padding(.bottom, 44) + .padding(.horizontal, 32) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .animation(.easeInOut(duration: 0.15), value: errorMessage) + .onAppear { + withAnimation(.easeOut(duration: 0.5).delay(0.1)) { + contentOpacity = 1.0 + } + } + } + + private var primaryTitle: String { mode == .signIn ? "Sign In" : "Create Account" } + private var workingTitle: String { mode == .signIn ? "Signing In" : "Creating Account" } + + private var modePicker: some View { + HStack(spacing: 3) { + modeButton(.signIn, title: "Sign in") + modeButton(.createAccount, title: "Create account") + } + .padding(3) + .background(NoirColors.glassChrome) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .glassBorder(cornerRadius: 8) + .disabled(auth.isWorking) + } + + private func modeButton(_ target: AuthMode, title: String) -> some View { + Button { + withAnimation(.easeInOut(duration: 0.15)) { + mode = target + errorMessage = nil + } + } label: { + Text(title) + .font(NoirFonts.font(size: 11, weight: .medium, design: .monospaced)) + .foregroundStyle(mode == target ? NoirColors.ctaForeground : NoirColors.textSecondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 7) + .background( + RoundedRectangle(cornerRadius: 6) + .fill(mode == target ? NoirColors.ctaBackground : Color.clear) + ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + private func submit() { + guard !auth.isWorking else { return } + if let problem = AuthValidation.problem(mode: mode, name: name, email: email, password: password) { + errorMessage = problem + return + } + errorMessage = nil + let mode = self.mode + Task { @MainActor in + do { + if mode == .signIn { + try await auth.signIn(email: email, password: password) + } else { + try await auth.signUp(name: name, email: email, password: password) + } + password = "" + onSignedIn() + } catch { + errorMessage = AuthService.failure(for: error, mode: mode).message + } + } + } +} + +/// The standalone sign in window for people past onboarding without a session. +@MainActor +final class SignInWindowController: NSObject, NSWindowDelegate { + static let shared = SignInWindowController() + + private var window: NSWindow? + private var onSignedIn: (() -> Void)? + private var completed = false + + var isVisible: Bool { window?.isVisible ?? false } + + func show(onSignedIn: @escaping () -> Void) { + self.onSignedIn = onSignedIn + if let window { + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + return + } + completed = false + + let root = ZStack { + VisualEffectBlur(material: .hudWindow, blendingMode: .behindWindow) + .ignoresSafeArea() + SignInScreen(auth: .shared, initialMode: .signIn) { [weak self] in + self?.finish() + } + } + .frame(width: 480, height: 600) + .preferredColorScheme(.dark) + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 480, height: 600), + styleMask: [.titled, .closable, .fullSizeContentView], + backing: .buffered, + defer: false + ) + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + window.isMovableByWindowBackground = true + window.isOpaque = false + window.backgroundColor = .clear + window.isReleasedWhenClosed = false + window.delegate = self + window.center() + window.contentView = NSHostingView(rootView: root) + window.makeKeyAndOrderFront(nil) + self.window = window + NSApp.activate(ignoringOtherApps: true) + } + + private func finish() { + completed = true + let finished = window + window = nil + finished?.close() + let callback = onSignedIn + onSignedIn = nil + callback?() + } + + func windowWillClose(_ notification: Notification) { + guard !completed else { return } + // Signing in is required: closing the window quits, and the next + // launch asks again. + window = nil + NSApp.terminate(nil) + } +} + +#Preview { + ZStack { + NoirColors.skyBlue.ignoresSafeArea() + SignInScreen(auth: .shared) {} + } + .frame(width: 600, height: 700) + .preferredColorScheme(.dark) +} diff --git a/holmes/tests/AuthValidationTests.swift b/holmes/tests/AuthValidationTests.swift new file mode 100644 index 0000000..124da88 --- /dev/null +++ b/holmes/tests/AuthValidationTests.swift @@ -0,0 +1,121 @@ +import Foundation + +final class MemoryCloudStore: CloudKeyValueStore { + var values: [String: Any] = [:] + func string(forKey key: String) -> String? { values[key] as? String } + func date(forKey key: String) -> Date? { values[key] as? Date } + func set(_ value: Any?, forKey key: String) { values[key] = value } +} + +final class TestClock { + var now = Date(timeIntervalSince1970: 1_800_000_000) + func advance(hours: Double) { now = now.addingTimeInterval(hours * 3600) } +} + +@main +struct AuthValidationTests { + static func main() async { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + + // Email format. + for good in ["a@b.co", "holmes.smoketest+1@example.com", " person@mail.example.org ", "x_y@sub.domain.io"] { + expect(AuthValidation.isValidEmail(good), "Valid email rejected: \(good)") + } + for bad in ["", "plain", "@example.com", "a@", "a@b", "a@b.", "a@.com", "a b@c.com", "a@@b.com", "a@b.c", "a@b.c0m"] { + expect(!AuthValidation.isValidEmail(bad), "Invalid email accepted: \(bad)") + } + + // Form problems, in order. + expect(AuthValidation.problem(mode: .createAccount, name: " ", email: "a@b.co", password: "12345678") == "Enter your name.", + "Create account needs a name") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "a@b.co", password: "x") == nil, + "Sign in needs no name and no minimum length") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "", password: "x") == "Enter your email address.", + "Empty email is reported") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "nope", password: "x")?.contains("look right") == true, + "Malformed email is reported") + expect(AuthValidation.problem(mode: .signIn, name: "", email: "a@b.co", password: "") == "Enter your password.", + "Empty password is reported") + expect(AuthValidation.problem(mode: .createAccount, name: "Ann", email: "a@b.co", password: "1234567")?.contains("at least 8") == true, + "Seven character password is too short") + expect(AuthValidation.problem(mode: .createAccount, name: "Ann", email: "a@b.co", password: "12345678") == nil, + "Eight character password is fine") + + // Error mapping. + let invalid = AuthErrorMessages.message(code: 401, type: "user_invalid_credentials", mode: .signIn) + expect(invalid.contains("don\u{2019}t match"), "Invalid credentials message") + let exists = AuthErrorMessages.message(code: 409, type: "user_already_exists", mode: .createAccount) + expect(exists.contains("already exists") && exists.contains("Sign in"), "Existing user is told to sign in") + expect(AuthErrorMessages.message(code: 409, type: nil, mode: .createAccount) == exists, "Bare 409 means existing user") + expect(AuthErrorMessages.message(code: 400, type: "general_argument_invalid", mode: .createAccount).contains("at least 8"), + "Invalid argument on sign up mentions password length") + expect(AuthErrorMessages.message(code: nil, type: nil, mode: .signIn) == AuthErrorMessages.offline, "No response means offline") + expect(AuthErrorMessages.message(code: 0, type: "", mode: .createAccount) == AuthErrorMessages.offline, "Code 0 means offline") + expect(AuthErrorMessages.message(code: 429, type: "general_rate_limit_exceeded", mode: .signIn).contains("Too many attempts"), + "Rate limit message") + expect(AuthErrorMessages.message(code: 429, type: nil, mode: .signIn).contains("Too many attempts"), "Bare 429 is rate limit") + expect(AuthErrorMessages.message(code: 401, type: "", mode: .signIn).contains("don\u{2019}t match"), "Bare 401 on sign in") + expect(AuthErrorMessages.message(code: 503, type: "general_server_error", mode: .signIn).contains("having trouble"), + "Server errors are named") + expect(AuthErrorMessages.message(code: 418, type: "something_new", mode: .signIn) == AuthErrorMessages.generic, + "Unknown errors fall back to generic") + + // Device facts formatting. + expect(DeviceFacts.formatOSVersion(major: 15, minor: 3, patch: 1) == "15.3.1", "OS version is major.minor.patch") + expect(DeviceFacts.formatOSVersion(major: 26, minor: 0, patch: 0) == "26.0.0", "Zero parts are kept") + let model: [CChar] = Array("Mac15,6".utf8CString) + [0, 0] + expect(DeviceFacts.modelString(fromSysctlBytes: model) == "Mac15,6", "sysctl model stops at NUL") + expect(DeviceFacts.modelString(fromSysctlBytes: [0]) == "unknown", "Empty model is unknown") + expect(DeviceFacts.normalized(nil) == "unknown" && DeviceFacts.normalized(" US ") == "US", "Normalization") + let facts = DeviceFacts(holmesVersion: "0.1.3", macosVersion: "15.3.1", macModel: "Mac15,6", region: "US", locale: "en_US") + let body = facts.trackBody(event: "install", installID: "11111111-2222-3333-4444-555555555555") + let decoded = (try? JSONSerialization.jsonObject(with: Data(body.utf8))) as? [String: String] ?? [:] + expect(decoded == ["event": "install", "install_id": "11111111-2222-3333-4444-555555555555", + "holmes_version": "0.1.3", "macos_version": "15.3.1", "mac_model": "Mac15,6", + "region": "US", "locale": "en_US"], "Track body has exactly the documented fields") + expect(!body.contains("email"), "Track body never carries an email") + + // Install id is created once. + let store = MemoryCloudStore() + let clock = TestClock() + let throttle = InstallPingThrottle(store: store, now: { clock.now }) + let id = throttle.installID + expect(id.count == 36 && UUID(uuidString: id) != nil, "Install id is a 36 character UUID") + expect(throttle.installID == id, "Install id is stable") + expect(InstallPingThrottle(store: store).installID == id, "Install id survives a new launch") + + // Throttle: first send, once per day, retry after failure. + var sends = 0 + expect(throttle.isDue, "First ping is due") + let failedSend = await throttle.runIfDue { sends += 1; return false } + expect(failedSend == false, "Failed send reports false") + expect(store.date(forKey: InstallPingThrottle.lastSentKey) == nil && throttle.isDue, "Failure records nothing and stays due") + let goodSend = await throttle.runIfDue { sends += 1; return true } + expect(goodSend, "Successful send reports true") + expect(sends == 2 && !throttle.isDue, "Success records the date") + clock.advance(hours: 23) + let earlySend = await throttle.runIfDue { sends += 1; return true } + expect(earlySend == false && sends == 2, "Not due again within a day") + clock.advance(hours: 1) + expect(throttle.isDue, "Due again after 24 hours") + let nextDaySend = await throttle.runIfDue { sends += 1; return true } + expect(nextDaySend && sends == 3, "Second day sends once") + clock.advance(hours: -5) + expect(throttle.isDue, "A clock moved backwards counts as due") + + // Throttle: no overlapping sends. + let fresh = InstallPingThrottle(store: MemoryCloudStore(), now: { clock.now }) + var overlapping = 0 + let first = Task { await fresh.runIfDue { overlapping += 1; try? await Task.sleep(nanoseconds: 200_000_000); return true } } + try? await Task.sleep(nanoseconds: 50_000_000) + let second = await fresh.runIfDue { overlapping += 1; return true } + let firstResult = await first.value + expect(firstResult && !second && overlapping == 1, "A send in flight blocks a second one") + + print("Passed \(checks) auth validation, error mapping, device facts and install ping checks") + } +} diff --git a/holmes/tests/run-auth-validation-tests.sh b/holmes/tests/run-auth-validation-tests.sh new file mode 100755 index 0000000..f200822 --- /dev/null +++ b/holmes/tests/run-auth-validation-tests.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -euo pipefail +auth_validation_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +auth_validation_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-auth-validation.XXXXXX") +trap 'rm -rf "$auth_validation_test_dir"' EXIT +cd "$auth_validation_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/AuthSupport.swift \ + holmes/tests/AuthValidationTests.swift \ + -o "$auth_validation_test_dir/auth-validation-tests" +"$auth_validation_test_dir/auth-validation-tests"