From 3330e133463cd70426821038dd7ecd0bf31e1597 Mon Sep 17 00:00:00 2001 From: Dan Motpan <24751897+SirReaDy@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:35:30 +0300 Subject: [PATCH] 10c: save signed .ipa instead of installing Each app on Preload can be ticked Save signed .ipa instead: it's signed for the team like an install and saved in a folder on the computer, not installed. Ticked apps say so on their row and take no free-app slot; the button counts the apps to install, says what installs and what's saved, or reads Sign and save when every app is ticked. In the same run the others install as before, and each saved app's step says where its file went. - Install first asks for the folder in the host's dialog; cancelling starts nothing. The RPC server keeps the path and gives the page an id for it; installApps names the folder by that id, and any other id is refused, so a run only writes where the user chose. - A saved IPA never carries the signing certificate's private key, is always compressed, and gets no pairing file. - Desktop: a file already in the folder is never replaced ("App (2).ipa"), and an interrupted save leaves nothing behind. - The desktop dialogs show no English of their own: the folder dialog keeps the system's button text, and the IPA file type is named "IPA". Engine: installApps save { folder, apps }, the save-N step and its saved detail, the SignedIpaFolder port. RPC: choose-save-folder. Strings in six languages, tests at every layer, a Preload screen with an app to save in the browser checks, docs and roadmap (10c; .p12 import and export is 10d). --- AGENTS.md | 1 + README.md | 2 +- .../adapters/file-signed-ipa-folder.test.ts | 74 +++++++++++++++++++ .../main/adapters/file-signed-ipa-folder.ts | 73 ++++++++++++++++++ apps/desktop/src/main/engine.ts | 3 + apps/desktop/src/main/index.ts | 11 +++ apps/desktop/src/main/rpc/choose-ipas.test.ts | 2 +- apps/desktop/src/main/rpc/choose-ipas.ts | 3 +- .../src/main/rpc/choose-save-folder.ts | 15 ++++ apps/desktop/src/main/rpc/serve-engine.ts | 4 +- apps/desktop/src/main/rpc/types.ts | 19 ++++- docs/design/roadmap.md | 4 +- docs/install-flows.md | 3 + docs/roadmap.md | 2 +- docs/rpc.md | 3 + docs/ui.md | 2 + packages/installer/src/__tests__/harness.ts | 17 ++++- packages/installer/src/deps.ts | 3 + packages/installer/src/domain/labels.ts | 2 + .../src/domain/ports/signed-ipa-folder.ts | 14 ++++ packages/installer/src/domain/step-weights.ts | 1 + packages/installer/src/domain/types.ts | 2 + packages/installer/src/flows/app-steps.ts | 15 ++++ .../installer/src/flows/install-apps.test.ts | 24 ++++++ packages/installer/src/flows/install-apps.ts | 21 +++++- packages/installer/src/index.ts | 1 + packages/installer/src/pipeline/types.ts | 2 + packages/installer/src/steps/save.test.ts | 17 +++++ packages/installer/src/steps/save.ts | 60 +++++++++++++++ packages/installer/src/steps/sign.ts | 22 ++++-- packages/installer/src/types.ts | 3 + packages/rpc/src/application/client.ts | 7 +- packages/rpc/src/application/server.ts | 8 +- .../rpc/src/application/server/commands.ts | 15 +++- packages/rpc/src/application/server/inputs.ts | 25 ++++++- .../src/application/server/save-folders.ts | 42 +++++++++++ packages/rpc/src/application/types.ts | 3 + .../src/domain/ports/choose-save-folder.ts | 6 ++ packages/rpc/src/domain/protocol/inputs.ts | 9 ++- packages/rpc/src/domain/protocol/messages.ts | 1 + packages/rpc/src/domain/protocol/requests.ts | 4 +- packages/rpc/src/domain/types.ts | 8 ++ packages/rpc/src/index.ts | 2 + packages/rpc/src/rpc.test.ts | 43 ++++++++++- packages/ui/src/__tests__/screen-table.ts | 8 +- packages/ui/src/__tests__/screens.ts | 16 ++++ .../install/run/utils/step-report-texts.ts | 2 + .../preload/home/components/install-chips.tsx | 32 ++++++++ .../home/components/preload-footer.tsx | 15 +++- .../preload/home/components/preload-list.tsx | 10 ++- .../preload/home/components/preload-row.tsx | 14 +++- .../preload/home/components/row-chips.tsx | 20 ++--- .../home/components/save-ipa-checkbox.tsx | 35 +++++++++ .../features/preload/home/preload-home.tsx | 26 +++++-- .../preload/home/utils/preload-totals.ts | 9 ++- .../preload/home/utils/run-apps-of.ts | 3 +- .../features/preload/preload-flow.test.tsx | 53 +++++++++++++ packages/ui/src/locales/ar.json | 15 +++- packages/ui/src/locales/de.json | 15 +++- packages/ui/src/locales/en.json | 15 +++- packages/ui/src/locales/ja.json | 15 +++- packages/ui/src/locales/ro.json | 15 +++- packages/ui/src/locales/ru.json | 15 +++- .../services/engine/fake/fake-apps-steps.ts | 40 +++++++++- .../engine/fake/fake-engine-client.ts | 4 +- .../src/services/engine/fake/fake-engine.ts | 7 +- .../services/engine/fake/fake-resolve-ipa.ts | 3 + packages/ui/src/state/active-run/types.ts | 2 + .../ui/src/state/preload/preload-store.ts | 2 + packages/ui/src/state/preload/types.ts | 4 + .../ui/src/website-screens.browser.test.tsx | 1 + 71 files changed, 906 insertions(+), 88 deletions(-) create mode 100644 apps/desktop/src/main/adapters/file-signed-ipa-folder.test.ts create mode 100644 apps/desktop/src/main/adapters/file-signed-ipa-folder.ts create mode 100644 apps/desktop/src/main/rpc/choose-save-folder.ts create mode 100644 packages/installer/src/domain/ports/signed-ipa-folder.ts create mode 100644 packages/installer/src/steps/save.test.ts create mode 100644 packages/installer/src/steps/save.ts create mode 100644 packages/rpc/src/application/server/save-folders.ts create mode 100644 packages/rpc/src/domain/ports/choose-save-folder.ts create mode 100644 packages/ui/src/features/preload/home/components/install-chips.tsx create mode 100644 packages/ui/src/features/preload/home/components/save-ipa-checkbox.tsx diff --git a/AGENTS.md b/AGENTS.md index 4f344885..d0281f2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,6 +64,7 @@ ipaforge/ | `apps/desktop/src/main/rpc/serve-engine.ts` | Serves the Engine to the window: a fresh `MessageChannelMain` per page load, `createRpcServer` on one end, the other posted to the page | | `apps/desktop/src/preload/forward-port.ts` | The preload's main job: forward the rpc and update ports to the page (`expose-file-paths.ts` adds its one function, a dropped file's path) | | `apps/desktop/src/main/rpc/choose-ipas.ts` | The IPA file dialog behind "Choose files…" on the Preload page, in the main process | +| `apps/desktop/src/main/rpc/choose-save-folder.ts` | The folder dialog behind Save signed .ipa instead (the RPC server keeps the path; the page gets an id) | | `apps/desktop/src/renderer/engine-port.ts` | Renderer: receives the ports and wraps each in a `Transport` for `createEngineClient` and `createUpdateClient` | | `apps/desktop/src/renderer/main.tsx` | Electron renderer: connects the `EngineClient` and the update client, then mounts `@ipaforge/ui` with the browser services and a hash history | | `apps/desktop/electron-builder.yml` | Installers (DMG and zip, NSIS and MSI, AppImage, deb, rpm) and the update metadata: `pnpm --filter @ipaforge/desktop dist` | diff --git a/README.md b/README.md index 7361d776..7324208b 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Sideloading tools tend to fail in a few recurring ways. IPAForge is designed aro 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). -New: the **Developer Portal** page, with your team's certificates (and the apps each one signs), App IDs, the profiles on your device, app groups and registered devices, and the iOS 17+ remote pairing file for SideStore. Pairing files per app: place, remove or give your own apps one, in one dialog. Coming next: `.p12` import and export, saving signed `.ipa` files, and guided onboarding. Installing over Wi-Fi to a device paired before already works. +New: the **Developer Portal** page, with your team's certificates (and the apps each one signs), App IDs, the profiles on your device, app groups and registered devices, and the iOS 17+ remote pairing file for SideStore. Pairing files per app: place, remove or give your own apps one, in one dialog. Save signed `.ipa` files instead of installing them. Coming next: `.p12` import and export, and guided onboarding. Installing over Wi-Fi to a device paired before already works. ## Requirements diff --git a/apps/desktop/src/main/adapters/file-signed-ipa-folder.test.ts b/apps/desktop/src/main/adapters/file-signed-ipa-folder.test.ts new file mode 100644 index 00000000..0cba7c84 --- /dev/null +++ b/apps/desktop/src/main/adapters/file-signed-ipa-folder.test.ts @@ -0,0 +1,74 @@ +import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, describe, expect, it } from 'vitest' + +import { createFileSignedIpaFolder } from '@desktop/main/adapters/file-signed-ipa-folder.ts' +import { utf8Encode } from '@ipaforge/kernel' + +const dirs: string[] = [] + +afterEach(async () => { + for (const dir of dirs.splice(0)) + await rm(dir, { recursive: true, force: true }) +}) + +const folder = async () => { + const dir = await mkdtemp(join(tmpdir(), 'ipaforge-signed-')) + + dirs.push(dir) + + return dir +} + +const streamOf = (text: string) => + new ReadableStream({ + start(controller) { + controller.enqueue(utf8Encode(text)) + controller.close() + } + }) + +const failing = () => + new ReadableStream({ + pull(controller) { + controller.error(new Error('signing stopped')) + } + }) + +describe('saving signed IPAs to a folder', () => { + it('writes the app under its name, and never replaces one already there', async () => { + const dir = await folder() + const output = createFileSignedIpaFolder() + + const first = await output.save(dir, 'App 1.0.ipa', streamOf('one')) + const second = await output.save(dir, 'App 1.0.ipa', streamOf('two')) + + expect(first).toBe(join(dir, 'App 1.0.ipa')) + expect(second).toBe(join(dir, 'App 1.0 (2).ipa')) + expect(await readFile(first, 'utf8')).toBe('one') + expect(await readFile(second, 'utf8')).toBe('two') + }) + + it('keeps a name with folders in it inside the folder', async () => { + const dir = await folder() + + const path = await createFileSignedIpaFolder().save( + dir, + '../../escape.ipa', + streamOf('x') + ) + + expect(path).toBe(join(dir, 'escape.ipa')) + }) + + it('leaves nothing behind when the signed app fails to arrive', async () => { + const dir = await folder() + + await expect( + createFileSignedIpaFolder().save(dir, 'App.ipa', failing()) + ).rejects.toThrow('signing stopped') + expect(await readdir(dir)).toEqual([]) + }) +}) diff --git a/apps/desktop/src/main/adapters/file-signed-ipa-folder.ts b/apps/desktop/src/main/adapters/file-signed-ipa-folder.ts new file mode 100644 index 00000000..39080091 --- /dev/null +++ b/apps/desktop/src/main/adapters/file-signed-ipa-folder.ts @@ -0,0 +1,73 @@ +// SignedIpaFolder on disk: Save signed .ipa instead writes into the folder the user picked. A file already there is +// never replaced: "App.ipa" becomes "App (2).ipa". It's written under a temporary name and renamed once complete, +// so an interrupted save leaves no half-written app. +import { open, rename, rm } from 'node:fs/promises' +import { basename, extname, join } from 'node:path' + +import type { SignedIpaFolder } from '@ipaforge/installer' + +const PARTIAL = '.part' +const MAX_TRIES = 100 + +/** The name as given, or with " (2)", " (3)"… before its extension. */ +const numbered = (name: string, count: number): string => { + if (count === 1) return name + const extension = extname(name) + + return `${basename(name, extension)} (${count})${extension}` +} + +/** Creates `path` only if it doesn't exist yet (the name stays taken while it's written). */ +const claim = async (path: string): Promise => { + try { + await (await open(path, 'wx')).close() + return true + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false + throw error + } +} + +const writeTo = async ( + path: string, + stream: ReadableStream +): Promise => { + const file = await open(path, 'w') + const reader = stream.getReader() + + try { + for (;;) { + const { done, value } = await reader.read() + + if (done) return + await file.write(value) + } + } finally { + reader.releaseLock() + await file.close() + } +} + +export const createFileSignedIpaFolder = (): SignedIpaFolder => ({ + save: async (folder, name, stream) => { + // Only a plain name is ever joined to the folder: nothing can climb out of it. + const safe = basename(name) + + for (let count = 1; count <= MAX_TRIES; count++) { + const path = join(folder, numbered(safe, count)) + + if (!(await claim(path))) continue + const partial = `${path}${PARTIAL}` + try { + await writeTo(partial, stream) + await rename(partial, path) + return path + } catch (error) { + await rm(partial, { force: true }) + await rm(path, { force: true }) + throw error + } + } + throw new Error(`no free name for ${safe} in ${folder}`) + } +}) diff --git a/apps/desktop/src/main/engine.ts b/apps/desktop/src/main/engine.ts index 0d7bde43..43e65302 100644 --- a/apps/desktop/src/main/engine.ts +++ b/apps/desktop/src/main/engine.ts @@ -5,6 +5,7 @@ import { createFileDownloadStore } from '@desktop/main/adapters/file-download-st import { createFileKeptIpaStore } from '@desktop/main/adapters/file-kept-ipa-store.ts' import { createFileScratchStore } from '@desktop/main/adapters/file-scratch-store.ts' import { createFileSecretStore } from '@desktop/main/adapters/file-secret-store.ts' +import { createFileSignedIpaFolder } from '@desktop/main/adapters/file-signed-ipa-folder.ts' import { createNodeHttpClient } from '@desktop/main/adapters/http-client.ts' import { createNodeUsbmuxTransport } from '@desktop/main/adapters/usbmux-transport.ts' import { createWebSocketFactory } from '@desktop/main/adapters/web-socket.ts' @@ -54,6 +55,8 @@ export const createDesktopEngine = ({ // What was installed on each device (not secret), and each app's original IPA, for Refresh. installed: createFileSecretStore(join(dataDir, 'installed.json')), kept: createFileKeptIpaStore(join(dataDir, 'kept')), + // Save signed .ipa instead: into the folder the user picked in the dialog. + signedIpaFolder: createFileSignedIpaFolder(), logger }) } diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index d66a43c6..e9e6aca9 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -26,6 +26,7 @@ import { createNodeHttpClient } from '@desktop/main/adapters/http-client.ts' import { createDesktopEngine } from '@desktop/main/engine.ts' import { createMainLogging, type MainLogging } from '@desktop/main/logger.ts' import { createIpaChooser } from '@desktop/main/rpc/choose-ipas.ts' +import { createSaveFolderChooser } from '@desktop/main/rpc/choose-save-folder.ts' import { createIpaResolver } from '@desktop/main/rpc/resolve-ipa.ts' import { serveEngine } from '@desktop/main/rpc/serve-engine.ts' import { createDesktopSecrets } from '@desktop/main/secrets.ts' @@ -79,6 +80,16 @@ const createEngineConnector = ({ logger, logs }: MainLogging) => { : dialog.showOpenDialog(settings) } }), + chooseSaveFolder: createSaveFolderChooser({ + showOpenDialog: (options) => { + const window = BrowserWindow.fromWebContents(contents) + const settings = { properties: [...options.properties] } + + return window + ? dialog.showOpenDialog(window, settings) + : dialog.showOpenDialog(settings) + } + }), logger, createChannel: () => new MessageChannelMain() }) diff --git a/apps/desktop/src/main/rpc/choose-ipas.test.ts b/apps/desktop/src/main/rpc/choose-ipas.test.ts index 828c2030..6359cc34 100644 --- a/apps/desktop/src/main/rpc/choose-ipas.test.ts +++ b/apps/desktop/src/main/rpc/choose-ipas.test.ts @@ -21,7 +21,7 @@ describe('createIpaChooser', () => { ]) expect(showOpenDialog).toHaveBeenCalledWith({ properties: ['openFile', 'multiSelections'], - filters: [{ name: 'iOS apps', extensions: ['ipa'] }] + filters: [{ name: 'IPA', extensions: ['ipa'] }] }) }) diff --git a/apps/desktop/src/main/rpc/choose-ipas.ts b/apps/desktop/src/main/rpc/choose-ipas.ts index ca005a0e..d8f2e079 100644 --- a/apps/desktop/src/main/rpc/choose-ipas.ts +++ b/apps/desktop/src/main/rpc/choose-ipas.ts @@ -6,7 +6,8 @@ import { basename } from 'node:path' import type { ChooseIpasDeps } from '@desktop/main/rpc/types.ts' import type { ChooseIpas } from '@ipaforge/rpc' -const IPA_FILTER = { name: 'iOS apps', extensions: ['ipa'] } +// The file type's name is the same in every language: this process doesn't know the user's. +const IPA_FILTER = { name: 'IPA', extensions: ['ipa'] } export const createIpaChooser = ({ showOpenDialog }: ChooseIpasDeps): ChooseIpas => diff --git a/apps/desktop/src/main/rpc/choose-save-folder.ts b/apps/desktop/src/main/rpc/choose-save-folder.ts new file mode 100644 index 00000000..1e0fa5c3 --- /dev/null +++ b/apps/desktop/src/main/rpc/choose-save-folder.ts @@ -0,0 +1,15 @@ +// The folder dialog behind Save signed .ipa instead on the Preload page. It runs here, in the main process: the +// window is sandboxed and never sees the file system; the RPC server keeps the path and gives the page an id for it. +import type { ChooseSaveFolderDeps } from '@desktop/main/rpc/types.ts' +import type { ChooseSaveFolder } from '@ipaforge/rpc' + +export const createSaveFolderChooser = + ({ showOpenDialog }: ChooseSaveFolderDeps): ChooseSaveFolder => + async () => { + const { canceled, filePaths } = await showOpenDialog({ + // The system's own button text: it's in the user's language, which this process doesn't know. + properties: ['openDirectory', 'createDirectory'] + }) + + return canceled ? undefined : filePaths[0] + } diff --git a/apps/desktop/src/main/rpc/serve-engine.ts b/apps/desktop/src/main/rpc/serve-engine.ts index 5948f37f..4c395186 100644 --- a/apps/desktop/src/main/rpc/serve-engine.ts +++ b/apps/desktop/src/main/rpc/serve-engine.ts @@ -16,6 +16,7 @@ export const serveEngine =

( resolveIpa, logs, chooseIpas, + chooseSaveFolder, logger, createChannel }: ServeEngineDeps

@@ -31,7 +32,8 @@ export const serveEngine =

( resolveIpa, logger, ...(logs ? { logs } : {}), - ...(chooseIpas ? { chooseIpas } : {}) + ...(chooseIpas ? { chooseIpas } : {}), + ...(chooseSaveFolder ? { chooseSaveFolder } : {}) }) contents.postMessage(RPC_PORT_CHANNEL, null, [port2]) logger.info('engine connected to the renderer') diff --git a/apps/desktop/src/main/rpc/types.ts b/apps/desktop/src/main/rpc/types.ts index 9153e0d0..d4813029 100644 --- a/apps/desktop/src/main/rpc/types.ts +++ b/apps/desktop/src/main/rpc/types.ts @@ -1,6 +1,11 @@ import type { Engine } from '@ipaforge/installer' import type { Logger } from '@ipaforge/kernel' -import type { ChooseIpas, LogSource, ResolveIpa } from '@ipaforge/rpc' +import type { + ChooseIpas, + ChooseSaveFolder, + LogSource, + ResolveIpa +} from '@ipaforge/rpc' export type MessageListener = (event: { readonly data: unknown }) => void @@ -34,11 +39,23 @@ export type ServeEngineDeps

= { readonly logs?: LogSource /** The file dialog for this window's "Choose files…" (main process only). */ readonly chooseIpas?: ChooseIpas + /** The folder dialog for Save signed .ipa instead (main process only). */ + readonly chooseSaveFolder?: ChooseSaveFolder readonly logger: Logger /** `() => new MessageChannelMain()` */ readonly createChannel: () => ChannelPair

} +/** The part of Electron's `dialog.showOpenDialog` the save-folder chooser uses, already bound to the window. */ +export type ChooseSaveFolderDeps = { + showOpenDialog(options: { + readonly properties: readonly ('openDirectory' | 'createDirectory')[] + }): Promise<{ + readonly canceled: boolean + readonly filePaths: readonly string[] + }> +} + /** The part of Electron's `dialog.showOpenDialog` the IPA chooser uses, already bound to the window. */ export type ChooseIpasDeps = { showOpenDialog(options: { diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index 0590d45c..61339ba3 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -116,9 +116,9 @@ Every feature below maps to the phases that deliver it. "Automatic" means the us - progress: - [x] **10a** the Developer Portal page (Certificates in the sidebar before): the team's certificates (who made each, this computer's, which apps on the device each signs, Revoke with what stops opening), App IDs (the app using each, Unused, Delete, the weekly limit), the device's provisioning profiles (Expired, Unused, Another team, Remove and Remove unused), app groups and registered devices, in small tabs with counts, also used by Preload (#86) - [x] **10b** pairing files per app, in one Pairing files dialog on the Apps page: whose files each pairing app and each other app IPAForge installed holds, Place, Remove, a path of your own for your own apps, a new remote pairing for SideStore, a No pairing file tag on an app that needs one, and Save pairing file on the Devices page (#87) - - [ ] **10c** `.p12` export and import of this computer's certificate, and saving a signed `.ipa` instead of installing it + - [x] **10c** Save signed .ipa instead, per app on Preload: signed for the team and saved in a folder picked in the host's dialog (named by an id, never a path from the page), without the certificate's private key, in the same run as the apps installed (#90) + - [ ] **10d** `.p12` export and import of this computer's certificate - later: signing in with a security key (today detected and explained, not completed) - - export signed IPAs (save the signed `.ipa` instead of installing it) - [ ] **11. Wireless and remote pairing**: pairing over Wi-Fi and finding devices beyond those usbmuxd lists, and the iOS 17+ remote-pairing (RP) file for SideStore - already in: installing over Wi-Fi to a device usbmuxd sees on the network (compressed, 1 MiB AFC writes), and a device seen over both USB and Wi-Fi listed once - **11.1** remote pairing for SideStore (iOS 17.4 and later): made over USB through the lockdown service `com.apple.dt.remotepairingdeviced.lockdown` (JSON framed with `RPPairing` and a 2-byte big-endian length, no tunnel): pair-setup (SRP-6a, 3072-bit group, SHA-512, the fixed USB PIN; Ed25519 identities under ChaCha20-Poly1305, the device's signature checked) and pair-verify before a saved one is reused. One identity per device, kept encrypted. SideStore gets it as its own file, `PairingFile_RemoteRP.plist` (`public_key`, `private_key`, `identifier`, `alt_irk`), next to the classic `PairingFile_Lockdown.plist`: a file with both key sets is ambiguous to SideStore. Repair SideStore checks it. Also: anisette server tests ask once, without retries (#82) diff --git a/docs/install-flows.md b/docs/install-flows.md index 176523ab..401e7105 100644 --- a/docs/install-flows.md +++ b/docs/install-flows.md @@ -34,6 +34,8 @@ A new certificate is stored with its private key, per account and team, as soon Installs one or more IPAs, from the catalog, from files or from links (an app source's apps are added by their download link), one after another (the Preload page). All apps are downloaded and inspected first, each checked against the device (minimum iOS, device family, architecture), so an app the device cannot run stops the run before any Apple call. The account steps then run once (sign-in, team, device, certificate) and check the App ID budget for all apps together. After that, each app goes through `free-apps`, `provision`, `sign` and `install`. When the list holds SideStore from the catalog (on its own or in LiveContainer), the run ends with the `pairing` step as Install SideStore does, so it gets this computer's pairing file too. Each app's steps carry its place in the list (`inspect-0`, `install-1`), which the UI groups them by. +**Save signed .ipa instead.** `installApps` takes `save: { folder, apps }`: the apps at those positions are provisioned and signed like the others, then written to `folder` (`save-N`, through the host's `SignedIpaFolder`; desktop: never over a file already there, `App (2).ipa` instead) and not installed. They take no free-app slot and get no pairing file. A saved IPA never carries the signing certificate's private key, whatever the app, and is always compressed. The folder comes from the host's folder dialog: the RPC server keeps its path and the page names it only by an id, so a run can only write where the user chose. + The signing certificate goes only into an app IPAForge has a reason to trust: - a catalog release whose download matched its published SHA-256; @@ -91,6 +93,7 @@ Each step tells the UI what it did, with `context.detail(detail)` (a `step-detai | `provision-N` | the number of profiles | | `sign-N` | the number of bundles signed, and whether the IPA was compressed (over Wi-Fi) | | `install-N` | uploading, then installing | +| `save-N` | where the signed IPA was saved | While they run, steps also report how far they are (`step-progress` with a detail): diff --git a/docs/roadmap.md b/docs/roadmap.md index fcfeb92a..ddd6e036 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ The detailed roadmap, with each phase's scope, is [design/roadmap.md](design/roa | 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), anisette servers in Settings ✓ (#80), days left as SideStore counts them and SideStore refreshed with its own date ✓ (#81) | | 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 | Developer Portal page ✓ (#86), pairing files per app ✓ (#87); `.p12` import/export, saving signed IPAs | +| 10 | Management tools | Developer Portal page ✓ (#86), pairing files per app ✓ (#87), saving signed IPAs ✓ (#90); `.p12` import/export | | 11 | Wireless & remote pairing | 11.1 the iOS 17.4+ remote pairing file for SideStore ✓ (#82); 11.2 installing through the iOS 17+ device tunnel over USB and Wi-Fi, and finding devices on the network; 11.3 Apple TV and Vision Pro (installing over Wi-Fi to a paired device works already) | | 12 | Release 1.0 | Docs site, translations, security review, Windows code signing and Apple notarisation, reusable packages on npm | diff --git a/docs/rpc.md b/docs/rpc.md index 6adb2c72..bb811e77 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -68,6 +68,7 @@ UI to Engine, each with an `id` that its response echoes: | `log-level` | `level?` | The level the host records at; with `level`, changes it first | | `log` | `record` | A record the UI logged, kept with the Engine's if the level would have recorded it | | `choose-ipas` | | The host's file dialog for IPAs: the files picked, or none | +| `choose-save-folder` | | The host's folder dialog for Save signed .ipa instead: `{ id, name }` of the folder picked, or null | Engine to UI: @@ -110,6 +111,8 @@ A `FileSource` cannot cross the channel, so the UI names an IPA instead: The UI never sees the file system. To pick IPAs it sends `choose-ipas` and gets back `[{ path, name, size }]` from the host's own file dialog (`createRpcServer({ chooseIpas })`; the desktop app opens it in the main process, bound to the window); without a dialog, or when the user cancels, the answer is empty. A file dropped on the window gets its path from the preload's one function (see [User Interface](ui.md)). +Save signed .ipa instead works the same way the other direction: `choose-save-folder` opens the host's folder dialog (`createRpcServer({ chooseSaveFolder })`), and the server keeps the path and answers with an id and the folder's name. `installApps` names the folder by that id (`save: { folderId, apps }`); the server turns it into the path, and an id it didn't give (or from another connection) is refused with `rpc.invalid_message`. A page can't make a run write anywhere the user didn't pick. + ## Errors Errors cross as serialized `IPAForgeError`s (`toJSON()`) and come back through `IPAForgeError.fromJSON()` with the same code, data and cause chain. `engine.classify(error)` therefore works on the UI side too. The RPC layer adds three codes of its own: diff --git a/docs/ui.md b/docs/ui.md index ab45f2bb..3f5e44ff 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -190,6 +190,8 @@ The list (`state/preload/`, kept while you visit other sections) asks the Engine 3. no app that can't be installed; 4. enough App IDs. +Each app can be ticked **Save signed .ipa instead**: it's signed and saved on the computer rather than installed (its row then says so, and it takes no free-app slot in the summary). When any app is ticked, Install first asks where to save (`engine.chooseSaveFolder()`, the host's folder dialog; cancelling starts nothing), and the button counts only the apps to install, with "N to install · M to save as signed .ipa" beside it, or reads **Sign and save** when every app is saved. The run shows each saved app's file under its `save-N` step. + It starts `engine.installApps` with the ready apps. The run is the same run view as Install (one run at a time, in `state/active-run/`, which holds either kind; the other page says an install is running and links to it), with the steps grouped by app: the device and Apple ID steps first, then each app's own. **Done** empties the list. The browser dev host's fake Engine plays it too: its file dialog picks `MyGame.ipa`, a link "downloads" for a moment, StikDebug is on the device in an older version, and names decide the problems (a name with `Encrypted`, `Future` or `NotAnApp` in it). Its sources: the catalog and SideStore's source built in, and any https link added as "Example Community Repo"; a link containing `unreachable` or `notsource` fails that way, and `skipped` leaves two apps out. The `source-offline` scenario makes SideStore's source fail to refresh. diff --git a/packages/installer/src/__tests__/harness.ts b/packages/installer/src/__tests__/harness.ts index 4b731a4c..d69334bf 100644 --- a/packages/installer/src/__tests__/harness.ts +++ b/packages/installer/src/__tests__/harness.ts @@ -26,16 +26,29 @@ export const createHarness = (options: HarnessOptions = {}) => { const signer = fakeSigner(options.signerIds) const secrets = memorySecrets() const scratch = memoryScratch() + // Save signed .ipa instead: what was written, by folder and name. + const saved: { folder: string; name: string; bytes: Uint8Array }[] = [] + const signedIpaFolder = { + save: async ( + folder: string, + name: string, + stream: ReadableStream + ) => { + saved.push({ folder, name, bytes: await new Response(stream).bytes() }) + return `${folder}/${name}` + } + } const engine = createEngine({ devices: devices.manager, apple: apple.apple, catalog: catalog.catalog, secrets, scratch, - signer: signer.signer + signer: signer.signer, + signedIpaFolder }) - return { engine, devices, apple, catalog, signer, secrets, scratch } + return { engine, devices, apple, catalog, signer, secrets, scratch, saved } } export type Answers = Readonly< diff --git a/packages/installer/src/deps.ts b/packages/installer/src/deps.ts index de04449c..942272a0 100644 --- a/packages/installer/src/deps.ts +++ b/packages/installer/src/deps.ts @@ -19,6 +19,9 @@ export const resolveInstallerDeps = ( installed: input.installed ?? createMemoryInstalledStore(), kept: input.kept ?? createMemoryKeptIpaStore(), signer: input.signer ?? createDefaultSigner(logger), + ...(input.signedIpaFolder + ? { signedIpaFolder: input.signedIpaFolder } + : {}), logger, clock: input.clock ?? systemClock, config: { ...DEFAULT_INSTALLER_CONFIG, ...input.config } diff --git a/packages/installer/src/domain/labels.ts b/packages/installer/src/domain/labels.ts index c4ece076..d434b16f 100644 --- a/packages/installer/src/domain/labels.ts +++ b/packages/installer/src/domain/labels.ts @@ -16,6 +16,8 @@ export const StepLabel = { refreshProfiles: 'install.steps.refresh_profiles', sign: 'install.steps.sign', install: 'install.steps.install', + /** Save signed .ipa instead: the signed app written to the folder the user picked. */ + save: 'install.steps.save', pairing: 'install.steps.pairing', remember: 'install.steps.remember', pairingTargets: 'pairing.steps.targets', diff --git a/packages/installer/src/domain/ports/signed-ipa-folder.ts b/packages/installer/src/domain/ports/signed-ipa-folder.ts new file mode 100644 index 00000000..281c0267 --- /dev/null +++ b/packages/installer/src/domain/ports/signed-ipa-folder.ts @@ -0,0 +1,14 @@ +// Where "Save signed .ipa instead" writes: a folder the user picked on the host (the desktop app's folder dialog). +// The Engine never chooses a folder itself: the path comes from the host, through the RPC server, never the page. + +export type SignedIpaFolder = { + /** + * Writes `stream` as `name` in `folder`, under a free name ("App (2).ipa" when "App.ipa" is taken), and returns + * the path it was written to. + */ + save( + folder: string, + name: string, + stream: ReadableStream + ): Promise +} diff --git a/packages/installer/src/domain/step-weights.ts b/packages/installer/src/domain/step-weights.ts index 870f9ce5..7f930633 100644 --- a/packages/installer/src/domain/step-weights.ts +++ b/packages/installer/src/domain/step-weights.ts @@ -8,5 +8,6 @@ export const StepWeight = { provision: 2, sign: 4, install: 6, + save: 1, pairing: 1 } as const diff --git a/packages/installer/src/domain/types.ts b/packages/installer/src/domain/types.ts index c5d0cda5..c84dcdcb 100644 --- a/packages/installer/src/domain/types.ts +++ b/packages/installer/src/domain/types.ts @@ -255,6 +255,8 @@ export type AppJob = { /** The signed IPA, waiting in the scratch store under `key` until the install step ends. */ readonly signed?: SignedIpa readonly installed?: boolean + /** Save signed .ipa instead: where the signed app was written on the computer. */ + readonly savedTo?: string } export type DeviceSummary = { diff --git a/packages/installer/src/flows/app-steps.ts b/packages/installer/src/flows/app-steps.ts index ffe83d94..16247404 100644 --- a/packages/installer/src/flows/app-steps.ts +++ b/packages/installer/src/flows/app-steps.ts @@ -12,6 +12,7 @@ import { inspectStep } from '@installer/steps/inspect.ts' import { installStep } from '@installer/steps/install.ts' import { provisionStep } from '@installer/steps/provision.ts' import { registerDeviceStep } from '@installer/steps/register-device.ts' +import { saveSignedStep } from '@installer/steps/save.ts' import { signStep } from '@installer/steps/sign.ts' import { signInStep } from '@installer/steps/sign-in.ts' import { teamStep } from '@installer/steps/team.ts' @@ -45,6 +46,20 @@ export const accountSteps = (runtime: FlowRuntime): Step[] => [ appIdsStep(runtime) ] +/** + * Save signed .ipa instead: provisioned and signed like an install (no private key inside), then written to the + * folder the user picked. It takes no free-app slot: nothing goes on the device. + */ +export const saveAppSteps = ( + runtime: FlowRuntime, + index: number, + folder: string +): Step[] => [ + provisionStep(runtime, index), + signStep(runtime, index, { forSaving: true }), + saveSignedStep(runtime, index, folder) +] + export const installAppSteps = ( runtime: FlowRuntime, index: number diff --git a/packages/installer/src/flows/install-apps.test.ts b/packages/installer/src/flows/install-apps.test.ts index f7d0f1e4..04ca8b78 100644 --- a/packages/installer/src/flows/install-apps.test.ts +++ b/packages/installer/src/flows/install-apps.test.ts @@ -241,4 +241,28 @@ describe('installApps', () => { const h = createHarness() expect(() => h.engine.installApps(install([]))).toThrow() }) + + it('saves the apps marked to save in the folder picked, signed without the private key, and installs the others', async () => { + const h = createHarness() + const result = await h.engine.installApps( + { + ...install([{ kind: 'catalog', appId: 'sidestore' }, file('one.ipa')]), + save: { folder: '/Users/me/Signed', apps: [0] } + }, + { onPrompt: scripted() } + ).result + + expect(result.status).toBe('completed') + expect(h.saved.map(({ folder, name }) => ({ folder, name }))).toEqual([ + { folder: '/Users/me/Signed', name: 'App.ipa' } + ]) + expect(h.devices.calls.installs).toHaveLength(1) + // SideStore saved to a folder doesn't carry the certificate's private key, nor gets a pairing file. + expect(sharesCertificate(h.signer.calls.signed[0])).toBe(false) + expect(h.devices.calls.placed).toEqual([]) + expect(h.scratch.keys.size).toBe(0) + if (result.status !== 'completed') return + expect(result.state.apps[0]?.savedTo).toBe('/Users/me/Signed/App.ipa') + expect(result.state.apps[0]?.installed).toBeUndefined() + }) }) diff --git a/packages/installer/src/flows/install-apps.ts b/packages/installer/src/flows/install-apps.ts index fedf5162..3a95348b 100644 --- a/packages/installer/src/flows/install-apps.ts +++ b/packages/installer/src/flows/install-apps.ts @@ -10,7 +10,8 @@ import type { import { accountSteps, installAppSteps, - prepareAppSteps + prepareAppSteps, + saveAppSteps } from '@installer/flows/app-steps.ts' import { CATALOG_PAIRING_APPS } from '@installer/flows/constants.ts' import type { Flow } from '@installer/flows/flow.ts' @@ -27,6 +28,14 @@ export type InstallAppsInput = { readonly apps: readonly AppSource[] /** Create App IDs even though Apple's count says none are left, when that count was negative (Try anyway). */ readonly tryAnyway?: boolean + /** + * Save signed .ipa instead: the apps (by position) signed and written to `folder` on the computer, not installed. + * The folder comes from the host's dialog, never from the page. + */ + readonly save?: { + readonly folder: string + readonly apps: readonly number[] + } } export const INSTALL_APPS = 'installApps' @@ -72,7 +81,11 @@ export const installAppsFlow = ( input: InstallAppsInput ): Flow => { assertSomethingToInstall(input) - const pairing = pairingTargets(input.apps) + const saved = new Set(input.save?.apps ?? []) + // Only an app that goes on the device gets the pairing file. + const pairing = pairingTargets(input.apps).filter( + (target) => !saved.has(target.index) + ) return { initial: compact({ @@ -89,7 +102,9 @@ export const installAppsFlow = ( ), ...accountSteps(runtime), ...input.apps.flatMap((_source, index) => - installAppSteps(runtime, index) + input.save && saved.has(index) + ? saveAppSteps(runtime, index, input.save.folder) + : installAppSteps(runtime, index) ), ...pairing.map((target) => installedPairingStep(runtime, target)), rememberTeamStep(runtime) diff --git a/packages/installer/src/index.ts b/packages/installer/src/index.ts index c83e11e0..a1e8dd59 100644 --- a/packages/installer/src/index.ts +++ b/packages/installer/src/index.ts @@ -28,6 +28,7 @@ export { StepLabel } from '@installer/domain/labels.ts' export type { InstalledStore } from '@installer/domain/ports/installed-store.ts' export type { KeptIpaStore } from '@installer/domain/ports/kept-ipa-store.ts' export type { ScratchStore } from '@installer/domain/ports/scratch-store.ts' +export type { SignedIpaFolder } from '@installer/domain/ports/signed-ipa-folder.ts' export type { IpaSigner, SignRequest } from '@installer/domain/ports/types.ts' export { PromptKind } from '@installer/domain/prompts.ts' export type { diff --git a/packages/installer/src/pipeline/types.ts b/packages/installer/src/pipeline/types.ts index fafff7eb..786aa14c 100644 --- a/packages/installer/src/pipeline/types.ts +++ b/packages/installer/src/pipeline/types.ts @@ -38,6 +38,8 @@ export type StepDetail = } | { readonly kind: 'team'; readonly name: string; readonly isFree: boolean } | { readonly kind: 'device-registration'; readonly isNew: boolean } + /** Save signed .ipa instead: where the signed app was written. */ + | { readonly kind: 'saved'; readonly path: string } | { readonly kind: 'certificate' readonly how: 'reused' | 'created' | 'replaced' diff --git a/packages/installer/src/steps/save.test.ts b/packages/installer/src/steps/save.test.ts new file mode 100644 index 00000000..ef0a901f --- /dev/null +++ b/packages/installer/src/steps/save.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' + +import { signedIpaName } from '@installer/steps/save.ts' + +describe('the saved file’s name', () => { + it('is the app’s name and version', () => { + expect(signedIpaName('SideStore', '0.7.0')).toBe('SideStore 0.7.0.ipa') + expect(signedIpaName('MyGame', undefined)).toBe('MyGame.ipa') + }) + + it('holds nothing a file name can’t, nor a folder', () => { + expect(signedIpaName('../evil/app: one?', '1')).toBe( + '.._evil_app_ one_ 1.ipa' + ) + expect(signedIpaName('', undefined)).toBe('App.ipa') + }) +}) diff --git a/packages/installer/src/steps/save.ts b/packages/installer/src/steps/save.ts new file mode 100644 index 00000000..fe85723f --- /dev/null +++ b/packages/installer/src/steps/save.ts @@ -0,0 +1,60 @@ +// Save signed .ipa instead: the app signed for the team, written to the folder the user picked on the computer +// instead of being installed. Its signed copy leaves the scratch store whatever happens. +import type { FlowRuntime } from '@installer/application/runtime.ts' +import { StepLabel } from '@installer/domain/labels.ts' +import { StepWeight } from '@installer/domain/step-weights.ts' +import type { InstallState } from '@installer/domain/types.ts' +import type { Step } from '@installer/pipeline/types.ts' +import { + appStepId, + jobAt, + required, + updateJob +} from '@installer/steps/app-job.ts' +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' + +/** `App 1.2.ipa` from the app's name and version: letters, digits, spaces and `. _ ( ) + @ -`, nothing else. */ +export const signedIpaName = (name: string, version: string | undefined) => + `${ + [name, version] + .filter(Boolean) + .join(' ') + .replace(/[^\p{L}\p{N} ._()+@-]/gu, '_') + .trim() + .slice(0, 120) || 'App' + }.ipa` + +export const saveSignedStep = ( + runtime: FlowRuntime, + index: number, + folder: string +): Step => ({ + id: appStepId('save', index), + labelKey: StepLabel.save, + weight: StepWeight.save, + run: async (state, context) => { + const output = runtime.deps.signedIpaFolder + if (!output) + throw new IPAForgeError(ErrorCode.Unexpected, { + message: 'this host cannot save signed IPAs' + }) + const job = jobAt(state, index) + const signed = required(job.signed, 'signed IPA') + const app = required(job.inspection, 'inspection').app + try { + const savedTo = await output.save( + folder, + signedIpaName(app.name, app.version), + signed.file.stream() + ) + runtime.deps.logger.info('signed IPA saved', { + bundleId: app.identifier + }) + context.detail({ kind: 'saved', path: savedTo }) + + return updateJob(state, index, { savedTo }) + } finally { + await runtime.deps.scratch.delete(signed.key) + } + } +}) diff --git a/packages/installer/src/steps/sign.ts b/packages/installer/src/steps/sign.ts index fdc2ce2f..b36689f0 100644 --- a/packages/installer/src/steps/sign.ts +++ b/packages/installer/src/steps/sign.ts @@ -48,12 +48,17 @@ const certificateAdditions = ( const onWifi = async (runtime: FlowRuntime, udid: string): Promise => (await runtime.device(udid)).device.connectionType === 'network' -/** Signs the job's IPA into the scratch store; also used by the install step when the signed copy is gone. */ +/** + * Signs the job's IPA into the scratch store; also used by the install step when the signed copy is gone. A copy to + * save on the computer (`forSaving`) never carries the certificate's private key (SideStore's additions), and is + * always compressed: it's a file to keep, not to send. + */ export const signToScratch = async ( runtime: FlowRuntime, state: InstallState, index: number, - context: StepContext + context: StepContext, + { forSaving = false }: { readonly forSaving?: boolean } = {} ): Promise => { const { signer, scratch } = runtime.deps const job = jobAt(state, index) @@ -66,7 +71,7 @@ export const signToScratch = async ( required(state.certificateSerial, 'certificate') ) const der = required(certificate.certificate.content, 'certificate content') - const isWifi = await onWifi(runtime, state.udid) + const isCompressed = forSaving || (await onWifi(runtime, state.udid)) const stream = await signer.sign( required(job.file, 'IPA file'), compact({ @@ -79,14 +84,14 @@ export const signToScratch = async ( deviceUdid: state.udid, // SideStore's certificate (when it may have it), and IPAForge's mark with where the app came from. additions: withMarker( - certificateAdditions(job, certificate, der), + forSaving ? undefined : certificateAdditions(job, certificate, der), markerFor( required(job.inspection, 'inspection').app.identifier, originOf(job), state.certificateSerial ) ), - compressionLevel: isWifi + compressionLevel: isCompressed ? runtime.deps.config.wifiCompressionLevel : undefined, onProgress: (fraction: number) => context.progress(fraction), @@ -95,18 +100,19 @@ export const signToScratch = async ( ) const key = `${SIGNED_PREFIX}/${globalThis.crypto.randomUUID()}.ipa` - return { key, file: await scratch.put(key, stream), compressed: isWifi } + return { key, file: await scratch.put(key, stream), compressed: isCompressed } } export const signStep = ( runtime: FlowRuntime, - index: number + index: number, + options: { readonly forSaving?: boolean } = {} ): Step => ({ id: appStepId('sign', index), labelKey: StepLabel.sign, weight: StepWeight.sign, run: async (state, context) => { - const signed = await signToScratch(runtime, state, index, context) + const signed = await signToScratch(runtime, state, index, context, options) context.detail({ kind: 'signed', bundles: required(jobAt(state, index).identity, 'identity plan').bundles diff --git a/packages/installer/src/types.ts b/packages/installer/src/types.ts index e34423d8..e47192d5 100644 --- a/packages/installer/src/types.ts +++ b/packages/installer/src/types.ts @@ -2,6 +2,7 @@ import type { InstallerConfig } from '@installer/domain/config.ts' import type { InstalledStore } from '@installer/domain/ports/installed-store.ts' import type { KeptIpaStore } from '@installer/domain/ports/kept-ipa-store.ts' import type { ScratchStore } from '@installer/domain/ports/scratch-store.ts' +import type { SignedIpaFolder } from '@installer/domain/ports/signed-ipa-folder.ts' import type { IpaSigner } from '@installer/domain/ports/types.ts' import type { AppleAccounts } from '@ipaforge/apple' import type { Catalog } from '@ipaforge/catalog' @@ -21,6 +22,8 @@ export type InstallerDeps = { /** Each installed app's original IPA, signed again by Refresh. */ readonly kept: KeptIpaStore readonly signer: IpaSigner + /** Where "Save signed .ipa instead" writes; without it, a run that saves fails before signing anything. */ + readonly signedIpaFolder?: SignedIpaFolder readonly logger: Logger readonly clock: Clock readonly config: InstallerConfig diff --git a/packages/rpc/src/application/client.ts b/packages/rpc/src/application/client.ts index e97a7145..00771ea4 100644 --- a/packages/rpc/src/application/client.ts +++ b/packages/rpc/src/application/client.ts @@ -33,6 +33,7 @@ import type { WireSubscriptionEvent } from '@rpc/domain/protocol/types.ts' import type { + ChosenFolder, ChosenIpa, EngineClient, EngineLogs, @@ -286,6 +287,10 @@ export const createEngineClient = ( classify, logs, chooseIpas: () => - requests.send({ type: 'choose-ipas' }) as Promise + requests.send({ type: 'choose-ipas' }) as Promise, + chooseSaveFolder: async () => + ((await requests.send({ + type: 'choose-save-folder' + })) as ChosenFolder | null) ?? undefined } } diff --git a/packages/rpc/src/application/server.ts b/packages/rpc/src/application/server.ts index 248d2a3c..28fdf7bf 100644 --- a/packages/rpc/src/application/server.ts +++ b/packages/rpc/src/application/server.ts @@ -15,6 +15,7 @@ import { createCommandStarter } from '@rpc/application/server/commands.ts' import { createLogRequests } from '@rpc/application/server/logs.ts' import { createQueryRunner } from '@rpc/application/server/queries.ts' import { createRunRegistry } from '@rpc/application/server/runs.ts' +import { createSaveFolders } from '@rpc/application/server/save-folders.ts' import { createSubscriptionRegistry } from '@rpc/application/server/subscriptions.ts' import type { RequestHandlers, @@ -33,6 +34,7 @@ export const createRpcServer = ({ resolveIpa, logs, chooseIpas, + chooseSaveFolder, logger = silentLogger }: RpcServerOptions): RpcServer => { const log = logger.child({ scope: 'rpc' }) @@ -54,8 +56,9 @@ export const createRpcServer = ({ } const runQuery = createQueryRunner(engine, resolveIpa) + const saveFolders = createSaveFolders(chooseSaveFolder) const runs = createRunRegistry({ - startCommand: createCommandStarter(engine, resolveIpa), + startCommand: createCommandStarter(engine, resolveIpa, saveFolders), checkpoints, send }) @@ -80,7 +83,8 @@ export const createRpcServer = ({ logs: (request) => logRequests.page(request.query), 'log-level': (request) => logRequests.level(request.level), log: (request) => logRequests.write(request.record as LogRecord), - 'choose-ipas': () => chooseIpas?.() ?? [] + 'choose-ipas': () => chooseIpas?.() ?? [], + 'choose-save-folder': () => saveFolders.choose() } const sendError = (id: string, error: IPAForgeError): void => { diff --git a/packages/rpc/src/application/server/commands.ts b/packages/rpc/src/application/server/commands.ts index f246c8d8..0c123877 100644 --- a/packages/rpc/src/application/server/commands.ts +++ b/packages/rpc/src/application/server/commands.ts @@ -5,6 +5,7 @@ import { toInstallAppsInput, toRefreshAppsInput } from '@rpc/application/server/inputs.ts' +import type { SaveFolders } from '@rpc/application/server/save-folders.ts' import type { CommandStarters, Options, @@ -19,13 +20,18 @@ const typed = (options: Options): CommandOptions => const commandStarters = ( engine: Engine, - resolveIpa: ResolveIpa + resolveIpa: ResolveIpa, + saveFolders: SaveFolders ): CommandStarters => ({ installSideStore: async (input, options) => engine.installSideStore(compact(input), typed(options)), installApps: async (input, options, signal) => engine.installApps( - await toInstallAppsInput(input, { resolveIpa, engine }, signal), + await toInstallAppsInput( + input, + { resolveIpa, engine, folderOf: saveFolders.pathOf }, + signal + ), typed(options) ), refreshApps: async (input, options, signal) => @@ -43,9 +49,10 @@ const commandStarters = ( export const createCommandStarter = ( engine: Engine, - resolveIpa: ResolveIpa + resolveIpa: ResolveIpa, + saveFolders: SaveFolders ): StartCommand => { - const starters = commandStarters(engine, resolveIpa) + const starters = commandStarters(engine, resolveIpa, saveFolders) // The union of starters cannot be called with the union of calls; `command` pairs them up. return (call, options, signal) => diff --git a/packages/rpc/src/application/server/inputs.ts b/packages/rpc/src/application/server/inputs.ts index e2f0c144..e423f585 100644 --- a/packages/rpc/src/application/server/inputs.ts +++ b/packages/rpc/src/application/server/inputs.ts @@ -83,12 +83,31 @@ const toAppSources = async ( return apps } +/** + * Save signed .ipa instead names its folder by the id the host's dialog gave it; the path never comes from the page. + */ export const toInstallAppsInput = async ( input: InstallAppsCall, - context: Omit, + context: Omit & { + readonly folderOf: (id: string) => string + }, signal: AbortSignal -): Promise => - compact({ ...input, apps: await toAppSources(input, context, signal) }) +): Promise => { + const { save, ...rest } = input + const folder = save ? context.folderOf(save.folderId) : undefined + + return compact({ + ...rest, + apps: await toAppSources(input, context, signal), + save: + save && folder !== undefined + ? { + folder, + apps: save.apps.filter((index) => index < input.apps.length) + } + : undefined + }) +} export const toRefreshAppsInput = async ( input: RefreshAppsCall, diff --git a/packages/rpc/src/application/server/save-folders.ts b/packages/rpc/src/application/server/save-folders.ts new file mode 100644 index 00000000..ddf75844 --- /dev/null +++ b/packages/rpc/src/application/server/save-folders.ts @@ -0,0 +1,42 @@ +// The folders the user picked in the host's dialog for Save signed .ipa instead, by id. The page names a folder only +// by its id, so a run can write only where the user chose. +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' +import type { ChooseSaveFolder } from '@rpc/domain/ports/choose-save-folder.ts' +import type { ChosenFolder } from '@rpc/domain/types.ts' + +/** The last part of a path, `/` or `\` separated: what the page shows of the folder. */ +const folderName = (path: string): string => + path.split(/[\\/]/).filter(Boolean).at(-1) ?? path + +export type SaveFolders = { + /** Opens the host's dialog; nothing when the user cancels or the host has none. */ + choose(): Promise + /** The path of a folder picked in this connection; `rpc.invalid_message` for any other id. */ + pathOf(id: string): string +} + +export const createSaveFolders = ( + chooseSaveFolder: ChooseSaveFolder | undefined +): SaveFolders => { + const folders = new Map() + + return { + choose: async () => { + const path = await chooseSaveFolder?.() + if (!path) return null + const id = globalThis.crypto.randomUUID() + folders.set(id, path) + + return { id, name: folderName(path) } + }, + pathOf: (id) => { + const path = folders.get(id) + if (path === undefined) + throw new IPAForgeError(ErrorCode.InvalidRpcMessage, { + message: 'unknown save folder' + }) + + return path + } + } +} diff --git a/packages/rpc/src/application/types.ts b/packages/rpc/src/application/types.ts index 7d5fde4e..08aab604 100644 --- a/packages/rpc/src/application/types.ts +++ b/packages/rpc/src/application/types.ts @@ -2,6 +2,7 @@ import type { Engine } from '@ipaforge/installer' import type { Logger } from '@ipaforge/kernel' import type { RpcConfig } from '@rpc/domain/config.ts' import type { ChooseIpas } from '@rpc/domain/ports/choose-ipas.ts' +import type { ChooseSaveFolder } from '@rpc/domain/ports/choose-save-folder.ts' import type { LogSource } from '@rpc/domain/ports/log-source.ts' import type { ResolveIpa } from '@rpc/domain/ports/resolve-ipa.ts' import type { Transport } from '@rpc/domain/ports/transport.ts' @@ -24,6 +25,8 @@ export type RpcServerOptions = { readonly logs?: LogSource /** The host's file dialog for IPAs; without it, choosing files answers with none. */ readonly chooseIpas?: ChooseIpas + /** The host's folder dialog for Save signed .ipa instead; without it, saving can't start. */ + readonly chooseSaveFolder?: ChooseSaveFolder readonly logger?: Logger } diff --git a/packages/rpc/src/domain/ports/choose-save-folder.ts b/packages/rpc/src/domain/ports/choose-save-folder.ts new file mode 100644 index 00000000..258137b5 --- /dev/null +++ b/packages/rpc/src/domain/ports/choose-save-folder.ts @@ -0,0 +1,6 @@ +/** + * Asks the user for a folder in the host's own dialog (the desktop app's main process), where Save signed .ipa + * instead writes. Resolves with its path, or nothing when the user cancels. The path stays on the server: the page + * only gets an id for it. + */ +export type ChooseSaveFolder = () => Promise diff --git a/packages/rpc/src/domain/protocol/inputs.ts b/packages/rpc/src/domain/protocol/inputs.ts index 6bd6457d..5f483a78 100644 --- a/packages/rpc/src/domain/protocol/inputs.ts +++ b/packages/rpc/src/domain/protocol/inputs.ts @@ -98,7 +98,14 @@ export const installAppsInputSchema = z.object({ ...accountSchema, teamId, apps: z.array(ipaSourceSchema), - tryAnyway + tryAnyway, + /** Save signed .ipa instead: the apps (by position) to save in a folder the host's dialog gave an id to. */ + save: z + .object({ + folderId: textSchema.max(64), + apps: z.array(z.number().int().nonnegative().max(999)).max(100) + }) + .optional() }) export const refreshPlanQuerySchema = z.object({ diff --git a/packages/rpc/src/domain/protocol/messages.ts b/packages/rpc/src/domain/protocol/messages.ts index f780b1d0..20805440 100644 --- a/packages/rpc/src/domain/protocol/messages.ts +++ b/packages/rpc/src/domain/protocol/messages.ts @@ -38,6 +38,7 @@ export const stepDetailSchema = z.discriminatedUnion('kind', [ detail('session', { how: z.enum(['reused', 'renewed', 'signed-in']) }), detail('team', { name: z.string(), isFree: z.boolean() }), detail('device-registration', { isNew: z.boolean() }), + detail('saved', { path: z.string().max(4096) }), detail('certificate', { how: z.enum(['reused', 'created', 'replaced']) }), detail('app-ids', { created: count, reused: count, left: count }), detail('free-apps', { diff --git a/packages/rpc/src/domain/protocol/requests.ts b/packages/rpc/src/domain/protocol/requests.ts index a9089db0..ceaccb1a 100644 --- a/packages/rpc/src/domain/protocol/requests.ts +++ b/packages/rpc/src/domain/protocol/requests.ts @@ -156,5 +156,7 @@ export const requestSchema = z.discriminatedUnion('type', [ /** A record the UI logged, kept with the Engine's so the viewer shows both. */ request('log', { record: logRecordSchema }), /** The host's file dialog for IPAs; the answer names the files the user picked. */ - request('choose-ipas', {}) + request('choose-ipas', {}), + /** The host's folder dialog for Save signed .ipa instead; the answer is the folder's id and name, or null. */ + request('choose-save-folder', {}) ]) diff --git a/packages/rpc/src/domain/types.ts b/packages/rpc/src/domain/types.ts index 653546d0..fb349df6 100644 --- a/packages/rpc/src/domain/types.ts +++ b/packages/rpc/src/domain/types.ts @@ -71,6 +71,12 @@ export type EngineLogs = { write(record: LogRecord): void } +/** A folder the user picked for Save signed .ipa instead: an id the Engine knows it by, and its name to show. */ +export type ChosenFolder = { + readonly id: string + readonly name: string +} + /** An IPA the user picked in the host's file dialog: where it is (to name it as a file source), its name and size. */ export type ChosenIpa = { readonly path: string @@ -117,6 +123,8 @@ export type EngineClient = Omit & { readonly logs: EngineLogs /** Opens the host's file dialog for IPAs (none when cancelled, or when the host has no dialog). */ chooseIpas(): Promise + /** Opens the host's folder dialog for Save signed .ipa instead (nothing when cancelled, or without a dialog). */ + chooseSaveFolder(): Promise } // What a value looks like after crossing the channel. Structured clone keeps data (Maps, Dates, bytes) but refuses diff --git a/packages/rpc/src/index.ts b/packages/rpc/src/index.ts index 4d9f1e9c..fccbccbf 100644 --- a/packages/rpc/src/index.ts +++ b/packages/rpc/src/index.ts @@ -43,6 +43,7 @@ export type { export { createUpdateClient, serveUpdates } from '@rpc/application/updates.ts' export { DEFAULT_RPC_CONFIG, type RpcConfig } from '@rpc/domain/config.ts' export type { ChooseIpas } from '@rpc/domain/ports/choose-ipas.ts' +export type { ChooseSaveFolder } from '@rpc/domain/ports/choose-save-folder.ts' export type { LogSource } from '@rpc/domain/ports/log-source.ts' export type { ResolveIpa } from '@rpc/domain/ports/resolve-ipa.ts' export type { Transport } from '@rpc/domain/ports/transport.ts' @@ -69,6 +70,7 @@ export type { } from '@rpc/domain/protocol/types.ts' export { updateStateSchema } from '@rpc/domain/protocol/updates.ts' export type { + ChosenFolder, ChosenIpa, EngineClient, EngineLogs, diff --git a/packages/rpc/src/rpc.test.ts b/packages/rpc/src/rpc.test.ts index c9554bfe..dbe4e178 100644 --- a/packages/rpc/src/rpc.test.ts +++ b/packages/rpc/src/rpc.test.ts @@ -19,7 +19,10 @@ const IPA_BYTES = new Uint8Array([1, 2, 3, 4]) const ACCOUNT = { udid: 'UDID1', accountId: 'acct' } const FILE_APP = { kind: 'file', path: '/picked/My App.ipa' } as const -const setup = () => { +const setup = ( + chooseSaveFolder: () => Promise = async () => + '/Users/me/Signed apps' +) => { const [serverEnd, clientEnd] = createMemoryTransportPair() const { engine, control } = createFakeEngine() const resolveIpa = vi.fn(async (ipa: ExternalIpa) => @@ -28,7 +31,12 @@ const setup = () => { IPA_BYTES ) ) - const server = createRpcServer({ engine, transport: serverEnd, resolveIpa }) + const server = createRpcServer({ + engine, + transport: serverEnd, + resolveIpa, + chooseSaveFolder + }) const client = createEngineClient(clientEnd) return { client, server, control, resolveIpa, serverEnd, clientEnd } @@ -180,6 +188,37 @@ describe('queries', () => { ).rejects.toMatchObject({ code: ErrorCode.InvalidRpcMessage }) }) + it('saves into the folder the host’s dialog gave, never a path from the page', async () => { + const { client, control } = setup() + + const folder = await client.chooseSaveFolder() + expect(folder?.name).toBe('Signed apps') + void client.installApps({ + ...ACCOUNT, + apps: [FILE_APP], + save: { folderId: folder?.id ?? '', apps: [0, 5] } + }) + await vi.waitFor(() => expect(control.appInputs).toHaveLength(1)) + expect(control.appInputs.at(-1)?.save).toEqual({ + folder: '/Users/me/Signed apps', + apps: [0] + }) + + await expect( + client.installApps({ + ...ACCOUNT, + apps: [FILE_APP], + save: { folderId: '/etc', apps: [0] } + }).result + ).rejects.toMatchObject({ code: ErrorCode.InvalidRpcMessage }) + }) + + it('answers with no folder when the dialog is cancelled', async () => { + const { client } = setup(async () => undefined) + + expect(await client.chooseSaveFolder()).toBeUndefined() + }) + it('manages app sources through the Engine, over https only', async () => { const { client } = setup() const url = 'https://example.com/apps.json' diff --git a/packages/ui/src/__tests__/screen-table.ts b/packages/ui/src/__tests__/screen-table.ts index ce5d52ae..6458848b 100644 --- a/packages/ui/src/__tests__/screen-table.ts +++ b/packages/ui/src/__tests__/screen-table.ts @@ -16,7 +16,8 @@ import { renderWhatsNew, repairShown, type ScreenOptions, - showSources + showSources, + tickSaveInstead } from '@ui/__tests__/screens.ts' const NEXT = '0.1.0-alpha.99' @@ -37,6 +38,11 @@ export const screens = { await renderScreen('/preload', options) await fillPreload() }, + 'preload-save': async (options: ScreenOptions) => { + await renderScreen('/preload', options) + await fillPreload() + await tickSaveInstead() + }, 'preload-sources': async (options: ScreenOptions) => { await renderScreen('/preload', options) await showSources() diff --git a/packages/ui/src/__tests__/screens.ts b/packages/ui/src/__tests__/screens.ts index b50ee251..635aedd7 100644 --- a/packages/ui/src/__tests__/screens.ts +++ b/packages/ui/src/__tests__/screens.ts @@ -136,6 +136,22 @@ export const fillPreload = async () => { }) } +/** Preload filled, with its last app ticked to save as a signed .ipa (the footer then says what installs and saves). */ +export const tickSaveInstead = async () => { + const boxes = await waitFor(() => { + const found = all('main ul li input[type="checkbox"]') + if (found.length < 2) throw new Error('no Save signed .ipa instead yet') + return found + }) + const last = boxes[boxes.length - 1] + if (last instanceof HTMLElement) last.click() + await waitFor(() => + expect(all('main input[type="checkbox"]:checked')).toHaveLength(1) + ) + // The list and its footer, in view. + boxes[0]?.closest('ul')?.scrollIntoView({ block: 'start' }) +} + /** The Devices page with its checklist open (LocalDevVPN to install, so with its QR code). */ export const checklistShown = () => waitFor(() => expect(all('main svg[role="img"]')).toHaveLength(1)) diff --git a/packages/ui/src/features/install/run/utils/step-report-texts.ts b/packages/ui/src/features/install/run/utils/step-report-texts.ts index 336e136d..f1133728 100644 --- a/packages/ui/src/features/install/run/utils/step-report-texts.ts +++ b/packages/ui/src/features/install/run/utils/step-report-texts.ts @@ -34,6 +34,8 @@ export const stepReportTexts: StepReportTexts = { session: (report, { t }) => t(`install.run.report.session.${report.how}`), team: (report, { t }) => report.isFree ? t('accounts.freeTeam', { name: report.name }) : report.name, + saved: (report, { t }) => + t('install.run.report.saved', { path: report.path }), 'device-registration': (report, { t }) => t( report.isNew diff --git a/packages/ui/src/features/preload/home/components/install-chips.tsx b/packages/ui/src/features/preload/home/components/install-chips.tsx new file mode 100644 index 00000000..8f9155cc --- /dev/null +++ b/packages/ui/src/features/preload/home/components/install-chips.tsx @@ -0,0 +1,32 @@ +import { useTranslation } from 'react-i18next' + +import { RowChip } from '@ui/features/preload/home/components/row-chip.tsx' +import type { InstallPlan } from '@ui/services/engine/types.ts' + +type InstallChipsProps = { + plan: InstallPlan + isPairingApp: boolean +} + +/** What installing an app does on the device: new or an update, and the pairing file for a pairing app. */ +export const InstallChips = ({ plan, isPairingApp }: InstallChipsProps) => { + const { t } = useTranslation() + + return ( + <> + {plan.installedVersion ? ( + + {t('preload.row.updates', { + from: plan.installedVersion, + to: plan.inspection.app.version ?? '' + })} + + ) : ( + {t('preload.row.new')} + )} + {isPairingApp ? ( + {t('preload.row.pairing')} + ) : null} + + ) +} diff --git a/packages/ui/src/features/preload/home/components/preload-footer.tsx b/packages/ui/src/features/preload/home/components/preload-footer.tsx index 930482f4..43356b34 100644 --- a/packages/ui/src/features/preload/home/components/preload-footer.tsx +++ b/packages/ui/src/features/preload/home/components/preload-footer.tsx @@ -8,6 +8,8 @@ type PreloadFooterProps = { readiness: Readiness /** Apps ready to install. */ count: number + /** Of them, the apps to save as signed .ipa files instead. */ + saving: number hasItems: boolean onInstall: () => void onClear: () => void @@ -17,6 +19,7 @@ type PreloadFooterProps = { export const PreloadFooter = ({ readiness, count, + saving, hasItems, onInstall, onClear @@ -27,8 +30,18 @@ export const PreloadFooter = ({

+ {saving > 0 && saving < count ? ( + + {t('preload.installAndSave', { + install: count - saving, + save: saving + })} + + ) : null} {hasItems ? (