diff --git a/CONTEXT.md b/CONTEXT.md index 2df69d7..499251c 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -36,6 +36,10 @@ _Avoid_: archive import, replace, synchronize The first half of a Bluesky archive import: reading a Cyd Bluesky archive off the device into verified, isolated staging, with no effect on any Bluesky local account. Intake ends *prepared*; the merge that follows is the rest of the import. _Avoid_: intake, extraction, unpacking, archive validation +**Cyd Bluesky archive export**: +Writing one Bluesky local account's Bluesky saved data out as a Cyd Bluesky archive, from a point-in-time snapshot taken while account-mutating work is briefly paused. It is the mirror of Bluesky archive intake and reads only what Cyd already holds, so it needs no Bluesky connection. +_Avoid_: export, backup, archive export + **Bluesky account settings**: Local preferences governing how Cyd saves and manages a Bluesky identity. A Cyd Bluesky archive can supply defaults for a new Bluesky local account, but does not silently override an existing Bluesky local account's preferences or schedules. _Avoid_: account settings, account data, archive state diff --git a/app/account/components/DevArchiveExportCard.tsx b/app/account/components/DevArchiveExportCard.tsx new file mode 100644 index 0000000..ca12385 --- /dev/null +++ b/app/account/components/DevArchiveExportCard.tsx @@ -0,0 +1,173 @@ +import { useCallback, useState } from "react"; +import { ActivityIndicator, StyleSheet, Text, View } from "react-native"; + +import { PrimaryButton } from "@/components/account/shared-tab-components"; +import { withBlueskyController } from "@/controllers"; +import { getPortableBlueskySettings } from "@/database/accounts"; +import type { BlueskyArchiveExportProgress } from "@/services/archive-export"; +import type { AccountTabPalette } from "@/types/account-tabs"; + +/** + * The development-only way to write a Cyd Bluesky archive. + * + * Mobile builds its version 2 writer before the readers that consume it, so + * that reader work has real archives to be tested against (ADR 0004). What + * that ordering must not do is put an export button in front of people before + * #100 proves an archive Mobile writes can be read back — by Mobile and by + * Desktop. Hence `__DEV__`: this renders nothing at all in a release build. + * + * It is deliberately plain. The shippable export flow — resumable, with its + * plaintext warning and a share sheet — is #99's, and none of it belongs here + * yet. + */ + +const PHASE_LABELS: Record = { + staging: "Pausing account work and copying the database…", + hashing: "Hashing preserved media…", + translating: "Translating into the interchange format…", + packaging: "Packaging the archive…", + done: "Finished", +}; + +type ExportState = + | { status: "idle" } + | { status: "running"; progress: BlueskyArchiveExportProgress } + | { + status: "done"; + location: string; + byteLength: number; + completeness: "complete" | "incomplete"; + assets: { available: number; missing: number; unavailable: number }; + } + | { status: "failed"; message: string }; + +export type DevArchiveExportCardProps = { + accountId: number; + accountUUID: string; + palette: AccountTabPalette; +}; + +export function DevArchiveExportCard({ + accountId, + accountUUID, + palette, +}: DevArchiveExportCardProps) { + const [state, setState] = useState({ status: "idle" }); + + const exportArchive = useCallback(async () => { + setState({ + status: "running", + progress: { phase: "staging", packagedPayloads: 0, totalPayloads: 0 }, + }); + try { + const portableSettings = await getPortableBlueskySettings(accountId); + const result = await withBlueskyController( + accountId, + accountUUID, + (controller) => + controller.exportBlueskyArchive({ + exportId: `dev-${Date.now()}`, + portableSettings, + onProgress: (progress) => setState({ status: "running", progress }), + }), + ); + setState({ + status: "done", + location: result.location, + byteLength: result.byteLength, + completeness: result.metadata.completeness, + assets: result.assets, + }); + } catch (error) { + setState({ + status: "failed", + message: error instanceof Error ? error.message : String(error), + }); + } + }, [accountId, accountUUID]); + + if (!__DEV__) { + return null; + } + + return ( + + + Export a Cyd Bluesky archive (development only) + + + Writes a version 2 archive into export staging. Not available in + release builds until Bluesky archive import is proven. + + + + + {state.status === "running" ? ( + + + + {PHASE_LABELS[state.progress.phase]} + {state.progress.totalPayloads > 0 + ? ` (${state.progress.packagedPayloads}/${state.progress.totalPayloads} media)` + : ""} + + + ) : null} + + {state.status === "done" ? ( + + + {`${state.completeness} · ${(state.byteLength / 1024).toFixed(1)} KiB · ` + + `${state.assets.available} assets packaged, ` + + `${state.assets.missing + state.assets.unavailable} unavailable`} + + + {state.location} + + + ) : null} + + {state.status === "failed" ? ( + + {state.message} + + ) : null} + + ); +} + +const styles = StyleSheet.create({ + card: { + borderWidth: 1, + borderRadius: 12, + borderStyle: "dashed", + padding: 16, + gap: 8, + marginTop: 24, + }, + title: { + fontSize: 15, + fontWeight: "600", + }, + body: { + fontSize: 13, + lineHeight: 18, + }, + path: { + fontSize: 11, + fontFamily: "monospace", + }, + status: { + gap: 6, + }, +}); diff --git a/app/account/components/__tests__/dev-archive-export-card.test.tsx b/app/account/components/__tests__/dev-archive-export-card.test.tsx new file mode 100644 index 0000000..01ed65f --- /dev/null +++ b/app/account/components/__tests__/dev-archive-export-card.test.tsx @@ -0,0 +1,105 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react-native"; +import React from "react"; + +import { Colors } from "@/constants/theme"; + +import { DevArchiveExportCard } from "../DevArchiveExportCard"; + +/** + * Export must not reach people before #100 proves an archive Mobile writes can + * be read back (ADR 0004). `__DEV__` is the whole of that gate, so it is worth + * a test that fails loudly if the affordance ever renders in a release build. + */ + +const mockExportBlueskyArchive = jest.fn(); + +jest.mock("@/controllers", () => ({ + withBlueskyController: jest.fn( + ( + _accountId: number, + _accountUUID: string, + fn: (controller: { exportBlueskyArchive: jest.Mock }) => Promise, + ) => fn({ exportBlueskyArchive: mockExportBlueskyArchive }), + ), +})); + +jest.mock("@/database/accounts", () => ({ + getPortableBlueskySettings: jest.fn().mockResolvedValue({ save_posts: true }), +})); + +function renderCard() { + return render( + , + ); +} + +function setDevBuild(value: boolean): void { + (global as unknown as { __DEV__: boolean }).__DEV__ = value; +} + +describe("DevArchiveExportCard", () => { + const wasDev = (global as unknown as { __DEV__: boolean }).__DEV__; + + afterEach(() => { + setDevBuild(wasDev); + jest.clearAllMocks(); + }); + + it("renders nothing in a release build", () => { + setDevBuild(false); + + renderCard(); + + expect(screen.queryByText(/Export archive/)).toBeNull(); + }); + + it("offers export in a development build", () => { + setDevBuild(true); + + renderCard(); + + expect(screen.getByText("Export archive")).toBeTruthy(); + expect( + screen.getByText(/Not available in release builds/), + ).toBeTruthy(); + }); + + it("reports what the export produced, including what was unavailable", async () => { + setDevBuild(true); + mockExportBlueskyArchive.mockResolvedValue({ + location: "file:///staging/dev-1/cyd-bluesky-alice.example-2026-09-10.cyd", + byteLength: 2048, + metadata: { completeness: "incomplete" }, + assets: { total: 3, available: 2, missing: 1, unavailable: 0 }, + }); + + renderCard(); + fireEvent.press(screen.getByText("Export archive")); + + await waitFor(() => { + expect(screen.getByText(/incomplete/)).toBeTruthy(); + }); + expect(screen.getByText(/1 unavailable/)).toBeTruthy(); + expect( + screen.getByText(/cyd-bluesky-alice.example-2026-09-10.cyd/), + ).toBeTruthy(); + }); + + it("shows why an export failed rather than failing silently", async () => { + setDevBuild(true); + mockExportBlueskyArchive.mockRejectedValue( + new Error("Cyd could not copy this account's data for export"), + ); + + renderCard(); + fireEvent.press(screen.getByText("Export archive")); + + await waitFor(() => { + expect(screen.getByText(/could not copy this account's data/)).toBeTruthy(); + }); + }); +}); diff --git a/app/account/tabs/dashboard-tab.tsx b/app/account/tabs/dashboard-tab.tsx index 670650a..47efbca 100644 --- a/app/account/tabs/dashboard-tab.tsx +++ b/app/account/tabs/dashboard-tab.tsx @@ -9,6 +9,7 @@ import { type ImageSourcePropType, } from "react-native"; +import { DevArchiveExportCard } from "@/app/account/components/DevArchiveExportCard"; import iconBrowse from "@/assets/images/icon-browse.png"; import iconDelete from "@/assets/images/icon-delete.png"; import iconSave from "@/assets/images/icon-save.png"; @@ -61,6 +62,7 @@ const TABLET_CARD_MIN_HEIGHT = 240; export function DashboardTab({ accountId, + accountUUID, handle, palette, onSelectTab, @@ -182,6 +184,11 @@ export function DashboardTab({ ); })} + ); diff --git a/controllers/BlueskyAccountController.ts b/controllers/BlueskyAccountController.ts index 67cd07e..ef51808 100644 --- a/controllers/BlueskyAccountController.ts +++ b/controllers/BlueskyAccountController.ts @@ -14,6 +14,13 @@ import { blueskyAccountMigrations, } from "@/database/account-db"; import type { AccountDeleteSettings } from "@/database/delete-settings"; +import { + createBlueskyArchiveExportEnvironment, + runBlueskyArchiveExport, + type BlueskyArchiveExportProgress, + type BlueskyArchiveExportResult, + type PortableSettings, +} from "@/services/archive-export"; import { restoreBlueskyOAuthSession } from "@/services/bluesky-oauth"; import { BaseAccountController, @@ -1718,6 +1725,86 @@ export class BlueskyAccountController extends BaseAccountController void; + }): Promise { + const identity = await this.resolveExportIdentity(); + const accountDatabase = this.requireDb(); + + // Only undo the pause this export caused. Somebody who paused their own + // save job before exporting should still be paused afterwards. + let pausedForExport = false; + + const environment = createBlueskyArchiveExportEnvironment({ + accountDatabase, + pauseAccountWork: () => { + pausedForExport = !this.isPaused(); + if (pausedForExport) { + this.pause(); + } + }, + resumeAccountWork: () => { + if (pausedForExport) { + this.resume(); + pausedForExport = false; + } + }, + }); + + return runBlueskyArchiveExport(environment, { + exportId: options.exportId, + accountUuid: this.getAccountUUID(), + accountDid: identity.did, + accountHandle: identity.handle, + portableSettings: options.portableSettings, + onProgress: options.onProgress, + }); + } + + /** + * The identity an archive names, read without needing an agent. + */ + private async resolveExportIdentity(): Promise<{ + did: string; + handle: string | null; + }> { + if (this.did) { + return { did: this.did, handle: this.handle }; + } + + const mainDb = await getDatabase(); + const row = await mainDb.getFirstAsync<{ + did: string | null; + handle: string | null; + }>( + `SELECT b.did, b.handle + FROM account a + INNER JOIN bsky_account b ON b.id = a.bskyAccountID + WHERE a.id = ?;`, + [this.accountId], + ); + if (!row?.did) { + throw new Error( + "This account has no Bluesky DID yet, so Cyd cannot name it in an archive.", + ); + } + return { did: row.did, handle: row.handle }; + } + async deleteAccountStorage(): Promise { await this.cleanup(); try { diff --git a/database/accounts.ts b/database/accounts.ts index 1ac6d1e..55d50ef 100644 --- a/database/accounts.ts +++ b/database/accounts.ts @@ -2,6 +2,11 @@ import type { AppBskyActorDefs } from "@atproto/api"; import type { OAuthSession } from "@atproto/oauth-client"; import type { SQLiteDatabase } from "expo-sqlite"; +import { + portableSettingsFromAccountRow, + type BlueskyAccountSettingsRow, + type PortableSettings, +} from "@/services/archive-export"; import { deleteBlueskyConnection } from "@/services/bluesky-connection-store"; import { getDatabase } from "./index"; @@ -418,3 +423,28 @@ export async function getAccountHandle( ); return row?.handle ?? null; } + +/** + * Read the save and delete defaults a Cyd Bluesky archive may carry. + * + * Deliberately narrow: this row also holds schedules and identity, and a Cyd + * Bluesky archive carries neither. Only the booleans + * {@link portableSettingsFromAccountRow} recognizes leave this function. + */ +export async function getPortableBlueskySettings( + accountId: number +): Promise { + const db = await getDatabase(); + const row = await db.getFirstAsync( + `SELECT b.settingSavePosts, b.settingSaveLikes, b.settingSaveBookmarks, + b.settingSaveChats, b.settingDeletePosts, b.settingDeleteReposts, + b.settingDeleteLikes, b.settingDeleteBookmarks, b.settingDeleteChats, + b.settingDeleteUnfollowEveryone + FROM account a + INNER JOIN bsky_account b ON b.id = a.bskyAccountID + WHERE a.id = ? + LIMIT 1;`, + [accountId] + ); + return portableSettingsFromAccountRow(row); +} diff --git a/docs/bluesky-archive-fixtures.md b/docs/bluesky-archive-fixtures.md index 36a3bc4..0bcb967 100644 --- a/docs/bluesky-archive-fixtures.md +++ b/docs/bluesky-archive-fixtures.md @@ -14,71 +14,99 @@ They are also **not a superset**. Mobile cannot populate several interchange groups at all, so these fixtures exercise less of the contract than `complete.cyd` does: -| Interchange | Why Mobile leaves it empty | +| Interchange | Why Mobile leaves it empty, or fills it differently | | --- | --- | -| `relationships` block, mute | Mobile stores follows only | +| `relationships` follow, block, mute | nothing writes Mobile's `follow` table: follows are fetched live when unfollowing everyone, never saved. A Mobile fixture's `relationships` is always empty | | `profiles.avatar_asset_id`, banner | avatars are URLs, never content-addressed | | `profiles.description`, `records.indexed_at` | not stored | | captured historical profiles | `profile` is `UNIQUE(did)`, updated in place | | `records.first_observed_at` vs `observed_at` | one `savedAt` column, so both are equal | -| `assets` kind `preview`, `thumbnail` | `media_asset` is `image\|video` only | +| `assets` kind `thumbnail` | a video's own thumbnail is a URL, never preserved; link preview thumbnails *are* packaged, as `preview` | | `record_assets` owner `profile`, `message` | written only from post persistence | +| `records.created_at` of a like or repost | Mobile stores the relationship's URI but never its creation time, so this is the observation time | +| `selections` for bookmarks | Mobile has no bookmark record URI, so the selection names the bookmarked post and there is no `record_subjects` row | +| a bookmark removed at source | with no bookmark record, there is nowhere to carry its deletion state | +| a like removed at source whose URI Cyd never saw | the selection names the post, and there is no like record to carry the deletion state | +| a link preview Cyd never downloaded | no asset row at all; the URL stays in the record's external context, and it does not make the archive incomplete | +| context for a record Cyd never saved | `record_context` keeps the author the AT URI names; `context_record_uri` stays `NULL` and the URI itself survives in `records.payload_json` | +| `portable_settings.save_reposts` | Mobile has no separate switch: reposts are saved with posts | `check_account_readiness.py` reprints this list, so it stays visible at the moment it matters rather than only here. ## 1. Curate the account first -Media dominates the size; `data.db` is tens of KiB. Budget **5 MiB** for the -committed fixture, and reach it by deleting data from the test account before -exporting rather than by trimming the archive afterward — committed media -persists in repository history, so a fixture regenerated a few times over is -permanently expensive. +Media dominates the size; `data.db` compresses to a few KiB inside the archive. +Budget **5 MiB** for the committed fixture, and reach it by deleting data from +the test account before exporting rather than by trimming the archive +afterward — committed media persists in repository history, so a fixture +regenerated a few times over is permanently expensive. Aim to cover, in as few records as possible: a plain post, a reply, a quote post, a post with an external link, a post with images, a post with video, a -repost, a like, a bookmark, one chat conversation with a couple of messages, -and a follow. One or two records per category is enough — this is a semantic -fixture, not a load test. +repost, a like, a bookmark, and one chat conversation with a couple of +messages. One or two records per category is enough — this is a semantic +fixture, not a load test. Following someone will not show up: Mobile never +saves follows. -Third parties land in `relationships` and `conversation_members`. Point the -follow and the chat at a second account you control so the fixture is entirely -yours. +Everything the account liked, reposted, replied to, or quoted is somebody +else's post, and it is committed to this repository permanently. Point the +likes, reposts, and the chat at a second account you control so the fixture is +entirely yours; the account's own posts are the ones worth keeping. ## 2. Save everything, and let media finish Connect the test account in a dev build and run each save job. Media downloads continue after the records land, and a pending download silently becomes an -`unavailable` asset — which turns a fixture meant to be `complete` into an +unavailable asset — which turns a fixture meant to be `complete` into an `incomplete` one that still looks fine. -## 3. Pull the account database and check readiness +## 3. Pull the account directory and check readiness Account data lives at `/accounts/bluesky-/`, holding `data.db` -and `media/`. On Android that is: +and `media/`. Pull the whole directory, not just the database: the export reads +the preserved media too. On Android: ```bash adb exec-out run-as systems.lockdown.cydmobile \ - cat files/accounts/bluesky-/data.db > /tmp/data.db + tar c files/accounts/bluesky- | tar x -C /tmp/cyd-fixture-account --strip-components=2 +adb exec-out run-as systems.lockdown.cydmobile cat files/main.db > /tmp/cyd-fixture-account/main.db ``` -On an iOS simulator it is under +On an iOS simulator the same directory is under `~/Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Documents/`. +`main.db` is optional but worth pulling: it is where the account's DID and its +save and delete defaults live, and passing it means the fixture's portable +settings are the account's real ones. + ```bash -npm run check:account-readiness -- /tmp/data.db +npm run check:account-readiness -- /tmp/cyd-fixture-account/data.db ``` It reports category coverage, context coverage, media download state, and the projected fixture size, and exits non-zero when the account is not ready. -## 4. Export, then check conformance +## 4. Export the complete fixture -Export through Mobile's v2 writer, then — before trusting the result — check it -against the pinned contract rather than against Mobile's own idea of the format: +`npm run export:archive` runs Mobile's own version 2 writer over the pulled +copy (ADR 0016), so the fixture is what the app itself would have produced: ```bash -npm run check:archive-conformance -- path/to/complete.cyd +npm run export:archive -- /tmp/cyd-fixture-account \ + --main-db /tmp/cyd-fixture-account/main.db \ + --out testUtils/fixtures/bluesky-archive/complete.cyd +``` + +Without `--main-db`, pass `--did` (and optionally `--handle`); the account UUID +is read from the directory name. The command prints a provenance block to paste +into this file. + +Then check the result against the pinned contract rather than against Mobile's +own idea of the format: + +```bash +npm run check:archive-conformance -- testUtils/fixtures/bluesky-archive/complete.cyd ``` This matters more than usual right now: Mobile builds its writer before the @@ -88,15 +116,40 @@ that enshrines its bugs. ## 5. Produce the incomplete variant -`incomplete.cyd` differs from `complete.cyd` by one unavailable asset. Get there -by failing a single download rather than by damaging the account — set one -`media_asset` row to `downloadState = 'failed'` and export again. The result -must report `completeness: incomplete`, keep every other record intact, and -still pass conformance. +`incomplete.cyd` differs from `complete.cyd` by one unavailable asset. Get +there by failing a single download rather than by damaging the account or +editing the archive, so every other record and payload stays identical: + +```bash +npm run export:archive -- /tmp/cyd-fixture-account \ + --main-db /tmp/cyd-fixture-account/main.db \ + --fail-asset \ + --out testUtils/fixtures/bluesky-archive/incomplete.cyd +``` + +`--fail-asset` marks that one `media_asset` row failed for the length of the +export and puts it back afterwards, and only ever touches the pulled copy. Pick +the largest payload, since leaving it out is also what keeps the incomplete +fixture small. The result must report `completeness: incomplete`, keep every +other record intact, and still pass conformance. + +Pass **the same `--created-at` to both exports**. An export stamps anything it +captured that has no time of its own — a profile known only by its DID — with +the moment it ran, so without a pinned timestamp the pair differs by the clock +as well as by the asset. ## 6. Commit with provenance Record alongside the fixtures: which test account produced them, the app version and commit, the date, which records were curated in, and the steps to regenerate. A fixture nobody can regenerate becomes unchangeable the moment the -contract moves. +contract moves. `testUtils/fixtures/bluesky-archive/README.md` is where that +goes. + +## Exporting from the app instead + +The dashboard carries a development-only export card in `__DEV__` builds +(ADR 0004). It writes the same archive through the same writer, into +`/archive-export//`, and prints the path. Pulling that +file works too — but every fix then costs a device round trip, which is why the +fixtures are made from a pulled copy instead. diff --git a/package-lock.json b/package-lock.json index d173e3e..9c16a3c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -78,6 +78,7 @@ "react-native-svg-transformer": "^1.5.3", "react-test-renderer": "19.2.3", "tsconfig": "^7.0.0", + "tsx": "^4.23.13", "typescript": "~6.0.3", "typescript-eslint": "^8.62.1" } @@ -2468,6 +2469,448 @@ "tslib": "^2.4.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.9.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", @@ -8957,6 +9400,48 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -18857,6 +19342,25 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/tsx": { + "version": "4.23.13", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.13.tgz", + "integrity": "sha512-BL5MGkRln6aDYhb0xbQlEAGw743BaZYWdbWtdJOBriYJboKgUUYCadFp2/FpBBZquBC/ezNBn7wMMPx7FDZUDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index 61b663c..0d5e16f 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "test:archive-conformance": "python3 scripts/archive-contract/self_test.py", "check:archive-conformance": "python3 scripts/archive-contract/conformance.py", "check:account-readiness": "python3 scripts/dev/check_account_readiness.py", + "export:archive": "tsx scripts/dev/export-fixture.ts", "test:watch": "jest --watch", "test:coverage": "jest --coverage" }, @@ -95,6 +96,7 @@ "react-native-svg-transformer": "^1.5.3", "react-test-renderer": "19.2.3", "tsconfig": "^7.0.0", + "tsx": "^4.23.13", "typescript": "~6.0.3", "typescript-eslint": "^8.62.1" }, diff --git a/plugins/__tests__/android-backup-rules.test.ts b/plugins/__tests__/android-backup-rules.test.ts index 5cd1c51..3418172 100644 --- a/plugins/__tests__/android-backup-rules.test.ts +++ b/plugins/__tests__/android-backup-rules.test.ts @@ -116,6 +116,19 @@ describe("android-backup-rules plugin", () => { } }); + it("keeps in-progress archive export staging out of every backup path", () => { + // A half-written archive is working state, and the account data it is + // built from is backed up on its own. + const [cloudBackup, deviceTransfer] = + DATA_EXTRACTION_RULES_XML.split(""); + + for (const rules of [BACKUP_RULES_XML, cloudBackup, deviceTransfer]) { + expect(rules).toContain( + '', + ); + } + }); + it("mirrors the cloud rules on Android 11 and lower", () => { // full-backup-content has no device-transfer path. expect(BACKUP_RULES_XML).toContain( diff --git a/plugins/android-backup-rules.js b/plugins/android-backup-rules.js index 7eaf1b5..df7213d 100644 --- a/plugins/android-backup-rules.js +++ b/plugins/android-backup-rules.js @@ -29,11 +29,11 @@ * with a hardware-backed Keystore key that never leaves the device, so a * restored copy would be undecryptable. * - * Archive import staging is excluded everywhere too. It lives in durable - * storage so an interrupted import can resume (ADR 0006), but it is - * half-unpacked working state: backing it up would inflate every backup with - * data the committed account already holds, and restore it onto a device where - * the import it belonged to no longer exists. + * Archive import and export staging are excluded everywhere too. Both live in + * durable storage so an interrupted job can resume (ADR 0006), but both are + * working state: backing them up would inflate every backup with data the + * committed account already holds, and restore it onto a device where the job + * it belonged to no longer exists. */ const { withAndroidManifest, withDangerousMod } = require("expo/config-plugins"); const fs = require("fs"); @@ -59,6 +59,13 @@ const SECURE_STORE_PREFS = "SecureStore"; */ const ARCHIVE_STAGING_PATH = "archive-intake"; +/** + * In-progress Bluesky archive export staging, under the `file` domain. Kept + * out of every backup path for the same reasons as import staging. Mirrors + * `ARCHIVE_EXPORT_DIRECTORY` in services/device-storage.ts. + */ +const ARCHIVE_EXPORT_PATH = "archive-export"; + const BACKUP_RULES_XML = ` @@ -68,6 +75,7 @@ const BACKUP_RULES_XML = ` + `; @@ -82,6 +90,7 @@ const DATA_EXTRACTION_RULES_XML = ` + @@ -90,6 +99,7 @@ const DATA_EXTRACTION_RULES_XML = ` + `; @@ -166,3 +176,4 @@ module.exports = withAndroidBackupRules; module.exports.BACKUP_RULES_XML = BACKUP_RULES_XML; module.exports.DATA_EXTRACTION_RULES_XML = DATA_EXTRACTION_RULES_XML; module.exports.ARCHIVE_STAGING_PATH = ARCHIVE_STAGING_PATH; +module.exports.ARCHIVE_EXPORT_PATH = ARCHIVE_EXPORT_PATH; diff --git a/scripts/archive-contract/test_bundle.py b/scripts/archive-contract/test_bundle.py index e35e9aa..e43d283 100644 --- a/scripts/archive-contract/test_bundle.py +++ b/scripts/archive-contract/test_bundle.py @@ -21,6 +21,8 @@ "fixtures/complete.cyd", "fixtures/incomplete.cyd", "fixtures/semantic-expectations.json", + # Mobile's writer embeds this file; the test compares the two. + "schema.sql", ) diff --git a/scripts/dev/check_account_readiness.py b/scripts/dev/check_account_readiness.py index b22c18c..004c73a 100755 --- a/scripts/dev/check_account_readiness.py +++ b/scripts/dev/check_account_readiness.py @@ -23,14 +23,20 @@ # Interchange groups Mobile cannot populate today, so a fixture exported from # Mobile is a complement to the canonical fixtures rather than a superset. KNOWN_GAPS = ( - ("relationships (block, mute)", "Mobile stores follows only"), + ("relationships (follow, block, mute)", "nothing writes the follow table; follows are fetched live to unfollow"), ("profiles.avatar_asset_id / banner", "avatars are URLs, never content-addressed"), ("profiles.description", "not stored"), ("captured historical profiles", "profile is UNIQUE(did), updated in place"), ("records.first_observed_at vs observed_at", "one savedAt column"), ("records.indexed_at", "not stored"), - ("assets kind preview / thumbnail", "media_asset is image|video only"), + ("assets kind thumbnail", "a video's own thumbnail is a URL, never preserved"), ("record_assets owner profile / message", "written only from post persistence"), + ("created_at of a like or repost", "no creation time stored, so it is the observation time"), + ("record_subjects for bookmarks", "no bookmark record URI, so the selection names the post"), + ("deletion state of a removed bookmark", "no bookmark record to carry it"), + ("deletion state of a like whose URI Cyd never saw", "no like record to carry it"), + ("context for records Cyd never saved", "author DID only; the URI stays in payload_json"), + ("portable_settings.save_reposts", "reposts are saved with posts, with no separate switch"), ) @@ -66,12 +72,13 @@ def main() -> int: print("Selected-record coverage") counts = { "posts": "SELECT COUNT(*) FROM post WHERE isRepost = 0", - "reposts": "SELECT COUNT(*) FROM post WHERE isRepost = 1", + # Matches what the writer exports: a repost record of its own, or a + # post the account reposted. + "reposts": "SELECT COUNT(*) FROM post WHERE isRepost = 1 OR viewerReposted = 1", "likes": "SELECT COUNT(*) FROM post WHERE viewerLiked = 1", "bookmarks": "SELECT COUNT(*) FROM bookmark", "chats": "SELECT COUNT(*) FROM conversation", "messages": "SELECT COUNT(*) FROM message", - "follows": "SELECT COUNT(*) FROM follow", } for label, query in counts.items(): total = scalar(database, query) @@ -117,22 +124,29 @@ def main() -> int: for missing in {"image", "video"} - present: problems.append(f"no preserved {missing} — the fixture will not exercise {missing} payloads") - media_bytes = scalar( - database, - "SELECT COALESCE(SUM(byteLength), 0) FROM media_asset WHERE downloadState = 'complete'", - ) - projected = media_bytes + arguments.database.stat().st_size - print(f"\nProjected fixture size (uncompressed): {human(projected)}") - if projected > SIZE_BUDGET_BYTES: + # Media is stored uncompressed in the archive and dominates its size, while + # data.db deflates to a few KiB. `media_asset.byteLength` is often NULL, so + # the files themselves are the reliable measure. + media_dir = arguments.media_dir or arguments.database.parent / "media" + if media_dir.is_dir(): + media_bytes = sum(f.stat().st_size for f in media_dir.rglob("*") if f.is_file()) + source = str(media_dir) + else: + media_bytes = scalar( + database, + "SELECT COALESCE(SUM(byteLength), 0) FROM media_asset " + "WHERE downloadState = 'complete'", + ) + source = "media_asset.byteLength (no media directory alongside the database)" + + print(f"\nProjected fixture size: {human(media_bytes)} of media, plus a compressed data.db") + print(f" measured from {source}") + if media_bytes > SIZE_BUDGET_BYTES: problems.append( - f"projected fixture is {human(projected)}, over the {human(SIZE_BUDGET_BYTES)} budget — " + f"projected fixture is {human(media_bytes)}, over the {human(SIZE_BUDGET_BYTES)} budget — " "curate the account further before exporting" ) - if arguments.media_dir: - on_disk = sum(f.stat().st_size for f in arguments.media_dir.rglob("*") if f.is_file()) - print(f"Media directory on disk: {human(on_disk)}") - print("\nInterchange groups Mobile cannot populate (expected to be empty)") for group, reason in KNOWN_GAPS: print(f" {group} — {reason}") diff --git a/scripts/dev/export-fixture.ts b/scripts/dev/export-fixture.ts new file mode 100644 index 0000000..cb68155 --- /dev/null +++ b/scripts/dev/export-fixture.ts @@ -0,0 +1,241 @@ +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import { runBlueskyArchiveExport } from "@/services/archive-export/export"; +import { portableSettingsFromAccountRow } from "@/services/archive-export/portable-settings"; + +import { createNodeBlueskyArchiveExportEnvironment } from "./node-export-environment"; + +/** + * Export a pulled Bluesky account directory as a Cyd Bluesky archive. + * + * This is how the committed real-data fixtures are made (ADR 0016). It runs + * Mobile's own version 2 writer over a copy of a curated test account, so the + * fixtures carry real facets, CIDs, media bytes, and identifiers rather than + * anything generated. See `docs/bluesky-archive-fixtures.md`. + * + * Usage: + * npm run export:archive -- --out [options] + * + * --out Where to write the archive. Required. + * --main-db Cyd's main database, for portable settings and DID. + * --did Account DID, if there is no main database to read. + * --uuid Account UUID; defaults to the directory's own suffix. + * --handle Handle, used only to suggest a filename. + * --fail-asset Mark one asset's download failed for this export, to + * produce the `incomplete` fixture. The change is + * reverted afterwards, and only ever touches the copy. + * --created-at Pin the export time. Pass the same value to both + * fixtures so the pair differs by the failed asset + * alone, rather than also by the clock: an export + * timestamps anything it captured with no time of its + * own, such as a profile known only by its DID. + */ + +type Options = { + accountDirectory: string; + out: string; + mainDatabase: string | null; + did: string | null; + uuid: string | null; + handle: string | null; + failAsset: string | null; + createdAt: Date | null; +}; + +function parseOptions(argv: string[]): Options { + const positional: string[] = []; + const flags = new Map(); + + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (argument.startsWith("--")) { + flags.set(argument.slice(2), argv[index + 1] ?? ""); + index += 1; + } else { + positional.push(argument); + } + } + + const accountDirectory = positional[0]; + const out = flags.get("out"); + if (!accountDirectory || !out) { + throw new Error( + "Usage: export-fixture.ts --out [--main-db ] [--did ] [--fail-asset ]", + ); + } + + return { + accountDirectory: path.resolve(accountDirectory), + out: path.resolve(out), + mainDatabase: flags.get("main-db") ? path.resolve(flags.get("main-db")!) : null, + did: flags.get("did") ?? null, + uuid: flags.get("uuid") ?? null, + handle: flags.get("handle") ?? null, + failAsset: flags.get("fail-asset") ?? null, + createdAt: flags.get("created-at") ? new Date(flags.get("created-at")!) : null, + }; +} + +type AccountIdentity = { + did: string; + uuid: string; + handle: string | null; + settings: ReturnType; +}; + +/** + * Work out who this account is. + * + * Cyd keeps identity and settings in its main database rather than in the + * account directory, so a pulled `main.db` is the best source. Without one, + * the DID has to be supplied: guessing it from a directory name would put a + * wrong identity into a fixture every later reader is tested against. + */ +function resolveIdentity(options: Options): AccountIdentity { + const uuid = + options.uuid ?? path.basename(options.accountDirectory).replace(/^bluesky-/, ""); + + if (!options.mainDatabase) { + if (!options.did) { + throw new Error("Pass --main-db or --did so the archive names an identity."); + } + return { did: options.did, uuid, handle: options.handle, settings: {} }; + } + + const main = new DatabaseSync(options.mainDatabase, { readOnly: true }); + try { + const row = main + .prepare( + `SELECT b.* FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ? LIMIT 1;`, + ) + .get(uuid) as Record | undefined; + if (!row) { + throw new Error(`No account with UUID ${uuid} in ${options.mainDatabase}`); + } + return { + did: options.did ?? (row.did as string), + uuid, + handle: options.handle ?? ((row.handle as string) ?? null), + settings: portableSettingsFromAccountRow(row), + }; + } finally { + main.close(); + } +} + +/** + * Fail one download for the length of this export. + * + * The `incomplete` fixture differs from the `complete` one by a single + * unavailable asset. Getting there by failing a download, rather than by + * deleting media or hand-editing the archive, keeps every other record and + * payload byte-for-byte the same as its complete counterpart. + */ +function withFailedAsset(options: Options, run: () => T): T { + if (!options.failAsset) { + return run(); + } + + const database = new DatabaseSync(path.join(options.accountDirectory, "data.db")); + const previous = database + .prepare("SELECT downloadState FROM media_asset WHERE contentCid = ?;") + .get(options.failAsset) as { downloadState: string } | undefined; + if (!previous) { + database.close(); + throw new Error(`No media_asset with contentCid ${options.failAsset}`); + } + + database + .prepare( + "UPDATE media_asset SET downloadState = 'failed', lastError = ? WHERE contentCid = ?;", + ) + .run("Download failed while saving.", options.failAsset); + database.close(); + + try { + return run(); + } finally { + const restore = new DatabaseSync(path.join(options.accountDirectory, "data.db")); + restore + .prepare( + "UPDATE media_asset SET downloadState = ?, lastError = NULL WHERE contentCid = ?;", + ) + .run(previous.downloadState, options.failAsset); + restore.close(); + } +} + +function currentCommit(): string { + try { + return execFileSync("git", ["rev-parse", "--short", "HEAD"], { + encoding: "utf8", + }).trim(); + } catch { + return "unknown"; + } +} + +async function main(): Promise { + const options = parseOptions(process.argv.slice(2)); + const identity = resolveIdentity(options); + const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-export-fixture-")); + + const result = await withFailedAsset(options, async () => { + const environment = createNodeBlueskyArchiveExportEnvironment({ + accountDirectory: options.accountDirectory, + stagingRoot: path.join(workspace, "staging"), + ...(options.createdAt ? { now: () => options.createdAt as Date } : {}), + }); + return runBlueskyArchiveExport(environment, { + exportId: "fixture", + accountUuid: identity.uuid, + accountDid: identity.did, + accountHandle: identity.handle, + portableSettings: identity.settings, + fileName: path.basename(options.out), + onProgress: (progress) => + process.stderr.write( + `\r${progress.phase.padEnd(12)} ${progress.packagedPayloads}/${progress.totalPayloads} payloads`, + ), + }); + }); + + fs.mkdirSync(path.dirname(options.out), { recursive: true }); + fs.copyFileSync(result.location, options.out); + result.staging.destroy(); + fs.rmSync(workspace, { recursive: true, force: true }); + + const kib = (result.byteLength / 1024).toFixed(1); + process.stderr.write("\r".padEnd(60) + "\r"); + console.log(`Wrote ${options.out} (${kib} KiB)`); + console.log(` completeness ${result.metadata.completeness}`); + console.log( + ` assets ${result.assets.available} available, ` + + `${result.assets.missing} missing, ${result.assets.unavailable} unavailable`, + ); + console.log(""); + console.log("Provenance, for docs/bluesky-archive-fixtures.md:"); + console.log(` account ${identity.handle ?? "(unknown handle)"} (${identity.did})`); + console.log(` uuid ${identity.uuid}`); + console.log(` exported ${result.metadata.createdAt}`); + console.log(` cyd-mobile ${currentCommit()}`); + console.log(""); + console.log(`Check it against the pinned contract before committing it:`); + console.log(` npm run check:archive-conformance -- ${options.out}`); + + return 0; +} + +main().then( + (code) => process.exit(code), + (error) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); + }, +); diff --git a/scripts/dev/node-export-environment.ts b/scripts/dev/node-export-environment.ts new file mode 100644 index 0000000..4d1a304 --- /dev/null +++ b/scripts/dev/node-export-environment.ts @@ -0,0 +1,175 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import type { + BlueskyArchiveExportEnvironment, + ExportStagingArea, + ReadableDatabase, + WritableDatabase, +} from "@/services/archive-export"; + +/** + * The Cyd Bluesky archive export ports, backed by Node instead of a phone. + * + * ADR 0016 says Mobile's real-data fixtures are produced by exporting a + * curated test account *through Mobile's own writer*. This is what makes that + * possible without a device round trip for every fix: the writer, the + * translation, and the packaging are the same code the app runs, and only the + * four things a phone does differently — SQLite, files, hashing, and pausing + * account work — are supplied from here. + * + * It works on a copy of an account directory pulled off a device, so there is + * no live account to pause and no way for anything it does to reach one. + */ + +export type NodeExportEnvironmentOptions = { + /** A pulled `accounts/bluesky-/` directory: `data.db` and `media/`. */ + accountDirectory: string; + /** Where export staging directories are created. */ + stagingRoot: string; + /** Runs after the staging pause, standing in for saving resuming. */ + onAccountWorkResumed?: () => void; + now?: () => Date; +}; + +class DirectoryStagingArea implements ExportStagingArea { + readonly root: string; + + constructor(root: string) { + this.root = root; + fs.mkdirSync(root, { recursive: true }); + } + + createFile(relativePath: string) { + const location = this.locate(relativePath); + fs.mkdirSync(path.dirname(location), { recursive: true }); + const handle = fs.openSync(location, "w"); + return { + write: (chunk: Uint8Array) => { + fs.writeSync(handle, chunk); + }, + close: () => fs.closeSync(handle), + }; + } + + locate(relativePath: string): string { + return path.join(this.root, relativePath); + } + + destroy(): void { + fs.rmSync(this.root, { recursive: true, force: true }); + } +} + +function asReadableDatabase(database: DatabaseSync): ReadableDatabase { + return { + all(sql: string): T[] { + return database.prepare(sql).all() as T[]; + }, + close: () => database.close(), + }; +} + +function asWritableDatabase(database: DatabaseSync): WritableDatabase { + return { + exec: (sql) => database.exec(sql), + run: (sql, params) => { + database.prepare(sql).run(...(params as never[])); + }, + close: () => database.close(), + }; +} + +export function createNodeBlueskyArchiveExportEnvironment( + options: NodeExportEnvironmentOptions, +): BlueskyArchiveExportEnvironment { + const accountDatabase = path.join(options.accountDirectory, "data.db"); + const mediaDirectory = path.join(options.accountDirectory, "media"); + + /** + * Find a file a device recorded by its own absolute path. + * + * `media_asset.localPath` is a URI from the phone's filesystem, which does + * not exist here. Preserved media is content-addressed by filename, so the + * last path segment is enough to find it in the pulled copy. + */ + const resolve = (location: string): string => { + const withoutScheme = location.startsWith("file://") + ? decodeURI(location.slice("file://".length)) + : location; + if (fs.existsSync(withoutScheme)) { + return withoutScheme; + } + return path.join(mediaDirectory, path.basename(withoutScheme)); + }; + + return { + openStaging: (exportId) => + new DirectoryStagingArea(path.join(options.stagingRoot, exportId)), + + async withAccountWorkPaused(work) { + const result = await work(); + options.onAccountWorkResumed?.(); + return result; + }, + + async snapshotAccountDatabase(staging, relativePath) { + const source = new DatabaseSync(accountDatabase, { readOnly: true }); + try { + const destination = staging.locate(relativePath); + fs.rmSync(destination, { force: true }); + source.prepare("VACUUM INTO ?").run(destination); + } finally { + source.close(); + } + }, + + openSnapshot: (staging, relativePath) => + asReadableDatabase( + new DatabaseSync(staging.locate(relativePath), { readOnly: true }), + ), + + createBlueskyInterchangeDatabase: (staging, relativePath) => { + const location = staging.locate(relativePath); + fs.rmSync(location, { force: true }); + return asWritableDatabase(new DatabaseSync(location)); + }, + + statFile: (location) => { + const resolved = resolve(location); + return fs.existsSync(resolved) + ? { byteLength: fs.statSync(resolved).size } + : null; + }, + + async readFile(location, onBytes) { + const handle = fs.openSync(resolve(location), "r"); + try { + const buffer = Buffer.alloc(256 * 1024); + while (true) { + const read = fs.readSync(handle, buffer, 0, buffer.length, null); + if (read === 0) { + break; + } + onBytes(new Uint8Array(buffer.subarray(0, read))); + } + } finally { + fs.closeSync(handle); + } + }, + + createHasher: () => { + const hash = crypto.createHash("sha256"); + return { + update: (chunk) => { + hash.update(chunk); + }, + digestHex: () => hash.digest("hex"), + }; + }, + + now: options.now ?? (() => new Date()), + }; +} diff --git a/services/__tests__/archive-contract-bundle.test.ts b/services/__tests__/archive-contract-bundle.test.ts index 18790d7..a4c2983 100644 --- a/services/__tests__/archive-contract-bundle.test.ts +++ b/services/__tests__/archive-contract-bundle.test.ts @@ -6,6 +6,7 @@ import { createTestBlueskyArchiveIntakeEnvironment, } from "@/testUtils/archiveFixtures"; +import { BLUESKY_ARCHIVE_V2_SCHEMA_SQL } from "../archive-export"; import { classifyBlueskyArchiveMetadata } from "../archive-metadata"; import { runBlueskyArchiveIntake, @@ -105,6 +106,16 @@ contractDescribe("pinned canonical Cyd Bluesky archive bundle", () => { }, ); + it("writes the pinned interchange schema, character for character", () => { + // Mobile's writer carries its own copy of schema.sql, because a phone + // cannot fetch the contract mid-export. A copy nobody compares is a fork, + // so this is the comparison: if cyd changes the schema, the pin bump has + // to bring the new text with it. + expect(BLUESKY_ARCHIVE_V2_SCHEMA_SQL).toBe( + fs.readFileSync(path.join(root, "schema.sql"), "utf8"), + ); + }); + it("matches the canonical version rejection outcomes", () => { const expectations = readExpectations(root); const input = JSON.parse( diff --git a/services/__tests__/device-storage.test.ts b/services/__tests__/device-storage.test.ts index cfaa6c1..626f239 100644 --- a/services/__tests__/device-storage.test.ts +++ b/services/__tests__/device-storage.test.ts @@ -1,5 +1,7 @@ import { + ARCHIVE_EXPORT_DIRECTORY, ARCHIVE_STAGING_DIRECTORY, + getArchiveExportStagingRoot, getArchiveStagingRoot, getBackupEligibleDataRoot, } from "../device-storage"; @@ -8,6 +10,7 @@ import { // eslint-disable-next-line @typescript-eslint/no-require-imports const backupRules = require("@/plugins/android-backup-rules") as { ARCHIVE_STAGING_PATH: string; + ARCHIVE_EXPORT_PATH: string; }; describe("device storage backup boundaries", () => { @@ -26,4 +29,14 @@ describe("device storage backup boundaries", () => { it("stages archive imports where Android backup rules exclude them", () => { expect(ARCHIVE_STAGING_DIRECTORY).toBe(backupRules.ARCHIVE_STAGING_PATH); }); + + it("assembles archive exports in durable storage so they can resume", () => { + expect(getArchiveExportStagingRoot()).toBe( + "file:///mock/document/directory/archive-export/", + ); + }); + + it("stages archive exports where Android backup rules exclude them", () => { + expect(ARCHIVE_EXPORT_DIRECTORY).toBe(backupRules.ARCHIVE_EXPORT_PATH); + }); }); diff --git a/services/archive-export/__tests__/export.test.ts b/services/archive-export/__tests__/export.test.ts new file mode 100644 index 0000000..60a0bcc --- /dev/null +++ b/services/archive-export/__tests__/export.test.ts @@ -0,0 +1,602 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import { unzipSync } from "fflate"; + +import { + applyAccountMigrations, + blueskyAccountMigrations, +} from "@/database/account-db"; +import { createNodeBlueskyArchiveExportEnvironment } from "@/scripts/dev/node-export-environment"; +import { runBlueskyArchiveIntake } from "@/services/archive-import"; +import { classifyBlueskyArchiveMetadata } from "@/services/archive-metadata"; +import { + createMemoryByteReader, + createTestBlueskyArchiveIntakeEnvironment, +} from "@/testUtils/archiveFixtures"; + +import { runBlueskyArchiveExport } from "../export"; + +/** + * End-to-end export against a real Bluesky account database. + * + * The account is built by running Mobile's own migrations, so this fails if the + * writer ever drifts from the runtime schema it translates, and the archive is + * inspected as bytes and SQLite rather than through the writer's own types. + */ + +const ACCOUNT_DID = "did:plc:alice"; +const ACCOUNT_UUID = "018d5f7a-9b3c-7d10-8a2e-1f4c6b8d0e12"; +const OTHER_DID = "did:plc:bob"; +const POST_URI = `at://${ACCOUNT_DID}/app.bsky.feed.post/one`; +const LIKED_URI = `at://${OTHER_DID}/app.bsky.feed.post/liked`; +const SAVED_AT = Date.UTC(2026, 8, 1, 12, 0, 0); + +type Account = { + directory: string; + database: DatabaseSync; + mediaDirectory: string; +}; + +function createAccount(root: string): Account { + const directory = path.join(root, `bluesky-${ACCOUNT_UUID}`); + const mediaDirectory = path.join(directory, "media"); + fs.mkdirSync(mediaDirectory, { recursive: true }); + + const database = new DatabaseSync(path.join(directory, "data.db")); + applyAccountMigrations( + { + getFirstSync: (sql: string) => database.prepare(sql).get() as T | null, + execSync: (sql: string) => database.exec(sql), + withTransactionSync: (run: () => void) => { + database.exec("BEGIN;"); + try { + run(); + database.exec("COMMIT;"); + } catch (error) { + database.exec("ROLLBACK;"); + throw error; + } + }, + }, + blueskyAccountMigrations, + ); + + return { directory, database, mediaDirectory }; +} + +function writeMedia(account: Account, name: string, contents: string): string { + const location = path.join(account.mediaDirectory, name); + fs.writeFileSync(location, contents); + // Devices record an absolute URI that does not exist on this machine, which + // is exactly what a pulled account directory looks like. + return `file:///data/user/0/systems.lockdown.cydmobile/files/accounts/bluesky-${ACCOUNT_UUID}/media/${name}`; +} + +const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +function writeMediaBytes(account: Account, name: string, bytes: Uint8Array): string { + fs.writeFileSync(path.join(account.mediaDirectory, name), bytes); + return `file:///data/user/0/systems.lockdown.cydmobile/files/accounts/bluesky-${ACCOUNT_UUID}/media/${name}`; +} + +function run(database: DatabaseSync, sql: string, params: unknown[] = []): void { + database.prepare(sql).run(...(params as never[])); +} + +function seedAccount(account: Account): void { + const { database } = account; + + for (const [did, handle] of [ + [ACCOUNT_DID, "alice.example"], + [OTHER_DID, "bob.example"], + ]) { + run( + database, + `INSERT INTO profile (did, handle, displayName, avatarUrl, savedAt, updatedAt) + VALUES (?, ?, ?, ?, ?, ?);`, + [did, handle, handle, "https://cdn.example/avatar", SAVED_AT, SAVED_AT], + ); + } + + run( + database, + `INSERT INTO post (uri, cid, authorDid, text, langs, isReply, isQuote, isRepost, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, viewerReposted, viewerBookmarked, + createdAt, savedAt) + VALUES (?, ?, ?, ?, 'en', 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, ?, ?);`, + [POST_URI, "bafypost", ACCOUNT_DID, "A post with pictures", "2026-08-30T09:00:00.000Z", SAVED_AT], + ); + run( + database, + `INSERT INTO post (uri, cid, authorDid, text, isReply, isQuote, isRepost, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, likeUri, viewerReposted, viewerBookmarked, + createdAt, savedAt) + VALUES (?, ?, ?, ?, 0, 0, 0, 0, 0, 0, 0, 1, ?, 0, 1, ?, ?);`, + [ + LIKED_URI, + "bafyliked", + OTHER_DID, + "Somebody else's post", + `at://${ACCOUNT_DID}/app.bsky.feed.like/one`, + "2026-08-20T09:00:00.000Z", + SAVED_AT, + ], + ); + + run( + database, + `INSERT INTO post_external (postUri, uri, title, description, thumbUrl, thumbLocalPath) + VALUES (?, 'https://example.com/story', 'A story', 'Something happened', + 'https://cdn.example/thumb.png', ?);`, + [POST_URI, writeMediaBytes(account, "external-thumb", PNG_HEADER)], + ); + + run( + database, + `INSERT INTO bookmark (subjectUri, postAuthorDid, postAuthorHandle, postText, + postCreatedAt, savedAt) + VALUES (?, ?, 'bob.example', ?, '2026-08-20T09:00:00.000Z', ?);`, + [LIKED_URI, OTHER_DID, "Somebody else's post", SAVED_AT], + ); + + run( + database, + `INSERT INTO follow (uri, cid, subjectDid, handle, createdAt, savedAt) + VALUES (?, 'bafyfollow', ?, 'bob.example', '2026-07-01T09:00:00.000Z', ?);`, + [`at://${ACCOUNT_DID}/app.bsky.graph.follow/bob`, OTHER_DID, SAVED_AT], + ); + + run( + database, + `INSERT INTO conversation (convoId, rev, memberDids, savedAt, updatedAt) + VALUES ('convo-1', 'rev-1', ?, ?, ?);`, + [JSON.stringify([ACCOUNT_DID, OTHER_DID]), SAVED_AT, SAVED_AT], + ); + run( + database, + `INSERT INTO message (messageId, convoId, rev, senderDid, text, sentAt, savedAt) + VALUES ('message-1', 'convo-1', 'rev-1', ?, 'Hello there', '2026-08-31T09:00:00.000Z', ?);`, + [OTHER_DID, SAVED_AT], + ); + + // Things a Cyd Bluesky archive must never carry. + run(database, `INSERT INTO config (key, value) VALUES ('session', ?);`, [ + "SUPERSECRETSESSION", + ]); + run( + database, + `INSERT INTO job (jobType, status, scheduledAt, progressJSON) + VALUES ('save', 'completed', ?, ?);`, + [SAVED_AT, '{"note":"SUPERSECRETJOB"}'], + ); +} + +function addMedia( + account: Account, + options: { + contentCid: string; + postUri: string; + position: number; + fileName: string; + contents: string; + downloadState?: string; + mediaType?: string; + }, +): void { + const localPath = + options.downloadState === "failed" + ? null + : writeMedia(account, options.fileName, options.contents); + run( + account.database, + `INSERT INTO media_asset (contentCid, mediaType, mimeType, byteLength, localPath, + sourceUrl, sourceDid, downloadState, downloadedAt) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + options.contentCid, + options.mediaType ?? "image", + options.mediaType === "video" ? "video/mp4" : "image/jpeg", + options.contents.length, + localPath, + `https://cdn.example/${options.contentCid}`, + ACCOUNT_DID, + options.downloadState ?? "complete", + SAVED_AT, + ], + ); + run( + account.database, + `INSERT INTO post_media (postUri, position, mediaType, blobCid, mimeType, alt, + width, height, assetCid) + VALUES (?, ?, ?, ?, ?, 'Alt text', 800, 600, ?);`, + [ + options.postUri, + options.position, + options.mediaType ?? "image", + options.contentCid, + options.mediaType === "video" ? "video/mp4" : "image/jpeg", + options.contentCid, + ], + ); +} + +type ExportedArchive = { + entries: Record; + database: DatabaseSync; + metadata: Record; + manifest: { algorithm: string; payloads: { path: string; bytes: number; sha256: string }[] }; + bytes: Uint8Array; +}; + +function openArchive(location: string, workspace: string): ExportedArchive { + const bytes = new Uint8Array(fs.readFileSync(location)); + const entries = unzipSync(bytes); + const extracted = path.join(workspace, "extracted.db"); + fs.writeFileSync(extracted, entries["data.db"]); + return { + entries, + bytes, + database: new DatabaseSync(extracted, { readOnly: true }), + metadata: JSON.parse(new TextDecoder().decode(entries["metadata.json"])), + manifest: JSON.parse(new TextDecoder().decode(entries["manifest.json"])), + }; +} + +async function exportAccount( + account: Account, + options: { onAccountWorkResumed?: () => void } = {}, +) { + const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-export-test-")); + const environment = createNodeBlueskyArchiveExportEnvironment({ + accountDirectory: account.directory, + stagingRoot: path.join(workspace, "staging"), + now: () => new Date("2026-09-10T00:00:00.000Z"), + onAccountWorkResumed: options.onAccountWorkResumed, + }); + + const result = await runBlueskyArchiveExport(environment, { + exportId: "export-1", + accountUuid: ACCOUNT_UUID, + accountDid: ACCOUNT_DID, + accountHandle: "alice.example", + portableSettings: { save_posts: true, save_likes: true, delete_posts: false }, + }); + + return { result, archive: openArchive(result.location, workspace), workspace }; +} + +describe("runBlueskyArchiveExport", () => { + let root: string; + let account: Account; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-account-")); + account = createAccount(root); + seedAccount(account); + }); + + afterEach(() => { + account.database.close(); + fs.rmSync(root, { recursive: true, force: true }); + }); + + it("packages an account as an archive Cyd's own reader recognizes", async () => { + addMedia(account, { + contentCid: "bafyimage", + postUri: POST_URI, + position: 0, + fileName: "bafyimage", + contents: "image bytes", + }); + + const { result, archive } = await exportAccount(account); + + const media = Object.keys(archive.entries).filter((name) => + name.startsWith("media/"), + ); + expect(Object.keys(archive.entries).sort()).toEqual( + ["data.db", "manifest.json", "metadata.json", ...media].sort(), + ); + // The post's image, and the preserved thumbnail of its link preview. + expect(media).toHaveLength(2); + for (const name of media) { + expect(name).toMatch(/^media\/sha256\/[0-9a-f]{2}\/[0-9a-f]{64}$/); + } + expect(classifyBlueskyArchiveMetadata(archive.metadata).supported).toBe(true); + expect(archive.metadata).toMatchObject({ + format: "cyd-archive", + platform: "bluesky", + version: 2, + accountDid: ACCOUNT_DID, + accountUuid: ACCOUNT_UUID, + completeness: "complete", + }); + expect(result.fileName).toBe("cyd-bluesky-alice.example-2026-09-10.cyd"); + expect(result.byteLength).toBe(archive.bytes.length); + }); + + it("produces an archive Cyd's own intake accepts", async () => { + // The reader is the only judge of the writer that ships in the same app: + // ZIP framing, the deflated database, the manifest, and the metadata all + // have to survive a real import's defensive checks. + addMedia(account, { + contentCid: "bafyimage", + postUri: POST_URI, + position: 0, + fileName: "bafyimage", + contents: "image bytes", + }); + + const { archive } = await exportAccount(account); + + const outcome = await runBlueskyArchiveIntake( + createTestBlueskyArchiveIntakeEnvironment(), + { + intakeId: "intake-of-our-own-export", + sourceUri: "file:///exported.cyd", + openReader: async () => createMemoryByteReader(archive.bytes), + }, + ); + + expect(outcome).toMatchObject({ + status: "prepared", + metadata: { accountDid: ACCOUNT_DID, completeness: "complete" }, + }); + }); + + it("lists every payload in the manifest with the digest it actually has", async () => { + addMedia(account, { + contentCid: "bafyimage", + postUri: POST_URI, + position: 0, + fileName: "bafyimage", + contents: "image bytes", + }); + + const { archive } = await exportAccount(account); + + const listed = archive.manifest.payloads.map((payload) => payload.path); + expect(listed).toEqual([...listed].sort()); + expect(listed).toEqual( + Object.keys(archive.entries) + .filter((name) => name !== "manifest.json") + .sort(), + ); + for (const payload of archive.manifest.payloads) { + const content = archive.entries[payload.path]; + expect(payload.bytes).toBe(content.length); + expect(payload.sha256).toBe( + require("node:crypto").createHash("sha256").update(content).digest("hex"), + ); + } + }); + + it("builds an interchange database, not a copy of Mobile's own", async () => { + const { archive } = await exportAccount(account); + + const tables = archive.database + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + ) + .all() + .map((row) => (row as { name: string }).name); + + expect(tables).toEqual([ + "archive", + "assets", + "conversation_members", + "conversations", + "identity", + "messages", + "portable_settings", + "profiles", + "record_assets", + "record_context", + "record_subjects", + "records", + "relationships", + "selections", + ]); + expect( + archive.database.prepare("PRAGMA application_id;").get(), + ).toEqual({ application_id: 0x43594232 }); + expect(archive.database.prepare("PRAGMA user_version;").get()).toEqual({ + user_version: 2, + }); + expect(archive.database.prepare("PRAGMA foreign_key_check;").all()).toEqual([]); + expect(archive.database.prepare("PRAGMA integrity_check;").get()).toEqual({ + integrity_check: "ok", + }); + }); + + it("carries the account's records, context, chats, follows, and settings", async () => { + const { archive } = await exportAccount(account); + const all = (sql: string) => archive.database.prepare(sql).all(); + + expect(all("SELECT category, subject_id FROM selections ORDER BY category")).toEqual([ + { category: "bookmarks", subject_id: LIKED_URI }, + { category: "chats", subject_id: "convo-1" }, + { + category: "likes", + subject_id: `at://${ACCOUNT_DID}/app.bsky.feed.like/one`, + }, + { category: "posts", subject_id: POST_URI }, + ]); + expect(all("SELECT kind FROM record_context")).toEqual([{ kind: "external" }]); + expect(all("SELECT COUNT(*) AS total FROM messages")).toEqual([{ total: 1 }]); + expect(all("SELECT kind, subject_did FROM relationships")).toEqual([ + { kind: "follow", subject_did: OTHER_DID }, + ]); + expect(all("SELECT key, value_json FROM portable_settings ORDER BY key")).toEqual([ + { key: "delete_posts", value_json: "false" }, + { key: "save_likes", value_json: "true" }, + { key: "save_posts", value_json: "true" }, + ]); + }); + + it("carries no credentials, jobs, or local file paths", async () => { + addMedia(account, { + contentCid: "bafyimage", + postUri: POST_URI, + position: 0, + fileName: "bafyimage", + contents: "image bytes", + }); + // An asset that vanishes forces the export down the path where a storage + // error's own message — which names a device path — could reach the + // archive as an unavailable_reason. + addMedia(account, { + contentCid: "bafygone", + postUri: POST_URI, + position: 1, + fileName: "bafygone", + contents: "doomed bytes", + }); + + const { archive } = await exportAccount(account, { + onAccountWorkResumed: () => + fs.rmSync(path.join(account.mediaDirectory, "bafygone")), + }); + const text = new TextDecoder().decode(archive.entries["data.db"]); + + expect(text).not.toContain("SUPERSECRETSESSION"); + expect(text).not.toContain("SUPERSECRETJOB"); + expect(text).not.toContain("/private/thumb.jpg"); + expect(text).not.toContain("file:///data/user/0"); + expect(text).not.toContain(account.mediaDirectory); + expect(text).not.toContain("ENOENT"); + expect(text).not.toContain(os.tmpdir()); + }); + + it("describes one point in time even when saving resumes underneath it", async () => { + addMedia(account, { + contentCid: "bafykept", + postUri: POST_URI, + position: 0, + fileName: "bafykept", + contents: "kept image bytes", + }); + addMedia(account, { + contentCid: "bafylost", + postUri: POST_URI, + position: 1, + fileName: "bafylost", + contents: "lost image bytes", + }); + + const { archive } = await exportAccount(account, { + onAccountWorkResumed: () => { + run( + account.database, + `INSERT INTO post (uri, cid, authorDid, text, isReply, isQuote, isRepost, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, viewerReposted, viewerBookmarked, + createdAt, savedAt) + VALUES (?, 'bafylater', ?, 'Saved after the snapshot', 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, '2026-09-09T09:00:00.000Z', ?);`, + [`at://${ACCOUNT_DID}/app.bsky.feed.post/later`, ACCOUNT_DID, Date.now()], + ); + fs.rmSync(path.join(account.mediaDirectory, "bafylost")); + }, + }); + + const records = archive.database + .prepare("SELECT uri FROM records ORDER BY uri") + .all() + .map((row) => (row as { uri: string }).uri); + expect(records).not.toContain(`at://${ACCOUNT_DID}/app.bsky.feed.post/later`); + + const assets = archive.database + .prepare("SELECT id, availability, unavailable_reason FROM assets ORDER BY id") + .all() as { id: string; availability: string; unavailable_reason: string | null }[]; + expect(assets).toEqual([ + expect.objectContaining({ id: "bafykept", availability: "available" }), + expect.objectContaining({ + id: "bafylost", + availability: "unavailable", + unavailable_reason: + "The preserved file could not be read while the export was being packaged.", + }), + expect.objectContaining({ + id: expect.stringContaining("preview:"), + availability: "available", + }), + ]); + expect(archive.metadata.completeness).toBe("incomplete"); + // A storage error names the path it failed on. That must not ride along + // into the archive as an explanation. + expect(assets[1].unavailable_reason).not.toMatch(/bafylost|ENOENT|\//); + }); + + it("exports the rest of an account whose media never finished downloading", async () => { + addMedia(account, { + contentCid: "bafyvideo", + postUri: POST_URI, + position: 0, + fileName: "bafyvideo", + contents: "", + downloadState: "failed", + mediaType: "video", + }); + + const { result, archive } = await exportAccount(account); + + expect(archive.metadata.completeness).toBe("incomplete"); + expect(result.assets).toEqual({ + total: 2, + available: 1, + missing: 1, + unavailable: 0, + }); + expect( + archive.database.prepare("SELECT COUNT(*) AS total FROM records").get(), + ).toEqual({ total: 3 }); + expect( + archive.database.prepare("SELECT COUNT(*) AS total FROM record_assets").get(), + ).toEqual({ total: 2 }); + // Only the preview: the video Cyd never finished downloading has no bytes. + expect( + Object.keys(archive.entries).filter((name) => name.startsWith("media/")), + ).toHaveLength(1); + }); + + it("packages an asset two records share exactly once", async () => { + addMedia(account, { + contentCid: "bafyshared", + postUri: POST_URI, + position: 0, + fileName: "bafyshared", + contents: "shared image bytes", + }); + run( + account.database, + `INSERT INTO post_media (postUri, position, mediaType, blobCid, mimeType, + width, height, assetCid) + VALUES (?, 0, 'image', 'bafyshared', 'image/jpeg', 800, 600, 'bafyshared');`, + [LIKED_URI], + ); + + const { archive } = await exportAccount(account); + + expect( + archive.database + .prepare("SELECT COUNT(*) AS total FROM assets WHERE kind = 'image'") + .get(), + ).toEqual({ total: 1 }); + expect( + archive.database + .prepare( + "SELECT COUNT(*) AS total FROM record_assets WHERE role = 'content'", + ) + .get(), + ).toEqual({ total: 2 }); + expect( + Object.keys(archive.entries).filter((name) => name.startsWith("media/")), + ).toHaveLength(2); + }); +}); diff --git a/services/archive-export/__tests__/fixtures.test.ts b/services/archive-export/__tests__/fixtures.test.ts new file mode 100644 index 0000000..10600d5 --- /dev/null +++ b/services/archive-export/__tests__/fixtures.test.ts @@ -0,0 +1,143 @@ +import fs from "node:fs"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import { unzipSync } from "fflate"; + +import { runBlueskyArchiveIntake } from "@/services/archive-import"; +import { + createMemoryByteReader, + createTestBlueskyArchiveIntakeEnvironment, +} from "@/testUtils/archiveFixtures"; + +/** + * Guards on the committed real-data fixtures. + * + * These are archives Mobile's own writer produced from a curated test account + * (ADR 0016), and `testUtils/fixtures/bluesky-archive/README.md` records where + * they came from. Two things about them are easy to break silently and are + * therefore checked here rather than described in prose: that Mobile can still + * read them, and that regenerating them did not quietly inflate the + * repository, since committed media persists in history forever. + * + * What they *mean* is not settled here. The pinned canonical bundle is the + * semantic oracle (ADR 0008); `npm run test:archive-contract` is that check. + */ + +const FIXTURE_DIRECTORY = path.join( + __dirname, + "../../../testUtils/fixtures/bluesky-archive", +); + +/** Both fixtures together, against the budget the fixtures doc states. */ +const SIZE_BUDGET_BYTES = 5 * 1024 * 1024; + +function read(name: string): Uint8Array { + return new Uint8Array(fs.readFileSync(path.join(FIXTURE_DIRECTORY, name))); +} + +function openDatabase(archive: Uint8Array): DatabaseSync { + const extracted = path.join( + fs.mkdtempSync(path.join(require("node:os").tmpdir(), "cyd-fixture-")), + "data.db", + ); + fs.writeFileSync(extracted, unzipSync(archive)["data.db"]); + return new DatabaseSync(extracted, { readOnly: true }); +} + +describe("committed Cyd Bluesky archive fixtures", () => { + it.each(["complete.cyd", "incomplete.cyd"])( + "%s is still an archive Cyd can take in", + async (name) => { + const outcome = await runBlueskyArchiveIntake( + createTestBlueskyArchiveIntakeEnvironment(), + { + intakeId: `fixture-${name}`, + sourceUri: `file:///fixtures/${name}`, + openReader: async () => createMemoryByteReader(read(name)), + }, + ); + + expect(outcome).toMatchObject({ + status: "prepared", + metadata: { + format: "cyd-archive", + platform: "bluesky", + version: 2, + accountDid: "did:plc:yn45xekh5kqrat27w6rmafcg", + completeness: name === "complete.cyd" ? "complete" : "incomplete", + }, + }); + }, + ); + + it("stays inside the committed size budget", () => { + const total = ["complete.cyd", "incomplete.cyd"].reduce( + (sum, name) => sum + fs.statSync(path.join(FIXTURE_DIRECTORY, name)).size, + 0, + ); + + expect(total).toBeLessThanOrEqual(SIZE_BUDGET_BYTES); + }); + + it("differs between the pair by one unavailable asset and nothing else", () => { + // What makes the pair useful to a reader: anything else that differs is a + // second variable in every test built on them. + const complete = openDatabase(read("complete.cyd")); + const incomplete = openDatabase(read("incomplete.cyd")); + + for (const table of [ + "identity", + "profiles", + "records", + "selections", + "record_subjects", + "record_context", + "conversations", + "conversation_members", + "messages", + "relationships", + "record_assets", + "portable_settings", + ]) { + expect({ + table, + rows: complete.prepare(`SELECT * FROM ${table}`).all(), + }).toEqual({ + table, + rows: incomplete.prepare(`SELECT * FROM ${table}`).all(), + }); + } + + const unavailable = incomplete + .prepare("SELECT id FROM assets WHERE availability != 'available'") + .all(); + expect(unavailable).toHaveLength(1); + expect( + complete.prepare("SELECT COUNT(*) AS n FROM assets WHERE availability = 'available'").get(), + ).toEqual({ n: 5 }); + expect( + incomplete.prepare("SELECT COUNT(*) AS n FROM assets WHERE availability = 'available'").get(), + ).toEqual({ n: 4 }); + + complete.close(); + incomplete.close(); + }); + + it("carries only accounts the maintainer controls", () => { + // The fixtures are public and permanent. A handle that is not one of these + // means somebody else's content was committed by accident. + const database = openDatabase(read("complete.cyd")); + + const handles = database + .prepare("SELECT handle FROM profiles WHERE handle IS NOT NULL ORDER BY handle") + .all() + .map((row) => (row as { handle: string }).handle); + + expect(handles).toEqual([ + "aurorabyte-cyd.bsky.social", + "glittertop-cyd.bsky.social", + ]); + database.close(); + }); +}); diff --git a/services/archive-export/__tests__/interchange.test.ts b/services/archive-export/__tests__/interchange.test.ts new file mode 100644 index 0000000..e776bdc --- /dev/null +++ b/services/archive-export/__tests__/interchange.test.ts @@ -0,0 +1,927 @@ +import type { ResolvedAsset } from "../assets"; +import { previewAssetKey } from "../assets"; +import { + translateBlueskyAccountToInterchange, + type BlueskyArchiveTranslationContext, + type BlueskyInterchangeContent, +} from "../interchange"; +import type { + MobileAccountSnapshot, + MobileBookmarkRow, + MobileConversationRow, + MobileFollowRow, + MobileMessageRow, + MobilePostRow, + MobileProfileRow, +} from "../mobile-snapshot"; + +const ACCOUNT_DID = "did:plc:alice"; +const ACCOUNT_UUID = "018d5f7a-9b3c-7d10-8a2e-1f4c6b8d0e12"; +const OTHER_DID = "did:plc:bob"; +const SAVED_AT = Date.UTC(2026, 8, 1, 12, 0, 0); +const EXPORTED_AT = new Date("2026-09-10T00:00:00.000Z"); + +function profile(overrides: Partial = {}): MobileProfileRow { + return { + did: ACCOUNT_DID, + handle: "alice.example", + displayName: "Alice", + savedAt: SAVED_AT, + updatedAt: SAVED_AT, + ...overrides, + }; +} + +function post(overrides: Partial = {}): MobilePostRow { + return { + uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + cid: "bafypost", + authorDid: ACCOUNT_DID, + text: "Hello", + facetsJSON: null, + embedJSON: null, + langs: "en", + isReply: 0, + replyParentUri: null, + replyRootUri: null, + isQuote: 0, + quotedPostUri: null, + isRepost: 0, + repostUri: null, + repostCid: null, + originalPostUri: null, + likeCount: 2, + repostCount: 1, + replyCount: 0, + quoteCount: 0, + viewerLiked: 0, + viewerReposted: 0, + viewerBookmarked: 0, + createdAt: "2026-08-30T09:00:00.000Z", + savedAt: SAVED_AT, + deletedPostAt: null, + deletedRepostAt: null, + deletedLikeAt: null, + deletedBookmarkAt: null, + likeUri: null, + ...overrides, + }; +} + +function bookmark(overrides: Partial = {}): MobileBookmarkRow { + return { + subjectUri: `at://${OTHER_DID}/app.bsky.feed.post/bookmarked`, + postAuthorDid: OTHER_DID, + postAuthorHandle: "bob.example", + postText: "Bookmarked post", + postCreatedAt: "2026-08-20T09:00:00.000Z", + savedAt: SAVED_AT, + deletedAt: null, + ...overrides, + }; +} + +function follow(overrides: Partial = {}): MobileFollowRow { + return { + uri: `at://${ACCOUNT_DID}/app.bsky.graph.follow/bob`, + subjectDid: OTHER_DID, + handle: "bob.example", + createdAt: "2026-07-01T09:00:00.000Z", + savedAt: SAVED_AT, + unfollowedAt: null, + ...overrides, + }; +} + +function conversation( + overrides: Partial = {}, +): MobileConversationRow { + return { + convoId: "convo-1", + rev: "rev-1", + memberDids: JSON.stringify([ACCOUNT_DID, OTHER_DID]), + savedAt: SAVED_AT, + updatedAt: SAVED_AT, + leftAt: null, + ...overrides, + }; +} + +function message(overrides: Partial = {}): MobileMessageRow { + return { + messageId: "message-1", + convoId: "convo-1", + rev: "rev-1", + senderDid: OTHER_DID, + text: "Hi there", + facetsJSON: null, + embedJSON: null, + sentAt: "2026-08-31T09:00:00.000Z", + savedAt: SAVED_AT, + deletedAt: null, + ...overrides, + }; +} + +function snapshot( + overrides: Partial = {}, +): MobileAccountSnapshot { + return { + profiles: [profile()], + posts: [], + postMedia: [], + postExternals: [], + bookmarks: [], + follows: [], + conversations: [], + messages: [], + mediaAssets: [], + ...overrides, + }; +} + +function availableAsset(key: string, sha256 = "a".repeat(64)): ResolvedAsset { + return { + key, + availability: "available", + sha256, + byteCount: 1024, + crc32: 7, + sniffedMediaType: "image/jpeg", + archivePath: `media/sha256/${sha256.slice(0, 2)}/${sha256}`, + localPath: `file:///accounts/media/${key}`, + }; +} + +function translate( + input: MobileAccountSnapshot, + context: Partial = {}, +): BlueskyInterchangeContent { + return translateBlueskyAccountToInterchange(input, { + accountDid: ACCOUNT_DID, + accountUuid: ACCOUNT_UUID, + createdAt: EXPORTED_AT, + assets: new Map(), + portableSettings: {}, + ...context, + }); +} + +describe("translateBlueskyAccountToInterchange", () => { + it("describes the archive and the identity it belongs to", () => { + const content = translate(snapshot()); + + expect(content.archive).toEqual({ + format: "cyd-archive", + platform: "bluesky", + version: 2, + created_at: "2026-09-10T00:00:00.000Z", + account_did: ACCOUNT_DID, + account_uuid: ACCOUNT_UUID, + completeness: "complete", + }); + expect(content.identity).toEqual({ + did: ACCOUNT_DID, + current_profile_id: `profile:${ACCOUNT_DID}`, + }); + expect(content.profiles).toEqual([ + { + id: `profile:${ACCOUNT_DID}`, + did: ACCOUNT_DID, + handle: "alice.example", + display_name: "Alice", + description: null, + avatar_asset_id: null, + banner_asset_id: null, + captured_at: "2026-09-01T12:00:00.000Z", + }, + ]); + }); + + it("gives the account an identity even before any profile was captured", () => { + const content = translate(snapshot({ profiles: [] })); + + expect(content.identity.current_profile_id).toBe(`profile:${ACCOUNT_DID}`); + expect(content.profiles).toEqual([ + expect.objectContaining({ did: ACCOUNT_DID, handle: null }), + ]); + }); + + it("translates a saved post with its text, facets, and observation times", () => { + const content = translate( + snapshot({ + posts: [ + post({ + facetsJSON: '[{"index":{"byteStart":0,"byteEnd":5}}]', + langs: "en,fr", + }), + ], + }), + ); + + expect(content.records).toEqual([ + expect.objectContaining({ + uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + cid: "bafypost", + record_type: "app.bsky.feed.post", + author_profile_id: `profile:${ACCOUNT_DID}`, + indexed_at: null, + created_at: "2026-08-30T09:00:00.000Z", + first_observed_at: "2026-09-01T12:00:00.000Z", + observed_at: "2026-09-01T12:00:00.000Z", + source_deleted_at: null, + text: "Hello", + facets_json: '[{"index":{"byteStart":0,"byteEnd":5}}]', + }), + ]); + expect(JSON.parse(content.records[0].payload_json)).toEqual({ + record: { + $type: "app.bsky.feed.post", + text: "Hello", + createdAt: "2026-08-30T09:00:00.000Z", + langs: ["en", "fr"], + }, + metrics: { likeCount: 2, repostCount: 1, replyCount: 0, quoteCount: 0 }, + }); + expect(content.selections).toEqual([ + { + category: "posts", + subject_id: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + selected_at: "2026-09-01T12:00:00.000Z", + }, + ]); + }); + + it("keeps the deletion state Bluesky's source no longer has", () => { + const deletedAt = Date.UTC(2026, 8, 5, 0, 0, 0); + const content = translate( + snapshot({ + posts: [post({ deletedPostAt: deletedAt })], + follows: [follow({ unfollowedAt: deletedAt })], + conversations: [conversation({ leftAt: deletedAt })], + messages: [message({ deletedAt })], + }), + ); + + expect(content.records[0].source_deleted_at).toBe("2026-09-05T00:00:00.000Z"); + expect(content.relationships[0].source_deleted_at).toBe( + "2026-09-05T00:00:00.000Z", + ); + expect(content.conversations[0].source_deleted_at).toBe( + "2026-09-05T00:00:00.000Z", + ); + expect(content.messages[0].source_deleted_at).toBe( + "2026-09-05T00:00:00.000Z", + ); + }); + + it("links a like to the record it is about", () => { + const likeUri = `at://${ACCOUNT_DID}/app.bsky.feed.like/one`; + const content = translate( + snapshot({ + posts: [ + post({ + uri: `at://${OTHER_DID}/app.bsky.feed.post/liked`, + authorDid: OTHER_DID, + viewerLiked: 1, + likeUri, + }), + ], + profiles: [profile(), profile({ did: OTHER_DID, handle: "bob.example" })], + }), + ); + + expect( + content.records.find((record) => record.uri === likeUri), + ).toEqual( + expect.objectContaining({ + record_type: "app.bsky.feed.like", + author_profile_id: `profile:${ACCOUNT_DID}`, + text: null, + }), + ); + expect(content.recordSubjects).toEqual([ + { + relationship_uri: likeUri, + subject_record_uri: `at://${OTHER_DID}/app.bsky.feed.post/liked`, + }, + ]); + expect(content.selections).toContainEqual( + expect.objectContaining({ category: "likes", subject_id: likeUri }), + ); + }); + + it("links a repost to the record it is about", () => { + const repostUri = `at://${ACCOUNT_DID}/app.bsky.feed.repost/one`; + const content = translate( + snapshot({ + posts: [ + post({ + uri: `at://${OTHER_DID}/app.bsky.feed.post/reposted`, + authorDid: OTHER_DID, + viewerReposted: 1, + repostUri, + }), + ], + profiles: [profile(), profile({ did: OTHER_DID, handle: "bob.example" })], + }), + ); + + expect( + content.records.find((record) => record.uri === repostUri)?.record_type, + ).toBe("app.bsky.feed.repost"); + expect(content.recordSubjects).toEqual([ + { + relationship_uri: repostUri, + subject_record_uri: `at://${OTHER_DID}/app.bsky.feed.post/reposted`, + }, + ]); + expect(content.selections).toContainEqual( + expect.objectContaining({ category: "reposts", subject_id: repostUri }), + ); + }); + + it("says a repost once, however many ways Cyd saw it", () => { + // An account feed can carry the repost as a record of its own *and* as + // viewer state on the post it points at. Both describe one repost, and the + // interchange keys would collide if the export said it twice. + const repostUri = `at://${ACCOUNT_DID}/app.bsky.feed.repost/one`; + const repostedUri = `at://${OTHER_DID}/app.bsky.feed.post/reposted`; + const content = translate( + snapshot({ + profiles: [profile(), profile({ did: OTHER_DID, handle: "bob.example" })], + posts: [ + post({ + uri: repostUri, + cid: "bafyrepost", + isRepost: 1, + originalPostUri: repostedUri, + text: "", + createdAt: "2026-08-31T09:00:00.000Z", + }), + post({ + uri: repostedUri, + authorDid: OTHER_DID, + viewerReposted: 1, + repostUri, + }), + ], + }), + ); + + expect( + content.selections.filter((row) => row.category === "reposts"), + ).toEqual([expect.objectContaining({ subject_id: repostUri })]); + expect(content.recordSubjects).toEqual([ + { relationship_uri: repostUri, subject_record_uri: repostedUri }, + ]); + // The saved repost record keeps its own CID and creation time. + expect(content.records.find((record) => record.uri === repostUri)).toEqual( + expect.objectContaining({ + cid: "bafyrepost", + created_at: "2026-08-31T09:00:00.000Z", + }), + ); + }); + + it("selects a bookmark and keeps the post it points at", () => { + const content = translate(snapshot({ bookmarks: [bookmark()] })); + + expect(content.selections).toEqual([ + expect.objectContaining({ + category: "bookmarks", + subject_id: `at://${OTHER_DID}/app.bsky.feed.post/bookmarked`, + }), + ]); + expect(content.records).toEqual([ + expect.objectContaining({ + uri: `at://${OTHER_DID}/app.bsky.feed.post/bookmarked`, + text: "Bookmarked post", + created_at: "2026-08-20T09:00:00.000Z", + author_profile_id: `profile:${OTHER_DID}`, + }), + ]); + }); + + it("captures the reply parent, quote, and external context of a post", () => { + const parentUri = `at://${OTHER_DID}/app.bsky.feed.post/parent`; + const quotedUri = `at://${OTHER_DID}/app.bsky.feed.post/quoted`; + const content = translate( + snapshot({ + profiles: [profile(), profile({ did: OTHER_DID, handle: "bob.example" })], + posts: [ + post({ + isReply: 1, + replyParentUri: parentUri, + replyRootUri: parentUri, + isQuote: 1, + quotedPostUri: quotedUri, + }), + post({ + uri: parentUri, + authorDid: OTHER_DID, + text: "Parent", + viewerLiked: 1, + likeUri: `at://${ACCOUNT_DID}/app.bsky.feed.like/parent`, + }), + post({ uri: quotedUri, authorDid: OTHER_DID, text: "Quoted" }), + ], + postExternals: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + uri: "https://example.com/story", + title: "A story", + description: "About something", + thumbUrl: "https://cdn.example/thumb.jpg", + }, + ], + }), + ); + + const context = content.recordContext.filter( + (row) => row.record_uri === `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + ); + expect(context).toEqual([ + { + record_uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + kind: "reply_parent", + context_record_uri: parentUri, + context_profile_id: `profile:${OTHER_DID}`, + external_json: null, + }, + { + record_uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + kind: "quote", + context_record_uri: quotedUri, + context_profile_id: `profile:${OTHER_DID}`, + external_json: null, + }, + { + record_uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + kind: "external", + context_record_uri: null, + context_profile_id: null, + external_json: JSON.stringify({ + uri: "https://example.com/story", + title: "A story", + description: "About something", + thumbUrl: "https://cdn.example/thumb.jpg", + }), + }, + ]); + }); + + it("keeps the author of context Cyd never saved, which the URI still names", () => { + const parentUri = `at://${OTHER_DID}/app.bsky.feed.post/unsaved`; + const content = translate( + snapshot({ + posts: [post({ isReply: 1, replyParentUri: parentUri })], + }), + ); + + expect(content.recordContext).toEqual([ + { + record_uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + kind: "reply_parent", + context_record_uri: null, + context_profile_id: `profile:${OTHER_DID}`, + external_json: null, + }, + ]); + expect(content.profiles).toContainEqual( + expect.objectContaining({ id: `profile:${OTHER_DID}`, handle: null }), + ); + expect(content.records.map((record) => record.uri)).not.toContain(parentUri); + }); + + it("packages a repeated asset once and points every use at it", () => { + const content = translate( + snapshot({ + posts: [ + post(), + post({ uri: `at://${ACCOUNT_DID}/app.bsky.feed.post/two` }), + ], + postMedia: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + position: 0, + mediaType: "image", + alt: "A picture", + width: 800, + height: 600, + assetCid: "bafyimage", + }, + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/two`, + position: 0, + mediaType: "image", + alt: "A picture", + width: 800, + height: 600, + assetCid: "bafyimage", + }, + ], + mediaAssets: [ + { + contentCid: "bafyimage", + mediaType: "image", + mimeType: "image/jpeg", + sourceUrl: "https://cdn.example/image", + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + }, + ], + }), + { assets: new Map([["bafyimage", availableAsset("bafyimage")]]) }, + ); + + expect(content.assets).toEqual([ + { + id: "bafyimage", + kind: "image", + media_type: "image/jpeg", + byte_count: 1024, + sha256: "a".repeat(64), + archive_path: `media/sha256/aa/${"a".repeat(64)}`, + availability: "available", + unavailable_reason: null, + source_url: "https://cdn.example/image", + width: 800, + height: 600, + alt_text: "A picture", + }, + ]); + expect(content.recordAssets).toEqual([ + { + owner_type: "record", + owner_id: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + asset_id: "bafyimage", + role: "content", + position: 0, + }, + { + owner_type: "record", + owner_id: `at://${ACCOUNT_DID}/app.bsky.feed.post/two`, + asset_id: "bafyimage", + role: "content", + position: 0, + }, + ]); + expect(content.payloads).toEqual([ + expect.objectContaining({ archivePath: `media/sha256/aa/${"a".repeat(64)}` }), + ]); + }); + + it("collapses two assets whose bytes turned out to be identical", () => { + const digest = "b".repeat(64); + const content = translate( + snapshot({ + posts: [post()], + postMedia: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + position: 0, + mediaType: "image", + alt: null, + width: null, + height: null, + assetCid: "bafyone", + }, + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + position: 1, + mediaType: "image", + alt: null, + width: null, + height: null, + assetCid: "bafytwo", + }, + ], + mediaAssets: [ + { + contentCid: "bafyone", + mediaType: "image", + mimeType: "image/jpeg", + sourceUrl: null, + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + }, + { + contentCid: "bafytwo", + mediaType: "image", + mimeType: "image/jpeg", + sourceUrl: null, + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + }, + ], + }), + { + assets: new Map([ + ["bafyone", availableAsset("bafyone", digest)], + ["bafytwo", availableAsset("bafytwo", digest)], + ]), + }, + ); + + expect(content.assets).toHaveLength(1); + expect(content.payloads).toHaveLength(1); + expect(content.recordAssets.map((row) => row.asset_id)).toEqual([ + "bafyone", + "bafyone", + ]); + }); + + it("says an asset Cyd never finished downloading is missing, not gone", () => { + const content = translate( + snapshot({ + posts: [post()], + postMedia: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + position: 0, + mediaType: "video", + alt: null, + width: 1280, + height: 720, + assetCid: "bafyvideo", + }, + ], + mediaAssets: [ + { + contentCid: "bafyvideo", + mediaType: "video", + mimeType: null, + sourceUrl: "https://cdn.example/video", + sourceMetadataJSON: null, + downloadState: "failed", + lastError: "Network error", + }, + ], + }), + { + assets: new Map([ + [ + "bafyvideo", + { + key: "bafyvideo", + availability: "missing", + reason: + "Cyd has not finished preserving this file, so it could not be included.", + }, + ], + ]), + }, + ); + + expect(content.assets).toEqual([ + expect.objectContaining({ + id: "bafyvideo", + kind: "video", + media_type: "video/mp4", + availability: "missing", + unavailable_reason: + "Cyd has not finished preserving this file, so it could not be included.", + byte_count: null, + sha256: null, + archive_path: null, + }), + ]); + expect(content.recordAssets).toHaveLength(1); + expect(content.payloads).toEqual([]); + expect(content.completeness).toBe("incomplete"); + }); + + it("packages the thumbnail of a link preview Cyd preserved", () => { + const key = previewAssetKey(`at://${ACCOUNT_DID}/app.bsky.feed.post/one`); + const content = translate( + snapshot({ + posts: [post()], + postExternals: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + uri: "https://example.com/story", + title: "A story", + description: null, + thumbUrl: "https://cdn.example/thumb.jpg", + }, + ], + }), + { assets: new Map([[key, availableAsset(key, "c".repeat(64))]]) }, + ); + + expect(content.assets).toEqual([ + expect.objectContaining({ + id: key, + kind: "preview", + media_type: "image/jpeg", + availability: "available", + source_url: "https://cdn.example/thumb.jpg", + }), + ]); + expect(content.recordAssets).toEqual([ + { + owner_type: "record", + owner_id: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + asset_id: key, + role: "preview", + position: 0, + }, + ]); + expect(content.payloads).toHaveLength(1); + }); + + it("leaves a link preview Cyd never downloaded out of the assets entirely", () => { + // Mobile does not count an undownloaded link thumbnail as part of its + // Bluesky saved data, so its absence must not make the archive incomplete. + // The URL survives in the record's external context. + const content = translate( + snapshot({ + posts: [post()], + postExternals: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + uri: "https://example.com/story", + title: "A story", + description: null, + thumbUrl: "https://cdn.example/thumb.jpg", + }, + ], + }), + ); + + expect(content.assets).toEqual([]); + expect(content.recordAssets).toEqual([]); + expect(content.completeness).toBe("complete"); + expect(JSON.parse(content.recordContext[0].external_json!)).toMatchObject({ + thumbUrl: "https://cdn.example/thumb.jpg", + }); + }); + + it("drops a subject link to a record the archive does not contain", () => { + // record_subjects.subject_record_uri is a foreign key: a repost of a post + // Cyd never saved must cost that one link, not the whole export. + const repostUri = `at://${ACCOUNT_DID}/app.bsky.feed.repost/one`; + const content = translate( + snapshot({ + posts: [ + post({ + uri: repostUri, + isRepost: 1, + originalPostUri: `at://${OTHER_DID}/app.bsky.feed.post/never-saved`, + text: "", + }), + ], + }), + ); + + expect(content.recordSubjects).toEqual([]); + expect(content.selections).toEqual([ + expect.objectContaining({ category: "reposts", subject_id: repostUri }), + ]); + expect(JSON.parse(content.records[0].payload_json).record.subject).toEqual({ + uri: `at://${OTHER_DID}/app.bsky.feed.post/never-saved`, + }); + }); + + it("never selects a bookmark it cannot describe", () => { + const content = translate( + snapshot({ + bookmarks: [ + bookmark({ subjectUri: "not-an-at-uri", postAuthorDid: null }), + ], + }), + ); + + expect(content.selections).toEqual([]); + expect(content.records).toEqual([]); + }); + + it("leaves out an asset no exported record refers to", () => { + const content = translate( + snapshot({ + mediaAssets: [ + { + contentCid: "bafyorphan", + mediaType: "image", + mimeType: "image/jpeg", + sourceUrl: null, + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + }, + ], + }), + { assets: new Map([["bafyorphan", availableAsset("bafyorphan")]]) }, + ); + + expect(content.assets).toEqual([]); + expect(content.payloads).toEqual([]); + expect(content.completeness).toBe("complete"); + }); + + it("translates a conversation, who was in it, and what was said", () => { + const content = translate( + snapshot({ + profiles: [profile(), profile({ did: OTHER_DID, handle: "bob.example" })], + conversations: [conversation()], + messages: [message()], + }), + ); + + expect(content.conversations).toEqual([ + { + id: "convo-1", + rev: "rev-1", + first_observed_at: "2026-09-01T12:00:00.000Z", + observed_at: "2026-09-01T12:00:00.000Z", + source_deleted_at: null, + }, + ]); + expect(content.conversationMembers).toEqual([ + { conversation_id: "convo-1", profile_id: `profile:${ACCOUNT_DID}` }, + { conversation_id: "convo-1", profile_id: `profile:${OTHER_DID}` }, + ]); + expect(content.messages).toEqual([ + expect.objectContaining({ + id: "message-1", + conversation_id: "convo-1", + sender_profile_id: `profile:${OTHER_DID}`, + sent_at: "2026-08-31T09:00:00.000Z", + text: "Hi there", + }), + ]); + expect(content.selections).toContainEqual( + expect.objectContaining({ category: "chats", subject_id: "convo-1" }), + ); + }); + + it("translates follows as relationships", () => { + const content = translate(snapshot({ follows: [follow()] })); + + expect(content.relationships).toEqual([ + { + uri: `at://${ACCOUNT_DID}/app.bsky.graph.follow/bob`, + kind: "follow", + actor_did: ACCOUNT_DID, + subject_did: OTHER_DID, + created_at: "2026-07-01T09:00:00.000Z", + observed_at: "2026-09-01T12:00:00.000Z", + source_deleted_at: null, + }, + ]); + }); + + it("carries portable settings as canonical JSON values", () => { + const content = translate(snapshot(), { + portableSettings: { save_posts: true, delete_likes: false }, + }); + + expect(content.portableSettings).toEqual([ + { key: "delete_likes", value_json: "false" }, + { key: "save_posts", value_json: "true" }, + ]); + }); + + it("never carries Mobile's private storage into the interchange", () => { + const content = translate( + snapshot({ + posts: [post()], + postMedia: [ + { + postUri: `at://${ACCOUNT_DID}/app.bsky.feed.post/one`, + position: 0, + mediaType: "image", + alt: null, + width: null, + height: null, + assetCid: "bafyimage", + }, + ], + mediaAssets: [ + { + contentCid: "bafyimage", + mediaType: "image", + mimeType: "image/jpeg", + sourceUrl: "https://cdn.example/image", + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + }, + ], + }), + { assets: new Map([["bafyimage", availableAsset("bafyimage")]]) }, + ); + + const serialized = JSON.stringify({ + ...content, + payloads: undefined, + }); + expect(serialized).not.toContain("file://"); + expect(serialized).not.toContain("localPath"); + expect(serialized).not.toContain("/accounts/"); + }); +}); diff --git a/services/archive-export/__tests__/portable-settings.test.ts b/services/archive-export/__tests__/portable-settings.test.ts new file mode 100644 index 0000000..cce2d18 --- /dev/null +++ b/services/archive-export/__tests__/portable-settings.test.ts @@ -0,0 +1,42 @@ +import { portableSettingsFromAccountRow } from "../portable-settings"; + +describe("portableSettingsFromAccountRow", () => { + it("carries the save and delete defaults an account chose", () => { + expect( + portableSettingsFromAccountRow({ + settingSavePosts: 1, + settingSaveLikes: 0, + settingSaveBookmarks: 1, + settingSaveChats: 0, + settingDeletePosts: 1, + settingDeleteReposts: 0, + settingDeleteLikes: 1, + settingDeleteBookmarks: 0, + settingDeleteChats: 1, + settingDeleteUnfollowEveryone: 0, + }), + ).toEqual({ + save_posts: true, + save_likes: false, + save_bookmarks: true, + save_chats: false, + delete_posts: true, + delete_reposts: false, + delete_likes: true, + delete_bookmarks: false, + delete_chats: true, + delete_follows: false, + }); + }); + + it("says nothing about a setting Mobile does not have", () => { + const settings = portableSettingsFromAccountRow({ settingSavePosts: 1 }); + + expect(settings).toEqual({ save_posts: true }); + expect("save_reposts" in settings).toBe(false); + }); + + it("carries nothing at all when the account row is missing", () => { + expect(portableSettingsFromAccountRow(null)).toEqual({}); + }); +}); diff --git a/services/archive-export/__tests__/zip-writer.test.ts b/services/archive-export/__tests__/zip-writer.test.ts new file mode 100644 index 0000000..449c856 --- /dev/null +++ b/services/archive-export/__tests__/zip-writer.test.ts @@ -0,0 +1,199 @@ +import { crc32 } from "@/services/archive-import/crc32"; +import { + readZipCentralDirectory, + streamZipEntry, +} from "@/services/archive-import/zip-reader"; +import { + createMemoryByteReader, + createTestBlueskyArchiveIntakeEnvironment, +} from "@/testUtils/archiveFixtures"; + +import { BlueskyArchiveZipWriter, type ArchiveByteSink } from "../zip-writer"; + +function createMemorySink(): ArchiveByteSink & { bytes(): Uint8Array; closed: boolean } { + const chunks: Uint8Array[] = []; + const sink = { + closed: false, + write(chunk: Uint8Array): void { + chunks.push(chunk.slice()); + }, + close(): void { + sink.closed = true; + }, + bytes(): Uint8Array { + const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0); + const joined = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + joined.set(chunk, offset); + offset += chunk.length; + } + return joined; + }, + }; + return sink; +} + +const encoder = new TextEncoder(); + +async function readBack(bytes: Uint8Array) { + const environment = createTestBlueskyArchiveIntakeEnvironment(); + const reader = createMemoryByteReader(bytes); + const directory = await readZipCentralDirectory(reader, { maxEntries: 64 }); + const contents = new Map(); + for (const entry of directory.entries) { + const chunks: Uint8Array[] = []; + await streamZipEntry(reader, entry, { + createDecompressor: environment.createDecompressor, + createHasher: environment.createHasher, + onBytes: (chunk) => chunks.push(chunk.slice()), + }); + contents.set( + entry.path, + chunks.map((chunk) => new TextDecoder().decode(chunk)).join(""), + ); + } + return { directory, contents }; +} + +async function writeArchive( + entries: { path: string; data: string }[], +): Promise { + const sink = createMemorySink(); + const writer = new BlueskyArchiveZipWriter(sink); + for (const entry of entries) { + const bytes = encoder.encode(entry.data); + await writer.addStoredEntry( + entry.path, + { byteLength: bytes.length, crc32: crc32(bytes) }, + async (push) => { + push(bytes); + }, + ); + } + writer.finish(); + return sink.bytes(); +} + +describe("BlueskyArchiveZipWriter", () => { + it("writes an archive Cyd's own archive reader can read back", async () => { + const bytes = await writeArchive([ + { path: "data.db", data: "SQLite format 3\u0000stand-in" }, + { + path: "media/sha256/ab/abababababababababababababababababababababababababababababababab", + data: "media bytes", + }, + { path: "metadata.json", data: '{"format":"cyd-archive"}' }, + ]); + + const { directory, contents } = await readBack(bytes); + + expect(directory.entries.map((entry) => entry.path)).toEqual([ + "data.db", + "media/sha256/ab/abababababababababababababababababababababababababababababababab", + "metadata.json", + ]); + expect(contents.get("metadata.json")).toBe('{"format":"cyd-archive"}'); + expect( + contents.get( + "media/sha256/ab/abababababababababababababababababababababababababababababababab", + ), + ).toBe("media bytes"); + }); + + it("stores entries uncompressed so writing never has to buffer one whole", async () => { + const bytes = await writeArchive([{ path: "data.db", data: "payload" }]); + + const { directory } = await readBack(bytes); + + expect(directory.entries[0].method).toBe(0); + expect(directory.entries[0].compressedBytes).toBe( + directory.entries[0].uncompressedBytes, + ); + }); + + it("streams an entry across as many chunks as the source produces", async () => { + const sink = createMemorySink(); + const writer = new BlueskyArchiveZipWriter(sink); + const payload = encoder.encode("one two three"); + await writer.addStoredEntry( + "data.db", + { byteLength: payload.length, crc32: crc32(payload) }, + async (push) => { + push(payload.slice(0, 4)); + push(payload.slice(4, 9)); + push(payload.slice(9)); + }, + ); + writer.finish(); + + const { contents } = await readBack(sink.bytes()); + expect(contents.get("data.db")).toBe("one two three"); + }); + + it("marks entries as regular files, which a reader is entitled to require", async () => { + const bytes = await writeArchive([{ path: "data.db", data: "payload" }]); + + // The central directory's external attributes carry the Unix mode in their + // high 16 bits. conformance.py rejects anything that is not a regular file. + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let centralHeaderOffset = -1; + for (let offset = 0; offset < bytes.length - 4; offset += 1) { + if (view.getUint32(offset, true) === 0x02014b50) { + centralHeaderOffset = offset; + break; + } + } + expect(centralHeaderOffset).toBeGreaterThan(-1); + const externalAttributes = view.getUint32(centralHeaderOffset + 38, true); + expect((externalAttributes >>> 16) & 0o170000).toBe(0o100000); + }); + + it("refuses an entry that does not produce the byte count it declared", async () => { + const writer = new BlueskyArchiveZipWriter(createMemorySink()); + + await expect( + writer.addStoredEntry("data.db", { byteLength: 12, crc32: 0 }, async (push) => { + push(encoder.encode("short")); + }), + ).rejects.toThrow(/declared 12 bytes/); + }); + + it("refuses an entry whose bytes do not match the checksum it declared", async () => { + const payload = encoder.encode("payload"); + const writer = new BlueskyArchiveZipWriter(createMemorySink()); + + await expect( + writer.addStoredEntry( + "data.db", + { byteLength: payload.length, crc32: crc32(payload) + 1 }, + async (push) => { + push(payload); + }, + ), + ).rejects.toThrow(/changed while it was being packaged/); + }); + + it("refuses an entry path that could escape the archive", async () => { + const writer = new BlueskyArchiveZipWriter(createMemorySink()); + + await expect( + writer.addStoredEntry( + "../escape.json", + { byteLength: 0, crc32: crc32(new Uint8Array(0)) }, + async () => {}, + ), + ).rejects.toThrow(/normalized relative file path/); + }); + + it("refuses to add the same path twice", async () => { + const sink = createMemorySink(); + const writer = new BlueskyArchiveZipWriter(sink); + const declared = { byteLength: 0, crc32: crc32(new Uint8Array(0)) }; + await writer.addStoredEntry("data.db", declared, async () => {}); + + await expect( + writer.addStoredEntry("data.db", declared, async () => {}), + ).rejects.toThrow(/more than once/); + }); +}); diff --git a/services/archive-export/assets.ts b/services/archive-export/assets.ts new file mode 100644 index 0000000..3af271d --- /dev/null +++ b/services/archive-export/assets.ts @@ -0,0 +1,188 @@ +import { Crc32 } from "@/services/archive-import/crc32"; + +import type { BlueskyArchiveExportEnvironment } from "./ports"; + +/** + * Deciding what Cyd can honestly claim about each preserved asset. + * + * A Cyd Bluesky archive is allowed to be incomplete; it is not allowed to be + * quietly wrong. So every asset the account references ends up in one of three + * states, and none of them is "left out": + * + * - `available` — the bytes were read and hashed, and go in the archive. + * - `missing` — Cyd never finished preserving it, so there is nothing to + * package. The record still references it, and the archive is incomplete. + * - `unavailable` — Cyd had preserved it, but it was gone or a different size + * by the time the export read it. This is the case the point-in-time + * inventory exists to catch (ADR 0010). + * + * Hashing happens after account work resumes, which is exactly why it can + * disagree with the inventory. That disagreement is information, so it is + * recorded rather than retried into silence. + * + * The reasons are written for whoever opens the archive, and are fixed strings + * on purpose: a storage error's own message names the file it failed on, and + * device filesystem paths are one of the things the contract's privacy + * boundary keeps out of a Cyd Bluesky archive. + */ + +/** Identifies a preserved file within one export, before it is hashed. */ +export type StagedAsset = { + key: string; + localPath: string | null; + /** Cyd's own record of whether it finished preserving the file. */ + preserved: boolean; + /** Size when the inventory was taken, or null if the file was not there. */ + stagedByteLength: number | null; +}; + +export type ResolvedAsset = + | { + key: string; + availability: "available"; + sha256: string; + byteCount: number; + crc32: number; + /** What the bytes turned out to be, when Cyd never recorded a type. */ + sniffedMediaType: string | null; + archivePath: string; + localPath: string; + } + | { + key: string; + availability: "missing" | "unavailable"; + reason: string; + }; + +/** How a link preview's preserved thumbnail is named in the inventory. */ +export function previewAssetKey(postUri: string): string { + return `preview:${postUri}`; +} + +/** Content-addressed location of an asset inside a Cyd Bluesky archive. */ +export function archivePathForDigest(sha256: string): string { + return `media/sha256/${sha256.slice(0, 2)}/${sha256}`; +} + +function unresolved( + key: string, + availability: "missing" | "unavailable", + reason: string, +): ResolvedAsset { + return { key, availability, reason }; +} + +const MAGIC_NUMBERS: { prefix: number[]; mediaType: string }[] = [ + { prefix: [0xff, 0xd8, 0xff], mediaType: "image/jpeg" }, + { prefix: [0x89, 0x50, 0x4e, 0x47], mediaType: "image/png" }, + { prefix: [0x47, 0x49, 0x46, 0x38], mediaType: "image/gif" }, +]; + +/** + * Name a file's type from its own first bytes. + * + * `assets.media_type` is required, and Cyd does not record a MIME type for + * every preserved file — link preview thumbnails have none at all. Reading it + * off the bytes beats defaulting to whatever is most common. + */ +export function sniffMediaType(head: Uint8Array): string | null { + for (const candidate of MAGIC_NUMBERS) { + if (candidate.prefix.every((byte, index) => head[index] === byte)) { + return candidate.mediaType; + } + } + // ISO base media format (MP4 and friends): "ftyp" at offset 4. + if (head[4] === 0x66 && head[5] === 0x74 && head[6] === 0x79 && head[7] === 0x70) { + return "video/mp4"; + } + return null; +} + +/** + * Read and hash every inventoried asset, one at a time. + * + * One file is in memory at most: assets are streamed through the hasher, so a + * long video costs the same as a thumbnail. + */ +export async function resolveStagedAssets( + environment: BlueskyArchiveExportEnvironment, + inventory: StagedAsset[], +): Promise> { + const resolved = new Map(); + + for (const asset of inventory) { + resolved.set(asset.key, await resolveOne(environment, asset)); + } + + return resolved; +} + +async function resolveOne( + environment: BlueskyArchiveExportEnvironment, + asset: StagedAsset, +): Promise { + if (!asset.preserved) { + return unresolved( + asset.key, + "missing", + "Cyd has not finished preserving this file, so it could not be included.", + ); + } + if (!asset.localPath) { + return unresolved( + asset.key, + "missing", + "Cyd has no local copy of this file.", + ); + } + if (asset.stagedByteLength === null) { + return unresolved( + asset.key, + "unavailable", + "The preserved file was no longer on this device when the export was staged.", + ); + } + + const hasher = environment.createHasher(); + const checksum = new Crc32(); + let byteCount = 0; + let head: Uint8Array | null = null; + try { + await environment.readFile(asset.localPath, (bytes) => { + if (head === null) { + head = bytes.slice(0, 12); + } + hasher.update(bytes); + checksum.update(bytes); + byteCount += bytes.length; + }); + } catch { + // The error's own message is discarded rather than reported: it names the + // device path it failed to open, which must not reach the archive. + return unresolved( + asset.key, + "unavailable", + "The preserved file could not be read while the export was being packaged.", + ); + } + + if (byteCount !== asset.stagedByteLength) { + return unresolved( + asset.key, + "unavailable", + "The preserved file changed while the export was being prepared.", + ); + } + + const sha256 = hasher.digestHex(); + return { + key: asset.key, + availability: "available", + sha256, + byteCount, + crc32: checksum.value(), + sniffedMediaType: head === null ? null : sniffMediaType(head), + archivePath: archivePathForDigest(sha256), + localPath: asset.localPath, + }; +} diff --git a/services/archive-export/database-writer.ts b/services/archive-export/database-writer.ts new file mode 100644 index 0000000..27cf104 --- /dev/null +++ b/services/archive-export/database-writer.ts @@ -0,0 +1,51 @@ +import type { BlueskyInterchangeContent } from "./interchange"; +import type { WritableDatabase } from "./ports"; +import { BLUESKY_ARCHIVE_V2_SCHEMA_SQL } from "./schema"; + +/** + * Writing the translated account into a Cyd Bluesky archive's `data.db`. + * + * The insert order is the foreign-key order, not an arbitrary one: SQLite + * enforces references as each row lands, so assets precede the profiles that + * point at them, profiles precede records, and so on. Leaving foreign keys on + * while writing is deliberate — it means a translation bug fails here, while + * the archive is still a staged working file, instead of at import time on + * somebody else's device. + */ +export function writeBlueskyInterchangeDatabase( + database: WritableDatabase, + content: BlueskyInterchangeContent, +): void { + database.exec(BLUESKY_ARCHIVE_V2_SCHEMA_SQL); + + insert(database, "assets", content.assets); + insert(database, "profiles", content.profiles); + insert(database, "records", content.records); + insert(database, "selections", content.selections); + insert(database, "record_subjects", content.recordSubjects); + insert(database, "record_context", content.recordContext); + insert(database, "conversations", content.conversations); + insert(database, "conversation_members", content.conversationMembers); + insert(database, "messages", content.messages); + insert(database, "relationships", content.relationships); + insert(database, "record_assets", content.recordAssets); + insert(database, "portable_settings", content.portableSettings); + insert(database, "identity", [content.identity]); + insert(database, "archive", [content.archive]); +} + +function insert( + database: WritableDatabase, + table: string, + rows: Record[], +): void { + for (const row of rows) { + const columns = Object.keys(row); + database.run( + `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${columns + .map(() => "?") + .join(", ")});`, + columns.map((column) => row[column]), + ); + } +} diff --git a/services/archive-export/deflate.ts b/services/archive-export/deflate.ts new file mode 100644 index 0000000..f822234 --- /dev/null +++ b/services/archive-export/deflate.ts @@ -0,0 +1,69 @@ +import { Deflate } from "fflate"; + +import { Crc32 } from "@/services/archive-import/crc32"; + +import type { BlueskyArchiveExportEnvironment, ExportStagingArea } from "./ports"; + +/** + * Compressing the Bluesky interchange database on its way into the archive. + * + * Media is left stored — JPEG and MP4 do not compress — but `data.db` is + * mostly empty SQLite pages and text, and shrinks by around thirty times. On a + * committed fixture that is the difference between 4 KiB and 144 KiB, and + * committed bytes live in repository history forever. + * + * Compression happens into a second staged file rather than in memory, for the + * same reason the ZIP writer stores everything else: an entry's compressed size + * has to be known before its header is written, and a phone must not have to + * hold a whole account database to find that out. + */ + +export type CompressedStagedFile = { + /** Size and checksum of the original, which is what the ZIP header records. */ + byteLength: number; + crc32: number; + sha256: string; + compressedByteLength: number; + /** Staging-relative path of the compressed copy. */ + compressedPath: string; +}; + +export async function compressStagedFile( + environment: BlueskyArchiveExportEnvironment, + staging: ExportStagingArea, + sourcePath: string, + compressedPath: string, +): Promise { + const output = staging.createFile(compressedPath); + const hasher = environment.createHasher(); + const checksum = new Crc32(); + let byteLength = 0; + let compressedByteLength = 0; + + const deflate = new Deflate((chunk) => { + if (chunk.length > 0) { + output.write(chunk); + compressedByteLength += chunk.length; + } + }); + + try { + await environment.readFile(staging.locate(sourcePath), (bytes) => { + hasher.update(bytes); + checksum.update(bytes); + byteLength += bytes.length; + deflate.push(bytes, false); + }); + deflate.push(new Uint8Array(0), true); + } finally { + output.close(); + } + + return { + byteLength, + crc32: checksum.value(), + sha256: hasher.digestHex(), + compressedByteLength, + compressedPath, + }; +} diff --git a/services/archive-export/environment.ts b/services/archive-export/environment.ts new file mode 100644 index 0000000..b4a6b77 --- /dev/null +++ b/services/archive-export/environment.ts @@ -0,0 +1,219 @@ +import { Directory, File, FileMode } from "expo-file-system"; +import { + defaultDatabaseDirectory, + openDatabaseSync, + type SQLiteDatabase, +} from "expo-sqlite"; +import { createHash } from "react-native-quick-crypto"; + +import { requireStagedFilePath } from "@/services/archive-import/entry-paths"; +import { + ARCHIVE_EXPORT_DIRECTORY, + getArchiveExportStagingRoot, +} from "@/services/device-storage"; + +import type { + BlueskyArchiveExportEnvironment, + ExportStagingArea, + Hasher, + ReadableDatabase, + StagedFileWriter, + WritableDatabase, +} from "./ports"; + +/** + * The device-backed implementation of the export ports. + * + * Everything platform-specific about writing a Cyd Bluesky archive lives here: + * SQLite handles, file handles, hashing, and pausing the account's own jobs. + * The export logic itself never sees any of it, which is what lets the same + * writer run under Node against a pulled account directory (ADR 0016). + */ + +/** How much of a file to read at a time while hashing or packaging. */ +const READ_CHUNK_BYTES = 256 * 1024; + +/** + * expo-sqlite wants a plain directory path, while the file APIs want a + * `file://` URI. Staging keeps both forms of the same location. + */ +function nativeStagingRoot(): string { + const sqliteDirectory = (defaultDatabaseDirectory as string).replace(/\/+$/, ""); + const parent = sqliteDirectory.slice(0, sqliteDirectory.lastIndexOf("/")); + return `${parent}/${ARCHIVE_EXPORT_DIRECTORY}`; +} + +class DeviceExportStagingArea implements ExportStagingArea { + readonly root: string; + readonly nativeRoot: string; + + constructor(exportId: string) { + this.root = `${getArchiveExportStagingRoot()}${exportId}/`; + this.nativeRoot = `${nativeStagingRoot()}/${exportId}`; + new Directory(this.root).create({ intermediates: true, idempotent: true }); + } + + createFile(relativePath: string): StagedFileWriter { + const file = new File(this.locate(relativePath)); + file.create({ intermediates: true, overwrite: true }); + const handle = file.open(FileMode.Truncate); + return { + write: (chunk) => handle.writeBytes(chunk), + close: () => handle.close(), + }; + } + + locate(relativePath: string): string { + return `${this.root}${requireStagedFilePath(relativePath)}`; + } + + /** The same staged file, named the way expo-sqlite expects. */ + locateNative(relativePath: string): { directory: string; name: string } { + const safePath = requireStagedFilePath(relativePath); + const separator = safePath.lastIndexOf("/"); + return separator === -1 + ? { directory: this.nativeRoot, name: safePath } + : { + directory: `${this.nativeRoot}/${safePath.slice(0, separator)}`, + name: safePath.slice(separator + 1), + }; + } + + destroy(): void { + const directory = new Directory(this.root); + if (directory.exists) { + directory.delete(); + } + } +} + +function requireDeviceStaging(staging: ExportStagingArea): DeviceExportStagingArea { + if (!(staging instanceof DeviceExportStagingArea)) { + throw new Error("This export environment only works with its own staging area."); + } + return staging; +} + +function asReadableDatabase(database: SQLiteDatabase): ReadableDatabase { + return { + all: (sql: string) => database.getAllSync(sql), + close: () => database.closeSync(), + }; +} + +function asWritableDatabase(database: SQLiteDatabase): WritableDatabase { + return { + exec: (sql) => database.execSync(sql), + run: (sql, params) => { + database.runSync(sql, params as never[]); + }, + close: () => database.closeSync(), + }; +} + +export type DeviceExportEnvironmentOptions = { + /** The live account database this export copies from. */ + accountDatabase: SQLiteDatabase; + /** + * Stop and restart the account's own save and delete work. + * + * Pausing is what keeps the database copy and the media inventory describing + * one instant. `VACUUM INTO` would give a consistent database either way — + * SQLite sees only committed state — but without the pause a job could add + * media between the copy and the inventory, and the archive would claim an + * asset its own database never mentioned. + */ + pauseAccountWork: () => void; + resumeAccountWork: () => void; +}; + +export function createBlueskyArchiveExportEnvironment( + options: DeviceExportEnvironmentOptions, +): BlueskyArchiveExportEnvironment { + const openStaged = ( + staging: ExportStagingArea, + relativePath: string, + ): SQLiteDatabase => { + const { directory, name } = requireDeviceStaging(staging).locateNative( + relativePath, + ); + return openDatabaseSync(name, {}, directory); + }; + + return { + openStaging: (exportId) => new DeviceExportStagingArea(exportId), + + async withAccountWorkPaused(work) { + options.pauseAccountWork(); + try { + return await work(); + } finally { + options.resumeAccountWork(); + } + }, + + async snapshotAccountDatabase(staging, relativePath) { + const device = requireDeviceStaging(staging); + const { directory, name } = device.locateNative(relativePath); + new Directory(`${device.root}`).create({ + intermediates: true, + idempotent: true, + }); + const existing = new File(device.locate(relativePath)); + if (existing.exists) { + existing.delete(); + } + await options.accountDatabase.runAsync("VACUUM INTO ?;", [ + `${directory}/${name}`, + ]); + }, + + openSnapshot: (staging, relativePath) => + asReadableDatabase(openStaged(staging, relativePath)), + + createBlueskyInterchangeDatabase: (staging, relativePath) => { + const existing = new File(requireDeviceStaging(staging).locate(relativePath)); + if (existing.exists) { + existing.delete(); + } + return asWritableDatabase(openStaged(staging, relativePath)); + }, + + statFile: (location) => { + const file = new File(location); + return file.exists ? { byteLength: file.size ?? 0 } : null; + }, + + async readFile(location, onBytes) { + const file = new File(location); + const handle = file.open(FileMode.ReadOnly); + try { + const total = handle.size ?? file.size ?? 0; + let offset = 0; + while (offset < total) { + handle.offset = offset; + const chunk = handle.readBytes(Math.min(READ_CHUNK_BYTES, total - offset)); + if (chunk.length === 0) { + break; + } + onBytes(chunk); + offset += chunk.length; + } + } finally { + handle.close(); + } + }, + + createHasher: (): Hasher => { + const hash = createHash("sha256"); + return { + update: (chunk) => { + hash.update(chunk); + }, + digestHex: () => hash.digest("hex"), + }; + }, + + now: () => new Date(), + }; +} diff --git a/services/archive-export/errors.ts b/services/archive-export/errors.ts new file mode 100644 index 0000000..af0864a --- /dev/null +++ b/services/archive-export/errors.ts @@ -0,0 +1,33 @@ +/** + * Failures that stop a Cyd Bluesky archive export. + * + * Export is the one archive operation that cannot damage anything it reads: + * every failure here ends with the staged working copy thrown away and the + * Bluesky local account exactly as it was. So these are written as an + * explanation of what Cyd could not produce, not as a warning about data loss. + * + * Note what is *not* here: a missing or unreadable media file is not an export + * failure. It is an unavailable asset and an incomplete Cyd Bluesky archive, + * which is the honest outcome the contract asks for. + */ +export type BlueskyArchiveExportErrorCode = + /** The point-in-time snapshot of the account database could not be taken. */ + | "snapshot-failed" + /** The staged snapshot is not the Bluesky account database it should be. */ + | "unreadable-snapshot" + /** An asset's bytes changed between hashing and packaging. */ + | "asset-changed" + /** A caller asked for an entry a Cyd Bluesky archive cannot contain. */ + | "invalid-entry" + /** Beyond what a non-ZIP64 archive can address. */ + | "archive-too-large"; + +export class BlueskyArchiveExportError extends Error { + readonly code: BlueskyArchiveExportErrorCode; + + constructor(code: BlueskyArchiveExportErrorCode, message: string) { + super(message); + this.name = "BlueskyArchiveExportError"; + this.code = code; + } +} diff --git a/services/archive-export/export.ts b/services/archive-export/export.ts new file mode 100644 index 0000000..ce6fbd7 --- /dev/null +++ b/services/archive-export/export.ts @@ -0,0 +1,337 @@ +import { + classifyBlueskyArchiveMetadata, + type BlueskyArchiveMetadata, +} from "@/services/archive-metadata"; +import { Crc32 } from "@/services/archive-import/crc32"; +import { + DATABASE_ENTRY_PATH, + MANIFEST_ENTRY_PATH, + METADATA_ENTRY_PATH, + type BlueskyArchiveManifestPayload, +} from "@/services/archive-import/manifest"; + +import { resolveStagedAssets } from "./assets"; +import { writeBlueskyInterchangeDatabase } from "./database-writer"; +import { compressStagedFile } from "./deflate"; +import { BlueskyArchiveExportError } from "./errors"; +import { + translateBlueskyAccountToInterchange, + type AssetRow, + type BlueskyInterchangeContent, + type PortableSettings, +} from "./interchange"; +import { readMobileAccountSnapshot } from "./mobile-snapshot"; +import type { + BlueskyArchiveExportEnvironment, + ExportStagingArea, +} from "./ports"; +import { stageBlueskyAccountSnapshot } from "./snapshot"; +import { BlueskyArchiveZipWriter } from "./zip-writer"; + +/** + * Writing one Bluesky local account out as a Cyd Bluesky archive. + * + * The order of the four steps is the whole design: + * + * 1. **Stage** — pause account work, copy the database, inventory the media. + * This is the point in time the archive describes (ADR 0010). + * 2. **Hash** — with saving running again, read every inventoried file. What + * disagrees with the inventory becomes an unavailable asset, not a lie. + * 3. **Translate** — turn Mobile's private rows into the interchange model and + * build `data.db` in staging (ADR 0002). + * 4. **Package** — stream media, database, metadata, and manifest into the ZIP. + * + * Nothing here reads the live account after step 1, so however long steps 2–4 + * take, the archive stays internally consistent. + * + * Building this writer is not the same as offering it to people: until #100 + * proves conformance both ways, export stays behind a development-only + * affordance (ADR 0004). Resumability, staging cleanup, and the plaintext + * warning belong to #99. + */ + +const BLUESKY_INTERCHANGE_PATH = "data.db"; +const COMPRESSED_INTERCHANGE_PATH = "data.db.deflate"; + +export type BlueskyArchiveExportPhase = + | "staging" + | "hashing" + | "translating" + | "packaging" + | "done"; + +export type BlueskyArchiveExportProgress = { + phase: BlueskyArchiveExportPhase; + packagedPayloads: number; + totalPayloads: number; +}; + +export type BlueskyArchiveExportRequest = { + /** Stable id for this export; names its staging directory. */ + exportId: string; + accountUuid: string; + accountDid: string; + accountHandle?: string | null; + /** + * Save and delete defaults to carry as portable settings. + * + * Passed in rather than read here, because they live in Cyd's main database + * alongside credentials and schedules. Only the caller's chosen booleans + * cross this boundary. + */ + portableSettings: PortableSettings; + /** Suggested filename. The format never treats a filename as authoritative. */ + fileName?: string; + onProgress?: (progress: BlueskyArchiveExportProgress) => void; +}; + +export type BlueskyArchiveAssetSummary = { + total: number; + available: number; + missing: number; + unavailable: number; +}; + +export type BlueskyArchiveExportResult = { + exportId: string; + /** Where the finished archive is, inside the export's staging area. */ + location: string; + fileName: string; + byteLength: number; + metadata: BlueskyArchiveMetadata; + assets: BlueskyArchiveAssetSummary; + /** The staging area holding the archive, for the caller to clean up. */ + staging: ExportStagingArea; +}; + +function suggestFileName(request: BlueskyArchiveExportRequest, createdAt: Date): string { + const subject = (request.accountHandle ?? request.accountDid).replace( + /[^a-zA-Z0-9._-]/g, + "-", + ); + return `cyd-bluesky-${subject}-${createdAt.toISOString().slice(0, 10)}.cyd`; +} + +export async function runBlueskyArchiveExport( + environment: BlueskyArchiveExportEnvironment, + request: BlueskyArchiveExportRequest, +): Promise { + const staging = environment.openStaging(request.exportId); + const report = ( + phase: BlueskyArchiveExportPhase, + packaged = 0, + total = 0, + ): void => request.onProgress?.({ phase, packagedPayloads: packaged, totalPayloads: total }); + + try { + report("staging"); + const staged = await stageBlueskyAccountSnapshot(environment, staging); + + report("hashing"); + const assets = await resolveStagedAssets(environment, staged.inventory); + + report("translating"); + const snapshotDatabase = environment.openSnapshot(staging, staged.snapshotPath); + let content: BlueskyInterchangeContent; + try { + content = translateBlueskyAccountToInterchange( + readMobileAccountSnapshot(snapshotDatabase), + { + accountDid: request.accountDid, + accountUuid: request.accountUuid, + createdAt: staged.takenAt, + assets, + portableSettings: request.portableSettings, + }, + ); + } finally { + snapshotDatabase.close(); + } + + const interchange = environment.createBlueskyInterchangeDatabase( + staging, + BLUESKY_INTERCHANGE_PATH, + ); + try { + writeBlueskyInterchangeDatabase(interchange, content); + } finally { + interchange.close(); + } + + const fileName = request.fileName ?? suggestFileName(request, staged.takenAt); + report("packaging", 0, content.payloads.length); + const byteLength = await packageArchive(environment, staging, { + archivePath: fileName, + content, + createdAt: staged.takenAt, + onPayloadPackaged: (packaged) => + report("packaging", packaged, content.payloads.length), + }); + + report("done", content.payloads.length, content.payloads.length); + return { + exportId: request.exportId, + location: staging.locate(fileName), + fileName, + byteLength, + metadata: buildMetadata(content), + assets: summarizeAssets(content), + staging, + }; + } catch (error) { + // An export that failed leaves nothing worth keeping: the archive is + // half-written and the account it came from is untouched. #99 replaces this + // with checkpoints an interrupted export can resume from. + staging.destroy(); + throw error; + } +} + +function buildMetadata(content: BlueskyInterchangeContent): BlueskyArchiveMetadata { + const metadata = { + format: "cyd-archive", + platform: "bluesky", + version: 2, + createdAt: content.archive.created_at, + accountDid: content.archive.account_did, + accountUuid: content.archive.account_uuid, + completeness: content.archive.completeness, + }; + + // Check the writer's own output with the reader's rules before it is + // packaged. A writer that cannot satisfy Cyd's own metadata reader has no + // business claiming to satisfy anybody else's. + const classified = classifyBlueskyArchiveMetadata(metadata); + if (!classified.supported) { + throw new BlueskyArchiveExportError("invalid-entry", classified.error); + } + return classified.metadata; +} + +function summarizeAssets(content: BlueskyInterchangeContent): BlueskyArchiveAssetSummary { + const count = (availability: AssetRow["availability"]): number => + content.assets.filter((asset) => asset.availability === availability).length; + return { + total: content.assets.length, + available: count("available"), + missing: count("missing"), + unavailable: count("unavailable"), + }; +} + +/** + * Stream the finished archive into staging. + * + * Media goes first, then the database, then metadata, and the manifest last — + * it is the only entry that has to know every other entry's digest. Each media + * file is copied straight from the account's storage to the ZIP, so packaging + * never holds more than one chunk of a video in memory. + */ +async function packageArchive( + environment: BlueskyArchiveExportEnvironment, + staging: ExportStagingArea, + options: { + archivePath: string; + content: BlueskyInterchangeContent; + createdAt: Date; + onPayloadPackaged: (packaged: number) => void; + }, +): Promise { + const writer = new BlueskyArchiveZipWriter(staging.createFile(options.archivePath), { + modifiedAt: options.createdAt, + }); + const manifestPayloads: BlueskyArchiveManifestPayload[] = []; + + const payloads = [...options.content.payloads].sort((left, right) => + left.archivePath < right.archivePath ? -1 : 1, + ); + let packaged = 0; + for (const payload of payloads) { + await writer.addStoredEntry( + payload.archivePath, + { byteLength: payload.byteCount, crc32: payload.crc32 }, + (push) => environment.readFile(payload.localPath, push), + ); + manifestPayloads.push({ + path: payload.archivePath, + bytes: payload.byteCount, + sha256: payload.sha256, + }); + packaged += 1; + options.onPayloadPackaged(packaged); + } + + const database = await compressStagedFile( + environment, + staging, + BLUESKY_INTERCHANGE_PATH, + COMPRESSED_INTERCHANGE_PATH, + ); + await writer.addDeflatedEntry( + DATABASE_ENTRY_PATH, + { + byteLength: database.byteLength, + crc32: database.crc32, + compressedByteLength: database.compressedByteLength, + }, + (push) => environment.readFile(staging.locate(database.compressedPath), push), + ); + manifestPayloads.push({ + path: DATABASE_ENTRY_PATH, + bytes: database.byteLength, + sha256: database.sha256, + }); + + const metadata = new TextEncoder().encode( + `${JSON.stringify(buildMetadata(options.content), null, 2)}\n`, + ); + await addBytesEntry(writer, environment, METADATA_ENTRY_PATH, metadata, manifestPayloads); + + const manifest = new TextEncoder().encode( + `${JSON.stringify( + { + algorithm: "sha256", + payloads: manifestPayloads.sort((left, right) => + left.path < right.path ? -1 : 1, + ), + }, + null, + 2, + )}\n`, + ); + await writer.addStoredEntry( + MANIFEST_ENTRY_PATH, + { byteLength: manifest.length, crc32: crc32Of(manifest) }, + async (push) => push(manifest), + ); + + writer.finish(); + return writer.byteLength; +} + +async function addBytesEntry( + writer: BlueskyArchiveZipWriter, + environment: BlueskyArchiveExportEnvironment, + path: string, + bytes: Uint8Array, + manifestPayloads: BlueskyArchiveManifestPayload[], +): Promise { + const hasher = environment.createHasher(); + hasher.update(bytes); + await writer.addStoredEntry( + path, + { byteLength: bytes.length, crc32: crc32Of(bytes) }, + async (push) => push(bytes), + ); + manifestPayloads.push({ + path, + bytes: bytes.length, + sha256: hasher.digestHex(), + }); +} + +function crc32Of(bytes: Uint8Array): number { + const checksum = new Crc32(); + checksum.update(bytes); + return checksum.value(); +} diff --git a/services/archive-export/index.ts b/services/archive-export/index.ts new file mode 100644 index 0000000..6365e6f --- /dev/null +++ b/services/archive-export/index.ts @@ -0,0 +1,36 @@ +/** + * Cyd Bluesky archive export: turning one Bluesky local account into a + * self-contained, point-in-time version 2 archive. + * + * Export is the only component that can produce a Cyd Bluesky archive, which + * is why it is built before the readers that consume it (ADR 0004). Offering + * it to people is a separate decision, gated on #100. + */ + +export { runBlueskyArchiveExport } from "./export"; +export type { + BlueskyArchiveAssetSummary, + BlueskyArchiveExportPhase, + BlueskyArchiveExportProgress, + BlueskyArchiveExportRequest, + BlueskyArchiveExportResult, +} from "./export"; +export { BlueskyArchiveExportError } from "./errors"; +export type { BlueskyArchiveExportErrorCode } from "./errors"; +export { createBlueskyArchiveExportEnvironment } from "./environment"; +export { PORTABLE_SETTING_KEYS, profileIdForDid } from "./interchange"; +export { + portableSettingsFromAccountRow, + type BlueskyAccountSettingsRow, +} from "./portable-settings"; +export type { + PortableSettingKey, + PortableSettings, +} from "./interchange"; +export { BLUESKY_ARCHIVE_V2_SCHEMA_SQL } from "./schema"; +export type { + BlueskyArchiveExportEnvironment, + ExportStagingArea, + ReadableDatabase, + WritableDatabase, +} from "./ports"; diff --git a/services/archive-export/interchange.ts b/services/archive-export/interchange.ts new file mode 100644 index 0000000..5f3ef8e --- /dev/null +++ b/services/archive-export/interchange.ts @@ -0,0 +1,989 @@ +import { previewAssetKey, type ResolvedAsset } from "./assets"; +import type { + MobileAccountSnapshot, + MobileMediaAssetRow, + MobilePostMediaRow, + MobilePostRow, +} from "./mobile-snapshot"; + +/** + * Translating Bluesky saved data into the version 2 interchange model. + * + * This is the other half of the adapter ADR 0002 describes, and it is pure: in + * go Mobile's rows and what the hashing pass learned about each asset, out come + * interchange rows. No database, no filesystem, no clock. + * + * Two rules shape most of the decisions here: + * + * 1. Nothing is invented. Where Mobile does not observe something the contract + * can hold — a like's creation time, a reply parent Cyd never saved — the + * export says so by leaving it out or by falling back to a fact it does + * have, such as the author DID that an AT URI already names. `docs/ + * bluesky-archive-fixtures.md` lists what Mobile cannot populate. + * 2. Nothing private leaks. Only the columns the snapshot reader selected are + * visible here, so local paths, jobs, and UI state cannot reach an archive + * even by accident. + */ + +export type ArchiveRow = { + format: "cyd-archive"; + platform: "bluesky"; + version: 2; + created_at: string; + account_did: string; + account_uuid: string; + completeness: "complete" | "incomplete"; +}; + +export type IdentityRow = { did: string; current_profile_id: string }; + +export type ProfileRow = { + id: string; + did: string; + handle: string | null; + display_name: string | null; + description: string | null; + avatar_asset_id: string | null; + banner_asset_id: string | null; + captured_at: string; +}; + +export type RecordRow = { + uri: string; + cid: string | null; + record_type: string; + author_profile_id: string; + indexed_at: string | null; + created_at: string; + first_observed_at: string; + observed_at: string; + source_deleted_at: string | null; + text: string | null; + facets_json: string | null; + payload_json: string; +}; + +export type SelectionCategory = + | "posts" + | "reposts" + | "likes" + | "bookmarks" + | "chats"; + +export type SelectionRow = { + category: SelectionCategory; + subject_id: string; + selected_at: string; +}; + +export type RecordSubjectRow = { + relationship_uri: string; + subject_record_uri: string; +}; + +export type RecordContextRow = { + record_uri: string; + kind: "reply_parent" | "quote" | "external"; + context_record_uri: string | null; + context_profile_id: string | null; + external_json: string | null; +}; + +export type ConversationRow = { + id: string; + rev: string | null; + first_observed_at: string; + observed_at: string; + source_deleted_at: string | null; +}; + +export type ConversationMemberRow = { + conversation_id: string; + profile_id: string; +}; + +export type MessageRow = { + id: string; + conversation_id: string; + sender_profile_id: string; + sent_at: string; + observed_at: string; + source_deleted_at: string | null; + text: string | null; + facets_json: string | null; + payload_json: string; +}; + +export type RelationshipRow = { + uri: string; + kind: "follow" | "block" | "mute"; + actor_did: string; + subject_did: string; + created_at: string | null; + observed_at: string; + source_deleted_at: string | null; +}; + +export type AssetRow = { + id: string; + kind: "image" | "preview" | "thumbnail" | "video"; + media_type: string; + byte_count: number | null; + sha256: string | null; + archive_path: string | null; + availability: "available" | "missing" | "unavailable"; + unavailable_reason: string | null; + source_url: string | null; + width: number | null; + height: number | null; + alt_text: string | null; +}; + +export type RecordAssetRow = { + owner_type: "record" | "message" | "profile"; + owner_id: string; + asset_id: string; + role: "content" | "preview" | "thumbnail" | "avatar" | "banner"; + position: number; +}; + +export const PORTABLE_SETTING_KEYS = [ + "save_posts", + "save_reposts", + "save_likes", + "save_bookmarks", + "save_chats", + "delete_posts", + "delete_reposts", + "delete_likes", + "delete_bookmarks", + "delete_chats", + "delete_follows", +] as const; + +export type PortableSettingKey = (typeof PORTABLE_SETTING_KEYS)[number]; + +export type PortableSettings = Partial>; + +export type PortableSettingRow = { key: PortableSettingKey; value_json: string }; + +/** One media file to copy into the archive, already hashed. */ +export type ArchivePayload = { + archivePath: string; + localPath: string; + byteCount: number; + crc32: number; + sha256: string; +}; + +export type BlueskyArchiveTranslationContext = { + accountDid: string; + accountUuid: string; + /** When this export was taken; also the archive's `created_at`. */ + createdAt: Date; + /** What the hashing pass concluded about each preserved asset, by CID. */ + assets: Map; + portableSettings: PortableSettings; +}; + +export type BlueskyInterchangeContent = { + archive: ArchiveRow; + identity: IdentityRow; + profiles: ProfileRow[]; + records: RecordRow[]; + selections: SelectionRow[]; + recordSubjects: RecordSubjectRow[]; + recordContext: RecordContextRow[]; + conversations: ConversationRow[]; + conversationMembers: ConversationMemberRow[]; + messages: MessageRow[]; + relationships: RelationshipRow[]; + assets: AssetRow[]; + recordAssets: RecordAssetRow[]; + portableSettings: PortableSettingRow[]; + /** Media the packaging step must copy in, one entry per unique digest. */ + payloads: ArchivePayload[]; + completeness: "complete" | "incomplete"; +}; + +const POST_TYPE = "app.bsky.feed.post"; +const REPOST_TYPE = "app.bsky.feed.repost"; +const LIKE_TYPE = "app.bsky.feed.like"; + +export function profileIdForDid(did: string): string { + return `profile:${did}`; +} + +/** The author DID an AT URI names, which is a fact even without the record. */ +function didFromAtUri(uri: string): string | null { + const match = /^at:\/\/(did:[^/]+)\//.exec(uri); + return match ? match[1] : null; +} + +function isoFromMillis(value: number | null | undefined): string | null { + return value ? new Date(value).toISOString() : null; +} + +/** + * Put a stored timestamp into the RFC 3339 UTC form the contract uses. + * + * A value Cyd cannot parse is passed through untouched rather than replaced: + * the original is at least what Bluesky said, and a substituted "now" would be + * a timestamp nobody observed. + */ +function normalizeTimestamp(value: string): string { + const parsed = Date.parse(value); + return Number.isNaN(parsed) ? value : new Date(parsed).toISOString(); +} + +function parseJson(value: string | null): unknown { + if (!value) { + return null; + } + try { + return JSON.parse(value); + } catch { + return null; + } +} + +/** Sort by one string field, so an unchanged account exports the same rows. */ +function compareBy(field: (row: T) => string) { + return (left: T, right: T): number => { + const a = field(left); + const b = field(right); + return a < b ? -1 : a > b ? 1 : 0; + }; +} + +function dropNulls(value: Record): Record { + return Object.fromEntries( + Object.entries(value).filter(([, entry]) => entry !== null && entry !== undefined), + ); +} + +export function translateBlueskyAccountToInterchange( + snapshot: MobileAccountSnapshot, + context: BlueskyArchiveTranslationContext, +): BlueskyInterchangeContent { + const exportedAt = context.createdAt.toISOString(); + const builder = new InterchangeBuilder(snapshot, context, exportedAt); + return builder.build(); +} + +class InterchangeBuilder { + private readonly profiles = new Map(); + private readonly records = new Map(); + // Keyed by their interchange primary keys. The same repost can reach the + // translation twice — once as a record of its own, once as the viewer state + // on the post it points at — and the archive must say it once. + private readonly selections = new Map(); + private readonly recordSubjects = new Map(); + private readonly recordContext: RecordContextRow[] = []; + private readonly relationships: RelationshipRow[] = []; + private readonly conversations: ConversationRow[] = []; + private readonly conversationMembers: ConversationMemberRow[] = []; + private readonly messages: MessageRow[] = []; + + constructor( + private readonly snapshot: MobileAccountSnapshot, + private readonly context: BlueskyArchiveTranslationContext, + private readonly exportedAt: string, + ) {} + + build(): BlueskyInterchangeContent { + this.addCapturedProfiles(); + const currentProfileId = this.ensureProfile(this.context.accountDid); + + this.addPosts(); + this.addBookmarks(); + this.addContext(); + this.addFollows(); + this.addConversations(); + + const media = this.buildAssets(); + const completeness = media.assets.every( + (asset) => asset.availability === "available", + ) + ? "complete" + : "incomplete"; + + return { + archive: { + format: "cyd-archive", + platform: "bluesky", + version: 2, + created_at: this.exportedAt, + account_did: this.context.accountDid, + account_uuid: this.context.accountUuid, + completeness, + }, + identity: { + did: this.context.accountDid, + current_profile_id: currentProfileId, + }, + profiles: [...this.profiles.values()].sort(compareBy((row) => row.id)), + records: [...this.records.values()].sort(compareBy((row) => row.uri)), + selections: [...this.selections.values()], + recordSubjects: this.knownRecordSubjects(), + recordContext: this.recordContext, + conversations: this.conversations, + conversationMembers: this.conversationMembers, + messages: this.messages, + relationships: this.relationships, + assets: media.assets, + recordAssets: media.recordAssets, + portableSettings: this.buildPortableSettings(), + payloads: media.payloads, + completeness, + }; + } + + /** + * Drop links to a record this archive does not contain. + * + * `record_subjects.subject_record_uri` is a foreign key, so a repost of a + * post Cyd never saved would abort the whole export. Losing one link is the + * right trade against losing the archive, and the repost record itself still + * carries its subject URI in `payload_json`. The pruning happens here rather + * than at insertion time because a later post row can supply the record an + * earlier one referenced. + */ + private knownRecordSubjects(): RecordSubjectRow[] { + return [...this.recordSubjects.values()].filter((row) => + this.records.has(row.subject_record_uri), + ); + } + + private addCapturedProfiles(): void { + for (const row of this.snapshot.profiles) { + this.profiles.set(profileIdForDid(row.did), { + id: profileIdForDid(row.did), + did: row.did, + handle: row.handle, + display_name: row.displayName, + description: null, + avatar_asset_id: null, + banner_asset_id: null, + captured_at: + isoFromMillis(row.updatedAt) ?? + isoFromMillis(row.savedAt) ?? + this.exportedAt, + }); + } + } + + /** + * Reference a Bluesky identity, capturing what little a URI tells us if that + * is all Cyd has. A later, fuller capture fills the stub in rather than + * replacing it, so ordering between callers does not matter. + */ + private ensureProfile( + did: string, + known: { handle?: string | null } = {}, + ): string { + const id = profileIdForDid(did); + const existing = this.profiles.get(id); + if (existing) { + if (!existing.handle && known.handle) { + existing.handle = known.handle; + } + return id; + } + this.profiles.set(id, { + id, + did, + handle: known.handle ?? null, + display_name: null, + description: null, + avatar_asset_id: null, + banner_asset_id: null, + captured_at: this.exportedAt, + }); + return id; + } + + private addPosts(): void { + for (const row of this.snapshot.posts) { + const observedAt = isoFromMillis(row.savedAt) ?? this.exportedAt; + const authorProfileId = this.ensureProfile(row.authorDid); + const isRepostRecord = row.isRepost === 1; + + this.records.set(row.uri, { + uri: row.uri, + cid: row.cid || null, + record_type: isRepostRecord ? REPOST_TYPE : POST_TYPE, + author_profile_id: authorProfileId, + indexed_at: null, + created_at: normalizeTimestamp(row.createdAt), + first_observed_at: observedAt, + observed_at: observedAt, + source_deleted_at: isoFromMillis( + isRepostRecord ? row.deletedRepostAt : row.deletedPostAt, + ), + text: isRepostRecord ? null : row.text, + facets_json: row.facetsJSON, + payload_json: JSON.stringify(this.buildPostPayload(row)), + }); + + if (isRepostRecord) { + this.select("reposts", row.uri, observedAt); + if (row.originalPostUri) { + this.recordSubjects.set(row.uri, { + relationship_uri: row.uri, + subject_record_uri: row.originalPostUri, + }); + } + continue; + } + + if (row.authorDid === this.context.accountDid) { + this.select("posts", row.uri, observedAt); + } + if (row.viewerReposted === 1 && row.repostUri) { + this.addRelationshipRecord({ + uri: row.repostUri, + cid: row.repostCid, + type: REPOST_TYPE, + subjectUri: row.uri, + subjectCid: row.cid, + category: "reposts", + observedAt, + sourceDeletedAt: isoFromMillis(row.deletedRepostAt), + }); + } + if (row.viewerLiked === 1) { + if (row.likeUri) { + this.addRelationshipRecord({ + uri: row.likeUri, + cid: null, + type: LIKE_TYPE, + subjectUri: row.uri, + subjectCid: row.cid, + category: "likes", + observedAt, + sourceDeletedAt: isoFromMillis(row.deletedLikeAt), + }); + } else { + // Cyd knows the post was liked but never saw the like's own URI, so + // the selection points at the post rather than inventing a record. + this.select("likes", row.uri, observedAt); + } + } + } + } + + /** + * Add the like or repost record that made a post part of the backup. + * + * Mobile stores the relationship's URI but never its creation time, so + * `created_at` is the moment Cyd observed it. That is a real timestamp with a + * weaker meaning than Bluesky's own, which is why it is called out in the + * fixtures documentation rather than passed off as the record's age. + */ + private addRelationshipRecord(options: { + uri: string; + cid: string | null; + type: typeof REPOST_TYPE | typeof LIKE_TYPE; + subjectUri: string; + subjectCid: string | null; + category: SelectionCategory; + observedAt: string; + sourceDeletedAt: string | null; + }): void { + // A repost Cyd saved as a record of its own is the better version of the + // same fact: it has the CID and the real creation time. Only fill in for + // one that was never saved on its own. + if (!this.records.has(options.uri)) { + this.records.set(options.uri, this.buildRelationshipRecord(options)); + } + this.recordSubjects.set(options.uri, { + relationship_uri: options.uri, + subject_record_uri: options.subjectUri, + }); + this.select(options.category, options.uri, options.observedAt); + } + + private buildRelationshipRecord(options: { + uri: string; + cid: string | null; + type: typeof REPOST_TYPE | typeof LIKE_TYPE; + subjectUri: string; + subjectCid: string | null; + observedAt: string; + sourceDeletedAt: string | null; + }): RecordRow { + return { + uri: options.uri, + cid: options.cid, + record_type: options.type, + author_profile_id: this.ensureProfile(this.context.accountDid), + indexed_at: null, + created_at: options.observedAt, + first_observed_at: options.observedAt, + observed_at: options.observedAt, + source_deleted_at: options.sourceDeletedAt, + text: null, + facets_json: null, + payload_json: JSON.stringify({ + record: { + $type: options.type, + subject: dropNulls({ + uri: options.subjectUri, + cid: options.subjectCid, + }), + }, + }), + }; + } + + private buildPostPayload(row: MobilePostRow): Record { + const record: Record = { + $type: row.isRepost === 1 ? REPOST_TYPE : POST_TYPE, + }; + if (row.isRepost === 1) { + record.createdAt = normalizeTimestamp(row.createdAt); + if (row.originalPostUri) { + record.subject = { uri: row.originalPostUri }; + } + } else { + record.text = row.text; + record.createdAt = normalizeTimestamp(row.createdAt); + if (row.langs) { + record.langs = row.langs.split(","); + } + if (row.replyParentUri || row.replyRootUri) { + record.reply = dropNulls({ + parent: row.replyParentUri ? { uri: row.replyParentUri } : null, + root: row.replyRootUri ? { uri: row.replyRootUri } : null, + }); + } + } + + const payload: Record = { record }; + const embed = parseJson(row.embedJSON); + if (embed !== null) { + payload.embed = embed; + } + payload.metrics = { + likeCount: row.likeCount, + repostCount: row.repostCount, + replyCount: row.replyCount, + quoteCount: row.quoteCount, + }; + return payload; + } + + /** + * Bookmarks, which Mobile knows only by what they point at. + * + * There is no bookmark record URI in Mobile's storage, so the selection names + * the bookmarked post directly. When that post was never saved in full, the + * denormalized author, text, and creation time the bookmark carries are + * enough for a real record — none of it is guessed. + */ + private addBookmarks(): void { + for (const row of this.snapshot.bookmarks) { + const observedAt = isoFromMillis(row.savedAt) ?? this.exportedAt; + + if (this.records.has(row.subjectUri)) { + this.select("bookmarks", row.subjectUri, observedAt); + continue; + } + const authorDid = row.postAuthorDid ?? didFromAtUri(row.subjectUri); + if (!authorDid) { + // Without an author there is no honest record to write, and a + // selection pointing at nothing is worse than one fewer bookmark. + continue; + } + this.select("bookmarks", row.subjectUri, observedAt); + this.records.set(row.subjectUri, { + uri: row.subjectUri, + cid: null, + record_type: POST_TYPE, + author_profile_id: this.ensureProfile(authorDid, { + handle: row.postAuthorHandle, + }), + indexed_at: null, + created_at: row.postCreatedAt + ? normalizeTimestamp(row.postCreatedAt) + : observedAt, + first_observed_at: observedAt, + observed_at: observedAt, + source_deleted_at: null, + text: row.postText, + facets_json: null, + payload_json: JSON.stringify({ + record: dropNulls({ + $type: POST_TYPE, + text: row.postText, + createdAt: row.postCreatedAt + ? normalizeTimestamp(row.postCreatedAt) + : observedAt, + }), + }), + }); + } + } + + /** + * The bounded context a record needs to make sense on its own. + * + * When the referenced record is part of the backup, the context points at it. + * When it is not, the context still names its author, because the AT URI says + * who that is. Nothing recurses: a reply parent's own parent is not pulled in. + */ + private addContext(): void { + for (const row of this.snapshot.posts) { + if (row.isRepost === 1) { + continue; + } + if (row.isReply === 1 && row.replyParentUri) { + this.addReferenceContext(row.uri, "reply_parent", row.replyParentUri); + } + if (row.isQuote === 1 && row.quotedPostUri) { + this.addReferenceContext(row.uri, "quote", row.quotedPostUri); + } + } + + for (const row of this.snapshot.postExternals) { + if (!this.records.has(row.postUri)) { + continue; + } + this.recordContext.push({ + record_uri: row.postUri, + kind: "external", + context_record_uri: null, + context_profile_id: null, + external_json: JSON.stringify( + dropNulls({ + uri: row.uri, + title: row.title, + description: row.description, + thumbUrl: row.thumbUrl, + }), + ), + }); + } + } + + private addReferenceContext( + recordUri: string, + kind: "reply_parent" | "quote", + referencedUri: string, + ): void { + const referenced = this.records.get(referencedUri); + const authorDid = referenced + ? this.profiles.get(referenced.author_profile_id)?.did + : didFromAtUri(referencedUri); + + this.recordContext.push({ + record_uri: recordUri, + kind, + context_record_uri: referenced ? referencedUri : null, + context_profile_id: authorDid ? this.ensureProfile(authorDid) : null, + external_json: null, + }); + } + + /** + * Follows, which Mobile does not actually save today. + * + * The `follow` table exists in Mobile's schema but nothing writes it — the + * unfollow-everyone job fetches follows live instead — so `relationships` is + * empty in practice. The translation is here because the table is, and + * because the day Mobile starts saving follows this should already be right. + */ + private addFollows(): void { + for (const row of this.snapshot.follows) { + this.ensureProfile(row.subjectDid, { handle: row.handle }); + this.relationships.push({ + uri: row.uri, + kind: "follow", + actor_did: this.context.accountDid, + subject_did: row.subjectDid, + created_at: row.createdAt ? normalizeTimestamp(row.createdAt) : null, + observed_at: isoFromMillis(row.savedAt) ?? this.exportedAt, + source_deleted_at: isoFromMillis(row.unfollowedAt), + }); + } + } + + private addConversations(): void { + const known = new Set(); + + for (const row of this.snapshot.conversations) { + const firstObserved = isoFromMillis(row.savedAt) ?? this.exportedAt; + known.add(row.convoId); + this.conversations.push({ + id: row.convoId, + rev: row.rev, + first_observed_at: firstObserved, + observed_at: isoFromMillis(row.updatedAt) ?? firstObserved, + // Leaving a conversation calls `chat.bsky.convo.leaveConvo` before + // `leftAt` is stamped, so it is removal at the source, not a local flag. + source_deleted_at: isoFromMillis(row.leftAt), + }); + this.select("chats", row.convoId, firstObserved); + + const members = parseJson(row.memberDids); + const seen = new Set(); + if (Array.isArray(members)) { + for (const member of members) { + if (typeof member !== "string" || seen.has(member)) { + continue; + } + seen.add(member); + this.conversationMembers.push({ + conversation_id: row.convoId, + profile_id: this.ensureProfile(member), + }); + } + } + } + + for (const row of this.snapshot.messages) { + if (!known.has(row.convoId)) { + continue; + } + const observedAt = isoFromMillis(row.savedAt) ?? this.exportedAt; + const embed = parseJson(row.embedJSON); + this.messages.push({ + id: row.messageId, + conversation_id: row.convoId, + sender_profile_id: this.ensureProfile(row.senderDid), + sent_at: normalizeTimestamp(row.sentAt), + observed_at: observedAt, + source_deleted_at: isoFromMillis(row.deletedAt), + text: row.text, + facets_json: row.facetsJSON, + payload_json: JSON.stringify( + dropNulls({ + record: { $type: "chat.bsky.convo.defs#messageView", text: row.text }, + embed, + }), + ), + }); + } + } + + /** + * Every asset an exported record refers to, each unique file exactly once. + * + * Deduplication happens twice over: Mobile already stores one file per blob + * CID within an account (ADR 0007), and two files that turn out to hash the + * same collapse here, because the interchange model keys assets by digest. + * + * Record media and link preview thumbnails both land here, from different + * Mobile storage. A preview Cyd never managed to download is not an asset at + * all — its URL stays in the record's external context, and its absence does + * not make the archive incomplete, because Mobile never counted it as part of + * the Bluesky saved data either. + */ + private buildAssets(): { + assets: AssetRow[]; + recordAssets: RecordAssetRow[]; + payloads: ArchivePayload[]; + } { + const metadata = new Map( + this.snapshot.mediaAssets.map((row) => [row.contentCid, row]), + ); + const assets: AssetRow[] = []; + const recordAssets: RecordAssetRow[] = []; + const payloads: ArchivePayload[] = []; + const assetIdByKey = new Map(); + const assetIdByDigest = new Map(); + + /** Add an asset once, collapsing anything that hashes the same. */ + const register = (key: string, build: (resolved: ResolvedAsset | undefined) => AssetRow): string => { + const existing = assetIdByKey.get(key); + if (existing) { + return existing; + } + + const resolved = this.context.assets.get(key); + const row = build(resolved); + const duplicate = row.sha256 ? assetIdByDigest.get(row.sha256) : undefined; + + const assetId = duplicate ?? row.id; + if (!duplicate) { + assets.push(row); + if (row.sha256 && row.archive_path && resolved?.availability === "available") { + assetIdByDigest.set(row.sha256, row.id); + payloads.push({ + archivePath: row.archive_path, + localPath: resolved.localPath, + byteCount: resolved.byteCount, + crc32: resolved.crc32, + sha256: row.sha256, + }); + } + } + assetIdByKey.set(key, assetId); + return assetId; + }; + + for (const media of this.snapshot.postMedia) { + if (!media.assetCid || !this.records.has(media.postUri)) { + continue; + } + const assetId = register(media.assetCid, (resolved) => + this.buildMediaAssetRow( + media.assetCid as string, + metadata.get(media.assetCid as string), + media, + resolved, + ), + ); + recordAssets.push({ + owner_type: "record", + owner_id: media.postUri, + asset_id: assetId, + role: "content", + position: media.position, + }); + } + + for (const external of this.snapshot.postExternals) { + if (!this.records.has(external.postUri)) { + continue; + } + const key = previewAssetKey(external.postUri); + if (!this.context.assets.has(key)) { + continue; + } + const assetId = register(key, (resolved) => + this.buildPreviewAssetRow(key, external.thumbUrl, resolved), + ); + recordAssets.push({ + owner_type: "record", + owner_id: external.postUri, + asset_id: assetId, + role: "preview", + position: 0, + }); + } + + return { assets, recordAssets, payloads }; + } + + private buildMediaAssetRow( + contentCid: string, + metadata: MobileMediaAssetRow | undefined, + media: MobilePostMediaRow, + resolved: ResolvedAsset | undefined, + ): AssetRow { + const kind = + (metadata?.mediaType ?? media.mediaType) === "video" ? "video" : "image"; + const sourceMetadata = parseJson(metadata?.sourceMetadataJSON ?? null) as + | { width?: number; height?: number; alt?: string } + | null; + + return this.finishAssetRow( + { + id: contentCid, + kind, + media_type: this.mediaTypeFor(metadata?.mimeType, kind, resolved), + source_url: metadata?.sourceUrl ?? null, + width: media.width ?? sourceMetadata?.width ?? null, + height: media.height ?? sourceMetadata?.height ?? null, + alt_text: media.alt ?? sourceMetadata?.alt ?? null, + }, + resolved, + ); + } + + private buildPreviewAssetRow( + key: string, + sourceUrl: string | null, + resolved: ResolvedAsset | undefined, + ): AssetRow { + return this.finishAssetRow( + { + id: key, + kind: "preview", + media_type: this.mediaTypeFor(null, "image", resolved), + source_url: sourceUrl, + width: null, + height: null, + alt_text: null, + }, + resolved, + ); + } + + /** + * What Cyd recorded, else what the bytes say, else what the kind implies. + */ + private mediaTypeFor( + stored: string | null | undefined, + kind: "image" | "video", + resolved: ResolvedAsset | undefined, + ): string { + if (stored) { + return stored; + } + if (resolved?.availability === "available" && resolved.sniffedMediaType) { + return resolved.sniffedMediaType; + } + return kind === "video" ? "video/mp4" : "image/jpeg"; + } + + private finishAssetRow( + common: Omit< + AssetRow, + "byte_count" | "sha256" | "archive_path" | "availability" | "unavailable_reason" + >, + resolved: ResolvedAsset | undefined, + ): AssetRow { + if (resolved?.availability === "available") { + return { + ...common, + byte_count: resolved.byteCount, + sha256: resolved.sha256, + archive_path: resolved.archivePath, + availability: "available", + unavailable_reason: null, + }; + } + + return { + ...common, + byte_count: null, + sha256: null, + archive_path: null, + availability: resolved?.availability ?? "missing", + unavailable_reason: + resolved === undefined + ? "Cyd has no record of preserving this file." + : resolved.reason, + }; + } + + private buildPortableSettings(): PortableSettingRow[] { + return PORTABLE_SETTING_KEYS.filter( + (key) => this.context.portableSettings[key] !== undefined, + ) + .map((key) => ({ + key, + value_json: JSON.stringify(this.context.portableSettings[key]), + })) + .sort(compareBy((row) => row.key)); + } + + /** Record that a subject was selected for saving, at most once per category. */ + private select( + category: SelectionCategory, + subjectId: string, + selectedAt: string, + ): void { + const key = `${category}\u0000${subjectId}`; + if (!this.selections.has(key)) { + this.selections.set(key, { + category, + subject_id: subjectId, + selected_at: selectedAt, + }); + } + } +} diff --git a/services/archive-export/mobile-snapshot.ts b/services/archive-export/mobile-snapshot.ts new file mode 100644 index 0000000..c2366a7 --- /dev/null +++ b/services/archive-export/mobile-snapshot.ts @@ -0,0 +1,254 @@ +import { previewAssetKey } from "./assets"; +import type { ReadableDatabase } from "./ports"; + +/** + * Reading Cyd Mobile's private per-account storage, and nothing else. + * + * This is one half of the version 2 adapter ADR 0002 calls for: the only place + * that knows Mobile's runtime column names. Everything downstream works on + * these row types, so a Mobile migration lands here and stops here instead of + * reaching the interchange model. + * + * The queries are also the privacy boundary in practice. `config`, `job`, and + * the local-only columns (`localPath`, `thumbLocalPath`, `preserve`) are not + * selected at all, so no later step can leak what it never received. + */ + +export type MobileProfileRow = { + did: string; + handle: string; + displayName: string | null; + savedAt: number; + updatedAt: number; +}; + +export type MobilePostRow = { + uri: string; + cid: string; + authorDid: string; + text: string; + facetsJSON: string | null; + embedJSON: string | null; + langs: string | null; + isReply: number; + replyParentUri: string | null; + replyRootUri: string | null; + isQuote: number; + quotedPostUri: string | null; + isRepost: number; + repostUri: string | null; + repostCid: string | null; + originalPostUri: string | null; + likeCount: number; + repostCount: number; + replyCount: number; + quoteCount: number; + viewerLiked: number; + viewerReposted: number; + viewerBookmarked: number; + createdAt: string; + savedAt: number; + deletedPostAt: number | null; + deletedRepostAt: number | null; + deletedLikeAt: number | null; + deletedBookmarkAt: number | null; + likeUri: string | null; +}; + +export type MobilePostMediaRow = { + postUri: string; + position: number; + mediaType: string; + alt: string | null; + width: number | null; + height: number | null; + assetCid: string | null; +}; + +export type MobilePostExternalRow = { + postUri: string; + uri: string; + title: string; + description: string | null; + thumbUrl: string | null; +}; + +export type MobileBookmarkRow = { + subjectUri: string; + postAuthorDid: string | null; + postAuthorHandle: string | null; + postText: string | null; + postCreatedAt: string | null; + savedAt: number; + deletedAt: number | null; +}; + +export type MobileFollowRow = { + uri: string; + subjectDid: string; + handle: string; + createdAt: string; + savedAt: number; + unfollowedAt: number | null; +}; + +export type MobileConversationRow = { + convoId: string; + rev: string | null; + memberDids: string; + savedAt: number; + updatedAt: number; + leftAt: number | null; +}; + +export type MobileMessageRow = { + messageId: string; + convoId: string; + rev: string | null; + senderDid: string; + text: string; + facetsJSON: string | null; + embedJSON: string | null; + sentAt: string; + savedAt: number; + deletedAt: number | null; +}; + +export type MobileMediaAssetRow = { + contentCid: string; + mediaType: string; + mimeType: string | null; + sourceUrl: string | null; + sourceMetadataJSON: string | null; + downloadState: string; + lastError: string | null; +}; + +/** + * Where a preserved asset's bytes are, which only the staging step may know. + * + * Deliberately not part of {@link MobileAccountSnapshot}: `localPath` is a + * device filesystem path, and the contract's privacy boundary keeps those out + * of a Cyd Bluesky archive. Translation never receives one. Neither is + * `media_asset.lastError` read anywhere — a stored download error is an error + * report, which the same boundary excludes. + */ +export type MobileInventoryRow = { + key: string; + localPath: string | null; + preserved: boolean; +}; + +export type MobileAccountSnapshot = { + profiles: MobileProfileRow[]; + posts: MobilePostRow[]; + postMedia: MobilePostMediaRow[]; + postExternals: MobilePostExternalRow[]; + bookmarks: MobileBookmarkRow[]; + follows: MobileFollowRow[]; + conversations: MobileConversationRow[]; + messages: MobileMessageRow[]; + mediaAssets: MobileMediaAssetRow[]; +}; + +/** + * Read everything an export needs out of one staged snapshot. + * + * Ordering is by stable identifier throughout, so two exports of unchanged + * data produce the same Bluesky interchange database rather than the same data + * in a + * different order. + */ +export function readMobileAccountSnapshot( + database: ReadableDatabase, +): MobileAccountSnapshot { + return { + profiles: database.all( + `SELECT did, handle, displayName, savedAt, updatedAt + FROM profile ORDER BY did;`, + ), + posts: database.all( + `SELECT uri, cid, authorDid, text, facetsJSON, embedJSON, langs, + isReply, replyParentUri, replyRootUri, + isQuote, quotedPostUri, + isRepost, repostUri, repostCid, originalPostUri, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, viewerReposted, viewerBookmarked, + createdAt, savedAt, + deletedPostAt, deletedRepostAt, deletedLikeAt, deletedBookmarkAt, + likeUri + FROM post ORDER BY uri;`, + ), + postMedia: database.all( + `SELECT postUri, position, mediaType, alt, width, height, assetCid + FROM post_media ORDER BY postUri, position;`, + ), + postExternals: database.all( + `SELECT postUri, uri, title, description, thumbUrl + FROM post_external ORDER BY postUri;`, + ), + bookmarks: database.all( + `SELECT subjectUri, postAuthorDid, postAuthorHandle, postText, + postCreatedAt, savedAt, deletedAt + FROM bookmark ORDER BY subjectUri;`, + ), + follows: database.all( + `SELECT uri, subjectDid, handle, createdAt, savedAt, unfollowedAt + FROM follow ORDER BY uri;`, + ), + conversations: database.all( + `SELECT convoId, rev, memberDids, savedAt, updatedAt, leftAt + FROM conversation ORDER BY convoId;`, + ), + messages: database.all( + `SELECT messageId, convoId, rev, senderDid, text, facetsJSON, embedJSON, + sentAt, savedAt, deletedAt + FROM message ORDER BY messageId;`, + ), + mediaAssets: database.all( + `SELECT contentCid, mediaType, mimeType, sourceUrl, + sourceMetadataJSON, downloadState, lastError + FROM media_asset ORDER BY contentCid;`, + ), + }; +} + +/** + * List where each preserved asset's bytes live, for the staging step alone. + * + * Taken from the same staged snapshot as everything else, so the inventory and + * the database agree on one point in time even if saving resumes immediately + * afterwards (ADR 0010). + * + * Two kinds of file are preserved on this device. Record media is + * content-addressed in `media_asset` and tracks its own download state. A link + * preview's thumbnail is not: `post_external` either has the file or it does + * not, so having a path is the whole of "preserved" for one. + */ +export function readAssetInventory(database: ReadableDatabase): MobileInventoryRow[] { + const media = database + .all<{ contentCid: string; localPath: string | null; downloadState: string }>( + `SELECT contentCid, localPath, downloadState + FROM media_asset ORDER BY contentCid;`, + ) + .map((row) => ({ + key: row.contentCid, + localPath: row.localPath, + preserved: row.downloadState === "complete", + })); + + const previews = database + .all<{ postUri: string; thumbLocalPath: string }>( + `SELECT postUri, thumbLocalPath + FROM post_external + WHERE thumbLocalPath IS NOT NULL + ORDER BY postUri;`, + ) + .map((row) => ({ + key: previewAssetKey(row.postUri), + localPath: row.thumbLocalPath, + preserved: true, + })); + + return [...media, ...previews]; +} diff --git a/services/archive-export/portable-settings.ts b/services/archive-export/portable-settings.ts new file mode 100644 index 0000000..9709f19 --- /dev/null +++ b/services/archive-export/portable-settings.ts @@ -0,0 +1,59 @@ +import type { PortableSettings } from "./interchange"; + +/** + * Which Bluesky account settings are portable, and which stay on the device. + * + * A Cyd Bluesky archive carries save and delete *defaults* — what the person + * chose to back up and what they chose to delete — because those make a + * restored account useful immediately. It carries no schedule, because a + * portable setting is a default and never authority to run deletion somewhere + * else (ADR 0015, and the contract's privacy boundary). + * + * Mobile has no separate "save reposts" switch: reposts come with posts. The + * key is left out rather than guessed at, so an importer sees "Mobile did not + * say" instead of a preference nobody set. + */ + +export type BlueskyAccountSettingsRow = { + settingSavePosts?: number | null; + settingSaveLikes?: number | null; + settingSaveBookmarks?: number | null; + settingSaveChats?: number | null; + settingDeletePosts?: number | null; + settingDeleteReposts?: number | null; + settingDeleteLikes?: number | null; + settingDeleteBookmarks?: number | null; + settingDeleteChats?: number | null; + settingDeleteUnfollowEveryone?: number | null; +}; + +const PORTABLE_COLUMNS = { + save_posts: "settingSavePosts", + save_likes: "settingSaveLikes", + save_bookmarks: "settingSaveBookmarks", + save_chats: "settingSaveChats", + delete_posts: "settingDeletePosts", + delete_reposts: "settingDeleteReposts", + delete_likes: "settingDeleteLikes", + delete_bookmarks: "settingDeleteBookmarks", + delete_chats: "settingDeleteChats", + // Mobile's unfollow-everyone switch is the delete-follows default. + delete_follows: "settingDeleteUnfollowEveryone", +} as const satisfies Partial>; + +export function portableSettingsFromAccountRow( + row: BlueskyAccountSettingsRow | null | undefined, +): PortableSettings { + if (!row) { + return {}; + } + + const settings: PortableSettings = {}; + for (const [key, column] of Object.entries(PORTABLE_COLUMNS)) { + const value = row[column as keyof BlueskyAccountSettingsRow]; + if (value !== undefined && value !== null) { + settings[key as keyof PortableSettings] = value !== 0; + } + } + return settings; +} diff --git a/services/archive-export/ports.ts b/services/archive-export/ports.ts new file mode 100644 index 0000000..898dcd6 --- /dev/null +++ b/services/archive-export/ports.ts @@ -0,0 +1,89 @@ +import type { CreateHasher } from "@/services/archive-import/ports"; + +/** + * The platform capabilities a Cyd Bluesky archive export needs. + * + * Export is pure logic over these ports, the same way intake is: pausing + * account work, snapshotting SQLite, reading preserved media, hashing, and + * writing staged files. React Native supplies them from `expo-sqlite` and + * `expo-file-system`; a Node adapter supplies them from `node:sqlite` and + * `node:fs`, which is what lets a curated test account be exported into a + * committed fixture without a device round trip (ADR 0016). + */ + +export type { CreateHasher, Hasher } from "@/services/archive-import/ports"; + +/** Read-only, synchronous access to a staged SQLite snapshot. */ +export type ReadableDatabase = { + all(sql: string): T[]; + close(): void; +}; + +/** The Bluesky interchange database being built in staging. */ +export type WritableDatabase = { + exec(sql: string): void; + run(sql: string, params: unknown[]): void; + close(): void; +}; + +export type StagedFileWriter = { + write(chunk: Uint8Array): void; + close(): void; +}; + +/** + * A directory that only ever holds one export's working files. + * + * Everything an export produces lands here first — the database snapshot, the + * Bluesky interchange database, the archive itself — so a failure or + * cancellation is one directory to delete, and nothing half-written is ever mistaken for a + * finished Cyd Bluesky archive. + */ +export type ExportStagingArea = { + readonly root: string; + createFile(relativePath: string): StagedFileWriter; + /** Absolute location of a staged file, for the file and SQLite ports. */ + locate(relativePath: string): string; + destroy(): void; +}; + +export type FileStat = { byteLength: number }; + +export type BlueskyArchiveExportEnvironment = { + openStaging(exportId: string): ExportStagingArea; + + /** + * Hold account-mutating work still for the duration of `work`. + * + * The pause is what makes the snapshot and the media inventory describe one + * moment (ADR 0010), so it covers as little as possible: a SQLite copy and a + * stat of each preserved file, never hashing or packaging. + */ + withAccountWorkPaused(work: () => Promise): Promise; + + /** Copy the live account database into staging as one consistent snapshot. */ + snapshotAccountDatabase( + staging: ExportStagingArea, + relativePath: string, + ): Promise; + + openSnapshot(staging: ExportStagingArea, relativePath: string): ReadableDatabase; + + /** Create an empty database in staging for the Bluesky interchange model. */ + createBlueskyInterchangeDatabase( + staging: ExportStagingArea, + relativePath: string, + ): WritableDatabase; + + /** Size of a file, or null when it is not there. */ + statFile(location: string): FileStat | null; + + /** Stream a file, in whatever chunks storage gives back. */ + readFile( + location: string, + onBytes: (bytes: Uint8Array) => void, + ): Promise; + + createHasher: CreateHasher; + now(): Date; +}; diff --git a/services/archive-export/schema.ts b/services/archive-export/schema.ts new file mode 100644 index 0000000..1c0d619 --- /dev/null +++ b/services/archive-export/schema.ts @@ -0,0 +1,160 @@ +/** + * The Cyd Bluesky archive version 2 interchange schema, verbatim. + * + * This is a copy of `schema.sql` from the pinned canonical contract bundle + * (ADR 0008), because a writer running on a phone cannot fetch the contract at + * export time. The contract requires `data.db` to implement it *exactly*, so + * this text is not a paraphrase and must not be "improved" locally: + * `npm run test:archive-contract` compares it against the pinned bundle and + * fails if the two ever drift. + * + * It is deliberately separate from `database/account-db/bluesky-migrations.ts`. + * That schema is Mobile's private runtime storage and evolves on Mobile's + * schedule; this one is the shared interchange model and only ever changes + * when the contract does (ADR 0002). + */ +export const BLUESKY_ARCHIVE_V2_SCHEMA_SQL = `PRAGMA application_id = 0x43594232; +PRAGMA user_version = 2; +PRAGMA foreign_keys = ON; + +CREATE TABLE archive ( + format TEXT NOT NULL CHECK (format = 'cyd-archive'), + platform TEXT NOT NULL CHECK (platform = 'bluesky'), + version INTEGER NOT NULL CHECK (version = 2), + created_at TEXT NOT NULL, + account_did TEXT NOT NULL, + account_uuid TEXT NOT NULL, + completeness TEXT NOT NULL CHECK (completeness IN ('complete', 'incomplete')) +); + +CREATE TABLE identity ( + did TEXT PRIMARY KEY, + current_profile_id TEXT NOT NULL +); + +CREATE TABLE profiles ( + id TEXT PRIMARY KEY, + did TEXT NOT NULL, + handle TEXT, + display_name TEXT, + description TEXT, + avatar_asset_id TEXT REFERENCES assets(id), + banner_asset_id TEXT REFERENCES assets(id), + captured_at TEXT NOT NULL +); + +CREATE TABLE records ( + uri TEXT PRIMARY KEY, + cid TEXT, + record_type TEXT NOT NULL, + author_profile_id TEXT NOT NULL REFERENCES profiles(id), + indexed_at TEXT, + created_at TEXT NOT NULL, + first_observed_at TEXT NOT NULL, + observed_at TEXT NOT NULL, + source_deleted_at TEXT, + text TEXT, + facets_json TEXT, + payload_json TEXT NOT NULL +); + +CREATE TABLE selections ( + category TEXT NOT NULL CHECK (category IN ('posts', 'reposts', 'likes', 'bookmarks', 'chats')), + subject_id TEXT NOT NULL, + selected_at TEXT NOT NULL, + PRIMARY KEY (category, subject_id) +); + +CREATE TABLE record_subjects ( + relationship_uri TEXT PRIMARY KEY REFERENCES records(uri), + subject_record_uri TEXT NOT NULL REFERENCES records(uri) +); + +CREATE TABLE record_context ( + record_uri TEXT NOT NULL REFERENCES records(uri), + kind TEXT NOT NULL CHECK (kind IN ('reply_parent', 'quote', 'external')), + context_record_uri TEXT, + context_profile_id TEXT REFERENCES profiles(id), + external_json TEXT, + PRIMARY KEY (record_uri, kind) +); + +CREATE TABLE conversations ( + id TEXT PRIMARY KEY, + rev TEXT, + first_observed_at TEXT NOT NULL, + observed_at TEXT NOT NULL, + source_deleted_at TEXT +); + +CREATE TABLE conversation_members ( + conversation_id TEXT NOT NULL REFERENCES conversations(id), + profile_id TEXT NOT NULL REFERENCES profiles(id), + PRIMARY KEY (conversation_id, profile_id) +); + +CREATE TABLE messages ( + id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL REFERENCES conversations(id), + sender_profile_id TEXT NOT NULL REFERENCES profiles(id), + sent_at TEXT NOT NULL, + observed_at TEXT NOT NULL, + source_deleted_at TEXT, + text TEXT, + facets_json TEXT, + payload_json TEXT NOT NULL +); + +CREATE TABLE relationships ( + uri TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('follow', 'block', 'mute')), + actor_did TEXT NOT NULL, + subject_did TEXT NOT NULL, + created_at TEXT, + observed_at TEXT NOT NULL, + source_deleted_at TEXT +); + +CREATE TABLE assets ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('image', 'preview', 'thumbnail', 'video')), + media_type TEXT NOT NULL, + byte_count INTEGER CHECK (byte_count IS NULL OR byte_count >= 0), + sha256 TEXT UNIQUE CHECK (sha256 IS NULL OR (length(sha256) = 64 AND sha256 = lower(sha256))), + archive_path TEXT UNIQUE, + availability TEXT NOT NULL CHECK (availability IN ('available', 'missing', 'unavailable')), + unavailable_reason TEXT, + source_url TEXT, + width INTEGER, + height INTEGER, + alt_text TEXT, + CHECK ( + (availability = 'available' AND byte_count IS NOT NULL AND sha256 IS NOT NULL AND archive_path IS NOT NULL AND unavailable_reason IS NULL) + OR + (availability != 'available' AND byte_count IS NULL AND sha256 IS NULL AND archive_path IS NULL AND unavailable_reason IS NOT NULL) + ) +); + +CREATE TABLE record_assets ( + owner_type TEXT NOT NULL CHECK (owner_type IN ('record', 'message', 'profile')), + owner_id TEXT NOT NULL, + asset_id TEXT NOT NULL REFERENCES assets(id), + role TEXT NOT NULL CHECK (role IN ('content', 'preview', 'thumbnail', 'avatar', 'banner')), + position INTEGER NOT NULL CHECK (position >= 0), + PRIMARY KEY (owner_type, owner_id, role, position) +); + +CREATE TABLE portable_settings ( + key TEXT PRIMARY KEY CHECK (key IN ( + 'save_posts', 'save_reposts', 'save_likes', 'save_bookmarks', 'save_chats', + 'delete_posts', 'delete_reposts', 'delete_likes', 'delete_bookmarks', + 'delete_chats', 'delete_follows' + )), + value_json TEXT NOT NULL +); + +CREATE INDEX records_author ON records(author_profile_id); +CREATE INDEX records_observed ON records(observed_at); +CREATE INDEX messages_conversation ON messages(conversation_id, sent_at); +CREATE INDEX assets_availability ON assets(availability); +`; diff --git a/services/archive-export/snapshot.ts b/services/archive-export/snapshot.ts new file mode 100644 index 0000000..5f5a345 --- /dev/null +++ b/services/archive-export/snapshot.ts @@ -0,0 +1,71 @@ +import type { StagedAsset } from "./assets"; +import { BlueskyArchiveExportError } from "./errors"; +import { readAssetInventory } from "./mobile-snapshot"; +import type { BlueskyArchiveExportEnvironment, ExportStagingArea } from "./ports"; + +/** + * Taking the one moment a Cyd Bluesky archive describes (ADR 0010). + * + * Everything an export claims comes from here: a SQLite copy of the account + * database, and a list of where each preserved file was and how big it was at + * that instant. Both are taken with account-mutating work paused, so they + * cannot disagree with each other — a save job that resumes a millisecond + * later can add records and files, but it cannot change what this snapshot + * already saw. + * + * The pause covers only these two things. Hashing megabytes of video and + * packaging a ZIP with saving frozen would be a long, visible stall for no + * benefit: an asset that changes after the inventory is caught by comparing it + * against the inventory, and reported as unavailable. + */ + +export const SNAPSHOT_DATABASE_PATH = "snapshot.db"; + +export type StagedAccountSnapshot = { + /** Staging-relative path of the copied account database. */ + snapshotPath: string; + inventory: StagedAsset[]; + takenAt: Date; +}; + +export async function stageBlueskyAccountSnapshot( + environment: BlueskyArchiveExportEnvironment, + staging: ExportStagingArea, +): Promise { + return environment.withAccountWorkPaused(async () => { + try { + await environment.snapshotAccountDatabase(staging, SNAPSHOT_DATABASE_PATH); + } catch (error) { + throw new BlueskyArchiveExportError( + "snapshot-failed", + `Cyd could not copy this account's data for export: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + + const database = environment.openSnapshot(staging, SNAPSHOT_DATABASE_PATH); + try { + const inventory = readAssetInventory(database).map((row) => ({ + ...row, + stagedByteLength: row.localPath + ? (environment.statFile(row.localPath)?.byteLength ?? null) + : null, + })); + return { + snapshotPath: SNAPSHOT_DATABASE_PATH, + inventory, + takenAt: environment.now(), + }; + } catch (error) { + throw new BlueskyArchiveExportError( + "unreadable-snapshot", + `Cyd could not read the copy it made of this account's data: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } finally { + database.close(); + } + }); +} diff --git a/services/archive-export/zip-writer.ts b/services/archive-export/zip-writer.ts new file mode 100644 index 0000000..c35f483 --- /dev/null +++ b/services/archive-export/zip-writer.ts @@ -0,0 +1,287 @@ +import { Crc32 } from "@/services/archive-import/crc32"; +import { checkZipEntryPath } from "@/services/archive-import/entry-paths"; + +import { BlueskyArchiveExportError } from "./errors"; + +/** + * The ZIP half of a Cyd Bluesky archive writer. + * + * Every entry's header is complete before its first byte is written, so an + * archive is produced in one sequential pass with no seeking and no data + * descriptors. That is why callers declare each entry's size and CRC up front: + * both come from an earlier pass over the same bytes, and re-checking them here + * turns "the file changed underneath us" into an error instead of a corrupt + * archive. + * + * Media is stored rather than deflated. JPEG and MP4 do not compress, and a + * streaming deflate cannot know its compressed size until it finishes — which + * on a phone packaging a multi-gigabyte video would mean buffering the whole + * entry. Something already compressed into a staged file can be added with + * {@link BlueskyArchiveZipWriter.addDeflatedEntry}, which is how `data.db` gets + * in without paying for its empty SQLite pages. + */ + +const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50; +const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50; +const END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50; + +const STORED = 0; +const DEFLATED = 8; +const VERSION_NEEDED = 20; +/** "Made by" Unix (3), so the mode in the external attributes is meaningful. */ +const VERSION_MADE_BY = (3 << 8) | VERSION_NEEDED; +/** Bit 11: entry names are UTF-8. */ +const FLAG_UTF8_NAMES = 0x0800; +/** A regular file, rw-r--r--, in the high 16 bits of the external attributes. */ +const REGULAR_FILE_ATTRIBUTES = 0o100644 << 16; + +/** ZIP without ZIP64 cannot describe an entry or an offset past this. */ +const MAX_ZIP32_BYTES = 0xffffffff; + +/** Where an archive's bytes go: a staged file on device, memory in tests. */ +export type ArchiveByteSink = { + write(chunk: Uint8Array): void; + close(): void; +}; + +export type DeclaredEntry = { + byteLength: number; + crc32: number; +}; + +/** Hands an entry's bytes to the writer, in as many chunks as it likes. */ +export type EntryProducer = (push: (bytes: Uint8Array) => void) => Promise; + +type WrittenEntry = { + path: string; + method: number; + byteLength: number; + compressedByteLength: number; + crc32: number; + localHeaderOffset: number; +}; + +const encoder = new TextEncoder(); + +function uint16(value: number): Uint8Array { + const bytes = new Uint8Array(2); + new DataView(bytes.buffer).setUint16(0, value, true); + return bytes; +} + +function uint32(value: number): Uint8Array { + const bytes = new Uint8Array(4); + new DataView(bytes.buffer).setUint32(0, value >>> 0, true); + return bytes; +} + +/** MS-DOS date and time, which is what a ZIP header carries. */ +function dosTimestamp(date: Date): { time: number; date: number } { + const year = Math.max(date.getUTCFullYear(), 1980); + return { + time: + (date.getUTCHours() << 11) | + (date.getUTCMinutes() << 5) | + (date.getUTCSeconds() >> 1), + date: + ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(), + }; +} + +export class BlueskyArchiveZipWriter { + private readonly entries: WrittenEntry[] = []; + private readonly dos: { time: number; date: number }; + private offset = 0; + private finished = false; + + constructor( + private readonly sink: ArchiveByteSink, + options: { modifiedAt?: Date } = {}, + ) { + this.dos = dosTimestamp(options.modifiedAt ?? new Date(Date.UTC(1980, 0, 1))); + } + + /** + * Write one entry, streaming its bytes straight through to the sink. + * + * A size or checksum that disagrees with what was declared throws *after* + * the entry's header is already written, so the caller must treat a failure + * here as fatal to the whole archive and discard it. That is the point: an + * archive whose payload no longer matches what was hashed is exactly what + * the manifest exists to make impossible. + */ + async addStoredEntry( + path: string, + declared: DeclaredEntry, + produce: EntryProducer, + ): Promise { + await this.addEntry(path, { ...declared, method: STORED }, produce); + } + + /** + * Write an entry whose bytes were already compressed into staging. + * + * `byteLength` and `crc32` describe the *original*, because that is what a + * ZIP header records and what a reader checks after inflating. The writer + * can only verify the compressed byte count itself; the checksum comes from + * the compression pass, which is the one place that saw the original bytes. + */ + async addDeflatedEntry( + path: string, + declared: DeclaredEntry & { compressedByteLength: number }, + produce: EntryProducer, + ): Promise { + await this.addEntry(path, { ...declared, method: DEFLATED }, produce); + } + + private async addEntry( + path: string, + declared: DeclaredEntry & { method: number; compressedByteLength?: number }, + produce: EntryProducer, + ): Promise { + this.requireUnfinished(); + const compressedByteLength = + declared.compressedByteLength ?? declared.byteLength; + const verifyChecksum = declared.method === STORED; + const safePath = this.requireEntryPath(path); + if (this.entries.some((entry) => entry.path === safePath)) { + throw new BlueskyArchiveExportError( + "invalid-entry", + `Refusing to write ${safePath} into the archive more than once.`, + ); + } + if ( + declared.byteLength > MAX_ZIP32_BYTES || + compressedByteLength > MAX_ZIP32_BYTES || + this.offset > MAX_ZIP32_BYTES + ) { + throw new BlueskyArchiveExportError( + "archive-too-large", + "This archive is larger than the Cyd Bluesky archive format can describe.", + ); + } + + const name = encoder.encode(safePath); + const localHeaderOffset = this.offset; + + this.push(uint32(LOCAL_FILE_HEADER_SIGNATURE)); + this.push(uint16(VERSION_NEEDED)); + this.push(uint16(FLAG_UTF8_NAMES)); + this.push(uint16(declared.method)); + this.push(uint16(this.dos.time)); + this.push(uint16(this.dos.date)); + this.push(uint32(declared.crc32)); + this.push(uint32(compressedByteLength)); + this.push(uint32(declared.byteLength)); + this.push(uint16(name.length)); + this.push(uint16(0)); + this.push(name); + + const checksum = new Crc32(); + let written = 0; + await produce((bytes) => { + written += bytes.length; + if (written > compressedByteLength) { + throw new BlueskyArchiveExportError( + "asset-changed", + `${safePath} declared ${compressedByteLength} bytes but produced more.`, + ); + } + checksum.update(bytes); + this.push(bytes); + }); + + if (written !== compressedByteLength) { + throw new BlueskyArchiveExportError( + "asset-changed", + `${safePath} declared ${compressedByteLength} bytes but produced ${written}.`, + ); + } + if (verifyChecksum && checksum.value() !== declared.crc32 >>> 0) { + throw new BlueskyArchiveExportError( + "asset-changed", + `${safePath} changed while it was being packaged.`, + ); + } + + this.entries.push({ + path: safePath, + method: declared.method, + byteLength: declared.byteLength, + compressedByteLength, + crc32: declared.crc32, + localHeaderOffset, + }); + } + + /** Write the central directory and close the sink. */ + finish(): void { + this.requireUnfinished(); + this.finished = true; + + const centralDirectoryOffset = this.offset; + for (const entry of this.entries) { + const name = encoder.encode(entry.path); + this.push(uint32(CENTRAL_FILE_HEADER_SIGNATURE)); + this.push(uint16(VERSION_MADE_BY)); + this.push(uint16(VERSION_NEEDED)); + this.push(uint16(FLAG_UTF8_NAMES)); + this.push(uint16(entry.method)); + this.push(uint16(this.dos.time)); + this.push(uint16(this.dos.date)); + this.push(uint32(entry.crc32)); + this.push(uint32(entry.compressedByteLength)); + this.push(uint32(entry.byteLength)); + this.push(uint16(name.length)); + this.push(uint16(0)); + this.push(uint16(0)); + this.push(uint16(0)); + this.push(uint16(0)); + this.push(uint32(REGULAR_FILE_ATTRIBUTES)); + this.push(uint32(entry.localHeaderOffset)); + this.push(name); + } + const centralDirectoryBytes = this.offset - centralDirectoryOffset; + + this.push(uint32(END_OF_CENTRAL_DIRECTORY_SIGNATURE)); + this.push(uint16(0)); + this.push(uint16(0)); + this.push(uint16(this.entries.length)); + this.push(uint16(this.entries.length)); + this.push(uint32(centralDirectoryBytes)); + this.push(uint32(centralDirectoryOffset)); + this.push(uint16(0)); + + this.sink.close(); + } + + /** Total bytes written so far, which is the archive's size once finished. */ + get byteLength(): number { + return this.offset; + } + + private push(bytes: Uint8Array): void { + this.sink.write(bytes); + this.offset += bytes.length; + } + + private requireUnfinished(): void { + if (this.finished) { + throw new BlueskyArchiveExportError( + "invalid-entry", + "This archive has already been finished.", + ); + } + } + + private requireEntryPath(path: string): string { + const check = checkZipEntryPath(path); + if (!check.ok || check.isDirectory) { + throw new BlueskyArchiveExportError( + "invalid-entry", + `Refusing to write an archive entry at ${path}: an entry path must be a normalized relative file path.`, + ); + } + return check.path; + } +} diff --git a/services/device-storage.ts b/services/device-storage.ts index e03132f..6b6a1cd 100644 --- a/services/device-storage.ts +++ b/services/device-storage.ts @@ -38,3 +38,23 @@ export const ARCHIVE_STAGING_DIRECTORY = "archive-intake"; export function getArchiveStagingRoot(): string { return `${getDocumentRoot()}${ARCHIVE_STAGING_DIRECTORY}/`; } + +/** + * Directory holding in-progress Bluesky archive export staging. + * + * Mirrors `ARCHIVE_EXPORT_PATH` in plugins/android-backup-rules.js. + */ +export const ARCHIVE_EXPORT_DIRECTORY = "archive-export"; + +/** + * Where an export assembles an archive while it works. + * + * Durable rather than cache storage for the same reason import staging is: an + * export the system interrupts has to be resumable on the next launch (ADR + * 0006), and the cache can be evicted underneath it. It is excluded from + * device backup: a half-written archive is working state, and the Bluesky + * saved data it was built from is backed up already (ADR 0014). + */ +export function getArchiveExportStagingRoot(): string { + return `${getDocumentRoot()}${ARCHIVE_EXPORT_DIRECTORY}/`; +} diff --git a/testUtils/fixtures/bluesky-archive/README.md b/testUtils/fixtures/bluesky-archive/README.md new file mode 100644 index 0000000..82bb274 --- /dev/null +++ b/testUtils/fixtures/bluesky-archive/README.md @@ -0,0 +1,75 @@ +# Real-data Cyd Bluesky archive fixtures + +`complete.cyd` and `incomplete.cyd` are Cyd Bluesky archives Cyd Mobile's own +version 2 writer produced from a curated Bluesky test account (ADR 0016). They +carry real facets, CIDs, JPEG bytes, and real identifiers, which synthetic +generation does not reproduce. + +They demonstrate **Mobile's behavior**, never the contract's meaning. The +pinned canonical bundle remains the semantic oracle (ADR 0008): if these and +`npm run test:archive-contract` ever disagree about what version 2 requires, +the bundle is right and these are wrong. + +## Provenance + +| | | +| --- | --- | +| Account | `glittertop-cyd.bsky.social`, `did:plc:yn45xekh5kqrat27w6rmafcg` | +| Bluesky local account UUID | `b67bfc6c-6155-47ef-8273-71593e04f01a` | +| Pulled from | Android device (SM-S916U1), 2026-09-11 | +| Written by | the writer at `d93a981`, plus the `--created-at` flag added alongside these files | +| Contract pinned at | `cbd261484d0f3cac4f1c997c423db7730d5d3009` (`scripts/archive-contract/pin.json`) | +| `archive.created_at` | `2026-09-11T16:41:02.492Z`, pinned so the pair differs by one asset alone | +| Size | 2.6 MiB + 0.7 MiB = 3.3 MiB, against a 5 MiB budget | + +Both pass `npm run check:archive-conformance`. + +## What the pair is + +`incomplete.cyd` differs from `complete.cyd` by exactly one asset — the 1.9 MiB +image, whose download was failed for the length of that one export — and by the +`archive.completeness` value that follows from it. Every other row in every +other table is identical. It is the largest payload on purpose: failing it is +what keeps the second fixture small. + +## What they cover + +| Covered | Not covered | +| --- | --- | +| 16 posts, 2 reposts, 1 like, 1 conversation with 7 messages | bookmarks — none were saved | +| 5 images across 4 posts, 6 `record_assets` | video — the account's two videos were 45 MiB of its 48 MiB | +| 3 quotes, one resolving to a record in the archive | replies — every reply in the account was written by somebody else | +| portable save and delete settings | external context and `preview` assets — the only link post was somebody else's | +| an asset that is `missing`, and an honestly incomplete archive | `relationships` — Mobile never saves follows locally (see below) | + +`docs/bluesky-archive-fixtures.md` lists everything Mobile cannot populate at +all, which is a longer list than this one. + +### Whose data is in here + +Only accounts the maintainer controls: `glittertop-cyd.bsky.social` and, as the +other party to the conversation, `aurorabyte-cyd.bsky.social`. Every post +written by somebody else was removed before export, along with both videos. + +One exception, deliberate: `did:plc:z72i7hdynmk6r22z27h6tvur` appears as a +profile row with no handle and no other content. A post of the account's own +quotes that record, and an AT URI names its author, so the quote context keeps +the DID. Removing it would mean removing the quote. + +## Regenerating them + +The account they came from no longer exists in this state — it kept being used. +Regenerating from a *new* curated account is the supported path, and it will +produce different identifiers; that is fine, because nothing should assert on +these specific URIs. Follow `docs/bluesky-archive-fixtures.md`, and pass the +same `--created-at` to both exports. + +The curation applied to this one, on a pulled copy rather than on the device: + +- removed both posts carrying video (45 MiB of 48 MiB); +- removed every post written by somebody else — three reposts and one like of + `bsky.app`, one like each of two individuals' posts; +- removed the media, link previews, and captured profiles those left behind. + +Likes and reposts survived that because the account had liked one of its own +posts and reposted two others. diff --git a/testUtils/fixtures/bluesky-archive/complete.cyd b/testUtils/fixtures/bluesky-archive/complete.cyd new file mode 100644 index 0000000..4a2dc81 Binary files /dev/null and b/testUtils/fixtures/bluesky-archive/complete.cyd differ diff --git a/testUtils/fixtures/bluesky-archive/incomplete.cyd b/testUtils/fixtures/bluesky-archive/incomplete.cyd new file mode 100644 index 0000000..7a28341 Binary files /dev/null and b/testUtils/fixtures/bluesky-archive/incomplete.cyd differ diff --git a/tsconfig.json b/tsconfig.json index a0b481a..6cf3449 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,6 +18,7 @@ "database/**/*.ts", "hooks/**/*.ts", "hooks/**/*.tsx", + "scripts/**/*.ts", "services/**/*.ts", "testUtils/**/*.ts", "testUtils/**/*.tsx",