diff --git a/README.md b/README.md index 6a119696..5acefb7f 100644 --- a/README.md +++ b/README.md @@ -27,45 +27,31 @@ Sideloading tools tend to fail in a few recurring ways. IPAForge is designed aro | Common failure | How IPAForge handles it | |---|---| -| Apple ID sign-in errors (`-80045`) | Anisette servers are health-checked and fall back automatically; macOS uses native anisette | +| Apple ID sign-in errors (`-80045`) | Anisette servers come from SideStore's up-to-date list and fall back automatically, or you choose or add your own in Settings | | `HTTP 404` when downloading SideStore or LiveContainer | Releases are resolved through the GitHub API from a catalog that can be updated remotely, never from hard-coded URLs | | "Unable to verify app" after installing | The signer matches Apple `codesign` byte for byte, and each extension gets the entitlements from its own profile | | Errors that don't say what to do | Every failure has a stable error code, a plain-language explanation and the fixes that apply | ## Features -- **One-click SideStore.** Install SideStore, or LiveContainer with SideStore, from the Stable or Nightly channel. The pairing file and signing certificate are placed automatically. -- **Keep apps working.** The Apps page lists what IPAForge installed, with when each app expires, and refreshes them (signed again, data kept) with one press or by itself before they expire. It updates them from their source too. -- **Preload apps.** Drop .ipa files, choose them, add a link, or browse apps from the catalog (LiveContainer, StikDebug, Feather…), SideStore's source and any AltStore-format source you add. Each app is checked before anything changes: its version, the App IDs it needs, whether the device can run it, and whether it updates one already installed. Then they install in one run. -- **Repair SideStore.** IPAForge checks, line by line, what keeps SideStore from refreshing your apps by itself (who signed it, its certificate, its pairing file, when it expires) and fixes it in one go. -- **SideStore links and QR codes.** Add a source to SideStore on the iPhone, or have SideStore install an app, by scanning a code. -- **A checklist for each device.** What it needs for its iOS version (Trust, a passcode, Developer Mode, trusting your Apple ID, LocalDevVPN for SideStore), ticked as you go. -- **Clear install plan.** Before anything changes, IPAForge shows what the install uses: App IDs and how many are left this week, free-app slots on the device, whether the certificate is reused, and the team. -- **Live progress.** Every step reports what it did, for example the release it found, whether a saved session was reused, or how many App IDs it registered. -- **Recovery, not dead ends.** Failures lead to a screen with the fixes that apply, such as continuing from where the run stopped or switching Apple ID. Diagnostics can be copied, and an issue report opens pre-filled. -- **Multiple Apple IDs.** Saved in the system keychain, with free and paid teams, and a quick switch when one is blocked on a device. +- **One-click SideStore.** SideStore, or LiveContainer with SideStore, Stable or Nightly. The pairing file and certificate are placed for you. +- **Preload your apps.** Drop .ipa files, paste a link, or browse the catalog, SideStore's source and any AltStore-format source you add. Each app is checked before anything changes, then they all install in one run. +- **Apps that don't expire.** See when each app expires. Refresh works like SideStore's: a new profile while your certificate is valid, nothing reinstalled. IPAForge can refresh them by itself before they expire. +- **Repair SideStore.** Checks what keeps SideStore from refreshing by itself, line by line, and fixes it in one go. +- **QR codes for SideStore.** Add a source to SideStore on your iPhone, or have SideStore install an app, by scanning a code. +- **A checklist for each iPhone.** Trust, passcode, Developer Mode, trusting your Apple ID, LocalDevVPN: what your iOS version needs, ticked as you go. +- **Recovery, not dead ends.** Every failure has a screen with the fixes that apply, copyable diagnostics and a pre-filled bug report. +- **Live progress.** Every step shows what it's doing: speed and time left while sending the app, Apple's steps, and iOS's own install progress, over USB or Wi-Fi. +- **Logs you can share.** Every step IPAForge took, with search and filters, saved to a file to attach to a bug report. +- **Several Apple IDs.** Two-factor sign-in with a code on your devices or by text. Kept in your system keychain, free and paid teams, with a quick switch when Apple blocks one on a device. +- **Anisette servers your way.** IPAForge picks a working server by itself from SideStore's list, with its own servers as a backup. Or choose one, add your own (a server on your computer included), and test each one. - **Works within Apple's limits.** The App ID quota, the three-app limit for free accounts and certificate limits are checked before any change, and each is explained. -- **Your language.** The language follows the system, and right-to-left languages are supported. Six languages today, every language iOS supports by 1.0. -- **Themes.** Six colour palettes, each with light and dark variants. -- **Updates itself.** IPAForge checks for a new version when it opens and installs it, each update checked against its release's Sigstore signature first. **What's new** says what changed, in plain words. +- **Updates itself.** A new version installs when IPAForge opens, after its release signature checks out, and What's new tells you what changed. +- **Your language, your look.** Six languages, right to left included, and six colour themes in light and dark. -Coming next: guided onboarding, management tools for certificates and App IDs, and wireless pairing with the iOS 17+ remote pairing file. Installing over Wi-Fi to a device paired before already works. +Sideload signing has been verified against real devices and Apple accounts: Apple's own `codesign --verify --deep --strict` accepts the output, including a full SideStore build signed in about half a second. Details: [Code Signing](docs/signing.md). -## Project status - -| Component | Package | Status | -|---|---|---| -| Code signing | `@ipaforge/signer` | ✅ Complete: matches Apple `codesign` on golden fixtures, verified with a real Apple Development certificate | -| Device communication | `@ipaforge/device` | ✅ Complete: usbmux, lockdown, pairing, AFC, house_arrest, installation_proxy, misagent | -| Apple account | `@ipaforge/apple` | ✅ Complete: sign-in with two-factor authentication, anisette with fallback, saved accounts | -| Developer services | `@ipaforge/apple` | ✅ Complete: teams, certificates, App IDs, app groups, devices, provisioning profiles | -| Release catalog | `@ipaforge/catalog` | ✅ Complete: GitHub release resolution, mirrors, verified downloads, cache, AltStore-format app sources | -| Install engine | `@ipaforge/installer` | ✅ Complete: resumable pipelines, install flows, free-app limit, error catalogue | -| Engine ⇄ UI protocol | `@ipaforge/rpc` | ✅ Complete: typed, validated messages over Electron IPC, and the update channel | -| User interface | `@ipaforge/ui` | ✅ Install and preload complete: accounts, devices with their checklist, the install run with its questions, step details and recovery, Preload with app sources, Apps with refresh, Repair SideStore, the log viewer, and What's new, in six languages, checked by screenshot and WCAG 2.2 AA tests; onboarding comes next | -| Desktop app | `apps/desktop` | ✅ Complete: installers for macOS (DMG, zip), Windows (NSIS, MSI) and Linux (AppImage, deb, rpm), built, Sigstore-signed and published by CI on a version tag; updates itself, checking each update's signature. Windows code signing and Apple notarisation come with 1.0 | - -Sideload signing has been verified against real devices and Apple accounts. Apple's own `codesign --verify --deep --strict` accepts the output, including a full SideStore build signed in about half a second. Details: [Code Signing](docs/signing.md). +Coming next: guided onboarding, management tools for certificates and App IDs, and wireless pairing with the iOS 17+ remote pairing file. Installing over Wi-Fi to a device paired before already works. ## Requirements diff --git a/apps/desktop/src/main/adapters/adapters.test.ts b/apps/desktop/src/main/adapters/adapters.test.ts index 6e254c39..86cdbb00 100644 --- a/apps/desktop/src/main/adapters/adapters.test.ts +++ b/apps/desktop/src/main/adapters/adapters.test.ts @@ -338,6 +338,37 @@ describe('encrypted file secret store', () => { }) }) +describe('encrypted file secret store, when the keychain says no', () => { + it('asks for the key again next time, so a later Allow is used', async () => { + const { createEncryptedFileSecretStore } = await import( + '@desktop/main/adapters/encrypted-file-secret-store.ts' + ) + const dir = await mkdtemp(join(tmpdir(), 'ipaforge-enc-')) + try { + const key = crypto.getRandomValues(new Uint8Array(32)) + let asked = 0 + const store = createEncryptedFileSecretStore( + join(dir, 'secrets.enc'), + async () => { + asked += 1 + if (asked === 1) throw new Error('denied') + return key + } + ) + await expect( + store.set('apple/session/x', utf8Encode('value')) + ).rejects.toThrow('denied') + await store.set('apple/session/x', utf8Encode('value')) + expect( + utf8Decode((await store.get('apple/session/x')) ?? new Uint8Array()) + ).toBe('value') + expect(asked).toBe(2) + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) +}) + describe('file download store', () => { it('keeps only verified downloads and never leaves partial files', async () => { const { createFileDownloadStore } = await import( diff --git a/apps/desktop/src/main/adapters/encrypted-file-secret-store.ts b/apps/desktop/src/main/adapters/encrypted-file-secret-store.ts index 85abcc46..0f662e93 100644 --- a/apps/desktop/src/main/adapters/encrypted-file-secret-store.ts +++ b/apps/desktop/src/main/adapters/encrypted-file-secret-store.ts @@ -31,7 +31,13 @@ export const createEncryptedFileSecretStore = ( let loading: Promise | undefined const cryptoKey = (): Promise => { - key ??= keyProvider().then(importAesKey) + key ??= keyProvider() + .then(importAesKey) + .catch((error: unknown) => { + // The keychain said no (or was dismissed): ask again next time, so a later Allow is not ignored. + key = undefined + throw error + }) return key } diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 55b095f2..d66a43c6 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -114,6 +114,7 @@ const createUpdates = (logger: Logger) => readText }), arch: process.arch, + translated: app.runningUnderARM64Translation, logger }) diff --git a/apps/desktop/src/main/updates/constants.ts b/apps/desktop/src/main/updates/constants.ts index 4385ee8c..ba758ef8 100644 --- a/apps/desktop/src/main/updates/constants.ts +++ b/apps/desktop/src/main/updates/constants.ts @@ -18,6 +18,9 @@ export const RELEASE_WORKFLOWS = [ export const UNTRUSTED_SIGNER = 'UNTRUSTED_SIGNER_ERROR' export const SIGSTORE_ISSUER = 'https://token.actions.githubusercontent.com' +/** Where an Intel build running under Rosetta sends the user for the Apple silicon one. */ +export const NATIVE_BUILD_URL = `${RELEASES_URL}/latest` + /** How long the check may take before IPAForge opens without it (offline, a slow network). */ export const CHECK_TIMEOUT_MS = 15_000 diff --git a/apps/desktop/src/main/updates/types.ts b/apps/desktop/src/main/updates/types.ts index f3fb124f..fe0391e1 100644 --- a/apps/desktop/src/main/updates/types.ts +++ b/apps/desktop/src/main/updates/types.ts @@ -56,6 +56,8 @@ export type UpdateServiceDeps = { readonly kind: InstallKind /** `process.arch`, to name the right file for a package that can't update itself. */ readonly arch: string + /** The Intel build running under Rosetta on Apple silicon (Electron's `app.runningUnderARM64Translation`). */ + readonly translated?: boolean readonly logger: Logger readonly checkTimeoutMs?: number readonly installDelayMs?: number diff --git a/apps/desktop/src/main/updates/update-service.test.ts b/apps/desktop/src/main/updates/update-service.test.ts index 9a58b088..b13b0b0f 100644 --- a/apps/desktop/src/main/updates/update-service.test.ts +++ b/apps/desktop/src/main/updates/update-service.test.ts @@ -78,6 +78,26 @@ describe('createUpdateService', () => { expect(service.current()).toEqual({ phase: 'idle' }) }) + it('says where the Apple silicon build is when the Intel one runs under Rosetta', async () => { + const service = createUpdateService({ + updater: fakeUpdater(undefined).port, + verifier: signedBy(), + kind: 'self', + arch: 'x64', + translated: true, + logger + }) + service.start() + await vi.runAllTimersAsync() + + expect(service.current()).toEqual({ + phase: 'idle', + nativeBuild: { + url: 'https://github.com/IPAForge/ipaforge/releases/latest' + } + }) + }) + it('downloads a newer version with progress, then installs it', async () => { const updater = fakeUpdater(NEXT) const { service } = start(updater.port) diff --git a/apps/desktop/src/main/updates/update-service.ts b/apps/desktop/src/main/updates/update-service.ts index bd50ffa9..d9651ecc 100644 --- a/apps/desktop/src/main/updates/update-service.ts +++ b/apps/desktop/src/main/updates/update-service.ts @@ -4,7 +4,8 @@ // on. A package that can't update itself only says which file to download. import { CHECK_TIMEOUT_MS, - INSTALL_DELAY_MS + INSTALL_DELAY_MS, + NATIVE_BUILD_URL } from '@desktop/main/updates/constants.ts' import { manualUpdate, @@ -17,7 +18,6 @@ import type { } from '@desktop/main/updates/types.ts' import type { UpdateState } from '@ipaforge/rpc' -const IDLE: UpdateState = { phase: 'idle' } const MAX_REASON_LENGTH = 500 const reasonOf = (error: unknown): string => @@ -41,11 +41,16 @@ export const createUpdateService = ({ verifier, kind, arch, + translated = false, logger, checkTimeoutMs = CHECK_TIMEOUT_MS, installDelayMs = INSTALL_DELAY_MS }: UpdateServiceDeps): UpdateService => { const log = logger.child({ scope: 'updates' }) + // Done; an Intel build on Apple silicon also says where the faster one is. + const IDLE: UpdateState = translated + ? { phase: 'idle', nativeBuild: { url: NATIVE_BUILD_URL } } + : { phase: 'idle' } const listeners = new Set<(state: UpdateState) => void>() let state: UpdateState = updater ? { phase: 'checking' } : IDLE let isRunning = false diff --git a/docs/apple-account.md b/docs/apple-account.md index 82faad3e..99eecdbc 100644 --- a/docs/apple-account.md +++ b/docs/apple-account.md @@ -10,7 +10,9 @@ - The server never sees your Apple ID or password. - IPAForge keeps one identity per server and reuses it. Apple distrusts a new machine on every attempt. - If a server is down, the next one is used automatically. - - The servers are a custom one (if set), the built-in ones, then the community list (`servers.sidestore.io/servers.json`, HTTPS servers only). The list is fetched when anisette is first needed and again once it is an hour old (on the next request, never polled); after a failed fetch it is tried again a minute later. The last list fetched is kept in the secret store, so an offline start or a failed fetch still uses it (`anisetteServerListMaxAgeMs`, `anisetteServerListRetryMs` in the config). + - **Automatic** (the default) tries the servers you added (newest first), then the one that worked last, then SideStore's list (`servers.sidestore.io/servers.json`, HTTPS servers only, in its order), then IPAForge's built-in servers that list lacks, as a backup. + - **Settings → Anisette servers** shows them in that order with where each comes from, and lets you test one or all (how fast each answers), update SideStore's list now, and add, edit or remove your own (name and address; plain `http://` is allowed only for a server you add, such as one on your own computer). **Choose a server** uses only the one you pick; a server you add while choosing is the one picked. Until you pick one, IPAForge still chooses by itself. The settings are kept in `anisette/settings`, next to the machine identity. Switching servers gives Apple a new machine identity, so the next sign-in may ask for a code. + - The community list is fetched when anisette is first needed and again once it is an hour old (on the next request, never polled); after a failed fetch it is tried again a minute later. The last list fetched is kept in the secret store, so an offline start or a failed fetch still uses it (`anisetteServerListMaxAgeMs`, `anisetteServerListRetryMs` in the config). 2. **Password check (SRP).** Apple checks a proof of your password and returns encrypted session data. 3. **Second factor.** If your account has trusted devices, IPAForge asks Apple to show a code on them straight away and opens the code step; you tap **Allow** on the device and type the code. **Didn't get a code?** offers **Send a new code** and, when the account has phone numbers, **Text** a number instead. When Apple refuses to send another (too many in a row), the step says so and stays open. 4. **Developer token.** IPAForge requests the token Xcode uses for developer services. It is valid for about a year. @@ -69,7 +71,9 @@ After sign-in, IPAForge uses the same developer API Xcode uses, through `apple.d | Code | Meaning | What to do | |---|---|---| -| `apple.anisette_unavailable` | No anisette server answered | Check the connection; try again later, or set a custom server | +| `apple.anisette_unavailable` | No anisette server answered (with a chosen server, `chosen` names it) | Check the connection; **Choose another anisette server** opens Settings at the servers | +| `apple.anisette_server_invalid` | A server you added has no name, an address that isn't `http(s)://`, or a placeholder address | Correct the name or address | +| `apple.anisette_server_exists` | A server you added is in the list already | Choose it from the list instead | | `apple.client_rejected` (`-80045`, `-90010`) | Apple is rejecting this sign-in method right now | Update IPAForge; it usually needs a config update | | `apple.invalid_credentials` (`-22406`, `-20970`) | Wrong Apple ID or password | Check them. IPAForge never retries a wrong password, so your account cannot be locked by repeated attempts | | `apple.account_locked` | Apple locked the account | Unlock it at iforgot.apple.com | diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index 790b6fc6..92053d61 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -95,6 +95,7 @@ Every feature below maps to the phases that deliver it. "Automatic" means the us - later: AltStore as an install target (`ALTDeviceId` in `Info.plist` and an encrypted `ALTPairingFile.dat` at the bundle root) - when Apple reports a negative number of App IDs left, the error says the count looks wrong and Try anyway asks Apple to create them (#73) - an app IPAForge didn't install is never installed again first from a source whose version is older than the device's; the picker says "older than installed" (#73) + - anisette servers in Settings: Automatic (the user's servers, then the last that worked, SideStore's list in its order, then the built-in servers as a backup) or one chosen server; test one or all, update SideStore's list, add, edit and remove your own (http allowed only for these), a note on the list's non-HTTPS servers, a warning when the chosen server doesn't answer; "Choose another anisette server" opens the card. Also: background checks never ask Apple for a 2FA code, Sign in again uses the saved password and asks only for the code, a refused keychain prompt is asked again, nothing but the update check runs until it's done, the app's mark in the top bar, and a note when the Intel build runs under Rosetta (#80) - [x] **9. Desktop app**: Electron 44 shell with Node adapters, a hardened preload (`contextIsolation`, typed RPC only), electron-builder packages (Windows NSIS, macOS DMG signed and notarized, Linux AppImage, deb and rpm), and auto-update - status: the shell (one window with `contextIsolation`, `sandbox`, a strict CSP and blocked navigation, rendering `@ipaforge/ui`) runs the real Engine over the rpc MessagePort, CI builds and Sigstore-signs it on Linux, Windows and macOS, and it updates itself (each update's signature checked); Windows code signing and Apple notarisation moved to 1.0 - progress: diff --git a/docs/roadmap.md b/docs/roadmap.md index a0f844a4..202b5272 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,7 +14,7 @@ The detailed roadmap, with each phase's scope, is [design/roadmap.md](design/roa | 5 | Installer engine + catalog ✓ | Pipelines, flows, release catalog, error catalog | | 6 | UI foundation ✓ | HeroUI + Tailwind shell, colour palettes, i18n, Engine connection, accounts, devices, install run, its questions, recovery, step details, the log viewer, and screenshot and accessibility tests (#28–#58) | | 7 | Onboarding | First-run guided wizard | -| 8 | Install & preload UX ✓ | One-click SideStore ✓, live run view ✓, recovery screens ✓, Apple ID switch ✓, preload picker ✓ (#59), app sources ✓ (#66), detailed install progress ✓ (#67), the Apps section ✓ (#68), Repair SideStore ✓ (#70), SideStore QR codes ✓ (#71), on-device checklist ✓ (#72), the smaller notes ✓ (#73) | +| 8 | Install & preload UX ✓ | One-click SideStore ✓, live run view ✓, recovery screens ✓, Apple ID switch ✓, preload picker ✓ (#59), app sources ✓ (#66), detailed install progress ✓ (#67), the Apps section ✓ (#68), Repair SideStore ✓ (#70), SideStore QR codes ✓ (#71), on-device checklist ✓ (#72), the smaller notes ✓ (#73), anisette servers in Settings ✓ (#80) | | 9 | Desktop app ✓ (#61, #62, #63, #64, #65, #69, #74, #75, #77) | Electron packages for Windows, macOS, Linux ✓; the macOS app signed with IPAForge's own certificate ✓; auto-update and What's new ✓ (#74); Windows signing and notarisation moved to 1.0 | | 10 | Management tools | Certificates, app IDs, pairing files, import/export | | 11 | Wireless & remote pairing | Pairing over Wi-Fi, finding devices on the network, and the iOS 17+ RP pairing file (installing over Wi-Fi to a paired device works already) | diff --git a/docs/ui.md b/docs/ui.md index 0f67a677..ed354198 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -23,9 +23,9 @@ pnpm --filter @ipaforge/ui build # production build into packages/ui/dist pnpm --filter @ipaforge/ui preview # serve the build ``` -In development it logs at debug level to the browser console; a production build logs from `info` up. Preferences are kept in `localStorage`. Without Electron there is no real Engine: `src/main.tsx` connects a fake one (`src/services/engine/fake/`) over the rpc memory transport. In development `?scenario=` picks what it plays (`happy`, `hot-plug`, `devices`, `accounts`, `no-accounts`, `sign-in-no-2fa`, `wrong-password`, `two-factor`, `two-teams`, `certificate-limit`, `free-app-limit`, `retry`, and the failures `device-locked`, `app-id-quota`, `profile-banned`, `offline`, `checksum`, `unsupported-ios`, `anisette`, and `logs`, which fills the log buffer with 3,000 lines to try paging, search and the virtual list); tests use the same fake. The fake keeps its own log buffer, and logs its runs and devices the way the real Engine does. The `hot-plug` scenario plugs the fake iPad in and out every 5 s. The `devices` scenario shows every device state: the iPhone on USB and Wi-Fi (ready, with `studio@` blocked on it), a locked iPad (unlocked on a later read), and an iPhone SE that doesn't trust this computer (**Ask again** pairs it, then its Developer Mode is off). +In development it logs at debug level to the browser console; a production build logs from `info` up. Preferences are kept in `localStorage`. Without Electron there is no real Engine: `src/main.tsx` connects a fake one (`src/services/engine/fake/`) over the rpc memory transport. In development `?scenario=` picks what it plays (`happy`, `hot-plug`, `devices`, `accounts`, `code-needed` (like `accounts`, the expired Apple ID with a saved password, so **Sign in again** asks only for the code), `no-accounts`, `sign-in-no-2fa`, `wrong-password`, `two-factor`, `two-teams`, `certificate-limit`, `free-app-limit`, `retry`, and the failures `device-locked`, `app-id-quota`, `profile-banned`, `offline`, `checksum`, `unsupported-ios`, `anisette`, and `logs`, which fills the log buffer with 3,000 lines to try paging, search and the virtual list); tests use the same fake. The fake keeps its own log buffer, and logs its runs and devices the way the real Engine does. The `hot-plug` scenario plugs the fake iPad in and out every 5 s. The `devices` scenario shows every device state: the iPhone on USB and Wi-Fi (ready, with `studio@` blocked on it), a locked iPad (unlocked on a later read), and an iPhone SE that doesn't trust this computer (**Ask again** pairs it, then its Developer Mode is off). -`?update=` shows the update screen as the desktop app does on launch: `checking`, `downloading`, `installing`, `failed`, or `manual` (a `.msi` copy told to download the new version). Without it the browser has nothing to update. +`?update=` shows the update screen as the desktop app does on launch: `checking`, `downloading`, `installing`, `failed`, `manual` (a `.msi` copy told to download the new version), or `rosetta` (the Intel build on an Apple silicon Mac, pointed to the Apple silicon one). Without it the browser has nothing to update. To try **Add Apple ID** in the browser: any Apple ID and password; the code step follows (as if Apple showed a code on your devices), with **Send a new code** and **Text** a number instead, and the code is `123456` (any other code is wrong and asked again). `?scenario=sign-in-no-2fa` signs in without a second factor, `?scenario=wrong-password` fails with `apple.invalid_credentials`. @@ -99,6 +99,8 @@ There are six palettes: **Graphite** (the default), **Ocean**, **Aurora**, **Sun The colour mode is `system`, `light` or `dark`. In `system` mode the theme follows the OS and switches live when the OS does. Palette and mode are saved through `PreferencesStore` and can be changed under **Settings → Appearance**. Each change is logged at debug level under `ui.theme`. +**Settings → Anisette servers** (`features/settings/anisette`) lists the Engine's anisette servers (`engine.anisetteServers`) in the order Automatic tries them, grouped as added by you, SideStore's list and backup, with **Automatic** or **Choose a server**, a test per server and **Test all** (results kept while the page is open), **Update list**, and a dialog to add or edit your own. Every change answers with the servers after it, which replace the cached query. The recovery action **Choose another anisette server** opens `/settings#anisette`, which scrolls to the card and outlines it a moment. + To add a palette, add its id to `paletteIds`, add its tokens to `palettes.ts` and add a label. The tests then check that it has every token in both schemes. ## The shell diff --git a/packages/apple/src/application/anisette.ts b/packages/apple/src/application/anisette.ts index e704fa7f..8e7b2b56 100644 --- a/packages/apple/src/application/anisette.ts +++ b/packages/apple/src/application/anisette.ts @@ -1,12 +1,23 @@ -// Anisette with automatic failover: users never have to pick a server. Servers come from the remote list (plus a -// built-in fallback and any custom server); the last server that worked is tried first; each server keeps its own -// provisioning state; a server that says "not provisioned" is re-provisioned once. +// Anisette with automatic failover, or the one server the user chose. Automatic tries the servers the user added, +// then the last server that worked, then SideStore's list, then IPAForge's built-in backup, moving on when one +// fails. Each server keeps its own provisioning state; a server that says "not provisioned" is re-provisioned once. +import { + addServer, + choose, + overview, + removeServer, + type ServerCatalog, + serverEntries, + serverToTest, + updateServer +} from '@apple/application/anisette/manage-servers.ts' import { fromV1, fromV3 } from '@apple/application/anisette/providers.ts' import { createRemoteServerList, dedupe } from '@apple/application/anisette/server-list.ts' +import { createAnisetteSettingsStore } from '@apple/application/anisette/settings-store.ts' import { createAnisetteStateStore } from '@apple/application/anisette/state-store.ts' import type { AnisetteService, ServerHealth } from '@apple/application/types.ts' import type { AnisetteData, AnisetteServer } from '@apple/domain/types.ts' @@ -26,14 +37,43 @@ export const createAnisetteService = ( ): AnisetteService => { const { logger, config } = deps const states = createAnisetteStateStore(deps.secrets) - const remoteList = createRemoteServerList(deps) + const settings = createAnisetteSettingsStore(deps.secrets, logger) + const catalog: ServerCatalog = { + deps, + settings, + remoteList: createRemoteServerList(deps), + ...(options.custom ? { configured: options.custom } : {}) + } const servers = async (): Promise => - dedupe([ - ...(options.custom ? [options.custom] : []), - ...config.fallbackAnisetteServers, - ...(await remoteList.current()) + (await serverEntries(catalog, await settings.load())).map( + ({ name, address, protocol }) => + protocol ? { name, address, protocol } : { name, address } + ) + + /** The servers to try, in order: the chosen one alone, or Automatic's order. */ + const candidates = async ( + preferred: AnisetteServer | undefined + ): Promise => { + const { choice, custom } = await settings.load() + const chosen = choice.mode === 'chosen' ? choice.server : undefined + if (chosen) { + const listed = (await servers()).find( + (server) => dedupe([server, chosen]).length === 1 + ) + + return [listed ?? chosen] + } + const all = await servers() + const lastGood = await states.lastGood() + + return dedupe([ + ...(preferred ? [preferred] : []), + ...custom, + ...all.filter((server) => server.address === lastGood), + ...all ]) + } const health = async (server: AnisetteServer): Promise => { const started = deps.clock.now().getTime() @@ -60,13 +100,8 @@ export const createAnisetteService = ( : fromV3(deps, states, server, signal) const get: AnisetteService['get'] = async (getOptions = {}) => { - const all = await servers() + const ordered = await candidates(getOptions.preferred) const lastGood = await states.lastGood() - const ordered = dedupe([ - ...(getOptions.preferred ? [getOptions.preferred] : []), - ...all.filter((server) => server.address === lastGood), - ...all - ]) const failures: { server: string; error: string }[] = [] for (const server of ordered) { getOptions.signal?.throwIfAborted() @@ -85,9 +120,13 @@ export const createAnisetteService = ( }) } } + const { choice } = await settings.load() throw new IPAForgeError(ErrorCode.AnisetteUnavailable, { message: `no anisette server worked (${failures.length} tried)`, - data: { tried: failures } + data: + choice.mode === 'chosen' && choice.server + ? { tried: failures, chosen: choice.server.name } + : { tried: failures } }) } @@ -137,5 +176,49 @@ export const createAnisetteService = ( if (!server) await states.forgetLastGood() } - return { servers, health, get, resync, reset } + const show = async () => overview(catalog, await states.lastGood()) + + return { + servers, + health, + get, + resync, + reset, + overview: show, + choose: async (choice) => { + await choose(catalog, choice) + return show() + }, + addServer: async (input) => { + await addServer(catalog, input) + return show() + }, + updateServer: async (address, input) => { + await updateServer(catalog, address, input) + return show() + }, + removeServer: async (address) => { + await states.forget(await removeServer(catalog, address)) + return show() + }, + test: async (address) => { + const result = await health(await serverToTest(catalog, address)) + logger.info('anisette server tested', { + server: result.server.name, + ok: result.ok, + ...(result.error ? { error: result.error } : {}) + }) + return result.latencyMs === undefined + ? { address: result.server.address, ok: result.ok } + : { + address: result.server.address, + ok: result.ok, + latencyMs: result.latencyMs + } + }, + updateList: async () => { + await catalog.remoteList.update() + return show() + } + } } diff --git a/packages/apple/src/application/anisette/manage-servers.test.ts b/packages/apple/src/application/anisette/manage-servers.test.ts new file mode 100644 index 00000000..0414ad4e --- /dev/null +++ b/packages/apple/src/application/anisette/manage-servers.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it, vi } from 'vitest' + +import { createAnisetteService } from '@apple/application/anisette.ts' +import { resolveAppleDeps } from '@apple/deps.ts' +import type { AnisetteServer } from '@apple/domain/types.ts' +import { ErrorCode, type HttpClient, type SecretStore } from '@ipaforge/kernel' + +const LIST_URL = 'https://servers.sidestore.io/servers.json' + +/** SideStore's list as the test serves it: one shared with the backup, one plain HTTP. */ +const LIST: AnisetteServer[] = [ + { name: 'SideStore', address: 'https://ani.sidestore.io' }, + { name: 'jkcoxson', address: 'https://mac-ani.jkcoxson.com' }, + // eslint-disable-next-line sonarjs/no-clear-text-protocols -- plain HTTP from the list must be left out + { name: 'Plain', address: 'http://192.0.2.1:6969' } +] + +const BACKUP: AnisetteServer[] = [ + { name: 'StikStore', address: 'https://ani3.stikstore.app' }, + { name: 'jkcoxson (built in)', address: 'https://mac-ani.jkcoxson.com' } +] + +const memorySecrets = (): SecretStore => { + const values = new Map() + + return { + get: async (key) => values.get(key), + set: async (key, value) => { + values.set(key, value) + }, + delete: async (key) => { + values.delete(key) + } + } +} + +/** Only the list answers; every anisette server is down. */ +const setup = () => { + const asked: string[] = [] + const request = vi.fn(async (req: { url: string }) => { + asked.push(req.url) + if (req.url !== LIST_URL) throw new Error('down') + return { + status: 200, + headers: {}, + body: new Response(JSON.stringify({ servers: LIST })) + .body as ReadableStream> + } + }) + const deps = resolveAppleDeps({ + http: { request } as unknown as HttpClient, + webSocket: undefined as never, + secrets: memorySecrets(), + clock: { now: () => new Date(1000) }, + sleep: async () => {}, + config: { retryAttempts: 1, fallbackAnisetteServers: BACKUP } + }) + + return { anisette: createAnisetteService(deps), asked } +} + +// eslint-disable-next-line sonarjs/no-clear-text-protocols -- a server the user runs at home may be plain HTTP +const MINE = { name: 'Mine', address: 'http://192.168.1.20:6969' } + +describe('anisette servers in Settings', () => { + it("lists SideStore's HTTPS servers in order, then the backup it lacks, and says what it left out", async () => { + const { anisette } = setup() + const overview = await anisette.overview() + + expect( + overview.servers.map((server) => [server.source, server.name]) + ).toEqual([ + ['list', 'SideStore'], + ['list', 'jkcoxson'], + ['backup', 'StikStore'] + ]) + expect(overview.choice).toEqual({ mode: 'automatic' }) + expect(overview.listUpdatedAt).toBe(1000) + expect(overview.skipped).toEqual(['Plain']) + }) + + it('puts a server the user adds first, plain HTTP allowed, and chooses it when picking servers', async () => { + const { anisette } = setup() + await anisette.choose({ mode: 'chosen' }) + const overview = await anisette.addServer(MINE) + + expect(overview.servers[0]).toEqual({ ...MINE, source: 'custom' }) + expect(overview.choice).toEqual({ mode: 'chosen', server: MINE }) + }) + + it('refuses a server already in the list, a placeholder or a nameless one', async () => { + const { anisette } = setup() + + await expect( + anisette.addServer({ + name: 'Again', + address: 'https://ani.sidestore.io/' + }) + ).rejects.toMatchObject({ code: ErrorCode.AnisetteServerExists }) + await expect( + anisette.addServer({ name: 'X', address: 'https://yourserver.com' }) + ).rejects.toMatchObject({ code: ErrorCode.AnisetteServerInvalid }) + await expect( + anisette.addServer({ name: ' ', address: 'https://own.example.net.io' }) + ).rejects.toMatchObject({ code: ErrorCode.AnisetteServerInvalid }) + }) + + it('edits and removes only servers the user added; removing the chosen one leaves none chosen', async () => { + const { anisette } = setup() + await anisette.addServer(MINE) + await anisette.choose({ mode: 'chosen', server: MINE }) + const edited = await anisette.updateServer(MINE.address, { + name: 'Home', + address: MINE.address + }) + expect(edited.choice).toEqual({ + mode: 'chosen', + server: { name: 'Home', address: MINE.address } + }) + + await expect( + anisette.removeServer('https://ani.sidestore.io') + ).rejects.toMatchObject({ code: ErrorCode.AnisetteServerInvalid }) + const removed = await anisette.removeServer(MINE.address) + expect(removed.servers.some((server) => server.source === 'custom')).toBe( + false + ) + expect(removed.choice).toEqual({ mode: 'chosen' }) + }) + + it('uses only the chosen server, and says which one failed', async () => { + const { anisette, asked } = setup() + await anisette.overview() + await anisette.choose({ + mode: 'chosen', + server: { name: 'StikStore', address: 'https://ani3.stikstore.app' } + }) + asked.length = 0 + + await expect(anisette.get()).rejects.toMatchObject({ + code: ErrorCode.AnisetteUnavailable, + data: { chosen: 'StikStore', tried: [{ server: 'StikStore' }] } + }) + const others = [...LIST, ...BACKUP].filter( + (server) => server.name !== 'StikStore' + ) + expect( + asked.filter((url) => + others.some((server) => url.startsWith(server.address)) + ) + ).toEqual([]) + }) + + it('cannot choose a server that is not in the list', async () => { + const { anisette } = setup() + + await expect( + anisette.choose({ mode: 'chosen', server: MINE }) + ).rejects.toMatchObject({ code: ErrorCode.AnisetteServerInvalid }) + }) + + it('tests a server, saying it does not answer', async () => { + const { anisette } = setup() + + expect(await anisette.test('https://ani.sidestore.io')).toEqual({ + address: 'https://ani.sidestore.io', + ok: false + }) + }) + + it("fetches SideStore's list again when asked, whatever its age", async () => { + const { anisette, asked } = setup() + await anisette.overview() + const before = asked.filter((url) => url === LIST_URL).length + await anisette.updateList() + + expect(asked.filter((url) => url === LIST_URL)).toHaveLength(before + 1) + }) +}) diff --git a/packages/apple/src/application/anisette/manage-servers.ts b/packages/apple/src/application/anisette/manage-servers.ts new file mode 100644 index 00000000..8c636808 --- /dev/null +++ b/packages/apple/src/application/anisette/manage-servers.ts @@ -0,0 +1,202 @@ +// The anisette servers Settings shows and changes: the order Automatic tries them in, the user's choice, the +// servers they add, edit and remove, and a test of any one of them. A server the user adds is used first: at the +// top in Automatic, and the chosen one when they pick servers themselves. + +import { dedupe } from '@apple/application/anisette/server-list.ts' +import type { + AnisetteChoice, + AnisetteOverview, + AnisetteServerEntry, + AnisetteServerInput, + AnisetteSettings, + AnisetteSettingsStore, + RemoteServerList +} from '@apple/application/anisette/types.ts' +import { validateServerUrl } from '@apple/domain/anisette.ts' +import type { AnisetteServer } from '@apple/domain/types.ts' +import type { AppleDeps } from '@apple/types.ts' +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' + +const MAX_NAME_LENGTH = 80 + +export type ServerCatalog = { + readonly deps: AppleDeps + readonly settings: AnisetteSettingsStore + readonly remoteList: RemoteServerList + /** A server configured by the host (a probe's command line), first among the ones added. */ + readonly configured?: AnisetteServer +} + +const sameAddress = (a: string, b: string): boolean => + dedupe([ + { name: '', address: a }, + { name: '', address: b } + ]).length === 1 + +/** Added by the user (newest first), then SideStore's list in its order, then the built-in servers it lacks. */ +export const serverEntries = async ( + catalog: ServerCatalog, + settings: AnisetteSettings +): Promise => { + const tag = + (source: AnisetteServerEntry['source']) => + (server: AnisetteServer): AnisetteServerEntry => ({ ...server, source }) + const all = [ + ...(catalog.configured ? [catalog.configured] : []).map(tag('custom')), + ...settings.custom.map(tag('custom')), + ...(await catalog.remoteList.current()).map(tag('list')), + ...catalog.deps.config.fallbackAnisetteServers.map(tag('backup')) + ] + + return dedupe(all) as AnisetteServerEntry[] +} + +export const overview = async ( + catalog: ServerCatalog, + lastUsed: string | undefined +): Promise => { + const settings = await catalog.settings.load() + const servers = await serverEntries(catalog, settings) + const list = await catalog.remoteList.snapshot() + + return { + servers, + choice: settings.choice, + ...(lastUsed ? { lastUsed } : {}), + ...(list ? { listUpdatedAt: list.fetchedAt } : {}), + skipped: list?.skipped ?? [] + } +} + +const invalid = (reason: string): IPAForgeError => + new IPAForgeError(ErrorCode.AnisetteServerInvalid, { + message: reason, + data: { reason } + }) + +/** The server as typed, checked: a name, an http(s) address that isn't a placeholder, and not in the list yet. */ +const checkedServer = async ( + catalog: ServerCatalog, + settings: AnisetteSettings, + input: AnisetteServerInput, + replacing?: string +): Promise => { + const name = input.name.trim() + if (name.length === 0 || name.length > MAX_NAME_LENGTH) throw invalid('name') + const url = validateServerUrl(input.address) + if (!url.ok) throw invalid(url.reason) + const taken = (await serverEntries(catalog, settings)).some( + (server) => + sameAddress(server.address, url.url) && + !(replacing !== undefined && sameAddress(server.address, replacing)) + ) + if (taken) + throw new IPAForgeError(ErrorCode.AnisetteServerExists, { + data: { address: url.url } + }) + + return { name, address: url.url } +} + +const isChosen = (choice: AnisetteChoice, address: string): boolean => + choice.mode === 'chosen' && + choice.server !== undefined && + sameAddress(choice.server.address, address) + +export const addServer = async ( + catalog: ServerCatalog, + input: AnisetteServerInput +): Promise => { + const settings = await catalog.settings.load() + const server = await checkedServer(catalog, settings, input) + await catalog.settings.save({ + choice: + settings.choice.mode === 'chosen' + ? { mode: 'chosen', server } + : settings.choice, + custom: [server, ...settings.custom] + }) + catalog.deps.logger.info('anisette server added', { server: server.name }) +} + +const findCustom = (settings: AnisetteSettings, address: string) => { + const found = settings.custom.find((server) => + sameAddress(server.address, address) + ) + if (!found) throw invalid('not_added') + return found +} + +export const updateServer = async ( + catalog: ServerCatalog, + address: string, + input: AnisetteServerInput +): Promise => { + const settings = await catalog.settings.load() + const old = findCustom(settings, address) + const server = await checkedServer(catalog, settings, input, old.address) + await catalog.settings.save({ + choice: isChosen(settings.choice, old.address) + ? { mode: 'chosen', server } + : settings.choice, + custom: settings.custom.map((candidate) => + candidate === old ? server : candidate + ) + }) +} + +/** Forgets a server the user added; when it was the chosen one, nothing is chosen (IPAForge picks by itself). */ +export const removeServer = async ( + catalog: ServerCatalog, + address: string +): Promise => { + const settings = await catalog.settings.load() + const old = findCustom(settings, address) + await catalog.settings.save({ + choice: isChosen(settings.choice, old.address) + ? { mode: 'chosen' } + : settings.choice, + custom: settings.custom.filter((candidate) => candidate !== old) + }) + return old +} + +export const choose = async ( + catalog: ServerCatalog, + choice: AnisetteChoice +): Promise => { + const settings = await catalog.settings.load() + const known = + choice.mode === 'chosen' && choice.server + ? (await serverEntries(catalog, settings)).find((server) => + sameAddress(server.address, choice.server?.address ?? '') + ) + : undefined + if (choice.mode === 'chosen' && choice.server && !known) + throw invalid('not_listed') + await catalog.settings.save({ + ...settings, + choice: known + ? { mode: 'chosen', server: { name: known.name, address: known.address } } + : choice + }) + catalog.deps.logger.info('anisette choice changed', { + mode: choice.mode, + ...(known ? { server: known.name } : {}) + }) +} + +/** A server to test: one in the list, or an address being typed into Add server (checked like one). */ +export const serverToTest = async ( + catalog: ServerCatalog, + address: string +): Promise => { + const settings = await catalog.settings.load() + const known = (await serverEntries(catalog, settings)).find((server) => + sameAddress(server.address, address) + ) + if (known) return known + const url = validateServerUrl(address) + if (!url.ok) throw invalid(url.reason) + return { name: url.url, address: url.url } +} diff --git a/packages/apple/src/application/anisette/server-list.ts b/packages/apple/src/application/anisette/server-list.ts index ccfe3d22..fcaca3eb 100644 --- a/packages/apple/src/application/anisette/server-list.ts +++ b/packages/apple/src/application/anisette/server-list.ts @@ -1,5 +1,5 @@ -// Which anisette servers to try, in which order: a custom server first, then the built-in fallback, then the -// remote community list. The remote list is kept up to date: fetched again once it is older than its maximum age +// The remote community list of anisette servers (SideStore's), which the anisette service tries after the servers +// the user added and before its own built-in backup. The remote list is kept up to date: fetched again once it is older than its maximum age // (on the next anisette request, never polled), and the last list fetched is kept in the secret store, so a failed // fetch or an offline start uses it instead of the built-in servers alone. @@ -51,21 +51,26 @@ export const dedupe = ( const httpsOnly = ( deps: AppleDeps, servers: readonly AnisetteServer[] -): AnisetteServer[] => - servers.filter((server) => { - const secure = server.address.startsWith('https://') - if (!secure) - deps.logger.warn( - 'ignoring non-HTTPS anisette server from the remote list', - { server: server.name } - ) - return secure - }) +): { servers: AnisetteServer[]; skipped: string[] } => { + const secure = servers.filter((server) => + server.address.startsWith('https://') + ) + const skipped = servers + .filter((server) => !secure.includes(server)) + .map((server) => server.name) + if (skipped.length > 0) + deps.logger.warn( + 'ignoring non-HTTPS anisette servers from the remote list', + { servers: skipped } + ) -/** The remote list's HTTPS servers, or undefined when it cannot be fetched. */ + return { servers: secure, skipped } +} + +/** The remote list's HTTPS servers and the names left out, or undefined when it cannot be fetched. */ const fetchRemoteServers = async ( deps: AppleDeps -): Promise => { +): Promise<{ servers: AnisetteServer[]; skipped: string[] } | undefined> => { const { config } = deps try { const response = await fetchApple(deps, config.anisetteServerListUrl, { @@ -89,6 +94,7 @@ const STORED_LIST_KEY = 'anisette/server-list' const storedListSchema = z.object({ fetchedAt: z.number(), + skipped: z.array(z.string()).optional(), servers: z.array( z.object({ name: z.string(), @@ -110,7 +116,8 @@ const loadStoredList = async ( return { fetchedAt: parsed.data.fetchedAt, - servers: parsed.data.servers.map((server) => compact(server)) + servers: parsed.data.servers.map((server) => compact(server)), + skipped: parsed.data.skipped ?? [] } } catch (error) { deps.logger.warn('saved anisette server list unreadable', { cause: error }) @@ -132,35 +139,58 @@ export const createRemoteServerList = (deps: AppleDeps): RemoteServerList => { const isRetryDue = (now: number): boolean => failedAt === undefined || now - failedAt >= config.anisetteServerListRetryMs - const refresh = async (): Promise => { - if (!loaded) { - known = await loadStoredList(deps) - loaded = true - } + const loadOnce = async () => { + if (loaded) return + known = await loadStoredList(deps) + loaded = true + } + + const refresh = async (force: boolean): Promise => { + await loadOnce() const now = clock.now().getTime() - if (isFresh(now) || !isRetryDue(now)) return known?.servers ?? [] - const servers = await fetchRemoteServers(deps) - if (!servers) { + if (!force && (isFresh(now) || !isRetryDue(now))) + return known?.servers ?? [] + const fetched = await fetchRemoteServers(deps) + if (!fetched) { failedAt = now return known?.servers ?? [] } failedAt = undefined - known = { servers, fetchedAt: now } + known = { ...fetched, fetchedAt: now } await deps.secrets.set(STORED_LIST_KEY, utf8Encode(JSON.stringify(known))) deps.logger.debug('anisette server list updated', { - servers: servers.length + servers: fetched.servers.length }) - return servers + return fetched.servers } - return { - current: () => { - inFlight ??= refresh().finally(() => { - inFlight = undefined - }) + const run = (force: boolean): Promise => { + // A forced update waits for a fetch already going, then fetches itself. + const previous = inFlight ?? Promise.resolve([]) + const next = force + ? previous.then( + () => refresh(true), + () => refresh(true) + ) + : (inFlight ?? refresh(false)) + const tracked = next.finally(() => { + if (inFlight === tracked) inFlight = undefined + }) + inFlight = tracked - return inFlight + return tracked + } + + return { + current: () => run(false), + snapshot: async () => { + await loadOnce() + return known + }, + update: async () => { + await run(true) + return known } } } diff --git a/packages/apple/src/application/anisette/settings-store.ts b/packages/apple/src/application/anisette/settings-store.ts new file mode 100644 index 00000000..37112307 --- /dev/null +++ b/packages/apple/src/application/anisette/settings-store.ts @@ -0,0 +1,61 @@ +// What the user set for anisette servers, in the store beside the machine identity (not a secret): the choice and +// the servers they added. Unreadable or missing settings are the defaults: Automatic, nothing added. + +import { z } from 'zod' + +import type { + AnisetteSettings, + AnisetteSettingsStore +} from '@apple/application/anisette/types.ts' +import { + compact, + type Logger, + type SecretStore, + utf8Decode, + utf8Encode +} from '@ipaforge/kernel' + +const SETTINGS_KEY = 'anisette/settings' + +const DEFAULT_SETTINGS: AnisetteSettings = { + choice: { mode: 'automatic' }, + custom: [] +} + +const serverSchema = z.object({ + name: z.string().min(1), + address: z.string().min(1) +}) + +const settingsSchema = z.object({ + choice: z.discriminatedUnion('mode', [ + z.object({ mode: z.literal('automatic') }), + z.object({ mode: z.literal('chosen'), server: serverSchema.optional() }) + ]), + custom: z.array(serverSchema) +}) + +export const createAnisetteSettingsStore = ( + secrets: SecretStore, + logger: Logger +): AnisetteSettingsStore => ({ + load: async () => { + try { + const raw = await secrets.get(SETTINGS_KEY) + if (!raw) return DEFAULT_SETTINGS + const parsed = settingsSchema.safeParse(JSON.parse(utf8Decode(raw))) + if (parsed.success) + return { + choice: compact(parsed.data.choice), + custom: parsed.data.custom + } + } catch (error) { + logger.warn('anisette settings unreadable; using the defaults', { + cause: error + }) + } + return DEFAULT_SETTINGS + }, + save: (settings) => + secrets.set(SETTINGS_KEY, utf8Encode(JSON.stringify(settings))) +}) diff --git a/packages/apple/src/application/anisette/types.ts b/packages/apple/src/application/anisette/types.ts index 86004e52..41507f6b 100644 --- a/packages/apple/src/application/anisette/types.ts +++ b/packages/apple/src/application/anisette/types.ts @@ -3,9 +3,66 @@ import type { AnisetteServer } from '@apple/domain/types.ts' export type FetchedList = { readonly servers: AnisetteServer[] readonly fetchedAt: number + /** Names of the list's servers left out because they are not HTTPS. */ + readonly skipped: readonly string[] } export type RemoteServerList = { /** The remote list, fetched again when older than `anisetteServerListMaxAgeMs`; the last known one otherwise. */ current(): Promise + /** The last list fetched (as `current` keeps it up to date), with when and what was left out; none yet: undefined. */ + snapshot(): Promise + /** Fetches the list now, whatever its age; the last known one stays when that fails. */ + update(): Promise +} + +/** + * How IPAForge picks an anisette server: by itself (`automatic`: the servers in order, moving on when one fails), + * or always the one the user chose. Choosing without a server yet still picks by itself. + */ +export type AnisetteChoice = + | { readonly mode: 'automatic' } + | { readonly mode: 'chosen'; readonly server?: AnisetteServer } + +/** What the user set: the choice, and the servers they added (newest first). */ +export type AnisetteSettings = { + readonly choice: AnisetteChoice + readonly custom: readonly AnisetteServer[] +} + +/** Where a server comes from: added by the user, SideStore's list, or IPAForge's built-in backup. */ +export type AnisetteServerSource = 'custom' | 'list' | 'backup' + +export type AnisetteServerEntry = AnisetteServer & { + readonly source: AnisetteServerSource +} + +/** The anisette servers as Settings shows them, in the order Automatic tries them. */ +export type AnisetteOverview = { + readonly servers: readonly AnisetteServerEntry[] + readonly choice: AnisetteChoice + /** The address of the server that worked last (Automatic tries it right after the ones the user added). */ + readonly lastUsed?: string + /** When SideStore's list was last fetched (ms since the epoch); never: absent. */ + readonly listUpdatedAt?: number + /** Names of the list's servers left out because they are not HTTPS. */ + readonly skipped: readonly string[] +} + +/** A server the user adds or edits. */ +export type AnisetteServerInput = { + readonly name: string + readonly address: string +} + +/** One server's test: whether it answered, and how fast. */ +export type AnisetteServerTest = { + readonly address: string + readonly ok: boolean + readonly latencyMs?: number +} + +export type AnisetteSettingsStore = { + load(): Promise + save(settings: AnisetteSettings): Promise } diff --git a/packages/apple/src/application/apple-accounts.test.ts b/packages/apple/src/application/apple-accounts.test.ts index bd3abf5a..2bfa4ad9 100644 --- a/packages/apple/src/application/apple-accounts.test.ts +++ b/packages/apple/src/application/apple-accounts.test.ts @@ -86,13 +86,39 @@ describe('resumeAccount', () => { const result = await resumeAccount(services, ID) expect(result.kind).toBe('signed_in') - expect(signIn).toHaveBeenCalledWith({ appleId: ID, password: PASSWORD }) + expect(signIn).toHaveBeenCalledWith({ + appleId: ID, + password: PASSWORD, + sendCode: true + }) expect(accounts.save).toHaveBeenCalledTimes(1) expect(records.map((record) => record.msg)).toContain( 'signing in again with the saved password' ) }) + it('in the background, stops at a second factor without asking Apple to send a code', async () => { + const { services, signIn, accounts } = setup({ + password: PASSWORD, + tokenError: expired + }) + signIn.mockResolvedValueOnce({ + kind: 'two_factor', + challenge: {} + } as never) + + expect(await resumeAccount(services, ID, { interactive: false })).toEqual({ + kind: 'needs_code', + appleId: ID + }) + expect(signIn).toHaveBeenCalledWith({ + appleId: ID, + password: PASSWORD, + sendCode: false + }) + expect(accounts.save).not.toHaveBeenCalled() + }) + it('needs the password when the session expired and none is saved, logging why', async () => { const { services, records } = setup({ tokenError: expired }) diff --git a/packages/apple/src/application/apple-accounts.ts b/packages/apple/src/application/apple-accounts.ts index 5a10863f..fc64251f 100644 --- a/packages/apple/src/application/apple-accounts.ts +++ b/packages/apple/src/application/apple-accounts.ts @@ -13,6 +13,7 @@ import type { AccountStore, AppleAccounts, AppleAccountsOptions, + ResumeOptions, ResumeResult, ResumeServices, SavedAccount @@ -64,8 +65,10 @@ const reuseSession = async ( /** Opens a saved account: its session, else a sign-in with its saved password, else "needs the password". */ export const resumeAccount = async ( services: ResumeServices, - id: string + id: string, + options: ResumeOptions = {} ): Promise => { + const interactive = options.interactive ?? true const account = await findSaved(services.accounts, id) if (!account) throw new IPAForgeError(ErrorCode.AccountNotFound, { data: { id } }) @@ -83,9 +86,17 @@ export const resumeAccount = async ( }) const result = await services.signIn.signIn({ appleId: account.appleId, - password + password, + sendCode: interactive }) if (result.kind === 'signed_in') await services.accounts.save(result.session) + if (result.kind === 'two_factor' && !interactive) { + services.deps.logger.info( + 'the saved password needs a second factor; left for the user', + { account: id } + ) + return { kind: 'needs_code', appleId: account.appleId } + } return result } @@ -114,7 +125,8 @@ export const createAppleAccounts = ( preflight: () => runPreflight(deps, anisette), signIn: (signInInput) => signInService.signIn(signInInput), appToken: (session, app) => tokens.appToken(session, app), - resume: (id) => resumeAccount(resumeServices, id), + resume: (id, resumeOptions) => + resumeAccount(resumeServices, id, resumeOptions), developer: (session) => createDeveloperServices(deps, anisette, tokens, session), markBanned: async (id, udid) => { diff --git a/packages/apple/src/application/sign-in.ts b/packages/apple/src/application/sign-in.ts index 89b1b008..36f89110 100644 --- a/packages/apple/src/application/sign-in.ts +++ b/packages/apple/src/application/sign-in.ts @@ -67,7 +67,11 @@ export const createSignInService = ( message: 'Apple still asks for a second factor' }) }), - { codeAlreadySent: secondFactor.codeAlreadySent } + // A code that is already on its way, or that nobody can type in, must not be sent (again). + { + codeAlreadySent: + secondFactor.codeAlreadySent || input.sendCode === false + } ) const signIn = async (input: SignInInput): Promise => { diff --git a/packages/apple/src/application/types.ts b/packages/apple/src/application/types.ts index f262388e..5c0dd2e5 100644 --- a/packages/apple/src/application/types.ts +++ b/packages/apple/src/application/types.ts @@ -1,3 +1,9 @@ +import type { + AnisetteChoice, + AnisetteOverview, + AnisetteServerInput, + AnisetteServerTest +} from '@apple/application/anisette/types.ts' import type { AppTokenService } from '@apple/application/app-token.ts' import type { DeveloperServices } from '@apple/application/developer.ts' import type { @@ -60,7 +66,7 @@ export type ServerHealth = { } export type AnisetteService = { - /** Custom server + built-in fallback + remote list (kept up to date), deduplicated, in preference order. */ + /** Added by the user, SideStore's list (kept up to date), then the built-in backup: deduplicated, in that order. */ servers(): Promise health(server: AnisetteServer): Promise /** Headers and client identity from the first server that works. */ @@ -75,11 +81,37 @@ export type AnisetteService = { resync(data: AnisetteData, resyncData: string): Promise /** Forgets provisioning state (all servers when omitted). Missing state is not an error. */ reset(server?: AnisetteServer): Promise + /** The servers, the choice, the last one that worked and SideStore's list's age, for Settings. */ + overview(): Promise + /** Automatic, or always one server of the list (none yet: still automatic). */ + choose(choice: AnisetteChoice): Promise + /** Adds a server, used first (and chosen, when the user picks servers). Http is allowed: the user typed it. */ + addServer(input: AnisetteServerInput): Promise + updateServer( + address: string, + input: AnisetteServerInput + ): Promise + removeServer(address: string): Promise + /** Whether a server answers, and how fast: one in the list, or an address being added. */ + test(address: string): Promise + /** Fetches SideStore's list now. */ + updateList(): Promise } export type ResumeResult = | SignInResult | { readonly kind: 'needs_password'; readonly appleId: string } + /** Not interactive, and Apple wants a second factor: nothing was sent, the user has to sign in again. */ + | { readonly kind: 'needs_code'; readonly appleId: string } + +export type ResumeOptions = { + /** + * False for checks nobody is waiting on (an account's status, its teams or quota): the saved session or password + * is still used, but when Apple wants a second factor no code is sent, since there is nowhere to type it. + * Default: true. + */ + readonly interactive?: boolean +} export type AppleAccounts = { readonly anisette: AnisetteService @@ -91,7 +123,7 @@ export type AppleAccounts = { * Re-opens a saved account: reuses its session while Apple accepts it, otherwise signs in again with the * saved password (usually without 2FA, since this machine is already known), otherwise asks for the password. */ - resume(id: string): Promise + resume(id: string, options?: ResumeOptions): Promise /** Developer services (teams, certificates, App IDs, profiles) for a signed-in session. */ developer(session: AppleSession): DeveloperServices /** Records that Apple blocked this account's profiles on a device, so the UI can offer another account. */ @@ -150,6 +182,8 @@ export type SignInInput = { readonly appleId: string readonly password: string readonly signal?: AbortSignal + /** False: when Apple asks for a second factor, don't ask it to send a code to the trusted devices. Default: true. */ + readonly sendCode?: boolean } export type SignInService = { diff --git a/packages/apple/src/domain/anisette.test.ts b/packages/apple/src/domain/anisette.test.ts index 9770ac1f..ae7ab144 100644 --- a/packages/apple/src/domain/anisette.test.ts +++ b/packages/apple/src/domain/anisette.test.ts @@ -20,6 +20,12 @@ describe('validateServerUrl', () => { expect(validateServerUrl('not a url').ok).toBe(false) }) + it('rejects an address with a user name or password, which would be saved and logged', () => { + expect(validateServerUrl('https://me:secret@ani.own-server.net').ok).toBe( + false + ) + }) + it('handles a long run of slashes inside the path quickly', () => { const path = `${'/'.repeat(100_000)}x` const result = validateServerUrl(`https://ani.sidestore.io${path}`) diff --git a/packages/apple/src/domain/anisette.ts b/packages/apple/src/domain/anisette.ts index 3cd1f6d4..14b1fb52 100644 --- a/packages/apple/src/domain/anisette.ts +++ b/packages/apple/src/domain/anisette.ts @@ -44,6 +44,9 @@ export const validateServerUrl = ( } if (url.protocol !== 'https:' && url.protocol !== 'http:') return { ok: false, reason: 'use http:// or https://' } + // A user name or password in the address would be saved and logged with it. + if (url.username || url.password) + return { ok: false, reason: 'no user name or password in the address' } if (PLACEHOLDER_HOSTS.test(url.hostname)) { return { ok: false, diff --git a/packages/apple/src/index.ts b/packages/apple/src/index.ts index b88e41ce..49786f5b 100644 --- a/packages/apple/src/index.ts +++ b/packages/apple/src/index.ts @@ -1,4 +1,12 @@ // Public API of @ipaforge/apple: Apple ID sign-in (SRP + 2FA), anisette with failover, app tokens, saved accounts. +export type { + AnisetteChoice, + AnisetteOverview, + AnisetteServerEntry, + AnisetteServerInput, + AnisetteServerSource, + AnisetteServerTest +} from '@apple/application/anisette/types.ts' export { XCODE_APP } from '@apple/application/app-token.ts' export { createAppleAccounts } from '@apple/application/apple-accounts.ts' export type { @@ -24,6 +32,7 @@ export type { AppleAccounts, AppleAccountsOptions, PreflightReport, + ResumeOptions, ResumeResult, SavedAccount, SaveOptions, diff --git a/packages/installer/src/application/runtime.ts b/packages/installer/src/application/runtime.ts index f76b2394..c1ed650b 100644 --- a/packages/installer/src/application/runtime.ts +++ b/packages/installer/src/application/runtime.ts @@ -15,15 +15,20 @@ export type FlowRuntime = { close(): Promise } +/** + * The account's session for questions nobody waits on (teams, quota, certificates): the saved session, or a new one + * from the saved password, but never a second factor, since there's nowhere to type its code. Signing in again + * with a code is the user's to start. + */ const savedSession = async ( deps: InstallerDeps, accountId: string ): Promise => { - const resumed = await deps.apple.resume(accountId) + const resumed = await deps.apple.resume(accountId, { interactive: false }) if (resumed.kind === 'signed_in') return resumed.session throw new IPAForgeError(ErrorCode.SessionExpired, { message: 'sign in again', - data: { account: accountId } + data: { account: accountId, needs: resumed.kind } }) } diff --git a/packages/installer/src/application/sign-in.ts b/packages/installer/src/application/sign-in.ts index e4946012..738fafdb 100644 --- a/packages/installer/src/application/sign-in.ts +++ b/packages/installer/src/application/sign-in.ts @@ -7,6 +7,7 @@ import { PromptKind } from '@installer/domain/prompts.ts' import type { StepContext } from '@installer/pipeline/types.ts' import type { InstallerDeps } from '@installer/types.ts' import type { AppleSession, SavedAccount, SignInResult } from '@ipaforge/apple' +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' const finish = async ( deps: InstallerDeps, @@ -62,11 +63,29 @@ export const signInAccount = async ( } if (resumed.kind === 'two_factor') return { session: await finish(deps, context, resumed), how: 'renewed' } + // An interactive resume never stops at "needs a code"; asking for the password covers the remaining case. const result = await signInWithPassword(deps, context, resumed.appleId) return { session: await finish(deps, context, result), how: 'signed-in' } } +/** Signs a saved account in again: what it still has (session, password) first, then prompts for the rest. */ +export const signInSavedAccount = async ( + deps: InstallerDeps, + context: StepContext, + accountId: string +): Promise => { + await signInAccount(deps, context, accountId) + const account = (await deps.apple.accounts.list()).find( + (candidate) => candidate.id === accountId + ) + if (!account) + throw new IPAForgeError(ErrorCode.AccountNotFound, { + data: { id: accountId } + }) + return account +} + /** * Signs in an Apple ID that is not saved yet (the password and any second factor through prompts) and saves it. * With `rememberPassword` the password is saved too (only through the SecretStore), so an expired session can diff --git a/packages/installer/src/diagnostics/catalogue.ts b/packages/installer/src/diagnostics/catalogue.ts index e464743c..924104b7 100644 --- a/packages/installer/src/diagnostics/catalogue.ts +++ b/packages/installer/src/diagnostics/catalogue.ts @@ -40,6 +40,8 @@ export const RECOVERY_CATALOGUE = { R.Retry ], 'apple.anisette_not_provisioned': [R.ChangeAnisetteServer, R.Retry], + 'apple.anisette_server_invalid': [R.ChangeAnisetteServer], + 'apple.anisette_server_exists': [R.ChangeAnisetteServer], 'apple.app_id_quota': [R.WaitForAppIdSlot, R.TryAnyway, R.SwitchAccount], 'apple.certificate_limit': [R.RevokeCertificate, R.SwitchAccount], 'apple.invalid_credentials': [R.ReEnterPassword], diff --git a/packages/installer/src/engine/queries.ts b/packages/installer/src/engine/queries.ts index f45e0784..047deb76 100644 --- a/packages/installer/src/engine/queries.ts +++ b/packages/installer/src/engine/queries.ts @@ -83,5 +83,13 @@ export const createEngineQueries = (deps: InstallerDeps): EngineQueries => ({ checkSideStore: (query) => checkSideStore(deps, query), catalogReleases: (appId) => catalogReleases(deps, appId), deviceApps: (udid) => deviceApps(deps, udid), - revealDeveloperMode: (udid) => revealDeveloperMode(deps, udid) + revealDeveloperMode: (udid) => revealDeveloperMode(deps, udid), + anisetteServers: () => deps.apple.anisette.overview(), + chooseAnisetteServer: (choice) => deps.apple.anisette.choose(choice), + addAnisetteServer: (input) => deps.apple.anisette.addServer(input), + updateAnisetteServer: (address, input) => + deps.apple.anisette.updateServer(address, input), + removeAnisetteServer: (address) => deps.apple.anisette.removeServer(address), + testAnisetteServer: (address) => deps.apple.anisette.test(address), + updateAnisetteServerList: () => deps.apple.anisette.updateList() }) diff --git a/packages/installer/src/engine/types.ts b/packages/installer/src/engine/types.ts index 4c3f63b2..00136d8f 100644 --- a/packages/installer/src/engine/types.ts +++ b/packages/installer/src/engine/types.ts @@ -17,6 +17,10 @@ import type { PromptRequest } from '@installer/pipeline/types.ts' import type { + AnisetteChoice, + AnisetteOverview, + AnisetteServerInput, + AnisetteServerTest, AppId, AppIdPlan, AppIdQuota, @@ -158,6 +162,21 @@ export type EngineQueries = { deviceApps(udid: string): Promise /** Makes the Developer Mode switch appear in the device's Settings. */ revealDeveloperMode(udid: string): Promise + /** The anisette servers in the order Automatic tries them, the choice, and SideStore's list's age. */ + anisetteServers(): Promise + /** Automatic, or always one server of the list. Each change below returns the servers after it. */ + chooseAnisetteServer(choice: AnisetteChoice): Promise + /** Adds a server, used first (and chosen when the user picks servers). */ + addAnisetteServer(input: AnisetteServerInput): Promise + updateAnisetteServer( + address: string, + input: AnisetteServerInput + ): Promise + removeAnisetteServer(address: string): Promise + /** Whether a server answers and how fast: one in the list, or an address being added. */ + testAnisetteServer(address: string): Promise + /** Fetches SideStore's list of servers now. */ + updateAnisetteServerList(): Promise } export type InstalledAppsQuery = { diff --git a/packages/installer/src/flows/sign-in.test.ts b/packages/installer/src/flows/sign-in.test.ts index 6468d1c5..464f4c5c 100644 --- a/packages/installer/src/flows/sign-in.test.ts +++ b/packages/installer/src/flows/sign-in.test.ts @@ -122,6 +122,52 @@ describe('signIn', () => { expect(prompts.asked.at(-1)?.data).toMatchObject({ resent: false }) }) + it('signs a saved account in again with what was saved, asking for nothing', async () => { + const h = createHarness() + const prompts = scripted({}) + const result = await h.engine.signIn( + { ...input, accountId: ACCOUNT }, + { onPrompt: prompts } + ).result + + expect(result.status === 'completed' && result.state.account?.id).toBe( + ACCOUNT + ) + expect(prompts.asked).toEqual([]) + }) + + it('asks a saved account only for the code when its saved password needs one', async () => { + const challenge = twoFactorChallenge('123456') + const h = createHarness({ + apple: { resume: async () => ({ kind: 'two_factor', challenge }) } + }) + const prompts = scripted({ [PromptKind.TwoFactorCode]: () => '123456' }) + const result = await h.engine.signIn( + { ...input, accountId: ACCOUNT }, + { onPrompt: prompts } + ).result + + expect(result.status).toBe('completed') + expect(prompts.asked.map((p) => p.kind)).toEqual([PromptKind.TwoFactorCode]) + expect(h.apple.calls.saved).toBe(1) + }) + + it('asks a saved account for the password when none was saved', async () => { + const h = createHarness({ + apple: { + resume: async () => ({ kind: 'needs_password', appleId: ACCOUNT }) + } + }) + const prompts = scripted({ [PromptKind.Password]: () => 'secret' }) + const result = await h.engine.signIn( + { ...input, accountId: ACCOUNT }, + { onPrompt: prompts } + ).result + + expect(result.status).toBe('completed') + expect(prompts.asked.map((p) => p.kind)).toEqual([PromptKind.Password]) + }) + it('keeps the password out of the state, and stops when it is declined', async () => { const h = createHarness() const events: RunEvent[] = [] diff --git a/packages/installer/src/flows/sign-in.ts b/packages/installer/src/flows/sign-in.ts index 1ce7faa0..669fc83d 100644 --- a/packages/installer/src/flows/sign-in.ts +++ b/packages/installer/src/flows/sign-in.ts @@ -1,7 +1,10 @@ -// signIn: adds an Apple ID. The password and the second factor are asked through prompts, so they never sit in -// the run's input, state or checkpoint; the saved account is the result. +// signIn: adds an Apple ID, or signs a saved one in again. The password and the second factor are asked through +// prompts, so they never sit in the run's input, state or checkpoint; the saved account is the result. import type { FlowRuntime } from '@installer/application/runtime.ts' -import { signInNewAccount } from '@installer/application/sign-in.ts' +import { + signInNewAccount, + signInSavedAccount +} from '@installer/application/sign-in.ts' import { StepLabel } from '@installer/domain/labels.ts' import { StepWeight } from '@installer/domain/step-weights.ts' import type { Flow } from '@installer/flows/flow.ts' @@ -13,18 +16,20 @@ export const SIGN_IN = 'signIn' const signInStep = ( runtime: FlowRuntime, - rememberPassword: boolean + input: SignInFlowInput ): Step => ({ id: 'sign-in', labelKey: StepLabel.signIn, weight: StepWeight.appleRequest, run: async (state, context) => ({ - account: await signInNewAccount( - runtime.deps, - context, - state.appleId, - rememberPassword - ) + account: input.accountId + ? await signInSavedAccount(runtime.deps, context, input.accountId) + : await signInNewAccount( + runtime.deps, + context, + state.appleId, + input.rememberPassword ?? false + ) }) }) @@ -33,7 +38,5 @@ export const signInFlow = ( input: SignInFlowInput ): Flow => ({ initial: { appleId: input.appleId }, - pipeline: pipeline(SIGN_IN, [ - signInStep(runtime, input.rememberPassword ?? false) - ]) + pipeline: pipeline(SIGN_IN, [signInStep(runtime, input)]) }) diff --git a/packages/installer/src/flows/types.ts b/packages/installer/src/flows/types.ts index bbe996ae..fadd4178 100644 --- a/packages/installer/src/flows/types.ts +++ b/packages/installer/src/flows/types.ts @@ -40,6 +40,11 @@ export type SignInFlowInput = { readonly appleId: string /** Save the password (in the SecretStore) so an expired session can be renewed without asking. Default: no. */ readonly rememberPassword?: boolean + /** + * "Sign in again" for this saved account: its saved session or password is used first, so only what's missing + * is asked (usually just the second factor's code). + */ + readonly accountId?: string } export type SignInState = { diff --git a/packages/kernel/src/errors/codes.ts b/packages/kernel/src/errors/codes.ts index b6aafd04..ad4b7b22 100644 --- a/packages/kernel/src/errors/codes.ts +++ b/packages/kernel/src/errors/codes.ts @@ -29,6 +29,10 @@ export const ErrorCode = { // apple AnisetteUnavailable: 'apple.anisette_unavailable', AnisetteNotProvisioned: 'apple.anisette_not_provisioned', + /** An anisette server the user typed can't be used: no name, not an http(s) address, or a placeholder. */ + AnisetteServerInvalid: 'apple.anisette_server_invalid', + /** An anisette server the user typed is in the list already. */ + AnisetteServerExists: 'apple.anisette_server_exists', AppIdQuotaExceeded: 'apple.app_id_quota', CertificateLimit: 'apple.certificate_limit', InvalidCredentials: 'apple.invalid_credentials', diff --git a/packages/rpc/src/__tests__/fake-engine.ts b/packages/rpc/src/__tests__/fake-engine.ts index 94ad5fdb..43ad6f3f 100644 --- a/packages/rpc/src/__tests__/fake-engine.ts +++ b/packages/rpc/src/__tests__/fake-engine.ts @@ -25,6 +25,18 @@ export type FakeState = { export const TEAMS = [{ id: 'TEAM1', name: 'Free team' }] +export const ANISETTE = { + servers: [ + { + name: 'SideStore', + address: 'https://ani.sidestore.io', + source: 'list' as const + } + ], + choice: { mode: 'automatic' as const }, + skipped: [] +} + const flow = (control: FakeControl) => pipeline('fake.install', [ { @@ -169,6 +181,17 @@ export const createFakeEngine = () => { }, listAccounts: async () => [{ id: 'acct', appleId: 'someone@example.com' }], canSaveAccounts: async () => true, + anisetteServers: async () => ANISETTE, + chooseAnisetteServer: async () => ANISETTE, + addAnisetteServer: async () => ANISETTE, + updateAnisetteServer: async () => ANISETTE, + removeAnisetteServer: async () => ANISETTE, + testAnisetteServer: async (address: string) => ({ + address, + ok: true, + latencyMs: 120 + }), + updateAnisetteServerList: async () => ANISETTE, listSources: async () => [], sourceApps: async () => [], checkSource: async (url: string) => ({ diff --git a/packages/rpc/src/application/client.ts b/packages/rpc/src/application/client.ts index 58fdf951..9ced1d9e 100644 --- a/packages/rpc/src/application/client.ts +++ b/packages/rpc/src/application/client.ts @@ -201,6 +201,19 @@ export const createEngineClient = ( setSourceEnabled: (id, enabled) => query({ method: 'setSourceEnabled', args: [id, enabled] }), refreshSources: (id) => query({ method: 'refreshSources', args: [id] }), + anisetteServers: () => query({ method: 'anisetteServers', args: [] }), + chooseAnisetteServer: (choice) => + query({ method: 'chooseAnisetteServer', args: [choice] }), + addAnisetteServer: (input) => + query({ method: 'addAnisetteServer', args: [input] }), + updateAnisetteServer: (address, input) => + query({ method: 'updateAnisetteServer', args: [address, input] }), + removeAnisetteServer: (address) => + query({ method: 'removeAnisetteServer', args: [address] }), + testAnisetteServer: (address) => + query({ method: 'testAnisetteServer', args: [address] }), + updateAnisetteServerList: () => + query({ method: 'updateAnisetteServerList', args: [] }), installedApps: (installedQuery) => query({ method: 'installedApps', diff --git a/packages/rpc/src/application/server/queries.ts b/packages/rpc/src/application/server/queries.ts index 46c7e590..c37218ad 100644 --- a/packages/rpc/src/application/server/queries.ts +++ b/packages/rpc/src/application/server/queries.ts @@ -17,6 +17,15 @@ const queryHandlers = ( pairDevice: ([udid]) => engine.pairDevice(udid), listAccounts: () => engine.listAccounts(), canSaveAccounts: () => engine.canSaveAccounts(), + anisetteServers: () => engine.anisetteServers(), + chooseAnisetteServer: ([choice]) => + engine.chooseAnisetteServer(compact(choice)), + addAnisetteServer: ([input]) => engine.addAnisetteServer(input), + updateAnisetteServer: ([address, input]) => + engine.updateAnisetteServer(address, input), + removeAnisetteServer: ([address]) => engine.removeAnisetteServer(address), + testAnisetteServer: ([address]) => engine.testAnisetteServer(address), + updateAnisetteServerList: () => engine.updateAnisetteServerList(), signOut: ([accountId]) => engine.signOut(accountId), listTeams: ([accountId]) => engine.listTeams(accountId), catalogApps: () => engine.catalogApps(), diff --git a/packages/rpc/src/domain/protocol/inputs.ts b/packages/rpc/src/domain/protocol/inputs.ts index 2730f0f8..c2831da6 100644 --- a/packages/rpc/src/domain/protocol/inputs.ts +++ b/packages/rpc/src/domain/protocol/inputs.ts @@ -122,8 +122,33 @@ export const placePairingInputSchema = z.object({ overwrite: z.enum(['replace', 'keep-existing']).optional() }) +const MAX_SERVER_NAME_LENGTH = 80 + +/** An anisette server's address: http allowed, for a server the user runs themselves. */ +export const anisetteAddressSchema = z.url({ protocol: /^https?$/ }) + +const anisetteServerSchema = z.object({ + name: textSchema.max(MAX_SERVER_NAME_LENGTH), + address: anisetteAddressSchema +}) + +/** A server the user adds or edits; the Engine checks the name and address again. */ +export const anisetteServerInputSchema = z.object({ + name: z.string().max(MAX_SERVER_NAME_LENGTH), + address: z.string().max(2048) +}) + +export const anisetteChoiceSchema = z.discriminatedUnion('mode', [ + z.object({ mode: z.literal('automatic') }), + z.object({ + mode: z.literal('chosen'), + server: anisetteServerSchema.optional() + }) +]) + /** The password and any second factor come later, as prompt answers, so they never sit in the run's input. */ export const signInInputSchema = z.object({ appleId: textSchema, - rememberPassword: z.boolean().optional() + rememberPassword: z.boolean().optional(), + accountId: textSchema.optional() }) diff --git a/packages/rpc/src/domain/protocol/requests.ts b/packages/rpc/src/domain/protocol/requests.ts index 1bd72309..d2d30c35 100644 --- a/packages/rpc/src/domain/protocol/requests.ts +++ b/packages/rpc/src/domain/protocol/requests.ts @@ -9,6 +9,9 @@ import { versionSchema } from '@rpc/domain/protocol/common.ts' import { + anisetteAddressSchema, + anisetteChoiceSchema, + anisetteServerInputSchema, checkSideStoreQuerySchema, installAppsInputSchema, installedAppsQuerySchema, @@ -65,7 +68,19 @@ export const queryCallSchema = z.discriminatedUnion('method', [ /** Asks Apple for the team's certificates and reads SideStore's files on the device. */ call('checkSideStore', z.tuple([checkSideStoreQuerySchema])), /** Not a read, but a one-shot call answered like one. */ - call('signOut', z.tuple([textSchema])) + call('signOut', z.tuple([textSchema])), + /** Fetches SideStore's list when it is old, so it can take a few seconds. */ + call('anisetteServers', z.tuple([])), + call('chooseAnisetteServer', z.tuple([anisetteChoiceSchema])), + call('addAnisetteServer', z.tuple([anisetteServerInputSchema])), + call( + 'updateAnisetteServer', + z.tuple([anisetteAddressSchema, anisetteServerInputSchema]) + ), + call('removeAnisetteServer', z.tuple([anisetteAddressSchema])), + /** Waits for the server's answer, up to the health check's timeout. */ + call('testAnisetteServer', z.tuple([z.string().min(1).max(2048)])), + call('updateAnisetteServerList', z.tuple([])) ]) export const commandCallSchema = z.discriminatedUnion('command', [ diff --git a/packages/rpc/src/domain/protocol/updates.ts b/packages/rpc/src/domain/protocol/updates.ts index 2282429b..18cfa5c6 100644 --- a/packages/rpc/src/domain/protocol/updates.ts +++ b/packages/rpc/src/domain/protocol/updates.ts @@ -21,8 +21,12 @@ export const manualPackageSchema = z.enum(['msi', 'deb', 'rpm', 'other']) * a failure) the app waits behind the update screen. */ export const updateStateSchema = z.discriminatedUnion('phase', [ - // Nothing to do: up to date, offline, or no updater (a browser, a development build). - z.object({ phase: z.literal('idle') }), + // Nothing to do: up to date, offline, or no updater (a browser, a development build). `nativeBuild`: this is + // the Intel build running translated on Apple silicon (slow), and where the Apple silicon one is. + z.object({ + phase: z.literal('idle'), + nativeBuild: z.object({ url: linkSchema }).optional() + }), z.object({ phase: z.literal('checking') }), // Bytes so far and in all (0 until the first progress report). z.object({ diff --git a/packages/rpc/src/rpc.test.ts b/packages/rpc/src/rpc.test.ts index fceed13e..e64de3b6 100644 --- a/packages/rpc/src/rpc.test.ts +++ b/packages/rpc/src/rpc.test.ts @@ -151,6 +151,32 @@ describe('queries', () => { client.checkSource('http://example.com/apps.json') ).rejects.toMatchObject({ code: ErrorCode.InvalidRpcMessage }) }) + + it('manages anisette servers through the Engine; a chosen server must be an http(s) address', async () => { + const { client } = setup() + // eslint-disable-next-line sonarjs/no-clear-text-protocols -- a server the user runs at home may be plain HTTP + const home = { name: 'Home', address: 'http://192.168.1.20:6969' } + + expect((await client.anisetteServers()).choice).toEqual({ + mode: 'automatic' + }) + await client.addAnisetteServer(home) + await client.updateAnisetteServer(home.address, home) + await client.chooseAnisetteServer({ mode: 'chosen', server: home }) + await client.removeAnisetteServer(home.address) + await client.updateAnisetteServerList() + expect(await client.testAnisetteServer(home.address)).toEqual({ + address: home.address, + ok: true, + latencyMs: 120 + }) + await expect( + client.chooseAnisetteServer({ + mode: 'chosen', + server: { name: 'Bad', address: 'ftp://example.com' } + }) + ).rejects.toMatchObject({ code: ErrorCode.InvalidRpcMessage }) + }) }) describe('runs', () => { diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index f1cc7c01..d2dba444 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -3,7 +3,6 @@ import type { RouterHistory } from '@tanstack/react-router' import { RouterProvider } from '@tanstack/react-router' import { useState } from 'react' -import { DeviceFeed } from '@ui/components/device-feed.tsx' import { createQueryClient } from '@ui/hooks/queries/query-client.ts' import { queryKeys } from '@ui/hooks/queries/query-keys.ts' import { LanguageProvider } from '@ui/i18n/provider/language-provider.tsx' @@ -33,8 +32,8 @@ export type AppProps = { } /** - * The whole UI: host services (the Engine client among them), the query cache for Engine queries kept in step - * with the device feed, what the user picked in the top bar, the install run (kept here so it goes on in other + * The whole UI: host services (the Engine client among them), the query cache for Engine queries (kept in step + * with the device feed once the update check is done), what the user picked in the top bar, the install run (kept here so it goes on in other * sections), the preload list, the log viewer's filters, the language, the theme, then the router (whose root route is the shell). Touches no browser global * at import time, so any host can mount it. HeroUI v3 itself needs no provider. */ @@ -69,7 +68,6 @@ export const App = ({ services, language, history }: AppProps) => { return ( - diff --git a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ar-chromium-linux.png b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ar-chromium-linux.png index 9dab531d..a85c93db 100644 Binary files a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ar-chromium-linux.png and b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ar-chromium-linux.png differ diff --git a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-de-chromium-linux.png b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-de-chromium-linux.png index 6b2ae466..d5dca2aa 100644 Binary files a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-de-chromium-linux.png and b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-de-chromium-linux.png differ diff --git a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-XA-chromium-linux.png b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-XA-chromium-linux.png index 55d4078c..04fe0528 100644 Binary files a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-XA-chromium-linux.png and b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-XA-chromium-linux.png differ diff --git a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-chromium-linux.png b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-chromium-linux.png index 51784a7e..18d651d2 100644 Binary files a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-chromium-linux.png and b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-chromium-linux.png differ diff --git a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-dark-chromium-linux.png b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-dark-chromium-linux.png index ba9810ac..8dcadde8 100644 Binary files a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-dark-chromium-linux.png and b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-en-dark-chromium-linux.png differ diff --git a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ja-chromium-linux.png b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ja-chromium-linux.png index 0f72b996..3eea9fb3 100644 Binary files a/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ja-chromium-linux.png and b/packages/ui/src/__screenshots__/screens.browser.test.tsx/settings-ja-chromium-linux.png differ diff --git a/packages/ui/src/components/shell/app-logo.tsx b/packages/ui/src/components/shell/app-logo.tsx new file mode 100644 index 00000000..d3dd1793 --- /dev/null +++ b/packages/ui/src/components/shell/app-logo.tsx @@ -0,0 +1,63 @@ +import { useId } from 'react' + +import { logoColors } from '@ui/components/shell/constants.ts' + +/** + * The app icon drawn inline, next to the app name: a phone with a spark on the indigo tile. The gradient ids are + * unique per use, so two marks on one page don't share them. + */ +export const AppLogo = () => { + const id = useId() + const tile = `${id}-tile` + const spark = `${id}-spark` + + return ( + + ) +} diff --git a/packages/ui/src/components/shell/constants.ts b/packages/ui/src/components/shell/constants.ts index 3dca3d09..60c3dc7a 100644 --- a/packages/ui/src/components/shell/constants.ts +++ b/packages/ui/src/components/shell/constants.ts @@ -43,3 +43,12 @@ export const PICKER_TRIGGER_CLASSES = [ 'flex min-w-0 items-center gap-2 rounded-lg border border-border bg-surface-secondary px-2.5 py-1.5 text-sm outline-none', 'hover:bg-surface-tertiary focus-visible:ring-2 focus-visible:ring-focus' ].join(' ') + +/** The app icon's colours (`apps/desktop/build/icon.svg`), for the mark in the top bar. */ +export const logoColors = { + tileFrom: '#312e81', + tileTo: '#0f172a', + sparkFrom: '#fde68a', + sparkTo: '#f97316', + phone: '#e0e7ff' +} as const diff --git a/packages/ui/src/components/shell/top-bar.tsx b/packages/ui/src/components/shell/top-bar.tsx index 1205a4f3..64b37d4f 100644 --- a/packages/ui/src/components/shell/top-bar.tsx +++ b/packages/ui/src/components/shell/top-bar.tsx @@ -1,15 +1,19 @@ import { useTranslation } from 'react-i18next' import { AccountPicker } from '@ui/components/shell/account-picker.tsx' +import { AppLogo } from '@ui/components/shell/app-logo.tsx' import { DevicePicker } from '@ui/components/shell/device-picker.tsx' -/** The app name on the start side, the device and Apple ID pickers on the end side. */ +/** The app's mark and name on the start side, the device and Apple ID pickers on the end side. */ export const TopBar = () => { const { t } = useTranslation() return (
- {t('app.name')} + + + {t('app.name')} +
diff --git a/packages/ui/src/features/accounts/accounts-page.test.tsx b/packages/ui/src/features/accounts/accounts-page.test.tsx index 1a701831..9390fda2 100644 --- a/packages/ui/src/features/accounts/accounts-page.test.tsx +++ b/packages/ui/src/features/accounts/accounts-page.test.tsx @@ -99,6 +99,26 @@ describe('Accounts page', () => { ).toBe(OLD) }) + it('signs in again with the saved password, asking only for the code', async () => { + const { user, list } = await openPage({ scenario: 'code-needed' }) + await user.click( + await within(rowFor(list, OLD)).findByRole('button', { + name: t('accounts.signInAgain') + }) + ) + const code = await screen.findByRole('dialog', { + name: t('prompts.code.title') + }) + expect(screen.queryByLabelText(/Password/)).toBeNull() + await user.type(within(code).getByRole('textbox'), '123456') + await user.click( + within(code).getByRole('button', { name: t('prompts.code.verify') }) + ) + expect( + await screen.findByRole('dialog', { name: t('signIn.done.title') }) + ).toBeDefined() + }) + it('asks before signing out, saying what is forgotten, and keeps the account on Cancel', async () => { const { user, list } = await openPage() await user.click( diff --git a/packages/ui/src/features/accounts/accounts-page.tsx b/packages/ui/src/features/accounts/accounts-page.tsx index b6d820f8..179d0843 100644 --- a/packages/ui/src/features/accounts/accounts-page.tsx +++ b/packages/ui/src/features/accounts/accounts-page.tsx @@ -18,7 +18,12 @@ import type { Account } from '@ui/services/engine/types.ts' /** Which dialog is open: sign-in (maybe again, for a saved Apple ID) or the sign-out confirmation. */ type OpenDialog = - | { readonly kind: 'sign-in'; readonly appleId?: string | undefined } + | { + readonly kind: 'sign-in' + readonly appleId?: string | undefined + /** "Sign in again" for this saved account. */ + readonly accountId?: string | undefined + } | { readonly kind: 'sign-out'; readonly account: Account } | undefined @@ -34,7 +39,11 @@ export const AccountsPage = () => { const onAddAppleId = () => setDialog({ kind: 'sign-in' }) const onUse = (account: Account) => select('account', account.id) const onSignInAgain = (account: Account) => - setDialog({ kind: 'sign-in', appleId: account.appleId }) + setDialog({ + kind: 'sign-in', + appleId: account.appleId, + accountId: account.id + }) const onSignOut = (account: Account) => setDialog({ kind: 'sign-out', account }) // Signing out the Apple ID in use hands its place to the next saved one; with none left, nothing is in use. @@ -84,6 +93,7 @@ export const AccountsPage = () => { {dialog?.kind === 'sign-in' ? ( diff --git a/packages/ui/src/features/accounts/sign-in/components/resuming-sign-in.tsx b/packages/ui/src/features/accounts/sign-in/components/resuming-sign-in.tsx new file mode 100644 index 00000000..84c0063e --- /dev/null +++ b/packages/ui/src/features/accounts/sign-in/components/resuming-sign-in.tsx @@ -0,0 +1,31 @@ +import { Button, Modal, Spinner } from '@heroui/react' +import { useTranslation } from 'react-i18next' + +type ResumingSignInProps = { + appleId: string + onCancel: () => void +} + +/** "Sign in again" before Apple asks for anything: IPAForge uses what it saved for this Apple ID. */ +export const ResumingSignIn = ({ appleId, onCancel }: ResumingSignInProps) => { + const { t } = useTranslation() + + return ( + <> + + {t('signIn.resuming.title')} + + +

+ + {t('signIn.resuming.body', { appleId })} +

+
+ + + + + ) +} diff --git a/packages/ui/src/features/accounts/sign-in/hooks/use-sign-in.ts b/packages/ui/src/features/accounts/sign-in/hooks/use-sign-in.ts index 18bc444b..21a2ae92 100644 --- a/packages/ui/src/features/accounts/sign-in/hooks/use-sign-in.ts +++ b/packages/ui/src/features/accounts/sign-in/hooks/use-sign-in.ts @@ -28,19 +28,26 @@ export const useSignIn = ( isPending: false }) const run = useRef(undefined) + // A "sign in again" run that found no saved password: the form's password answers its question. + const awaitingPassword = useRef(false) const done = useRef(onSignedIn) done.current = onSignedIn // Closing the dialog mid sign-in cancels the run. useEffect(() => () => run.current?.cancel(), []) - const follow = (handle: SignInRun, password: string) => { + const follow = (handle: SignInRun, password: string | undefined) => { let count = 0 let passwordSent = false handle.subscribe((event) => { if (event.type !== 'prompt') return if (event.request.kind === PromptKind.Password && !passwordSent) { passwordSent = true + if (password === undefined) { + awaitingPassword.current = true + setState({ phase: 'form', isPending: false }) + return + } handle.answer(password) return } @@ -84,6 +91,13 @@ export const useSignIn = ( return { state, start: (appleId, password, rememberPassword) => { + const waiting = run.current + if (awaitingPassword.current && waiting?.pending()) { + awaitingPassword.current = false + waiting.answer(password) + setState({ phase: 'form', isPending: true }) + return + } const handle = engine.signIn({ appleId: appleId.trim(), rememberPassword @@ -92,6 +106,12 @@ export const useSignIn = ( setState({ phase: 'form', isPending: true }) follow(handle, password) }, + resume: (appleId, accountId) => { + const handle = engine.signIn({ appleId, accountId }) + run.current = handle + setState({ phase: 'resuming' }) + follow(handle, undefined) + }, answer: (answer) => respond((handle) => handle.answer(answer)), decline: () => respond((handle) => handle.decline()) } diff --git a/packages/ui/src/features/accounts/sign-in/sign-in-dialog.test.tsx b/packages/ui/src/features/accounts/sign-in/sign-in-dialog.test.tsx index 621c6e99..915177dd 100644 --- a/packages/ui/src/features/accounts/sign-in/sign-in-dialog.test.tsx +++ b/packages/ui/src/features/accounts/sign-in/sign-in-dialog.test.tsx @@ -182,8 +182,16 @@ const holdApple = () => { return { appleAnswer, release } } -/** Records whether the Apple ID/password form is ever on screen from now on. */ -const watchForForm = () => { +/** + * Records whether the Apple ID/password form is ever on screen from now on. It first waits for the form that was + * just replaced to finish leaving (its closing animation keeps it in the page a moment on a slow machine). + */ +const watchForForm = async () => { + await waitFor(() => + expect( + screen.queryByRole('heading', { name: t('signIn.title') }) + ).toBeNull() + ) let seen = false const check = () => { if (screen.queryByRole('heading', { name: t('signIn.title') })) seen = true @@ -233,7 +241,7 @@ describe('Add Apple ID, while Apple answers', () => { await submitForm(user) await apple.release() await apple.release() - const form = watchForForm() + const form = await watchForForm() const code = await screen.findByRole('dialog', { name: t('prompts.code.title') }) @@ -261,7 +269,7 @@ describe('Add Apple ID, while Apple answers', () => { await submitForm(user) await apple.release() await apple.release() - const form = watchForForm() + const form = await watchForForm() await enterCode(user, '123456') const code = screen.getByRole('dialog', { name: t('prompts.code.title') }) @@ -288,7 +296,7 @@ describe('Add Apple ID, while Apple answers', () => { await submitForm(user) await apple.release() await apple.release() - const form = watchForForm() + const form = await watchForForm() await enterCode(user, '000000') await apple.release() diff --git a/packages/ui/src/features/accounts/sign-in/sign-in-dialog.tsx b/packages/ui/src/features/accounts/sign-in/sign-in-dialog.tsx index 69322d84..5ed750e5 100644 --- a/packages/ui/src/features/accounts/sign-in/sign-in-dialog.tsx +++ b/packages/ui/src/features/accounts/sign-in/sign-in-dialog.tsx @@ -1,3 +1,6 @@ +import { useEffect, useRef } from 'react' + +import { ResumingSignIn } from '@ui/features/accounts/sign-in/components/resuming-sign-in.tsx' import { SignInForm } from '@ui/features/accounts/sign-in/components/sign-in-form.tsx' import { SignInPrompt } from '@ui/features/accounts/sign-in/components/sign-in-prompt.tsx' import { SignInShell } from '@ui/features/accounts/sign-in/components/sign-in-shell.tsx' @@ -8,6 +11,11 @@ import type { Account } from '@ui/services/engine/types.ts' type SignInDialogProps = { /** "Sign in again" for a saved Apple ID: the form starts with it filled in. */ appleId?: string | undefined + /** + * "Sign in again" for this saved account: it starts at once with what's saved, and asks only for what's missing + * (usually the second factor's code; the password only when none is saved). + */ + accountId?: string | undefined onClose: () => void /** The account the Engine saved, e.g. to show or select it. */ onSignedIn: (account: Account) => void @@ -19,11 +27,20 @@ type SignInDialogProps = { */ export const SignInDialog = ({ appleId, + accountId, onClose, onSignedIn }: SignInDialogProps) => { const signIn = useSignIn(onSignedIn) const { state } = signIn + const resume = useRef(signIn.resume) + resume.current = signIn.resume + + // Starts when the dialog opens. Unmounting cancels the run (the hook), so StrictMode's second mount starts again. + useEffect(() => { + if (accountId && appleId) resume.current(appleId, accountId) + }, [accountId, appleId]) + if (state.phase === 'prompt') return ( + {state.phase === 'resuming' ? ( + + ) : null} {state.phase === 'signed-in' ? ( - ) : ( + ) : null} + {state.phase === 'form' ? ( - )} + ) : null} ) } diff --git a/packages/ui/src/features/accounts/sign-in/types.ts b/packages/ui/src/features/accounts/sign-in/types.ts index 7636f537..5c4492de 100644 --- a/packages/ui/src/features/accounts/sign-in/types.ts +++ b/packages/ui/src/features/accounts/sign-in/types.ts @@ -20,12 +20,16 @@ export type SignInState = readonly count: number readonly isPending: boolean } + /** "Sign in again": signing in with what the account has saved, before Apple asks for anything. */ + | { readonly phase: 'resuming' } | { readonly phase: 'signed-in'; readonly account: Account } export type UseSignIn = { readonly state: SignInState /** `rememberPassword`: save the password in the system keychain, to renew an expired session without asking. */ start: (appleId: string, password: string, rememberPassword: boolean) => void + /** "Sign in again" for a saved account: its saved session or password first; asks only for what's missing. */ + resume: (appleId: string, accountId: string) => void answer: (answer: unknown) => void decline: () => void } diff --git a/packages/ui/src/features/install/home/components/sign-in-needed-notice.tsx b/packages/ui/src/features/install/home/components/sign-in-needed-notice.tsx index 7c331ab8..bbcaea3f 100644 --- a/packages/ui/src/features/install/home/components/sign-in-needed-notice.tsx +++ b/packages/ui/src/features/install/home/components/sign-in-needed-notice.tsx @@ -7,8 +7,8 @@ import { SignInDialog } from '@ui/features/accounts/sign-in/sign-in-dialog.tsx' import { useActiveAccount, useDevicesInUse } from '@ui/hooks/use-selection.ts' /** - * Says when the Apple ID in use needs signing in again, with a way to do it now. It does not block installing: - * the run's sign-in step asks for the password itself. + * Says when the Apple ID in use needs signing in again, with a way to do it now: with what IPAForge saved, so it + * asks only for what's missing (usually the code). It does not block installing: the run's sign-in step asks too. */ export const SignInNeededNotice = () => { const { t } = useTranslation() @@ -23,6 +23,7 @@ export const SignInNeededNotice = () => { isSigningIn && account ? ( diff --git a/packages/ui/src/features/install/recovery/constants.ts b/packages/ui/src/features/install/recovery/constants.ts index ba0f832f..ce324b88 100644 --- a/packages/ui/src/features/install/recovery/constants.ts +++ b/packages/ui/src/features/install/recovery/constants.ts @@ -31,7 +31,11 @@ export const fixes = { ], buttonKey: 'recovery.retry' }, - [R.ChangeAnisetteServer]: { kind: 'later' }, + [R.ChangeAnisetteServer]: { + kind: 'settings', + howKey: 'recovery.fix.changeAnisetteServer.how', + buttonKey: 'recovery.fix.changeAnisetteServer.button' + }, [R.ReEnterPassword]: { kind: 'resume', howKey: 'recovery.fix.reEnterPassword.how', diff --git a/packages/ui/src/features/install/recovery/hooks/use-fix-handlers.ts b/packages/ui/src/features/install/recovery/hooks/use-fix-handlers.ts index ae20e4d6..c509b8f0 100644 --- a/packages/ui/src/features/install/recovery/hooks/use-fix-handlers.ts +++ b/packages/ui/src/features/install/recovery/hooks/use-fix-handlers.ts @@ -1,12 +1,16 @@ +import { useNavigate } from '@tanstack/react-router' + import { usePairDevice } from '@ui/features/devices/hooks/use-pair-device.ts' import type { FixHandlers } from '@ui/features/install/recovery/types.ts' import { otherChannel } from '@ui/features/install/recovery/utils/other-channel.ts' +import { ANISETTE_CARD_ID } from '@ui/features/settings/anisette/constants.ts' import { useRun } from '@ui/hooks/use-run.ts' import type { ActiveRun } from '@ui/state/active-run/types.ts' /** * What each kind of fix does for a failed run: continue from the checkpoint (or start again without one), ask the - * device to trust this computer and then continue, open the Apple ID picker, or start again on the other channel. + * device to trust this computer and then continue, open the Apple ID picker, start again on the other channel, or + * open the anisette servers in Settings. */ export const useFixHandlers = ( run: ActiveRun, @@ -14,6 +18,7 @@ export const useFixHandlers = ( ): FixHandlers & { readonly isPairing: boolean } => { const { resume, restart } = useRun() const pair = usePairDevice(run.input.udid) + const navigate = useNavigate() const onContinue = () => (run.view.checkpoint ? resume() : restart({})) return { @@ -25,6 +30,9 @@ export const useFixHandlers = ( if (run.kind === 'sidestore') restart({ channel: otherChannel(run.input.channel) }) }, + settings: () => { + void navigate({ to: '/settings', hash: ANISETTE_CARD_ID }) + }, isPairing: pair.isPending } } diff --git a/packages/ui/src/features/install/recovery/types.ts b/packages/ui/src/features/install/recovery/types.ts index bb469a91..80420660 100644 --- a/packages/ui/src/features/install/recovery/types.ts +++ b/packages/ui/src/features/install/recovery/types.ts @@ -5,11 +5,12 @@ import type { RunFailure } from '@ui/state/active-run/types.ts' /** * What pressing a fix does: continue from the checkpoint, ask the device to trust this computer first, start - * again with another Apple ID or the other channel, nothing (it only explains), or not shown yet (its screen - * comes in a later phase). + * again with another Apple ID or the other channel, open a Settings card, nothing (it only explains), or not shown + * yet (its screen comes in a later phase). */ export type FixKind = | 'resume' + | 'settings' | 'pair' | 'account' | 'channel' diff --git a/packages/ui/src/features/install/recovery/utils/recovery-fixes.test.ts b/packages/ui/src/features/install/recovery/utils/recovery-fixes.test.ts index d5f580d1..c10c64f3 100644 --- a/packages/ui/src/features/install/recovery/utils/recovery-fixes.test.ts +++ b/packages/ui/src/features/install/recovery/utils/recovery-fixes.test.ts @@ -19,9 +19,10 @@ describe('recoveryFixes', () => { }) it('leaves out fixes whose screen comes later', () => { - expect( - recoveryFixes(['change-anisette-server', 'check-network', 'retry']) - ).toEqual({ first: 'check-network', others: [] }) + expect(recoveryFixes(['choose-team', 'check-network', 'retry'])).toEqual({ + first: 'check-network', + others: [] + }) expect(recoveryFixes(['update-ipaforge', 'report-issue'])).toEqual({ first: undefined, others: [] @@ -29,6 +30,17 @@ describe('recoveryFixes', () => { }) }) +describe('anisette server failures', () => { + it('first open the anisette servers in Settings, keeping Try again', () => { + expect( + recoveryFixes(['change-anisette-server', 'check-network', 'retry']) + ).toEqual({ + first: 'change-anisette-server', + others: ['check-network', 'retry'] + }) + }) +}) + describe('Try anyway', () => { const quota = [ 'wait-for-app-id-slot', diff --git a/packages/ui/src/features/settings/anisette/anisette-settings.test.tsx b/packages/ui/src/features/settings/anisette/anisette-settings.test.tsx new file mode 100644 index 00000000..64ff1753 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/anisette-settings.test.tsx @@ -0,0 +1,189 @@ +// Settings › Anisette servers, against the fake Engine: SideStore's list, the built-in backup, and servers added here. +import { screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, expect, it } from 'vitest' + +import { t } from '@ui/__tests__/test-i18n.ts' +import { renderApp } from '@ui/__tests__/test-services.tsx' + +// eslint-disable-next-line sonarjs/no-clear-text-protocols -- a server the user runs at home may be plain HTTP +const HOME = 'http://192.168.1.20:6969' + +type User = ReturnType + +const openCard = async (path = '/settings') => { + const user = userEvent.setup() + const rendered = await renderApp(path) + const card = await screen.findByRole('region', { + name: t('settings.anisette.title') + }) + await within(card).findByText('https://ani.sidestore.io') + + return { user, card, ...rendered } +} + +const rowOf = (card: HTMLElement, address: string) => { + const row = within(card).getByText(address).closest('li') + if (!row) throw new Error(`no row for ${address}`) + return row +} + +const addServer = async (user: User, name: string, address: string) => { + const [add] = screen.getAllByRole('button', { + name: t('settings.anisette.add') + }) + if (add) await user.click(add) + const dialog = await screen.findByRole('dialog', { + name: t('settings.anisette.dialog.addTitle') + }) + await user.type( + within(dialog).getByLabelText(t('settings.anisette.dialog.name')), + name + ) + await user.type( + within(dialog).getByLabelText(t('settings.anisette.dialog.address')), + address + ) + await user.click( + within(dialog).getByRole('button', { name: t('settings.anisette.add') }) + ) + + return dialog +} + +describe('Anisette servers', () => { + it("lists SideStore's list in Automatic's order, then the backup, and says what was left out", async () => { + const { card } = await openCard() + + expect( + within(card).getByText(t('settings.anisette.group.list')) + ).toBeDefined() + expect( + within(card).getByText(t('settings.anisette.group.backup')) + ).toBeDefined() + expect( + within(rowOf(card, 'https://ani.sidestore.io')).getByText( + t('settings.anisette.tag.inUse') + ) + ).toBeDefined() + expect( + within(card).getByRole('img', { + name: t('settings.anisette.position', { position: 1 }) + }) + ).toBeDefined() + expect(card.textContent).toContain( + t('settings.anisette.count', { count: 8 }) + ) + expect(card.textContent).toContain('Macley') + }) + + it('adds a plain-HTTP server of your own, first in the list', async () => { + const { user, card } = await openCard() + await addServer(user, 'Home', HOME) + + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + const first = within(card).getAllByRole('listitem')[1] + expect(first?.textContent).toContain('Home') + expect(first?.textContent).toContain(t('settings.anisette.tag.custom')) + }) + + it('refuses a server already in the list, or one without a name', async () => { + const { user } = await openCard() + const dialog = await addServer(user, 'Again', 'https://ani.sidestore.io/') + + expect( + await within(dialog).findByText(t('settings.anisette.dialog.exists')) + ).toBeDefined() + await user.clear( + within(dialog).getByLabelText(t('settings.anisette.dialog.name')) + ) + await user.click( + within(dialog).getByRole('button', { name: t('settings.anisette.add') }) + ) + expect( + await within(dialog).findByText(t('settings.anisette.dialog.nameMissing')) + ).toBeDefined() + }) + + it('tests a server and says how fast it answered, or that it did not', async () => { + const { user, card } = await openCard() + await user.click( + within(rowOf(card, 'https://ani.sidestore.io')).getByRole('button', { + name: t('settings.anisette.testOne', { name: 'SideStore' }) + }) + ) + await waitFor(() => + expect(rowOf(card, 'https://ani.sidestore.io').textContent).toMatch( + /Working · \d+ ms/ + ) + ) + + await user.click( + within(rowOf(card, 'https://ani.sidestore.zip')).getByRole('button', { + name: t('settings.anisette.testOne', { name: 'SideStore (.zip)' }) + }) + ) + await waitFor(() => + expect(rowOf(card, 'https://ani.sidestore.zip').textContent).toContain( + t('settings.anisette.status.bad') + ) + ) + }) + + it('picks one server, and warns when it does not answer', async () => { + const { user, card } = await openCard() + await user.click( + within(card).getByRole('radio', { + name: t('settings.anisette.mode.chosen') + }) + ) + expect( + await within(card).findByText(t('settings.anisette.noneChosen')) + ).toBeDefined() + + await user.click( + within(card).getByRole('radio', { + name: t('settings.anisette.use', { name: 'SideStore (.zip)' }) + }) + ) + expect( + await within(card).findByText( + t('settings.anisette.modeHint.chosen', { name: 'SideStore (.zip)' }) + ) + ).toBeDefined() + await user.click( + within(rowOf(card, 'https://ani.sidestore.zip')).getByRole('button', { + name: t('settings.anisette.testOne', { name: 'SideStore (.zip)' }) + }) + ) + expect( + await within(card).findByText( + t('settings.anisette.chosenDown', { name: 'SideStore (.zip)' }) + ) + ).toBeDefined() + }) + + it('removes a server you added, after asking', async () => { + const { user, card } = await openCard() + await addServer(user, 'Home', HOME) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + await user.click( + within(rowOf(card, HOME)).getByRole('button', { + name: t('settings.anisette.remove', { name: 'Home' }) + }) + ) + await user.click( + within(rowOf(card, HOME)).getByRole('button', { + name: t('settings.anisette.removeYes') + }) + ) + + await waitFor(() => expect(within(card).queryByText(HOME)).toBeNull()) + }) + + it('is outlined when opened from "Choose another anisette server"', async () => { + const { card } = await openCard('/settings#anisette') + + await waitFor(() => expect(card.className).toContain('ring-accent')) + }) +}) diff --git a/packages/ui/src/features/settings/anisette/components/anisette-settings.tsx b/packages/ui/src/features/settings/anisette/components/anisette-settings.tsx new file mode 100644 index 00000000..4324ffbf --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/anisette-settings.tsx @@ -0,0 +1,132 @@ +import { Button, Card, Spinner } from '@heroui/react' +import { Plus } from 'lucide-react' +import { useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' + +import { ChoiceNotice } from '@ui/features/settings/anisette/components/choice-notice.tsx' +import { ListBar } from '@ui/features/settings/anisette/components/list-bar.tsx' +import { ModeSwitch } from '@ui/features/settings/anisette/components/mode-switch.tsx' +import { ServerDialog } from '@ui/features/settings/anisette/components/server-dialog.tsx' +import { ServerList } from '@ui/features/settings/anisette/components/server-list.tsx' +import { SkippedNote } from '@ui/features/settings/anisette/components/skipped-note.tsx' +import { ANISETTE_CARD_ID } from '@ui/features/settings/anisette/constants.ts' +import { useCardHighlight } from '@ui/features/settings/anisette/hooks/use-card-highlight.ts' +import { useServerTests } from '@ui/features/settings/anisette/hooks/use-server-tests.ts' +import type { + ServerDialogTarget, + ServerTestState +} from '@ui/features/settings/anisette/types.ts' +import { useAnisetteActions } from '@ui/hooks/queries/use-anisette-actions.ts' +import { useAnisetteServers } from '@ui/hooks/queries/use-anisette-servers.ts' +import type { + AnisetteChoice, + AnisetteServerEntry +} from '@ui/services/engine/types.ts' + +/** + * Anisette servers: Automatic (the servers in order, moving on when one fails) or one chosen server, the servers + * the user added first, then SideStore's list, then the built-in backup; each can be tested, and the user's own + * added, edited and removed. + */ +export const AnisetteSettings = () => { + const { t } = useTranslation() + const card = useRef(null) + const isHighlighted = useCardHighlight(card) + const servers = useAnisetteServers() + const actions = useAnisetteActions() + const tests = useServerTests() + const [dialog, setDialog] = useState() + const overview = servers.data + const isTesting = Object.values(tests.states).some( + (state) => state.phase === 'testing' + ) + const onMode = (mode: AnisetteChoice['mode']) => + actions.choose.mutate(mode === 'automatic' ? { mode } : { mode: 'chosen' }) + const onChoose = (server: AnisetteServerEntry) => + actions.choose.mutate({ + mode: 'chosen', + server: { name: server.name, address: server.address } + }) + const onAdd = () => setDialog({ mode: 'add' }) + const onEdit = (server: AnisetteServerEntry) => + setDialog({ mode: 'edit', server }) + const onClose = () => setDialog(undefined) + const onSaved = (address: string, test: ServerTestState | undefined) => { + if (test && test.phase !== 'testing') tests.record(address, test) + setDialog(undefined) + } + const onRemove = (address: string) => actions.remove.mutate(address) + const onUpdate = () => actions.updateList.mutate() + const onTestAll = () => + tests.testAll(overview?.servers.map((server) => server.address) ?? []) + + return ( + + +
+
+

+ {t('settings.anisette.title')} +

+

+ {t('settings.anisette.hint')} +

+
+ +
+ {overview ? ( + <> + + + + + + + ) : ( +

+ + {t('settings.anisette.loading')} +

+ )} +
+ {dialog && overview ? ( + + ) : null} +
+ ) +} diff --git a/packages/ui/src/features/settings/anisette/components/choice-notice.tsx b/packages/ui/src/features/settings/anisette/components/choice-notice.tsx new file mode 100644 index 00000000..41d77925 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/choice-notice.tsx @@ -0,0 +1,44 @@ +import { Alert } from '@heroui/react' +import { useTranslation } from 'react-i18next' + +import type { ServerTests } from '@ui/features/settings/anisette/types.ts' +import type { AnisetteChoice } from '@ui/services/engine/types.ts' + +type ChoiceNoticeProps = { + choice: AnisetteChoice + tests: ServerTests +} + +/** + * When the user picks servers: none picked yet (IPAForge still picks by itself), or the picked one didn't answer + * its test (signing in fails until it's back, another is picked, or Automatic is on again). + */ +export const ChoiceNotice = ({ choice, tests }: ChoiceNoticeProps) => { + const { t } = useTranslation() + if (choice.mode !== 'chosen') return null + const { server } = choice + + if (!server) + return ( + + + + + {t('settings.anisette.noneChosen')} + + + + ) + if (tests.states[server.address]?.phase !== 'bad') return null + + return ( + + + + + {t('settings.anisette.chosenDown', { name: server.name })} + + + + ) +} diff --git a/packages/ui/src/features/settings/anisette/components/list-bar.tsx b/packages/ui/src/features/settings/anisette/components/list-bar.tsx new file mode 100644 index 00000000..914a3507 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/list-bar.tsx @@ -0,0 +1,79 @@ +import { Button, Spinner } from '@heroui/react' +import { Activity, RefreshCw } from 'lucide-react' +import { useTranslation } from 'react-i18next' + +import { timeAgo } from '@ui/features/preload/home/utils/time-ago.ts' +import { useFormat } from '@ui/hooks/use-format.ts' +import type { AnisetteOverview } from '@ui/services/engine/types.ts' + +type ListBarProps = { + overview: AnisetteOverview + isUpdating: boolean + isTesting: boolean + onUpdate: () => void + onTestAll: () => void +} + +/** How many servers and from where, when SideStore's list was fetched, Update list and Test all. */ +export const ListBar = ({ + overview, + isUpdating, + isTesting, + onUpdate, + onTestAll +}: ListBarProps) => { + const { t } = useTranslation() + const { relativeTime } = useFormat() + const count = (source: string) => + overview.servers.filter((server) => server.source === source).length + const listAge = overview.listUpdatedAt + ? t('settings.anisette.listUpdated', { + ago: timeAgo(new Date(overview.listUpdatedAt), new Date(), relativeTime) + }) + : t('settings.anisette.listNever') + const updated = isUpdating ? t('settings.anisette.updating') : listAge + + return ( +
+ + + {t('settings.anisette.count', { count: overview.servers.length })} + {' '} + {t('settings.anisette.sources', { + custom: count('custom'), + list: count('list'), + backup: count('backup') + })}{' '} + {updated} + + + +
+ ) +} diff --git a/packages/ui/src/features/settings/anisette/components/mode-switch.tsx b/packages/ui/src/features/settings/anisette/components/mode-switch.tsx new file mode 100644 index 00000000..06fabe13 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/mode-switch.tsx @@ -0,0 +1,49 @@ +import { ToggleButton, ToggleButtonGroup } from '@heroui/react' +import type { Key } from 'react' +import { useTranslation } from 'react-i18next' + +import { + anisetteModes, + modeHintKeys, + modeLabelKeys +} from '@ui/features/settings/anisette/constants.ts' +import type { AnisetteChoice } from '@ui/services/engine/types.ts' + +type ModeSwitchProps = { + choice: AnisetteChoice + onChange: (mode: AnisetteChoice['mode']) => void +} + +/** Automatic or Choose a server, and what that means now. */ +export const ModeSwitch = ({ choice, onChange }: ModeSwitchProps) => { + const { t } = useTranslation() + const onSelectionChange = (keys: Set) => { + const [selected] = keys + const mode = anisetteModes.find((candidate) => candidate === selected) + if (mode) onChange(mode) + } + const chosen = choice.mode === 'chosen' ? choice.server : undefined + const hint = chosen + ? t('settings.anisette.modeHint.chosen', { name: chosen.name }) + : t(modeHintKeys[choice.mode]) + + return ( +
+ + {anisetteModes.map((mode) => ( + + {t(modeLabelKeys[mode])} + + ))} + + {hint} +
+ ) +} diff --git a/packages/ui/src/features/settings/anisette/components/remove-confirm.tsx b/packages/ui/src/features/settings/anisette/components/remove-confirm.tsx new file mode 100644 index 00000000..5effdf1a --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/remove-confirm.tsx @@ -0,0 +1,36 @@ +import { Button } from '@heroui/react' +import { useTranslation } from 'react-i18next' + +type RemoveConfirmProps = { + name: string + isPending: boolean + onRemove: () => void + onCancel: () => void +} + +/** Under a server the user added: Remove it? with Remove and Cancel. */ +export const RemoveConfirm = ({ + name, + isPending, + onRemove, + onCancel +}: RemoveConfirmProps) => { + const { t } = useTranslation() + + return ( +
+ {t('settings.anisette.confirmRemove', { name })} + + +
+ ) +} diff --git a/packages/ui/src/features/settings/anisette/components/server-dialog.tsx b/packages/ui/src/features/settings/anisette/components/server-dialog.tsx new file mode 100644 index 00000000..a34c4d18 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/server-dialog.tsx @@ -0,0 +1,148 @@ +import { + Button, + Description, + FieldError, + Input, + Label, + Modal, + TextField +} from '@heroui/react' +import { Activity } from 'lucide-react' +import type { FormEvent } from 'react' +import { useTranslation } from 'react-i18next' + +import { ServerStatus } from '@ui/features/settings/anisette/components/server-status.tsx' +import { useServerForm } from '@ui/features/settings/anisette/hooks/use-server-form.ts' +import type { + ServerDialogTarget, + ServerTestState +} from '@ui/features/settings/anisette/types.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +type ServerDialogProps = { + target: ServerDialogTarget + servers: readonly AnisetteServerEntry[] + onSaved: (address: string, test: ServerTestState | undefined) => void + onClose: () => void +} + +/** + * Add an anisette server, or edit one the user added: a name and an address (https, or http for one they run + * themselves), a test before saving, and Save. A server that doesn't answer can still be added. + */ +export const ServerDialog = ({ + target, + servers, + onSaved, + onClose +}: ServerDialogProps) => { + const { t } = useTranslation() + const form = useServerForm(target, servers, onSaved) + const isEditing = target.mode === 'edit' + const onOpenChange = (isOpen: boolean) => { + if (!(isOpen || form.isSaving)) onClose() + } + const onSubmit = (event: FormEvent) => { + event.preventDefault() + form.onSave() + } + + return ( + + + + +
+ + + {t( + isEditing + ? 'settings.anisette.dialog.editTitle' + : 'settings.anisette.dialog.addTitle' + )} + + + +

+ {t('settings.anisette.dialog.body')} +

+ + + + {form.problems.name ? ( + {t(form.problems.name)} + ) : null} + + + + + {form.problems.address ? ( + {t(form.problems.address)} + ) : ( + + {t('settings.anisette.dialog.addressHint')} + + )} + +
+ {form.test ? : null} + {form.test?.phase === 'bad' ? ( + + {t('settings.anisette.dialog.stillAdd')} + + ) : null} +
+
+ + + + + +
+
+
+
+
+ ) +} diff --git a/packages/ui/src/features/settings/anisette/components/server-lead.tsx b/packages/ui/src/features/settings/anisette/components/server-lead.tsx new file mode 100644 index 00000000..f9c2e4a2 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/server-lead.tsx @@ -0,0 +1,63 @@ +import { RadioButton, RadioField } from 'react-aria-components' +import { useTranslation } from 'react-i18next' + +import { ServerName } from '@ui/features/settings/anisette/components/server-name.tsx' +import { LEAD_CLASS } from '@ui/features/settings/anisette/constants.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +type ServerLeadProps = { + server: AnisetteServerEntry + /** Where Automatic tries it (1 first); undefined when the user picks a server, which shows a radio instead. */ + position: number | undefined + markKey: + | 'settings.anisette.tag.inUse' + | 'settings.anisette.tag.chosen' + | undefined +} + +/** + * A server's place in Automatic's order and its name; when the user picks a server, a radio instead of the place, + * and the whole name selects it. + */ +export const ServerLead = ({ server, position, markKey }: ServerLeadProps) => { + const { t } = useTranslation() + const name = + + if (position !== undefined) + return ( +
+ + {position} + + {name} +
+ ) + + return ( + + + {({ isSelected, isFocusVisible }) => ( + <> + + + ) +} diff --git a/packages/ui/src/features/settings/anisette/components/server-list.tsx b/packages/ui/src/features/settings/anisette/components/server-list.tsx new file mode 100644 index 00000000..05e32e05 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/server-list.tsx @@ -0,0 +1,95 @@ +import { RadioGroup } from 'react-aria-components' +import { useTranslation } from 'react-i18next' + +import { ServerRow } from '@ui/features/settings/anisette/components/server-row.tsx' +import { groupLabelKeys } from '@ui/features/settings/anisette/constants.ts' +import type { ServerTests } from '@ui/features/settings/anisette/types.ts' +import { markKeyFor } from '@ui/features/settings/anisette/utils/mark-key.ts' +import { serverKey } from '@ui/features/settings/anisette/utils/server-form-problems.ts' +import { serverGroups } from '@ui/features/settings/anisette/utils/server-groups.ts' +import type { + AnisetteOverview, + AnisetteServerEntry +} from '@ui/services/engine/types.ts' + +type ServerListProps = { + overview: AnisetteOverview + tests: ServerTests + removing: string | undefined + onChoose: (server: AnisetteServerEntry) => void + onEdit: (server: AnisetteServerEntry) => void + onRemove: (address: string) => void +} + +/** + * The servers by group, in the order Automatic tries them, numbered; when the user picks a server, a radio list + * instead. + */ +export const ServerList = ({ + overview, + tests, + removing, + onChoose, + onEdit, + onRemove +}: ServerListProps) => { + const { t } = useTranslation() + const isChoosing = overview.choice.mode === 'chosen' + const chosen = + overview.choice.mode === 'chosen' ? overview.choice.server : undefined + const groups = serverGroups(overview.servers) + const onChange = (address: string) => { + const server = overview.servers.find( + (candidate) => candidate.address === address + ) + if (server) onChoose(server) + } + let position = 0 + + const list = ( +
    + {groups.map((group) => ( +
  • +

    + {t(groupLabelKeys[group.source])} +

    +
      + {group.servers.map((server) => { + position += 1 + const isSelected = + chosen !== undefined && + serverKey(chosen.address) === serverKey(server.address) + + return ( + + ) + })} +
    +
  • + ))} +
+ ) + + if (!isChoosing) return list + + return ( + + {list} + + ) +} diff --git a/packages/ui/src/features/settings/anisette/components/server-name.tsx b/packages/ui/src/features/settings/anisette/components/server-name.tsx new file mode 100644 index 00000000..caeae524 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/server-name.tsx @@ -0,0 +1,37 @@ +import { useTranslation } from 'react-i18next' + +import { TAG_CLASS } from '@ui/features/settings/anisette/constants.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +type ServerNameProps = { + server: AnisetteServerEntry + /** "In use" (Automatic) or "Chosen" (picked by the user), filled in the accent colour. */ + markKey: + | 'settings.anisette.tag.inUse' + | 'settings.anisette.tag.chosen' + | undefined +} + +/** A server's name, its tags, and its address under it. */ +export const ServerName = ({ server, markKey }: ServerNameProps) => { + const { t } = useTranslation() + + return ( + + {server.name} + {server.source === 'custom' ? ( + + {t('settings.anisette.tag.custom')} + + ) : null} + {markKey ? ( + + {t(markKey)} + + ) : null} + + {server.address} + + + ) +} diff --git a/packages/ui/src/features/settings/anisette/components/server-row.tsx b/packages/ui/src/features/settings/anisette/components/server-row.tsx new file mode 100644 index 00000000..8dc4763f --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/server-row.tsx @@ -0,0 +1,100 @@ +import { Button } from '@heroui/react' +import { Activity, Pencil, Trash2 } from 'lucide-react' +import { useState } from 'react' +import { useTranslation } from 'react-i18next' + +import { RemoveConfirm } from '@ui/features/settings/anisette/components/remove-confirm.tsx' +import { ServerLead } from '@ui/features/settings/anisette/components/server-lead.tsx' +import { ServerStatus } from '@ui/features/settings/anisette/components/server-status.tsx' +import type { ServerTestState } from '@ui/features/settings/anisette/types.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +type ServerRowProps = { + server: AnisetteServerEntry + position: number | undefined + markKey: + | 'settings.anisette.tag.inUse' + | 'settings.anisette.tag.chosen' + | undefined + isSelected: boolean + test: ServerTestState | undefined + isRemoving: boolean + onTest: (address: string) => void + onEdit: (server: AnisetteServerEntry) => void + onRemove: (address: string) => void +} + +/** One server: its place or radio, name and address, its last test, and Test (Edit and Remove for yours). */ +export const ServerRow = ({ + server, + position, + markKey, + isSelected, + test, + isRemoving, + onTest, + onEdit, + onRemove +}: ServerRowProps) => { + const { t } = useTranslation() + const [isConfirming, setIsConfirming] = useState(false) + const isOwn = server.source === 'custom' + const onTestPress = () => onTest(server.address) + const onEditPress = () => onEdit(server) + const onRemovePress = () => setIsConfirming(true) + const onCancelRemove = () => setIsConfirming(false) + const onConfirmRemove = () => onRemove(server.address) + + return ( +
  • + + + + + + + {isOwn ? ( + <> + + + + ) : null} + + {isConfirming ? ( + + ) : null} +
  • + ) +} diff --git a/packages/ui/src/features/settings/anisette/components/server-status.tsx b/packages/ui/src/features/settings/anisette/components/server-status.tsx new file mode 100644 index 00000000..95cc7552 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/server-status.tsx @@ -0,0 +1,32 @@ +import { Spinner } from '@heroui/react' +import { useTranslation } from 'react-i18next' + +import { statusClasses } from '@ui/features/settings/anisette/constants.ts' +import type { ServerTestState } from '@ui/features/settings/anisette/types.ts' + +type ServerStatusProps = { state: ServerTestState | undefined } + +/** A server's last test: Not tested, Testing…, Working · 240 ms, or Not responding. */ +export const ServerStatus = ({ state }: ServerStatusProps) => { + const { t } = useTranslation() + const phase = state?.phase ?? 'untested' + const classes = statusClasses[phase] + + return ( + + {phase === 'testing' ? ( + + ) : ( + + ) +} diff --git a/packages/ui/src/features/settings/anisette/components/skipped-note.tsx b/packages/ui/src/features/settings/anisette/components/skipped-note.tsx new file mode 100644 index 00000000..6f6bb693 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/components/skipped-note.tsx @@ -0,0 +1,18 @@ +import { useTranslation } from 'react-i18next' + +import { useFormat } from '@ui/hooks/use-format.ts' + +type SkippedNoteProps = { names: readonly string[] } + +/** The servers of SideStore's list left out because they aren't HTTPS, and that the user can add one themselves. */ +export const SkippedNote = ({ names }: SkippedNoteProps) => { + const { t } = useTranslation() + const { list } = useFormat() + if (names.length === 0) return null + + return ( +

    + {t('settings.anisette.skipped', { names: list(names) })} +

    + ) +} diff --git a/packages/ui/src/features/settings/anisette/constants.ts b/packages/ui/src/features/settings/anisette/constants.ts new file mode 100644 index 00000000..612bad95 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/constants.ts @@ -0,0 +1,51 @@ +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +/** The id of the Anisette servers card: "Choose another anisette server" opens Settings at it. */ +export const ANISETTE_CARD_ID = 'anisette' + +/** The list's groups, in the order Automatic tries them. */ +export const serverSources = [ + 'custom', + 'list', + 'backup' +] as const satisfies readonly AnisetteServerEntry['source'][] + +/** Each group's heading. */ +export const groupLabelKeys = { + custom: 'settings.anisette.group.custom', + list: 'settings.anisette.group.list', + backup: 'settings.anisette.group.backup' +} as const satisfies Record + +/** The two ways of picking a server, as the switch shows them. */ +export const anisetteModes = ['automatic', 'chosen'] as const + +/** What each mode means, next to the switch (Choose a server, with none chosen yet). */ +export const modeHintKeys = { + automatic: 'settings.anisette.modeHint.automatic', + chosen: 'settings.anisette.modeHint.none' +} as const + +/** A server's place, or its radio, beside its name. */ +export const LEAD_CLASS = + 'grid grid-cols-[1.75rem_minmax(0,1fr)] items-center gap-3' + +/** A tag next to a server's name. */ +export const TAG_CLASS = 'whitespace-nowrap rounded-full px-2 py-0.5 text-xs' + +/** Each mode's label in the switch. */ +export const modeLabelKeys = { + automatic: 'settings.anisette.mode.automatic', + chosen: 'settings.anisette.mode.chosen' +} as const + +/** A test's status: its dot's colour and its text's colour. */ +export const statusClasses = { + untested: { dot: 'bg-surface-tertiary', text: 'text-muted' }, + testing: { dot: '', text: 'text-muted' }, + ok: { dot: 'bg-success', text: 'text-success' }, + bad: { dot: 'bg-danger', text: 'text-danger-soft-foreground' } +} as const + +/** How long the card stays outlined after "Choose another anisette server" opened it. */ +export const HIGHLIGHT_MS = 1600 diff --git a/packages/ui/src/features/settings/anisette/hooks/use-card-highlight.ts b/packages/ui/src/features/settings/anisette/hooks/use-card-highlight.ts new file mode 100644 index 00000000..60f19953 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/hooks/use-card-highlight.ts @@ -0,0 +1,26 @@ +import { useLocation } from '@tanstack/react-router' +import { type RefObject, useEffect, useState } from 'react' + +import { + ANISETTE_CARD_ID, + HIGHLIGHT_MS +} from '@ui/features/settings/anisette/constants.ts' + +/** Opened from "Choose another anisette server" (`/settings#anisette`): scrolls to the card and outlines it a moment. */ +export const useCardHighlight = ( + card: RefObject +): boolean => { + const hash = useLocation({ select: (location) => location.hash }) + const [isHighlighted, setIsHighlighted] = useState(false) + + useEffect(() => { + if (hash !== ANISETTE_CARD_ID) return + card.current?.scrollIntoView?.({ block: 'start' }) + setIsHighlighted(true) + const timer = setTimeout(() => setIsHighlighted(false), HIGHLIGHT_MS) + + return () => clearTimeout(timer) + }, [hash, card]) + + return isHighlighted +} diff --git a/packages/ui/src/features/settings/anisette/hooks/use-server-form.ts b/packages/ui/src/features/settings/anisette/hooks/use-server-form.ts new file mode 100644 index 00000000..94154390 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/hooks/use-server-form.ts @@ -0,0 +1,82 @@ +import { useState } from 'react' + +import { toIPAForgeError } from '@ipaforge/kernel' +import type { + ServerDialogTarget, + ServerFormProblems, + ServerTestState +} from '@ui/features/settings/anisette/types.ts' +import { serverFormProblems } from '@ui/features/settings/anisette/utils/server-form-problems.ts' +import { useAnisetteActions } from '@ui/hooks/queries/use-anisette-actions.ts' +import { useEngine } from '@ui/hooks/use-engine.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +/** What the Engine said to a save it refused, as the field's problem. */ +const engineProblem = (error: unknown): ServerFormProblems => + toIPAForgeError(error).code === 'apple.anisette_server_exists' + ? { address: 'settings.anisette.dialog.exists' } + : { address: 'settings.anisette.dialog.addressInvalid' } + +/** + * The Add or Edit server form: the name and address, their problems once the user tries to test or save, the + * dialog's own test, and the save (adding a server makes it the one used). + */ +export const useServerForm = ( + target: ServerDialogTarget, + servers: readonly AnisetteServerEntry[], + onSaved: (address: string, test: ServerTestState | undefined) => void +) => { + const engine = useEngine() + const { add, update } = useAnisetteActions() + const editing = target.mode === 'edit' ? target.server : undefined + const [name, setName] = useState(editing?.name ?? '') + const [address, setAddress] = useState(editing?.address ?? '') + const [problems, setProblems] = useState({}) + const [test, setTest] = useState() + const check = () => { + const found = serverFormProblems(name, address, servers, editing?.address) + setProblems(found) + return found + } + + return { + name, + address, + problems, + test, + isSaving: add.isPending || update.isPending, + onNameChange: (value: string) => { + setName(value) + setProblems(({ address: kept }) => (kept ? { address: kept } : {})) + }, + onAddressChange: (value: string) => { + setAddress(value) + setTest(undefined) + setProblems(({ name: kept }) => (kept ? { name: kept } : {})) + }, + onTest: () => { + if (check().address) return + setTest({ phase: 'testing' }) + engine.testAnisetteServer(address.trim()).then( + (result) => + setTest( + result.ok && result.latencyMs !== undefined + ? { phase: 'ok', latencyMs: result.latencyMs } + : { phase: 'bad' } + ), + () => setTest({ phase: 'bad' }) + ) + }, + onSave: () => { + const found = check() + if (found.name || found.address) return + const input = { name: name.trim(), address: address.trim() } + const options = { + onSuccess: () => onSaved(input.address, test), + onError: (error: unknown) => setProblems(engineProblem(error)) + } + if (editing) update.mutate({ ...input, from: editing.address }, options) + else add.mutate(input, options) + } + } +} diff --git a/packages/ui/src/features/settings/anisette/hooks/use-server-tests.ts b/packages/ui/src/features/settings/anisette/hooks/use-server-tests.ts new file mode 100644 index 00000000..986ffd1d --- /dev/null +++ b/packages/ui/src/features/settings/anisette/hooks/use-server-tests.ts @@ -0,0 +1,40 @@ +import { useState } from 'react' + +import type { + ServerTestState, + ServerTests +} from '@ui/features/settings/anisette/types.ts' +import { useEngine } from '@ui/hooks/use-engine.ts' +import type { AnisetteServerTest } from '@ui/services/engine/types.ts' + +const toState = (result: AnisetteServerTest): ServerTestState => + result.ok && result.latencyMs !== undefined + ? { phase: 'ok', latencyMs: result.latencyMs } + : { phase: 'bad' } + +/** + * Each server's test while Settings is open: Testing…, then how fast it answered or that it didn't. Test all runs + * them side by side; nothing is kept once the page closes. + */ +export const useServerTests = (): ServerTests => { + const engine = useEngine() + const [states, setStates] = useState>({}) + const record = (address: string, state: ServerTestState) => + setStates((current) => ({ ...current, [address]: state })) + const test = (address: string) => { + record(address, { phase: 'testing' }) + engine.testAnisetteServer(address).then( + (result) => record(address, toState(result)), + () => record(address, { phase: 'bad' }) + ) + } + + return { + states, + test, + testAll: (addresses) => { + for (const address of addresses) test(address) + }, + record + } +} diff --git a/packages/ui/src/features/settings/anisette/types.ts b/packages/ui/src/features/settings/anisette/types.ts new file mode 100644 index 00000000..561db117 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/types.ts @@ -0,0 +1,35 @@ +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +/** A server's last test in this window: running, answered (how fast), or no answer. */ +export type ServerTestState = + | { readonly phase: 'testing' } + | { readonly phase: 'ok'; readonly latencyMs: number } + | { readonly phase: 'bad' } + +/** The tests run so far, by address, and how to run one or all. */ +export type ServerTests = { + readonly states: Readonly> + test(address: string): void + testAll(addresses: readonly string[]): void + /** Records a result the Add server dialog already has. */ + record(address: string, state: ServerTestState): void +} + +/** The list's groups, in the order Automatic tries them. */ +export type ServerGroup = { + readonly source: AnisetteServerEntry['source'] + readonly servers: readonly AnisetteServerEntry[] +} + +/** What the Add or Edit server dialog edits: nothing for a new one, else the server being edited. */ +export type ServerDialogTarget = + | { readonly mode: 'add' } + | { readonly mode: 'edit'; readonly server: AnisetteServerEntry } + +/** Why the typed server can't be saved, as a translation key per field. */ +export type ServerFormProblems = { + readonly name?: 'settings.anisette.dialog.nameMissing' + readonly address?: + | 'settings.anisette.dialog.addressInvalid' + | 'settings.anisette.dialog.exists' +} diff --git a/packages/ui/src/features/settings/anisette/utils/mark-key.ts b/packages/ui/src/features/settings/anisette/utils/mark-key.ts new file mode 100644 index 00000000..05869845 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/utils/mark-key.ts @@ -0,0 +1,21 @@ +import type { + AnisetteOverview, + AnisetteServerEntry +} from '@ui/services/engine/types.ts' + +/** "Chosen" for the server the user picked, "In use" for the one Automatic used last, else nothing. */ +export const markKeyFor = ( + overview: AnisetteOverview, + server: AnisetteServerEntry, + isSelected: boolean +): + | 'settings.anisette.tag.inUse' + | 'settings.anisette.tag.chosen' + | undefined => { + if (overview.choice.mode === 'chosen') + return isSelected ? 'settings.anisette.tag.chosen' : undefined + + return overview.lastUsed === server.address + ? 'settings.anisette.tag.inUse' + : undefined +} diff --git a/packages/ui/src/features/settings/anisette/utils/server-form-problems.ts b/packages/ui/src/features/settings/anisette/utils/server-form-problems.ts new file mode 100644 index 00000000..a7dcad6f --- /dev/null +++ b/packages/ui/src/features/settings/anisette/utils/server-form-problems.ts @@ -0,0 +1,48 @@ +import type { ServerFormProblems } from '@ui/features/settings/anisette/types.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +/** The address without trailing slashes, lower case: how the Engine tells two servers apart. */ +export const serverKey = (address: string): string => { + let end = address.length + while (end > 0 && address[end - 1] === '/') end -= 1 + + return address.slice(0, end).trim().toLowerCase() +} + +const isHttpAddress = (address: string): boolean => { + if (!URL.canParse(address)) return false + const { protocol, username, password } = new URL(address) + + return ( + (protocol === 'https:' || protocol === 'http:') && !(username || password) + ) +} + +/** + * What's wrong with the server as typed, before the Engine is asked: no name, not an http(s) address (or one with a + * user name or password in it), or one in + * the list already (`editing`: the address the server had, which it may keep). + */ +export const serverFormProblems = ( + name: string, + address: string, + servers: readonly AnisetteServerEntry[], + editing?: string +): ServerFormProblems => { + const trimmed = address.trim() + const taken = servers.some( + (server) => + serverKey(server.address) === serverKey(trimmed) && + (editing === undefined || + serverKey(server.address) !== serverKey(editing)) + ) + let addressProblem: ServerFormProblems['address'] + if (!isHttpAddress(trimmed)) + addressProblem = 'settings.anisette.dialog.addressInvalid' + else if (taken) addressProblem = 'settings.anisette.dialog.exists' + + return { + ...(name.trim() ? {} : { name: 'settings.anisette.dialog.nameMissing' }), + ...(addressProblem ? { address: addressProblem } : {}) + } +} diff --git a/packages/ui/src/features/settings/anisette/utils/server-groups.ts b/packages/ui/src/features/settings/anisette/utils/server-groups.ts new file mode 100644 index 00000000..484624f0 --- /dev/null +++ b/packages/ui/src/features/settings/anisette/utils/server-groups.ts @@ -0,0 +1,14 @@ +import { serverSources } from '@ui/features/settings/anisette/constants.ts' +import type { ServerGroup } from '@ui/features/settings/anisette/types.ts' +import type { AnisetteServerEntry } from '@ui/services/engine/types.ts' + +/** The servers by where they come from (added by you, SideStore's list, backup), empty groups left out. */ +export const serverGroups = ( + servers: readonly AnisetteServerEntry[] +): ServerGroup[] => + serverSources + .map((source) => ({ + source, + servers: servers.filter((server) => server.source === source) + })) + .filter((group) => group.servers.length > 0) diff --git a/packages/ui/src/features/settings/settings-page.tsx b/packages/ui/src/features/settings/settings-page.tsx index 5e8cd69b..a795f64a 100644 --- a/packages/ui/src/features/settings/settings-page.tsx +++ b/packages/ui/src/features/settings/settings-page.tsx @@ -1,12 +1,14 @@ import { PageHeader } from '@ui/components/page-header.tsx' +import { AnisetteSettings } from '@ui/features/settings/anisette/components/anisette-settings.tsx' import { AppearanceSettings } from '@ui/features/settings/components/appearance-settings.tsx' import { LanguageSettings } from '@ui/features/settings/components/language-settings.tsx' -/** Settings: one card per group (appearance, then language). */ +/** Settings: one card per group (appearance, language, then anisette servers). */ export const SettingsPage = () => (
    +
    ) diff --git a/packages/ui/src/features/updates/components/native-build-dialog.tsx b/packages/ui/src/features/updates/components/native-build-dialog.tsx new file mode 100644 index 00000000..f4968ea9 --- /dev/null +++ b/packages/ui/src/features/updates/components/native-build-dialog.tsx @@ -0,0 +1,54 @@ +import { Button, Modal } from '@heroui/react' +import { useTranslation } from 'react-i18next' + +import { useUiServices } from '@ui/hooks/use-ui-services.ts' + +type NativeBuildDialogProps = { + /** Where the Apple silicon build is. */ + url: string + onLater: () => void +} + +/** + * The Intel build is running under Rosetta on an Apple silicon Mac, where everything is slower: says so, and where + * the Apple silicon build is. Installing it over this one keeps everything. + */ +export const NativeBuildDialog = ({ url, onLater }: NativeBuildDialogProps) => { + const { t } = useTranslation() + const { links } = useUiServices() + const onOpenChange = (isOpen: boolean) => { + if (!isOpen) onLater() + } + const onDownload = () => { + links.open(url) + onLater() + } + + return ( + + + + + + {t('updates.nativeBuild.title')} + + +

    {t('updates.nativeBuild.body')}

    + + {t('updates.nativeBuild.file')} + +
    + + + + +
    +
    +
    +
    + ) +} diff --git a/packages/ui/src/features/updates/components/update-gate.tsx b/packages/ui/src/features/updates/components/update-gate.tsx index cdf5bdac..9a980bcb 100644 --- a/packages/ui/src/features/updates/components/update-gate.tsx +++ b/packages/ui/src/features/updates/components/update-gate.tsx @@ -1,6 +1,7 @@ import { type ReactNode, useState } from 'react' import { ManualUpdateDialog } from '@ui/features/updates/components/manual-update-dialog.tsx' +import { NativeBuildDialog } from '@ui/features/updates/components/native-build-dialog.tsx' import { UpdateScreen } from '@ui/features/updates/components/update-screen.tsx' import { blockingPhases } from '@ui/features/updates/constants.ts' import { useUpdateState } from '@ui/features/updates/hooks/use-update-state.ts' @@ -10,7 +11,7 @@ type UpdateGateProps = { children: ReactNode } /** * Keeps the app behind the update screen while IPAForge checks for, downloads and installs a newer version, so an * old version isn't used meanwhile. After a failure the user may go on; a copy that can't update itself only says - * a new version is out. + * a new version is out, and the Intel build on an Apple silicon Mac says where the faster one is. */ export const UpdateGate = ({ children }: UpdateGateProps) => { const state = useUpdateState() @@ -26,6 +27,9 @@ export const UpdateGate = ({ children }: UpdateGateProps) => { {state.phase === 'manual' && !isDismissed ? ( ) : null} + {state.phase === 'idle' && state.nativeBuild && !isDismissed ? ( + + ) : null} ) } diff --git a/packages/ui/src/features/updates/update-gate.test.tsx b/packages/ui/src/features/updates/update-gate.test.tsx index 42451db4..d62b41e4 100644 --- a/packages/ui/src/features/updates/update-gate.test.tsx +++ b/packages/ui/src/features/updates/update-gate.test.tsx @@ -1,10 +1,12 @@ import { screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { UpdateState } from '@ipaforge/rpc' import { t } from '@ui/__tests__/test-i18n.ts' import { renderApp } from '@ui/__tests__/test-services.tsx' +import { createFakeEngine } from '@ui/services/engine/fake/fake-engine.ts' +import { createFakeEngineClient } from '@ui/services/engine/fake/fake-engine-client.ts' import { createFixedUpdateSource } from '@ui/services/updates/fixed-update-source.ts' const NEXT = '0.1.0-alpha.99' @@ -56,6 +58,45 @@ describe('UpdateGate', () => { expect(sidebar()).toBeNull() }) + it('on an Apple silicon Mac running the Intel build, says so and opens the Apple silicon download', async () => { + const user = userEvent.setup() + const url = 'https://github.com/IPAForge/ipaforge/releases/latest' + const { links } = await renderWith({ + phase: 'idle', + nativeBuild: { url } + }) + + const dialog = await screen.findByRole('alertdialog', { + name: t('updates.nativeBuild.title') + }) + expect(dialog.textContent).toContain(t('updates.nativeBuild.body')) + expect(sidebar()).not.toBeNull() + await user.click( + screen.getByRole('button', { name: t('updates.nativeBuild.download') }) + ) + expect(links.opened).toEqual([url]) + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()) + }) + + it('asks the Engine nothing while it checks: no devices, no Apple IDs', async () => { + const fake = createFakeEngine({ delayMs: 0, appleDelayMs: 0 }) + const watchDevices = vi.fn(fake.watchDevices) + const listAccounts = vi.fn(fake.listAccounts) + const engine = createFakeEngineClient({ + delayMs: 0, + appleDelayMs: 0, + overrides: { watchDevices, listAccounts } + }) + await renderApp('/install', { + engine, + updates: createFixedUpdateSource({ phase: 'checking' }) + }) + + expect(await screen.findByText(t('updates.checking.title'))).toBeDefined() + expect(watchDevices).not.toHaveBeenCalled() + expect(listAccounts).not.toHaveBeenCalled() + }) + it('after a failed update: tries again, opens the release page, or goes on with this version', async () => { const user = userEvent.setup() const { updates, links } = await renderWith({ diff --git a/packages/ui/src/hooks/queries/query-keys.ts b/packages/ui/src/hooks/queries/query-keys.ts index 2249baa2..c5faa33d 100644 --- a/packages/ui/src/hooks/queries/query-keys.ts +++ b/packages/ui/src/hooks/queries/query-keys.ts @@ -40,6 +40,8 @@ export const queryKeys = { query ? ([...teamKey(query), 'certificates'] as const) : ['idle'], planInstall: (input: RemotePlanInstallInput | undefined) => ['plan', input ?? null] as const, + /** The anisette servers, the choice and SideStore's list's age (Settings). */ + anisette: ['anisette'] as const, /** Pages of the Engine's log buffer for one filter; never cached between visits to Logs. */ logs: (filter: LogFilter) => ['logs', 'lines', filter] as const, logLevel: ['logs', 'level'] as const diff --git a/packages/ui/src/hooks/queries/use-anisette-actions.ts b/packages/ui/src/hooks/queries/use-anisette-actions.ts new file mode 100644 index 00000000..a5c1efe9 --- /dev/null +++ b/packages/ui/src/hooks/queries/use-anisette-actions.ts @@ -0,0 +1,47 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' + +import { queryKeys } from '@ui/hooks/queries/query-keys.ts' +import { useEngine } from '@ui/hooks/use-engine.ts' +import type { + AnisetteChoice, + AnisetteOverview +} from '@ui/services/engine/types.ts' + +type ServerInput = { readonly name: string; readonly address: string } + +/** Changing the anisette servers: each change answers with the servers after it, which replace the cached ones. */ +export const useAnisetteActions = () => { + const engine = useEngine() + const client = useQueryClient() + const onSuccess = (overview: AnisetteOverview) => + client.setQueryData(queryKeys.anisette, overview) + + return { + choose: useMutation({ + mutationFn: (choice: AnisetteChoice) => + engine.chooseAnisetteServer(choice), + onSuccess + }), + add: useMutation({ + mutationFn: (input: ServerInput) => engine.addAnisetteServer(input), + onSuccess + }), + update: useMutation({ + mutationFn: ({ + from, + name, + address + }: ServerInput & { readonly from: string }) => + engine.updateAnisetteServer(from, { name, address }), + onSuccess + }), + remove: useMutation({ + mutationFn: (address: string) => engine.removeAnisetteServer(address), + onSuccess + }), + updateList: useMutation({ + mutationFn: () => engine.updateAnisetteServerList(), + onSuccess + }) + } +} diff --git a/packages/ui/src/hooks/queries/use-anisette-servers.ts b/packages/ui/src/hooks/queries/use-anisette-servers.ts new file mode 100644 index 00000000..713ef6a3 --- /dev/null +++ b/packages/ui/src/hooks/queries/use-anisette-servers.ts @@ -0,0 +1,14 @@ +import { useQuery } from '@tanstack/react-query' + +import { queryKeys } from '@ui/hooks/queries/query-keys.ts' +import { useEngine } from '@ui/hooks/use-engine.ts' + +/** The anisette servers in the order Automatic tries them, the choice, and SideStore's list's age. */ +export const useAnisetteServers = () => { + const engine = useEngine() + + return useQuery({ + queryKey: queryKeys.anisette, + queryFn: () => engine.anisetteServers() + }) +} diff --git a/packages/ui/src/locales/ar.json b/packages/ui/src/locales/ar.json index 83efa2f2..86ec116a 100644 --- a/packages/ui/src/locales/ar.json +++ b/packages/ui/src/locales/ar.json @@ -257,6 +257,73 @@ "system": "النظام ({language})", "hint": "يتبع IPAForge لغة النظام ما لم تختر لغة أخرى هنا.", "draft": "مسودة" + }, + "anisette": { + "title": "خوادم anisette", + "hint": "يحتاج تسجيل الدخول إلى Apple خادم anisette يخبر Apple بالكمبيوتر الذي يسجّل الدخول. يستخدم IPAForge خادمًا يعمل من تلقاء نفسه؛ اختر خادمًا معيّنًا هنا إن أردت، أو أضف خادمك.", + "add": "إضافة خادم", + "loading": "جارٍ تحميل الخوادم…", + "modeLabel": "كيف يختار IPAForge الخادم", + "mode": { + "automatic": "تلقائي", + "chosen": "اختيار خادم" + }, + "modeHint": { + "automatic": "يجرّب الخوادم بهذا الترتيب وينتقل إلى التالي عند فشل أحدها.", + "chosen": "يستخدم {name} دائمًا.", + "none": "اختر الخادم الذي سيستخدمه IPAForge دائمًا." + }, + "noneChosen": "لم يُختر خادم بعد: إلى أن تختار، يختار IPAForge بنفسه.", + "chosenDown": "لا يستجيب {name}. لن يعمل تسجيل الدخول حتى يعود، أو تختار خادمًا آخر، أو تعود إلى الوضع التلقائي.", + "count": "{count, plural, zero {لا خوادم} one {خادم واحد} two {خادمان} few {# خوادم} many {# خادمًا} other {# خادم}}", + "sources": "{custom, plural, =0 {} other {أضفت #، }}{list} من قائمة SideStore، {backup} احتياطيًا ·", + "listUpdated": "حُدّثت قائمة SideStore {ago}", + "listNever": "لم تُجلب قائمة SideStore بعد", + "updateList": "تحديث القائمة", + "updating": "جارٍ التحديث…", + "testAll": "اختبار الكل", + "testing": "جارٍ الاختبار…", + "group": { + "custom": "أضفتها أنت · تُستخدم أولًا", + "list": "من قائمة SideStore", + "backup": "احتياطي · فقط عند تعذّر الوصول إلى قائمة SideStore أو عدم استجابة أي منها" + }, + "tag": { + "custom": "أضفته أنت", + "inUse": "قيد الاستخدام", + "chosen": "مختار" + }, + "position": "يُجرَّب بالترتيب {position}", + "use": "استخدام {name}", + "chooseLabel": "الخادم المستخدم", + "status": { + "untested": "لم يُختبر", + "testing": "جارٍ الاختبار…", + "ok": "يعمل · {ms} م.ث", + "bad": "لا يستجيب" + }, + "test": "اختبار", + "testOne": "اختبار {name}", + "edit": "تعديل {name}", + "remove": "إزالة {name}", + "confirmRemove": "إزالة {name}؟", + "removeYes": "إزالة", + "skipped": "غير مستخدمة من قائمة SideStore: {names} (بلا HTTPS). يمكنك إضافة خادم HTTP بنفسك، مثل خادم على كمبيوترك.", + "dialog": { + "addTitle": "إضافة خادم anisette", + "editTitle": "تعديل الخادم", + "body": "يعمل أي خادم anisette يستخدم البروتوكول المعتاد: خادم عام أو خادم تشغّله بنفسك.", + "name": "الاسم", + "namePlaceholder": "خادمي", + "address": "العنوان", + "addressPlaceholder": "https://anisette.my-server.net", + "addressHint": "https://‎ أو، لخادم تشغّله بنفسك، http://‎", + "nameMissing": "أعطه اسمًا.", + "addressInvalid": "أدخل عنوانًا يبدأ بـ https://‎ أو http://‎.", + "exists": "هذا الخادم موجود في القائمة بالفعل.", + "stillAdd": "ما زال بإمكانك إضافته.", + "save": "حفظ" + } } }, "theme": { @@ -465,6 +532,14 @@ "developer_request_failed": { "title": "فشلت خدمات Apple للمطورين", "body": "فشل طلب إلى خدمات Apple للمطورين. حاول مرة أخرى، وأبلغ عن المشكلة إذا استمرت." + }, + "anisette_server_invalid": { + "title": "لا يمكن استخدام خادم anisette هذا", + "body": "تحقّق من الاسم والعنوان: يبدأ العنوان بـ https://‎ أو http://‎." + }, + "anisette_server_exists": { + "title": "خادم anisette هذا موجود في القائمة بالفعل", + "body": "اختره من القائمة في الإعدادات بدلًا من ذلك." } }, "catalog": { @@ -753,6 +828,10 @@ "open": "فتح", "tryAnyway": { "how": "أبلغت Apple عن عدد سالب من معرّفات التطبيقات المتبقية، وهو خلل معروف لديها: قد يكون العدد الحقيقي أكبر. «حاول على أي حال» يطلب من Apple إنشاءها؛ وإن كان الحد قد بلغ فعلًا فستقول ذلك." + }, + "changeAnisetteServer": { + "how": "افتح الإعدادات، واختبر خوادم anisette، واختر خادمًا يعمل، أو عُد إلى الوضع التلقائي.", + "button": "فتح خوادم anisette" } }, "reportHint": "يفتح بلاغًا جديدًا على GitHub مع ملء التشخيص. لا يُرسل شيء حتى ترسله بنفسك." @@ -934,7 +1013,12 @@ "close": "تم" }, "rememberPassword": "احفظ كلمة السر في سلسلة مفاتيح النظام", - "rememberPasswordHint": "يتيح لـ IPAForge تسجيل الدخول مجددًا بنفسه عند انتهاء الجلسة." + "rememberPasswordHint": "يتيح لـ IPAForge تسجيل الدخول مجددًا بنفسه عند انتهاء الجلسة.", + "resuming": { + "title": "تسجيل الدخول مجددًا", + "body": "جارٍ تسجيل الدخول إلى {appleId} بما حفظه IPAForge…", + "cancel": "إلغاء" + } }, "accounts": { "description": "معرّفات Apple التي يوقّع بها IPAForge التطبيقات. المعرّف المستخدم يظهر في الشريط العلوي.", @@ -1586,6 +1670,13 @@ "body": "ثُبّتت هذه النسخة من {package, select, msi {مثبّت ‎.msi} deb {حزمة ‎.deb} rpm {حزمة ‎.rpm} other {حزمة}} لا يمكنها تحديث نفسها. نزّل الإصدار الجديد وثبّته فوق هذا: تبقى معرّفات Apple والتطبيقات والإعدادات كما هي.", "download": "نزّل {version}", "later": "لاحقًا" + }, + "nativeBuild": { + "title": "هذا إصدار Intel", + "body": "جهاز Mac لديك يعمل بمعالج Apple silicon، لذا تعمل هذه النسخة من IPAForge عبر Rosetta وكل شيء أبطأ. نزّل إصدار Apple silicon وثبّته فوق هذه النسخة؛ تبقى معرّفات Apple والأجهزة والتطبيقات كما هي.", + "file": "IPAForge-…-mac-arm64.dmg", + "later": "لاحقًا", + "download": "تنزيل لـ Apple silicon" } }, "whatsNew": { diff --git a/packages/ui/src/locales/de.json b/packages/ui/src/locales/de.json index 5144892e..1a14aba7 100644 --- a/packages/ui/src/locales/de.json +++ b/packages/ui/src/locales/de.json @@ -257,6 +257,73 @@ "system": "System ({language})", "hint": "IPAForge verwendet die Systemsprache, solange du hier keine andere auswählst.", "draft": "Entwurf" + }, + "anisette": { + "title": "Anisette-Server", + "hint": "Für die Anmeldung bei Apple braucht es einen Anisette-Server, der Apple sagt, welcher Computer sich anmeldet. IPAForge nimmt selbst einen, der funktioniert; wähle hier einen bestimmten Server oder füge deinen eigenen hinzu.", + "add": "Server hinzufügen", + "loading": "Server werden geladen…", + "modeLabel": "Wie IPAForge einen Server wählt", + "mode": { + "automatic": "Automatisch", + "chosen": "Server wählen" + }, + "modeHint": { + "automatic": "Probiert die Server in dieser Reihenfolge und nimmt den nächsten, wenn einer ausfällt.", + "chosen": "Nutzt immer {name}.", + "none": "Wähle den Server, den IPAForge immer nutzen soll." + }, + "noneChosen": "Noch kein Server gewählt: bis du einen wählst, entscheidet IPAForge selbst.", + "chosenDown": "{name} antwortet nicht. Die Anmeldung klappt erst wieder, wenn er zurück ist, du einen anderen Server wählst oder auf Automatisch wechselst.", + "count": "{count, plural, one {# Server} other {# Server}}", + "sources": "{custom, plural, =0 {} other {# von dir hinzugefügt, }}{list} aus der Liste von SideStore, {backup} als Reserve ·", + "listUpdated": "Liste von SideStore aktualisiert {ago}", + "listNever": "Liste von SideStore noch nicht geladen", + "updateList": "Liste aktualisieren", + "updating": "Wird aktualisiert…", + "testAll": "Alle testen", + "testing": "Wird getestet…", + "group": { + "custom": "Von dir hinzugefügt · zuerst genutzt", + "list": "Aus der Liste von SideStore", + "backup": "Reserve · nur wenn die Liste von SideStore nicht erreichbar ist oder keiner davon antwortet" + }, + "tag": { + "custom": "Von dir hinzugefügt", + "inUse": "In Gebrauch", + "chosen": "Gewählt" + }, + "position": "Als Nummer {position} probiert", + "use": "{name} nutzen", + "chooseLabel": "Zu nutzender Server", + "status": { + "untested": "Nicht getestet", + "testing": "Wird getestet…", + "ok": "Funktioniert · {ms} ms", + "bad": "Antwortet nicht" + }, + "test": "Testen", + "testOne": "{name} testen", + "edit": "{name} bearbeiten", + "remove": "{name} entfernen", + "confirmRemove": "{name} entfernen?", + "removeYes": "Entfernen", + "skipped": "Aus der Liste von SideStore nicht genutzt: {names} (kein HTTPS). Einen HTTP-Server kannst du selbst hinzufügen, etwa einen auf deinem eigenen Computer.", + "dialog": { + "addTitle": "Anisette-Server hinzufügen", + "editTitle": "Server bearbeiten", + "body": "Jeder Anisette-Server mit dem üblichen Protokoll funktioniert: ein öffentlicher oder einer, den du selbst betreibst.", + "name": "Name", + "namePlaceholder": "Mein Server", + "address": "Adresse", + "addressPlaceholder": "https://anisette.my-server.net", + "addressHint": "https:// oder, für einen eigenen Server, http://", + "nameMissing": "Gib ihm einen Namen.", + "addressInvalid": "Gib eine Adresse ein, die mit https:// oder http:// beginnt.", + "exists": "Dieser Server ist schon in der Liste.", + "stillAdd": "Du kannst ihn trotzdem hinzufügen.", + "save": "Speichern" + } } }, "theme": { @@ -465,6 +532,14 @@ "developer_request_failed": { "title": "Fehler bei den Entwicklerdiensten von Apple", "body": "Eine Anfrage an die Entwicklerdienste von Apple ist fehlgeschlagen. Versuche es erneut und melde das Problem, wenn es weiter auftritt." + }, + "anisette_server_invalid": { + "title": "Dieser Anisette-Server kann nicht genutzt werden", + "body": "Prüfe Name und Adresse: Die Adresse beginnt mit https:// oder http://." + }, + "anisette_server_exists": { + "title": "Dieser Anisette-Server ist schon in der Liste", + "body": "Wähle ihn stattdessen in den Einstellungen aus der Liste." } }, "catalog": { @@ -753,6 +828,10 @@ "open": "Öffnen", "tryAnyway": { "how": "Apple hat eine negative Zahl freier App-IDs gemeldet – ein bekannter Fehler auf Apples Seite; die echte Zahl kann höher sein. „Trotzdem versuchen“ bittet Apple, sie anzulegen; ist das Limit wirklich erreicht, sagt Apple das." + }, + "changeAnisetteServer": { + "how": "Öffne die Einstellungen, teste die Anisette-Server und wähle einen, der funktioniert, oder wechsle zurück zu Automatisch.", + "button": "Anisette-Server öffnen" } }, "reportHint": "Öffnet ein neues GitHub-Issue mit der Diagnose. Nichts wird gesendet, bevor du es abschickst." @@ -934,7 +1013,12 @@ "close": "Fertig" }, "rememberPassword": "Mein Passwort im Schlüsselbund des Systems speichern", - "rememberPasswordHint": "Damit kann sich IPAForge selbst erneut anmelden, wenn die Sitzung abläuft." + "rememberPasswordHint": "Damit kann sich IPAForge selbst erneut anmelden, wenn die Sitzung abläuft.", + "resuming": { + "title": "Erneut anmelden", + "body": "Anmeldung bei {appleId} mit dem, was IPAForge gespeichert hat…", + "cancel": "Abbrechen" + } }, "accounts": { "description": "Die Apple-IDs, mit denen IPAForge Apps signiert. Die verwendete steht in der oberen Leiste.", @@ -1586,6 +1670,13 @@ "body": "Diese Kopie wurde aus {package, select, msi {einem .msi-Installer} deb {einem .deb-Paket} rpm {einem .rpm-Paket} other {einem Paket}} installiert, das sich nicht selbst aktualisieren kann. Lade die neue Version und installiere sie über diese: Deine Apple-IDs, Apps und Einstellungen bleiben erhalten.", "download": "{version} laden", "later": "Später" + }, + "nativeBuild": { + "title": "Das ist die Intel-Version", + "body": "Dein Mac hat Apple Silicon, daher läuft diese IPAForge-Kopie über Rosetta und alles ist langsamer. Lade die Apple-Silicon-Version und installiere sie über diese; Apple-IDs, Geräte und Apps bleiben erhalten.", + "file": "IPAForge-…-mac-arm64.dmg", + "later": "Später", + "download": "Für Apple Silicon laden" } }, "whatsNew": { diff --git a/packages/ui/src/locales/en.json b/packages/ui/src/locales/en.json index c16f5cb9..4225976d 100644 --- a/packages/ui/src/locales/en.json +++ b/packages/ui/src/locales/en.json @@ -257,6 +257,73 @@ "system": "System ({language})", "hint": "IPAForge follows your system language unless you choose one here.", "draft": "draft" + }, + "anisette": { + "title": "Anisette servers", + "hint": "Signing in to Apple needs an anisette server, which tells Apple which computer is signing in. IPAForge uses one that works, by itself; choose one here if you prefer a particular server, or add your own.", + "add": "Add server", + "loading": "Loading the servers…", + "modeLabel": "How IPAForge picks a server", + "mode": { + "automatic": "Automatic", + "chosen": "Choose a server" + }, + "modeHint": { + "automatic": "Tries the servers in this order and moves on when one fails.", + "chosen": "Always uses {name}.", + "none": "Pick the server IPAForge should always use." + }, + "noneChosen": "No server chosen yet: until you pick one, IPAForge keeps choosing by itself.", + "chosenDown": "{name} isn't responding. Signing in won't work until it's back, or until you choose another server or switch to Automatic.", + "count": "{count, plural, one {# server} other {# servers}}", + "sources": "{custom, plural, =0 {} other {# added by you, }}{list} from SideStore's list, {backup} as a backup ·", + "listUpdated": "SideStore's list updated {ago}", + "listNever": "SideStore's list not fetched yet", + "updateList": "Update list", + "updating": "Updating…", + "testAll": "Test all", + "testing": "Testing…", + "group": { + "custom": "Added by you · used first", + "list": "From SideStore's list", + "backup": "Backup · only when SideStore's list can't be reached or none of it answers" + }, + "tag": { + "custom": "Added by you", + "inUse": "In use", + "chosen": "Chosen" + }, + "position": "Tried as number {position}", + "use": "Use {name}", + "chooseLabel": "Server to use", + "status": { + "untested": "Not tested", + "testing": "Testing…", + "ok": "Working · {ms} ms", + "bad": "Not responding" + }, + "test": "Test", + "testOne": "Test {name}", + "edit": "Edit {name}", + "remove": "Remove {name}", + "confirmRemove": "Remove {name}?", + "removeYes": "Remove", + "skipped": "Not used from SideStore's list: {names} (no HTTPS). You can add a plain-HTTP server yourself, for example one on your own computer.", + "dialog": { + "addTitle": "Add an anisette server", + "editTitle": "Edit server", + "body": "Any anisette server that speaks the usual protocol works: a public one, or one you run yourself.", + "name": "Name", + "namePlaceholder": "My server", + "address": "Address", + "addressPlaceholder": "https://anisette.my-server.net", + "addressHint": "https:// or, for a server you run yourself, http://", + "nameMissing": "Give it a name.", + "addressInvalid": "Enter an address that starts with https:// or http://.", + "exists": "This server is already in the list.", + "stillAdd": "You can still add it.", + "save": "Save" + } } }, "theme": { @@ -465,6 +532,14 @@ "developer_request_failed": { "title": "Apple's developer services failed", "body": "A request to Apple's developer services failed. Try again, and report it if it keeps happening." + }, + "anisette_server_invalid": { + "title": "This anisette server can't be used", + "body": "Check its name and address: the address starts with https:// or http://." + }, + "anisette_server_exists": { + "title": "This anisette server is already in the list", + "body": "Choose it from the list in Settings instead." } }, "catalog": { @@ -753,6 +828,10 @@ "open": "Open", "tryAnyway": { "how": "Apple reported a negative number of App IDs left, which is a known glitch on its side: the real number may be higher. Try anyway asks Apple to create them; if it really is at the limit, it says so." + }, + "changeAnisetteServer": { + "how": "Open Settings, test the anisette servers, and choose one that works, or go back to Automatic.", + "button": "Open anisette servers" } }, "reportHint": "Opens a new GitHub issue with the diagnostics filled in. Nothing is sent until you submit it." @@ -934,7 +1013,12 @@ "close": "Done" }, "rememberPassword": "Save my password in the system keychain", - "rememberPasswordHint": "Lets IPAForge sign in again on its own when the session expires." + "rememberPasswordHint": "Lets IPAForge sign in again on its own when the session expires.", + "resuming": { + "title": "Signing in again", + "body": "Signing in to {appleId} with what IPAForge saved…", + "cancel": "Cancel" + } }, "accounts": { "description": "The Apple IDs IPAForge signs apps with. The one in use is shown in the top bar.", @@ -1586,6 +1670,13 @@ "body": "This copy was installed from {package, select, msi {a .msi installer} deb {a .deb package} rpm {an .rpm package} other {a package}}, which can't update itself. Download the new version and install it over this one: your Apple IDs, apps and settings stay.", "download": "Download {version}", "later": "Later" + }, + "nativeBuild": { + "title": "This is the Intel build", + "body": "Your Mac has Apple silicon, so this copy of IPAForge runs through Rosetta and everything is slower. Download the Apple silicon build and install it over this one; your Apple IDs, devices and apps stay.", + "file": "IPAForge-…-mac-arm64.dmg", + "later": "Later", + "download": "Download for Apple silicon" } }, "whatsNew": { diff --git a/packages/ui/src/locales/ja.json b/packages/ui/src/locales/ja.json index d0401bb3..274ee23d 100644 --- a/packages/ui/src/locales/ja.json +++ b/packages/ui/src/locales/ja.json @@ -257,6 +257,73 @@ "system": "システム({language})", "hint": "ここで言語を選ばない限り、IPAForgeはシステムの言語に従います。", "draft": "下書き" + }, + "anisette": { + "title": "anisette サーバー", + "hint": "Apple へのサインインには anisette サーバーが必要です。どのコンピュータがサインインしているかを Apple に伝えます。IPAForge は動作するサーバーを自動で使います。特定のサーバーを使いたい場合はここで選ぶか、自分のサーバーを追加してください。", + "add": "サーバーを追加", + "loading": "サーバーを読み込んでいます…", + "modeLabel": "IPAForge のサーバーの選び方", + "mode": { + "automatic": "自動", + "chosen": "サーバーを選ぶ" + }, + "modeHint": { + "automatic": "この順番でサーバーを試し、失敗したら次へ進みます。", + "chosen": "常に {name} を使います。", + "none": "IPAForge が常に使うサーバーを選んでください。" + }, + "noneChosen": "まだサーバーが選ばれていません。選ぶまでは IPAForge が自動で選びます。", + "chosenDown": "{name} が応答しません。復旧するか、別のサーバーを選ぶか、自動に戻すまでサインインできません。", + "count": "{count, plural, other {# 台のサーバー}}", + "sources": "{custom, plural, =0 {} other {追加したもの # 台、}}SideStore のリストから {list} 台、予備 {backup} 台 ·", + "listUpdated": "SideStore のリストを{ago}に更新", + "listNever": "SideStore のリストはまだ取得していません", + "updateList": "リストを更新", + "updating": "更新中…", + "testAll": "すべてテスト", + "testing": "テスト中…", + "group": { + "custom": "追加したもの · 最初に使用", + "list": "SideStore のリストから", + "backup": "予備 · SideStore のリストに接続できないか、どれも応答しないときだけ" + }, + "tag": { + "custom": "追加したもの", + "inUse": "使用中", + "chosen": "選択中" + }, + "position": "{position} 番目に試行", + "use": "{name} を使う", + "chooseLabel": "使用するサーバー", + "status": { + "untested": "未テスト", + "testing": "テスト中…", + "ok": "動作中 · {ms} ms", + "bad": "応答なし" + }, + "test": "テスト", + "testOne": "{name} をテスト", + "edit": "{name} を編集", + "remove": "{name} を削除", + "confirmRemove": "{name} を削除しますか?", + "removeYes": "削除", + "skipped": "SideStore のリストから使用しないもの: {names}(HTTPS なし)。自分のコンピュータ上のサーバーなど、HTTP のサーバーは自分で追加できます。", + "dialog": { + "addTitle": "anisette サーバーを追加", + "editTitle": "サーバーを編集", + "body": "通常のプロトコルに対応した anisette サーバーなら使えます。公開サーバーでも、自分で動かしているサーバーでも構いません。", + "name": "名前", + "namePlaceholder": "自分のサーバー", + "address": "アドレス", + "addressPlaceholder": "https://anisette.my-server.net", + "addressHint": "https:// または、自分で動かすサーバーなら http://", + "nameMissing": "名前を付けてください。", + "addressInvalid": "https:// または http:// で始まるアドレスを入力してください。", + "exists": "このサーバーはすでにリストにあります。", + "stillAdd": "それでも追加できます。", + "save": "保存" + } } }, "theme": { @@ -465,6 +532,14 @@ "developer_request_failed": { "title": "Appleのデベロッパサービスでエラーが発生しました", "body": "Appleのデベロッパサービスへのリクエストに失敗しました。もう一度試し、続く場合は問題を報告してください。" + }, + "anisette_server_invalid": { + "title": "この anisette サーバーは使えません", + "body": "名前とアドレスを確認してください。アドレスは https:// または http:// で始まります。" + }, + "anisette_server_exists": { + "title": "この anisette サーバーはすでにリストにあります", + "body": "代わりに設定のリストから選んでください。" } }, "catalog": { @@ -753,6 +828,10 @@ "open": "開く", "tryAnyway": { "how": "Appleが残りのApp ID数を負の値で返しました。これはApple側の既知の不具合で、実際にはもっと残っている可能性があります。「それでも試す」でAppleに作成を依頼します。本当に上限に達している場合はAppleがそう返します。" + }, + "changeAnisetteServer": { + "how": "設定を開いて anisette サーバーをテストし、動作するものを選ぶか、自動に戻してください。", + "button": "anisette サーバーを開く" } }, "reportHint": "診断情報を記入した新しいGitHub Issueを開きます。送信するまで何も送られません。" @@ -934,7 +1013,12 @@ "close": "完了" }, "rememberPassword": "パスワードをシステムのキーチェーンに保存する", - "rememberPasswordHint": "セッションの期限が切れたとき、IPAForgeが自動でサインインし直せます。" + "rememberPasswordHint": "セッションの期限が切れたとき、IPAForgeが自動でサインインし直せます。", + "resuming": { + "title": "もう一度サインイン", + "body": "IPAForge が保存した情報で {appleId} にサインインしています…", + "cancel": "キャンセル" + } }, "accounts": { "description": "IPAForgeがアプリの署名に使うApple ID。使用中のものは上部のバーに表示されます。", @@ -1586,6 +1670,13 @@ "body": "このコピーは自動でアップデートできない{package, select, msi {.msi インストーラー} deb {.deb パッケージ} rpm {.rpm パッケージ} other {パッケージ}}からインストールされています。新しいバージョンをダウンロードして、このバージョンの上からインストールしてください。Apple ID、アプリ、設定はそのまま残ります。", "download": "{version} をダウンロード", "later": "あとで" + }, + "nativeBuild": { + "title": "これは Intel 版です", + "body": "この Mac は Apple シリコンを搭載しているため、この IPAForge は Rosetta 経由で動作し、すべてが遅くなります。Apple シリコン版をダウンロードして上書きインストールしてください。Apple ID、デバイス、App はそのまま残ります。", + "file": "IPAForge-…-mac-arm64.dmg", + "later": "後で", + "download": "Apple シリコン版をダウンロード" } }, "whatsNew": { diff --git a/packages/ui/src/locales/ro.json b/packages/ui/src/locales/ro.json index a0969eae..e816b674 100644 --- a/packages/ui/src/locales/ro.json +++ b/packages/ui/src/locales/ro.json @@ -257,6 +257,73 @@ "system": "Sistem ({language})", "hint": "IPAForge folosește limba sistemului, dacă nu alegi alta aici.", "draft": "ciornă" + }, + "anisette": { + "title": "Servere anisette", + "hint": "Conectarea la Apple are nevoie de un server anisette, care îi spune lui Apple ce computer se conectează. IPAForge folosește singur unul care funcționează; alege aici un anumit server dacă preferi, sau adaugă-l pe al tău.", + "add": "Adaugă server", + "loading": "Se încarcă serverele…", + "modeLabel": "Cum alege IPAForge un server", + "mode": { + "automatic": "Automat", + "chosen": "Alege un server" + }, + "modeHint": { + "automatic": "Încearcă serverele în această ordine și trece la următorul când unul nu merge.", + "chosen": "Folosește mereu {name}.", + "none": "Alege serverul pe care IPAForge îl va folosi mereu." + }, + "noneChosen": "Niciun server ales încă: până alegi unul, IPAForge alege singur.", + "chosenDown": "{name} nu răspunde. Conectarea nu va merge până nu revine, până nu alegi alt server sau până nu treci pe Automat.", + "count": "{count, plural, one {# server} few {# servere} other {# de servere}}", + "sources": "{custom, plural, =0 {} other {# adăugate de tine, }}{list} din lista SideStore, {backup} de rezervă ·", + "listUpdated": "Lista SideStore actualizată {ago}", + "listNever": "Lista SideStore nu a fost descărcată încă", + "updateList": "Actualizează lista", + "updating": "Se actualizează…", + "testAll": "Testează tot", + "testing": "Se testează…", + "group": { + "custom": "Adăugate de tine · folosite primele", + "list": "Din lista SideStore", + "backup": "Rezervă · doar când lista SideStore nu poate fi accesată sau niciunul nu răspunde" + }, + "tag": { + "custom": "Adăugat de tine", + "inUse": "În uz", + "chosen": "Ales" + }, + "position": "Încercat al {position}-lea", + "use": "Folosește {name}", + "chooseLabel": "Serverul folosit", + "status": { + "untested": "Netestat", + "testing": "Se testează…", + "ok": "Funcționează · {ms} ms", + "bad": "Nu răspunde" + }, + "test": "Testează", + "testOne": "Testează {name}", + "edit": "Editează {name}", + "remove": "Elimină {name}", + "confirmRemove": "Elimini {name}?", + "removeYes": "Elimină", + "skipped": "Nefolosite din lista SideStore: {names} (fără HTTPS). Poți adăuga singur un server HTTP, de exemplu unul de pe computerul tău.", + "dialog": { + "addTitle": "Adaugă un server anisette", + "editTitle": "Editează serverul", + "body": "Merge orice server anisette care folosește protocolul obișnuit: unul public sau unul pe care îl rulezi tu.", + "name": "Nume", + "namePlaceholder": "Serverul meu", + "address": "Adresă", + "addressPlaceholder": "https://anisette.my-server.net", + "addressHint": "https:// sau, pentru un server rulat de tine, http://", + "nameMissing": "Dă-i un nume.", + "addressInvalid": "Introdu o adresă care începe cu https:// sau http://.", + "exists": "Acest server este deja în listă.", + "stillAdd": "Îl poți adăuga oricum.", + "save": "Salvează" + } } }, "theme": { @@ -465,6 +532,14 @@ "developer_request_failed": { "title": "Serviciile Apple pentru dezvoltatori au eșuat", "body": "O cerere către serviciile Apple pentru dezvoltatori a eșuat. Încearcă din nou și raportează problema dacă se repetă." + }, + "anisette_server_invalid": { + "title": "Acest server anisette nu poate fi folosit", + "body": "Verifică numele și adresa: adresa începe cu https:// sau http://." + }, + "anisette_server_exists": { + "title": "Acest server anisette este deja în listă", + "body": "Alege-l din listă, în Setări." } }, "catalog": { @@ -753,6 +828,10 @@ "open": "Deschide", "tryAnyway": { "how": "Apple a raportat un număr negativ de App ID-uri rămase, o eroare cunoscută a Apple: numărul real poate fi mai mare. „Încearcă oricum” îi cere Apple să le creeze; dacă limita e chiar atinsă, Apple spune asta." + }, + "changeAnisetteServer": { + "how": "Deschide Setările, testează serverele anisette și alege unul care funcționează, sau revino la Automat.", + "button": "Deschide serverele anisette" } }, "reportHint": "Deschide un tichet nou pe GitHub, cu diagnosticul completat. Nu se trimite nimic până nu îl publici tu." @@ -934,7 +1013,12 @@ "close": "Gata" }, "rememberPassword": "Salvează parola în portcheiul sistemului", - "rememberPasswordHint": "Permite IPAForge să se autentifice singur din nou când expiră sesiunea." + "rememberPasswordHint": "Permite IPAForge să se autentifice singur din nou când expiră sesiunea.", + "resuming": { + "title": "Te conectezi din nou", + "body": "Conectare la {appleId} cu ce a salvat IPAForge…", + "cancel": "Anulează" + } }, "accounts": { "description": "Apple ID-urile cu care IPAForge semnează aplicații. Cel folosit apare în bara de sus.", @@ -1586,6 +1670,13 @@ "body": "Această copie a fost instalată dintr-{package, select, msi {un installer .msi} deb {un pachet .deb} rpm {un pachet .rpm} other {un pachet}}, care nu se poate actualiza singur. Descarcă versiunea nouă și instaleaz-o peste aceasta: ID-urile Apple, aplicațiile și setările rămân.", "download": "Descarcă {version}", "later": "Mai târziu" + }, + "nativeBuild": { + "title": "Aceasta este versiunea pentru Intel", + "body": "Mac-ul tău are Apple silicon, așa că această copie IPAForge rulează prin Rosetta și totul merge mai încet. Descarcă versiunea pentru Apple silicon și instaleaz-o peste aceasta; ID-urile Apple, dispozitivele și aplicațiile rămân.", + "file": "IPAForge-…-mac-arm64.dmg", + "later": "Mai târziu", + "download": "Descarcă pentru Apple silicon" } }, "whatsNew": { diff --git a/packages/ui/src/locales/ru.json b/packages/ui/src/locales/ru.json index ed7a70c2..55d1c534 100644 --- a/packages/ui/src/locales/ru.json +++ b/packages/ui/src/locales/ru.json @@ -257,6 +257,73 @@ "system": "Системный ({language})", "hint": "IPAForge использует язык системы, если вы не выберете другой здесь.", "draft": "черновик" + }, + "anisette": { + "title": "Серверы anisette", + "hint": "Для входа в Apple нужен сервер anisette: он сообщает Apple, какой компьютер входит. IPAForge сам выбирает работающий; здесь можно выбрать конкретный сервер или добавить свой.", + "add": "Добавить сервер", + "loading": "Загрузка серверов…", + "modeLabel": "Как IPAForge выбирает сервер", + "mode": { + "automatic": "Автоматически", + "chosen": "Выбрать сервер" + }, + "modeHint": { + "automatic": "Пробует серверы в этом порядке и переходит к следующему, если один не работает.", + "chosen": "Всегда использует {name}.", + "none": "Выберите сервер, который IPAForge будет использовать всегда." + }, + "noneChosen": "Сервер ещё не выбран: пока вы не выберете, IPAForge выбирает сам.", + "chosenDown": "{name} не отвечает. Вход не будет работать, пока сервер не вернётся, пока вы не выберете другой или не включите «Автоматически».", + "count": "{count, plural, one {# сервер} few {# сервера} many {# серверов} other {# сервера}}", + "sources": "{custom, plural, =0 {} other {добавлено вами: #, }}из списка SideStore: {list}, резервных: {backup} ·", + "listUpdated": "Список SideStore обновлён {ago}", + "listNever": "Список SideStore ещё не загружен", + "updateList": "Обновить список", + "updating": "Обновление…", + "testAll": "Проверить все", + "testing": "Проверка…", + "group": { + "custom": "Добавлены вами · используются первыми", + "list": "Из списка SideStore", + "backup": "Резерв · только если список SideStore недоступен или ни один из него не отвечает" + }, + "tag": { + "custom": "Добавлен вами", + "inUse": "Используется", + "chosen": "Выбран" + }, + "position": "Проверяется {position}-м", + "use": "Использовать {name}", + "chooseLabel": "Используемый сервер", + "status": { + "untested": "Не проверен", + "testing": "Проверка…", + "ok": "Работает · {ms} мс", + "bad": "Не отвечает" + }, + "test": "Проверить", + "testOne": "Проверить {name}", + "edit": "Изменить {name}", + "remove": "Удалить {name}", + "confirmRemove": "Удалить {name}?", + "removeYes": "Удалить", + "skipped": "Не используются из списка SideStore: {names} (нет HTTPS). Сервер с HTTP можно добавить самостоятельно, например запущенный на вашем компьютере.", + "dialog": { + "addTitle": "Добавить сервер anisette", + "editTitle": "Изменить сервер", + "body": "Подойдёт любой сервер anisette с обычным протоколом: публичный или ваш собственный.", + "name": "Название", + "namePlaceholder": "Мой сервер", + "address": "Адрес", + "addressPlaceholder": "https://anisette.my-server.net", + "addressHint": "https:// или, для своего сервера, http://", + "nameMissing": "Дайте ему название.", + "addressInvalid": "Введите адрес, начинающийся с https:// или http://.", + "exists": "Этот сервер уже есть в списке.", + "stillAdd": "Его всё равно можно добавить.", + "save": "Сохранить" + } } }, "theme": { @@ -465,6 +532,14 @@ "developer_request_failed": { "title": "Сбой служб Apple для разработчиков", "body": "Не удалось выполнить запрос к службам Apple для разработчиков. Повторите попытку и сообщите о проблеме, если она повторяется." + }, + "anisette_server_invalid": { + "title": "Этот сервер anisette нельзя использовать", + "body": "Проверьте название и адрес: адрес начинается с https:// или http://." + }, + "anisette_server_exists": { + "title": "Этот сервер anisette уже есть в списке", + "body": "Выберите его из списка в настройках." } }, "catalog": { @@ -753,6 +828,10 @@ "open": "Открыть", "tryAnyway": { "how": "Apple сообщила отрицательное число оставшихся App ID — это известный сбой на стороне Apple; на самом деле их может быть больше. «Всё равно попробовать» попросит Apple создать их; если лимит действительно исчерпан, Apple так и скажет." + }, + "changeAnisetteServer": { + "how": "Откройте настройки, проверьте серверы anisette и выберите работающий или вернитесь к «Автоматически».", + "button": "Открыть серверы anisette" } }, "reportHint": "Открывает новый issue на GitHub с заполненной диагностикой. Ничего не отправляется, пока вы его не отправите." @@ -934,7 +1013,12 @@ "close": "Готово" }, "rememberPassword": "Сохранить пароль в системной связке ключей", - "rememberPasswordHint": "IPAForge сможет сам войти снова, когда сеанс истечёт." + "rememberPasswordHint": "IPAForge сможет сам войти снова, когда сеанс истечёт.", + "resuming": { + "title": "Повторный вход", + "body": "Вход в {appleId} с тем, что сохранил IPAForge…", + "cancel": "Отмена" + } }, "accounts": { "description": "Apple ID, которыми IPAForge подписывает приложения. Используемый показан на верхней панели.", @@ -1586,6 +1670,13 @@ "body": "Эта копия установлена из {package, select, msi {установщика .msi} deb {пакета .deb} rpm {пакета .rpm} other {пакета}}, который не умеет обновляться сам. Скачайте новую версию и установите её поверх этой: Apple ID, приложения и настройки сохранятся.", "download": "Скачать {version}", "later": "Позже" + }, + "nativeBuild": { + "title": "Это версия для Intel", + "body": "В вашем Mac процессор Apple silicon, поэтому эта копия IPAForge работает через Rosetta и всё медленнее. Скачайте версию для Apple silicon и установите её поверх этой; Apple ID, устройства и приложения сохранятся.", + "file": "IPAForge-…-mac-arm64.dmg", + "later": "Позже", + "download": "Скачать для Apple silicon" } }, "whatsNew": { diff --git a/packages/ui/src/router.tsx b/packages/ui/src/router.tsx index 616d4707..86370c67 100644 --- a/packages/ui/src/router.tsx +++ b/packages/ui/src/router.tsx @@ -8,6 +8,7 @@ import { import type { ComponentType } from 'react' import { compact } from '@ipaforge/kernel' +import { DeviceFeed } from '@ui/components/device-feed.tsx' import { AppShell } from '@ui/components/shell/app-shell.tsx' import { AccountsPage } from '@ui/features/accounts/accounts-page.tsx' import { AppsPage } from '@ui/features/apps/apps-page.tsx' @@ -39,6 +40,8 @@ const sectionPages = { const rootRoute = createRootRoute({ component: () => ( + {/* Behind the gate: on launch only the update check runs, then the devices, accounts and the rest. */} + diff --git a/packages/ui/src/services/engine/fake/fake-anisette.ts b/packages/ui/src/services/engine/fake/fake-anisette.ts new file mode 100644 index 00000000..ffa0d75c --- /dev/null +++ b/packages/ui/src/services/engine/fake/fake-anisette.ts @@ -0,0 +1,142 @@ +// Anisette servers for the fake Engine: SideStore's list as it looks today (one plain-HTTP entry left out), the +// built-in backup it lacks, and servers added by hand. Addresses with "down" in them, and two of the list's, don't +// answer a test, so every status can be seen; the others answer in a time worked out from the address. +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' +import type { Engine } from '@ipaforge/rpc' +import type { + AnisetteChoice, + AnisetteOverview, + AnisetteServerEntry +} from '@ui/services/engine/types.ts' + +const LIST: AnisetteServerEntry[] = [ + ['SideStore', 'https://ani.sidestore.io'], + ['SideStore (.app)', 'https://ani.sidestore.app'], + ['SideStore (.zip)', 'https://ani.sidestore.zip'], + ['SideStore (Windows ADI)', 'https://win.ani.sidestore.io'], + ['jkcoxson', 'https://mac-ani.jkcoxson.com'], + ['nythepegasus', 'https://ani.npeg.us'], + ['WE. Studio', 'https://anisette.wedotstud.io'] +].map(([name = '', address = '']) => ({ name, address, source: 'list' })) + +const BACKUP: AnisetteServerEntry[] = [ + { name: 'StikStore', address: 'https://ani3.stikstore.app', source: 'backup' } +] + +const DOWN = ['https://ani.sidestore.zip', 'https://anisette.wedotstud.io'] + +const LIST_AGE_MS = 12 * 60_000 + +/** A steady answer time per address, between 90 and 610 ms. */ +const latencyOf = (address: string): number => { + let hash = 0 + for (const char of address) hash = (hash * 31 + char.charCodeAt(0)) >>> 0 + + return 90 + (hash % 520) +} + +/** The address without trailing slashes. */ +const trimmed = (address: string): string => { + let end = address.length + while (end > 0 && address[end - 1] === '/') end -= 1 + + return address.slice(0, end) +} + +const key = (address: string) => trimmed(address).toLowerCase() + +type AnisetteQueries = Pick< + Engine, + | 'anisetteServers' + | 'chooseAnisetteServer' + | 'addAnisetteServer' + | 'updateAnisetteServer' + | 'removeAnisetteServer' + | 'testAnisetteServer' + | 'updateAnisetteServerList' +> + +export const createFakeAnisette = ( + wait: () => Promise, + now: () => number = Date.now +): AnisetteQueries => { + let custom: AnisetteServerEntry[] = [] + let choice: AnisetteChoice = { mode: 'automatic' } + let listUpdatedAt = now() - LIST_AGE_MS + + const overview = (): AnisetteOverview => ({ + servers: [...custom, ...LIST, ...BACKUP], + choice, + lastUsed: 'https://ani.sidestore.io', + listUpdatedAt, + skipped: ['Macley'] + }) + const checked = ( + input: { name: string; address: string }, + replacing?: string + ): AnisetteServerEntry => { + const name = input.name.trim() + const address = trimmed(input.address.trim()) + if (!(name && URL.canParse(address) && address.startsWith('http'))) + throw new IPAForgeError(ErrorCode.AnisetteServerInvalid) + const taken = overview().servers.some( + (server) => + key(server.address) === key(address) && + key(server.address) !== key(replacing ?? '') + ) + if (taken) throw new IPAForgeError(ErrorCode.AnisetteServerExists) + return { name, address, source: 'custom' } + } + const isChosen = (address: string) => + choice.mode === 'chosen' && + choice.server !== undefined && + key(choice.server.address) === key(address) + + return { + anisetteServers: async () => overview(), + chooseAnisetteServer: async (next) => { + choice = next + return overview() + }, + addAnisetteServer: async (input) => { + const server = checked(input) + custom = [server, ...custom] + if (choice.mode === 'chosen') + choice = { + mode: 'chosen', + server: { name: server.name, address: server.address } + } + return overview() + }, + updateAnisetteServer: async (address, input) => { + const server = checked(input, address) + if (isChosen(address)) + choice = { + mode: 'chosen', + server: { name: server.name, address: server.address } + } + custom = custom.map((old) => + key(old.address) === key(address) ? server : old + ) + return overview() + }, + removeAnisetteServer: async (address) => { + if (isChosen(address)) choice = { mode: 'chosen' } + custom = custom.filter((old) => key(old.address) !== key(address)) + return overview() + }, + testAnisetteServer: async (address) => { + await wait() + const isDown = address.includes('down') || DOWN.includes(key(address)) + + return isDown + ? { address, ok: false } + : { address, ok: true, latencyMs: latencyOf(address) } + }, + updateAnisetteServerList: async () => { + await wait() + listUpdatedAt = now() + return overview() + } + } +} diff --git a/packages/ui/src/services/engine/fake/fake-engine.ts b/packages/ui/src/services/engine/fake/fake-engine.ts index 66d2cf63..01b9cdd6 100644 --- a/packages/ui/src/services/engine/fake/fake-engine.ts +++ b/packages/ui/src/services/engine/fake/fake-engine.ts @@ -11,6 +11,7 @@ import { type RunHandle, StepLabel } from '@ipaforge/rpc' +import { createFakeAnisette } from '@ui/services/engine/fake/fake-anisette.ts' import { fakeAppFor, fakePlanFor } from '@ui/services/engine/fake/fake-apps.ts' import { fakeAppsSteps } from '@ui/services/engine/fake/fake-apps-steps.ts' import { @@ -115,8 +116,9 @@ const signInRun = ( world: FakeWorld, { appleId, + accountId, rememberPassword - }: { appleId: string; rememberPassword?: boolean }, + }: { appleId: string; accountId?: string; rememberPassword?: boolean }, options: CommandOptions | undefined ) => startScriptedRun({ @@ -126,7 +128,12 @@ const signInRun = ( stepId: 'sign-in', labelKey: StepLabel.signIn, run: async (_state, context) => { - const password = await askPassword(context, appleId) + // Signing a saved account in again uses its saved password; only the code is asked. + const saved = + accountId !== undefined && + (world.savedPasswords.has(accountId) || + world.codeNeeded.has(accountId)) + const password = saved ? 'saved' : await askPassword(context, appleId) // Apple checks the password. await world.appleAnswer() if (password.length === 0 || world.scenario === 'wrong-password') @@ -134,7 +141,8 @@ const signInRun = ( // Apple skips the second factor for a computer it already knows. if (world.scenario !== 'sign-in-no-2fa') await completeTwoFactor(context, world.appleAnswer) - if (rememberPassword) world.savedPasswords.add(appleId) + if (rememberPassword || saved) world.savedPasswords.add(appleId) + world.codeNeeded.delete(appleId) return { account: saveAccount(world, appleId) } } } @@ -237,6 +245,9 @@ export const createFakeEngine = ({ scenario, () => new Promise((resolve) => setTimeout(resolve, delayMs)) ), + ...createFakeAnisette( + () => new Promise((resolve) => setTimeout(resolve, delayMs)) + ), listAccounts: async () => world.accounts, canSaveAccounts: async () => world.scenario !== 'no-keychain', signOut: async (accountId) => forgetAccount(world, accountId), diff --git a/packages/ui/src/services/engine/fake/fake-scenarios.ts b/packages/ui/src/services/engine/fake/fake-scenarios.ts index 5ceb5b65..b3d293e3 100644 --- a/packages/ui/src/services/engine/fake/fake-scenarios.ts +++ b/packages/ui/src/services/engine/fake/fake-scenarios.ts @@ -11,6 +11,7 @@ export const fakeScenarioIds = [ 'hot-plug', 'devices', 'accounts', + 'code-needed', 'no-accounts', 'sign-in-no-2fa', 'no-keychain', diff --git a/packages/ui/src/services/engine/fake/fake-world.ts b/packages/ui/src/services/engine/fake/fake-world.ts index 4a3819f6..5c55c414 100644 --- a/packages/ui/src/services/engine/fake/fake-world.ts +++ b/packages/ui/src/services/engine/fake/fake-world.ts @@ -24,6 +24,8 @@ export type FakeWorld = { readonly failed: Set /** Accounts whose password was saved at sign-in: an expired session is renewed with it, without asking. */ readonly savedPasswords: Set + /** Accounts with a saved password that Apple wants a code for: signing in again asks only for the code. */ + readonly codeNeeded: Set } /** `studio@` as Apple blocked it on the fake iPhone. */ @@ -38,13 +40,13 @@ const bannedOnIphone = (account: Account): Account => /** * The saved Apple IDs: one with a single team and one with two (`studio@`). The `accounts` scenario adds one * whose session expired and has Apple block `studio@` on the fake iPhone (`devices` blocks it too); - * `no-accounts` starts with none. + * `code-needed` has the same accounts, the expired one with a saved password; `no-accounts` starts with none. */ const accountsFor = (scenario: FakeScenarioId): Account[] => { if (scenario === 'no-accounts') return [] const accounts = fakeAccounts() if (scenario === 'devices') return accounts.map(bannedOnIphone) - if (scenario !== 'accounts') return accounts + if (scenario !== 'accounts' && scenario !== 'code-needed') return accounts return [...accounts.map(bannedOnIphone), EXPIRED_ACCOUNT] } @@ -80,7 +82,8 @@ export const createFakeWorld = ( .map((account) => account.id) ), failed: new Set(), - savedPasswords: new Set() + savedPasswords: new Set(), + codeNeeded: new Set(scenario === 'code-needed' ? [EXPIRED_ACCOUNT.id] : []) } } diff --git a/packages/ui/src/services/engine/types.ts b/packages/ui/src/services/engine/types.ts index 74df7f93..cc5bda7f 100644 --- a/packages/ui/src/services/engine/types.ts +++ b/packages/ui/src/services/engine/types.ts @@ -25,6 +25,10 @@ export type SourceApp = SourceApps['apps'][number] export type SourceAppVersion = SourceApp['versions'][number] export type SourcePreview = Resolved<'checkSource'> export type InstalledApp = Resolved<'installedApps'>[number] +export type AnisetteOverview = Resolved<'anisetteServers'> +export type AnisetteServerEntry = AnisetteOverview['servers'][number] +export type AnisetteChoice = AnisetteOverview['choice'] +export type AnisetteServerTest = Resolved<'testAnisetteServer'> /** A catalog app's latest release on one channel. */ export type CatalogRelease = Resolved<'catalogReleases'>[number] diff --git a/packages/ui/src/services/updates/fake-updates.ts b/packages/ui/src/services/updates/fake-updates.ts index 9f5f1b3f..15b5ee6f 100644 --- a/packages/ui/src/services/updates/fake-updates.ts +++ b/packages/ui/src/services/updates/fake-updates.ts @@ -28,6 +28,11 @@ const sampleStates: Readonly> = { packageType: 'msi', fileName: `IPAForge-${NEXT}-win-x64.msi`, url: RELEASE + }, + // The Intel build running under Rosetta on an Apple silicon Mac. + rosetta: { + phase: 'idle', + nativeBuild: { url: 'https://github.com/IPAForge/ipaforge/releases/latest' } } }