Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(apps): ask at the computer before a phone brings it into its account, and pair by short code

leepokai3945dded48c6
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt
index 665b2b10..09c5264c 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt
@@ -11,14 +11,18 @@ import kotlinx.coroutines.sync.withLock
// Pairing and the links notifications, widgets and other apps open.
-/** Pairs with the computer in a `codync://pair` link: scanned or pasted ([PairedVia.Qr]) or opened from outside ([PairedVia.Link]). */
+/**
+ * Pairs with the computer in a `codync://pair` link: scanned or pasted ([PairedVia.Qr]) or opened from outside ([PairedVia.Link]).
+ * A short code typed from the computer ([Pairing.shortCode]) is turned into its link by the cloud first.
+ */
internal fun AccountStore.pair(text: String, via: PairedVia) {
if (pairingJob?.isActive == true) return
pairingJob = contextScope.launch {
state.first { !it.loading }
mutableState.update { it.copy(pairing = true, error = null) }
try {
- val pairing = Pairing.parse(text, BuildConfig.URL_SCHEME)
+ val link = Pairing.shortCode(text)?.let { code -> (cloud ?: throw IOException(NO_PROOF)).pairingLink(code) } ?: text
+ val pairing = Pairing.parse(link, BuildConfig.URL_SCHEME)
val old = state.value.computers.firstOrNull { it.id == pairing.computer.id }
require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }
val identity = withContext(Dispatchers.IO) { local.identity() }
@@ -67,11 +71,13 @@ private suspend fun AccountStore.accountProof(): DeviceCertificate {
null
}
val proof = fresh ?: cached?.takeIf { it.expiresAt > System.currentTimeMillis() }
- ?: throw IOException("Connect to the internet to pair, so Codync can confirm your account.")
+ ?: throw IOException(NO_PROOF)
deviceCertificate = proof
return proof
}
+private const val NO_PROOF = "Connect to the internet to pair, so Codync can confirm your account."
+
/** [step] of joining the account, which pairing goes on without: a failure is only logged. */
private suspend fun <T> bestEffort(what: String, step: suspend () -> T): T? = try { step() }
catch (error: CancellationException) { throw error }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
index e25fe073..6125b914 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
@@ -236,7 +236,7 @@ private enum class ComputerOS { Mac, Linux }
}
Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(Palette.surface).padding(start = 14.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically) {
- PlainTextField(pasted, { pasted = it }, Modifier.weight(1f), tr("Or paste a {scheme}://pair link").replace("{scheme}", BuildConfig.URL_SCHEME), singleLine = true,
+ PlainTextField(pasted, { pasted = it }, Modifier.weight(1f), tr("Paste a pairing link, or type the code from the computer"), singleLine = true,
style = Type.callout.monospaced, keyboard = KeyboardOptions(capitalization = KeyboardCapitalization.None, autoCorrectEnabled = false,
imeAction = ImeAction.Go), actions = KeyboardActions(onGo = { pair(pasted) }))
IconButton("Pair", "arrow.right", enabled = pasted.isNotEmpty() && !state.pairing) { pair(pasted) }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
index 3de8010d..3c0c9f47 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
@@ -99,6 +99,10 @@ class CloudClient private constructor(base: String, private val identity: Device
request("POST", listOf("v1", "claims", claimId, "complete"), signed)
}
+ /** The pairing link a short code ([Pairing.shortCode]) stands for. The cloud hands it out once. */
+ suspend fun pairingLink(code: String): String =
+ requireNotNull(request("GET", listOf("v1", "pairing-codes", code)).text("link")) { "Invalid pairing code response" }
+
suspend fun computers(): List<CloudComputer> {
val result = request("GET", listOf("v1", "computers"), signed = true)
return json.decodeFromJsonElement(result.getValue("computers"))
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
index bd9dada4..bd5d283b 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
@@ -21,6 +21,15 @@ data class Pairing(val computer: Computer, val code: String) {
fun checkCode(identity: DeviceIdentity): String = RelayCrypto.pairCheck(identity.deviceKey, computer.signKey.decodeBase64Url(32))
companion object {
+ private val SHORT_CODE = Regex("([A-Za-z]{4})[- ]?([0-9]{4})")
+
+ /**
+ * A short code `codync-host pair` prints (`QRTX-4821`: 4 letters, an optional dash or space, 4 digits) as the cloud
+ * takes it, or null for anything else (iOS `Pairing.shortCode`). The cloud resolves it to the pairing link.
+ */
+ fun shortCode(text: String): String? =
+ SHORT_CODE.matchEntire(text.trim())?.destructured?.let { (letters, digits) -> "${letters.uppercase()}-$digits" }
+
fun parse(text: String, scheme: String): Pairing {
if (text.length > 16 * 1024) throw PairingProblem(PairingProblem.Kind.Invalid)
val url = try { URI(text.trim()) } catch (error: Exception) {
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
index d0fe332e..bdeed310 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
@@ -60,6 +60,26 @@ class CloudClientTest {
} finally { server.shutdown() }
}
+ @Test fun `a pairing code is looked up unsigned and an unknown one fails with the cloud's message`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("""{"link":"codync://pair?v=3"}"""))
+ server.enqueue(MockResponse().setResponseCode(404)
+ .setBody("""{"error":{"code":"notFound","message":"That code expired or was used. Show a new one on the computer."}}"""))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ assertEquals("codync://pair?v=3", client.pairingLink("QRTX-4821"))
+ val request = server.takeRequest()
+ assertEquals("GET", request.method)
+ assertEquals("/v1/pairing-codes/QRTX-4821", request.path)
+ assertEquals("Bearer session", request.getHeader("Authorization"))
+ assertNull(request.getHeader("Codync-Sig"))
+ val error = try { client.pairingLink("QRTX-4821"); error("Expected a used code") } catch (error: CloudError) { error }
+ assertEquals(404, error.status)
+ assertEquals("That code expired or was used. Show a new one on the computer.", error.message)
+ } finally { server.shutdown() }
+ }
+
@Test fun `an error page that isn't JSON still fails with its status`() = runBlocking {
val server = MockWebServer()
server.start()
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
index 254cc318..7b226513 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
@@ -16,6 +16,13 @@ class PairingTest {
private fun link(fields: Map<String, String> = params): String = "codync://pair?" + fields.entries.joinToString("&") {
"${it.key}=${URLEncoder.encode(it.value, "UTF-8")}" }
+ @Test fun `short pairing codes are recognized in any case and links are not codes`() {
+ for (typed in listOf("QRTX-4821", "qrtx4821", " Qrtx 4821\n", "QRTX4821")) assertEquals("QRTX-4821", Pairing.shortCode(typed))
+ for (other in listOf("QRT-4821", "QRTX-482", "QRTX--4821", "QRTX_4821", "1234-QRTX", "QRTXX4821", link(), "")) {
+ assertEquals(null, Pairing.shortCode(other))
+ }
+ }
+
@Test fun `a valid pairing preserves pins direct candidates relay and name`() {
val pairing = Pairing.parse(" ${link()} \n", "codync")
assertEquals(params["id"], pairing.computer.id)
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 3fb4af0b..7be7d2b0 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -184,6 +184,10 @@ function registerIPC(tray: Tray) {
})
ipcMain.handle('app:clipboardFiles', () => readClipboardFiles())
ipcMain.on('app:traySummary', (_e, summary) => tray.update(summary))
+ ipcMain.on('app:showWindow', () => {
+ openChat()
+ if (isMac) app.focus({ steal: true })
+ })
ipcMain.handle('app:showInDock', () => showInDock())
ipcMain.handle('app:setShowInDock', (_e, on: boolean) => {
const visible = setShowInDock(on)
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index b8ae69b3..b0f51f27 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -137,6 +137,7 @@ const bridge: CodyncBridge = {
pickExport: () => ipcRenderer.invoke('app:pickExport'),
readClipboardFiles: () => ipcRenderer.invoke('app:clipboardFiles'),
setTraySummary: (summary: TraySummary) => ipcRenderer.send('app:traySummary', summary),
+ showWindow: () => ipcRenderer.send('app:showWindow'),
onCommand: (cb: (c: WindowCommand) => void) => listen('app:command', cb),
resetAllData: () => ipcRenderer.invoke('app:resetAllData'),
setLaunchAtLogin: (on) => ipcRenderer.invoke('app:setLaunchAtLogin', on),
diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.ts
index 0bf62476..2ff1f388 100644
--- a/apps/desktop/src/renderer/client/host-client.ts
+++ b/apps/desktop/src/renderer/client/host-client.ts
@@ -7,6 +7,7 @@ import {
type CloudStatus,
type Entry,
type Hello,
+ type PairingRequest,
type ScreenState,
type Usage,
} from '@shared/models'
@@ -75,6 +76,7 @@ export type HostEvent =
| { type: 'artifact'; artifact: Artifact }
| { type: 'screen'; screen: ScreenState }
| { type: 'accessRequests'; requests: AccessRequest[] }
+ | { type: 'pairingRequests'; requests: PairingRequest[] }
| { type: 'cloud'; cloud: CloudStatus }
/** This computer's network changed (members, roles, presence, offered bots) or cloud assistants were switched. */
| { type: 'network'; network: NetworkView }
@@ -128,6 +130,8 @@ export function parseEvent(line: string): HostEvent | null {
}
case 'accessRequests':
return { type, requests: (raw.requests as AccessRequest[]) ?? [] }
+ case 'pairingRequests':
+ return { type, requests: (raw.requests as PairingRequest[]) ?? [] }
case 'cloud':
return raw.cloud ? { type, cloud: raw.cloud as CloudStatus } : null
case 'network':
diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.ts
index 2f2a6460..37294043 100644
--- a/apps/desktop/src/renderer/demo/bridge.ts
+++ b/apps/desktop/src/renderer/demo/bridge.ts
@@ -102,6 +102,7 @@ const bridge: CodyncBridge = {
pickExport: async () => null,
readClipboardFiles: async () => [],
setTraySummary() {},
+ showWindow() {},
onCommand: none,
resetAllData: async () => {},
setLaunchAtLogin: async () => false,
diff --git a/apps/desktop/src/renderer/lib/account-copy.test.ts b/apps/desktop/src/renderer/lib/account-copy.test.ts
new file mode 100644
index 00000000..40335c7d
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/account-copy.test.ts
@@ -0,0 +1,27 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { devicesLoseAccess, pairingAskText, spacedCode } from './account-copy.ts'
+
+const tr = (text: string) => text
+
+test('the pairing ask names the phone, its account and the spaced code', () => {
+ assert.deepEqual(pairingAskText(tr, { deviceName: 'Pixel', email: '[email protected]', code: '123456' }), {
+ title: 'Let Pixel in?',
+ message: "[email protected] wants to use this computer, which then joins [email protected]'s account. Check Pixel shows 123\u00a0456.",
+ })
+})
+
+test('a phone without an email is a Codync account, and names keep their braces', () => {
+ const text = pairingAskText(tr, { deviceName: '{code}', email: null, code: '000042' })
+ assert.equal(text.title, 'Let {code} in?')
+ assert.equal(text.message, "A Codync account wants to use this computer, which then joins A Codync account's account. Check {code} shows 000\u00a0042.")
+})
+
+test('changing account drops every device of the old one', () => {
+ assert.equal(devicesLoseAccess(tr, '[email protected]'), "Every device of [email protected]'s account loses access.")
+ assert.equal(devicesLoseAccess(tr, null), 'Every device of that account loses access.')
+})
+
+test('codes other than 6 digits stay as they are', () => {
+ assert.equal(spacedCode('12345'), '12345')
+})
diff --git a/apps/desktop/src/renderer/lib/account-copy.ts b/apps/desktop/src/renderer/lib/account-copy.ts
new file mode 100644
index 00000000..9ceb6255
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/account-copy.ts
@@ -0,0 +1,24 @@
+/** What the interface says when a computer joins or leaves an account (docs/plans/require-sign-in.md, phase 2). */
+
+type Tr = (text: string) => string
+
+/** "123 456" for a 6-digit code. */
+export const spacedCode = (code: string) => (code.length === 6 ? `${code.slice(0, 3)} ${code.slice(3)}` : code)
+
+/** Fills `{key}` in one pass: a device named "{code}" stays as written. */
+const fill = (text: string, values: Record<string, string>) => text.replace(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match)
+
+/** A signed-in phone scanned a computer in no account: letting it in brings the computer into the phone's account. */
+export function pairingAskText(tr: Tr, request: { deviceName: string; email?: string | null; code: string }) {
+ // A no-break space: the code never wraps apart.
+ const values = { name: request.deviceName, email: request.email || tr('A Codync account'), code: spacedCode(request.code).replace(' ', '\u00a0') }
+ return {
+ title: fill(tr('Let {name} in?'), values),
+ message: fill(tr("{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}."), values),
+ }
+}
+
+/** A computer that changes its account drops every device of the old one, QR-paired ones included. */
+export function devicesLoseAccess(tr: Tr, email: string | null | undefined) {
+ return email ? fill(tr("Every device of {email}'s account loses access."), { email }) : tr('Every device of that account loses access.')
+}
diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.ts
index 24d80d76..0a9ad7e2 100644
--- a/apps/desktop/src/renderer/store/app-model.ts
+++ b/apps/desktop/src/renderer/store/app-model.ts
@@ -1,6 +1,6 @@
import { trackBody } from '@shared/analytics'
import type { HostSnapshot, LocalHost } from '@shared/ipc'
-import type { AccessRequest, Bot, Computer } from '@shared/models'
+import type { AccessRequest, Bot, Computer, PairingRequest } from '@shared/models'
import { HostError, LoopbackTransport } from '../client/host-client'
import { Observable } from '../lib/observable'
import { account } from './account'
@@ -37,6 +37,13 @@ export interface Approval {
request: AccessRequest
}
+/** A signed-in phone asking a computer this app manages, in no account, to let it in and join its account. */
+export interface PairingAsk {
+ id: string
+ store: BotStore
+ request: PairingRequest
+}
+
/**
* The window's model: this computer's own host (from the main process), one `BotStore` per
* computer, the selection, and what the menu bar shows. Mirrors kit's `AccountStore`.
@@ -226,6 +233,17 @@ export class AppModel extends Observable {
await client.call('decideAccessRequest', { requestId: a.request.requestId, approve }, 30_000)
}
+ get pairingAsks(): PairingAsk[] {
+ return this.managedStores.flatMap((store) =>
+ store.pairingRequests.map((request) => ({ id: `${store.computer.id}/${request.requestId}`, store, request })),
+ )
+ }
+
+ async decidePairing(ask: PairingAsk, approve: boolean) {
+ const client = await ask.store.ready()
+ await client.call('decidePairing', { requestId: ask.request.requestId, approve }, 30_000)
+ }
+
get needsAttention() {
return this.roster.some((i) => i.bot.status === 'needsInput') || this.approvals.length > 0
}
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.ts
index fb9bcaf6..204399eb 100644
--- a/apps/desktop/src/renderer/store/bot-mirror.ts
+++ b/apps/desktop/src/renderer/store/bot-mirror.ts
@@ -6,6 +6,7 @@ import {
type Computer,
type Entry,
type Hello,
+ type PairingRequest,
type ScreenState,
type Usage,
} from '@shared/models'
@@ -79,6 +80,7 @@ export class BotMirror extends Observable {
usage: Usage = { providers: [] }
screen: ScreenState | null = null
accessRequests: AccessRequest[] = []
+ pairingRequests: PairingRequest[] = []
cloud: CloudStatus | null = null
/** This computer's network; null until known, and on hosts without `networkView`. */
network: NetworkView | null = null
diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.ts
index f18d671a..2dda00a5 100644
--- a/apps/desktop/src/renderer/store/bot-sync.ts
+++ b/apps/desktop/src/renderer/store/bot-sync.ts
@@ -1,4 +1,4 @@
-import { isChat, type AccessRequest, type CloudStatus, type Entry } from '@shared/models'
+import { isChat, type AccessRequest, type CloudStatus, type Entry, type PairingRequest } from '@shared/models'
import { isOutsideLoadedWindow, snapshotFloors } from '@shared/mirror-window'
import { HostClient, HostError, type HostEvent } from '../client/host-client'
import { undoOnFailure } from '../lib/undo-on-failure'
@@ -151,6 +151,9 @@ export class BotSync extends BotMirror {
try {
this.accessRequests = (await client.call<{ requests: AccessRequest[] }>('accessRequests')).requests
} catch {}
+ try {
+ this.pairingRequests = (await client.call<{ requests: PairingRequest[] }>('pairingRequests')).requests
+ } catch {}
try {
this.cloud = await client.call<CloudStatus>('cloudStatus')
} catch {}
@@ -268,6 +271,9 @@ export class BotSync extends BotMirror {
case 'accessRequests':
this.accessRequests = event.requests
break
+ case 'pairingRequests':
+ this.pairingRequests = event.requests
+ break
case 'cloud':
this.cloud = event.cloud
break
diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.ts
index 44e1c537..a82b0bea 100644
--- a/apps/desktop/src/renderer/store/cloud.ts
+++ b/apps/desktop/src/renderer/store/cloud.ts
@@ -235,8 +235,8 @@ export class CloudModel extends Observable {
}
/**
- * Yes to `moveOffer`: out of the other account, then into this one. Devices that account approved lose
- * access; out of an account the host turns the 6-digit check back on, so the new account's devices show
+ * Yes to `moveOffer`: out of the other account, then into this one. Every device of that account loses
+ * access, QR-paired ones included; out of an account the host turns the 6-digit check back on, so the new account's devices show
* a code before getting in.
*/
async moveHere(store: BotStore) {
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 2bc74b11..d23950cb 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -38,6 +38,7 @@ export { EmptyState } from './HostStateView'
import { RefreshIndicator } from './RefreshIndicator'
import { StarPrompt } from './StarPrompt'
import { MoveComputerPrompt } from './MoveComputerPrompt'
+import { PairingRequestPrompt } from './PairingRequestPrompt'
import { OpenVoiceSettings } from './call/CallView'
import { AccountPanelLayer, ProfileAvatar } from './PanelMenus'
import { DesktopActionMenu, type ActionItem } from './DesktopActionMenu'
@@ -165,6 +166,7 @@ export function ChatWindow() {
<Sheet open={approval !== null} onClose={() => approval && app.deferApproval(approval)}>
{approval ? <ApprovalSheet key={approval.id} approval={approval} /> : null}
</Sheet>
+ <PairingRequestPrompt />
</div>
)
}
diff --git a/apps/desktop/src/renderer/views/MoveComputerPrompt.tsx b/apps/desktop/src/renderer/views/MoveComputerPrompt.tsx
index 33af442f..625bc999 100644
--- a/apps/desktop/src/renderer/views/MoveComputerPrompt.tsx
+++ b/apps/desktop/src/renderer/views/MoveComputerPrompt.tsx
@@ -1,4 +1,5 @@
import { Dialog } from '../components/Overlay'
+import { devicesLoseAccess } from '../lib/account-copy'
import { useModel } from '../lib/observable'
import { useTr } from '../lib/use-language'
import { useAccount } from '../store/account'
@@ -17,7 +18,7 @@ export function MoveComputerPrompt() {
<Dialog
open={offer !== null}
title={tr('Move this computer to your account?')}
- message={`${where} ${tr('Devices that were approved through the account lose access. Devices paired with a QR code keep it.')} ${tr('New devices ask for access with a 6-digit code.')}`}
+ message={`${where} ${devicesLoseAccess(tr, offer?.from)} ${tr('New devices ask for access with a 6-digit code.')}`}
// A choice either way: "keep it there" is remembered, so it isn't a dismissal.
cancel={null}
actions={offer ? [
diff --git a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
new file mode 100644
index 00000000..61c79546
--- /dev/null
+++ b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
@@ -0,0 +1,46 @@
+import { useEffect, useState } from 'react'
+import { Dialog } from '../components/Overlay'
+import { pairingAskText } from '../lib/account-copy'
+import { useModels } from '../lib/observable'
+import { useTr } from '../lib/use-language'
+import { useApp } from '../store/context'
+import { errorText } from './settings/parts'
+
+/**
+ * A signed-in phone scanned a computer this app manages that is in no account: let it in, and the computer joins
+ * the phone's account (docs/plans/require-sign-in.md, phase 2). The phone shows the same code. Unanswered, the
+ * host turns the phone away after 2 minutes.
+ */
+export function PairingRequestPrompt() {
+ const tr = useTr()
+ const app = useApp()
+ useModels(app.managedStores)
+ // Answered here: gone at once, not when the host's event arrives.
+ const [answered, setAnswered] = useState<ReadonlySet<string>>(new Set())
+ const ask = app.pairingAsks.find((a) => !answered.has(a.id)) ?? null
+ // The phone is in someone's hand at this computer, maybe scanning the menu bar's pairing window.
+ useEffect(() => {
+ if (ask) window.codync.app.showWindow()
+ }, [ask?.id])
+
+ const decide = (approve: boolean) => {
+ if (!ask) return
+ setAnswered((ids) => new Set(ids).add(ask.id))
+ app.decidePairing(ask, approve).catch((error: unknown) => app.setError(errorText(error)))
+ }
+ const text = ask ? pairingAskText(tr, ask.request) : null
+ return (
+ <Dialog
+ open={ask !== null}
+ title={text?.title ?? ''}
+ message={text?.message}
+ // A choice either way: closing would leave the phone waiting.
+ cancel={null}
+ actions={[
+ { title: "Don't allow", action: () => decide(false) },
+ { title: 'Let in', action: () => decide(true) },
+ ]}
+ onClose={() => {}}
+ />
+ )
+}
diff --git a/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx b/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx
index 0f574d0f..b876afdb 100644
--- a/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx
+++ b/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx
@@ -6,7 +6,8 @@ import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import type { Approval } from '../../store/app-model'
import { useApp } from '../../store/context'
-import { deviceIcon, errorText, spacedCode } from './parts'
+import { deviceIcon, errorText } from './parts'
+import { spacedCode } from '../../lib/account-copy'
import { useTr } from '../../lib/use-language'
diff --git a/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx b/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx
index d14de5fe..551fd3e2 100644
--- a/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx
+++ b/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx
@@ -31,7 +31,7 @@ export function AuthorizedDevicesSection({ store }: { store: BotStore }) {
}, [store])
// Also when it changes account: the devices approved through the old one lose access.
- useEffect(() => void loadDevices(), [loadDevices, online, store.accessRequests.length, store.cloud?.owner?.userId])
+ useEffect(() => void loadDevices(), [loadDevices, online, store.accessRequests.length, store.pairingRequests.length, store.cloud?.owner?.userId])
const revoke = async (device: AuthorizedDevice) => {
try {
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 4ca37e0d..335a3665 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -15,6 +15,7 @@ import { ComputerBadge } from '../ComputerBadge'
import { PairingCode } from '../PairingCode'
import { AuthorizedDevicesSection } from './AuthorizedDevicesSection'
import { ComputersUsedSection } from './ComputersUsedSection'
+import { devicesLoseAccess } from '../../lib/account-copy'
import { cloudStatusLine } from '../../lib/relay-copy'
import { useTr } from '../../lib/use-language'
import { errorText, liveClient, relativeDay, SectionHeader, statusText, thisMac } from './parts'
@@ -89,10 +90,10 @@ export function ComputersView() {
<Dialog
open={removing !== null}
title={tr(removingOlder ? 'Remove the older {name}?' : 'Remove {name} from the account?').replaceAll('{name}', removing?.name ?? 'computer')}
- message={tr(removingOlder
- ? "It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account."
+ message={removingOlder
+ ? tr("It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.").replaceAll('{name}', removing.name)
// Offline may only mean asleep: removal unclaims it, and its own app won't add it back by itself.
- : 'Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.').replaceAll('{name}', removing?.name ?? 'a computer')}
+ : `${devicesLoseAccess(tr, account.user?.email)} ${tr('Access comes back only when you add {name} to the account again on {name} itself.').replaceAll('{name}', removing?.name ?? 'a computer')}`}
actions={removing ? [{ title: 'Remove', destructive: true, action: () => void cloud.removeFromAccount(removing.computerId) }] : []}
onClose={() => setRemoving(null)}
/>
@@ -271,7 +272,7 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B
<Dialog
open={confirmUnclaim}
title={tr('Remove {name} from the account?').replaceAll('{name}', name)}
- message={tr('Devices that were approved through the account lose access. Devices paired with a QR code keep it.')}
+ message={devicesLoseAccess(tr, owner?.email)}
actions={[{ title: 'Remove from account', destructive: true, action: () => run(() => app.cloud.unclaim(store)) }]}
onClose={() => setConfirmUnclaim(false)}
/>
diff --git a/apps/desktop/src/renderer/views/settings/parts.tsx b/apps/desktop/src/renderer/views/settings/parts.tsx
index 69841d2f..b3a6eaa8 100644
--- a/apps/desktop/src/renderer/views/settings/parts.tsx
+++ b/apps/desktop/src/renderer/views/settings/parts.tsx
@@ -60,6 +60,3 @@ export function statusText(store: BotStore) {
/** The live client, or null while the computer isn't connected (kit's `store.client`). */
export const liveClient = (store: BotStore) => (store.connection.kind === 'online' ? store.client : null)
-
-/** "123 456" for a 6-digit code. */
-export const spacedCode = (code: string) => (code.length === 6 ? `${code.slice(0, 3)} ${code.slice(3)}` : code)
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index fdf8fe80..b0df7236 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -255,6 +255,8 @@ export interface CodyncBridge {
pickExport(): Promise<string | null>
readClipboardFiles(): Promise<PickedFile[]>
setTraySummary(summary: TraySummary): void
+ /** Brings the chat window forward (a phone waits for this computer to let it in). */
+ showWindow(): void
onCommand(cb: (command: WindowCommand) => void): () => void
resetAllData(): Promise<void>
setLaunchAtLogin(on: boolean): Promise<boolean>
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 86d6b2c7..8045cdee 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -529,6 +529,18 @@ export interface AccessRequest {
expiresAt?: number | null
}
+/** A signed-in phone that scanned a computer in no account, waiting to be let in (loopback `pairingRequests`). */
+export interface PairingRequest {
+ requestId: string
+ deviceName: string
+ platform?: string | null
+ /** The phone's account, which the computer joins. */
+ email?: string | null
+ /** The 6 digits the phone shows too. */
+ code: string
+ expiresAt?: number | null
+}
+
/** A device the host authorized (loopback `devices`). */
export interface AuthorizedDevice {
key: string
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index 39818269..94044243 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -215,9 +215,16 @@ final class AppStore {
WidgetCenter.shared.reloadAllTimelines()
}
- /// A scanned, pasted or opened pairing link; one that can't be read is recorded before it's shown.
- func pairing(from link: String) throws -> Pairing {
- do { return try Pairing.parse(link) } catch { throw pairingFailed(error) }
+ /// A scanned, pasted or opened pairing link, or a short code typed from the computer, which the cloud
+ /// turns into its link; one that can't be read is recorded before it's shown.
+ func pairing(from text: String) async throws -> Pairing {
+ do {
+ guard let code = Pairing.shortCode(text) else { return try Pairing.parse(text) }
+ guard let cloud else { throw AccountStore.noCertificate }
+ return try Pairing.parse(try await cloud.pairingLink(code: code))
+ } catch {
+ throw pairingFailed(error)
+ }
}
/// `via`: `qr` scanned or pasted here, `link` opened from the Camera app.
@@ -248,7 +255,7 @@ final class AppStore {
// Scanned with the Camera app: pair right away.
let accounts = accounts
Task {
- do { _ = try await pair(try pairing(from: url.absoluteString), via: .link) } catch { accounts.lastError = error.localizedDescription }
+ do { _ = try await pair(try await pairing(from: url.absoluteString), via: .link) } catch { accounts.lastError = error.localizedDescription }
}
case "bot":
guard let ref = storage.reference(from: url), accounts.store(for: ref.computerId) != nil else { return }
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
index 05df85fd..0a9144c9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
@@ -167,6 +167,15 @@ public struct CloudClient: Sendable {
let _: Ignored = try await request("POST", "v1/claims/\(claimId)/complete", json: claim, signed: false)
}
+ // MARK: pairing codes
+
+ /// The pairing link a short code (`Pairing.shortCode`) stands for. The cloud hands it out once.
+ public func pairingLink(code: String) async throws -> String {
+ struct Res: Decodable { var link: String }
+ let res: Res = try await request("GET", "v1/pairing-codes/\(code)")
+ return res.link
+ }
+
// MARK: plumbing
private struct NoBody: Encodable {}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift
index c4ca5982..78714410 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift
@@ -31,6 +31,13 @@ public struct Pairing: Hashable, Sendable {
self = p
}
+ /// A short code `codync-host pair` prints (`QRTX-4821`: 4 letters, an optional dash or space, 4 digits) as the
+ /// cloud takes it, or nil for anything else. The cloud resolves it to the pairing link.
+ public static func shortCode(_ text: String) -> String? {
+ guard let match = text.trimmingCharacters(in: .whitespacesAndNewlines).wholeMatch(of: /([A-Za-z]{4})[- ]?([0-9]{4})/) else { return nil }
+ return "\(match.1.uppercased())-\(match.2)"
+ }
+
public static func parse(_ string: String) throws(Problem) -> Pairing {
guard let url = URL(string: string.trimmingCharacters(in: .whitespacesAndNewlines)) else { throw .notPairingLink }
return try parse(url)
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 8706cbdc..c8a1a7bf 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1481,5 +1481,18 @@
"Keep it there": "Dort lassen",
"Move here": "Hierher verschieben",
"If the computer asks, check it shows {code}.": "Wenn der Computer fragt, prüfe, dass er {code} anzeigt.",
- "Connect to the internet to pair, so Codync can confirm your account.": "Verbinde dich mit dem Internet, damit Codync beim Koppeln dein Konto bestätigen kann."
+ "Connect to the internet to pair, so Codync can confirm your account.": "Verbinde dich mit dem Internet, damit Codync beim Koppeln dein Konto bestätigen kann.",
+ "Let {name} in?": "{name} hereinlassen?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} möchte diesen Computer nutzen, der dann dem Konto von {email} beitritt. Prüfe, dass {name} {code} anzeigt.",
+ "Let in": "Hereinlassen",
+ "Don't allow": "Nicht erlauben",
+ "A Codync account": "Ein Codync-Konto",
+ "Every device of {email}'s account loses access.": "Alle Geräte des Kontos von {email} verlieren den Zugriff.",
+ "Every device of that account loses access.": "Alle Geräte dieses Kontos verlieren den Zugriff.",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "Der Zugriff kommt erst zurück, wenn du {name} auf {name} selbst wieder zum Konto hinzufügst.",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} möchte diesen Computer nutzen. Er tritt dem Konto von {email} bei. Prüfe, dass das Telefon {code} anzeigt.",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "In keinem Konto: Ein angemeldetes Telefon, das dies scannt, bittet darum, den Computer in sein Konto aufzunehmen.",
+ "Paste a pairing link, or type the code from the computer": "Füge einen Kopplungslink ein oder gib den Code vom Computer ein",
+ "That code isn't valid. Check it on the computer.": "Dieser Code ist ungültig. Prüfe ihn auf dem Computer.",
+ "That code expired or was used. Show a new one on the computer.": "Dieser Code ist abgelaufen oder wurde schon verwendet. Lass dir auf dem Computer einen neuen anzeigen."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index f237e22c..9d54c762 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1481,5 +1481,18 @@
"Keep it there": "Dejarla ahí",
"Move here": "Mover aquí",
"If the computer asks, check it shows {code}.": "Si el ordenador lo pregunta, comprueba que muestra {code}.",
- "Connect to the internet to pair, so Codync can confirm your account.": "Conéctate a internet para vincular, así Codync puede confirmar tu cuenta."
+ "Connect to the internet to pair, so Codync can confirm your account.": "Conéctate a internet para vincular, así Codync puede confirmar tu cuenta.",
+ "Let {name} in?": "¿Dejar entrar a {name}?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} quiere usar esta computadora, que luego se une a la cuenta de {email}. Comprueba que {name} muestra {code}.",
+ "Let in": "Dejar entrar",
+ "Don't allow": "No permitir",
+ "A Codync account": "Una cuenta de Codync",
+ "Every device of {email}'s account loses access.": "Todos los dispositivos de la cuenta de {email} pierden el acceso.",
+ "Every device of that account loses access.": "Todos los dispositivos de esa cuenta pierden el acceso.",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "El acceso solo vuelve cuando añades {name} a la cuenta de nuevo desde {name}.",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} quiere usar esta computadora. Se une a la cuenta de {email}. Comprueba que el teléfono muestra {code}.",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Sin cuenta: un teléfono con sesión iniciada que escanee esto pedirá añadir la computadora a su cuenta.",
+ "Paste a pairing link, or type the code from the computer": "Pega un enlace de emparejamiento o escribe el código de la computadora",
+ "That code isn't valid. Check it on the computer.": "Ese código no es válido. Revísalo en la computadora.",
+ "That code expired or was used. Show a new one on the computer.": "Ese código caducó o ya se usó. Muestra uno nuevo en la computadora."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index da6d86c8..3c38a6dc 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1481,5 +1481,18 @@
"Keep it there": "Le laisser là",
"Move here": "Déplacer ici",
"If the computer asks, check it shows {code}.": "Si l'ordinateur le demande, vérifiez qu'il affiche {code}.",
- "Connect to the internet to pair, so Codync can confirm your account.": "Connectez-vous à Internet pour appairer, afin que Codync confirme votre compte."
+ "Connect to the internet to pair, so Codync can confirm your account.": "Connectez-vous à Internet pour appairer, afin que Codync confirme votre compte.",
+ "Let {name} in?": "Laisser entrer {name} ?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} veut utiliser cet ordinateur, qui rejoint alors le compte de {email}. Vérifiez que {name} affiche {code}.",
+ "Let in": "Laisser entrer",
+ "Don't allow": "Ne pas autoriser",
+ "A Codync account": "Un compte Codync",
+ "Every device of {email}'s account loses access.": "Tous les appareils du compte de {email} perdent l’accès.",
+ "Every device of that account loses access.": "Tous les appareils de ce compte perdent l’accès.",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "L’accès ne revient que si vous ajoutez de nouveau {name} au compte depuis {name} lui-même.",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} veut utiliser cet ordinateur. Il rejoint le compte de {email}. Vérifiez que le téléphone affiche {code}.",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Dans aucun compte : un téléphone connecté qui scanne ceci demande à ajouter l’ordinateur à son compte.",
+ "Paste a pairing link, or type the code from the computer": "Collez un lien d'appairage ou saisissez le code affiché sur l'ordinateur",
+ "That code isn't valid. Check it on the computer.": "Ce code n'est pas valide. Vérifiez-le sur l'ordinateur.",
+ "That code expired or was used. Show a new one on the computer.": "Ce code a expiré ou a déjà été utilisé. Affichez-en un nouveau sur l'ordinateur."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index f6a7732b..896e429a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1481,5 +1481,18 @@
"Keep it there": "そのままにする",
"Move here": "ここに移動",
"If the computer asks, check it shows {code}.": "コンピュータに確認を求められたら、{code} と表示されているか確かめてください。",
- "Connect to the internet to pair, so Codync can confirm your account.": "ペアリングするにはインターネットに接続してください。Codync がアカウントを確認します。"
+ "Connect to the internet to pair, so Codync can confirm your account.": "ペアリングするにはインターネットに接続してください。Codync がアカウントを確認します。",
+ "Let {name} in?": "{name} を許可しますか?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} がこのコンピュータを使おうとしています。許可すると、このコンピュータは {email} のアカウントに加わります。{name} に {code} と表示されているか確かめてください。",
+ "Let in": "許可",
+ "Don't allow": "許可しない",
+ "A Codync account": "Codync アカウント",
+ "Every device of {email}'s account loses access.": "{email} のアカウントのすべてのデバイスがアクセスできなくなります。",
+ "Every device of that account loses access.": "そのアカウントのすべてのデバイスがアクセスできなくなります。",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "{name} 自体で {name} を再びアカウントに追加したときだけ、アクセスが戻ります。",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} がこのコンピュータを使おうとしています。このコンピュータは {email} のアカウントに加わります。スマートフォンに {code} と表示されているか確かめてください。",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "アカウントに入っていません:サインイン済みのスマートフォンがこれをスキャンすると、このコンピュータをそのアカウントに加えるよう求めます。",
+ "Paste a pairing link, or type the code from the computer": "ペアリングリンクを貼り付けるか、コンピューターに表示されたコードを入力します",
+ "That code isn't valid. Check it on the computer.": "このコードは無効です。コンピューターで確認してください。",
+ "That code expired or was used. Show a new one on the computer.": "このコードは期限切れか、すでに使用されています。コンピューターで新しいコードを表示してください。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 603dfcb3..53d1ab56 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1481,5 +1481,18 @@
"Keep it there": "그대로 두기",
"Move here": "여기로 옮기기",
"If the computer asks, check it shows {code}.": "컴퓨터가 물으면 {code}가 표시되는지 확인하세요.",
- "Connect to the internet to pair, so Codync can confirm your account.": "페어링하려면 인터넷에 연결하세요. Codync가 계정을 확인해야 합니다."
+ "Connect to the internet to pair, so Codync can confirm your account.": "페어링하려면 인터넷에 연결하세요. Codync가 계정을 확인해야 합니다.",
+ "Let {name} in?": "{name}의 접속을 허용할까요?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email}에서 이 컴퓨터를 사용하려고 합니다. 허용하면 이 컴퓨터가 {email} 계정에 추가됩니다. {name}에 {code}가 표시되는지 확인하세요.",
+ "Let in": "허용",
+ "Don't allow": "허용 안 함",
+ "A Codync account": "Codync 계정",
+ "Every device of {email}'s account loses access.": "{email} 계정의 모든 기기가 접근 권한을 잃습니다.",
+ "Every device of that account loses access.": "그 계정의 모든 기기가 접근 권한을 잃습니다.",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "{name}에서 직접 {name}을(를) 다시 계정에 추가해야만 접근 권한이 돌아옵니다.",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name}에서 이 컴퓨터를 사용하려고 합니다. 이 컴퓨터는 {email} 계정에 추가됩니다. 휴대폰에 {code}가 표시되는지 확인하세요.",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "계정에 속해 있지 않음: 로그인된 휴대폰이 이것을 스캔하면 이 컴퓨터를 그 계정에 추가하도록 요청합니다.",
+ "Paste a pairing link, or type the code from the computer": "페어링 링크를 붙여넣거나 컴퓨터에 표시된 코드를 입력하세요",
+ "That code isn't valid. Check it on the computer.": "유효하지 않은 코드입니다. 컴퓨터에서 확인하세요.",
+ "That code expired or was used. Show a new one on the computer.": "코드가 만료되었거나 이미 사용되었습니다. 컴퓨터에서 새 코드를 표시하세요."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index af0dbf92..89690b04 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1481,5 +1481,18 @@
"Keep it there": "留在原处",
"Move here": "移到这里",
"If the computer asks, check it shows {code}.": "如果电脑问你,确认它显示 {code}。",
- "Connect to the internet to pair, so Codync can confirm your account.": "请连上网络再配对,Codync 才能确认你的账户。"
+ "Connect to the internet to pair, so Codync can confirm your account.": "请连上网络再配对,Codync 才能确认你的账户。",
+ "Let {name} in?": "要让 {name} 进入吗?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} 想使用这台电脑,之后这台电脑会加入 {email} 的账户。请确认 {name} 显示 {code}。",
+ "Let in": "允许进入",
+ "Don't allow": "不允许",
+ "A Codync account": "一个 Codync 账户",
+ "Every device of {email}'s account loses access.": "{email} 账户的所有设备都会失去访问。",
+ "Every device of that account loses access.": "该账户的所有设备都会失去访问。",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "只有在 {name} 本机上将 {name} 重新加入账户,访问才会恢复。",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} 想使用这台电脑。这台电脑会加入 {email} 的账户。请确认手机显示 {code}。",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "不在任何账户中:已登录的手机扫描这个码时,会请求把这台电脑加入它的账户。",
+ "Paste a pairing link, or type the code from the computer": "粘贴配对链接,或输入电脑上的代码",
+ "That code isn't valid. Check it on the computer.": "代码无效,请在电脑上核对。",
+ "That code expired or was used. Show a new one on the computer.": "代码已过期或已被使用,请在电脑上显示新的代码。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index 2e77a686..a85a532c 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1481,5 +1481,18 @@
"Keep it there": "留在原處",
"Move here": "移到這裡",
"If the computer asks, check it shows {code}.": "如果電腦問你,確認它顯示 {code}。",
- "Connect to the internet to pair, so Codync can confirm your account.": "請連上網路再配對,Codync 才能確認你的賬戶。"
+ "Connect to the internet to pair, so Codync can confirm your account.": "請連上網路再配對,Codync 才能確認你的賬戶。",
+ "Let {name} in?": "要讓 {name} 進入嗎?",
+ "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} 想使用這臺電腦,之後這臺電腦會加入 {email} 的賬戶。請確認 {name} 顯示 {code}。",
+ "Let in": "允許進入",
+ "Don't allow": "不允許",
+ "A Codync account": "一個 Codync 賬戶",
+ "Every device of {email}'s account loses access.": "{email} 賬戶的所有裝置都會失去訪問。",
+ "Every device of that account loses access.": "該賬戶的所有裝置都會失去訪問。",
+ "Access comes back only when you add {name} to the account again on {name} itself.": "只有在 {name} 本機上將 {name} 重新加入賬戶,訪問才會恢復。",
+ "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} 想使用這臺電腦。這臺電腦會加入 {email} 的賬戶。請確認手機顯示 {code}。",
+ "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "不在任何賬戶中:已登入的手機掃描這個碼時,會請求把這臺電腦加入它的賬戶。",
+ "Paste a pairing link, or type the code from the computer": "貼上配對連結,或輸入電腦上的代碼",
+ "That code isn't valid. Check it on the computer.": "代碼無效,請到電腦上確認。",
+ "That code expired or was used. Show a new one on the computer.": "代碼已過期或已使用過,請在電腦上顯示新的代碼。"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index 1bef5982..30422992 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -128,7 +128,7 @@ public final class AccountStore {
return computer
}
- static let noCertificate = CloudError(status: 0, code: "noCertificate",
+ public static let noCertificate = CloudError(status: 0, code: "noCertificate",
message: "Connect to the internet to pair, so Codync can confirm your account.")
/// This device's certificate: the one held while more than a day is left, else a new one, registering
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift
new file mode 100644
index 00000000..61d9e913
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift
@@ -0,0 +1,65 @@
+import Foundation
+import os
+import Testing
+@testable import CodyncKit
+
+/// The cloud's pairing-code route: `QRTX-4821` resolves to its link, any other code is unknown.
+private final class PairingCodeCloudStub: URLProtocol {
+ static let requests = OSAllocatedUnfairLock(initialState: [URLRequest]())
+
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+
+ override func startLoading() {
+ let request = request
+ Self.requests.withLock { $0.append(request) }
+ let known = request.url?.path == "/v1/pairing-codes/QRTX-4821"
+ let json = known ? #"{"link":"codync://pair?v=3"}"#
+ : #"{"error":{"code":"notFound","message":"That code isn't valid. Check it on the computer."}}"#
+ let response = HTTPURLResponse(url: request.url!, statusCode: known ? 200 : 404, httpVersion: nil, headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data(json.utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+/// 4 letters, an optional dash or space, 4 digits, in any case; everything else (links included) isn't a code.
+@Test func shortPairingCodesAreRecognizedAndNormalized() {
+ for typed in ["QRTX-4821", "qrtx4821", " Qrtx 4821\n", "QRTX4821"] {
+ #expect(Pairing.shortCode(typed) == "QRTX-4821")
+ }
+ for other in ["QRT-4821", "QRTX-482", "QRTX--4821", "QRTX_4821", "1234-QRTX", "QRTXX4821", "codync://pair?v=3", ""] {
+ #expect(Pairing.shortCode(other) == nil)
+ }
+}
+
+/// The code is looked up with the account's session, unsigned; the cloud's message is what an unknown one shows.
+@Test func aPairingCodeResolvesToItsLinkThroughTheCloud() async throws {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [PairingCodeCloudStub.self]
+ let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: DeviceIdentity(signing: .init(), push: .init()),
+ session: URLSession(configuration: config)) { "token" }
+
+ #expect(try await cloud.pairingLink(code: "QRTX-4821") == "codync://pair?v=3")
+ let request = try #require(PairingCodeCloudStub.requests.withLock { $0.last })
+ #expect(request.httpMethod == "GET")
+ #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer token")
+ #expect(request.value(forHTTPHeaderField: "Codync-Sig") == nil)
+
+ await #expect(throws: CloudError(status: 404, code: "notFound", message: "That code isn't valid. Check it on the computer.")) {
+ try await cloud.pairingLink(code: "ABCD-1234")
+ }
+ #expect(CloudError(status: 404, code: "notFound", message: "That code isn't valid. Check it on the computer.").localizedDescription
+ == "That code isn't valid. Check it on the computer.")
+}
+
+/// The paste field's placeholder and the cloud's two code messages read in every language the app speaks.
+@Test func pairingCodeCopyIsTranslatedEverywhere() {
+ for language in [AppLanguage.zh, .zhHant, .ja, .ko, .fr, .de, .es] {
+ for phrase in ["Paste a pairing link, or type the code from the computer", "That code isn't valid. Check it on the computer.",
+ "That code expired or was used. Show a new one on the computer."] {
+ #expect(L10n.tr(phrase, preference: language, systemIsChinese: false) != phrase, "\(language) \(phrase)")
+ }
+ }
+}
diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swift
index 38619b3b..c622f125 100644
--- a/apps/ios/Views/PairingView.swift
+++ b/apps/ios/Views/PairingView.swift
@@ -235,7 +235,7 @@ private struct ScanPage: View {
viewfinder
HStack {
- TextField(L10n.tr("Or paste a {scheme}://pair link").replacingOccurrences(of: "{scheme}", with: AppEnvironment.current.urlScheme), text: $pasted)
+ TextField(L10n.tr("Paste a pairing link, or type the code from the computer"), text: $pasted)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.font(.callout.monospaced())
@@ -338,18 +338,14 @@ private struct ScanPage: View {
}
private func pair(_ text: String) {
- let p: Pairing
- do {
- p = try app.pairing(from: text.trimmingCharacters(in: .whitespacesAndNewlines))
- } catch {
- show(error)
- return
- }
+ // A short code works once: Return pressed again while it resolves mustn't spend it twice.
+ guard !pairing else { return }
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { error = nil }
pairing = true
Task {
defer { pairing = false }
do {
+ let p = try await app.pairing(from: text.trimmingCharacters(in: .whitespacesAndNewlines))
_ = try await app.pair(p, via: .qr)
pasted = ""
paired()
diff --git a/host/src/api/events.rs b/host/src/api/events.rs
index c06760f3..f984ad8d 100644
--- a/host/src/api/events.rs
+++ b/host/src/api/events.rs
@@ -45,7 +45,7 @@ impl Drop for PhoneClientGuard {
}
/// Event types only this computer's own apps receive.
-const LOCAL_EVENTS: &[&str] = &["accessRequests", "cloud"];
+const LOCAL_EVENTS: &[&str] = &["accessRequests", "cloud", "pairingRequests"];
#[cfg(test)]
mod tests;
diff --git a/host/src/remote/channel/pairing.rs b/host/src/remote/channel/pairing.rs
index 2c1cef81..ba7a2031 100644
--- a/host/src/remote/channel/pairing.rs
+++ b/host/src/remote/channel/pairing.rs
@@ -103,9 +103,10 @@ impl Channel {
(close::PAIRED, "paired")
}
- /// The signed claim for `{claimId, nonce}`, or null without one or with no Codync accounts here.
+ /// The signed claim for `{claimId, nonce}`, or null without one, or with the Codync cloud off or a private
+ /// relay here (no account to join).
async fn claim(&self, claim: &Value, user_id: &str) -> Value {
- if claim.is_null() {
+ if claim.is_null() || crate::remote::cloud::codync_url(&self.hub).is_err() {
return Value::Null;
}
let request = json!({"claimId": claim["claimId"], "nonce": claim["nonce"], "userId": user_id});
diff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rs
index 56a6c31c..8df0cd11 100644
--- a/host/src/remote/channel/tests/accounts.rs
+++ b/host/src/remote/channel/tests/accounts.rs
@@ -40,6 +40,8 @@ async fn a_phone_of_another_account_is_refused_with_the_owner_masked() {
#[tokio::test]
async fn a_computer_in_no_account_asks_then_joins_the_phones() {
let hub = unowned_hub();
+ // With the Codync cloud on there is an account to join, so the computer signs the phone's claim.
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
for approve in [false, true] {
let (mut p, code) = pairing_phone(&hub).await;
let mut body = pair_body(&p, &code, "Pixel", "android", "user_2");
@@ -58,7 +60,6 @@ async fn a_computer_in_no_account_asks_then_joins_the_phones() {
if approve {
assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());
assert_eq!(hub.store.device(&p.dk()).unwrap().account.as_deref(), Some("user_2"));
- // Codync accounts are on by default here, so the computer signs the phone's claim.
let claim = &reply["ok"]["claim"];
assert_eq!(claim["computerId"], hub.identity.computer_id());
let input =
diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rs
index 94cd50a8..20612d6c 100644
--- a/host/src/remote/relay.rs
+++ b/host/src/remote/relay.rs
@@ -70,6 +70,9 @@ pub async fn run(hub: Arc<Hub>) {
if address.is_none() {
s.owner = None;
s.last_error = None;
+ } else if s.owner.is_none() {
+ // Until the cloud answers (or while it can't be reached), the account last seen.
+ s.owner = super::owner::owner(&hub.store);
}
});
let restart = if let Some(address) = address {
diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rs
index 93479345..64f9cbd3 100644
--- a/host/src/tui/app/events.rs
+++ b/host/src/tui/app/events.rs
@@ -4,7 +4,7 @@ use std::collections::HashMap;
use serde_json::{Value, json};
-use super::{After, App, Bot, Dir, Entry, Focus, Msg, Overlay, PairCode, Status, merge_toggles};
+use super::{After, App, Bot, Dir, Entry, Focus, Msg, Overlay, Status, merge_toggles};
/// An entry the mirror doesn't hold, below the floor its bot's loaded chat had when this
/// connection began: `seq` grows with insertion, so it predates the window and only arrived because
@@ -64,6 +64,8 @@ impl App {
Some("usage") => self.usage = v["usage"].clone(),
Some("screen") => self.screen = v["screen"].clone(),
Some("network") => self.network_changed(&v["network"]),
+ Some("cloud") => self.cloud = v["cloud"].clone(),
+ Some("pairingRequests") => self.pairing_requests_changed(v),
Some("bot") => {
self.upsert_bot(&v["bot"]);
self.memory_moved(&v["bot"]);
@@ -165,6 +167,10 @@ impl App {
self.network_reply(n, r);
return;
}
+ if matches!(after, After::Pairing | After::Cloud | After::PairingRequests) {
+ self.pair_reply(&after, r);
+ return;
+ }
let v = match r {
Ok(v) => v,
Err(e) => {
@@ -197,12 +203,6 @@ impl App {
p.busy = false;
}
}
- // In place of the code, which may have expired.
- After::Pairing => {
- if let Some(Overlay::Pair(code)) = self.overlays.last_mut() {
- *code = PairCode::Failed(e);
- }
- }
_ => self.flash(&e),
}
return;
@@ -215,7 +215,10 @@ impl App {
| After::Sheet(_)
| After::Network(_)
| After::Sent(_)
- | After::Connection(_, _) => {}
+ | After::Connection(_, _)
+ | After::Pairing
+ | After::Cloud
+ | After::PairingRequests => {}
After::Installed => {
self.error = None;
self.flash("Host installed; connecting…");
@@ -292,14 +295,6 @@ impl App {
p.error = None;
}
}
- After::Pairing => {
- if let Some(Overlay::Pair(code)) = self.overlays.last_mut() {
- *code = match v["pairingUrl"].as_str() {
- Some(url) => PairCode::Ready(url.to_owned()),
- None => PairCode::Failed("The host sent no pairing code.".into()),
- };
- }
- }
After::Saved => {
let saved = self
.overlays
diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rs
index 78f3b476..976bba71 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -5,17 +5,12 @@ use serde_json::{Value, json};
use std::collections::BTreeMap;
use super::{
- After, App, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, PairCode, SHAPES, Toggle, cycle,
+ After, App, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, SHAPES, Toggle, cycle,
merge_toggles,
};
use crate::tui::manage::Page;
impl App {
- pub(super) fn open_pair(&mut self) {
- self.overlays.push(Overlay::Pair(PairCode::Loading));
- self.call("pairing", json!({}), After::Pairing);
- }
-
pub(in crate::tui) fn edit_bot(&mut self) {
if let Some(id) = self.selected.clone() {
self.edit_bot_of(&id);
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index a3398849..ac15ba2d 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -14,6 +14,7 @@ mod model;
mod navigate;
mod new_bot;
mod overlay_keys;
+mod pair;
mod roster;
mod section_order;
mod slash;
@@ -71,6 +72,10 @@ pub struct App {
pub screen: Value,
/// This computer's network (`networkView`'s shape); null on hosts without one.
pub network: Value,
+ /// The host's account and relay (`cloudStatus`, `cloud` events): null until the pair sheet asks.
+ pub cloud: Value,
+ /// Phones waiting for this computer to let them in (`pairingRequests`), oldest first.
+ pub pairing_requests: Vec<Value>,
pub backends: Vec<Value>,
pub custom_icons: bool,
pub selected: Option<String>,
@@ -169,6 +174,8 @@ impl App {
usage: Value::Null,
screen: Value::Null,
network: Value::Null,
+ cloud: Value::Null,
+ pairing_requests: vec![],
backends: vec![],
custom_icons: false,
selected: None,
diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rs
index 2726196b..e4f017dc 100644
--- a/host/src/tui/app/model.rs
+++ b/host/src/tui/app/model.rs
@@ -40,6 +40,9 @@ pub enum After {
Dirs(String),
WorkspaceSelected(String),
Pairing,
+ /// The pair sheet's `cloudStatus` and `pairingRequests`.
+ Cloud,
+ PairingRequests,
Backends,
Update,
Saved,
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 376277fe..9ace9394 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -130,6 +130,11 @@ impl App {
Overlay::Skill(s) => self.skill_key(s, k),
Overlay::Analytics(s) => s.key(k),
Overlay::Network(n) => self.network_key(n, k),
+ // A phone that scanned the code waits for this computer to let it in.
+ o @ Overlay::Pair(_) if matches!(k.code, KeyCode::Char('y' | 'n')) && !self.pairing_requests.is_empty() => {
+ self.decide_pairing(k.code == KeyCode::Char('y'));
+ Some(o)
+ }
// A new code: after a failure, or in place of the one shown.
Overlay::Pair(_) if k.code == KeyCode::Char('r') => {
self.call("pairing", json!({}), After::Pairing);
diff --git a/host/src/tui/app/pair.rs b/host/src/tui/app/pair.rs
new file mode 100644
index 00000000..5241123c
--- /dev/null
+++ b/host/src/tui/app/pair.rs
@@ -0,0 +1,95 @@
+//! The pair-a-phone sheet: its code, whether the computer is in an account, and the phones waiting for it to
+//! let them in, which brings it into their account (docs/plans/require-sign-in.md, phase 2).
+
+use serde_json::{Value, json};
+
+use super::{After, App, Overlay, PairCode};
+
+impl App {
+ pub(super) fn open_pair(&mut self) {
+ self.overlays.push(Overlay::Pair(PairCode::Loading));
+ self.call("pairing", json!({}), After::Pairing);
+ self.call("cloudStatus", json!({}), After::Cloud);
+ self.call("pairingRequests", json!({}), After::PairingRequests);
+ }
+
+ pub(super) fn pair_reply(&mut self, after: &After, r: Result<Value, String>) {
+ match (after, r) {
+ (After::Pairing, r) => {
+ if let Some(Overlay::Pair(code)) = self.overlays.last_mut() {
+ *code = match r {
+ // In place of the code, which may have expired.
+ Err(e) => PairCode::Failed(e),
+ Ok(v) => v["pairingUrl"].as_str().map_or_else(
+ || PairCode::Failed("The host sent no pairing code.".into()),
+ |url| PairCode::Ready(url.to_owned()),
+ ),
+ };
+ }
+ }
+ (After::Cloud, Ok(v)) => self.cloud = v,
+ (After::PairingRequests, Ok(v)) => self.pairing_requests = requests(&v),
+ // Hosts before accounts have neither: the sheet shows the code alone.
+ _ => {}
+ }
+ }
+
+ /// A `pairingRequests` event: the whole list, each time it changes.
+ pub(super) fn pairing_requests_changed(&mut self, v: &Value) {
+ self.pairing_requests = requests(v);
+ }
+
+ /// `y` / `n` on the sheet: the first waiting phone gets in (and the computer joins its account), or doesn't.
+ pub(super) fn decide_pairing(&mut self, approve: bool) {
+ if self.pairing_requests.is_empty() {
+ return;
+ }
+ // Off the sheet at once; the host's event follows.
+ let request = self.pairing_requests.remove(0);
+ self.call("decidePairing", json!({"requestId": request["requestId"], "approve": approve}), After::Nothing);
+ }
+
+ /// Known to be in no account while it could join one: a signed-in phone that scans the code asks to bring the
+ /// computer into its own. With the cloud off or a private relay there is no account to join.
+ pub fn outside_account(&self) -> bool {
+ self.cloud.is_object()
+ && self.cloud["owner"].is_null()
+ && self.cloud["enabled"] == true
+ && self.cloud["relay"] != "private"
+ }
+}
+
+fn requests(v: &Value) -> Vec<Value> {
+ v["requests"].as_array().cloned().unwrap_or_default()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::test_app;
+ use super::*;
+
+ #[tokio::test]
+ async fn waiting_phones_and_the_account_follow_the_host() {
+ let mut app = test_app();
+ assert!(!app.outside_account(), "unknown until the host says");
+ app.pair_reply(&After::Cloud, Ok(json!({"enabled": false, "owner": null})));
+ assert!(!app.outside_account(), "no account to join with the cloud off");
+ app.pair_reply(&After::Cloud, Ok(json!({"enabled": true, "relay": "private", "owner": null})));
+ assert!(!app.outside_account(), "nor on a private relay");
+ app.pair_reply(&After::Cloud, Ok(json!({"enabled": true, "relay": "codync", "owner": null})));
+ assert!(app.outside_account());
+ app.pair_reply(&After::Cloud, Ok(json!({"enabled": true, "owner": {"userId": "user_1"}})));
+ assert!(!app.outside_account());
+
+ app.pairing_requests_changed(&json!({"requests": [{"requestId": "a", "deviceName": "Pixel", "code": "123456"},
+ {"requestId": "b", "deviceName": "iPhone", "code": "654321"}]}));
+ app.decide_pairing(true);
+ assert_eq!(app.pairing_requests.len(), 1, "an answered phone leaves the sheet at once");
+ assert_eq!(app.pairing_requests[0]["requestId"], "b");
+ app.pair_reply(&After::PairingRequests, Err("unknown method".into()));
+ assert_eq!(app.pairing_requests.len(), 1, "an older host's refusal changes nothing");
+ app.pairing_requests_changed(&json!({"requests": []}));
+ app.decide_pairing(false);
+ assert_eq!(app.pairing_requests, Vec::<Value>::new());
+ }
+}
diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rs
index d83909c9..ad7178c1 100644
--- a/host/src/tui/view/overlay.rs
+++ b/host/src/tui/view/overlay.rs
@@ -139,7 +139,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay
Overlay::Form(form) => form_view(buf, area, app, form),
Overlay::Group(g) => group_view(buf, area, app, g),
Overlay::Usage(scroll) => usage(buf, area, app, *scroll),
- Overlay::Pair(code) => pair(buf, area, code),
+ Overlay::Pair(code) => pair(buf, area, app, code),
Overlay::Memory(m) => super::super::sheets::memory(buf, area, app, m),
Overlay::BotChat(c) => super::bot_chat::bot_chat(buf, area, app, c),
Overlay::Routines(l) => super::super::sheets::routines(buf, area, app, l),
diff --git a/host/src/tui/view/pair.rs b/host/src/tui/view/pair.rs
index 9a14ba86..672c72ab 100644
--- a/host/src/tui/view/pair.rs
+++ b/host/src/tui/view/pair.rs
@@ -1,18 +1,26 @@
//! The pair-a-phone sheet.
+use std::borrow::Cow;
+
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Style};
+use ratatui::text::{Line, Span};
+use serde_json::Value;
-use super::super::app::PairCode;
-use super::super::md::{truncate, width as w};
-use super::buffer::{centered, frame_box, put, u};
+use super::super::app::{App, PairCode};
+use super::super::l10n::tr;
+use super::super::md::{truncate, width as w, wrap};
+use super::buffer::{centered, frame_box, put, put_line, u};
use super::style::theme;
-pub(super) fn pair(buf: &mut Buffer, area: Rect, code: &PairCode) {
+pub(super) fn pair(buf: &mut Buffer, area: Rect, app: &App, code: &PairCode) {
+ if let Some(request) = app.pairing_requests.first() {
+ return ask(buf, area, request);
+ }
let t = theme();
let (text, style) = match code {
- PairCode::Ready(url) => return qr(buf, area, url),
+ PairCode::Ready(url) => return qr(buf, area, url, app.outside_account()),
PairCode::Loading => ("Getting the pairing code…", t.secondary),
PairCode::Failed(e) => (e.as_str(), t.red),
};
@@ -24,15 +32,56 @@ pub(super) fn pair(buf: &mut Buffer, area: Rect, code: &PairCode) {
}
}
-fn qr(buf: &mut Buffer, area: Rect, url: &str) {
+/// A phone that scanned the code waits for this computer: `y` lets it in and the computer joins its account.
+fn ask(buf: &mut Buffer, area: Rect, request: &Value) {
+ let t = theme();
+ let name = request["deviceName"].as_str().unwrap_or("A phone");
+ let email =
+ request["email"].as_str().filter(|e| !e.is_empty()).map_or_else(|| tr("A Codync account"), Cow::Borrowed);
+ let code = request["code"].as_str().unwrap_or_default();
+ // A no-break space: the code never wraps apart.
+ let code = match code.split_at_checked(3) {
+ Some((a, b)) if code.len() == 6 => format!("{a}\u{a0}{b}"),
+ _ => code.to_owned(),
+ };
+ // The name last: whatever it says stays as written.
+ let text = tr("{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.")
+ .replace("{email}", &email)
+ .replace("{code}", &code)
+ .replace("{name}", name);
+ let lines = note(text, 52, t.text.patch(t.panel));
+ let r = centered(area, 56, u(lines.len() + 5));
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
+ for (y, line) in (inner.y + 1..).zip(&lines) {
+ put_line(buf, inner.x, y, inner.width, line);
+ }
+ put(buf, inner.x, inner.bottom() - 1, inner.width, "y let in · n don't allow", t.dim.patch(t.panel));
+}
+
+fn note(text: String, width: usize, style: Style) -> Vec<Line<'static>> {
+ wrap(&[Span::styled(text, style)], width, &[], &[])
+}
+
+fn qr(buf: &mut Buffer, area: Rect, url: &str, outside_account: bool) {
let t = theme();
let qr = qrcode::QrCode::new(url.as_bytes())
.map(|c| c.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build())
.unwrap_or_default();
let lines: Vec<&str> = qr.lines().collect();
let qw = lines.first().map_or(0, |l| w(l));
- let fits = u(lines.len() + 6) <= area.height && u(qw + 4) <= area.width;
- let (bw, bh) = if fits { (u(qw.max(50) + 4), u(lines.len() + 6)) } else { (70, 8) };
+ let account = |width: usize| {
+ let text =
+ tr("Not in an account: a signed-in phone that scans this asks to bring the computer into its account.");
+ if outside_account { note(text.into_owned(), width, t.dim.patch(t.panel)) } else { vec![] }
+ };
+ let wide = account(qw.max(50));
+ let fits = u(lines.len() + 6 + wide.len()) <= area.height && u(qw + 4) <= area.width;
+ let (bw, bh, account) = if fits {
+ (u(qw.max(50) + 4), u(lines.len() + 6 + wide.len()), wide)
+ } else {
+ let narrow = account(66);
+ (70, u(8 + narrow.len()), narrow)
+ };
let r = centered(area, bw, bh);
let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
let mut y = inner.y;
@@ -61,5 +110,48 @@ fn qr(buf: &mut Buffer, area: Rect, url: &str) {
t.secondary.patch(t.panel),
);
put(buf, inner.x, y + 1, inner.width, &truncate(url, usize::from(inner.width)), t.dim.patch(t.panel));
+ for (y, line) in (y + 2..).zip(&account) {
+ put_line(buf, inner.x, y, inner.width, line);
+ }
put(buf, inner.x, inner.bottom() - 1, inner.width, "r new code · esc close", t.dim.patch(t.panel));
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn shown(buf: &Buffer) -> String {
+ let a = buf.area;
+ (a.top()..a.bottom())
+ .map(|y| (a.left()..a.right()).map(|x| buf[(x, y)].symbol()).collect::<String>())
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ #[test]
+ fn a_waiting_phone_shows_its_account_the_code_and_the_keys() {
+ let mut buf = Buffer::empty(Rect::new(0, 0, 80, 20));
+ let request = json!({"requestId": "a", "deviceName": "Pixel", "email": "[email protected]", "code": "123456"});
+ let area = buf.area;
+ ask(&mut buf, area, &request);
+ let text = shown(&buf);
+ for part in ["Pixel", "[email protected]", "123\u{a0}456", "y let in · n don't allow"] {
+ assert!(text.contains(part), "{part} in\n{text}");
+ }
+ }
+
+ #[test]
+ fn a_computer_in_no_account_says_so_under_the_code() {
+ let note =
+ tr("Not in an account: a signed-in phone that scans this asks to bring the computer into its account.");
+ // Its start, which fits on the first line in any language.
+ let first: String = note.chars().take(6).collect();
+ for (outside, says) in [(true, true), (false, false)] {
+ let mut buf = Buffer::empty(Rect::new(0, 0, 100, 60));
+ let area = buf.area;
+ qr(&mut buf, area, "codync://pair?id=x&code=y", outside);
+ assert_eq!(shown(&buf).contains(&first), says);
+ }
+ }
+}