diff --git a/apps/desktop/scripts/connection-progress-smoke.mjs b/apps/desktop/scripts/connection-progress-smoke.mjs index 8068d1666..bba7700a1 100644 --- a/apps/desktop/scripts/connection-progress-smoke.mjs +++ b/apps/desktop/scripts/connection-progress-smoke.mjs @@ -54,7 +54,7 @@ try { app.exit = () => {}; }); const pairingWindow = await firstApp.firstWindow({ timeout: 15_000 }); - await pairingWindow.getByRole("heading", { name: "Connect this computer." }).waitFor(); + await pairingWindow.getByRole("heading", { name: "Connect this computer to mdbase" }).waitFor(); await pairingWindow.getByText("Use another Connect server", { exact: true }).click(); await pairingWindow.getByLabel("Server address").fill(portalUrl); await pairingWindow.getByLabel("Computer name").fill("Progress test computer"); diff --git a/apps/desktop/scripts/docker-server-e2e.mjs b/apps/desktop/scripts/docker-server-e2e.mjs index a75914309..2c7d7e14f 100644 --- a/apps/desktop/scripts/docker-server-e2e.mjs +++ b/apps/desktop/scripts/docker-server-e2e.mjs @@ -61,7 +61,7 @@ try { }); const pairingWindow = await pairingApp.firstWindow({ timeout: 30_000 }); pairingWindow.setDefaultTimeout(30_000); - await waitForDesktopHeading(pairingWindow, "Connect this computer."); + await waitForDesktopHeading(pairingWindow, "Connect this computer to mdbase"); await pairingWindow .getByText("Use another Connect server", { exact: true }) .click(); diff --git a/apps/desktop/scripts/electron-smoke.mjs b/apps/desktop/scripts/electron-smoke.mjs index 843e008e1..bf9e3143b 100644 --- a/apps/desktop/scripts/electron-smoke.mjs +++ b/apps/desktop/scripts/electron-smoke.mjs @@ -43,7 +43,7 @@ try { if (screenshot) await window.screenshot({ path: screenshot, animations: "disabled" }); await window.getByRole("button", { name: "Cancel" }).click(); await window.getByRole("button", { name: /App access/ }).click(); - await window.getByRole("heading", { name: "Connect this computer." }).waitFor(); + await window.getByRole("heading", { name: "Connect this computer to mdbase" }).waitFor(); await window.getByRole("button", { name: /Overview/ }).click(); const title = await window.title(); if (title !== "mdbase connect") throw new Error(`Unexpected window title: ${title}`); diff --git a/apps/desktop/src/main/deep-link.ts b/apps/desktop/src/main/deep-link.ts index 8181b98cb..b21534ad7 100644 --- a/apps/desktop/src/main/deep-link.ts +++ b/apps/desktop/src/main/deep-link.ts @@ -17,7 +17,7 @@ export function routeForDeepLink(value: string | undefined): string | null { const collectionId = url.searchParams.get("collection"); return collectionId ? `collections:mirror:${collectionId}` : "collections"; } - if (url.hostname === "paired") return "overview"; + if (url.hostname === "paired") return "paired"; } catch { return null; } diff --git a/apps/desktop/src/main/main.ts b/apps/desktop/src/main/main.ts index 95a5ff325..69035efde 100644 --- a/apps/desktop/src/main/main.ts +++ b/apps/desktop/src/main/main.ts @@ -365,7 +365,7 @@ function registerIpc(): void { server_url: string | null; }>("account.configuration"); if (!configuration.configured || !configuration.server_url) { - throw new Error("Connect this computer to a portal first."); + throw new Error("Connect this computer to your mdbase account first."); } const accountUrl = new URL("/account", validateServerUrl(configuration.server_url)); await shell.openExternal(accountUrl.href); @@ -380,7 +380,7 @@ function registerIpc(): void { server_url: string | null; }>("account.configuration"); if (!configuration.configured || !configuration.server_url) { - throw new Error("Connect this computer to a portal first."); + throw new Error("Connect this computer to your mdbase account first."); } const authorizationUrl = new URL( `/authorize/${encodeURIComponent(requestId)}`, diff --git a/apps/desktop/src/renderer/authority-transfer-receipt.tsx b/apps/desktop/src/renderer/authority-transfer-receipt.tsx new file mode 100644 index 000000000..4881c80b1 --- /dev/null +++ b/apps/desktop/src/renderer/authority-transfer-receipt.tsx @@ -0,0 +1,35 @@ +import React from "react"; +import type { AuthorityTransferReceipt as Receipt } from "./onboarding-state.mjs"; + +export function AuthorityTransferReceipt({ receipt, onOpen, onReconnect, onViewDetails, onDismiss }: { + receipt: Receipt; + onOpen(): void; + onReconnect(): void; + onViewDetails(): void; + onDismiss(): void; +}) { + const local = receipt.direction === "hosted_to_local"; + return
+
+
+

Main copy moved

+

{receipt.collectionName} has a new main copy.

+
+ +
+
+
New main copy
{receipt.newMainCopy}
+
Previous authority
{receipt.oldAuthority}
+
Completed
{new Date(receipt.completedAt).toLocaleString()}
+
+
+

{receipt.applications.length} {receipt.applications.length === 1 ? "application needs" : "applications need"} fresh access{receipt.applications.length ? `: ${receipt.applications.join(", ")}` : "."}

+

{receipt.replicas.length} {receipt.replicas.length === 1 ? "synced folder was" : "synced folders were"} retired{receipt.replicas.length ? `: ${receipt.replicas.join(", ")}` : "."}

+
+
+ + {receipt.applications.length > 0 && } + +
+
; +} diff --git a/apps/desktop/src/renderer/collections-view.tsx b/apps/desktop/src/renderer/collections-view.tsx index 7f3db8553..da0132582 100644 --- a/apps/desktop/src/renderer/collections-view.tsx +++ b/apps/desktop/src/renderer/collections-view.tsx @@ -6,6 +6,12 @@ import { plural, relativeTime } from "./view-model"; +import { + clearTransferProgress, + readTransferProgress, + writeTransferProgress, + type AuthorityTransferReceipt +} from "./onboarding-state.mjs"; const FILE_CLASS_OPTIONS: Array<{ value: DesktopFileMediaClass; @@ -133,9 +139,11 @@ function SelectiveSyncSettings({ value, disabled, onChange }: { export function Collections({ collections, hosted, + grants, cloudConfigured, mirrors, mirrorTarget, + detailTarget, authorityConflicts, busy, copiedCollectionPath, @@ -144,14 +152,19 @@ export function Collections({ onCreate, onRegisterCopy, onMirrorTargetHandled, + onDetailTargetHandled, onAct, + onTransfer, + onTransferComplete, onNotice }: { collections: CollectionSummary[]; hosted: HostedControlSnapshot; + grants: GrantSummary[]; cloudConfigured: boolean; mirrors: DesktopMirrorSummary[]; mirrorTarget: string | null; + detailTarget: string | null; authorityConflicts: AuthorityConflict[]; busy: boolean; copiedCollectionPath: string | null; @@ -160,12 +173,29 @@ export function Collections({ onCreate(): void; onRegisterCopy(): void; onMirrorTargetHandled(): void; + onDetailTargetHandled(): void; onAct(action: () => Promise): Promise; + onTransfer(action: () => Promise): Promise; + onTransferComplete(receipt: AuthorityTransferReceipt): void; onNotice(value: string): void; }) { + const localIds = new Set(collections.map((collection) => collection.id)); + const retiredByLocalId = new Map(); + for (const collection of hosted.hosted_collections) { + if (collection.authority_state !== "transferred" || !collection.transferred_collection_id + || !localIds.has(collection.transferred_collection_id)) continue; + const history = retiredByLocalId.get(collection.transferred_collection_id) ?? []; + history.push(collection); + retiredByLocalId.set(collection.transferred_collection_id, history); + } + const visibleHosted = hosted.hosted_collections.filter((collection) => + collection.authority_state !== "transferred" + || !collection.transferred_collection_id + || !localIds.has(collection.transferred_collection_id) + ); return (
- + @@ -222,9 +252,15 @@ export function Collections({ ))} @@ -239,21 +275,26 @@ export function Collections({ : hosted.online ? "Available to approved apps without this computer." : "Hosted controls are offline; last known state is shown."} - count={hosted.hosted_collections.length} + count={visibleHosted.length} /> - {hosted.hosted_collections.length === 0 ? ( + {visibleHosted.length === 0 ? ( ) : (
- {hosted.hosted_collections.map((collection) => ( + {visibleHosted.map((collection) => ( ))} @@ -264,16 +305,34 @@ export function Collections({ ); } -function CollectionRow({ collection, cloudConfigured, busy, onAct, onNotice }: { +function CollectionRow({ collection, grants, authorityHistory, cloudConfigured, openDetails, busy, onTargetHandled, onAct, onTransfer, onTransferComplete, onNotice }: { collection: CollectionSummary; + grants: GrantSummary[]; + authorityHistory: HostedCollectionSummary[]; cloudConfigured: boolean; + openDetails: boolean; busy: boolean; + onTargetHandled(): void; onAct(action: () => Promise): Promise; + onTransfer(action: () => Promise): Promise; + onTransferComplete(receipt: AuthorityTransferReceipt): void; onNotice(value: string): void; }) { + const savedTransfer = readTransferProgress(localStorage); const [editing, setEditing] = useState(false); const [name, setName] = useState(collection.display_name); const [description, setDescription] = useState(collection.description ?? ""); + const [transferReviewing, setTransferReviewing] = useState(savedTransfer?.collectionId === collection.id); + const [transferStarted, setTransferStarted] = useState(savedTransfer?.collectionId === collection.id); + const [transferPhase, setTransferPhase] = useState<"uploading" | "finishing" | null>(null); + const affectedApplications = uniqueNames(grants + .filter((grant) => grant.collection_id === collection.id && grant.revocation_status !== "revoked") + .map((grant) => grant.application_name)); + useEffect(() => { + if (!openDetails) return; + setEditing(true); + onTargetHandled(); + }, [onTargetHandled, openDetails]); useEffect(() => { if (!editing) { setName(collection.display_name); @@ -304,6 +363,10 @@ function CollectionRow({ collection, cloudConfigured, busy, onAct, onNotice }: {
+ {authorityHistory.length > 0 &&
+ History and recovery + {authorityHistory.map((entry) => `${entry.display_name}: hosted copy retained for recovery`).join(" · ")} +
} {editing &&
{ event.preventDefault(); void onAct(async () => { const updated = await window.mdbaseConnect.updateCollectionMetadata({ collectionId: collection.id, name, description }); setEditing(false); onNotice(`${updated.display_name} details were saved to mdbase.yaml.`); }); }}>
@@ -331,28 +394,64 @@ function CollectionRow({ collection, cloudConfigured, busy, onAct, onNotice }: { Keep this collection available without this computer while this folder continues to sync edits both ways.
- + disabled={busy || transferPhase !== null || !cloudConfigured || !collection.enabled} + onClick={() => setTransferReviewing(true)} + >Review main-copy move} {!cloudConfigured && Connect this computer to an account first.}
+ {transferReviewing && setTransferReviewing(false)} + onApprove={() => { + setTransferStarted(true); + setTransferPhase("uploading"); + writeTransferProgress(localStorage, { + collectionId: collection.id, + collectionName: collection.display_name, + direction: "local_to_hosted", + phase: "uploading" + }); + void onTransfer(async () => { + try { + const result = await window.mdbaseConnect.transferCollectionAuthority(collection.id); + setTransferPhase("finishing"); + onTransferComplete({ + collectionId: result.mirror.collection_id, + collectionName: collection.display_name, + direction: "local_to_hosted", + newMainCopy: "Hosted by mdbase", + oldAuthority: `Folder retained as a synced copy · ${collection.path}`, + applications: affectedApplications, + replicas: [], + completedAt: new Date().toISOString() + }); + clearTransferProgress(localStorage); + setTransferStarted(false); + setEditing(false); + setTransferReviewing(false); + } finally { + setTransferPhase(null); + } + }); + }} + />}
Removing this collection from mdbase connect never deletes its files. @@ -364,19 +463,29 @@ function CollectionRow({ collection, cloudConfigured, busy, onAct, onNotice }: { function HostedCollectionRow({ collection, + grants, mirrors, openMirror, + openDetails, busy, onTargetHandled, + onDetailTargetHandled, onAct, + onTransfer, + onTransferComplete, onNotice }: { collection: HostedCollectionSummary; + grants: GrantSummary[]; mirrors: DesktopMirrorSummary[]; openMirror: boolean; + openDetails: boolean; busy: boolean; onTargetHandled(): void; + onDetailTargetHandled(): void; onAct(action: () => Promise): Promise; + onTransfer(action: () => Promise): Promise; + onTransferComplete(receipt: AuthorityTransferReceipt): void; onNotice(value: string): void; }) { const [editing, setEditing] = useState(openMirror); @@ -385,8 +494,12 @@ function HostedCollectionRow({ const [mode, setMode] = useState<"read_only" | "read_write">("read_write"); const [syncPolicy, setSyncPolicy] = useState(emptySelectiveSyncPolicy); const [promotionStarting, setPromotionStarting] = useState(false); + const [promotionReviewing, setPromotionReviewing] = useState(false); const mirror = mirrors.find((candidate) => candidate.collection_id === collection.id); const activeReplicas = collection.replicas.filter((replica) => replica.revocation_status !== "revoked"); + const affectedApplications = uniqueNames(grants + .filter((grant) => grant.collection_id === collection.id && grant.revocation_status !== "revoked") + .map((grant) => grant.application_name)); const editorCollectionId = collection.authority_state === "active" ? collection.id : collection.authority_state === "transferred" @@ -399,12 +512,20 @@ function HostedCollectionRow({ onTargetHandled(); } }, [onTargetHandled, openMirror]); + useEffect(() => { + if (!openDetails) return; + setEditing(true); + onDetailTargetHandled(); + }, [onDetailTargetHandled, openDetails]); useEffect(() => { if (!editing) setName(collection.display_name); }, [collection.display_name, editing]); useEffect(() => { setSyncPolicy(mirror?.selective_sync ?? emptySelectiveSyncPolicy()); }, [mirror?.replica_id, JSON.stringify(mirror?.selective_sync)]); + useEffect(() => { + if (mirror?.promotion_pending) setPromotionReviewing(true); + }, [mirror?.promotion_pending]); async function chooseMirrorFolder() { const selected = await window.mdbaseConnect.chooseMirrorFolder(); @@ -577,42 +698,54 @@ function HostedCollectionRow({ {promotion.title} {promotion.detail}
- + {mirror.promotion_pending ? "Review and resume" : "Review main-copy move"} + } + {promotionReviewing && replica.id !== mirror.replica_id).map((replica) => replica.name)} + recovery="The hosted authority is retained as recovery history after it stops accepting changes. Local files in retired replicas remain on their computers." + cancellation="Cancellation is available while waiting for approval and preparation. It is unavailable after authority fencing begins." + instruction="Keep Connect open and this computer awake while it synchronizes, verifies, registers, and activates the folder." + phase={mirror.promotion?.phase ? promotion.detail : promotionStarting ? "Opening browser approval" : null} + action={mirror.promotion_pending ? "Resume main-copy move" : "Continue to approval"} + disabled={!promotion.enabled} + onCancel={() => setPromotionReviewing(false)} + onApprove={() => { + setPromotionStarting(true); + void onTransfer(async () => { + try { + const result = await window.mdbaseConnect.promoteMirrorAuthority(mirror.replica_id); + onTransferComplete({ + collectionId: result.collection_id, + collectionName: collection.display_name, + direction: "hosted_to_local", + newMainCopy: result.path, + oldAuthority: "Hosted copy retained for recovery", + applications: affectedApplications, + replicas: activeReplicas.filter((replica) => replica.id !== mirror.replica_id).map((replica) => replica.name), + completedAt: new Date().toISOString() + }); + setEditing(false); + setPromotionReviewing(false); + } finally { + setPromotionStarting(false); + } + }); + }} + />} )} {activeReplicas.some((replica) => replica.id !== mirror?.replica_id) && ( @@ -646,3 +779,65 @@ function HostedCollectionRow({ ); } + +function AuthorityTransferPreflight({ + currentMainCopy, + proposedMainCopy, + sourceReady, + targetReady, + lastSync, + inventory, + applications, + replicas, + recovery, + cancellation, + instruction, + phase, + action, + disabled, + onCancel, + onApprove +}: { + currentMainCopy: string; + proposedMainCopy: string; + sourceReady: string; + targetReady: string; + lastSync: string; + inventory: string; + applications: string[]; + replicas: string[]; + recovery: string; + cancellation: string; + instruction: string; + phase: string | null; + action: string; + disabled: boolean; + onCancel(): void; + onApprove(): void; +}) { + return
+
+
Current main copy{currentMainCopy}{sourceReady}
+ +
Proposed main copy{proposedMainCopy}{targetReady}
+
+
+
Latest sync
{lastSync}
+
Transfer inventory
{inventory}
+
Applications revoked
{applications.length ? applications.join(", ") : "No active application grants"}
+
Other replicas retired
{replicas.length ? replicas.join(", ") : "No other active replicas"}
+
Recovery
{recovery}
+
Cancellation boundary
{cancellation}
+
+

{instruction}

+ {phase &&
{phase}
} +
+ + +
+
; +} + +function uniqueNames(names: string[]): string[] { + return [...new Set(names)].sort((left, right) => left.localeCompare(right)); +} diff --git a/apps/desktop/src/renderer/completion-receipt.tsx b/apps/desktop/src/renderer/completion-receipt.tsx new file mode 100644 index 000000000..ead18155d --- /dev/null +++ b/apps/desktop/src/renderer/completion-receipt.tsx @@ -0,0 +1,37 @@ +import React from "react"; +import type { CollectionCompletionReceipt as Receipt } from "./onboarding-state.mjs"; + +export function CollectionCompletionReceipt({ receipt, hasPendingAuthorization, onOpenFolder, onUseInApplication, onOpenEditor, onViewDetails, onAddSyncedFolder, onDismiss }: { + receipt: Receipt; + hasPendingAuthorization: boolean; + onOpenFolder(): void; + onUseInApplication(): void; + onOpenEditor(): void; + onViewDetails(): void; + onAddSyncedFolder(): void; + onDismiss(): void; +}) { + const local = receipt.authority === "local"; + return
+
+
+

Collection ready

+

{receipt.collectionName} is connected.

+
+ +
+
+
Main copy
{local ? "On this computer" : "Hosted by mdbase"}
+ {local && receipt.path &&
Folder
{receipt.path}
} +
Privacy
{local ? "The folder path stays private." : "Add a synced folder if you want a copy on this computer."}
+
+
+ {local + ? + : } + {hasPendingAuthorization && } + + +
+
; +} diff --git a/apps/desktop/src/renderer/main.tsx b/apps/desktop/src/renderer/main.tsx index dda3e3b93..8f5c53804 100644 --- a/apps/desktop/src/renderer/main.tsx +++ b/apps/desktop/src/renderer/main.tsx @@ -12,7 +12,24 @@ import "@mdbase/connect-ui/styles.css"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { createRoot } from "react-dom/client"; import { Collections } from "./collections-view"; +import { CollectionCompletionReceipt } from "./completion-receipt"; +import { AuthorityTransferReceipt } from "./authority-transfer-receipt"; import { presentConnection } from "./connection-state.mjs"; +import { + COMPLETION_RECEIPT_KEY, + POST_PAIRING_KEY, + RESUME_AUTHORIZATION_KEY, + clearCompletionReceipt, + clearTransferReceipt, + consumePairingCompleted, + readAuthorizationTarget, + readCompletionReceipt, + readTransferReceipt, + writeTransferReceipt, + writeCompletionReceipt, + type CollectionCompletionReceipt as CompletionReceipt, + type AuthorityTransferReceipt as TransferReceipt +} from "./onboarding-state.mjs"; import { RequestPermissionChoices } from "./authorization-components"; import { ConnectionProgress, Overview } from "./overview-view"; import { singleFlight } from "./single-flight.mjs"; @@ -28,7 +45,6 @@ import { ThemeMenu } from "./ui-components"; import { - allOperations, host, message, plural, @@ -66,10 +82,8 @@ const routeCopy: Record } }; -const RESUME_AUTHORIZATION_KEY = "mdbase:resume-authorization"; - function storedAuthorizationTarget(): string | null { - return localStorage.getItem(RESUME_AUTHORIZATION_KEY); + return readAuthorizationTarget(localStorage); } function App() { @@ -93,6 +107,10 @@ function App() { const [newPath, setNewPath] = useState(""); const [newAuthority, setNewAuthority] = useState<"local" | "hosted">("local"); const [mirrorTarget, setMirrorTarget] = useState(null); + const [detailTarget, setDetailTarget] = useState(null); + const [completionReceipt, setCompletionReceipt] = useState(() => readCompletionReceipt(localStorage)); + const [transferReceipt, setTransferReceipt] = useState(() => readTransferReceipt(localStorage)); + const [initialRefreshComplete, setInitialRefreshComplete] = useState(false); const [navigationOpen, setNavigationOpen] = useState(false); const runRefresh = useCallback(async (quiet = false) => { @@ -116,6 +134,7 @@ function App() { } catch (refreshError) { if (!quiet) setError(message(refreshError)); } + setInitialRefreshComplete(true); }, []); const refresh = useMemo(() => singleFlight(runRefresh), [runRefresh]); @@ -135,6 +154,12 @@ function App() { setRoute("collections"); return; } + if (next === "paired") { + localStorage.setItem(POST_PAIRING_KEY, "completed"); + setInitialRefreshComplete(false); + void refresh(); + return; + } if (["overview", "collections", "access", "activity", "settings"].includes(next)) { setRoute(next as Route); } @@ -147,6 +172,12 @@ function App() { }; }, [refresh]); + useEffect(() => { + if (!initialRefreshComplete || !cloud?.configured || !consumePairingCompleted(localStorage)) return; + if (authorizationTarget) setRoute("access"); + else setRoute("collections"); + }, [authorizationTarget, cloud?.configured, initialRefreshComplete]); + useEffect(() => { if (cloud?.configured && route === "access" && authorizationTarget) { localStorage.removeItem(RESUME_AUTHORIZATION_KEY); @@ -176,11 +207,27 @@ function App() { } } + async function transferAct(action: () => Promise) { + setError(null); + setNotice(null); + try { + await action(); + await refresh(true); + } catch (actionError) { + setError(message(actionError)); + } + } + async function addExisting() { await act(async () => { const result = await window.mdbaseConnect.addCollection(); if (result?.status === "added") { - setNotice(`${result.collection.display_name} is now available to mdbase connect.`); + showCompletionReceipt({ + collectionId: result.collection.id, + collectionName: result.collection.display_name, + authority: "local", + path: result.collection.path + }); } else if (result?.status === "copy_requires_new_identity") { setCopiedCollectionPath(result.path); } @@ -192,7 +239,7 @@ function App() { await act(async () => { const added = await window.mdbaseConnect.addCopiedCollection(copiedCollectionPath); setCopiedCollectionPath(null); - setNotice(`${added.display_name} was registered as an independent collection.`); + showCompletionReceipt({ collectionId: added.id, collectionName: added.display_name, authority: "local", path: added.path }); }); } @@ -211,14 +258,14 @@ function App() { name: newName, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }); - setNotice(`${result.collection.display_name} is now hosted by mdbase.`); + showCompletionReceipt({ collectionId: result.collection.id, collectionName: result.collection.display_name, authority: "hosted" }); } else { const created = await window.mdbaseConnect.createCollection({ path: newPath, name: newName, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }); - setNotice(`${created.display_name} was created on this computer.`); + showCompletionReceipt({ collectionId: created.id, collectionName: created.display_name, authority: "local", path: created.path }); } setCreateOpen(false); setNewName(""); @@ -227,6 +274,28 @@ function App() { }); } + function showCompletionReceipt(receipt: CompletionReceipt) { + writeCompletionReceipt(localStorage, receipt); + setCompletionReceipt(receipt); + setRoute("collections"); + } + + function dismissCompletionReceipt() { + clearCompletionReceipt(localStorage); + setCompletionReceipt(null); + } + + function showTransferReceipt(receipt: TransferReceipt) { + writeTransferReceipt(localStorage, receipt); + setTransferReceipt(receipt); + setRoute("collections"); + } + + function dismissTransferReceipt() { + clearTransferReceipt(localStorage); + setTransferReceipt(null); + } + const copy = routeCopy[route]; const connection = presentConnection(status, cloud); const combinedAccess = useMemo(() => { @@ -246,7 +315,12 @@ function App() { pending_authorizations: [...pending.values()] }; }, [access, hosted]); - const collectionCount = collections.length + hosted.hosted_collections.length; + const localCollectionIds = new Set(collections.map((collection) => collection.id)); + const collectionCount = collections.length + hosted.hosted_collections.filter((collection) => + collection.authority_state !== "transferred" + || !collection.transferred_collection_id + || !localCollectionIds.has(collection.transferred_collection_id) + ).length; const selectRoute = (next: Route) => { setRoute(next); setNavigationOpen(false); @@ -275,6 +349,42 @@ function App() { {notice &&
{notice}
} + {completionReceipt && cloud !== null && 0} + onOpenFolder={() => { + if (completionReceipt.path) void window.mdbaseConnect.openPath(completionReceipt.path); + }} + onUseInApplication={() => setRoute("access")} + onOpenEditor={() => void window.mdbaseConnect.openEditor(completionReceipt.collectionId)} + onViewDetails={() => { + setDetailTarget(completionReceipt.collectionId); + setRoute("collections"); + }} + onAddSyncedFolder={() => { + setMirrorTarget(completionReceipt.collectionId); + setRoute("collections"); + }} + onDismiss={dismissCompletionReceipt} + />} + + {transferReceipt && cloud !== null && { + if (transferReceipt.direction === "hosted_to_local") { + void window.mdbaseConnect.openPath(transferReceipt.newMainCopy); + } else { + void window.mdbaseConnect.openEditor(transferReceipt.collectionId); + } + }} + onReconnect={() => setRoute("access")} + onViewDetails={() => { + setDetailTarget(transferReceipt.collectionId); + setRoute("collections"); + }} + onDismiss={dismissTransferReceipt} + />} + {cloud === null ? : route === "overview" ? ( setCreateOpen(true)} onRegisterCopy={() => void registerCopiedCollection()} onMirrorTargetHandled={() => setMirrorTarget(null)} + onDetailTargetHandled={() => setDetailTarget(null)} onAct={act} + onTransfer={transferAct} + onTransferComplete={showTransferReceipt} onNotice={setNotice} /> ) : route === "access" ? ( @@ -380,9 +495,9 @@ function Access({ cloud, access, focusedRequestId, resumeAuthorization, busy, on return (
- + {access.pending_authorizations.length === 0 ? ( - + ) : (
{pendingAuthorizations.map((request) => {identity} Expires {relativeTime(request.expires_at)}
-

Choose the collection and review the exact permissions in the portal. If this is a new application installation, local code comparison follows separately.

+

Choose the collection and review the exact permissions in Connect. If this is a new application installation, local code comparison follows separately.

+ })}>Review in Connect ; } @@ -481,11 +596,7 @@ function ApplicationGrantGroup({ group, busy, onAct, onNotice }: { function GrantEditor({ grant, busy, onAct, onNotice }: { grant: GrantSummary; busy: boolean; onAct(action: () => Promise): Promise; onNotice(value: string): void }) { const [operations, setOperations] = useState(grant.operations); - const contractScoped = grant.scope.contracts.length > 0; - const allowedOperations = useMemo( - () => contractScoped ? allOperations.filter((operation) => operation !== "validate") : allOperations, - [contractScoped] - ); + const allowedOperations = grant.operations; const permissionGroups = useMemo( () => groupAuthorizationOperations(allowedOperations), [allowedOperations] @@ -506,7 +617,7 @@ function GrantEditor({ grant, busy, onAct, onNotice }: { grant: GrantSummary; bu

{authority}

{grant.collection_name}

{grant.application_distribution === "portable" ? "Downloaded file · encrypted access" : host(grant.application_origin || grant.application_homepage)}Connected {relativeTime(grant.created_at)}{grant.scope.contracts.length > 0 && {scopeDescription(grant.scope.contracts)}}
-
Permissions{allowedOperations.length} available actions across {permissionGroups.length} {plural(permissionGroups.length, "category", "categories")}.
+
PermissionsYou can remove previously approved actions here. An application must request any additional access separately.
@@ -526,8 +637,8 @@ function GrantEditor({ grant, busy, onAct, onNotice }: { grant: GrantSummary; bu + onNotice(`Narrower access for ${grant.application_name} was saved.`); + })}>Save narrower access
@@ -569,7 +680,7 @@ function Settings({ startup, cloud, access, status, updateStatus, busy, onAct, o
- +
diff --git a/apps/desktop/src/renderer/onboarding-state.mts b/apps/desktop/src/renderer/onboarding-state.mts new file mode 100644 index 000000000..6b3098df7 --- /dev/null +++ b/apps/desktop/src/renderer/onboarding-state.mts @@ -0,0 +1,134 @@ +export const RESUME_AUTHORIZATION_KEY = "mdbase:resume-authorization"; +export const POST_PAIRING_KEY = "mdbase:post-pairing"; +export const COMPLETION_RECEIPT_KEY = "mdbase:collection-completion"; +export const TRANSFER_RECEIPT_KEY = "mdbase:authority-transfer-completion"; +export const TRANSFER_PROGRESS_KEY = "mdbase:authority-transfer-progress"; + +export interface CollectionCompletionReceipt { + collectionId: string; + collectionName: string; + authority: "local" | "hosted"; + path?: string; +} + +export interface AuthorityTransferReceipt { + collectionId: string; + collectionName: string; + direction: "local_to_hosted" | "hosted_to_local"; + newMainCopy: string; + oldAuthority: string; + applications: string[]; + replicas: string[]; + completedAt: string; +} + +export interface AuthorityTransferProgress { + collectionId: string; + collectionName: string; + direction: "local_to_hosted"; + phase: "uploading"; +} + +interface StorageLike { + getItem(key: string): string | null; + setItem(key: string, value: string): void; + removeItem(key: string): void; +} + +export function readAuthorizationTarget(storage: StorageLike): string | null { + return storage.getItem(RESUME_AUTHORIZATION_KEY); +} + +export function markPairingCompleted(storage: StorageLike): void { + storage.setItem(POST_PAIRING_KEY, "completed"); +} + +export function consumePairingCompleted(storage: StorageLike): boolean { + if (storage.getItem(POST_PAIRING_KEY) !== "completed") return false; + storage.removeItem(POST_PAIRING_KEY); + return true; +} + +export function readCompletionReceipt(storage: StorageLike): CollectionCompletionReceipt | null { + const value = storage.getItem(COMPLETION_RECEIPT_KEY); + if (!value) return null; + try { + const parsed = JSON.parse(value) as Partial; + if ( + typeof parsed.collectionId !== "string" + || typeof parsed.collectionName !== "string" + || (parsed.authority !== "local" && parsed.authority !== "hosted") + || (parsed.path !== undefined && typeof parsed.path !== "string") + ) throw new Error("invalid receipt"); + return parsed as CollectionCompletionReceipt; + } catch { + storage.removeItem(COMPLETION_RECEIPT_KEY); + return null; + } +} + +export function writeCompletionReceipt(storage: StorageLike, receipt: CollectionCompletionReceipt): void { + storage.setItem(COMPLETION_RECEIPT_KEY, JSON.stringify(receipt)); +} + +export function clearCompletionReceipt(storage: StorageLike): void { + storage.removeItem(COMPLETION_RECEIPT_KEY); +} + +export function readTransferReceipt(storage: StorageLike): AuthorityTransferReceipt | null { + const value = storage.getItem(TRANSFER_RECEIPT_KEY); + if (!value) return null; + try { + const parsed = JSON.parse(value) as Partial; + if ( + typeof parsed.collectionId !== "string" + || typeof parsed.collectionName !== "string" + || (parsed.direction !== "local_to_hosted" && parsed.direction !== "hosted_to_local") + || typeof parsed.newMainCopy !== "string" + || typeof parsed.oldAuthority !== "string" + || !Array.isArray(parsed.applications) + || parsed.applications.some((name) => typeof name !== "string") + || !Array.isArray(parsed.replicas) + || parsed.replicas.some((name) => typeof name !== "string") + || typeof parsed.completedAt !== "string" + ) throw new Error("invalid transfer receipt"); + return parsed as AuthorityTransferReceipt; + } catch { + storage.removeItem(TRANSFER_RECEIPT_KEY); + return null; + } +} + +export function writeTransferReceipt(storage: StorageLike, receipt: AuthorityTransferReceipt): void { + storage.setItem(TRANSFER_RECEIPT_KEY, JSON.stringify(receipt)); +} + +export function clearTransferReceipt(storage: StorageLike): void { + storage.removeItem(TRANSFER_RECEIPT_KEY); +} + +export function readTransferProgress(storage: StorageLike): AuthorityTransferProgress | null { + const value = storage.getItem(TRANSFER_PROGRESS_KEY); + if (!value) return null; + try { + const parsed = JSON.parse(value) as Partial; + if ( + typeof parsed.collectionId !== "string" + || typeof parsed.collectionName !== "string" + || parsed.direction !== "local_to_hosted" + || parsed.phase !== "uploading" + ) throw new Error("invalid transfer progress"); + return parsed as AuthorityTransferProgress; + } catch { + storage.removeItem(TRANSFER_PROGRESS_KEY); + return null; + } +} + +export function writeTransferProgress(storage: StorageLike, progress: AuthorityTransferProgress): void { + storage.setItem(TRANSFER_PROGRESS_KEY, JSON.stringify(progress)); +} + +export function clearTransferProgress(storage: StorageLike): void { + storage.removeItem(TRANSFER_PROGRESS_KEY); +} diff --git a/apps/desktop/src/renderer/styles.css b/apps/desktop/src/renderer/styles.css index 6d86c7cd6..09a95f4e7 100644 --- a/apps/desktop/src/renderer/styles.css +++ b/apps/desktop/src/renderer/styles.css @@ -14,6 +14,15 @@ h1 { margin: 0; font-size: 26px; font-weight: 700; line-height: 1.15; letter-spa .error-message { color: var(--danger); border-color: color-mix(in oklch, var(--danger) 34%, var(--line)); } .notice-message { color: var(--connected); border-color: color-mix(in oklch, var(--connected) 34%, var(--line)); } .workspace-stack { display: grid; gap: 56px; margin-top: 32px; } +.completion-receipt { margin-top: 24px; padding: 18px 0 20px; border-top: 2px solid var(--connected); border-bottom: 1px solid var(--line); } +.completion-receipt-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; } +.completion-receipt-heading h2 { margin: 3px 0 0; font-size: 20px; letter-spacing: -0.025em; } +.completion-receipt-facts { display: grid; grid-template-columns: minmax(130px, .65fr) minmax(220px, 1.35fr) minmax(220px, 1fr); margin: 18px 0; border-top: 1px solid var(--line); } +.completion-receipt-facts > div { min-width: 0; padding: 12px 18px 0 0; } +.completion-receipt-facts dt { color: var(--muted); font-family: var(--mono); font-size: var(--type-metadata); text-transform: uppercase; } +.completion-receipt-facts dd { margin: 5px 0 0; font-size: var(--type-supporting); } +.completion-receipt-facts code { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.completion-receipt-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 14px; } .connection-progress { display: grid; grid-template-columns: 7px minmax(0, 1fr); align-items: center; gap: 12px; margin-top: 24px; padding: 18px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); } .connection-progress div { display: grid; gap: 4px; } .connection-progress strong { font-size: var(--type-body); font-weight: 700; } @@ -187,6 +196,23 @@ h1 { margin: 0; font-size: 26px; font-weight: 700; line-height: 1.15; letter-spa .authority-transfer-control strong { font-size: var(--type-body); } .authority-transfer-control small { display: block; max-width: 68ch; margin-top: 3px; color: var(--muted); font-size: var(--type-supporting); line-height: 1.45; } .authority-transfer-control .button { flex: 0 0 auto; } +.authority-history { display: flex; align-items: baseline; gap: 12px; padding: 10px 0; border-top: 1px solid var(--line); color: var(--muted); font-size: var(--type-supporting); } +.authority-history strong { color: var(--ink); white-space: nowrap; } +.authority-transfer-preflight { display: grid; grid-column: 1 / -1; gap: 16px; padding: 18px; border: 1px solid var(--line-strong); background: var(--hover); } +.authority-transfer-route { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 16px; } +.authority-transfer-route > div { display: grid; gap: 4px; min-width: 0; } +.authority-transfer-route span, .authority-transfer-facts dt { color: var(--muted); font-family: var(--mono); font-size: var(--type-metadata); text-transform: uppercase; } +.authority-transfer-route strong { overflow: hidden; font-size: var(--type-body); text-overflow: ellipsis; white-space: nowrap; } +.authority-transfer-route small { color: var(--muted); font-size: var(--type-supporting); } +.authority-transfer-facts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); margin: 0; border-top: 1px solid var(--line); } +.authority-transfer-facts > div { padding: 12px 16px 0 0; } +.authority-transfer-facts dd { margin: 5px 0 0; font-size: var(--type-supporting); line-height: 1.45; } +.authority-transfer-instruction { margin: 0; color: var(--ink); font-size: var(--type-supporting); } +.authority-transfer-phase { display: flex; align-items: center; gap: 8px; font-size: var(--type-supporting); } +.authority-transfer-actions { display: flex; justify-content: flex-end; gap: 8px; } +.transfer-impact-summary { display: grid; gap: 5px; margin: -4px 0 18px; color: var(--muted); font-size: var(--type-supporting); } +.transfer-impact-summary p { margin: 0; } +.transfer-impact-summary strong { color: var(--ink); font-family: var(--mono); } .collection-editor-footer { padding: 14px 0; } .collection-danger-row { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 12px 0 14px; } .collection-danger-row small { color: var(--muted); font-size: var(--type-action); } @@ -369,6 +395,8 @@ fieldset legend { margin-bottom: 6px; } .manual-grant { grid-template-columns: 1fr 1fr; } } @media (max-width: 780px) { + .completion-receipt-facts { grid-template-columns: 1fr; } + .completion-receipt-actions { align-items: stretch; flex-direction: column; } .content { padding-inline: 24px; } .request-panel, .grant-review, .request-section, .collection-editor-section { grid-template-columns: 1fr; } .request-collection-create { grid-template-columns: 1fr; } @@ -400,6 +428,10 @@ fieldset legend { margin-bottom: 6px; } .application-grant-actions { align-items: flex-start; flex-direction: column; } .collection-danger-row { align-items: flex-start; flex-direction: column; } .authority-transfer-control { align-items: flex-start; flex-direction: column; } + .authority-transfer-route, .authority-transfer-facts { grid-template-columns: 1fr; } + .authority-transfer-route > span { transform: rotate(90deg); justify-self: start; } + .authority-transfer-actions { align-items: stretch; flex-direction: column-reverse; } + .authority-history { align-items: flex-start; flex-direction: column; gap: 4px; } .overview-row { grid-template-columns: 95px minmax(0, 1fr) auto; } .pairing-form { grid-template-columns: 1fr; } .pairing-form .button { grid-column: 1; } diff --git a/apps/desktop/src/renderer/ui-components.tsx b/apps/desktop/src/renderer/ui-components.tsx index 1b4fc150f..4d0ebcb46 100644 --- a/apps/desktop/src/renderer/ui-components.tsx +++ b/apps/desktop/src/renderer/ui-components.tsx @@ -11,6 +11,7 @@ import { } from "@mdbase/connect-ui/theme"; import React, { useEffect, useRef, useState } from "react"; import type { ConnectionDotState } from "./connection-state.mjs"; +import { markPairingCompleted } from "./onboarding-state.mjs"; import { message, type Route } from "./view-model"; export function PairingPanel({ resumeAuthorization = false }: { resumeAuthorization?: boolean }) { @@ -28,6 +29,7 @@ export function PairingPanel({ resumeAuthorization = false }: { resumeAuthorizat const result = await window.mdbaseConnect.pairingStatus(pairing.pairingId); if (result.status === "paired") { window.clearInterval(timer); + markPairingCompleted(localStorage); setCompleting(true); } } catch (error) { @@ -56,12 +58,12 @@ export function PairingPanel({ resumeAuthorization = false }: { resumeAuthorizat

Account connection

-

{pairing ? "Finish in your browser." : resumeAuthorization ? "Connect this computer to continue." : "Connect this computer."}

+

{pairing ? "Finish in your browser." : resumeAuthorization ? "Connect this computer to continue." : "Connect this computer to mdbase"}

{pairing ? "Sign in and approve this computer. This window updates automatically, and there is no code to copy." : resumeAuthorization ? "Your application request will keep waiting. Sign in so you can choose a folder on this computer, then continue the same request." - : "Sign in so approved applications can find collections on this computer. Folder locations remain private."}

+ : "Sign in so applications can discover your collections and you can manage their access. Local folders remain on this computer, and their locations stay private."}

{pairError &&
{pairError}
} {pairing ? ( diff --git a/apps/desktop/test/deep-link.test.mjs b/apps/desktop/test/deep-link.test.mjs index 5b0dfdddd..0c078a98d 100644 --- a/apps/desktop/test/deep-link.test.mjs +++ b/apps/desktop/test/deep-link.test.mjs @@ -19,7 +19,7 @@ test("authorization links preserve the exact request route", () => { }); test("other supported links retain their existing routes", () => { - assert.equal(routeForDeepLink("mdbase-connect://paired"), "overview"); + assert.equal(routeForDeepLink("mdbase-connect://paired"), "paired"); assert.equal( routeForDeepLink("mdbase-connect://mirror?collection=collection-1"), "collections:mirror:collection-1" diff --git a/apps/desktop/test/onboarding-state.test.mjs b/apps/desktop/test/onboarding-state.test.mjs new file mode 100644 index 000000000..665d8f23d --- /dev/null +++ b/apps/desktop/test/onboarding-state.test.mjs @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + COMPLETION_RECEIPT_KEY, + TRANSFER_RECEIPT_KEY, + clearTransferProgress, + clearTransferReceipt, + consumePairingCompleted, + markPairingCompleted, + readCompletionReceipt, + readTransferReceipt, + readTransferProgress, + writeTransferProgress, + writeTransferReceipt, + writeCompletionReceipt +} from "../src/renderer/onboarding-state.mts"; + +function storage(initial = {}) { + const values = new Map(Object.entries(initial)); + return { + getItem: (key) => values.get(key) ?? null, + setItem: (key, value) => values.set(key, value), + removeItem: (key) => values.delete(key) + }; +} + +test("pairing completion is consumed once", () => { + const target = storage(); + assert.equal(consumePairingCompleted(target), false); + markPairingCompleted(target); + assert.equal(consumePairingCompleted(target), true); + assert.equal(consumePairingCompleted(target), false); +}); + +test("collection completion receipts survive renderer restarts", () => { + const target = storage(); + const receipt = { collectionId: "collection-1", collectionName: "Notes", authority: "local", path: "/Notes" }; + writeCompletionReceipt(target, receipt); + assert.deepEqual(readCompletionReceipt(target), receipt); +}); + +test("invalid completion receipt data is discarded", () => { + const target = storage({ [COMPLETION_RECEIPT_KEY]: '{"authority":"somewhere"}' }); + assert.equal(readCompletionReceipt(target), null); + assert.equal(target.getItem(COMPLETION_RECEIPT_KEY), null); +}); + +test("authority transfer receipts survive renderer restarts until dismissed", () => { + const target = storage(); + const receipt = { + collectionId: "collection-1", + collectionName: "Notes", + direction: "hosted_to_local", + newMainCopy: "/Notes", + oldAuthority: "Hosted recovery copy", + applications: ["Tasks"], + replicas: ["Laptop"], + completedAt: "2026-08-22T00:00:00.000Z" + }; + writeTransferReceipt(target, receipt); + assert.deepEqual(readTransferReceipt(target), receipt); + clearTransferReceipt(target); + assert.equal(target.getItem(TRANSFER_RECEIPT_KEY), null); +}); + +test("invalid authority transfer receipt data is discarded", () => { + const target = storage({ [TRANSFER_RECEIPT_KEY]: '{"direction":"sideways"}' }); + assert.equal(readTransferReceipt(target), null); + assert.equal(target.getItem(TRANSFER_RECEIPT_KEY), null); +}); + +test("an interrupted local authority transfer remains resumable", () => { + const target = storage(); + const progress = { + collectionId: "collection-1", + collectionName: "Notes", + direction: "local_to_hosted", + phase: "uploading" + }; + writeTransferProgress(target, progress); + assert.deepEqual(readTransferProgress(target), progress); + clearTransferProgress(target); + assert.equal(readTransferProgress(target), null); +}); diff --git a/apps/editor/src/App.test.tsx b/apps/editor/src/App.test.tsx index 1142d16c8..796ac414f 100644 --- a/apps/editor/src/App.test.tsx +++ b/apps/editor/src/App.test.tsx @@ -991,10 +991,10 @@ describe("mdbase editor", () => { }); render(); - await userEvent.click(await screen.findByRole("button", { name: "Choose another collection" })); + await userEvent.click(await screen.findByRole("button", { name: "Connect another collection" })); expect(authorize).toHaveBeenCalledOnce(); - expect(authorize).toHaveBeenCalledWith("choose"); + expect(authorize).toHaveBeenCalledWith("choose", { presentation: "popup" }); }); it("authorizes the requested collection from a portal deep link", async () => { @@ -1013,10 +1013,10 @@ describe("mdbase editor", () => { }); render(); - await userEvent.click(await screen.findByRole("button", { name: "Choose another collection" })); + await userEvent.click(await screen.findByRole("button", { name: "Connect another collection" })); expect(authorize).toHaveBeenCalledOnce(); - expect(authorize).toHaveBeenCalledWith("selected"); + expect(authorize).toHaveBeenCalledWith("selected", { presentation: "popup" }); }); it("returns to collection authorization when the SDK invalidates a stale grant", async () => { @@ -1046,7 +1046,7 @@ describe("mdbase editor", () => { expect(screen.getByText(/edit notes and move notes/i)).toBeInTheDocument(); expect(screen.getByText(/shows only what needs to be added/i)).toBeInTheDocument(); await userEvent.click(screen.getByRole("button", { name: "Update access" })); - expect(authorize).toHaveBeenCalledWith("selected"); + expect(authorize).toHaveBeenCalledWith("selected", { presentation: "popup" }); }); it("keeps note editing available when only optional type access is missing", async () => { @@ -1068,7 +1068,7 @@ describe("mdbase editor", () => { expect(await screen.findByRole("heading", { name: "Type access needed" })).toBeInTheDocument(); expect(screen.getByText(/Notes are ready/i)).toBeInTheDocument(); await userEvent.click(screen.getByRole("button", { name: "Update access" })); - expect(authorize).toHaveBeenCalledWith("selected"); + expect(authorize).toHaveBeenCalledWith("selected", { presentation: "popup" }); }); it("shows a dropped connection and offers an immediate retry", async () => { diff --git a/apps/editor/src/App.tsx b/apps/editor/src/App.tsx index 895fd0674..11910ba92 100644 --- a/apps/editor/src/App.tsx +++ b/apps/editor/src/App.tsx @@ -991,7 +991,7 @@ export function App({ gateway }: { gateway: CollectionGateway }) { return; } setConfirmation({ - title: "Choose another collection?", + title: "Connect another collection?", body:

Unsaved type or creation changes will be discarded when the new collection opens. Note and property changes will finish saving first.

, confirmLabel: "Continue", onConfirm: connectAnotherCollection diff --git a/apps/editor/src/ConnectApp.test.tsx b/apps/editor/src/ConnectApp.test.tsx index 255bc623b..1ccf6dc0f 100644 --- a/apps/editor/src/ConnectApp.test.tsx +++ b/apps/editor/src/ConnectApp.test.tsx @@ -238,7 +238,7 @@ describe("ConnectApp", () => { expect(await screen.findByText("No computers connected")).toBeInTheDocument(); expect(screen.getByRole("link", { name: "Open mdbase connect" })).toHaveAttribute("href", "mdbase-connect://open"); - expect(screen.getByRole("link", { name: "Install the latest release" })).toHaveAttribute("href", "https://github.com/mdbase-dev/mdbase-connect/releases/latest"); + expect(screen.getByRole("link", { name: "Install the latest release" })).toHaveAttribute("href", "https://mdbase.dev/downloads/"); }); it("shows each pending request once and describes application access plainly", async () => { diff --git a/apps/editor/src/ConnectApp.tsx b/apps/editor/src/ConnectApp.tsx index 5be66dcdd..d3e5a7fa3 100644 --- a/apps/editor/src/ConnectApp.tsx +++ b/apps/editor/src/ConnectApp.tsx @@ -44,7 +44,7 @@ const serverUrl = new URLSearchParams(location.search).get("server") ?? import.meta.env.VITE_MDBASE_CONNECT_URL ?? "https://connect.mdbase.dev"; const management = new ConnectManagementClient(serverUrl); -const desktopReleaseUrl = "https://github.com/mdbase-dev/mdbase-connect/releases/latest"; +const desktopReleaseUrl = "https://mdbase.dev/downloads/"; const allOperations = [ "describe", "changes", "read", "query", "list_views", "execute_view", "read_view_source", "validate", "create", "update", "delete", "rename", "create_view_source", "update_view_source", "delete_view_source", diff --git a/apps/editor/src/ConnectionScreens.tsx b/apps/editor/src/ConnectionScreens.tsx index 39e56b32b..c9fb6d064 100644 --- a/apps/editor/src/ConnectionScreens.tsx +++ b/apps/editor/src/ConnectionScreens.tsx @@ -45,7 +45,7 @@ export function ConnectScreen({ notice, missingCapabilities = [], connections, o

{updatingAccess ? "mdbase connect keeps the access you already approved and shows only what needs to be added." @@ -82,7 +82,7 @@ export function CollectionSwitcher({ activeCollectionId, connections, displayNam })}

- +
; } diff --git a/apps/editor/src/collection-authorization.ts b/apps/editor/src/collection-authorization.ts index 6ea5f0097..994b71826 100644 --- a/apps/editor/src/collection-authorization.ts +++ b/apps/editor/src/collection-authorization.ts @@ -14,7 +14,7 @@ export function useCollectionAuthorization(input: { }) { async function authorizeCollection(target: CollectionAuthorizationTarget) { const previous = input.gateway.sessionSnapshot(); - await input.gateway.authorize(target); + await input.gateway.authorize(target, { presentation: "popup" }); const next = input.gateway.sessionSnapshot(); input.setSessionSnapshot(next); if ( diff --git a/apps/editor/src/model.ts b/apps/editor/src/model.ts index a102b47d7..967b092a3 100644 --- a/apps/editor/src/model.ts +++ b/apps/editor/src/model.ts @@ -194,6 +194,7 @@ export interface CollectionGateway { export interface CollectionAuthorizationOptions { signal?: AbortSignal; + presentation?: "redirect" | "popup"; } export type TypeDocument = CollectionTypeDocument; diff --git a/apps/editor/tests/authorization-recovery.spec.ts b/apps/editor/tests/authorization-recovery.spec.ts index ac374fd5c..8c1f04a90 100644 --- a/apps/editor/tests/authorization-recovery.spec.ts +++ b/apps/editor/tests/authorization-recovery.spec.ts @@ -196,8 +196,11 @@ test("recovers from a stale local grant without bypassing the connector", async ); }, { configuredServerUrl: serverUrl, configuredManifestPath: manifestPath })).toBeNull(); + const popupPromise = page.waitForEvent("popup"); await page.getByRole("button", { name: "Choose a collection" }).click(); - await expect(page).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); + const popup = await popupPromise; + await expect(popup).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); + await popup.close(); }); async function json(route: Route, body: unknown, status = 200): Promise { diff --git a/apps/editor/tests/remote-authority-editor.spec.ts b/apps/editor/tests/remote-authority-editor.spec.ts index ab8846058..b7dcf1c69 100644 --- a/apps/editor/tests/remote-authority-editor.spec.ts +++ b/apps/editor/tests/remote-authority-editor.spec.ts @@ -15,12 +15,16 @@ test("chooses a remote authority collection and performs CRUD through its provid await page.goto("/"); await expect(page.getByText("Choose the collection you want to write in.")).toBeVisible(); + const popupPromise = page.waitForEvent("popup"); await page.getByRole("button", { name: "Choose a collection" }).click(); - await expect(page).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); - const collection = page.getByRole("combobox", { name: "Collection" }); + const popup = await popupPromise; + await expect(popup).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); + const collection = popup.getByRole("combobox", { name: "Collection" }); await expect(collection).toHaveValue(collectionId); await expect(collection).toContainText("Hosted writing · Hosted by mdbase"); - await page.getByRole("button", { name: "Allow access" }).click(); + const popupClosed = popup.waitForEvent("close"); + await popup.getByRole("button", { name: "Allow access" }).click(); + await popupClosed; await expect(page.getByRole("heading", { name: "Hosted writing" })).toBeVisible(); await expect(page.getByRole("textbox", { name: "Note title" })).toHaveValue("Welcome to hosted writing"); @@ -65,20 +69,28 @@ test("returns to the newly chosen remote authority when switching collections", await authority.install(); await page.goto("/"); + const firstPopupPromise = page.waitForEvent("popup"); await page.getByRole("button", { name: "Choose a collection" }).click(); - await expect(page).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); - await page.getByRole("button", { name: "Allow access" }).click(); + const firstPopup = await firstPopupPromise; + await expect(firstPopup).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); + const firstPopupClosed = firstPopup.waitForEvent("close"); + await firstPopup.getByRole("button", { name: "Allow access" }).click(); + await firstPopupClosed; await expect(page.getByRole("heading", { name: "Hosted writing" })).toBeVisible(); await page.getByRole("button", { name: "Switch collection, current collection Hosted writing" }).click(); - await page.getByRole("button", { name: "Choose another collection" }).click(); + const secondPopupPromise = page.waitForEvent("popup"); + await page.getByRole("button", { name: "Connect another collection" }).click(); - await expect(page).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); - const collection = page.getByRole("combobox", { name: "Collection" }); + const secondPopup = await secondPopupPromise; + await expect(secondPopup).toHaveURL(/connect\.mdbase\.dev\/oauth\/authorize/); + const collection = secondPopup.getByRole("combobox", { name: "Collection" }); await collection.selectOption(secondCollectionId); - await page.getByRole("button", { name: "Allow access" }).click(); + const secondPopupClosed = secondPopup.waitForEvent("close"); + await secondPopup.getByRole("button", { name: "Allow access" }).click(); + await secondPopupClosed; await expect(page).toHaveURL(new RegExp(`collection=${secondCollectionId}`)); await expect(page.getByRole("heading", { name: "Research" })).toBeVisible(); diff --git a/apps/portal/src/api.ts b/apps/portal/src/api.ts index a34e756fe..466a369be 100644 --- a/apps/portal/src/api.ts +++ b/apps/portal/src/api.ts @@ -89,6 +89,10 @@ export interface PendingAuthorization { requirements: ApplicationRequirements; provisions: ApplicationProvisions; notifications: ApplicationNotifications; + existing_access?: Array<{ + collection_id: string; + operations: string[]; + }>; available_collections?: AvailableCollection[]; unavailable_connectors?: UnavailableConnector[]; } diff --git a/apps/portal/src/authorization-permissions.tsx b/apps/portal/src/authorization-permissions.tsx index f98567a59..77a1baae2 100644 --- a/apps/portal/src/authorization-permissions.tsx +++ b/apps/portal/src/authorization-permissions.tsx @@ -1,6 +1,22 @@ import { groupAuthorizationOperations } from "@mdbase/connect-ui/access"; import type { PendingAuthorization } from "./api"; +export function PermissionDelta({ existingAccess, collectionId, selected }: { + existingAccess: PendingAuthorization["existing_access"]; + collectionId: string; + selected: ReadonlySet; +}) { + const existing = new Set(existingAccess?.find((access) => + access.collection_id === collectionId)?.operations ?? []); + if (existing.size === 0) return null; + const approved = [...selected].filter((operation) => existing.has(operation)).length; + const added = selected.size - approved; + return
+ {approved} already approved + {added} {added === 1 ? "action" : "actions"} added by this request +
; +} + export function PermissionCapabilitySummary({ groups, selected, diff --git a/apps/portal/src/authorization-view.tsx b/apps/portal/src/authorization-view.tsx index a8c27d439..85b96e436 100644 --- a/apps/portal/src/authorization-view.tsx +++ b/apps/portal/src/authorization-view.tsx @@ -32,6 +32,7 @@ import { FilePermissionSummary, NotificationAccess, PermissionCapabilitySummary, + PermissionDelta, PermissionChoices } from "./authorization-permissions"; import { @@ -44,7 +45,6 @@ import { scopeDescription } from "./portal-model"; import { Loading, PageBrand, useSystemTheme } from "./portal-ui"; - export function DeviceAuthorization() { const initialCode = formatDeviceCode(new URLSearchParams(location.search).get("user_code") ?? ""); const [code, setCode] = useState(initialCode); @@ -284,7 +284,7 @@ function DesktopContinuation({ request, onReviewHere }: { Open mdbase connect -

If the desktop app does not open, install the latest release, then return to this page. The request expires {relativeTime(request.expires_at)}.

+

If the desktop app does not open, install the current Connect release, then return to this page. The request expires {relativeTime(request.expires_at)}.

); } @@ -862,6 +862,7 @@ export function ApprovalForm({ {permissionCount} requested actions across {permissionCategoryCount} {permissionCategoryCount === 1 ? "capability" : "capabilities"}.
+ {selected && } {permissionGroups.length > 0 && { async authorize( options: MdbaseAuthorizeOptions = {} ): Promise> { - return withRequestBudget(options, this.timeouts.requestMs, (budget) => + const authorizationTimeout = options.presentation === "popup" + ? 10 * 60 * 1_000 + : this.timeouts.requestMs; + return withRequestBudget(options, authorizationTimeout, (budget) => this.authorizeWithinBudget({ ...options, signal: budget.signal, timeoutMs: null }) ); } @@ -260,31 +268,14 @@ export class MdbaseConnectInternals { private async authorizeWithinBudget( options: MdbaseAuthorizeOptions ): Promise> { - if (typeof location === "undefined" && !this.navigate && !options.openVerification) { - throw connectError( - "browser_required", - "Authorization navigation requires a browser environment." - ); - } const portableDeclared = typeof this.manifest !== "string" && this.manifest.distribution === "portable"; - const popup = portableDeclared - && !options.openVerification - && !this.navigate - && typeof window !== "undefined" - ? window.open( - "", - "mdbase-connect-authorization", - "popup,width=620,height=760" - ) - : null; - let application: Application; - try { - application = await this.registerWithinBudget(options.signal!); - } catch (error) { - popup?.close(); - throw error; - } + const { application, popup } = await prepareAuthorizationWindow({ + options, + portableDeclared, + navigate: this.navigate, + register: (signal) => this.registerWithinBudget(signal) + }); if (application.distribution === "portable") { if (options.openVerification) popup?.close(); return this.authorizePortable( @@ -293,13 +284,13 @@ export class MdbaseConnectInternals { options.openVerification ? null : popup ); } - popup?.close(); - return this.authorizeWeb(application, options); + return this.authorizeWeb(application, options, popup); } private async authorizeWeb( application: Application, - options: MdbaseAuthorizeOptions + options: MdbaseAuthorizeOptions, + popup: Window | null ): Promise> { const { verifier, challenge } = await createPkce(); const state = randomBase64Url(24); @@ -363,7 +354,8 @@ export class MdbaseConnectInternals { keyHandle, authorizationId, applicationAgreementPublicKey: grantKey.agreementPublicKey, - applicationSigningPublicKey: grantKey.signingPublicKey + applicationSigningPublicKey: grantKey.signingPublicKey, + ...(options.presentation === "popup" && popup ? { presentation: "popup" as const } : {}) }; this.storage.setItem(this.pendingKey(state), JSON.stringify(pending)); try { @@ -406,6 +398,20 @@ export class MdbaseConnectInternals { "The authorization service returned an invalid authorization response." ); } + if (options.presentation === "popup" && popup) { + popup.location.href = body.authorization_uri; + return await waitForPopupAuthorization({ + storage: this.storage, + storagePrefix: this.storagePrefix(), + state, + pending, + popup, + signal: options.signal!, + keyStore: this.keyStore, + connection: (collectionId) => this.connection(collectionId) + }); + } + popup?.close(); if (this.navigate) await this.navigate(body.authorization_uri); else if (typeof location !== "undefined") location.assign(body.authorization_uri); else { @@ -416,6 +422,7 @@ export class MdbaseConnectInternals { } return { kind: "redirecting" }; } catch (error) { + popup?.close(); this.storage.removeItem(this.pendingKey(state)); await this.keyStore.delete(keyHandle); if (options.signal?.aborted) { @@ -710,9 +717,18 @@ export class MdbaseConnectInternals { "Authorization callback is missing its state." )); } + const pending = parseStored(this.storage.getItem(this.pendingKey(state))); + const popupAttempt = pending?.presentation === "popup"; const existing = this.completionPromises.get(state); if (existing) return existing; - const completion = this.performAuthorizationCompletion(callbackUrl, state, signal); + const completion = publishPopupAuthorizationCompletion({ + storage: this.storage, + storagePrefix: this.storagePrefix(), + state, + pending, + popupAttempt, + completion: this.performAuthorizationCompletion(callbackUrl, state, signal) + }); const shared = completion.finally(() => { if (this.completionPromises.get(state) === shared) this.completionPromises.delete(state); }); @@ -813,7 +829,7 @@ export class MdbaseConnectInternals { connections(): MdbaseConnectionInfo[] { const connections: MdbaseConnectionInfo[] = []; - for (const collectionId of this.connectionIds()) { + for (const collectionId of connectionIds(this.storage, this.storagePrefix())) { const info = this.connection(collectionId)?.info(); if (info) connections.push(info); } @@ -861,7 +877,7 @@ export class MdbaseConnectInternals { void this.keyStore.delete(previous.keyHandle).catch(() => undefined); } this.storage.setItem(this.tokenKey(collectionId), JSON.stringify(token)); - this.addConnectionId(collectionId); + addConnectionId(this.storage, this.storagePrefix(), collectionId); this.invalidatedConnections.delete(collectionId); this.connectionCache.delete(collectionId); this.emitConnections(); @@ -927,13 +943,7 @@ export class MdbaseConnectInternals { for (const transport of ["web_push", "fcm"] as const) { this.storage.removeItem(this.notificationKey(collectionId, transport)); } - this.storage.setItem( - this.connectionsKey(), - JSON.stringify({ - version: 1, - collectionIds: this.connectionIds().filter((id) => id !== collectionId) - } satisfies StoredConnectionIndex) - ); + removeConnectionId(this.storage, this.storagePrefix(), collectionId); this.connectionCache.delete(collectionId); this.emitConnections(); } @@ -971,28 +981,6 @@ export class MdbaseConnectInternals { return `mdbase-connect:${this.serverUrl}:${this.manifestSource}`; } - private connectionsKey(): string { - return `${this.storagePrefix()}:connections`; - } - - private connectionIds(): string[] { - const index = parseStored(this.storage.getItem(this.connectionsKey())); - return index?.version === 1 && Array.isArray(index.collectionIds) - && index.collectionIds.every((collectionId) => typeof collectionId === "string") - ? index.collectionIds - : []; - } - - private addConnectionId(collectionId: string): void { - this.storage.setItem( - this.connectionsKey(), - JSON.stringify({ - version: 1, - collectionIds: [...new Set([...this.connectionIds(), collectionId])] - } satisfies StoredConnectionIndex) - ); - } - private emitConnections(): void { const connections = this.connections(); for (const listener of this.listeners) listener(connections); diff --git a/packages/client/src/connection-index.ts b/packages/client/src/connection-index.ts new file mode 100644 index 000000000..cf82c1de4 --- /dev/null +++ b/packages/client/src/connection-index.ts @@ -0,0 +1,29 @@ +import type { StoredConnectionIndex } from "./internal-types.js"; +import { parseStored } from "./runtime-utils.js"; + +export function connectionIds(storage: Storage, storagePrefix: string): string[] { + const index = parseStored(storage.getItem(`${storagePrefix}:connections`)); + return index?.version === 1 && Array.isArray(index.collectionIds) + && index.collectionIds.every((collectionId) => typeof collectionId === "string") + ? index.collectionIds + : []; +} + +export function addConnectionId(storage: Storage, storagePrefix: string, collectionId: string): void { + writeConnectionIds(storage, storagePrefix, [...connectionIds(storage, storagePrefix), collectionId]); +} + +export function removeConnectionId(storage: Storage, storagePrefix: string, collectionId: string): void { + writeConnectionIds( + storage, + storagePrefix, + connectionIds(storage, storagePrefix).filter((id) => id !== collectionId) + ); +} + +function writeConnectionIds(storage: Storage, storagePrefix: string, ids: string[]): void { + storage.setItem(`${storagePrefix}:connections`, JSON.stringify({ + version: 1, + collectionIds: [...new Set(ids)] + } satisfies StoredConnectionIndex)); +} diff --git a/packages/client/src/connection.ts b/packages/client/src/connection.ts index 7ba4f781a..916041108 100644 --- a/packages/client/src/connection.ts +++ b/packages/client/src/connection.ts @@ -140,6 +140,8 @@ export type MdbaseAuthorizationTarget = export interface MdbaseAuthorizeOptions extends ConnectRequestOptions { operations?: CollectionOperation[]; + /** Keep a web application loaded while Connect owns the approval ceremony. */ + presentation?: "redirect" | "popup"; /** Choose any compatible collection, or require one exact collection. */ target?: MdbaseAuthorizationTarget; /** App-local location to restore after the authorization callback. */ @@ -152,6 +154,7 @@ export interface MdbaseAuthorizeOptions extends ConnectRequestOptions { export interface MdbaseConnectionAuthorizeOptions extends ConnectRequestOptions { operations?: CollectionOperation[]; + presentation?: "redirect" | "popup"; returnTo?: string; onDeviceCode?: (authorization: MdbaseDeviceAuthorization) => void; openVerification?: (authorization: MdbaseDeviceAuthorization) => void | Promise; diff --git a/packages/client/src/index.test.ts b/packages/client/src/index.test.ts index 5aceae6c8..224a8125b 100644 --- a/packages/client/src/index.test.ts +++ b/packages/client/src/index.test.ts @@ -2539,6 +2539,126 @@ describe("authorization renewal", () => { }); }); + it("keeps a web application loaded while popup authorization completes", async () => { + const storage = new MemoryStorage(); + const popup = { + closed: false, + location: { href: "" }, + close: vi.fn(() => { popup.closed = true; }) + }; + const open = vi.fn(() => popup); + const closeAuthorizationWindow = vi.fn(); + vi.stubGlobal("window", { open, close: closeAuthorizationWindow }); + vi.stubGlobal("location", { assign: vi.fn() }); + let state = ""; + vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => { + const url = String(request); + if (url.endsWith("/v1/apps/register")) { + return jsonResponse({ application: registeredApplication() }); + } + if (url.endsWith("/oauth/authorization_request")) { + const form = new URLSearchParams(String(init?.body)); + const proof = JSON.parse(form.get("application_authorization")!); + state = proof.binding.state; + return jsonResponse({ + authorization_id: proof.binding.authorization_id, + authorization_uri: `https://connect.example/oauth/authorize?request_id=${proof.binding.authorization_id}`, + expires_in: 600 + }); + } + if (url.endsWith("/oauth/token")) { + return jsonResponse({ + access_token: "mdb_popup", + expires_in: 3600, + collection_id: TEST_COLLECTION_ID, + collection_name: "Popup tasks", + operations: ["query"], + scope: { contracts: [], access: "full_collection" } + }); + } + throw new Error(`Unexpected request: ${url}`); + }); + const manager = new MdbaseConnect({ + serverUrl: "https://connect.example", + manifest: { + manifest_version: 1, + id: "dev.tasks", + name: "Tasks", + homepage: "https://tasks.example/", + redirect_uris: ["https://tasks.example/callback"] + }, + redirectUri: "https://tasks.example/callback", + storage, + keyStore: new MemoryGrantKeyStore(), + identityStore: new MemoryApplicationIdentityStore(), + relayEncryption: "disabled" + }); + + const authorization = manager.authorize({ + presentation: "popup", + operations: ["query"], + returnTo: "/today" + }); + expect(open).toHaveBeenCalledOnce(); + expect(open).toHaveBeenCalledWith("", "mdbase-connect-authorization", "popup,width=620,height=760"); + await vi.waitFor(() => expect(popup.location.href).toContain("https://connect.example/oauth/authorize")); + // Cross-Origin-Opener-Policy can sever the proxy while the window remains + // alive. Completion must be driven by shared callback state, not `closed`. + popup.closed = true; + await expect(manager.completeAuthorization( + `https://tasks.example/callback?code=popup-code&state=${state}` + )).resolves.toMatchObject({ ok: true }); + await expect(authorization).resolves.toMatchObject({ + ok: true, + value: { + kind: "connected", + returnTo: "/today", + connection: { collectionId: TEST_COLLECTION_ID } + } + }); + expect(popup.close).toHaveBeenCalled(); + expect(closeAuthorizationWindow).toHaveBeenCalledOnce(); + }); + + it("falls back to full-page redirect when a web popup is blocked", async () => { + const assign = vi.fn(); + vi.stubGlobal("window", { open: vi.fn(() => null) }); + vi.stubGlobal("location", { assign }); + vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => { + if (String(request).endsWith("/v1/apps/register")) { + return jsonResponse({ application: registeredApplication() }); + } + const form = new URLSearchParams(String(init?.body)); + const proof = JSON.parse(form.get("application_authorization")!); + return jsonResponse({ + authorization_id: proof.binding.authorization_id, + authorization_uri: "https://connect.example/oauth/authorize?request_id=blocked-popup", + expires_in: 600 + }); + }); + const manager = new MdbaseConnect({ + serverUrl: "https://connect.example", + manifest: { + manifest_version: 1, + id: "dev.tasks", + name: "Tasks", + homepage: "https://tasks.example/", + redirect_uris: ["https://tasks.example/callback"] + }, + redirectUri: "https://tasks.example/callback", + storage: new MemoryStorage(), + keyStore: new MemoryGrantKeyStore(), + identityStore: new MemoryApplicationIdentityStore(), + relayEncryption: "disabled" + }); + + await expect(manager.authorize({ presentation: "popup" })).resolves.toMatchObject({ + ok: true, + value: { kind: "redirecting" } + }); + expect(assign).toHaveBeenCalledWith("https://connect.example/oauth/authorize?request_id=blocked-popup"); + }); + it("signs v2 recovery only when an exact pending mutation matches the target and operation", async () => { const storage = new MemoryStorage(); const target = TEST_COLLECTION_ID; diff --git a/packages/client/src/internal-types.ts b/packages/client/src/internal-types.ts index f5a3edb48..f2981b13a 100644 --- a/packages/client/src/internal-types.ts +++ b/packages/client/src/internal-types.ts @@ -36,8 +36,13 @@ export interface StoredAuthorization { authorizationId?: string; applicationAgreementPublicKey?: string; applicationSigningPublicKey?: string; + presentation?: "popup"; } +export type StoredAuthorizationCompletion = + | { version: 1; status: "connected"; collectionId: string; returnTo?: string } + | { version: 1; status: "failed"; code: string; message: string; returnTo?: string }; + export interface StoredToken { version: 1; accessToken: string; diff --git a/packages/client/src/popup-authorization.ts b/packages/client/src/popup-authorization.ts new file mode 100644 index 000000000..206a7e4ce --- /dev/null +++ b/packages/client/src/popup-authorization.ts @@ -0,0 +1,138 @@ +import type { JsonObject } from "@mdbase-dev/connect-protocol"; +import { abortableDelay } from "./async.js"; +import type { + MdbaseAuthorizeOptions, + MdbaseAuthorizationOutcome, + MdbaseAuthorizationResult, + MdbaseConnection +} from "./connection.js"; +import type { GrantKeyStore } from "./crypto.js"; +import { MdbaseConnectError, connectError, serverConnectError } from "./errors.js"; +import type { + Application, + StoredAuthorization, + StoredAuthorizationCompletion +} from "./internal-types.js"; +import { parseStored } from "./runtime-utils.js"; + +export async function prepareAuthorizationWindow(input: { + options: MdbaseAuthorizeOptions; + portableDeclared: boolean; + navigate?: (url: string) => void | Promise; + register(signal: AbortSignal): Promise; +}): Promise<{ application: Application; popup: Window | null }> { + if (typeof location === "undefined" && !input.navigate && !input.options.openVerification) { + throw connectError("browser_required", "Authorization navigation requires a browser environment."); + } + const popupRequested = input.options.presentation === "popup" || input.portableDeclared; + const popup = popupRequested + && !input.options.openVerification + && !input.navigate + && typeof window !== "undefined" + ? window.open("", "mdbase-connect-authorization", "popup,width=620,height=760") + : null; + try { + return { + application: await input.register(input.options.signal!), + popup + }; + } catch (error) { + popup?.close(); + throw error; + } +} + +export async function waitForPopupAuthorization(input: { + storage: Storage; + storagePrefix: string; + state: string; + pending: StoredAuthorization; + popup: Window; + signal: AbortSignal; + keyStore: GrantKeyStore; + connection(collectionId: string): MdbaseConnection | null; +}): Promise> { + const completionKey = authorizationCompletionKey(input.storagePrefix, input.state); + try { + while (true) { + const completion = parseStored(input.storage.getItem(completionKey)); + if (completion?.version === 1) { + input.storage.removeItem(completionKey); + if (completion.status === "failed") { + throw serverConnectError(completion.code, completion.message, { + details: completion.returnTo ? { return_to: completion.returnTo } : undefined + }); + } + const connection = input.connection(completion.collectionId); + if (!connection) { + throw connectError("invalid_callback", "Authorization completed without a usable saved connection."); + } + return { + kind: "connected", + connection, + ...(completion.returnTo ? { returnTo: completion.returnTo } : {}) + }; + } + // Cross-origin opener isolation may report a live Connect window as + // closed. Shared callback state, abort, or the request budget owns exit. + await abortableDelay(200, input.signal); + } + } finally { + input.popup.close(); + input.storage.removeItem(completionKey); + const pendingKey = `${input.storagePrefix}:pending:${input.state}`; + const outstanding = parseStored(input.storage.getItem(pendingKey)); + if (outstanding?.state === input.state) { + input.storage.removeItem(pendingKey); + if (input.pending.keyHandle) await input.keyStore.delete(input.pending.keyHandle); + } + } +} + +export function publishPopupAuthorizationCompletion(input: { + storage: Storage; + storagePrefix: string; + state: string; + pending: StoredAuthorization | null; + popupAttempt: boolean; + completion: Promise>; +}): Promise> { + return input.completion.then((result) => { + if (input.popupAttempt) writeCompletion(input, { + version: 1, + status: "connected", + collectionId: result.connection.collectionId, + ...(result.returnTo ? { returnTo: result.returnTo } : {}) + }); + if (input.popupAttempt) closeCallbackWindow(); + return result; + }).catch((error: unknown) => { + if (input.popupAttempt) writeCompletion(input, { + version: 1, + status: "failed", + code: error instanceof MdbaseConnectError ? error.code : "invalid_callback", + message: error instanceof Error ? error.message : "Authorization could not be completed.", + ...(input.pending?.returnTo ? { returnTo: input.pending.returnTo } : {}) + }); + if (input.popupAttempt) closeCallbackWindow(); + throw error; + }); +} + +function writeCompletion( + input: Pick[0], "storage" | "storagePrefix" | "state">, + completion: StoredAuthorizationCompletion +): void { + input.storage.setItem( + authorizationCompletionKey(input.storagePrefix, input.state), + JSON.stringify(completion) + ); +} + +function authorizationCompletionKey(storagePrefix: string, state: string): string { + return `${storagePrefix}:completion:${state}`; +} + +function closeCallbackWindow(): void { + if (typeof window !== "undefined" && typeof window.close === "function") window.close(); +} diff --git a/scripts/browser-accessibility.test.mjs b/scripts/browser-accessibility.test.mjs index 97e185fe9..ba9b8678d 100644 --- a/scripts/browser-accessibility.test.mjs +++ b/scripts/browser-accessibility.test.mjs @@ -413,6 +413,12 @@ async function auditDesktopRoutes() { const page = await browser.newPage(); const errors = watchPageErrors(page); await page.addInitScript((pendingAuthorization) => { + localStorage.setItem("mdbase:collection-completion", JSON.stringify({ + collectionId: "55555555-5555-4555-8555-555555555555", + collectionName: "Personal notes", + authority: "local", + path: "/home/example/Personal notes" + })); const status = { protocol_version: 1, state: "connected", @@ -466,7 +472,9 @@ async function auditDesktopRoutes() { setLaunchAtLogin: async () => ({ enabled: false, available: true }), checkForUpdates: async () => updateStatus, installUpdate: async () => updateStatus, - openAuthorization: async () => undefined + openAuthorization: async () => undefined, + openPath: async () => undefined, + openEditor: async () => undefined }; }, desktopAuthorizationFixture("44444444-4444-4444-8444-444444444444")); await page.goto(servers[1].origin); @@ -474,6 +482,10 @@ async function auditDesktopRoutes() { await page.getByRole("button", { name: "Add existing folder" }).waitFor(); await page.getByRole("button", { name: "Create collection" }).waitFor(); await page.getByRole("button", { name: "Pause app access" }).waitFor(); + await page.getByRole("heading", { name: "Personal notes is connected." }).waitFor(); + await page.getByRole("button", { name: "Open folder" }).waitFor(); + await page.getByRole("button", { name: "Use in application" }).waitFor(); + await page.getByText("The folder path stays private.", { exact: true }).waitFor(); await auditPage(page, "desktop overview", { keyboard: true }); for (const route of [ @@ -485,7 +497,7 @@ async function auditDesktopRoutes() { await page.getByRole("button", { name: route[0] }).click(); await page.getByRole("heading", { name: route[1] }).waitFor(); if (route[0] === "App access") { - await page.getByRole("button", { name: "Review in portal" }).waitFor(); + await page.getByRole("button", { name: "Review in Connect" }).waitFor(); assert.equal(await page.getByRole("button", { name: "Reject" }).count(), 0); } await auditPage(page, `desktop ${route[0].toLowerCase()}`); diff --git a/scripts/ci/verify-qualified-commit b/scripts/ci/verify-qualified-commit index f7bb71078..60b048b54 100755 --- a/scripts/ci/verify-qualified-commit +++ b/scripts/ci/verify-qualified-commit @@ -55,15 +55,23 @@ manifest=$temporary/qualification.json printf 'Qualification artifact or checkout identity is invalid.\n' >&2 exit 1 } +# Pull-request artifacts record GitHub's synthetic merge SHA while the run API +# identifies the PR head. Accept that SHA only for the artifact from this exact +# run, and still require its qualified tree to equal the head tree checked out +# by the publisher. jq -e \ --arg commit "$commit" \ + --arg event "$expected_event" \ + --arg run_id "$run_id" \ --arg tree "$(git rev-parse HEAD^{tree})" \ --arg pnpm "$(sha256_file pnpm-lock.yaml)" \ --arg cargo "$(sha256_file deploy/docker/Cargo.lock.hosted-provider)" \ --arg revision "$(tr -d '\r\n' { +test("builds and deploys the editor against lab by default", async () => { const calls = []; await deployDevelopmentEditor({}, async (command, args, environment) => { calls.push({ command, args, environment }); }); const build = calls.find(({ args }) => args.includes("mdbase-editor") && args.includes("build")); - assert.equal(build.environment.MDBASE_EDITOR_ORIGIN, developmentDeployment.editorOrigin); - assert.equal(build.environment.MDBASE_CONNECT_URL, developmentDeployment.connectOrigin); - assert.equal(build.environment.VITE_MDBASE_CONNECT_URL, developmentDeployment.connectOrigin); + assert.equal(build.environment.MDBASE_EDITOR_ORIGIN, developmentDeployments.lab.editorOrigin); + assert.equal(build.environment.MDBASE_CONNECT_URL, developmentDeployments.lab.connectOrigin); + assert.equal(build.environment.VITE_MDBASE_CONNECT_URL, developmentDeployments.lab.connectOrigin); const manifestChecks = calls.filter(({ args }) => args.includes("apps/editor/scripts/verify-deployment-manifest.mjs")); assert.equal(manifestChecks.length, 2); for (const check of manifestChecks) { - assert.equal(check.args.at(-1), developmentDeployment.connectOrigin); + assert.equal(check.args.at(-1), developmentDeployments.lab.connectOrigin); } const deploy = calls.find(({ args }) => args.includes("wrangler@4.114.0")); assert.ok(deploy); assert.ok(deploy.args.includes("--project-name=mdbase-editor")); + assert.ok(deploy.args.includes("--branch=candidate-b")); +}); + +test("staging requires an explicit environment and production is rejected", async () => { + const calls = []; + await deployDevelopmentEditor({ MDBASE_ENV: "staging" }, async (command, args, environment) => { + calls.push({ command, args, environment }); + }); + const deploy = calls.find(({ args }) => args.includes("wrangler@4.114.0")); assert.ok(deploy.args.includes("--branch=staging")); + assert.equal(deploy.environment.MDBASE_CONNECT_URL, developmentDeployments.staging.connectOrigin); + await assert.rejects( + deployDevelopmentEditor({ MDBASE_ENV: "production" }, async () => undefined), + /restricted to lab and staging/ + ); + await assert.rejects( + deployDevelopmentEditor({ MDBASE_ENV: "lab", MDBASE_CONNECT_URL: developmentDeployments.staging.connectOrigin }, async () => undefined), + /does not match the lab environment/ + ); }); diff --git a/services/server/src/features/authorizations/routes.ts b/services/server/src/features/authorizations/routes.ts index 14c59c6e9..e2b12a75f 100644 --- a/services/server/src/features/authorizations/routes.ts +++ b/services/server/src/features/authorizations/routes.ts @@ -569,6 +569,28 @@ export function registerAuthorizationRoutes( [requestId, user.id] ); if (!authorization.rows[0]) return reply.code(404).send(apiError("authorization_not_found", "Authorization request expired or was not found.")); + const activeGrants = await options.db.query<{ + collection_id: string; + operations: string[]; + }>( + `SELECT COALESCE(col.local_id, g.hosted_collection_id)::text AS collection_id, + g.operations + FROM grants g + LEFT JOIN collections col ON col.id = g.collection_id + WHERE g.user_id = $1 AND g.application_id = $2 + AND g.activated_at IS NOT NULL AND g.revoked_at IS NULL`, + [user.id, authorization.rows[0].application_id] + ); + const operationsByCollection = new Map>(); + for (const grant of activeGrants.rows) { + const operations = operationsByCollection.get(grant.collection_id) ?? new Set(); + for (const operation of grant.operations) operations.add(operation); + operationsByCollection.set(grant.collection_id, operations); + } + const existingAccess = [...operationsByCollection].map(([collection_id, operations]) => ({ + collection_id, + operations: [...operations].sort() + })); const local = requiresHostedCollection(authorization.rows[0].requirements) ? { collections: [], unavailable_connectors: [] } : await liveAuthorizationCollections(options.db, relay, user.id, requestId); @@ -619,7 +641,10 @@ export function registerAuthorizationRoutes( ...hostedCollections ]; return { - authorization: authorization.rows[0], + authorization: { + ...authorization.rows[0], + existing_access: existingAccess + }, hosted_collections_available: options.hostedCollections === true, unavailable_connectors: local.unavailable_connectors, collections: requiresHostedCollection(authorization.rows[0].requirements) diff --git a/services/server/src/live-authorization.test.ts b/services/server/src/live-authorization.test.ts index c00dd7fa5..88b1b1346 100644 --- a/services/server/src/live-authorization.test.ts +++ b/services/server/src/live-authorization.test.ts @@ -326,11 +326,16 @@ describe("live connector-mediated authorization", () => { "replacement", installationIdentity ); - const replacementOffer = (await app.inject({ + const replacementPending = await app.inject({ method: "GET", url: `/v1/authorization-requests/${replacementRequestId}`, headers: { cookie } - })).json().collections[0]; + }); + expect(replacementPending.json().authorization.existing_access).toEqual([{ + collection_id: serverCollectionId, + operations: ["describe"] + }]); + const replacementOffer = replacementPending.json().collections[0]; const replacement = await app.inject({ method: "POST", url: `/v1/authorization-requests/${replacementRequestId}/approve`, @@ -574,7 +579,7 @@ describe("live connector-mediated authorization", () => { peer: "connector" }, minimum_connector_version: "0.1.0-beta.33", - update_url: "https://github.com/mdbase-dev/mdbase-connect/releases/latest" + update_url: "https://mdbase.dev/downloads/" }); const [code] = await closePromise; expect(code).toBe(4406); @@ -593,7 +598,7 @@ describe("live connector-mediated authorization", () => { connector_version: "0.1.0-beta.30", incompatibility_code: "transport_protocol_incompatible", minimum_connector_version: "0.1.0-beta.33", - connector_update_url: "https://github.com/mdbase-dev/mdbase-connect/releases/latest" + connector_update_url: "https://mdbase.dev/downloads/" }); const overview = await app.inject({ method: "GET", url: "/v1/me", headers: { cookie } }); expect(overview.json().connectors).toContainEqual(expect.objectContaining({ @@ -601,7 +606,7 @@ describe("live connector-mediated authorization", () => { connector_version: "0.1.0-beta.30", compatibility: "upgrade_required", minimum_connector_version: "0.1.0-beta.33", - update_url: "https://github.com/mdbase-dev/mdbase-connect/releases/latest" + update_url: "https://mdbase.dev/downloads/" })); const compatibleConnector = (await app.inject({ diff --git a/services/server/src/relay-compatibility.ts b/services/server/src/relay-compatibility.ts index dc6eb2035..b6dae9bf6 100644 --- a/services/server/src/relay-compatibility.ts +++ b/services/server/src/relay-compatibility.ts @@ -10,7 +10,7 @@ import type { WebSocket } from "ws"; const HANDSHAKE_TIMEOUT_MS = 5_000; const INCOMPATIBLE_CLOSE_CODE = 4406; export const CONNECTOR_UPDATE_URL = - "https://github.com/mdbase-dev/mdbase-connect/releases/latest"; + "https://mdbase.dev/downloads/"; export interface RelayHello { protocol_version: number;